repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/servicelayer/scopedstorage/Utils.kt | 1 | 2505 | /*
* Copyright (c) 2022 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.servicelayer.scopedstorage
import androidx.annotation.CheckResult
import com.ichi2.anki.RobolectricTest
import com.ichi2.anki.model.DiskFile
import com.ichi2.anki.servicelayer.ScopedStorageService
import com.ichi2.libanki.Media
import org.acra.util.IOUtils
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.*
import java.io.File
/** Adds a media file to collection.media which [Media] is not aware of */
@CheckResult
internal fun addUntrackedMediaFile(media: Media, content: String, path: List<String>): DiskFile {
val file = convertPathToMediaFile(media, path)
File(file.parent!!).mkdirs()
IOUtils.writeStringToFile(file, content)
return DiskFile.createInstance(file)!!
}
private fun convertPathToMediaFile(media: Media, path: List<String>): File {
val mutablePath = ArrayDeque(path)
var file = File(media.dir())
while (mutablePath.any()) {
file = File(file, mutablePath.removeFirst())
}
return file
}
/** A [File] reference to the AnkiDroid directory of the current collection */
internal fun RobolectricTest.ankiDroidDirectory() = File(col.path).parentFile!!
/** Adds a file to collection.media which [Media] is not aware of */
@CheckResult
internal fun RobolectricTest.addUntrackedMediaFile(content: String, path: List<String>): DiskFile =
addUntrackedMediaFile(col.media, content, path)
fun RobolectricTest.assertMigrationInProgress() {
assertThat("the migration should be in progress", ScopedStorageService.userMigrationIsInProgress(this.targetContext), equalTo(true))
}
fun RobolectricTest.assertMigrationNotInProgress() {
assertThat("the migration should not be in progress", ScopedStorageService.userMigrationIsInProgress(this.targetContext), equalTo(false))
}
| gpl-3.0 | ac497ef70f966d586511614caeafdb77 | 40.065574 | 141 | 0.76487 | 4.168053 | false | true | false | false |
caiorrs/FastHub | app/src/main/java/com/fastaccess/ui/adapter/viewholder/PullRequestEventViewHolder.kt | 4 | 20988 | package com.fastaccess.ui.adapter.viewholder
import android.annotation.SuppressLint
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.text.style.BackgroundColorSpan
import android.view.View
import android.view.ViewGroup
import butterknife.BindView
import com.fastaccess.R
import com.fastaccess.data.dao.timeline.PullRequestTimelineModel
import com.fastaccess.helper.ParseDateFormat
import com.fastaccess.helper.PrefGetter
import com.fastaccess.helper.ViewHelper
import com.fastaccess.provider.scheme.LinkParserHelper
import com.fastaccess.provider.timeline.HtmlHelper
import com.fastaccess.ui.widgets.AvatarLayout
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.ForegroundImageView
import com.fastaccess.ui.widgets.SpannableBuilder
import com.fastaccess.ui.widgets.recyclerview.BaseRecyclerAdapter
import com.fastaccess.ui.widgets.recyclerview.BaseViewHolder
import com.zzhoujay.markdown.style.CodeSpan
import github.PullRequestTimelineQuery
import github.type.StatusState
/**
* Created by kosh on 03/08/2017.
*/
class PullRequestEventViewHolder private constructor(view: View, adapter: BaseRecyclerAdapter<*, *, *>) :
BaseViewHolder<PullRequestTimelineModel>(view, adapter) {
@BindView(R.id.stateImage) lateinit var stateImage: ForegroundImageView
@BindView(R.id.avatarLayout) lateinit var avatarLayout: AvatarLayout
@BindView(R.id.stateText) lateinit var stateText: FontTextView
@BindView(R.id.commitStatus) lateinit var commitStatus: ForegroundImageView
override fun bind(t: PullRequestTimelineModel) {
val node = t.node
commitStatus.visibility = View.GONE
if (node != null) {
when {
node.asAssignedEvent() != null -> assignedEvent(node.asAssignedEvent()!!)
node.asBaseRefForcePushedEvent() != null -> forcePushEvent(node.asBaseRefForcePushedEvent()!!)
node.asClosedEvent() != null -> closedEvent(node.asClosedEvent()!!)
node.asCommit() != null -> commitEvent(node.asCommit()!!)
node.asDemilestonedEvent() != null -> demilestonedEvent(node.asDemilestonedEvent()!!)
node.asDeployedEvent() != null -> deployedEvent(node.asDeployedEvent()!!)
node.asHeadRefDeletedEvent() != null -> refDeletedEvent(node.asHeadRefDeletedEvent()!!)
node.asHeadRefForcePushedEvent() != null -> refForPushedEvent(node.asHeadRefForcePushedEvent()!!)
node.asHeadRefRestoredEvent() != null -> headRefRestoredEvent(node.asHeadRefRestoredEvent()!!)
node.asLabeledEvent() != null -> labeledEvent(node.asLabeledEvent()!!)
node.asLockedEvent() != null -> lockEvent(node.asLockedEvent()!!)
node.asMergedEvent() != null -> mergedEvent(node.asMergedEvent()!!)
node.asMilestonedEvent() != null -> milestoneEvent(node.asMilestonedEvent()!!)
node.asReferencedEvent() != null -> referenceEvent(node.asReferencedEvent()!!)
node.asRenamedTitleEvent() != null -> renamedEvent(node.asRenamedTitleEvent()!!)
node.asReopenedEvent() != null -> reopenedEvent(node.asReopenedEvent()!!)
node.asUnassignedEvent() != null -> unassignedEvent(node.asUnassignedEvent()!!)
node.asUnlabeledEvent() != null -> unlabeledEvent(node.asUnlabeledEvent()!!)
node.asUnlockedEvent() != null -> unlockedEvent(node.asUnlockedEvent()!!)
else -> reset()
}
} else {
reset()
}
}
private fun reset() {
stateText.text = ""
avatarLayout.setUrl(null, null, false, false)
}
@SuppressLint("SetTextI18n")
private fun unlockedEvent(event: PullRequestTimelineQuery.AsUnlockedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("unlocked this conversation")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_lock)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun unlabeledEvent(event: PullRequestTimelineQuery.AsUnlabeledEvent) {
event.actor()?.let {
val color = Color.parseColor("#" + event.label().color())
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("removed")
.append(" ")
.append(event.label().name(), CodeSpan(color, ViewHelper.generateTextColor(color), 5.0f))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_label)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun unassignedEvent(event: PullRequestTimelineQuery.AsUnassignedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("unassigned") //TODO add "removed their assignment" for self
.append(" ")
.append(event.user()?.login())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_profile)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun reopenedEvent(event: PullRequestTimelineQuery.AsReopenedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("reopened this")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_issue_opened)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun renamedEvent(event: PullRequestTimelineQuery.AsRenamedTitleEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("changed the title from").append(" ").append(event.previousTitle())
.append(" ").append("to").append(" ").bold(event.currentTitle())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_edit)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun referenceEvent(event: PullRequestTimelineQuery.AsReferencedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("referenced in")
.append(" ")
.append("from").append(" ")
.url(if (event.commit() != null) {
substring(event.commit()?.oid()?.toString())
} else if (event.subject().asIssue() != null) {
if (event.isCrossRepository) {
"${event.commitRepository().nameWithOwner()} ${event.subject().asIssue()?.title()}#${event.subject().asIssue()?.number()}"
} else {
"${event.subject().asIssue()?.title()}#${event.subject().asIssue()?.number()}"
}
} else if (event.subject().asPullRequest() != null) {
if (event.isCrossRepository) {
"${event.commitRepository().nameWithOwner()} ${event.subject().asPullRequest()?.title()}" +
"#${event.subject().asPullRequest()?.number()}"
} else {
"${event.subject().asPullRequest()?.title()}#${event.subject().asPullRequest()?.number()}"
}
} else {
event.commitRepository().nameWithOwner()
})
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun milestoneEvent(event: PullRequestTimelineQuery.AsMilestonedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("added this to the")
.append(" ")
.append(event.milestoneTitle()).append(" ").append("milestone")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_milestone)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun mergedEvent(event: PullRequestTimelineQuery.AsMergedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("merged commit")
.append(" ")
.url(substring(event.commit()?.oid()?.toString()))
.append(" ")
.append("into")
.append(" ")
.append(event.actor())
.append(":")
.append(event.mergeRefName(), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_merge)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun lockEvent(event: PullRequestTimelineQuery.AsLockedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("locked and limited conversation to collaborators")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_lock)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun labeledEvent(event: PullRequestTimelineQuery.AsLabeledEvent) {
event.actor()?.let {
val color = Color.parseColor("#" + event.label().color())
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("labeled")
.append(" ")
.append(event.label().name(), CodeSpan(color, ViewHelper.generateTextColor(color), 5.0f))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_label)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun headRefRestoredEvent(event: PullRequestTimelineQuery.AsHeadRefRestoredEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("restored the")
.append(" ")
.append(it.login())
.append(":")
.append(event.pullRequest().headRefName(), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append("branch")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun refForPushedEvent(event: PullRequestTimelineQuery.AsHeadRefForcePushedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("reference force pushed to", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.url(substring(event.afterCommit().oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun refDeletedEvent(event: PullRequestTimelineQuery.AsHeadRefDeletedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("deleted the")
.append(" ")
.append(it.login())
.append(":")
.append(substring(event.headRefName()), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append("branch")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_trash)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun deployedEvent(event: PullRequestTimelineQuery.AsDeployedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("made a deployment", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append(event.deployment().latestStatus()?.state()?.name)
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun demilestonedEvent(event: PullRequestTimelineQuery.AsDemilestonedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("removed this from the")
.append(" ")
.append(event.milestoneTitle()).append(" ").append("milestone")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_milestone)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun commitEvent(event: PullRequestTimelineQuery.AsCommit) {
event.author()?.let {
stateText.text = SpannableBuilder.builder()//Review[k0shk0sh] We may want to suppress more then 3 or 4 commits. since it will clog the it
.bold(if (it.user() == null) it.name() else it.user()?.login())
.append(" ")
.append("committed")
.append(" ")
.append(event.messageHeadline())
.append(" ")
.url(substring(event.oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.committedDate().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.user()?.avatarUrl().toString(), it.user()?.login(), false,
LinkParserHelper.isEnterprise(it.user()?.url().toString()))
event.status()?.let {
commitStatus.visibility = View.VISIBLE
val context = commitStatus.context
commitStatus.tintDrawableColor(when (it.state()) {
StatusState.ERROR -> ContextCompat.getColor(context, R.color.material_red_700)
StatusState.FAILURE -> ContextCompat.getColor(context, R.color.material_deep_orange_700)
StatusState.SUCCESS -> ContextCompat.getColor(context, R.color.material_green_700)
else -> ContextCompat.getColor(context, R.color.material_yellow_700)
})
}
}
}
private fun closedEvent(event: PullRequestTimelineQuery.AsClosedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("closed this in")
.append(" ")
.url(substring(event.commit()?.oid()?.toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_merge)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun forcePushEvent(event: PullRequestTimelineQuery.AsBaseRefForcePushedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("force pushed to", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.url(substring(event.afterCommit().oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun assignedEvent(event: PullRequestTimelineQuery.AsAssignedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("assigned") //TODO add "self-assigned" for self
.append(" ")
.append(event.user()?.login())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_profile)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun substring(value: String?): String {
if (value == null) {
return ""
}
return if (value.length <= 7) value
else value.substring(0, 7)
}
companion object {
fun newInstance(parent: ViewGroup, adapter: BaseRecyclerAdapter<*, *, *>): PullRequestEventViewHolder {
return PullRequestEventViewHolder(getView(parent, R.layout.issue_timeline_row_item), adapter)
}
}
} | gpl-3.0 | e0d412bfd06916be434960441beecae7 | 49.698068 | 150 | 0.569706 | 5.298662 | false | false | false | false |
GymDon-P-Q11Info-13-15/game | Game Commons/src/de/gymdon/inf1315/game/tile/Tile.kt | 1 | 529 | package de.gymdon.inf1315.game.tile
data class Tile(val id: Int, val name: String, val groundFactor: Double = 1.0) {
val isWalkable: Boolean
get() = groundFactor != Double.POSITIVE_INFINITY
companion object {
val grass = Tile(0, "grass", 1.0)
val grass2 = Tile(0, "grass", 1.0)
val sand = Tile(1, "sand", 2.0)
val sand2 = Tile(1, "sand", 2.0)
val water = Tile(2, "water", Double.POSITIVE_INFINITY)
val water2 = Tile(2, "water", Double.POSITIVE_INFINITY)
}
}
| gpl-3.0 | a25ee8b7259a488244dadd1ee3866b57 | 32.0625 | 80 | 0.601134 | 3.186747 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/data/models/local/cursor/output/Field.kt | 1 | 1504 | package com.infinum.dbinspector.data.models.local.cursor.output
import com.infinum.dbinspector.data.models.local.proto.output.SettingsEntity
internal data class Field(
val type: FieldType,
val text: String? = null,
val blob: ByteArray? = null,
val linesCount: Int = Int.MAX_VALUE,
val truncate: SettingsEntity.TruncateMode = SettingsEntity.TruncateMode.UNRECOGNIZED,
val blobPreview: SettingsEntity.BlobPreviewMode = SettingsEntity.BlobPreviewMode.UNRECOGNIZED
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Field
if (type != other.type) return false
if (text != other.text) return false
if (blob != null) {
if (other.blob == null) return false
if (!blob.contentEquals(other.blob)) return false
} else if (other.blob != null) return false
if (linesCount != other.linesCount) return false
if (truncate != other.truncate) return false
if (blobPreview != other.blobPreview) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result = 31 * result + (text?.hashCode() ?: 0)
result = 31 * result + (blob?.contentHashCode() ?: 0)
result = 31 * result + linesCount
result = 31 * result + truncate.hashCode()
result = 31 * result + blobPreview.hashCode()
return result
}
}
| apache-2.0 | 94d4d1fa46da6703a3c1b78d22cf741c | 35.682927 | 97 | 0.642287 | 4.502994 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/libanki/DecksTest.kt | 1 | 11728 | /*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki
import android.annotation.SuppressLint
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.libanki.Decks.Companion.CURRENT_DECK
import com.ichi2.libanki.backend.exception.DeckRenameException
import com.ichi2.testutils.AnkiAssert.assertDoesNotThrow
import com.ichi2.testutils.AnkiAssert.assertEqualsArrayList
import org.apache.http.util.Asserts
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@RunWith(AndroidJUnit4::class)
class DecksTest : RobolectricTest() {
@Test
@Suppress("SpellCheckingInspection")
fun ensureDeckList() {
val decks = col.decks
for (deckName in TEST_DECKS) {
addDeck(deckName)
}
val brokenDeck = decks.byName("cmxieunwoogyxsctnjmv::INSBGDS")
Asserts.notNull(brokenDeck, "We should get deck with given name")
// Changing the case. That could exists in an old collection or during sync.
brokenDeck!!.put("name", "CMXIEUNWOOGYXSCTNJMV::INSBGDS")
decks.save(brokenDeck)
decks.childMap()
for (deck in decks.all()) {
val did = deck.getLong("id")
for (parent in decks.parents(did)) {
Asserts.notNull(parent, "Parent should not be null")
}
}
}
@Test
fun trim() {
assertThat(Decks.strip("A\nB C\t D"), equalTo("A\nB C\t D"))
assertThat(Decks.strip("\n A\n\t"), equalTo("A"))
assertThat(Decks.strip("Z::\n A\n\t::Y"), equalTo("Z::A::Y"))
}
/******************
* autogenerated from https://github.com/ankitects/anki/blob/2c73dcb2e547c44d9e02c20a00f3c52419dc277b/pylib/tests/test_cards.py*
*/
@Test
fun test_basic() {
val col = col
val decks = col.decks
// we start with a standard col
assertEquals(1, decks.allSortedNames().size.toLong())
// it should have an id of 1
assertNotNull(decks.name(1))
// create a new col
val parentId = addDeck("new deck")
assertNotEquals(parentId, 0)
assertEquals(2, decks.allSortedNames().size.toLong())
// should get the same id
assertEquals(parentId, addDeck("new deck"))
// we start with the default col selected
assertEquals(1, decks.selected())
assertEqualsArrayList(arrayOf(1L), decks.active())
// we can select a different col
decks.select(parentId)
assertEquals(parentId, decks.selected())
assertEqualsArrayList(arrayOf(parentId), decks.active())
// let's create a child
val childId = addDeck("new deck::child")
col.reset()
// it should have been added to the active list
assertEquals(parentId, decks.selected())
assertEqualsArrayList(arrayOf(parentId, childId), decks.active())
// we can select the child individually too
decks.select(childId)
assertEquals(childId, decks.selected())
assertEqualsArrayList(arrayOf(childId), decks.active())
// parents with a different case should be handled correctly
addDeck("ONE")
val m = col.models.current()
m!!.put("did", addDeck("one::two"))
col.models.save(m, false)
val n = col.newNote()
n.setItem("Front", "abc")
col.addNote(n)
assertEquals(decks.id_for_name("new deck")!!.toLong(), parentId)
assertEquals(decks.id_for_name(" New Deck ")!!.toLong(), parentId)
assertNull(decks.id_for_name("Not existing deck"))
assertNull(decks.id_for_name("new deck::not either"))
}
@Test
fun test_remove() {
val col = col
// create a new col, and add a note/card to it
val deck1 = addDeck("deck1")
val note = col.newNote()
note.setItem("Front", "1")
note.model().put("did", deck1)
col.addNote(note)
val c = note.cards()[0]
assertEquals(deck1, c.did)
assertEquals(1, col.cardCount().toLong())
col.decks.rem(deck1)
assertEquals(0, col.cardCount().toLong())
// if we try to get it, we get the default
assertEquals("[no deck]", col.decks.name(c.did))
}
@Test
@SuppressLint("CheckResult")
@Throws(DeckRenameException::class)
fun test_rename() {
val col = col
var id = addDeck("hello::world")
// should be able to rename into a completely different branch, creating
// parents as necessary
val decks = col.decks
decks.rename(decks.get(id), "foo::bar")
var names: List<String?> = decks.allSortedNames()
assertTrue(names.contains("foo"))
assertTrue(names.contains("foo::bar"))
assertFalse(names.contains("hello::world"))
// create another col
/* TODO: do we want to follow upstream here ?
// automatically adjusted if a duplicate name
decks.rename(decks.get(id), "FOO");
names = decks.allSortedNames();
assertThat(names, containsString("FOO+"));
*/
// when renaming, the children should be renamed too
addDeck("one::two::three")
id = addDeck("one")
col.decks.rename(col.decks.get(id), "yo")
names = col.decks.allSortedNames()
for (n in arrayOf("yo", "yo::two", "yo::two::three")) {
assertTrue(names.contains(n))
}
// over filtered
val filteredId = addDynamicDeck("filtered")
col.decks.get(filteredId)
val childId = addDeck("child")
val child = col.decks.get(childId)
assertThrows(DeckRenameException::class.java) {
col.decks.rename(
child,
"filtered::child"
)
}
assertThrows(DeckRenameException::class.java) {
col.decks.rename(
child,
"FILTERED::child"
)
}
}
/* TODO: maybe implement. We don't drag and drop here anyway, so buggy implementation is okay
@Test public void test_renameForDragAndDrop() throws DeckRenameException {
// TODO: upstream does not return "default", remove it
Collection col = getCol();
long languages_did = addDeck("Languages");
long chinese_did = addDeck("Chinese");
long hsk_did = addDeck("Chinese::HSK");
// Renaming also renames children
col.getDecks().renameForDragAndDrop(chinese_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto itself is a no-op
col.getDecks().renameForDragAndDrop(languages_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto its parent is a no-op
col.getDecks().renameForDragAndDrop(hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto a descendant is a no-op
col.getDecks().renameForDragAndDrop(languages_did, hsk_did);
// TODO: real problem to correct, even if we don't have drag and drop
// assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Can drag a grandchild onto its grandparent. It becomes a child
col.getDecks().renameForDragAndDrop(hsk_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::HSK"}, col.getDecks().allSortedNames());
// Can drag a col onto its sibling
col.getDecks().renameForDragAndDrop(hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Can drag a col back to the top level
col.getDecks().renameForDragAndDrop(chinese_did, null);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Languages"}, col.getDecks().allSortedNames());
// Dragging a top level col to the top level is a no-op
col.getDecks().renameForDragAndDrop(chinese_did, null);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Languages"}, col.getDecks().allSortedNames());
// decks are renamed if necessary«
long new_hsk_did = addDeck("hsk");
col.getDecks().renameForDragAndDrop(new_hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Chinese::hsk+", "Languages"}, col.getDecks().allSortedNames());
col.getDecks().rem(new_hsk_did);
}
*/
@Test
fun curDeckIsLong() {
// Regression for #8092
val col = col
val decks = col.decks
val id = addDeck("test")
decks.select(id)
assertDoesNotThrow("curDeck should be saved as a long. A deck id.") {
col.get_config_long(
CURRENT_DECK
)
}
}
@Test
fun isDynStd() {
val col = col
val decks = col.decks
val filteredId = addDynamicDeck("filtered")
val filtered = decks.get(filteredId)
val deckId = addDeck("deck")
val deck = decks.get(deckId)
assertThat(deck.isStd, equalTo(true))
assertThat(deck.isDyn, equalTo(false))
assertThat(filtered.isStd, equalTo(false))
assertThat(filtered.isDyn, equalTo(true))
val filteredConfig = decks.confForDid(filteredId)
val deckConfig = decks.confForDid(deckId)
assertThat(deckConfig.isStd, equalTo((true)))
assertThat(deckConfig.isDyn, equalTo((false)))
assertThat(filteredConfig.isStd, equalTo((false)))
assertThat(filteredConfig.isDyn, equalTo((true)))
}
@Test
fun confForDidReturnsDefaultIfNotFound() {
// https://github.com/ankitects/anki/commit/94d369db18c2a6ac3b0614498d8abcc7db538633
val decks = col.decks
val d = decks.all()[0]
d.put("conf", 12L)
decks.save()
val config = decks.confForDid(d.getLong("id"))
assertThat(
"If a config is not found, return the default",
config.getLong("id"),
equalTo(1L)
)
}
companion object {
// Used in other class to populate decks.
@Suppress("SpellCheckingInspection")
val TEST_DECKS = arrayOf(
"scxipjiyozczaaczoawo",
"cmxieunwoogyxsctnjmv::abcdefgh::ZYXW",
"cmxieunwoogyxsctnjmv::INSBGDS",
"::foobar", // Addition test for issue #11026
"A::"
)
}
}
| gpl-3.0 | fc02f65efd382012bd80602938f87e8e | 38.877551 | 152 | 0.632975 | 4.235549 | false | true | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/components/DateSelectorHelper.kt | 1 | 3631 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.timetableapp.ui.components
import android.app.Activity
import android.app.DatePickerDialog
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.widget.DatePicker
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.util.DateUtils
import org.threeten.bp.LocalDate
/**
* A helper class for setting up a [TextView] to show and change the date.
*/
class DateSelectorHelper(val activity: Activity, @IdRes val textViewResId: Int) {
private val mTextView = activity.findViewById(textViewResId) as TextView
private var mDate: LocalDate? = null
/**
* Sets up this helper class, displaying the date and preparing actions for when the
* [TextView] is clicked.
*
* @param initialDate the date to initially display on the [TextView]. This can be null, in
* which case a hint text will be initially displayed.
* @param onDateSet a function to be invoked when the date has been changed
*/
fun setup(initialDate: LocalDate?,
onDateSet: (view: DatePicker, date: LocalDate) -> Unit) {
mDate = initialDate
updateDateText()
setupOnClick(onDateSet)
}
private fun setupOnClick(onDateSet: (DatePicker, LocalDate) -> Unit) = mTextView.setOnClickListener {
// N.B. month-1 and month+1 in code because Android month values are from 0-11 (to
// correspond with java.util.Calendar) but LocalDate month values are from 1-12.
val listener = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
onDateSet.invoke(view, LocalDate.of(year, month + 1, dayOfMonth))
}
val displayedDate = mDate ?: LocalDate.now()
DatePickerDialog(
activity,
listener,
displayedDate.year,
displayedDate.monthValue - 1,
displayedDate.dayOfMonth
).show()
}
/**
* Updates the displayed text according to the [date].
*
* @param date used to update the displayed text. This can be null, in which case a
* 'hint' text is shown.
* @param hintTextRes the string resource used to display the hint text
*/
@JvmOverloads
fun updateDate(date: LocalDate?, @StringRes hintTextRes: Int = R.string.property_date) {
mDate = date
updateDateText(hintTextRes)
}
private fun updateDateText(@StringRes hintTextRes: Int = R.string.property_date) {
val date = mDate
if (date == null) {
mTextView.text = activity.getString(hintTextRes)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black_secondary))
} else {
mTextView.text = date.format(DateUtils.FORMATTER_FULL_DATE)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black))
}
}
}
| apache-2.0 | 98ff574d9f16ba2332d49138f9552873 | 35.676768 | 105 | 0.673093 | 4.516169 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/driver/scsi/commands/ScsiInquiryResponse.kt | 2 | 2962 | /*
* (C) Copyright 2014 mjahnen <[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 me.jahnen.libaums.core.driver.scsi.commands
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.experimental.and
/**
* This class represents the response of a SCSI Inquiry. It holds various
* information about the mass storage device.
*
*
* This response is received in the data phase.
*
* @author mjahnen
* @see com.github.mjdev.libaums.driver.scsi.commands.ScsiInquiry
*/
class ScsiInquiryResponse private constructor() {
/**
*
* @return Zero if a device is connected to the unit.
*/
var peripheralQualifier: Byte = 0
private set
/**
* The type of the mass storage device.
*
* @return Zero for a direct access block device.
*/
var peripheralDeviceType: Byte = 0
private set
/**
*
* @return True if the media can be removed (eg. card reader).
*/
var isRemovableMedia: Boolean = false
internal set
/**
* This method returns the version of the SCSI Primary Commands (SPC)
* standard the device supports.
*
* @return Version of the SPC standard
*/
var spcVersion: Byte = 0
internal set
var responseDataFormat: Byte = 0
internal set
override fun toString(): String {
return ("ScsiInquiryResponse [peripheralQualifier=" + peripheralQualifier
+ ", peripheralDeviceType=" + peripheralDeviceType + ", removableMedia="
+ isRemovableMedia + ", spcVersion=" + spcVersion + ", responseDataFormat="
+ responseDataFormat + "]")
}
companion object {
/**
* Constructs a new object with the given data.
*
* @param buffer
* The data where the [.ScsiInquiryResponse] is located.
* @return The parsed [.ScsiInquiryResponse].
*/
fun read(buffer: ByteBuffer): ScsiInquiryResponse {
buffer.order(ByteOrder.LITTLE_ENDIAN)
val b = buffer.get()
return ScsiInquiryResponse().apply {
peripheralQualifier = b and 0xe0.toByte()
peripheralDeviceType = b and 0x1f.toByte()
isRemovableMedia = buffer.get().toInt() == 0x80
spcVersion = buffer.get()
responseDataFormat = buffer.get() and 0x7.toByte()
}
}
}
}
| apache-2.0 | 79b52a43a27cb32fdaba61bc1827282b | 30.178947 | 91 | 0.632681 | 4.508371 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/IDataProvider.kt | 1 | 2013 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.DataProvider
import org.spongepowered.api.data.DataTransactionResult
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import java.util.Optional
interface IDataProvider<V : Value<E>, E : Any> : DataProvider<V, E> {
override fun getKey(): Key<V>
override fun isSupported(container: DataHolder): Boolean
override fun allowsAsynchronousAccess(container: DataHolder): Boolean
@JvmDefault
override fun getValue(container: DataHolder): Optional<V> = super.getValue(container)
override fun get(container: DataHolder): Optional<E>
override fun offer(container: DataHolder.Mutable, element: E): DataTransactionResult
@JvmDefault
fun offerFast(container: DataHolder.Mutable, element: E) = offer(container, element).isSuccessful
@JvmDefault
override fun offerValue(container: DataHolder.Mutable, value: V): DataTransactionResult = super.offerValue(container, value)
@JvmDefault
fun offerValueFast(container: DataHolder.Mutable, value: V) = offerValue(container, value).isSuccessful
override fun remove(container: DataHolder.Mutable): DataTransactionResult
@JvmDefault
fun removeFast(container: DataHolder.Mutable) = remove(container).isSuccessful
override fun <I : DataHolder.Immutable<I>> with(immutable: I, element: E): Optional<I>
@JvmDefault
override fun <I : DataHolder.Immutable<I>> withValue(immutable: I, value: V): Optional<I> = super.withValue(immutable, value)
override fun <I : DataHolder.Immutable<I>> without(immutable: I): Optional<I>
}
| mit | d03cff81ff7e52d39d93a814f8e26442 | 35.6 | 129 | 0.752111 | 4.228992 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/callbacks/PaymentServiceEventHandler.kt | 1 | 809 | package com.mercadopago.android.px.internal.callbacks
import android.arch.lifecycle.MutableLiveData
import com.mercadopago.android.px.internal.viewmodel.PaymentModel
import com.mercadopago.android.px.model.Card
import com.mercadopago.android.px.model.PaymentRecovery
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.tracking.internal.model.Reason
internal class PaymentServiceEventHandler {
val paymentFinishedLiveData = MutableLiveData<Event<PaymentModel>>()
val requireCvvLiveData = MutableLiveData<Event<Pair<Card, Reason>>>()
val recoverInvalidEscLiveData = MutableLiveData<Event<PaymentRecovery>>()
val paymentErrorLiveData = MutableLiveData<Event<MercadoPagoError>>()
val visualPaymentLiveData = MutableLiveData<Event<Unit>>()
} | mit | 7bfd6c3e349b3390bc0a22d81f9754aa | 49.625 | 77 | 0.829419 | 4.649425 | false | false | false | false |
davidwhitman/changelogs | app/src/main/java/com/thunderclouddev/changelogs/ui/views/TextViewWithResizableCompoundDrawable.kt | 1 | 3467 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.views
import android.content.Context
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet
import com.thunderclouddev.changelogs.R
class TextViewWithResizableCompoundDrawable : AppCompatTextView {
private var mDrawableWidth: Int = 0
private var mDrawableHeight: Int = 0
constructor(context: Context) : super(context) {
init(context, null, 0, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs, 0, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs, defStyleAttr, 0)
}
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public TextViewWithResizableCompoundDrawable(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// init(context, attrs, defStyleAttr, defStyleRes);
// }
private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
val array = context.obtainStyledAttributes(attrs, R.styleable.TextViewWithResizableCompoundDrawable, defStyleAttr, defStyleRes)
try {
mDrawableWidth = array.getDimensionPixelSize(R.styleable.TextViewWithResizableCompoundDrawable_compoundDrawableWidth, -1)
mDrawableHeight = array.getDimensionPixelSize(R.styleable.TextViewWithResizableCompoundDrawable_compoundDrawableHeight, -1)
} finally {
array.recycle()
}
if (mDrawableWidth > 0 || mDrawableHeight > 0) {
initCompoundDrawableSize()
}
}
private fun initCompoundDrawableSize() {
val drawables =
if (compoundDrawables.any { it != null })
compoundDrawables
else
compoundDrawablesRelative
for (drawable in drawables) {
if (drawable == null) {
continue
}
val realBounds = drawable.bounds
val scaleFactor = realBounds.height() / realBounds.width().toFloat()
var drawableWidth = realBounds.width().toFloat()
var drawableHeight = realBounds.height().toFloat()
if (mDrawableWidth > 0) {
// save scale factor of image
if (drawableWidth > mDrawableWidth) {
drawableWidth = mDrawableWidth.toFloat()
drawableHeight = drawableWidth * scaleFactor
}
}
if (mDrawableHeight > 0) {
// save scale factor of image
if (drawableHeight > mDrawableHeight) {
drawableHeight = mDrawableHeight.toFloat()
drawableWidth = drawableHeight / scaleFactor
}
}
realBounds.right = realBounds.left + Math.round(drawableWidth)
realBounds.bottom = realBounds.top + Math.round(drawableHeight)
drawable.bounds = realBounds
}
setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3])
}
}
| gpl-3.0 | afd999bc55bc7b0eb8376fa0e24f749a | 35.494737 | 135 | 0.631093 | 5.174627 | false | false | false | false |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/retry/SyncRetryExecutorKotlinTest.kt | 1 | 4109 | /*
* Copyright (c) 2016. KESTI co, ltd
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.core.retry
import debop4k.core.asyncs.ready
import nl.komponents.kovenant.Kovenant
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.deferred
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.concurrent.atomic.*
/**
* SyncRetryExecutorKotlinTest
* @author debop [email protected]
*/
class SyncRetryExecutorKotlinTest : AbstractRetryKotlinTest() {
private val executor: RetryExecutor = SyncRetryExecutor
@Test
fun shouldReturnPromiseWhenDoWithRetryCalled() {
// given
val mainThread = Thread.currentThread().name
val poolThread = AtomicReference<String>()
// when
val promise = executor.doWithRetry { ctx -> poolThread.set(Thread.currentThread().name) }
promise.get()
assertThat(poolThread.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInPromiseRatherThanThrowingIt() {
val promise = executor.doWithRetry { ctx -> throw IllegalArgumentException(DON_T_PANIC) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryCalled() {
//given
val mainThread = Thread.currentThread().name
//when
val promise = executor.getWithRetry { Thread.currentThread().name }
//then
assertThat(promise.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetry() {
//given
val block = { throw IllegalArgumentException(DON_T_PANIC) }
val promise = executor.getWithRetry { ctx -> block() }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryCalledContext() {
//given
val mainThread = Thread.currentThread().name
//when
val promise = executor.getWithRetry { ctx -> Thread.currentThread().name }
//then
assertThat(promise.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetryContext() {
//given
val block = { ctx: RetryContext -> throw IllegalArgumentException(DON_T_PANIC) }
val promise = executor.getWithRetry { block.invoke(it) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryOnFutureCalled() {
//given
val mainThread = Thread.currentThread().name
//when
val result = executor.getFutureWithRetry { ctx -> Promise.of(Thread.currentThread().name) }
//then
assertThat(result.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetryOnFuture() {
//given
val block = { ctx: RetryContext ->
val defer = deferred<String, Exception>(Kovenant.context)
defer.reject(IllegalArgumentException(DON_T_PANIC))
defer.promise
}
val promise = executor.getFutureWithRetry<String> { block(it) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
} | apache-2.0 | 7901218ce785f0e27c48e755ad842595 | 29 | 95 | 0.722317 | 4.361996 | false | true | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/provider/ScheduleDatabase.kt | 1 | 4036 | package com.gdgnantes.devfest.android.provider
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
internal class ScheduleDatabase(private val context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "schedule.db"
private const val DATABASE_VERSION = 1
}
object Tables {
const val ROOMS = "Rooms"
const val SESSIONS = "Sessions"
const val SESSIONS_SPEAKERS = "SessionsSpeakers"
const val SPEAKERS = "Speakers"
const val SESSIONS_LJ_ROOMS = "Sessions " +
"LEFT JOIN Rooms ON session_room_id = room_id"
const val SESSIONS_LJ_ROOMS_LJ_SESSIONS_SPEAKERS_J_SPEAKERS = "Sessions " +
"LEFT JOIN Rooms ON session_room_id = room_id " +
"LEFT JOIN SessionsSpeakers ON session_speaker_session_id = session_id " +
"LEFT JOIN Speakers ON session_speaker_speaker_id = speaker_id"
const val SESSIONS_SPEAKERS_J_SESSIONS_J_SPEAKERS_LJ_ROOMS = "SessionsSpeakers " +
"JOIN Sessions ON session_speaker_session_id = session_id " +
"JOIN Speakers ON session_speaker_speaker_id = speaker_id " +
"LEFT JOIN Rooms ON session_room_id = room_id"
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE ${Tables.ROOMS} (" +
"${ScheduleContract.Rooms.ROOM_ID} TEXT NOT NULL, " +
"${ScheduleContract.Rooms.ROOM_NAME} TEXT, " +
"UNIQUE (${ScheduleContract.Rooms.ROOM_ID}) ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SESSIONS} (" +
"${ScheduleContract.Sessions.SESSION_ID} TEXT NOT NULL, " +
"${ScheduleContract.Sessions.SESSION_DESCRIPTION} TEXT, " +
"${ScheduleContract.Sessions.SESSION_END_TIMESTAMP} INTEGER, " +
"${ScheduleContract.Sessions.SESSION_LANGUAGE} TEXT, " +
"${ScheduleContract.Sessions.SESSION_ROOM_ID} TEXT, " +
"${ScheduleContract.Sessions.SESSION_START_TIMESTAMP} INTEGER, " +
"${ScheduleContract.Sessions.SESSION_TITLE} TEXT, " +
"${ScheduleContract.Sessions.SESSION_TRACK} TEXT, " +
"${ScheduleContract.Sessions.SESSION_TYPE} TEXT, " +
"UNIQUE (${ScheduleContract.Sessions.SESSION_ID}) ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SESSIONS_SPEAKERS} (" +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID} TEXT NOT NULL, " +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID} TEXT NOT NULL, " +
"UNIQUE (" +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID}, " +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID}) " +
"ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SPEAKERS} (" +
"${ScheduleContract.Speakers.SPEAKER_ID} TEXT NOT NULL, " +
"${ScheduleContract.Speakers.SPEAKER_BIO} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_COMPANY} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_NAME} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_PHOTO_URL} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_SOCIAL_LINKS} TEXT, " +
"UNIQUE (${ScheduleContract.Speakers.SPEAKER_ID}) ON CONFLICT REPLACE)")
ScheduleSeed(context).seed(db)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS ${Tables.ROOMS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SESSIONS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SESSIONS_SPEAKERS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SPEAKERS}")
onCreate(db)
}
}
| apache-2.0 | 7ec50141ee9c0e65bcfadad5926c0ba2 | 47.626506 | 99 | 0.619177 | 4.63908 | false | false | false | false |
actorapp/actor-bots | actor-bots/src/main/java/im/actor/bots/framework/persistence/KotlinExtensions.kt | 1 | 1123 | package im.actor.bots.framework.persistence
import akka.util.Timeout
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import shardakka.keyvalue.SimpleKeyValueJava
import java.io.ByteArrayOutputStream
import java.util.concurrent.TimeUnit
fun <T> ServerKeyValue.setDataClass(key: String, obj: T?) {
if (obj == null) {
setStringValue(key, null)
} else {
val output = ByteArrayOutputStream()
val generator = jacksonObjectMapper().jsonFactory.createGenerator(output)
generator.writeObject(obj)
val str = String(output.toByteArray())
setStringValue(key, str)
}
}
inline fun <reified T: Any> ServerKeyValue.getDataClass(key: String): T? {
val str = getStringValue(key)
if (str == null) {
return null
} else {
return jacksonObjectMapper().readValue<T>(str)
}
}
fun <T> SimpleKeyValueJava<T>.get(key: String): T? {
val res = syncGet(key, Timeout.apply(10, TimeUnit.SECONDS))
if (res.isPresent) {
return res.get()
} else {
return null
}
} | apache-2.0 | 15f387f6e5b2e8295adb3c823dc9867e | 28.578947 | 81 | 0.685663 | 3.940351 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/powdermaker/PowderMakerRegistry.kt | 1 | 11238 | package net.ndrei.teslapoweredthingies.machines.powdermaker
import com.google.gson.JsonElement
import net.minecraft.client.Minecraft
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.IRecipe
import net.minecraft.util.JsonUtils
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fml.common.discovery.ASMDataTable
import net.minecraftforge.fml.common.registry.GameRegistry
import net.minecraftforge.oredict.OreDictionary
import net.minecraftforge.registries.IForgeRegistry
import net.ndrei.teslacorelib.MaterialColors
import net.ndrei.teslacorelib.PowderRegistry
import net.ndrei.teslacorelib.TeslaCoreLib
import net.ndrei.teslacorelib.annotations.AutoRegisterRecipesHandler
import net.ndrei.teslacorelib.annotations.RegistryHandler
import net.ndrei.teslacorelib.config.readItemStack
import net.ndrei.teslacorelib.config.readItemStacks
import net.ndrei.teslacorelib.items.powders.ColoredPowderItem
import net.ndrei.teslacorelib.utils.copyWithSize
import net.ndrei.teslapoweredthingies.MOD_ID
import net.ndrei.teslapoweredthingies.common.*
import net.ndrei.teslapoweredthingies.config.readExtraRecipesFile
/**
* Created by CF on 2017-07-06.
*/
@RegistryHandler
object PowderMakerRegistry : BaseTeslaRegistry<PowderMakerRecipe>("powder_maker_recipes", PowderMakerRecipe::class.java) {
private val registeredDustNames = mutableListOf<String>()
private val registeredDusts = mutableListOf<ColoredPowderItem>()
override fun registerItems(asm : ASMDataTable, registry: IForgeRegistry<Item>) {
// get all ores
val ores = OreDictionary.getOreNames()
.filter { it.startsWith("ore") }
.map { it.substring(3) }
.filter { OreDictionary.doesOreNameExist("ingot$it") }
// register powder maker recipes
ores.forEach {
val dustName = "dust$it"
var hasDust = false
if (!OreDictionary.doesOreNameExist(dustName)) {
// look for an item with color
val color = MaterialColors.getColor(it)
if (color != null) {
val material = it.decapitalize()
PowderRegistry.addMaterial(it) { registry ->
val item = object: ColoredPowderItem(material, color, 0.0f, "ingot${material.capitalize()}") {}
registry.register(item)
item.registerRecipe { AutoRegisterRecipesHandler.registerRecipe(GameRegistry.findRegistry(IRecipe::class.java), it) }
if (TeslaCoreLib.isClientSide) {
item.registerRenderer()
registeredDusts.add(item)
}
OreDictionary.registerOre("dust${material.capitalize()}", item)
item
}
hasDust = true
}
} else {
hasDust = true
}
if (hasDust) {
this.registeredDustNames.add(it)
}
}
}
override fun registerRecipes(asm: ASMDataTable, registry: IForgeRegistry<IRecipe>) {
// register default recipes
// stones -> 75% gravel
listOf("stone", "cobblestone").forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_$it"),
OreDictionary.getOres(it).map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
}
listOf("stoneGranite", "stoneDiorite", "stoneAndesite").forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_$it"),
OreDictionary.getOres(it).map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_${it}Polished"),
OreDictionary.getOres("${it}Polished").map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
}
// vanilla default ore recipes
this.registerDefaultOreRecipe("coal")
this.registerDefaultOreRecipe("diamond")
this.registerDefaultOreRecipe("emerald")
this.registerDefaultOreRecipe("redstone")
this.registerDefaultOreRecipe("lapis")
// register dust recipes
this.registeredDustNames.forEach {
// register ingot -> dust
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_ingot$it"),
OreDictionary.getOres("ingot$it").map { it.copyWithSize(1) },
listOf(OreOutput("dust$it", 1))
))
// register ore -> dust
this.registerDefaultOreRecipe(it)
}
OreDictionary.getOreNames()
.filter { it.startsWith("ore") }
.map { it.substring(3) }
.filter { OreDictionary.doesOreNameExist("dust$it") }
.filter { key -> !this.hasRecipe { it.getPossibleInputs().any { OreDictionary.getOreIDs(it).contains(OreDictionary.getOreID("ore$key")) } } }
.forEach {
this.registerDefaultOreRecipe(it)
}
readExtraRecipesFile(PowderMakerBlock.registryName!!.path) { json ->
val inputs = json.readItemStacks("input_stack")
if (inputs.isNotEmpty() && json.has("outputs")) {
val secondary = json.getAsJsonArray("outputs").mapNotNull<JsonElement, SecondaryOutput> {
if (it.isJsonObject) {
val stack = it.asJsonObject.readItemStack() ?: return@mapNotNull null
val chance = JsonUtils.getFloat(it.asJsonObject, "chance", 1.0f)
if (chance > 0.0f) {
return@mapNotNull SecondaryOutput(Math.min(chance, 1.0f), stack)
}
}
return@mapNotNull null
}
if (secondary.isNotEmpty()) {
inputs.forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), secondary))
}
}
}
}
}
override fun postInit(asm: ASMDataTable) {
if (this.registeredDusts.isNotEmpty() && TeslaCoreLib.isClientSide) {
this.registeredDusts.forEach {
Minecraft.getMinecraft().itemColors.registerItemColorHandler({ s: ItemStack, t: Int -> it.getColorFromItemStack(s, t) }, arrayOf<Item>(it))
}
this.registeredDusts.clear()
}
}
//#region default ore recipes
private val defaultOreRecipes = mutableMapOf<String, (input: ItemStack, isOre: Boolean) -> PowderMakerRecipe>()
private fun findDefaultOreRecipe(oreKey: String, input: ItemStack, isOre: Boolean): PowderMakerRecipe? {
return if (this.defaultOreRecipes.containsKey(oreKey)) {
this.defaultOreRecipes[oreKey]?.invoke(input, isOre)
}
else null
}
fun registerDefaultOreRecipe(oreKey: String, input: ItemStack, isOre: Boolean) {
val recipe = this.findDefaultOreRecipe(oreKey, input, isOre)
if ((recipe != null) && recipe.ensureValidOutputs().isNotEmpty()) {
this.addRecipe(recipe)
}
else if (recipe == null) {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, input.item.registryName.toString().replace(':', '_')),
listOf(input), mutableListOf<IRecipeOutput>().also { list ->
list.add(OreOutput("dust${oreKey.capitalize()}", 2))
if (isOre) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
}))
}
}
private fun registerDefaultOreRecipe(oreKey: String) {
OreDictionary.getOres("ore${oreKey.capitalize()}").forEach { stack ->
this.registerDefaultOreRecipe(oreKey.decapitalize(), stack, true)
}
}
private fun addDefaultOreRecipe(key: String, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, "dust${key.capitalize()}", *output)
}
private fun addDefaultOreRecipe(key: String, primaryOutput: String, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, primaryOutput, 2, *output)
}
private fun addDefaultOreRecipe(key: String, primaryOutput: String, primaryOutputCount: Int, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, { it, ore ->
PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), mutableListOf<IRecipeOutput>().also { list ->
list.add(OreOutput(primaryOutput, primaryOutputCount))
if (ore) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
if (output.isNotEmpty()) {
list.addAll(output)
}
})
})
}
private fun addDefaultOreRecipe(key: String, builder: (input: ItemStack, isOre: Boolean) -> PowderMakerRecipe) {
this.defaultOreRecipes[key] = builder
}
init {
this.addDefaultOreRecipe("iron",
SecondaryOreOutput(0.05f, "dustTin", 1),
SecondaryOreOutput(0.1f, "dustNickel", 1))
this.addDefaultOreRecipe("gold")
this.addDefaultOreRecipe("copper",
SecondaryOreOutput(0.125f, "dustGold", 1))
this.addDefaultOreRecipe("tin")
this.addDefaultOreRecipe("silver",
SecondaryOreOutput(0.1f, "dustLead", 1))
this.addDefaultOreRecipe("lead",
SecondaryOreOutput(0.1f, "dustSilver", 1))
this.addDefaultOreRecipe("aluminum")
this.addDefaultOreRecipe("nickel",
SecondaryOreOutput(0.1f, "dustPlatinum", 1))
this.addDefaultOreRecipe("platinum")
this.addDefaultOreRecipe("iridium")
this.addDefaultOreRecipe("coal", { it, ore ->
PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), mutableListOf<IRecipeOutput>().also { list ->
list.add(Output(ItemStack(Items.COAL, 5)))
if (ore) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
})
})
this.addDefaultOreRecipe("diamond", "dustDiamond", 3)
this.addDefaultOreRecipe("emerald", "dustEmerald", 3)
this.addDefaultOreRecipe("redstone", "dustRedstone", 6)
this.addDefaultOreRecipe("lapis", "gemLapis", 5)
}
//#endregion
fun hasRecipe(stack: ItemStack) = this.hasRecipe { it.canProcess(stack) }
fun findRecipe(stack: ItemStack): PowderMakerRecipe? = this.findRecipe { it.canProcess(stack) }
}
| mit | fd97a984a36d90f3cb41b733f39fe592 | 42.057471 | 155 | 0.603488 | 4.894599 | false | false | false | false |
matiuri/Minesweeper | core/src/kotlin/mati/minesweeper/Game.kt | 1 | 8902 | package mati.minesweeper
import com.badlogic.gdx.Application.LOG_DEBUG
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.scenes.scene2d.InputListener
import mati.advancedgdx.AdvancedGame
import mati.advancedgdx.assets.FontLoader.FontLoaderParameter
import mati.advancedgdx.utils.isDesktop
import mati.minesweeper.board.Cell
import mati.minesweeper.screens.GameS
import mati.minesweeper.screens.NewGame
import mati.minesweeper.screens.StatsScreen
import mati.minesweeper.screens.Title
import mati.minesweeper.statistics.Statistics
import mati.minesweeper.statistics.Statistics.StatisticsSerializer
import java.security.MessageDigest
import kotlin.properties.Delegates
import kotlin.reflect.KClass
class Game(val cellInput: KClass<out InputListener>) : AdvancedGame() {
companion object Static {
var game: Game by Delegates.notNull<Game>()
var superDebug: Boolean by Delegates.notNull<Boolean>()
fun init(game: Game) {
this.game = game
superDebug = if (Gdx.files.local("debug").exists() &&
Gdx.files.local("debug").readString().substring(0, 2) == "on") {
val digest: MessageDigest = MessageDigest.getInstance("SHA-512")
val text = Gdx.files.local("debug").readString().substring(2)
digest.update(text.toByteArray())
val hasharr: ByteArray = digest.digest()
val sb: StringBuffer = StringBuffer()
for (i in hasharr.indices)
sb.append(Integer.toString((hasharr[i].toInt() and 0xff) + 0x100, 16).substring(1));
sb.toString() == "70620298b6ffda5a28a02eae45c3f07f930b6f6cbb41023134e86e160cb6b51290cbb03" +
"6db26bf750deb9d3c846737fccc3584543c84127056fbb6c574eb0b94"
} else false
}
}
var cursors: Array<Cursor> by Delegates.notNull<Array<Cursor>>()
var stats: Statistics by Delegates.notNull<Statistics>()
override fun create() {
Static.init(this)
super.create()
init(this)
Gdx.input.isCatchBackKey = true
Gdx.app.logLevel = LOG_DEBUG
prepare()
if (superDebug)
Gdx.gl.glClearColor(0.25f, 0f, 0f, 1f)
else
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1f)
}
private fun prepare() {
scrManager.add("Title", Title(this)).add("Game", GameS(this)).add("New", NewGame(this))
.add("Stats", StatsScreen(this))
astManager.queue("UbuntuBGen", "fonts/Ubuntu-B.ttf", FreeTypeFontGenerator::class)
.queue("UbuntuRGen", "fonts/Ubuntu-R.ttf", FreeTypeFontGenerator::class)
.queue("UbuntuMRGen", "fonts/UbuntuMono-R.ttf", FreeTypeFontGenerator::class)
.queue("Title", "TitleFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 64
it.color = Color.YELLOW
it.borderColor = Color.BLACK
it.borderWidth = 5f
})
.queue("GeneralW", "GeneralFontW", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.WHITE
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("GeneralB", "GeneralFontB", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.BLACK
it.borderColor = Color.WHITE
it.borderWidth = 1f
})
.queue("GeneralR", "GeneralFontR", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.RED
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("WarningF", "WarningFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 48
it.color = Color.WHITE
it.borderColor = Color.BLACK
it.borderWidth = 5f
})
.queue("TimerF", "TimerFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuMRGen"]) {
it.size = 24
it.color = Color.GOLD
it.borderColor = Color.WHITE
it.borderWidth = 0.5f
})
.queue("GameOverF", "GameOverFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 32
it.color = Color.RED
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("WinF", "WinFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 32
it.color = Color.GREEN
it.borderColor = Color.WHITE
it.borderWidth = 1f
})
.queue("AndroidF", "AndroidFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 16
it.color = Color.WHITE
})
.queue("ButtonUp", "GUI/ButtonUp.png", Texture::class)
.queue("ButtonDown", "GUI/ButtonDown.png", Texture::class)
.queue("ButtonLocked", "GUI/ButtonLocked.png", Texture::class)
.queue("CellUp", "game/CellUp.png", Texture::class)
.queue("CellDown", "game/CellDown.png", Texture::class)
.queue("CellOpen", "game/CellOpen.png", Texture::class)
.queue("N", "game/", ".png", Texture::class, 1, 7)
.queue("Mine", "game/Mine.png", Texture::class)
.queue("Mine1", "game/Mine1.png", Texture::class)
.queue("Flag", "game/Flag.png", Texture::class)
.queue("CursorBlue", "GUI/CursorBlue.png", Pixmap::class)
.queue("CursorRed", "GUI/CursorRed.png", Pixmap::class)
.queue("GUIb", "GUI/GUIb.png", Texture::class)
.queue("GUIt", "GUI/GUIt.png", Texture::class)
.queue("GUIl", "GUI/GUIl.png", Texture::class)
.queue("CamDD", "GUI/CamDownDown.png", Texture::class)
.queue("CamDU", "GUI/CamDownUp.png", Texture::class)
.queue("CamLD", "GUI/CamLeftDown.png", Texture::class)
.queue("CamLU", "GUI/CamLeftUp.png", Texture::class)
.queue("CamRD", "GUI/CamRightDown.png", Texture::class)
.queue("CamRU", "GUI/CamRightUp.png", Texture::class)
.queue("CamUD", "GUI/CamUpDown.png", Texture::class)
.queue("CamUU", "GUI/CamUpUp.png", Texture::class)
.queue("CamPU", "GUI/CamPlusUp.png", Texture::class)
.queue("CamPD", "GUI/CamPlusDown.png", Texture::class)
.queue("CamMU", "GUI/CamMinusUp.png", Texture::class)
.queue("CamMD", "GUI/CamMinusDown.png", Texture::class)
.queue("CamCU", "GUI/CamCenterUp.png", Texture::class)
.queue("CamCD", "GUI/CamCenterDown.png", Texture::class)
.queue("Dialog", "GUI/Dialog.png", Texture::class)
.queue("PauseUp", "GUI/PauseUp.png", Texture::class)
.queue("PauseDown", "GUI/PauseDown.png", Texture::class)
.queue("OpenS", "sounds/Open.ogg", Sound::class)
.queue("ExplosionS", "sounds/Explosion.ogg", Sound::class)
.queue("WinS", "sounds/Win.ogg", Sound::class)
.load {
if (isDesktop()) {
cursors = arrayOf(Gdx.graphics.newCursor(astManager["CursorBlue", Pixmap::class], 0, 0),
Gdx.graphics.newCursor(astManager["CursorRed", Pixmap::class], 0, 0))
Gdx.graphics.setCursor(cursors[0])
}
Cell.init(this)
scrManager.loadAll()
scrManager.change("Title")
if (ioManager.exists("stats")) stats = ioManager.load("stats", StatisticsSerializer::class)
else stats = Statistics()
if (!stats.cheated) {
stats.cheated = superDebug
stats.save()
}
}
}
override fun render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
super.render()
}
}
| gpl-2.0 | 9dd0e685721fcc50b92f755c8611e884 | 49.011236 | 118 | 0.552685 | 4.281866 | false | false | false | false |
ansman/okhttp | okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt | 3 | 5738 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls.internal.der
import java.math.BigInteger
import okio.Buffer
import okio.BufferedSink
import okio.ByteString
internal class DerWriter(sink: BufferedSink) {
/** A stack of buffers that will be concatenated once we know the length of each. */
private val stack = mutableListOf(sink)
/** Type hints scoped to the call stack, manipulated with [pushTypeHint] and [popTypeHint]. */
private val typeHintStack = mutableListOf<Any?>()
/**
* The type hint for the current object. Used to pick adapters based on other fields, such as
* in extensions which have different types depending on their extension ID.
*/
var typeHint: Any?
get() = typeHintStack.lastOrNull()
set(value) {
typeHintStack[typeHintStack.size - 1] = value
}
/** Names leading to the current location in the ASN.1 document. */
private val path = mutableListOf<String>()
/**
* False unless we made a recursive call to [write] at the current stack frame. The explicit box
* adapter can clear this to synthesize non-constructed values that are embedded in octet strings.
*/
var constructed = false
fun write(name: String, tagClass: Int, tag: Long, block: (BufferedSink) -> Unit) {
val constructedBit: Int
val content = Buffer()
stack.add(content)
constructed = false // The enclosed object written in block() is not constructed.
path += name
try {
block(content)
constructedBit = if (constructed) 0b0010_0000 else 0
constructed = true // The enclosing object is constructed.
} finally {
stack.removeAt(stack.size - 1)
path.removeAt(path.size - 1)
}
val sink = sink()
// Write the tagClass, tag, and constructed bit. This takes 1 byte if tag is less than 31.
if (tag < 31) {
val byte0 = tagClass or constructedBit or tag.toInt()
sink.writeByte(byte0)
} else {
val byte0 = tagClass or constructedBit or 0b0001_1111
sink.writeByte(byte0)
writeVariableLengthLong(tag)
}
// Write the length. This takes 1 byte if length is less than 128.
val length = content.size
if (length < 128) {
sink.writeByte(length.toInt())
} else {
// count how many bytes we'll need to express the length.
val lengthBitCount = 64 - java.lang.Long.numberOfLeadingZeros(length)
val lengthByteCount = (lengthBitCount + 7) / 8
sink.writeByte(0b1000_0000 or lengthByteCount)
for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) {
sink.writeByte((length shr shift).toInt())
}
}
// Write the payload.
sink.writeAll(content)
}
/**
* Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no
* longer usable by the current type's members.
*/
fun <T> withTypeHint(block: () -> T): T {
typeHintStack.add(null)
try {
return block()
} finally {
typeHintStack.removeAt(typeHintStack.size - 1)
}
}
private fun sink(): BufferedSink = stack[stack.size - 1]
fun writeBoolean(b: Boolean) {
sink().writeByte(if (b) -1 else 0)
}
fun writeBigInteger(value: BigInteger) {
sink().write(value.toByteArray())
}
fun writeLong(v: Long) {
val sink = sink()
val lengthBitCount: Int = if (v < 0L) {
65 - java.lang.Long.numberOfLeadingZeros(v xor -1L)
} else {
65 - java.lang.Long.numberOfLeadingZeros(v)
}
val lengthByteCount = (lengthBitCount + 7) / 8
for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) {
sink.writeByte((v shr shift).toInt())
}
}
fun writeBitString(bitString: BitString) {
val sink = sink()
sink.writeByte(bitString.unusedBitsCount)
sink.write(bitString.byteString)
}
fun writeOctetString(byteString: ByteString) {
sink().write(byteString)
}
fun writeUtf8(value: String) {
sink().writeUtf8(value)
}
fun writeObjectIdentifier(s: String) {
val utf8 = Buffer().writeUtf8(s)
val v1 = utf8.readDecimalLong()
require(utf8.readByte() == '.'.toByte())
val v2 = utf8.readDecimalLong()
writeVariableLengthLong(v1 * 40 + v2)
while (!utf8.exhausted()) {
require(utf8.readByte() == '.'.toByte())
val vN = utf8.readDecimalLong()
writeVariableLengthLong(vN)
}
}
fun writeRelativeObjectIdentifier(s: String) {
// Add a leading dot so each subidentifier has a dot prefix.
val utf8 = Buffer()
.writeByte('.'.toByte().toInt())
.writeUtf8(s)
while (!utf8.exhausted()) {
require(utf8.readByte() == '.'.toByte())
val vN = utf8.readDecimalLong()
writeVariableLengthLong(vN)
}
}
/** Used for tags and subidentifiers. */
private fun writeVariableLengthLong(v: Long) {
val sink = sink()
val bitCount = 64 - java.lang.Long.numberOfLeadingZeros(v)
val byteCount = (bitCount + 6) / 7
for (shift in (byteCount - 1) * 7 downTo 0 step 7) {
val lastBit = if (shift == 0) 0 else 0b1000_0000
sink.writeByte(((v shr shift) and 0b0111_1111).toInt() or lastBit)
}
}
override fun toString() = path.joinToString(separator = " / ")
}
| apache-2.0 | 650d4eda6ff2df9f2af72826cdbc7b1b | 29.849462 | 100 | 0.660857 | 3.976438 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/activities/BaseActivity.kt | 1 | 1952 | package com.quickblox.sample.pushnotifications.kotlin.activities
import android.app.ProgressDialog
import android.content.DialogInterface
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import com.quickblox.sample.pushnotifications.kotlin.R
import com.quickblox.sample.pushnotifications.kotlin.utils.showSnackbar
abstract class BaseActivity : AppCompatActivity() {
private var progressDialog: ProgressDialog? = null
protected fun showProgressDialog(@StringRes messageId: Int) {
if (progressDialog == null) {
progressDialog = ProgressDialog(this)
progressDialog?.isIndeterminate = true
progressDialog?.setCancelable(false)
progressDialog?.setCanceledOnTouchOutside(false)
// disable the back button
val keyListener = DialogInterface.OnKeyListener { dialog, keyCode, event -> keyCode == KeyEvent.KEYCODE_BACK }
progressDialog?.setOnKeyListener(keyListener)
}
progressDialog?.setMessage(getString(messageId))
progressDialog?.show()
}
override fun onPause() {
super.onPause()
hideProgressDialog()
}
protected fun hideProgressDialog() {
if (progressDialog?.isShowing == true) {
progressDialog?.dismiss()
}
}
protected fun showErrorSnackbar(@StringRes resId: Int, e: Exception, clickListener: View.OnClickListener?) {
val rootView = window.decorView.findViewById<View>(android.R.id.content)
rootView?.let {
showSnackbar(it, resId, e, R.string.dlg_retry, clickListener)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
} | bsd-3-clause | 6d0da3e2a4e9d121ff87f1e688528209 | 33.875 | 122 | 0.690574 | 5.304348 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/data/PortalRepository.kt | 1 | 14964 | package jp.kentan.studentportalplus.data
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import jp.kentan.studentportalplus.data.component.LectureQuery
import jp.kentan.studentportalplus.data.component.NoticeQuery
import jp.kentan.studentportalplus.data.component.PortalData
import jp.kentan.studentportalplus.data.component.PortalDataSet
import jp.kentan.studentportalplus.data.dao.*
import jp.kentan.studentportalplus.data.model.*
import jp.kentan.studentportalplus.data.parser.LectureCancellationParser
import jp.kentan.studentportalplus.data.parser.LectureInformationParser
import jp.kentan.studentportalplus.data.parser.MyClassParser
import jp.kentan.studentportalplus.data.parser.NoticeParser
import jp.kentan.studentportalplus.data.shibboleth.ShibbolethClient
import jp.kentan.studentportalplus.data.shibboleth.ShibbolethDataProvider
import jp.kentan.studentportalplus.util.getSimilarSubjectThresholdFloat
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.jetbrains.anko.defaultSharedPreferences
class PortalRepository(
private val context: Context,
shibbolethDataProvider: ShibbolethDataProvider
) {
private val client = ShibbolethClient(context, shibbolethDataProvider)
private val similarSubjectThresholdListener: SharedPreferences.OnSharedPreferenceChangeListener
private val noticeParser = NoticeParser()
private val lectureInfoParser = LectureInformationParser()
private val lectureCancelParser = LectureCancellationParser()
private val myClassParser = MyClassParser()
private val noticeDao = NoticeDao(context.database)
private val lectureInfoDao: LectureInformationDao
private val lectureCancelDao: LectureCancellationDao
private val myClassDao = MyClassDao(context.database)
private val _portalDataSet = MutableLiveData<PortalDataSet>()
private val noticeList = MutableLiveData<List<Notice>>()
private val lectureInfoList = MutableLiveData<List<LectureInformation>>()
private val lectureCancelList = MutableLiveData<List<LectureCancellation>>()
private val _myClassList = MutableLiveData<List<MyClass>>()
val portalDataSet: LiveData<PortalDataSet>
get() = _portalDataSet
val myClassList: LiveData<List<MyClass>>
get() = _myClassList
val subjectList: LiveData<List<String>> by lazy {
return@lazy MediatorLiveData<List<String>>().apply {
addSource(lectureInfoList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
addSource(lectureCancelList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
addSource(_myClassList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
}
}
init {
val threshold = context.defaultSharedPreferences.getSimilarSubjectThresholdFloat()
lectureInfoDao = LectureInformationDao(context.database, threshold)
lectureCancelDao = LectureCancellationDao(context.database, threshold)
similarSubjectThresholdListener = SharedPreferences.OnSharedPreferenceChangeListener { pref, key ->
if (key == "similar_subject_threshold") {
val th = pref.getSimilarSubjectThresholdFloat()
lectureInfoDao.similarThreshold = th
lectureCancelDao.similarThreshold = th
GlobalScope.launch {
postValues(
lectureInfoList = lectureInfoDao.getAll(),
lectureCancelList = lectureCancelDao.getAll()
)
}
}
}
context.defaultSharedPreferences.registerOnSharedPreferenceChangeListener(similarSubjectThresholdListener)
}
@Throws(Exception::class)
fun sync() = GlobalScope.async {
val noticeList = noticeParser.parse(PortalData.NOTICE.fetchDocument())
val lectureInfoList = lectureInfoParser.parse(PortalData.LECTURE_INFO.fetchDocument())
val lectureCancelList = lectureCancelParser.parse(PortalData.LECTURE_CANCEL.fetchDocument())
val myClassList = myClassParser.parse(PortalData.MY_CLASS.fetchDocument())
myClassDao.updateAll(myClassList)
val updatedNoticeList = noticeDao.updateAll(noticeList)
val updatedLectureInfoList = lectureInfoDao.updateAll(lectureInfoList)
val updatedLectureCancelList = lectureCancelDao.updateAll(lectureCancelList)
loadFromDb().await()
return@async mapOf(
PortalData.NOTICE to updatedNoticeList,
PortalData.LECTURE_INFO to updatedLectureInfoList,
PortalData.LECTURE_CANCEL to updatedLectureCancelList
)
}
fun loadFromDb() = GlobalScope.async {
postValues(
noticeList = noticeDao.getAll(),
lectureInfoList = lectureInfoDao.getAll(),
lectureCancelList = lectureCancelDao.getAll(),
myClassList = myClassDao.getAll()
)
}
fun getNoticeList(query: NoticeQuery): LiveData<List<Notice>> {
val result = MediatorLiveData<List<Notice>>()
result.addSource(noticeList) { list ->
GlobalScope.launch {
result.postValue(
list.filter { notice ->
if (query.isUnread && notice.isRead) {
return@filter false
}
if (query.isRead && !notice.isRead) {
return@filter false
}
if (query.isFavorite && !notice.isFavorite) {
return@filter false
}
if (query.dateRange != NoticeQuery.DateRange.ALL) {
return@filter notice.createdDate.time >= query.dateRange.time
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any { notice.title.contains(it, true) }
}
return@filter true
}
)
}
}
return result
}
fun getLectureInfoList(query: LectureQuery): LiveData<List<LectureInformation>> {
val result = MediatorLiveData<List<LectureInformation>>()
result.addSource(lectureInfoList) { list ->
GlobalScope.launch {
val filtered = list.filter { lecture ->
if (query.isUnread && lecture.isRead) {
return@filter false
}
if (query.isRead && !lecture.isRead) {
return@filter false
}
if (query.isAttend && !lecture.attend.isAttend()) {
return@filter false
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any {
lecture.subject.contains(it, true) || lecture.instructor.contains(it, true)
}
}
return@filter true
}
result.postValue(
if (query.order == LectureQuery.Order.ATTEND_CLASS) {
filtered.sortedBy { !it.attend.isAttend() }
} else {
filtered
}
)
}
}
return result
}
fun getLectureCancelList(query: LectureQuery): LiveData<List<LectureCancellation>> {
val result = MediatorLiveData<List<LectureCancellation>>()
result.addSource(lectureCancelList) { list ->
GlobalScope.launch {
val filtered = list.filter { lecture ->
if (query.isUnread && lecture.isRead) {
return@filter false
}
if (query.isRead && !lecture.isRead) {
return@filter false
}
if (query.isAttend && !lecture.attend.isAttend()) {
return@filter false
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any {
lecture.subject.contains(it, true) || lecture.instructor.contains(it, true)
}
}
return@filter true
}
result.postValue(
if (query.order == LectureQuery.Order.ATTEND_CLASS) {
filtered.sortedBy { !it.attend.isAttend() }
} else {
filtered
}
)
}
}
return result
}
fun getMyClassSubjectList() = myClassDao.getSubjectList()
fun getNotice(id: Long): LiveData<Notice> {
if (noticeList.value == null) {
loadFromDb()
}
return Transformations.map(noticeList) { list -> list.find { it.id == id } }
}
fun getLectureInfo(id: Long): LiveData<LectureInformation> {
if (lectureInfoList.value == null) {
loadFromDb()
}
return Transformations.map(lectureInfoList) { list -> list.find { it.id == id } }
}
fun getLectureCancel(id: Long): LiveData<LectureCancellation> {
if (lectureCancelList.value == null) {
loadFromDb()
}
return Transformations.map(lectureCancelList) { list -> list.find { it.id == id } }
}
fun getMyClass(id: Long, isAllowNullOnlyFirst: Boolean = false): LiveData<MyClass> {
val result = MediatorLiveData<MyClass>()
var isFirst = true
result.addSource(_myClassList) { list ->
val data = list.find { it.id == id }
if (!isAllowNullOnlyFirst || isFirst || data != null) {
result.value = data
}
isFirst = false
}
return result
}
fun getMyClassWithSync(id: Long) = _myClassList.value?.find { it.id == id }
fun updateNotice(data: Notice) = GlobalScope.async {
if (noticeDao.update(data) > 0) {
postValues(noticeList = noticeDao.getAll())
return@async true
}
return@async false
}
fun updateLectureInfo(data: LectureInformation) = GlobalScope.async {
if (lectureInfoDao.update(data) > 0) {
postValues(lectureInfoList = lectureInfoDao.getAll())
return@async true
}
return@async false
}
fun updateLectureCancel(data: LectureCancellation) = GlobalScope.async {
if (lectureCancelDao.update(data) > 0) {
postValues(lectureCancelList = lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun updateMyClass(data: MyClass) = GlobalScope.async {
if (myClassDao.update(data) > 0) {
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun addMyClass(data: MyClass) = GlobalScope.async {
if (myClassDao.insert(listOf(data)) > 0) {
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun addToMyClass(data: Lecture) = GlobalScope.async {
try {
val list = myClassParser.parse(data)
myClassDao.insert(list)
} catch (e: Exception) {
Log.e("PortalRepository", "Failed to add to MyClass", e)
return@async false
}
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll()
)
return@async true
}
fun deleteFromMyClass(subject: String) = GlobalScope.async {
try {
myClassDao.delete(subject)
} catch (e: Exception) {
Log.e("PortalRepository", "Failed to delete from MyClass", e)
return@async false
}
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll()
)
return@async true
}
fun deleteAll() = GlobalScope.async {
val isSuccess = context.deleteDatabase(context.database.databaseName)
if (isSuccess) {
postValues(emptyList(), emptyList(), emptyList(), emptyList())
}
return@async isSuccess
}
private fun postValues(
myClassList: List<MyClass>? = null,
lectureInfoList: List<LectureInformation>? = null,
lectureCancelList: List<LectureCancellation>? = null,
noticeList: List<Notice>? = null
) {
var postCount = 0
var set = _portalDataSet.value ?: PortalDataSet()
if (myClassList != null) {
postCount++
this._myClassList.postValue(myClassList)
set = set.copy(myClassList = myClassList)
}
if (lectureInfoList != null) {
postCount++
this.lectureInfoList.postValue(lectureInfoList)
set = set.copy(lectureInfoList = lectureInfoList)
}
if (lectureCancelList != null) {
postCount++
this.lectureCancelList.postValue(lectureCancelList)
set = set.copy(lectureCancelList = lectureCancelList)
}
if (noticeList != null) {
postCount++
this.noticeList.postValue(noticeList)
set = set.copy(noticeList = noticeList)
}
if (postCount > 0 && _portalDataSet.value != set) {
_portalDataSet.postValue(set)
}
Log.d("PortalRepository", "posted $postCount lists")
}
private fun PortalData.fetchDocument() = client.fetch(url)
} | gpl-3.0 | 7ea5970e5b8a226a540c89e426b2c2f1 | 33.88345 | 114 | 0.570837 | 5.573184 | false | false | false | false |
sandjelkovic/dispatchd | content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/trakt/converter/Trakt2SeasonConverter.kt | 1 | 811 | package com.sandjelkovic.dispatchd.content.trakt.converter
import com.sandjelkovic.dispatchd.content.data.entity.Season
import com.sandjelkovic.dispatchd.content.trakt.dto.SeasonTrakt
import org.springframework.core.convert.converter.Converter
/**
* @author sandjelkovic
* @date 14.4.18.
*/
class Trakt2SeasonConverter : Converter<SeasonTrakt, Season> {
override fun convert(source: SeasonTrakt): Season = Season().apply {
number = source.number
description = source.overview ?: ""
airDate = source.firstAired
episodesCount = source.episodeCount ?: 0
episodesAiredCount = source.airedEpisodes
traktId = source.ids.getOrDefault("trakt", "")
imdbId = source.ids.getOrDefault("imdb", "")
tvdbId = source.ids.getOrDefault("tvdb", "")
}
}
| apache-2.0 | 8900d10869e5c046ed0d2e4183d443c7 | 35.863636 | 72 | 0.709001 | 4.31383 | false | false | false | false |
arturbosch/detekt | detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/baseline/BaselineResultMapping.kt | 1 | 1654 | package io.gitlab.arturbosch.detekt.core.baseline
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.ReportingExtension
import io.gitlab.arturbosch.detekt.api.RuleSetId
import io.gitlab.arturbosch.detekt.api.SetupContext
import io.gitlab.arturbosch.detekt.api.UnstableApi
import io.gitlab.arturbosch.detekt.api.getOrNull
import io.gitlab.arturbosch.detekt.core.DetektResult
import java.nio.file.Path
@OptIn(UnstableApi::class)
class BaselineResultMapping : ReportingExtension {
private var baselineFile: Path? = null
private var createBaseline: Boolean = false
override fun init(context: SetupContext) {
baselineFile = context.getOrNull(DETEKT_BASELINE_PATH_KEY)
createBaseline = context.getOrNull(DETEKT_BASELINE_CREATION_KEY) ?: false
}
override fun transformFindings(findings: Map<RuleSetId, List<Finding>>): Map<RuleSetId, List<Finding>> {
val baselineFile = baselineFile
require(!createBaseline || (createBaseline && baselineFile != null)) {
"Invalid baseline options invariant."
}
return baselineFile?.let { findings.transformWithBaseline(it) } ?: findings
}
private fun Map<RuleSetId, List<Finding>>.transformWithBaseline(baselinePath: Path): Map<RuleSetId, List<Finding>> {
val facade = BaselineFacade()
val flatten = this.flatMap { it.value }
if (flatten.isEmpty()) {
return this
}
if (createBaseline) {
facade.createOrUpdate(baselinePath, flatten)
}
return facade.transformResult(baselinePath, DetektResult(this)).findings
}
}
| apache-2.0 | d1a9294970d8da5679e193b802ee602f | 34.956522 | 120 | 0.717654 | 4.458221 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserActionGroup.kt | 1 | 9816 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import org.jetbrains.plugins.github.api.GithubRepositoryPath
import org.jetbrains.plugins.github.pullrequest.action.GithubPullRequestKeys
import org.jetbrains.plugins.github.util.GithubGitHelper
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GithubOpenInBrowserActionGroup
: ActionGroup("Open on GitHub", "Open corresponding link in browser", AllIcons.Vcs.Vendors.Github), DumbAware {
override fun update(e: AnActionEvent) {
val repositories = getData(e.dataContext)?.first
e.presentation.isEnabledAndVisible = repositories != null && repositories.isNotEmpty()
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.first.size <= 1) return emptyArray()
return data.first.map { GithubOpenInBrowserAction(it, data.second) }.toTypedArray()
}
override fun isPopup(): Boolean = true
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first.first(), it.second) }?.actionPerformed(e)
}
override fun canBePerformed(context: DataContext): Boolean {
return getData(context)?.first?.size == 1
}
override fun disableIfNoVisibleChildren(): Boolean = false
protected open fun getData(dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val pullRequest = dataContext.getData(GithubPullRequestKeys.SELECTED_PULL_REQUEST) ?: return null
val serverPath = dataContext.getData(GithubPullRequestKeys.SERVER_PATH) ?: return null
val fullPath = dataContext.getData(GithubPullRequestKeys.FULL_PATH) ?: return null
val htmlUrl = pullRequest.pullRequestLinks?.htmlUrl ?: return null
return setOf(GithubRepositoryPath(serverPath, fullPath)) to Data.URL(project, htmlUrl)
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val filePath = dataContext.getData(VcsDataKeys.FILE_PATH) ?: return null
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFile(filePath)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories to Data.Revision(project, fileRevision.revisionNumber.asString())
}
private fun getDataFromLog(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val log = dataContext.getData(VcsLogDataKeys.VCS_LOG) ?: return null
val selectedCommits = log.selectedCommits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(commit.root)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories to Data.Revision(project, commit.hash.asString())
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories to Data.File(project, repository.root, virtualFile)
}
protected sealed class Data(val project: Project) {
class File(project: Project, val gitRepoRoot: VirtualFile, val virtualFile: VirtualFile) : Data(project)
class Revision(project: Project, val revisionHash: String) : Data(project)
class URL(project: Project, val htmlUrl: String) : Data(project)
}
private companion object {
private const val CANNOT_OPEN_IN_BROWSER = "Can't open in browser"
class GithubOpenInBrowserAction(private val repoPath: GithubRepositoryPath, val data: Data)
: DumbAwareAction(repoPath.toString().replace('_', ' ')) {
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(repoPath, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, repoPath, data.virtualFile, e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GithubRepositoryPath, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GithubRepositoryPath,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "File is not under repository root",
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "Can't get last revision.")
return
}
val githubUrl = makeUrlToOpen(editor, relativePath, hash, path)
if (githubUrl != null) BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, "Getting Last Revision", true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
private fun makeUrlToOpen(editor: Editor?,
relativePath: String,
branch: String,
path: GithubRepositoryPath): String? {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(relativePath)
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
}
}
} | apache-2.0 | aacf72bb596c91f1227cefd112a16938 | 43.420814 | 140 | 0.713529 | 4.935143 | false | false | false | false |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/app/mvi/RedViewModelFactory.kt | 1 | 960 | package com.benoitquenaudon.tvfoot.red.app.mvi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class RedViewModelFactory @Inject constructor(
private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class $modelClass")
}
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException()
}
}
} | apache-2.0 | a32e60054ab6345feea6424fa54d8808 | 28.121212 | 92 | 0.684375 | 4.444444 | false | false | false | false |
cjkent/osiris | integration/src/test/kotlin/ws/osiris/integration/IntegrationTests.kt | 1 | 3842 | package ws.osiris.integration
import com.google.gson.Gson
import org.testng.annotations.Test
import ws.osiris.core.ContentType
import ws.osiris.core.HttpHeaders
import ws.osiris.core.InMemoryTestClient
import ws.osiris.core.JSON_CONTENT_TYPE
import ws.osiris.core.MimeTypes
import ws.osiris.core.TestClient
import ws.osiris.localserver.LocalHttpTestClient
import java.nio.file.Paths
import kotlin.test.assertEquals
import kotlin.test.assertTrue
private val components: TestComponents = TestComponentsImpl("Bob", 42)
private const val STATIC_DIR = "src/test/static"
@Test
class InMemoryIntegrationTest {
fun testApiInMemory() {
val client = InMemoryTestClient.create(components, api, Paths.get(STATIC_DIR))
assertApi(client)
}
}
@Test
class LocalHttpIntegrationTest {
fun testApiLocalHttpServer() {
LocalHttpTestClient.create(api, components, STATIC_DIR).use { assertApi(it) }
}
}
internal fun assertApi(client: TestClient) {
val gson = Gson()
fun Any?.parseJson(): Map<*, *> {
val json = this as? String ?: throw IllegalArgumentException("Value is not a string: $this")
return gson.fromJson(json, Map::class.java)
}
val rootResponse = client.get("/")
assertEquals(mapOf("message" to "hello, root!"), rootResponse.body.parseJson())
assertEquals(JSON_CONTENT_TYPE, ContentType.parse(rootResponse.headers[HttpHeaders.CONTENT_TYPE]!!))
assertEquals(200, rootResponse.status)
val response1 = client.get("/helloworld")
assertEquals(mapOf("message" to "hello, world!"), response1.body.parseJson())
assertEquals(JSON_CONTENT_TYPE, ContentType.parse(rootResponse.headers[HttpHeaders.CONTENT_TYPE]!!))
assertEquals(200, response1.status)
val response2 = client.get("/helloplain")
assertEquals("hello, world!", response2.body)
assertEquals(MimeTypes.TEXT_PLAIN, response2.headers[HttpHeaders.CONTENT_TYPE])
assertEquals(mapOf("message" to "hello, world!"), client.get("/hello/queryparam1").body.parseJson())
assertEquals(mapOf("message" to "hello, Alice!"), client.get("/hello/queryparam1?name=Alice").body.parseJson())
assertEquals(mapOf("message" to "hello, Tom!"), client.get("/hello/queryparam2?name=Tom").body.parseJson())
assertEquals(mapOf("message" to "hello, Peter!"), client.get("/hello/Peter").body.parseJson())
assertEquals(mapOf("message" to "hello, Bob!"), client.get("/hello/env").body.parseJson())
assertEquals(mapOf("message" to "hello, Max!"), client.post("/foo", "{\"name\":\"Max\"}").body.parseJson())
val response3 = client.get("/hello/queryparam2")
assertEquals(400, response3.status)
assertEquals("No value named 'name'", response3.body)
assertEquals(mapOf("message" to "foo 123 found"), client.get("/foo/123").body.parseJson())
val response5 = client.get("/foo/234")
assertEquals(404, response5.status)
assertEquals("No foo found with ID 234", response5.body)
val response6 = client.get("/servererror")
assertEquals(500, response6.status)
assertEquals("Server Error", response6.body)
val response7 = client.get("/public")
assertEquals(200, response7.status)
val body7 = response7.body
assertTrue(body7 is String && body7.contains("hello, world!"))
val response8 = client.get("/public/")
assertEquals(200, response8.status)
val body8 = response8.body
assertTrue(body8 is String && body8.contains("hello, world!"))
val response9 = client.get("/public/index.html")
assertEquals(200, response9.status)
val body9 = response9.body
assertTrue(body9 is String && body9.contains("hello, world!"))
val response10 = client.get("/public/baz/bar.html")
assertEquals(200, response10.status)
val body10 = response10.body
assertTrue(body10 is String && body10.contains("hello, bar!"))
}
| apache-2.0 | a419ce2039354199acb92974cc58ada2 | 39.020833 | 115 | 0.716814 | 3.924413 | false | true | false | false |
AlexLandau/semlang | kotlin/semlang-language-server/src/main/kotlin/server.kt | 1 | 6874 | package net.semlang.languageserver
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.eclipse.lsp4j.services.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CopyOnWriteArrayList
interface LanguageClientProvider {
fun getLanguageClient(): LanguageClient
}
class SemlangLanguageServer: LanguageServer, LanguageClientAware, LanguageClientProvider {
private val languageClientHolder = CopyOnWriteArrayList<LanguageClient>()
private val textDocumentService = SemlangTextDocumentService(this)
private val workspaceService = SemlangWorkspaceService(this)
override fun getTextDocumentService(): TextDocumentService {
return textDocumentService
}
override fun exit() {
System.exit(0)
}
override fun initialize(params: InitializeParams?): CompletableFuture<InitializeResult> {
// TODO: Configure capabilities
val capabilities = ServerCapabilities()
val textDocumentSyncOptions = TextDocumentSyncOptions()
textDocumentSyncOptions.openClose = true
textDocumentSyncOptions.change = TextDocumentSyncKind.Full // TODO: Incremental would be better
capabilities.setTextDocumentSync(textDocumentSyncOptions)
val result = InitializeResult(capabilities)
return CompletableFuture.completedFuture(result)
}
override fun getWorkspaceService(): WorkspaceService {
return workspaceService
}
override fun shutdown(): CompletableFuture<Any> {
// TODO: Release unused resources
return CompletableFuture.completedFuture(null)
}
override fun connect(client: LanguageClient) {
if (!languageClientHolder.isEmpty()) {
error("Expected empty languageClientHolder")
}
languageClientHolder.add(client)
}
override fun getLanguageClient(): LanguageClient {
return languageClientHolder[0]
}
}
class SemlangWorkspaceService(private val languageClientProvider: LanguageClientProvider): WorkspaceService {
override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didChangeConfiguration(params: DidChangeConfigurationParams?) {
// TODO: If we ever have settings, update them here.
}
override fun symbol(params: WorkspaceSymbolParams?): CompletableFuture<MutableList<out SymbolInformation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
class SemlangTextDocumentService(private val languageClientProvider: LanguageClientProvider): TextDocumentService {
val model = AllModulesModel(languageClientProvider)
override fun resolveCompletionItem(unresolved: CompletionItem?): CompletableFuture<CompletionItem> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun codeAction(params: CodeActionParams?): CompletableFuture<MutableList<out Command>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hover(position: TextDocumentPositionParams?): CompletableFuture<Hover> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun documentHighlight(position: TextDocumentPositionParams?): CompletableFuture<MutableList<out DocumentHighlight>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onTypeFormatting(params: DocumentOnTypeFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun definition(position: TextDocumentPositionParams?): CompletableFuture<MutableList<out Location>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rangeFormatting(params: DocumentRangeFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun codeLens(params: CodeLensParams?): CompletableFuture<MutableList<out CodeLens>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rename(params: RenameParams?): CompletableFuture<WorkspaceEdit> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun completion(position: TextDocumentPositionParams?): CompletableFuture<Either<MutableList<CompletionItem>, CompletionList>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun documentSymbol(params: DocumentSymbolParams?): CompletableFuture<MutableList<out SymbolInformation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didOpen(params: DidOpenTextDocumentParams) {
val document = params.textDocument
model.documentWasOpened(document.uri, document.text)
}
override fun didSave(params: DidSaveTextDocumentParams?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun signatureHelp(position: TextDocumentPositionParams?): CompletableFuture<SignatureHelp> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didClose(params: DidCloseTextDocumentParams) {
val document = params.textDocument
model.documentWasClosed(document.uri)
}
override fun formatting(params: DocumentFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didChange(params: DidChangeTextDocumentParams) {
val document = params.textDocument
model.documentWasUpdated(document.uri, params.contentChanges[0].text)
}
override fun references(params: ReferenceParams?): CompletableFuture<MutableList<out Location>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun resolveCodeLens(unresolved: CodeLens?): CompletableFuture<CodeLens> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| apache-2.0 | 4c1a9bb04736708ee25e1442fa36e38e | 43.064103 | 140 | 0.739308 | 5.324555 | false | false | false | false |
android-gems/inspector | inspector/src/main/kotlin/kotlinx/html/AttributeTypes.kt | 3 | 2804 | package kotlinx.html
public abstract class Attribute<T>(val name: String) {
public fun get(tag: HtmlTag, property: PropertyMetadata): T {
return decode(tag[name]);
}
public fun set(tag: HtmlTag, property: PropertyMetadata, value: T) {
tag[name] = encode(value);
}
public abstract fun encode(t: T): String
public abstract fun decode(s: String): T
}
public open class StringAttribute(name: String) : Attribute<String>(name) {
public override fun encode(t: String): String {
return t // TODO: it actually might need HTML escaping
}
public override fun decode(s: String): String {
return s // TODO: it actually might need decode
}
}
public class TextAttribute(name: String) : StringAttribute(name)
public class RegexpAttribute(name: String) : StringAttribute(name)
public class IdAttribute(name: String) : StringAttribute(name)
public class MimeAttribute(name: String) : StringAttribute(name)
public class IntAttribute(name: String) : Attribute<Int>(name) {
public override fun encode(t: Int): String {
return t.toString()
}
public override fun decode(s: String): Int {
return s.toInt()
}
}
public open class BooleanAttribute(name: String, val trueValue: String = "true", val falseValue: String = "false") : Attribute<Boolean>(name) {
public override fun encode(t: Boolean): String {
return if (t) trueValue else falseValue
}
public override fun decode(s: String): Boolean {
return when (s) {
trueValue -> true
falseValue -> false
else -> throw RuntimeException("Unknown value for $name=$s")
}
}
}
public class TickerAttribute(name: String) : BooleanAttribute(name, name, "")
public class LinkAttribute(name: String) : Attribute<Link>(name) {
public override fun encode(t: Link): String {
return t.href()
}
public override fun decode(s: String): Link {
return DirectLink(s)
}
}
public interface StringEnum<T : Enum<T>> : Enum<T> {
public val value: String get() = name()
}
public class EnumAttribute<T : StringEnum<T>>(name: String, val klass: Class<T>) : Attribute<T>(name) {
public override fun encode(t: T): String {
return t.value
}
public override fun decode(s: String): T {
for (c in klass.getEnumConstants()) {
if (encode(c) == s) return c
}
throw RuntimeException("Can't decode '$s' as value of '${klass.getName()}'")
}
}
public class MimeTypesAttribute(name: String) : Attribute<List<String>>(name) {
public override fun encode(t: List<String>): String {
return t.join(",")
}
public override fun decode(s: String): List<String> {
return s.split(',').map { it.trim() }
}
}
| mit | ebafdbf62feef230e8f4f5275fb2ae3d | 29.150538 | 143 | 0.644437 | 3.994302 | false | false | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/main/java/dWallet/core/infrastructure/Event.kt | 1 | 561 | package dwallet.core.infrastructure
/**
* Created by unsignedint8 on 8/18/17.
*/
open class Event {
private val observers = mutableMapOf<String, MutableList<EventCallback>>()
protected fun register(event: String, callback: EventCallback) {
var list = observers[event]
if (list == null) {
list = mutableListOf()
observers[event] = list
}
list.add(callback)
}
protected fun trigger(event: String, sender: Any, params: Any) = observers[event]?.forEach { it.invoke(sender, params) }
} | gpl-3.0 | a5072d09c2b60bb308cd46b2ce0eedd0 | 23.434783 | 124 | 0.636364 | 4.218045 | false | false | false | false |
AndroidX/androidx | appsearch/appsearch-ktx/src/androidTest/java/AnnotationProcessorKtTest.kt | 3 | 11682 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appsearch.ktx
import android.content.Context
import androidx.appsearch.annotation.Document
import androidx.appsearch.app.AppSearchSchema
import androidx.appsearch.app.AppSearchSession
import androidx.appsearch.app.GenericDocument
import androidx.appsearch.app.PutDocumentsRequest
import androidx.appsearch.app.SearchSpec
import androidx.appsearch.app.SetSchemaRequest
import androidx.appsearch.localstorage.LocalStorage
import androidx.appsearch.testutil.AppSearchTestUtils.checkIsBatchResultSuccess
import androidx.appsearch.testutil.AppSearchTestUtils.convertSearchResultsToDocuments
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
public class AnnotationProcessorKtTest {
private companion object {
private const val DB_NAME = ""
}
private lateinit var session: AppSearchSession
@Before
public fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
session = LocalStorage.createSearchSessionAsync(
LocalStorage.SearchContext.Builder(context, DB_NAME).build()
).get()
// Cleanup whatever documents may still exist in these databases. This is needed in
// addition to tearDown in case a test exited without completing properly.
cleanup()
}
@After
public fun tearDown() {
// Cleanup whatever documents may still exist in these databases.
cleanup()
}
private fun cleanup() {
session.setSchemaAsync(SetSchemaRequest.Builder().setForceOverride(true).build()).get()
}
@Document
internal data class Card(
@Document.Namespace
val namespace: String,
@Document.Id
val id: String,
@Document.CreationTimestampMillis
val creationTimestampMillis: Long = 0L,
@Document.StringProperty(
indexingType = AppSearchSchema.StringPropertyConfig.INDEXING_TYPE_PREFIXES,
tokenizerType = AppSearchSchema.StringPropertyConfig.TOKENIZER_TYPE_PLAIN
)
val string: String? = null,
)
@Document
internal data class Gift(
@Document.Namespace
val namespace: String,
@Document.Id
val id: String,
@Document.CreationTimestampMillis
val creationTimestampMillis: Long = 0L,
// Collections
@Document.LongProperty
val collectLong: Collection<Long>,
@Document.LongProperty
val collectInteger: Collection<Int>,
@Document.DoubleProperty
val collectDouble: Collection<Double>,
@Document.DoubleProperty
val collectFloat: Collection<Float>,
@Document.BooleanProperty
val collectBoolean: Collection<Boolean>,
@Document.BytesProperty
val collectByteArr: Collection<ByteArray>,
@Document.StringProperty
val collectString: Collection<String>,
@Document.DocumentProperty
val collectCard: Collection<Card>,
// Arrays
@Document.LongProperty
val arrBoxLong: Array<Long>,
@Document.LongProperty
val arrUnboxLong: LongArray,
@Document.LongProperty
val arrBoxInteger: Array<Int>,
@Document.LongProperty
val arrUnboxInt: IntArray,
@Document.DoubleProperty
val arrBoxDouble: Array<Double>,
@Document.DoubleProperty
val arrUnboxDouble: DoubleArray,
@Document.DoubleProperty
val arrBoxFloat: Array<Float>,
@Document.DoubleProperty
val arrUnboxFloat: FloatArray,
@Document.BooleanProperty
val arrBoxBoolean: Array<Boolean>,
@Document.BooleanProperty
val arrUnboxBoolean: BooleanArray,
@Document.BytesProperty
val arrUnboxByteArr: Array<ByteArray>,
@Document.BytesProperty
val boxByteArr: Array<Byte>,
@Document.StringProperty
val arrString: Array<String>,
@Document.DocumentProperty
val arrCard: Array<Card>,
// Single values
@Document.StringProperty
val string: String,
@Document.LongProperty
val boxLong: Long,
@Document.LongProperty
val unboxLong: Long = 0,
@Document.LongProperty
val boxInteger: Int,
@Document.LongProperty
val unboxInt: Int = 0,
@Document.DoubleProperty
val boxDouble: Double,
@Document.DoubleProperty
val unboxDouble: Double = 0.0,
@Document.DoubleProperty
val boxFloat: Float,
@Document.DoubleProperty
val unboxFloat: Float = 0f,
@Document.BooleanProperty
val boxBoolean: Boolean,
@Document.BooleanProperty
val unboxBoolean: Boolean = false,
@Document.BytesProperty
val unboxByteArr: ByteArray,
@Document.DocumentProperty
val card: Card
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Gift
if (namespace != other.namespace) return false
if (id != other.id) return false
if (collectLong != other.collectLong) return false
if (collectInteger != other.collectInteger) return false
if (collectDouble != other.collectDouble) return false
if (collectFloat != other.collectFloat) return false
if (collectBoolean != other.collectBoolean) return false
// It's complicated to do a deep comparison of this, so we skip it
// if (collectByteArr != other.collectByteArr) return false
if (collectString != other.collectString) return false
if (collectCard != other.collectCard) return false
if (!arrBoxLong.contentEquals(other.arrBoxLong)) return false
if (!arrUnboxLong.contentEquals(other.arrUnboxLong)) return false
if (!arrBoxInteger.contentEquals(other.arrBoxInteger)) return false
if (!arrUnboxInt.contentEquals(other.arrUnboxInt)) return false
if (!arrBoxDouble.contentEquals(other.arrBoxDouble)) return false
if (!arrUnboxDouble.contentEquals(other.arrUnboxDouble)) return false
if (!arrBoxFloat.contentEquals(other.arrBoxFloat)) return false
if (!arrUnboxFloat.contentEquals(other.arrUnboxFloat)) return false
if (!arrBoxBoolean.contentEquals(other.arrBoxBoolean)) return false
if (!arrUnboxBoolean.contentEquals(other.arrUnboxBoolean)) return false
if (!arrUnboxByteArr.contentDeepEquals(other.arrUnboxByteArr)) return false
if (!boxByteArr.contentEquals(other.boxByteArr)) return false
if (!arrString.contentEquals(other.arrString)) return false
if (!arrCard.contentEquals(other.arrCard)) return false
if (string != other.string) return false
if (boxLong != other.boxLong) return false
if (unboxLong != other.unboxLong) return false
if (boxInteger != other.boxInteger) return false
if (unboxInt != other.unboxInt) return false
if (boxDouble != other.boxDouble) return false
if (unboxDouble != other.unboxDouble) return false
if (boxFloat != other.boxFloat) return false
if (unboxFloat != other.unboxFloat) return false
if (boxBoolean != other.boxBoolean) return false
if (unboxBoolean != other.unboxBoolean) return false
if (!unboxByteArr.contentEquals(other.unboxByteArr)) return false
if (card != other.card) return false
return true
}
}
@Test
fun testAnnotationProcessor() {
session.setSchemaAsync(
SetSchemaRequest.Builder()
.addDocumentClasses(Card::class.java, Gift::class.java).build()
).get()
// Create a Gift object and assign values.
val inputDocument = createPopulatedGift()
// Index the Gift document and query it.
checkIsBatchResultSuccess(
session.putAsync(
PutDocumentsRequest.Builder().addDocuments(inputDocument).build()
)
)
val searchResults = session.search("", SearchSpec.Builder().build())
val documents = convertSearchResultsToDocuments(searchResults)
assertThat(documents).hasSize(1)
// Convert GenericDocument to Gift and check values.
val outputDocument = documents[0].toDocumentClass(Gift::class.java)
assertThat(outputDocument).isEqualTo(inputDocument)
}
@Test
fun testGenericDocumentConversion() {
val inGift = createPopulatedGift()
val genericDocument1 = GenericDocument.fromDocumentClass(inGift)
val genericDocument2 = GenericDocument.fromDocumentClass(inGift)
val outGift = genericDocument2.toDocumentClass(Gift::class.java)
assertThat(inGift).isNotSameInstanceAs(outGift)
assertThat(inGift).isEqualTo(outGift)
assertThat(genericDocument1).isNotSameInstanceAs(genericDocument2)
assertThat(genericDocument1).isEqualTo(genericDocument2)
}
private fun createPopulatedGift(): Gift {
val card1 = Card("card.namespace", "card.id1")
val card2 = Card("card.namespace", "card.id2")
return Gift(
namespace = "gift.namespace",
id = "gift.id",
arrBoxBoolean = arrayOf(true, false),
arrBoxDouble = arrayOf(0.0, 1.0),
arrBoxFloat = arrayOf(2.0f, 3.0f),
arrBoxInteger = arrayOf(4, 5),
arrBoxLong = arrayOf(6L, 7L),
arrString = arrayOf("cat", "dog"),
boxByteArr = arrayOf(8, 9),
arrUnboxBoolean = booleanArrayOf(false, true),
arrUnboxByteArr = arrayOf(byteArrayOf(0, 1), byteArrayOf(2, 3)),
arrUnboxDouble = doubleArrayOf(1.0, 0.0),
arrUnboxFloat = floatArrayOf(3.0f, 2.0f),
arrUnboxInt = intArrayOf(5, 4),
arrUnboxLong = longArrayOf(7, 6),
arrCard = arrayOf(card2, card2),
collectLong = listOf(6L, 7L),
collectInteger = listOf(4, 5),
collectBoolean = listOf(false, true),
collectString = listOf("cat", "dog"),
collectDouble = listOf(0.0, 1.0),
collectFloat = listOf(2.0f, 3.0f),
collectByteArr = listOf(byteArrayOf(0, 1), byteArrayOf(2, 3)),
collectCard = listOf(card2, card2),
string = "String",
boxLong = 1L,
unboxLong = 2L,
boxInteger = 3,
unboxInt = 4,
boxDouble = 5.0,
unboxDouble = 6.0,
boxFloat = 7.0f,
unboxFloat = 8.0f,
boxBoolean = true,
unboxBoolean = false,
unboxByteArr = byteArrayOf(1, 2, 3),
card = card1
)
}
}
| apache-2.0 | e0c59aea3068e82d23ec876da8c89265 | 34.293051 | 95 | 0.646807 | 4.823287 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/Position.kt | 1 | 3832 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.sudoku
/**
* A two dimensional cartesian Coordinate.
* Implemented as Flyweight (not quite, but Position.get(x,y) gives memoized objects)
*
* @property x the x coordinate
* @property y the y coordinate
*
*/
class Position(var x: Int, var y: Int) {
/**
* Instanziiert ein neues Position-Objekt mit den spezifizierten x- und y-Koordinaten. Ist eine der Koordinaten
* kleiner als 0, so wird eine IllegalArgumentException geworfen.
*
* @throws IllegalArgumentException
* Wird geworfen, falls eine der Koordinaten kleiner als 0 ist
*/
/** Identifies, if this Position is a Flyweight and thus may not be changed. */
private var fixed = true
/**
* Tests for equality with other [Position].
*
* @return true if obj is of same type and coordinates match
*/
override fun equals(obj: Any?): Boolean {
return if (obj == null || obj !is Position) {
false
} else {
x == obj.x
&& y == obj.y
}
}
/**
* Generates a unique hashcode for coordinates `< 65519`
*/
override fun hashCode(): Int {
val p = 65519
val q = 65521
return x * p + y * q
}
/**
* returns a distance vector by subtracting the parameter. (both objects remain unchanged)
* @param p a position to substract from this position
* @return distance between this and other as position(this-p)
*/
fun distance(p: Position): Position {
return Position(x - p.x, y - p.y)
}
/**
* Returns a String Representation of this Position.
*/
override fun toString(): String {
return "$x, $y"
}
companion object {
/**
* Das statische Position-Array
*/
private var positions: Array<Array<Position>>? = null
/**
* Returns a [Position] with the specified coordinates
*
* @param x the desired x-coordinate
* @param y the desired y-coordinate
* @return Position Object with the coordinates
* @throws IllegalArgumentException if either coordinate is > 0
*/
@JvmStatic
operator fun get(x: Int, y: Int): Position {
require(x >= 0 && y >= 0) { "a parameter is less than zero" }
if (positions == null) {
initializePositions()
}
return if (x < 25 && y < 25) {
positions!![x][y]
} else {
val pos = Position(x, y)
pos.fixed = false
pos
}
}
/**
* Initialises the Position Array for efficient Position storage.
*/
private fun initializePositions() {
positions = Array(25) { Array(25) { Position(0, 0) } }
for (x in 0..24) {
for (y in 0..24) {
positions!![x][y] = Position(x, y)
}
}
}
}
} | gpl-3.0 | a5fa146665319129c4f10a27684a12fe | 32.321739 | 243 | 0.587053 | 4.383295 | false | false | false | false |
ioc1778/incubator | incubator-events/src/main/java/com/riaektiv/loop/LongEventHandler.kt | 2 | 1015 | package com.riaektiv.loop
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.CountDownLatch
/**
* Coding With Passion Since 1991
* Created: 4/1/2017, 2:59 PM Eastern Time
* @author Sergey Chuykov
*/
class LongEventHandler(var eventsToConsume: Int, var latch: CountDownLatch) : EventHandler<LongEvent> {
val l: Logger = LoggerFactory.getLogger(javaClass)
constructor() : this(0, CountDownLatch(1)) {
}
var checkSequence = false
var consumed = 0
override fun consumed(): Int {
return consumed
}
override fun onEvent(event: LongEvent) {
if (consumed < eventsToConsume) {
if(checkSequence && consumed.toLong() != event.value) {
l.debug("consumed={} {}", consumed, event)
l.debug("Failed")
latch.countDown()
}
if (++consumed >= eventsToConsume) {
l.debug("Done")
latch.countDown()
}
}
}
} | bsd-3-clause | 22fbaf168bed8031debf501bc39aa6ae | 24.4 | 103 | 0.596059 | 4.319149 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/cli/options/OptionDefinition.kt | 1 | 3213 | /*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.cli.options
abstract class OptionDefinition(
val group: OptionGroup,
val longName: String,
val description: String,
val acceptsValue: Boolean,
val shortName: Char? = null,
val allowMultiple: Boolean = false
) {
private var alreadySeen: Boolean = false
abstract val valueSource: OptionValueSource
val longOption = "--$longName"
val shortOption = if (shortName != null) "-$shortName" else null
init {
if (longName == "") {
throw IllegalArgumentException("Option long name must not be empty.")
}
if (longName.startsWith("-")) {
throw IllegalArgumentException("Option long name must not start with a dash.")
}
if (longName.length < 2) {
throw IllegalArgumentException("Option long name must be at least two characters long.")
}
if (description == "") {
throw IllegalArgumentException("Option description must not be empty.")
}
if (shortName != null && !shortName.isLetterOrDigit()) {
throw IllegalArgumentException("Option short name must be alphanumeric.")
}
}
fun parse(args: Iterable<String>): OptionParsingResult {
if (args.none()) {
throw IllegalArgumentException("List of arguments cannot be empty.")
}
if (alreadySeen && !allowMultiple) {
return specifiedMultipleTimesError()
}
val arg = args.first()
val argName = arg.substringBefore("=")
if (!nameMatches(argName)) {
throw IllegalArgumentException("Next argument in list of arguments is not for this option.")
}
alreadySeen = true
return parseValue(args)
}
private fun specifiedMultipleTimesError(): OptionParsingResult {
val shortOptionHint = if (shortName != null) " (or '$shortOption')" else ""
return OptionParsingResult.InvalidOption("Option '$longOption'$shortOptionHint cannot be specified multiple times.")
}
private fun nameMatches(nameFromArgument: String): Boolean {
return nameFromArgument == longOption || nameFromArgument == shortOption
}
internal abstract fun parseValue(args: Iterable<String>): OptionParsingResult
internal abstract fun checkDefaultValue(): DefaultApplicationResult
open val descriptionForHelp: String = description
open val valueFormatForHelp: String = "value"
}
sealed class DefaultApplicationResult {
object Succeeded : DefaultApplicationResult()
data class Failed(val message: String) : DefaultApplicationResult()
}
| apache-2.0 | 394a19aa92f3c31617830c2a9d1a76a4 | 32.821053 | 124 | 0.676004 | 5.149038 | false | false | false | false |
applivery/applivery-android-sdk | applivery-data/src/main/java/com/applivery/data/response/Mappers.kt | 1 | 758 | package com.applivery.data.response
import com.applivery.base.domain.model.UserProfile
import com.applivery.base.domain.model.UserType
import java.text.SimpleDateFormat
import java.util.Locale
fun UserEntity.toDomain(): UserProfile = UserProfile(
id = id.orEmpty(),
email = email,
firstName = firstName,
fullName = fullName,
lastName = lastName,
type = type?.toDomain(),
createdAt = createdAt?.let {
runCatching {
SimpleDateFormat(
ServerResponse.ApiDateFormat,
Locale.getDefault()
).parse(it)
}.getOrNull()
}
)
fun ApiUserType.toDomain(): UserType = when (this) {
ApiUserType.User -> UserType.User
ApiUserType.Employee -> UserType.Employee
}
| apache-2.0 | 277e96155122dc258c450e2614da1d3f | 26.071429 | 53 | 0.663588 | 4.432749 | false | false | false | false |
androidx/androidx | compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/util/AnchorMap.kt | 3 | 1504 | /*
* 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.compose.ui.inspection.util
import java.util.IdentityHashMap
const val NO_ANCHOR_ID = 0
/**
* A map of anchors with a unique id generator.
*/
class AnchorMap {
private val anchorLookup = mutableMapOf<Int, Any>()
private val idLookup = IdentityHashMap<Any, Int>()
/**
* Return a unique id for the specified [anchor] instance.
*/
operator fun get(anchor: Any?): Int =
anchor?.let { idLookup.getOrPut(it) { generateUniqueId(it) } } ?: NO_ANCHOR_ID
/**
* Return the anchor associated with a given unique anchor [id].
*/
operator fun get(id: Int): Any? = anchorLookup[id]
private fun generateUniqueId(anchor: Any): Int {
var id = anchor.hashCode()
while (id == NO_ANCHOR_ID || anchorLookup.containsKey(id)) {
id++
}
anchorLookup[id] = anchor
return id
}
}
| apache-2.0 | b79210eeed51c56e0ed3ca3afe25066b | 29.693878 | 86 | 0.670878 | 4.064865 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/TyFunctionGenerator.kt | 1 | 4932 | package org.elm.ide.intentions
import org.elm.lang.core.imports.ImportAdder.Import
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmFunctionDeclarationLeft
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.moduleName
import org.elm.lang.core.resolve.scope.ModuleScope
import org.elm.lang.core.types.*
abstract class TyFunctionGenerator(
protected val file: ElmFile,
protected val root: Ty
) {
data class GeneratedFunction(
val name: String,
val paramTy: Ty,
val paramName: String,
val body: String,
val qualifier: String
)
data class Ref(val module: String, val name: String)
fun TyUnion.toRef() = Ref(module, name)
fun AliasInfo.toRef() = Ref(module, name)
fun DeclarationInTy.toRef() = Ref(module, name)
/** All types and aliases referenced in the root ty */
protected val declarations by lazy { root.allDeclarations().toList() }
/** Additional encoder functions to generate */
protected val funcsByTy = mutableMapOf<Ty, GeneratedFunction>()
/** Cache of already existing callable expressions that aren't in [funcsByTy] */
private val callablesByTy = mutableMapOf<Ty, String>()
/** Unions that need their variants exposed. */
protected val unionsToExpose = mutableSetOf<Ref>()
/** The name of the module in the current file */
protected val moduleName by lazy { file.getModuleDecl()?.name ?: "" }
/** The name to use for the encoder function for each type (does not include the "encoder" prefix) */
// There might be multiple types with the same name in different modules, so add the module
// name the function for any type with a conflict that isn't defined in this module
protected val funcNames by lazy {
declarations.groupBy { it.name }
.map { (_, decls) ->
decls.map {
it.toRef() to when {
decls.size == 1 -> it.name
else -> it.module.replace(".", "") + it.name
}
}
}.flatten().toMap()
}
/** Qualified names of all imported modules */
private val importedModules: Set<String> by lazy {
file.findChildrenByClass(ElmImportClause::class.java).mapTo(mutableSetOf()) { it.referenceName }
}
/** Generate the code and imports for this function */
fun run(): Pair<String, List<Import>> = generateCode() to generateImports()
/** The code to insert for this function */
protected abstract fun generateCode(): String
/** The list of imports needed by generated code. */
protected open fun generateImports(): List<Import> {
val visibleTypes = ModuleScope.getVisibleTypes(file).all
.mapNotNullTo(mutableSetOf()) { it.name?.let { n -> Ref(it.moduleName, n) } }
// Hack in List since GlobalScope.getVisibleTypes can't return it
val visibleModules = importedModules + "List"
return declarations
.filter {
it.module != moduleName &&
(it.toRef() in unionsToExpose || it.module !in visibleModules && it.toRef() !in visibleTypes)
}
.map {
Import(
moduleName = it.module,
moduleAlias = null,
nameToBeExposed = if (it.isUnion) "${it.name}(..)" else ""
)
}
}
/** Get the module qualifier prefix to add to a name */
protected fun qualifierFor(ref: Ref): String {
return when (ref.module) {
moduleName -> ""
// We always fully qualify references to modules that we add imports for
!in importedModules -> "${ref.module}."
else -> ModuleScope.getQualifierForName(file, ref.module, ref.name) ?: ""
}
}
/** Prefix [name], defined in [module], with the necessary qualifier */
protected fun qual(module: String, name: String) = "${qualifierFor(Ref(module, name))}$name"
/** Return the callable for a user-supplied function to process [ty] if there is one */
protected fun existing(ty: Ty): String? {
if (ty in callablesByTy) return callablesByTy[ty]!!
ModuleScope.getReferencableValues(file).all
.filterIsInstance<ElmFunctionDeclarationLeft>()
.forEach {
val t = it.findTy()
if (t != null && isExistingFunction(ty, t)) {
val code = qual(it.moduleName, it.name)
callablesByTy[ty] = code
return code
}
}
return null
}
protected abstract fun isExistingFunction(needle: Ty, function: Ty): Boolean
}
| mit | b796bfe44a6b37563bab002e60f56c5a | 40.1 | 121 | 0.592255 | 4.742308 | false | false | false | false |
MegaShow/college-programming | Homework/Mobile Phone Application Development/Lab5 WebAPI/app/src/main/java/com/icytown/course/experimentfive/webapi/ui/issue/RecyclerViewAdapter.kt | 1 | 1426 | package com.icytown.course.experimentfive.webapi.ui.issue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.icytown.course.experimentfive.webapi.R
import com.icytown.course.experimentfive.webapi.data.model.Issue
import com.icytown.course.experimentfive.webapi.databinding.IssueItemBinding
class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.BindingHolder>() {
var items: List<Issue> = ArrayList()
fun reset(list: List<Issue>) {
items = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder {
val binding = DataBindingUtil.inflate<IssueItemBinding>(
LayoutInflater.from(parent.context),
R.layout.issue_item,
parent,
false
)
val holder = BindingHolder(binding.root)
holder.binding = binding
return holder
}
override fun onBindViewHolder(holder: BindingHolder, position: Int) {
holder.binding.model = items[position]
holder.binding.executePendingBindings()
}
override fun getItemCount(): Int {
return items.size
}
class BindingHolder(view: View) : RecyclerView.ViewHolder(view) {
lateinit var binding: IssueItemBinding
}
}
| mit | 42035fc22b31639ba1e8f14adb225dae | 30.688889 | 87 | 0.715288 | 4.883562 | false | false | false | false |
ligi/SCR | android/src/main/java/org/ligi/scr/EventViewHolder.kt | 1 | 2094 | package org.ligi.scr
import android.content.Intent
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.text.method.LinkMovementMethod
import android.view.ViewGroup
import android.widget.FrameLayout
import info.metadude.java.library.halfnarp.model.GetTalksResponse
import kotlinx.android.synthetic.main.item_event.view.*
import org.joda.time.format.DateTimeFormat
import org.ligi.compat.HtmlCompat
import org.ligi.scr.model.Event
import org.ligi.scr.model.decorated.EventDecorator
class EventViewHolder(private val root: CardView) : RecyclerView.ViewHolder(root) {
fun apply(response: Event) {
val eventDecorator = EventDecorator(response)
itemView.titleTV.text = response.title + response.room
itemView.speaker.text = response.duration
itemView.abstractTV.text = eventDecorator.start.toString(DateTimeFormat.shortTime()) + " " + eventDecorator.end.toString(DateTimeFormat.shortTime()) + " " + response.abstractText
val main = 5 * eventDecorator.duration.standardMinutes
root.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, main.toInt())
root.requestLayout()
}
fun apply(response: GetTalksResponse, moveMethod: (Int, Int) -> Unit) {
itemView.titleTV.text = response.title
itemView.abstractTV.text = HtmlCompat.fromHtml(response.abstract)
itemView.abstractTV.movementMethod = LinkMovementMethod.getInstance()
itemView.speaker.text = response.speakers
itemView.yesButton.setOnClickListener {
moveMethod.invoke(1, adapterPosition)
}
itemView.noButton.setOnClickListener {
moveMethod.invoke(-1, adapterPosition)
}
itemView.shareView.setOnClickListener {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_SUBJECT, response.title)
intent.putExtra(Intent.EXTRA_TEXT, response.abstract)
intent.type = "text/plain"
root.context.startActivity(intent)
}
}
}
| gpl-3.0 | 9f9982821c0647f712c5626609096748 | 36.392857 | 186 | 0.725406 | 4.417722 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/test-kit/src/test/kotlin/org/jetbrains/kotlinx/jupyter/testkit/test/JupyterReplWithResolverTest.kt | 1 | 1623 | package org.jetbrains.kotlinx.jupyter.testkit.test
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.string.shouldContain
import org.jetbrains.kotlinx.jupyter.exceptions.ReplCompilerException
import org.jetbrains.kotlinx.jupyter.exceptions.ReplPreprocessingException
import org.jetbrains.kotlinx.jupyter.testkit.JupyterReplTestCase
import org.jetbrains.kotlinx.jupyter.testkit.ReplProvider
import org.junit.jupiter.api.Test
class JupyterReplWithResolverTest : JupyterReplTestCase(
ReplProvider.withDefaultClasspathResolution(
shouldResolve = { it != "lets-plot" },
shouldResolveToEmpty = { it == "multik" }
)
) {
@Test
fun dataframe() {
val dfHtml = execHtml(
"""
%use dataframe
val name by column<String>()
val height by column<Int>()
dataFrameOf(name, height)(
"Bill", 135,
"Mark", 160
)
""".trimIndent()
)
dfHtml shouldContain "Bill"
}
@Test
fun `lets-plot is not resolved as it is an exception`() {
val exception = shouldThrow<ReplPreprocessingException> {
exec("%use lets-plot")
}
exception.message shouldContain "Unknown library"
}
@Test
fun `multik resolves to empty`() {
exec("%use multik")
val exception = shouldThrow<ReplCompilerException> {
exec("import org.jetbrains.kotlinx.multik.api.*")
}
exception.message shouldContain "Unresolved reference: multik"
}
}
| apache-2.0 | b2f1948c9a32718885ac51b3df64a025 | 29.055556 | 74 | 0.631547 | 4.637143 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/http/HttpConnection.kt | 1 | 2386 | /*
* Copyright (C) 2018 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.processor.query.http
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import uk.co.reecedunn.intellij.plugin.processor.query.MissingHostNameException
import uk.co.reecedunn.intellij.plugin.processor.query.connection.InstanceDetails
import java.io.Closeable
class HttpConnection(val settings: InstanceDetails) : Closeable {
init {
if (settings.hostname.isEmpty())
throw MissingHostNameException()
}
private var client: CloseableHttpClient? = null
private val httpClient: CloseableHttpClient
get() {
if (client == null) {
client = if (settings.username == null || settings.password == null) {
HttpClients.createDefault()
} else {
val credentials = BasicCredentialsProvider()
credentials.setCredentials(
AuthScope(settings.hostname, settings.databasePort),
UsernamePasswordCredentials(settings.username, settings.password)
)
HttpClients.custom().setDefaultCredentialsProvider(credentials).build()
}
}
return client!!
}
fun execute(request: HttpUriRequest): CloseableHttpResponse = httpClient.execute(request)
override fun close() {
if (client != null) {
client!!.close()
client = null
}
}
}
| apache-2.0 | 4977bf8cdb56a152d059299ccd343d63 | 38.114754 | 93 | 0.681056 | 4.781563 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/model/AssignmentCode.kt | 1 | 1351 | package org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model
import org.worldcubeassociation.tnoodle.server.serial.SingletonStringEncoder
data class AssignmentCode(val wcaString: String) {
val isStaff
get() = this.wcaString.startsWith(PREFIX_STAFF)
val isCompetitor
get() = this.wcaString == COMPETITOR
val isStaffJudge
get() = this.wcaString == STAFF_JUDGE
val isStaffScrambler
get() = this.wcaString == STAFF_SCRAMBLER
val isStaffRunner
get() = this.wcaString == STAFF_RUNNER
val isStaffDataEntry
get() = this.wcaString == STAFF_DATAENTRY
val isStaffAnnouncer
get() = this.wcaString == STAFF_ANNOUNCER
companion object : SingletonStringEncoder<AssignmentCode>("AssignmentCode") {
const val PREFIX_STAFF = "staff"
const val COMPETITOR = "competitor"
const val STAFF_JUDGE = "$PREFIX_STAFF-judge"
const val STAFF_SCRAMBLER = "$PREFIX_STAFF-scrambler"
const val STAFF_RUNNER = "$PREFIX_STAFF-runner"
const val STAFF_DATAENTRY = "$PREFIX_STAFF-dataentry"
const val STAFF_ANNOUNCER = "$PREFIX_STAFF-announcer"
override fun encodeInstance(instance: AssignmentCode) = instance.wcaString
override fun makeInstance(deserialized: String) = AssignmentCode(deserialized)
}
}
| gpl-3.0 | 1350d8d816884d4fe70d2db3201d6257 | 32.775 | 86 | 0.694301 | 4.248428 | false | false | false | false |
dhleong/ideavim | test/org/jetbrains/plugins/ideavim/action/motion/updown/MotionPercentOrMatchActionTest.kt | 1 | 5924 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jetbrains.plugins.ideavim.action.motion.updown
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.helper.StringHelper.parseKeys
import org.jetbrains.plugins.ideavim.VimTestCase
/**
* @author Alex Plate
*/
class MotionPercentOrMatchActionTest : VimTestCase() {
fun `test percent match simple`() {
typeTextInFile(parseKeys("%"),
"foo(b${c}ar)\n")
assertOffset(3)
}
fun `test percent match multi line`() {
typeTextInFile(parseKeys("%"),
"""foo(bar,
|baz,
|${c}quux)
""".trimMargin())
assertOffset(3)
}
fun `test percent visual mode match multi line end of line`() {
typeTextInFile(parseKeys("v$%"),
"""${c}foo(
|bar)""".trimMargin())
assertOffset(8)
}
fun `test percent visual mode match from start multi line end of line`() {
typeTextInFile(parseKeys("v$%"),
"""$c(
|bar)""".trimMargin())
assertOffset(5)
}
fun `test percent visual mode find brackets on the end of line`() {
typeTextInFile(parseKeys("v$%"),
"""foo(${c}bar)""")
assertOffset(3)
}
fun `test percent twice visual mode find brackets on the end of line`() {
typeTextInFile(parseKeys("v$%%"),
"""foo(${c}bar)""")
assertOffset(7)
}
fun `test percent match parens in string`() {
typeTextInFile(parseKeys("%"),
"""foo(bar, "foo(bar", ${c}baz)
""")
assertOffset(3)
}
fun `test percent match xml comment start`() {
configureByXmlText("$c<!-- foo -->")
typeText(parseKeys("%"))
myFixture.checkResult("<!-- foo --$c>")
}
fun `test percent doesnt match partial xml comment`() {
configureByXmlText("<!$c-- ")
typeText(parseKeys("%"))
myFixture.checkResult("<!$c-- ")
}
fun `test percent match xml comment end`() {
configureByXmlText("<!-- foo --$c>")
typeText(parseKeys("%"))
myFixture.checkResult("$c<!-- foo -->")
}
fun `test percent match java comment start`() {
configureByJavaText("/$c* foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/* foo *$c/")
}
fun `test percent doesnt match partial java comment`() {
configureByJavaText("$c/* ")
typeText(parseKeys("%"))
myFixture.checkResult("$c/* ")
}
fun `test percent match java comment end`() {
configureByJavaText("/* foo $c*/")
typeText(parseKeys("%"))
myFixture.checkResult("$c/* foo */")
}
fun `test percent match java doc comment start`() {
configureByJavaText("/*$c* foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/** foo *$c/")
}
fun `test percent match java doc comment end`() {
configureByJavaText("/** foo *$c/")
typeText(parseKeys("%"))
myFixture.checkResult("$c/** foo */")
}
fun `test percent doesnt match after comment start`() {
configureByJavaText("/*$c foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/*$c foo */")
}
fun `test percent doesnt match before comment end`() {
configureByJavaText("/* foo $c */")
typeText(parseKeys("%"))
myFixture.checkResult("/* foo $c */")
}
fun `test motion with quote on the way`() {
doTest(parseKeys("%"), """
for (; c!= cj;c = it.next()) ${c}{
if (dsa) {
if (c == '\\') {
dsadsakkk
}
}
}
""".trimIndent(),
"""
for (; c!= cj;c = it.next()) {
if (dsa) {
if (c == '\\') {
dsadsakkk
}
}
${c}}
""".trimIndent(), CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion outside text`() {
doTest(parseKeys("%"), """
(
""${'"'}
""${'"'} + ${c}title("Display")
""${'"'}
""${'"'}
)
""".trimIndent(),
"""
(
""${'"'}
""${'"'} + title("Display"${c})
""${'"'}
""${'"'}
)
""".trimIndent(), CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text`() {
doTest(parseKeys("%"), """ "I found ${c}it in a (legendary) land" """,
""" "I found it in a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes`() {
doTest(parseKeys("%"), """ "I found ${c}it in \"a (legendary) land" """,
""" "I found it in \"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes start before quote`() {
doTest(parseKeys("%"), """ ${c} "I found it in \"a (legendary) land" """,
""" "I found it in \"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes and double escape`() {
doTest(parseKeys("%"), """ "I found ${c}it in \\\"a (legendary) land" """,
""" "I found it in \\\"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
} | gpl-2.0 | a5174b242285ec0614bb64a624273cfa | 29.229592 | 111 | 0.565834 | 4.375185 | false | true | false | false |
siosio/GradleDependenciesHelperPlugin | src/main/java/siosio/searcher/DefaultSearcher.kt | 1 | 960 | package siosio.searcher
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.impl.*
import com.intellij.codeInsight.lookup.*
import siosio.*
import java.awt.SystemColor.*
class DefaultSearcher(override val dependencyText: DependencyText) : CentralSearcher {
override fun find(resultSet: CompletionResultSet) {
val result = Client.get("https://search.maven.org/solrsearch/select?q=${dependencyText.text}&rows=100&wt=json")
resultSet.withRelevanceSorter(
CompletionSorter.emptySorter().weigh(PreferStartMatching())
).addAllElements(ID_PATTERN.findAll(result)
.mapNotNull {
it.groups[1]?.value
}
.map {
LookupElementBuilder.create(it)
}
.toList()
)
}
companion object {
private val ID_PATTERN = Regex("\\{\"id\":\"([^\"]+)\"")
}
} | mit | c3a663bf1dc1d6200272d6c39921da21 | 30 | 119 | 0.614583 | 4.8 | false | false | false | false |
BloodWorkXGaming/ExNihiloCreatio | src/main/java/exnihilocreatio/json/CustomItemInfoJson.kt | 1 | 2149 | package exnihilocreatio.json
import com.google.gson.*
import exnihilocreatio.util.ItemInfo
import exnihilocreatio.util.LogUtil
import net.minecraft.item.Item
import net.minecraft.nbt.JsonToNBT
import net.minecraft.nbt.NBTException
import net.minecraft.nbt.NBTTagCompound
import java.lang.reflect.Type
object CustomItemInfoJson : JsonDeserializer<ItemInfo>, JsonSerializer<ItemInfo> {
override fun serialize(src: ItemInfo, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val nbt = src.nbt
if (nbt == null || nbt.isEmpty)
return JsonPrimitive(src.item.registryName!!.toString() + ":" + src.meta)
return JsonObject().apply {
add("name", context.serialize(src.item.registryName!!.toString()))
add("meta", context.serialize(src.meta))
add("nbt", context.serialize(src.nbt.toString()))
}
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ItemInfo {
if (json.isJsonPrimitive && json.asJsonPrimitive.isString) {
val name = json.asString
return ItemInfo(name)
} else {
val helper = JsonHelper(json)
val name = helper.getString("name")
val meta = helper.getNullableInteger("meta", 0)
val item = Item.getByNameOrId(name)
var nbt: NBTTagCompound? = null
if (json.asJsonObject.has("nbt")) {
try {
nbt = JsonToNBT.getTagFromJson(json.asJsonObject.get("nbt").asString)
} catch (e: NBTException) {
LogUtil.error("Could not convert JSON to NBT: " + json.asJsonObject.get("nbt").asString, e)
e.printStackTrace()
}
}
if (item == null) {
LogUtil.error("Error parsing JSON: Invalid Item: $json")
LogUtil.error("This may result in crashing or other undefined behavior")
return ItemInfo.EMPTY
}
return ItemInfo(item, meta, nbt)
}
}
}
| mit | b0232cd1adae75976735c45b4a7762ce | 35.423729 | 111 | 0.614239 | 4.743929 | false | false | false | false |
android/performance-samples | MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/util/Utils.kt | 1 | 1342 | /*
* 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 com.example.macrobenchmark.target.util
import android.content.Context
import android.util.TypedValue
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
const val TAG = "Perf Sample"
val KEY_USER = stringPreferencesKey("user")
val KEY_PASSWORD = stringPreferencesKey("password")
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
fun Int.dp(context: Context): Float =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this.toFloat(),
context.resources.displayMetrics
)
| apache-2.0 | e66fa2d694b8143ee5cad7f6e48bbfb4 | 34.315789 | 88 | 0.770492 | 4.443709 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | login_presentation/src/main/java/com/vmenon/mpo/login/presentation/fragment/LoginFragment.kt | 1 | 4125 | package com.vmenon.mpo.login.presentation.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.vmenon.mpo.common.framework.livedata.observeUnhandled
import com.vmenon.mpo.login.presentation.databinding.FragmentLoginBinding
import com.vmenon.mpo.login.presentation.di.dagger.toLoginComponent
import com.vmenon.mpo.login.presentation.di.dagger.LoginComponent
import com.vmenon.mpo.login.presentation.model.LoadingState
import com.vmenon.mpo.login.presentation.model.LoggedInState
import com.vmenon.mpo.login.presentation.viewmodel.LoginViewModel
import com.vmenon.mpo.navigation.domain.login.LoginNavigationLocation
import com.vmenon.mpo.navigation.domain.NavigationOrigin
import com.vmenon.mpo.navigation.domain.NoNavigationParams
import com.vmenon.mpo.view.BaseViewBindingFragment
import com.vmenon.mpo.view.LoadingStateHelper
import com.vmenon.mpo.view.R
import com.vmenon.mpo.view.activity.BaseActivity
class LoginFragment : BaseViewBindingFragment<LoginComponent, FragmentLoginBinding>(),
NavigationOrigin<NoNavigationParams> by NavigationOrigin.from(LoginNavigationLocation) {
private val viewModel: LoginViewModel by viewModel()
override fun bind(inflater: LayoutInflater, container: ViewGroup?) =
FragmentLoginBinding.inflate(inflater, container, false)
override fun setupComponent(context: Context): LoginComponent = context.toLoginComponent()
override fun inject(component: LoginComponent) {
component.inject(this)
component.inject(viewModel)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val activity = (requireActivity() as BaseActivity<*>)
val loadingStateHelper = LoadingStateHelper.overlayContent(activity.requireLoadingView())
navigationController.setupWith(
this,
binding.toolbar,
drawerLayout(),
navigationView()
)
viewModel.loginState().observeUnhandled(viewLifecycleOwner, { state ->
when (state) {
LoadingState -> {
loadingStateHelper.showLoadingState()
}
is LoggedInState -> {
loadingStateHelper.showContentState()
if (state.promptToEnrollInBiometrics) {
promptToSetupBiometrics()
}
}
else -> {
loadingStateHelper.showContentState()
}
}
binding.state = state
})
binding.registrationValid = viewModel.registrationValid()
binding.registration = viewModel.registration
binding.lifecycleOwner = viewLifecycleOwner
binding.loginForm.registerLink.setOnClickListener {
viewModel.registerClicked()
}
binding.loginForm.loginLink.setOnClickListener {
viewModel.loginClicked(this)
}
binding.loginForm.useBiometrics.setOnClickListener {
viewModel.loginWithBiometrics(this)
}
binding.registerForm.registerUser.setOnClickListener {
viewModel.performRegistration(this)
}
binding.accountView.logoutLink.setOnClickListener {
viewModel.logoutClicked(this)
}
}
private fun promptToSetupBiometrics() {
val builder = AlertDialog.Builder(requireContext())
builder.apply {
setPositiveButton(getString(R.string.yes)) { _, _ ->
viewModel.userWantsToEnrollInBiometrics(this@LoginFragment)
}
setNegativeButton(R.string.no) { _, _ ->
viewModel.userDoesNotWantBiometrics()
}
setTitle(getString(com.vmenon.mpo.login.presentation.R.string.use_biometrics))
setMessage(getString(com.vmenon.mpo.login.presentation.R.string.use_biometrics_for_login))
}
builder.create().show()
}
} | apache-2.0 | 65bdce8a2eccc3ed344ef80ea8d15039 | 39.851485 | 102 | 0.688727 | 5.124224 | false | false | false | false |
gustavoasevedo/sDatabase | library/src/main/java/com/dss/sdatabase/model/BDInsert.kt | 1 | 417 | package com.dss.sdatabase.model
import java.lang.reflect.Field
/**
* Created by gustavo.vieira on 04/05/2015.
*/
class BDInsert {
var field: Field? = null
var fieldName = String()
var fieldValue = Any()
constructor(field: Field, fieldName: String, fieldValue: Any) {
this.field = field
this.fieldName = fieldName
this.fieldValue = fieldValue
}
constructor()
}
| apache-2.0 | 0c93af177e94598aa1716fac9d4562d5 | 17.130435 | 67 | 0.645084 | 3.790909 | false | false | false | false |
da1z/intellij-community | tools/index-tools/src/org/jetbrains/index/IndexGenerator.kt | 4 | 3548 | // 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 org.jetbrains.index
import com.google.common.hash.HashCode
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.stubs.FileContentHashing
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.io.PersistentHashMap
import junit.framework.TestCase
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* @author traff
*/
abstract class IndexGenerator<Value>(private val indexStorageFilePath: String) {
companion object {
val CHECK_HASH_COLLISIONS: Boolean = System.getenv("INDEX_GENERATOR_CHECK_HASH_COLLISIONS")?.toBoolean() ?: false
}
open val fileFilter
get() = VirtualFileFilter { f -> !f.isDirectory }
data class Stats(val indexed: AtomicInteger, val skipped: AtomicInteger) {
constructor() : this(AtomicInteger(0), AtomicInteger(0))
}
protected fun buildIndexForRoots(roots: List<VirtualFile>) {
val hashing = FileContentHashing()
val storage = createStorage(indexStorageFilePath)
println("Writing indices to ${storage.baseFile.absolutePath}")
try {
val map = HashMap<HashCode, Pair<String, Value>>()
for (file in roots) {
println("Processing files in root ${file.path}")
val stats = Stats()
VfsUtilCore.visitChildrenRecursively(file,
object : VirtualFileVisitor<Boolean>() {
override fun visitFile(file: VirtualFile): Boolean {
return indexFile(file, hashing, map, storage, stats)
}
})
println("${stats.indexed.get()} entries written, ${stats.skipped.get()} skipped")
}
}
finally {
storage.close()
}
}
private fun indexFile(file: VirtualFile,
hashing: FileContentHashing,
map: HashMap<HashCode, Pair<String, Value>>,
storage: PersistentHashMap<HashCode, Value>,
stats: Stats): Boolean {
try {
if (fileFilter.accept(file)) {
val fileContent = FileContentImpl(
file, file.contentsToByteArray())
val hashCode = hashing.hashString(fileContent)
val value = getIndexValue(fileContent)
if (value != null) {
val item = map[hashCode]
if (item == null) {
storage.put(hashCode, value)
stats.indexed.incrementAndGet()
if (CHECK_HASH_COLLISIONS) {
map.put(hashCode,
Pair(fileContent.contentAsText.toString(), value))
}
}
else {
TestCase.assertEquals(item.first,
fileContent.contentAsText.toString())
TestCase.assertTrue(value == item.second)
}
}
else {
stats.skipped.incrementAndGet()
}
}
}
catch (e: NoSuchElementException) {
return false
}
return true
}
protected abstract fun getIndexValue(fileContent: FileContentImpl): Value?
protected abstract fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, Value>
} | apache-2.0 | 9cebc506e6e00ac28881bb51be7b7405 | 32.168224 | 140 | 0.61274 | 5.068571 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/feed/tag/TagActivity.kt | 1 | 3072 | package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag
import android.content.Context
import android.content.Intent
import android.os.Bundle
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.createNewEntry
import io.github.feelfreelinux.wykopmobilny.utils.api.getTag
import kotlinx.android.synthetic.main.activity_feed.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.launchTagActivity(tag : String) {
val intent = Intent(this, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
startActivity(intent)
}
class TagActivity : BaseActivity(), TagView {
private lateinit var entryTag : String
lateinit var tagDataFragment : DataFragment<PagedDataModel<List<Entry>>>
@Inject lateinit var presenter : TagPresenter
companion object {
val EXTRA_TAG = "EXTRA_TAG"
val EXTRA_TAG_DATA_FRAGMENT = "DATA_FRAGMENT_#"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed)
setSupportActionBar(toolbar)
entryTag = intent.data?.getTag() ?: intent.getStringExtra(EXTRA_TAG)
tagDataFragment = supportFragmentManager.getDataFragmentInstance(EXTRA_TAG_DATA_FRAGMENT + entryTag)
tagDataFragment.data?.apply {
presenter.page = page
}
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = "#" + entryTag
}
WykopApp.uiInjector.inject(this)
presenter.tag = entryTag
presenter.subscribe(this)
feedRecyclerView.apply {
presenter = [email protected]
initAdapter(tagDataFragment.data?.model)
onFabClickedListener = {
context.createNewEntry(null)
}
}
setSupportActionBar(toolbar)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
tagDataFragment.data = PagedDataModel(presenter.page, feedRecyclerView.entries)
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(tagDataFragment)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun addDataToAdapter(entryList: List<Entry>, shouldClearAdapter: Boolean) =
feedRecyclerView.addDataToAdapter(entryList, shouldClearAdapter)
} | mit | 574e0f147dff21dad536cd71a2367a8e | 36.47561 | 108 | 0.734701 | 4.97893 | false | false | false | false |
esqr/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/feed/tag/TagActivity.kt | 1 | 5115 | package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.dataclass.TagMeta
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.createNewEntry
import io.github.feelfreelinux.wykopmobilny.utils.api.getTag
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.linkparser.TagLinkParser
import kotlinx.android.synthetic.main.activity_feed.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.getTagActivityIntent(tag : String) : Intent {
val intent = Intent(this, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
return intent
}
class TagActivity : BaseActivity(), TagView {
private lateinit var entryTag : String
lateinit var tagDataFragment : DataFragment<PagedDataModel<List<Entry>>>
@Inject lateinit var userManager : UserManagerApi
@Inject lateinit var presenter : TagPresenter
private var tagMeta : TagMeta? = null
companion object {
val EXTRA_TAG = "EXTRA_TAG"
val EXTRA_TAG_DATA_FRAGMENT = "DATA_FRAGMENT_#"
fun createIntent(context : Context, tag : String): Intent {
val intent = Intent(context, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed)
setSupportActionBar(toolbar)
WykopApp.uiInjector.inject(this)
entryTag = intent.getStringExtra(EXTRA_TAG)?: TagLinkParser.getTag(intent.data.toString())
tagDataFragment = supportFragmentManager.getDataFragmentInstance(EXTRA_TAG_DATA_FRAGMENT + entryTag)
tagDataFragment.data?.apply {
presenter.page = page
}
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = "#" + entryTag
}
presenter.tag = entryTag
presenter.subscribe(this)
feedRecyclerView.apply {
presenter = [email protected]
fab = [email protected]
initAdapter(tagDataFragment.data?.model)
onFabClickedListener = {
context.createNewEntry(null)
}
}
setSupportActionBar(toolbar)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.tag_menu, menu)
if (userManager.isUserAuthorized()) {
tagMeta?.apply {
menu.apply {
if (isObserved) {
findItem(R.id.action_unobserve).isVisible = true
} else if (!isBlocked) {
findItem(R.id.action_observe).isVisible = true
findItem(R.id.action_block).isVisible = true
} else if (isBlocked) {
findItem(R.id.action_unblock).isVisible = true
}
}
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_observe -> presenter.observeTag()
R.id.action_unobserve -> presenter.unobserveTag()
R.id.action_block -> presenter.blockTag()
R.id.action_unblock -> presenter.unblockTag()
}
return super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
tagDataFragment.data = PagedDataModel(presenter.page, feedRecyclerView.entries)
}
override fun setMeta(tagMeta: TagMeta) {
this.tagMeta = tagMeta
invalidateOptionsMenu()
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(tagDataFragment)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun addDataToAdapter(entryList: List<Entry>, shouldClearAdapter: Boolean) =
feedRecyclerView.addDataToAdapter(entryList, shouldClearAdapter)
override fun disableLoading() {
feedRecyclerView.disableLoading()
}
} | mit | d60db277c67ba1899c23efe0b86fb47f | 36.072464 | 108 | 0.684457 | 4.885387 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper/src/test/java/com/prateekj/snooper/networksnooper/presenter/HttpCallPresenterTest.kt | 1 | 4494 | package com.prateekj.snooper.networksnooper.presenter
import com.prateekj.snooper.infra.BackgroundTask
import com.prateekj.snooper.infra.BackgroundTaskExecutor
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.ERROR
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.HEADERS
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.REQUEST
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.RESPONSE
import com.prateekj.snooper.networksnooper.helper.DataCopyHelper
import com.prateekj.snooper.networksnooper.model.HttpCallRecord
import com.prateekj.snooper.networksnooper.views.HttpCallView
import com.prateekj.snooper.utils.FileUtil
import com.prateekj.snooper.utils.TestUtils.getDate
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Before
import org.junit.Test
class HttpCallPresenterTest {
private lateinit var view: HttpCallView
private lateinit var httpCall: HttpCallRecord
private lateinit var dataCopyHelper: DataCopyHelper
private lateinit var fileUtil: FileUtil
private lateinit var backgroundTaskExecutor: BackgroundTaskExecutor
private lateinit var httpCallPresenter: HttpCallPresenter
@Before
@Throws(Exception::class)
fun setUp() {
view = mockk(relaxed = true)
httpCall = mockk(relaxed = true)
dataCopyHelper = mockk(relaxed = true)
fileUtil = mockk(relaxed = true)
backgroundTaskExecutor = mockk(relaxed = true)
httpCallPresenter = HttpCallPresenter(
dataCopyHelper,
httpCall,
view,
fileUtil,
backgroundTaskExecutor
)
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheResponseData() {
val responseBody = "response body"
every { dataCopyHelper.getResponseDataForCopy() } returns responseBody
httpCallPresenter.copyHttpCallBody(RESPONSE)
verify { view.copyToClipboard(responseBody) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheRequestData() {
val formatRequestBody = "format Request body"
every { dataCopyHelper.getRequestDataForCopy() } returns formatRequestBody
httpCallPresenter.copyHttpCallBody(REQUEST)
verify { view.copyToClipboard(formatRequestBody) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheHeaders() {
val headers = "headers"
every { dataCopyHelper.getHeadersForCopy() } returns headers
httpCallPresenter.copyHttpCallBody(HEADERS)
verify { view.copyToClipboard(headers) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheError() {
val error = "error"
every { dataCopyHelper.getErrorsForCopy() } returns error
httpCallPresenter.copyHttpCallBody(ERROR)
verify { view.copyToClipboard(error) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheEmptyStringIfErrorNotCaptured() {
every { dataCopyHelper.getErrorsForCopy() } returns null
httpCallPresenter.copyHttpCallBody(ERROR)
verify { view.copyToClipboard("") }
}
@Test
@Throws(Exception::class)
fun shouldShareRequestResponseData() {
every { httpCall.date } returns getDate(2017, 4, 12, 1, 2, 3)
val stringBuilder = StringBuilder()
every { dataCopyHelper.getHttpCallData() } returns stringBuilder
every {
fileUtil.createLogFile(
eq(stringBuilder),
eq("2017_05_12_01_02_03.txt")
)
} returns "filePath"
resolveBackgroundTask()
httpCallPresenter.shareHttpCallBody()
verify { view.shareData("filePath") }
}
@Test
@Throws(Exception::class)
fun shouldNotShareDataIfFileNotCreated() {
every { httpCall.date } returns getDate(2017, 4, 12, 1, 2, 3)
val stringBuilder = StringBuilder()
every { dataCopyHelper.getHttpCallData() } returns stringBuilder
every {
fileUtil.createLogFile(
eq(stringBuilder),
eq("2017_05_12_01_02_03.txt")
)
} returns ""
resolveBackgroundTask()
httpCallPresenter.shareHttpCallBody()
verify(exactly = 0) { view.shareData("filePath") }
}
@Test
@Throws(Exception::class)
fun shouldShowShareNotAvailableDialogWhenPermissionIsDenied() {
httpCallPresenter.onPermissionDenied()
verify { view.showMessageShareNotAvailable() }
}
private fun resolveBackgroundTask() {
every { backgroundTaskExecutor.execute(any<BackgroundTask<String>>()) } answers {
val backgroundTask = this.firstArg<BackgroundTask<String>>()
backgroundTask.onResult(backgroundTask.onExecute())
}
}
} | apache-2.0 | ea02c98ab6ba868ff433bf095abd8795 | 28.188312 | 85 | 0.746106 | 4.691023 | false | true | false | false |
sirixdb/sirix | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/HistoryHandler.kt | 1 | 3564 | package org.sirix.rest.crud
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.withContext
import org.sirix.access.DatabaseType
import org.sirix.access.Databases.*
import org.sirix.api.Database
import org.sirix.service.json.serialize.StringValue
import java.nio.charset.StandardCharsets
import java.nio.file.Path
class HistoryHandler(private val location: Path) {
suspend fun handle(ctx: RoutingContext): Route {
val databaseName = ctx.pathParam("database")
val resourceName = ctx.pathParam("resource")
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") val database: Database<*> =
when (getDatabaseType(location.resolve(databaseName).toAbsolutePath())) {
DatabaseType.JSON -> openJsonDatabase(location.resolve(databaseName))
DatabaseType.XML -> openXmlDatabase(location.resolve(databaseName))
}
withContext(ctx.vertx().dispatcher()) {
val buffer = StringBuilder()
database.use {
val manager = database.beginResourceSession(resourceName)
manager.use {
val numberOfRevisions = ctx.queryParam("revisions")
val startRevision = ctx.queryParam("startRevision")
val endRevision = ctx.queryParam("endRevision")
val historyList = if (numberOfRevisions.isEmpty()) {
if (startRevision.isEmpty() && endRevision.isEmpty()) {
manager.history
} else {
val startRevisionAsInt = startRevision[0].toInt()
val endRevisionAsInt = endRevision[0].toInt()
manager.getHistory(startRevisionAsInt, endRevisionAsInt)
}
} else {
val revisions = numberOfRevisions[0].toInt()
manager.getHistory(revisions)
}
buffer.append("{\"history\":[")
historyList.forEachIndexed { index, revisionTuple ->
buffer.append("{\"revision\":")
buffer.append(revisionTuple.revision)
buffer.append(",")
buffer.append("\"revisionTimestamp\":\"")
buffer.append(revisionTuple.revisionTimestamp)
buffer.append("\",")
buffer.append("\"author\":\"")
buffer.append(StringValue.escape(revisionTuple.user.name))
buffer.append("\",")
buffer.append("\"commitMessage\":\"")
buffer.append(StringValue.escape(revisionTuple.commitMessage.orElse("")))
buffer.append("\"}")
if (index != historyList.size - 1)
buffer.append(",")
}
buffer.append("]}")
}
}
val content = buffer.toString()
val res = ctx.response().setStatusCode(200)
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, content.toByteArray(StandardCharsets.UTF_8).size.toString())
res.write(content)
res.end()
}
return ctx.currentRoute()
}
} | bsd-3-clause | b002dcdc5e4e7a097e889a97ed54a462 | 39.511364 | 115 | 0.545735 | 5.603774 | false | false | false | false |
maxoumime/emoji-data-java | src/main/java/com/maximebertheau/emoji/Node.kt | 1 | 538 | package com.maximebertheau.emoji
internal class Node(private val char: Char? = null) {
private val children = mutableMapOf<Char, Node>()
var emoji: Emoji? = null
fun hasChild(child: Char): Boolean = children.containsKey(child)
fun addChild(child: Char) {
children[child] = Node(child)
}
fun getChild(child: Char): Node? = children[child]
override fun toString(): String {
return """(${emoji?.unicode}) | $char -> [${children.map { it.key.toInt().toString(16).toUpperCase() }}]"""
}
}
| mit | 3e49dab16552ef47f69012b5bc1c566d | 27.315789 | 115 | 0.635688 | 3.788732 | false | false | false | false |
MaTriXy/android-UniversalMusicPlayer | common/src/main/java/com/example/android/uamp/media/library/AlbumArtContentProvider.kt | 2 | 1981 | /*
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileNotFoundException
class AlbumArtContentProvider : ContentProvider() {
override fun onCreate() = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val context = this.context ?: return null
val file = File(uri.path)
if (!file.exists()) {
throw FileNotFoundException(uri.path)
}
// Only allow access to files under cache path
val cachePath = context.cacheDir.path
if (!file.path.startsWith(cachePath)) {
throw FileNotFoundException()
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
}
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? = null
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
) = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0
override fun getType(uri: Uri): String? = null
}
| apache-2.0 | 0a6ceb31ca095b7ac612c6caacac7ce1 | 29.015152 | 86 | 0.722362 | 4.306522 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModel.kt | 5 | 2292 | // 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.gradleTooling
import org.jetbrains.kotlin.idea.projectModel.*
import org.jetbrains.plugins.gradle.model.ExternalDependency
import org.jetbrains.plugins.gradle.model.ModelFactory
import java.io.Serializable
typealias KotlinDependency = ExternalDependency
class KotlinDependencyMapper {
private var currentIndex: KotlinDependencyId = 0
private val idToDependency = HashMap<KotlinDependencyId, KotlinDependency>()
private val dependencyToId = HashMap<KotlinDependency, KotlinDependencyId>()
fun getDependency(id: KotlinDependencyId) = idToDependency[id]
fun getId(dependency: KotlinDependency): KotlinDependencyId {
return dependencyToId[dependency] ?: let {
currentIndex++
dependencyToId[dependency] = currentIndex
idToDependency[currentIndex] = dependency
return currentIndex
}
}
fun toDependencyMap(): Map<KotlinDependencyId, KotlinDependency> = idToDependency
}
fun KotlinDependency.deepCopy(cache: MutableMap<Any, Any>): KotlinDependency {
val cachedValue = cache[this] as? KotlinDependency
return if (cachedValue != null) {
cachedValue
} else {
val result = ModelFactory.createCopy(this)
cache[this] = result
result
}
}
interface KotlinMPPGradleModel : KotlinSourceSetContainer, Serializable {
val dependencyMap: Map<KotlinDependencyId, KotlinDependency>
val targets: Collection<KotlinTarget>
val extraFeatures: ExtraFeatures
val kotlinNativeHome: String
val cacheAware: CompilerArgumentsCacheAware
@Deprecated(level = DeprecationLevel.WARNING, message = "Use KotlinMPPGradleModel#cacheAware instead")
val partialCacheAware: CompilerArgumentsCacheAware
val kotlinImportingDiagnostics: KotlinImportingDiagnosticsContainer
@Deprecated("Use 'sourceSetsByName' instead", ReplaceWith("sourceSetsByName"), DeprecationLevel.ERROR)
val sourceSets: Map<String, KotlinSourceSet>
get() = sourceSetsByName
override val sourceSetsByName: Map<String, KotlinSourceSet>
companion object {
const val NO_KOTLIN_NATIVE_HOME = ""
}
} | apache-2.0 | c001dc432414805923ad4c8e2e46b848 | 35.983871 | 120 | 0.750873 | 5.603912 | false | false | false | false |
Hexworks/zircon | zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DHorizontalFlipper.kt | 1 | 999 | package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.transformer.Java2DTextureTransformer
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import java.awt.geom.AffineTransform
import java.awt.image.AffineTransformOp
import java.awt.image.BufferedImage
class Java2DHorizontalFlipper : Java2DTextureTransformer() {
override fun transform(texture: TileTexture<BufferedImage>, tile: Tile): TileTexture<BufferedImage> {
val backend = texture.texture
val tx = AffineTransform.getScaleInstance(-1.0, 1.0)
tx.translate(-backend.width.toDouble(), 0.0)
return DefaultTileTexture(
width = texture.width,
height = texture.height,
texture = AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(backend, null),
cacheKey = tile.cacheKey
)
}
}
| apache-2.0 | 4eed68c331aa5e95cc3e1414ae2d8ac1 | 38.96 | 107 | 0.745746 | 4.269231 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/ProviderCodecs.kt | 1 | 13728 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.artifacts.component.BuildIdentifier
import org.gradle.api.file.Directory
import org.gradle.api.file.RegularFile
import org.gradle.api.internal.file.DefaultFilePropertyFactory.DefaultDirectoryVar
import org.gradle.api.internal.file.DefaultFilePropertyFactory.DefaultRegularFileVar
import org.gradle.api.internal.file.FilePropertyFactory
import org.gradle.api.internal.provider.DefaultListProperty
import org.gradle.api.internal.provider.DefaultMapProperty
import org.gradle.api.internal.provider.DefaultProperty
import org.gradle.api.internal.provider.DefaultProvider
import org.gradle.api.internal.provider.DefaultSetProperty
import org.gradle.api.internal.provider.DefaultValueSourceProviderFactory.ValueSourceProvider
import org.gradle.api.internal.provider.PropertyFactory
import org.gradle.api.internal.provider.ProviderInternal
import org.gradle.api.internal.provider.ValueSourceProviderFactory
import org.gradle.api.internal.provider.ValueSupplier
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ValueSourceParameters
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.gradle.api.services.internal.BuildServiceProvider
import org.gradle.api.services.internal.BuildServiceRegistryInternal
import org.gradle.configurationcache.extensions.serviceOf
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingSharedIdentity
import org.gradle.configurationcache.serialization.encodePreservingSharedIdentityOf
import org.gradle.configurationcache.serialization.logPropertyProblem
import org.gradle.configurationcache.serialization.readClassOf
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.internal.build.BuildStateRegistry
/**
* This is not used directly when encoding or decoding the object graph. This codec takes care of substituting a provider whose
* value is known at configuration time with a fixed value.
*/
internal
class FixedValueReplacingProviderCodec(
valueSourceProviderFactory: ValueSourceProviderFactory,
buildStateRegistry: BuildStateRegistry
) {
private
val providerWithChangingValueCodec = Bindings.of {
bind(ValueSourceProviderCodec(valueSourceProviderFactory))
bind(BuildServiceProviderCodec(buildStateRegistry))
bind(BeanCodec)
}.build()
suspend fun WriteContext.encodeProvider(value: ProviderInternal<*>) {
val state = try {
value.calculateExecutionTimeValue()
} catch (e: Exception) {
logPropertyProblem("serialize", e) {
text("value ")
reference(value.toString())
text(" failed to unpack provider")
}
writeByte(0)
write(BrokenValue(e))
return
}
encodeValue(state)
}
suspend fun WriteContext.encodeValue(value: ValueSupplier.ExecutionTimeValue<*>) {
when {
value.isMissing -> {
// Can serialize a fixed value and discard the provider
// TODO - should preserve information about the source, for diagnostics at execution time
writeByte(1)
}
value.isFixedValue -> {
// Can serialize a fixed value and discard the provider
// TODO - should preserve information about the source, for diagnostics at execution time
writeByte(2)
write(value.fixedValue)
}
else -> {
// Cannot write a fixed value, so write the provider itself
writeByte(3)
providerWithChangingValueCodec.run { encode(value.changingValue) }
}
}
}
suspend fun ReadContext.decodeProvider(): ProviderInternal<*> {
return decodeValue().toProvider()
}
suspend fun ReadContext.decodeValue(): ValueSupplier.ExecutionTimeValue<*> =
when (readByte()) {
0.toByte() -> {
val value = read() as BrokenValue
ValueSupplier.ExecutionTimeValue.changingValue(DefaultProvider { value.rethrow() })
}
1.toByte() -> ValueSupplier.ExecutionTimeValue.missing<Any>()
2.toByte() -> ValueSupplier.ExecutionTimeValue.ofNullable(read()) // nullable because serialization may replace value with null, eg when using provider of Task
3.toByte() -> ValueSupplier.ExecutionTimeValue.changingValue<Any>(providerWithChangingValueCodec.run { decode() }!!.uncheckedCast())
else -> throw IllegalStateException("Unexpected provider value")
}
}
/**
* Handles Provider instances seen in the object graph, and delegates to another codec that handles the value.
*/
internal
class ProviderCodec(
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<ProviderInternal<*>> {
override suspend fun WriteContext.encode(value: ProviderInternal<*>) {
// TODO - should write the provider value type
providerCodec.run { encodeProvider(value) }
}
override suspend fun ReadContext.decode() =
providerCodec.run { decodeProvider() }
}
internal
class BuildServiceProviderCodec(
private val buildStateRegistry: BuildStateRegistry
) : Codec<BuildServiceProvider<*, *>> {
override suspend fun WriteContext.encode(value: BuildServiceProvider<*, *>) {
encodePreservingSharedIdentityOf(value) {
val buildIdentifier = value.buildIdentifier
write(buildIdentifier)
writeString(value.name)
writeClass(value.implementationType)
write(value.parameters)
writeInt(
buildServiceRegistryOf(buildIdentifier).forService(value).maxUsages
)
}
}
override suspend fun ReadContext.decode(): BuildServiceProvider<*, *>? =
decodePreservingSharedIdentity {
val buildIdentifier = readNonNull<BuildIdentifier>()
val name = readString()
val implementationType = readClassOf<BuildService<*>>()
val parameters = read() as BuildServiceParameters?
val maxUsages = readInt()
buildServiceRegistryOf(buildIdentifier).register(name, implementationType, parameters, maxUsages)
}
private
fun buildServiceRegistryOf(buildIdentifier: BuildIdentifier) =
buildStateRegistry.getBuild(buildIdentifier).mutableModel.serviceOf<BuildServiceRegistryInternal>()
}
internal
class ValueSourceProviderCodec(
private val valueSourceProviderFactory: ValueSourceProviderFactory
) : Codec<ValueSourceProvider<*, *>> {
override suspend fun WriteContext.encode(value: ValueSourceProvider<*, *>) {
when (value.obtainedValueOrNull) {
null -> {
// source has **NOT** been used as build logic input:
// serialize the source
writeBoolean(true)
encodeValueSource(value)
}
else -> {
// source has been used as build logic input:
// serialize the value directly as it will be part of the
// cached state fingerprint.
// Currently not necessary due to the unpacking that happens
// to the TypeSanitizingProvider put around the ValueSourceProvider.
throw IllegalStateException("build logic input")
}
}
}
override suspend fun ReadContext.decode(): ValueSourceProvider<*, *>? =
when (readBoolean()) {
true -> decodeValueSource()
false -> throw IllegalStateException()
}
private
suspend fun WriteContext.encodeValueSource(value: ValueSourceProvider<*, *>) {
encodePreservingSharedIdentityOf(value) {
value.run {
writeClass(valueSourceType)
writeClass(parametersType as Class<*>)
write(parameters)
}
}
}
private
suspend fun ReadContext.decodeValueSource(): ValueSourceProvider<*, *> =
decodePreservingSharedIdentity {
val valueSourceType = readClass()
val parametersType = readClass()
val parameters = read()!!
val provider =
valueSourceProviderFactory.instantiateValueSourceProvider<Any, ValueSourceParameters>(
valueSourceType.uncheckedCast(),
parametersType.uncheckedCast(),
parameters.uncheckedCast()
)
provider.uncheckedCast()
}
}
internal
class PropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultProperty<*>) {
writeClass(value.type as Class<*>)
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val provider = providerCodec.run { decodeProvider() }
return propertyFactory.property(type).provider(provider)
}
}
internal
class DirectoryPropertyCodec(
private val filePropertyFactory: FilePropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultDirectoryVar> {
override suspend fun WriteContext.encode(value: DefaultDirectoryVar) {
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultDirectoryVar {
val provider: Provider<Directory> = providerCodec.run { decodeProvider() }.uncheckedCast()
return filePropertyFactory.newDirectoryProperty().value(provider) as DefaultDirectoryVar
}
}
internal
class RegularFilePropertyCodec(
private val filePropertyFactory: FilePropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultRegularFileVar> {
override suspend fun WriteContext.encode(value: DefaultRegularFileVar) {
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultRegularFileVar {
val provider: Provider<RegularFile> = providerCodec.run { decodeProvider() }.uncheckedCast()
return filePropertyFactory.newFileProperty().value(provider) as DefaultRegularFileVar
}
}
internal
class ListPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultListProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultListProperty<*>) {
writeClass(value.elementType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultListProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val value: ValueSupplier.ExecutionTimeValue<List<Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.listProperty(type).apply {
fromState(value)
}
}
}
internal
class SetPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultSetProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultSetProperty<*>) {
writeClass(value.elementType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultSetProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val value: ValueSupplier.ExecutionTimeValue<Set<Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.setProperty(type).apply {
fromState(value)
}
}
}
internal
class MapPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultMapProperty<*, *>> {
override suspend fun WriteContext.encode(value: DefaultMapProperty<*, *>) {
writeClass(value.keyType)
writeClass(value.valueType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultMapProperty<*, *> {
val keyType: Class<Any> = readClass().uncheckedCast()
val valueType: Class<Any> = readClass().uncheckedCast()
val state: ValueSupplier.ExecutionTimeValue<Map<Any, Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.mapProperty(keyType, valueType).apply {
fromState(state)
}
}
}
| apache-2.0 | d95d424091d1c63ae6d9363a6f33c667 | 38.222857 | 171 | 0.701195 | 5.451946 | false | false | false | false |
edwardharks/Aircraft-Recognition | aircraftsearch/src/main/java/com/edwardharker/aircraftrecognition/ui/search/SearchAdapter.kt | 1 | 1789 | package com.edwardharker.aircraftrecognition.ui.search
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.edwardharker.aircraftrecognition.android.diffutils.AircraftDiffCallback
import com.edwardharker.aircraftrecognition.model.Aircraft
import com.edwardharker.aircraftsearch.R
class SearchAdapter(
private val aircraftClickListener: (Aircraft) -> Unit,
private val feedbackClickListener: () -> Unit
) : ListAdapter<Aircraft, SearchAdapter.ViewHolder>(AircraftDiffCallback) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position < super.getItemCount()) {
bindAircraft(position, holder)
} else {
bindFeedback(holder)
}
}
private fun bindFeedback(holder: ViewHolder) {
holder.label.text = holder.itemView.context.getString(R.string.suggest_aircraft)
holder.itemView.setOnClickListener { feedbackClickListener() }
}
private fun bindAircraft(
position: Int,
holder: ViewHolder
) {
val aircraft = getItem(position)
holder.label.text = aircraft.name
holder.itemView.setOnClickListener { aircraftClickListener(aircraft) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.view_search_result, parent, false)
)
}
override fun getItemCount(): Int = super.getItemCount() + 1
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val label = view as TextView
}
}
| gpl-3.0 | 49f07b6ae0a53be93a231b3db0487071 | 34.078431 | 88 | 0.716601 | 4.822102 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/KeyParentImpl.kt | 1 | 10212 | // 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.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class KeyParentImpl : KeyParent, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(KeyParent::class.java, KeyChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField
var _keyField: String? = null
override val keyField: String
get() = _keyField!!
@JvmField
var _notKeyField: String? = null
override val notKeyField: String
get() = _notKeyField!!
override val children: List<KeyChild>
get() = snapshot.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: KeyParentData?) : ModifiableWorkspaceEntityBase<KeyParent>(), KeyParent.Builder {
constructor() : this(KeyParentData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity KeyParent is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isKeyFieldInitialized()) {
error("Field KeyParent#keyField should be initialized")
}
if (!getEntityData().isNotKeyFieldInitialized()) {
error("Field KeyParent#notKeyField should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field KeyParent#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field KeyParent#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as KeyParent
this.entitySource = dataSource.entitySource
this.keyField = dataSource.keyField
this.notKeyField = dataSource.notKeyField
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var keyField: String
get() = getEntityData().keyField
set(value) {
checkModificationAllowed()
getEntityData().keyField = value
changedProperty.add("keyField")
}
override var notKeyField: String
get() = getEntityData().notKeyField
set(value) {
checkModificationAllowed()
getEntityData().notKeyField = value
changedProperty.add("notKeyField")
}
// List of non-abstract referenced types
var _children: List<KeyChild>? = emptyList()
override var children: List<KeyChild>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<KeyChild>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<KeyChild> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): KeyParentData = result ?: super.getEntityData() as KeyParentData
override fun getEntityClass(): Class<KeyParent> = KeyParent::class.java
}
}
class KeyParentData : WorkspaceEntityData<KeyParent>() {
lateinit var keyField: String
lateinit var notKeyField: String
fun isKeyFieldInitialized(): Boolean = ::keyField.isInitialized
fun isNotKeyFieldInitialized(): Boolean = ::notKeyField.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<KeyParent> {
val modifiable = KeyParentImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): KeyParent {
val entity = KeyParentImpl()
entity._keyField = keyField
entity._notKeyField = notKeyField
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return KeyParent::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return KeyParent(keyField, notKeyField, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.entitySource != other.entitySource) return false
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun equalsByKey(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
return true
}
override fun hashCodeByKey(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 24324bd62f05369fd68a7166e64ab746 | 33.734694 | 166 | 0.679691 | 5.250386 | false | false | false | false |
micolous/metrodroid | src/main/java/au/id/micolous/metrodroid/ui/NfcSettingsPreference.kt | 1 | 2545 | /*
* NfcSettingsPreference.kt
*
* Copyright 2019 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.ui
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.util.AttributeSet
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.preference.Preference
import au.id.micolous.metrodroid.util.Utils
class NfcSettingsPreference : Preference {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) :
super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) :
super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onClick() {
showNfcSettings(context)
}
companion object {
private const val TAG = "NfcSettingsPreference"
private const val ADVANCED_CONNECTED_DEVICE_SETTINGS =
"com.android.settings.ADVANCED_CONNECTED_DEVICE_SETTINGS"
fun showNfcSettings(context: Context) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
// Workaround for https://issuetracker.google.com/135970325
// Only required for Android P
if (Utils.tryStartActivity(context, ADVANCED_CONNECTED_DEVICE_SETTINGS))
return
}
// JB and later; we target JB+, so can skip the version check
if (Utils.tryStartActivity(context, Settings.ACTION_NFC_SETTINGS))
return
// Fallback
if (Utils.tryStartActivity(context, Settings.ACTION_WIRELESS_SETTINGS))
return
Log.w(TAG, "Failed to launch NFC settings")
}
}
}
| gpl-3.0 | e60a583e8a0e903477b2934b6e3eca43 | 36.426471 | 93 | 0.68998 | 4.52847 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/navigation/RoutingActivity.kt | 1 | 3584 | package net.squanchy.navigation
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.disposables.CompositeDisposable
import net.squanchy.R
import net.squanchy.navigation.deeplink.DeepLinkRouter
import net.squanchy.onboarding.Onboarding
import net.squanchy.signin.SignInService
import timber.log.Timber
class RoutingActivity : AppCompatActivity() {
private lateinit var deepLinkRouter: DeepLinkRouter
private lateinit var navigator: Navigator
private lateinit var onboarding: Onboarding
private lateinit var signInService: SignInService
private lateinit var firstStartPersister: FirstStartPersister
private val subscriptions = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val component = routingComponent(this)
deepLinkRouter = component.deepLinkRouter()
navigator = component.navigator()
onboarding = component.onboarding()
signInService = component.signInService()
firstStartPersister = component.firstStartPersister()
}
override fun onStart() {
super.onStart()
subscriptions.add(
signInService.signInAnonymouslyIfNecessary()
.subscribe(::onboardOrProceedToRouting, ::handleSignInError)
)
}
private fun handleSignInError(throwable: Throwable) {
Timber.e(throwable, "Error while signing in on routing")
if (!firstStartPersister.hasBeenStartedAlready()) {
// We likely have no data here and it'd be a horrible UX, so we show a warning instead
// to let people know it won't work.
val continuationIntent = createContinueIntentFrom(intent)
navigator.toFirstStartWithNoNetwork(continuationIntent)
} else {
Toast.makeText(this, R.string.routing_sign_in_unexpected_error, Toast.LENGTH_LONG).show()
}
finish()
}
private fun createContinueIntentFrom(intent: Intent) =
Intent(intent).apply {
removeCategory(Intent.CATEGORY_LAUNCHER)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
ONBOARDING_REQUEST_CODE -> handleOnboardingResult(resultCode)
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
private fun handleOnboardingResult(resultCode: Int) {
when (resultCode) {
Activity.RESULT_OK -> onboardOrProceedToRouting()
else -> finish()
}
}
private fun onboardOrProceedToRouting() {
onboarding.nextPageToShow()
?.let { navigator.toOnboardingForResult(it, ONBOARDING_REQUEST_CODE) }
?: proceedTo(intent)
}
private fun proceedTo(intent: Intent) {
if (deepLinkRouter.hasDeepLink(intent)) {
val intentUriString = intent.dataString!!
Timber.i("Deeplink detected, navigating to $intentUriString")
deepLinkRouter.navigateTo(intentUriString)
} else {
navigator.toHomePage()
}
firstStartPersister.storeHasBeenStarted()
finish()
}
override fun onStop() {
super.onStop()
subscriptions.clear()
}
companion object {
private const val ONBOARDING_REQUEST_CODE = 2453
}
}
| apache-2.0 | bd9e4a7a28514ce1af793b9a3423d423 | 32.495327 | 101 | 0.678292 | 5.005587 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateEnumConstantAction.kt | 1 | 4382 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.ExpectedTypeUtil
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate
import com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInspection.CommonQuickFixBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.jvm.actions.CreateEnumConstantActionGroup
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.ExpectedTypes
import com.intellij.lang.jvm.actions.JvmActionGroup
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiFile
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
internal class CreateEnumConstantAction(
target: PsiClass,
override val request: CreateFieldRequest
) : CreateFieldActionBase(target, request), HighPriorityAction {
override fun getActionGroup(): JvmActionGroup = CreateEnumConstantActionGroup
override fun getText(): String = CommonQuickFixBundle.message("fix.create.title.x", JavaElementKind.ENUM_CONSTANT.`object`(), request.fieldName)
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val constructor = target.constructors.firstOrNull() ?: return IntentionPreviewInfo.EMPTY
val hasParameters = constructor.parameters.isNotEmpty()
val text = if (hasParameters) "${request.fieldName}(...)" else request.fieldName
return IntentionPreviewInfo.CustomDiff(JavaFileType.INSTANCE, "", text)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val name = request.fieldName
val targetClass = target
val elementFactory = JavaPsiFacade.getElementFactory(project)!!
// add constant
var enumConstant: PsiEnumConstant
enumConstant = elementFactory.createEnumConstantFromText(name, null)
enumConstant = targetClass.add(enumConstant) as PsiEnumConstant
// start template
val constructor = targetClass.constructors.firstOrNull() ?: return
val parameters = constructor.parameterList.parameters
if (parameters.isEmpty()) return
val paramString = parameters.joinToString(",") { it.name }
enumConstant = enumConstant.replace(elementFactory.createEnumConstantFromText("$name($paramString)", null)) as PsiEnumConstant
val builder = TemplateBuilderImpl(enumConstant)
val argumentList = enumConstant.argumentList!!
for (expression in argumentList.expressions) {
builder.replaceElement(expression, EmptyExpression())
}
enumConstant = forcePsiPostprocessAndRestoreElement(enumConstant) ?: return
val template = builder.buildTemplate()
val newEditor = positionCursor(project, targetClass.containingFile, enumConstant) ?: return
val range = enumConstant.textRange
newEditor.document.deleteString(range.startOffset, range.endOffset)
startTemplate(newEditor, template, project)
}
}
internal fun canCreateEnumConstant(targetClass: PsiClass, request: CreateFieldRequest): Boolean {
if (!targetClass.isEnum) return false
val lastConstant = targetClass.fields.filterIsInstance<PsiEnumConstant>().lastOrNull()
if (lastConstant != null && PsiTreeUtil.hasErrorElements(lastConstant)) return false
return checkExpectedTypes(request.fieldType, targetClass, targetClass.project)
}
private fun checkExpectedTypes(types: ExpectedTypes, targetClass: PsiClass, project: Project): Boolean {
val typeInfos = extractExpectedTypes(project, types)
if (typeInfos.isEmpty()) return true
val enumType = JavaPsiFacade.getElementFactory(project).createType(targetClass)
return typeInfos.any {
ExpectedTypeUtil.matches(enumType, it)
}
}
| apache-2.0 | dfa7d4da4a29c4699f98ec8adb13c9a4 | 46.630435 | 146 | 0.805796 | 5.030999 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SetVFUEntityImpl.kt | 2 | 8568 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SetVFUEntityImpl(val dataSource: SetVFUEntityData) : SetVFUEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: String
get() = dataSource.data
override val fileProperty: Set<VirtualFileUrl>
get() = dataSource.fileProperty
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SetVFUEntityData?) : ModifiableWorkspaceEntityBase<SetVFUEntity, SetVFUEntityData>(result), SetVFUEntity.Builder {
constructor() : this(SetVFUEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SetVFUEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
index(this, "fileProperty", this.fileProperty.toHashSet())
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field SetVFUEntity#data should be initialized")
}
if (!getEntityData().isFilePropertyInitialized()) {
error("Field SetVFUEntity#fileProperty should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override fun afterModification() {
val collection_fileProperty = getEntityData().fileProperty
if (collection_fileProperty is MutableWorkspaceSet<*>) {
collection_fileProperty.cleanModificationUpdateAction()
}
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SetVFUEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (this.fileProperty != dataSource.fileProperty) this.fileProperty = dataSource.fileProperty.toMutableSet()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
private val filePropertyUpdater: (value: Set<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "fileProperty", value.toHashSet())
changedProperty.add("fileProperty")
}
override var fileProperty: MutableSet<VirtualFileUrl>
get() {
val collection_fileProperty = getEntityData().fileProperty
if (collection_fileProperty !is MutableWorkspaceSet) return collection_fileProperty
if (diff == null || modifiable.get()) {
collection_fileProperty.setModificationUpdateAction(filePropertyUpdater)
}
else {
collection_fileProperty.cleanModificationUpdateAction()
}
return collection_fileProperty
}
set(value) {
checkModificationAllowed()
getEntityData(true).fileProperty = value
filePropertyUpdater.invoke(value)
}
override fun getEntityClass(): Class<SetVFUEntity> = SetVFUEntity::class.java
}
}
class SetVFUEntityData : WorkspaceEntityData<SetVFUEntity>() {
lateinit var data: String
lateinit var fileProperty: MutableSet<VirtualFileUrl>
fun isDataInitialized(): Boolean = ::data.isInitialized
fun isFilePropertyInitialized(): Boolean = ::fileProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SetVFUEntity> {
val modifiable = SetVFUEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SetVFUEntity {
return getCached(snapshot) {
val entity = SetVFUEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): SetVFUEntityData {
val clonedEntity = super.clone()
clonedEntity as SetVFUEntityData
clonedEntity.fileProperty = clonedEntity.fileProperty.toMutableWorkspaceSet()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SetVFUEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SetVFUEntity(data, fileProperty, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SetVFUEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SetVFUEntityData
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.fileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | f86762ed540e0c350e347b45d86a20e0 | 33.548387 | 138 | 0.726774 | 5.351655 | false | false | false | false |
ftomassetti/kolasu | core/src/main/kotlin/com/strumenta/kolasu/cli/ASTProcessingCommand.kt | 1 | 5156 | package com.strumenta.kolasu.cli
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.help
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import com.strumenta.kolasu.model.Node
import com.strumenta.kolasu.parsing.ASTParser
import com.strumenta.kolasu.parsing.ParsingResult
import com.strumenta.kolasu.validation.IssueSeverity
import java.io.File
import java.nio.charset.Charset
import java.util.function.Function
import kotlin.system.exitProcess
typealias ParserInstantiator<P> = Function<File, P?>
abstract class ASTProcessingCommand<R : Node, P : ASTParser<R>>(
val parserInstantiator: ParserInstantiator<P>,
help: String = "",
name: String? = null,
) :
CliktCommand(help = help, name = name) {
protected val inputs by argument().file(mustExist = true).multiple()
protected val charset by option("--charset", "-c")
.help("Set the charset to use to load the files. Default is UTF-8")
.default("UTF-8")
protected val ignorePositions by option("--ignore-positions")
.help("Ignore positions, so that they do not appear in the AST")
.flag("--consider-positions", default = false)
protected val verbose by option("--verbose", "-v")
.help("Print additional messages")
.flag(default = false)
override fun run() {
initializeRun()
if (inputs.isEmpty()) {
echo("No inputs specified, exiting", trailingNewline = true)
exitProcess(1)
}
inputs.forEach { processInput(it, explicit = true, relativePath = "") }
finalizeRun()
}
protected open fun initializeRun() {
}
protected open fun finalizeRun() {
}
/**
* If null is returned it means we cannot parse this file
*/
private fun instantiateParser(input: File): P? {
return parserInstantiator.apply(input)
}
protected abstract fun processResult(input: File, relativePath: String, result: ParsingResult<R>, parser: P)
protected abstract fun processException(input: File, relativePath: String, e: Exception)
private fun processSourceFile(input: File, relativePath: String) {
try {
val parser = instantiateParser(input)
if (parser == null) {
if (verbose) {
echo("skipping ${input.absolutePath}", trailingNewline = true)
}
return
}
if (verbose) {
echo("processing ${input.absolutePath}", trailingNewline = true)
}
val parsingResult =
parser.parse(input, Charset.forName(charset), considerPosition = !ignorePositions)
if (verbose) {
val nErrors = parsingResult.issues.count { it.severity == IssueSeverity.ERROR }
val nWarnings = parsingResult.issues.count { it.severity == IssueSeverity.WARNING }
if (nErrors == 0 && nWarnings == 0) {
echo(" no errors and no warnings", trailingNewline = true)
} else {
if (nErrors == 0) {
echo(" $nWarnings warnings", trailingNewline = true)
} else if (nWarnings == 0) {
echo(" $nErrors errors", trailingNewline = true)
} else {
echo(" $nErrors errors and $nWarnings warnings", trailingNewline = true)
}
}
}
processResult(input, relativePath, parsingResult, parser)
} catch (e: Exception) {
processException(input, relativePath, e)
}
}
private fun processInput(input: File, explicit: Boolean = false, relativePath: String) {
if (input.isDirectory) {
input.listFiles()?.forEach {
processInput(it, relativePath = relativePath + File.separator + it.name)
}
} else if (input.isFile) {
processSourceFile(input, relativePath)
} else {
if (explicit) {
echo(
"The provided input is neither a file or a directory, we will ignore it: " +
"${input.absolutePath}",
trailingNewline = true
)
} else {
// ignore silently
}
}
}
}
fun File.changeExtension(newExtension: String): File {
var name = this.name
val i = name.lastIndexOf('.')
return if (i == -1) {
val prefix = this.path.substring(0, this.path.length - this.name.length)
name = "$name.$newExtension"
File("${prefix}$name")
} else {
val prefix = this.path.substring(0, this.path.length - this.name.length)
name = name.substring(0, i + 1) + newExtension
File("${prefix}$name")
}
}
| apache-2.0 | f9560c68c9062c86e940e270a866f0bc | 37.766917 | 112 | 0.601629 | 4.570922 | false | false | false | false |
winterbe/expekt | src/main/kotlin/com/winterbe/expekt/ExpectCollection.kt | 1 | 4615 | package com.winterbe.expekt
/**
* @author Benjamin Winterberg
*/
class ExpectCollection<T>(subject: Collection<T>?, flavor: Flavor): ExpectAny<Collection<T>>(subject, flavor) {
private var anyMode = false
private var haveMode = false
val any: ExpectCollection<T> get() {
words.add("any")
anyMode = true
return this
}
val all: ExpectCollection<T> get() {
words.add("all")
anyMode = false
return this
}
override val have: ExpectCollection<T> get() {
words.add("have")
haveMode = true
return this
}
val contain: ExpectCollection<T> get() {
words.add("contain")
haveMode = false
return this
}
fun contain(other: T): ExpectCollection<T> {
words.add("contain")
words.add(other.toString())
verify { subject!!.contains(other) }
return this
}
fun elements(vararg elements: T): ExpectCollection<T> {
words.add("elements")
words.add(elements.toList().toString())
if (anyMode) {
verify { containsAny(elements) }
} else {
verify { containsAll(elements) }
}
return this
}
private fun containsAll(elements: Array<out T>): Boolean {
if (haveMode && elements.size != subject!!.size) {
return false
}
for (element in elements) {
if (!subject!!.contains(element)) {
return false
}
}
return true
}
private fun containsAny(elements: Array<out T>): Boolean {
// is the same for haveAny
for (element in elements) {
if (subject!!.contains(element)) {
return true
}
}
return false
}
val empty: ExpectCollection<T> get() {
words.add("empty")
verify { subject!!.isEmpty() }
return this
}
val size: ExpectComparable<Int> get() {
words.add("size")
val expectInt = ExpectComparable(subject!!.size, flavor)
expectInt.negated = negated
expectInt.words.addAll(words)
expectInt.words.removeAt(0)
expectInt.words.removeAt(0)
return expectInt
}
fun size(size: Int): ExpectCollection<T> {
words.add("size")
words.add(size.toString())
verify { subject!!.size == size }
return this
}
override val to: ExpectCollection<T> get() {
super.to
return this
}
override val be: ExpectCollection<T> get() {
super.be
return this
}
override val been: ExpectCollection<T> get() {
super.been
return this
}
override val that: ExpectCollection<T> get() {
super.that
return this
}
override val which: ExpectCollection<T> get() {
super.which
return this
}
override val and: ExpectCollection<T> get() {
super.and
return this
}
override val has: ExpectCollection<T> get() {
super.has
return this
}
override val with: ExpectCollection<T> get() {
super.with
return this
}
override val at: ExpectCollection<T> get() {
super.at
return this
}
override val a: ExpectCollection<T> get() {
super.a
return this
}
override val an: ExpectCollection<T> get() {
super.an
return this
}
override val of: ExpectCollection<T> get() {
super.of
return this
}
override val same: ExpectCollection<T> get() {
super.same
return this
}
override val the: ExpectCollection<T> get() {
super.the
return this
}
override val `is`: ExpectCollection<T> get() {
super.`is`
return this
}
override val not: ExpectCollection<T> get() {
super.not
return this
}
override val `null`: ExpectCollection<T> get() {
super.`null`
return this
}
override fun <S : Collection<T>> instanceof(type: Class<S>): ExpectCollection<T> {
super.instanceof(type)
return this
}
override fun identity(expected: Collection<T>?): ExpectCollection<T> {
super.identity(expected)
return this
}
override fun equal(expected: Collection<T>?): ExpectCollection<T> {
super.equal(expected)
return this
}
override fun satisfy(predicate: (Collection<T>) -> Boolean): ExpectCollection<T> {
super.satisfy(predicate)
return this
}
} | mit | d50b8cb51bc31569d855a7c18d99d681 | 21.738916 | 111 | 0.557313 | 4.476237 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/widget/materialdialogs/QuadStateMultiChoiceDialogAdapter.kt | 2 | 5447 | package eu.kanade.tachiyomi.widget.materialdialogs
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import eu.kanade.tachiyomi.databinding.DialogQuadstatemultichoiceItemBinding
private object CheckPayload
private object InverseCheckPayload
private object UncheckPayload
private object IndeterminatePayload
typealias QuadStateMultiChoiceListener = (indices: IntArray) -> Unit
// isAction state: Uncheck-> Check-> Invert else Uncheck-> Indeterminate (only if initial so)-> Check
// isAction for list of action to operate on like filter include, exclude
internal class QuadStateMultiChoiceDialogAdapter(
internal var items: List<CharSequence>,
disabledItems: IntArray?,
private var initialSelected: IntArray,
internal var listener: QuadStateMultiChoiceListener,
val isActionList: Boolean = true
) : RecyclerView.Adapter<QuadStateMultiChoiceViewHolder>() {
private val states = QuadStateTextView.State.values()
private var currentSelection: IntArray = initialSelected
set(value) {
val previousSelection = field
field = value
previousSelection.forEachIndexed { index, previous ->
val current = value[index]
when {
current == QuadStateTextView.State.CHECKED.ordinal && previous != QuadStateTextView.State.CHECKED.ordinal -> {
// This value was selected
notifyItemChanged(index, CheckPayload)
}
current == QuadStateTextView.State.INVERSED.ordinal && previous != QuadStateTextView.State.INVERSED.ordinal -> {
// This value was inverse selected
notifyItemChanged(index, InverseCheckPayload)
}
current == QuadStateTextView.State.UNCHECKED.ordinal && previous != QuadStateTextView.State.UNCHECKED.ordinal -> {
// This value was unselected
notifyItemChanged(index, UncheckPayload)
}
current == QuadStateTextView.State.INDETERMINATE.ordinal && previous != QuadStateTextView.State.INDETERMINATE.ordinal -> {
// This value was set back to Indeterminate
notifyItemChanged(index, IndeterminatePayload)
}
}
}
}
private var disabledIndices: IntArray = disabledItems ?: IntArray(0)
internal fun itemActionClicked(index: Int) {
val newSelection = this.currentSelection.toMutableList()
newSelection[index] = when (currentSelection[index]) {
QuadStateTextView.State.CHECKED.ordinal -> QuadStateTextView.State.INVERSED.ordinal
QuadStateTextView.State.INVERSED.ordinal -> QuadStateTextView.State.UNCHECKED.ordinal
// INDETERMINATE or UNCHECKED
else -> QuadStateTextView.State.CHECKED.ordinal
}
this.currentSelection = newSelection.toIntArray()
listener(currentSelection)
}
internal fun itemDisplayClicked(index: Int) {
val newSelection = this.currentSelection.toMutableList()
newSelection[index] = when (currentSelection[index]) {
QuadStateTextView.State.UNCHECKED.ordinal -> QuadStateTextView.State.CHECKED.ordinal
QuadStateTextView.State.CHECKED.ordinal -> when (initialSelected[index]) {
QuadStateTextView.State.INDETERMINATE.ordinal -> QuadStateTextView.State.INDETERMINATE.ordinal
else -> QuadStateTextView.State.UNCHECKED.ordinal
}
// INDETERMINATE or UNCHECKED
else -> QuadStateTextView.State.UNCHECKED.ordinal
}
this.currentSelection = newSelection.toIntArray()
listener(currentSelection)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): QuadStateMultiChoiceViewHolder {
return QuadStateMultiChoiceViewHolder(
itemBinding = DialogQuadstatemultichoiceItemBinding
.inflate(LayoutInflater.from(parent.context), parent, false),
adapter = this
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(
holder: QuadStateMultiChoiceViewHolder,
position: Int
) {
holder.isEnabled = !disabledIndices.contains(position)
holder.controlView.state = states[currentSelection[position]]
holder.controlView.text = items[position]
}
override fun onBindViewHolder(
holder: QuadStateMultiChoiceViewHolder,
position: Int,
payloads: MutableList<Any>
) {
when (payloads.firstOrNull()) {
CheckPayload -> {
holder.controlView.state = QuadStateTextView.State.CHECKED
return
}
InverseCheckPayload -> {
holder.controlView.state = QuadStateTextView.State.INVERSED
return
}
UncheckPayload -> {
holder.controlView.state = QuadStateTextView.State.UNCHECKED
return
}
IndeterminatePayload -> {
holder.controlView.state = QuadStateTextView.State.INDETERMINATE
return
}
}
super.onBindViewHolder(holder, position, payloads)
}
}
| apache-2.0 | fdc5de5f99da7f6fe5f81b2fa6b3a9ee | 41.554688 | 142 | 0.644759 | 5.998899 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/filter/CheckboxItem.kt | 3 | 1644 | package eu.kanade.tachiyomi.ui.browse.source.filter
import android.view.View
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Filter
open class CheckboxItem(val filter: Filter.CheckBox) : AbstractFlexibleItem<CheckboxItem.Holder>() {
override fun getLayoutRes(): Int {
return R.layout.navigation_view_checkbox
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder {
return Holder(view, adapter)
}
override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>?) {
val view = holder.check
view.text = filter.name
view.isChecked = filter.state
holder.itemView.setOnClickListener {
view.toggle()
filter.state = view.isChecked
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return filter == (other as CheckboxItem).filter
}
override fun hashCode(): Int {
return filter.hashCode()
}
class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) {
val check: CheckBox = itemView.findViewById(R.id.nav_view_item)
}
}
| apache-2.0 | 716082742da3f688a94d114d2a2e5dc4 | 34.73913 | 149 | 0.716545 | 4.617978 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/list/views/HabitCardListAdapter.kt | 1 | 8424 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.activities.habits.list.views
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.isoron.uhabits.activities.habits.list.MAX_CHECKMARK_COUNT
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.HabitMatcher
import org.isoron.uhabits.core.models.ModelObservable
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.ui.screens.habits.list.HabitCardListCache
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsMenuBehavior
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsSelectionMenuBehavior
import org.isoron.uhabits.core.utils.MidnightTimer
import org.isoron.uhabits.inject.ActivityScope
import java.util.LinkedList
import javax.inject.Inject
/**
* Provides data that backs a [HabitCardListView].
*
*
* The data if fetched and cached by a [HabitCardListCache]. This adapter
* also holds a list of items that have been selected.
*/
@ActivityScope
class HabitCardListAdapter @Inject constructor(
private val cache: HabitCardListCache,
private val preferences: Preferences,
private val midnightTimer: MidnightTimer
) : RecyclerView.Adapter<HabitCardViewHolder?>(),
HabitCardListCache.Listener,
MidnightTimer.MidnightListener,
ListHabitsMenuBehavior.Adapter,
ListHabitsSelectionMenuBehavior.Adapter {
val observable: ModelObservable = ModelObservable()
private var listView: HabitCardListView? = null
val selected: LinkedList<Habit> = LinkedList()
override fun atMidnight() {
cache.refreshAllHabits()
}
fun cancelRefresh() {
cache.cancelTasks()
}
fun hasNoHabit(): Boolean {
return cache.hasNoHabit()
}
/**
* Sets all items as not selected.
*/
override fun clearSelection() {
selected.clear()
notifyDataSetChanged()
observable.notifyListeners()
}
override fun getSelected(): List<Habit> {
return ArrayList(selected)
}
/**
* Returns the item that occupies a certain position on the list
*
* @param position position of the item
* @return the item at given position or null if position is invalid
*/
@Deprecated("")
fun getItem(position: Int): Habit? {
return cache.getHabitByPosition(position)
}
override fun getItemCount(): Int {
return cache.habitCount
}
override fun getItemId(position: Int): Long {
return getItem(position)!!.id!!
}
/**
* Returns whether list of selected items is empty.
*
* @return true if selection is empty, false otherwise
*/
val isSelectionEmpty: Boolean
get() = selected.isEmpty()
val isSortable: Boolean
get() = cache.primaryOrder == HabitList.Order.BY_POSITION
/**
* Notify the adapter that it has been attached to a ListView.
*/
fun onAttached() {
cache.onAttached()
midnightTimer.addListener(this)
}
override fun onBindViewHolder(
holder: HabitCardViewHolder,
position: Int
) {
if (listView == null) return
val habit = cache.getHabitByPosition(position)
val score = cache.getScore(habit!!.id!!)
val checkmarks = cache.getCheckmarks(habit.id!!)
val notes = cache.getNotes(habit.id!!)
val selected = selected.contains(habit)
listView!!.bindCardView(holder, habit, score, checkmarks, notes, selected)
}
override fun onViewAttachedToWindow(holder: HabitCardViewHolder) {
listView!!.attachCardView(holder)
}
override fun onViewDetachedFromWindow(holder: HabitCardViewHolder) {
listView!!.detachCardView(holder)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): HabitCardViewHolder {
val view = listView!!.createHabitCardView()
return HabitCardViewHolder(view)
}
/**
* Notify the adapter that it has been detached from a ListView.
*/
fun onDetached() {
cache.onDetached()
midnightTimer.removeListener(this)
}
override fun onItemChanged(position: Int) {
notifyItemChanged(position)
observable.notifyListeners()
}
override fun onItemInserted(position: Int) {
notifyItemInserted(position)
observable.notifyListeners()
}
override fun onItemMoved(oldPosition: Int, newPosition: Int) {
notifyItemMoved(oldPosition, newPosition)
observable.notifyListeners()
}
override fun onItemRemoved(position: Int) {
notifyItemRemoved(position)
observable.notifyListeners()
}
override fun onRefreshFinished() {
observable.notifyListeners()
}
/**
* Removes a list of habits from the adapter.
*
*
* Note that this only has effect on the adapter cache. The database is not
* modified, and the change is lost when the cache is refreshed. This method
* is useful for making the ListView more responsive: while we wait for the
* database operation to finish, the cache can be modified to reflect the
* changes immediately.
*
* @param selected list of habits to be removed
*/
override fun performRemove(selected: List<Habit>) {
for (habit in selected) cache.remove(habit.id!!)
}
/**
* Changes the order of habits on the adapter.
*
*
* Note that this only has effect on the adapter cache. The database is not
* modified, and the change is lost when the cache is refreshed. This method
* is useful for making the ListView more responsive: while we wait for the
* database operation to finish, the cache can be modified to reflect the
* changes immediately.
*
* @param from the habit that should be moved
* @param to the habit that currently occupies the desired position
*/
fun performReorder(from: Int, to: Int) {
cache.reorder(from, to)
}
override fun refresh() {
cache.refreshAllHabits()
}
override fun setFilter(matcher: HabitMatcher) {
cache.setFilter(matcher)
}
/**
* Sets the HabitCardListView that this adapter will provide data for.
*
*
* This object will be used to generated new HabitCardViews, upon demand.
*
* @param listView the HabitCardListView associated with this adapter
*/
fun setListView(listView: HabitCardListView?) {
this.listView = listView
}
override var primaryOrder: HabitList.Order
get() = cache.primaryOrder
set(value) {
cache.primaryOrder = value
preferences.defaultPrimaryOrder = value
}
override var secondaryOrder: HabitList.Order
get() = cache.secondaryOrder
set(value) {
cache.secondaryOrder = value
preferences.defaultSecondaryOrder = value
}
/**
* Selects or deselects the item at a given position.
*
* @param position position of the item to be toggled
*/
fun toggleSelection(position: Int) {
val h = getItem(position) ?: return
val k = selected.indexOf(h)
if (k < 0) selected.add(h) else selected.remove(h)
notifyDataSetChanged()
}
init {
cache.setListener(this)
cache.setCheckmarkCount(
MAX_CHECKMARK_COUNT
)
cache.secondaryOrder = preferences.defaultSecondaryOrder
cache.primaryOrder = preferences.defaultPrimaryOrder
setHasStableIds(true)
}
}
| gpl-3.0 | 9dc0286f342777e5e6ca2250f45df710 | 30.429104 | 85 | 0.677668 | 4.674251 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/dataset/internal/DataSetInstanceServiceImpl.kt | 1 | 8379 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.dataset.internal
import dagger.Reusable
import io.reactivex.Single
import java.util.Date
import javax.inject.Inject
import org.hisp.dhis.android.core.category.CategoryOption
import org.hisp.dhis.android.core.category.CategoryOptionCollectionRepository
import org.hisp.dhis.android.core.category.CategoryOptionComboService
import org.hisp.dhis.android.core.dataset.DataSet
import org.hisp.dhis.android.core.dataset.DataSetCollectionRepository
import org.hisp.dhis.android.core.dataset.DataSetEditableStatus
import org.hisp.dhis.android.core.dataset.DataSetInstanceService
import org.hisp.dhis.android.core.dataset.DataSetNonEditableReason
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitService
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodType
import org.hisp.dhis.android.core.period.internal.ParentPeriodGenerator
import org.hisp.dhis.android.core.period.internal.PeriodHelper
@Reusable
@Suppress("TooManyFunctions")
internal class DataSetInstanceServiceImpl @Inject constructor(
private val dataSetCollectionRepository: DataSetCollectionRepository,
private val categoryOptionRepository: CategoryOptionCollectionRepository,
private val organisationUnitService: OrganisationUnitService,
private val periodHelper: PeriodHelper,
private val categoryOptionComboService: CategoryOptionComboService,
private val periodGenerator: ParentPeriodGenerator,
) : DataSetInstanceService {
override fun getEditableStatus(
dataSetUid: String,
periodId: String,
organisationUnitUid: String,
attributeOptionComboUid: String
): Single<DataSetEditableStatus> {
return Single.fromCallable {
blockingGetEditableStatus(
dataSetUid = dataSetUid,
periodId = periodId,
organisationUnitUid = organisationUnitUid,
attributeOptionComboUid = attributeOptionComboUid
)
}
}
@Suppress("ComplexMethod")
override fun blockingGetEditableStatus(
dataSetUid: String,
periodId: String,
organisationUnitUid: String,
attributeOptionComboUid: String
): DataSetEditableStatus {
val dataSet = dataSetCollectionRepository.uid(dataSetUid).blockingGet()
val period = periodHelper.getPeriodForPeriodId(periodId).blockingGet()
return when {
!blockingHasDataWriteAccess(dataSetUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.NO_DATASET_DATA_WRITE_ACCESS)
!blockingIsCategoryOptionHasDataWriteAccess(attributeOptionComboUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.NO_ATTRIBUTE_OPTION_COMBO_ACCESS)
!blockingIsPeriodInCategoryOptionRange(period, attributeOptionComboUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.PERIOD_IS_NOT_IN_ATTRIBUTE_OPTION_RANGE)
!blockingIsOrgUnitInCaptureScope(organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.ORGUNIT_IS_NOT_IN_CAPTURE_SCOPE)
!blockingIsAttributeOptionComboAssignToOrgUnit(attributeOptionComboUid, organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.ATTRIBUTE_OPTION_COMBO_NO_ASSIGN_TO_ORGUNIT)
!blockingIsPeriodInOrgUnitRange(period, organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.PERIOD_IS_NOT_IN_ORGUNIT_RANGE)
!blockingIsExpired(dataSet, period) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.EXPIRED)
!blockingIsClosed(dataSet, period) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.CLOSED)
else -> DataSetEditableStatus.Editable
}
}
fun blockingIsCategoryOptionHasDataWriteAccess(categoryOptionComboUid: String): Boolean {
val categoryOptions = getCategoryOptions(categoryOptionComboUid)
return categoryOptionComboService.blockingHasWriteAccess(categoryOptions)
}
fun blockingIsPeriodInCategoryOptionRange(period: Period, categoryOptionComboUid: String): Boolean {
val categoryOptions = getCategoryOptions(categoryOptionComboUid)
val dates = listOf(period.startDate(), period.endDate())
return dates.all { date ->
categoryOptionComboService.isInOptionRange(categoryOptions, date)
}
}
fun blockingIsOrgUnitInCaptureScope(orgUnitUid: String): Boolean {
return organisationUnitService.blockingIsInCaptureScope(orgUnitUid)
}
fun blockingIsAttributeOptionComboAssignToOrgUnit(
categoryOptionComboUid: String,
orgUnitUid: String
): Boolean {
return categoryOptionComboService.blockingIsAssignedToOrgUnit(
categoryOptionComboUid = categoryOptionComboUid,
orgUnitUid = orgUnitUid
)
}
fun blockingIsExpired(dataSet: DataSet, period: Period): Boolean {
val expiryDays = dataSet.expiryDays() ?: return false
val generatedPeriod = period.endDate()?.let { endDate ->
periodGenerator.generatePeriod(
periodType = PeriodType.Daily,
date = endDate,
offset = expiryDays - 1
)
}
return Date().after(generatedPeriod?.endDate())
}
fun blockingIsClosed(dataSet: DataSet, period: Period): Boolean {
val periodType = dataSet.periodType() ?: return true
val openFuturePeriods = dataSet.openFuturePeriods() ?: 0
val generatedPeriod = periodGenerator.generatePeriod(
periodType = periodType,
date = Date(),
offset = openFuturePeriods - 1
)
return period.endDate()?.before(generatedPeriod?.endDate()) ?: true
}
override fun hasDataWriteAccess(dataSetUid: String): Single<Boolean> {
return Single.just(blockingHasDataWriteAccess(dataSetUid))
}
fun blockingHasDataWriteAccess(dataSetUid: String): Boolean {
val dataSet = dataSetCollectionRepository.uid(dataSetUid).blockingGet() ?: return false
return dataSet.access().write() ?: false
}
fun blockingIsPeriodInOrgUnitRange(period: Period, orgUnitUid: String): Boolean {
return listOfNotNull(period.startDate(), period.endDate()).all { date ->
organisationUnitService.blockingIsDateInOrgunitRange(orgUnitUid, date)
}
}
private fun getCategoryOptions(attributeOptionComboUid: String): List<CategoryOption> {
return categoryOptionRepository
.byCategoryOptionComboUid(attributeOptionComboUid)
.blockingGet()
}
}
| bsd-3-clause | 90ae6901b1f62a94ef9724f5fcf7e180 | 46.607955 | 119 | 0.735291 | 5.367713 | false | false | false | false |
sybila/ctl-model-checker | src/main/kotlin/com/github/sybila/checker/CheckerStats.kt | 3 | 1900 | package com.github.sybila.checker
import java.io.PrintStream
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
object CheckerStats {
private val printInterval = 4000
private var output: PrintStream? = System.out
private val totalMapReduce = AtomicLong()
private val totalMapReduceSize = AtomicLong()
private val operator = AtomicReference<String>("none")
private val mapReduce = AtomicLong()
private val mapReduceSize = AtomicLong()
private val lastPrint = AtomicLong(System.currentTimeMillis())
fun reset(output: PrintStream?) {
this.output = output
lastPrint.set(System.currentTimeMillis())
mapReduce.set(0)
mapReduceSize.set(0)
}
fun setOperator(operator: String) {
this.operator.set(operator)
}
fun mapReduce(size: Long) {
val time = System.currentTimeMillis()
val last = lastPrint.get()
val calls = mapReduce.incrementAndGet()
val currentSize = mapReduceSize.addAndGet(size)
//CAS ensures only one thread will actually print something.
//We might lose one or two calls, but that really doesn't matter.
if (time > last + printInterval && lastPrint.compareAndSet(last, time)) {
mapReduce.set(0)
mapReduceSize.set(0)
output?.println("Map-Reduce: $calls calls. (avr. size: ${currentSize/calls})")
output?.println("Verification: ${operator.get()}")
}
//update global stats
totalMapReduce.incrementAndGet()
totalMapReduceSize.addAndGet(size)
}
fun printGlobal() {
val total = totalMapReduce.get()
val totalSize = totalMapReduceSize.get()
output?.println("Total Map-Reduce calls: $total")
output?.println("Average call size: ${totalSize/Math.max(1, total).toDouble()}")
}
} | gpl-3.0 | 5acb015f49e1b6ac857b2a93a5f7e4ae | 32.946429 | 90 | 0.663684 | 4.656863 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/CopyPathProvider.kt | 5 | 5626 | // 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 com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.CopyReferenceUtil.getElementsToCopy
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.ui.tabs.impl.TabLabel
import java.awt.datatransfer.StringSelection
abstract class CopyPathProvider : AnAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val dataContext = e.dataContext
val editor = CommonDataKeys.EDITOR.getData(dataContext)
val project = e.project
e.presentation.isEnabledAndVisible = project != null
&& getQualifiedName(project, getElementsToCopy(editor, dataContext), editor, dataContext) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = getEventProject(e)
val dataContext = e.dataContext
val editor = CommonDataKeys.EDITOR.getData(dataContext)
val customDataContext = createCustomDataContext(dataContext)
val elements = getElementsToCopy(editor, customDataContext)
project?.let {
val copy = getQualifiedName(project, elements, editor, customDataContext)
CopyPasteManager.getInstance().setContents(StringSelection(copy))
CopyReferenceUtil.setStatusBarText(project, IdeBundle.message("message.path.to.fqn.has.been.copied", copy))
CopyReferenceUtil.highlight(editor, project, elements)
}
}
private fun createCustomDataContext(dataContext: DataContext): DataContext {
val component = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(dataContext)
if (component !is TabLabel) return dataContext
val file = component.info.`object`
if (file !is VirtualFile) return dataContext
return SimpleDataContext.builder()
.setParent(dataContext)
.add(LangDataKeys.VIRTUAL_FILE, file)
.add(CommonDataKeys.VIRTUAL_FILE_ARRAY, arrayOf(file))
.build()
}
@NlsSafe
open fun getQualifiedName(project: Project, elements: List<PsiElement>, editor: Editor?, dataContext: DataContext): String? {
if (elements.isEmpty()) {
return getPathToElement(project, editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }, editor)
}
val refs =
elements
.mapNotNull { getPathToElement(project, (if (it is PsiFileSystemItem) it.virtualFile else it.containingFile?.virtualFile), editor) }
.ifEmpty { CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext)?.mapNotNull { getPathToElement(project, it, editor) } }
.orEmpty()
.filter { it.isNotBlank() }
return if (refs.isNotEmpty()) refs.joinToString("\n") else null
}
open fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? = null
}
abstract class DumbAwareCopyPathProvider : CopyPathProvider(), DumbAware
class CopyAbsolutePathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?) = virtualFile?.presentableUrl
}
class CopyContentRootPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project,
virtualFile: VirtualFile?,
editor: Editor?): String? {
return virtualFile?.let {
ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile, false)?.let { module ->
ModuleRootManager.getInstance(module).contentRoots.mapNotNull { root ->
VfsUtilCore.getRelativePath(virtualFile, root)
}.singleOrNull()
}
}
}
}
class CopyFileWithLineNumberPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project,
virtualFile: VirtualFile?,
editor: Editor?): String? {
return if (virtualFile == null) null
else editor?.let { CopyReferenceUtil.getVirtualFileFqn(virtualFile, project) + ":" + (editor.caretModel.logicalPosition.line + 1) }
}
}
class CopySourceRootPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?) =
virtualFile?.let {
VfsUtilCore.getRelativePath(virtualFile, ProjectFileIndex.getInstance(project).getSourceRootForFile(virtualFile) ?: return null)
}
}
class CopyTBXReferenceProvider : CopyPathProvider() {
override fun getQualifiedName(project: Project,
elements: List<PsiElement>,
editor: Editor?,
dataContext: DataContext): String? =
CopyTBXReferenceAction.createJetBrainsLink(project, elements, editor)
}
class CopyFileNameProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? = virtualFile?.name
} | apache-2.0 | baa1f3ab6cc04ce614d77ee78d5084d2 | 42.284615 | 158 | 0.732847 | 5.063906 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/common/Duration.kt | 1 | 3426 | /*
* Copyright (c) 2019 Spotify AB.
*
* 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 com.spotify.heroic.common
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
/**
* A helper type that represents a duration as the canonical duration/unit.
* <p>
* This is provided so that we can implement a parser for it to simplify configurations that require
* durations.
* <p>
* This type is intended to be conveniently de-serialize from a short-hand string type, like the
* following examples.
* <p>
* <ul> <li>1H - 1 Hour</li> <li>5m - 5 minutes</li> </ul>
*
* @author udoprog
*/
data class Duration(val duration: Long, var unit: TimeUnit? = TimeUnit.SECONDS) {
init {
unit = unit ?: TimeUnit.SECONDS
}
fun convert(unit: TimeUnit) = unit.convert(duration, this.unit)
fun toMilliseconds() = convert(TimeUnit.MILLISECONDS)
fun withUnit(other: TimeUnit) = Duration(duration, other)
fun toDSL() = duration.toString() + unitSuffix(unit!!)
companion object {
@JvmField val DEFAULT_UNIT = TimeUnit.MILLISECONDS
@JvmStatic
fun of(duration: Long, unit: TimeUnit?) = Duration(duration, unit)
private val PATTERN = Pattern.compile("^(\\d+)([a-zA-Z]*)$")
private val units = mapOf(
"ms" to TimeUnit.MILLISECONDS,
"s" to TimeUnit.SECONDS,
"m" to TimeUnit.MINUTES,
"h" to TimeUnit.HOURS,
"H" to TimeUnit.HOURS,
"d" to TimeUnit.DAYS
)
fun unitSuffix(unit: TimeUnit): String {
return when (unit) {
TimeUnit.MILLISECONDS -> "ms"
TimeUnit.SECONDS -> "s"
TimeUnit.MINUTES -> "m"
TimeUnit.HOURS -> "h"
TimeUnit.DAYS -> "d"
else -> throw IllegalStateException("Unit not supported for serialization: $unit")
}
}
@JvmStatic
fun parseDuration(string: String): Duration {
val m = PATTERN.matcher(string)
if (!m.matches()) throw IllegalArgumentException("Invalid duration: $string")
val duration = m.group(1).toLong()
val unitString = m.group(2)
if (unitString.isEmpty()) return Duration(duration, DEFAULT_UNIT)
if ("w" == unitString) return Duration(duration * 7, TimeUnit.DAYS)
val unit = units[unitString]
?: throw IllegalArgumentException("Invalid unit ($unitString) in duration: $string")
return Duration(duration, unit)
}
}
}
| apache-2.0 | 4c388d2d4c300033e43069e5ccbf8361 | 32.588235 | 100 | 0.642148 | 4.314861 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/FilesProcessorWithNotificationImpl.kt | 1 | 5114 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs
import com.intellij.CommonBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vfs.VirtualFile
abstract class FilesProcessorWithNotificationImpl(protected val project: Project, parentDisposable: Disposable) : FilesProcessor {
private val vcsNotifier = VcsNotifier.getInstance(project)
protected val projectProperties = PropertiesComponent.getInstance(project)
private val files = mutableSetOf<VirtualFile>()
private val NOTIFICATION_LOCK = Object()
private var notification: Notification? = null
abstract val askedBeforeProperty: String
abstract val doForCurrentProjectProperty: String
abstract val showActionText: String
abstract val forCurrentProjectActionText: String
abstract val forAllProjectsActionText: String?
abstract val muteActionText: String
abstract fun notificationTitle(): String
abstract fun notificationMessage(): String
abstract fun doActionOnChosenFiles(files: Collection<VirtualFile>)
abstract fun doFilterFiles(files: Collection<VirtualFile>): Collection<VirtualFile>
abstract fun rememberForAllProjects()
init {
Disposer.register(parentDisposable, this)
}
override fun processFiles(files: List<VirtualFile>): List<VirtualFile> {
val filteredFiles = doFilterFiles(files)
if (filteredFiles.isEmpty()) return files
addNewFiles(filteredFiles)
if (needDoForCurrentProject()) {
doActionOnChosenFiles(acquireValidFiles())
clearFiles()
}
else {
proposeToProcessFiles()
}
return files - filteredFiles
}
private fun proposeToProcessFiles() {
synchronized(NOTIFICATION_LOCK) {
if (notAskedBefore() && notificationNotPresent()) {
val notificationActions = mutableListOf(showAction(), addForCurrentProjectAction()).apply {
if (forAllProjectsActionText != null) {
add(forAllProjectsAction())
}
add(muteAction())
}
notification = vcsNotifier.notifyMinorInfo(true, notificationTitle(), notificationMessage(), *notificationActions.toTypedArray())
}
}
}
@Synchronized
private fun removeFiles(filesToRemove: Collection<VirtualFile>) {
files.removeAll(filesToRemove)
}
@Synchronized
private fun isFilesEmpty() = files.isEmpty()
@Synchronized
private fun addNewFiles(filesToAdd: Collection<VirtualFile>) {
files.addAll(filesToAdd)
}
@Synchronized
private fun acquireValidFiles(): List<VirtualFile> {
files.removeAll { !it.isValid }
return files.toList()
}
@Synchronized
private fun clearFiles() {
files.clear()
}
override fun dispose() {
clearFiles()
}
private fun showAction() = NotificationAction.createSimple(showActionText) {
val allFiles = acquireValidFiles()
if (allFiles.isNotEmpty()) {
with(SelectFilesDialog.init(project, allFiles, null, null, true, true,
CommonBundle.getAddButtonText(), CommonBundle.getCancelButtonText())) {
selectedFiles = allFiles
if (showAndGet()) {
val userSelectedFiles = selectedFiles
doActionOnChosenFiles(userSelectedFiles)
removeFiles(userSelectedFiles)
if (isFilesEmpty()) {
expireNotification()
}
}
}
}
}
private fun addForCurrentProjectAction() = NotificationAction.create(forCurrentProjectActionText) { _, _ ->
doActionOnChosenFiles(acquireValidFiles())
projectProperties.setValue(doForCurrentProjectProperty, true)
projectProperties.setValue(askedBeforeProperty, true)
expireNotification()
clearFiles()
}
private fun forAllProjectsAction() = NotificationAction.create(forAllProjectsActionText!!) { _, _ ->
doActionOnChosenFiles(acquireValidFiles())
projectProperties.setValue(doForCurrentProjectProperty, true)
projectProperties.setValue(askedBeforeProperty, true)
rememberForAllProjects()
expireNotification()
clearFiles()
}
private fun muteAction() = NotificationAction.create(muteActionText) { _, notification ->
projectProperties.setValue(doForCurrentProjectProperty, false)
projectProperties.setValue(askedBeforeProperty, true)
notification.expire()
}
private fun notificationNotPresent() =
synchronized(NOTIFICATION_LOCK) {
notification?.isExpired ?: true
}
private fun expireNotification() =
synchronized(NOTIFICATION_LOCK) {
notification?.expire()
}
private fun notAskedBefore() = !projectProperties.getBoolean(askedBeforeProperty, false)
private fun needDoForCurrentProject() = projectProperties.getBoolean(doForCurrentProjectProperty, false)
} | apache-2.0 | b67bc91af4347ec0d45849e646048dca | 30.380368 | 140 | 0.738365 | 5.234391 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/playback/PlaybackService.kt | 1 | 10710 | package de.ph1b.audiobook.playback
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaSessionCompat
import androidx.media.MediaBrowserServiceCompat
import androidx.media.session.MediaButtonReceiver
import de.ph1b.audiobook.common.getIfPresent
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.injection.appComponent
import de.ph1b.audiobook.misc.RxBroadcast
import de.ph1b.audiobook.misc.rxCompletable
import de.ph1b.audiobook.persistence.pref.Pref
import de.ph1b.audiobook.playback.PlayStateManager.PauseReason
import de.ph1b.audiobook.playback.PlayStateManager.PlayState
import de.ph1b.audiobook.playback.events.HeadsetPlugReceiver
import de.ph1b.audiobook.playback.utils.BookUriConverter
import de.ph1b.audiobook.playback.utils.ChangeNotifier
import de.ph1b.audiobook.playback.utils.MediaBrowserHelper
import de.ph1b.audiobook.playback.utils.NotificationCreator
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.util.UUID
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
/**
* Service that hosts the longtime playback and handles its controls.
*/
class PlaybackService : MediaBrowserServiceCompat() {
private val disposables = CompositeDisposable()
private var isForeground = false
@field:[Inject Named(PrefKeys.CURRENT_BOOK)]
lateinit var currentBookIdPref: Pref<UUID>
@Inject
lateinit var player: MediaPlayer
@Inject
lateinit var repo: BookRepository
@Inject
lateinit var notificationManager: NotificationManager
@Inject
lateinit var notificationCreator: NotificationCreator
@Inject
lateinit var playStateManager: PlayStateManager
@Inject
lateinit var bookUriConverter: BookUriConverter
@Inject
lateinit var mediaBrowserHelper: MediaBrowserHelper
@Inject
lateinit var mediaSession: MediaSessionCompat
@Inject
lateinit var changeNotifier: ChangeNotifier
@Inject
lateinit var autoConnected: AndroidAutoConnectedReceiver
@Inject
lateinit var notifyOnAutoConnectionChange: NotifyOnAutoConnectionChange
@field:[Inject Named(PrefKeys.RESUME_ON_REPLUG)]
lateinit var resumeOnReplugPref: Pref<Boolean>
override fun onCreate() {
appComponent.playbackComponent()
.playbackService(this)
.build()
.inject(this)
super.onCreate()
sessionToken = mediaSession.sessionToken
// update book when changed by player
player.bookContentStream.map { it.settings }
.distinctUntilChanged()
.switchMapCompletable { settings ->
rxCompletable { repo.updateBookSettings(settings) }
}
.subscribe()
.disposeOnDestroy()
notifyOnAutoConnectionChange.listen()
currentBookIdPref.stream
.subscribe { currentBookIdChanged(it) }
.disposeOnDestroy()
val bookUpdated = currentBookIdPref.stream
.switchMap { repo.byId(it).getIfPresent() }
.distinctUntilChanged { old, new ->
old.content == new.content
}
bookUpdated
.doOnNext {
Timber.i("init ${it.name}")
player.init(it.content)
}
.switchMapCompletable {
rxCompletable {
changeNotifier.notify(ChangeNotifier.Type.METADATA, it, autoConnected.connected)
}
}
.subscribe()
.disposeOnDestroy()
bookUpdated
.distinctUntilChanged { book -> book.content.currentChapter }
.switchMapCompletable {
rxCompletable {
if (isForeground) {
updateNotification(it)
}
}
}
.subscribe()
.disposeOnDestroy()
playStateManager.playStateStream()
.observeOn(Schedulers.io())
.switchMapCompletable {
rxCompletable { handlePlaybackState(it) }
}
.subscribe()
.disposeOnDestroy()
HeadsetPlugReceiver.events(this@PlaybackService)
.filter { it == HeadsetPlugReceiver.HeadsetState.PLUGGED }
.subscribe { headsetPlugged() }
.disposeOnDestroy()
repo.booksStream()
.map { it.size }
.distinctUntilChanged()
.subscribe {
notifyChildrenChanged(bookUriConverter.allBooksId())
}
.disposeOnDestroy()
RxBroadcast
.register(
this@PlaybackService,
IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)
)
.subscribe { audioBecomingNoisy() }
.disposeOnDestroy()
tearDownAutomatically()
}
private suspend fun updateNotification(book: Book) {
val notification = notificationCreator.createNotification(book)
notificationManager.notify(NOTIFICATION_ID, notification)
}
private fun tearDownAutomatically() {
val idleTimeOutInSeconds: Long = 7
playStateManager.playStateStream()
.distinctUntilChanged()
.debounce(idleTimeOutInSeconds, TimeUnit.SECONDS)
.filter { it == PlayState.STOPPED }
.subscribe {
Timber.d("STOPPED for $idleTimeOutInSeconds. Stop self")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android O has the dumb restriction that a service that was launched by startForegroundService must go to foreground within
// 10 seconds - even if we are going to stop it anyways.
// @see [https://issuetracker.google.com/issues/76112072]
startForeground(NOTIFICATION_ID, notificationCreator.createDummyNotification())
}
stopSelf()
}
.disposeOnDestroy()
}
private fun currentBookIdChanged(id: UUID) {
if (player.bookContent?.id != id) {
player.stop()
repo.bookById(id)?.let { player.init(it.content) }
}
}
private fun headsetPlugged() {
if (playStateManager.pauseReason == PauseReason.BECAUSE_HEADSET) {
if (resumeOnReplugPref.value) {
play()
}
}
}
private fun audioBecomingNoisy() {
Timber.d("audio becoming noisy. playState=${playStateManager.playState}")
if (playStateManager.playState === PlayState.PLAYING) {
playStateManager.pauseReason = PauseReason.BECAUSE_HEADSET
player.pause(true)
}
}
private suspend fun handlePlaybackState(state: PlayState) {
Timber.d("handlePlaybackState $state")
when (state) {
PlayState.PLAYING -> handlePlaybackStatePlaying()
PlayState.PAUSED -> handlePlaybackStatePaused()
PlayState.STOPPED -> handlePlaybackStateStopped()
}
currentBook()?.let {
changeNotifier.notify(ChangeNotifier.Type.PLAY_STATE, it, autoConnected.connected)
}
}
private fun currentBook(): Book? {
val id = currentBookIdPref.value
return repo.bookById(id)
}
private fun handlePlaybackStateStopped() {
mediaSession.isActive = false
notificationManager.cancel(NOTIFICATION_ID)
stopForeground(true)
isForeground = false
}
private suspend fun handlePlaybackStatePaused() {
stopForeground(false)
isForeground = false
currentBook()?.let {
updateNotification(it)
}
}
private suspend fun handlePlaybackStatePlaying() {
Timber.d("set mediaSession to active")
mediaSession.isActive = true
currentBook()?.let {
val notification = notificationCreator.createNotification(it)
startForeground(NOTIFICATION_ID, notification)
isForeground = true
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Timber.v("onStartCommand, intent=$intent, flags=$flags, startId=$startId")
when (intent?.action) {
Intent.ACTION_MEDIA_BUTTON -> {
MediaButtonReceiver.handleIntent(mediaSession, intent)
}
PlayerController.ACTION_SPEED -> {
val speed = intent.getFloatExtra(PlayerController.EXTRA_SPEED, 1F)
player.setPlaybackSpeed(speed)
}
PlayerController.ACTION_CHANGE -> {
val time = intent.getIntExtra(PlayerController.CHANGE_TIME, 0)
val file = File(intent.getStringExtra(PlayerController.CHANGE_FILE))
player.changePosition(time, file)
}
PlayerController.ACTION_FORCE_NEXT -> player.next()
PlayerController.ACTION_FORCE_PREVIOUS -> player.previous(toNullOfNewTrack = true)
PlayerController.ACTION_LOUDNESS -> {
val loudness = intent.getIntExtra(PlayerController.CHANGE_LOUDNESS, 0)
player.setLoudnessGain(loudness)
}
PlayerController.ACTION_SKIP_SILENCE -> {
val skipSilences = intent.getBooleanExtra(PlayerController.SKIP_SILENCE, false)
player.setSkipSilences(skipSilences)
}
PlayerController.ACTION_PLAY_PAUSE -> {
if (playStateManager.playState == PlayState.PLAYING) {
player.pause(true)
} else {
play()
}
}
PlayerController.ACTION_STOP -> player.stop()
PlayerController.ACTION_PLAY -> play()
PlayerController.ACTION_REWIND -> player.skip(forward = false)
PlayerController.ACTION_REWIND_AUTO_PLAY -> {
player.skip(forward = false)
play()
}
PlayerController.ACTION_FAST_FORWARD -> player.skip(forward = true)
PlayerController.ACTION_FAST_FORWARD_AUTO_PLAY -> {
player.skip(forward = true)
play()
}
}
return Service.START_NOT_STICKY
}
override fun onLoadChildren(
parentId: String,
result: Result<List<MediaBrowserCompat.MediaItem>>
) {
result.detach()
val job = GlobalScope.launch {
val children = mediaBrowserHelper.loadChildren(parentId)
result.sendResult(children)
}
Disposables.fromAction { job.cancel() }.disposeOnDestroy()
}
override fun onGetRoot(
clientPackageName: String,
clientUid: Int,
rootHints: Bundle?
): BrowserRoot {
return MediaBrowserServiceCompat.BrowserRoot(mediaBrowserHelper.root(), null)
}
private fun play() {
GlobalScope.launch { repo.markBookAsPlayedNow(currentBookIdPref.value) }
player.play()
}
private fun Disposable.disposeOnDestroy() {
disposables.add(this)
}
override fun onDestroy() {
Timber.v("onDestroy called")
player.stop()
mediaSession.release()
disposables.dispose()
notifyOnAutoConnectionChange.unregister()
super.onDestroy()
}
companion object {
private const val NOTIFICATION_ID = 42
}
}
| lgpl-3.0 | 35df274278ad4da786ea38dab244f210 | 30.043478 | 135 | 0.710924 | 4.636364 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/index/KotlinPerFileElementTypeModificationTrackerTest.kt | 1 | 2158 | // 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.index
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.indexing.StubIndexPerFileElementTypeModificationTrackerTestHelper
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.stubs.elements.KtFileElementType
class KotlinPerFileElementTypeModificationTrackerTest : KotlinLightCodeInsightFixtureTestCase() {
companion object {
val KOTLIN = KtFileElementType.INSTANCE
}
private val helper = StubIndexPerFileElementTypeModificationTrackerTestHelper()
override fun setUp() {
super.setUp()
helper.setUp()
}
fun `test mod counter changes on file creation and stub change`() {
helper.initModCounts(KOTLIN)
val psi = myFixture.addFileToProject("a/Foo.kt", """
class Foo {
var value: Integer = 42
}
""".trimIndent())
helper.ensureStubIndexUpToDate(project)
helper.checkModCountHasChanged(KOTLIN)
WriteAction.run<Throwable> { VfsUtil.saveText(psi.containingFile.virtualFile, """
class Foo {
var value: Double = 42.42
}
""".trimIndent()); }
helper.checkModCountHasChanged(KOTLIN)
}
fun `test mod counter doesnt change on non-stub changes`() {
helper.initModCounts(KOTLIN)
val psi = myFixture.addFileToProject("Foo.kt", """
class Foo {
fun test(x: Integer): Boolean {
return false
}
}
""".trimIndent())
helper.checkModCountHasChanged(KOTLIN)
helper.ensureStubIndexUpToDate(project)
WriteAction.run<Throwable> { VfsUtil.saveText(psi.containingFile.virtualFile, """
class Foo {
fun test(x: Integer): Boolean {
return x >= 0
}
}
""".trimIndent()); }
helper.checkModCountIsSame(KOTLIN)
}
} | apache-2.0 | bc92e939259d21ca64f16c1b946ed6d7 | 34.983333 | 120 | 0.645968 | 5.077647 | false | true | false | false |
Masterzach32/SwagBot | src/main/kotlin/commands/Prune.kt | 1 | 1452 | package xyz.swagbot.commands
import discord4j.common.util.*
import discord4j.core.`object`.entity.*
import io.facet.commands.*
import io.facet.common.*
import kotlinx.coroutines.flow.*
object Prune : GlobalGuildApplicationCommand, PermissibleApplicationCommand {
override val request = applicationCommandRequest("prune", "Delete the last X number of messages in this text channel") {
int("count", "Number of messages to delete", true)
}
override suspend fun hasPermission(user: User, guild: Guild?): Boolean = user.id == user.client.applicationInfo.await().ownerId
override suspend fun GuildSlashCommandContext.execute() {
val count: Long by options
val channel = getChannel()
if (count !in 2..100)
return event.reply("`count` must be between 2 and 100.").withEphemeral(true).await()
event.acknowledgeEphemeral().await()
val notDeleted: List<Snowflake> = channel.bulkDelete(
channel.getMessagesBefore(event.interaction.id)
.take(count)
.map { it.id }
).await()
val stillNotDeleted = notDeleted.asFlow()
.map { client.getMessageById(channel.id, it).await() }
.buffer()
.map { it?.delete()?.await() }
.count()
event.interactionResponse
.createFollowupMessage("Deleted **${count - stillNotDeleted}** messages.")
.await()
}
}
| gpl-2.0 | f39a1dda67f834cc9d48223f2329d516 | 33.571429 | 131 | 0.643251 | 4.523364 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/data/personal_deadlines/repository/DeadlinesRepositoryImpl.kt | 1 | 2537 | package org.stepik.android.data.personal_deadlines.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import ru.nobird.android.domain.rx.doCompletableOnSuccess
import org.stepic.droid.util.then
import org.stepic.droid.web.storage.model.StorageRecord
import org.stepik.android.data.personal_deadlines.source.DeadlinesCacheDataSource
import org.stepik.android.data.personal_deadlines.source.DeadlinesRemoteDataSource
import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper
import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository
import javax.inject.Inject
class DeadlinesRepositoryImpl
@Inject
constructor(
private val deadlinesRemoteDataSource: DeadlinesRemoteDataSource,
private val deadlinesCacheDataSource: DeadlinesCacheDataSource
) : DeadlinesRepository {
override fun createDeadlineRecord(deadlines: DeadlinesWrapper): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.createDeadlineRecord(deadlines)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun updateDeadlineRecord(record: StorageRecord<DeadlinesWrapper>): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.updateDeadlineRecord(record)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun removeDeadlineRecord(recordId: Long): Completable =
deadlinesCacheDataSource.removeDeadlineRecord(recordId) then
deadlinesRemoteDataSource.removeDeadlineRecord(recordId)
override fun removeDeadlineRecordByCourseId(courseId: Long): Completable =
deadlinesRemoteDataSource
.getDeadlineRecordByCourseId(courseId)
.flatMapCompletable { removeDeadlineRecord(it.id!!) }
override fun removeAllCachedDeadlineRecords(): Completable =
deadlinesCacheDataSource.removeAllDeadlineRecords()
override fun getDeadlineRecordByCourseId(courseId: Long): Maybe<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.getDeadlineRecordByCourseId(courseId)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun getDeadlineRecords(): Single<PagedList<StorageRecord<DeadlinesWrapper>>> =
deadlinesRemoteDataSource
.getDeadlinesRecords()
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecords)
} | apache-2.0 | f4c0f6e2102f39ba44ea66fedbeee21d | 46.886792 | 121 | 0.798187 | 5.913753 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/rhmodding/bread/model/brcad/Sprite.kt | 2 | 1139 | package rhmodding.bread.model.brcad
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import rhmodding.bread.model.ISprite
import rhmodding.bread.util.Unknown
import kotlin.math.sign
class Sprite : ISprite {
@Unknown
var unknown: Short = 0
override val parts: MutableList<SpritePart> = mutableListOf()
override fun copy(): Sprite {
return Sprite().also {
it.unknown = unknown
parts.mapTo(it.parts) { it.copy() }
}
}
override fun toString(): String {
return "Sprite=[numParts=${parts.size}, unknown=0x${unknown.toString(16)}, parts=[${parts.joinToString(separator = "\n")}]]"
}
fun render(batch: SpriteBatch, sheet: Texture, offsetX: Float, offsetY: Float) {
parts.forEach { part ->
val prevColour = batch.packedColor
batch.packedColor = Color.WHITE_FLOAT_BITS
part.render(batch, sheet, offsetX + (part.posX.toInt() - 512), offsetY + (1024 - part.posY.toInt() - 512))
batch.packedColor = prevColour
}
}
} | gpl-3.0 | bf01cf1742bf7bfb574ae67dad76c0ef | 29 | 132 | 0.649693 | 4.010563 | false | false | false | false |
allotria/intellij-community | java/java-features-trainer/src/com/intellij/java/ift/JavaLearningCourse.kt | 2 | 5614 | // 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.java.ift
import com.intellij.java.ift.lesson.assistance.JavaEditorCodingAssistanceLesson
import com.intellij.java.ift.lesson.basic.JavaContextActionsLesson
import com.intellij.java.ift.lesson.basic.JavaSelectLesson
import com.intellij.java.ift.lesson.basic.JavaSurroundAndUnwrapLesson
import com.intellij.java.ift.lesson.completion.*
import com.intellij.java.ift.lesson.navigation.*
import com.intellij.java.ift.lesson.refactorings.JavaExtractMethodCocktailSortLesson
import com.intellij.java.ift.lesson.refactorings.JavaRefactoringMenuLesson
import com.intellij.java.ift.lesson.refactorings.JavaRenameLesson
import com.intellij.java.ift.lesson.run.JavaDebugLesson
import com.intellij.java.ift.lesson.run.JavaRunConfigurationLesson
import com.intellij.lang.java.JavaLanguage
import training.dsl.LessonUtil
import training.learn.LessonsBundle
import training.learn.course.LearningCourseBase
import training.learn.course.LearningModule
import training.learn.course.LessonType
import training.learn.lesson.general.*
import training.learn.lesson.general.assistance.CodeFormatLesson
import training.learn.lesson.general.assistance.ParameterInfoLesson
import training.learn.lesson.general.assistance.QuickPopupsLesson
import training.learn.lesson.general.navigation.FindInFilesLesson
import training.learn.lesson.general.refactorings.ExtractVariableFromBubbleLesson
class JavaLearningCourse : LearningCourseBase(JavaLanguage.INSTANCE.id) {
override fun modules() = listOf(
LearningModule(name = LessonsBundle.message("essential.module.name"),
description = LessonsBundle.message("essential.module.description", LessonUtil.productName),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
JavaContextActionsLesson(),
GotoActionLesson(ls("00.Actions.java.sample"), firstLesson = false),
JavaSearchEverywhereLesson(),
JavaBasicCompletionLesson(),
)
},
LearningModule(name = LessonsBundle.message("editor.basics.module.name"),
description = LessonsBundle.message("editor.basics.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
JavaSelectLesson(),
SingleLineCommentLesson(ls("02.Comment.java.sample")),
DuplicateLesson(ls("04.Duplicate.java.sample")),
MoveLesson("run()", ls("05.Move.java.sample")),
CollapseLesson(ls("06.Collapse.java.sample")),
JavaSurroundAndUnwrapLesson(),
MultipleSelectionHtmlLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.completion.module.name"),
description = LessonsBundle.message("code.completion.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
listOf(
JavaBasicCompletionLesson(),
JavaSmartTypeCompletionLesson(),
JavaPostfixCompletionLesson(),
JavaStatementCompletionLesson(),
JavaCompletionWithTabLesson(),
)
},
LearningModule(name = LessonsBundle.message("refactorings.module.name"),
description = LessonsBundle.message("refactorings.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
fun ls(sampleName: String) = loadSample("Refactorings/$sampleName")
listOf(
JavaRenameLesson(),
ExtractVariableFromBubbleLesson(ls("ExtractVariable.java.sample")),
JavaExtractMethodCocktailSortLesson(),
JavaRefactoringMenuLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.assistance.module.name"),
description = LessonsBundle.message("code.assistance.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
fun ls(sampleName: String) = loadSample("CodeAssistance/$sampleName")
listOf(
CodeFormatLesson(ls("CodeFormat.java.sample"), true),
ParameterInfoLesson(ls("ParameterInfo.java.sample")),
QuickPopupsLesson(ls("QuickPopups.java.sample")),
JavaEditorCodingAssistanceLesson(ls("EditorCodingAssistance.java.sample")),
)
},
LearningModule(name = LessonsBundle.message("navigation.module.name"),
description = LessonsBundle.message("navigation.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.PROJECT) {
listOf(
JavaSearchEverywhereLesson(),
FindInFilesLesson("src/warehouse/FindInFilesSample.java"),
JavaFileStructureLesson(),
JavaDeclarationAndUsagesLesson(),
JavaInheritanceHierarchyLesson(),
JavaRecentFilesLesson(),
JavaOccurrencesLesson(),
)
},
LearningModule(name = LessonsBundle.message("run.debug.module.name"),
description = LessonsBundle.message("run.debug.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
listOf(
JavaRunConfigurationLesson(),
JavaDebugLesson(),
)
},
)
} | apache-2.0 | ca88a1edc76389a36b1cf024ffd413e8 | 46.991453 | 140 | 0.704489 | 5.150459 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/application/options/editor/EditorCloseButtonPosition.kt | 3 | 2110 | // 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.application.options.editor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.search.BooleanOptionDescription
import com.intellij.openapi.application.ApplicationBundle.message
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.layout.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
private const val LEFT = "Left"
private const val RIGHT = "Right"
private const val NONE = "None"
private val items = listOf(LEFT, RIGHT, NONE)
@Nls
private fun optionName(@NonNls option: String): String = when (option) {
LEFT -> message("combobox.tab.placement.left")
RIGHT -> message("combobox.tab.placement.right")
else -> message("combobox.tab.placement.none")
}
internal val CLOSE_BUTTON_POSITION = message("tabs.close.button.placement")
internal fun Cell.closeButtonPositionComboBox() {
comboBox(CollectionComboBoxModel<String>(items),
{ getCloseButtonPlacement() },
{ set(it) },
listCellRenderer { value, _, _ -> text = optionName(value) }
)
}
internal fun closeButtonPlacementOptionDescription(): Collection<BooleanOptionDescription> = items.map { asOptionDescriptor(it) }
private fun set(s: String?) {
ui.showCloseButton = s != NONE
if (s != NONE) {
ui.closeTabButtonOnTheRight = s == RIGHT
}
}
private fun asOptionDescriptor(s: String) = object : BooleanOptionDescription(CLOSE_BUTTON_POSITION + " | " + optionName(s), ID) {
override fun isOptionEnabled() = getCloseButtonPlacement() === s
override fun setOptionState(enabled: Boolean) {
when {
enabled -> set(s)
else -> set(
when {
s === RIGHT -> LEFT
else -> RIGHT
})
}
UISettings.instance.fireUISettingsChanged()
}
}
private fun getCloseButtonPlacement() = when {
!ui.showCloseButton -> NONE
java.lang.Boolean.getBoolean("closeTabButtonOnTheLeft") || !ui.closeTabButtonOnTheRight -> LEFT
else -> RIGHT
} | apache-2.0 | 781f5873e400cf9739f386372413a38b | 31.984375 | 140 | 0.718009 | 4.145383 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/sources-jvm/utility/MTypeReference.kt | 1 | 2155 | package io.fluidsonic.json.annotationprocessor
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import io.fluidsonic.meta.*
internal fun MTypeReference.Class.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName {
val typeNames = name.withoutPackage().kotlin.split('.')
return ClassName(
packageName = name.packageName.kotlin,
simpleNames = typeNames
)
.let { className ->
if (this.arguments.isNotEmpty()) {
className.parameterizedBy(*arguments.map { it.forKotlinPoet(typeParameters = typeParameters) }.toTypedArray())
}
else
className
}
.copy(nullable = isNullable)
}
internal fun MTypeReference.TypeParameter.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
typeParameters.first { it.id == id }.let { typeParameter ->
TypeVariableName(
name = typeParameter.name.kotlin,
bounds = typeParameter.upperBounds
.map { it.forKotlinPoet(typeParameters = typeParameters) }
.ifEmpty { listOf(KotlinpoetTypeNames.nullableAny) }
.toTypedArray(),
variance = typeParameter.variance.kModifier
).copy(nullable = isNullable || typeParameter.upperBounds.all { it.isNullable })
}
internal fun MTypeReference.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
when (this) {
is MTypeReference.Class -> forKotlinPoet(typeParameters = typeParameters)
is MTypeReference.TypeParameter -> forKotlinPoet(typeParameters = typeParameters)
else -> error("not supported")
}
internal fun MTypeArgument.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
when (this) {
is MTypeArgument.StarProjection -> STAR
is MTypeArgument.Type -> {
when (variance) {
MVariance.IN -> WildcardTypeName.consumerOf(forKotlinPoet(typeParameters = typeParameters))
MVariance.OUT -> WildcardTypeName.producerOf(forKotlinPoet(typeParameters = typeParameters))
MVariance.INVARIANT -> type.forKotlinPoet(typeParameters = typeParameters)
}
}
}
private val MVariance.kModifier
get() = when (this) {
MVariance.INVARIANT -> null
MVariance.IN -> KModifier.IN
MVariance.OUT -> KModifier.OUT
}
| apache-2.0 | 5983d1f5e4cc8dc887b705a60fac4339 | 32.153846 | 114 | 0.759629 | 4.292829 | false | false | false | false |
allotria/intellij-community | platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt | 3 | 8814 | // 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.ide.browsers
import com.intellij.CommonBundle
import com.intellij.Patches
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.BrowserUtil
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.PathUtil
import com.intellij.util.io.URLUtil
import java.awt.Desktop
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.Path
private val LOG = logger<BrowserLauncherAppless>()
open class BrowserLauncherAppless : BrowserLauncher() {
companion object {
@JvmStatic
fun canUseSystemDefaultBrowserPolicy(): Boolean =
isDesktopActionSupported(Desktop.Action.BROWSE) || SystemInfo.isMac || SystemInfo.isWindows || SystemInfo.isUnix && SystemInfo.hasXdgOpen()
fun isOpenCommandUsed(command: GeneralCommandLine): Boolean = SystemInfo.isMac && ExecUtil.openCommandPath == command.exePath
}
override fun open(url: String): Unit = openOrBrowse(url, false)
override fun browse(file: File) {
var path = file.absolutePath
if (SystemInfo.isWindows && path[0] != '/') {
path = "/$path"
}
openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true)
}
override fun browse(file: Path) {
var path = file.toAbsolutePath().toString()
if (SystemInfo.isWindows && path[0] != '/') {
path = "/$path"
}
openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true)
}
protected open fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) {
browseUsingPath(url, browserPath, project = project)
}
protected open fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) {
val url = signUrl(_url.trim { it <= ' ' })
LOG.debug { "opening [$url]" }
if (url.startsWith("mailto:") && isDesktopActionSupported(Desktop.Action.MAIL)) {
try {
LOG.debug("Trying Desktop#mail")
Desktop.getDesktop().mail(URI(url))
}
catch (e: Exception) {
LOG.warn("[$url]", e)
}
return
}
if (!BrowserUtil.isAbsoluteURL(url)) {
val file = File(url)
if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) {
if (!file.exists()) {
showError(IdeBundle.message("error.file.does.not.exist", file.path), project = project)
return
}
try {
LOG.debug("Trying Desktop#open")
Desktop.getDesktop().open(file)
return
}
catch (e: IOException) {
LOG.warn("[$url]", e)
}
}
browse(file)
return
}
val settings = generalSettings
if (settings.isUseDefaultBrowser) {
openWithDefaultBrowser(url, project)
}
else {
openWithExplicitBrowser(url, settings.browserPath, project = project)
}
}
private fun openWithDefaultBrowser(url: String, project: Project?) {
if (isDesktopActionSupported(Desktop.Action.BROWSE)) {
val uri = VfsUtil.toUri(url)
if (uri == null) {
showError(IdeBundle.message("error.malformed.url", url), project = project)
return
}
try {
LOG.debug("Trying Desktop#browse")
Desktop.getDesktop().browse(uri)
return
}
catch (e: Exception) {
LOG.warn("[$url]", e)
if (SystemInfo.isMac && e.message!!.contains("Error code: -10814")) {
return // if "No application knows how to open" the URL, there is no sense in retrying with 'open' command
}
}
}
val command = defaultBrowserCommand
if (command == null) {
showError(IdeBundle.message("browser.default.not.supported"), project = project)
return
}
if (url.startsWith("jar:")) return
doLaunch(GeneralCommandLine(command).withParameters(url), project)
}
protected open fun signUrl(url: String): String = url
override fun browse(url: String, browser: WebBrowser?, project: Project?) {
val effectiveBrowser = getEffectiveBrowser(browser)
// if browser is not passed, UrlOpener should be not used for non-http(s) urls
if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) {
openOrBrowse(url, true, project)
}
else {
UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) }
}
}
override fun browseUsingPath(url: String?,
browserPath: String?,
browser: WebBrowser?,
project: Project?,
openInNewWindow: Boolean,
additionalParameters: Array<String>): Boolean {
if (url != null && url.startsWith("jar:")) return false
val byName = browserPath == null && browser != null
val effectivePath = if (byName) PathUtil.toSystemDependentName(browser!!.path) else browserPath
val fix: (() -> Unit)? = if (byName) { -> browseUsingPath(url, null, browser!!, project, openInNewWindow, additionalParameters) } else null
if (effectivePath.isNullOrBlank()) {
val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath())
showError(message, browser, project, IdeBundle.message("title.browser.not.found"), fix)
return false
}
val commandWithUrl = BrowserUtil.getOpenBrowserCommand(effectivePath, openInNewWindow).toMutableList()
if (url != null) {
if (browser != null) browser.addOpenUrlParameter(commandWithUrl, url)
else commandWithUrl += url
}
val commandLine = GeneralCommandLine(commandWithUrl)
val browserSpecificSettings = browser?.specificSettings
if (browserSpecificSettings != null) {
commandLine.environment.putAll(browserSpecificSettings.environmentVariables)
}
val specific = browserSpecificSettings?.additionalParameters ?: emptyList()
if (specific.size + additionalParameters.size > 0) {
if (isOpenCommandUsed(commandLine)) {
commandLine.addParameter("--args")
}
commandLine.addParameters(specific)
commandLine.addParameters(*additionalParameters)
}
doLaunch(commandLine, project, browser, fix)
return true
}
private fun doLaunch(command: GeneralCommandLine, project: Project?, browser: WebBrowser? = null, fix: (() -> Unit)? = null) {
LOG.debug { command.commandLineString }
ProcessIOExecutorService.INSTANCE.execute {
try {
val output = CapturingProcessHandler.Silent(command).runProcess(10000, false)
if (!output.checkSuccess(LOG) && output.exitCode == 1) {
@NlsSafe
val error = output.stderrLines.firstOrNull()
showError(error, browser, project, null, fix)
}
}
catch (e: ExecutionException) {
showError(e.message, browser, project, null, fix)
}
}
}
protected open fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser? = null, project: Project? = null, @NlsContexts.DialogTitle title: String? = null, fix: (() -> Unit)? = null) {
// Not started yet. Not able to show message up. (Could happen in License panel under Linux).
LOG.warn(error)
}
protected open fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser
}
private fun isDesktopActionSupported(action: Desktop.Action): Boolean =
!Patches.SUN_BUG_ID_6486393 && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action)
private val generalSettings: GeneralSettings
get() = (if (ApplicationManager.getApplication() != null) GeneralSettings.getInstance() else null) ?: GeneralSettings()
private val defaultBrowserCommand: List<String>?
get() = when {
SystemInfo.isWindows -> listOf(ExecUtil.windowsShellName, "/c", "start", GeneralCommandLine.inescapableQuote(""))
SystemInfo.isMac -> listOf(ExecUtil.openCommandPath)
SystemInfo.isUnix && SystemInfo.hasXdgOpen() -> listOf("xdg-open")
else -> null
} | apache-2.0 | bccfe8a2935677720ad9d6407603ab38 | 36.351695 | 205 | 0.683685 | 4.53862 | false | false | false | false |
ursjoss/sipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/paper/PaperRecordMapperTest.kt | 2 | 7913 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.persistence.paper
import ch.difty.scipamato.core.db.tables.records.PaperRecord
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.persistence.RecordMapperTest
import io.mockk.every
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.RecordMapper
class PaperRecordMapperTest : RecordMapperTest<PaperRecord, Paper>() {
override val mapper: RecordMapper<PaperRecord, Paper> = PaperRecordMapper()
override fun makeRecord(): PaperRecord {
val record = PaperRecord()
record.id = ID
record.number = NUMBER
record.pmId = PM_ID
record.doi = DOI
record.authors = AUTHORS
record.firstAuthor = FIRST_AUTHOR
record.firstAuthorOverridden = FIRST_AUTHOR_OVERRIDDEN
record.title = TITLE
record.location = LOCATION
record.publicationYear = PUBLICATION_YEAR
record.goals = GOALS
record.population = POPULATION
record.methods = METHODS
record.populationPlace = POPULATION_PLACE
record.populationParticipants = POPULATION_PARTICIPANTS
record.populationDuration = POPULATION_DURATION
record.exposurePollutant = EXPOSURE_POLLUTANT
record.exposureAssessment = EXPOSURE_ASSESSMENT
record.methodStudyDesign = METHOD_STUDY_DESIGN
record.methodOutcome = METHOD_OUTCOME
record.methodStatistics = METHOD_STATISTICS
record.methodConfounders = METHOD_CONFOUNDERS
record.result = RESULT
record.comment = COMMENT
record.intern = INTERN
record.resultExposureRange = RESULT_EXPOSURE_RANGE
record.resultEffectEstimate = RESULT_EFFECT_ESTIMATE
record.resultMeasuredOutcome = RESULT_MEASURED_OUTCOME
record.conclusion = CONCLUSION
record.originalAbstract = ORIGINAL_ABSTRACT
record.mainCodeOfCodeclass1 = MAIN_CODE_OF_CODECLASS1
return record
}
override fun setAuditFieldsIn(record: PaperRecord) {
record.created = CREATED
record.createdBy = CREATED_BY
record.lastModified = LAST_MOD
record.lastModifiedBy = LAST_MOD_BY
record.version = VERSION
}
override fun assertEntity(entity: Paper) {
entity.id shouldBeEqualTo ID
entity.number shouldBeEqualTo NUMBER
entity.pmId shouldBeEqualTo PM_ID
entity.doi shouldBeEqualTo DOI
entity.authors shouldBeEqualTo AUTHORS
entity.firstAuthor shouldBeEqualTo FIRST_AUTHOR
entity.isFirstAuthorOverridden shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN
entity.title shouldBeEqualTo TITLE
entity.location shouldBeEqualTo LOCATION
entity.publicationYear shouldBeEqualTo PUBLICATION_YEAR
entity.goals shouldBeEqualTo GOALS
entity.population shouldBeEqualTo POPULATION
entity.methods shouldBeEqualTo METHODS
entity.populationPlace shouldBeEqualTo POPULATION_PLACE
entity.populationParticipants shouldBeEqualTo POPULATION_PARTICIPANTS
entity.populationDuration shouldBeEqualTo POPULATION_DURATION
entity.exposurePollutant shouldBeEqualTo EXPOSURE_POLLUTANT
entity.exposureAssessment shouldBeEqualTo EXPOSURE_ASSESSMENT
entity.methodStudyDesign shouldBeEqualTo METHOD_STUDY_DESIGN
entity.methodOutcome shouldBeEqualTo METHOD_OUTCOME
entity.methodStatistics shouldBeEqualTo METHOD_STATISTICS
entity.methodConfounders shouldBeEqualTo METHOD_CONFOUNDERS
entity.result shouldBeEqualTo RESULT
entity.comment shouldBeEqualTo COMMENT
entity.intern shouldBeEqualTo INTERN
entity.resultExposureRange shouldBeEqualTo RESULT_EXPOSURE_RANGE
entity.resultEffectEstimate shouldBeEqualTo RESULT_EFFECT_ESTIMATE
entity.resultMeasuredOutcome shouldBeEqualTo RESULT_MEASURED_OUTCOME
entity.conclusion shouldBeEqualTo CONCLUSION
entity.originalAbstract shouldBeEqualTo ORIGINAL_ABSTRACT
entity.mainCodeOfCodeclass1 shouldBeEqualTo MAIN_CODE_OF_CODECLASS1
entity.codes.shouldBeEmpty()
}
companion object {
const val ID = 1L
const val NUMBER = 10L
const val PM_ID = 2
const val DOI = "101000/1234"
const val AUTHORS = "authors"
const val FIRST_AUTHOR = "first author"
const val FIRST_AUTHOR_OVERRIDDEN = false
const val TITLE = "title"
const val LOCATION = "location"
const val PUBLICATION_YEAR = 3
const val GOALS = "goals"
const val POPULATION = "population"
const val METHODS = "methods"
const val POPULATION_PLACE = "population place"
const val POPULATION_PARTICIPANTS = "population participants"
const val POPULATION_DURATION = "population duration"
const val EXPOSURE_POLLUTANT = "exposure pollutant"
const val EXPOSURE_ASSESSMENT = "exposure assessment"
const val METHOD_STUDY_DESIGN = "method study design"
const val METHOD_OUTCOME = "method outcome"
const val METHOD_STATISTICS = "method statistics"
const val METHOD_CONFOUNDERS = "method confounders"
const val RESULT = "result"
const val COMMENT = "comment"
const val INTERN = "intern"
const val RESULT_EXPOSURE_RANGE = "result exposure range"
const val RESULT_EFFECT_ESTIMATE = "result effect estimate"
const val RESULT_MEASURED_OUTCOME = "result measured outcome"
const val CONCLUSION = "conclusion"
const val ORIGINAL_ABSTRACT = "oa"
const val MAIN_CODE_OF_CODECLASS1 = "1F"
fun entityFixtureWithoutIdFields(entityMock: Paper) {
every { entityMock.number } returns NUMBER
every { entityMock.pmId } returns PM_ID
every { entityMock.doi } returns DOI
every { entityMock.authors } returns AUTHORS
every { entityMock.firstAuthor } returns FIRST_AUTHOR
every { entityMock.isFirstAuthorOverridden } returns FIRST_AUTHOR_OVERRIDDEN
every { entityMock.title } returns TITLE
every { entityMock.location } returns LOCATION
every { entityMock.publicationYear } returns PUBLICATION_YEAR
every { entityMock.goals } returns GOALS
every { entityMock.population } returns POPULATION
every { entityMock.methods } returns METHODS
every { entityMock.populationPlace } returns POPULATION_PLACE
every { entityMock.populationParticipants } returns POPULATION_PARTICIPANTS
every { entityMock.populationDuration } returns POPULATION_DURATION
every { entityMock.exposurePollutant } returns EXPOSURE_POLLUTANT
every { entityMock.exposureAssessment } returns EXPOSURE_ASSESSMENT
every { entityMock.methodStudyDesign } returns METHOD_STUDY_DESIGN
every { entityMock.methodOutcome } returns METHOD_OUTCOME
every { entityMock.methodStatistics } returns METHOD_STATISTICS
every { entityMock.methodConfounders } returns METHOD_CONFOUNDERS
every { entityMock.result } returns RESULT
every { entityMock.comment } returns COMMENT
every { entityMock.intern } returns INTERN
every { entityMock.resultExposureRange } returns RESULT_EXPOSURE_RANGE
every { entityMock.resultEffectEstimate } returns RESULT_EFFECT_ESTIMATE
every { entityMock.resultMeasuredOutcome } returns RESULT_MEASURED_OUTCOME
every { entityMock.conclusion } returns CONCLUSION
every { entityMock.originalAbstract } returns ORIGINAL_ABSTRACT
every { entityMock.mainCodeOfCodeclass1 } returns MAIN_CODE_OF_CODECLASS1
auditFixtureFor(entityMock)
}
}
}
| gpl-3.0 | eb149c56c7861e2a758c33fed5b67919 | 41.772973 | 88 | 0.703273 | 5.560787 | false | false | false | false |
allotria/intellij-community | java/java-features-trainer/src/com/intellij/java/ift/lesson/run/JavaRunLessonsUtils.kt | 3 | 1689 | // 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.java.ift.lesson.run
import training.dsl.parseLessonSample
object JavaRunLessonsUtils {
const val demoClassName = "Sample"
val demoSample = parseLessonSample("""
public class $demoClassName {
public static void main(String[] args) {
double average = findAverage(prepareValues());
System.out.println("The average is " + average);
}
private static double findAverage(String[] input) {
checkInput(input);
double result = 0;
for (String s : input) {
<caret>result += <select id=1>validateNumber(extractNumber(removeQuotes(s)))</select>;
}
<caret id=3/>return result;
}
private static String[] prepareValues() {
return new String[] {"'apple 1'", "orange 2", "'tomato 3'"};
}
private static int extractNumber(String s) {
return Integer.parseInt(<select id=2>s.split(" ")[0]</select>);
}
private static void checkInput(String[] input) {
if (input == null || input.length == 0) {
throw new IllegalArgumentException("Invalid input");
}
}
private static String removeQuotes(String s) {
if (s.startsWith("'") && s.endsWith("'") && s.length() > 1) {
return s.substring(1, s.length() - 1);
}
return s;
}
private static int validateNumber(int number) {
if (number < 0) throw new IllegalArgumentException("Invalid number: " + number);
return number;
}
}
""".trimIndent())
} | apache-2.0 | ce8dd6feb7af636ed84c7d9d338f0ebf | 30.886792 | 140 | 0.60746 | 4.275949 | false | false | false | false |
android/wear-os-samples | WearTilesKotlin/app/src/main/java/com/example/wear/tiles/messaging/MessagingTileLayout.kt | 1 | 6093 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.wear.tiles.messaging
import android.content.Context
import android.graphics.BitmapFactory
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.wear.tiles.DeviceParametersBuilders
import androidx.wear.tiles.ModifiersBuilders
import androidx.wear.tiles.material.Button
import androidx.wear.tiles.material.ButtonColors
import androidx.wear.tiles.material.ChipColors
import androidx.wear.tiles.material.CompactChip
import androidx.wear.tiles.material.layouts.MultiButtonLayout
import androidx.wear.tiles.material.layouts.PrimaryLayout
import com.example.wear.tiles.R
import com.example.wear.tiles.tools.IconSizePreview
import com.example.wear.tiles.tools.WearSmallRoundDevicePreview
import com.example.wear.tiles.tools.emptyClickable
import com.google.android.horologist.compose.tools.LayoutElementPreview
import com.google.android.horologist.compose.tools.LayoutRootPreview
import com.google.android.horologist.compose.tools.buildDeviceParameters
import com.google.android.horologist.tiles.images.drawableResToImageResource
/**
* Layout definition for the Messaging Tile.
*
* By separating the layout completely, we can pass fake data for the [MessageTilePreview] so it can
* be rendered in Android Studio (use the "Split" or "Design" editor modes).
*/
internal fun messagingTileLayout(
state: MessagingTileState,
context: Context,
deviceParameters: DeviceParametersBuilders.DeviceParameters
) = PrimaryLayout.Builder(deviceParameters)
.setContent(
MultiButtonLayout.Builder()
.apply {
// In a PrimaryLayout with a compact chip at the bottom, we can fit 5 buttons.
// We're only taking the first 4 contacts so that we can fit a Search button too.
state.contacts.take(4).forEach { contact ->
addButtonContent(contactLayout(context, contact, emptyClickable))
}
}
.addButtonContent(searchLayout(context, emptyClickable))
.build()
).setPrimaryChipContent(
CompactChip.Builder(
context,
context.getString(R.string.tile_messaging_create_new),
emptyClickable,
deviceParameters
)
.setChipColors(ChipColors.primaryChipColors(MessagingTileTheme.colors))
.build()
)
.build()
private fun contactLayout(
context: Context,
contact: Contact,
clickable: ModifiersBuilders.Clickable
) = Button.Builder(context, clickable)
.setContentDescription(contact.name)
.apply {
if (contact.avatarUrl != null) {
setImageContent(contact.imageResourceId())
} else {
setTextContent(contact.initials)
setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
}
}
.build()
private fun Contact.imageResourceId() = "${MessagingTileRenderer.ID_CONTACT_PREFIX}$id"
private fun searchLayout(
context: Context,
clickable: ModifiersBuilders.Clickable
) = Button.Builder(context, clickable)
.setContentDescription(context.getString(R.string.tile_messaging_search))
.setIconContent(MessagingTileRenderer.ID_IC_SEARCH)
.setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
.build()
@WearSmallRoundDevicePreview
@Composable
private fun MessageTilePreview() {
val context = LocalContext.current
val state = MessagingTileState(MessagingRepo.knownContacts)
LayoutRootPreview(
messagingTileLayout(
state,
context,
buildDeviceParameters(context.resources)
)
) {
addIdToImageMapping(
state.contacts[1].imageResourceId(),
bitmapToImageResource(
BitmapFactory.decodeResource(context.resources, R.drawable.ali)
)
)
addIdToImageMapping(
state.contacts[2].imageResourceId(),
bitmapToImageResource(
BitmapFactory.decodeResource(context.resources, R.drawable.taylor)
)
)
addIdToImageMapping(
MessagingTileRenderer.ID_IC_SEARCH,
drawableResToImageResource(R.drawable.ic_search_24)
)
}
}
@IconSizePreview
@Composable
private fun ContactPreview() {
LayoutElementPreview(
contactLayout(
context = LocalContext.current,
contact = MessagingRepo.knownContacts[0],
clickable = emptyClickable
)
)
}
@IconSizePreview
@Composable
private fun ContactWithImagePreview() {
val context = LocalContext.current
val contact = MessagingRepo.knownContacts[1]
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.ali)
val layout = contactLayout(
context = context,
contact = contact,
clickable = emptyClickable
)
LayoutElementPreview(layout) {
addIdToImageMapping(
"${MessagingTileRenderer.ID_CONTACT_PREFIX}${contact.id}",
bitmapToImageResource(bitmap)
)
}
}
@IconSizePreview
@Composable
private fun SearchButtonPreview() {
LayoutElementPreview(
searchLayout(
context = LocalContext.current,
clickable = emptyClickable
)
) {
addIdToImageMapping(
MessagingTileRenderer.ID_IC_SEARCH,
drawableResToImageResource(R.drawable.ic_search_24)
)
}
}
| apache-2.0 | 6697ce6faf510ed954b87637b0a5df4a | 33.230337 | 100 | 0.701132 | 4.812796 | false | false | false | false |
AMaiyndy/employees | src/main/java/ru/technoserv/services/impl/AuditServiceImplKt.kt | 1 | 1196 | package ru.technoserv.services.impl
import org.springframework.stereotype.Service
import ru.technoserv.dao.AuditDao
import ru.technoserv.domain.AuditInfo
import ru.technoserv.domain.SearchDate
import ru.technoserv.services.AuditService
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.Date
@Service
class AuditServiceImplKt(private val dao :AuditDao) : AuditService {
private var formatter : SimpleDateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm")
override fun createRecord(auditInfo: AuditInfo?) {
dao.createRecord(auditInfo)
}
override fun getRecordsOfPeriodForDepartment(searchDate: SearchDate, depId: Int?): MutableList<AuditInfo> {
var from : Date = formatter.parse(searchDate.from)
var to : Date = formatter.parse(searchDate.to)
return dao.getRecordsOfPeriodForDepartment(from, to, depId);
}
override fun getRecordsOfPeriodForEmployee(searchDate: SearchDate, empId: Int?): MutableList<AuditInfo> {
var from : Date = formatter.parse(searchDate.from)
var to : Date = formatter.parse(searchDate.to)
return dao.getRecordsOfPeriodForEmployee(from, to, empId);
}
} | apache-2.0 | c5755ae82797a8e28f03f48da90277a3 | 36.40625 | 111 | 0.759197 | 4.256228 | false | false | false | false |
allotria/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/version/VersionStabilityInferrer.kt | 1 | 4615 | package com.jetbrains.packagesearch.intellij.plugin.version
// NOTE: This file was copied from com.jetbrains.kpm.maven.wanderer.maven.index.version
import com.jetbrains.packagesearch.intellij.plugin.version.VersionTokenMatcher.Companion.regex
import com.jetbrains.packagesearch.intellij.plugin.version.VersionTokenMatcher.Companion.substring
private val singleLetterUnstableMarkerRegex = "\\b[abmt][.\\-]?\\d{1,3}\\w?\\b".toRegex(RegexOption.IGNORE_CASE) // E.g., a01, b-2, m.3a
internal fun looksLikeStableVersion(versionName: String): Boolean {
if (versionName.isBlank()) return false
if (singleLetterUnstableMarkerRegex.containsMatchIn(versionName)) {
return false
}
val tokens = tokenizeVersionName(versionName)
return tokens.none { token ->
unstableTokens.any { matcher -> matcher.matches(token) }
}
}
private fun tokenizeVersionName(versionName: String): List<String> {
val tokens = mutableListOf<String>()
var previousChar: Char? = null
val tokenBuilder = StringBuilder(versionName.length)
versionName.forEach { char ->
if (previousChar != null && char.isTokenBoundary(previousChar!!)) {
tokens += tokenBuilder.toString()
tokenBuilder.clear()
}
tokenBuilder.append(char)
previousChar = char
}
tokens += tokenBuilder.toString()
return tokens.filter { token -> token.any { it.isLetterOrDigit() } }
}
private fun Char.isTokenBoundary(previousChar: Char): Boolean = when {
!isLetterOrDigit() -> true
isLetter() && !previousChar.isLetter() -> true
isDigit() && !previousChar.isDigit() -> true
else -> false
}
private val unstableTokens = listOf(
substring("alpha"),
substring("beta"),
substring("bate"),
substring("commit"),
substring("unofficial"),
substring("exp"),
substring("experiment"),
substring("experimental"),
substring("milestone"),
substring("deprecated"),
substring("rc"),
substring("rctest"),
substring("cr"),
substring("draft"),
substring("ignored"),
substring("test"),
substring("placeholder"),
substring("incubating"),
substring("nightly"),
substring("weekly"),
regex("\\b(rel(ease)?[.\\-_]?)?candidate\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\br?dev(elop(ment)?)?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\beap?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("pre(view)?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\bsnap(s?shot)?\\b".toRegex(RegexOption.IGNORE_CASE))
)
private sealed class VersionTokenMatcher {
abstract fun matches(value: String): Boolean
class SubstringMatcher(val toMatch: String) : VersionTokenMatcher() {
private val toMatchLength = toMatch.length
override fun matches(value: String): Boolean {
val substringIndex = value.indexOf(toMatch, ignoreCase = true)
if (substringIndex < 0) return false
val afterSubstringIndex = substringIndex + toMatchLength
val valueLength = value.length
// Case 1. The value matches entirely
if (substringIndex == 0 && afterSubstringIndex == valueLength) return true
// Case 2. The match is at the beginning of value
if (substringIndex == 0) {
val nextLetter = value[afterSubstringIndex]
return !nextLetter.isLetter() // Matching whole word
}
// Case 2. The match is at the end of value
if (afterSubstringIndex == valueLength) {
val previousLetter = value[substringIndex - 1]
return !previousLetter.isLetterOrDigit() && previousLetter != '_' // Matching whole word
}
// Case 3. The match is somewhere inside of value
val previousLetter = value[substringIndex - 1]
val startsAtWordBoundary = !previousLetter.isLetterOrDigit() && previousLetter != '_'
val nextLetter = value[afterSubstringIndex]
val endsAtWordBoundary = !nextLetter.isLetter()
return startsAtWordBoundary && endsAtWordBoundary // Needs to be matching a whole word
}
}
class RegexMatcher(val regex: Regex) : VersionTokenMatcher() {
override fun matches(value: String): Boolean = regex.containsMatchIn(value)
}
companion object {
fun substring(toMatch: String) = SubstringMatcher(toMatch)
fun regex(regex: Regex) = RegexMatcher(regex)
}
}
| apache-2.0 | c446363da6c1571d81ff58cfd1960939 | 34.5 | 136 | 0.642254 | 4.762642 | false | false | false | false |
Adeynack/kotti | kotti-swing/src/main/kotlin/com/github/adeynack/kotti/swing/FlowPanel.kt | 1 | 2437 | package com.github.adeynack.kotti.swing
import java.awt.Component
import java.awt.FlowLayout
import javax.swing.Action
import javax.swing.JButton
import javax.swing.JPanel
/**
* [JPanel] with an automatic layout of type [FlowLayout].
*
* Allows less verbose creation of such a panel.
*
* val loginPanel = FlowPanel.left(txtUserName, txtPassword, btnLogin, vgap = 16)
*
* It also allows creation of button bars ([JButton]) from a list of [Action].
*
* val buttonBar = FlowPanel.right(actionOK, actionCancel, actionHelp)
*
*/
class FlowPanel(
align: Int = defaultAlign,
hgap: Int = defaultHGap,
vgap: Int = defaultVGap,
content: Iterable<Component> = emptyList()
) : JPanel(FlowLayout(align, hgap, vgap)) {
companion object {
// Default values taken from java.awt.FlowLayout.FlowLayout() (default constructor)
private val defaultAlign = FlowLayout.CENTER
private val defaultHGap = 5
private val defaultVGap = 5
fun left(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, content)
fun center(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, content)
fun right(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, content)
fun left(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, content.asIterable())
fun center(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, content.asIterable())
fun right(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, content.asIterable())
fun left(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, actions.map(::JButton))
fun center(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, actions.map(::JButton))
fun right(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, actions.map(::JButton))
}
init {
content.forEach { add(it) }
}
}
| mit | 47b2ac659c9520b3f8cf409c14a20ab0 | 44.981132 | 160 | 0.701272 | 4.144558 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/flow/Migration.kt | 1 | 17494 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
@file:Suppress("unused", "DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER", "NO_EXPLICIT_RETURN_TYPE_IN_API_MODE")
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.jvm.*
/**
* **GENERAL NOTE**
*
* These deprecations are added to improve user experience when they will start to
* search for their favourite operators and/or patterns that are missing or renamed in Flow.
* Deprecated functions also are moved here when they renamed. The difference is that they have
* a body with their implementation while pure stubs have [noImpl].
*/
internal fun noImpl(): Nothing =
throw UnsupportedOperationException("Not implemented, should not be called")
/**
* `observeOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flowable
* .observeOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.observeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `publishOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flux
* .publishOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.publishOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `subscribeOn` has no direct match in [Flow] API because [Flow] preserves its context and does not leak it.
*
* For example, the following code:
* ```
* flowable
* .map { value -> println("Doing map in IO"); value }
* .subscribeOn(Schedulers.io())
* .observeOn(Schedulers.computation())
* .doOnEach { value -> println("Processing $value in computation")
* .subscribe()
* ```
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.Default) {
* flow
* .map { value -> println("Doing map in IO"); value }
* .flowOn(Dispatchers.IO) // Works upstream, doesn't change downstream
* .collect { value ->
* println("Processing $value in computation")
* }
* }
* ```
* Opposed to subscribeOn, it it **possible** to use multiple `flowOn` operators in the one flow
* @suppress
*/
@Deprecated(message = "Use 'flowOn' instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.subscribeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResume(fallback: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResumeNext(fallback: Flow<T>): Flow<T> = noImpl()
/**
* `subscribe` is Rx-specific API that has no direct match in flows.
* One can use [launchIn] instead, for example the following:
* ```
* flowable
* .observeOn(Schedulers.io())
* .subscribe({ println("Received $it") }, { println("Exception $it happened") }, { println("Flowable is completed successfully") }
* ```
*
* has the following Flow equivalent:
* ```
* flow
* .onEach { value -> println("Received $value") }
* .onCompletion { cause -> if (cause == null) println("Flow is completed successfully") }
* .catch { cause -> println("Exception $cause happened") }
* .flowOn(Dispatchers.IO)
* .launchIn(myScope)
* ```
*
* Note that resulting value of [launchIn] is not used because the provided scope takes care of cancellation.
*
* Or terminal operators like [single] can be used from suspend functions.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)
public fun <T> Flow<T>.subscribe(): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit, onError: suspend (Throwable) -> Unit): Unit = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flatMapMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue is 'flatMapConcat'",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.flatMap(mapper: suspend (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `concatMap` is [flatMapConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatMap' is 'flatMapConcat'",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.concatMap(mapper: (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flattenMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'merge' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.merge(): Flow<T> = noImpl()
/**
* Flow analogue of `flatten` is [flattenConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'flatten' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.flatten(): Flow<T> = noImpl()
/**
* Kotlin has a built-in generic mechanism for making chained calls.
* If you wish to write something like
* ```
* myFlow.compose(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* you can replace it with
*
* ```
* myFlow.let(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'compose' is 'let'",
replaceWith = ReplaceWith("let(transformer)")
)
public fun <T, R> Flow<T>.compose(transformer: Flow<T>.() -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `skip` is [drop].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'skip' is 'drop'",
replaceWith = ReplaceWith("drop(count)")
)
public fun <T> Flow<T>.skip(count: Int): Flow<T> = noImpl()
/**
* Flow extension to iterate over elements is [collect].
* Foreach wasn't introduced deliberately to avoid confusion.
* Flow is not a collection, iteration over it may be not idempotent
* and can *launch* computations with side-effects.
* This behaviour is not reflected in [forEach] name.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'forEach' is 'collect'",
replaceWith = ReplaceWith("collect(action)")
)
public fun <T> Flow<T>.forEach(action: suspend (value: T) -> Unit): Unit = noImpl()
/**
* Flow has less verbose [scan] shortcut.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow has less verbose 'scan' shortcut",
replaceWith = ReplaceWith("scan(initial, operation)")
)
public fun <T, R> Flow<T>.scanFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> =
noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emit(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emit(fallback) }'",
replaceWith = ReplaceWith("catch { emit(fallback) }")
)
// Note: this version without predicate gives better "replaceWith" action
public fun <T> Flow<T>.onErrorReturn(fallback: T): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { e -> if (predicate(e)) emit(fallback) else throw e }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { e -> if (predicate(e)) emit(fallback) else throw e }'",
replaceWith = ReplaceWith("catch { e -> if (predicate(e)) emit(fallback) else throw e }")
)
public fun <T> Flow<T>.onErrorReturn(fallback: T, predicate: (Throwable) -> Boolean = { true }): Flow<T> =
catch { e ->
// Note: default value is for binary compatibility with preview version, that is why it has body
if (!predicate(e)) throw e
emit(fallback)
}
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emit(value) }'",
replaceWith = ReplaceWith("onStart { emit(value) }")
)
public fun <T> Flow<T>.startWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emitAll(other) }'",
replaceWith = ReplaceWith("onStart { emitAll(other) }")
)
public fun <T> Flow<T>.startWith(other: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { emit(value) }'",
replaceWith = ReplaceWith("onCompletion { emit(value) }")
)
public fun <T> Flow<T>.concatWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { if (it == null) emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { if (it == null) emitAll(other) }'",
replaceWith = ReplaceWith("onCompletion { if (it == null) emitAll(other) }")
)
public fun <T> Flow<T>.concatWith(other: Flow<T>): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("this.combine(other, transform)")
)
public fun <T1, T2, R> Flow<T1>.combineLatest(other: Flow<T2>, transform: suspend (T1, T2) -> R): Flow<R> =
combine(this, other, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, transform)")
)
public fun <T1, T2, T3, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
transform: suspend (T1, T2, T3) -> R
) = combine(this, other, other2, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public fun <T1, T2, T3, T4, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
transform: suspend (T1, T2, T3, T4) -> R
) = combine(this, other, other2, other3, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public fun <T1, T2, T3, T4, T5, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
other4: Flow<T5>,
transform: suspend (T1, T2, T3, T4, T5) -> R
): Flow<R> = combine(this, other, other2, other3, other4, transform)
/**
* Delays the emission of values from this flow for the given [timeMillis].
* Use `onStart { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR, // since 1.3.0, error in 1.5.0
message = "Use 'onStart { delay(timeMillis) }'",
replaceWith = ReplaceWith("onStart { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayFlow(timeMillis: Long): Flow<T> = onStart { delay(timeMillis) }
/**
* Delays each element emitted by the given flow for the given [timeMillis].
* Use `onEach { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR, // since 1.3.0, error in 1.5.0
message = "Use 'onEach { delay(timeMillis) }'",
replaceWith = ReplaceWith("onEach { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayEach(timeMillis: Long): Flow<T> = onEach { delay(timeMillis) }
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogues of 'switchMap' are 'transformLatest', 'flatMapLatest' and 'mapLatest'",
replaceWith = ReplaceWith("this.flatMapLatest(transform)")
)
public fun <T, R> Flow<T>.switchMap(transform: suspend (value: T) -> Flow<R>): Flow<R> = flatMapLatest(transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR, // Warning since 1.3.8, was experimental when deprecated, ERROR since 1.5.0
message = "'scanReduce' was renamed to 'runningReduce' to be consistent with Kotlin standard library",
replaceWith = ReplaceWith("runningReduce(operation)")
)
public fun <T> Flow<T>.scanReduce(operation: suspend (accumulator: T, value: T) -> T): Flow<T> = runningReduce(operation)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'publish()' is 'shareIn'. \n" +
"publish().connect() is the default strategy (no extra call is needed), \n" +
"publish().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"publish().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, 0)")
)
public fun <T> Flow<T>.publish(): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'publish(bufferSize)' is 'buffer' followed by 'shareIn'. \n" +
"publish().connect() is the default strategy (no extra call is needed), \n" +
"publish().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"publish().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.buffer(bufferSize).shareIn(scope, 0)")
)
public fun <T> Flow<T>.publish(bufferSize: Int): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'replay()' is 'shareIn' with unlimited replay. \n" +
"replay().connect() is the default strategy (no extra call is needed), \n" +
"replay().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"replay().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, Int.MAX_VALUE)")
)
public fun <T> Flow<T>.replay(): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'replay(bufferSize)' is 'shareIn' with the specified replay parameter. \n" +
"replay().connect() is the default strategy (no extra call is needed), \n" +
"replay().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"replay().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, bufferSize)")
)
public fun <T> Flow<T>.replay(bufferSize: Int): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'cache()' is 'shareIn' with unlimited replay and 'started = SharingStared.Lazily' argument'",
replaceWith = ReplaceWith("this.shareIn(scope, Int.MAX_VALUE, started = SharingStared.Lazily)")
)
public fun <T> Flow<T>.cache(): Flow<T> = noImpl()
| apache-2.0 | e800c3c46a7fc3f1413250d362831633 | 34.341414 | 135 | 0.667257 | 3.754883 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/com/jchanghong/ActivityCategoryDetails.kt | 2 | 6648 | package com.jchanghong
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.Snackbar
import android.support.v7.app.ActionBar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.jchanghong.adapter.ListAdapterNote
import com.jchanghong.data.DatabaseManager
import com.jchanghong.model.Category
import com.jchanghong.model.Note
import com.jchanghong.utils.Tools
class ActivityCategoryDetails : AppCompatActivity() {
lateinit private var toolbar: Toolbar
lateinit private var actionBar: ActionBar
lateinit private var menu: Menu
lateinit private var image: ImageView
lateinit private var name: TextView
lateinit private var appbar: AppBarLayout
private var ext_category: Category? = null
lateinit var recyclerView: RecyclerView
lateinit var mAdapter: ListAdapterNote
lateinit private var lyt_not_found: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_details)
// get extra object
ext_category = intent.getSerializableExtra(EXTRA_OBJCT) as Category
iniComponent()
if (ext_category != null) {
setCategoryView()
}
initToolbar()
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
lyt_not_found = findViewById(R.id.lyt_not_found) as LinearLayout
recyclerView.layoutManager = LinearLayoutManager(this@ActivityCategoryDetails)
recyclerView.setHasFixedSize(true)
recyclerView.itemAnimator = DefaultItemAnimator()
displayData(DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0))
}
private fun iniComponent() {
image = findViewById(R.id.image) as ImageView
name = findViewById(R.id.name) as TextView
appbar = findViewById(R.id.appbar) as AppBarLayout
}
private fun setCategoryView() {
image.setImageResource(Tools.StringToResId(ext_category!!.icon, applicationContext))
image.setColorFilter(Color.parseColor(ext_category?.color))
name.text = ext_category?.name
appbar.setBackgroundColor(Color.parseColor(ext_category?.color))
Tools.systemBarLolipopCustom(this@ActivityCategoryDetails, ext_category?.color!!)
}
private fun initToolbar() {
toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
actionBar = supportActionBar!!
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeButtonEnabled(true)
actionBar.title = ""
}
private fun displayData(items: List<Note>) {
mAdapter = ListAdapterNote(applicationContext, items)
recyclerView.adapter = mAdapter
mAdapter.setOnItemClickListener(
object : ListAdapterNote.OnItemClickListener {
override fun onItemClick(view: View, model: Note) {
val intent = Intent(applicationContext, ActivityNoteEdit::class.java)
intent.putExtra(ActivityNoteEdit.EXTRA_OBJCT, model)
startActivity(intent)
}
}
)
if (mAdapter.itemCount == 0) {
lyt_not_found.visibility = View.VISIBLE
} else {
lyt_not_found.visibility = View.GONE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> onBackPressed()
R.id.action_edit_cat -> {
val i = Intent(applicationContext, ActivityCategoryEdit::class.java)
i.putExtra(ActivityCategoryDetails.EXTRA_OBJCT, ext_category)
startActivity(i)
}
R.id.action_delete_cat -> if (DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0).isEmpty()) {
// DatabaseManager.deleteCategory(ext_category.getId());
// Toast.makeText(getApplicationContext(),"Category deleted", Toast.LENGTH_SHORT).show();
deleteConfirmation()
// finish();
} else {
Snackbar.make(recyclerView, getString(R.string.Categoryisnotempty), Snackbar.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
this.menu = menu
menuInflater.inflate(R.menu.menu_activity_category, menu)
return true
}
override fun onResume() {
super.onResume()
ext_category = DatabaseManager.getCategoryById(ext_category?.id ?: 1)
recyclerView.layoutManager = LinearLayoutManager(this@ActivityCategoryDetails)
recyclerView.setHasFixedSize(true)
recyclerView.itemAnimator = DefaultItemAnimator()
image.setImageResource(Tools.StringToResId(ext_category?.icon!!, applicationContext))
image.setColorFilter(Color.parseColor(ext_category?.color))
name.text = ext_category?.name
appbar.setBackgroundColor(Color.parseColor(ext_category?.color))
Tools.systemBarLolipopCustom(this@ActivityCategoryDetails, ext_category?.color ?: DatabaseManager.cat_color[0])
displayData(DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0))
}
private fun deleteConfirmation() {
val builder = AlertDialog.Builder(this@ActivityCategoryDetails)
builder.setTitle(getString(R.string.deleteconfirmation))
builder.setMessage(getString(R.string.areyousuredeletec))
builder.setPositiveButton("Yes") { _, _ ->
if (ext_category != null) {
DatabaseManager.deleteCategory(ext_category?.id ?: 1)
}
Toast.makeText(applicationContext, getString(R.string.categorydeleted), Toast.LENGTH_SHORT).show()
finish()
}
builder.setNegativeButton("No", null)
builder.show()
}
companion object {
val EXTRA_OBJCT = "com.jchanghong.EXTRA_OBJECT_CATEGORY"
}
}
| gpl-2.0 | 113ab59acbda079bc4b124698a6a3e73 | 37.651163 | 124 | 0.677948 | 4.924444 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/Db.kt | 1 | 12273 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.db
import slatekit.common.values.Record
import slatekit.common.conf.Confs
import slatekit.common.data.*
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Statement
import slatekit.common.repeatWith
import slatekit.db.DbUtils.executeCall
import slatekit.db.DbUtils.executeCon
import slatekit.db.DbUtils.executePrep
import slatekit.db.DbUtils.executeStmt
import slatekit.db.DbUtils.fillArgs
/**
* Light-weight JDBC based database access wrapper
* This is used for 2 purposes:
* 1. Facilitate Unit Testing
* 2. Facilitate support for the Entities / ORM ( SqlFramework ) project
* to abstract away JDBC for Android
*
* 1. sql-server: driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
* 2. sql-server: url = "jdbc:sqlserver://<server_name>:<port>;database=<database>;user=<user>;
* password=<password>;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
*/
class Db(private val dbCon: DbCon,
errorCallback: ((Exception) -> Unit)? = null,
val settings:DbSettings = DbSettings(true)) : IDb {
override val errHandler = errorCallback ?: this::errorHandler
/**
* Driver name e.g. com.mysql.jdbc.Driver
*/
override val driver: String = dbCon.driver
/**
* registers the jdbc driver
* @return
*/
override fun open(): Db {
Class.forName(dbCon.driver)
return this
}
/**
* Execute raw sql ( used for DDL )
*/
override fun execute(sql: String) {
executeStmt(dbCon, settings, { _, stmt -> stmt.execute(sql) }, errHandler)
}
/**
* executes an insert using the sql or stored proc and gets the id
*
* @param sql : The sql or stored proc
* @param inputs : The inputs for the sql or stored proc
* @return : The id ( primary key )
*/
override fun insert(sql: String, inputs: List<Value>?): Long {
val res = executeCon(dbCon, settings, { con: Connection ->
val stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
stmt.use { s ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(s, inputs, errHandler) }
// execute the update
s.executeUpdate()
// get id.
val rs = s.generatedKeys
rs.use { r ->
val id = when (r.next()) {
true -> r.getLong(1)
false -> 0L
}
id
}
}
}, errHandler)
return res ?: 0
}
/**
* executes an insert using the sql or stored proc and gets the id
*
* @param sql : The sql or stored proc
* @param inputs : The inputs for the sql or stored proc
* @return : The id ( primary key )
*/
override fun insertGetId(sql: String, inputs: List<Value>?): String {
val res = executeCon(dbCon, settings, { con: Connection ->
val stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
stmt.use { s ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(s, inputs, errHandler) }
// execute the update
s.executeUpdate()
// get id.
val rs = s.generatedKeys
rs.use { r ->
val id = when (r.next()) {
true -> r.getString(1)
false -> ""
}
id
}
}
}, errHandler)
return res ?: ""
}
/**
* executes the update sql with prepared statement using inputs
* @param sql : sql statement
* @param inputs : Inputs for the sql or stored proc
* @return : The number of affected records
*/
override fun update(sql: String, inputs: List<Value>?): Int {
val result = executePrep<Int>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// update and get number of affected records
val count = stmt.executeUpdate()
count
}, errHandler)
return result ?: 0
}
/**
* executes the update sql with prepared statement using inputs
* @param sql : sql statement
* @param inputs : Inputs for the sql or stored proc
* @return : The number of affected records
*/
override fun call(sql: String, inputs: List<Value>?): Int {
val result = executeCall<Int>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// update and get number of affected records
val count = stmt.executeUpdate()
count
}, errHandler)
return result ?: 0
}
/**
* gets a scalar string value using the sql provided
*
* @param sql : The sql text
* @return
*/
override fun <T> getScalarOrNull(sql: String, typ: DataType, inputs: List<Value>?): T? {
return executePrep<T>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// execute
val rs = stmt.executeQuery()
rs.use { r ->
val res: T? = when (r.next()) {
true -> DbUtils.getScalar<T>(r, typ)
false -> null
}
res
}
}, errHandler)
}
/**
* Executes a sql query
* @param sql : The sql to query
* @param callback : The callback to handle the resultset
* @param moveNext : Whether or not to automatically move the resultset to the next/first row
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> query(
sql: String,
callback: (ResultSet) -> T?,
moveNext: Boolean,
inputs: List<Value>?
): T? {
val result = executePrep<T>(dbCon, settings, sql, { _: Connection, stmt: PreparedStatement ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// execute
val rs = stmt.executeQuery()
rs.use { r ->
val v = when(if (moveNext) r.next() else true) {
true -> callback(r)
false -> null
}
v
}
}, errHandler)
return result
}
/**
* maps a single item using the sql supplied
*
* @param sql : The sql
* @param mapper : THe mapper to map the item of type T
* @tparam T : The type of the item
* @return
*/
@Suppress("UNCHECKED_CAST")
override fun <T> mapOne(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): T? {
val res = query(sql, { rs ->
val rec = RecordSet(rs)
if (rs.next())
mapper.invoke(rec)
else
null
}, false, inputs)
return res
}
/**
* maps multiple items using the sql supplied
*
* @param sql : The sql
* @param mapper : THe mapper to map the item of type T
* @tparam T : The type of the item
* @return
*/
@Suppress("UNCHECKED_CAST")
override fun <T> mapAll(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): List<T>? {
val res = query(sql, { rs ->
val rec = RecordSet(rs)
val buf = mutableListOf<T>()
while (rs.next()) {
val item = mapper.invoke(rec)
buf.add(item as T)
}
buf.toList()
}, false, inputs)
return res
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param callback : The callback to handle the resultset
* @param moveNext : Whether or not to automatically move the resultset to the next/first row
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> callQuery(
procName: String,
callback: (ResultSet) -> T?,
moveNext: Boolean,
inputs: List<Value>?
): T? {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return query(sql, callback, moveNext, inputs)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param mapper : The callback to handle the resultset
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> callQueryMapped(
procName: String,
mapper: (Record) -> T?,
inputs: List<Value>?
): List<T>? {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return mapAll(sql, inputs, mapper)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun callCreate(procName: String, inputs: List<Value>?): String {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return insertGetId(sql, inputs)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun callUpdate(procName: String, inputs: List<Value>?): Int {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return call(sql, inputs)
}
override fun errorHandler(ex: Exception) {
throw ex
}
companion object {
/**
* Load Db from config file, which could be a java packaged resource or on file
* @param cls: Class holding resource files
* @param path: URI of file
* 1. "usr://.slatekit/common/conf/db.conf"
* 2. "jar://env.conf
*/
fun of(cls:Class<*>, path:String):IDb {
return when(val con = Confs.readDbCon(cls,path)) {
null -> throw Exception("Unable to load database connection from $path")
else -> of(con)
}
}
/**
* Load Db using a default connection from Connections
* @param cons: Connection collection
*/
fun of(cons:Connections):IDb {
return when(val con = cons.default()){
null -> throw Exception("Unable to load default connection from connections")
else -> of(con)
}
}
/**
* Only here for convenience to call open
*/
fun of(con:DbCon):IDb {
return with(Db(con)) { open() }
}
}
/*
* DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getUserByEmail`(in email varchar(80))
BEGIN
select * from `user` where email = email;
END$$
DELIMITER ;
**/
}
| apache-2.0 | bb271b3d1507524e625e54da01a643df | 31.128272 | 105 | 0.554062 | 4.364509 | false | false | false | false |
leafclick/intellij-community | plugins/stats-collector/src/com/intellij/stats/storage/factors/MutableElementStorage.kt | 1 | 777 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.storage.factors
import com.intellij.stats.personalization.session.ElementSessionFactorsStorage
import com.intellij.completion.sorting.FeatureUtils
class MutableElementStorage : LookupElementStorage {
private var factors: Map<String, Any>? = null
override fun getLastUsedFactors(): Map<String, Any>? {
return factors
}
fun fireElementScored(factors: MutableMap<String, Any>, score: Double?) {
if (score != null) {
factors[FeatureUtils.ML_RANK] = score
}
this.factors = factors
}
override val sessionFactors: ElementSessionFactorsStorage = ElementSessionFactorsStorage()
} | apache-2.0 | 0185ff13980a1a950e73c81ae31fdc7b | 34.363636 | 140 | 0.763192 | 4.222826 | false | false | false | false |
Pozo/threejs-kotlin | threejs/src/main/kotlin/three/materials/sprite/SpriteMaterialParam.kt | 1 | 457 | package three.materials.sprite
import three.textures.Texture
class SpriteMaterialParam {
var asDynamic: dynamic
constructor() {
asDynamic = {}
}
var color: Int = 0
set(value) {
asDynamic.color = value
}
var opacity: Float = 0f
set(value) {
asDynamic.opacity = value
}
var map: Texture = Texture()
set(value) {
asDynamic.map = value
}
}
| mit | 9f044065758e83db31c331ff1de43111 | 17.28 | 37 | 0.538293 | 4.394231 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/runtime/memory/var2.kt | 1 | 313 | package runtime.memory.var2
import kotlin.test.*
@Test fun runTest() {
var x = Any()
for (i in 0..1) {
val c = Any()
if (i == 0) x = c
}
// x refcount is 1.
val y = try {
x
} finally {
x = Any()
}
y.use()
}
fun Any?.use() {
var x = this
} | apache-2.0 | 58ecf366548a86f95d8d10d4fa5faf85 | 11.076923 | 27 | 0.428115 | 2.980952 | false | true | false | false |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ContentEntryBridge.kt | 3 | 5019 | package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ExcludeFolder
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.SourceRootEntity
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
internal class ContentEntryBridge(internal val model: ModuleRootModelBridge,
val sourceRootEntities: List<SourceRootEntity>,
val entity: ContentRootEntity,
val updater: (((WorkspaceEntityStorageDiffBuilder) -> Unit) -> Unit)?) : ContentEntry {
private val excludeFolders by lazy {
entity.excludedUrls.map { ExcludeFolderBridge(this, it) }
}
private val sourceFolders by lazy {
sourceRootEntities.map { SourceFolderBridge(this, it) }
}
override fun getFile(): VirtualFile? {
val virtualFilePointer = entity.url as VirtualFilePointer
return virtualFilePointer.file
}
override fun getUrl(): String = entity.url.url
override fun getSourceFolders(): Array<SourceFolder> = sourceFolders.toTypedArray()
override fun getExcludeFolders(): Array<ExcludeFolder> = excludeFolders.toTypedArray()
override fun getExcludePatterns(): List<String> = entity.excludedPatterns
override fun getExcludeFolderFiles(): Array<VirtualFile> {
val result = ArrayList<VirtualFile>(excludeFolders.size)
excludeFolders.mapNotNullTo(result) { it.file }
for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) {
excludePolicy.getExcludeRootsForModule(model).mapNotNullTo(result) { it.file }
}
return VfsUtilCore.toVirtualFileArray(result)
}
override fun getExcludeFolderUrls(): MutableList<String> {
val result = ArrayList<String>(excludeFolders.size)
excludeFolders.mapTo(result) { it.url }
for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) {
excludePolicy.getExcludeRootsForModule(model).mapTo(result) { it.url }
}
return result
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun isSynthetic() = false
override fun getRootModel() = model
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> = getSourceFolders(setOf(rootType))
override fun getSourceFolders(rootTypes: Set<JpsModuleSourceRootType<*>>): List<SourceFolder> = sourceFolders.filter { it.rootType in rootTypes }
override fun getSourceFolderFiles() = sourceFolders.mapNotNull { it.file }.toTypedArray()
override fun <P : JpsElement?> addSourceFolder(file: VirtualFile,
type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder = throwReadonly()
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = throwReadonly()
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>) = throwReadonly()
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder = throwReadonly()
override fun removeSourceFolder(sourceFolder: SourceFolder) = throwReadonly()
override fun clearSourceFolders() = throwReadonly()
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = throwReadonly()
override fun addExcludeFolder(url: String): ExcludeFolder = throwReadonly()
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) = throwReadonly()
override fun removeExcludeFolder(url: String): Boolean = throwReadonly()
override fun clearExcludeFolders() = throwReadonly()
override fun addExcludePattern(pattern: String) = throwReadonly()
override fun removeExcludePattern(pattern: String) = throwReadonly()
override fun setExcludePatterns(patterns: MutableList<String>) = throwReadonly()
private fun throwReadonly(): Nothing = error("This model is read-only")
}
| apache-2.0 | 863685bc16826c01bd75bf98ce423478 | 51.831579 | 147 | 0.74218 | 5.350746 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Mat4d.kt | 1 | 27554 | package de.fabmax.kool.math
import de.fabmax.kool.KoolException
import de.fabmax.kool.lock
import de.fabmax.kool.util.Float32Buffer
import kotlin.math.*
open class Mat4d {
val matrix = DoubleArray(16)
init {
setIdentity()
}
fun translate(tx: Float, ty: Float, tz: Float): Mat4d = translate(tx.toDouble(), ty.toDouble(), tz.toDouble())
fun translate(tx: Double, ty: Double, tz: Double): Mat4d {
for (i in 0..3) {
matrix[12 + i] += matrix[i] * tx + matrix[4 + i] * ty + matrix[8 + i] * tz
}
return this
}
fun translate(t: Vec3f): Mat4d = translate(t.x.toDouble(), t.y.toDouble(), t.z.toDouble())
fun translate(t: Vec3d): Mat4d = translate(t.x, t.y, t.z)
fun translate(tx: Double, ty: Double, tz: Double, result: Mat4d): Mat4d {
for (i in 0..11) {
result.matrix[i] = matrix[i]
}
for (i in 0..3) {
result.matrix[12 + i] = matrix[i] * tx + matrix[4 + i] * ty + matrix[8 + i] * tz + matrix[12 + i]
}
return result
}
fun rotate(angleDeg: Double, axX: Double, axY: Double, axZ: Double): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(angleDeg, axX, axY, axZ)
set(mul(tmpMatA, tmpMatB))
}
}
fun rotate(angleDeg: Float, axis: Vec3f) = rotate(angleDeg.toDouble(), axis.x.toDouble(), axis.y.toDouble(), axis.z.toDouble())
fun rotate(angleDeg: Double, axis: Vec3d) = rotate(angleDeg, axis.x, axis.y, axis.z)
fun rotate(eulerX: Double, eulerY: Double, eulerZ: Double): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(eulerX, eulerY, eulerZ)
set(mul(tmpMatA, tmpMatB))
}
}
fun rotate(angleDeg: Double, axX: Double, axY: Double, axZ: Double, result: Mat4d): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(angleDeg, axX, axY, axZ)
mul(tmpMatA, result)
}
}
fun rotate(angleDeg: Double, axis: Vec3d, result: Mat4d) = rotate(angleDeg, axis.x, axis.y, axis.z, result)
fun rotate(eulerX: Double, eulerY: Double, eulerZ: Double, result: Mat4d): Mat4d {
result.set(this)
result.rotate(eulerX, eulerY, eulerZ)
return result
}
fun scale(s: Double) = scale(s, s, s)
fun scale(sx: Double, sy: Double, sz: Double): Mat4d {
for (i in 0..3) {
matrix[i] *= sx
matrix[4 + i] *= sy
matrix[8 + i] *= sz
}
return this
}
fun scale(scale: Vec3d): Mat4d = scale(scale.x, scale.y, scale.z)
fun scale(sx: Double, sy: Double, sz: Double, result: Mat4d): Mat4d {
for (i in 0..3) {
result.matrix[0] = matrix[0] * sx
result.matrix[4 + i] = matrix[4 + i] * sy
result.matrix[8 + i] = matrix[8 + i] * sz
result.matrix[12 + i] = matrix[12 + i]
}
return result
}
fun resetScale(): Mat4d {
val s0 = 1.0 / sqrt(this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0])
val s1 = 1.0 / sqrt(this[0, 1] * this[0, 1] + this[1, 1] * this[1, 1] + this[2, 1] * this[2, 1])
val s2 = 1.0 / sqrt(this[0, 2] * this[0, 2] + this[1, 2] * this[1, 2] + this[2, 2] * this[2, 2])
scale(s0, s1, s2)
return this
}
fun transpose(): Mat4d {
return lock(tmpMatLock) {
set(transpose(tmpMatA))
}
}
fun transpose(result: Mat4d): Mat4d {
for (i in 0..3) {
val mBase = i * 4
result.matrix[i] = matrix[mBase]
result.matrix[i + 4] = matrix[mBase + 1]
result.matrix[i + 8] = matrix[mBase + 2]
result.matrix[i + 12] = matrix[mBase + 3]
}
return result
}
fun invert(eps: Double = 0.0): Boolean {
return lock(tmpMatLock) { invert(tmpMatA, eps).also { if (it) set(tmpMatA) } }
}
fun invert(result: Mat4d, eps: Double = 0.0): Boolean {
// Invert a 4 x 4 matrix using Cramer's Rule
// transpose matrix
val src0 = matrix[0]
val src4 = matrix[1]
val src8 = matrix[2]
val src12 = matrix[3]
val src1 = matrix[4]
val src5 = matrix[5]
val src9 = matrix[6]
val src13 = matrix[7]
val src2 = matrix[8]
val src6 = matrix[9]
val src10 = matrix[10]
val src14 = matrix[11]
val src3 = matrix[12]
val src7 = matrix[13]
val src11 = matrix[14]
val src15 = matrix[15]
// calculate pairs for first 8 elements (cofactors)
val atmp0 = src10 * src15
val atmp1 = src11 * src14
val atmp2 = src9 * src15
val atmp3 = src11 * src13
val atmp4 = src9 * src14
val atmp5 = src10 * src13
val atmp6 = src8 * src15
val atmp7 = src11 * src12
val atmp8 = src8 * src14
val atmp9 = src10 * src12
val atmp10 = src8 * src13
val atmp11 = src9 * src12
// calculate first 8 elements (cofactors)
val dst0 = atmp0 * src5 + atmp3 * src6 + atmp4 * src7 - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7)
val dst1 = atmp1 * src4 + atmp6 * src6 + atmp9 * src7 - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7)
val dst2 = atmp2 * src4 + atmp7 * src5 + atmp10 * src7 - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7)
val dst3 = atmp5 * src4 + atmp8 * src5 + atmp11 * src6 - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6)
val dst4 = atmp1 * src1 + atmp2 * src2 + atmp5 * src3 - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3)
val dst5 = atmp0 * src0 + atmp7 * src2 + atmp8 * src3 - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3)
val dst6 = atmp3 * src0 + atmp6 * src1 + atmp11 * src3 - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3)
val dst7 = atmp4 * src0 + atmp9 * src1 + atmp10 * src2 - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2)
// calculate pairs for second 8 elements (cofactors)
val btmp0 = src2 * src7
val btmp1 = src3 * src6
val btmp2 = src1 * src7
val btmp3 = src3 * src5
val btmp4 = src1 * src6
val btmp5 = src2 * src5
val btmp6 = src0 * src7
val btmp7 = src3 * src4
val btmp8 = src0 * src6
val btmp9 = src2 * src4
val btmp10 = src0 * src5
val btmp11 = src1 * src4
// calculate second 8 elements (cofactors)
val dst8 = btmp0 * src13 + btmp3 * src14 + btmp4 * src15 - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15)
val dst9 = btmp1 * src12 + btmp6 * src14 + btmp9 * src15 - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15)
val dst10 = btmp2 * src12 + btmp7 * src13 + btmp10 * src15 - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15)
val dst11 = btmp5 * src12 + btmp8 * src13 + btmp11 * src14 - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14)
val dst12 = btmp2 * src10 + btmp5 * src11 + btmp1 * src9 - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10)
val dst13 = btmp8 * src11 + btmp0 * src8 + btmp7 * src10 - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8)
val dst14 = btmp6 * src9 + btmp11 * src11 + btmp3 * src8 - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9)
val dst15 = btmp10 * src10 + btmp4 * src8 + btmp9 * src9 - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8)
// calculate determinant
val det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3
if (det.isFuzzyZero(eps)) {
return false
}
// calculate matrix inverse
val invdet = 1.0 / det
result.matrix[0] = dst0 * invdet
result.matrix[1] = dst1 * invdet
result.matrix[2] = dst2 * invdet
result.matrix[3] = dst3 * invdet
result.matrix[4] = dst4 * invdet
result.matrix[5] = dst5 * invdet
result.matrix[6] = dst6 * invdet
result.matrix[7] = dst7 * invdet
result.matrix[8] = dst8 * invdet
result.matrix[9] = dst9 * invdet
result.matrix[10] = dst10 * invdet
result.matrix[11] = dst11 * invdet
result.matrix[12] = dst12 * invdet
result.matrix[13] = dst13 * invdet
result.matrix[14] = dst14 * invdet
result.matrix[15] = dst15 * invdet
return true
}
fun transform(vec: MutableVec3f, w: Float = 1.0f): MutableVec3f {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return vec.set(x.toFloat(), y.toFloat(), z.toFloat())
}
fun transform(vec: Vec3f, w: Float, result: MutableVec3f): MutableVec3f {
result.x = (vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]).toFloat()
result.y = (vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]).toFloat()
result.z = (vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]).toFloat()
return result
}
fun transform(vec: MutableVec4f): MutableVec4f {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
val w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return vec.set(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
}
fun transform(vec: Vec4f, result: MutableVec4f): MutableVec4f {
result.x = (vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]).toFloat()
result.y = (vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]).toFloat()
result.z = (vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]).toFloat()
result.w = (vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]).toFloat()
return result
}
fun transform(vec: MutableVec3d, w: Double = 1.0): MutableVec3d {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return vec.set(x, y, z)
}
fun transform(vec: Vec3d, w: Double = 1.0, result: MutableVec3d): MutableVec3d {
result.x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
result.y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
result.z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return result
}
fun transform(vec: MutableVec4d): MutableVec4d {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
val w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return vec.set(x, y, z, w)
}
fun transform(vec: Vec4d, result: MutableVec4d): MutableVec4d {
result.x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
result.y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
result.z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
result.w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return result
}
fun add(other: Mat4d): Mat4d {
for (i in 0..15) {
matrix[i] += other.matrix[i]
}
return this
}
fun mul(other: Mat4d): Mat4d {
return lock(tmpMatLock) {
mul(other, tmpMatA)
set(tmpMatA)
}
}
fun mul(other: Mat4d, result: Mat4d): Mat4d {
for (i in 0..3) {
for (j in 0..3) {
var x = 0.0
for (k in 0..3) {
x += matrix[j + k * 4] * other.matrix[i * 4 + k]
}
result.matrix[i * 4 + j] = x
}
}
return result
}
fun set(other: Mat4d): Mat4d {
for (i in 0..15) {
matrix[i] = other.matrix[i]
}
return this
}
fun set(other: Mat4f): Mat4d {
for (i in 0..15) {
matrix[i] = other.matrix[i].toDouble()
}
return this
}
fun set(doubles: List<Double>): Mat4d {
for (i in 0..15) {
matrix[i] = doubles[i]
}
return this
}
fun setZero(): Mat4d {
for (i in 0..15) {
matrix[i] = 0.0
}
return this
}
fun setIdentity(): Mat4d {
for (i in 1..15) {
matrix[i] = 0.0
}
matrix[0] = 1.0
matrix[5] = 1.0
matrix[10] = 1.0
matrix[15] = 1.0
return this
}
fun setRotate(eulerX: Double, eulerY: Double, eulerZ: Double): Mat4d {
val a = eulerX.toRad()
val b = eulerY.toRad()
val c = eulerZ.toRad()
val ci = cos(a)
val cj = cos(b)
val ch = cos(c)
val si = sin(a)
val sj = sin(b)
val sh = sin(c)
val cc = ci * ch
val cs = ci * sh
val sc = si * ch
val ss = si * sh
matrix[0] = cj * ch
matrix[4] = sj * sc - cs
matrix[8] = sj * cc + ss
matrix[12] = 0.0
matrix[1] = cj * sh
matrix[5] = sj * ss + cc
matrix[9] = sj * cs - sc
matrix[13] = 0.0
matrix[2] = -sj
matrix[6] = cj * si
matrix[10] = cj * ci
matrix[14] = 0.0
matrix[3] = 0.0
matrix[7] = 0.0
matrix[11] = 0.0
matrix[15] = 1.0
return this
}
fun setRotate(rotA: Double, axX: Double, axY: Double, axZ: Double): Mat4d {
val a = rotA.toRad()
var x = axX
var y = axY
var z = axZ
matrix[3] = 0.0
matrix[7] = 0.0
matrix[11] = 0.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 0.0
matrix[15] = 1.0
val s = sin(a)
val c = cos(a)
if (x > 0.0 && y == 0.0 && z == 0.0) {
matrix[5] = c
matrix[10] = c
matrix[6] = s
matrix[9] = -s
matrix[1] = 0.0
matrix[2] = 0.0
matrix[4] = 0.0
matrix[8] = 0.0
matrix[0] = 1.0
} else if (x == 0.0 && y > 0.0 &&z == 0.0) {
matrix[0] = c
matrix[10] = c
matrix[8] = s
matrix[2] = -s
matrix[1] = 0.0
matrix[4] = 0.0
matrix[6] = 0.0
matrix[9] = 0.0
matrix[5] = 1.0
} else if (x == 0.0 && y == 0.0 && z > 0.0) {
matrix[0] = c
matrix[5] = c
matrix[1] = s
matrix[4] = -s
matrix[2] = 0.0
matrix[6] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[10] = 1.0
} else {
val recipLen = 1.0f / sqrt(x*x + y*y + z*z)
x *= recipLen
y *= recipLen
z *= recipLen
val nc = 1.0 - c
val xy = x * y
val yz = y * z
val zx = z * x
val xs = x * s
val ys = y * s
val zs = z * s
matrix[0] = x * x * nc + c
matrix[4] = xy * nc - zs
matrix[8] = zx * nc + ys
matrix[1] = xy * nc + zs
matrix[5] = y * y * nc + c
matrix[9] = yz * nc - xs
matrix[2] = zx * nc - ys
matrix[6] = yz * nc + xs
matrix[10] = z * z * nc + c
}
return this
}
fun setRotate(quaternion: Vec4d): Mat4d {
val r = quaternion.w
val i = quaternion.x
val j = quaternion.y
val k = quaternion.z
var s = sqrt(r*r + i*i + j*j + k*k)
s = 1.0 / (s * s)
this[0, 0] = 1.0 - 2*s*(j*j + k*k)
this[0, 1] = 2.0*s*(i*j - k*r)
this[0, 2] = 2.0*s*(i*k + j*r)
this[0, 3] = 0.0
this[1, 0] = 2.0*s*(i*j + k*r)
this[1, 1] = 1.0 - 2*s*(i*i + k*k)
this[1, 2] = 2.0*s*(j*k - i*r)
this[1, 3] = 0.0
this[2, 0] = 2.0*s*(i*k - j*r)
this[2, 1] = 2.0*s*(j*k + i*r)
this[2, 2] = 1.0 - 2*s*(i*i + j*j)
this[2, 3] = 0.0
this[3, 0] = 0.0
this[3, 1] = 0.0
this[3, 2] = 0.0
this[3, 3] = 1.0
return this
}
fun setRotation(mat3: Mat3f): Mat4d {
for (row in 0..2) {
for (col in 0..2) {
this[row, col] = mat3[row, col].toDouble()
}
}
val l0 = this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0] + this[3, 0] * this[3, 0]
val s = 1f / sqrt(l0)
scale(s, s, s)
return this
}
fun setRotation(mat4: Mat4d): Mat4d {
for (row in 0..2) {
for (col in 0..2) {
this[row, col] = mat4[row, col]
}
}
val l0 = this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0] + this[3, 0] * this[3, 0]
val s = 1f / sqrt(l0)
scale(s, s, s)
return this
}
fun setTranslate(translation: Vec3d) = setTranslate(translation.x, translation.y, translation.z)
fun setTranslate(x: Double, y: Double, z: Double): Mat4d {
for (i in 1..15) {
matrix[i] = 0.0
}
matrix[12] = x
matrix[13] = y
matrix[14] = z
matrix[0] = 1.0
matrix[5] = 1.0
matrix[10] = 1.0
matrix[15] = 1.0
return this
}
fun setLookAt(position: Vec3f, lookAt: Vec3f, up: Vec3f) = setLookAt(
position.x.toDouble(), position.y.toDouble(), position.z.toDouble(),
lookAt.x.toDouble(), lookAt.y.toDouble(), lookAt.z.toDouble(),
up.x.toDouble(), up.y.toDouble(), up.z.toDouble())
fun setLookAt(position: Vec3d, lookAt: Vec3d, up: Vec3d) =
setLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z)
private fun setLookAt(px: Double, py: Double, pz: Double, lx: Double, ly: Double, lz: Double, upx: Double, upy: Double, upz: Double): Mat4d {
// See the OpenGL GLUT documentation for gluLookAt for a description
// of the algorithm. We implement it in a straightforward way:
var fx = lx - px
var fy = ly - py
var fz = lz - pz
// Normalize f
val rlf = 1.0 / sqrt(fx*fx + fy*fy + fz*fz)
fx *= rlf
fy *= rlf
fz *= rlf
// compute s = f x up (x means "cross product")
var sx = fy * upz - fz * upy
var sy = fz * upx - fx * upz
var sz = fx * upy - fy * upx
// and normalize s
val rls = 1.0 / sqrt(sx*sx + sy*sy + sz*sz)
sx *= rls
sy *= rls
sz *= rls
// compute u = s x f
val ux = sy * fz - sz * fy
val uy = sz * fx - sx * fz
val uz = sx * fy - sy * fx
matrix[0] = sx
matrix[1] = ux
matrix[2] = -fx
matrix[3] = 0.0
matrix[4] = sy
matrix[5] = uy
matrix[6] = -fy
matrix[7] = 0.0
matrix[8] = sz
matrix[9] = uz
matrix[10] = -fz
matrix[11] = 0.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 0.0
matrix[15] = 1.0
return translate(-px, -py, -pz)
}
fun setOrthographic(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) =
setOrthographic(left.toDouble(), right.toDouble(), bottom.toDouble(), top.toDouble(), near.toDouble(), far.toDouble())
fun setOrthographic(left: Double, right: Double, bottom: Double, top: Double, near: Double, far: Double): Mat4d {
if (left == right) {
throw IllegalArgumentException("left == right")
}
if (bottom == top) {
throw IllegalArgumentException("bottom == top")
}
if (near == far) {
throw IllegalArgumentException("near == far")
}
val width = 1.0 / (right - left)
val height = 1.0 / (top - bottom)
val depth = 1.0 / (far - near)
val x = 2.0 * width
val y = 2.0 * height
val z = -2.0 * depth
val tx = -(right + left) * width
val ty = -(top + bottom) * height
val tz = -(far + near) * depth
matrix[0] = x
matrix[5] = y
matrix[10] = z
matrix[12] = tx
matrix[13] = ty
matrix[14] = tz
matrix[15] = 1.0
matrix[1] = 0.0
matrix[2] = 0.0
matrix[3] = 0.0
matrix[4] = 0.0
matrix[6] = 0.0
matrix[7] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[11] = 0.0
return this
}
fun setPerspective(fovy: Float, aspect: Float, near: Float, far: Float) =
setPerspective(fovy.toDouble(), aspect.toDouble(), near.toDouble(), far.toDouble())
fun setPerspective(fovy: Double, aspect: Double, near: Double, far: Double): Mat4d {
val f = 1.0 / tan(fovy * (PI / 360.0))
val rangeReciprocal = 1.0 / (near - far)
matrix[0] = f / aspect
matrix[1] = 0.0
matrix[2] = 0.0
matrix[3] = 0.0
matrix[4] = 0.0
matrix[5] = f
matrix[6] = 0.0
matrix[7] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[10] = (far + near) * rangeReciprocal
matrix[11] = -1.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 2.0 * far * near * rangeReciprocal
matrix[15] = 0.0
return this
}
operator fun get(i: Int): Double = matrix[i]
operator fun get(row: Int, col: Int): Double = matrix[col * 4 + row]
operator fun set(i: Int, value: Double) {
matrix[i] = value
}
operator fun set(row: Int, col: Int, value: Double) {
matrix[col * 4 + row] = value
}
fun setRow(row: Int, vec: Vec3d, w: Double) {
this[row, 0] = vec.x
this[row, 1] = vec.y
this[row, 2] = vec.z
this[row, 3] = w
}
fun setRow(row: Int, value: Vec4d) {
this[row, 0] = value.x
this[row, 1] = value.y
this[row, 2] = value.z
this[row, 3] = value.w
}
fun getRow(row: Int, result: MutableVec4d): MutableVec4d {
result.x = this[row, 0]
result.y = this[row, 1]
result.z = this[row, 2]
result.w = this[row, 3]
return result
}
fun setCol(col: Int, vec: Vec3d, w: Double) {
this[0, col] = vec.x
this[1, col] = vec.y
this[2, col] = vec.z
this[3, col] = w
}
fun setCol(col: Int, value: Vec4d) {
this[0, col] = value.x
this[1, col] = value.y
this[2, col] = value.z
this[3, col] = value.w
}
fun getCol(col: Int, result: MutableVec4d): MutableVec4d {
result.x = this[0, col]
result.y = this[1, col]
result.z = this[2, col]
result.w = this[3, col]
return result
}
fun getOrigin(result: MutableVec3d): MutableVec3d {
result.x = this[0, 3]
result.y = this[1, 3]
result.z = this[2, 3]
return result
}
fun getRotation(result: Mat3f): Mat3f {
result[0, 0] = this[0, 0].toFloat()
result[0, 1] = this[0, 1].toFloat()
result[0, 2] = this[0, 2].toFloat()
result[1, 0] = this[1, 0].toFloat()
result[1, 1] = this[1, 1].toFloat()
result[1, 2] = this[1, 2].toFloat()
result[2, 0] = this[2, 0].toFloat()
result[2, 1] = this[2, 1].toFloat()
result[2, 2] = this[2, 2].toFloat()
return result
}
fun getRotationTransposed(result: Mat3f): Mat3f {
result[0, 0] = this[0, 0].toFloat()
result[0, 1] = this[1, 0].toFloat()
result[0, 2] = this[2, 0].toFloat()
result[1, 0] = this[0, 1].toFloat()
result[1, 1] = this[1, 1].toFloat()
result[1, 2] = this[2, 1].toFloat()
result[2, 0] = this[0, 2].toFloat()
result[2, 1] = this[1, 2].toFloat()
result[2, 2] = this[2, 2].toFloat()
return result
}
fun getRotation(result: MutableVec4d): MutableVec4d {
val trace = this[0, 0] + this[1, 1] + this[2, 2]
if (trace > 0f) {
var s = sqrt(trace + 1f)
result.w = s * 0.5
s = 0.5f / s
result.x = (this[2, 1] - this[1, 2]) * s
result.y = (this[0, 2] - this[2, 0]) * s
result.z = (this[1, 0] - this[0, 1]) * s
} else {
val i = if (this[0, 0] < this[1, 1]) {
if (this[1, 1] < this[2, 2]) { 2 } else { 1 }
} else {
if (this[0, 0] < this[2, 2]) { 2 } else { 0 }
}
val j = (i + 1) % 3
val k = (i + 2) % 3
var s = sqrt(this[i, i] - this[j, j] - this[k, k] + 1f)
result[i] = s * 0.5f
s = 0.5f / s
result.w = (this[k, j] - this[j, k]) * s
result[j] = (this[j, i] + this[i, j]) * s
result[k] = (this[k, i] + this[i, k]) * s
}
return result
}
fun toBuffer(buffer: Float32Buffer): Float32Buffer {
for (i in 0 until 16) {
buffer.put(matrix[i].toFloat())
}
buffer.flip()
return buffer
}
fun toList(): List<Double> {
val list = mutableListOf<Double>()
for (i in 0..15) {
list += matrix[i]
}
return list
}
fun dump() {
for (r in 0..3) {
for (c in 0..3) {
print("${this[r, c]} ")
}
println()
}
}
companion object {
private val tmpMatLock = Any()
private val tmpMatA = Mat4d()
private val tmpMatB = Mat4d()
}
}
class Mat4dStack(val stackSize: Int = DEFAULT_STACK_SIZE) : Mat4d() {
companion object {
const val DEFAULT_STACK_SIZE = 32
}
private var stackIndex = 0
private val stack = DoubleArray(16 * stackSize)
fun push(): Mat4dStack {
if (stackIndex >= stackSize) {
throw KoolException("Matrix stack overflow")
}
val offset = stackIndex * 16
for (i in 0 .. 15) {
stack[offset + i] = matrix[i]
}
stackIndex++
return this
}
fun pop(): Mat4dStack {
if (stackIndex <= 0) {
throw KoolException("Matrix stack underflow")
}
stackIndex--
val offset = stackIndex * 16
for (i in 0 .. 15) {
matrix[i] = stack[offset + i]
}
return this
}
fun reset(): Mat4dStack {
stackIndex = 0
setIdentity()
return this
}
} | apache-2.0 | 948a2ba8c135882a35893338e767fb68 | 30.892361 | 145 | 0.482072 | 3.012683 | false | false | false | false |
FTL-Lang/FTL-Compiler | src/main/kotlin/com/thomas/needham/ftl/utils/GlobalFunctions.kt | 1 | 8202 | /*
The MIT License (MIT)
FTL-Compiler Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.utils
import com.thomas.needham.ftl.utils.Tuple3
import java.io.*
typealias EvaluateStringParams = Tuple3<Int, StringBuilder, Array<Char>>
/**
* Static object containing useful utility functions which are accessible from the global scope
*/
object GlobalFunctions {
@JvmStatic inline fun <reified INNER> array2d(sizeOuter: Int, sizeInner: Int, noinline innerInit: (Int) -> INNER): Array<Array<INNER>> = Array(sizeOuter) { Array<INNER>(sizeInner, innerInit) }
@JvmStatic fun array2dOfInt(sizeOuter: Int, sizeInner: Int): Array<IntArray> = Array(sizeOuter) { IntArray(sizeInner) }
@JvmStatic fun array2dOfShort(sizeOuter: Int, sizeInner: Int): Array<ShortArray> = Array(sizeOuter) { ShortArray(sizeInner) }
@JvmStatic fun array2dOfLong(sizeOuter: Int, sizeInner: Int): Array<LongArray> = Array(sizeOuter) { LongArray(sizeInner) }
@JvmStatic fun array2dOfByte(sizeOuter: Int, sizeInner: Int): Array<ByteArray> = Array(sizeOuter) { ByteArray(sizeInner) }
@JvmStatic fun array2dOfChar(sizeOuter: Int, sizeInner: Int): Array<CharArray> = Array(sizeOuter) { CharArray(sizeInner) }
@JvmStatic fun array2dOfFloat(sizeOuter: Int, sizeInner: Int): Array<FloatArray> = Array(sizeOuter) { FloatArray(sizeInner) }
@JvmStatic fun array2dOfDouble(sizeOuter: Int, sizeInner: Int): Array<DoubleArray> = Array(sizeOuter) { DoubleArray(sizeInner) }
@JvmStatic fun array2dOfBoolean(sizeOuter: Int, sizeInner: Int): Array<BooleanArray> = Array(sizeOuter) { BooleanArray(sizeInner) }
val CONSOLE_COLOUR_RESET = "\u001B[0m"
val CONSOLE_COLOUR_BLACK = "\u001B[30m"
val CONSOLE_COLOUR_RED = "\u001B[31m"
val CONSOLE_COLOUR_GREEN = "\u001B[32m"
val CONSOLE_COLOUR_YELLOW = "\u001B[33m"
val CONSOLE_COLOUR_BLUE = "\u001B[34m"
val CONSOLE_COLOUR_PURPLE = "\u001B[35m"
val CONSOLE_COLOUR_CYAN = "\u001B[36m"
val CONSOLE_COLOUR_WHITE = "\u001B[37m"
/**
* Returns a binary files contents
* @param path the path of the file to return
* @return The Contents of the file
*/
@Throws(IOException::class)
@JvmStatic fun fileToString(path: String): String {
val builder = StringBuilder()
val reader = BufferedReader(FileReader(path))
var line: String?
line = reader.readLine()
while (line != null) {
builder.append(line).append('\n')
line = reader.readLine()
}
reader.close()
return builder.toString()
}
/**
* Returns a text files contents
* @param path the path of the file to return
* @return The Contents of the file
* @throws IOException
* @throws FileNotFoundException
*/
@Throws(IOException::class, FileNotFoundException::class)
fun ReadAllText(file: File): String {
if (file.isDirectory || !file.canRead()) {
throw FileNotFoundException("Invalid File: ${file.path}")
}
val fr: FileReader = FileReader(file)
val br: BufferedReader = BufferedReader(fr)
val contents = br.readText()
if (contents.isNullOrBlank() || contents.isNullOrEmpty())
println("File is Empty: ${file.path}")
br.close()
fr.close()
return contents
}
/**
* Extension method for Double that safely tries to parse a double
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Double.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toDouble()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Float that safely tries to parse a float
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Float.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toFloat()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Int that safely tries to parse a int
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Int.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toInt()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Long that safely tries to parse a long
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Long.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toLong()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Short that safely tries to parse a short
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Short.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toShort()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Byte that safely tries to parse a byte
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Byte.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toByte()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Int that safely tries to decode a int
* @param value the value to parse
* @return true if the parse succeeded false if the decode failed
*/
fun Int.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
Integer.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Long that safely tries to decode a long
* @param value the value to parse
* @return true if the parse succeeded false if the decode failed
*/
fun Long.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Long.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Short that safely tries to decode a short
* @param value the value to Decode
* @param base the base of the number
* @return true if the Decode succeeded false if the decode failed
*/
fun Short.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Short.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Byte that safely tries to decode a byte
* @param value the value to Decode
* @param base the base of the number
* @return true if the Decode succeeded false if the decode failed
*/
fun Byte.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Byte.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
} | mit | aa6f07192a626cc47d43d04b050e06d7 | 32.757202 | 193 | 0.718971 | 3.876181 | false | false | false | false |
ncoe/rosetta | Product_of_divisors/Kotlin/src/main/kotlin/ProductOfDivisors.kt | 1 | 910 | import kotlin.math.pow
private fun divisorCount(n: Long): Long {
var nn = n
var total: Long = 1
// Deal with powers of 2 first
while (nn and 1 == 0L) {
++total
nn = nn shr 1
}
// Odd prime factors up to the square root
var p: Long = 3
while (p * p <= nn) {
var count = 1L
while (nn % p == 0L) {
++count
nn /= p
}
total *= count
p += 2
}
// If n > 1 then it's prime
if (nn > 1) {
total *= 2
}
return total
}
private fun divisorProduct(n: Long): Long {
return n.toDouble().pow(divisorCount(n) / 2.0).toLong()
}
fun main() {
val limit: Long = 50
println("Product of divisors for the first $limit positive integers:")
for (n in 1..limit) {
print("%11d".format(divisorProduct(n)))
if (n % 5 == 0L) {
println()
}
}
}
| mit | 2e368a84987ef8541941d8c92aaf933b | 20.666667 | 74 | 0.492308 | 3.48659 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/decoys/DecoyFqNames.kt | 3 | 1758 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.lower.decoys
import androidx.compose.compiler.plugins.kotlin.ComposeCallableIds
import androidx.compose.compiler.plugins.kotlin.ComposeClassIds
import androidx.compose.compiler.plugins.kotlin.ComposeFqNames
object DecoyClassIds {
val Decoy = ComposeClassIds.internalClassIdFor("Decoy")
val DecoyImplementation = ComposeClassIds.internalClassIdFor("DecoyImplementation")
val DecoyImplementationDefaultsBitMask =
ComposeClassIds.internalClassIdFor("DecoyImplementationDefaultsBitMask")
}
object DecoyCallableIds {
val illegalDecoyCallException =
ComposeCallableIds.internalTopLevelCallableId("illegalDecoyCallException")
}
object DecoyFqNames {
val Decoy = DecoyClassIds.Decoy.asSingleFqName()
val DecoyImplementation = DecoyClassIds.DecoyImplementation.asSingleFqName()
val DecoyImplementationDefaultsBitMask =
DecoyClassIds.DecoyImplementationDefaultsBitMask.asSingleFqName()
val CurrentComposerIntrinsic = ComposeFqNames.fqNameFor("\$get-currentComposer\$\$composable")
val key = ComposeFqNames.fqNameFor("key\$composable")
}
| apache-2.0 | 6bab50e1fefc37ee31eb2ddd0445e816 | 39.883721 | 98 | 0.790102 | 4.738544 | false | false | false | false |
HughG/yested | src/main/kotlin/net/yested/utils/Moment.kt | 2 | 5681 | package net.yested.utils
@JsName("moment")
external private fun moment_js(): MomentJs = definedExternally
@JsName("moment")
external private fun moment_js(millisecondsSinceUnixEpoch: Long): MomentJs = definedExternally
@JsName("moment")
external private fun moment_js(input: String, format: String): MomentJs = definedExternally
@JsName("Moment")
external class MomentJs {
fun format(formatString: String? = definedExternally): String = definedExternally
fun valueOf(): Long = definedExternally
fun millisecond(value: Int? = definedExternally): Int = definedExternally
fun second(value: Int? = definedExternally): Int = definedExternally
fun minute(value: Int? = definedExternally): Int = definedExternally
fun hour(value: Int? = definedExternally): Int = definedExternally
fun date(value: Int? = definedExternally): Int = definedExternally
fun day(value: Int? = definedExternally): Int = definedExternally
fun weekday(value: Int? = definedExternally): Int = definedExternally
fun isoWeekday(value: Int? = definedExternally): Int = definedExternally
fun dayOfYear(value: Int? = definedExternally): Int = definedExternally
fun week(value: Int? = definedExternally): Int = definedExternally
fun isoWeek(value: Int? = definedExternally): Int = definedExternally
fun month(value: Int? = definedExternally): Int = definedExternally
fun quarter(value: Int? = definedExternally): Int = definedExternally
fun year(value: Int? = definedExternally): Int = definedExternally
fun weekYear(value: Int? = definedExternally): Int = definedExternally
fun isoWeekYear(value: Int? = definedExternally): Int = definedExternally
fun weeksInYear(): Int = definedExternally
fun locale(localeName: String): Unit = definedExternally
fun unix():Int = definedExternally
fun unix(t:Int): Unit = definedExternally
}
class Moment(private val moment: MomentJs) {
fun format(format: String): String = moment.format(format)
fun format(format: FormatString): String = moment.format(format.toString())
val millisecondsSinceUnixEpoch: Long
get() = moment.valueOf()
var unix: Int
get() = moment.unix()
set(value) {
moment.unix(value)
}
var millisecond: Int
get() = moment.millisecond()
set(value) {
moment.millisecond(value)
}
var second: Int
get() = moment.second()
set(value) {
moment.second(value)
}
var minute: Int
get() = moment.minute()
set(value) {
moment.minute(value)
}
var hour: Int
get() = moment.hour()
set(value) {
moment.hour(value)
}
var dayOfMonth: Int
get() = moment.date()
set(value) {
moment.date(value)
}
var dayOfYear: Int
get() = moment.dayOfYear()
set(value) {
moment.dayOfYear(value)
}
var month: Int
get() = moment.month()
set(value) {
moment.month(value)
}
var year: Int
get() = moment.year()
set(value) {
moment.year(value)
}
companion object {
fun now(): Moment = Moment(moment_js())
fun parse(input: String, format: String): Moment = Moment(moment_js(input, format))
fun parseMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment{
requireNotNull(millisecondsSinceUnixEpoch)
return Moment(moment_js(millisecondsSinceUnixEpoch))
}
fun setLocale(localeName: String) {
moment_js().locale(localeName)
}
}
}
class FormatElement (val str: String) {
fun plus(b: FormatElement): FormatString {
return FormatString(arrayListOf(this, b))
}
operator fun plus(b: String): FormatString {
return FormatString(arrayListOf(this, FormatElement(b)))
}
}
class FormatString(private val elements: MutableList<FormatElement> = arrayListOf()) {
operator fun plus(b: FormatElement): FormatString {
elements.add(b)
return FormatString(elements)
}
operator fun plus(b: String): FormatString {
elements.add(FormatElement(b))
return FormatString(elements)
}
override fun toString(): String = elements.map { it.str }.joinToString(separator = "")
}
class Digit(private val oneDigitFactory: ()->FormatElement, private val twoDigitsFactory: ()->FormatElement, private val fourDigitsFactory: ()->FormatElement) {
val oneDigit: FormatElement
get() = oneDigitFactory()
val twoDigits: FormatElement
get() = twoDigitsFactory()
val fourDigits: FormatElement
get() = fourDigitsFactory()
}
class FormatStringBuilder() {
val year: Digit = Digit({throw UnsupportedOperationException("bla")}, {FormatElement("YY")}, {FormatElement("YYYY")})
val month: Digit = Digit({FormatElement("M")}, {FormatElement("MM")}, {throw UnsupportedOperationException()})
val dayOfMonth: Digit = Digit({FormatElement("D")}, {FormatElement("DD")}, {throw UnsupportedOperationException()})
val hour24: Digit = Digit({FormatElement("H")}, {FormatElement("HH")}, {throw UnsupportedOperationException()})
val hour12: Digit = Digit({FormatElement("h")}, {FormatElement("hh")}, {throw UnsupportedOperationException()})
val minutes: Digit = Digit({FormatElement("m")}, {FormatElement("mm")}, {throw UnsupportedOperationException()})
val seconds: Digit = Digit({FormatElement("s")}, {FormatElement("ss")}, {throw UnsupportedOperationException()})
}
fun format(init: FormatStringBuilder.() -> FormatString): FormatString {
return FormatStringBuilder().init()
} | mit | 0a1ee92c43255044d06742cc31acaaca | 35.658065 | 160 | 0.669248 | 4.798142 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/units/Temperature.kt | 3 | 4305 | /*
* 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.health.connect.client.units
/** Represents a unit of temperature. Supported units:
*
* - Celsius - see [Temperature.celsius], [Double.celsius]
* - Fahrenheit - see [Temperature.fahrenheit], [Double.fahrenheit]
**/
class Temperature private constructor(
private val value: Double,
private val type: Type,
) : Comparable<Temperature> {
/** Returns the temperature in Celsius degrees. */
@get:JvmName("getCelsius")
val inCelsius: Double
get() =
when (type) {
Type.CELSIUS -> value
Type.FAHRENHEIT -> (value - 32.0) / 1.8
}
/** Returns the temperature in Fahrenheit degrees. */
@get:JvmName("getFahrenheit")
val inFahrenheit: Double
get() =
when (type) {
Type.CELSIUS -> value * 1.8 + 32.0
Type.FAHRENHEIT -> value
}
override fun compareTo(other: Temperature): Int =
if (type == other.type) {
value.compareTo(other.value)
} else {
inCelsius.compareTo(other.inCelsius)
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Temperature) return false
if (value != other.value) return false
if (type != other.type) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = value.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String = "$value ${type.title}"
companion object {
/** Creates [Temperature] with the specified value in Celsius degrees. */
@JvmStatic fun celsius(value: Double): Temperature = Temperature(value, Type.CELSIUS)
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@JvmStatic fun fahrenheit(value: Double): Temperature = Temperature(value, Type.FAHRENHEIT)
}
private enum class Type {
CELSIUS {
override val title: String = "Celsius"
},
FAHRENHEIT {
override val title: String = "Fahrenheit"
};
abstract val title: String
}
}
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Double.celsius: Temperature
get() = Temperature.celsius(value = this)
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Long.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Float.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Int.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Double.fahrenheit: Temperature
get() = Temperature.fahrenheit(value = this)
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Long.fahrenheit: Temperature
get() = toDouble().fahrenheit
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Float.fahrenheit: Temperature
get() = toDouble().fahrenheit
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Int.fahrenheit: Temperature
get() = toDouble().fahrenheit
| apache-2.0 | 307cc6b417117e4330296d173382e662 | 30.654412 | 99 | 0.654123 | 4.503138 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/solver/binderprovider/LiveDataQueryResultBinderProvider.kt | 3 | 2067 | /*
* Copyright (C) 2017 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.room.solver.binderprovider
import androidx.room.ext.LifecyclesTypeNames
import androidx.room.compiler.processing.XRawType
import androidx.room.compiler.processing.XType
import androidx.room.processor.Context
import androidx.room.solver.ObservableQueryResultBinderProvider
import androidx.room.solver.query.result.LiveDataQueryResultBinder
import androidx.room.solver.query.result.QueryResultAdapter
import androidx.room.solver.query.result.QueryResultBinder
class LiveDataQueryResultBinderProvider(context: Context) :
ObservableQueryResultBinderProvider(context) {
private val liveDataType: XRawType? by lazy {
context.processingEnv.findType(LifecyclesTypeNames.LIVE_DATA)?.rawType
}
override fun extractTypeArg(declared: XType): XType = declared.typeArguments.first()
override fun create(
typeArg: XType,
resultAdapter: QueryResultAdapter?,
tableNames: Set<String>
): QueryResultBinder {
return LiveDataQueryResultBinder(
typeArg = typeArg,
tableNames = tableNames,
adapter = resultAdapter
)
}
override fun matches(declared: XType): Boolean =
declared.typeArguments.size == 1 && isLiveData(declared)
private fun isLiveData(declared: XType): Boolean {
if (liveDataType == null) {
return false
}
return declared.rawType.isAssignableFrom(liveDataType!!)
}
} | apache-2.0 | 2e5e5f97b64c0c88715b8a82932610fd | 35.280702 | 88 | 0.735849 | 4.762673 | false | false | false | false |
GunoH/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/USerializableInspectionBase.kt | 2 | 2466 | // 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.codeInspection
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.psi.PsiClass
import com.intellij.psi.util.InheritanceUtil
import com.siyeh.InspectionGadgetsBundle
import com.siyeh.ig.BaseInspection.formatString
import com.siyeh.ig.BaseInspection.parseString
import com.siyeh.ig.psiutils.SerializationUtils
import com.siyeh.ig.ui.UiUtils
import org.jdom.Element
import org.jetbrains.annotations.NonNls
import org.jetbrains.uast.UElement
import javax.swing.JComponent
import javax.swing.JPanel
abstract class USerializableInspectionBase(vararg hint: Class<out UElement>) : AbstractBaseUastLocalInspectionTool(*hint) {
var ignoreAnonymousInnerClasses = false
private var superClassString: @NonNls String = "java.awt.Component"
private val superClassList: MutableList<String> = mutableListOf()
override fun readSettings(node: Element) {
super.readSettings(node)
parseString(superClassString, superClassList)
}
override fun writeSettings(node: Element) {
if (superClassList.isNotEmpty()) superClassString = formatString(superClassList)
super.writeSettings(node)
}
override fun createOptionsPanel(): JComponent? =
MultipleCheckboxOptionsPanel(this).apply {
val chooserList = UiUtils.createTreeClassChooserList(
superClassList,
InspectionGadgetsBundle.message("ignore.classes.in.hierarchy.column.name"),
InspectionGadgetsBundle.message("choose.class")
)
UiUtils.setComponentSize(chooserList, 7, 25)
add(chooserList, "growx, wrap")
val additionalOptions = createAdditionalOptions()
for (additionalOption in additionalOptions) {
val constraints = if (additionalOption is JPanel) "grow, wrap" else "growx, wrap"
add(additionalOption, constraints)
}
addCheckbox(InspectionGadgetsBundle.message("ignore.anonymous.inner.classes"), "ignoreAnonymousInnerClasses")
}
private fun createAdditionalOptions(): Array<JComponent> = emptyArray()
protected fun isIgnoredSubclass(aClass: PsiClass): Boolean {
if (SerializationUtils.isDirectlySerializable(aClass)) return false
for (superClassName in superClassList) if (InheritanceUtil.isInheritor(aClass, superClassName)) return true
return false
}
override fun getAlternativeID(): String = "serial"
}
| apache-2.0 | 6621faecff13414dc93e62aaf8f40f75 | 39.42623 | 123 | 0.778183 | 4.724138 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.