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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vase4kin/TeamCityApp | app/src/test/java/com/github/vase4kin/teamcityapp/changes/presenter/ChangesPresenterImplTest.kt | 1 | 4640 | /*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.changes.presenter
import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener
import com.github.vase4kin.teamcityapp.base.tracker.ViewTracker
import com.github.vase4kin.teamcityapp.changes.api.Changes
import com.github.vase4kin.teamcityapp.changes.data.ChangesDataManager
import com.github.vase4kin.teamcityapp.changes.extractor.ChangesValueExtractor
import com.github.vase4kin.teamcityapp.changes.view.ChangesView
import com.github.vase4kin.teamcityapp.utils.any
import com.github.vase4kin.teamcityapp.utils.capture
import com.github.vase4kin.teamcityapp.utils.eq
import com.mugen.MugenCallbacks
import org.hamcrest.core.Is.`is`
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.runners.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ChangesPresenterImplTest {
@Captor
private lateinit var onLoadMoreListenerArgumentCaptor: ArgumentCaptor<MugenCallbacks>
@Captor
private lateinit var onChangesLoadingListener: ArgumentCaptor<OnLoadingListener<List<Changes.Change>>>
@Captor
private lateinit var onLoadingListenerArgumentCaptor: ArgumentCaptor<OnLoadingListener<Int>>
@Mock
private lateinit var loadingListener: OnLoadingListener<List<Changes.Change>>
@Mock
private lateinit var view: ChangesView
@Mock
internal lateinit var dataManager: ChangesDataManager
@Mock
internal lateinit var tracker: ViewTracker
@Mock
internal lateinit var valueExtractor: ChangesValueExtractor
private lateinit var presenter: ChangesPresenterImpl
@Before
fun setUp() {
presenter = ChangesPresenterImpl(view, dataManager, tracker, valueExtractor)
}
@Test
fun testInitViews() {
`when`(dataManager.canLoadMore()).thenReturn(false)
presenter.initViews()
verify(view).setLoadMoreListener(capture(onLoadMoreListenerArgumentCaptor))
val onLoadMoreListener = onLoadMoreListenerArgumentCaptor.value
assertThat(onLoadMoreListener.hasLoadedAllItems(), `is`(true))
verify(dataManager).canLoadMore()
onLoadMoreListener.onLoadMore()
verify(view).addLoadMore()
verify(dataManager).loadMore(capture(onChangesLoadingListener))
assertThat(presenter.isLoadMoreLoading, `is`(true))
val onChangesLoadingListener = this.onChangesLoadingListener.value
val changes = emptyList<Changes.Change>()
onChangesLoadingListener.onSuccess(changes)
verify(view).removeLoadMore()
verify(view).addMoreBuilds(any())
assertThat(presenter.isLoadMoreLoading, `is`(false))
onChangesLoadingListener.onFail("error")
verify(view, times(2)).removeLoadMore()
verify(view).showRetryLoadMoreSnackBar()
assertThat(presenter.isLoadMoreLoading, `is`(false))
}
@Test
fun testLoadData() {
`when`(valueExtractor.url).thenReturn("url")
presenter.loadData(loadingListener, false)
verify(valueExtractor).url
verify(dataManager).loadLimited(eq("url"), eq(loadingListener), eq(false))
verifyNoMoreInteractions(view, dataManager, tracker, valueExtractor)
}
@Test
fun testCreateModel() {
val changes = mutableListOf<Changes.Change>()
assertThat(presenter.createModel(changes).itemCount, `is`(0))
}
@Test
fun testOnViewsCreated() {
`when`(valueExtractor.url).thenReturn("url")
presenter.onViewsCreated()
verify(valueExtractor, times(2)).url
verify(dataManager).loadTabTitle(eq("url"), capture(onLoadingListenerArgumentCaptor))
val listener = onLoadingListenerArgumentCaptor.value
listener.onSuccess(1)
verify(dataManager).postChangeTabTitleEvent(eq(1))
listener.onFail("error")
verifyNoMoreInteractions(valueExtractor)
}
}
| apache-2.0 | 2e5e12d8f42c90caec403b6b932d9bd1 | 37.032787 | 106 | 0.747414 | 4.594059 | false | true | false | false |
roylanceMichael/yaorm | buildSrc/src/main/java/utilities/FileProcessUtilities.kt | 1 | 7511 | package utilities
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream
import org.apache.commons.io.IOUtils
import java.io.*
import java.util.*
object FileProcessUtilities {
private const val Space = " "
private const val TempDirectory = "java.io.tmpdir"
private val knownApplicationLocations = HashMap<String, String>()
private val whitespaceRegex = Regex("\\s+")
fun buildCommand(application: String, allArguments: String):List<String> {
val returnList = ArrayList<String>()
val actualApplicationLocation = getActualLocation(application)
print(actualApplicationLocation)
if (actualApplicationLocation.isEmpty()) {
returnList.add(application)
}
else {
returnList.add(actualApplicationLocation)
}
val splitArguments = allArguments.split(whitespaceRegex)
returnList.addAll(splitArguments)
return returnList
}
fun readFile(path: String): String {
val foundFile = File(path)
return foundFile.readText()
}
fun writeFile(file: String, path: String) {
val newFile = File(path)
newFile.writeText(file)
}
fun handleProcess(process: ProcessBuilder, name: String) {
try {
process.redirectError(ProcessBuilder.Redirect.INHERIT)
process.redirectOutput(ProcessBuilder.Redirect.INHERIT)
process.start().waitFor()
println("finished $name")
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fun buildReport(process: Process): MusubiModel.ProcessReport {
val returnReport = MusubiModel.ProcessReport.newBuilder()
val inputWriter = StringWriter()
val errorWriter = StringWriter()
IOUtils.copy(process.inputStream, inputWriter)
IOUtils.copy(process.errorStream, errorWriter)
return returnReport.setErrorOutput(errorWriter.toString()).setNormalOutput(inputWriter.toString()).build()
}
fun executeProcess(location: String,
application: String,
allArguments: String): MusubiModel.ProcessReport {
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
val actualCommand = buildCommand(application, allArguments).joinToString(Space)
val tempScript = buildTempScript(location, actualCommand)
tempFile.writeText(tempScript)
try {
Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
val report = buildReport(process).toBuilder()
report.normalOutput = report.normalOutput + "\n" + tempScript
return report.build()
}
finally {
tempFile.delete()
}
}
fun executeScript(location: String, application: String, script: String): MusubiModel.ProcessReport {
val tempScript = File(getTempDirectory(), UUID.randomUUID().toString())
tempScript.writeText(script)
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
val actualCommand = buildCommand(application, tempScript.absolutePath).joinToString(Space)
val tempExecuteScript = buildTempScript(location, actualCommand)
tempFile.writeText(tempExecuteScript)
try {
Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempScript.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
val report = buildReport(process).toBuilder()
report.normalOutput = report.normalOutput + "\n" + tempScript
return report.build()
}
finally {
tempScript.delete()
tempFile.delete()
}
}
fun createTarFromDirectory(inputDirectory: String, outputFile: String, directoriesToExclude: HashSet<String>): Boolean {
val directory = File(inputDirectory)
if (!directory.exists()) {
return false
}
val outputStream = FileOutputStream(File(outputFile))
val bufferedOutputStream = BufferedOutputStream(outputStream)
val gzipOutputStream = GzipCompressorOutputStream(bufferedOutputStream)
val tarOutputStream = TarArchiveOutputStream(gzipOutputStream)
try {
addFileToTarGz(tarOutputStream, inputDirectory, "", directoriesToExclude)
}
finally {
tarOutputStream.finish()
tarOutputStream.close()
gzipOutputStream.close()
bufferedOutputStream.close()
outputStream.close()
}
return true
}
fun getActualLocation(application: String): String {
if (knownApplicationLocations.containsKey(application)) {
return knownApplicationLocations[application]!!
}
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
tempFile.writeText("""#!/usr/bin/env bash
. ~/.bash_profile
. ~/.bashrc
which $application""")
print(tempFile.readText())
val inputWriter = StringWriter()
try {
Runtime.getRuntime().exec("${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
IOUtils.copy(process.inputStream, inputWriter)
return inputWriter.toString().trim()
}
finally {
inputWriter.close()
tempFile.delete()
}
}
private fun addFileToTarGz(tarOutputStream: TarArchiveOutputStream, path: String, base: String, directoriesToExclude: HashSet<String>) {
val fileOrDirectory = File(path)
if (directoriesToExclude.contains(fileOrDirectory.name)) {
return
}
val entryName: String
if (base.isEmpty()) {
entryName = "."
}
else {
entryName = base + fileOrDirectory.name
}
val tarEntry = TarArchiveEntry(fileOrDirectory, entryName)
tarOutputStream.putArchiveEntry(tarEntry)
if (fileOrDirectory.isDirectory) {
fileOrDirectory.listFiles()?.forEach { file ->
addFileToTarGz(tarOutputStream, file.absolutePath, "$entryName/", directoriesToExclude)
}
}
else {
val inputStream = FileInputStream(fileOrDirectory)
try {
IOUtils.copy(inputStream, tarOutputStream)
}
finally {
inputStream.close()
tarOutputStream.closeArchiveEntry()
}
}
}
private fun getTempDirectory(): String {
return System.getProperty(TempDirectory)
}
private fun buildTempScript(location: String, actualCommand: String): String {
return """#!/usr/bin/env bash
. ~/.bash_profile
. ~/.bashrc
pushd $location
$actualCommand
"""
}
} | mit | 83197775fcd204954682a35b667fb01b | 33.617512 | 140 | 0.641193 | 5.158654 | false | false | false | false |
rumboalla/apkupdater | app/src/main/java/com/apkupdater/repository/googleplay/GooglePlayRepository.kt | 1 | 3434 | package com.apkupdater.repository.googleplay
import android.content.Context
import android.content.res.Resources
import android.util.Log
import com.apkupdater.R
import com.apkupdater.model.ui.AppInstalled
import com.apkupdater.model.ui.AppSearch
import com.apkupdater.model.ui.AppUpdate
import com.apkupdater.util.aurora.NativeDeviceInfoProvider
import com.apkupdater.util.aurora.OkHttpClientAdapter
import com.apkupdater.util.ioScope
import com.apkupdater.util.orZero
import com.dragons.aurora.playstoreapiv2.AppDetails
import com.dragons.aurora.playstoreapiv2.DocV2
import com.dragons.aurora.playstoreapiv2.GooglePlayAPI
import com.dragons.aurora.playstoreapiv2.PlayStoreApiBuilder
import com.dragons.aurora.playstoreapiv2.SearchIterator
import kotlinx.coroutines.async
import org.koin.core.KoinComponent
import org.koin.core.inject
@Suppress("BlockingMethodInNonBlockingContext")
class GooglePlayRepository: KoinComponent {
private val dispenserUrl = "http://auroraoss.com:8080"
private val context: Context by inject()
private val api: GooglePlayAPI by lazy { getApi(context) }
fun updateAsync(apps: Sequence<AppInstalled>) = ioScope.async {
runCatching {
val details = api.bulkDetails(apps.map { it.packageName }.toList())
val updates = mutableListOf<AppUpdate>()
// TODO: Filter experimental?
details.entryList.forEach { entry ->
runCatching {
apps.getApp(entry.doc.details.appDetails.packageName)?.let { app ->
if (entry.doc.details.appDetails.versionCode > app.versionCode.orZero()) {
updates.add(AppUpdate.from(app, entry.doc.details.appDetails))
}
}
}.onFailure { Log.e("GooglePlayRepository", "updateAsync", it) }
}
updates
}.fold(onSuccess = { Result.success(it) }, onFailure = { Result.failure(it) })
}
fun searchAsync(text: String) = ioScope.async {
runCatching {
SearchIterator(api, text).next()?.toList().orEmpty().map { AppSearch.from(it) }.shuffled().take(10).sortedBy { it.name }.toList()
}.fold(onSuccess = { Result.success(it) }, onFailure = { Result.failure(it) })
}
fun getDownloadUrl(packageName: String, versionCode: Int, oldVersionCode: Int): String {
val p = api.purchase(packageName, versionCode, 1)
val d = api.delivery(packageName, oldVersionCode, versionCode, 1, p.downloadToken)
return d.appDeliveryData.downloadUrl
}
private fun getProvider(context: Context) = NativeDeviceInfoProvider().apply {
setContext(context)
setLocaleString(Resources.getSystem().configuration.locale.toString())
}
private fun getApi(context: Context): GooglePlayAPI = PlayStoreApiBuilder().apply {
httpClient = OkHttpClientAdapter(context)
tokenDispenserUrl = dispenserUrl
deviceInfoProvider = getProvider(context)
}.build()
private fun AppSearch.Companion.from(doc: DocV2) = AppSearch(
doc.title,
"play",
doc.imageList.find { image -> image.imageType == GooglePlayAPI.IMAGE_TYPE_APP_ICON }?.imageUrl.orEmpty(),
doc.details.appDetails.packageName,
R.drawable.googleplay_logo,
doc.details.appDetails.packageName,
doc.details.appDetails.versionCode
)
private fun AppUpdate.Companion.from(app: AppInstalled, entry: AppDetails) = AppUpdate(
app.name,
app.packageName,
entry.versionString,
entry.versionCode,
app.version,
app.versionCode,
"play",
R.drawable.googleplay_logo
)
private fun Sequence<AppInstalled>.getApp(packageName: String) = this.find { it.packageName == packageName }
} | gpl-3.0 | a143a2d1255c7cea8a276ffc828c3d07 | 34.412371 | 132 | 0.764997 | 3.595812 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/view/activities/LessonActivity.kt | 1 | 3211 | package net.tlalka.fiszki.view.activities
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import butterknife.BindView
import butterknife.OnClick
import net.tlalka.fiszki.R
import net.tlalka.fiszki.domain.controllers.LessonController
import net.tlalka.fiszki.domain.utils.ValidUtils
import net.tlalka.fiszki.model.dto.parcel.LessonDto
import net.tlalka.fiszki.model.types.LanguageType
import net.tlalka.fiszki.view.fragments.LanguageDialogFragment
import net.tlalka.fiszki.view.navigations.Navigator
import javax.inject.Inject
class LessonActivity : BasePageActivity(), LanguageDialogFragment.DialogListener {
@BindView(R.id.lesson_topic)
lateinit var lessonTopic: TextView
@BindView(R.id.lesson_progress)
lateinit var lessonProgress: TextView
@BindView(R.id.lesson_show_word)
lateinit var lessonShowWord: Button
@BindView(R.id.lesson_check_word)
lateinit var lessonCheckWord: Button
@Inject
lateinit var lessonController: LessonController
@Inject
lateinit var navigator: Navigator
@Inject
lateinit var lessonDto: LessonDto
public override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
super.setContentView(R.layout.lesson_activity)
super.activityComponent.inject(this)
runActivity()
}
private fun runActivity() {
lessonTopic.text = getString(R.string.lesson_topic, lessonDto.lessonIndex, lessonDto.lessonName)
generateView()
}
private fun generateView() {
if (lessonController.hasNextWord()) {
lessonProgress.text = lessonController.getLessonStatus()
lessonShowWord.text = lessonController.getNextWord()
lessonCheckWord.text = getText(R.string.lesson_check_word)
} else {
showLessonSummary()
}
}
private fun showLessonSummary() {
lessonController.updateLessonDto(lessonDto)
lessonController.updateLessonProgress()
navigator.openLessonScoreActivity(this, lessonDto)
navigator.finish(this)
}
@OnClick(R.id.lesson_check_word)
fun onCheckWordClick(@Suppress("UNUSED_PARAMETER") view: View?) {
val word = this.lessonController.getTranslateWord()
if (ValidUtils.isNotNull(word)) {
lessonCheckWord.text = word.value
} else {
LanguageDialogFragment
.getInstance(lessonController.getLanguages())
.show(fragmentManager, LanguageDialogFragment::class.java.name)
}
}
override fun onLanguageSelected(languageType: LanguageType) {
lessonController.setTranslation(languageType)
onCheckWordClick(lessonCheckWord)
}
@OnClick(R.id.button_correct)
fun onCorrectClick(@Suppress("UNUSED_PARAMETER") view: View) {
lessonController.correctAnswer()
generateView()
}
@OnClick(R.id.button_incorrect)
fun onIncorrectClick(@Suppress("UNUSED_PARAMETER") view: View) {
lessonController.incorrectAnswer()
generateView()
}
}
| mit | fe1e41d368ef39571c4fc93ae6307707 | 30.11 | 104 | 0.685768 | 4.541726 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/project/project.kt | 1 | 12484 | package com.github.czyzby.setup.data.project
import com.badlogic.gdx.Files
import com.badlogic.gdx.utils.GdxRuntimeException
import com.github.czyzby.setup.data.files.*
import com.github.czyzby.setup.data.gradle.GradleFile
import com.github.czyzby.setup.data.gradle.RootGradleFile
import com.github.czyzby.setup.data.langs.Java
import com.github.czyzby.setup.data.libs.unofficial.USL
import com.github.czyzby.setup.data.platforms.Android
import com.github.czyzby.setup.data.platforms.Assets
import com.github.czyzby.setup.data.platforms.Platform
import com.github.czyzby.setup.data.templates.KtxTemplate
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.AdvancedData
import com.github.czyzby.setup.views.BasicProjectData
import com.github.czyzby.setup.views.ExtensionsData
import com.github.czyzby.setup.views.LanguagesData
import com.kotcrab.vis.ui.util.OsUtils
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
/**
* Contains data about the generated project.
* @author MJ
*/
class Project(val basic: BasicProjectData, val platforms: Map<String, Platform>, val advanced: AdvancedData,
val languages: LanguagesData, val extensions: ExtensionsData, val template: Template) {
private val gradleFiles: Map<String, GradleFile>
val files = mutableListOf<ProjectFile>()
val rootGradle: RootGradleFile
val properties = mutableMapOf(
"org.gradle.daemon" to "true",
"org.gradle.jvmargs" to "-Xms128m -Xmx512m",
"org.gradle.configureondemand" to "true")
val postGenerationTasks = mutableListOf<(Project) -> Unit>()
val gwtInherits = mutableSetOf<String>()
val androidPermissions = mutableSetOf<String>()
val reflectedClasses = mutableSetOf<String>()
val reflectedPackages = mutableSetOf<String>()
// README.md:
var readmeDescription = ""
val gradleTaskDescriptions = mutableMapOf<String, String>()
init {
gradleFiles = mutableMapOf<String, GradleFile>()
rootGradle = RootGradleFile(this)
platforms.forEach { gradleFiles[it.key] = it.value.createGradleFile(this) }
addBasicGradleTasksDescriptions()
}
private fun addBasicGradleTasksDescriptions() {
if (advanced.generateReadme) {
arrayOf("idea" to "generates IntelliJ project data.",
"cleanIdea" to "removes IntelliJ project data.",
"eclipse" to "generates Eclipse project data.",
"cleanEclipse" to "removes Eclipse project data.",
"clean" to "removes `build` folders, which store compiled classes and built archives.",
"test" to "runs unit tests (if any).",
"build" to "builds sources and archives of every project.",
"--daemon" to "thanks to this flag, Gradle daemon will be used to run chosen tasks.",
"--offline" to "when using this flag, cached dependency archives will be used.",
"--continue" to "when using this flag, errors will not stop the tasks from running.",
"--refresh-dependencies" to "this flag forces validation of all dependencies. Useful for snapshot versions.")
.forEach { gradleTaskDescriptions[it.first] = it.second }
}
}
fun hasPlatform(id: String): Boolean = platforms.containsKey(id)
fun getGradleFile(id: String): GradleFile = gradleFiles.get(id)!!
fun addGradleTaskDescription(task: String, description: String) {
if (advanced.generateReadme) {
gradleTaskDescriptions[task] = description
}
}
fun generate() {
addBasicFiles()
template.apply(this)
addExtensions()
addJvmLanguagesSupport()
addPlatforms()
addSkinAssets()
addReadmeFile()
saveProperties()
saveFiles()
// Invoking post-generation tasks:
postGenerationTasks.forEach { it(this) }
}
private fun addBasicFiles() {
// Adding global assets folder:
files.add(SourceDirectory(Assets.ID, ""))
// Adding .gitignore:
files.add(CopiedFile(path = ".gitignore", original = path("generator", "gitignore")))
}
private fun addJvmLanguagesSupport() {
Java().initiate(this) // Java is supported by default.
languages.getSelectedLanguages().forEach {
it.initiate(this)
properties[it.id + "Version"] = languages.getVersion(it.id)
}
languages.appendSelectedLanguagesVersions(this)
}
private fun addExtensions() {
extensions.getSelectedOfficialExtensions().forEach { it.initiate(this) }
extensions.getSelectedThirdPartyExtensions().forEach { it.initiate(this) }
}
private fun addPlatforms() {
platforms.values.forEach { it.initiate(this) }
SettingsFile(platforms.values).save(basic.destination)
}
private fun saveFiles() {
rootGradle.save(basic.destination)
gradleFiles.values.forEach { it.save(basic.destination) }
files.forEach { it.save(basic.destination) }
}
private fun saveProperties() {
// Adding LibGDX version property:
properties["gdxVersion"] = advanced.gdxVersion
PropertiesFile(properties).save(basic.destination)
}
private fun addSkinAssets() {
if (advanced.generateSkin || advanced.generateUsl) {
// Adding raw assets directory:
files.add(SourceDirectory("raw", "ui"))
// Adding GUI assets directory:
files.add(SourceDirectory(Assets.ID, "ui"))
}
if (advanced.generateSkin) {
// Adding JSON only if USL is not checked
if (!advanced.generateUsl) {
files.add(CopiedFile(projectName = Assets.ID, path = path("ui", "skin.json"),
original = path("generator", "assets", "ui", "skin.json")))
}
// Android does not support classpath fonts loading through skins.
// Explicitly copying Arial font if Android platform is included:
if (hasPlatform(Android.ID)) {
arrayOf("png", "fnt").forEach {
val path = path("com", "badlogic", "gdx", "utils", "arial-15.$it")
files.add(CopiedFile(projectName = Assets.ID, path = path, original = path,
fileType = Files.FileType.Classpath))
}
}
// README task description:
gradleTaskDescriptions["pack"] = "packs GUI assets from `raw/ui`. Saves the atlas file at `assets/ui`."
// Copying raw assets - internal files listing doesn't work, so we're hard-coding raw/ui content:
arrayOf("check.png", "check-on.png", "dot.png", "knob-h.png", "knob-v.png", "line-h.png", "line-v.png",
"pack.json", "rect.png", "select.9.png", "square.png", "tree-minus.png", "tree-plus.png",
"window-border.9.png", "window-resize.9.png").forEach {
files.add(CopiedFile(projectName = "raw", path = "ui${File.separator}$it",
original = path("generator", "raw", "ui", it)))
}
// Appending "pack" task to root Gradle:
postGenerationTasks.add({
basic.destination.child(rootGradle.path).writeString("""
// Run `gradle pack` task to generate skin.atlas file at assets/ui.
import com.badlogic.gdx.tools.texturepacker.TexturePacker
task pack << {
// Note that if you need multiple atlases, you can duplicate the
// TexturePacker.process invocation and change paths to generate
// additional atlases with this task.
TexturePacker.process(
'raw/ui', // Raw assets path.
'assets/ui', // Output directory.
'skin' // Name of the generated atlas (without extension).
)
}""", true, "UTF-8");
})
}
if (advanced.generateUsl) {
// Make sure USL extension is added
USL().initiate(this)
// Copy USL file:
files.add(CopiedFile(projectName = "raw", path = path("ui", "skin.usl"),
original = path("generator", "raw", "ui", "skin.usl")))
gradleTaskDescriptions["compileSkin"] = "compiles USL skin from `raw/ui`. Saves the result json file at `assets/ui`."
// Add "compileSkin" task to root Gradle file:
postGenerationTasks.add({
basic.destination.child(rootGradle.path).writeString("""
// Run `gradle compileSkin` task to generate skin.json at assets/ui.
task compileSkin << {
// Convert USL skin file into JSON
String[] uslArgs = [
projectDir.path + '/raw/ui/skin.usl', // Input USL file
projectDir.path + '/assets/ui/skin.json' // Output JSON file
]
com.kotcrab.vis.usl.Main.main(uslArgs)
}""", true, "UTF-8");
})
}
if (advanced.generateSkin && advanced.generateUsl) {
gradleTaskDescriptions["packAndCompileSkin"] = "pack GUI assets and compiles USL skin from `raw/ui`. Saves the result files at `assets/ui`."
// Add "packAndCompileSkin" task to root Gradle file:
postGenerationTasks.add({
basic.destination.child(rootGradle.path).writeString("""
// Run `gradle packAndCompileSkin` to generate skin atlas and compile USL into JSON
task packAndCompileSkin(dependsOn: [pack, compileSkin])""", true, "UTF-8");
})
}
}
private fun addReadmeFile() {
if (advanced.generateReadme) {
files.add(SourceFile(projectName = "", fileName = "README.md", content = """# ${basic.name}
A [LibGDX](http://libgdx.badlogicgames.com/) project generated with [gdx-setup](https://github.com/czyzby/gdx-setup).
${readmeDescription}
## Gradle
This project uses [Gradle](http://gradle.org/) to manage dependencies. ${if (advanced.addGradleWrapper)
"Gradle wrapper was included, so you can run Gradle tasks using `gradlew.bat` or `./gradlew` commands."
else
"Gradle wrapper was not included by default, so you have to install Gradle locally."} Useful Gradle tasks and flags:
${gradleTaskDescriptions.map { "- `${it.key}`: ${it.value}" }.sorted().joinToString(separator = "\n")}
Note that most tasks that are not specific to a single project can be run with `name:` prefix, where the `name` should be replaced with the ID of a specific project.
For example, `core:clean` removes `build` folder only from the `core` project."""))
}
}
fun includeGradleWrapper(logger: ProjectLogger) {
if (advanced.addGradleWrapper) {
arrayOf("gradlew", "gradlew.bat", path("gradle", "wrapper", "gradle-wrapper.jar"),
path("gradle", "wrapper", "gradle-wrapper.properties")).forEach {
CopiedFile(path = it, original = path("generator", it)).save(basic.destination)
}
basic.destination.child("gradlew").file().setExecutable(true)
basic.destination.child("gradlew.bat").file().setExecutable(true)
logger.logNls("copyGradle")
}
val gradleTasks = advanced.gradleTasks
if (gradleTasks.isNotEmpty()) {
logger.logNls("runningGradleTasks")
val commands = determineGradleCommand() + advanced.gradleTasks
logger.log(commands.joinToString(separator = " "))
val process = ProcessBuilder(*commands).directory(basic.destination.file())
.redirectErrorStream(true).start()
val stream = BufferedReader(InputStreamReader(process.inputStream))
var line = stream.readLine();
while (line != null) {
logger.log(line)
line = stream.readLine();
}
process.waitFor()
if (process.exitValue() != 0) {
throw GdxRuntimeException("Gradle process ended with non-zero value.")
}
}
}
private fun determineGradleCommand(): Array<String> {
return if (OsUtils.isWindows()) {
arrayOf("cmd", "/c", if (advanced.addGradleWrapper) "gradlew" else "gradle")
} else {
arrayOf(if (advanced.addGradleWrapper) "./gradlew" else "gradle")
}
}
}
interface ProjectLogger {
fun log(message: String)
fun logNls(bundleLine: String)
}
| unlicense | 12ed5ab94971a8da96120ed2b340ce28 | 42.498258 | 165 | 0.630487 | 4.366562 | false | false | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt | 1 | 8461 | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This was copied from https://github.com/google/google-java-format and modified extensively to
* work for Kotlin formatting
*/
package com.facebook.ktfmt.kdoc
import com.facebook.ktfmt.kdoc.KDocToken.Type.CODE_BLOCK_MARKER
import com.facebook.ktfmt.kdoc.KDocToken.Type.HEADER_OPEN_TAG
import com.facebook.ktfmt.kdoc.KDocToken.Type.LIST_ITEM_OPEN_TAG
import com.facebook.ktfmt.kdoc.KDocToken.Type.PARAGRAPH_OPEN_TAG
import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.BLANK_LINE
import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.CONDITIONAL_WHITESPACE
import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.NEWLINE
import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.NONE
import com.facebook.ktfmt.kdoc.KDocWriter.RequestedWhitespace.WHITESPACE
import com.google.common.base.Strings
import com.google.common.collect.Ordering
import com.google.common.collect.Sets.immutableEnumSet
/**
* Stateful object that accepts "requests" and "writes," producing formatted Javadoc.
*
* Our Javadoc formatter doesn't ever generate a parse tree, only a stream of tokens, so the writer
* must compute and store the answer to questions like "How many levels of nested HTML list are we
* inside?"
*/
internal class KDocWriter(blockIndentCount: Int, private val maxLineLength: Int) {
/**
* Tokens that are always pinned to the following token. For example, `<p>` in `<p>Foo bar` (never
* `<p> Foo bar` or `<p>\nFoo bar`).
*
* This is not the only kind of "pinning" that we do: See also the joining of LITERAL tokens done
* by the lexer. The special pinning here is necessary because these tokens are not of type
* LITERAL (because they require other special handling).
*/
private val START_OF_LINE_TOKENS =
immutableEnumSet(LIST_ITEM_OPEN_TAG, PARAGRAPH_OPEN_TAG, HEADER_OPEN_TAG)
private val output = StringBuilder()
private val blockIndent = Strings.repeat(" ", blockIndentCount + 1)
private var remainingOnLine: Int = 0
private var atStartOfLine: Boolean = false
private var inCodeBlock: Boolean = false
private var requestedWhitespace = NONE
/**
* Requests whitespace between the previously written token and the next written token. The
* request may be honored, or it may be overridden by a request for "more significant" whitespace,
* like a newline.
*/
fun requestWhitespace() {
requestWhitespace(WHITESPACE)
}
fun writeBeginJavadoc() {
/*
* JavaCommentsHelper will make sure this is indented right. But it seems sensible enough that,
* if our input starts with ∕✱✱, so too does our output.
*/
appendTrackingLength("/**")
}
fun writeEndJavadoc() {
requestCloseCodeBlockMarker()
output.append("\n")
appendTrackingLength(blockIndent)
appendTrackingLength("*/")
}
fun writeListItemOpen(token: KDocToken) {
requestCloseCodeBlockMarker()
requestNewline()
writeToken(token)
}
fun writePreOpen(token: KDocToken) {
requestBlankLine()
writeToken(token)
}
fun writePreClose(token: KDocToken) {
writeToken(token)
requestBlankLine()
}
fun writeCodeOpen(token: KDocToken) {
writeToken(token)
}
fun writeCodeClose(token: KDocToken) {
writeToken(token)
}
fun writeTableOpen(token: KDocToken) {
requestBlankLine()
writeToken(token)
}
fun writeTableClose(token: KDocToken) {
writeToken(token)
requestBlankLine()
}
fun writeTag(token: KDocToken) {
requestNewline()
writeToken(token)
}
fun writeCodeLine(token: KDocToken) {
requestOpenCodeBlockMarker()
requestNewline()
if (token.value.isNotEmpty()) {
writeToken(token)
}
}
/** Adds a code block marker if we are not in a code block currently */
private fun requestCloseCodeBlockMarker() {
if (inCodeBlock) {
this.requestedWhitespace = NEWLINE
writeExplicitCodeBlockMarker(KDocToken(CODE_BLOCK_MARKER, "```"))
}
}
/** Adds a code block marker if we are in a code block currently */
private fun requestOpenCodeBlockMarker() {
if (!inCodeBlock) {
this.requestedWhitespace = NEWLINE
writeExplicitCodeBlockMarker(KDocToken(CODE_BLOCK_MARKER, "```"))
}
}
fun writeExplicitCodeBlockMarker(token: KDocToken) {
requestNewline()
writeToken(token)
requestNewline()
inCodeBlock = !inCodeBlock
}
fun writeLiteral(token: KDocToken) {
requestCloseCodeBlockMarker()
writeToken(token)
}
fun writeMarkdownLink(token: KDocToken) {
writeToken(token)
}
override fun toString(): String {
return output.toString()
}
fun requestBlankLine() {
requestWhitespace(BLANK_LINE)
}
fun requestNewline() {
requestWhitespace(NEWLINE)
}
private fun requestWhitespace(requestedWhitespace: RequestedWhitespace) {
this.requestedWhitespace =
Ordering.natural<Comparable<*>>().max(requestedWhitespace, this.requestedWhitespace)
}
/**
* The kind of whitespace that has been requested between the previous and next tokens. The order
* of the values is significant: It goes from lowest priority to highest. For example, if the
* previous token requests [.BLANK_LINE] after it but the next token requests only [ ][.NEWLINE]
* before it, we insert [.BLANK_LINE].
*/
internal enum class RequestedWhitespace {
NONE,
/**
* Add one space, only if the next token seems like a word In contrast, punctuation like a dot
* does need a space before it.
*/
CONDITIONAL_WHITESPACE,
/** Add one space, e.g. " " */
WHITESPACE,
/** Break to the next line */
NEWLINE,
/** Add a whole blank line between the two lines of content */
BLANK_LINE,
}
private fun writeToken(token: KDocToken) {
if (requestedWhitespace == BLANK_LINE) {
writeBlankLine()
requestedWhitespace = NONE
} else if (requestedWhitespace == NEWLINE) {
writeNewline()
requestedWhitespace = NONE
}
val needWhitespace =
when (requestedWhitespace) {
WHITESPACE -> true
CONDITIONAL_WHITESPACE -> token.value.first().isLetterOrDigit()
else -> false
}
/*
* Write a newline if necessary to respect the line limit. (But if we're at the beginning of the
* line, a newline won't help. Or it might help but only by separating "<p>veryverylongword,"
* which goes against our style.)
*/
if (!atStartOfLine && token.length() + (if (needWhitespace) 1 else 0) > remainingOnLine) {
writeNewline()
}
if (!atStartOfLine && needWhitespace) {
appendTrackingLength(" ")
}
appendTrackingLength(token.value)
requestedWhitespace = NONE
if (!START_OF_LINE_TOKENS.contains(token.type)) {
atStartOfLine = false
}
}
private fun writeBlankLine() {
output.append("\n")
appendTrackingLength(blockIndent)
appendTrackingLength("*")
writeNewline()
}
private fun writeNewline() {
output.append("\n")
remainingOnLine = maxLineLength
appendTrackingLength(blockIndent)
appendTrackingLength("* ")
atStartOfLine = true
}
/*
* TODO(cpovirk): We really want the number of "characters," not chars. Figure out what the
* right way of measuring that is (grapheme count (with BreakIterator?)? sum of widths of all
* graphemes? I don't think that our style guide is specific about this.). Moreover, I am
* probably brushing other problems with surrogates, etc. under the table. Hopefully I mostly
* get away with it by joining all non-space, non-tab characters together.
*
* Possibly the "width" question has no right answer:
* http://denisbider.blogspot.com/2015/09/when-monospace-fonts-arent-unicode.html
*/
private fun appendTrackingLength(str: String) {
output.append(str)
remainingOnLine -= str.length
}
}
| apache-2.0 | 249290d91fb9fc5043ec5fa90be48b25 | 29.523466 | 100 | 0.705618 | 4.154791 | false | false | false | false |
gmillz/SlimFileManager | manager/src/main/java/com/slim/slimfilemanager/utils/FileUtil.kt | 1 | 9351 | package com.slim.slimfilemanager.utils
import android.content.Context
import android.os.Build
import android.support.v4.provider.DocumentFile
import android.text.TextUtils
import android.util.Log
import com.slim.slimfilemanager.settings.SettingsProvider
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import org.apache.commons.io.IOUtils
import java.io.DataOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStream
object FileUtil {
fun copyFile(context: Context, f: String, fol: String): Boolean {
val file = File(f)
val folder = File(fol)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
var fis: FileInputStream? = null
var os: OutputStream? = null
try {
fis = FileInputStream(file)
val target = DocumentFile.fromFile(folder)
os = context.contentResolver.openOutputStream(target.uri)
IOUtils.copy(fis, os)
return true
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
fis?.close()
if (os != null) {
os.flush()
os.close()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}
if (file.exists()) {
if (!folder.exists()) {
if (!mkdir(context, folder)) return false
}
try {
if (file.isDirectory) {
FileUtils.copyDirectoryToDirectory(file, folder)
} else if (file.isFile) {
FileUtils.copyFileToDirectory(file, folder)
}
return true
} catch (e: IOException) {
return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT,
false)
&& RootUtils.isRootAvailable && RootUtils.copyFile(f, fol))
}
} else {
return false
}
}
fun moveFile(context: Context, source: String, destination: String): Boolean {
if (TextUtils.isEmpty(source) || TextUtils.isEmpty(destination)) {
return false
}
val file = File(source)
val folder = File(destination)
try {
FileUtils.moveFileToDirectory(file, folder, true)
return true
} catch (e: IOException) {
return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)
&& RootUtils.isRootAvailable && RootUtils.moveFile(source, destination))
}
}
fun deleteFile(context: Context, path: String): Boolean {
try {
FileUtils.forceDelete(File(path))
return true
} catch (e: IOException) {
return (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)
&& RootUtils.isRootAvailable && RootUtils.deleteFile(path))
}
}
fun getFileProperties(context: Context, file: File): Array<String>? {
var info: Array<String>? = null
val out: RootUtils.CommandOutput?
if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT,
false) && RootUtils.isRootAvailable) {
out = RootUtils.runCommand("ls -l " + file.absolutePath)
} else {
out = runCommand("ls -l " + file.absolutePath)
}
if (out == null) return null
if (TextUtils.isEmpty(out.error) && out.exitCode == 0) {
info = getAttrs(out.output!!)
}
return info
}
private fun getAttrs(string: String): Array<String> {
if (string.length < 44) {
throw IllegalArgumentException("Bad ls -l output: $string")
}
val chars = string.toCharArray()
val results = emptyArray<String>()
var ind = 0
val current = StringBuilder()
Loop@ for (i in chars.indices) {
when (chars[i]) {
' ', '\t' -> if (current.length != 0) {
results[ind] = current.toString()
ind++
current.setLength(0)
if (ind == 10) {
results[ind] = string.substring(i).trim({ it <= ' ' })
break@Loop
}
}
else -> current.append(chars[i])
}
}
return results
}
fun runCommand(cmd: String): RootUtils.CommandOutput {
val output = RootUtils.CommandOutput()
try {
val process = Runtime.getRuntime().exec("sh")
val os = DataOutputStream(
process.outputStream)
os.writeBytes(cmd + "\n")
os.writeBytes("exit\n")
os.flush()
output.exitCode = process.waitFor()
output.output = IOUtils.toString(process.inputStream)
output.error = IOUtils.toString(process.errorStream)
if (output.exitCode != 0 || !TextUtils.isEmpty(output.error)) {
Log.e("Shell Error, cmd: $cmd", "error: " + output.error!!)
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
return output
}
fun changeGroupOwner(context: Context, file: File, owner: String, group: String): Boolean {
try {
var useRoot = false
if (!file.canWrite() && SettingsProvider.getBoolean(context,
SettingsProvider.KEY_ENABLE_ROOT, false)
&& RootUtils.isRootAvailable) {
useRoot = true
RootUtils.remountSystem("rw")
}
if (useRoot) {
RootUtils.runCommand("chown " + owner + "." + group + " "
+ file.absolutePath)
} else {
runCommand("chown " + owner + "." + group + " "
+ file.absolutePath)
}
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
fun applyPermissions(context: Context, file: File, permissions: Permissions): Boolean {
try {
var useSu = false
if (!file.canWrite() && SettingsProvider.getBoolean(context,
SettingsProvider.KEY_ENABLE_ROOT, false)
&& RootUtils.isRootAvailable) {
useSu = true
RootUtils.remountSystem("rw")
}
if (useSu) {
RootUtils.runCommand("chmod " + permissions.octalPermissions + " "
+ file.absolutePath)
} else {
runCommand("chmod " + permissions.octalPermissions + " "
+ file.absolutePath)
}
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
fun mkdir(context: Context, dir: File): Boolean {
if (dir.exists()) {
return false
}
if (dir.mkdirs()) {
return true
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val document = DocumentFile.fromFile(dir.parentFile)
if (document.exists()) {
if (document.createDirectory(dir.absolutePath)!!.exists()) {
return true
}
}
}
}
return (SettingsProvider.getBoolean(context,
SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable
&& RootUtils.createFolder(dir))
}
fun getExtension(fileName: String): String {
return FilenameUtils.getExtension(fileName)
}
fun removeExtension(s: String): String {
return FilenameUtils.removeExtension(File(s).name)
}
fun writeFile(context: Context, content: String, file: File, encoding: String) {
if (file.canWrite()) {
try {
FileUtils.write(file, content, encoding)
} catch (e: IOException) {
// ignore
}
} else if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)) {
RootUtils.writeFile(file, content)
}
}
fun renameFile(context: Context, oldFile: File, newFile: File) {
if (oldFile.renameTo(newFile)) {
return
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val document = DocumentFile.fromFile(oldFile)
if (document.renameTo(newFile.absolutePath)) {
return
}
}
}
if (SettingsProvider.getBoolean(context, SettingsProvider.KEY_ENABLE_ROOT, false)) {
RootUtils.renameFile(oldFile, newFile)
}
}
fun getFileSize(file: File): Long {
return file.length()
}
}
| gpl-3.0 | 60d4048674fa09126ba258aabe03ff79 | 31.695804 | 99 | 0.521869 | 4.895812 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/ElementEditsTable.kt | 1 | 1501 | package de.westnordost.streetcomplete.data.osm.edits
object ElementEditsTable {
const val NAME = "osm_element_edits"
object Columns {
const val ID = "id"
const val QUEST_TYPE = "quest_type"
const val ELEMENT_ID = "element_id"
const val ELEMENT_TYPE = "element_type"
const val ELEMENT = "element"
const val GEOMETRY = "geometry"
const val SOURCE = "source"
const val LATITUDE = "latitude"
const val LONGITUDE = "longitude"
const val CREATED_TIMESTAMP = "created"
const val IS_SYNCED = "synced"
const val ACTION = "action"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Columns.QUEST_TYPE} varchar(255) NOT NULL,
${Columns.ELEMENT_ID} int NOT NULL,
${Columns.ELEMENT_TYPE} varchar(255) NOT NULL,
${Columns.ELEMENT} text NOT NULL,
${Columns.GEOMETRY} text NOT NULL,
${Columns.SOURCE} varchar(255) NOT NULL,
${Columns.LATITUDE} double NOT NULL,
${Columns.LONGITUDE} double NOT NULL,
${Columns.CREATED_TIMESTAMP} int NOT NULL,
${Columns.IS_SYNCED} int NOT NULL,
${Columns.ACTION} text
);"""
const val ELEMENT_INDEX_CREATE = """
CREATE INDEX osm_element_edits_index ON $NAME (
${Columns.ELEMENT_TYPE},
${Columns.ELEMENT_ID}
);
"""
}
| gpl-3.0 | 3981d282be54837458b6c99fc547025f | 33.906977 | 60 | 0.575616 | 4.288571 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/jvmMain/kotlin/nl/adaptivity/util/HttpMessage.kt | 1 | 18753 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util
import net.devrieze.util.Iterators
import net.devrieze.util.security.SimplePrincipal
import net.devrieze.util.toString
import net.devrieze.util.webServer.HttpRequest
import net.devrieze.util.webServer.parseMultipartFormDataTo
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import nl.adaptivity.xmlutil.*
import org.w3c.dom.Document
import java.io.*
import java.io.IOException
import java.net.URLDecoder
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.security.Principal
import java.util.*
import javax.activation.DataHandler
import javax.activation.DataSource
import javax.servlet.http.HttpServletRequest
import javax.xml.bind.annotation.XmlAttribute
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.Map.Entry
import nl.adaptivity.xmlutil.serialization.XmlSerialName
import nl.adaptivity.xmlutil.xmlserializable.writeChildren
// TODO change this to handle regular request bodies.
/*
@Element(name = HttpMessage.ELEMENTLOCALNAME, nsUri = HttpMessage.NAMESPACE, attributes = arrayOf(
Attribute("user")),
children = arrayOf(
Child(property = "queries",
type = Query::class),
Child(property = "posts",
type = Post::class),
Child(
name = HttpMessage.BODYELEMENTLOCALNAME, property = "body",
type = AnyType::class)))
@XmlDeserializer(HttpMessage.Factory::class)
*/
class HttpMessage {
private val _queries: MutableMap<String, String>// by lazy { HashMap<String, String>() }
@XmlSerialName("query", HttpMessage.NAMESPACE, "http")
val queries: Collection<Query>
get() = QueryCollection(_queries)
private val _post: MutableMap<String, String>// by lazy { HashMap<String, String>() }
@XmlSerialName("post", HttpMessage.NAMESPACE, "http")
val posts: Collection<Post>
get() = PostCollection(_post)
@XmlSerialName("body", HttpMessage.NAMESPACE, "http")
var body: ICompactFragment? = null
private val _byteContent: MutableList<ByteContentDataSource> by lazy { ArrayList<ByteContentDataSource>() }
val byteContent: List<ByteContentDataSource>
get() = _byteContent
@get:XmlAttribute
var requestPath: String? = null
var contextPath: String? = null
var method: String? = null
var contentType: String? = null
private set
var characterEncoding: Charset? = null
private set
private val _headers: Map<String, List<String>>
val headers: Map<String, List<String>>
get() = Collections.unmodifiableMap(_headers)
private val _attachments: MutableMap<String, DataSource>
val attachments: Map<String, DataSource>
get() = Collections.unmodifiableMap(_attachments)
var userPrincipal: Principal? = null
internal set
val content: XmlReader?
@Throws(XmlException::class)
get() = body?.getXmlReader()
@XmlSerialName("user", HttpMessage.NAMESPACE, "http")
internal var user: String?
get() = userPrincipal?.name
set(name) {
userPrincipal = name?.let { SimplePrincipal(it) }
}
class ByteContentDataSource(
private var name: String?,
private var contentType: String?,
var byteContent: ByteArray?
) : DataSource {
val dataHandler: DataHandler
get() = DataHandler(this)
fun setContentType(contentType: String) {
this.contentType = contentType
}
override fun getContentType(): String? {
return contentType
}
fun setName(name: String) {
this.name = name
}
override fun getName(): String? {
return name
}
@Throws(IOException::class)
override fun getInputStream(): InputStream {
return ByteArrayInputStream(byteContent!!)
}
@Throws(IOException::class)
override fun getOutputStream(): OutputStream {
throw UnsupportedOperationException("Byte content is not writable")
}
override fun toString(): String {
return "ByteContentDataSource [name=" + name + ", contentType=" + contentType + ", byteContent=\"" + String(
byteContent!!
) + "\"]"
}
}
private class QueryIterator(iterator: MutableIterator<Entry<String, String>>) : PairBaseIterator<Query>(iterator) {
override fun newItem(): Query {
return Query(mIterator!!.next())
}
}
private class PostIterator(iterator: MutableIterator<Entry<String, String>>) : PairBaseIterator<Post>(iterator) {
override fun newItem(): Post {
return Post(mIterator!!.next())
}
}
abstract class PairBaseIterator<T : PairBase>(protected val mIterator: MutableIterator<Entry<String, String>>?) :
MutableIterator<T> {
override fun hasNext(): Boolean {
return mIterator != null && mIterator.hasNext()
}
override fun next(): T {
if (mIterator == null) {
throw NoSuchElementException()
}
return newItem()
}
protected abstract fun newItem(): T
override fun remove() {
if (mIterator == null) {
throw IllegalStateException("Removing elements from empty collection")
}
mIterator.remove()
}
}
class Query : PairBase {
protected constructor() {}
constructor(entry: Entry<String, String>) : super(entry) {}
companion object {
private val ELEMENTNAME = QName(NAMESPACE, "query", "http")
}
}
class Post : PairBase {
protected constructor()
constructor(entry: Entry<String, String>) : super(entry) {}
companion object {
private val ELEMENTNAME = QName(NAMESPACE, "post", "http")
}
}
abstract class PairBase {
@XmlSerialName("name", HttpMessage.NAMESPACE, "http")
lateinit var key: String
lateinit var value: String
protected constructor() {}
protected constructor(entry: Entry<String, String>) {
key = entry.key
value = entry.value
}
override fun hashCode(): Int {
val prime = 31
var result = 1
result = prime * result + key.hashCode()
result = prime * result + value.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other == null) {
return false
}
if (javaClass != other.javaClass) {
return false
}
other as PairBase?
if (key != other.key) {
return false
}
if (value != other.value) {
return false
}
return true
}
}
class QueryCollection(map: MutableMap<String, String>) : PairBaseCollection<Query>(map) {
override fun iterator(): MutableIterator<Query> {
return QueryIterator(map.entries.iterator())
}
}
class PostCollection(map: MutableMap<String, String>) : PairBaseCollection<Post>(map) {
override fun iterator(): MutableIterator<Post> {
return PostIterator(map.entries.iterator())
}
}
abstract class PairBaseCollection<T : PairBase>(map: MutableMap<String, String>?) : AbstractCollection<T>() {
protected var map = map?.toMutableMap() ?: mutableMapOf()
override fun add(element: T): Boolean {
return map.put(element.key, element.value) != null
}
override fun clear() {
map.clear()
}
override operator fun contains(element: T): Boolean {
return element.value == map[element.key]
}
override fun isEmpty(): Boolean {
return map.isEmpty()
}
override fun remove(element: T): Boolean {
val candidate = map[element.key]
if (candidate != null && candidate == element.value) {
map.remove(element.key)
return true
} else {
return false
}
}
override val size: Int get() = map.size
}
private constructor() {
_headers = HashMap()
_post = HashMap()
_queries = HashMap()
_attachments = HashMap()
}
@Throws(IOException::class)
constructor(request: HttpServletRequest) {
_headers = getHeaders(request)
_queries = toQueries(request.queryString)
var post: MutableMap<String, String>? = null
var attachments: MutableMap<String, DataSource> = HashMap()
userPrincipal = request.userPrincipal
method = request.method
val pathInfo = request.pathInfo
requestPath = if (pathInfo == null || pathInfo.length == 0) request.servletPath else pathInfo
contextPath = request.contextPath
if ("POST" == request.method || "PUT" == request.method) {
contentType = request.contentType
characterEncoding = null
contentType?.let { contentType ->
var i = contentType.indexOf(';')
if (i >= 0) {
var tail: String = contentType
this.contentType = contentType.substring(0, i).trim { it <= ' ' }
while (i >= 0) {
tail = tail.substring(i + 1).trim { it <= ' ' }
i = tail.indexOf(';')
val param: String
if (i > 0) {
param = tail.substring(0, i).trim { it <= ' ' }
} else {
param = tail
}
val j = param.indexOf('=')
if (j >= 0) {
val paramName = param.substring(0, j).trim { it <= ' ' }
if (paramName == "charset") {
characterEncoding = Charset.forName(param.substring(j + 1).trim { it <= ' ' })
}
}
}
}
}
if (characterEncoding == null) {
characterEncoding = getCharacterEncoding(request)
}
if (characterEncoding == null) {
characterEncoding = DEFAULT_CHARSSET
}
val isMultipart = contentType != null && contentType!!.startsWith("multipart/")
if ("application/x-www-form-urlencoded" == contentType) {
post = toQueries(String(getBody(request)))
} else if (isMultipart) {
request.inputStream.parseMultipartFormDataTo(attachments, HttpRequest.mimeType(request.contentType))
} else {
val bytes = getBody(request)
val xml: Document
val isXml =
XmlStreaming.newReader(InputStreamReader(ByteArrayInputStream(bytes), characterEncoding!!)).isXml()
if (!isXml) {
addByteContent(bytes, request.contentType)
} else {
val decoder = characterEncoding!!.newDecoder()
val buffer = decoder.decode(ByteBuffer.wrap(bytes))
var chars: CharArray? = null
if (buffer.hasArray()) {
chars = buffer.array()
if (chars!!.size > buffer.limit()) {
chars = null
}
}
if (chars == null) {
chars = CharArray(buffer.limit())
buffer.get(chars)
}
body = CompactFragment(emptyList(), chars)
}
}
}
this._post = post ?: mutableMapOf()
this._attachments = attachments ?: mutableMapOf()
}
protected fun getCharacterEncoding(request: HttpServletRequest): Charset {
val name = request.characterEncoding ?: return DEFAULT_CHARSSET
return Charset.forName(request.characterEncoding)
}
private fun addByteContent(byteArray: ByteArray, contentType: String) {
_byteContent.add(ByteContentDataSource(null, contentType, byteArray))
}
/*
* Getters and setters
*/
fun getQuery(name: String): String? {
return if (_queries == null) null else _queries!![name]
}
fun getPosts(name: String): String? {
if (_post != null) {
var result: String? = _post!![name]
if (result == null && _attachments != null) {
val source = _attachments!![name]
if (source != null) {
try {
result = toString(InputStreamReader(source.inputStream, "UTF-8"))
return result
} catch (e: UnsupportedEncodingException) {
throw RuntimeException(e)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
}
return if (_post == null) null else _post!![name]
}
fun getParam(name: String): String? {
val result = getQuery(name)
return result ?: getPosts(name)
}
fun getAttachment(name: String?): DataSource? {
return _attachments[name ?: NULL_KEY]
}
fun getHeaders(name: String): Iterable<String> {
return Collections.unmodifiableList(_headers[name])
}
fun getHeader(name: String): String? {
val list = _headers[name]
return if (list == null || list.size < 1) {
null
} else list[0]
}
companion object {
const val NULL_KEY = "KJJMBZLZKNC<MNCJHASIUJZNCZM>NSJHLCALSNDM<>BNADSBLKH"
const val NAMESPACE = "http://adaptivity.nl/HttpMessage"
const val ELEMENTLOCALNAME = "httpMessage"
val ELEMENTNAME = QName(NAMESPACE, ELEMENTLOCALNAME, "http")
internal const val BODYELEMENTLOCALNAME = "Body"
internal val BODYELEMENTNAME = QName(NAMESPACE, BODYELEMENTLOCALNAME, "http")
private val DEFAULT_CHARSSET = Charset.forName("UTF-8")
/*
* Utility methods
*/
private fun getHeaders(request: HttpServletRequest): Map<String, List<String>> {
val result = HashMap<String, List<String>>()
for (oname in Iterators.toIterable(request.headerNames)) {
val name = oname as String
val values = Iterators.toList(request.getHeaders(name))
result[name] = values
}
return result
}
private fun toQueries(queryString: String?): MutableMap<String, String> {
val result = HashMap<String, String>()
if (queryString == null) {
return result
}
var query: String = queryString
if (query.length > 0 && query[0] == '?') {
/* strip questionmark */
query = query.substring(1)
}
var startPos = 0
var key: String? = null
for (i in 0 until query.length) {
if (key == null) {
if ('=' == query[i]) {
key = query.substring(startPos, i)
startPos = i + 1
}
} else {
if ('&' == query[i] || ';' == query[i]) {
val value: String
try {
value = URLDecoder.decode(query.substring(startPos, i), "UTF-8")
} catch (e: UnsupportedEncodingException) {
throw RuntimeException(e)
}
result[key] = value
key = null
startPos = i + 1
}
}
}
if (key == null) {
key = query.substring(startPos)
if (key.length > 0) {
result[key] = ""
}
} else {
try {
val value = URLDecoder.decode(query.substring(startPos), "UTF-8")
result[key] = value
} catch (e: UnsupportedEncodingException) {
throw RuntimeException(e)
}
}
return result
}
private fun getBody(request: HttpServletRequest): ByteArray {
val contentLength = request.contentLength
val baos: ByteArrayOutputStream =
if (contentLength > 0) ByteArrayOutputStream(contentLength) else ByteArrayOutputStream()
val buffer = ByteArray(0xfffff)
request.inputStream.use { inStream ->
var i: Int = inStream.read(buffer)
while (i >= 0) {
baos.write(buffer, 0, i)
i = inStream.read(buffer)
}
}
return baos.toByteArray()
}
}
}
| lgpl-3.0 | 877b8af3305005aef1f2a340e50d4a59 | 31.784965 | 128 | 0.531702 | 5.203385 | false | false | false | false |
akvo/akvo-flow-mobile | app/src/main/java/org/akvo/flow/presentation/form/view/groups/QuestionViewHolder.kt | 1 | 14648 | /*
* Copyright (C) 2020 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.presentation.form.view.groups
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText
import org.akvo.flow.R
import org.akvo.flow.presentation.form.view.groups.entity.ViewQuestionAnswer
import org.akvo.flow.util.image.GlideImageLoader
import org.akvo.flow.util.image.ImageLoader
sealed class QuestionViewHolder<T : ViewQuestionAnswer>(val view: View) :
RecyclerView.ViewHolder(view) {
abstract fun setUpView(questionAnswer: T, index: Int)
private fun mandatoryText(mandatory: Boolean): String {
return when {
mandatory -> {
"*"
}
else -> {
""
}
}
}
fun setUpTitle(title: String, mandatory: Boolean) {
view.findViewById<TextView>(R.id.questionTitle).text = "$title${mandatoryText(mandatory)}"
}
fun setUpInputText(answer: String, textInputEditText: TextInputEditText) {
if (answer.isEmpty()) {
textInputEditText.visibility = View.GONE
} else {
textInputEditText.visibility = View.VISIBLE
textInputEditText.setText(answer)
}
}
class NumberQuestionViewHolder(singleView: View) :
QuestionViewHolder<ViewQuestionAnswer.NumberViewQuestionAnswer>(singleView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.NumberViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
setUpAnswer(questionAnswer.answer)
setUpRepetition(questionAnswer.requireDoubleEntry, questionAnswer.answer)
}
//TODO: repeated code from number/text... refactor
private fun setUpRepetition(repeated: Boolean, answer: String) {
val repeatedInput = view.findViewById<TextInputEditText>(
R.id.questionResponseRepeated
)
val repeatTitle = view.findViewById<TextView>(
R.id.repeatTitle
)
if (repeated) {
setUpInputText(answer, repeatedInput)
if (answer.isEmpty()) {
repeatTitle.visibility = View.GONE
} else {
repeatTitle.visibility = View.VISIBLE
}
} else {
repeatTitle.visibility = View.GONE
repeatedInput.visibility = View.GONE
}
}
private fun setUpAnswer(answer: String) {
val textInputEditText = view.findViewById<TextInputEditText>(
R.id.questionResponseInput
)
setUpInputText(answer, textInputEditText)
}
}
class TextQuestionViewHolder(singleView: View) :
QuestionViewHolder<ViewQuestionAnswer.FreeTextViewQuestionAnswer>(singleView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.FreeTextViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
setUpAnswer(questionAnswer.answer)
setUpRepetition(questionAnswer.requireDoubleEntry, questionAnswer.answer)
}
private fun setUpAnswer(answer: String) {
val textInputEditText = view.findViewById<TextInputEditText>(
R.id.questionResponseInput
)
setUpInputText(answer, textInputEditText)
}
private fun setUpRepetition(repeatable: Boolean, answer: String) {
val repeatedInput = view.findViewById<TextInputEditText>(
R.id.questionResponseRepeated
)
val repeatTitle = view.findViewById<TextView>(
R.id.repeatTitle
)
if (repeatable) {
setUpInputText(answer, repeatedInput)
if (answer.isEmpty()) {
repeatTitle.visibility = View.GONE
} else {
repeatTitle.visibility = View.VISIBLE
}
} else {
repeatTitle.visibility = View.GONE
repeatedInput.visibility = View.GONE
}
}
}
class PhotoQuestionViewHolder(mediaView: View) :
QuestionViewHolder<ViewQuestionAnswer.PhotoViewQuestionAnswer>(mediaView) {
private val mediaLayout: MediaQuestionLayout = view.findViewById(R.id.preview_container)
override fun setUpView(
questionAnswer: ViewQuestionAnswer.PhotoViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
if (questionAnswer.filePath.isNotEmpty()) {
mediaLayout.visibility = View.VISIBLE
mediaLayout.setUpImageDisplay(index, questionAnswer.filePath)
setupLocation(questionAnswer)
} else {
mediaLayout.visibility = View.GONE
}
}
private fun setupLocation(questionAnswer: ViewQuestionAnswer.PhotoViewQuestionAnswer) {
val locationTv = view.findViewById(R.id.location_info) as TextView
val location = questionAnswer.location
if (location != null) {
val locationText: String = view.context
.getString(
R.string.image_location_coordinates,
location.latitude,
location.longitude
)
locationTv.text = locationText
locationTv.visibility = View.VISIBLE
} else {
locationTv.visibility = View.GONE
}
}
}
class VideoQuestionViewHolder(mediaView: View) :
QuestionViewHolder<ViewQuestionAnswer.VideoViewQuestionAnswer>(mediaView) {
private val mediaLayout: MediaQuestionLayout = view.findViewById(R.id.preview_container)
override fun setUpView(
questionAnswer: ViewQuestionAnswer.VideoViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
if (questionAnswer.filePath.isNotEmpty()) {
mediaLayout.visibility = View.VISIBLE
mediaLayout.setUpImageDisplay(index, questionAnswer.filePath)
} else {
mediaLayout.visibility = View.GONE
}
}
}
class SignatureQuestionViewHolder(signView: View) :
QuestionViewHolder<ViewQuestionAnswer.SignatureViewQuestionAnswer>(signView) {
private val imageIv: ImageView = view.findViewById(R.id.signatureIv)
private val nameTv: TextView = view.findViewById(R.id.signatureTv)
private val questionLayout: LinearLayout = view.findViewById(R.id.questionContentLayout)
private var imageLoader: ImageLoader = GlideImageLoader(view.context)
override fun setUpView(
questionAnswer: ViewQuestionAnswer.SignatureViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
if (questionAnswer.base64ImageString.isNotEmpty() && questionAnswer.name.isNotEmpty()) {
questionLayout.visibility = View.VISIBLE
imageIv.visibility = View.VISIBLE
imageLoader.loadFromBase64String(questionAnswer.base64ImageString, imageIv)
nameTv.text = questionAnswer.name
} else {
questionLayout.visibility = View.GONE
}
}
}
class DateQuestionViewHolder(dateView: View) :
QuestionViewHolder<ViewQuestionAnswer.DateViewQuestionAnswer>(dateView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.DateViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
val textInputEditText = view.findViewById<TextInputEditText>(
R.id.questionResponseInput
)
setUpInputText(questionAnswer.answer, textInputEditText)
}
}
class LocationQuestionViewHolder(locationView: View) :
QuestionViewHolder<ViewQuestionAnswer.LocationViewQuestionAnswer>(locationView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.LocationViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
if (questionAnswer.viewLocation != null && questionAnswer.viewLocation.isValid()) {
view.findViewById<TextInputEditText>(R.id.lat_et)
.setText(questionAnswer.viewLocation.latitude)
view.findViewById<TextInputEditText>(R.id.lon_et)
.setText(questionAnswer.viewLocation.longitude)
view.findViewById<TextInputEditText>(R.id.height_et)
.setText(questionAnswer.viewLocation.altitude)
val accuracy = questionAnswer.viewLocation.accuracy
val accuracyTv = view.findViewById<TextView>(R.id.acc_tv)
if (accuracy.isNotEmpty()) {
accuracyTv.text = accuracy
} else {
accuracyTv.setText(R.string.geo_location_accuracy_default)
}
}
}
}
class ShapeQuestionViewHolder(geoshapeView: View) :
QuestionViewHolder<ViewQuestionAnswer.GeoShapeViewQuestionAnswer>(geoshapeView) {
private val viewShapeBt = view.findViewById<Button>(R.id.view_shape_btn)
private val shapeTv = view.findViewById<TextView>(R.id.geo_shape_captured_text)
override fun setUpView(
questionAnswer: ViewQuestionAnswer.GeoShapeViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
if (questionAnswer.geojsonAnswer.isNotEmpty()) {
viewShapeBt.visibility = View.VISIBLE
shapeTv.visibility = View.VISIBLE
viewShapeBt.setOnClickListener {
val activityContext = view.context
if (activityContext is GeoShapeListener) {
activityContext.viewShape(questionAnswer.geojsonAnswer)
} else {
throw throw IllegalArgumentException("Activity must implement GeoShapeListener")
}
}
} else {
viewShapeBt.visibility = View.GONE
shapeTv.visibility = View.GONE
}
}
}
class OptionsViewHolder(optionsView: View) :
QuestionViewHolder<ViewQuestionAnswer.OptionViewQuestionAnswer>(optionsView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.OptionViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
val optionsQuestionLayout = view.findViewById<OptionsQuestionLayout>(R.id.options_layout)
if (questionAnswer.options.isNotEmpty()){
optionsQuestionLayout.visibility = View.VISIBLE
optionsQuestionLayout.setUpViews(questionAnswer)
} else {
optionsQuestionLayout.visibility = View.GONE
}
}
}
class BarcodeViewHolder(barcodeView: View) :
QuestionViewHolder<ViewQuestionAnswer.BarcodeViewQuestionAnswer>(barcodeView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.BarcodeViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
val barcodesQuestionLayout =
view.findViewById<BarcodesQuestionLayout>(R.id.barcodes_layout)
if (questionAnswer.answers.isNotEmpty()) {
barcodesQuestionLayout.visibility = View.VISIBLE
barcodesQuestionLayout.setUpViews(questionAnswer)
} else {
barcodesQuestionLayout.visibility = View.GONE
}
}
}
class CascadeViewHolder(barcodeView: View) :
QuestionViewHolder<ViewQuestionAnswer.CascadeViewQuestionAnswer>(barcodeView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.CascadeViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
val barcodesQuestionLayout =
view.findViewById<CascadeQuestionLayout>(R.id.barcodes_layout)
if (questionAnswer.answers.isNotEmpty()) {
barcodesQuestionLayout.visibility = View.VISIBLE
barcodesQuestionLayout.setUpViews(questionAnswer)
} else {
barcodesQuestionLayout.visibility = View.GONE
}
}
}
class CaddisflyViewHolder(barcodeView: View) :
QuestionViewHolder<ViewQuestionAnswer.CaddisflyViewQuestionAnswer>(barcodeView) {
override fun setUpView(
questionAnswer: ViewQuestionAnswer.CaddisflyViewQuestionAnswer,
index: Int
) {
setUpTitle(questionAnswer.title, questionAnswer.mandatory)
val barcodesQuestionLayout =
view.findViewById<CaddisflyQuestionLayout>(R.id.caddisfly_layout)
if (questionAnswer.answers.isNotEmpty()) {
barcodesQuestionLayout.visibility = View.VISIBLE
barcodesQuestionLayout.setUpViews(questionAnswer)
} else {
barcodesQuestionLayout.visibility = View.GONE
}
}
}
} | gpl-3.0 | b39708e2e9d3bbb51577cd5858e757b8 | 39.578947 | 105 | 0.628072 | 5.305324 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonMain/src/kotlinx/serialization/PolymorphicSerializer.kt | 1 | 4268 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlinx.serialization.builtins.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.internal.*
import kotlinx.serialization.modules.*
import kotlin.reflect.*
/**
* This class provides support for multiplatform polymorphic serialization for interfaces and abstract classes.
*
* To avoid the most common security pitfalls and reflective lookup (and potential load) of an arbitrary class,
* all serializable implementations of any polymorphic type must be [registered][SerializersModuleBuilder.polymorphic]
* in advance in the scope of base polymorphic type, efficiently preventing unbounded polymorphic serialization
* of an arbitrary type.
*
* Polymorphic serialization is enabled automatically by default for interfaces and [Serializable] abstract classes.
* To enable this feature explicitly on other types, use `@SerializableWith(PolymorphicSerializer::class)`
* or [Polymorphic] annotation on the property.
*
* Usage of the polymorphic serialization can be demonstrated by the following example:
* ```
* abstract class BaseRequest()
* @Serializable
* data class RequestA(val id: Int): BaseRequest()
* @Serializable
* data class RequestB(val s: String): BaseRequest()
*
* abstract class BaseResponse()
* @Serializable
* data class ResponseC(val payload: Long): BaseResponse()
* @Serializable
* data class ResponseD(val payload: ByteArray): BaseResponse()
*
* @Serializable
* data class Message(
* @Polymorphic val request: BaseRequest,
* @Polymorphic val response: BaseResponse
* )
* ```
* In this example, both request and response in `Message` are serializable with [PolymorphicSerializer].
*
* `BaseRequest` and `BaseResponse` are base classes and they are captured during compile time by the plugin.
* Yet [PolymorphicSerializer] for `BaseRequest` should only allow `RequestA` and `RequestB` serializers, and none of the response's serializers.
*
* This is achieved via special registration function in the module:
* ```
* val requestAndResponseModule = SerializersModule {
* polymorphic(BaseRequest::class) {
* subclass(RequestA::class)
* subclass(RequestB::class)
* }
* polymorphic(BaseResponse::class) {
* subclass(ResponseC::class)
* subclass(ResponseD::class)
* }
* }
* ```
*
* @see SerializersModule
* @see SerializersModuleBuilder.polymorphic
*/
@OptIn(ExperimentalSerializationApi::class)
public class PolymorphicSerializer<T : Any>(override val baseClass: KClass<T>) : AbstractPolymorphicSerializer<T>() {
@PublishedApi // See comment in SealedClassSerializer
internal constructor(
baseClass: KClass<T>,
classAnnotations: Array<Annotation>
) : this(baseClass) {
_annotations = classAnnotations.asList()
}
private var _annotations: List<Annotation> = emptyList()
public override val descriptor: SerialDescriptor by lazy(LazyThreadSafetyMode.PUBLICATION) {
buildSerialDescriptor("kotlinx.serialization.Polymorphic", PolymorphicKind.OPEN) {
element("type", String.serializer().descriptor)
element(
"value",
buildSerialDescriptor("kotlinx.serialization.Polymorphic<${baseClass.simpleName}>", SerialKind.CONTEXTUAL)
)
annotations = _annotations
}.withContext(baseClass)
}
override fun toString(): String {
return "kotlinx.serialization.PolymorphicSerializer(baseClass: $baseClass)"
}
}
@InternalSerializationApi
public fun <T : Any> AbstractPolymorphicSerializer<T>.findPolymorphicSerializer(
decoder: CompositeDecoder,
klassName: String?
): DeserializationStrategy<out T> =
findPolymorphicSerializerOrNull(decoder, klassName) ?: throwSubtypeNotRegistered(klassName, baseClass)
@InternalSerializationApi
public fun <T : Any> AbstractPolymorphicSerializer<T>.findPolymorphicSerializer(
encoder: Encoder,
value: T
): SerializationStrategy<T> =
findPolymorphicSerializerOrNull(encoder, value) ?: throwSubtypeNotRegistered(value::class, baseClass)
| apache-2.0 | 83e4e50e55454e923897685ba95ba814 | 38.155963 | 145 | 0.737582 | 4.806306 | false | false | false | false |
android/topeka | base/src/main/java/com/google/samples/apps/topeka/model/JsonAttributes.kt | 3 | 1114 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.model
object JsonAttributes {
const val ANSWER = "answer"
const val END = "end"
const val ID = "id"
const val MAX = "max"
const val MIN = "min"
const val NAME = "name"
const val OPTIONS = "options"
const val QUESTION = "question"
const val QUIZZES = "quizzes"
const val START = "start"
const val STEP = "step"
const val THEME = "theme"
const val TYPE = "type"
const val SCORES = "scores"
const val SOLVED = "solved"
} | apache-2.0 | 5e3c3042d5dd7edf6388af9b7d58f6ed | 29.972222 | 75 | 0.684022 | 3.841379 | false | false | false | false |
ursjoss/scipamato | core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/paper/jasper/summary/PaperSummaryTest.kt | 2 | 3753 | package ch.difty.scipamato.core.web.paper.jasper.summary
import ch.difty.scipamato.core.web.paper.jasper.CoreShortFieldConcatenator
import ch.difty.scipamato.core.web.paper.jasper.CoreShortFieldWithEmptyMainFieldConcatenator
import ch.difty.scipamato.core.web.paper.jasper.ExportEntityTest
import ch.difty.scipamato.core.web.paper.jasper.ReportHeaderFields
import nl.jqno.equalsverifier.EqualsVerifier
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
internal class PaperSummaryTest : ExportEntityTest() {
private val shortFieldConcatenator: CoreShortFieldConcatenator = CoreShortFieldWithEmptyMainFieldConcatenator()
private lateinit var ps: PaperSummary
private var rhf = newReportHeaderFields()
private fun newReportHeaderFields() = ReportHeaderFields(
headerPart = HEADER_PART,
brand = BRAND,
populationLabel = POPULATION_LABEL,
goalsLabel = GOALS_LABEL,
methodsLabel = METHODS_LABEL,
resultLabel = RESULT_LABEL,
commentLabel = COMMENT_LABEL,
)
@Test
fun instantiating() {
ps = PaperSummary(p, shortFieldConcatenator, rhf)
assertPaperSummary()
}
private fun assertPaperSummary() {
ps.number shouldBeEqualTo NUMBER.toString()
ps.authors shouldBeEqualTo AUTHORS
ps.title shouldBeEqualTo TITLE
ps.location shouldBeEqualTo LOCATION
ps.goals shouldBeEqualTo GOALS
ps.population shouldBeEqualTo POPULATION
ps.methods shouldBeEqualTo METHODS
ps.result shouldBeEqualTo RESULT
ps.comment shouldBeEqualTo COMMENT
ps.populationLabel shouldBeEqualTo POPULATION_LABEL
ps.methodsLabel shouldBeEqualTo METHODS_LABEL
ps.resultLabel shouldBeEqualTo RESULT_LABEL
ps.commentLabel shouldBeEqualTo COMMENT_LABEL
ps.header shouldBeEqualTo "$HEADER_PART $NUMBER"
ps.brand shouldBeEqualTo BRAND
ps.createdBy shouldBeEqualTo CREATED_BY
}
@Test
fun populationLabelIsBlankIfPopulationIsBlank() {
p.population = ""
ps = newPaperSummary()
ps.population shouldBeEqualTo ""
ps.populationLabel shouldBeEqualTo ""
}
private fun newPaperSummary(): PaperSummary = PaperSummary(p, shortFieldConcatenator, rhf)
@Test
fun methodsLabelIsBlankIfMethodsIsBlank() {
p.methods = ""
ps = newPaperSummary()
ps.methods shouldBeEqualTo ""
ps.methodsLabel shouldBeEqualTo ""
}
@Test
fun resultLabelIsBlankIfResultIsBlank() {
p.result = ""
ps = newPaperSummary()
ps.result shouldBeEqualTo ""
ps.resultLabel shouldBeEqualTo ""
}
@Test
fun commentLabelIsBlankIfCommentIsBlank() {
p.comment = ""
ps = newPaperSummary()
ps.comment shouldBeEqualTo ""
ps.commentLabel shouldBeEqualTo ""
}
@Test
fun headerHasNoNumberIfNumberIsNull() {
p.number = null
ps = newPaperSummary()
ps.header shouldBeEqualTo "headerPart"
}
@Test
fun headerOnlyShowsIdIfHeaderPartIsBlank() {
rhf = ReportHeaderFields(
headerPart = "",
brand = BRAND,
populationLabel = POPULATION_LABEL,
goalsLabel = GOALS_LABEL,
methodsLabel = METHODS_LABEL,
resultLabel = RESULT_LABEL,
commentLabel = COMMENT_LABEL,
)
p.number = 5L
ps = newPaperSummary()
ps.header shouldBeEqualTo "5"
}
@Test
fun equalsVerify() {
EqualsVerifier.simple()
.forClass(PaperSummary::class.java)
.withRedefinedSuperclass()
.withOnlyTheseFields("number")
.verify()
}
}
| bsd-3-clause | cd9ebb7ba05360e86248f39c75296e04 | 31.353448 | 115 | 0.673328 | 4.673724 | false | true | false | false |
pokk/mvp-magazine | app/src/main/kotlin/taiwan/no1/app/ui/adapter/viewholder/MovieCrewViewHolder.kt | 1 | 2248 | package taiwan.no1.app.ui.adapter.viewholder
import android.support.v7.widget.CardView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import kotterknife.bindView
import taiwan.no1.app.R
import taiwan.no1.app.mvp.contracts.adapter.MovieCrewAdapterContract
import taiwan.no1.app.mvp.models.FilmCastsModel
import taiwan.no1.app.ui.adapter.CommonRecyclerAdapter
import taiwan.no1.app.ui.listeners.GlideResizeTargetListener
import taiwan.no1.app.utilies.ImageLoader.IImageLoader
import javax.inject.Inject
/**
* A [BaseViewHolder] of displaying crews of the movie view of the MVP architecture's V.
*
* @author Jieyi
* @since 1/7/17
*/
class MovieCrewViewHolder(view: View) : BaseViewHolder<FilmCastsModel.CrewBean>(view), MovieCrewAdapterContract.View {
@Inject
lateinit var presenter: MovieCrewAdapterContract.Presenter
@Inject
lateinit var imageLoader: IImageLoader
//region View variables
val item by bindView<CardView>(R.id.item_cast)
val ivCast by bindView<ImageView>(R.id.iv_cast)
val tvCharacter by bindView<TextView>(R.id.tv_character)
val tvName by bindView<TextView>(R.id.tv_name)
//endregion
//region BaseViewHolder
override fun initView(model: FilmCastsModel.CrewBean, position: Int, adapter: CommonRecyclerAdapter) {
super.initView(model, position, adapter)
this.ivCast.viewTreeObserver.addOnGlobalLayoutListener {
this.ivCast.measuredWidth.let {
this.tvCharacter.width = it
this.tvName.width = it
}
}
}
override fun inject() {
this.component.inject(MovieCrewViewHolder@ this)
}
override fun initPresenter(model: FilmCastsModel.CrewBean) {
this.presenter.init(MovieCrewViewHolder@ this, model)
}
//endregion
//region ViewHolder implementations
override fun showCrewProfilePhoto(uri: String) {
this.imageLoader.display(uri, listener = GlideResizeTargetListener(this.ivCast, this.item))
}
override fun showCrewCharacter(character: String) {
this.tvCharacter.text = character
}
override fun showCrewName(name: String) {
this.tvName.text = name
}
//endregion
} | apache-2.0 | 7ac8ef837923b911bdcc653f6bedf97f | 31.128571 | 118 | 0.727313 | 4.05045 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/util/magic/PatternMagic.kt | 1 | 4156 | package nl.hannahsten.texifyidea.util.magic
import nl.hannahsten.texifyidea.inspections.latex.codestyle.LatexLineBreakInspection
import java.util.regex.Pattern
typealias RegexPattern = Pattern
/**
* @author Hannah Schellekens
*/
object PatternMagic {
val ellipsis = Regex("""(?<!\.)(\.\.\.)(?!\.)""")
/**
* This is the only correct way of using en dashes.
*/
val correctEnDash = RegexPattern.compile("[0-9]+--[0-9]+")!!
/**
* Matches the prefix of a label. Amazing comment this is right?
*/
val labelPrefix = RegexPattern.compile(".*:")!!
/**
* Matches the end of a sentence.
*
* Includes `[^.][^.]` because of abbreviations (at least in Dutch) like `s.v.p.`
*/
const val sentenceEndPrefix = "[^.A-Z][^.A-Z]"
val sentenceEnd = RegexPattern.compile("($sentenceEndPrefix[.?!;;] +[^%\\s])|(^\\. )")!!
/**
* Matches all interpunction that marks the end of a sentence.
*/
val sentenceSeparator = RegexPattern.compile("[.?!;;]")!!
/**
* Matches all sentenceSeparators at the end of a line (with or without space).
*/
val sentenceSeparatorAtLineEnd = RegexPattern.compile("$sentenceSeparator\\s*$")!!
/**
* Matches when a string ends with a non breaking space.
*/
val endsWithNonBreakingSpace = RegexPattern.compile("~$")!!
/**
* Finds all abbreviations that have at least two letters separated by comma's.
*
* It might be more parts, like `b.v.b.d. ` is a valid abbreviation. Likewise are `sajdflkj.asdkfj.asdf ` and
* `i.e. `. Single period abbreviations are not being detected as they can easily be confused with two letter words
* at the end of the sentence (also localisation...) For this there is a quickfix in [LatexLineBreakInspection].
*/
val abbreviation = RegexPattern.compile("[0-9A-Za-z.]+\\.[A-Za-z](\\.[\\s~])")!!
/**
* Abbreviations not detected by [PatternMagic.abbreviation].
*/
val unRegexableAbbreviations = listOf(
"et al."
)
/** [abbreviation]s that are missing a normal space (or a non-breaking space) */
val abbreviationWithoutNormalSpace = RegexPattern.compile("[0-9A-Za-z.]+\\.[A-Za-z](\\.[\\s])")!!
/**
* Matches all comments, starting with % and ending with a newline.
*/
val comments: RegexPattern = RegexPattern.compile("%(.*)\\n")
/**
* Matches leading and trailing whitespace on a string.
*/
val excessWhitespace = RegexPattern.compile("(^(\\s+).*(\\s*)\$)|(^(\\s*).*(\\s+)\$)")!!
/**
* Matches a non-ASCII character.
*/
val nonAscii = RegexPattern.compile("\\P{ASCII}")!!
/**
* Separator for multiple parameter values in one parameter.
*
* E.g. when you have \cite{citation1,citation2,citation3}, this pattern will match the separating
* comma.
*/
val parameterSplit = RegexPattern.compile("\\s*,\\s*")!!
/**
* Matches the extension of a file name.
*/
val fileExtension = RegexPattern.compile("\\.[a-zA-Z0-9]+$")!!
/**
* Matches all leading whitespace.
*/
val leadingWhitespace = RegexPattern.compile("^\\s*")!!
/**
* Matches newlines.
*/
val newline = RegexPattern.compile("\\n")!!
/**
* Checks if the string is `text`, two newlines, `text`.
*/
val containsMultipleNewlines = RegexPattern.compile("[^\\n]*\\n\\n+[^\\n]*")!!
/**
* Matches HTML tags of the form `<tag>`, `<tag/>` and `</tag>`.
*/
val htmlTag = RegexPattern.compile("""<.*?/?>""")!!
/**
* Matches a LaTeX command that is the start of an \if-\fi structure.
*/
val ifCommand = RegexPattern.compile("\\\\if[a-zA-Z@]*")!!
/**
* Matches the begin and end commands of the cases and split environments.
*/
val casesOrSplitCommands = Regex(
"((?=\\\\begin\\{cases})|(?<=\\\\begin\\{cases}))" +
"|((?=\\\\end\\{cases})|(?<=\\\\end\\{cases}))" +
"|((?=\\\\begin\\{split})|(?<=\\\\begin\\{split}))" +
"|((?=\\\\end\\{split})|(?<=\\\\end\\{split}))"
)
}
| mit | 8c736f08e23f5b3c9e6a2830cbec9a57 | 31.20155 | 119 | 0.579201 | 3.900469 | false | false | false | false |
FHannes/intellij-community | java/java-impl/src/com/intellij/psi/filters/getters/BuilderCompletion.kt | 4 | 4168 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.filters.getters
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.completion.JavaMethodCallElement
import com.intellij.codeInsight.lookup.ExpressionLookupItem
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.PlatformIcons
import java.util.*
/**
* @author peter
*/
internal class BuilderCompletion(private val expectedType: PsiClassType, private val expectedClass: PsiClass, private val place: PsiElement) {
fun suggestBuilderVariants(): List<LookupElement> {
val result = ArrayList<LookupElement>()
for (builderClass in expectedClass.innerClasses.filter { it.name?.contains("Builder") == true }) {
for (buildMethods in methodsReturning(expectedClass, builderClass, true)) {
for (createMethods in methodsReturning(builderClass, expectedClass, false)) {
createBuilderCall(buildMethods, createMethods)?.let { result.add(it) }
}
}
}
return result
}
private fun methodsReturning(containingClass: PsiClass, returnedClass: PsiClass, isStatic: Boolean): Collection<List<PsiMethod>> {
return containingClass.methods
.filter { it.hasModifierProperty(PsiModifier.STATIC) == isStatic &&
returnedClass == PsiUtil.resolveClassInClassTypeOnly(it.returnType) &&
PsiUtil.isAccessible(it, place, null) }
.groupBy { it.name }
.values
}
private fun showOverloads(methods: List<PsiMethod>) = if (methods.any { it.parameterList.parametersCount > 0 }) "..." else ""
private fun createBuilderCall(buildOverloads: List<PsiMethod>, createOverloads: List<PsiMethod>): LookupElement? {
val classQname = expectedClass.qualifiedName ?: return null
val classShortName = expectedClass.name ?: return null
val buildName = buildOverloads.first().name
val createName = createOverloads.first().name
val typeArgs = JavaMethodCallElement.getTypeParamsText(false, expectedClass, expectedType.resolveGenerics().substitutor) ?: ""
val canonicalText = "$classQname.$typeArgs$buildName().$createName()"
val presentableText = "$classShortName.$buildName(${showOverloads(buildOverloads)}).$createName(${showOverloads(createOverloads)})"
val expr =
try { JavaPsiFacade.getElementFactory(expectedClass.project).createExpressionFromText(canonicalText, place) }
catch(e: IncorrectOperationException) { return null }
if (expr.type != expectedType) return null
return object: ExpressionLookupItem(expr, PlatformIcons.METHOD_ICON, presentableText, canonicalText, presentableText, buildName, createName) {
override fun handleInsert(context: InsertionContext) {
super.handleInsert(context)
positionCaret(context)
}
}
}
}
private fun positionCaret(context: InsertionContext) {
val createCall = PsiTreeUtil.findElementOfClassAtOffset(context.file, context.tailOffset - 1, PsiMethodCallExpression::class.java, false)
val buildCall = createCall?.methodExpression?.qualifierExpression as? PsiMethodCallExpression ?: return
val hasParams = buildCall.methodExpression.multiResolve(true).any { ((it.element as? PsiMethod)?.parameterList?.parametersCount ?: 0) > 0 }
val argRange = buildCall.argumentList.textRange
context.editor.caretModel.moveToOffset(if (hasParams) (argRange.startOffset + argRange.endOffset) / 2 else argRange.endOffset)
}
| apache-2.0 | 0d317ab36e5bc473a6d8ed1109e783ee | 44.304348 | 146 | 0.754798 | 4.730988 | false | false | false | false |
AriaLyy/Aria | app/src/main/java/com/arialyy/simple/core/download/KotlinDownloadActivity.kt | 2 | 9812 | /*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* 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.arialyy.simple.core.download
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.arialyy.annotations.Download
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.download.DownloadEntity
import com.arialyy.aria.core.inf.IEntity
import com.arialyy.aria.core.listener.ISchedulers
import com.arialyy.aria.util.ALog
import com.arialyy.aria.util.CommonUtil
import com.arialyy.frame.util.show.T
import com.arialyy.simple.R
import com.arialyy.simple.R.string
import com.arialyy.simple.base.BaseActivity
import com.arialyy.simple.common.ModifyPathDialog
import com.arialyy.simple.common.ModifyUrlDialog
import com.arialyy.simple.databinding.ActivitySingleKotlinBinding
import com.arialyy.simple.util.AppUtil
import com.pddstudio.highlightjs.models.Language
import java.io.IOException
class KotlinDownloadActivity : BaseActivity<ActivitySingleKotlinBinding>() {
private var mUrl: String? = null
private var mFilePath: String? = null
private var mModule: HttpDownloadModule? = null
private var mTaskId: Long = -1
internal var receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
if (intent.action == ISchedulers.ARIA_TASK_INFO_ACTION) {
ALog.d(
TAG,
"state = " + intent.getIntExtra(ISchedulers.TASK_STATE, -1)
)
ALog.d(
TAG, "type = " + intent.getIntExtra(ISchedulers.TASK_TYPE, -1)
)
ALog.d(
TAG,
"speed = " + intent.getLongExtra(ISchedulers.TASK_SPEED, -1)
)
ALog.d(
TAG, "percent = " + intent.getIntExtra(
ISchedulers.TASK_PERCENT, -1
)
)
ALog.d(
TAG, "entity = " + intent.getParcelableExtra<DownloadEntity>(
ISchedulers.TASK_ENTITY
).toString()
)
}
}
}
override fun onResume() {
super.onResume()
//registerReceiver(receiver, new IntentFilter(ISchedulers.ARIA_TASK_INFO_ACTION));
}
override fun onDestroy() {
super.onDestroy()
//unregisterReceiver(receiver);
Aria.download(this)
.unRegister()
}
override fun init(savedInstanceState: Bundle?) {
super.init(savedInstanceState)
title = "单任务下载"
Aria.download(this)
.register()
mModule = ViewModelProviders.of(this)
.get(HttpDownloadModule::class.java)
mModule!!.getHttpDownloadInfo(this)
.observe(this, Observer { entity ->
if (entity == null) {
return@Observer
}
if (entity.state == IEntity.STATE_STOP) {
binding.stateStr = getString(string.resume)
}
if (Aria.download(this).load(entity.id).isRunning) {
binding.stateStr = getString(string.stop)
}
if (entity.fileSize != 0L) {
binding.fileSize = CommonUtil.formatFileSize(entity.fileSize.toDouble())
binding.progress = if (entity.isComplete)
100
else
(entity.currentProgress * 100 / entity.fileSize).toInt()
}
binding.url = entity.url
binding.filePath = entity.filePath
mUrl = entity.url
mFilePath = entity.filePath
})
binding.viewModel = this
try {
binding.codeView.setSource(AppUtil.getHelpCode(this, "KotlinHttpDownload.kt"), Language.JAVA)
} catch (e: IOException) {
e.printStackTrace()
}
}
fun chooseUrl() {
val dialog = ModifyUrlDialog(this, getString(R.string.modify_url_dialog_title), mUrl)
dialog.show(supportFragmentManager, "ModifyUrlDialog")
}
fun chooseFilePath() {
val dialog = ModifyPathDialog(this, getString(R.string.modify_file_path), mFilePath)
dialog.show(supportFragmentManager, "ModifyPathDialog")
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_single_task_activity, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onMenuItemClick(item: MenuItem): Boolean {
var speed = -1
var msg = ""
when (item.itemId) {
R.id.help -> {
msg = ("一些小知识点:\n"
+ "1、你可以在注解中增加链接,用于指定被注解的方法只能被特定的下载任务回调,以防止progress乱跳\n"
+ "2、当遇到网络慢的情况时,你可以先使用onPre()更新UI界面,待连接成功时,再在onTaskPre()获取完整的task数据,然后给UI界面设置正确的数据\n"
+ "3、你可以在界面初始化时通过Aria.download(this).load(URL).getPercent()等方法快速获取相关任务的一些数据")
showMsgDialog("tip", msg)
}
R.id.speed_0 -> speed = 0
R.id.speed_128 -> speed = 128
R.id.speed_256 -> speed = 256
R.id.speed_512 -> speed = 512
R.id.speed_1m -> speed = 1024
}
if (speed > -1) {
msg = item.title.toString()
Aria.download(this)
.setMaxSpeed(speed)
T.showShort(this, msg)
}
return true
}
@Download.onWait
fun onWait(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
Log.d(TAG, "wait ==> " + task.downloadEntity.fileName)
}
}
@Download.onPre
fun onPre(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.stateStr = getString(R.string.stop)
}
}
@Download.onTaskStart
fun taskStart(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.fileSize = task.convertFileSize
}
}
@Download.onTaskRunning
fun running(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
//Log.d(TAG, task.getKey());
val len = task.fileSize
if (len == 0L) {
binding.progress = 0
} else {
binding.progress = task.percent
}
binding.speed = task.convertSpeed
}
}
@Download.onTaskResume
fun taskResume(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.stateStr = getString(R.string.stop)
}
}
@Download.onTaskStop
fun taskStop(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.stateStr = getString(R.string.resume)
binding.speed = ""
}
}
@Download.onTaskCancel
fun taskCancel(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.progress = 0
binding.stateStr = getString(R.string.start)
binding.speed = ""
Log.d(TAG, "cancel")
}
}
/**
*
*/
@Download.onTaskFail
fun taskFail(
task: com.arialyy.aria.core.task.DownloadTask,
e: Exception
) {
if (task.key == mUrl) {
Toast.makeText(this, getString(R.string.download_fail), Toast.LENGTH_SHORT)
.show()
binding.stateStr = getString(R.string.start)
}
}
@Download.onTaskComplete
fun taskComplete(task: com.arialyy.aria.core.task.DownloadTask) {
if (task.key == mUrl) {
binding.progress = 100
Toast.makeText(
this, getString(R.string.download_success),
Toast.LENGTH_SHORT
)
.show()
binding.stateStr = getString(R.string.re_start)
binding.speed = ""
}
}
override fun setLayoutId(): Int {
return R.layout.activity_single_kotlin
}
fun onClick(view: View) {
when (view.id) {
R.id.start -> if (Aria.download(this).load(mTaskId).isRunning) {
Aria.download(this)
.load(mTaskId)
.stop()
} else {
startD()
}
R.id.stop -> Aria.download(this).load(mTaskId).stop()
R.id.cancel -> Aria.download(this).load(mTaskId).cancel(true)
}
}
private fun startD() {
if (mTaskId == -1L) {
mTaskId = Aria.download(this)
.load(mUrl!!)
//.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
//.addHeader("Accept-Encoding", "gzip, deflate")
//.addHeader("DNT", "1")
//.addHeader("Cookie", "BAIDUID=648E5FF020CC69E8DD6F492D1068AAA9:FG=1; BIDUPSID=648E5FF020CC69E8DD6F492D1068AAA9; PSTM=1519099573; BD_UPN=12314753; locale=zh; BDSVRTM=0")
.setFilePath(mFilePath!!, true)
.create()
} else {
Aria.download(this)
.load(mTaskId)
.resume()
}
}
override fun onStop() {
super.onStop()
//Aria.download(this).unRegister();
}
override fun dataCallback(
result: Int,
data: Any
) {
super.dataCallback(result, data)
if (result == ModifyUrlDialog.MODIFY_URL_DIALOG_RESULT) {
mModule!!.uploadUrl(this, data.toString())
} else if (result == ModifyPathDialog.MODIFY_PATH_RESULT) {
mModule!!.updateFilePath(this, data.toString())
}
}
} | apache-2.0 | ba115b94385a10526c58ad8f9cfc76c6 | 28.642857 | 180 | 0.642812 | 3.542687 | false | false | false | false |
GeoffreyMetais/vlc-android | application/moviepedia/src/main/java/org/videolan/moviepedia/models/body/ScrobbleBody.kt | 1 | 1665 | /*
* ************************************************************************
* ScrobbleBody.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.moviepedia.models.body
data class ScrobbleBody(
val osdbhash: String? = null,
val infohash: String? = null,
val imdbId: String? = null,
val dvdId: String? = null,
val title: String? = null,
val alternativeTitles: String? = null,
val filename: String? = null,
val show: String? = null,
val year: String? = null,
val season: String? = null,
val episode: String? = null,
val duration: String? = null
)
data class ScrobbleBodyBatch(
val id: String,
val metadata: ScrobbleBody
)
| gpl-2.0 | b2590b324f140e6951539eaad3c636da | 35.173913 | 80 | 0.584135 | 4.609418 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/filesystem/smb/CifsContexts.kt | 3 | 3589 | /*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.filesystem.smb
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import jcifs.CIFSException
import jcifs.config.PropertyConfiguration
import jcifs.context.BaseContext
import jcifs.context.SingletonContext
import java.util.*
import java.util.concurrent.ConcurrentHashMap
object CifsContexts {
const val SMB_URI_PREFIX = "smb://"
private val TAG = CifsContexts::class.java.simpleName
private val defaultProperties: Properties = Properties().apply {
setProperty("jcifs.resolveOrder", "BCAST")
setProperty("jcifs.smb.client.responseTimeout", "30000")
setProperty("jcifs.netbios.retryTimeout", "5000")
setProperty("jcifs.netbios.cachePolicy", "-1")
}
private val contexts: MutableMap<String, BaseContext> = ConcurrentHashMap()
@JvmStatic
fun clearBaseContexts() {
contexts.forEach {
try {
it.value.close()
} catch (e: CIFSException) {
Log.w(TAG, "Error closing SMB connection", e)
}
}
contexts.clear()
}
@JvmStatic
fun createWithDisableIpcSigningCheck(
basePath: String,
disableIpcSigningCheck: Boolean
): BaseContext {
return if (disableIpcSigningCheck) {
val extraProperties = Properties()
extraProperties["jcifs.smb.client.ipcSigningEnforced"] = "false"
create(basePath, extraProperties)
} else {
create(basePath, null)
}
}
@JvmStatic
fun create(basePath: String, extraProperties: Properties?): BaseContext {
val basePathKey: String = Uri.parse(basePath).run {
val prefix = "$scheme://$authority"
val suffix = if (TextUtils.isEmpty(query)) "" else "?$query"
"$prefix$suffix"
}
return if (contexts.containsKey(basePathKey)) {
contexts.getValue(basePathKey)
} else {
val context = Single.fromCallable {
try {
val p = Properties(defaultProperties)
if (extraProperties != null) p.putAll(extraProperties)
BaseContext(PropertyConfiguration(p))
} catch (e: CIFSException) {
Log.e(TAG, "Error initialize jcifs BaseContext, returning default", e)
SingletonContext.getInstance()
}
}.subscribeOn(Schedulers.io())
.blockingGet()
contexts[basePathKey] = context
context
}
}
}
| gpl-3.0 | 4eef752dbc2c3a6c154cd740e3d894c4 | 34.534653 | 107 | 0.647813 | 4.508794 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/lread.kt | 1 | 1898 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.reverseRemoveDuplication
/**
* Created by AoEiuV020 on 2018.06.03-19:35:33.
*/
class Lread : DslJsoupNovelContext() {init {
hide = true
site {
name = "乐阅读"
baseUrl = "https://www.6ks.net"
logo = "https://www.6ks.net/images/logo.gif"
}
search {
post {
// https://www.lread.net/modules/article/search.php?searchkey=%B6%BC%CA%D0
charset = "UTF-8"
url = "/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
}
}
// 搜索结果可能过多,但是页面不太大,无所谓了,
document {
items("#nr") {
name("> td:nth-child(1) > a")
author("> td:nth-child(3)")
}
}
}
// https://m.lread.net/book/88917.html
// https://www.lread.net/read/88917/
detailPageTemplate = "/read/%s/"
detail {
document {
novel {
name("#info > h1")
author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)"))
}
image("#fmimg > img")
update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
introduction("#intro > p")
}
}
chapters {
document {
items("#list > dl > dd > a")
lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
}.reverseRemoveDuplication()
}
// https://www.lread.net/read/88917/32771268.html
contentPageTemplate = "/read/%s.html"
content {
document {
items("#content")
}
}
}
}
| gpl-3.0 | 7f0a75f8adb00973677fb05bb209815d | 27.920635 | 113 | 0.5 | 3.558594 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/search/FuzzySearchActivity.kt | 1 | 6144 | package cc.aoeiuv020.panovel.search
import android.content.Context
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.NovelManager
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.list.NovelListAdapter
import cc.aoeiuv020.panovel.settings.ListSettings
import cc.aoeiuv020.panovel.settings.OtherSettings
import cc.aoeiuv020.panovel.util.getStringExtra
import com.google.android.material.snackbar.Snackbar
import com.miguelcatalan.materialsearchview.MaterialSearchView
import kotlinx.android.synthetic.main.activity_fuzzy_search.*
import kotlinx.android.synthetic.main.novel_item_list.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.ctx
import org.jetbrains.anko.startActivity
class FuzzySearchActivity : AppCompatActivity(), IView, AnkoLogger {
companion object {
fun start(ctx: Context) {
ctx.startActivity<FuzzySearchActivity>()
}
fun start(ctx: Context, novel: Novel) {
// 精确搜索,refine search,
start(ctx, novel.name, novel.author)
}
fun start(ctx: Context, name: String) {
// 模糊搜索,fuzzy search,
ctx.startActivity<FuzzySearchActivity>("name" to name)
}
fun start(ctx: Context, name: String, author: String) {
// 精确搜索,refine search,
ctx.startActivity<FuzzySearchActivity>("name" to name, "author" to author)
}
fun startSingleSite(ctx: Context, site: String) {
// 单个网站模糊搜索,fuzzy search,
ctx.startActivity<FuzzySearchActivity>("site" to site)
}
}
private lateinit var presenter: FuzzySearchPresenter
private val novelListAdapter by lazy {
NovelListAdapter(onError = ::showError)
}
private var name: String? = null
private var author: String? = null
private var site: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fuzzy_search)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
searchView.setOnQueryTextListener(object : MaterialSearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
searchView.hideKeyboard(searchView)
search(query)
return true
}
override fun onQueryTextChange(newText: String?): Boolean = false
})
rvNovel.layoutManager = if (ListSettings.gridView) {
androidx.recyclerview.widget.GridLayoutManager(ctx, if (ListSettings.largeView) 3 else 5)
} else {
androidx.recyclerview.widget.LinearLayoutManager(ctx)
}
presenter = FuzzySearchPresenter()
presenter.attach(this)
rvNovel.adapter = novelListAdapter
name = getStringExtra("name", savedInstanceState)
author = getStringExtra("author", savedInstanceState)
site = getStringExtra("site", savedInstanceState)
site?.let {
presenter.singleSite(it)
}
srlRefresh.setOnRefreshListener {
// 任何时候刷新都没影响,所以一开始就初始化好,
forceRefresh()
}
// 如果传入了名字,就直接开始搜索,
name?.let { nameNonnull ->
search(nameNonnull, author)
} ?: searchView.post { showSearch() }
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("name", name)
outState.putString("author", author)
}
private fun showSearch() {
searchView.showSearch()
searchView.setQuery(presenter.name, false)
}
override fun onDestroy() {
presenter.detach()
super.onDestroy()
}
private fun search(name: String, author: String? = null) {
srlRefresh.isRefreshing = true
title = name
this.name = name
this.author = author
novelListAdapter.clear()
if (OtherSettings.refreshOnSearch) {
novelListAdapter.refresh()
}
presenter.search(name, author)
}
private fun refresh() {
// 重新搜索就是刷新了,
// 没搜索就刷新也是不禁止的,所以要判断下,
name?.let {
search(it, author)
} ?: run {
srlRefresh.isRefreshing = false
}
}
/**
* 刷新列表,同时刷新小说章节信息,
* 为了方便从书架过来,找一本小说的所有源的最新章节,
*/
private fun forceRefresh() {
novelListAdapter.refresh()
refresh()
}
fun addResult(list: List<NovelManager>) {
// 插入有时会导致下滑,原因不明,保存状态解决,
val lm = rvNovel.layoutManager ?: return
val state = lm.onSaveInstanceState() ?: return
novelListAdapter.addAll(list)
lm.onRestoreInstanceState(state)
}
fun showOnComplete() {
srlRefresh.isRefreshing = false
}
private val snack: Snackbar by lazy {
Snackbar.make(rvNovel, "", Snackbar.LENGTH_SHORT)
}
fun showError(message: String, e: Throwable) {
srlRefresh.isRefreshing = false
snack.setText(message + e.message)
snack.show()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_fuzzy_search, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.search -> {
searchView.showSearch()
searchView.setQuery(presenter.name, false)
}
android.R.id.home -> onBackPressed()
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
| gpl-3.0 | 50a795d158f4f1f46addb13b3ba414ab | 29.867725 | 101 | 0.640555 | 4.529503 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/core/src/test/kotlin/org/droidmate/test_tools/device_simulation/GuiScreen.kt | 1 | 11231 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.test_tools.device_simulation
import org.droidmate.deviceInterface.exploration.DeviceResponse
import org.droidmate.deviceInterface.exploration.ExplorationAction
/**
* <p>
* The time generator provides successive timestamps to the logs returned by the simulated device from a call to
* {@link #perform(org.droidmate.uiautomator_daemon.guimodel.ExplorationAction)}.
*
* </p><p>
* If this object s a part of simulation obtained from exploration output the time generator is null, as no time needs to be
* generated. Instead, all time is obtained from the exploration output timestamps.
*
* </p>
*/
class GuiScreen /*constructor(private val internalId: String,
packageName : String = "",
private val timeGenerator : ITimeGenerator? = null)*/ // TODO Fix tests
: IGuiScreen {
override fun perform(action: ExplorationAction): IScreenTransitionResult {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getGuiSnapshot(): DeviceResponse {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getId(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addHomeScreenReference(home: IGuiScreen) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addMainScreenReference(main: IGuiScreen) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen, ignoreDuplicates: Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun buildInternals() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun verify() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
// TODO Fix tests
//private static final String packageAndroidLauncher = new DeviceConfigurationFactory(DeviceConstants.DEVICE_DEFAULT).getConfiguration().getPackageAndroidLauncher()
/*companion object {
const val idHome = "home"
const val idChrome = "chrome"
val reservedIds = arrayListOf(idHome, idChrome)
val reservedIdsPackageNames = mapOf(
idHome to DeviceModel.buildDefault().getAndroidLauncherPackageName(),
idChrome to "com.android.chrome")
fun getSingleMatchingWidget(action: ClickAction, widgets: List<Widget>): Widget {
return widgets.find { w->w.xpath==action.xPath }!!
}
fun getSingleMatchingWidget(action: CoordinateClickAction, widgets: List<Widget>): Widget {
return widgets.find { w->w.bounds.contains(action.x, action.y) }!!
}
}
private val packageName: String
private var internalGuiSnapshot: IDeviceGuiSnapshot = MissingGuiSnapshot()
private var home: IGuiScreen? = null
private var main: IGuiScreen? = null
private val widgetTransitions: MutableMap<Widget, IGuiScreen> = mutableMapOf()
private var finishedBuilding = false
constructor(snapshot: IDeviceGuiSnapshot) : this(snapshot.id, snapshot.getPackageName()) {
this.internalGuiSnapshot = snapshot
}
initialize {
this.packageName = if (packageName.isNotEmpty()) packageName else reservedIdsPackageNames[internalId]!!
assert(this.internalId.isNotEmpty())
assert(this.packageName.isNotEmpty())
assert((this.internalId !in reservedIds) || (this.packageName == reservedIdsPackageNames[internalId]))
assert((this.internalId in reservedIds) || (this.packageName !in reservedIdsPackageNames.values))
}
override fun perform(action: ExplorationAction): IScreenTransitionResult {
assert(finishedBuilding)
return when (action) {
// TODO review
is SimulationAdbClearPackageAction -> internalPerform(action)
is LaunchAppAction -> internalPerform(action)
is ClickAction -> internalPerform(action)
is CoordinateClickAction -> internalPerform(action)
is LongClickAction -> internalPerform(action)
is CoordinateLongClickAction -> internalPerform(action)
else -> throw UnsupportedMultimethodDispatch(action)
}
}
//region internalPerform multimethod
// This method is used: it is a multimethod.
private fun internalPerform(clearPackage: SimulationAdbClearPackageAction): IScreenTransitionResult {
return if (this.getGuiSnapshot().getPackageName() == clearPackage.packageName)
ScreenTransitionResult(home!!, ArrayList())
else
ScreenTransitionResult(this, ArrayList())
}
@Suppress("UNUSED_PARAMETER")
private fun internalPerform(launch: LaunchAppAction): IScreenTransitionResult =
ScreenTransitionResult(main!!, this.buildMonitorMessages())
private fun internalPerform(action: ExplorationAction): IScreenTransitionResult {
return when (action) {
is PressHomeAction -> ScreenTransitionResult(home!!, ArrayList())
is EnableWifiAction -> {
assert(this == home)
ScreenTransitionResult(this, ArrayList())
}
is PressBackAction -> ScreenTransitionResult(this, ArrayList())
is ClickAction -> {
val widget = getSingleMatchingWidget(action, widgetTransitions.keys.toList())
ScreenTransitionResult(widgetTransitions[widget]!!, ArrayList())
}
is CoordinateClickAction -> {
val widget = getSingleMatchingWidget(action, widgetTransitions.keys.toList())
ScreenTransitionResult(widgetTransitions[widget]!!, ArrayList())
}
else -> throw UnexpectedIfElseFallthroughError("Found action $action")
}
}
//endregion internalPerform multimethod
override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen, ignoreDuplicates: Boolean) {
assert(!finishedBuilding)
assert(this.internalId !in reservedIds)
assert(ignoreDuplicates || !(widgetTransitions.keys.any { it.id.contains(widgetId) }))
if (!(ignoreDuplicates && widgetTransitions.keys.any { it.id.contains(widgetId) })) {
val widget = if (this.getGuiSnapshot() !is MissingGuiSnapshot)
this.getGuiSnapshot().guiState.widgets.single { it.id == widgetId }
else
WidgetTestHelper.newClickableWidget(mutableMapOf("uid" to widgetId), /* widgetGenIndex */ widgetTransitions.keys.size)
widgetTransitions[widget] = targetScreen
}
assert(widgetTransitions.keys.any { it.id.contains(widgetId) })
}
override fun addHomeScreenReference(home: IGuiScreen) {
assert(!finishedBuilding)
assert(home.getId() == idHome)
this.home = home
}
override fun addMainScreenReference(main: IGuiScreen) {
assert(!finishedBuilding)
assert(main.getId() !in reservedIds)
this.main = main
}
override fun buildInternals() {
assert(!this.finishedBuilding)
assert(this.getGuiSnapshot() is MissingGuiSnapshot)
val widgets = widgetTransitions.keys
when (internalId) {
!in reservedIds -> {
val guiState = if (widgets.isEmpty()) {
buildEmptyInternals()
} else
GuiStateTestHelper.newGuiStateWithWidgets(
widgets.size, packageName, /* enabled */ true, internalId, widgets.map { it.id })
this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.fromGuiState(guiState)
}
idHome -> this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.newHomeScreenWindowDump(this.internalId)
idChrome -> this.internalGuiSnapshot = UiautomatorWindowDumpTestHelper.newAppOutOfScopeWindowDump(this.internalId)
else -> throw UnexpectedIfElseFallthroughError("Unsupported reserved uid: $internalId")
}
assert(this.getGuiSnapshot().id.isNotEmpty())
}
private fun buildEmptyInternals(): DeviceResponse {
val guiState = GuiStateTestHelper.newGuiStateWithTopLevelNodeOnly(packageName, internalId)
// This one widget is necessary, as it is the only xml element from which packageName can be obtained. Without it, following
// method would fail: UiautomatorWindowDump.getPackageName when called on
// org.droidmate.exploration.device.simulation.GuiScreen.guiSnapshot.
assert(guiState.widgets.size == 1)
return guiState
}
override fun verify() {
assert(!finishedBuilding)
this.finishedBuilding = true
assert(this.home?.getId() == idHome)
assert(this.main?.getId() !in reservedIds)
assert(this.getGuiSnapshot().id.isNotEmpty())
assert(this.getGuiSnapshot().guiState.id.isNotEmpty())
// TODO: Review later
//assert((this.internalId in reservedIds) || (this.widgetTransitions.keys.map { it.uid }.sorted() == this.getGuiSnapshot().guiStatus.getActionableWidgets().map { it.uid }.sorted()))
assert(this.finishedBuilding)
}
private fun buildMonitorMessages(): List<TimeFormattedLogMessageI> {
return listOf(
TimeFormattedLogcatMessage.from(
this.timeGenerator!!.shiftAndGet(mapOf("milliseconds" to 1500)), // Milliseconds amount based on empirical evidence.
MonitorConstants.loglevel.toUpperCase(),
MonitorConstants.tag_mjt,
"4224", // arbitrary process ID
MonitorConstants.msg_ctor_success),
TimeFormattedLogcatMessage.from(
this.timeGenerator.shiftAndGet(mapOf("milliseconds" to 1810)), // Milliseconds amount based on empirical evidence.
MonitorConstants.loglevel.toUpperCase(),
MonitorConstants.tag_mjt,
"4224", // arbitrary process ID
MonitorConstants.msgPrefix_init_success + this.packageName)
)
}
override fun toString(): String {
return MoreObjects.toStringHelper(this)
.update("uid", internalId)
.toString()
}
override fun getId(): String = this.internalId
override fun getGuiSnapshot(): IDeviceGuiSnapshot = this.internalGuiSnapshot
override fun addWidgetTransition(widgetId: String, targetScreen: IGuiScreen) {
addWidgetTransition(widgetId, targetScreen, false)
}*/
} | gpl-3.0 | 619d3746074201277230d1d46c7f7cb8 | 39.402878 | 184 | 0.737601 | 4.246125 | false | false | false | false |
soniccat/android-taskmanager | storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/disk/serializer/DiskMetadataDeserializer.kt | 1 | 1748 | package com.example.alexeyglushkov.cachemanager.disk.serializer
import com.example.alexeyglushkov.cachemanager.disk.DiskStorageMetadata
import com.example.alexeyglushkov.jacksonlib.CustomDeserializer
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import java.io.IOException
/**
* Created by alexeyglushkov on 18.09.16.
*/
class DiskMetadataDeserializer(vc: Class<DiskStorageMetadata>) : CustomDeserializer<DiskStorageMetadata>(vc) {
override fun createObject(): DiskStorageMetadata {
return DiskStorageMetadata()
}
@Throws(IOException::class)
protected override fun handle(p: JsonParser, ctxt: DeserializationContext, metadata: DiskStorageMetadata): Boolean {
val name = p.currentName
var isHandled = false
when (name) {
"contentSize" -> {
val contentSize = _parseLong(p, ctxt)
metadata.contentSize = contentSize
isHandled = true
}
"createTime" -> {
val createTime = _parseLong(p, ctxt)
metadata.createTime = createTime
isHandled = true
}
"expireTime" -> {
val expireTime = _parseLong(p, ctxt)
metadata.expireTime = expireTime
isHandled = true
}
"entryClass" -> {
val className = _parseString(p, ctxt)
try {
metadata.entryClass = Class.forName(className)
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
isHandled = true
}
}
return isHandled
}
} | mit | 0c4b13407978acce7b20f741875e3b4a | 34.693878 | 120 | 0.59611 | 5.378462 | false | false | false | false |
juxeii/dztools | java/dzjforex/src/main/kotlin/com/jforex/dzjforex/stop/BrokerStop.kt | 1 | 2120 | package com.jforex.dzjforex.stop
import com.dukascopy.api.IOrder
import com.jforex.dzjforex.misc.*
import com.jforex.dzjforex.order.OrderLookupApi.getTradeableOrderForId
import com.jforex.dzjforex.zorro.BROKER_ADJUST_SL_FAIL
import com.jforex.dzjforex.zorro.BROKER_ADJUST_SL_OK
import com.jforex.kforexutils.order.event.OrderEvent
import com.jforex.kforexutils.order.event.OrderEventType
import com.jforex.kforexutils.order.extension.setSL
object BrokerStopApi {
fun <F> ContextDependencies<F>.brokerStop(orderId: Int, slPrice: Double) =
getTradeableOrderForId(orderId)
.flatMap { order ->
logger.debug("BrokerStop: setting stop loss price $slPrice for oder $order")
setSLPrice(order, slPrice)
}
.map(::processCloseEvent)
.handleErrorWith { error -> processError(error) }
private fun <F> ContextDependencies<F>.processError(error: Throwable) = delay {
when (error) {
is OrderIdNotFoundException ->
natives.logAndPrintErrorOnZorro("BrokerStop: order id ${error.orderId} not found!")
is AssetNotTradeableException ->
natives.logAndPrintErrorOnZorro("BrokerStop: ${error.instrument} currently not tradeable!")
else ->
logger.error(
"BrokerStop failed! Error: ${error.message} " +
"Stack trace: ${getStackTrace(error)}"
)
}
BROKER_ADJUST_SL_FAIL
}
fun processCloseEvent(orderEvent: OrderEvent) =
if (orderEvent.type == OrderEventType.CHANGED_SL) {
logger.debug("BrokerStop: stop loss price successfully set for order ${orderEvent.order}")
BROKER_ADJUST_SL_OK
} else {
logger.debug("BrokerStop: setting stop loss failed for order ${orderEvent.order} event $orderEvent")
BROKER_ADJUST_SL_FAIL
}
fun <F> ContextDependencies<F>.setSLPrice(order: IOrder, slPrice: Double) = catch {
order
.setSL(slPrice = slPrice) {}
.blockingLast()
}
} | mit | a009a5d2b66a137aac786d3cf4135505 | 40.588235 | 112 | 0.642925 | 4.108527 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/IgnoredReturnValueSpec.kt | 1 | 28441 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import io.gitlab.arturbosch.detekt.test.lintWithContext
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object IgnoredReturnValueSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
describe("default config with non-annotated return values") {
val subject by memoized { IgnoredReturnValue() }
it("does not report when a function which returns a value is called and the return is ignored") {
val code = """
fun foo() {
listOf("hello")
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called before a valid return") {
val code = """
fun foo() : Int {
listOf("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called in chain and the return is ignored") {
val code = """
fun foo() {
listOf("hello").isEmpty().not()
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called before a semicolon") {
val code = """
fun foo() {
listOf("hello");println("foo")
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called after a semicolon") {
val code = """
fun foo() {
println("foo");listOf("hello")
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called between comments") {
val code = """
fun foo() {
listOf("hello")//foo
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when an extension function which returns a value is called and the return is ignored") {
val code = """
fun Int.isTheAnswer(): Boolean = this == 42
fun foo(input: Int) {
input.isTheAnswer()
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when the return value is assigned to a pre-existing variable") {
val code = """
package test
annotation class CheckReturnValue
@CheckReturnValue
@Deprecated("Yes")
fun listA() = listOf("hello")
fun foo() {
var x: List<String>
x = listA()
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which doesn't return a value is called") {
val code = """
fun noReturnValue() {}
fun foo() {
noReturnValue()
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used in a test statement") {
val code = """
fun returnsBoolean() = true
fun f() {
if (returnsBoolean()) {}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used in a comparison") {
val code = """
fun returnsInt() = 42
fun f() {
if (42 == returnsInt()) {}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used as parameter for another call") {
val code = """
fun returnsInt() = 42
fun f() {
println(returnsInt())
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used with named parameters") {
val code = """
fun returnsInt() = 42
fun f() {
println(message = returnsInt())
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
}
describe("default config with annotated return values") {
val subject by memoized { IgnoredReturnValue() }
it("reports when a function which returns a value is called and the return is ignored") {
val code = """
package annotation
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() {
listOfChecked("hello")
println("foo")
}
"""
val annotationClass = """
package annotation
annotation class CheckReturnValue
"""
val findings = subject.lintWithContext(env, code, annotationClass)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(7, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function which returns a value is called before a valid return") {
val code = """
package noreturn
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.lintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(9, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function which returns a value is called in chain as first statement and the return is ignored") {
val code = """
package noreturn
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello").isEmpty().not()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which returns a value is called in the middle of a chain and the return is ignored") {
val code = """
package noreturn
annotation class CheckReturnValue
@CheckReturnValue
fun String.listOfChecked() = listOf(this)
fun foo() : Int {
val hello = "world "
hello.toUpperCase()
.trim()
.listOfChecked()
.isEmpty()
.not()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("reports when a function which returns a value is called in the end of a chain and the return is ignored") {
val code = """
package noreturn
annotation class CheckReturnValue
@CheckReturnValue
fun String.listOfChecked() = listOf(this)
fun foo() : Int {
val hello = "world "
hello.toUpperCase()
.trim()
.listOfChecked()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(12, 10)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function which returns a value is called before a semicolon") {
val code = """
package special
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() {
listOfChecked("hello");println("foo")
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(9, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function which returns a value is called after a semicolon") {
val code = """
package special
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
println("foo");listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(9, 20)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function which returns a value is called between comments") {
val code = """
package special
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
/* foo */listOfChecked("hello")//foo
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(9, 14)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when an extension function which returns a value is called and the return is ignored") {
val code = """
package specialize
annotation class CheckReturnValue
@CheckReturnValue
fun Int.isTheAnswer(): Boolean = this == 42
fun foo(input: Int) : Int {
input.isTheAnswer()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(8, 11)
assertThat(findings[0]).hasMessage("The call isTheAnswer is returning a value that is ignored.")
}
it("does not report when the return value is assigned to a pre-existing variable") {
val code = """
package specialize
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
var x: List<String>
x = listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function which doesn't return a value is called") {
val code = """
package specialize
annotation class CheckReturnValue
@CheckReturnValue
fun noReturnValue() {}
fun foo() : Int {
noReturnValue()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used in a test statement") {
val code = """
package comparison
annotation class CheckReturnValue
@CheckReturnValue
fun returnsBoolean() = true
fun f() {
if (returnsBoolean()) {}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used in a comparison") {
val code = """
package comparison
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun f() {
if (42 == returnsInt()) {}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used as parameter for another call") {
val code = """
package parameter
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun f() {
println(returnsInt())
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function's return value is used with named parameters") {
val code = """
package parameter
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun f() {
println(message = returnsInt())
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function is the last statement in a block and it's used") {
val code = """
package block
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
val result = if (true) {
1
} else {
returnsInt()
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("report when a function is not the last statement in a 'if' block and 'if' block is used") {
val code = """
package block
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
val result = if (true) {
1
} else {
returnsInt()
2
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("does not report when a function is the last statement in a block and it's in a chain") {
val code = """
package block
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun test() {
if (true) {
1
} else {
returnsInt()
}.plus(1)
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("report when a function is not the last statement in a block and it's in a chain") {
val code = """
package block
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun test() {
if (true) {
1
} else {
returnsInt()
2
}.plus(1)
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("report when a function is the last statement in a block") {
val code = """
package block
annotation class CheckReturnValue
@CheckReturnValue
fun returnsInt() = 42
fun test() {
if (true) {
println("hello")
} else {
returnsInt()
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("does not report when a function return value is consumed in a chain that returns a Unit") {
val code = """
package callchain
annotation class CheckReturnValue
@CheckReturnValue
fun String.listOfChecked() = listOf(this)
fun List<String>.print() { println(this) }
fun foo() : Int {
val hello = "world "
hello.toUpperCase()
.trim()
.listOfChecked()
.print()
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("reports when the containing class of a function has `@CheckReturnValue`") {
val code = """
package foo
annotation class CheckReturnValue
@CheckReturnValue
class Assertions {
fun listOfChecked(value: String) = listOf(value)
}
fun main() {
Assertions().listOfChecked("hello")
}
"""
val findings = subject.lintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("reports when the containing object of a function has `@CheckReturnValue`") {
val code = """
package foo
annotation class CheckReturnValue
@CheckReturnValue
object Assertions {
fun listOfChecked(value: String) = listOf(value)
}
fun main() {
Assertions.listOfChecked("hello")
}
"""
val findings = subject.lintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("does not report when the containing class of a function has `@CheckReturnValue` but the function has `@CanIgnoreReturnValue`") {
val code = """
package foo
annotation class CheckReturnValue
annotation class CanIgnoreReturnValue
@CheckReturnValue
class Assertions {
@CanIgnoreReturnValue
fun listOfChecked(value: String) = listOf(value)
}
fun main() {
Assertions().listOfChecked("hello")
}
"""
val findings = subject.lintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when the containing class of a function has no `@CheckReturnValue` but the parent class has `@CheckReturnValue`") {
val code = """
package foo
annotation class CheckReturnValue
@CheckReturnValue
class Parent {
class Child {
fun listOfChecked(value: String) = listOf(value)
}
}
fun main() {
Parent.Child().listOfChecked("hello")
}
"""
val findings = subject.lintWithContext(env, code)
assertThat(findings).isEmpty()
}
}
describe("custom annotation config") {
val subject by memoized {
IgnoredReturnValue(
TestConfig(mapOf("returnValueAnnotations" to listOf("*.CustomReturn")))
)
}
it("reports when a function is annotated with the custom annotation") {
val code = """
package config
annotation class CustomReturn
@CustomReturn
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(8, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("does not report when a function is annotated with the not included annotation") {
val code = """
package config
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function is not annotated") {
val code = """
package config
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
}
describe("restrict to annotated methods config") {
val subject by memoized {
IgnoredReturnValue(TestConfig(mapOf("restrictToAnnotatedMethods" to false)))
}
it("reports when a function is annotated with a custom annotation") {
val code = """
package config
annotation class CheckReturnValue
@CheckReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(9, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("reports when a function is not annotated") {
val code = """
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(4, 5)
assertThat(findings[0]).hasMessage("The call listOfChecked is returning a value that is ignored.")
}
it("does not report when a function has `@CanIgnoreReturnValue`") {
val code = """
package foo
annotation class CanIgnoreReturnValue
@CanIgnoreReturnValue
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("does not report when a function has a custom annotation") {
val code = """
package foo
annotation class CustomIgnoreReturn
@CustomIgnoreReturn
fun listOfChecked(value: String) = listOf(value)
fun foo() : Int {
listOfChecked("hello")
return 42
}
"""
val rule = IgnoredReturnValue(
TestConfig(
mapOf(
"ignoreReturnValueAnnotations" to listOf("*.CustomIgnoreReturn"),
"restrictToAnnotatedMethods" to false
)
)
)
val findings = rule.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
}
})
| apache-2.0 | c66f0d5acd56f225b15f44e18feb9413 | 33.811506 | 143 | 0.479062 | 6.249396 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/di/AppModule.kt | 1 | 1686 | package com.apps.adrcotfas.goodtime.di
import android.content.Context
import com.apps.adrcotfas.goodtime.bl.CurrentSessionManager
import com.apps.adrcotfas.goodtime.bl.NotificationHelper
import com.apps.adrcotfas.goodtime.bl.RingtoneAndVibrationPlayer
import com.apps.adrcotfas.goodtime.database.AppDatabase
import com.apps.adrcotfas.goodtime.settings.PreferenceHelper
import com.apps.adrcotfas.goodtime.settings.reminders.ReminderHelper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun providePreferenceHelper(@ApplicationContext context: Context) = PreferenceHelper(context)
@Provides
@Singleton
fun provideRingtoneAndVibrationPlayer(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) =
RingtoneAndVibrationPlayer(context, preferenceHelper)
@Provides
@Singleton
fun provideCurrentSessionManager(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) = CurrentSessionManager(context, preferenceHelper)
@Provides
@Singleton
fun provideReminderHelper(@ApplicationContext context: Context, preferenceHelper: PreferenceHelper) = ReminderHelper(context, preferenceHelper)
@Provides
@Singleton
fun provideNotificationHelper(@ApplicationContext context: Context) = NotificationHelper(context)
@Provides
@Singleton
fun provideLocalDatabase(@ApplicationContext context: Context) = AppDatabase.getDatabase(context)
} | apache-2.0 | da540585d6d4c22bf60e491b749a3c05 | 37.340909 | 161 | 0.822657 | 5.219814 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/AbstractOption.kt | 1 | 1655 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.options
import javafx.scene.input.KeyCodeCombination
import java.io.Serializable
abstract class AbstractOption(
override var code: String = "",
override var aliases: MutableList<String> = mutableListOf<String>(),
override var label: String = "",
override var isRow: Boolean = true,
override var isMultiple: Boolean = false,
override var newTab: Boolean = false,
override var prompt: Boolean = false,
override var refresh: Boolean = false,
override var shortcut: KeyCodeCombination? = null
) : Option, Serializable {
protected fun copyTo(result: AbstractOption) {
result.code = code
result.aliases = ArrayList<String>(aliases)
result.label = label
result.isRow = isRow
result.isMultiple = isMultiple
result.newTab = newTab
result.prompt = prompt
result.refresh = refresh
result.shortcut = shortcut
}
}
| gpl-3.0 | 064089047c3fe8c7bd4e9aded81083db | 34.978261 | 76 | 0.710574 | 4.648876 | false | false | false | false |
ksmirenko/flexicards-android | app/src/main/java/com/ksmirenko/flexicards/app/parsers/TxtParser.kt | 1 | 1636 | package com.ksmirenko.flexicards.app.parsers
import com.ksmirenko.flexicards.app.datatypes.CardPack
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.ArrayList
/**
* Parses a text file into a CardPack.
*
* @author Kirill Smirenko
*/
class TxtParser(file : File) {
val reader : BufferedReader
val pack : CardPack
init {
reader = BufferedReader(FileReader(file))
pack = CardPack(null, null, null, ArrayList<Pair<String, String>>())
}
fun parse() : CardPack? {
try {
var line = reader.readLine()
val list = pack.cardList as ArrayList
while (line != null) {
when {
line.startsWith("category=", true) ->
pack.categoryName = line.removeSurrounding("category=\"", "\"")
line.startsWith("lang=", true) ->
pack.language = line.removeSurrounding("lang=\"", "\"")
line.startsWith("module=", true) ->
pack.moduleName = line.removeSurrounding("module=\"", "\"")
line.contains('\t') -> {
val arr = line.split('\t')
if (arr.size == 2) {
list.add(arr[0] to arr[1])
}
}
}
line = reader.readLine()
}
return pack
}
catch (e : IOException) {
return null
}
finally {
reader.close()
}
}
} | apache-2.0 | 22f1f8ebff22b708387c358c97c5c2f6 | 29.314815 | 87 | 0.490831 | 4.621469 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/player/filter/selection/SelectFilterSongViewModel.kt | 1 | 1176 | package be.florien.anyflow.feature.player.filter.selection
import be.florien.anyflow.data.DataRepository
import be.florien.anyflow.data.local.model.DbSongDisplay
import be.florien.anyflow.data.view.Filter
import be.florien.anyflow.player.FiltersManager
import javax.inject.Inject
class SelectFilterSongViewModel @Inject constructor(val dataRepository: DataRepository, filtersManager: FiltersManager) : SelectFilterViewModel(filtersManager) {
override val itemDisplayType = ITEM_LIST
override fun getUnfilteredPagingList() = dataRepository.getSongs(::convert)
override fun getFilteredPagingList(search: String) = dataRepository.getSongsFiltered(search, ::convert)
override suspend fun getFoundFilters(search: String): List<FilterItem> = dataRepository.getSongsFilteredList(search, ::convert)
override fun getFilter(filterValue: FilterItem) = Filter.SongIs(filterValue.id, filterValue.displayName, filterValue.artUrl)
private fun convert(song: DbSongDisplay) =
FilterItem(song.id, "${song.title}\nby ${song.artistName}\nfrom ${song.albumName}", song.art, filtersManager.isFilterInEdition(Filter.SongIs(song.id, song.title, song.art)))
} | gpl-3.0 | c9aabbd20c8c730f74e5d8e60eea20b6 | 55.047619 | 185 | 0.801871 | 4.155477 | false | false | false | false |
mockk/mockk | modules/mockk-dsl/src/jvmMain/kotlin/io/mockk/MockKSettings.kt | 1 | 1457 | package io.mockk
import java.util.*
actual object MockKSettings {
private val properties = Properties()
init {
MockKSettings::class.java
.getResourceAsStream("settings.properties")
?.use(properties::load)
}
private fun booleanProperty(property: String, defaultValue: String) =
properties.getProperty(
property,
defaultValue
)!!.toBoolean()
actual val relaxed: Boolean
get() = booleanProperty("relaxed", "false")
actual val relaxUnitFun: Boolean
get() = booleanProperty("relaxUnitFun", "false")
actual val recordPrivateCalls: Boolean
get() = booleanProperty("recordPrivateCalls", "false")
actual val stackTracesOnVerify: Boolean
get() = booleanProperty("stackTracesOnVerify", "true")
actual val stackTracesAlignment: StackTracesAlignment
get() = stackTracesAlignmentValueOf(properties.getProperty("stackTracesAlignment", "center"))
fun setRelaxed(value: Boolean) {
properties.setProperty("relaxed", value.toString());
}
fun setRelaxUnitFun(value: Boolean) {
properties.setProperty("relaxUnitFun", value.toString());
}
fun setRecordPrivateCalls(value: Boolean) {
properties.setProperty("recordPrivateCalls", value.toString());
}
fun setStackTracesAlignment(value: String) {
properties.setProperty("stackTracesAlignment", value)
}
}
| apache-2.0 | 2c85c9246da5d387310f1c6836ef5e42 | 27.019231 | 101 | 0.66987 | 5.059028 | false | false | false | false |
devmpv/chan-reactor | src/main/kotlin/com/devmpv/model/Thread.kt | 1 | 544 | package com.devmpv.model
import javax.persistence.*
/**
* Thread entity based on [Message]
*
* @author devmpv
*/
@Entity
class Thread(
@ManyToOne
@JoinColumn(name = "board_id", nullable = false)
var board: Board? = null,
title: String,
text: String
) : Message(title, text) {
@OneToMany(cascade = arrayOf(CascadeType.ALL), fetch = FetchType.LAZY, mappedBy = "thread", targetEntity = Message::class)
var messages: MutableSet<Message> = HashSet()
constructor() : this(null, "", "")
}
| mit | f0e83ef0db1fc32602243671c4cafdd8 | 20.76 | 126 | 0.628676 | 3.804196 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/Shaders3D.kt | 1 | 8923 | package com.soywiz.korge3d
import com.soywiz.korag.shader.*
import com.soywiz.korag.shader.gl.*
import com.soywiz.korge.internal.*
@Korge3DExperimental
open class Shaders3D {
//@ThreadLocal
private val programCache = LinkedHashMap<String, Program>()
var printShaders = false
@Suppress("RemoveCurlyBracesFromTemplate")
fun getProgram3D(nlights: Int, nweights: Int, meshMaterial: Material3D?, hasTexture: Boolean): Program {
return programCache.getOrPut("program_L${nlights}_W${nweights}_M${meshMaterial?.kind}_T${hasTexture}") {
StandardShader3D(nlights, nweights, meshMaterial, hasTexture).program.apply {
if (printShaders) {
println(GlslGenerator(kind = ShaderType.VERTEX).generate(this.vertex.stm))
println(GlslGenerator(kind = ShaderType.FRAGMENT).generate(this.fragment.stm))
}
}
}
}
companion object {
val u_Shininess = Uniform("u_shininess", VarType.Float1)
val u_IndexOfRefraction = Uniform("u_indexOfRefraction", VarType.Float1)
val u_AmbientColor = Uniform("u_ambientColor", VarType.Float4)
val u_ProjMat = Uniform("u_ProjMat", VarType.Mat4)
val u_ViewMat = Uniform("u_ViewMat", VarType.Mat4)
val u_BindShapeMatrix = Uniform("u_BindShapeMat", VarType.Mat4)
val u_BindShapeMatrixInv = Uniform("u_BindShapeMatInv", VarType.Mat4)
val u_ModMat = Uniform("u_ModMat", VarType.Mat4)
val u_NormMat = Uniform("u_NormMat", VarType.Mat4)
//val MAX_BONE_MATS = 16
val MAX_BONE_MATS = 64
val u_BoneMats = Uniform("u_BoneMats", VarType.Mat4, arrayCount = MAX_BONE_MATS)
val u_TexUnit = Uniform("u_TexUnit", VarType.TextureUnit)
val a_pos = Attribute("a_Pos", VarType.Float3, normalized = false, precision = Precision.HIGH)
val a_norm = Attribute("a_Norm", VarType.Float3, normalized = false, precision = Precision.HIGH)
val a_tex = Attribute("a_TexCoords", VarType.Float2, normalized = false, precision = Precision.MEDIUM)
val a_boneIndex = Array(4) { Attribute("a_BoneIndex$it", VarType.Float4, normalized = false) }
val a_weight = Array(4) { Attribute("a_Weight$it", VarType.Float4, normalized = false) }
val a_col = Attribute("a_Col", VarType.Float3, normalized = true)
val v_col = Varying("v_Col", VarType.Float3)
val v_Pos = Varying("v_Pos", VarType.Float3, precision = Precision.HIGH)
val v_Norm = Varying("v_Norm", VarType.Float3, precision = Precision.HIGH)
val v_TexCoords = Varying("v_TexCoords", VarType.Float2, precision = Precision.MEDIUM)
val v_Temp1 = Varying("v_Temp1", VarType.Float4)
val programColor3D = Program(
vertex = VertexShader {
SET(v_col, a_col)
SET(out, u_ProjMat * u_ModMat * u_ViewMat * vec4(a_pos, 1f.lit))
},
fragment = FragmentShader {
SET(out, vec4(v_col, 1f.lit))
//SET(out, vec4(1f.lit, 1f.lit, 1f.lit, 1f.lit))
},
name = "programColor3D"
)
val lights = (0 until 4).map { LightAttributes(it) }
val emission = MaterialLightUniform("emission")
val ambient = MaterialLightUniform("ambient")
val diffuse = MaterialLightUniform("diffuse")
val specular = MaterialLightUniform("specular")
val layoutPosCol = VertexLayout(a_pos, a_col)
private val FLOATS_PER_VERTEX = layoutPosCol.totalSize / Int.SIZE_BYTES /*Float.SIZE_BYTES is not defined*/
}
class LightAttributes(val id: Int) {
val u_sourcePos = Uniform("light${id}_pos", VarType.Float3)
val u_color = Uniform("light${id}_color", VarType.Float4)
val u_attenuation = Uniform("light${id}_attenuation", VarType.Float3)
}
class MaterialLightUniform(val kind: String) {
//val mat = Material3D
val u_color = Uniform("u_${kind}_color", VarType.Float4)
val u_texUnit = Uniform("u_${kind}_texUnit", VarType.TextureUnit)
}
}
@Korge3DExperimental
data class StandardShader3D(
override val nlights: Int,
override val nweights: Int,
override val meshMaterial: Material3D?,
override val hasTexture: Boolean
) : AbstractStandardShader3D()
@Korge3DExperimental
abstract class AbstractStandardShader3D() : BaseShader3D() {
abstract val nlights: Int
abstract val nweights: Int
abstract val meshMaterial: Material3D?
abstract val hasTexture: Boolean
override fun Program.Builder.vertex() = Shaders3D.run {
val modelViewMat = createTemp(VarType.Mat4)
val normalMat = createTemp(VarType.Mat4)
val boneMatrix = createTemp(VarType.Mat4)
val localPos = createTemp(VarType.Float4)
val localNorm = createTemp(VarType.Float4)
val skinPos = createTemp(VarType.Float4)
if (nweights == 0) {
//SET(boneMatrix, mat4Identity())
SET(localPos, vec4(a_pos, 1f.lit))
SET(localNorm, vec4(a_norm, 0f.lit))
} else {
SET(localPos, vec4(0f.lit))
SET(localNorm, vec4(0f.lit))
SET(skinPos, u_BindShapeMatrix * vec4(a_pos["xyz"], 1f.lit))
for (wIndex in 0 until nweights) {
IF(getBoneIndex(wIndex) ge 0.lit) {
SET(boneMatrix, getBone(wIndex))
SET(localPos, localPos + boneMatrix * vec4(skinPos["xyz"], 1f.lit) * getWeight(wIndex))
SET(localNorm, localNorm + boneMatrix * vec4(a_norm, 0f.lit) * getWeight(wIndex))
}
}
SET(localPos, u_BindShapeMatrixInv * localPos)
}
SET(modelViewMat, u_ModMat * u_ViewMat)
SET(normalMat, u_NormMat)
SET(v_Pos, vec3(modelViewMat * (vec4(localPos["xyz"], 1f.lit))))
SET(v_Norm, vec3(normalMat * normalize(vec4(localNorm["xyz"], 1f.lit))))
if (hasTexture) SET(v_TexCoords, a_tex["xy"])
SET(out, u_ProjMat * vec4(v_Pos, 1f.lit))
}
override fun Program.Builder.fragment() {
val meshMaterial = meshMaterial
if (meshMaterial != null) {
computeMaterialLightColor(out, Shaders3D.diffuse, meshMaterial.diffuse)
} else {
SET(out, vec4(.5f.lit, .5f.lit, .5f.lit, 1f.lit))
}
for (n in 0 until nlights) {
addLight(Shaders3D.lights[n], out)
}
//SET(out, vec4(v_Temp1.x, v_Temp1.y, v_Temp1.z, 1f.lit))
}
open fun Program.Builder.computeMaterialLightColor(out: Operand, uniform: Shaders3D.MaterialLightUniform, light: Material3D.Light) {
when (light) {
is Material3D.LightColor -> {
SET(out, uniform.u_color)
}
is Material3D.LightTexture -> {
SET(out, vec4(texture2D(uniform.u_texUnit, Shaders3D.v_TexCoords["xy"])["rgb"], 1f.lit))
}
else -> error("Unsupported MateriaList: $light")
}
}
fun Program.Builder.mat4Identity() = Program.Func("mat4",
1f.lit, 0f.lit, 0f.lit, 0f.lit,
0f.lit, 1f.lit, 0f.lit, 0f.lit,
0f.lit, 0f.lit, 1f.lit, 0f.lit,
0f.lit, 0f.lit, 0f.lit, 1f.lit
)
open fun Program.Builder.addLight(light: Shaders3D.LightAttributes, out: Operand) {
val v = Shaders3D.v_Pos
val N = Shaders3D.v_Norm
val L = createTemp(VarType.Float3)
val E = createTemp(VarType.Float3)
val R = createTemp(VarType.Float3)
val attenuation = createTemp(VarType.Float1)
val dist = createTemp(VarType.Float1)
val NdotL = createTemp(VarType.Float1)
val lightDir = createTemp(VarType.Float3)
SET(L, normalize(light.u_sourcePos["xyz"] - v))
SET(E, normalize(-v)) // we are in Eye Coordinates, so EyePos is (0,0,0)
SET(R, normalize(-reflect(L, N)))
val constantAttenuation = light.u_attenuation.x
val linearAttenuation = light.u_attenuation.y
val quadraticAttenuation = light.u_attenuation.z
SET(lightDir, light.u_sourcePos["xyz"] - Shaders3D.v_Pos)
SET(dist, length(lightDir))
//SET(dist, length(vec3(4f.lit, 1f.lit, 6f.lit) - vec3(0f.lit, 0f.lit, 0f.lit)))
SET(attenuation, 1f.lit / (constantAttenuation + linearAttenuation * dist + quadraticAttenuation * dist * dist))
//SET(attenuation, 1f.lit / (1f.lit + 0f.lit * dist + 0.00111109f.lit * dist * dist))
//SET(attenuation, 0.9.lit)
SET(NdotL, max(dot(normalize(N), normalize(lightDir)), 0f.lit))
IF(NdotL ge 0f.lit) {
SET(out["rgb"], out["rgb"] + (light.u_color["rgb"] * NdotL + Shaders3D.u_AmbientColor["rgb"]) * attenuation * Shaders3D.u_Shininess)
}
//SET(out["rgb"], out["rgb"] * attenuation)
//SET(out["rgb"], out["rgb"] + clamp(light.diffuse * max(dot(N, L), 0f.lit), 0f.lit, 1f.lit)["rgb"])
//SET(out["rgb"], out["rgb"] + clamp(light.specular * pow(max(dot(R, E), 0f.lit), 0.3f.lit * u_Shininess), 0f.lit, 1f.lit)["rgb"])
}
fun Program.Builder.getBoneIndex(index: Int): Operand = int(Shaders3D.a_boneIndex[index / 4][index % 4])
fun Program.Builder.getWeight(index: Int): Operand = Shaders3D.a_weight[index / 4][index % 4]
fun Program.Builder.getBone(index: Int): Operand = Shaders3D.u_BoneMats[getBoneIndex(index)]
}
@Korge3DExperimental
abstract class BaseShader3D {
abstract fun Program.Builder.vertex()
abstract fun Program.Builder.fragment()
val program by lazy {
Program(
vertex = VertexShader { vertex() },
fragment = FragmentShader { fragment() },
name = [email protected]()
)
}
}
private fun Program.Builder.transpose(a: Operand) = Program.Func("transpose", a)
private fun Program.Builder.inverse(a: Operand) = Program.Func("inverse", a)
private fun Program.Builder.int(a: Operand) = Program.Func("int", a)
private operator fun Operand.get(index: Operand) = Program.ArrayAccess(this, index)
| apache-2.0 | a08227af385559333fdf82c61ac7a63a | 36.649789 | 135 | 0.703351 | 2.846252 | false | false | false | false |
pr0ves/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/pokemon/CatchablePokemon.kt | 2 | 7008 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.pokemon
import POGOProtos.Data.Capture.CaptureProbabilityOuterClass.CaptureProbability
import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId
import POGOProtos.Networking.Responses.CatchPokemonResponseOuterClass.CatchPokemonResponse.CatchStatus
import ink.abb.pogo.api.cache.Inventory
import ink.abb.pogo.api.cache.MapPokemon
import ink.abb.pogo.api.request.CatchPokemon
import ink.abb.pogo.api.request.UseItemCapture
import ink.abb.pogo.scraper.util.Log
import java.util.concurrent.atomic.AtomicInteger
/**
* Extension function to make the code more readable in the CatchOneNearbyPokemon task
*/
fun MapPokemon.catch(normalizedHitPosition: Double = 1.0,
normalizedReticleSize: Double = 1.95 + Math.random() * 0.05,
spinModifier: Double = 0.85 + Math.random() * 0.15,
ballType: ItemId = ItemId.ITEM_POKE_BALL): rx.Observable<CatchPokemon> {
return poGoApi.queueRequest(CatchPokemon()
.withEncounterId(encounterId)
.withHitPokemon(true)
.withNormalizedHitPosition(normalizedHitPosition)
.withNormalizedReticleSize(normalizedReticleSize)
.withPokeball(ballType)
.withSpinModifier(spinModifier)
.withSpawnPointId(spawnPointId))
}
fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false, waitBetweenThrows: Boolean = false, amount: Int): rx.Observable<CatchPokemon> {
var catch: rx.Observable<CatchPokemon>
var numThrows = 0
do {
catch = catch(captureProbability, inventory, desiredCatchProbability, alwaysCurve, allowBerries, randomBallThrows)
val first = catch.toBlocking().first()
if (first != null) {
val result = first.response
if (result.status != CatchStatus.CATCH_ESCAPE && result.status != CatchStatus.CATCH_MISSED) {
break
}
if (waitBetweenThrows) {
val waitTime = (Math.random() * 2900 + 100)
Log.blue("Pokemon got out of the ball. Waiting for ca. ${Math.round(waitTime / 1000)} second(s) until next throw")
Thread.sleep(waitTime.toLong())
}
numThrows++
}
} while (amount < 0 || numThrows < amount)
return catch
}
fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false): rx.Observable<CatchPokemon> {
val ballTypes = captureProbability.pokeballTypeList
val probabilities = captureProbability.captureProbabilityList
//Log.yellow(probabilities.toString())
var ball: ItemId? = null
var needCurve = alwaysCurve
var needRazzBerry = false
var highestAvailable: ItemId? = null
var catchProbability = 0f
for ((index, ballType) in ballTypes.withIndex()) {
val probability = probabilities.get(index)
val ballAmount = inventory.items.getOrPut(ballType, { AtomicInteger(0) }).get()
if (ballAmount == 0) {
//Log.yellow("Don't have any ${ballType}")
continue
} else {
//Log.yellow("Have ${ballAmount} of ${ballType}")
highestAvailable = ballType
catchProbability = probability
}
if (probability >= desiredCatchProbability) {
catchProbability = probability
ball = ballType
break
} else if (probability >= desiredCatchProbability - 0.1) {
ball = ballType
needCurve = true
catchProbability = probability + 0.1f
break
} else if (probability >= desiredCatchProbability - 0.2) {
ball = ballType
needCurve = true
needRazzBerry = true
catchProbability = probability + 0.2f
break
}
}
if (highestAvailable == null) {
/*Log.red("No pokeballs?!")
Log.red("Has pokeballs: ${itemBag.hasPokeballs()}")*/
return rx.Observable.just(null)
}
if (ball == null) {
ball = highestAvailable
needCurve = true
needRazzBerry = true
catchProbability += 0.2f
}
var logMessage = "Using ${ball.name}"
val razzBerryCount = inventory.items.getOrPut(ItemId.ITEM_RAZZ_BERRY, { AtomicInteger(0) }).get()
if (allowBerries && razzBerryCount > 0 && needRazzBerry) {
logMessage += "; Using Razz Berry"
poGoApi.queueRequest(UseItemCapture().withEncounterId(encounterId).withItemId(ItemId.ITEM_RAZZ_BERRY).withSpawnPointId(spawnPointId)).toBlocking()
}
if (needCurve) {
logMessage += "; Using curve"
}
logMessage += "; achieved catch probability: ${Math.round(catchProbability * 100.0)}%, desired: ${Math.round(desiredCatchProbability * 100.0)}%"
Log.yellow(logMessage)
//excellent throw value
var recticleSize = 1.7 + Math.random() * 0.3
if (randomBallThrows) {
//excellent throw if capture probability is still less then desired
if (catchProbability <= desiredCatchProbability) {
// the recticle size is already set for an excelent throw
}
//if catch probability is too high...
else {
// we substract the difference from the recticle size, the lower this size, the worse the ball
recticleSize = 1 + Math.random() - (catchProbability - desiredCatchProbability) * 0.5
if (recticleSize > 2) {
recticleSize = 2.0
} else if (recticleSize < 0) {
recticleSize = 0.01
}
if (recticleSize < 1) {
Log.blue("Your trainer threw a normal ball, no xp/catching bonus, good for pretending to be not a bot however")
} else if (recticleSize >= 1 && recticleSize < 1.3) {
Log.blue("Your trainer got a 'Nice throw' - nice")
} else if (recticleSize >= 1.3 && recticleSize < 1.7) {
Log.blue("Your trainer got a 'Great throw!'")
} else if (recticleSize > 1.7) {
Log.blue("Your trainer got an 'Excellent throw!' - that's suspicious, might he be a bot?")
}
}
}
return catch(
normalizedHitPosition = 1.0,
normalizedReticleSize = recticleSize,
spinModifier = if (needCurve) 0.85 + Math.random() * 0.15 else Math.random() * 0.10,
ballType = ball
)
}
| gpl-3.0 | 5df9521ea287fb021aafd2369e66dafa | 41.993865 | 291 | 0.640696 | 4.265368 | false | false | false | false |
RuntimeModels/chazm | chazm-model/src/main/kotlin/runtimemodels/chazm/model/parser/entity/ParsePolicy.kt | 2 | 1114 | package runtimemodels.chazm.model.parser.entity
import runtimemodels.chazm.api.entity.PolicyId
import runtimemodels.chazm.api.organization.Organization
import runtimemodels.chazm.model.entity.EntityFactory
import runtimemodels.chazm.model.entity.impl.DefaultPolicyId
import runtimemodels.chazm.model.parser.attribute
import runtimemodels.chazm.model.parser.build
import javax.inject.Inject
import javax.inject.Singleton
import javax.xml.namespace.QName
import javax.xml.stream.events.StartElement
@Singleton
internal class ParsePolicy @Inject constructor(
private val entityFactory: EntityFactory
) {
fun canParse(qName: QName): Boolean = POLICY_ELEMENT == qName.localPart
operator fun invoke(element: StartElement, organization: Organization, policies: MutableMap<String, PolicyId>) {
val id = DefaultPolicyId(element attribute NAME_ATTRIBUTE)
build(id, policies, element, entityFactory::build, organization::add)
}
companion object {
private const val POLICY_ELEMENT = "Policy" //$NON-NLS-1$
private const val NAME_ATTRIBUTE = "name" //$NON-NLS-1$
}
}
| apache-2.0 | 95c631cfdc50fe68fd2b07ce17763995 | 37.413793 | 116 | 0.778276 | 4.268199 | false | false | false | false |
DuckBoss/Programming-Challenges | Fibonacci_Numbers/FibonacciNumbers.kt | 1 | 666 | fun main(args: Array<String>) {
if(args.size != 3) {
println("This program requires 2 starting integers, and the max terms!")
return
}
println("Program Started...")
val start1: Int = args[0].toInt()
val start2: Int = args[1].toInt()
var maxCount: Int = args[2].toInt()
if(maxCount < 2) {
maxCount = 2
}
val fullList = IntArray(maxCount)
fullList[0] = start1
fullList[1] = start2
for(i in 2..maxCount-1) {
fullList[i] = fullList[i-1]+fullList[i-2]
}
print("Result - {")
for(fib in fullList) {
print(" %d".format(fib))
}
print(" }\n")
println()
}
| unlicense | 9f7f705d900f3c547995f3a0032d0704 | 18.588235 | 80 | 0.543544 | 3.363636 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/health/service/HealthCareServices.kt | 1 | 4022 | package ffc.app.health.service
import ffc.api.ApiErrorException
import ffc.api.FfcCentral
import ffc.app.mockRepository
import ffc.app.util.RepoCallback
import ffc.app.util.TaskCallback
import ffc.entity.gson.toJson
import ffc.entity.healthcare.HealthCareService
import retrofit2.dsl.enqueue
import timber.log.Timber
import java.util.concurrent.ConcurrentHashMap
internal interface HealthCareServices {
fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit)
fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit)
fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit)
}
private class InMemoryHealthCareServices(val personId: String) : HealthCareServices {
override fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) {
val callback = TaskCallback<HealthCareService>().apply(dslCallback)
repository[personId]?.let {
it.remove(service)
it.add(service)
}
callback.result(service)
}
override fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) {
require(services.patientId == personId) { "Not match patinet id" }
Timber.d("homevisit = %s", services.toJson())
val callback = TaskCallback<HealthCareService>().apply(dslCallback)
val list = repository[personId] ?: mutableListOf()
list.add(services)
repository[personId] = list
callback.result.invoke(services)
}
override fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit) {
val callback = RepoCallback<List<HealthCareService>>().apply(dsl)
callback.always?.invoke()
val list = repository[personId] ?: listOf<HealthCareService>()
if (list.isNotEmpty()) {
callback.onFound!!.invoke(list)
} else {
callback.onNotFound!!.invoke()
}
}
companion object {
val repository: ConcurrentHashMap<String, MutableList<HealthCareService>> = ConcurrentHashMap()
}
}
private class ApiHealthCareServices(
val org: String,
val person: String
) : HealthCareServices {
override fun update(service: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) {
val callback = TaskCallback<HealthCareService>().apply(dslCallback)
api.put(org, service).enqueue {
onSuccess { callback.result(body()!!) }
onError { callback.expception?.invoke(ApiErrorException(this)) }
onFailure { callback.expception?.invoke(it) }
}
}
val api = FfcCentral().service<HealthCareServiceApi>()
override fun add(services: HealthCareService, dslCallback: TaskCallback<HealthCareService>.() -> Unit) {
val callback = TaskCallback<HealthCareService>().apply(dslCallback)
api.post(services, org).enqueue {
onSuccess {
callback.result.invoke(body()!!)
}
onError {
callback.expception?.invoke(ApiErrorException(this))
}
onFailure {
callback.expception?.invoke(it)
}
}
}
override fun all(dsl: RepoCallback<List<HealthCareService>>.() -> Unit) {
val callback = RepoCallback<List<HealthCareService>>().apply(dsl)
api.get(org, person).enqueue {
onSuccess {
callback.onFound!!.invoke(body()!!)
}
onClientError {
callback.onNotFound!!.invoke()
}
onServerError {
callback.onFail!!.invoke(ApiErrorException(this))
}
onFailure {
callback.onFail!!.invoke(it)
}
}
}
}
internal fun healthCareServicesOf(personId: String, orgId: String): HealthCareServices = if (mockRepository)
InMemoryHealthCareServices(personId) else ApiHealthCareServices(orgId, personId)
| apache-2.0 | 329642b7db213b7f170df79343bed913 | 34.59292 | 110 | 0.651169 | 4.765403 | false | false | false | false |
plombardi89/kbaseball | common/src/main/kotlin/kbaseball/email/SimpleEmailer.kt | 1 | 1992 | /*
Copyright (C) 2015 Philip Lombardi <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package kbaseball.email
import org.apache.commons.mail.HtmlEmail
import org.slf4j.LoggerFactory
import javax.mail.Authenticator
/**
* A class that can send emails and has limited customizability.
*
* @author [email protected]
* @since 1.0
*/
data class SimpleEmailer(
val host: String,
val port: Int,
val authenticator: Authenticator,
val from: String
): Emailer {
private val log = LoggerFactory.getLogger(SimpleEmailer::class.java)
private fun buildBaseEmail(): HtmlEmail {
val base = HtmlEmail()
base.hostName = host
base.setSmtpPort(port)
base.setAuthenticator(authenticator)
base.setFrom(from)
base.setStartTLSEnabled(true)
return base
}
override fun sendEmail(to: Set<String>, subject: String, content: EmailContent, cc: Set<String>, bcc: Set<String>) {
log.debug("sending email (to: {}, subject: {})", to, subject)
val email = buildBaseEmail()
email.setSubject(subject)
email.addTo(*to.toTypedArray())
email.setHtmlMsg(content.html)
if (content.alternateText != null) {
email.setTextMsg(content.alternateText)
}
if (cc.isNotEmpty()) {
email.addCc(*cc.toTypedArray())
}
if (bcc.isNotEmpty()) {
email.addBcc(*bcc.toTypedArray())
}
email.send()
}
} | agpl-3.0 | 0dd37063f934bb64a8a60306b018bb37 | 27.070423 | 118 | 0.718373 | 3.883041 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheetConfigurationKtx.kt | 1 | 4527 | package com.stripe.android.paymentsheet
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import com.stripe.android.ui.core.PaymentsTheme
import com.stripe.android.ui.core.PaymentsThemeDefaults
import com.stripe.android.ui.core.PrimaryButtonColors
import com.stripe.android.ui.core.PrimaryButtonShape
import com.stripe.android.ui.core.PrimaryButtonTypography
import java.security.InvalidParameterException
internal fun PaymentSheet.Configuration.validate() {
// These are not localized as they are not intended to be displayed to a user.
when {
merchantDisplayName.isBlank() -> {
throw InvalidParameterException(
"When a Configuration is passed to PaymentSheet," +
" the Merchant display name cannot be an empty string."
)
}
customer?.id?.isBlank() == true -> {
throw InvalidParameterException(
"When a CustomerConfiguration is passed to PaymentSheet," +
" the Customer ID cannot be an empty string."
)
}
customer?.ephemeralKeySecret?.isBlank() == true -> {
throw InvalidParameterException(
"When a CustomerConfiguration is passed to PaymentSheet, " +
"the ephemeralKeySecret cannot be an empty string."
)
}
}
}
internal fun PaymentSheet.Appearance.parseAppearance() {
PaymentsTheme.colorsLightMutable = PaymentsThemeDefaults.colorsLight.copy(
component = Color(colorsLight.component),
componentBorder = Color(colorsLight.componentBorder),
componentDivider = Color(colorsLight.componentDivider),
onComponent = Color(colorsLight.onComponent),
subtitle = Color(colorsLight.subtitle),
placeholderText = Color(colorsLight.placeholderText),
appBarIcon = Color(colorsLight.appBarIcon),
materialColors = lightColors(
primary = Color(colorsLight.primary),
surface = Color(colorsLight.surface),
onSurface = Color(colorsLight.onSurface),
error = Color(colorsLight.error)
)
)
PaymentsTheme.colorsDarkMutable = PaymentsThemeDefaults.colorsDark.copy(
component = Color(colorsDark.component),
componentBorder = Color(colorsDark.componentBorder),
componentDivider = Color(colorsDark.componentDivider),
onComponent = Color(colorsDark.onComponent),
subtitle = Color(colorsDark.subtitle),
placeholderText = Color(colorsDark.placeholderText),
appBarIcon = Color(colorsDark.appBarIcon),
materialColors = darkColors(
primary = Color(colorsDark.primary),
surface = Color(colorsDark.surface),
onSurface = Color(colorsDark.onSurface),
error = Color(colorsDark.error)
)
)
PaymentsTheme.shapesMutable = PaymentsThemeDefaults.shapes.copy(
cornerRadius = shapes.cornerRadiusDp,
borderStrokeWidth = shapes.borderStrokeWidthDp
)
PaymentsTheme.typographyMutable = PaymentsThemeDefaults.typography.copy(
fontFamily = typography.fontResId,
fontSizeMultiplier = typography.sizeScaleFactor
)
PaymentsTheme.primaryButtonStyle = PaymentsThemeDefaults.primaryButtonStyle.copy(
colorsLight = PrimaryButtonColors(
background = Color(primaryButton.colorsLight.background ?: colorsLight.primary),
onBackground = Color(primaryButton.colorsLight.onBackground),
border = Color(primaryButton.colorsLight.border)
),
colorsDark = PrimaryButtonColors(
background = Color(primaryButton.colorsDark.background ?: colorsDark.primary),
onBackground = Color(primaryButton.colorsDark.onBackground),
border = Color(primaryButton.colorsDark.border)
),
shape = PrimaryButtonShape(
cornerRadius = primaryButton.shape.cornerRadiusDp ?: shapes.cornerRadiusDp,
borderStrokeWidth =
primaryButton.shape.borderStrokeWidthDp ?: shapes.borderStrokeWidthDp
),
typography = PrimaryButtonTypography(
fontFamily = primaryButton.typography.fontResId ?: typography.fontResId,
fontSize = primaryButton.typography.fontSizeSp?.sp
?: (PaymentsThemeDefaults.typography.largeFontSize * typography.sizeScaleFactor)
)
)
}
| mit | 011221b4fa0db74286c36c7a6c999743 | 42.951456 | 96 | 0.685222 | 5.197474 | false | false | false | false |
slartus/4pdaClient-plus | app/src/main/java/org/softeg/slartus/forpdaplus/tabs/TabsManager.kt | 1 | 1657 | package org.softeg.slartus.forpdaplus.tabs
class TabsManager {
private object Holder {
val INSTANCE = TabsManager()
}
companion object {
const val TAG = "TabsManager"
@JvmStatic
val instance by lazy { Holder.INSTANCE }
}
private var currentFragmentTag: String? = null
private var tabIterator = 0
fun getTabIterator(): Int {
return tabIterator
}
fun setTabIterator(tabIterator: Int) {
this.tabIterator = tabIterator
}
fun clearTabIterator() {
tabIterator = 0
}
fun plusTabIterator() {
tabIterator++
}
fun getCurrentFragmentTag(): String? {
return currentFragmentTag
}
fun setCurrentFragmentTag(s: String?) {
currentFragmentTag = s
}
private val mTabItems = mutableListOf<TabItem>()
fun getTabItems(): MutableList<TabItem> {
return mTabItems
}
fun getLastTabPosition(delPos: Int): Int {
var delPos = delPos
if (mTabItems.size - 1 < delPos) delPos--
return delPos
}
fun isContainsByTag(tag: String?): Boolean {
for (item in getTabItems()) if (item.tag == tag) return true
return false
}
fun isContainsByUrl(url: String?): Boolean {
for (item in getTabItems()) if (item.url == url) return true
return false
}
fun getTabByTag(tag: String?): TabItem? {
for (item in getTabItems()) if (item.tag == tag) return item
return null
}
fun getTabByUrl(url: String): TabItem? {
for (item in getTabItems()) if (item.url == url) return item
return null
}
} | apache-2.0 | 8b227b5f6da8313954c4021341804a1f | 21.405405 | 68 | 0.604104 | 4.326371 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/ConnectExampleActivity.kt | 1 | 1583 | package com.stripe.example.activity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.stripe.example.databinding.ConnectExampleActivityBinding
class ConnectExampleActivity : StripeIntentActivity() {
private val viewBinding: ConnectExampleActivityBinding by lazy {
ConnectExampleActivityBinding.inflate(layoutInflater)
}
private val snackbarController: SnackbarController by lazy {
SnackbarController(viewBinding.coordinator)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
viewModel.inProgress.observe(this, { enableUi(!it) })
viewModel.status.observe(this, Observer(viewBinding.status::setText))
viewBinding.payNow.setOnClickListener {
viewBinding.cardWidget.paymentMethodCreateParams?.let {
val connectAccount =
viewBinding.connectAccount.text.toString().takeIf(String::isNotBlank)
createAndConfirmPaymentIntent("us", it, stripeAccountId = connectAccount)
} ?: showSnackbar("Missing card details")
}
}
private fun showSnackbar(message: String) {
snackbarController.show(message)
}
private fun enableUi(enable: Boolean) {
viewBinding.progressBar.visibility = if (enable) View.INVISIBLE else View.VISIBLE
viewBinding.payNow.isEnabled = enable
viewBinding.cardWidget.isEnabled = enable
viewBinding.connectAccount.isEnabled = enable
}
}
| mit | a28e0d57d11f4b96a8250496328d3b68 | 36.690476 | 89 | 0.716993 | 5.329966 | false | false | false | false |
ebean-orm-examples/example-kotlin | src/test/kotlin/org/example/domain/LoadExampleData.kt | 1 | 4700 | package org.example.domain
import io.ebean.Ebean
import io.ebean.EbeanServer
class LoadExampleData {
companion object Once {
var runOnce: Boolean = false
}
private val server: EbeanServer = Ebean.getDefaultServer()
private var contactEmailNum: Int = 1
fun load() {
if (runOnce) {
return
}
runOnce = true
val txn = server.beginTransaction()
try {
if (Country.query().findCount() > 0) {
return;
}
//deleteAll()
insertCountries()
insertProducts()
insertTestCustAndOrders()
txn.commit()
} finally {
txn.end()
}
}
// private fun deleteAll() {
// OrderDetail.query().delete()
// Order.query().delete()
// Contact.query().delete()
// Customer.query().delete()
// Address.query().delete()
// Country.query().delete()
// Product.query().delete()
// }
private fun insertCountries() {
Country("NZ", "New Zealand").save()
Country("AU", "Australia").save()
}
private fun insertProducts() {
Product("Chair", "C001").save()
Product("Desk", "DSK1").save()
Product("C002", "Computer").save()
val product = Product(sku = "C003", name = "Printer")
product.description = "A Colour printer"
product.save()
}
private fun insertTestCustAndOrders() {
val cust1 = insertCustomer("Rob")
val cust2 = insertCustomerNoAddress()
insertCustomerFiona()
insertCustomerNoContacts("NoContactsCust")
insertCustomer("Roberto")
createOrder1(cust1)
createOrder2(cust2)
createOrder3(cust1)
createOrder4(cust1)
}
private fun insertCustomerFiona(): Customer {
val c = createCustomer("Fiona", "12 Apple St", "West Coast Rd", 1)
c.contacts.add(createContact("Fiona", "Black"))
c.contacts.add(createContact("Tracy", "Red"))
c.save()
return c
}
private fun createContact(firstName: String, lastName: String): Contact {
val contact = Contact(firstName, lastName)
contact.email = (contact.lastName + (contactEmailNum++) + "@test.com").toLowerCase()
return contact
}
private fun insertCustomerNoContacts(name: String): Customer {
val customer = createCustomer(name, "15 Kumera Way", "Bos town", 1)
customer.save()
return customer
}
private fun insertCustomerNoAddress(): Customer {
val customer = Customer("Customer NoAddress")
customer.contacts.add(createContact("Jack", "Black"))
customer.save()
return customer
}
private fun insertCustomer(name: String): Customer {
val customer = createCustomer(name, "1 Banana St", "P.O.Box 1234", 1)
customer.save()
return customer
}
private fun createCustomer(name: String, shippingStreet: String?, billingStreet: String?, contactSuffix: Int): Customer {
val customer = Customer(name)
if (contactSuffix > 0) {
customer.contacts.add(Contact("Jim$contactSuffix", "Cricket"))
customer.contacts.add(Contact("Fred$contactSuffix", "Blue"))
customer.contacts.add(Contact("Bugs$contactSuffix", "Bunny"))
}
val nz = Country.ref("NZ")
if (shippingStreet != null) {
val shipAddress = Address(shippingStreet, nz)
shipAddress.line2 = "Sandringham"
shipAddress.city = "Auckland"
customer.shippingAddress = shipAddress
}
if (billingStreet != null) {
val address = Address(
line1 = billingStreet,
line2 = "St Lukes",
city = "Auckland",
country = nz)
with(address) {
line1 = billingStreet
line2 = "St Lukes"
city = "Auckland"
country = nz
}
customer.billingAddress =
with(Address(billingStreet, nz)) {
line2 = "St Lukes"
city = "Auckland"
this
}
}
return customer
}
private fun createOrder1(customer: Customer): Order {
return with(Order(customer)) {
addItem(Product.ref(1), 22, 12.0)
details.add(OrderDetail(Product.ref(1), 5, 10.50))
details.add(OrderDetail(Product.ref(2), 3, 1.10))
details.add(OrderDetail(Product.ref(3), 1, 2.00))
save()
this
}
}
private fun createOrder2(customer: Customer) {
with(Order(customer)) {
status = Order.Status.SHIPPED
this.details.add(OrderDetail(Product.ref(1), 4, 10.50))
save()
}
}
private fun createOrder3(customer: Customer) {
with(Order(customer)) {
status = Order.Status.COMPLETE
this.details.add(OrderDetail(Product.ref(1), 3, 10.50))
this.details.add(OrderDetail(Product.ref(3), 40, 2.10))
save()
}
}
private fun createOrder4(customer: Customer) {
with(Order(customer)) {
save()
}
}
}
| apache-2.0 | cfaba5dda7f4c74bafa47b9e98a09a32 | 22.267327 | 123 | 0.625957 | 3.663289 | false | false | false | false |
AndroidX/androidx | camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/internal/Camera2CameraImplCameraReopenTest.kt | 3 | 24855 | /*
* Copyright 2019 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.camera.camera2.internal
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraManager.AvailabilityCallback
import android.os.Handler
import android.os.HandlerThread
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
import androidx.camera.camera2.AsyncCameraDevice
import androidx.camera.camera2.Camera2Config
import androidx.camera.camera2.internal.compat.CameraAccessExceptionCompat
import androidx.camera.camera2.internal.compat.CameraManagerCompat
import androidx.camera.core.CameraSelector
import androidx.camera.core.CameraUnavailableException
import androidx.camera.core.Logger
import androidx.camera.core.impl.CameraInternal
import androidx.camera.core.impl.CameraStateRegistry
import androidx.camera.core.impl.Observable
import androidx.camera.core.impl.utils.MainThreadAsyncHandler
import androidx.camera.core.impl.utils.executor.CameraXExecutors
import androidx.camera.testing.CameraUtil
import androidx.camera.testing.CameraUtil.PreTestCameraIdList
import androidx.core.os.HandlerCompat
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import com.google.common.truth.Truth
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import kotlin.math.ceil
import org.junit.After
import org.junit.AfterClass
import org.junit.Assume
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
/** Contains [Camera2CameraImpl] tests for reopening the camera with failures. */
@LargeTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 21)
class Camera2CameraImplCameraReopenTest {
@get:Rule
val cameraRule = CameraUtil.grantCameraPermissionAndPreTest(
PreTestCameraIdList(Camera2Config.defaultConfig())
)
private var camera2CameraImpl: Camera2CameraImpl? = null
private var cameraId: String? = null
private var anotherCameraDevice: AsyncCameraDevice? = null
@Before
fun setUp() {
cameraId = CameraUtil.getCameraIdWithLensFacing(CameraSelector.LENS_FACING_BACK)
Assume.assumeFalse("Device doesn't have an available back facing camera", cameraId == null)
}
@After
@Throws(InterruptedException::class, ExecutionException::class)
fun testTeardown() {
// Release camera, otherwise the CameraDevice is not closed, which can cause problems that
// interfere with other tests.
if (camera2CameraImpl != null) {
camera2CameraImpl!!.release().get()
camera2CameraImpl = null
}
anotherCameraDevice?.closeAsync()
anotherCameraDevice = null
}
@Test
@Throws(Exception::class)
fun openCameraAfterMultipleFailures_whenCameraReopenLimitNotReached() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Try opening the camera. This will fail and trigger reopening attempts
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Wait for half the max reopen attempts to occur
val maxReopenAttempts = ceil(REOPEN_LIMIT_MS / REOPEN_DELAY_MS.toDouble()).toInt()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
maxReopenAttempts / 2, REOPEN_LIMIT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Allow camera opening to succeed
cameraManagerImpl.shouldFailCameraOpen = false
// Verify the camera opens
awaitCameraOpen()
}
@Test
@Throws(Exception::class)
fun doNotAttemptCameraReopen_whenCameraReopenLimitReached() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Try opening the camera. This will fail and trigger reopening attempts
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Wait for max reopen attempts to occur
awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore)
// Verify 0 camera reopen attempts occurred.
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isFalse()
}
@Test
@Throws(Exception::class)
fun openCameraAfterReopenLimitReached_whenCameraExplicitlyOpened() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Try opening the camera. This will fail and trigger reopening attempts
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Wait for max reopen attempts to occur
awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore)
// Allow camera opening to succeed
cameraManagerImpl.shouldFailCameraOpen = false
// Try opening the camera. This should succeed
camera2CameraImpl!!.open()
// Verify the camera opens
awaitCameraOpen()
}
@Test
@Throws(Exception::class)
fun openCameraAfterReopenLimitReached_whenCameraBecomesAvailable() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Try opening the camera. This will fail and trigger reopening attempts
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Wait for max reopen attempts to occur
awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore)
// Allow camera opening to succeed
cameraManagerImpl.shouldFailCameraOpen = false
// Make camera available
camera2CameraImpl!!.cameraAvailability.onCameraAvailable(cameraId!!)
// Verify the camera opens
awaitCameraOpen()
}
@Test
@Throws(Exception::class)
fun activeResuming_openCameraAfterMultipleReopening_whenCameraUnavailable() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
cameraManagerImpl.shouldEmitCameraInUseError = true
// Enable active reopening which will open the camera even when camera is unavailable.
camera2CameraImpl!!.setActiveResumingMode(true)
// Try opening the camera. This will fail and trigger reopening attempts
camera2CameraImpl!!.open()
// make camera unavailable.
cameraExecutor!!.execute {
camera2CameraImpl!!.cameraAvailability.onCameraUnavailable(
cameraId!!
)
}
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// Wait for half the max reopen attempts to occur
val maxReopenAttempts = ceil(10000.0 / ACTIVE_REOPEN_DELAY_BASE_MS).toInt()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
maxReopenAttempts / 2, 10000,
TimeUnit.MILLISECONDS
)
).isTrue()
// Allow camera opening to succeed
cameraManagerImpl.shouldFailCameraOpen = false
// Verify the camera opens
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
awaitCameraOpen()
}
private fun openAnotherCamera() {
val cameraManager = ApplicationProvider.getApplicationContext<Context>()
.getSystemService(Context.CAMERA_SERVICE) as CameraManager
anotherCameraDevice =
AsyncCameraDevice(cameraManager, cameraId!!, cameraHandler!!).apply { openAsync() }
}
@SdkSuppress(minSdkVersion = 23)
@Test
@Throws(Exception::class)
fun activeResuming_reopenCamera_whenCameraIsInterruptedInActiveResuming() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Open camera will succeed.
cameraManagerImpl.shouldFailCameraOpen = false
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
awaitCameraOpen()
// Enable active resuming which will open the camera even when camera is unavailable.
camera2CameraImpl!!.setActiveResumingMode(true)
// Disconnect the current camera.
openAnotherCamera()
// Verify the camera opens
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
awaitCameraOpen()
}
@SdkSuppress(minSdkVersion = 23)
@Test
@Throws(Exception::class)
fun activeResuming_reopenCamera_whenCameraPendingOpenThenResume() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener = object :
FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Open camera will succeed.
cameraManagerImpl.shouldFailCameraOpen = false
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
awaitCameraOpen()
// Disconnect the current camera.
openAnotherCamera()
// Wait until camera is pending_open which will wait for camera availability
awaitCameraPendingOpen()
// Enable active resuming to see if it can resume the camera.
camera2CameraImpl!!.setActiveResumingMode(true)
// Verify the camera opens
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
awaitCameraOpen()
}
@Test
@Throws(Exception::class)
fun activeResuming_doNotReopenCamera_whenCameraDeviceError() {
// Set up the camera
val cameraManagerImpl = FailCameraOpenCameraManagerImpl()
setUpCamera(cameraManagerImpl)
// Set up camera open attempt listener
val cameraOpenSemaphore = Semaphore(0)
cameraManagerImpl.onCameraOpenAttemptListener =
object : FailCameraOpenCameraManagerImpl.OnCameraOpenAttemptListener {
override fun onCameraOpenAttempt() {
cameraOpenSemaphore.release()
}
}
// Open camera will succeed.
cameraManagerImpl.shouldFailCameraOpen = false
camera2CameraImpl!!.open()
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
// wait onOpened to get CameraDevice
awaitCameraOpen()
camera2CameraImpl!!.setActiveResumingMode(true)
cameraExecutor!!.execute {
cameraManagerImpl.deviceStateCallback!!.notifyOnError(
CameraDevice.StateCallback.ERROR_CAMERA_DEVICE
)
}
// Make camera unavailable after onClosed so that we can verify if camera is not opened
// again. For ERROR_CAMERA_DEVICE, it should not reopen the camera if the camera is
// not available.
cameraManagerImpl.deviceStateCallback!!.runWhenOnClosed { openAnotherCamera() }
// 2nd camera open should not happen
Truth.assertThat(
cameraOpenSemaphore.tryAcquire(
1, WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isFalse()
}
@Throws(CameraAccessExceptionCompat::class, CameraUnavailableException::class)
private fun setUpCamera(cameraManagerImpl: FailCameraOpenCameraManagerImpl) {
// Build camera manager wrapper
val cameraManagerCompat = CameraManagerCompat.from(cameraManagerImpl)
// Build camera info
val camera2CameraInfo = Camera2CameraInfoImpl(
cameraId!!, cameraManagerCompat
)
// Initialize camera instance
camera2CameraImpl = Camera2CameraImpl(
cameraManagerCompat,
cameraId!!,
camera2CameraInfo,
CameraStateRegistry(1),
cameraExecutor!!,
cameraHandler!!,
DisplayInfoManager.getInstance(ApplicationProvider.getApplicationContext())
)
}
@Throws(InterruptedException::class)
private fun awaitCameraOpen() {
awaitCameraState(CameraInternal.State.OPEN)
}
@Throws(InterruptedException::class)
private fun awaitCameraPendingOpen() {
awaitCameraState(CameraInternal.State.PENDING_OPEN)
}
@Throws(InterruptedException::class)
private fun awaitCameraState(state: CameraInternal.State) {
val cameraStateSemaphore = Semaphore(0)
val observer: Observable.Observer<CameraInternal.State?> =
object : Observable.Observer<CameraInternal.State?> {
override fun onNewData(newState: CameraInternal.State?) {
if (newState == state) {
cameraStateSemaphore.release()
}
}
override fun onError(t: Throwable) {
Logger.e("CameraReopenTest", "Camera state error: " + t.message)
}
}
camera2CameraImpl!!.cameraState.addObserver(
CameraXExecutors.directExecutor(),
observer
)
try {
Truth.assertThat(
cameraStateSemaphore.tryAcquire(
WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(),
TimeUnit.MILLISECONDS
)
).isTrue()
} finally {
camera2CameraImpl!!.cameraState.removeObserver(observer)
}
}
@Throws(InterruptedException::class)
private fun awaitCameraMaxReopenAttemptsReached(cameraOpenSemaphore: Semaphore) {
while (true) {
val cameraOpenAttempted = cameraOpenSemaphore.tryAcquire(
1,
WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS
)
if (!cameraOpenAttempted) {
return
}
}
}
companion object {
private const val REOPEN_DELAY_MS =
Camera2CameraImpl.StateCallback.CameraReopenMonitor.REOPEN_DELAY_MS
private const val REOPEN_LIMIT_MS =
Camera2CameraImpl.StateCallback.CameraReopenMonitor.REOPEN_LIMIT_MS
private const val ACTIVE_REOPEN_DELAY_BASE_MS =
Camera2CameraImpl.StateCallback.CameraReopenMonitor.ACTIVE_REOPEN_DELAY_BASE_MS
private const val WAIT_FOR_CAMERA_OPEN_TIMEOUT_MS = 2000
private var cameraHandlerThread: HandlerThread? = null
private var cameraHandler: Handler? = null
private var cameraExecutor: ExecutorService? = null
@BeforeClass
@JvmStatic
fun classSetup() {
cameraHandlerThread = HandlerThread("cameraThread")
cameraHandlerThread!!.start()
cameraHandler = HandlerCompat.createAsync(
cameraHandlerThread!!.looper
)
cameraExecutor = CameraXExecutors.newHandlerExecutor(
cameraHandler!!
)
}
@AfterClass
@JvmStatic
fun classTeardown() {
cameraHandlerThread!!.quitSafely()
}
}
}
/**
* Wraps a [CameraManagerCompat.CameraManagerCompatImpl] instance and controls camera opening
* by either allowing it to succeed or fail.
*/
@RequiresApi(21)
internal class FailCameraOpenCameraManagerImpl : CameraManagerCompat.CameraManagerCompatImpl {
private val forwardCameraManagerCompatImpl:
CameraManagerCompat.CameraManagerCompatImpl by lazy {
CameraManagerCompat.CameraManagerCompatImpl.from(
ApplicationProvider.getApplicationContext(),
MainThreadAsyncHandler.getInstance()
)
}
private val lock = Any()
@GuardedBy("lock")
var onCameraOpenAttemptListener: OnCameraOpenAttemptListener? = null
get() {
synchronized(lock) {
return field
}
}
set(value) {
synchronized(lock) {
field = value
}
}
@GuardedBy("lock")
var shouldFailCameraOpen = true
get() {
synchronized(lock) {
return field
}
}
set(value) {
synchronized(lock) {
field = value
}
}
@Volatile
var shouldEmitCameraInUseError = false
@GuardedBy("lock")
var deviceStateCallback: CameraDeviceCallbackWrapper? = null
get() {
synchronized(lock) {
return field
}
}
set(value) {
synchronized(lock) {
field = value
}
}
@Throws(CameraAccessExceptionCompat::class)
override fun getCameraIdList(): Array<String> {
return forwardCameraManagerCompatImpl.cameraIdList
}
override fun registerAvailabilityCallback(
executor: Executor,
callback: AvailabilityCallback
) {
forwardCameraManagerCompatImpl.registerAvailabilityCallback(executor, callback)
}
override fun unregisterAvailabilityCallback(
callback: AvailabilityCallback
) {
forwardCameraManagerCompatImpl.unregisterAvailabilityCallback(callback)
}
@Throws(CameraAccessExceptionCompat::class)
override fun getCameraCharacteristics(camId: String): CameraCharacteristics {
return forwardCameraManagerCompatImpl.getCameraCharacteristics(camId)
}
override fun getCameraManager(): CameraManager {
return forwardCameraManagerCompatImpl.cameraManager
}
@Throws(CameraAccessExceptionCompat::class)
override fun openCamera(
camId: String,
executor: Executor,
callback: CameraDevice.StateCallback
) {
synchronized(lock) {
deviceStateCallback = CameraDeviceCallbackWrapper(callback)
if (onCameraOpenAttemptListener != null) {
onCameraOpenAttemptListener!!.onCameraOpenAttempt()
}
if (shouldFailCameraOpen) {
if (shouldEmitCameraInUseError) {
executor.execute {
callback.onError(
mock(CameraDevice::class.java),
CameraDevice.StateCallback.ERROR_CAMERA_IN_USE
)
}
}
// Throw any exception
throw SecurityException("Lacking privileges")
} else {
forwardCameraManagerCompatImpl
.openCamera(camId, executor, deviceStateCallback!!)
}
}
}
interface OnCameraOpenAttemptListener {
/** Triggered whenever an attempt to open the camera is made. */
fun onCameraOpenAttempt()
}
internal class CameraDeviceCallbackWrapper(
private val deviceCallback: CameraDevice.StateCallback
) : CameraDevice.StateCallback() {
private var cameraDevice: CameraDevice? = null
private var runnableForOnClosed: Runnable? = null
override fun onOpened(device: CameraDevice) {
cameraDevice = device
deviceCallback.onOpened(device)
}
override fun onClosed(camera: CameraDevice) {
deviceCallback.onClosed(camera)
if (runnableForOnClosed != null) {
runnableForOnClosed!!.run()
}
}
override fun onDisconnected(device: CameraDevice) {
deviceCallback.onDisconnected(device)
}
override fun onError(device: CameraDevice, error: Int) {
deviceCallback.onError(device, error)
}
fun notifyOnError(error: Int) {
onError(cameraDevice!!, error)
}
fun runWhenOnClosed(runnable: Runnable) {
runnableForOnClosed = runnable
}
}
}
| apache-2.0 | 47b6ad576d98d587952d0e4ab68b6417 | 33.957806 | 99 | 0.645423 | 5.297315 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddSelfFix.kt | 3 | 1463 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.rawValueParameters
class AddSelfFix(function: RsFunction) : LocalQuickFixAndIntentionActionOnPsiElement(function) {
override fun getFamilyName() = "Add self to function"
override fun getText() = "Add self to function"
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
val function = startElement as RsFunction
val hasParameters = function.rawValueParameters.isNotEmpty()
val psiFactory = RsPsiFactory(project)
val valueParameterList = function.valueParameterList
val lparen = valueParameterList?.firstChild
val self = psiFactory.createSelfReference()
valueParameterList?.addAfter(self, lparen)
if (hasParameters) {
// IDE error if use addAfter(comma, self)
val parent = lparen?.parent
parent?.addAfter(psiFactory.createComma(), parent.firstChild.nextSibling)
}
}
}
| mit | 0987db06e6de0db915e986f44f019ed6 | 36.512821 | 125 | 0.740943 | 4.719355 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsLifetimeParameter.kt | 4 | 1562 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.lang.core.psi.RsLifetime
import org.rust.lang.core.psi.RsLifetimeParameter
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.stubs.RsLifetimeParameterStub
val RsLifetimeParameter.bounds: List<RsLifetime>
get() {
val owner = parent?.parent as? RsGenericDeclaration
val whereBounds = owner?.whereClause?.wherePredList.orEmpty()
.filter { it.lifetime?.reference?.resolve() == this }
.flatMap { it.lifetimeParamBounds?.lifetimeList.orEmpty() }
return lifetimeParamBounds?.lifetimeList.orEmpty() + whereBounds
}
abstract class RsLifetimeParameterImplMixin : RsStubbedNamedElementImpl<RsLifetimeParameterStub>, RsLifetimeParameter {
constructor(node: ASTNode) : super(node)
constructor(stub: RsLifetimeParameterStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getNameIdentifier(): PsiElement = quoteIdentifier
override fun setName(name: String): PsiElement? {
nameIdentifier.replace(RsPsiFactory(project).createQuoteIdentifier(name))
return this
}
override fun getUseScope(): SearchScope = RsPsiImplUtil.getParameterUseScope(this) ?: super.getUseScope()
}
| mit | 5932164164e06c9744742d4035324125 | 37.097561 | 119 | 0.756722 | 4.4 | false | false | false | false |
codebutler/odyssey | retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/logging/TimberLoggingHandler.kt | 1 | 1587 | package com.codebutler.retrograde.lib.logging
import android.util.Log
import timber.log.Timber
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogRecord
class TimberLoggingHandler : Handler() {
@Throws(SecurityException::class)
override fun close() { }
override fun flush() {}
override fun publish(record: LogRecord) {
val tag = loggerNameToTag(record.loggerName)
val level = getAndroidLevel(record.level)
Timber.tag(tag).log(level, record.message)
}
// https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/com/android/internal/logging/AndroidHandler.java
private fun getAndroidLevel(level: Level): Int {
val value = level.intValue()
return when {
value >= 1000 -> Log.ERROR // SEVERE
value >= 900 -> Log.WARN // WARNING
value >= 800 -> Log.INFO // INFO
else -> Log.DEBUG
}
}
// https://android.googlesource.com/platform/libcore/+/master/dalvik/src/main/java/dalvik/system/DalvikLogging.java
private fun loggerNameToTag(loggerName: String?): String {
if (loggerName == null) {
return "null"
}
val length = loggerName.length
if (length <= 23) {
return loggerName
}
val lastPeriod = loggerName.lastIndexOf(".")
return if (length - (lastPeriod + 1) <= 23) {
loggerName.substring(lastPeriod + 1)
} else {
loggerName.substring(loggerName.length - 23)
}
}
}
| gpl-3.0 | 23764a87c73df8c88c226ade941918b1 | 32.0625 | 136 | 0.628859 | 4.132813 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangamainac/MangaMainac.kt | 1 | 6248 | package eu.kanade.tachiyomi.multisrc.mangamainac
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.util.Calendar
// Based On TCBScans sources
// MangaManiac is a network of sites built by Animemaniac.co.
abstract class MangaMainac(
override val name: String,
override val baseUrl: String,
override val lang: String,
) : ParsedHttpSource() {
override val supportsLatest = false
override val client: OkHttpClient = network.cloudflareClient
// popular
override fun popularMangaRequest(page: Int): Request {
return GET(baseUrl)
}
override fun popularMangaSelector() = "#page"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.thumbnail_url = element.select(".mangainfo_body > img").attr("src")
manga.url = "" //element.select("#primary-menu .menu-item:first-child").attr("href")
manga.title = element.select(".intro_content h2").text()
return manga
}
override fun popularMangaNextPageSelector(): String? = null
// latest
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException()
override fun latestUpdatesSelector(): String = throw UnsupportedOperationException()
override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException()
override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException()
// search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException()
override fun searchMangaSelector(): String = throw UnsupportedOperationException()
override fun searchMangaFromElement(element: Element): SManga = throw UnsupportedOperationException()
override fun searchMangaNextPageSelector(): String? = throw UnsupportedOperationException()
// manga details
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val info = document.select(".intro_content").text()
thumbnail_url = document.select(".mangainfo_body > img").attr("src")
title = document.select(".intro_content h2").text()
author = if ("Author" in info) substringextract(info, "Author(s):", "Released") else null
artist = author
genre = if ("Genre" in info) substringextract(info, "Genre(s):", "Status") else null
status = parseStatus(document.select(".intro_content").text())
description = if ("Description" in info) info.substringAfter("Description:").trim() else null
}
private fun substringextract(text: String, start: String, end: String): String = text.substringAfter(start).substringBefore(end).trim()
private fun parseStatus(element: String): Int = when {
element.toLowerCase().contains("ongoing (pub") -> SManga.ONGOING
element.toLowerCase().contains("completed (pub") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// chapters
override fun chapterListSelector() = "table.chap_tab tr"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a").first()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = element.select("a").text()
chapter.date_upload = element.select("#time i").last()?.text()?.let { parseChapterDate(it) }
?: 0
return chapter
}
private fun parseChapterDate(date: String): Long {
val dateWords: List<String> = date.split(" ")
if (dateWords.size == 3) {
val timeAgo = Integer.parseInt(dateWords[0])
val dates: Calendar = Calendar.getInstance()
when {
dateWords[1].contains("minute") -> {
dates.add(Calendar.MINUTE, -timeAgo)
}
dateWords[1].contains("hour") -> {
dates.add(Calendar.HOUR_OF_DAY, -timeAgo)
}
dateWords[1].contains("day") -> {
dates.add(Calendar.DAY_OF_YEAR, -timeAgo)
}
dateWords[1].contains("week") -> {
dates.add(Calendar.WEEK_OF_YEAR, -timeAgo)
}
dateWords[1].contains("month") -> {
dates.add(Calendar.MONTH, -timeAgo)
}
dateWords[1].contains("year") -> {
dates.add(Calendar.YEAR, -timeAgo)
}
}
return dates.timeInMillis
}
return 0L
}
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
val chapterList = document.select(chapterListSelector()).map { chapterFromElement(it) }
return if (hasCountdown(chapterList[0]))
chapterList.subList(1, chapterList.size)
else
chapterList
}
private fun hasCountdown(chapter: SChapter): Boolean {
val document = client.newCall(
GET(
baseUrl + chapter.url,
headersBuilder().build()
)
).execute().asJsoup()
return document
.select("iframe[src^=https://free.timeanddate.com/countdown/]")
.isNotEmpty()
}
// pages
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
var i = 0
document.select(".container .img_container center img").forEach { element ->
val url = element.attr("src")
i++
if (url.isNotEmpty()) {
pages.add(Page(i, "", url))
}
}
return pages
}
override fun imageUrlParse(document: Document) = ""
}
| apache-2.0 | e43ce257f854bd580c012c163fadab81 | 38.295597 | 139 | 0.637484 | 4.74772 | false | false | false | false |
develar/mapsforge-tile-server | pixi/src/bitmapFont.kt | 1 | 7947 | package org.develar.mapsforgeTileServer.pixi
import com.carrotsearch.hppc.*
import org.kxml2.io.KXmlParser
import org.mapsforge.core.graphics.FontFamily
import org.mapsforge.core.graphics.FontStyle
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.xmlpull.v1.XmlPullParser
import java.awt.Point
import java.awt.Rectangle
import java.io.*
import java.util.ArrayList
private val LOG: Logger = LoggerFactory.getLogger(javaClass<FontManager>())
public fun KXmlParser.get(name: String): String = getAttributeValue(null, name)!!
data
public class FontInfo(public val index: Int,
public val size: Int,
public val style: FontStyle,
val chars: List<CharInfo>,
private val
charToIndex: CharIntMap,
val fontColor: Int,
val strokeWidth: Float = -1f,
val strokeColor: Int = -1) {
fun getCharInfoByChar(char: Char): CharInfo? {
val index = getCharIndex(char)
return if (index == -1) null else chars.get(index)
}
fun getCharIndex(char: Char) = charToIndex.getOrDefault(char, -1)
fun getCharInfoByIndex(index: Int) = chars.get(index)
}
data
public class CharInfo(public val xOffset: Int, public val yOffset: Int, public val xAdvance: Int, public val rectangle: Rectangle) {
val kerning = IntIntOpenHashMap()
}
// fonts - ordered by font size
public class FontManager(private val fonts: List<FontInfo>) {
fun measureText(text: String, font: FontInfo): Point {
var x = 0
var height = 0
var prevCharIndex = -1;
for (char in text) {
val charIndex = font.getCharIndex(char)
if (charIndex == -1) {
LOG.warn("missed char: " + char + " " + char.toInt())
continue
}
val charInfo = font.getCharInfoByIndex(charIndex)
if (prevCharIndex != -1) {
x += charInfo.kerning.getOrDefault(prevCharIndex, 0);
}
x += charInfo.xAdvance;
height = Math.max(height, charInfo.rectangle.height + charInfo.yOffset)
prevCharIndex = charIndex
}
return Point(x, height)
}
fun getFont(@suppress("UNUSED_PARAMETER") family: FontFamily, style: FontStyle, size: Int): FontInfo? {
for (font in fonts) {
if (font.size == size && font.style == style) {
return font
}
}
return null
}
fun getFont(@suppress("UNUSED_PARAMETER") family: FontFamily, style: FontStyle, size: Int, fontColor: Int, strokeWidth: Float = -1f, strokeColor: Int = -1): FontInfo {
for (font in fonts) {
if (font.size == size && font.style == style && font.fontColor == fontColor && font.strokeWidth == strokeWidth && font.strokeColor == strokeColor) {
return font
}
}
throw Exception("Unknown font " + family + " " + style + " " + size)
}
}
public fun parseFontInfo(file: File, fontIndex: Int): FontInfo {
val parser = KXmlParser()
parser.setInput(FileReader(file))
var eventType = parser.getEventType()
var chars: MutableList<CharInfo>? = null
var charToIndex: CharIntMap? = null
var idToCharInfo: IntObjectMap<CharInfo>? = null
var idToCharIndex: IntIntMap? = null
var fontSize: Int? = null
var fontStyle: FontStyle? = null
do {
when (eventType) {
XmlPullParser.START_TAG -> {
when (parser.getName()!!) {
"info" -> {
fontSize = parser["size"].toInt()
val bold = parser["bold"] == "1"
val italic = parser["italic"] == "1"
fontStyle = when {
bold && italic -> FontStyle.BOLD_ITALIC
bold -> FontStyle.BOLD
italic -> FontStyle.ITALIC
else -> FontStyle.NORMAL
}
}
"common" -> {
if (parser["pages"] != "1") {
throw UnsupportedOperationException("Only one page supported")
}
}
"chars" -> {
val charCount = parser["count"].toInt()
charToIndex = CharIntOpenHashMap(charCount)
chars = ArrayList(charCount)
idToCharInfo = IntObjectOpenHashMap(charCount)
idToCharIndex = IntIntOpenHashMap(charCount)
}
"char" -> {
val rect = Rectangle(parser["x"].toInt(), parser["y"].toInt(), parser["width"].toInt(), parser["height"].toInt())
val charInfo = CharInfo(parser["xoffset"].toInt(), parser["yoffset"].toInt(), parser["xadvance"].toInt(), rect)
val char: Char
val letter = parser["letter"]
char = when (letter) {
"space" -> ' '
""" -> '"'
"<" -> '<'
">" -> '>'
"&" -> '&'
else -> {
assert(letter.length() == 1)
letter[0]
}
}
charToIndex!!.put(char, chars!!.size())
chars.add(charInfo)
idToCharInfo!!.put(parser["id"].toInt(), charInfo)
}
"kerning" -> {
val charInfo = idToCharInfo!![parser["second"].toInt()]
if (charInfo != null) {
charInfo.kerning.put(idToCharIndex!![parser["first"].toInt()], parser["amount"].toInt())
}
}
}
}
}
eventType = parser.next()
}
while (eventType != XmlPullParser.END_DOCUMENT)
val fileName = file.name
val items = fileName.substring(0, fileName.lastIndexOf('.')).split('-')
val strokeWidth: Float
val strokeColor: Int
if (items.size() > 3) {
strokeWidth = items[3].toFloat()
strokeColor = getColor(items[4])
}
else {
strokeWidth = -1f
strokeColor = -1
}
return FontInfo(fontIndex, fontSize!!, fontStyle!!, chars!!, charToIndex!!, getColor(items[2]), strokeWidth, strokeColor)
}
private fun getColor(colorString: String): Int {
val red = Integer.parseInt(colorString.substring(0, 2), 16);
val green = Integer.parseInt(colorString.substring(2, 4), 16);
val blue = Integer.parseInt(colorString.substring(4, 6), 16);
return colorToRgba(255, red, green, blue);
}
public fun generateFontInfo(fonts: List<FontInfo>, outFile: File, textureAtlas: TextureAtlasInfo, fontToRegionName: Map<FontInfo, String>) {
val out = BufferedOutputStream(FileOutputStream(outFile))
val buffer = ByteArrayOutput()
buffer.writeUnsignedVarInt(fonts.size())
for (font in fonts) {
//buffer.writeUnsighedVarInt(font.size)
//buffer.write(font.style.ordinal())
//buffer.writeTo(out)
//buffer.reset()
val chars = font.chars
buffer.writeUnsignedVarInt(chars.size())
buffer.writeTo(out)
buffer.reset()
var prevX = 0
var prevY = 0
val region = textureAtlas.getRegion(fontToRegionName[font]!!)
for (charInfo in chars) {
out.write(charInfo.xOffset)
out.write(charInfo.yOffset)
out.write(charInfo.xAdvance)
val x = region.left + charInfo.rectangle.x
val y = region.top + charInfo.rectangle.y
buffer.writeSignedVarInt(x - prevX)
buffer.writeSignedVarInt(y - prevY)
buffer.writeTo(out)
buffer.reset()
prevX = x
prevY = y
out.write(charInfo.rectangle.width)
out.write(charInfo.rectangle.height)
writeKerningsInfo(charInfo, buffer, out)
}
}
out.close()
}
private fun writeKerningsInfo(charInfo: CharInfo, buffer: ByteArrayOutput, out: OutputStream) {
buffer.writeUnsignedVarInt(charInfo.kerning.size())
buffer.writeTo(out)
buffer.reset()
if (charInfo.kerning.isEmpty()) {
return
}
val sortedKernings = charInfo.kerning.keys().toArray()
sortedKernings.sort()
var prevCharIndex = 0
for (i in 0..sortedKernings.size() - 1) {
val charIndex = sortedKernings[i]
buffer.writeUnsignedVarInt(charIndex - prevCharIndex)
buffer.writeTo(out)
buffer.reset()
out.write(charInfo.kerning.get(charIndex))
prevCharIndex = charIndex
}
} | mit | 79b6833ef90db36a073b6bd87a18b212 | 30.41502 | 169 | 0.612055 | 4.007564 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt | 1 | 2403 | package info.nightscout.androidaps.plugins.insulin
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.interfaces.Insulin
import info.nightscout.androidaps.utils.T
import java.util.*
import kotlin.math.floor
class ActivityGraph : GraphView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
fun show(insulin: Insulin, diaSample: Double? = null) {
removeAllSeries()
val dia = diaSample ?: insulin.dia
mSecondScale = null
val hours = floor(dia + 1).toLong()
val bolus = Bolus(
timestamp = 0,
amount = 1.0,
type = Bolus.Type.NORMAL
)
val activityArray: MutableList<DataPoint> = ArrayList()
val iobArray: MutableList<DataPoint> = ArrayList()
var time: Long = 0
while (time <= T.hours(hours).msecs()) {
val iob = insulin.iobCalcForTreatment(bolus, time, dia)
activityArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.activityContrib))
iobArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.iobContrib))
time += T.mins(5).msecs()
}
addSeries(LineGraphSeries(Array(activityArray.size) { i -> activityArray[i] }).also {
it.thickness = 8
gridLabelRenderer.verticalLabelsColor = it.color
})
viewport.isXAxisBoundsManual = true
viewport.setMinX(0.0)
viewport.setMaxX((hours * 60).toDouble())
viewport.isYAxisBoundsManual = true
viewport.setMinY(0.0)
viewport.setMaxY(0.01)
gridLabelRenderer.numHorizontalLabels = (hours + 1).toInt()
gridLabelRenderer.horizontalAxisTitle = "[min]"
secondScale.addSeries(LineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also {
it.isDrawBackground = true
it.color = Color.MAGENTA
it.backgroundColor = Color.argb(70, 255, 0, 255)
})
secondScale.minY = 0.0
secondScale.maxY = 1.0
gridLabelRenderer.verticalLabelsSecondScaleColor = Color.MAGENTA
}
} | agpl-3.0 | e873c6c900f0bab905ff17452bdf58e7 | 38.409836 | 95 | 0.662089 | 4.171875 | false | false | false | false |
thecoshman/bblm | src/main/kotlin/com/thecoshman/bblm/webui/WebUI.kt | 1 | 1623 | package com.thecoshman.bblm.webui
import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.web.servlet.ViewResolver
import org.thymeleaf.TemplateEngine
import org.thymeleaf.spring4.SpringTemplateEngine
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver
import org.thymeleaf.spring4.view.ThymeleafViewResolver
import org.thymeleaf.templateresolver.ITemplateResolver
open class WebUI : ApplicationContextAware {
private var appContext: ApplicationContext? = null
@Throws(BeansException::class)
override fun setApplicationContext(applicationContext: ApplicationContext) {
appContext = applicationContext
}
fun viewResolver(): ViewResolver {
with(ThymeleafViewResolver()) {
templateEngine = templateEngine() as SpringTemplateEngine?
characterEncoding = "UTF-8"
contentType = "text/html; charset=UTF-8"
return this
}
}
fun templateEngine(): TemplateEngine {
with (SpringTemplateEngine()) {
setTemplateResolver(templateResolver())
return this
}
}
fun templateResolver(): ITemplateResolver {
with(SpringResourceTemplateResolver()) {
setApplicationContext(appContext)
prefix = "/main/WEB-INF/templates/"
suffix = ".html"
// templateMode = TemplateMode.HTML // This is default vOv
characterEncoding = "UTF-8"
return this
}
}
}
| mit | 1c3623e8d05c2df6da4e6c0e721b0255 | 32.8125 | 80 | 0.704868 | 4.933131 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/widget/DragHandle.kt | 1 | 2155 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.design.compose.widget
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import app.ss.design.compose.theme.SsColor
private object DragHandleDefaults {
val width = 48.dp
val height = 4.dp
}
@Composable
fun DragHandle(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.size(
width = DragHandleDefaults.width,
height = DragHandleDefaults.height
)
.background(backgroundColor(), CircleShape)
)
}
@Composable
private fun backgroundColor(): Color =
if (isSystemInDarkTheme()) {
SsColor.BaseGrey2
} else {
SsColor.BaseGrey1
}
| mit | ef4ea7b2ded6b69044397cdc406ba900 | 35.525424 | 80 | 0.742459 | 4.434156 | false | false | false | false |
ahant-pabi/field-validator | src/main/kotlin/com/github/ahant/validator/validation/util/RequiredFieldValidator.kt | 1 | 4919 | package com.github.ahant.validator.validation.util
import com.github.ahant.validator.annotation.CollectionType
import com.github.ahant.validator.annotation.FieldInfo
import com.github.ahant.validator.constants.ApplicationConstants.COLLECTION_MIN_SIZE_ERROR
import com.github.ahant.validator.constants.ApplicationConstants.REQUIRED_FIELD_MISSING
import com.github.ahant.validator.util.CommonUtil.isNotBlank
import com.github.ahant.validator.validation.FieldValidationType
import com.google.common.collect.Sets
/**
* Created by ahant on 8/14/2016.
*/
object RequiredFieldValidator {
/**
* Get all the declared fields of 'type' object and invoke their respective field validators. throw exception if validator returns false.
* The thrown exception must be of type Application exception with message as required field missing along with field name.
*/
fun validate(type: Any, validationType: FieldValidationType): Set<String> {
return performFieldValidation(type, validationType)
}
/**
* Iterates over all declared fields and performs validation using their declared validator or default validator if none has been provided.
* @param type type instance for which validation needs to be performed
* *
* @param validationType If `FieldValidationType.FAIL_FAST`, the process terminates as soon as it encounters a failed scenario else continues validation.
* *
* @param requiredAnnotationPresent indicates if the given type object has 'Required' annotation at class level. If present, all of it's fields are considered as required
* * unless explicitly mentioned as 'optional'.
* *
* @return returns a set of error messages, if any or empty. It never returns `null`.
*/
private fun performFieldValidation(type: Any, validationType: FieldValidationType): Set<String> {
val errors = Sets.newHashSet<String>()
val fields = type.javaClass.declaredFields
for (field in fields) {
field.isAccessible = true
val info = field.getAnnotation(FieldInfo::class.java)
var fieldValue: Any?
try {
fieldValue = field.get(type)
} catch (e: IllegalAccessException) {
// ignore exception and either terminate or continue based on validationType.
if (FieldValidationType.CONTINUE == validationType) {
continue
} else {
errors.add(e.message)
return errors
}
}
val fieldName = if (info != null && isNotBlank(info.name)) info.name else field.name
if (info != null && !info.optional && fieldValue == null) {
errors.add(getExceptionMessage(fieldName))
}
/**
* continue if
* 1) the field has a non null value
* 2) there are no errors OR validation type is {@code FieldValidationType.CONTINUE}
* 3) the field a validator type declared
*/
if (fieldValue != null && (FieldValidationType.CONTINUE == validationType || errors.isEmpty()) && (info != null)) {
val validator = info.validatorType.get()
validator.setCountry(info.countryCode)
var fieldError: Set<String> = Sets.newHashSet<String>()
val collectionAnnotation = field.getAnnotation(CollectionType::class.java)
if (collectionAnnotation == null) {
fieldError = validator.validate(fieldValue)
} else {
val collectionData = fieldValue as Collection<*>
if (collectionData.size < collectionAnnotation.minSize) {
errors.add(getCollectionErrorMessage(fieldName, collectionAnnotation.minSize))
} else {
val collectionFieldIterator = collectionData.iterator()
while (collectionFieldIterator.hasNext()) {
val collectionValue = collectionFieldIterator.next()
val tempErrors = validator.validate(collectionValue as Any)
fieldError.plus(tempErrors)
}
}
}
errors.addAll(fieldError)
}
if (FieldValidationType.FAIL_FAST == validationType && !errors.isEmpty()) {
break
}
}
return errors
}
private fun getExceptionMessage(fieldName: String): String {
return String.format(REQUIRED_FIELD_MISSING, fieldName)
}
private fun getCollectionErrorMessage(fieldName: String, minSize: Int): String {
return String.format(COLLECTION_MIN_SIZE_ERROR, minSize, fieldName)
}
}
| apache-2.0 | e9ca377c56e641e630f565546a31d52d | 47.70297 | 174 | 0.620248 | 5.232979 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/Annotation.kt | 1 | 2330 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
/**
* An Arcs annotations containing additional information on an Arcs manifest element.
* An Annotation may be attached to a plan, particle, handle, type etc.
*/
data class Annotation(val name: String, val params: Map<String, AnnotationParam> = emptyMap()) {
fun getParam(name: String): AnnotationParam {
return requireNotNull(params[name]) {
"Annotation '$this.name' missing '$name' parameter"
}
}
fun getStringParam(paramName: String): String {
val paramValue = getParam(paramName)
require(paramValue is AnnotationParam.Str) {
"Annotation param $paramName must be string, instead got $paramValue"
}
return paramValue.value
}
fun getOptionalStringParam(paramName: String): String? {
return if (params.containsKey(paramName)) getStringParam(paramName) else null
}
companion object {
fun createArcId(id: String) = Annotation("arcId", mapOf("id" to AnnotationParam.Str(id)))
fun createTtl(value: String) = Annotation(
"ttl",
mapOf("value" to AnnotationParam.Str(value))
)
fun createCapability(name: String) = Annotation(name)
/**
* Returns an annotation indicating that a particle is an egress particle.
*
* @param egressType optional egress type for the particle
*/
fun createEgress(egressType: String? = null): Annotation {
val params = mutableMapOf<String, AnnotationParam>()
if (egressType != null) {
params["type"] = AnnotationParam.Str(egressType)
}
return Annotation("egress", params)
}
/** Returns an annotation indicating the name of the policy which governs a recipe. */
fun createPolicy(policyName: String): Annotation {
return Annotation("policy", mapOf("name" to AnnotationParam.Str(policyName)))
}
/** Annotation indicating that a particle is isolated. */
val isolated = Annotation("isolated")
/** Annotation indicating that a particle has ingress. */
val ingress = Annotation("ingress")
}
}
| bsd-3-clause | b8ed45f77d01b42e125a82631723946c | 31.361111 | 96 | 0.692704 | 4.363296 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt | 2 | 3069 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.util.PlatformUtils
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress
import org.jetbrains.kotlin.idea.util.projectStructure.allModules
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.isJvm
abstract class ConfigureKotlinInProjectAction : AnAction() {
abstract fun getApplicableConfigurators(project: Project): Collection<KotlinProjectConfigurator>
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val (modules, configurators) = underModalProgress(project, KotlinJvmBundle.message("lookup.project.configurators.progress.text")) {
val modules = getConfigurableModules(project)
if (modules.all(::isModuleConfigured)) {
return@underModalProgress modules to emptyList<KotlinProjectConfigurator>()
}
val configurators = getApplicableConfigurators(project)
modules to configurators
}
if (modules.all(::isModuleConfigured)) {
Messages.showInfoMessage(KotlinJvmBundle.message("all.modules.with.kotlin.files.are.configured"), e.presentation.text!!)
return
}
when {
configurators.size == 1 -> configurators.first().configure(project, emptyList())
configurators.isEmpty() -> Messages.showErrorDialog(
KotlinJvmBundle.message("there.aren.t.configurators.available"),
e.presentation.text!!
)
else -> {
val configuratorsPopup =
KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList())
configuratorsPopup.showInBestPositionFor(e.dataContext)
}
}
}
}
class ConfigureKotlinJsInProjectAction : ConfigureKotlinInProjectAction() {
override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter {
it.targetPlatform.isJs()
}
override fun update(e: AnActionEvent) {
val project = e.project
if (!PlatformUtils.isIntelliJ() &&
(project == null || project.allModules().all { it.buildSystemType != BuildSystemType.JPS })
) {
e.presentation.isEnabledAndVisible = false
}
}
}
class ConfigureKotlinJavaInProjectAction : ConfigureKotlinInProjectAction() {
override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter {
it.targetPlatform.isJvm()
}
} | apache-2.0 | dd492e6feab4ce96c016ea75640b78bc | 41.054795 | 158 | 0.710655 | 5.255137 | false | true | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/NotificationsPreference.kt | 2 | 1911 | package com.fsck.k9.ui.settings.account
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.util.AttributeSet
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat.startActivity
import androidx.core.content.res.TypedArrayUtils
import androidx.fragment.app.DialogFragment
import androidx.preference.Preference
import com.takisoft.preferencex.PreferenceFragmentCompat
typealias NotificationChannelIdProvider = () -> String
@SuppressLint("RestrictedApi")
@RequiresApi(Build.VERSION_CODES.O)
class NotificationsPreference
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = TypedArrayUtils.getAttr(
context, androidx.preference.R.attr.preferenceStyle,
android.R.attr.preferenceStyle
),
defStyleRes: Int = 0
) : Preference(context, attrs, defStyleAttr, defStyleRes) {
var notificationChannelIdProvider: NotificationChannelIdProvider? = null
override fun onClick() {
notificationChannelIdProvider.let { provider ->
val intent = if (provider == null) {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
} else {
val notificationChannelId = provider.invoke()
Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_CHANNEL_ID, notificationChannelId)
}
}
intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.context.packageName)
startActivity(this.context, intent, null)
}
}
companion object {
init {
PreferenceFragmentCompat.registerPreferenceFragment(
NotificationsPreference::class.java, DialogFragment::class.java
)
}
}
}
| apache-2.0 | 345b0cc5ae0902d6af0b31b90e383b1c | 33.125 | 81 | 0.710099 | 5.015748 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/rex/REXLayer.kt | 1 | 1729 | package org.hexworks.zircon.internal.util.rex
import org.hexworks.zircon.api.builder.data.TileBuilder
import org.hexworks.zircon.api.builder.graphics.LayerBuilder
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.api.resource.TilesetResource
val TRANSPARENT_BACKGROUND = TileColor.create(255, 0, 255)
/**
* Represents a REX Paint Layer, which contains its size information (width, height) and a [List] of [REXCell]s.
*/
data class REXLayer(
val width: Int,
val height: Int,
val cells: List<REXCell>
) {
/**
* Returns itself as a [REXLayer].
*/
fun toLayer(tileset: TilesetResource): Layer {
val layer = LayerBuilder.newBuilder()
.withTileset(tileset)
.withSize(Size.create(width, height))
.build()
for (y in 0 until height) {
for (x in 0 until width) {
// Have to swap x and y due to how image data is stored
val cell = cells[x * height + y]
if (cell.backgroundColor == TRANSPARENT_BACKGROUND) {
// Skip transparent characters
continue
}
layer.draw(
tile = TileBuilder.newBuilder()
.withCharacter(cell.character)
.withBackgroundColor(cell.backgroundColor)
.withForegroundColor(cell.foregroundColor)
.build(),
drawPosition = Position.create(x, y)
)
}
}
return layer
}
}
| apache-2.0 | 6086552c776c01652e46d704f40d0e75 | 33.58 | 112 | 0.591093 | 4.490909 | false | false | false | false |
fcostaa/kotlin-rxjava-android | library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/UrlEntity.kt | 1 | 599 | package com.github.felipehjcosta.marvelapp.cache.data
import androidx.room.*
@Entity(
tableName = "url",
indices = [Index(value = ["url_character_id"], name = "url_character_index")],
foreignKeys = [ForeignKey(
entity = CharacterEntity::class,
parentColumns = ["id"],
childColumns = ["url_character_id"]
)]
)
data class UrlEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "url_id")
var id: Long = 0L,
var url: String = "",
var type: String = "",
@ColumnInfo(name = "url_character_id")
var characterId: Long = 0L
)
| mit | 3e2ff5cb3f25f754b2632e36bb2ce192 | 22.038462 | 82 | 0.617696 | 3.767296 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/builders/ScanStateListItemsBuilder.kt | 1 | 15048 | package org.wordpress.android.ui.jetpack.scan.builders
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import dagger.Reusable
import org.wordpress.android.Constants
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.scan.ScanStateModel
import org.wordpress.android.fluxc.model.scan.ScanStateModel.ScanProgressStatus
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel
import org.wordpress.android.fluxc.store.ScanStore
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ActionButtonState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.DescriptionState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.DescriptionState.ClickableTextInfo
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.HeaderState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.IconState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ProgressState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.FootnoteState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatsHeaderItemState
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsListItemsBuilder
import org.wordpress.android.ui.reader.utils.DateProvider
import org.wordpress.android.ui.utils.HtmlMessageUtils
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringResWithParams
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.text.PercentFormatter
import org.wordpress.android.viewmodel.ResourceProvider
import javax.inject.Inject
@Reusable
class ScanStateListItemsBuilder @Inject constructor(
private val dateProvider: DateProvider,
private val htmlMessageUtils: HtmlMessageUtils,
private val resourceProvider: ResourceProvider,
private val threatItemBuilder: ThreatItemBuilder,
private val threatDetailsListItemsBuilder: ThreatDetailsListItemsBuilder,
private val scanStore: ScanStore,
private val percentFormatter: PercentFormatter
) {
@Suppress("LongParameterList")
suspend fun buildScanStateListItems(
model: ScanStateModel,
site: SiteModel,
fixingThreatIds: List<Long>,
onScanButtonClicked: () -> Unit,
onFixAllButtonClicked: () -> Unit,
onThreatItemClicked: (threatId: Long) -> Unit,
onHelpClicked: () -> Unit,
onEnterServerCredsIconClicked: () -> Unit
): List<JetpackListItemState> {
return if (fixingThreatIds.isNotEmpty()) {
buildThreatsFixingStateItems(fixingThreatIds)
} else when (model.state) {
ScanStateModel.State.IDLE -> {
model.threats?.takeIf { threats -> threats.isNotEmpty() }?.let { threats ->
buildThreatsFoundStateItems(
model,
threats,
site,
onScanButtonClicked,
onFixAllButtonClicked,
onThreatItemClicked,
onHelpClicked,
onEnterServerCredsIconClicked
)
} ?: buildThreatsNotFoundStateItems(model, onScanButtonClicked)
}
ScanStateModel.State.SCANNING -> buildScanningStateItems(model.mostRecentStatus, model.currentStatus)
ScanStateModel.State.PROVISIONING -> buildProvisioningStateItems()
ScanStateModel.State.UNAVAILABLE, ScanStateModel.State.UNKNOWN -> emptyList()
}
}
private suspend fun buildThreatsFixingStateItems(fixingThreatIds: List<Long>): List<JetpackListItemState> {
val items = mutableListOf<JetpackListItemState>()
val scanIcon = buildScanIcon(R.drawable.ic_shield_warning_white, R.color.error)
val scanHeaderResId = if (fixingThreatIds.size > 1) {
R.string.scan_fixing_threats_title_plural
} else R.string.scan_fixing_threats_title_singular
val scanHeader = HeaderState(UiStringRes(scanHeaderResId))
val scanDescriptionResId = if (fixingThreatIds.size > 1) {
R.string.scan_fixing_threats_description_plural
} else R.string.scan_fixing_threats_description_singular
val scanDescription = DescriptionState(UiStringRes(scanDescriptionResId))
val scanProgress = ProgressState(isIndeterminate = true, isVisible = fixingThreatIds.isNotEmpty())
items.add(scanIcon)
items.add(scanHeader)
items.add(scanDescription)
items.add(scanProgress)
items.add(ThreatsHeaderItemState(threatsCount = fixingThreatIds.size))
items.addAll(
fixingThreatIds.mapNotNull { threatId ->
scanStore.getThreatModelByThreatId(threatId)?.let { threatModel ->
val threatItem = threatItemBuilder.buildThreatItem(threatModel).copy(
isFixing = true,
subHeader = threatDetailsListItemsBuilder.buildFixableThreatDescription(
requireNotNull(threatModel.baseThreatModel.fixable)
).text
)
threatItem
}
}
)
return items
}
@Suppress("LongParameterList")
private fun buildThreatsFoundStateItems(
model: ScanStateModel,
threats: List<ThreatModel>,
site: SiteModel,
onScanButtonClicked: () -> Unit,
onFixAllButtonClicked: () -> Unit,
onThreatItemClicked: (threatId: Long) -> Unit,
onHelpClicked: () -> Unit,
onEnterServerCredsIconClicked: () -> Unit
): List<JetpackListItemState> {
val items = mutableListOf<JetpackListItemState>()
val scanIcon = buildScanIcon(R.drawable.ic_shield_warning_white, R.color.error)
val scanHeader = HeaderState(UiStringRes(R.string.scan_idle_threats_found_title))
val scanDescription = buildThreatsFoundDescription(site, threats.size, onHelpClicked)
val scanButton = buildScanButtonAction(titleRes = R.string.scan_again, onClick = onScanButtonClicked)
items.add(scanIcon)
items.add(scanHeader)
items.add(scanDescription)
val fixableThreats = threats.filter { it.baseThreatModel.fixable != null }
buildFixAllButtonAction(
onFixAllButtonClicked = onFixAllButtonClicked,
isEnabled = model.hasValidCredentials
).takeIf { fixableThreats.isNotEmpty() }?.let { items.add(it) }
if (!model.hasValidCredentials && fixableThreats.isNotEmpty()) {
items.add(
buildEnterServerCredsMessageState(
onEnterServerCredsIconClicked,
iconResId = R.drawable.ic_plus_white_24dp,
iconColorResId = R.color.colorPrimary,
threatsCount = threats.size,
siteId = site.siteId
)
)
}
items.add(scanButton)
threats.takeIf { it.isNotEmpty() }?.let {
items.add(ThreatsHeaderItemState(threatsCount = threats.size))
items.addAll(threats.map { threat -> threatItemBuilder.buildThreatItem(threat, onThreatItemClicked) })
}
return items
}
private fun buildThreatsNotFoundStateItems(
scanStateModel: ScanStateModel,
onScanButtonClicked: () -> Unit
): List<JetpackListItemState> {
val items = mutableListOf<JetpackListItemState>()
val scanIcon = buildScanIcon(R.drawable.ic_shield_tick_white, R.color.jetpack_green_40)
val scanHeader = HeaderState(UiStringRes(R.string.scan_idle_no_threats_found_title))
val scanDescription = scanStateModel.mostRecentStatus?.startDate?.time?.let {
buildLastScanDescription(it)
} ?: DescriptionState(UiStringRes(R.string.scan_idle_manual_scan_description))
val scanButton = buildScanButtonAction(titleRes = R.string.scan_now, onClick = onScanButtonClicked)
items.add(scanIcon)
items.add(scanHeader)
items.add(scanDescription)
items.add(scanButton)
return items
}
@Suppress("ForbiddenComment")
private fun buildScanningStateItems(
mostRecentStatus: ScanProgressStatus?,
currentProgress: ScanProgressStatus?
): List<JetpackListItemState> {
val items = mutableListOf<JetpackListItemState>()
// TODO: ashiagr replace icon with stroke, using direct icon (color = null) causing issues with dynamic tinting
val progress = currentProgress?.progress ?: 0
val scanIcon = buildScanIcon(R.drawable.ic_shield_white, R.color.jetpack_green_5)
val scanTitleRes = if (progress == 0) R.string.scan_preparing_to_scan_title else R.string.scan_scanning_title
val scanHeader = HeaderState(UiStringRes(scanTitleRes))
val descriptionRes = if (mostRecentStatus?.isInitial == true) {
R.string.scan_scanning_is_initial_description
} else {
R.string.scan_scanning_description
}
val scanDescription = DescriptionState(UiStringRes(descriptionRes))
val scanProgress = ProgressState(
progress = progress,
progressLabel = UiStringText(percentFormatter.format(progress))
)
items.add(scanIcon)
items.add(scanHeader)
items.add(scanDescription)
items.add(scanProgress)
return items
}
private fun buildProvisioningStateItems(): List<JetpackListItemState> {
val items = mutableListOf<JetpackListItemState>()
val scanIcon = buildScanIcon(R.drawable.ic_shield_white, R.color.jetpack_green_5)
val scanHeader = HeaderState(UiStringRes(R.string.scan_preparing_to_scan_title))
val scanDescription = DescriptionState(UiStringRes(R.string.scan_provisioning_description))
items.add(scanIcon)
items.add(scanHeader)
items.add(scanDescription)
return items
}
private fun buildScanIcon(@DrawableRes icon: Int, @ColorRes color: Int?) = IconState(
icon = icon,
colorResId = color,
sizeResId = R.dimen.scan_icon_size,
marginResId = R.dimen.scan_icon_margin,
contentDescription = UiStringRes(R.string.scan_state_icon)
)
private fun buildScanButtonAction(@StringRes titleRes: Int, onClick: () -> Unit) = ActionButtonState(
text = UiStringRes(titleRes),
onClick = onClick,
contentDescription = UiStringRes(titleRes),
isSecondary = true
)
private fun buildFixAllButtonAction(
onFixAllButtonClicked: () -> Unit,
isEnabled: Boolean = true
): ActionButtonState {
val title = UiStringRes(R.string.threats_fix_all)
return ActionButtonState(
text = title,
onClick = onFixAllButtonClicked,
contentDescription = title,
isEnabled = isEnabled
)
}
private fun buildLastScanDescription(timeInMs: Long): DescriptionState {
val durationInMs = dateProvider.getCurrentDate().time - timeInMs
val hours = durationInMs / ONE_HOUR
val minutes = durationInMs / ONE_MINUTE
val displayDuration = when {
hours > 0 -> UiStringResWithParams(R.string.scan_in_hours_ago, listOf(UiStringText("${hours.toInt()}")))
minutes > 0 -> UiStringResWithParams(
R.string.scan_in_minutes_ago,
listOf(UiStringText("${minutes.toInt()}"))
)
else -> UiStringRes(R.string.scan_in_few_seconds)
}
return DescriptionState(
UiStringResWithParams(
R.string.scan_idle_last_scan_description,
listOf(displayDuration, UiStringRes(R.string.scan_idle_manual_scan_description))
)
)
}
private fun buildThreatsFoundDescription(
site: SiteModel,
threatsCount: Int,
onHelpClicked: () -> Unit
): DescriptionState {
val clickableText = resourceProvider.getString(R.string.scan_here_to_help)
val descriptionText = if (threatsCount > 1) {
htmlMessageUtils
.getHtmlMessageFromStringFormatResId(
R.string.scan_idle_threats_description_plural,
"<b>$threatsCount</b>",
"<b>${site.name ?: resourceProvider.getString(R.string.scan_this_site)}</b>",
clickableText
)
} else {
htmlMessageUtils
.getHtmlMessageFromStringFormatResId(
R.string.scan_idle_threats_description_singular,
"<b>${site.name ?: resourceProvider.getString(R.string.scan_this_site)}</b>",
clickableText
)
}
val clickableTextStartIndex = descriptionText.indexOf(clickableText)
val clickableTextEndIndex = clickableTextStartIndex + clickableText.length
val clickableTextsInfo = listOf(
ClickableTextInfo(
startIndex = clickableTextStartIndex,
endIndex = clickableTextEndIndex,
onClick = onHelpClicked
)
)
return DescriptionState(
text = UiStringText(descriptionText),
clickableTextsInfo = clickableTextsInfo
)
}
private fun buildEnterServerCredsMessageState(
onEnterServerCredsIconClicked: () -> Unit,
@DrawableRes iconResId: Int? = null,
@ColorRes iconColorResId: Int? = null,
threatsCount: Int,
siteId: Long
): FootnoteState {
val messageResId = if (threatsCount > 1) {
R.string.threat_fix_enter_server_creds_msg_plural
} else {
R.string.threat_fix_enter_server_creds_msg_singular
}
return FootnoteState(
iconResId = iconResId,
iconColorResId = iconColorResId,
text = UiStringText(
htmlMessageUtils.getHtmlMessageFromStringFormatResId(
messageResId,
"${Constants.URL_JETPACK_SETTINGS}/$siteId"
)
),
onIconClick = onEnterServerCredsIconClicked
)
}
companion object {
private const val ONE_MINUTE = 60 * 1000L
private const val ONE_HOUR = 60 * ONE_MINUTE
}
}
| gpl-2.0 | fd5807cb2a0b6cefbe9c488246d8dcad | 42.491329 | 119 | 0.641148 | 5.0735 | false | false | false | false |
MER-GROUP/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/DomainGenerator.kt | 1 | 12076 | package org.jetbrains.protocolModelGenerator
import com.intellij.util.SmartList
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.FileUpdater
import org.jetbrains.protocolReader.JSON_READER_PARAMETER_DEF
import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
internal class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Domain, val fileUpdater: FileUpdater) {
fun registerTypes() {
domain.types?.let {
for (type in it) {
generator.typeMap.getTypeData(domain.domain(), type.id()).type = type
}
}
}
fun generateCommandsAndEvents() {
for (command in domain.commands()) {
val hasResponse = command.returns != null
val returnType = if (hasResponse) generator.naming.commandResult.getShortName(command.name()) else "Unit"
generateTopLevelOutputClass(generator.naming.params, command.name(), command.description, "${generator.naming.requestClassName}<$returnType>", {
append('"')
if (!domain.domain().isEmpty()) {
append(domain.domain()).append('.')
}
append(command.name()).append('"')
}, command.parameters)
if (hasResponse) {
generateJsonProtocolInterface(generator.naming.commandResult.getShortName(command.name()), command.description, command.returns, null)
generator.jsonProtocolParserClassNames.add(generator.naming.commandResult.getFullName(domain.domain(), command.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), command.name(), generator.naming.commandResult))
}
}
if (domain.events != null) {
for (event in domain.events!!) {
generateEvenData(event)
generator.jsonProtocolParserClassNames.add(generator.naming.eventData.getFullName(domain.domain(), event.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), event.name(), generator.naming.eventData))
}
}
}
fun generateCommandAdditionalParam(type: ProtocolMetaModel.StandaloneType) {
generateTopLevelOutputClass(generator.naming.additionalParam, type.id(), type.description, null, null, type.properties)
}
private fun <P : ItemDescriptor.Named> generateTopLevelOutputClass(nameScheme: ClassNameScheme, baseName: String, description: String?, baseType: String?, methodName: (TextOutput.() -> Unit)?, properties: List<P>?) {
generateOutputClass(fileUpdater.out.newLine().newLine(), nameScheme.getFullName(domain.domain(), baseName), description, baseType, methodName, properties)
}
private fun <P : ItemDescriptor.Named> generateOutputClass(out: TextOutput, classNamePath: NamePath, description: String?, baseType: String?, methodName: (TextOutput.() -> Unit)?, properties: List<P>?) {
out.doc(description)
out.append(if (baseType == null) "class" else "fun").space().append(classNamePath.lastComponent).append('(')
val classScope = OutputClassScope(this, classNamePath)
val (mandatoryParameters, optionalParameters) = getParametersInfo(classScope, properties)
if (properties.isNullOrEmpty()) {
assert(baseType != null)
out.append(") = ")
out.append(baseType ?: "org.jetbrains.jsonProtocol.OutMessage")
out.append('(')
methodName?.invoke(out)
out.append(')')
return
}
else {
classScope.writeMethodParameters(out, mandatoryParameters, false)
classScope.writeMethodParameters(out, optionalParameters, mandatoryParameters.isNotEmpty())
out.append(')')
out.append(" : ").append(baseType ?: "org.jetbrains.jsonProtocol.OutMessage")
if (baseType == null) {
out.append("()").openBlock().append("init")
}
}
out.block(baseType != null) {
if (baseType != null) {
out.append("val m = ").append(baseType)
out.append('(')
methodName?.invoke(out)
out.append(')')
}
if (!properties.isNullOrEmpty()) {
val qualifier = if (baseType == null) null else "m"
classScope.writeWriteCalls(out, mandatoryParameters, qualifier)
classScope.writeWriteCalls(out, optionalParameters, qualifier)
if (baseType != null) {
out.newLine().append("return m")
}
}
}
if (baseType == null) {
// close class
out.closeBlock()
}
classScope.writeAdditionalMembers(out)
}
private fun <P : ItemDescriptor.Named> getParametersInfo(classScope: OutputClassScope, properties: List<P>?): Pair<List<Pair<P, BoxableType>>, List<Pair<P, BoxableType>>> {
if (properties.isNullOrEmpty()) {
return Pair(emptyList(), emptyList())
}
val mandatoryParameters = SmartList<Pair<P, BoxableType>>()
val optionalParameters = SmartList<Pair<P, BoxableType>>()
if (properties != null) {
for (parameter in properties) {
val type = MemberScope(classScope, parameter.name()).resolveType(parameter).type
if (parameter.optional) {
optionalParameters.add(parameter to type)
}
else {
mandatoryParameters.add(parameter to type)
}
}
}
return Pair(mandatoryParameters, optionalParameters)
}
fun createStandaloneOutputTypeBinding(type: ProtocolMetaModel.StandaloneType, name: String) = switchByType(type, MyCreateStandaloneTypeBindingVisitorBase(this, type, name))
fun createStandaloneInputTypeBinding(type: ProtocolMetaModel.StandaloneType): StandaloneTypeBinding {
return switchByType(type, object : CreateStandaloneTypeBindingVisitorBase(this, type) {
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?) = createStandaloneObjectInputTypeBinding(type, properties)
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
override fun generate() {
fileUpdater.out.doc(type.description)
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding {
val resolveAndGenerateScope = object : ResolveAndGenerateScope {
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings
// inside TypeDef class.
override fun getDomainName() = domain.domain()
override fun getTypeDirection() = TypeData.Direction.INPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type)
return createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext) = arrayType
}, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}
})
}
fun createStandaloneObjectInputTypeBinding(type: ProtocolMetaModel.StandaloneType, properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
val name = type.id()
val fullTypeName = generator.naming.inputValue.getFullName(domain.domain(), name)
generator.jsonProtocolParserClassNames.add(fullTypeName.getFullText())
return object : StandaloneTypeBinding {
override fun getJavaType() = subMessageType(fullTypeName)
override fun generate() {
val className = generator.naming.inputValue.getFullName(domain.domain(), name)
val out = fileUpdater.out
out.newLine().newLine()
descriptionAndRequiredImport(type.description, out)
out.append("interface ").append(className.lastComponent).openBlock()
val classScope = InputClassScope(this@DomainGenerator, className)
if (properties != null) {
classScope.generateDeclarationBody(out, properties)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
/**
* Typedef is an empty class that just holds description and
* refers to an actual type (such as String).
*/
fun createTypedefTypeBinding(type: ProtocolMetaModel.StandaloneType, target: Target, nameScheme: ClassNameScheme, direction: TypeData.Direction?): StandaloneTypeBinding {
val name = type.id()
val typedefJavaName = nameScheme.getFullName(domain.domain(), name)
val actualJavaType = target.resolve(object : Target.ResolveContext {
override fun generateNestedObject(shortName: String, description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
if (direction == null) {
throw RuntimeException("Unsupported")
}
when (direction) {
TypeData.Direction.INPUT -> throw RuntimeException("TODO")
TypeData.Direction.OUTPUT -> generateOutputClass(TextOutput(StringBuilder()), NamePath(shortName, typedefJavaName), description, null, null, properties)
}
return subMessageType(NamePath(shortName, typedefJavaName))
}
})
return object : StandaloneTypeBinding {
override fun getJavaType() = actualJavaType
override fun generate() {
}
override fun getDirection() = direction
}
}
private fun generateEvenData(event: ProtocolMetaModel.Event) {
val className = generator.naming.eventData.getShortName(event.name())
val domainName = domain.domain()
val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText()
generateJsonProtocolInterface(className, event.description, event.parameters) { out ->
out.newLine().append("companion object TYPE : org.jetbrains.jsonProtocol.EventType<").append(fullName)
if (event.optionalData || event.parameters.isNullOrEmpty()) {
out.append('?')
}
out.append(", ").append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME).append('>')
out.append("(\"")
if (!domainName.isNullOrEmpty()) {
out.append(domainName).append('.')
}
out.append(event.name()).append("\")").block() {
out.append("override fun read(protocolReader: ")
out.append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME).append(", ").append(JSON_READER_PARAMETER_DEF).append(")")
out.append(" = protocolReader.").append(generator.naming.eventData.getParseMethodName(domainName, event.name())).append("(reader)")
}
}
}
private fun generateJsonProtocolInterface(className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: ((out: TextOutput) -> Unit)?) {
val out = fileUpdater.out
out.newLine().newLine()
descriptionAndRequiredImport(description, out)
out.append("interface ").append(className).block {
val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain()))))
if (additionalMembersText != null) {
classScope.addMember(additionalMembersText)
}
if (parameters != null) {
classScope.generateDeclarationBody(out, parameters)
}
classScope.writeAdditionalMembers(out)
}
}
private fun descriptionAndRequiredImport(description: String?, out: TextOutput) {
if (description != null) {
out.doc(description)
}
// out.append("@JsonType").newLine()
}
}
fun subMessageType(namePath: NamePath) = StandaloneType(namePath, "writeMessage", null) | apache-2.0 | e9b6da5b9f290ca48b2819423ba4cb69 | 42.757246 | 218 | 0.701805 | 4.807325 | false | false | false | false |
MER-GROUP/intellij-community | platform/configuration-store-impl/src/FileBasedStorage.kt | 4 | 10542 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.store.ReadOnlyModificationException
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import org.jdom.Element
import org.jdom.JDOMException
import org.jdom.Parent
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.ByteBuffer
open class FileBasedStorage(file: File,
fileSpec: String,
rootElementName: String,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
private var lineSeparator: LineSeparator? = null
private var blockSavingTheContent = false
@Volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode && file.path.startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog: Boolean = false
// we never set io file to null
fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (!storage.blockSavingTheContent) {
super.save()
}
}
override fun saveLocally(element: Element?) {
if (storage.lineSeparator == null) {
storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
}
val virtualFile = storage.getVirtualFile()
if (element == null) {
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog)
}
}
}
fun getVirtualFile(): VirtualFile? {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByIoFile(file)
cachedVirtualFile = result
}
return cachedVirtualFile
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
try {
val file = getVirtualFile()
if (file == null || file.isDirectory || !file.isValid) {
LOG.debug { "Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}" }
}
else if (file.length == 0L) {
processReadException(null)
}
else {
val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray()))
lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.loadDocument(charBuffer).detachRootElement()
}
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
private fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated && (isProjectOrModuleFile(fileSpec) || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) {
if (e != null) {
LOG.info(e)
}
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.getMessage()}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING).notify(null)
}
}
override fun toString() = file.systemIndependentPath
}
fun writeFile(file: File?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile {
val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) {
StorageUtil.getOrCreateVirtualFile(requestor, file)
}
else {
virtualFile!!
}
if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) {
val content = element.toBufferExposingByteArray(lineSeparator.separatorString)
if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) {
throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}")
}
else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------"
}
}
doWrite(requestor, result, element, lineSeparator, prependXmlProlog)
return result
}
private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray()
private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size() + lineSeparator.separatorBytes.size()
if (result.length.toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size(), lineSeparator.separatorBytes))) {
return false
}
for (i in headerLength..oldContent.size() - 1) {
if (oldContent[i] != content.internalBuffer[i - headerLength]) {
return false
}
}
return true
}
private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
LOG.debug { "Save ${file.presentableUrl}" }
val token = WriteAction.start()
try {
val out = file.getOutputStream(requestor)
try {
if (prependXmlProlog) {
out.write(XML_PROLOG)
out.write(lineSeparator.separatorBytes)
}
if (content is Element) {
JDOMUtil.writeParent(content, out, lineSeparator.separatorString)
}
else {
(content as BufferExposingByteArrayOutputStream).writeTo(out)
}
}
finally {
out.close()
}
}
catch (e: FileNotFoundException) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = if (content is Element) content.toBufferExposingByteArray(lineSeparator.separatorString) else (content as BufferExposingByteArrayOutputStream)
throw ReadOnlyModificationException(file, e, object : StateStorage.SaveSession {
override fun save() {
doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog)
}
})
}
finally {
token.finish()
}
}
fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.writeParent(this, out, lineSeparator)
return out
}
public fun isProjectOrModuleFile(fileSpec: String): Boolean = StoragePathMacros.PROJECT_FILE == fileSpec || fileSpec.startsWith(StoragePathMacros.PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE
fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: File, requestor: Any, virtualFile: VirtualFile?) {
if (virtualFile == null) {
LOG.warn("Cannot find virtual file ${file.absolutePath}")
}
if (virtualFile == null) {
if (file.exists()) {
FileUtil.delete(file)
}
}
else if (virtualFile.exists()) {
try {
deleteFile(requestor, virtualFile)
}
catch (e: FileNotFoundException) {
throw ReadOnlyModificationException(virtualFile, e, object : StateStorage.SaveSession {
override fun save() {
deleteFile(requestor, virtualFile)
}
})
}
}
}
fun deleteFile(requestor: Any, virtualFile: VirtualFile) {
runWriteAction { virtualFile.delete(requestor) }
} | apache-2.0 | 1ab2de926ea5f8919b6e0cd1fff32da0 | 37.061372 | 327 | 0.719408 | 4.787466 | false | false | false | false |
hermantai/samples | kotlin/developer-android/sunflower-main/app/src/main/java/com/google/samples/apps/sunflower/HomeViewPagerFragment.kt | 1 | 2572 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayoutMediator
import com.google.samples.apps.sunflower.adapters.MY_GARDEN_PAGE_INDEX
import com.google.samples.apps.sunflower.adapters.PLANT_LIST_PAGE_INDEX
import com.google.samples.apps.sunflower.adapters.SunflowerPagerAdapter
import com.google.samples.apps.sunflower.databinding.FragmentViewPagerBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeViewPagerFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentViewPagerBinding.inflate(inflater, container, false)
val tabLayout = binding.tabs
val viewPager = binding.viewPager
viewPager.adapter = SunflowerPagerAdapter(this)
// Set the icon and text for each tab
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.setIcon(getTabIcon(position))
tab.text = getTabTitle(position)
}.attach()
(activity as AppCompatActivity).setSupportActionBar(binding.toolbar)
return binding.root
}
private fun getTabIcon(position: Int): Int {
return when (position) {
MY_GARDEN_PAGE_INDEX -> R.drawable.garden_tab_selector
PLANT_LIST_PAGE_INDEX -> R.drawable.plant_list_tab_selector
else -> throw IndexOutOfBoundsException()
}
}
private fun getTabTitle(position: Int): String? {
return when (position) {
MY_GARDEN_PAGE_INDEX -> getString(R.string.my_garden_title)
PLANT_LIST_PAGE_INDEX -> getString(R.string.plant_list_title)
else -> null
}
}
}
| apache-2.0 | 2a8f3378621fb7e393f4e8d92f125f3c | 34.722222 | 82 | 0.71423 | 4.344595 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | ui/ui_image_details/src/androidTest/kotlin/siarhei/luskanau/iot/doorbell/ui/imagedetails/ImageDetailsFragmentTest.kt | 1 | 4275 | package siarhei.luskanau.iot.doorbell.ui.imagedetails
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.karumi.shot.ScreenshotTest
import io.mockk.every
import io.mockk.mockk
import kotlin.test.Test
import siarhei.luskanau.iot.doorbell.ui.common.R as CommonR
class ImageDetailsFragmentTest : ScreenshotTest {
companion object {
const val EXPECTED_ERROR_MESSAGE = "Test Exception"
}
private fun createNormalFragmentFactory() = object : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment =
ImageDetailsFragment { fragment: Fragment ->
mockk(relaxed = true, relaxUnitFun = true) {
every { getImageDetailsStateData() } returns
MutableLiveData<ImageDetailsState>().apply {
value = NormalImageDetailsState(
adapter = object : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = 1
override fun createFragment(position: Int): Fragment =
Fragment(R.layout.layout_image_details_slide_normal)
}
)
}
}
}
}
private fun createErrorFragmentFactory() =
object : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment =
ImageDetailsFragment {
object : ImageDetailsPresenter {
override fun getImageDetailsStateData(): LiveData<ImageDetailsState> =
MutableLiveData<ImageDetailsState>().apply {
value = ErrorImageDetailsState(
error = RuntimeException(EXPECTED_ERROR_MESSAGE)
)
}
}
}
}
@Test
fun testNormalState() {
val fragmentFactory = createNormalFragmentFactory()
val scenario = launchFragmentInContainer<ImageDetailsFragment>(
factory = fragmentFactory,
themeResId = CommonR.style.AppTheme
)
scenario.moveToState(Lifecycle.State.RESUMED)
// normal view is displayed
Espresso.onView(ViewMatchers.withId(R.id.viewPager2))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// error view does not exist
Espresso.onView(ViewMatchers.withId(CommonR.id.error_message))
.check(ViewAssertions.doesNotExist())
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".normal"
)
}
}
@Test
fun testErrorState() {
val fragmentFactory = createErrorFragmentFactory()
val scenario = launchFragmentInContainer<ImageDetailsFragment>(
factory = fragmentFactory,
themeResId = CommonR.style.AppTheme
)
scenario.moveToState(Lifecycle.State.RESUMED)
// error view is displayed
Espresso.onView(ViewMatchers.withId(CommonR.id.error_message))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withText(EXPECTED_ERROR_MESSAGE))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// normal view does not exist
Espresso.onView(ViewMatchers.withId(R.id.viewPager2))
.check(ViewAssertions.doesNotExist())
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".empty"
)
}
}
}
| mit | 0f8038b06dcfe34a782c0f490f68e0cc | 38.220183 | 94 | 0.607953 | 5.896552 | false | true | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/plugins/groovy/wizard/MavenGroovyNewProjectBuilder.kt | 2 | 4811 | // 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.idea.maven.plugins.groovy.wizard
import com.intellij.ide.util.EditorHelper
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.GitSilentFileAdderProvider
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.project.DumbAwareRunnable
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.ModulesProvider
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
import org.jetbrains.idea.maven.wizards.AbstractMavenModuleBuilder
import org.jetbrains.idea.maven.wizards.MavenStructureWizardStep
import org.jetbrains.idea.maven.wizards.MavenWizardBundle
import org.jetbrains.idea.maven.wizards.SelectPropertiesStep
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.config.wizard.createSampleGroovyCodeFile
import java.util.*
import kotlin.io.path.Path
import kotlin.io.path.createDirectories
/**
* Currently used only for new project wizard, thus the functionality is rather limited
*/
class MavenGroovyNewProjectBuilder(private val groovySdkVersion: String) : AbstractMavenModuleBuilder() {
var createSampleCode = false
override fun createWizardSteps(wizardContext: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> = arrayOf(
MavenStructureWizardStep(this, wizardContext),
SelectPropertiesStep(wizardContext.project, this),
)
override fun setupRootModel(rootModel: ModifiableRootModel) {
val project = rootModel.project
val contentPath = contentEntryPath ?: return
val path = FileUtil.toSystemIndependentName(contentPath).also { Path(it).createDirectories() }
val root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) ?: return
rootModel.addContentEntry(root)
if (myJdk != null) {
rootModel.sdk = myJdk
}
else {
rootModel.inheritSdk()
}
MavenUtil.runWhenInitialized(project, DumbAwareRunnable { setupMavenStructure (project, root) })
}
private fun setupMavenStructure(project: Project, root: VirtualFile) {
val vcsFileAdder = GitSilentFileAdderProvider.create(project)
try {
root.refresh(true, false) {
val pom = WriteCommandAction.writeCommandAction(project)
.withName(MavenWizardBundle.message("maven.new.project.wizard.groovy.creating.groovy.project"))
.compute<VirtualFile, RuntimeException> {
root.refresh(true, false)
root.findChild(MavenConstants.POM_XML)?.delete(this)
val file = root.createChildData(this, MavenConstants.POM_XML)
vcsFileAdder.markFileForAdding(file)
val properties = Properties()
val conditions = Properties()
properties.setProperty("GROOVY_VERSION", groovySdkVersion)
properties.setProperty("GROOVY_REPOSITORY", GroovyConfigUtils.getMavenSdkRepository(groovySdkVersion))
conditions.setProperty("NEED_POM",
(GroovyConfigUtils.compareSdkVersions(groovySdkVersion, GroovyConfigUtils.GROOVY2_5) >= 0).toString())
conditions.setProperty("CREATE_SAMPLE_CODE", "true")
MavenUtil.runOrApplyMavenProjectFileTemplate(project, file, projectId, null, null, properties,
conditions, MAVEN_GROOVY_XML_TEMPLATE, false)
file
}
val sourceDirectory = VfsUtil.createDirectories(root.path + "/src/main/groovy")
VfsUtil.createDirectories(root.path + "/src/main/resources")
VfsUtil.createDirectories(root.path + "/src/test/groovy")
if (createSampleCode) {
vcsFileAdder.markFileForAdding(sourceDirectory)
createSampleGroovyCodeFile(project, sourceDirectory)
}
MavenProjectsManager.getInstance(project).forceUpdateAllProjectsOrFindAllAvailablePomFiles()
MavenUtil.invokeLater(project, ModalityState.NON_MODAL) {
PsiManager.getInstance(project).findFile(pom)?.let(EditorHelper::openInEditor)
}
}
}
finally {
vcsFileAdder.finish()
}
}
}
private const val MAVEN_GROOVY_XML_TEMPLATE = "Maven Groovy.xml" | apache-2.0 | 2c0ad481781447c7787dbd24b48d6604 | 44.396226 | 137 | 0.750156 | 4.712047 | false | true | false | false |
GunoH/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/AttachComponentsFocusUtil.kt | 2 | 1135 | package com.intellij.xdebugger.impl.ui.attach.dialog.items
import com.intellij.ui.table.JBTable
import com.intellij.util.application
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
internal fun JBTable.installSelectionOnFocus() {
addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent) {
if (e.cause != FocusEvent.Cause.TRAVERSAL &&
e.cause != FocusEvent.Cause.TRAVERSAL_BACKWARD &&
e.cause != FocusEvent.Cause.TRAVERSAL_FORWARD &&
e.cause != FocusEvent.Cause.TRAVERSAL_DOWN &&
e.cause != FocusEvent.Cause.TRAVERSAL_UP
) {
return
}
focusFirst()
application.invokeLater { updateUI() }
}
override fun focusLost(e: FocusEvent) {
if (e.cause != FocusEvent.Cause.TRAVERSAL &&
e.cause != FocusEvent.Cause.TRAVERSAL_BACKWARD &&
e.cause != FocusEvent.Cause.TRAVERSAL_FORWARD &&
e.cause != FocusEvent.Cause.TRAVERSAL_DOWN &&
e.cause != FocusEvent.Cause.TRAVERSAL_UP
) {
return
}
application.invokeLater { updateUI() }
}
})
} | apache-2.0 | 9ce6ca1308b6f4a0e101bb5c0595324d | 31.457143 | 59 | 0.651982 | 4.315589 | false | false | false | false |
GunoH/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/findusages/EditorConfigFindVariableUsagesHandler.kt | 2 | 3218 | // 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.editorconfig.language.codeinsight.findusages
import com.intellij.find.findUsages.FindUsagesHandler
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiReference
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.Processor
import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement
import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor
import org.editorconfig.language.schema.descriptors.impl.EditorConfigReferenceDescriptor
import org.editorconfig.language.util.EditorConfigTextMatchingUtil.textMatchesToIgnoreCase
import org.editorconfig.language.util.EditorConfigVfsUtil
class EditorConfigFindVariableUsagesHandler(element: EditorConfigDescribableElement) : FindUsagesHandler(element) {
override fun processElementUsages(element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions) =
runReadAction {
getId(element)?.let { id -> findAllUsages(element, id) }
?.map(::UsageInfo)
?.all(processor::process) == true
}
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope) =
runReadAction {
if (searchScope !is LocalSearchScope) return@runReadAction emptyList<PsiReference>()
val id = getId(target) ?: return@runReadAction emptyList<PsiReference>()
searchScope.scope.asSequence()
.flatMap { PsiTreeUtil.findChildrenOfType(it, EditorConfigDescribableElement::class.java).asSequence() }
.filter { matches(it, id, target) }
.mapNotNull(EditorConfigDescribableElement::getReference)
.toList()
}
private fun findAllUsages(element: PsiElement, id: String) =
EditorConfigVfsUtil.getEditorConfigFiles(element.project)
.asSequence()
.map(PsiManager.getInstance(element.project)::findFile)
.flatMap { PsiTreeUtil.findChildrenOfType(it, EditorConfigDescribableElement::class.java).asSequence() }
.filter { matches(it, id, element) }
private fun matches(element: PsiElement, id: String, template: PsiElement): Boolean {
if (element !is EditorConfigDescribableElement) return false
if (!textMatchesToIgnoreCase(element, template)) return false
return when (val descriptor = element.getDescriptor(false)) {
is EditorConfigDeclarationDescriptor -> descriptor.id == id
is EditorConfigReferenceDescriptor -> descriptor.id == id
else -> false
}
}
companion object {
fun getId(element: PsiElement): String? {
if (element !is EditorConfigDescribableElement) return null
return when (val descriptor = element.getDescriptor(false)) {
is EditorConfigDeclarationDescriptor -> descriptor.id
is EditorConfigReferenceDescriptor -> descriptor.id
else -> null
}
}
}
}
| apache-2.0 | c7c315cf6ff314850163999729873a18 | 47.029851 | 140 | 0.770976 | 4.973725 | false | true | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/patched/SwingComponentWrapper.kt | 3 | 8944 | /*
* License (BSD):
* ==============
*
* Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com)
* 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 MiG InfoCom AB 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.
*
* @version 1.0
* @author Mikael Grev, MiG InfoCom AB
* Date: 2006-sep-08
*/
package com.intellij.ui.layout.migLayout.patched
import com.intellij.ide.ui.laf.VisualPaddingsProvider
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.util.ThreeState
import net.miginfocom.layout.ComponentWrapper
import net.miginfocom.layout.ContainerWrapper
import net.miginfocom.layout.LayoutUtil
import net.miginfocom.layout.PlatformDefaults
import java.awt.*
import javax.swing.JComponent
import javax.swing.JEditorPane
import javax.swing.JTextArea
import javax.swing.SwingUtilities
import javax.swing.border.LineBorder
import javax.swing.border.TitledBorder
/** Debug color for component bounds outline.
*/
private val DB_COMP_OUTLINE = Color(0, 0, 200)
internal open class SwingComponentWrapper(private val c: JComponent) : ComponentWrapper {
private var hasBaseLine = ThreeState.UNSURE
private var isPrefCalled = false
private var visualPaddings: IntArray? = null
override fun getBaseline(width: Int, height: Int): Int {
var h = height
val visualPaddings = visualPadding
if (h < 0) {
h = c.height
}
else if (visualPaddings != null) {
h = height + visualPaddings[0] + visualPaddings[2]
}
var baseLine = c.getBaseline(if (width < 0) c.width else width, h)
if (baseLine != -1 && visualPaddings != null) {
baseLine -= visualPaddings[0]
}
return baseLine
}
override fun getComponent() = c
override fun getPixelUnitFactor(isHor: Boolean): Float {
throw RuntimeException("Do not use LPX/LPY")
}
override fun getX() = c.x
override fun getY() = c.y
override fun getHeight() = c.height
override fun getWidth() = c.width
override fun getScreenLocationX(): Int {
val p = Point()
SwingUtilities.convertPointToScreen(p, c)
return p.x
}
override fun getScreenLocationY(): Int {
val p = Point()
SwingUtilities.convertPointToScreen(p, c)
return p.y
}
override fun getMinimumHeight(sz: Int): Int {
if (!isPrefCalled) {
c.preferredSize // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize();
isPrefCalled = true
}
return c.minimumSize.height
}
override fun getMinimumWidth(sz: Int): Int {
if (!isPrefCalled) {
c.preferredSize // To defeat a bug where the minimum size is different before and after the first call to getPreferredSize();
isPrefCalled = true
}
return c.minimumSize.width
}
override fun getPreferredHeight(sz: Int): Int {
// If the component has not gotten size yet and there is a size hint, trick Swing to return a better height.
if (c.width == 0 && c.height == 0 && sz != -1) {
c.setBounds(c.x, c.y, sz, 1)
}
return c.preferredSize.height
}
override fun getPreferredWidth(sz: Int): Int {
// If the component has not gotten size yet and there is a size hint, trick Swing to return a better height.
if (c.width == 0 && c.height == 0 && sz != -1) {
c.setBounds(c.x, c.y, 1, sz)
}
return c.preferredSize.width
}
override fun getMaximumHeight(sz: Int) = if (c.isMaximumSizeSet) c.maximumSize.height else Integer.MAX_VALUE
override fun getMaximumWidth(sz: Int) = if (c.isMaximumSizeSet) c.maximumSize.width else Integer.MAX_VALUE
override fun getParent(): ContainerWrapper? {
val p = c.parent ?: return null
return SwingContainerWrapper(p as JComponent)
}
override fun getHorizontalScreenDPI(): Int {
try {
return c.toolkit.screenResolution
}
catch (ex: HeadlessException) {
return PlatformDefaults.getDefaultDPI()
}
}
override fun getVerticalScreenDPI(): Int {
try {
return c.toolkit.screenResolution
}
catch (ex: HeadlessException) {
return PlatformDefaults.getDefaultDPI()
}
}
override fun getScreenWidth(): Int {
try {
return c.toolkit.screenSize.width
}
catch (ignore: HeadlessException) {
return 1024
}
}
override fun getScreenHeight(): Int {
try {
return c.toolkit.screenSize.height
}
catch (ignore: HeadlessException) {
return 768
}
}
override fun hasBaseline(): Boolean {
if (hasBaseLine == ThreeState.UNSURE) {
try {
// do not use component dimensions since it made some components layout themselves to the minimum size
// and that stuck after that. E.g. JLabel with HTML content and white spaces would be very tall.
// Use large number but don't risk overflow or exposing size bugs with Integer.MAX_VALUE
hasBaseLine = ThreeState.fromBoolean(getBaseline(8192, 8192) > -1)
}
catch (ignore: Throwable) {
hasBaseLine = ThreeState.NO
}
}
return hasBaseLine.toBoolean()
}
override fun getLinkId(): String? = c.name
override fun setBounds(x: Int, y: Int, width: Int, height: Int) {
c.setBounds(x, y, width, height)
}
override fun isVisible() = c.isVisible
override fun getVisualPadding(): IntArray? {
visualPaddings?.let {
return it
}
val component = when (c) {
is ComponentWithBrowseButton<*> -> c.childComponent
else -> c
}
val border = component.border ?: return null
if (border is LineBorder || border is TitledBorder) {
return null
}
val paddings = when (border) {
is VisualPaddingsProvider -> border.getVisualPaddings(c)
else -> border.getBorderInsets(component)
} ?: return null
if (paddings.top == 0 && paddings.left == 0 && paddings.bottom == 0 && paddings.right == 0) {
return null
}
visualPaddings = intArrayOf(paddings.top, paddings.left, paddings.bottom, paddings.right)
return visualPaddings
}
override fun paintDebugOutline(showVisualPadding: Boolean) {
if (!c.isShowing) {
return
}
val g = c.graphics as? Graphics2D ?: return
g.paint = DB_COMP_OUTLINE
g.stroke = BasicStroke(1f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10f, floatArrayOf(2f, 4f), 0f)
g.drawRect(0, 0, width - 1, height - 1)
if (showVisualPadding) {
val padding = visualPadding
if (padding != null) {
g.color = Color.GREEN
g.drawRect(padding[1], padding[0], width - 1 - (padding[1] + padding[3]), height - 1 - (padding[0] + padding[2]))
}
}
}
override fun getComponentType(disregardScrollPane: Boolean): Int {
throw RuntimeException("Should be not called and used")
}
override fun getLayoutHashCode(): Int {
var d = c.maximumSize
var hash = d.width + (d.height shl 5)
d = c.preferredSize
hash += (d.width shl 10) + (d.height shl 15)
d = c.minimumSize
hash += (d.width shl 20) + (d.height shl 25)
if (c.isVisible)
hash += 1324511
linkId?.let {
hash += it.hashCode()
}
return hash
}
override fun hashCode() = component.hashCode()
override fun equals(other: Any?) = other is ComponentWrapper && c == other.component
override fun getContentBias(): Int {
return when {
c is JTextArea || c is JEditorPane || java.lang.Boolean.TRUE == c.getClientProperty("migLayout.dynamicAspectRatio") -> LayoutUtil.HORIZONTAL
else -> -1
}
}
}
| apache-2.0 | bdea868b7f63b02fc7b8ae9986ff74f8 | 30.272727 | 146 | 0.682021 | 4.110294 | false | false | false | false |
luks91/prparadise | app/src/main/java/com/github/luks91/teambucket/connection/BitbucketApi.kt | 2 | 4551 | /**
* Copyright (c) 2017-present, Team Bucket Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package com.github.luks91.teambucket.connection
import com.github.luks91.teambucket.model.*
import io.reactivex.Emitter
import io.reactivex.Observable
import io.reactivex.functions.BiConsumer
import io.reactivex.subjects.BehaviorSubject
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Path
import retrofit2.http.Query
import java.util.concurrent.Callable
interface BitbucketApi {
@GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/pull-requests")
fun getPullRequests(
@Header("Authorization") token: String,
@Path("projectName") projectName: String,
@Path("slug") slug: String,
@Query("start") start: Int,
@Query("limit") limit: Int = BitbucketApi.PAGE_SIZE,
@PullRequestStatus @Query("state") status: String = STATUS_OPEN,
@Query("avatarSize") avatarSize: Int = 92,
@Order @Query("order") order: String = NEWEST
): Observable<PagedResponse<PullRequest>>
@GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/pull-requests/{id}/activities")
fun getPullRequestActivities(
@Header("Authorization") token: String,
@Path("projectName") projectName: String,
@Path("slug") slug: String,
@Path("id") pullRequestId: Long,
@Query("start") start: Int,
@Query("limit") limit: Int = BitbucketApi.PAGE_SIZE
): Observable<PagedResponse<PullRequestActivity>>
@GET("/rest/api/1.0/projects/{projectName}/repos/{slug}/participants")
fun getRepositoryParticipants(
@Header("Authorization") token: String,
@Path("projectName") projectName: String,
@Path("slug") slug: String,
@Query("start") start: Int,
@Query("limit") limit: Int = BitbucketApi.PAGE_SIZE
): Observable<PagedResponse<User>>
@GET("/rest/api/1.0/projects/{projectName}/repos")
fun getProjectRepositories(
@Header("Authorization") token: String,
@Path("projectName") projectName: String,
@Query("start") start: Int,
@Query("limit") limit: Int = BitbucketApi.PAGE_SIZE
): Observable<PagedResponse<Repository>>
@GET("/rest/api/1.0/projects/")
fun getProjects(
@Header("Authorization") token: String,
@Query("start") start: Int,
@Query("limit") limit: Int = BitbucketApi.PAGE_SIZE
): Observable<PagedResponse<Project>>
@GET("/rest/api/1.0/users/{userName}")
fun getUser(
@Header("Authorization") token: String,
@Path("userName") userName: String
): Observable<User>
companion object Utility {
const val PAGE_SIZE = 50
fun <TData> queryPaged(generator: (start: Int) -> Observable<PagedResponse<TData>>): Observable<List<TData>> {
return Observable.generate<List<TData>, BehaviorSubject<Int>>(
Callable<BehaviorSubject<Int>> { BehaviorSubject.createDefault(0) },
BiConsumer<BehaviorSubject<Int>, Emitter<List<TData>>> { pageSubject, emitter ->
pageSubject.take(1)
.concatMap { start -> generator.invoke(start) }
.blockingSubscribe({ data ->
if (data.isLastPage) {
if (!data.values.isEmpty()) {
emitter.onNext(data.values)
}
emitter.onComplete()
} else {
emitter.onNext(data.values)
pageSubject.onNext(data.nextPageStart)
}
}, { error -> emitter.onError(error) })
})
}
}
} | apache-2.0 | 3dab30b1d757b4581965798e020b0c62 | 42.769231 | 118 | 0.58998 | 4.677287 | false | false | false | false |
jimandreas/BottomNavigationView-plus-LeakCanary | app/src/main/java/com/jimandreas/android/designlibdemo/SettingsFragment.kt | 2 | 2430 | package com.jimandreas.android.designlibdemo
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatDelegate
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import timber.log.Timber
class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
Timber.v("onSharedPrefChanged: key is %s", key)
}
internal interface RestartCallback {
fun doRestart()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_sandbox)
// Preferences.sync(getPreferenceManager());
// gist from: https://gist.github.com/yujikosuga/1234287
var pref = findPreference("fmi_key")
pref.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference ->
val key = preference.key
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(
"https://github.com/jimandreas/BottomNavigationView-plus-LeakCanary/blob/master/README.md")
startActivity(intent)
true
}
pref = findPreference("nightmode")
pref.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference ->
val key = preference.key
val nightModeSetting = PreferenceManager
.getDefaultSharedPreferences(activity)
.getBoolean("nightmode", false)
Timber.v("click listener: turn night mode: %s", if (nightModeSetting) "on" else "off")
AppCompatDelegate
.setDefaultNightMode(if (nightModeSetting) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)
(activity as RestartCallback).doRestart()
true
}
}
override fun onCreatePreferences(bundle: Bundle?, s: String?) {}
override fun onPreferenceTreeClick(preference: Preference?): Boolean {
val key = preference?.key
return super.onPreferenceTreeClick(preference)
}
} | apache-2.0 | cd436fdffc837d9a89a4b7b80c0716ee | 38.209677 | 133 | 0.695473 | 5.340659 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt | 3 | 5256 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.internal.statistic.utils
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.containers.ObjectIntHashMap
import gnu.trove.THashSet
import java.util.*
fun isDevelopedByJetBrains(pluginId: PluginId?): Boolean {
val plugin = PluginManager.getPlugin(pluginId)
return plugin == null || plugin.isBundled || PluginManagerMain.isDevelopedByJetBrains(plugin.vendor)
}
/**
* Constructs a proper UsageDescriptor for a boolean value,
* by adding "enabled" or "disabled" suffix to the given key, depending on the value.
*/
fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor {
return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1)
}
fun getEnumUsage(key: String, value: Enum<*>?): UsageDescriptor {
return UsageDescriptor(key + "." + value?.name?.toLowerCase(Locale.ENGLISH), 1)
}
/**
* Constructs a proper UsageDescriptor for a counting value.
* If one needs to know a number of some items in the project, there is no direct way to report usages per-project.
* Therefore this workaround: create several keys representing interesting ranges, and report that key which correspond to the range
* which the given value belongs to.
*
* For example, to report a number of commits in Git repository, you can call this method like that:
* ```
* val usageDescriptor = getCountingUsage("git.commit.count", listOf(0, 1, 100, 10000, 100000), realCommitCount)
* ```
* and if there are e.g. 50000 commits in the repository, one usage of the following key will be reported: `git.commit.count.10K+`.
*
* NB:
* (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined.
* (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported:
* `git.commit.count.<1`.
*
* @key The key prefix which will be appended with "." and range code.
* @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly.
* @value Value to be checked among the given ranges.
*/
fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor {
if (steps.isEmpty()) return UsageDescriptor("$key.$value", 1)
if (value < steps[0]) return UsageDescriptor("$key.<${steps[0]}", 1)
var stepIndex = 0
while (stepIndex < steps.size - 1) {
if (value < steps[stepIndex + 1]) break
stepIndex++
}
val step = steps[stepIndex]
val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1
val stepName = humanize(step) + if (addPlus) "+" else ""
return UsageDescriptor("$key.$stepName", 1)
}
/**
* [getCountingUsage] with steps (0, 1, 2, 3, 5, 10, 15, 30, 50, 100, 500, 1000, 5000, 10000, ...)
*/
fun getCountingUsage(key: String, value: Int): UsageDescriptor {
if (value > Int.MAX_VALUE / 10) return UsageDescriptor("$key.MANY", 1)
if (value < 0) return UsageDescriptor("$key.<0", 1)
if (value < 3) return UsageDescriptor("$key.$value", 1)
val fixedSteps = listOf(3, 5, 10, 15, 30, 50)
var step = fixedSteps.last { it <= value }
while (true) {
if (value < step * 2) break
step *= 2
if (value < step * 5) break
step *= 5
}
val stepName = humanize(step)
return UsageDescriptor("$key.$stepName+", 1)
}
private val kilo = 1000
private val mega = kilo * kilo
private fun humanize(number: Int): String {
if (number == 0) return "0"
val m = number / mega
val k = (number % mega) / kilo
val r = (number % kilo)
val ms = if (m > 0) "${m}M" else ""
val ks = if (k > 0) "${k}K" else ""
val rs = if (r > 0) "${r}" else ""
return ms + ks + rs
}
fun toUsageDescriptors(result: ObjectIntHashMap<String>): Set<UsageDescriptor> {
if (result.isEmpty) {
return emptySet()
}
else {
val descriptors = THashSet<UsageDescriptor>(result.size())
result.forEachEntry { key, value ->
descriptors.add(UsageDescriptor(key, value))
true
}
return descriptors
}
}
fun merge(first: Set<UsageDescriptor>, second: Set<UsageDescriptor>): Set<UsageDescriptor> {
if (first.isEmpty()) {
return second
}
if (second.isEmpty()) {
return first
}
val merged = ObjectIntHashMap<String>()
addAll(merged, first)
addAll(merged, second)
return toUsageDescriptors(merged)
}
private fun addAll(result: ObjectIntHashMap<String>, usages: Set<UsageDescriptor>) {
for (usage in usages) {
val key = usage.key
result.put(key, result.get(key, 0) + usage.value)
}
}
| apache-2.0 | 9ed878fdd44f86d14d584b1b8db20eea | 34.04 | 132 | 0.69863 | 3.754286 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/list/ListLogStatusIndicatorCell.kt | 1 | 620 | package lt.markmerkk.widgets.list
import javafx.scene.Parent
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.scene.shape.Circle
import tornadofx.*
class ListLogStatusIndicatorCell: TableCellFragment<ListLogWidget.LogViewModel, String>() {
private lateinit var viewStatusIndicator: Circle
override val root: Parent = stackpane {
viewStatusIndicator = circle {
centerX = 12.0
centerY = 12.0
radius = 10.0
}
}
override fun onDock() {
super.onDock()
viewStatusIndicator.fill = Paint.valueOf(item)
}
} | apache-2.0 | d93a79ceabcdc0c74f953614a00646c6 | 22.884615 | 91 | 0.680645 | 4.217687 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupNotifier.kt | 2 | 5563 | package eu.kanade.tachiyomi.data.backup
import android.content.Context
import android.graphics.BitmapFactory
import androidx.core.app.NotificationCompat
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.NotificationReceiver
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.notificationBuilder
import eu.kanade.tachiyomi.util.system.notificationManager
import uy.kohesive.injekt.injectLazy
import java.io.File
import java.util.concurrent.TimeUnit
class BackupNotifier(private val context: Context) {
private val preferences: PreferencesHelper by injectLazy()
private val progressNotificationBuilder = context.notificationBuilder(Notifications.CHANNEL_BACKUP_RESTORE_PROGRESS) {
setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
setSmallIcon(R.drawable.ic_tachi)
setAutoCancel(false)
setOngoing(true)
setOnlyAlertOnce(true)
}
private val completeNotificationBuilder = context.notificationBuilder(Notifications.CHANNEL_BACKUP_RESTORE_COMPLETE) {
setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
setSmallIcon(R.drawable.ic_tachi)
setAutoCancel(false)
}
private fun NotificationCompat.Builder.show(id: Int) {
context.notificationManager.notify(id, build())
}
fun showBackupProgress(): NotificationCompat.Builder {
val builder = with(progressNotificationBuilder) {
setContentTitle(context.getString(R.string.creating_backup))
setProgress(0, 0, true)
}
builder.show(Notifications.ID_BACKUP_PROGRESS)
return builder
}
fun showBackupError(error: String?) {
context.notificationManager.cancel(Notifications.ID_BACKUP_PROGRESS)
with(completeNotificationBuilder) {
setContentTitle(context.getString(R.string.creating_backup_error))
setContentText(error)
show(Notifications.ID_BACKUP_COMPLETE)
}
}
fun showBackupComplete(unifile: UniFile) {
context.notificationManager.cancel(Notifications.ID_BACKUP_PROGRESS)
with(completeNotificationBuilder) {
setContentTitle(context.getString(R.string.backup_created))
setContentText(unifile.filePath ?: unifile.name)
// Clear old actions if they exist
clearActions()
addAction(
R.drawable.ic_share_24dp,
context.getString(R.string.action_share),
NotificationReceiver.shareBackupPendingBroadcast(context, unifile.uri, Notifications.ID_BACKUP_COMPLETE)
)
show(Notifications.ID_BACKUP_COMPLETE)
}
}
fun showRestoreProgress(content: String = "", progress: Int = 0, maxAmount: Int = 100): NotificationCompat.Builder {
val builder = with(progressNotificationBuilder) {
setContentTitle(context.getString(R.string.restoring_backup))
if (!preferences.hideNotificationContent()) {
setContentText(content)
}
setProgress(maxAmount, progress, false)
setOnlyAlertOnce(true)
// Clear old actions if they exist
clearActions()
addAction(
R.drawable.ic_close_24dp,
context.getString(R.string.action_stop),
NotificationReceiver.cancelRestorePendingBroadcast(context, Notifications.ID_RESTORE_PROGRESS)
)
}
builder.show(Notifications.ID_RESTORE_PROGRESS)
return builder
}
fun showRestoreError(error: String?) {
context.notificationManager.cancel(Notifications.ID_RESTORE_PROGRESS)
with(completeNotificationBuilder) {
setContentTitle(context.getString(R.string.restoring_backup_error))
setContentText(error)
show(Notifications.ID_RESTORE_COMPLETE)
}
}
fun showRestoreComplete(time: Long, errorCount: Int, path: String?, file: String?) {
context.notificationManager.cancel(Notifications.ID_RESTORE_PROGRESS)
val timeString = context.getString(
R.string.restore_duration,
TimeUnit.MILLISECONDS.toMinutes(time),
TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(time)
)
)
with(completeNotificationBuilder) {
setContentTitle(context.getString(R.string.restore_completed))
setContentText(context.resources.getQuantityString(R.plurals.restore_completed_message, errorCount, timeString, errorCount))
// Clear old actions if they exist
clearActions()
if (errorCount > 0 && !path.isNullOrEmpty() && !file.isNullOrEmpty()) {
val destFile = File(path, file)
val uri = destFile.getUriCompat(context)
val errorLogIntent = NotificationReceiver.openErrorLogPendingActivity(context, uri)
setContentIntent(errorLogIntent)
addAction(
R.drawable.ic_folder_24dp,
context.getString(R.string.action_show_errors),
errorLogIntent,
)
}
show(Notifications.ID_RESTORE_COMPLETE)
}
}
}
| apache-2.0 | a71888e65741e0f90fdd7b50dd72ddf0 | 35.123377 | 136 | 0.67194 | 5.066485 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Double/DoubleVec2.kt | 1 | 20332 | package glm
data class DoubleVec2(val x: Double, val y: Double) {
// Initializes each element by evaluating init from 0 until 1
constructor(init: (Int) -> Double) : this(init(0), init(1))
operator fun get(idx: Int): Double = when (idx) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): DoubleVec2 = DoubleVec2(x.inc(), y.inc())
operator fun dec(): DoubleVec2 = DoubleVec2(x.dec(), y.dec())
operator fun unaryPlus(): DoubleVec2 = DoubleVec2(+x, +y)
operator fun unaryMinus(): DoubleVec2 = DoubleVec2(-x, -y)
operator fun plus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x + rhs.x, y + rhs.y)
operator fun minus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x - rhs.x, y - rhs.y)
operator fun times(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x * rhs.x, y * rhs.y)
operator fun div(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x / rhs.x, y / rhs.y)
operator fun rem(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(x % rhs.x, y % rhs.y)
operator fun plus(rhs: Double): DoubleVec2 = DoubleVec2(x + rhs, y + rhs)
operator fun minus(rhs: Double): DoubleVec2 = DoubleVec2(x - rhs, y - rhs)
operator fun times(rhs: Double): DoubleVec2 = DoubleVec2(x * rhs, y * rhs)
operator fun div(rhs: Double): DoubleVec2 = DoubleVec2(x / rhs, y / rhs)
operator fun rem(rhs: Double): DoubleVec2 = DoubleVec2(x % rhs, y % rhs)
inline fun map(func: (Double) -> Double): DoubleVec2 = DoubleVec2(func(x), func(y))
fun toList(): List<Double> = listOf(x, y)
// Predefined vector constants
companion object Constants {
val zero: DoubleVec2 = DoubleVec2(0.0, 0.0)
val ones: DoubleVec2 = DoubleVec2(1.0, 1.0)
val unitX: DoubleVec2 = DoubleVec2(1.0, 0.0)
val unitY: DoubleVec2 = DoubleVec2(0.0, 1.0)
}
// Conversions to Float
fun toVec(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(z: Float = 0f): Vec3 = Vec3(x.toFloat(), y.toFloat(), z)
inline fun toVec3(z: Float = 0f, conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), z)
fun toVec4(z: Float = 0f, w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z, w)
inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w)
// Conversions to Float
fun toMutableVec(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(z: Float = 0f): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z)
inline fun toMutableVec3(z: Float = 0f, conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z)
fun toMutableVec4(z: Float = 0f, w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z, w)
inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toDoubleVec(): DoubleVec2 = DoubleVec2(x, y)
inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y)
inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(z: Double = 0.0): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec3(z: Double = 0.0, conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z)
fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0): DoubleVec4 = DoubleVec4(x, y, z, w)
inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec2 = MutableDoubleVec2(x, y)
inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y)
inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(z: Double = 0.0): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z)
fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w)
inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toIntVec(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(z: Int = 0): IntVec3 = IntVec3(x.toInt(), y.toInt(), z)
inline fun toIntVec3(z: Int = 0, conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z)
fun toIntVec4(z: Int = 0, w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z, w)
inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(z: Int = 0): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z)
inline fun toMutableIntVec3(z: Int = 0, conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z)
fun toMutableIntVec4(z: Int = 0, w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z, w)
inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toLongVec(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(z: Long = 0L): LongVec3 = LongVec3(x.toLong(), y.toLong(), z)
inline fun toLongVec3(z: Long = 0L, conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z)
fun toLongVec4(z: Long = 0L, w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z, w)
inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(z: Long = 0L): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z)
inline fun toMutableLongVec3(z: Long = 0L, conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z)
fun toMutableLongVec4(z: Long = 0L, w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z, w)
inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toShortVec(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(z: Short = 0.toShort()): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z)
inline fun toShortVec3(z: Short = 0.toShort(), conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z)
fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(z: Short = 0.toShort()): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z)
inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z)
fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z, w)
inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toByteVec(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(z: Byte = 0.toByte()): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z)
inline fun toByteVec3(z: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z)
fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(z: Byte = 0.toByte()): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z)
inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z)
fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z, w)
inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toCharVec(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(z: Char): CharVec3 = CharVec3(x.toChar(), y.toChar(), z)
inline fun toCharVec3(z: Char, conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z)
fun toCharVec4(z: Char, w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z, w)
inline fun toCharVec4(z: Char, w: Char, conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(z: Char): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z)
inline fun toMutableCharVec3(z: Char, conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z)
fun toMutableCharVec4(z: Char, w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z, w)
inline fun toMutableCharVec4(z: Char, w: Char, conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toBoolVec(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0)
inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0)
inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z)
inline fun toBoolVec3(z: Boolean = false, conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z)
fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z, w)
inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0)
inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0)
inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z)
inline fun toMutableBoolVec3(z: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z)
fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z, w)
inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z)
inline fun toStringVec3(z: String = "", conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), z)
fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w)
inline fun toStringVec4(z: String = "", w: String = "", conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z)
inline fun toMutableStringVec3(z: String = "", conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z)
fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w)
inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(z: T2, conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toTVec4(z: T2, w: T2, conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(z: T2, conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: DoubleVec2 get() = DoubleVec2(x, x)
val xy: DoubleVec2 get() = DoubleVec2(x, y)
val yx: DoubleVec2 get() = DoubleVec2(y, x)
val yy: DoubleVec2 get() = DoubleVec2(y, y)
val xxx: DoubleVec3 get() = DoubleVec3(x, x, x)
val xxy: DoubleVec3 get() = DoubleVec3(x, x, y)
val xyx: DoubleVec3 get() = DoubleVec3(x, y, x)
val xyy: DoubleVec3 get() = DoubleVec3(x, y, y)
val yxx: DoubleVec3 get() = DoubleVec3(y, x, x)
val yxy: DoubleVec3 get() = DoubleVec3(y, x, y)
val yyx: DoubleVec3 get() = DoubleVec3(y, y, x)
val yyy: DoubleVec3 get() = DoubleVec3(y, y, y)
val xxxx: DoubleVec4 get() = DoubleVec4(x, x, x, x)
val xxxy: DoubleVec4 get() = DoubleVec4(x, x, x, y)
val xxyx: DoubleVec4 get() = DoubleVec4(x, x, y, x)
val xxyy: DoubleVec4 get() = DoubleVec4(x, x, y, y)
val xyxx: DoubleVec4 get() = DoubleVec4(x, y, x, x)
val xyxy: DoubleVec4 get() = DoubleVec4(x, y, x, y)
val xyyx: DoubleVec4 get() = DoubleVec4(x, y, y, x)
val xyyy: DoubleVec4 get() = DoubleVec4(x, y, y, y)
val yxxx: DoubleVec4 get() = DoubleVec4(y, x, x, x)
val yxxy: DoubleVec4 get() = DoubleVec4(y, x, x, y)
val yxyx: DoubleVec4 get() = DoubleVec4(y, x, y, x)
val yxyy: DoubleVec4 get() = DoubleVec4(y, x, y, y)
val yyxx: DoubleVec4 get() = DoubleVec4(y, y, x, x)
val yyxy: DoubleVec4 get() = DoubleVec4(y, y, x, y)
val yyyx: DoubleVec4 get() = DoubleVec4(y, y, y, x)
val yyyy: DoubleVec4 get() = DoubleVec4(y, y, y, y)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Double, y: Double): DoubleVec2 = DoubleVec2(x, y)
operator fun Double.plus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this + rhs.x, this + rhs.y)
operator fun Double.minus(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this - rhs.x, this - rhs.y)
operator fun Double.times(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this * rhs.x, this * rhs.y)
operator fun Double.div(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this / rhs.x, this / rhs.y)
operator fun Double.rem(rhs: DoubleVec2): DoubleVec2 = DoubleVec2(this % rhs.x, this % rhs.y)
| mit | c9a61164f314f1d1709270a183ea2088 | 72.136691 | 167 | 0.655863 | 3.374046 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/assimp/src/templates/kotlin/assimp/AssimpTypes.kt | 2 | 62779 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package assimp
import org.lwjgl.generator.*
import java.io.*
val ASSIMP_BINDING = object : SimpleBinding(Module.ASSIMP, "ASSIMP") {
override fun PrintWriter.generateFunctionSetup(nativeClass: NativeClass) {
println("\n${t}private static final SharedLibrary DRACO = Library.loadNative(Assimp.class, \"${module.java}\", Configuration.ASSIMP_DRACO_LIBRARY_NAME.get(Platform.mapLibraryNameBundled(\"draco\")), true);")
println("${t}private static final SharedLibrary ASSIMP = Library.loadNative(Assimp.class, \"${module.java}\", Configuration.ASSIMP_LIBRARY_NAME.get(Platform.mapLibraryNameBundled(\"assimp\")), true);")
generateFunctionsClass(nativeClass, "\n$t/** Contains the function pointers loaded from the assimp {@link SharedLibrary}. */")
println("""
/** Returns the assimp {@link SharedLibrary}. */
public static SharedLibrary getLibrary() {
return ASSIMP;
}
/** Returns the Draco {@link SharedLibrary}. */
public static SharedLibrary getDraco() {
return DRACO;
}""")
}
}
val ai_int32 = typedef(int32_t, "ai_int32")
val ai_uint32 = typedef(uint32_t, "ai_uint32")
val ai_real = typedef(float, "ai_real")
/*val aiPlane = struct(Binding.ASSIMP, "AIPlane", nativeName = "struct aiPlane") {
documentation = "Represents a plane in a three-dimensional, euclidean space."
float("a", "Plane equation")
float("b", "Plane equation")
float("c", "Plane equation")
float("d", "Plane equation")
}*/
val aiVector2D = struct(Module.ASSIMP, "AIVector2D", nativeName = "struct aiVector2D", mutable = false) {
float("x", "")
float("y", "")
}
val aiVector3D = struct(Module.ASSIMP, "AIVector3D", nativeName = "struct aiVector3D") {
float("x", "")
float("y", "")
float("z", "")
}
val aiAABB = struct(Module.ASSIMP, "AIAABB", nativeName = "struct aiAABB") {
aiVector3D("mMin", "")
aiVector3D("mMax", "")
}
/*val aiRay = struct(Binding.ASSIMP, "AIRay", nativeName = "struct aiRay") {
documentation = "Represents a ray."
aiVector3D("pos", "Position of the ray")
aiVector3D("dir", "Direction of the ray")
}*/
val aiColor3D = struct(Module.ASSIMP, "AIColor3D", nativeName = "struct aiColor3D", mutable = false) {
documentation = "Represents a color in Red-Green-Blue space."
float("r", "The red color value")
float("g", "The green color value")
float("b", "The blue color value")
}
val aiString = struct(Module.ASSIMP, "AIString", nativeName = "struct aiString") {
documentation = "Represents an UTF-8 string, zero byte terminated."
AutoSize("data")..ai_uint32("length", "Binary length of the string excluding the terminal 0.")
NullTerminatedMember..charUTF8("data", "String buffer.")["Assimp.MAXLEN"]
}
val aiMemoryInfo = struct(Module.ASSIMP, "AIMemoryInfo", nativeName = "struct aiMemoryInfo", mutable = false) {
documentation = "Stores the memory requirements for different components (e.g. meshes, materials, animations) of an import. All sizes are in bytes."
unsigned_int("textures", "Storage allocated for texture data")
unsigned_int("materials", "Storage allocated for material data")
unsigned_int("meshes", "Storage allocated for mesh data")
unsigned_int("nodes", "Storage allocated for node data")
unsigned_int("animations", "Storage allocated for animation data")
unsigned_int("cameras", "Storage allocated for camera data")
unsigned_int("lights", "Storage allocated for light data")
unsigned_int("total", "Total storage allocated for the full import.")
}
val aiTexel = struct(Module.ASSIMP, "AITexel", nativeName = "struct aiTexel", mutable = false) {
documentation = "Helper structure to represent a texel in a ARGB8888 format. Used by aiTexture."
unsigned_char("b", "The blue color component")
unsigned_char("g", "The green color component")
unsigned_char("r", "The red color component")
unsigned_char("a", "The alpha color component")
}
private const val HINTMAXTEXTURELEN = 9
val aiTexture = struct(Module.ASSIMP, "AITexture", nativeName = "struct aiTexture", mutable = false) {
documentation =
"""
Helper structure to describe an embedded texture.
Normally textures are contained in external files but some file formats embed them directly in the model file. There are two types of embedded
textures:
${ul(
"Uncompressed textures. The color data is given in an uncompressed format.",
"Compressed textures stored in a file format like png or jpg."
)}
The raw file bytes are given so the application must utilize an image decoder (e.g. DevIL) to get access to the actual color data.
Embedded textures are referenced from materials using strings like "*0", "*1", etc. as the texture paths (a single asterisk character followed by the
zero-based index of the texture in the ##AIScene{@code ::mTextures} array).
"""
AutoSize("pcData")..unsigned_int(
"mWidth",
"""
Width of the texture, in pixels. If {@code mHeight} is zero the texture is compressed in a format like JPEG. In this case {@code mWidth} specifies the
size of the memory area {@code pcData} is pointing to, in bytes.
"""
)
AutoSize("pcData")..unsigned_int(
"mHeight",
"Height of the texture, in pixels. If this value is zero, {@code pcData} points to an compressed texture in any format (e.g. JPEG)."
)
charASCII(
"achFormatHint",
"""
A hint from the loader to make it easier for applications to determine the type of embedded textures.
If {@code mHeight != 0} this member is show how data is packed. Hint will consist of two parts: channel order and channel bitness (count of the bits
for every color channel). For simple parsing by the viewer it's better to not omit absent color channel and just use 0 for bitness. For example:
${ol(
"Image contain RGBA and 8 bit per channel, {@code achFormatHint == \"rgba8888\";}",
"Image contain ARGB and 8 bit per channel, {@code achFormatHint == \"argb8888\";}",
"Image contain RGB and 5 bit for R and B channels and 6 bit for G channel, {@code achFormatHint == \"rgba5650\";}",
"One color image with B channel and 1 bit for it, {@code achFormatHint == \"rgba0010\";}"
)}
If {@code mHeight == 0} then {@code achFormatHint} is set set to '\0\0\0\0' if the loader has no additional information about the texture file format
used OR the file extension of the format without a trailing dot. If there are multiple file extensions for a format, the shortest extension is chosen
(JPEG maps to 'jpg', not to 'jpeg'). E.g. 'dds\0', 'pcx\0', 'jpg\0'. All characters are lower-case. The fourth character will always be '\0'.
"""
)[HINTMAXTEXTURELEN] // 8 for string + 1 for terminator.
aiTexel.p(
"pcData",
"""
Data of the texture.
Points to an array of {@code mWidth * mHeight} ##AITexel's. The format of the texture data is always ARGB8888 to make the implementation for user of
the library as easy as possible. If {@code mHeight = 0} this is a pointer to a memory buffer of size {@code mWidth} containing the compressed texture
data. Good luck, have fun!
"""
)
aiString("mFilename", "texture original filename. Used to get the texture reference.")
customMethod("""
/** Returns a {@code char *} view of the array pointed to by the {@code pcData} field. */
@NativeType("char *")
public ByteBuffer pcDataCompressed() { return npcDataCompressed(address()); }
/** Unsafe version of {@link #pcDataCompressed}. */
public static ByteBuffer npcDataCompressed(long struct) { return memByteBuffer(memGetAddress(struct + AITexture.PCDATA), nmWidth(struct)); }""")
customMethodBuffer("""
$t/** Returns a {@code char *} view of the array pointed to by the {@code pcData} field. */
@NativeType("char *")
public ByteBuffer pcDataCompressed() { return npcDataCompressed(address()); }""")
}
val aiColor4D = struct(Module.ASSIMP, "AIColor4D", nativeName = "struct aiColor4D") {
documentation = "Represents a color in Red-Green-Blue space including an alpha component. Color values range from 0 to 1."
float("r", "The red color component")
float("g", "The green color component")
float("b", "The blue color component")
float("a", "The alpha color component")
}
val aiMatrix4x4 = struct(Module.ASSIMP, "AIMatrix4x4", nativeName = "struct aiMatrix4x4") {
documentation = "Represents a row-major 4x4 matrix, use this for homogeneous coordinates."
float("a1", "")
float("a2", "")
float("a3", "")
float("a4", "")
float("b1", "")
float("b2", "")
float("b3", "")
float("b4", "")
float("c1", "")
float("c2", "")
float("c3", "")
float("c4", "")
float("d1", "")
float("d2", "")
float("d3", "")
float("d4", "")
}
val aiMatrix3x3 = struct(Module.ASSIMP, "AIMatrix3x3", nativeName = "struct aiMatrix3x3") {
documentation = "Represents a row-major 3x3 matrix."
float("a1", "")
float("a2", "")
float("a3", "")
float("b1", "")
float("b2", "")
float("b3", "")
float("c1", "")
float("c2", "")
float("c3", "")
}
val aiMetadataType = "aiMetadataType".enumType
val aiMetadataEntry = struct(Module.ASSIMP, "AIMetaDataEntry", nativeName = "struct aiMetadataEntry") {
aiMetadataType("mType", "")
void.p("mData", "")
}
val aiMetadata = struct(Module.ASSIMP, "AIMetaData", nativeName = "struct aiMetadata") {
AutoSize("mKeys", "mValues")..unsigned_int("mNumProperties", "Length of the {@code mKeys} and {@code mValues} arrays, respectively")
aiString.p("mKeys", "Arrays of keys, may not be #NULL. Entries in this array may not be #NULL as well.")
aiMetadataEntry.p(
"mValues",
"Arrays of values, may not be #NULL. Entries in this array may be #NULL if the corresponding property key has no assigned value."
)
}
private val _aiNode = struct(Module.ASSIMP, "AINode", nativeName = "struct aiNode")
val aiNode = struct(Module.ASSIMP, "AINode", nativeName = "struct aiNode") {
documentation =
"""
A node in the imported hierarchy.
Each node has name, a parent node (except for the root node), a transformation relative to its parent and possibly several child nodes. Simple file
formats don't support hierarchical structures - for these formats the imported scene does consist of only a single root node without children.
"""
aiString(
"mName",
"""
The name of the node.
The name might be empty (length of zero) but all nodes which need to be referenced by either bones or animations are named. Multiple nodes may have the
same name, except for nodes which are referenced by bones (see ##AIBone and ##AIMesh{@code ::mBones}). Their names <b>must</b> be unique.
Cameras and lights reference a specific node by name - if there are multiple nodes with this name, they are assigned to each of them.
There are no limitations with regard to the characters contained in the name string as it is usually taken directly from the source file.
Implementations should be able to handle tokens such as whitespace, tabs, line feeds, quotation marks, ampersands etc.
Sometimes assimp introduces new nodes not present in the source file into the hierarchy (usually out of necessity because sometimes the source
hierarchy format is simply not compatible). Their names are surrounded by {@code <>} e.g. {@code <DummyRootNode>}.
"""
)
aiMatrix4x4("mTransformation", "The transformation relative to the node's parent.")
nullable.._aiNode.p("mParent", "Parent node. #NULL if this node is the root node.")
AutoSize("mChildren", optional = true)..unsigned_int("mNumChildren", "The number of child nodes of this node.")
_aiNode.p.p("mChildren", "The child nodes of this node. #NULL if {@code mNumChildren} is 0.")
AutoSize("mMeshes", optional = true)..unsigned_int("mNumMeshes", "The number of meshes of this node.")
unsigned_int.p("mMeshes", "The meshes of this node. Each entry is an index into the mesh list of the ##AIScene.")
nullable..aiMetadata.p(
"mMetadata",
"""
Metadata associated with this node or #NULL if there is no metadata.
Whether any metadata is generated depends on the source file format. See the importer notes page for more information on every source file format.
Importers that don't document any metadata don't write any.
"""
)
}
val aiFace = struct(Module.ASSIMP, "AIFace", nativeName = "struct aiFace") {
documentation =
"""
A single face in a mesh, referring to multiple vertices.
If {@code mNumIndices} is 3, we call the face 'triangle', for {@code mNumIndices > 3} it's called 'polygon' (hey, that's just a definition!).
##AIMesh{@code ::mPrimitiveTypes} can be queried to quickly examine which types of primitive are actually present in a mesh. The #Process_SortByPType
flag executes a special post-processing algorithm which splits meshes with *different* primitive types mixed up (e.g. lines and triangles) in several
'clean' submeshes. Furthermore there is a configuration option (#AI_CONFIG_PP_SBP_REMOVE) to force #Process_SortByPType to remove specific kinds of
primitives from the imported scene, completely and forever.
"""
AutoSize("mIndices")..unsigned_int(
"mNumIndices",
"Number of indices defining this face. The maximum value for this member is #AI_MAX_FACE_INDICES."
)
unsigned_int.p("mIndices", "Pointer to the indices array. Size of the array is given in {@code numIndices}.")
}
val aiVertexWeight = struct(Module.ASSIMP, "AIVertexWeight", nativeName = "struct aiVertexWeight") {
documentation = "A single influence of a bone on a vertex."
unsigned_int("mVertexId", "Index of the vertex which is influenced by the bone.")
float("mWeight", "The strength of the influence in the range (0...1). The influence from all bones at one vertex amounts to 1.")
}
val aiBone = struct(Module.ASSIMP, "AIBone", nativeName = "struct aiBone") {
documentation =
"""
A single bone of a mesh.
A bone has a name by which it can be found in the frame hierarchy and by which it can be addressed by animations. In addition it has a number of
influences on vertices, and a matrix relating the mesh position to the position of the bone at the time of binding.
"""
aiString("mName", "the name of the bone.")
AutoSize("mWeights")..unsigned_int(
"mNumWeights",
"the number of vertices affected by this bone. The maximum value for this member is #AI_MAX_BONE_WEIGHTS."
)
aiNode.p("mArmature", "the bone armature node - used for skeleton conversion you must enable #Process_PopulateArmatureData to populate this");
aiNode.p("mNode", "the bone node in the scene - used for skeleton conversion you must enable #Process_PopulateArmatureData to populate this");
aiVertexWeight.p("mWeights", "the influence weights of this bone, by vertex index")
aiMatrix4x4(
"mOffsetMatrix",
"""
matrix that transforms from mesh space to bone space in bind pose.
This matrix describes the position of the mesh in the local space of this bone when the skeleton was bound. Thus it can be used directly to determine a
desired vertex position, given the world-space transform of the bone when animated, and the position of the vertex in mesh space.
It is sometimes called an inverse-bind matrix, or inverse bind pose matrix.
"""
)
}
val aiAnimMesh = struct(Module.ASSIMP, "AIAnimMesh", nativeName = "struct aiAnimMesh") {
documentation =
"""
An {@code AnimMesh} is an attachment to an ##AIMesh stores per-vertex animations for a particular frame.
You may think of an {@code aiAnimMesh} as a `patch` for the host mesh, which replaces only certain vertex data streams at a particular time. Each mesh
stores n attached attached meshes (##AIMesh{@code ::mAnimMeshes}). The actual relationship between the time line and anim meshes is established by
{@code aiMeshAnim}, which references singular mesh attachments by their ID and binds them to a time offset.
"""
aiString("mName", "the {@code AnimMesh} name")
nullable..aiVector3D.p(
"mVertices",
"""
Replacement for ##AIMesh{@code ::mVertices}. If this array is non-#NULL, it *must* contain {@code mNumVertices} entries. The corresponding array in the
host mesh must be non-#NULL as well - animation meshes may neither add or nor remove vertex components (if a replacement array is #NULL and the
corresponding source array is not, the source data is taken instead).
"""
)
nullable..aiVector3D.p("mNormals", "Replacement for ##AIMesh{@code ::mNormals}.")
nullable..aiVector3D.p("mTangents", "Replacement for ##AIMesh{@code ::mTangents}.")
nullable..aiVector3D.p("mBitangents", "Replacement for ##AIMesh{@code ::mBitangents}.")
nullable..aiColor4D.p("mColors", "Replacement for ##AIMesh{@code ::mColors}")["Assimp.AI_MAX_NUMBER_OF_COLOR_SETS"]
nullable..aiVector3D.p("mTextureCoords", "Replacement for ##AIMesh{@code ::mTextureCoords}")["Assimp.AI_MAX_NUMBER_OF_TEXTURECOORDS"]
AutoSize(
"mVertices", "mNormals", "mTangents", "mBitangents"
)..AutoSizeIndirect(
"mColors", "mTextureCoords"
)..unsigned_int(
"mNumVertices",
"""
The number of vertices in the {@code aiAnimMesh}, and thus the length of all the member arrays.
This has always the same value as the {@code mNumVertices} property in the corresponding ##AIMesh. It is duplicated here merely to make the length of
the member arrays accessible even if the {@code aiMesh} is not known, e.g. from language bindings.
"""
)
float("mWeight", "Weight of the {@code AnimMesh}.")
}
val aiMesh = struct(Module.ASSIMP, "AIMesh", nativeName = "struct aiMesh") {
javaImport("static org.lwjgl.assimp.Assimp.*")
documentation =
"""
A mesh represents a geometry or model with a single material.
It usually consists of a number of vertices and a series of primitives/faces referencing the vertices. In addition there might be a series of bones,
each of them addressing a number of vertices with a certain weight. Vertex data is presented in channels with each channel containing a single
per-vertex information such as a set of texture coordinates or a normal vector. If a data pointer is non-null, the corresponding data stream is
present.
A Mesh uses only a single material which is referenced by a material ID.
"""
unsigned_int(
"mPrimitiveTypes",
"""
Bitwise combination of the members of the {@code aiPrimitiveType} enum. This specifies which types of primitives are present in the mesh. The
"SortByPrimitiveType"-Step can be used to make sure the output meshes consist of one primitive type each.
"""
).links("PrimitiveType_\\w+", LinkMode.BITFIELD)
AutoSize(
"mVertices", "mNormals", "mTangents", "mBitangents"
)..AutoSizeIndirect(
"mColors", "mTextureCoords"
)..unsigned_int(
"mNumVertices",
"""
The number of vertices in this mesh. This is also the size of all of the per-vertex data arrays. The maximum value for this member is #AI_MAX_VERTICES.
"""
)
AutoSize("mFaces")..unsigned_int(
"mNumFaces",
"""
The number of primitives (triangles, polygons, lines) in this mesh. This is also the size of the {@code mFaces} array. The maximum value for this
member is #AI_MAX_FACES.
"""
)
aiVector3D.p("mVertices", "Vertex positions. This array is always present in a mesh. The array is {@code mNumVertices} in size.")
nullable..aiVector3D.p(
"mNormals",
"""
Vertex normals.
The array contains normalized vectors, #NULL if not present. The array is {@code mNumVertices} in size. Normals are undefined for point and line
primitives. A mesh consisting of points and lines only may not have normal vectors. Meshes with mixed primitive types (i.e. lines and triangles) may
have normals, but the normals for vertices that are only referenced by point or line primitives are undefined and set to {@code qNaN}.
${note("""
Normal vectors computed by Assimp are always unit-length. However, this needn't apply for normals that have been taken directly from the model file
""")}
"""
)
nullable..aiVector3D.p(
"mTangents",
"""
Vertex tangents.
The tangent of a vertex points in the direction of the positive X texture axis. The array contains normalized vectors, #NULL if not present. The array
is {@code mNumVertices} in size. A mesh consisting of points and lines only may not have normal vectors. Meshes with mixed primitive types (i.e. lines
and triangles) may have normals, but the normals for vertices that are only referenced by point or line primitives are undefined and set to
{@code qNaN}.
${note("If the mesh contains tangents, it automatically also contains bitangents.")}
"""
)
nullable..aiVector3D.p(
"mBitangents",
"""
Vertex bitangents.
The bitangent of a vertex points in the direction of the positive Y texture axis. The array contains normalized vectors, #NULL if not present. The
array is {@code mNumVertices} in size.
${note("If the mesh contains tangents, it automatically also contains bitangents.")}
"""
)
nullable..aiColor4D.p(
"mColors",
"""
Vertex color sets. A mesh may contain 0 to #AI_MAX_NUMBER_OF_COLOR_SETS vertex colors per vertex. #NULL if not present. Each array is
{@code mNumVertices} in size if present.
"""
)["AI_MAX_NUMBER_OF_COLOR_SETS"]
nullable..aiVector3D.p(
"mTextureCoords",
"""
Vertex texture coordinates, also known as UV channels. A mesh may contain 0 to #AI_MAX_NUMBER_OF_TEXTURECOORDS per vertex. #NULL if not present. The
array is {@code mNumVertices} in size.
"""
)["AI_MAX_NUMBER_OF_TEXTURECOORDS"]
unsigned_int(
"mNumUVComponents",
"""
Specifies the number of components for a given UV channel. Up to three channels are supported (UVW, for accessing volume or cube maps). If the value is
2 for a given channel n, the component {@code p.z} of {@code mTextureCoords[n][p]} is set to 0.0f. If the value is 1 for a given channel, {@code p.y}
is set to 0.0f, too.
Note: 4D coordinates are not supported.
"""
)["AI_MAX_NUMBER_OF_TEXTURECOORDS"]
aiFace.p(
"mFaces",
"""
The faces the mesh is constructed from. Each face refers to a number of vertices by their indices. This array is always present in a mesh, its size is
given in {@code mNumFaces}. If the #AI_SCENE_FLAGS_NON_VERBOSE_FORMAT is NOT set each face references an unique set of vertices.
"""
)
AutoSize("mBones", optional = true)..unsigned_int(
"mNumBones",
"The number of bones this mesh contains. Can be 0, in which case the {@code mBones} array is #NULL."
)
aiBone.p.p(
"mBones",
"The bones of this mesh. A bone consists of a name by which it can be found in the frame hierarchy and a set of vertex weights."
)
unsigned_int(
"mMaterialIndex",
"""
The material used by this mesh. A mesh uses only a single material. If an imported model uses multiple materials, the import splits up the mesh. Use
this value as index into the scene's material list.
"""
)
aiString(
"mName",
"""
Name of the mesh.
Meshes can be named, but this is not a requirement and leaving this field empty is totally fine. There are mainly three uses for mesh names:
${ul(
"some formats name nodes and meshes independently.",
"""
importers tend to split meshes up to meet the one-material-per-mesh requirement. Assigning the same (dummy) name to each of the result meshes aids
the caller at recovering the original mesh partitioning.
""",
"vertex animations refer to meshes by their names."
)}
"""
)
AutoSize("mAnimMeshes", optional = true)..unsigned_int(
"mNumAnimMeshes",
"The number of attachment meshes. Note! Currently only works with Collada loader."
)
aiAnimMesh.p.p(
"mAnimMeshes",
"""
Attachment meshes for this mesh, for vertex-based animation. Attachment meshes carry replacement data for some of the mesh'es vertex components
(usually positions, normals). Note! Currently only works with Collada loader.
"""
)
unsigned_int("mMethod", "Method of morphing when anim-meshes are specified.").links("MorphingMethod_\\w+")
aiAABB("mAABB", "the bounding box")
Check("AI_MAX_NUMBER_OF_TEXTURECOORDS")..nullable..aiString.p.p(
"mTextureCoordsNames",
"Vertex UV stream names. Pointer to array of size #AI_MAX_NUMBER_OF_TEXTURECOORDS."
)
}
val aiSkeletonBone = struct(Module.ASSIMP, "AISkeletonBone", nativeName = "struct aiSkeletonBone") {
int("mParent", "the parent bone index, is -1 one if this bone represents the root bone")
nullable..aiNode.p(
"mArmature",
"""
The bone armature node - used for skeleton conversion.
You must enable #Process_PopulateArmatureData to populate this.
"""
)
nullable..aiNode.p(
"mNode",
"""
The bone node in the scene - used for skeleton conversion.
You must enable #Process_PopulateArmatureData to populate this.
"""
)
AutoSize("mMeshId", "mWeights")..unsigned_int("mNumnWeights", "the number of weights");
aiMesh.p("mMeshId", "the mesh index, which will get influenced by the weight")
aiVertexWeight.p("mWeights", "the influence weights of this bone, by vertex index")
aiMatrix4x4(
"mOffsetMatrix",
"""
Matrix that transforms from bone space to mesh space in bind pose.
This matrix describes the position of the mesh in the local space of this bone when the skeleton was bound. Thus it can be used directly to determine a
desired vertex position, given the world-space transform of the bone when animated, and the position of the vertex in mesh space.
It is sometimes called an inverse-bind matrix, or inverse bind pose matrix.
"""
)
aiMatrix4x4("mLocalMatrix", "matrix that transforms the local bone in bind pose")
}
val aiSkeleton = struct(Module.ASSIMP, "AISkeleton", nativeName = "struct aiSkeleton") {
aiString("mName", "")
AutoSize("mBones")..unsigned_int("mNumBones", "")
aiSkeletonBone.p.p("mBones", "");
}
val aiUVTransform = struct(Module.ASSIMP, "AIUVTransform", nativeName = "struct aiUVTransform", mutable = false) {
documentation =
"""
Defines how an UV channel is transformed.
This is just a helper structure for the #_AI_MATKEY_UVTRANSFORM_BASE key. See its documentation for more details.
Typically you'll want to build a matrix of this information. However, we keep separate scaling/translation/rotation values to make it easier to process
and optimize UV transformations internally.
"""
aiVector2D("mTranslation", "Translation on the u and v axes. The default value is (0|0).")
aiVector2D("mScaling", "Scaling on the u and v axes. The default value is (1|1).")
float(
"mRotation",
"Rotation - in counter-clockwise direction. The rotation angle is specified in radians. The rotation center is 0.5f|0.5f. The default value 0.f."
)
}
val aiPropertyTypeInfo = "aiPropertyTypeInfo".enumType
val aiMaterialProperty = struct(Module.ASSIMP, "AIMaterialProperty", nativeName = "struct aiMaterialProperty", mutable = false) {
documentation =
"""
Data structure for a single material property.
As a user, you'll probably never need to deal with this data structure. Just use the provided {@code aiGetMaterialXXX()} family of functions to query
material properties easily. Processing them manually is faster, but it is not the recommended way. It isn't worth the effort.
Material property names follow a simple scheme:
${codeBlock("""
$<name>
?<name>
A public property, there must be corresponding AI_MATKEY_XXX define
2nd: Public, but ignored by the aiProcess_RemoveRedundantMaterials
post-processing step.
~<name>
A temporary property for internal use.
""")}
"""
aiString("mKey", "Specifies the name of the property (key). Keys are generally case insensitive.")
unsigned_int(
"mSemantic",
"Textures: Specifies their exact usage semantic. For non-texture properties, this member is always 0 (or, better-said, #TextureType_NONE)."
)
unsigned_int("mIndex", "Textures: Specifies the index of the texture. For non-texture properties, this member is always 0.")
AutoSize("mData")..unsigned_int("mDataLength", "Size of the buffer {@code mData} is pointing to, in bytes. This value may not be 0.")
aiPropertyTypeInfo(
"mType",
"""
Type information for the property. Defines the data layout inside the data buffer. This is used by the library internally to perform debug checks and
to utilize proper type conversions. (It's probably a hacky solution, but it works.)
"""
)
char.p("mData", "Binary buffer to hold the property's value. The size of the buffer is always mDataLength.")
}
val aiMaterial = struct(Module.ASSIMP, "AIMaterial", nativeName = "struct aiMaterial") {
documentation =
"""
Data structure for a material.
Material data is stored using a key-value structure. A single key-value pair is called a 'material property'. C++ users should use the provided member
functions of {@code aiMaterial} to process material properties, C users have to stick with the {@code aiMaterialGetXXX} family of unbound functions.
The library defines a set of standard keys (AI_MATKEY_XXX).
"""
aiMaterialProperty.p.p("mProperties", "List of all material properties loaded.")
AutoSize("mProperties")..unsigned_int("mNumProperties", "Number of properties in the data base")
unsigned_int("mNumAllocated", "Storage allocated")
}
val aiQuaternion = struct(Module.ASSIMP, "AIQuaternion", nativeName = "struct aiQuaternion") {
documentation = "Represents a quaternion in a 4D vector."
float("w", "The w component")
float("x", "The x component")
float("y", "The y component")
float("z", "The z component")
}
val aiVectorKey = struct(Module.ASSIMP, "AIVectorKey", nativeName = "struct aiVectorKey") {
documentation = "A time-value pair specifying a certain 3D vector for the given time."
double("mTime", "The time of this key")
aiVector3D("mValue", "The value of this key")
}
val aiQuatKey = struct(Module.ASSIMP, "AIQuatKey", nativeName = "struct aiQuatKey") {
documentation = "A time-value pair specifying a rotation for the given time. Rotations are expressed with quaternions."
double("mTime", "The time of this key")
aiQuaternion("mValue", "The value of this key")
}
val aiMeshKey = struct(Module.ASSIMP, "AIMeshKey", nativeName = "struct aiMeshKey") {
documentation = "Binds a anim mesh to a specific point in time."
double("mTime", "The time of this key")
unsigned_int(
"mValue",
"""
Index into the ##AIMesh{@code ::mAnimMeshes} array of the mesh coresponding to the ##AIMeshAnim hosting this key frame. The referenced anim mesh is
evaluated according to the rules defined in the docs for ##AIAnimMesh.
"""
)
}
val aiMeshMorphKey = struct(Module.ASSIMP, "AIMeshMorphKey", nativeName = "struct aiMeshMorphKey") {
documentation = "Binds a morph anim mesh to a specific point in time."
double("mTime", "the time of this key")
unsigned_int.p("mValues", "the values at the time of this key")
double.p("mWeights", "the weights at the time of this key")
AutoSize("mValues", "mWeights")..unsigned_int("mNumValuesAndWeights", "the number of values and weights")
}
val aiAnimBehaviour = "aiAnimBehaviour".enumType
val aiNodeAnim = struct(Module.ASSIMP, "AINodeAnim", nativeName = "struct aiNodeAnim") {
documentation =
"""
Describes the animation of a single node. The name specifies the bone/node which is affected by this animation channel. The keyframes are given in
three separate series of values, one each for position, rotation and scaling. The transformation matrix computed from these values replaces the node's
original transformation matrix at a specific time.
This means all keys are absolute and not relative to the bone default pose. The order in which the transformations are applied is - as usual - scaling,
rotation, translation.
<h5>Note:</h5>
All keys are returned in their correct, chronological order. Duplicate keys don't pass the validation step. Most likely there will be no negative time
values, but they are not forbidden also ( so implementations need to cope with them! )
"""
aiString("mNodeName", "The name of the node affected by this animation. The node must exist and it must be unique.")
AutoSize("mPositionKeys", optional = true)..unsigned_int("mNumPositionKeys", "The number of position keys")
aiVectorKey.p(
"mPositionKeys",
"""
The position keys of this animation channel. Positions are specified as 3D vector. The array is {@code mNumPositionKeys} in size. If there are position
keys, there will also be at least one scaling and one rotation key.
"""
)
AutoSize("mRotationKeys", optional = true)..unsigned_int("mNumRotationKeys", "The number of rotation keys")
aiQuatKey.p(
"mRotationKeys",
"""
The rotation keys of this animation channel. Rotations are given as quaternions, which are 4D vectors. The array is {@code mNumRotationKeys} in size.
If there are rotation keys, there will also be at least one scaling and one position key.
"""
)
AutoSize("mScalingKeys", optional = true)..unsigned_int("mNumScalingKeys", "The number of scaling keys")
aiVectorKey.p(
"mScalingKeys",
"""
The scaling keys of this animation channel. Scalings are specified as 3D vector. The array is {@code mNumScalingKeys} in size. If there are scaling
keys, there will also be at least one position and one rotation key.
"""
)
aiAnimBehaviour(
"mPreState",
"""
Defines how the animation behaves before the first key is encountered. The default value is aiAnimBehaviour_DEFAULT (the original transformation matrix
of the affected node is used).
"""
).links("AnimBehaviour_\\w+")
aiAnimBehaviour(
"mPostState",
"""
Defines how the animation behaves after the last key was processed. The default value is aiAnimBehaviour_DEFAULT (the original transformation matrix of
the affected node is taken).
"""
).links("AnimBehaviour_\\w+")
}
val aiMeshAnim = struct(Module.ASSIMP, "AIMeshAnim", nativeName = "struct aiMeshAnim") {
documentation =
"""
Describes vertex-based animations for a single mesh or a group of meshes. Meshes carry the animation data for each frame in their
##AIMesh{@code ::mAnimMeshes} array. The purpose of {@code aiMeshAnim} is to define keyframes linking each mesh attachment to a particular point in
time.
"""
aiString(
"mName",
"""
Name of the mesh to be animated. An empty string is not allowed, animated meshes need to be named (not necessarily uniquely, the name can basically
serve as wildcard to select a group of meshes with similar animation setup)
""")
AutoSize("mKeys")..unsigned_int("mNumKeys", "Size of the {@code mKeys} array. Must be 1, at least.")
aiMeshKey.p("mKeys", "Key frames of the animation. May not be #NULL.")
}
val aiMeshMorphAnim = struct(Module.ASSIMP, "AIMeshMorphAnim", nativeName = "struct aiMeshMorphAnim") {
documentation = "Describes a morphing animation of a given mesh."
aiString(
"mName",
"""
Name of the mesh to be animated. An empty string is not allowed, animated meshes need to be named (not necessarily uniquely, the name can basically
serve as wildcard to select a group of meshes with similar animation setup).
""")
AutoSize("mKeys")..unsigned_int("mNumKeys", "Size of the {@code mKeys} array. Must be 1, at least.")
aiMeshMorphKey.p("mKeys", "Key frames of the animation. May not be #NULL.")
}
val aiAnimation = struct(Module.ASSIMP, "AIAnimation", nativeName = "struct aiAnimation") {
documentation =
"""
An animation consists of keyframe data for a number of nodes. For each node affected by the animation a separate series of data is given.
"""
aiString(
"mName",
"""
The name of the animation. If the modeling package this data was exported from does support only a single animation channel, this name is usually empty
(length is zero).
"""
)
double("mDuration", "Duration of the animation in ticks.")
double("mTicksPerSecond", "Ticks per second. 0 if not specified in the imported file")
AutoSize("mChannels", optional = true)..unsigned_int("mNumChannels", "The number of bone animation channels. Each channel affects a single node.")
aiNodeAnim.p.p("mChannels", "The node animation channels. Each channel affects a single node. The array is {@code mNumChannels} in size.")
AutoSize("mMeshChannels", optional = true)..unsigned_int(
"mNumMeshChannels",
"The number of mesh animation channels. Each channel affects a single mesh and defines vertex-based animation."
)
aiMeshAnim.p.p("mMeshChannels", "The mesh animation channels. Each channel affects a single mesh. The array is {@code mNumMeshChannels} in size.")
AutoSize("mMorphMeshChannels", optional = true)..unsigned_int(
"mNumMorphMeshChannels",
"the number of mesh animation channels. Each channel affects a single mesh and defines morphing animation."
)
aiMeshMorphAnim.p.p(
"mMorphMeshChannels",
"the morph mesh animation channels. Each channel affects a single mesh. The array is {@code mNumMorphMeshChannels} in size."
)
}
val aiLightSourceType = "aiLightSourceType".enumType
val aiLight = struct(Module.ASSIMP, "AILight", nativeName = "struct aiLight", mutable = false) {
documentation =
"""
Helper structure to describe a light source.
Assimp supports multiple sorts of light sources, including directional, point and spot lights. All of them are defined with just a single structure and
distinguished by their parameters. Note - some file formats (such as 3DS, ASE) export a "target point" - the point a spot light is looking at (it can
even be animated). Assimp writes the target point as a sub-node of a spot-lights's main node, called "<spotName>.Target". However, this is just
additional information then, the transformation tracks of the main node make the spot light already point in the right direction.
"""
aiString(
"mName",
"""
The name of the light source. There must be a node in the scene-graph with the same name. This node specifies the position of the light in the scene
hierarchy and can be animated.
"""
)
aiLightSourceType(
"mType",
"The type of the light source. #LightSource_UNDEFINED is not a valid value for this member."
).links("LightSource_(?!UNDEFINED)\\w+")
aiVector3D(
"mPosition",
"""
Position of the light source in space. Relative to the transformation of the node corresponding to the light. The position is undefined for directional
lights.
"""
)
aiVector3D(
"mDirection",
"""
Direction of the light source in space. Relative to the transformation of the node corresponding to the light. The direction is undefined for point
lights. The vector may be normalized, but it needn't.
"""
)
aiVector3D(
"mUp",
"""
Up direction of the light source in space. Relative to the transformation of the node corresponding to the light. The direction is undefined for point
lights. The vector may be normalized, but it needn't.
"""
)
float(
"mAttenuationConstant",
"""
Constant light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is
{@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att0 variable in the equation. Naturally undefined for directional
lights.
"""
)
float(
"mAttenuationLinear",
"""
Linear light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is
{@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att1 variable in the equation. Naturally undefined for directional
lights.
"""
)
float(
"mAttenuationQuadratic",
"""
Quadratic light attenuation factor. The intensity of the light source at a given distance 'd' from the light's position is
{@code Atten = 1/( att0 + att1 * d + att2 * d*d)}. This member corresponds to the att2 variable in the equation. Naturally undefined for directional
lights.
"""
)
aiColor3D(
"mColorDiffuse",
"""
Diffuse color of the light source. The diffuse light color is multiplied with the diffuse material color to obtain the final color that contributes to
the diffuse shading term.
"""
)
aiColor3D(
"mColorSpecular",
"""
Specular color of the light source. The specular light color is multiplied with the specular material color to obtain the final color that contributes
to the specular shading term.
"""
)
aiColor3D(
"mColorAmbient",
"""
Ambient color of the light source. The ambient light color is multiplied with the ambient material color to obtain the final color that contributes to
the ambient shading term. Most renderers will ignore this value it, is just a remaining of the fixed-function pipeline that is still supported by quite
many file formats.
"""
)
float(
"mAngleInnerCone",
"""
Inner angle of a spot light's light cone. The spot light has maximum influence on objects inside this angle. The angle is given in radians. It is 2PI
for point lights and undefined for directional lights.
"""
)
float(
"mAngleOuterCone",
"""
Outer angle of a spot light's light cone. The spot light does not affect objects outside this angle. The angle is given in radians. It is 2PI for point
lights and undefined for directional lights. The outer angle must be greater than or equal to the inner angle. It is assumed that the application uses
a smooth interpolation between the inner and the outer cone of the spot light.
"""
)
aiVector2D("mSize", "Size of area light source.")
}
val aiCamera = struct(Module.ASSIMP, "AICamera", nativeName = "struct aiCamera") {
documentation =
"""
Helper structure to describe a virtual camera.
Cameras have a representation in the node graph and can be animated. An important aspect is that the camera itself is also part of the scenegraph. This
means, any values such as the look-at vector are not *absolute*, they're <b>relative</b> to the coordinate system defined by the node which corresponds
to the camera. This allows for camera animations. For static cameras parameters like the 'look-at' or 'up' vectors are usually specified directly in
{@code aiCamera}, but beware, they could also be encoded in the node transformation.
"""
aiString(
"mName",
"""
The name of the camera. There must be a node in the scenegraph with the same name. This node specifies the position of the camera in the scene
hierarchy and can be animated.
"""
)
aiVector3D("mPosition", "Position of the camera relative to the coordinate space defined by the corresponding node. The default value is 0|0|0.")
aiVector3D(
"mUp",
"""
'Up' - vector of the camera coordinate system relative to the coordinate space defined by the corresponding node. The 'right' vector of the camera
coordinate system is the cross product of the up and lookAt vectors. The default value is 0|1|0. The vector may be normalized, but it needn't.
"""
)
aiVector3D(
"mLookAt",
"""
'LookAt' - vector of the camera coordinate system relative to the coordinate space defined by the corresponding node. This is the viewing direction of
the user. The default value is {@code 0|0|1}. The vector may be normalized, but it needn't.
"""
)
float(
"mHorizontalFOV",
"""
Horizontal field of view angle, in radians. The field of view angle is the angle between the center line of the screen and the left or right border.
The default value is {@code 1/4PI}.
"""
)
float(
"mClipPlaneNear",
"""
Distance of the near clipping plane from the camera. The value may not be 0.f (for arithmetic reasons to prevent a division through zero). The default
value is 0.1f.
"""
)
float(
"mClipPlaneFar",
"""Distance of the far clipping plane from the camera. The far clipping plane must, of course, be further away than the near clipping plane. The
default value is 1000.f. The ratio between the near and the far plane should not be too large (between 1000-10000 should be ok) to avoid floating-point
inaccuracies which could lead to z-fighting.
"""
)
float(
"mAspect",
"""
Screen aspect ratio. This is the ration between the width and the height of the screen. Typical values are 4/3, 1/2 or 1/1. This value is 0 if the
aspect ratio is not defined in the source file. 0 is also the default value.
"""
)
float(
"mOrthographicWidth",
"""
Half horizontal orthographic width, in scene units.
The orthographic width specifies the half width of the orthographic view box. If non-zero the camera is orthographic and the {@code mAspect} should
define to the ratio between the orthographic width and height and {@code mHorizontalFOV} should be set to 0. The default value is 0 (not orthographic).
"""
)
}
val aiScene = struct(Module.ASSIMP, "AIScene", nativeName = "struct aiScene") {
documentation =
"""
The root structure of the imported data.
Everything that was imported from the given file can be accessed from here. Objects of this class are generally maintained and owned by Assimp, not by
the caller. You shouldn't want to instance it, nor should you ever try to delete a given scene on your own.
"""
unsigned_int(
"mFlags",
"""
Any combination of the AI_SCENE_FLAGS_XXX flags. By default this value is 0, no flags are set. Most applications will want to reject all scenes with
the AI_SCENE_FLAGS_INCOMPLETE bit set.
"""
).links("AI_SCENE_FLAGS_\\w+", LinkMode.BITFIELD)
nullable..aiNode.p(
"mRootNode",
"""
The root node of the hierarchy. There will always be at least the root node if the import was successful (and no special flags have been set). Presence
of further nodes depends on the format and content of the imported file.
"""
)
AutoSize("mMeshes", optional = true)..unsigned_int("mNumMeshes", "The number of meshes in the scene.")
aiMesh.p.p(
"mMeshes",
"""
The array of meshes. Use the indices given in the ##AINode structure to access this array. The array is {@code mNumMeshes} in size. If the
#AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always be at least ONE material.
"""
)
AutoSize("mMaterials", optional = true)..unsigned_int("mNumMaterials", "The number of materials in the scene.")
aiMaterial.p.p(
"mMaterials",
"""
The array of materials. Use the index given in each ##AIMesh structure to access this array. The array is {@code mNumMaterials} in size. If the
#AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always be at least ONE material.
"""
)
AutoSize("mAnimations", optional = true)..unsigned_int("mNumAnimations", "The number of animations in the scene.")
aiAnimation.p.p(
"mAnimations",
"The array of animations. All animations imported from the given file are listed here. The array is {@code mNumAnimations} in size."
)
AutoSize("mTextures", optional = true)..unsigned_int("mNumTextures", "The number of textures embedded into the file")
aiTexture.p.p(
"mTextures",
"""
The array of embedded textures. Not many file formats embed their textures into the file. An example is Quake's MDL format (which is also used by some
GameStudio versions)
"""
)
AutoSize("mLights", optional = true)..unsigned_int(
"mNumLights",
"The number of light sources in the scene. Light sources are fully optional, in most cases this attribute will be 0"
)
aiLight.p.p(
"mLights",
"The array of light sources. All light sources imported from the given file are listed here. The array is {@code mNumLights} in size."
)
AutoSize("mCameras", optional = true)..unsigned_int(
"mNumCameras",
"The number of cameras in the scene. Cameras are fully optional, in most cases this attribute will be 0"
)
aiCamera.p.p(
"mCameras",
"""
The array of cameras. All cameras imported from the given file are listed here. The array is {@code mNumCameras} in size. The first camera in the array
(if existing) is the default camera view into the scene.
"""
)
nullable..aiMetadata.p(
"mMetaData",
"""
The global metadata assigned to the scene itself.
This data contains global metadata which belongs to the scene like unit-conversions, versions, vendors or other model-specific data. This can be used
to store format-specific metadata as well.
"""
)
aiString("mName", "The name of the scene itself.")
unsigned_int("mNumSkeletons", "")
aiSkeleton.p.p("mSkeletons", "")
char.p("mPrivate", "Internal use only, do not touch!").private()
}
val aiReturn = "aiReturn".enumType
val aiTextureType = "aiTextureType".enumType
val aiTextureMapping = "aiTextureMapping".enumType
val aiTextureOp = "aiTextureOp".enumType
val aiTextureMapMode = "aiTextureMapMode".enumType
val aiImporterDesc = struct(Module.ASSIMP, "AIImporterDesc", nativeName = "struct aiImporterDesc") {
documentation =
"""
Meta information about a particular importer. Importers need to fill this structure, but they can freely decide how talkative they are. A common use
case for loader meta info is a user interface in which the user can choose between various import/export file formats. Building such an UI by hand
means a lot of maintenance as importers / exporters are added to Assimp, so it might be useful to have a common mechanism to query some rough importer
characteristics.
"""
charASCII.const.p("mName", "Full name of the importer (i.e. Blender3D importer)")
charUTF8.const.p("mAuthor", "Original author (left blank if unknown or whole assimp team)")
charUTF8.const.p("mMaintainer", "Current maintainer, left blank if the author maintains")
charUTF8.const.p("mComments", "Implementation comments, i.e. unimplemented features")
unsigned_int("mFlags", "These flags indicate some characteristics common to many importers.")
unsigned_int("mMinMajor", "Minimum major format that can be loaded in major.minor style.")
unsigned_int("mMinMinor", "Minimum minor format that can be loaded in major.minor style.")
unsigned_int("mMaxMajor", "Maximum major format that can be loaded in major.minor style.")
unsigned_int("mMaxMinor", "Maximum minor format that can be loaded in major.minor style.")
charASCII.const.p(
"mFileExtensions",
"""
List of file extensions this importer can handle. List entries are separated by space characters. All entries are lower case without a leading dot
(i.e. "xml dae" would be a valid value. Note that multiple importers may respond to the same file extension - assimp calls all importers in the order
in which they are registered and each importer gets the opportunity to load the file until one importer "claims" the file. Apart from file extension
checks, importers typically use other methods to quickly reject files (i.e. magic words) so this does not mean that common or generic file extensions
such as XML would be tediously slow.
"""
)
}
private val _aiFile = struct(Module.ASSIMP, "AIFile", nativeName = "struct aiFile")
private val _aiFileIO = struct(Module.ASSIMP, "AIFileIO", nativeName = "struct aiFileIO")
val aiFileWriteProc = Module.ASSIMP.callback {
size_t(
"AIFileWriteProc",
"File write procedure.",
_aiFile.p("pFile", "file pointer to write to"),
char.const.p("pBuffer", "the buffer to be written"),
size_t("memB", "size of the individual element to be written"),
size_t("count", "number of elements to be written"),
returnDoc = "the number of elements written",
nativeType = "aiFileWriteProc"
)
}
val aiFileReadProc = Module.ASSIMP.callback {
size_t(
"AIFileReadProc",
"File read procedure",
_aiFile.p("pFile", "file pointer to read from"),
char.p("pBuffer", "the buffer to read the values"),
size_t("size", "size in bytes of each element to be read"),
size_t("count", "number of elements to be read"),
returnDoc = "the number of elements read",
nativeType = "aiFileReadProc"
)
}
val aiFileTellProc = Module.ASSIMP.callback {
size_t(
"AIFileTellProc",
"File tell procedure.",
_aiFile.p("pFile", "file pointer to query"),
returnDoc = "the current file position",
nativeType = "aiFileTellProc"
)
}
val aiFileFlushProc = Module.ASSIMP.callback {
void(
"AIFileFlushProc",
"File flush procedure.",
_aiFile.p("pFile", "file pointer to flush"),
nativeType = "aiFileFlushProc"
)
}
val aiOrigin = "aiOrigin".enumType
val aiFileSeek = Module.ASSIMP.callback {
aiReturn(
"AIFileSeek",
"File seek procedure",
_aiFile.p("pFile", "file pointer to seek"),
size_t("offset", "number of bytes to shift from origin"),
aiOrigin("origin", "position used as reference for the offset"),
returnDoc = "an {@code aiReturn} value",
nativeType = "aiFileSeek"
)
}
val aiFileOpenProc = Module.ASSIMP.callback {
_aiFile.p(
"AIFileOpenProc",
"File open procedure",
_aiFileIO.p("pFileIO", "{@code FileIO} pointer"),
charUTF8.const.p("fileName", "name of the file to be opened"),
charUTF8.const.p("openMode", "mode in which to open the file"),
returnDoc = "pointer to an ##AIFile structure, or #NULL if the file could not be opened",
nativeType = "aiFileOpenProc",
)
}
val aiFileCloseProc = Module.ASSIMP.callback {
void(
"AIFileCloseProc",
"File close procedure",
_aiFileIO.p("pFileIO", "{@code FileIO} pointer"),
_aiFile.p("pFile", "file pointer to close"),
nativeType = "aiFileCloseProc"
)
}
val aiUserData = typedef(opaque_p, "aiUserData")
val aiFileIO = struct(Module.ASSIMP, "AIFileIO", nativeName = "struct aiFileIO") {
documentation =
"""
Provided are functions to open and close files. Supply a custom structure to the import function. If you don't, a default implementation is used. Use
custom file systems to enable reading from other sources, such as ZIPs or memory locations.
"""
aiFileOpenProc("OpenProc", "Function used to open a new file")
aiFileCloseProc("CloseProc", "Function used to close an existing file")
nullable..aiUserData("UserData", "User-defined, opaque data")
}
val aiFile = struct(Module.ASSIMP, "AIFile", nativeName = "struct aiFile") {
documentation = """
Actually, it's a data structure to wrap a set of fXXXX (e.g fopen) replacement functions.
The default implementation of the functions utilizes the fXXX functions from the CRT. However, you can supply a custom implementation to Assimp by
delivering a custom ##AIFileIO. Use this to enable reading from other sources, such as ZIP archives or memory locations.
"""
aiFileReadProc("ReadProc", "Callback to read from a file")
aiFileWriteProc("WriteProc", "Callback to write to a file")
aiFileTellProc("TellProc", "Callback to retrieve the current position of the file cursor (ftell())")
aiFileTellProc("FileSizeProc", "Callback to retrieve the size of the file, in bytes")
aiFileSeek("SeekProc", "Callback to set the current position of the file cursor (fseek())")
aiFileFlushProc("FlushProc", "Callback to flush the file contents")
nullable..aiUserData("UserData", "User-defined, opaque data")
}
val aiLogStreamCallback = Module.ASSIMP.callback {
void(
"AILogStreamCallback",
"Callback to be called for log stream messages",
charUTF8.const.p("message", "The message to be logged"),
Unsafe..nullable..char.p("user", "The user data from the log stream"),
nativeType = "aiLogStreamCallback"
)
}
val aiLogStream = struct(Module.ASSIMP, "AILogStream", nativeName = "struct aiLogStream") {
documentation = "Represents a log stream. A log stream receives all log messages and streams them somewhere"
aiLogStreamCallback("callback", "callback to be called")
nullable..char.p("user", "user data to be passed to the callback")
}
val aiPropertyStore = struct(Module.ASSIMP, "AIPropertyStore", nativeName = "struct aiPropertyStore") {
documentation = "Represents an opaque set of settings to be used during importing."
char("sentinel", "")
}
val aiBool = typedef(intb, "aiBool")
val aiDefaultLogStream = "aiDefaultLogStream".enumType
val aiExportFormatDesc = struct(Module.ASSIMP, "AIExportFormatDesc", nativeName = "struct aiExportFormatDesc") {
documentation = """
Describes an file format which Assimp can export to. Use #GetExportFormatCount() to learn how many export-formats are supported by the current
Assimp-build and #GetExportFormatDescription() to retrieve the description of the export format option.
"""
charUTF8.const.p(
"id",
"""
a short string ID to uniquely identify the export format. Use this ID string to specify which file format you want to export to when calling
#ExportScene(). Example: "dae" or "obj"
"""
)
charUTF8.const.p(
"description",
"A short description of the file format to present to users. Useful if you want to allow the user to select an export format."
)
charUTF8.const.p("fileExtension", "Recommended file extension for the exported file in lower case.")
}
private val _aiExportDataBlob = struct(Module.ASSIMP, "AIExportDataBlob", nativeName = "struct aiExportDataBlob")
val aiExportDataBlob = struct(Module.ASSIMP, "AIExportDataBlob", nativeName = "struct aiExportDataBlob") {
documentation = """
Describes a blob of exported scene data. Use #ExportSceneToBlob() to create a blob containing an exported scene. The memory referred by this structure
is owned by Assimp. to free its resources. Don't try to free the memory on your side - it will crash for most build configurations due to conflicting
heaps.
Blobs can be nested - each blob may reference another blob, which may in turn reference another blob and so on. This is used when exporters write more
than one output file for a given ##AIScene. See the remarks for {@code aiExportDataBlob::name} for more information.
"""
AutoSize("data")..size_t("size", "Size of the data in bytes")
void.p("data", "The data.")
aiString(
"name",
"""
Name of the blob. An empty string always indicates the first (and primary) blob, which contains the actual file data. Any other blobs are auxiliary
files produced by exporters (i.e. material files). Existence of such files depends on the file format. Most formats don't split assets across multiple
files.
If used, blob names usually contain the file extension that should be used when writing the data to disc.
The blob names generated can be influenced by setting the #AI_CONFIG_EXPORT_BLOB_NAME export property to the name that is used for the master blob. All
other names are typically derived from the base name, by the file format exporter.
"""
)
nullable.._aiExportDataBlob.p("next", "Pointer to the next blob in the chain or NULL if there is none.")
} | bsd-3-clause | 669346a8c81472f98c313ce108ee5975 | 45.955871 | 215 | 0.674063 | 4.300521 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/search/filter/TokenParamFilterCriterion.kt | 1 | 4091 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.search.filter
import ca.uhn.fhir.rest.gclient.TokenClientParam
import com.google.android.fhir.search.ConditionParam
import com.google.android.fhir.search.Operation
import com.google.android.fhir.search.SearchDslMarker
import org.hl7.fhir.r4.model.CodeType
import org.hl7.fhir.r4.model.CodeableConcept
import org.hl7.fhir.r4.model.Coding
import org.hl7.fhir.r4.model.ContactPoint
import org.hl7.fhir.r4.model.Identifier
import org.hl7.fhir.r4.model.UriType
/**
* Represents a criterion for filtering [TokenClientParam]. e.g. filter(Patient.GENDER, { value =
* of(CodeType("male")) })
*/
@SearchDslMarker
data class TokenParamFilterCriterion(var parameter: TokenClientParam) : FilterCriterion {
var value: TokenFilterValue? = null
/** Returns [TokenFilterValue] from [Boolean]. */
fun of(boolean: Boolean) =
TokenFilterValue().apply {
tokenFilters.add(TokenParamFilterValueInstance(code = boolean.toString()))
}
/** Returns [TokenFilterValue] from [String]. */
fun of(string: String) =
TokenFilterValue().apply { tokenFilters.add(TokenParamFilterValueInstance(code = string)) }
/** Returns [TokenFilterValue] from [UriType]. */
fun of(uriType: UriType) =
TokenFilterValue().apply {
tokenFilters.add(TokenParamFilterValueInstance(code = uriType.value))
}
/** Returns [TokenFilterValue] from [CodeType]. */
fun of(codeType: CodeType) =
TokenFilterValue().apply {
tokenFilters.add(TokenParamFilterValueInstance(code = codeType.value))
}
/** Returns [TokenFilterValue] from [Coding]. */
fun of(coding: Coding) =
TokenFilterValue().apply {
tokenFilters.add(TokenParamFilterValueInstance(uri = coding.system, code = coding.code))
}
/** Returns [TokenFilterValue] from [CodeableConcept]. */
fun of(codeableConcept: CodeableConcept) =
TokenFilterValue().apply {
codeableConcept.coding.forEach {
tokenFilters.add(TokenParamFilterValueInstance(uri = it.system, code = it.code))
}
}
/** Returns [TokenFilterValue] from [Identifier]. */
fun of(identifier: Identifier) =
TokenFilterValue().apply {
tokenFilters.add(
TokenParamFilterValueInstance(uri = identifier.system, code = identifier.value)
)
}
/** Returns [TokenFilterValue] from [ContactPoint]. */
fun of(contactPoint: ContactPoint) =
TokenFilterValue().apply {
tokenFilters.add(
TokenParamFilterValueInstance(uri = contactPoint.use?.toCode(), code = contactPoint.value)
)
}
override fun getConditionalParams() =
value!!.tokenFilters.map {
ConditionParam(
"index_value = ? ${ if (it.uri.isNullOrBlank()) "" else "AND IFNULL(index_system,'') = ?" }",
listOfNotNull(it.code, it.uri)
)
}
}
@SearchDslMarker
class TokenFilterValue internal constructor() {
internal val tokenFilters = mutableListOf<TokenParamFilterValueInstance>()
}
/**
* A structure like [CodeableConcept] may contain multiple [Coding] values each of which will be a
* filter value. We use [TokenParamFilterValueInstance] to represent individual filter value.
*/
@SearchDslMarker
internal data class TokenParamFilterValueInstance(var uri: String? = null, var code: String)
internal data class TokenParamFilterCriteria(
var parameter: TokenClientParam,
override val filters: List<TokenParamFilterCriterion>,
override val operation: Operation,
) : FilterCriteria(filters, operation, parameter, "TokenIndexEntity")
| apache-2.0 | 6eef2a3f02987e4da8192f56814c9da5 | 34.573913 | 101 | 0.727451 | 3.877725 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/ImageRecsFragment.kt | 1 | 24980 | package org.wikipedia.suggestededits
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.icu.text.ListFormatter
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.palette.graphics.Palette
import com.google.android.material.bottomsheet.BottomSheetBehavior
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil
import org.wikipedia.analytics.ImageRecommendationsFunnel
import org.wikipedia.analytics.eventplatform.ImageRecommendationsEvent
import org.wikipedia.auth.AccountUtil
import org.wikipedia.commons.FilePageActivity
import org.wikipedia.databinding.FragmentSuggestedEditsImageRecommendationItemBinding
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.SiteMatrix
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.dataclient.restbase.ImageRecommendationResponse
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider
import org.wikipedia.util.*
import org.wikipedia.util.log.L
import org.wikipedia.views.FaceAndColorDetectImageView
import org.wikipedia.views.ImageZoomHelper
import org.wikipedia.views.ViewAnimations
import java.util.*
class ImageRecsFragment : SuggestedEditsItemFragment(), ImageRecsDialog.Callback {
private var _binding: FragmentSuggestedEditsImageRecommendationItemBinding? = null
private val binding get() = _binding!!
private var publishing = false
private var publishSuccess = false
private var recommendation: ImageRecommendationResponse? = null
private var recommendationSequence = 0
private val funnel = ImageRecommendationsFunnel()
private var startMillis = 0L
private var buttonClickedMillis = 0L
private var infoClicked = false
private var detailsClicked = false
private var scrolled = false
private lateinit var bottomSheetBehavior: BottomSheetBehavior<CoordinatorLayout>
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentSuggestedEditsImageRecommendationItemBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
recommendationSequence = Prefs.getImageRecsItemSequence()
Prefs.setImageRecsItemSequence(recommendationSequence + 1)
binding.cardItemErrorView.backClickListener = OnClickListener { requireActivity().finish() }
binding.cardItemErrorView.retryClickListener = OnClickListener {
binding.cardItemProgressBar.visibility = VISIBLE
binding.cardItemErrorView.visibility = GONE
getNextItem()
}
binding.cardItemErrorView.nextClickListener = OnClickListener { callback().nextPage(this) }
val transparency = 0xd8000000
binding.publishOverlayContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff))
binding.publishOverlayContainer.visibility = GONE
binding.publishBackgroundView.alpha = if (WikipediaApp.getInstance().currentTheme.isDark) 0.3f else 0.1f
binding.imageCard.elevation = 0f
binding.imageCard.strokeColor = ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_border_color)
binding.imageCard.strokeWidth = DimenUtil.roundedDpToPx(0.5f)
binding.acceptButton.setOnClickListener {
buttonClickedMillis = SystemClock.uptimeMillis()
doPublish(ImageRecommendationsFunnel.RESPONSE_ACCEPT, emptyList())
}
binding.rejectButton.setOnClickListener {
buttonClickedMillis = SystemClock.uptimeMillis()
ImageRecsDialog.newInstance(ImageRecommendationsFunnel.RESPONSE_REJECT)
.show(childFragmentManager, null)
}
binding.notSureButton.setOnClickListener {
buttonClickedMillis = SystemClock.uptimeMillis()
ImageRecsDialog.newInstance(ImageRecommendationsFunnel.RESPONSE_NOT_SURE)
.show(childFragmentManager, null)
}
binding.imageCard.setOnClickListener {
recommendation?.let {
startActivity(FilePageActivity.newIntent(requireActivity(), PageTitle("File:" + it.image, WikiSite(Service.COMMONS_URL)), false, getSuggestionReason()))
detailsClicked = true
}
}
binding.imageCard.setOnLongClickListener {
if (ImageZoomHelper.isZooming) {
// Dispatch a fake CANCEL event to the container view, so that the long-press ripple is cancelled.
binding.imageCard.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0))
}
false
}
binding.articleContentContainer.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, _, _, _ ->
scrolled = true
})
binding.readMoreButton.setOnClickListener {
recommendation?.let {
val title = PageTitle(it.pageTitle, WikipediaApp.getInstance().wikiSite)
startActivity(PageActivity.newIntentForNewTab(requireActivity(), HistoryEntry(title, HistoryEntry.SOURCE_SUGGESTED_EDITS), title))
}
}
ImageZoomHelper.setViewZoomable(binding.imageView)
binding.dailyProgressView.setMaximum(DAILY_COUNT_TARGET)
bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomSheetCoordinatorLayout).apply {
state = BottomSheetBehavior.STATE_EXPANDED
}
getNextItem()
updateContents(null)
}
override fun onResume() {
super.onResume()
startMillis = SystemClock.uptimeMillis()
}
override fun onStart() {
super.onStart()
callback().updateActionButton()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun maybeShowTooltipSequence() {
binding.root.post {
if (!isResumed || !isAdded) {
return@post
}
if (Prefs.shouldShowImageRecsOnboarding()) {
Prefs.setShowImageRecsOnboarding(false)
val balloon = FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip1), autoDismiss = true, showDismissButton = true)
balloon.showAlignBottom(binding.articleTitlePlaceholder)
balloon.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip2), autoDismiss = true, showDismissButton = true), binding.instructionText)
.relayShowAlignBottom(FeedbackUtil.getTooltip(requireContext(), getString(R.string.image_recommendations_tooltip3), autoDismiss = true, showDismissButton = true), binding.acceptButton)
}
}
}
private fun getNextItem() {
if (recommendation != null) {
return
}
disposables.add(EditingSuggestionsProvider.getNextArticleWithMissingImage(WikipediaApp.getInstance().appOrSystemLanguageCode, recommendationSequence)
.subscribeOn(Schedulers.io())
.flatMap {
recommendation = it
ServiceFactory.get(WikipediaApp.getInstance().wikiSite).getInfoByPageId(recommendation!!.pageId.toString())
}
.flatMap {
recommendation!!.pageTitle = it.query()!!.firstPage()!!.displayTitle(WikipediaApp.getInstance().appOrSystemLanguageCode)
if (recommendation!!.pageTitle.isEmpty()) {
throw ThrowableUtil.EmptyException()
}
ServiceFactory.getRest(WikipediaApp.getInstance().wikiSite).getSummary(null, recommendation!!.pageTitle).subscribeOn(Schedulers.io())
}
.observeOn(AndroidSchedulers.mainThread())
.retry(10)
.subscribe({ summary ->
updateContents(summary)
}, { this.setErrorState(it) }))
}
private fun setErrorState(t: Throwable) {
L.e(t)
recommendation = null
binding.cardItemErrorView.setError(t)
binding.cardItemErrorView.visibility = VISIBLE
binding.cardItemProgressBar.visibility = GONE
binding.articleContentContainer.visibility = GONE
binding.imageSuggestionContainer.visibility = GONE
}
private fun updateContents(summary: PageSummary?) {
binding.cardItemErrorView.visibility = GONE
binding.articleContentContainer.visibility = if (recommendation != null) VISIBLE else GONE
binding.imageSuggestionContainer.visibility = GONE
binding.readMoreButton.visibility = GONE
binding.cardItemProgressBar.visibility = VISIBLE
if (recommendation == null || summary == null) {
return
}
disposables.add((if (siteInfoList == null)
ServiceFactory.get(WikiSite(Service.COMMONS_URL)).siteMatrix
.subscribeOn(Schedulers.io())
.map {
siteInfoList = SiteMatrix.getSites(it)
siteInfoList!!
}
else Observable.just(siteInfoList!!))
.flatMap {
ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo("File:" + recommendation!!.image, WikipediaApp.getInstance().appOrSystemLanguageCode)
.subscribeOn(Schedulers.io())
}
.observeOn(AndroidSchedulers.mainThread())
.retry(5)
.subscribe({ response ->
binding.cardItemProgressBar.visibility = GONE
val imageInfo = response.query()!!.firstPage()!!.imageInfo()!!
binding.articleTitle.text = StringUtil.fromHtml(summary.displayTitle)
binding.articleDescription.text = summary.description
binding.articleExtract.text = StringUtil.fromHtml(summary.extractHtml).trim()
binding.readMoreButton.visibility = VISIBLE
binding.imageView.loadImage(Uri.parse(ImageUrlUtil.getUrlForPreferredSize(imageInfo.thumbUrl, Constants.PREFERRED_CARD_THUMBNAIL_SIZE)),
roundedCorners = false, cropped = false, listener = object : FaceAndColorDetectImageView.OnImageLoadListener {
override fun onImageLoaded(palette: Palette, bmpWidth: Int, bmpHeight: Int) {
if (isAdded) {
var color1 = palette.getLightVibrantColor(ContextCompat.getColor(requireContext(), R.color.base70))
var color2 = palette.getLightMutedColor(ContextCompat.getColor(requireContext(), R.color.base30))
if (WikipediaApp.getInstance().currentTheme.isDark) {
color1 = ResourceUtil.darkenColor(color1)
color2 = ResourceUtil.darkenColor(color2)
}
val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, arrayOf(color1, color2).toIntArray())
binding.imageViewContainer.background = gradientDrawable
val params = binding.imageInfoButton.layoutParams as FrameLayout.LayoutParams
val containerAspect = binding.imageViewContainer.width.toFloat() / binding.imageViewContainer.height.toFloat()
val bmpAspect = bmpWidth.toFloat() / bmpHeight.toFloat()
if (bmpAspect > containerAspect) {
params.marginEnd = DimenUtil.roundedDpToPx(8f)
} else {
val width = binding.imageViewContainer.height.toFloat() * bmpAspect
params.marginEnd = DimenUtil.roundedDpToPx(8f) + (binding.imageViewContainer.width / 2 - width.toInt() / 2)
}
binding.imageInfoButton.layoutParams = params
}
}
override fun onImageFailed() {}
})
binding.imageCaptionText.text = if (imageInfo.metadata == null) null else StringUtil.removeHTMLTags(imageInfo.metadata!!.imageDescription())
binding.articleScrollSpacer.post {
if (isAdded) {
binding.articleScrollSpacer.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, bottomSheetBehavior.peekHeight)
// Collapse bottom sheet if the article title is not visible when loaded
binding.suggestedEditsItemRootView.doViewsOverlap(binding.articleTitle, binding.bottomSheetCoordinatorLayout).run {
if (this) {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
}
}
val arr = imageInfo.commonsUrl.split('/')
binding.imageFileNameText.text = StringUtil.removeUnderscores(UriUtil.decodeURL(arr[arr.size - 1]))
binding.imageSuggestionReason.text = StringUtil.fromHtml(getString(R.string.image_recommendations_task_suggestion_reason, getSuggestionReason()))
ViewAnimations.fadeIn(binding.imageSuggestionContainer)
maybeShowTooltipSequence()
}, { setErrorState(it) }))
callback().updateActionButton()
}
override fun publish() {
// the "Publish" button in our case is actually the "skip" button.
callback().nextPage(this)
}
override fun onDialogSubmit(response: Int, selectedItems: List<Int>) {
doPublish(response, selectedItems)
}
private fun doPublish(response: Int, reasons: List<Int>) {
if (publishing || publishSuccess || recommendation == null) {
return
}
// -- point of no return --
publishing = true
publishSuccess = false
binding.publishProgressCheck.visibility = GONE
binding.publishOverlayContainer.visibility = VISIBLE
binding.publishBoltView.visibility = GONE
binding.publishProgressBar.visibility = VISIBLE
funnel.logSubmit(WikipediaApp.getInstance().language().appLanguageCodes.joinToString(","),
recommendation!!.pageTitle, recommendation!!.image, getFunnelReason(), response, reasons, detailsClicked, infoClicked, scrolled,
buttonClickedMillis - startMillis, SystemClock.uptimeMillis() - startMillis,
if (Prefs.isImageRecsConsentEnabled() && AccountUtil.isLoggedIn) AccountUtil.userName else null,
Prefs.isImageRecsTeacherMode())
ImageRecommendationsEvent.logImageRecommendationInteraction(WikipediaApp.getInstance().language().appLanguageCodes.joinToString(","),
recommendation!!.pageTitle, recommendation!!.image, getFunnelReason(), response, reasons, detailsClicked, infoClicked, scrolled,
buttonClickedMillis - startMillis, SystemClock.uptimeMillis() - startMillis,
if (Prefs.isImageRecsConsentEnabled() && AccountUtil.isLoggedIn) AccountUtil.userName else null,
Prefs.isImageRecsTeacherMode())
publishSuccess = true
onSuccess()
}
private fun onSuccess() {
val pair = updateDailyCount(1)
val oldCount = pair.first
val newCount = pair.second
Prefs.setImageRecsItemSequenceSuccess(recommendationSequence + 1)
val waitUntilNextMillis = when (newCount) {
DAILY_COUNT_TARGET -> 2500L
else -> 1500L
}
val checkDelayMillis = 700L
val checkAnimationDuration = 300L
val progressText = when {
newCount < DAILY_COUNT_TARGET -> getString(R.string.suggested_edits_image_recommendations_task_goal_progress)
newCount == DAILY_COUNT_TARGET -> getString(R.string.suggested_edits_image_recommendations_task_goal_complete)
else -> getString(R.string.suggested_edits_image_recommendations_task_goal_surpassed)
}
binding.dailyProgressView.update(oldCount, oldCount, DAILY_COUNT_TARGET, getString(R.string.image_recommendations_task_processing))
showConfetti(newCount == DAILY_COUNT_TARGET)
updateNavBarColor(true)
var progressCount = 0
binding.publishProgressBar.post(object : Runnable {
override fun run() {
if (isAdded) {
if (binding.publishProgressBar.progress >= 100) {
binding.dailyProgressView.update(oldCount, newCount, DAILY_COUNT_TARGET, progressText)
binding.publishProgressCheck.alpha = 0f
binding.publishProgressCheck.visibility = VISIBLE
binding.publishProgressCheck.animate()
.alpha(1f)
.withEndAction {
if (newCount >= DAILY_COUNT_TARGET) {
binding.publishProgressCheck.postDelayed({
if (isAdded) {
binding.publishProgressBar.visibility = INVISIBLE
binding.publishProgressCheck.visibility = GONE
binding.publishBoltView.visibility = VISIBLE
}
}, checkDelayMillis)
}
binding.publishProgressBar.postDelayed({
if (isAdded) {
showConfetti(false)
updateNavBarColor(false)
binding.publishOverlayContainer.visibility = GONE
callback().nextPage(this@ImageRecsFragment)
callback().logSuccess()
}
}, waitUntilNextMillis + checkDelayMillis)
}
.duration = checkAnimationDuration
} else {
binding.publishProgressBar.progress = ++progressCount * 3
binding.publishProgressBar.post(this)
}
}
}
})
}
private fun showConfetti(enable: Boolean) {
binding.successConfettiImage.visibility = if (enable) VISIBLE else GONE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Change statusBar and actionBar color
requireActivity().window.statusBarColor = if (enable) ResourceUtil.getThemedColor(requireContext(),
R.attr.color_group_70) else Color.TRANSPARENT
(requireActivity() as AppCompatActivity).supportActionBar?.setBackgroundDrawable(if (enable)
ColorDrawable(ResourceUtil.getThemedColor(requireContext(), R.attr.color_group_70)) else null)
}
// Update actionbar menu items
requireActivity().window.decorView.findViewById<TextView>(R.id.menu_help).apply {
visibility = if (enable) GONE else VISIBLE
}
(requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(!enable)
}
private fun updateNavBarColor(enable: Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Change navigationBar color
requireActivity().window.navigationBarColor = if (enable) ResourceUtil.getThemedColor(requireContext(),
R.attr.color_group_69) else Color.TRANSPARENT
}
}
override fun publishEnabled(): Boolean {
return true
}
override fun publishOutlined(): Boolean {
return false
}
private fun getSuggestionReason(): String {
val hasWikidata = recommendation!!.foundOnWikis.contains("wd")
val langWikis = recommendation!!.foundOnWikis
.sortedBy { WikipediaApp.getInstance().language().getLanguageCodeIndex(it) }
.take(3)
.mapNotNull { getCanonicalName(it) }
if (langWikis.isNotEmpty()) {
return getString(R.string.image_recommendations_task_suggestion_reason_wikilist,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ListFormatter.getInstance().format(langWikis)
} else {
langWikis.joinToString(separator = ", ")
})
} else if (hasWikidata) {
return getString(R.string.image_recommendations_task_suggestion_reason_wikidata)
}
return getString(R.string.image_recommendations_task_suggestion_reason_commons)
}
private fun getFunnelReason(): String {
val hasWikidata = recommendation!!.foundOnWikis.contains("wd")
val langWikis = recommendation!!.foundOnWikis.filter { it != "wd" && it != "com" && it != "species" }
return when {
langWikis.isNotEmpty() -> {
"wikipedia"
}
hasWikidata -> {
"wikidata"
}
else -> "commons"
}
}
private fun getCanonicalName(code: String): String? {
var canonicalName = siteInfoList?.find { it.code() == code }?.localName()
if (canonicalName.isNullOrEmpty()) {
canonicalName = WikipediaApp.getInstance().language().getAppLanguageCanonicalName(code)
}
return canonicalName
}
private fun callback(): Callback {
return FragmentUtil.getCallback(this, Callback::class.java)!!
}
fun onInfoClicked() {
infoClicked = true
}
companion object {
private val SUPPORTED_LANGUAGES = arrayOf("ar", "arz", "bn", "cs", "de", "en", "es", "eu", "fa", "fr", "he", "hu", "hy", "it", "ko", "pl", "pt", "ru", "sr", "sv", "tr", "uk", "vi")
private var siteInfoList: List<SiteMatrix.SiteInfo>? = null
const val DAILY_COUNT_TARGET = 10
fun isFeatureEnabled(): Boolean {
return AccountUtil.isLoggedIn &&
SUPPORTED_LANGUAGES.any { it == WikipediaApp.getInstance().appOrSystemLanguageCode }
}
fun updateDailyCount(increaseCount: Int = 0): Pair<Int, Int> {
val day = Calendar.getInstance().get(Calendar.DAY_OF_YEAR)
var oldCount = Prefs.getImageRecsDailyCount()
if (day != Prefs.getImageRecsDayId()) {
// it's a brand new day!
Prefs.setImageRecsDayId(day)
oldCount = 0
}
val newCount = oldCount + increaseCount
Prefs.setImageRecsDailyCount(newCount)
return oldCount to newCount
}
fun newInstance(): SuggestedEditsItemFragment {
return ImageRecsFragment()
}
}
}
| apache-2.0 | c3d8c0bae11102dbc6ccdd782545752f | 46.580952 | 210 | 0.626261 | 5.636282 | false | false | false | false |
retomerz/intellij-community | platform/configuration-store-impl/src/StorageBaseEx.kt | 1 | 3082 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.impl.stores.StateStorageBase
import com.intellij.openapi.util.JDOMUtil
import org.jdom.Element
abstract class StorageBaseEx<T : Any> : StateStorageBase<T>() {
fun <S : Any> createGetSession(component: PersistentStateComponent<S>, componentName: String, stateClass: Class<S>, reload: Boolean = false) = StateGetter(component, componentName, getStorageData(reload), stateClass, this)
/**
* serializedState is null if state equals to default (see XmlSerializer.serializeIfNotDefault)
*/
abstract fun archiveState(storageData: T, componentName: String, serializedState: Element?)
}
class StateGetter<S : Any, T : Any>(private val component: PersistentStateComponent<S>,
private val componentName: String,
private val storageData: T,
private val stateClass: Class<S>,
private val storage: StorageBaseEx<T>) {
var serializedState: Element? = null
fun getState(mergeInto: S? = null): S? {
LOG.assertTrue(serializedState == null)
serializedState = storage.getSerializedState(storageData, component, componentName, false)
return storage.deserializeState(serializedState, stateClass, mergeInto)
}
fun close() {
if (serializedState == null) {
return
}
val stateAfterLoad: S?
try {
stateAfterLoad = component.state
}
catch (e: Throwable) {
LOG.error("Cannot get state after load", e)
stateAfterLoad = null
}
val serializedStateAfterLoad = if (stateAfterLoad == null) {
serializedState
}
else {
serializeState(stateAfterLoad)?.normalizeRootName().let {
if (JDOMUtil.isEmpty(it)) null else it
}
}
if (ApplicationManager.getApplication().isUnitTestMode &&
serializedState != serializedStateAfterLoad &&
(serializedStateAfterLoad == null || !JDOMUtil.areElementsEqual(serializedState, serializedStateAfterLoad))) {
LOG.warn("$componentName state changed after load. \nOld: ${JDOMUtil.writeElement(serializedState!!)}\n\nNew: ${serializedStateAfterLoad?.let { JDOMUtil.writeElement(it) } ?: "null"}\n")
}
storage.archiveState(storageData, componentName, serializedStateAfterLoad)
}
} | apache-2.0 | 6c339c0bdd51c3acf83269f19c66a871 | 38.525641 | 224 | 0.703439 | 4.756173 | false | false | false | false |
pkleimann/livingdoc2 | livingdoc-repository-file/src/main/kotlin/org/livingdoc/repositories/format/HtmlFormat.kt | 1 | 4923 | package org.livingdoc.repositories.format
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import org.livingdoc.repositories.DocumentFormat
import org.livingdoc.repositories.HtmlDocument
import org.livingdoc.repositories.ParseException
import org.livingdoc.repositories.model.decisiontable.DecisionTable
import org.livingdoc.repositories.model.decisiontable.Field
import org.livingdoc.repositories.model.decisiontable.Header
import org.livingdoc.repositories.model.decisiontable.Row
import org.livingdoc.repositories.model.scenario.Scenario
import org.livingdoc.repositories.model.scenario.Step
import java.io.InputStream
import java.nio.charset.Charset
class HtmlFormat : DocumentFormat {
private val supportedFileExtensions = setOf("html", "htm")
override fun canHandle(fileExtension: String): Boolean {
return supportedFileExtensions.contains(fileExtension.toLowerCase())
}
override fun parse(stream: InputStream): HtmlDocument {
val streamContent = stream.readBytes().toString(Charset.defaultCharset())
val document = Jsoup.parse(streamContent)
val elements = parseTables(document) + parseLists(document)
// TODO: provide elements in order they occur inside the original source document
return HtmlDocument(elements, document)
}
private fun parseTables(document: Document): List<DecisionTable> {
val tableElements = document.getElementsByTag("table")
return parseTableElements(tableElements)
}
private fun parseTableElements(tableElements: Elements): List<DecisionTable> {
fun tableHasAtLeastTwoRows(table: Element) = table.getElementsByTag("tr").size > 1
return tableElements
.filter(::tableHasAtLeastTwoRows)
.map(::parseTableToDecisionTable)
}
private fun parseTableToDecisionTable(table: Element): DecisionTable {
val tableRows = table.getElementsByTag("tr")
val headers = extractHeadersFromFirstRow(tableRows)
val dataRows = parseDataRow(headers, tableRows)
return DecisionTable(headers, dataRows)
}
private fun extractHeadersFromFirstRow(tableRows: Elements): List<Header> {
val firstRowContainingHeaders = tableRows[0]
val headers = firstRowContainingHeaders.children()
.filter(::isHeaderOrDataCell)
.map(Element::text)
.map(::Header).toList()
if (headers.size != headers.distinct().size) {
throw ParseException("Headers must contains only unique values: $headers")
}
return headers
}
private fun parseDataRow(headers: List<Header>, tableRows: Elements): List<Row> {
val dataRows = mutableListOf<Row>()
tableRows.drop(1).forEachIndexed { rowIndex, row ->
val dataCells = row.children().filter(::isHeaderOrDataCell)
if (headers.size != dataCells.size) {
throw ParseException(
"Header count must match the data cell count in data row ${rowIndex + 1}. Headers: ${headers.map(
Header::name
)}, DataCells: $dataCells"
)
}
val rowData = headers.mapIndexed { headerIndex, headerName ->
headerName to Field(dataCells[headerIndex].text())
}.toMap()
dataRows.add(Row(rowData))
}
return dataRows
}
private fun isHeaderOrDataCell(it: Element) = it.tagName() == "th" || it.tagName() == "td"
private fun parseLists(document: Document): List<Scenario> {
val unorderedListElements = document.getElementsByTag("ul")
val orderedListElements = document.getElementsByTag("ol")
return parseListElements(unorderedListElements) + parseListElements(orderedListElements)
}
private fun parseListElements(htmlListElements: Elements): List<Scenario> {
fun listHasAtLeastTwoItems(htmlList: Element) = htmlList.getElementsByTag("li").size > 1
return htmlListElements
.filter(::listHasAtLeastTwoItems)
.map(::parseListIntoScenario)
}
private fun parseListIntoScenario(htmlList: Element): Scenario {
verifyZeroNestedLists(htmlList)
val listItemElements = htmlList.getElementsByTag("li")
return Scenario(parseListItems(listItemElements))
}
private fun parseListItems(listItemElements: Elements): List<Step> {
return listItemElements.map { Step(it.text()) }.toList()
}
private fun verifyZeroNestedLists(htmlList: Element) {
val innerHtml = htmlList.html()
if (innerHtml.contains("<ul") || innerHtml.contains("<ol")) {
throw ParseException("Nested lists within unordered or ordered lists are not supported: ${htmlList.html()}")
}
}
}
| apache-2.0 | 8fc618375c3f124ad5b3917a4f716e77 | 39.02439 | 121 | 0.683933 | 4.788911 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/folding.kt | 1 | 1883 | package me.serce.solidity.ide
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilder
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbAware
import me.serce.solidity.lang.core.SolidityTokenTypes
import java.util.*
class SolidityFoldingBuilder : FoldingBuilder, DumbAware {
override fun buildFoldRegions(node: ASTNode, document: Document): Array<FoldingDescriptor> {
val descriptors = ArrayList<FoldingDescriptor>()
collectDescriptorsRecursively(node, document, descriptors)
return descriptors.toTypedArray()
}
override fun getPlaceholderText(node: ASTNode): String? {
val type = node.elementType
return when (type) {
SolidityTokenTypes.BLOCK -> "{...}"
SolidityTokenTypes.COMMENT -> "/*...*/"
SolidityTokenTypes.CONTRACT_DEFINITION -> "${node.text.substringBefore("{")} {...} "
else -> "..."
}
}
override fun isCollapsedByDefault(node: ASTNode): Boolean {
return false
}
companion object {
private fun collectDescriptorsRecursively(
node: ASTNode,
document: Document,
descriptors: MutableList<FoldingDescriptor>
) {
val type = node.elementType
if (
type === SolidityTokenTypes.BLOCK && spanMultipleLines(node, document) ||
type === SolidityTokenTypes.COMMENT ||
type === SolidityTokenTypes.CONTRACT_DEFINITION) {
descriptors.add(FoldingDescriptor(node, node.textRange))
}
for (child in node.getChildren(null)) {
collectDescriptorsRecursively(child, document, descriptors)
}
}
private fun spanMultipleLines(node: ASTNode, document: Document): Boolean {
val range = node.textRange
return document.getLineNumber(range.startOffset) < document.getLineNumber(range.endOffset)
}
}
}
| mit | c7f1e076611edd04f03aed1628ef29d6 | 32.035088 | 96 | 0.710568 | 4.767089 | false | false | false | false |
tommyli/nem12-manager | fenergy-service/src/main/kotlin/co/firefire/fenergy/shared/domain/LoginNmi.kt | 1 | 2377 | // Tommy Li ([email protected]), 2017-07-03
package co.firefire.fenergy.shared.domain
import co.firefire.fenergy.nem12.domain.NmiMeterRegister
import org.hibernate.annotations.GenericGenerator
import org.hibernate.annotations.Parameter
import java.util.*
import javax.persistence.CascadeType
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.OneToMany
import javax.persistence.OrderBy
@Entity
data class LoginNmi(
@ManyToOne(optional = false)
@JoinColumn(name = "login", referencedColumnName = "id", nullable = false)
var login: Login = Login(),
var nmi: String = ""
) : Comparable<LoginNmi> {
@Id
@GenericGenerator(
name = "LoginNmiIdSeq",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = arrayOf(
Parameter(name = "sequence_name", value = "login_nmi_id_seq"),
Parameter(name = "initial_value", value = "1000"),
Parameter(name = "increment_size", value = "1")
)
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "LoginNmiIdSeq")
var id: Long? = null
var label: String? = null
@OneToMany(mappedBy = "loginNmi", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true)
@OrderBy("meterSerial, registerId, nmiSuffix")
var nmiMeterRegisters: SortedSet<NmiMeterRegister> = TreeSet()
fun addNmiMeterRegister(nmiMeterRegister: NmiMeterRegister) {
nmiMeterRegister.loginNmi = this
nmiMeterRegisters.add(nmiMeterRegister)
}
fun mergeNmiMeterRegister(nmr: NmiMeterRegister) {
val existing: NmiMeterRegister? = nmiMeterRegisters.find { it.loginNmi == nmr.loginNmi && it.meterSerial == nmr.meterSerial && it.registerId == nmr.registerId && it.nmiSuffix == nmr.nmiSuffix }
if (existing == null) {
addNmiMeterRegister(nmr)
} else {
existing.mergeIntervalDays(nmr.intervalDays.values)
}
}
override fun compareTo(other: LoginNmi) = compareValuesBy(this, other, { it.login }, { it.nmi })
override fun toString() = "LoginNmi(login=$login, nmi='$nmi', id=$id, label=$label)"
}
| apache-2.0 | a77e906c8b8799565afdcb7c84e6666d | 34.477612 | 201 | 0.684897 | 4.148342 | false | false | false | false |
android/location-samples | SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/data/db/SleepDatabase.kt | 2 | 1997 | /*
* Copyright (C) 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 com.android.example.sleepsamplekotlin.data.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
private const val DATABASE_NAME = "sleep_segments_database"
/**
* Stores all sleep segment data.
*/
@Database(
entities = [SleepSegmentEventEntity::class, SleepClassifyEventEntity::class],
version = 3,
exportSchema = false
)
abstract class SleepDatabase : RoomDatabase() {
abstract fun sleepSegmentEventDao(): SleepSegmentEventDao
abstract fun sleepClassifyEventDao(): SleepClassifyEventDao
companion object {
// For Singleton instantiation
@Volatile
private var INSTANCE: SleepDatabase? = null
fun getDatabase(context: Context): SleepDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context,
SleepDatabase::class.java,
DATABASE_NAME
)
// Wipes and rebuilds instead of migrating if no Migration object.
// Migration is not part of this sample.
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
// return instance
instance
}
}
}
}
| apache-2.0 | 61dabf76a0ef7e3820deb1047a84acec | 32.283333 | 86 | 0.652479 | 5.030227 | false | false | false | false |
SpectraLogic/ds3_java_browser | dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/factories/PutJobFactory.kt | 1 | 3208 | /*
* ***************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.dsbrowser.gui.services.jobService.factories
import com.spectralogic.ds3client.Ds3Client
import com.spectralogic.dsbrowser.api.services.logging.LoggingService
import com.spectralogic.dsbrowser.gui.DeepStorageBrowserPresenter
import com.spectralogic.dsbrowser.gui.services.JobWorkers
import com.spectralogic.dsbrowser.gui.services.Workers
import com.spectralogic.dsbrowser.gui.services.jobService.JobTask
import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement
import com.spectralogic.dsbrowser.gui.services.jobService.PutJob
import com.spectralogic.dsbrowser.gui.services.jobService.data.PutJobData
import com.spectralogic.dsbrowser.gui.services.jobinterruption.JobInterruptionStore
import com.spectralogic.dsbrowser.gui.services.sessionStore.Session
import com.spectralogic.dsbrowser.gui.util.treeItem.SafeHandler
import com.spectralogic.dsbrowser.util.andThen
import org.slf4j.LoggerFactory
import java.nio.file.Path
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PutJobFactory @Inject constructor(
private val loggingService: LoggingService,
private val jobInterruptionStore: JobInterruptionStore,
private val deepStorageBrowserPresenter: DeepStorageBrowserPresenter,
private val jobWorkers: JobWorkers,
private val workers: Workers,
private val jobTaskElementFactory: JobTaskElement.JobTaskElementFactory
) {
private companion object {
private val LOG = LoggerFactory.getLogger(PutJobFactory::class.java)
private const val TYPE: String = "Put"
}
fun create(session: Session, files: List<Pair<String, Path>>, bucket: String, targetDir: String, client: Ds3Client, refreshBehavior: () -> Unit = {}) {
PutJobData(files, targetDir, bucket, jobTaskElementFactory.create(client))
.let { PutJob(it) }
.let { JobTask(it, session.sessionName) }
.apply {
onSucceeded = SafeHandler.logHandle(onSucceeded(TYPE, LOG).andThen(refreshBehavior))
onFailed = SafeHandler.logHandle(onFailed(client, jobInterruptionStore, deepStorageBrowserPresenter, loggingService, workers, TYPE).andThen(refreshBehavior))
onCancelled = SafeHandler.logHandle(onCancelled(client, loggingService, jobInterruptionStore, deepStorageBrowserPresenter).andThen(refreshBehavior))
}
.also { jobWorkers.execute(it) }
}
} | apache-2.0 | c1ccbb2b87af0ef58497a3f6629bffdd | 51.606557 | 177 | 0.726309 | 4.656023 | false | false | false | false |
MGaetan89/ShowsRage | app/src/test/kotlin/com/mgaetan89/showsrage/network/SickRageApi_GetPosterUrlTest.kt | 1 | 10095 | package com.mgaetan89.showsrage.network
import android.content.SharedPreferences
import com.mgaetan89.showsrage.extension.getApiKey
import com.mgaetan89.showsrage.extension.getPortNumber
import com.mgaetan89.showsrage.extension.getServerAddress
import com.mgaetan89.showsrage.extension.getServerPath
import com.mgaetan89.showsrage.extension.useHttps
import com.mgaetan89.showsrage.model.ImageType
import com.mgaetan89.showsrage.model.Indexer
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
@RunWith(Parameterized::class)
class SickRageApi_GetPosterUrlTest(
val useHttps: Boolean, val address: String, val port: String, val path: String,
val apiKey: String, val indexerId: Int, val indexer: Indexer?, val url: String
) {
@Before
fun before() {
val preferences = mock(SharedPreferences::class.java)
`when`(preferences.useHttps()).thenReturn(this.useHttps)
`when`(preferences.getServerAddress()).thenReturn(this.address)
`when`(preferences.getPortNumber()).thenReturn(this.port)
`when`(preferences.getServerPath()).thenReturn(this.path)
`when`(preferences.getApiKey()).thenReturn(this.apiKey)
SickRageApi.instance.init(preferences)
}
@Test
fun getPosterUrl() {
assertThat(SickRageApi.instance.getImageUrl(ImageType.POSTER, this.indexerId, this.indexer)).isEqualTo(this.url)
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "[{6}] {index} - {0}://{1}:{2}/{3}/{4}/")
fun data(): Collection<Array<Any?>> {
return listOf(
arrayOf(false, "", "", "", "", 0, null, "http://127.0.0.1/?cmd=show.getposter"),
arrayOf(false, "127.0.0.1", "", "", "", 123, null, "http://127.0.0.1/?cmd=show.getposter"),
arrayOf(true, "", "", "", "", 0, null, "http://127.0.0.1/?cmd=show.getposter"),
arrayOf(true, "127.0.0.1", "", "", "", 123, null, "https://127.0.0.1/?cmd=show.getposter"),
// TVDB
arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVDB, "http://127.0.0.1:8083/?cmd=show.getposter&tvdbid=0"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVDB, "https://127.0.0.1:8083/?cmd=show.getposter&tvdbid=0"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvdbid=123"),
// TVRage
arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVRAGE, "http://127.0.0.1:8083/?cmd=show.getposter&tvrageid=0"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVRAGE, "https://127.0.0.1:8083/?cmd=show.getposter&tvrageid=0"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvrageid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvrageid=123"),
// TVMaze
arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVMAZE, "http://127.0.0.1:8083/?cmd=show.getposter&tvmazeid=0"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVMAZE, "https://127.0.0.1:8083/?cmd=show.getposter&tvmazeid=0"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvmazeid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvmazeid=123"),
// TMDB
arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TMDB, "http://127.0.0.1:8083/?cmd=show.getposter&tmdbid=0"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TMDB, "https://127.0.0.1:8083/?cmd=show.getposter&tmdbid=0"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tmdbid=123"),
arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tmdbid=123")
)
}
}
}
| apache-2.0 | 6c5d2926d5f42b9b43386d8fda5a7147 | 85.282051 | 155 | 0.636057 | 2.482784 | false | false | false | false |
taumechanica/ml | src/main/kotlin/ml/strong/EncodingForest.kt | 1 | 1160 | // Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package taumechanica.ml.strong
import taumechanica.ml.data.DataFrame
import taumechanica.ml.meta.RandomTree
class EncodingForest {
val encoders: Array<RandomTree>
constructor(
frame: DataFrame,
complexity: Int,
extract: () -> IntArray?,
size: Int = 0
) {
encoders = if (size > 0) {
val indices = IntArray(frame.features.size, { it })
Array<RandomTree>(size, { RandomTree(frame, indices, complexity) })
} else {
var trees = mutableListOf<RandomTree>()
var indices = extract()
while (indices != null) {
trees.add(RandomTree(frame, indices, complexity))
indices = extract()
}
trees.toTypedArray()
}
}
fun encode(values: DoubleArray, targetIndex: Int) = DoubleArray(
encoders.size + 1, {
if (it < encoders.size) {
encoders[it].encode(values)
} else {
values[targetIndex]
}
}
)
}
| mit | af43465c6d216573be29bf20b31d0562 | 27.292683 | 79 | 0.550862 | 4.344569 | false | false | false | false |
auricgoldfinger/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/specialdates/home/HomeNavigator.kt | 3 | 5126 | package com.alexstyl.specialdates.home
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import com.alexstyl.specialdates.CrashAndErrorTracker
import com.alexstyl.specialdates.ShareAppIntentCreator
import com.alexstyl.specialdates.Strings
import com.alexstyl.specialdates.addevent.AddEventActivity
import com.alexstyl.specialdates.analytics.Analytics
import com.alexstyl.specialdates.analytics.Screen
import com.alexstyl.specialdates.contact.Contact
import com.alexstyl.specialdates.date.Date
import com.alexstyl.specialdates.donate.DonateActivity
import com.alexstyl.specialdates.events.namedays.activity.NamedaysOnADayActivity
import com.alexstyl.specialdates.facebook.FacebookProfileActivity
import com.alexstyl.specialdates.facebook.FacebookUserSettings
import com.alexstyl.specialdates.facebook.login.FacebookLogInActivity
import com.alexstyl.specialdates.permissions.ContactPermissionActivity
import com.alexstyl.specialdates.person.PersonActivity
import com.alexstyl.specialdates.search.SearchActivity
import com.alexstyl.specialdates.theming.AttributeExtractor
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.novoda.simplechromecustomtabs.SimpleChromeCustomTabs
class HomeNavigator(private val analytics: Analytics,
private val strings: Strings,
private val facebookUserSettings: FacebookUserSettings,
private val tracker: CrashAndErrorTracker,
private val attributeExtractor: AttributeExtractor) {
fun toDonate(activity: Activity) {
if (hasPlayStoreInstalled(activity)) {
val intent = DonateActivity.createIntent(activity)
activity.startActivity(intent)
} else {
SimpleChromeCustomTabs.getInstance()
.withFallback { navigateToDonateWebsite(activity) }
.withIntentCustomizer { simpleChromeCustomTabsIntentBuilder ->
val toolbarColor = attributeExtractor.extractPrimaryColorFrom(activity)
simpleChromeCustomTabsIntentBuilder.withToolbarColor(toolbarColor)
}
.navigateTo(SUPPORT_URL, activity)
}
analytics.trackScreen(Screen.DONATE)
}
private fun hasPlayStoreInstalled(activity: Activity): Boolean {
val googleApiAvailability = GoogleApiAvailability.getInstance()
val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(activity)
return resultCode == ConnectionResult.SUCCESS
}
private fun navigateToDonateWebsite(activity: Activity) {
try {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = SUPPORT_URL
activity.startActivity(intent)
} catch (e: ActivityNotFoundException) {
tracker.track(e)
}
}
fun toAddEvent(activity: Activity, code: Int) {
val intent = Intent(activity, AddEventActivity::class.java)
activity.startActivityForResult(intent, code)
}
fun toFacebookImport(activity: Activity) {
if (facebookUserSettings.isLoggedIn) {
val intent = Intent(activity, FacebookProfileActivity::class.java)
activity.startActivity(intent)
} else {
val intent = Intent(activity, FacebookLogInActivity::class.java)
activity.startActivity(intent)
}
}
fun toSearch(activity: Activity) {
val intent = Intent(activity, SearchActivity::class.java)
activity.startActivity(intent)
analytics.trackScreen(Screen.SEARCH)
}
fun toDateDetails(dateSelected: Date, activity: Activity) {
val intent = NamedaysOnADayActivity.getStartIntent(activity, dateSelected)
activity.startActivity(intent)
analytics.trackScreen(Screen.DATE_DETAILS)
}
fun toAppInvite(activity: Activity) {
val intent = ShareAppIntentCreator(strings).buildIntent()
val shareTitle = strings.inviteFriend()
activity.startActivity(Intent.createChooser(intent, shareTitle))
analytics.trackAppInviteRequested()
}
fun toGithubPage(activity: Activity) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://github.com/alexstyl/Memento-Calendar")
analytics.trackVisitGithub()
activity.startActivity(intent)
}
fun toContactDetails(contact: Contact, activity: Activity) {
val intent = PersonActivity.buildIntentFor(activity, contact)
activity.startActivity(intent)
analytics.trackContactDetailsViewed(contact)
}
fun toContactPermission(activity: Activity, requestCode: Int) {
val intent = Intent(activity, ContactPermissionActivity::class.java)
activity.startActivityForResult(intent, requestCode)
analytics.trackScreen(Screen.CONTACT_PERMISSION_REQUESTED)
}
companion object {
private val SUPPORT_URL = Uri.parse("https://g3mge.app.goo.gl/jdF1")
}
}
| mit | 88a4c14e4594cd5d36917aeecf2c4717 | 40.674797 | 95 | 0.722981 | 5.005859 | false | false | false | false |
kohry/gorakgarakANPR | app/src/main/java/com/gorakgarak/anpr/ml/NeuralNetwork.kt | 1 | 2611 | package com.gorakgarak.anpr.ml
import android.content.Context
import com.gorakgarak.anpr.R
import com.gorakgarak.anpr.parser.GorakgarakXMLParser
import org.opencv.core.Core
import org.opencv.core.CvType.CV_32FC1
import org.opencv.core.CvType.CV_32SC1
import org.opencv.core.Mat
import org.opencv.core.Scalar
import org.opencv.ml.ANN_MLP
import org.opencv.ml.Ml.ROW_SAMPLE
import java.io.FileInputStream
/**
* Created by kohry on 2017-10-15.
*/
object NeuralNetwork {
val CHAR_COUNT = 30
val LAYER_COUNT = 10
val strCharacters = arrayOf('0','1','2','3','4','5','6','7','8','9','B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z')
val ann: ANN_MLP = ANN_MLP.create()
private fun readXML(context: Context): Pair<Mat, Mat> {
// val inputStream = context.assets.open(fileName)
// val fs = opencv_core.FileStorage()
// fs.open(fileName,opencv_core.FileStorage.READ)
//
// val train = Mat(fs["TrainingDataF15"].mat().address())
// val classes = Mat(fs["classes"].mat().address())
return GorakgarakXMLParser.parse(context.resources.openRawResource(R.raw.ann),"TrainingDataF15")
}
fun train(context: Context) {
if (ann.isTrained) return
val data = readXML(context)
val trainData = data.first
val classes = data.second
val layerSizes = Mat(1,3,CV_32SC1)
val r = trainData.rows()
val c = trainData.cols()
layerSizes.put(0, 0, intArrayOf(trainData.cols()))
layerSizes.put(0, 1, intArrayOf(LAYER_COUNT))
layerSizes.put(0, 2, intArrayOf(CHAR_COUNT))
ann.layerSizes = layerSizes
ann.setActivationFunction(ANN_MLP.SIGMOID_SYM)
val trainClasses = Mat()
trainClasses.create(trainData.rows(), CHAR_COUNT, CV_32FC1)
(0 until trainClasses.rows()).forEach { row ->
(0 until trainClasses.cols()).forEach { col ->
if (col == classes.get(row, 0).get(0).toInt()) trainClasses.put(row, col, floatArrayOf(1f))
else trainClasses.put(col, row, floatArrayOf(0f))
}
}
//this part has changed from opencv 2 -> 3. ann class does not need weights anymore.
// val weights = Mat(1, trainData.rows(), CV_32FC1, Scalar.all(1.0))
ann.train(trainData, ROW_SAMPLE, trainClasses)
}
fun classify(f: Mat): Double {
val result = -1
val output = Mat(1, CHAR_COUNT, CV_32FC1)
ann.predict(f)
val minMaxLoc = Core.minMaxLoc(output)
return minMaxLoc.maxLoc.x
}
} | mit | 4a8d276082c7a9e39bfd1056a7f82209 | 30.46988 | 171 | 0.619686 | 3.219482 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/SENewUIHeaderView.kt | 1 | 1863 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions.searcheverywhere
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import java.util.function.Function
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.border.EmptyBorder
internal class SENewUIHeaderView(tabs: List<SearchEverywhereHeader.SETab>, shortcutSupplier: Function<in String?, String?>,
toolbar: JComponent) {
lateinit var tabbedPane: JBTabbedPane
@JvmField
val panel: DialogPanel
init {
panel = panel {
row {
tabbedPane = tabbedPaneHeader()
.customize(Gaps.EMPTY)
.applyToComponent {
font = JBFont.regular()
background = JBUI.CurrentTheme.ComplexPopup.HEADER_BACKGROUND
isFocusable = false
}
.component
toolbar.putClientProperty(ActionToolbarImpl.USE_BASELINE_KEY, true)
cell(toolbar)
.resizableColumn()
.align(AlignX.RIGHT)
}
}
val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets()
@Suppress("UseDPIAwareBorders")
panel.border = JBUI.Borders.compound(
JBUI.Borders.customLineBottom(JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground()),
EmptyBorder(0, headerInsets.left, 0, headerInsets.right))
for (tab in tabs) {
val shortcut = shortcutSupplier.apply(tab.id)
tabbedPane.addTab(tab.name, null, JPanel(), shortcut)
}
}
}
| apache-2.0 | bdb785ebde40ad56cd5c8a7873e337f7 | 33.5 | 123 | 0.713366 | 4.373239 | false | false | false | false |
Leifzhang/AndroidRouter | kspCompiler/src/main/java/com/kronos/ksp/compiler/KotlinPoetExe.kt | 1 | 5016 | package com.kronos.ksp.compiler
import com.google.devtools.ksp.isLocal
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.Variance.CONTRAVARIANT
import com.google.devtools.ksp.symbol.Variance.COVARIANT
import com.google.devtools.ksp.symbol.Variance.INVARIANT
import com.google.devtools.ksp.symbol.Variance.STAR
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets.UTF_8
import com.squareup.kotlinpoet.STAR as KpStar
/**
*
* @Author LiABao
* @Since 2021/3/8
*
*/
internal fun KSType.toClassName(): ClassName {
val decl = declaration
check(decl is KSClassDeclaration)
return decl.toClassName()
}
internal fun KSType.toTypeName(typeParamResolver: TypeParameterResolver): TypeName {
val type = when (val decl = declaration) {
is KSClassDeclaration -> decl.toTypeName(arguments.map { it.toTypeName(typeParamResolver) })
is KSTypeParameter -> typeParamResolver[decl.name.getShortName()]
is KSTypeAlias -> decl.type.resolve().toTypeName(typeParamResolver)
else -> error("Unsupported type: $declaration")
}
return type.copy(nullable = isMarkedNullable)
}
internal fun KSClassDeclaration.toTypeName(argumentList: List<TypeName> = emptyList()): TypeName {
val className = toClassName()
return if (argumentList.isNotEmpty()) {
className.parameterizedBy(argumentList)
} else {
className
}
}
internal interface TypeParameterResolver {
val parametersMap: Map<String, TypeVariableName>
operator fun get(index: String): TypeVariableName
}
internal fun List<KSTypeParameter>.toTypeParameterResolver(
fallback: TypeParameterResolver? = null,
sourceType: String? = null,
): TypeParameterResolver {
val parametersMap = LinkedHashMap<String, TypeVariableName>()
val typeParamResolver = { id: String ->
parametersMap[id]
?: fallback?.get(id)
?: throw IllegalStateException("No type argument found for $id! Anaylzing $sourceType")
}
val resolver = object : TypeParameterResolver {
override val parametersMap: Map<String, TypeVariableName> = parametersMap
override operator fun get(index: String): TypeVariableName = typeParamResolver(index)
}
// Fill the parametersMap. Need to do sequentially and allow for referencing previously defined params
for (typeVar in this) {
// Put the simple typevar in first, then it can be referenced in the full toTypeVariable()
// replacement later that may add bounds referencing this.
val id = typeVar.name.getShortName()
parametersMap[id] = TypeVariableName(id)
// Now replace it with the full version.
parametersMap[id] = typeVar.toTypeVariableName(resolver)
}
return resolver
}
internal fun KSClassDeclaration.toClassName(): ClassName {
require(!isLocal()) {
"Local/anonymous classes are not supported!"
}
val pkgName = packageName.asString()
val typesString = qualifiedName!!.asString().removePrefix("$pkgName.")
val simpleNames = typesString
.split(".")
return ClassName(pkgName, simpleNames)
}
internal fun KSTypeParameter.toTypeName(typeParamResolver: TypeParameterResolver): TypeName {
if (variance == STAR) return KpStar
return toTypeVariableName(typeParamResolver)
}
internal fun KSTypeParameter.toTypeVariableName(
typeParamResolver: TypeParameterResolver,
): TypeVariableName {
val typeVarName = name.getShortName()
val typeVarBounds = bounds.map { it.toTypeName(typeParamResolver) }
val typeVarVariance = when (variance) {
COVARIANT -> KModifier.OUT
CONTRAVARIANT -> KModifier.IN
else -> null
}
return TypeVariableName(
typeVarName,
bounds = typeVarBounds.toList(),
variance = typeVarVariance
)
}
internal fun KSTypeArgument.toTypeName(typeParamResolver: TypeParameterResolver): TypeName {
val typeName = type?.resolve()?.toTypeName(typeParamResolver) ?: return KpStar
return when (variance) {
COVARIANT -> WildcardTypeName.producerOf(typeName)
CONTRAVARIANT -> WildcardTypeName.consumerOf(typeName)
STAR -> KpStar
INVARIANT -> typeName
}
}
internal fun KSTypeReference.toTypeName(typeParamResolver: TypeParameterResolver): TypeName {
val type = resolve()
return type.toTypeName(typeParamResolver)
}
internal fun FileSpec.writeTo(codeGenerator: CodeGenerator, logger: KSPLogger) {
// logger.warn("start dependencies")
// logger.error("dependencies:$dependencies")
// Don't use writeTo(file) because that tries to handle directories under the hood
logger.info("codeGenerator:${codeGenerator.generatedFile}")
}
| mit | 710c4ef52cdb26601e371622970067be | 34.076923 | 106 | 0.730463 | 4.644444 | false | false | false | false |
JetBrains/intellij-community | plugins/full-line/local/src/org/jetbrains/completion/full/line/local/tokenizer/PriorityQueue.kt | 1 | 1281 | package org.jetbrains.completion.full.line.local.tokenizer
// import org.apache.commons.math3.random.MersenneTwister
import org.apache.commons.math3.distribution.UniformRealDistribution
import java.util.*
abstract class BasePriorityQueue<T> {
abstract fun push(x: T)
abstract fun pop(): T?
}
class STLQueue<T> : BasePriorityQueue<T>() {
private val q = PriorityQueue<T>()
override fun push(x: T) {
this.q.add(x)
}
override fun pop(): T? {
return this.q.poll()
}
}
class DropoutQueue<T>(var skipProb: Double) : BasePriorityQueue<T>() {
// val rnd = MersenneTwister()
var dist = UniformRealDistribution(0.0, 1.0)
private val q = PriorityQueue<T>()
private val skippedElements = ArrayList<T>()
override fun push(x: T) {
q.add(x)
}
override fun pop(): T? {
assert(skippedElements.isEmpty())
while (true) {
if (q.isEmpty()) {
skippedElements.forEach {
q.add(it)
}
skippedElements.clear()
return null
}
val temp = q.peek()
q.poll()
if (dist.sample() < skipProb) {
skippedElements.add(temp)
}
else {
skippedElements.forEach {
q.add(it)
}
skippedElements.clear()
return temp
}
}
}
}
| apache-2.0 | 8093c9d919734ab31e4f499c0d8be3c2 | 20.711864 | 70 | 0.610461 | 3.462162 | false | false | false | false |
google/iosched | mobile/src/test/java/com/google/samples/apps/iosched/ui/signin/SignInViewModelTest.kt | 1 | 2198 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.signin
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.samples.apps.iosched.test.data.MainCoroutineRule
import com.google.samples.apps.iosched.test.util.fakes.FakeSignInViewModelDelegate
import junit.framework.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class SignInViewModelTest {
// Executes tasks in the Architecture Components in the same thread
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
@Test
fun signedInUser_signsOut() {
// Given a view model with a signed in user
val signInViewModelDelegate = FakeSignInViewModelDelegate().apply {
injectIsSignedIn = true
}
val viewModel = SignInViewModel(signInViewModelDelegate)
// When sign out is requested
viewModel.onSignOut()
// Then a sign out request is emitted
assertEquals(1, signInViewModelDelegate.signOutRequestsEmitted)
}
@Test
fun noSignedInUser_signsIn() {
// Given a view model with a signed out user
val signInViewModelDelegate = FakeSignInViewModelDelegate().apply {
injectIsSignedIn = false
}
val viewModel = SignInViewModel(signInViewModelDelegate)
// When sign out is requested
viewModel.onSignIn()
// Then a sign out request is emitted
assertEquals(1, signInViewModelDelegate.signInRequestsEmitted)
}
}
| apache-2.0 | f039ad605cda04408c9826261183ce38 | 32.815385 | 82 | 0.722475 | 4.884444 | false | true | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/config/GitVcsPanel.kt | 1 | 21621 | // Copyright 2000-2021 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 git4idea.config
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.dvcs.branch.DvcsSyncSettings
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.components.service
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.options.SearchableConfigurable
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vcs.changes.onChangeListAvailabilityChanged
import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.TextComponentEmptyText
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.execution.ParametersListUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.VcsExecutablePathSelector
import com.intellij.vcs.commit.CommitModeManager
import com.intellij.vcs.log.VcsLogFilterCollection.STRUCTURE_FILTER
import com.intellij.vcs.log.impl.MainVcsLogUiProperties
import com.intellij.vcs.log.ui.VcsLogColorManagerImpl
import com.intellij.vcs.log.ui.filter.StructureFilterPopupComponent
import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi
import git4idea.GitVcs
import git4idea.branch.GitBranchIncomingOutgoingManager
import git4idea.i18n.GitBundle
import git4idea.i18n.GitBundle.message
import git4idea.index.canEnableStagingArea
import git4idea.index.enableStagingArea
import git4idea.repo.GitRepositoryManager
import git4idea.update.GitUpdateProjectInfoLogProperties
import git4idea.update.getUpdateMethods
import org.jetbrains.annotations.CalledInAny
import java.awt.Color
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.JLabel
import javax.swing.border.Border
private fun gitSharedSettings(project: Project) = GitSharedSettings.getInstance(project)
private fun projectSettings(project: Project) = GitVcsSettings.getInstance(project)
private val applicationSettings get() = GitVcsApplicationSettings.getInstance()
private val gitOptionGroupName get() = message("settings.git.option.group")
// @formatter:off
private fun cdSyncBranches(project: Project) = CheckboxDescriptor(DvcsBundle.message("sync.setting"), PropertyBinding({ projectSettings(project).syncSetting == DvcsSyncSettings.Value.SYNC }, { projectSettings(project).syncSetting = if (it) DvcsSyncSettings.Value.SYNC else DvcsSyncSettings.Value.DONT_SYNC }), groupName = gitOptionGroupName)
private val cdCommitOnCherryPick get() = CheckboxDescriptor(message("settings.commit.automatically.on.cherry.pick"), PropertyBinding(applicationSettings::isAutoCommitOnCherryPick, applicationSettings::setAutoCommitOnCherryPick), groupName = gitOptionGroupName)
private fun cdAddCherryPickSuffix(project: Project) = CheckboxDescriptor(message("settings.add.suffix"), PropertyBinding({ projectSettings(project).shouldAddSuffixToCherryPicksOfPublishedCommits() }, { projectSettings(project).setAddSuffixToCherryPicks(it) }), groupName = gitOptionGroupName)
private fun cdWarnAboutCrlf(project: Project) = CheckboxDescriptor(message("settings.crlf"), PropertyBinding({ projectSettings(project).warnAboutCrlf() }, { projectSettings(project).setWarnAboutCrlf(it) }), groupName = gitOptionGroupName)
private fun cdWarnAboutDetachedHead(project: Project) = CheckboxDescriptor(message("settings.detached.head"), PropertyBinding({ projectSettings(project).warnAboutDetachedHead() }, { projectSettings(project).setWarnAboutDetachedHead(it) }), groupName = gitOptionGroupName)
private fun cdAutoUpdateOnPush(project: Project) = CheckboxDescriptor(message("settings.auto.update.on.push.rejected"), PropertyBinding({ projectSettings(project).autoUpdateIfPushRejected() }, { projectSettings(project).setAutoUpdateIfPushRejected(it) }), groupName = gitOptionGroupName)
private fun cdShowCommitAndPushDialog(project: Project) = CheckboxDescriptor(message("settings.push.dialog"), PropertyBinding({ projectSettings(project).shouldPreviewPushOnCommitAndPush() }, { projectSettings(project).setPreviewPushOnCommitAndPush(it) }), groupName = gitOptionGroupName)
private fun cdHidePushDialogForNonProtectedBranches(project: Project) = CheckboxDescriptor(message("settings.push.dialog.for.protected.branches"), PropertyBinding({ projectSettings(project).isPreviewPushProtectedOnly }, { projectSettings(project).isPreviewPushProtectedOnly = it }), groupName = gitOptionGroupName)
private val cdOverrideCredentialHelper get() = CheckboxDescriptor(message("settings.credential.helper"), PropertyBinding({ applicationSettings.isUseCredentialHelper }, { applicationSettings.isUseCredentialHelper = it }), groupName = gitOptionGroupName)
private fun synchronizeBranchProtectionRules(project: Project) = CheckboxDescriptor(message("settings.synchronize.branch.protection.rules"), PropertyBinding({gitSharedSettings(project).isSynchronizeBranchProtectionRules}, { gitSharedSettings(project).isSynchronizeBranchProtectionRules = it }), groupName = gitOptionGroupName, comment = message("settings.synchronize.branch.protection.rules.description"))
private val cdEnableStagingArea get() = CheckboxDescriptor(message("settings.enable.staging.area"), PropertyBinding({ applicationSettings.isStagingAreaEnabled }, { enableStagingArea(it) }), groupName = gitOptionGroupName, comment = message("settings.enable.staging.area.comment"))
// @formatter:on
internal fun gitOptionDescriptors(project: Project): List<OptionDescription> {
val list = mutableListOf(
cdCommitOnCherryPick,
cdAutoUpdateOnPush(project),
cdWarnAboutCrlf(project),
cdWarnAboutDetachedHead(project),
cdEnableStagingArea
)
val manager = GitRepositoryManager.getInstance(project)
if (manager.moreThanOneRoot()) {
list += cdSyncBranches(project)
}
return list.map(CheckboxDescriptor::asOptionDescriptor)
}
internal class GitVcsPanel(private val project: Project) :
BoundConfigurable(GitBundle.message("settings.git.option.group"), "project.propVCSSupport.VCSs.Git"),
SearchableConfigurable {
private val projectSettings by lazy { GitVcsSettings.getInstance(project) }
@Volatile
private var versionCheckRequested = false
private val currentUpdateInfoFilterProperties = MyLogProperties(project.service<GitUpdateProjectInfoLogProperties>())
private lateinit var branchUpdateInfoRow: Row
private lateinit var branchUpdateInfoCommentRow: Row
private lateinit var supportedBranchUpLabel: JLabel
private val pathSelector: VcsExecutablePathSelector by lazy {
VcsExecutablePathSelector(GitVcs.NAME, disposable!!, object : VcsExecutablePathSelector.ExecutableHandler {
override fun patchExecutable(executable: String): String? {
return GitExecutableDetector.patchExecutablePath(executable)
}
override fun testExecutable(executable: String) {
testGitExecutable(executable)
}
})
}
private fun testGitExecutable(pathToGit: String) {
val modalityState = ModalityState.stateForComponent(pathSelector.mainPanel)
val errorNotifier = InlineErrorNotifierFromSettings(
GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null),
modalityState, disposable!!
)
object : Task.Modal(project, GitBundle.message("git.executable.version.progress.title"), true) {
private lateinit var gitVersion: GitVersion
override fun run(indicator: ProgressIndicator) {
val executableManager = GitExecutableManager.getInstance()
val executable = executableManager.getExecutable(pathToGit)
executableManager.dropVersionCache(executable)
gitVersion = executableManager.identifyVersion(executable)
}
override fun onThrowable(error: Throwable) {
val problemHandler = findGitExecutableProblemHandler(project)
problemHandler.showError(error, errorNotifier)
}
override fun onSuccess() {
if (gitVersion.isSupported) {
errorNotifier.showMessage(message("git.executable.version.is", gitVersion.presentation))
}
else {
showUnsupportedVersionError(project, gitVersion, errorNotifier)
}
}
}.queue()
}
private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent,
private val modalityState: ModalityState,
disposable: Disposable) :
InlineErrorNotifier(inlineComponent, modalityState, disposable) {
@CalledInAny
override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) {
if (fixOption is ErrorNotifier.FixOption.Configure) {
super.showError(text, description, null)
}
else {
super.showError(text, description, fixOption)
}
}
override fun resetGitExecutable() {
super.resetGitExecutable()
GitExecutableManager.getInstance().getDetectedExecutable(project) // populate cache
invokeAndWaitIfNeeded(modalityState) {
resetPathSelector()
}
}
}
private fun getCurrentExecutablePath(): String? = pathSelector.currentPath?.takeIf { it.isNotBlank() }
private fun LayoutBuilder.gitExecutableRow() = row {
pathSelector.mainPanel(growX)
.onReset {
resetPathSelector()
}
.onIsModified {
val projectSettingsPathToGit = projectSettings.pathToGit
val currentPath = getCurrentExecutablePath()
if (pathSelector.isOverridden) {
currentPath != projectSettingsPathToGit
}
else {
currentPath != applicationSettings.savedPathToGit || projectSettingsPathToGit != null
}
}
.onApply {
val executablePathOverridden = pathSelector.isOverridden
val currentPath = getCurrentExecutablePath()
if (executablePathOverridden) {
projectSettings.pathToGit = currentPath
}
else {
applicationSettings.setPathToGit(currentPath)
projectSettings.pathToGit = null
}
validateExecutableOnceAfterClose()
updateBranchUpdateInfoRow()
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
}
}
private fun resetPathSelector() {
val projectSettingsPathToGit = projectSettings.pathToGit
val detectedExecutable = try {
GitExecutableManager.getInstance().getDetectedExecutable(project)
}
catch (e: ProcessCanceledException) {
GitExecutableDetector.getDefaultExecutable()
}
pathSelector.reset(applicationSettings.savedPathToGit,
projectSettingsPathToGit != null,
projectSettingsPathToGit,
detectedExecutable)
updateBranchUpdateInfoRow()
}
/**
* Special method to check executable after it has been changed through settings
*/
private fun validateExecutableOnceAfterClose() {
if (!versionCheckRequested) {
ApplicationManager.getApplication().invokeLater(
{
object : Task.Backgroundable(project, message("git.executable.version.progress.title"), true) {
override fun run(indicator: ProgressIndicator) {
GitExecutableManager.getInstance().testGitExecutableVersionValid(project)
}
}.queue()
versionCheckRequested = false
},
ModalityState.NON_MODAL)
versionCheckRequested = true
}
}
private fun updateBranchUpdateInfoRow() {
val branchInfoSupported = GitVersionSpecialty.INCOMING_OUTGOING_BRANCH_INFO.existsIn(project)
branchUpdateInfoRow.enabled = Registry.`is`("git.update.incoming.outgoing.info") && branchInfoSupported
branchUpdateInfoCommentRow.visible = !branchInfoSupported
supportedBranchUpLabel.foreground = if (!branchInfoSupported && projectSettings.incomingCheckStrategy != GitIncomingCheckStrategy.Never) {
DialogWrapper.ERROR_FOREGROUND_COLOR
}
else {
UIUtil.getContextHelpForeground()
}
}
private fun LayoutBuilder.branchUpdateInfoRow() {
branchUpdateInfoRow = row {
supportedBranchUpLabel = JBLabel(message("settings.supported.for.2.9"))
cell {
label(message("settings.explicitly.check") + " ")
comboBox(
EnumComboBoxModel(GitIncomingCheckStrategy::class.java),
{
projectSettings.incomingCheckStrategy
},
{ selectedStrategy ->
projectSettings.incomingCheckStrategy = selectedStrategy as GitIncomingCheckStrategy
updateBranchUpdateInfoRow()
if (!project.isDefault) {
GitBranchIncomingOutgoingManager.getInstance(project).updateIncomingScheduling()
}
})
}
branchUpdateInfoCommentRow = row {
supportedBranchUpLabel()
}
}
}
override fun getId() = "vcs.${GitVcs.NAME}"
override fun createPanel(): DialogPanel = panel {
gitExecutableRow()
row {
checkBox(cdEnableStagingArea)
.enableIf(StagingAreaAvailablePredicate(project, disposable!!))
}
if (project.isDefault || GitRepositoryManager.getInstance(project).moreThanOneRoot()) {
row {
checkBox(cdSyncBranches(project)).applyToComponent {
toolTipText = DvcsBundle.message("sync.setting.description", GitVcs.DISPLAY_NAME.get())
}
}
}
row {
checkBox(cdCommitOnCherryPick)
.enableIf(ChangeListsEnabledPredicate(project, disposable!!))
}
row {
checkBox(cdAddCherryPickSuffix(project))
}
row {
checkBox(cdWarnAboutCrlf(project))
}
row {
checkBox(cdWarnAboutDetachedHead(project))
}
branchUpdateInfoRow()
row {
cell {
label(message("settings.update.method"))
comboBox(
CollectionComboBoxModel(getUpdateMethods()),
{ projectSettings.updateMethod },
{ projectSettings.updateMethod = it!! },
renderer = SimpleListCellRenderer.create<UpdateMethod>("", UpdateMethod::getName)
)
}
}
row {
cell {
label(message("settings.clean.working.tree"))
buttonGroup({ projectSettings.saveChangesPolicy }, { projectSettings.saveChangesPolicy = it }) {
GitSaveChangesPolicy.values().forEach { saveSetting ->
radioButton(saveSetting.text, saveSetting)
}
}
}
}
row {
checkBox(cdAutoUpdateOnPush(project))
}
row {
val previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project))
row {
checkBox(cdHidePushDialogForNonProtectedBranches(project))
.enableIf(previewPushOnCommitAndPush.selected)
}
}
row {
cell {
label(message("settings.protected.branched"))
val sharedSettings = gitSharedSettings(project)
val protectedBranchesField =
ExpandableTextFieldWithReadOnlyText(ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER)
if (sharedSettings.isSynchronizeBranchProtectionRules) {
protectedBranchesField.readOnlyText = ParametersListUtil.COLON_LINE_JOINER.`fun`(sharedSettings.additionalProhibitedPatterns)
}
protectedBranchesField(growX)
.withBinding<List<String>>(
{ ParametersListUtil.COLON_LINE_PARSER.`fun`(it.text) },
{ component, value -> component.text = ParametersListUtil.COLON_LINE_JOINER.`fun`(value) },
PropertyBinding(
{ sharedSettings.forcePushProhibitedPatterns },
{ sharedSettings.forcePushProhibitedPatterns = it })
)
}
row {
checkBox(synchronizeBranchProtectionRules(project))
}
}
row {
checkBox(cdOverrideCredentialHelper)
}
if (AbstractCommonUpdateAction.showsCustomNotification(listOf(GitVcs.getInstance(project)))) {
updateProjectInfoFilter()
}
}
private fun LayoutBuilder.updateProjectInfoFilter() {
row {
cell {
val storedProperties = project.service<GitUpdateProjectInfoLogProperties>()
val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toSet()
val model = VcsLogClassicFilterUi.FileFilterModel(roots, currentUpdateInfoFilterProperties, null)
val component = object : StructureFilterPopupComponent(currentUpdateInfoFilterProperties, model, VcsLogColorManagerImpl(roots)) {
override fun shouldDrawLabel(): Boolean = false
override fun shouldIndicateHovering(): Boolean = false
override fun getDefaultSelectorForeground(): Color = UIUtil.getLabelForeground()
override fun createUnfocusedBorder(): Border {
return FilledRoundedBorder(JBColor.namedColor("Component.borderColor", Gray.xBF), ARC_SIZE, 1)
}
}.initUi()
label(message("settings.filter.update.info") + " ")
component()
.onIsModified {
storedProperties.getFilterValues(STRUCTURE_FILTER.name) != currentUpdateInfoFilterProperties.structureFilter
}
.onApply {
storedProperties.saveFilterValues(STRUCTURE_FILTER.name, currentUpdateInfoFilterProperties.structureFilter)
}
.onReset {
currentUpdateInfoFilterProperties.structureFilter = storedProperties.getFilterValues(STRUCTURE_FILTER.name)
model.updateFilterFromProperties()
}
}
}
}
private class MyLogProperties(mainProperties: GitUpdateProjectInfoLogProperties) : MainVcsLogUiProperties by mainProperties {
var structureFilter: List<String>? = null
override fun getFilterValues(filterName: String): List<String>? = structureFilter.takeIf { filterName == STRUCTURE_FILTER.name }
override fun saveFilterValues(filterName: String, values: MutableList<String>?) {
if (filterName == STRUCTURE_FILTER.name) {
structureFilter = values
}
}
}
}
private typealias ParserFunction = Function<String, List<String>>
private typealias JoinerFunction = Function<List<String>, String>
internal class ExpandableTextFieldWithReadOnlyText(lineParser: ParserFunction,
private val lineJoiner: JoinerFunction) : ExpandableTextField(lineParser, lineJoiner) {
var readOnlyText = ""
init {
addFocusListener(object : FocusAdapter() {
override fun focusLost(e: FocusEvent) {
val myComponent = this@ExpandableTextFieldWithReadOnlyText
if (e.component == myComponent) {
val document = myComponent.document
val documentText = document.getText(0, document.length)
updateReadOnlyText(documentText)
}
}
})
}
override fun setText(t: String?) {
if (!t.isNullOrBlank() && t != text) {
updateReadOnlyText(t)
}
super.setText(t)
}
private fun updateReadOnlyText(@NlsSafe text: String) {
if (readOnlyText.isBlank()) return
val readOnlySuffix = if (text.isBlank()) readOnlyText else lineJoiner.join("", readOnlyText) // NON-NLS
with(emptyText as TextComponentEmptyText) {
clear()
appendText(text, SimpleTextAttributes.REGULAR_ATTRIBUTES)
appendText(readOnlySuffix, SimpleTextAttributes.GRAYED_ATTRIBUTES)
setTextToTriggerStatus(text) //this will force status text rendering in case if the text field is not empty
}
}
fun JoinerFunction.join(vararg items: String): String = `fun`(items.toList())
}
private class StagingAreaAvailablePredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() {
override fun addListener(listener: (Boolean) -> Unit) {
project.messageBus.connect(disposable).subscribe(CommitModeManager.SETTINGS, object : CommitModeManager.SettingsListener {
override fun settingsChanged() {
listener(invoke())
}
})
}
override fun invoke(): Boolean = canEnableStagingArea()
}
private class ChangeListsEnabledPredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() {
override fun addListener(listener: (Boolean) -> Unit) {
onChangeListAvailabilityChanged(project, disposable, false) { listener(invoke()) }
}
override fun invoke(): Boolean = ChangeListManager.getInstance(project).areChangeListsEnabled()
}
| apache-2.0 | 8d7801fa420e569513a1c71262c841bf | 44.327044 | 420 | 0.728042 | 5.188625 | false | false | false | false |
ursjoss/sipamato | public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/newstudies/NewStudyListPage.kt | 1 | 9092 | package ch.difty.scipamato.publ.web.newstudies
import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG
import ch.difty.scipamato.common.web.LABEL_TAG
import ch.difty.scipamato.publ.entity.NewStudy
import ch.difty.scipamato.publ.entity.NewStudyPageLink
import ch.difty.scipamato.publ.entity.NewStudyTopic
import ch.difty.scipamato.publ.entity.Newsletter
import ch.difty.scipamato.publ.persistence.api.NewStudyTopicService
import ch.difty.scipamato.publ.web.CommercialFontResourceProvider
import ch.difty.scipamato.publ.web.PublicPageParameters
import ch.difty.scipamato.publ.web.common.BasePage
import ch.difty.scipamato.publ.web.paper.browse.PublicPaperDetailPage
import ch.difty.scipamato.publ.web.resources.IcoMoonIconType
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapExternalLink
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapLink
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons
import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType
import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType
import org.apache.wicket.markup.ComponentTag
import org.apache.wicket.markup.head.CssHeaderItem
import org.apache.wicket.markup.head.IHeaderResponse
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.link.ExternalLink
import org.apache.wicket.markup.html.link.Link
import org.apache.wicket.markup.html.list.ListItem
import org.apache.wicket.markup.html.list.ListView
import org.apache.wicket.model.Model
import org.apache.wicket.model.PropertyModel
import org.apache.wicket.model.StringResourceModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.request.resource.CssResourceReference
import org.apache.wicket.spring.injection.annot.SpringBean
import org.wicketstuff.annotation.mount.MountPath
/**
* The page lists 'new studies', i.e. studies that were collected and flagged by the SciPaMaTo-team
* as eligible for this page. By default, the newest collection of new studies is presented.
*
* With the use of page-parameters, an older collection of new studies can be selected instead.
*
* The page is typically shown in an iframe of a CMS.
*/
@MountPath("new-studies")
@Suppress("SameParameterValue")
open class NewStudyListPage(parameters: PageParameters) : BasePage<Void>(parameters) {
@SpringBean
private lateinit var newStudyTopicService: NewStudyTopicService
@SpringBean(name = "simplonFontResourceProvider")
private lateinit var simplonFontResourceProvider: CommercialFontResourceProvider
@SpringBean(name = "icoMoonFontResourceProvider")
private lateinit var icoMoonFontResourceProvider: CommercialFontResourceProvider
override fun renderAdditionalCommercialFonts(response: IHeaderResponse) {
response.render(CssHeaderItem.forReference(simplonFontResourceProvider.cssResourceReference))
response.render(CssHeaderItem.forReference(icoMoonFontResourceProvider.cssResourceReference))
}
override fun renderHead(response: IHeaderResponse) {
super.renderHead(response)
response.render(CssHeaderItem.forReference(CssResourceReference(NewStudyListPage::class.java, "NewStudyListPage.css")))
}
override fun onInitialize() {
super.onInitialize()
newIntroSection()
newNewsletterSection()
newExternalLinkSection()
newArchiveSectionWithPreviousNewsletters()
}
/**
* Introductory paragraph
*/
private fun newIntroSection() {
queue(newLabel("h1Title"))
queue(newLabel("introParagraph"))
queue(newDbSearchLink("dbLink", properties.cmsUrlSearchPage))
}
private fun newDbSearchLink(id: String, href: String?) = object : ExternalLink(
id,
href,
StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null).string
) {
override fun onComponentTag(tag: ComponentTag) {
super.onComponentTag(tag)
tag.put(TARGET, BLANK)
}
}
/**
* The actual newsletter/new study list part with topics and nested studies
*/
private fun newNewsletterSection() {
queue(newNewStudyCollection("topics"))
}
private fun newNewStudyCollection(id: String): ListView<NewStudyTopic> {
val topics = retrieveStudyCollection()
paperIdManager.initialize(extractPaperNumbersFrom(topics))
return object : ListView<NewStudyTopic>(id, topics) {
override fun populateItem(topic: ListItem<NewStudyTopic>) {
topic.add(Label("topicTitle", PropertyModel<Any>(topic.model, "title")))
topic.add(object : ListView<NewStudy>("topicStudies", topic.modelObject.studies) {
override fun populateItem(study: ListItem<NewStudy>) {
study.add(Label("headline", PropertyModel<Any>(study.model, "headline")))
study.add(Label("description", PropertyModel<Any>(study.model, "description")))
study.add(newLinkToStudy("reference", study))
}
})
}
}
}
private fun retrieveStudyCollection(): List<NewStudyTopic> {
val issue = pageParameters[PublicPageParameters.ISSUE.parameterName]
return if (issue.isNull || issue.isEmpty)
newStudyTopicService.findMostRecentNewStudyTopics(languageCode)
else newStudyTopicService.findNewStudyTopicsForNewsletterIssue(issue.toString(), languageCode)
}
private fun extractPaperNumbersFrom(topics: List<NewStudyTopic>): List<Long> = topics.flatMap { it.studies }.map { it.number }
/**
* Link pointing to the study detail page with the current [study] (with [id])
*/
private fun newLinkToStudy(id: String, study: ListItem<NewStudy>): Link<NewStudy> {
val pp = PageParameters()
pp[PublicPageParameters.NUMBER.parameterName] = study.modelObject.number
return object : Link<NewStudy>(id) {
override fun onClick() {
paperIdManager.setFocusToItem(study.modelObject.number)
setResponsePage(PublicPaperDetailPage(pp, pageReference))
}
}.apply {
add(Label("$id$LABEL_TAG", PropertyModel<String>(study.model, "reference")))
}
}
/**
* Any links configured in database table new_study_page_links will be published in this section.
*/
private fun newExternalLinkSection() {
queue(newLinkList("links"))
}
private fun newLinkList(id: String): ListView<NewStudyPageLink> {
val links = newStudyTopicService.findNewStudyPageLinks(languageCode)
return object : ListView<NewStudyPageLink>(id, links) {
override fun populateItem(link: ListItem<NewStudyPageLink>) {
link.add(newExternalLink("link", link))
}
}
}
private fun newExternalLink(id: String, linkItem: ListItem<NewStudyPageLink>) = object : BootstrapExternalLink(
id,
Model.of(linkItem.modelObject.url)
) {
}.apply {
setTarget(BootstrapExternalLink.Target.blank)
setIconType(chooseIcon(GlyphIconType.arrowright, IcoMoonIconType.arrow_right))
setLabel(Model.of(linkItem.modelObject.title))
}
fun chooseIcon(free: IconType, commercial: IconType): IconType = if (properties.isCommercialFontPresent) commercial else free
/** The archive section lists links pointing to previous newsletters with their studies. */
private fun newArchiveSectionWithPreviousNewsletters() {
queue(newLabel("h2ArchiveTitle"))
queue(newNewsletterArchive("archive"))
}
private fun newLabel(id: String) = Label(
id,
StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null)
)
private fun newNewsletterArchive(id: String): ListView<Newsletter> {
val newsletterCount = properties.numberOfPreviousNewslettersInArchive
val newsletters = newStudyTopicService.findArchivedNewsletters(newsletterCount, languageCode)
return object : ListView<Newsletter>(id, newsletters) {
override fun populateItem(nl: ListItem<Newsletter>) {
nl.add(newLinkToArchivedNewsletter("monthName", nl))
}
}
}
private fun newLinkToArchivedNewsletter(id: String, newsletter: ListItem<Newsletter>): Link<Newsletter> {
val pp = PageParameters()
pp[PublicPageParameters.ISSUE.parameterName] = newsletter.modelObject.issue
val monthName = newsletter.modelObject.getMonthName(languageCode)
return object : BootstrapLink<Newsletter>(id, Buttons.Type.Link) {
override fun onClick() = setResponsePage(NewStudyListPage(pp))
}.apply {
setLabel(Model.of(monthName))
setIconType(chooseIcon(GlyphIconType.link, IcoMoonIconType.link))
}
}
companion object {
private const val serialVersionUID = 1L
private const val TARGET = "target"
private const val BLANK = "_blank"
}
}
| gpl-3.0 | 25b714d0abca20448e811d84365b55cb | 42.295238 | 130 | 0.716124 | 4.424331 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHEditableHtmlPaneHandle.kt | 2 | 2601 | // Copyright 2000-2021 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.pullrequest.ui
import com.intellij.CommonBundle
import com.intellij.ide.plugins.newui.VerticalLayout
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.scale.JBUIScale
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPreLoadingSubmittableTextFieldModel
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHSubmittableTextFieldFactory
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.util.successOnEdt
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
import javax.swing.text.BadLocationException
import javax.swing.text.Utilities
internal open class GHEditableHtmlPaneHandle(private val editorPane: HtmlEditorPane,
private val loadSource: () -> CompletableFuture<String>,
private val updateText: (String) -> CompletableFuture<out Any?>) {
val panel = NonOpaquePanel(VerticalLayout(JBUIScale.scale(8))).apply {
add(wrapEditorPane(editorPane))
}
protected open fun wrapEditorPane(editorPane: HtmlEditorPane): JComponent = editorPane
private var editor: JComponent? = null
fun showAndFocusEditor() {
if (editor == null) {
val placeHolderText = StringUtil.repeatSymbol('\n', Integer.max(0, getLineCount() - 1))
val model = GHPreLoadingSubmittableTextFieldModel(placeHolderText, loadSource()) { newText ->
updateText(newText).successOnEdt {
hideEditor()
}
}
editor = GHSubmittableTextFieldFactory(model).create(CommonBundle.message("button.submit"), onCancel = {
hideEditor()
})
panel.add(editor!!, VerticalLayout.FILL_HORIZONTAL)
panel.validate()
panel.repaint()
}
editor?.let { GHUIUtil.focusPanel(it) }
}
private fun hideEditor() {
editor?.let {
panel.remove(it)
panel.revalidate()
panel.repaint()
}
editor = null
}
private fun getLineCount(): Int {
if (editorPane.document.length == 0) return 0
var lineCount = 0
var offset = 0
while (true) {
try {
offset = Utilities.getRowEnd(editorPane, offset) + 1
lineCount++
}
catch (e: BadLocationException) {
break
}
}
return lineCount
}
}
| apache-2.0 | ae1e96c327685c4e4025d9c3cc874bce | 33.223684 | 140 | 0.702422 | 4.492228 | false | false | false | false |
LivingDoc/livingdoc | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/LivingDoc.kt | 2 | 5561 | package org.livingdoc.engine
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.documents.Group
import org.livingdoc.api.tagging.Tag
import org.livingdoc.config.ConfigProvider
import org.livingdoc.engine.config.TaggingConfig
import org.livingdoc.engine.execution.ExecutionException
import org.livingdoc.engine.execution.MalformedFixtureException
import org.livingdoc.engine.execution.groups.GroupFixture
import org.livingdoc.engine.execution.groups.ImplicitGroup
import org.livingdoc.reports.ReportsManager
import org.livingdoc.repositories.RepositoryManager
import org.livingdoc.repositories.config.RepositoryConfiguration
import org.livingdoc.results.documents.DocumentResult
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Executes the given document class and returns the [DocumentResult]. The document's class must be annotated
* with [ExecutableDocument].
*
* @return the [DocumentResult] of the execution
* @throws ExecutionException in case the execution failed in a way that did not produce a viable result
* @since 2.0
*/
class LivingDoc(
private val configProvider: ConfigProvider = ConfigProvider.load(),
private val repositoryManager: RepositoryManager =
RepositoryManager.from(RepositoryConfiguration.from(configProvider)),
private val decisionTableToFixtureMatcher: DecisionTableToFixtureMatcher = DecisionTableToFixtureMatcher(),
private val scenarioToFixtureMatcher: ScenarioToFixtureMatcher = ScenarioToFixtureMatcher()
) {
companion object {
/**
* Indicates whether the execution should fail fast due to a specific
* thrown exception and not execute any more tests.
*/
var failFastActivated: Boolean = false
/**
* Global ExecutorService which uses a WorkStealing(Thread)Pool
* for the parallel execution of tasks in the LivingDoc engine
*/
val executor: ExecutorService = Executors.newWorkStealingPool()
}
val taggingConfig = TaggingConfig.from(configProvider)
/**
* Executes the given document classes and returns the list of [DocumentResults][DocumentResult]. The document
* classes must be annotated with [ExecutableDocument].
*
* @param documentClasses the document classes to execute
* @return a list of [DocumentResults][DocumentResult] of the execution
* @throws ExecutionException in case the execution failed in a way that did not produce a viable result
*/
@Throws(ExecutionException::class)
fun execute(documentClasses: List<Class<*>>): List<DocumentResult> {
// Execute documents
val documentResults = documentClasses.filter {
val tags = getTags(it)
when {
taggingConfig.includedTags.isNotEmpty() && tags.none { tag -> taggingConfig.includedTags.contains(tag) }
-> false
tags.any { tag -> taggingConfig.excludedTags.contains(tag) } -> false
else -> true
}
}.groupBy { documentClass ->
extractGroup(documentClass)
}.flatMap { (groupClass, documentClasses) ->
executeGroup(groupClass, documentClasses)
}
// Generate reports
val reportsManager = ReportsManager.from(configProvider)
reportsManager.generateReports(documentResults)
// Return results for further processing
return documentResults
}
private fun getTags(documentClass: Class<*>): List<String> {
return documentClass.getAnnotationsByType(Tag::class.java).map {
it.value
}
}
/**
* Executes the given group, which contains the given document classes and returns the list of
* [DocumentResults][DocumentResult]. The group class must be annotated with [Group] and the document classes must
* be annotated with [ExecutableDocument].
*
* @param groupClass the group that contains the documentClasses
* @param documentClasses the document classes to execute
* @return a list of [DocumentResults][DocumentResult] of the execution
* @throws ExecutionException in case the execution failed in a way that did not produce a viable result
*/
@Throws(ExecutionException::class)
private fun executeGroup(groupClass: Class<*>, documentClasses: List<Class<*>>): List<DocumentResult> {
return GroupFixture(
groupClass,
documentClasses,
repositoryManager,
decisionTableToFixtureMatcher,
scenarioToFixtureMatcher
).execute()
}
private fun extractGroup(documentClass: Class<*>): Class<*> {
val declaringGroup = documentClass.declaringClass?.takeIf { declaringClass ->
declaringClass.isAnnotationPresent(Group::class.java)
}
val annotationGroup =
documentClass.getAnnotation(ExecutableDocument::class.java).group.java.takeIf { annotationClass ->
annotationClass.isAnnotationPresent(Group::class.java)
}
if (declaringGroup != null && annotationGroup != null && declaringGroup != annotationGroup)
throw MalformedFixtureException(
documentClass, listOf(
"Ambiguous group definition: declared inside ${declaringGroup.name}, " +
"annotation specifies ${annotationGroup.name}"
)
)
return declaringGroup ?: annotationGroup ?: ImplicitGroup::class.java
}
}
| apache-2.0 | 2c93521fe458f8ed772248486de31d5c | 42.108527 | 120 | 0.698256 | 5.168216 | false | true | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/PathResolverState.kt | 1 | 770 | package jetbrains.buildServer.agent.runner
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.rx.Observer
data class PathResolverState(
public val pathToResolve: Path,
public val virtualPathObserver: Observer<Path>,
public val commandToResolve: Path = Path("")) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PathResolverState
if (pathToResolve != other.pathToResolve) return false
if (commandToResolve != other.commandToResolve) return false
return true
}
override fun hashCode(): Int {
var result = pathToResolve.hashCode()
result = 31 * result + commandToResolve.hashCode()
return result
}
} | apache-2.0 | a53769ecea7050dd5dcc4a49ac0e99b2 | 27.555556 | 63 | 0.718182 | 4.556213 | false | false | false | false |
Raizlabs/DBFlow | tests/src/androidTest/java/com/dbflow5/sql/language/WhereTest.kt | 1 | 6118 | package com.dbflow5.sql.language
import com.dbflow5.BaseUnitTest
import com.dbflow5.assertEquals
import com.dbflow5.config.databaseForTable
import com.dbflow5.models.SimpleModel
import com.dbflow5.models.SimpleModel_Table.name
import com.dbflow5.models.TwoColumnModel
import com.dbflow5.models.TwoColumnModel_Table.id
import com.dbflow5.query.NameAlias
import com.dbflow5.query.OrderBy.Companion.fromNameAlias
import com.dbflow5.query.Where
import com.dbflow5.query.groupBy
import com.dbflow5.query.having
import com.dbflow5.query.min
import com.dbflow5.query.nameAlias
import com.dbflow5.query.or
import com.dbflow5.query.property.property
import com.dbflow5.query.select
import com.dbflow5.query.update
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
class WhereTest : BaseUnitTest() {
@Test
fun validateBasicWhere() {
val query = select from SimpleModel::class where name.`is`("name")
"SELECT * FROM `SimpleModel` WHERE `name`='name'".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateComplexQueryWhere() {
val query = select from SimpleModel::class where name.`is`("name") or id.eq(1) and (id.`is`(0) or name.eq("hi"))
"SELECT * FROM `SimpleModel` WHERE `name`='name' OR `id`=1 AND (`id`=0 OR `name`='hi')".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateGroupBy() {
val query = select from SimpleModel::class where name.`is`("name") groupBy name
"SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateGroupByNameAlias() {
val query = (select from SimpleModel::class where name.`is`("name")).groupBy("name".nameAlias, "id".nameAlias)
"SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`,`id`".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateGroupByNameProps() {
val query = (select from SimpleModel::class where name.`is`("name")).groupBy(name, id)
"SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`,`id`".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateHaving() {
val query = select from SimpleModel::class where name.`is`("name") having name.like("That")
"SELECT * FROM `SimpleModel` WHERE `name`='name' HAVING `name` LIKE 'That'".assertEquals(query)
assertCanCopyQuery(query)
"SELECT * FROM `SimpleModel` GROUP BY exampleValue HAVING MIN(ROWID)>5".assertEquals(
(select from SimpleModel::class
groupBy NameAlias.rawBuilder("exampleValue").build()
having min(NameAlias.rawBuilder("ROWID").build().property).greaterThan(5))
)
}
@Test
fun validateLimit() {
val query = select from SimpleModel::class where name.`is`("name") limit 10
"SELECT * FROM `SimpleModel` WHERE `name`='name' LIMIT 10".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateOffset() {
val query = select from SimpleModel::class where name.`is`("name") offset 10
"SELECT * FROM `SimpleModel` WHERE `name`='name' OFFSET 10".assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateWhereExists() {
val query = (select from SimpleModel::class
whereExists (select(name) from SimpleModel::class where name.like("Andrew")))
("SELECT * FROM `SimpleModel` " +
"WHERE EXISTS (SELECT `name` FROM `SimpleModel` WHERE `name` LIKE 'Andrew')").assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateOrderByWhere() {
val query = (select from SimpleModel::class
where name.eq("name")).orderBy(name, true)
("SELECT * FROM `SimpleModel` WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateOrderByWhereAlias() {
val query = (select from SimpleModel::class
where name.eq("name")).orderBy("name".nameAlias, true)
("SELECT * FROM `SimpleModel` " +
"WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateOrderBy() {
val query = (select from SimpleModel::class
where name.eq("name") orderBy fromNameAlias("name".nameAlias).ascending())
("SELECT * FROM `SimpleModel` " +
"WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query)
assertCanCopyQuery(query)
}
private fun <T : Any> assertCanCopyQuery(query: Where<T>) {
val actual = query.cloneSelf()
query.assertEquals(actual)
assertTrue(actual !== query)
}
@Test
fun validateOrderByAll() {
val query = (select from TwoColumnModel::class
where name.eq("name"))
.orderByAll(listOf(
fromNameAlias("name".nameAlias).ascending(),
fromNameAlias("id".nameAlias).descending()))
("SELECT * FROM `TwoColumnModel` " +
"WHERE `name`='name' ORDER BY `name` ASC,`id` DESC").assertEquals(query)
assertCanCopyQuery(query)
}
@Test
fun validateNonSelectThrowError() {
databaseForTable<SimpleModel> { db ->
try {
update<SimpleModel>().set(name.`is`("name")).querySingle(db)
fail("Non select passed")
} catch (i: IllegalArgumentException) {
// expected
}
try {
update<SimpleModel>().set(name.`is`("name")).queryList(db)
fail("Non select passed")
} catch (i: IllegalArgumentException) {
// expected
}
}
}
@Test
fun validate_match_operator() {
val query = (select from SimpleModel::class where (name match "%s"))
("SELECT * FROM `SimpleModel` WHERE `name` MATCH '%s'").assertEquals(query)
assertCanCopyQuery(query)
}
}
| mit | 20a6262cfa5b7ffd73fab859cfa7130d | 35.634731 | 120 | 0.634848 | 4.133784 | false | true | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/type/AgencyTypePagerAdapter.kt | 1 | 1766 | package org.mtransit.android.ui.type
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import org.mtransit.android.commons.MTLog
import org.mtransit.android.data.IAgencyUIProperties
import org.mtransit.android.ui.type.poi.AgencyPOIsFragment
import org.mtransit.android.ui.type.rts.RTSAgencyRoutesFragment
class AgencyTypePagerAdapter(f: Fragment) : FragmentStateAdapter(f), MTLog.Loggable {
companion object {
private val LOG_TAG = AgencyTypePagerAdapter::class.java.simpleName
}
override fun getLogTag(): String = LOG_TAG
private var agencies: MutableList<IAgencyUIProperties>? = null
fun setAgencies(newAgencies: List<IAgencyUIProperties>?): Boolean { // TODO DiffUtil
var changed = false
if (!this.agencies.isNullOrEmpty()) {
this.agencies?.clear()
this.agencies = null // loading
changed = true
}
newAgencies?.let {
this.agencies = mutableListOf<IAgencyUIProperties>().apply {
changed = addAll(it)
}
}
if (changed) {
notifyDataSetChanged()
}
return changed
}
fun isReady() = agencies != null
override fun getItemCount() = agencies?.size ?: 0
override fun createFragment(position: Int): Fragment {
val agency = agencies?.getOrNull(position) ?: throw RuntimeException("Trying to create fragment at $position!")
if (agency.isRTS) {
return RTSAgencyRoutesFragment.newInstance(
agency.authority,
agency.colorInt
)
}
return AgencyPOIsFragment.newInstance(
agency.authority,
agency.colorInt
)
}
} | apache-2.0 | f8b03f6f4d6307d09dea6c53938533e6 | 31.127273 | 119 | 0.648924 | 4.709333 | false | false | false | false |
martinlau/fixture | src/test/kotlin/io/fixture/feature/step/StepDefs.kt | 1 | 5755 | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 Martin Lau
* %%
* 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.
* #L%
*/
package io.fixture.feature.step
import cucumber.api.java.en.Given
import cucumber.api.java.en.Then
import cucumber.api.java.en.When
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import kotlin.test.assertNotNull
import cucumber.api.PendingException
import cucumber.api.DataTable
import org.subethamail.wiser.Wiser
import java.util.regex.Pattern
import java.net.URI
import java.net.URL
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpHead
class StepDefs [Autowired] (
val driver: WebDriver,
val httpClient: HttpClient,
val wiser: Wiser
) {
[Value(value = "#{systemProperties['tomcat.http.port']}")]
var tomcatPort: Int? = null
[Given(value = """^I open any page""")]
fun I_open_any_page() {
driver.get("http://localhost:${tomcatPort}/fixture")
}
[Given(value = """^I select the theme "([^"]*)"$""")]
fun I_select_the_theme(theme: String) {
driver.get(driver.getCurrentUrl() + "?theme=${theme}")
}
[When(value = """^I go to the page "([^"]*)"$""")]
fun I_go_to_the_page(page: String) {
driver.get("http://localhost:${tomcatPort}/fixture${page}")
}
[When(value = """^I click on the link "([^"]*)"$""")]
fun I_click_on_the_link(link: String) {
driver.findElement(By.linkText(link))!!.click()
}
[When(value = """^I log in with the credentials "([^"]*)" and "([^"]*)"$""")]
fun I_log_in_with_the_credentials(username: String, password: String) {
// HACK: drone.io seems to need some time to load the page - this allows that
driver.getCurrentUrl()
driver.findElement(By.id("username"))!!.sendKeys(username)
driver.findElement(By.id("password"))!!.sendKeys(password)
driver.findElement(By.id("submit"))!!.click()
}
[When(value = """^I fill in the form "([^\"]*)" with:$""")]
fun I_fill_in_the_form_with(formId: String, data: DataTable) {
val form = driver.findElement(By.id(formId))!!
data.asMaps()!!.forEach {
val name = it.get("field")
val value = it.get("value")
val field = form.findElement(By.name(name))!!
if (field.getAttribute("type") == "checkbox") {
if ("true" == value) field.click()
}
else {
field.sendKeys(value)
}
}
form.submit()
}
[When(value = """^I click the link in the activation email$""")]
fun I_click_the_link_in_the_activation_email() {
val message = wiser.getMessages().last!!
val pattern = Pattern.compile(""".*(https?://[\da-z\.-]+(:\d+)?[^\s]*).*""", Pattern.DOTALL)
val matcher = pattern.matcher(message.toString()!!)
if (matcher.matches()) {
val url = matcher.group(1)
driver.get(url)
}
}
[Then(value = """^the theme should change to "([^"]*)"$""")]
fun the_theme_should_change_to(theme: String) {
// HACK: drone.io seems to need some time to load the page - this allows that
driver.getCurrentUrl()
assertTrue(driver.getPageSource().contains("href=\"/fixture/static/bootswatch/2.3.1/${theme}/bootstrap.min.css\""))
}
[Then(value = """^I should see the "([^"]*)" link$""")]
fun I_should_see_the_link(link: String) {
// HACK: drone.io seems to need some time to load the page - this allows that
driver.getCurrentUrl()
assertNotNull(driver.findElement(By.linkText(link)))
}
[Then(value = """^I should see the page "([^"]*)"$""")]
fun I_should_see_the_page(title: String) {
// HACK: drone.io seems to need some time to load the page - this allows that
driver.getCurrentUrl()
assertEquals(title, driver.getTitle())
}
[Then(value = """^I should see the alert "([^"]*)"$""")]
fun I_should_see_the_alert(message: String) {
// HACK: drone.io seems to need some time to load the page - this allows that
driver.getCurrentUrl()
assertTrue(driver.findElement(By.className("alert"))!!.getText()!!.contains(message))
}
[Then(value = """^all "([^"]*)" tags should have valid "([^"]*)" attributes$""")]
fun all_tags_should_have_valid_attributes(tag: String, attribute: String) {
val base = driver.getCurrentUrl()!!
driver.findElements(By.tagName(tag))?.forEach {
val path = it.getAttribute(attribute)!!
val uri = URI.create(base).resolve(path)
val request = HttpHead(uri)
try {
val response = httpClient.execute(request)!!
assertEquals(200, response.getStatusLine()!!.getStatusCode())
}
finally {
request.releaseConnection()
}
}
}
}
| apache-2.0 | 45f09952fc9de60dbce1d4aa85d0d60a | 32.265896 | 123 | 0.613553 | 3.831558 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/TaskerIntegration.kt | 1 | 2817 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui
import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.twofortyfouram.locale.sdk.client.receiver.AbstractPluginSettingReceiver
import com.twofortyfouram.locale.sdk.client.ui.activity.AbstractPluginActivity
import org.blokada.R
import ui.utils.cause
import utils.Logger
private const val EVENT_KEY_COMMAND = "command"
class TaskerActivity : AbstractPluginActivity() {
private lateinit var command: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tasker)
command = findViewById(R.id.tasker_command)
findViewById<Button>(R.id.tasker_done).setOnClickListener { finish() }
}
override fun onPostCreateWithPreviousResult(previousBundle: Bundle, previousBlurp: String) {
when {
previousBundle.containsKey(EVENT_KEY_COMMAND) -> {
command.setText(previousBundle.getString(EVENT_KEY_COMMAND))
}
}
}
override fun getResultBundle() = Bundle().apply {
putString(EVENT_KEY_COMMAND, command.text.toString())
}
override fun isBundleValid(bundle: Bundle) = bundle.containsKey(EVENT_KEY_COMMAND)
override fun getResultBlurb(bundle: Bundle): String {
val command = bundle.getString(EVENT_KEY_COMMAND)
return "%s: %s".format("Blokada", command)
}
}
class TaskerReceiver : AbstractPluginSettingReceiver() {
private val log = Logger("TaskerReceiver")
init {
log.v("TaskerReceiver created")
}
override fun isAsync(): Boolean {
return false
}
override fun firePluginSetting(ctx: Context, bundle: Bundle) {
when {
bundle.containsKey(EVENT_KEY_COMMAND) -> cmd(ctx, bundle.getString(EVENT_KEY_COMMAND)!!)
else -> log.e("unknown app intent")
}
}
private fun cmd(ctx: Context, command: String) {
try {
log.v("Executing command from Tasker: $command")
val intent = getIntentForCommand(command)
ctx.startService(intent)
Toast.makeText(ctx, "Tasker: Blokada ($command)", Toast.LENGTH_SHORT).show()
} catch (ex: Exception) {
log.e("Invalid switch app intent".cause(ex))
}
}
override fun isBundleValid(bundle: Bundle) = bundle.containsKey(EVENT_KEY_COMMAND)
} | mpl-2.0 | 88927fcafd982743c311276ee4265e0a | 28.968085 | 100 | 0.677912 | 4.135095 | false | false | false | false |
FirebaseExtended/mlkit-material-android | app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ProminentObjectProcessor.kt | 1 | 7015 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.ml.md.kotlin.objectdetection
import android.graphics.RectF
import android.util.Log
import androidx.annotation.MainThread
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.objects.FirebaseVisionObject
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions
import com.google.firebase.ml.md.kotlin.camera.CameraReticleAnimator
import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay
import com.google.firebase.ml.md.R
import com.google.firebase.ml.md.kotlin.camera.WorkflowModel
import com.google.firebase.ml.md.kotlin.camera.WorkflowModel.WorkflowState
import com.google.firebase.ml.md.kotlin.camera.FrameProcessorBase
import com.google.firebase.ml.md.kotlin.settings.PreferenceUtils
import java.io.IOException
import java.util.ArrayList
/** A processor to run object detector in prominent object only mode. */
class ProminentObjectProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) :
FrameProcessorBase<List<FirebaseVisionObject>>() {
private val detector: FirebaseVisionObjectDetector
private val confirmationController: ObjectConfirmationController = ObjectConfirmationController(graphicOverlay)
private val cameraReticleAnimator: CameraReticleAnimator = CameraReticleAnimator(graphicOverlay)
private val reticleOuterRingRadius: Int = graphicOverlay
.resources
.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_radius)
init {
val optionsBuilder = FirebaseVisionObjectDetectorOptions.Builder()
.setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE)
if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) {
optionsBuilder.enableClassification()
}
this.detector = FirebaseVision.getInstance().getOnDeviceObjectDetector(optionsBuilder.build())
}
override fun stop() {
try {
detector.close()
} catch (e: IOException) {
Log.e(TAG, "Failed to close object detector!", e)
}
}
override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionObject>> {
return detector.processImage(image)
}
@MainThread
override fun onSuccess(
image: FirebaseVisionImage,
results: List<FirebaseVisionObject>,
graphicOverlay: GraphicOverlay
) {
var objects = results
if (!workflowModel.isCameraLive) {
return
}
if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) {
val qualifiedObjects = ArrayList<FirebaseVisionObject>()
qualifiedObjects.addAll(objects
.filter { it.classificationCategory != FirebaseVisionObject.CATEGORY_UNKNOWN }
)
objects = qualifiedObjects
}
if (objects.isEmpty()) {
confirmationController.reset()
workflowModel.setWorkflowState(WorkflowState.DETECTING)
} else {
val objectIndex = 0
val visionObject = objects[objectIndex]
if (objectBoxOverlapsConfirmationReticle(graphicOverlay, visionObject)) {
// User is confirming the object selection.
confirmationController.confirming(visionObject.trackingId)
workflowModel.confirmingObject(
DetectedObject(visionObject, objectIndex, image), confirmationController.progress
)
} else {
// Object detected but user doesn't want to pick this one.
confirmationController.reset()
workflowModel.setWorkflowState(WorkflowState.DETECTED)
}
}
graphicOverlay.clear()
if (objects.isEmpty()) {
graphicOverlay.add(ObjectReticleGraphic(graphicOverlay, cameraReticleAnimator))
cameraReticleAnimator.start()
} else {
if (objectBoxOverlapsConfirmationReticle(graphicOverlay, objects[0])) {
// User is confirming the object selection.
cameraReticleAnimator.cancel()
graphicOverlay.add(
ObjectGraphicInProminentMode(
graphicOverlay, objects[0], confirmationController
)
)
if (!confirmationController.isConfirmed &&
PreferenceUtils.isAutoSearchEnabled(graphicOverlay.context)) {
// Shows a loading indicator to visualize the confirming progress if in auto search mode.
graphicOverlay.add(ObjectConfirmationGraphic(graphicOverlay, confirmationController))
}
} else {
// Object is detected but the confirmation reticle is moved off the object box, which
// indicates user is not trying to pick this object.
graphicOverlay.add(
ObjectGraphicInProminentMode(
graphicOverlay, objects[0], confirmationController
)
)
graphicOverlay.add(ObjectReticleGraphic(graphicOverlay, cameraReticleAnimator))
cameraReticleAnimator.start()
}
}
graphicOverlay.invalidate()
}
private fun objectBoxOverlapsConfirmationReticle(
graphicOverlay: GraphicOverlay,
visionObject: FirebaseVisionObject
): Boolean {
val boxRect = graphicOverlay.translateRect(visionObject.boundingBox)
val reticleCenterX = graphicOverlay.width / 2f
val reticleCenterY = graphicOverlay.height / 2f
val reticleRect = RectF(
reticleCenterX - reticleOuterRingRadius,
reticleCenterY - reticleOuterRingRadius,
reticleCenterX + reticleOuterRingRadius,
reticleCenterY + reticleOuterRingRadius
)
return reticleRect.intersect(boxRect)
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Object detection failed!", e)
}
companion object {
private const val TAG = "ProminentObjProcessor"
}
}
| apache-2.0 | 9489bb3d27c75d04441a0ce84f7d7445 | 41.515152 | 115 | 0.674697 | 5.266517 | false | false | false | false |
JuliusKunze/kotlin-native | performance/src/main/kotlin/org/jetbrains/ring/IntArrayBenchmark.kt | 2 | 3887 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
open class IntArrayBenchmark {
private var _data: IntArray? = null
val data: IntArray
get() = _data!!
fun setup() {
val list = IntArray(BENCHMARK_SIZE)
var index = 0
for (n in intValues(BENCHMARK_SIZE))
list[index++] = n
_data = list
}
//Benchmark
fun copy(): List<Int> {
return data.toList()
}
//Benchmark
fun copyManual(): ArrayList<Int> {
val list = ArrayList<Int>(data.size)
for (item in data) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.filter { filterLoad(it) }.count()
}
//Benchmark
fun filterSomeAndCount(): Int {
return data.filter { filterSome(it) }.count()
}
//Benchmark
fun filterAndMap(): List<String> {
return data.filter { filterLoad(it) }.map { mapLoad(it) }
}
//Benchmark
fun filterAndMapManual(): ArrayList<String> {
val list = ArrayList<String>()
for (it in data) {
if (filterLoad(it)) {
val value = mapLoad(it)
list.add(value)
}
}
return list
}
//Benchmark
fun filter(): List<Int> {
return data.filter { filterLoad(it) }
}
//Benchmark
fun filterSome(): List<Int> {
return data.filter { filterSome(it) }
}
//Benchmark
fun filterPrime(): List<Int> {
return data.filter { filterPrime(it) }
}
//Benchmark
fun filterManual(): ArrayList<Int> {
val list = ArrayList<Int>()
for (it in data) {
if (filterLoad(it))
list.add(it)
}
return list
}
//Benchmark
fun filterSomeManual(): ArrayList<Int> {
val list = ArrayList<Int>()
for (it in data) {
if (filterSome(it))
list.add(it)
}
return list
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFilteredSomeManual(): Int {
var count = 0
for (it in data) {
if (filterSome(it))
count++
}
return count
}
//Benchmark
fun countFilteredPrimeManual(): Int {
var count = 0
for (it in data) {
if (filterPrime(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.count { filterLoad(it) }
}
//Benchmark
fun countFilteredSome(): Int {
return data.count { filterSome(it) }
}
//Benchmark
fun countFilteredPrime(): Int {
val res = data.count { filterPrime(it) }
//println(res)
return res
}
//Benchmark
fun countFilteredLocal(): Int {
return data.cnt { filterLoad(it) }
}
//Benchmark
fun countFilteredSomeLocal(): Int {
return data.cnt { filterSome(it) }
}
//Benchmark
fun reduce(): Int {
return data.fold(0) { acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
}
| apache-2.0 | f4e6ee217cd41b9c6f4a43fc19cb11ca | 21.730994 | 79 | 0.543607 | 4.197624 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/relations/MythicRelationManager.kt | 1 | 2179 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.relations
import com.tealcube.minecraft.bukkit.mythicdrops.api.choices.Choice
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.Relation
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager
class MythicRelationManager : RelationManager {
private val managedRelations = mutableMapOf<String, Relation>()
override fun get(): Set<Relation> = managedRelations.values.toSet()
override fun contains(id: String): Boolean = managedRelations.containsKey(id.toLowerCase())
override fun add(toAdd: Relation) {
managedRelations[toAdd.name.toLowerCase()] = toAdd
}
override fun remove(id: String) {
managedRelations.remove(id.toLowerCase())
}
override fun getById(id: String): Relation? = managedRelations[id.toLowerCase()]
override fun clear() {
managedRelations.clear()
}
override fun random(): Relation? = Choice.between(get()).choose()
}
| mit | 0e03346f25754e291d6d483e3a37be37 | 42.58 | 105 | 0.754933 | 4.568134 | 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.