content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsConfiguration.StandardConfirmation.ADD
import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY
import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY
import com.intellij.openapi.vcs.changes.ChangeListListener
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.VcsIgnoreManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.project.isDirectoryBased
import com.intellij.project.stateStore
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.vfs.AsyncVfsEventsListener
import com.intellij.vfs.AsyncVfsEventsPostProcessor
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.write
internal const val ASKED_ADD_EXTERNAL_FILES_PROPERTY = "ASKED_ADD_EXTERNAL_FILES" //NON-NLS
private val LOG = logger<ExternallyAddedFilesProcessorImpl>()
/**
* Extend [VcsVFSListener] to automatically add/propose to add into VCS files that were created not by IDE (externally created).
*/
internal class ExternallyAddedFilesProcessorImpl(project: Project,
private val parentDisposable: Disposable,
private val vcs: AbstractVcs,
private val addChosenFiles: (Collection<VirtualFile>) -> Unit)
: FilesProcessorWithNotificationImpl(project, parentDisposable), FilesProcessor, AsyncVfsEventsListener, ChangeListListener {
private val UNPROCESSED_FILES_LOCK = ReentrantReadWriteLock()
private val queue = QueueProcessor<Collection<VirtualFile>> { files -> processFiles(files) }
private val unprocessedFiles = mutableSetOf<VirtualFile>()
private val vcsManager = ProjectLevelVcsManager.getInstance(project)
private val vcsIgnoreManager = VcsIgnoreManager.getInstance(project)
fun install() {
runReadAction {
if (!project.isDisposed) {
project.messageBus.connect(parentDisposable).subscribe(ChangeListListener.TOPIC, this)
AsyncVfsEventsPostProcessor.getInstance().addListener(this, this)
}
}
}
override fun unchangedFileStatusChanged(upToDate: Boolean) {
if (!upToDate) return
if (!needProcessExternalFiles()) return
val files: Set<VirtualFile>
UNPROCESSED_FILES_LOCK.write {
files = unprocessedFiles.toHashSet()
unprocessedFiles.clear()
}
if (files.isEmpty()) return
if (needDoForCurrentProject()) {
LOG.debug("Add external files to ${vcs.displayName} silently ", files)
addChosenFiles(doFilterFiles(files))
}
else {
LOG.debug("Process external files and prompt to add if needed to ${vcs.displayName} ", files)
queue.add(files)
}
}
override fun filesChanged(events: List<VFileEvent>) {
if (!needProcessExternalFiles()) return
LOG.debug("Got events", events)
val configDir = project.getProjectConfigDir()
val externallyAddedFiles =
events.asSequence()
.filter {
it.isFromRefresh &&
it is VFileCreateEvent &&
!isProjectConfigDirOrUnderIt(configDir, it.parent)
}
.mapNotNull(VFileEvent::getFile)
.toList()
if (externallyAddedFiles.isEmpty()) return
LOG.debug("Got external files from VFS events", externallyAddedFiles)
UNPROCESSED_FILES_LOCK.write {
unprocessedFiles.addAll(externallyAddedFiles)
}
}
private fun doNothingSilently() = vcsManager.getStandardConfirmation(ADD, vcs).value == DO_NOTHING_SILENTLY
private fun needProcessExternalFiles(): Boolean {
if (doNothingSilently()) return false
if (!Registry.`is`("vcs.process.externally.added.files")) return false
return true
}
override fun dispose() {
super.dispose()
queue.clear()
UNPROCESSED_FILES_LOCK.write {
unprocessedFiles.clear()
}
}
override val notificationDisplayId: String = VcsNotificationIdsHolder.EXTERNALLY_ADDED_FILES
override val askedBeforeProperty = ASKED_ADD_EXTERNAL_FILES_PROPERTY
override val doForCurrentProjectProperty: String get() = throw UnsupportedOperationException() // usages overridden
override val showActionText: String = VcsBundle.message("external.files.add.notification.action.view")
override val forCurrentProjectActionText: String = VcsBundle.message("external.files.add.notification.action.add")
override val muteActionText: String = VcsBundle.message("external.files.add.notification.action.mute")
override val viewFilesDialogTitle: String? = VcsBundle.message("external.files.add.view.dialog.title", vcs.displayName)
override fun notificationTitle() = ""
override fun notificationMessage(): String = VcsBundle.message("external.files.add.notification.message", vcs.displayName)
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
addChosenFiles(files)
}
override fun setForCurrentProject(isEnabled: Boolean) {
if (isEnabled) vcsManager.getStandardConfirmation(ADD, vcs).value = DO_ACTION_SILENTLY
VcsConfiguration.getInstance(project).ADD_EXTERNAL_FILES_SILENTLY = isEnabled
}
override fun needDoForCurrentProject() =
vcsManager.getStandardConfirmation(ADD, vcs).value == DO_ACTION_SILENTLY
&& VcsConfiguration.getInstance(project).ADD_EXTERNAL_FILES_SILENTLY
override fun doFilterFiles(files: Collection<VirtualFile>): Collection<VirtualFile> {
val parents = files.toHashSet()
return ChangeListManagerImpl.getInstanceImpl(project).unversionedFiles
.asSequence()
.filterNot(vcsIgnoreManager::isPotentiallyIgnoredFile)
.filter { isUnder(parents, it) }
.toSet()
}
private fun isUnder(parents: Set<VirtualFile>, child: VirtualFile) = generateSequence(child) { it.parent }.any { it in parents }
private fun isProjectConfigDirOrUnderIt(configDir: VirtualFile?, file: VirtualFile) =
configDir != null && VfsUtilCore.isAncestor(configDir, file, false)
private fun Project.getProjectConfigDir(): VirtualFile? {
if (!isDirectoryBased || isDefault) return null
val projectConfigDir = stateStore.directoryStorePath?.let(LocalFileSystem.getInstance()::findFileByNioFile)
if (projectConfigDir == null) {
LOG.warn("Cannot find project config directory for non-default and non-directory based project ${name}")
}
return projectConfigDir
}
@TestOnly
fun waitForEventsProcessedInTestMode() {
assert(ApplicationManager.getApplication().isUnitTestMode)
queue.waitFor()
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/ExternallyAddedFilesProcessorImpl.kt | 2665078425 |
package com.hadihariri.leanpub
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
/**
* Created by hadihariri on 23/01/16.
*/
class PublishAction: AnAction() {
override fun actionPerformed(actionEvent: AnActionEvent) {
val leanpub = LeanpubSettingsProvider.create(actionEvent.project!!)
val leanpubApi = LeanpubAPI()
val response = leanpubApi.requestPublish(leanpub.apikey, leanpub.slug)
displayBalloon(actionEvent.project!!, response.message, response.isError)
}
}
| src/main/kotlin/com/hadihariri/leanpub/PublishAction.kt | 1814918972 |
package alraune
import vgrechka.*
object StorikanPublic {
val uploadUrlPath = "/upload"
val downloadUrlPath = "/download"
val uploadMethod = "POST"
val downloadMethod = "GET"
object getParam {
val fileName by myName()
val simulateStatus by myName()
val simulateMessage by myName()
}
}
| alraune/alraune/src/main/java/alraune/StorikanPublic.kt | 4232460548 |
fun f(a: Int) {
if (a > 0) {
<lineMarker descr="Recursive call">f</lineMarker>(a - 1)
}
} | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/recursiveCall/simple.kt | 3454084957 |
// 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.find.impl
import com.intellij.find.FindBundle
import com.intellij.find.FindManager
import com.intellij.find.FindModel
import com.intellij.find.FindSettings
import com.intellij.find.impl.TextSearchRightActionAction.*
import com.intellij.ide.actions.GotoActionBase
import com.intellij.ide.actions.SearchEverywhereBaseAction
import com.intellij.ide.actions.SearchEverywhereClassifier
import com.intellij.ide.actions.searcheverywhere.*
import com.intellij.ide.actions.searcheverywhere.AbstractGotoSEContributor.createContext
import com.intellij.ide.util.RunOnceUtil
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo
import com.intellij.ide.util.scopeChooser.ScopeDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.observable.properties.AtomicBooleanProperty
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Key
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.reference.SoftReference
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageViewPresentation
import com.intellij.util.CommonProcessors
import com.intellij.util.PlatformUtils
import com.intellij.util.Processor
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.JBIterable
import java.lang.ref.Reference
import java.lang.ref.WeakReference
import javax.swing.ListCellRenderer
internal class TextSearchContributor(
val event: AnActionEvent
) : WeightedSearchEverywhereContributor<SearchEverywhereItem>,
SearchFieldActionsContributor,
PossibleSlowContributor,
DumbAware, ScopeSupporting, Disposable {
private val project = event.getRequiredData(CommonDataKeys.PROJECT)
private val model = FindManager.getInstance(project).findInProjectModel
private var everywhereScope = getEverywhereScope()
private var projectScope: GlobalSearchScope?
private var selectedScopeDescriptor: ScopeDescriptor
private var psiContext = getPsiContext()
private lateinit var onDispose: () -> Unit
init {
val scopes = createScopes()
projectScope = getProjectScope(scopes)
selectedScopeDescriptor = getInitialSelectedScope(scopes)
}
private fun getPsiContext() = GotoActionBase.getPsiContext(event)?.let {
SmartPointerManager.getInstance(project).createSmartPsiElementPointer(it)
}
private fun getEverywhereScope() =
SearchEverywhereClassifier.EP_Manager.getEverywhereScope(project) ?: GlobalSearchScope.everythingScope(project)
private fun getProjectScope(descriptors: List<ScopeDescriptor>): GlobalSearchScope? {
SearchEverywhereClassifier.EP_Manager.getProjectScope(project)?.let { return it }
GlobalSearchScope.projectScope(project).takeIf { it != everywhereScope }?.let { return it }
val secondScope = JBIterable.from(descriptors).filter { !it.scopeEquals(everywhereScope) && !it.scopeEquals(null) }.first()
return if (secondScope != null) secondScope.scope as GlobalSearchScope? else everywhereScope
}
override fun getSearchProviderId() = ID
override fun getGroupName() = FindBundle.message("search.everywhere.group.name")
override fun getSortWeight() = 1500
override fun showInFindResults() = enabled()
override fun isShownInSeparateTab() = true
override fun fetchWeightedElements(pattern: String,
indicator: ProgressIndicator,
consumer: Processor<in FoundItemDescriptor<SearchEverywhereItem>>) {
FindModel.initStringToFind(model, pattern)
val presentation = FindInProjectUtil.setupProcessPresentation(project, UsageViewPresentation())
val scope = GlobalSearchScope.projectScope(project) // TODO use scope from model ?
val recentItemRef = ThreadLocal<Reference<SearchEverywhereItem>>()
FindInProjectUtil.findUsages(model, project, indicator, presentation, emptySet()) {
val usage = UsageInfo2UsageAdapter.CONVERTER.`fun`(it) as UsageInfo2UsageAdapter
indicator.checkCanceled()
val recentItem = SoftReference.dereference(recentItemRef.get())
val newItem = if (recentItem != null && recentItem.usage.merge(usage)) {
// recompute merged presentation
recentItem.withPresentation(usagePresentation(project, scope, recentItem.usage))
}
else {
SearchEverywhereItem(usage, usagePresentation(project, scope, usage)).also {
if (!consumer.process(FoundItemDescriptor(it, 0))) return@findUsages false
}
}
recentItemRef.set(WeakReference(newItem))
true
}
}
override fun getElementsRenderer(): ListCellRenderer<in SearchEverywhereItem> = TextSearchRenderer()
override fun processSelectedItem(selected: SearchEverywhereItem, modifiers: Int, searchText: String): Boolean {
// TODO async navigation
val info = selected.usage
if (!info.canNavigate()) return false
info.navigate(true)
return true
}
override fun getActions(onChanged: Runnable): List<AnAction> =
listOf(ScopeAction { onChanged.run() }, JComboboxAction(project) { onChanged.run() }.also { onDispose = it.saveMask })
override fun createRightActions(onChanged: Runnable): List<TextSearchRightActionAction> {
lateinit var regexp: AtomicBooleanProperty
val word = AtomicBooleanProperty(model.isWholeWordsOnly).apply { afterChange { model.isWholeWordsOnly = it; if (it) regexp.set(false) } }
val case = AtomicBooleanProperty(model.isCaseSensitive).apply { afterChange { model.isCaseSensitive = it } }
regexp = AtomicBooleanProperty(model.isRegularExpressions).apply { afterChange { model.isRegularExpressions = it; if (it) word.set(false) } }
return listOf(CaseSensitiveAction(case, onChanged), WordAction(word, onChanged), RegexpAction(regexp, onChanged))
}
override fun getDataForItem(element: SearchEverywhereItem, dataId: String): Any? {
if (CommonDataKeys.PSI_ELEMENT.`is`(dataId)) {
return element.usage.element
}
return null
}
private fun getInitialSelectedScope(scopeDescriptors: List<ScopeDescriptor>): ScopeDescriptor {
val scope = SE_TEXT_SELECTED_SCOPE.get(project) ?: return ScopeDescriptor(projectScope)
return scopeDescriptors.find { scope == it.displayName && !it.scopeEquals(null) } ?: ScopeDescriptor(projectScope)
}
private fun setSelectedScope(scope: ScopeDescriptor) {
selectedScopeDescriptor = scope
SE_TEXT_SELECTED_SCOPE.set(project, if (scope.scopeEquals(everywhereScope) || scope.scopeEquals(projectScope)) null else scope.displayName)
FindSettings.getInstance().customScope = selectedScopeDescriptor.scope?.displayName
model.customScopeName = selectedScopeDescriptor.scope?.displayName
model.customScope = selectedScopeDescriptor.scope
model.isCustomScope = true
}
private fun createScopes() = mutableListOf<ScopeDescriptor>().also {
ScopeChooserCombo.processScopes(project, createContext(project, psiContext),
ScopeChooserCombo.OPT_LIBRARIES or ScopeChooserCombo.OPT_EMPTY_SCOPES,
CommonProcessors.CollectProcessor(it))
}
override fun getScope() = selectedScopeDescriptor
override fun getSupportedScopes() = createScopes()
override fun setScope(scope: ScopeDescriptor) {
setSelectedScope(scope)
}
private inner class ScopeAction(val onChanged: () -> Unit) : ScopeChooserAction() {
override fun onScopeSelected(descriptor: ScopeDescriptor) {
setSelectedScope(descriptor)
onChanged()
}
override fun getSelectedScope() = selectedScopeDescriptor
override fun isEverywhere() = selectedScopeDescriptor.scopeEquals(everywhereScope)
override fun processScopes(processor: Processor<in ScopeDescriptor>) = ContainerUtil.process(createScopes(), processor)
override fun onProjectScopeToggled() {
isEverywhere = !selectedScopeDescriptor.scopeEquals(everywhereScope)
}
override fun setEverywhere(everywhere: Boolean) {
setSelectedScope(ScopeDescriptor(if (everywhere) everywhereScope else projectScope))
onChanged()
}
override fun canToggleEverywhere() = if (everywhereScope == projectScope) false
else selectedScopeDescriptor.scopeEquals(everywhereScope) || selectedScopeDescriptor.scopeEquals(projectScope)
}
override fun dispose() {
if (this::onDispose.isInitialized) onDispose()
}
companion object {
private const val ID = "TextSearchContributor"
private const val ADVANCED_OPTION_ID = "se.text.search"
private val SE_TEXT_SELECTED_SCOPE = Key.create<String>("SE_TEXT_SELECTED_SCOPE")
private fun enabled() = AdvancedSettings.getBoolean(ADVANCED_OPTION_ID)
class Factory : SearchEverywhereContributorFactory<SearchEverywhereItem> {
override fun isAvailable() = enabled()
override fun createContributor(event: AnActionEvent) = TextSearchContributor(event)
}
class TextSearchAction : SearchEverywhereBaseAction(), DumbAware {
override fun update(event: AnActionEvent) {
super.update(event)
event.presentation.isEnabledAndVisible = enabled()
}
override fun actionPerformed(e: AnActionEvent) {
showInSearchEverywherePopup(ID, e, true, true)
}
}
class TextSearchActivity : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
RunOnceUtil.runOnceForApp(ADVANCED_OPTION_ID) {
AdvancedSettings.setBoolean(ADVANCED_OPTION_ID, PlatformUtils.isRider())
}
}
}
}
} | platform/lang-impl/src/com/intellij/find/impl/TextSearchContributor.kt | 4150863671 |
package com.intellij.cce.visitor
import com.intellij.cce.core.CodeFragment
import com.intellij.cce.core.Language
import com.intellij.cce.processor.EvaluationRootProcessor
import com.intellij.cce.util.FilesHelper
import com.intellij.cce.util.text
import com.intellij.cce.visitor.exceptions.PsiConverterException
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
open class CodeFragmentFromPsiBuilder(private val project: Project, val language: Language) : CodeFragmentBuilder() {
private val dumbService: DumbService = DumbService.getInstance(project)
open fun getVisitors(): List<CompletionEvaluationVisitor> = CompletionEvaluationVisitor.EP_NAME.extensions.toList()
override fun build(file: VirtualFile, rootProcessor: EvaluationRootProcessor): CodeFragment {
val psi = dumbService.runReadActionInSmartMode<PsiFile> {
PsiManager.getInstance(project).findFile(file)
} ?: throw PsiConverterException("Cannot get PSI of file ${file.path}")
val filePath = FilesHelper.getRelativeToProjectPath(project, file.path)
val visitors = getVisitors().filter { it.language == language }
if (visitors.isEmpty()) throw IllegalStateException("No suitable visitors")
if (visitors.size > 1) throw IllegalStateException("More than 1 suitable visitors")
val fileTokens = getFileTokens(visitors.first(), psi)
fileTokens.path = filePath
fileTokens.text = file.text()
return findRoot(fileTokens, rootProcessor)
}
private fun getFileTokens(visitor: CompletionEvaluationVisitor, psi: PsiElement): CodeFragment {
if (visitor !is PsiElementVisitor) throw IllegalArgumentException("Visitor must implement PsiElementVisitor")
dumbService.runReadActionInSmartMode {
assert(!dumbService.isDumb) { "Generating actions during indexing." }
psi.accept(visitor)
}
return visitor.getFile()
}
}
| plugins/evaluation-plugin/languages/src/com/intellij/cce/visitor/CodeFragmentFromPsiBuilder.kt | 2656046904 |
// PROBLEM: none
// WITH_STDLIB
// COMPILER_ARGUMENTS: -Xopt-in=kotlin.RequiresOptIn
@RequiresOptIn
annotation class Marker
abstract class Base {
@Marker
abstract val foo: Int
}
class Derived : Base() {
@OptIn(<caret>Marker::class)
override val foo: Int = 5
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/unnecessaryOptInAnnotation/necessaryOverrideProperty1.kt | 3399978194 |
package a
fun bar(s: String) {
val t: X = X(A()) { s }
} | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveInnerToTop/moveNestedClassToTopLevelInTheSamePackageAndAddOuterInstanceWithLambda/after/a/specificImport.kt | 1528876203 |
package com.kenyee.teamcity.util
import org.jetbrains.teamcity.rest.BuildLocator
import org.jetbrains.teamcity.rest.BuildStatus
import org.jetbrains.teamcity.rest.TeamCityInstance
import org.slf4j.LoggerFactory
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.SafeConstructor
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStreamWriter
import java.net.Socket
import java.util.*
/*
* Main graphite polling loop
*
* Data sent to graphite:
* <prefix>.queuesize
* <prefix>.build.<config>.queuetime
* <prefix>.build.<config>.buildtime
*/
class GraphiteStats {
fun someLibraryMethod(): Boolean {
return true
}
companion object {
private val LOG = LoggerFactory.getLogger("GraphiteStats")
@JvmStatic fun main(args: Array<String>) {
val configPath = if (args.size > 0) args[0] else "config.yml"
val configInfo = loadConfig(configPath)
if (configInfo == null) {
println("ERROR - Configuration error!")
System.exit(1);
}
runLoop(configInfo!!)
}
fun runLoop(configInfo: ConfigInfo) {
val tcServer = TeamCityInstance.httpAuth(configInfo.teamcityServer,
configInfo.username.toString(), configInfo.password.toString())
var lastPollTime = Date()
while (true) {
try {
val queuedBuilds = tcServer.queuedBuilds().list()
LOG.debug("Queue length: ${queuedBuilds.size}")
sendGraphiteStat(configInfo, configInfo.getQueueLengthMetricName(), queuedBuilds.size.toString())
if (LOG.isDebugEnabled()) {
queuedBuilds.map({ it -> LOG.debug(it.toString()) })
}
val successfulBuildsLocator = (tcServer.builds()
.withStatus(BuildStatus.SUCCESS)
.sinceDate(lastPollTime)
.limitResults(configInfo.maxBuilds))
if (successfulBuildsLocator is BuildLocator) {
val successfulBuilds = successfulBuildsLocator.list();
LOG.debug("Successful Build count: ${successfulBuilds.size}")
successfulBuilds
.map({
if (it.fetchFinishDate() > lastPollTime) {
lastPollTime = it.fetchFinishDate()
}
})
successfulBuilds
.filter({ it ->
var includeBuild = true
for (exclusion in configInfo.excludeProjects) {
if (exclusion.toRegex().matches(it.buildConfigurationId)) {
includeBuild = false
break
}
}
includeBuild
})
.map({
val buildTime = (it.fetchFinishDate().time - it.fetchStartDate().time) / 1000
val queueTime = (it.fetchStartDate().time - it.fetchQueuedDate().time) / 1000
LOG.debug("$it $buildTime $queueTime")
sendGraphiteStat(configInfo, configInfo.getBuildRunTimeMetricName(it.buildConfigurationId), buildTime.toString())
sendGraphiteStat(configInfo, configInfo.getBuildWaitTimeMetricName(it.buildConfigurationId), queueTime.toString())
});
}
} catch (e: Exception) {
LOG.error("Error reading from Teamcity: ", e)
} catch (e: java.lang.Error) {
LOG.error("Error connecting to Teamcity: ", e)
}
Thread.sleep(configInfo.pollPeriodSecs.times(1000).toLong());
}
}
fun loadConfig(configPath: String): ConfigInfo? {
val configFile = File(configPath);
println("Loading configuration from: " + configFile.absolutePath)
if (!configFile.exists()) {
println("ERROR - Configuration file not found!")
return null
}
val yaml = Yaml(SafeConstructor())
val configData = yaml.load(FileInputStream(configFile))
if (configData is Map<*, *>) {
val graphiteServer = configData.get("graphite").toString()
if (graphiteServer.isNullOrEmpty()) {
println("ERROR - Graphite server must be specified")
}
val prefix = configData.get("prefix").toString()
val teamcityServer = configData.get("teamcity").toString()
if (teamcityServer.isNullOrEmpty()) {
println("ERROR - Teamcity server URL must be specified")
}
val username = configData.get("username").toString()
val password = configData.get("password").toString()
var pollPeriodSecs = configData.get("pollsecs") as Int?
if (pollPeriodSecs == null) {
println("Poll period not specified...defaulting to 10sec polling")
pollPeriodSecs = 10
}
var maxBuilds = configData.get("maxbuilds") as Int?
if (maxBuilds == null) {
println("Max build limit for period not specified...defaulting to 100")
maxBuilds = 10
}
@Suppress("UNCHECKED_CAST")
var exclusions = configData.get("exclude") as List<String>?
if (exclusions == null) {
exclusions = ArrayList<String>()
}
val configInfo = ConfigInfo(graphiteServer, prefix, teamcityServer, username, password,
pollPeriodSecs, maxBuilds, exclusions)
return configInfo
}
return null
}
fun sendGraphiteStat(configInfo: ConfigInfo, metricName: String, metricValue: String) {
val message = metricName.formatMetric(metricValue)
val socket = Socket(configInfo.graphiteServer, 2003)
val writer = OutputStreamWriter(socket.getOutputStream())
try {
writer.write(message);
writer.flush();
} catch (e: IOException) {
LOG.error("Error writing to graphite: ", e)
}
}
fun String.formatMetric(metricValue: String): String {
return this + " " + metricValue + " " + Math.round(System.currentTimeMillis() / 1000.0) + "\n";
}
}
data class ConfigInfo(
val graphiteServer: String,
val prefix: String?,
val teamcityServer : String,
val username : String?,
val password : String?,
val pollPeriodSecs : Int,
val maxBuilds : Int,
val excludeProjects : List<String>) {
fun getQueueLengthMetricName(): String {
return prefix + ".queuesize"
}
fun getBuildWaitTimeMetricName(buildConfigurationId: String): String {
return prefix + ".build." + buildConfigurationId + ".queuetime"
}
fun getBuildRunTimeMetricName(buildConfigurationId: String): String {
return prefix + ".build." + buildConfigurationId + ".buildtime"
}
}
}
| src/main/kotlin/com/kenyee/teamcity/util/GraphiteStats.kt | 818677779 |
// PROBLEM: none
// WITH_STDLIB
val x = sequenceOf(System.getProperty("")).<caret>filterIsInstance<String>() | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnCollection/FilterIsForFlexibleOnSequence.kt | 2723323346 |
package test
actual class C {
actual var foo: Int
get() = 1
set(value) {}
actual var bar: Int
get() = 1
set(value) {}
}
fun test(c: C) {
c.foo
c.foo = 1
c.bar
c.bar = 1
} | plugins/kotlin/idea/tests/testData/refactoring/renameMultiModule/headersAndImplsByImplClassMemberVal/before/JVM/src/test/test.kt | 526429221 |
package net.benwoodworth.fastcraft.util
data class Expr(val expression: String) {
fun toRegex(): Regex {
if (expression.length >= 2 &&
expression.startsWith('/') &&
expression.endsWith('/')
) {
return Regex(expression.substring(1 until expression.lastIndex))
}
return Regex.escape(expression)
.replace("*", """\E.*\Q""")
.let { Regex("^$it$") }
}
}
| fastcraft-core/src/main/kotlin/net/benwoodworth/fastcraft/util/Expr.kt | 1322517977 |
package xyz.nulldev.ts.sandbox
import android.content.Context
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.conf.global
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.singleton
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import xyz.nulldev.androidcompat.androidimpl.CustomContext
import xyz.nulldev.androidcompat.androidimpl.FakePackageManager
import xyz.nulldev.androidcompat.config.ApplicationInfoConfigModule
import xyz.nulldev.androidcompat.config.FilesConfigModule
import xyz.nulldev.androidcompat.config.SystemConfigModule
import xyz.nulldev.androidcompat.info.ApplicationInfoImpl
import xyz.nulldev.androidcompat.io.AndroidFiles
import xyz.nulldev.androidcompat.pm.PackageController
import xyz.nulldev.ts.config.ConfigManager
import xyz.nulldev.ts.config.ServerConfig
import java.io.Closeable
import java.io.File
/**
* Sandbox used to isolate different contexts from each other
*/
class Sandbox(configFolder: File) : Closeable {
val configManager = SandboxedConfigManager(configFolder.absolutePath).apply {
// Re-register config modules
registerModules(
ServerConfig.register(this.config),
FilesConfigModule.register(this.config),
ApplicationInfoConfigModule.register(this.config),
SystemConfigModule.register(this.config)
)
}
val kodein by lazy {
Kodein {
extend(Kodein.global)
//Define sandboxed components
bind<ConfigManager>(overrides = true) with singleton { configManager }
bind<AndroidFiles>(overrides = true) with singleton { AndroidFiles(configManager) }
bind<ApplicationInfoImpl>(overrides = true) with singleton { ApplicationInfoImpl(this) }
bind<FakePackageManager>(overrides = true) with singleton { FakePackageManager() }
bind<PackageController>(overrides = true) with singleton { PackageController() }
bind<CustomContext>(overrides = true) with singleton { CustomContext(this) }
bind<Context>(overrides = true) with singleton { instance<CustomContext>() }
bind<DatabaseHelper>(overrides = true) with singleton { DatabaseHelper(instance()) }
}
}
/**
* Clean-up sandbox
*/
override fun close() {
kodein.instance<DatabaseHelper>().db.close()
}
} | TachiServer/src/main/java/xyz/nulldev/ts/sandbox/Sandbox.kt | 4231358203 |
package com.sksamuel.kotest.property.arbitrary
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.ints.shouldBeBetween
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.property.Arb
import io.kotest.property.arbitrary.bigInt
import io.kotest.property.checkAll
import java.math.BigInteger
class BigIntArbTest : ShouldSpec({
should("Generate different big ints") {
val generated = mutableSetOf<BigInteger>()
Arb.bigInt(100).checkAll { generated += it }
generated.size shouldBeGreaterThan 500
}
should("Generate all big ints with the same probability") {
val generated = hashMapOf<BigInteger, Int>()
Arb.bigInt(4, 4).checkAll(100_000) {
generated.merge(it, 1) { a, b -> a + b }
}
generated.forEach {
// Each value should be generated 100_000/2^4 times, so ~6250
it.value.shouldBeBetween(5800, 6600)
}
}
})
| kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/arbitrary/BigIntArbTest.kt | 3760027759 |
package com.sksamuel.kotest.engine.active
import io.kotest.assertions.fail
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.core.spec.style.WordSpec
class BangDisableWordSpec : WordSpec({
"using the bang symbol" should {
"!disable this test" {
fail("boom")
}
}
})
class BangDisableBehaviorSpec : BehaviorSpec({
given("given a test") {
`when`("when using bang") {
then("!test should be disabled") {
fail("boom")
}
}
}
given("!given a disabled given") {
error("boom")
}
})
| kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/active/BangDisableWord.kt | 1947512336 |
/*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.
*/
import big.*
import com.jtransc.BuildBackend
import com.jtransc.gen.js.JsGenerator
import com.jtransc.gen.js.JsTarget
import com.jtransc.plugin.service.ConfigServiceLoader
import issues.Issue100Double
import issues.Issue105
import issues.Issue135
import issues.issue130.Issue130
import issues.issue146.Issue146
import issues.issue158.Issue158
import javatest.ExtendedCharsetsTest
import javatest.MemberCollisionsTest
import javatest.MessageDigestTest
import javatest.misc.BenchmarkTest
import javatest.misc.TryFinallyCheck
import javatest.net.URLEncoderDecoderTest
import javatest.utils.KotlinInheritanceTest
import jtransc.ExtraKeywordsTest
import jtransc.ExtraRefsTest
import jtransc.ProcessTest
import jtransc.bug.JTranscBug110
import jtransc.bug.JTranscBug127
import jtransc.java8.Java8Test
import jtransc.java8.Java8Test2
import jtransc.jtransc.js.ScriptEngineTest
import jtransc.jtransc.nativ.JTranscJsNativeMixedTest
import jtransc.micro.MicroHelloWorld
import jtransc.micro.NanoHelloWorldTest
import jtransc.ref.MethodBodyReferencesTest
import jtransc.staticinit.StaticInitTest
import jtransc.staticinit.StaticInitTest2
import org.junit.Assert
import org.junit.Ignore
import org.junit.Test
import testservice.test.ServiceLoaderTest
import testservice.test.TestServiceJs2
class JsTest : _Base() {
override val DEFAULT_TARGET = JsTarget()
//override val TREESHAKING_TRACE = true
@Test fun testBig() = testClass(Params(clazz = BigTest::class.java, minimize = false, log = false))
@Test fun testBigMin() = testClass(Params(clazz = BigTest::class.java, minimize = true, log = false))
@Test fun testBigIO() = testClass(Params(clazz = BigIOTest::class.java, minimize = true, log = false, treeShaking = true))
@Test fun testProcess() = testClass(Params(clazz = ProcessTest::class.java, minimize = true, log = false, treeShaking = true))
@Test fun testJTranscBug110() = testClass(Params(clazz = JTranscBug110::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testScriptEngine() = testClass(Params(clazz = ScriptEngineTest::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testJavaEightJs() = testClass(Params(clazz = Java8Test::class.java, minimize = false, log = false))
@Test fun testNanoHelloWorld() = testClass(Params(clazz = NanoHelloWorldTest::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testStaticInitIssue135() = testClass(Params(clazz = Issue135::class.java, minimize = false, log = false, treeShaking = true))
@Ignore("Already included in BigTest")
@Test fun testJTranscBug127() = testClass(Params(clazz = JTranscBug127::class.java, minimize = false, log = false, treeShaking = true))
@Ignore("Already included in BigTest")
@Test fun testDescentIssue130() = testClass(Params(clazz = Issue130::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testNanoHelloWorldShouldReferenceGetMethods() {
val result = _action(Params(clazz = NanoHelloWorldTest::class.java, minimize = false, log = false, treeShaking = true), run = false)
val generator = result.generator as JsGenerator
val outputFile = generator.jsOutputFile
val output = outputFile.readString()
Assert.assertEquals(false, output.contains("getMethod"))
println("OutputSize: ${outputFile.size}")
Assert.assertEquals(true, outputFile.size < 220 * 1024) // Size should be < 220 KB
}
@Test fun testMicroHelloWorld() = testClass(Params(clazz = MicroHelloWorld::class.java, minimize = true, log = false, treeShaking = true))
@Test fun testKotlinInheritanceTestJs() = testClass(Params(clazz = KotlinInheritanceTest::class.java, minimize = false, log = false))
@Test fun testTwoJavaEightTwoJs() = testClass(Params(clazz = Java8Test2::class.java, minimize = false, log = false))
@Test fun testURLEncoderDecoder() = testClass(Params(clazz = URLEncoderDecoderTest::class.java, minimize = false, log = false, treeShaking = true))
//@Test fun testIssue100Double() = testClass<Issue100Double>(minimize = true, log = true, treeShaking = true, debug = true)
@Test fun testIssue100Double() = testClass(Params(clazz = Issue100Double::class.java, minimize = true, log = false, treeShaking = true))
@Test fun testIssue105() = testClass(Params(clazz = Issue105::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testExtendedCharsets() = testClass(Params(clazz = ExtendedCharsetsTest::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testMessageDigestTest() = testClass(Params(clazz = MessageDigestTest::class.java, minimize = false, log = false, treeShaking = true))
//@Test fun testMicroHelloWorldAsm2() = testClass<MicroHelloWorld>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2)
//@Test fun testMicroHelloWorldAsm2() = testClass<MicroHelloWorld>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2)
//@Test fun testMicroHelloWorldAsm2() = testClass<HelloWorldTest>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2)
//@Test fun testMicroHelloWorldAsm2() = testClass<BenchmarkTest>(minimize = false, log = false, treeShaking = true, backend = BuildBackend.ASM2)
@Test fun testMicroStaticInitTest() = testClass(Params(clazz = StaticInitTest::class.java, minimize = false, log = false, backend = BuildBackend.ASM, treeShaking = true))
@Test fun testMicroStaticInitTest2() = testClass(Params(clazz = StaticInitTest2::class.java, minimize = false, log = false, backend = BuildBackend.ASM, treeShaking = true))
@Test fun testHelloWorld() = testClass(Params(clazz = HelloWorldTest::class.java, minimize = false, log = false))
@Test fun testBenchmarkTest() = testClass(Params(clazz = BenchmarkTest::class.java, minimize = false, log = false))
@Test fun testServiceLoaderTest() = testNativeClass("""
TestServiceImpl1.test:ss
TestServiceJs10
""", Params(clazz = ServiceLoaderTest::class.java, minimize = false, configureInjector = {
mapInstance(ConfigServiceLoader(
classesToSkip = listOf(
TestServiceJs2::class.java.name
)
))
}))
@Test fun nativeJsTest() = testNativeClass("""
17
-333
Services:
TestServiceImpl1.test:ss
/Services:
2
hello
world
10
jtransc_jtransc_JTranscInternalNamesTest
main([Ljava/lang/String;)V
___hello
Error !(10 < 10)
ok
JTranscReinterpretArrays:
MethodBodyReferencesTestJs:true
MethodBodyReferencesTestCpp:false
MethodBodyReferencesTestJvm:false
OK!
MixedJsKotlin.main[1]
MixedJsKotlin.main[2]
[ 1, 2, 3 ]
<Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f>
{"a":10,"b":"c","c":[1,2,3]}
.txt
1
2
0
true
1234567
1
hello
777
999
21
HELLO WORLD1demo
HELLO WORLD2test
Timeout!
""", Params(clazz = JTranscJsNativeMixedTest::class.java, minimize = false, treeShaking = true))
@Test fun referencesTest() = testNativeClass("""
MethodBodyReferencesTestJs:true
MethodBodyReferencesTestCpp:false
MethodBodyReferencesTestJvm:false
""", Params(clazz = MethodBodyReferencesTest::class.java, minimize = true, treeShaking = false))
@Test fun extraKeywordsJs() = testNativeClass("""
1
2
3
4
5
6
7
8
9
""", Params(clazz = ExtraKeywordsTest::class.java, minimize = true))
@Test fun extraRefsTest() = testNativeClass("""
OK
""", Params(clazz = ExtraRefsTest::class.java, minimize = true))
@Test fun testNumberFormatTest2() = testClass(Params(clazz = NumberFormatTest2::class.java, minimize = false, log = false))
@Test fun testTryFinallyCheck() = testClass(Params(clazz = TryFinallyCheck::class.java, minimize = false, log = false))
@Test fun testMemberCollisionsTest() = testClass(Params(clazz = MemberCollisionsTest::class.java, minimize = false, log = false))
@Test fun testAsyncIO() = testClass(Params(clazz = AsyncIOTest::class.java, minimize = false, log = false, treeShaking = true))
@Ignore("Must fix #146")
@Test fun testIssue146() = testClass(Params(clazz = Issue146::class.java, minimize = false, log = false, treeShaking = true))
@Test fun testIssue158() = testClass(Params(clazz = Issue158::class.java, minimize = false, log = false, treeShaking = true))
} | jtransc-main/test/JsTest.kt | 3475991654 |
package koma.gui.element.control
import javafx.scene.control.ListCell
import javafx.scene.control.ScrollBar
import javafx.scene.control.Skin
import koma.gui.element.control.skin.KVirtualFlow
import koma.gui.element.control.skin.ScrollBarSkin
import mu.KotlinLogging
import org.controlsfx.tools.Utils
private val logger = KotlinLogging.logger {}
/**
* This custom ScrollBar is used to map the increment & decrement features
* to pixel based scrolling rather than thumb/track based scrolling, if the
* "virtual" attribute is true.
*/
class KVirtualScrollBar<I, T>(
private val flow: KVirtualFlow<I, T>,
private val isVirtual: Boolean = true
) : ScrollBar()
where I: ListCell<T> {
override fun decrement() {
if (isVirtual) {
flow.scrollPixels(-10.0)
} else {
super.decrement()
}
}
override fun increment() {
if (isVirtual) {
flow.scrollPixels(10.0)
} else {
super.increment()
}
}
fun turnPageByPos(pos: Double) {
val oldValue = flow.getPosition()
val newValue = (max - min) * Utils.clamp(0.0, pos, 1.0) + min
if (newValue < oldValue) {
pageUp()
} else if (newValue > oldValue) {
pageDown()
}
}
fun pageUp(){
val cell = flow.firstVisibleCell ?: return
flow.scrollToBottom(cell)
}
fun pageDown(){
val cell = flow.lastVisibleCell ?: return
flow.scrollToTop(cell)
}
fun end() {
val s = flow.itemsSize()
if (s == null){
logger.error { "trying to get to the bottom of an empty list" }
return
}
flow.scrollToTop( s - 1)
}
override fun createDefaultSkin(): Skin<*> {
return ScrollBarSkin(this)
}
}
| src/main/kotlin/koma/gui/element/control/KVirtualScrollBar.kt | 2334699653 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miditools
import com.example.android.miditools.EventScheduler.SchedulableEvent
import org.junit.Assert
import org.junit.Test
/**
* Unit Tests for the EventScheduler
*/
class TestEventScheduler {
@Test
fun testEventPool() {
val scheduler = EventScheduler()
val time1 = 723L
val event1 = SchedulableEvent(time1)
Assert.assertEquals("event time", time1, event1.timestamp)
Assert.assertEquals("empty event pool", null, scheduler.removeEventFromPool())
scheduler.addEventToPool(event1)
Assert.assertEquals("always leave one event in pool", null,
scheduler.removeEventFromPool())
val time2 = 9817L
val event2 = SchedulableEvent(time2)
scheduler.addEventToPool(event2)
Assert.assertEquals("first event in pool", event1, scheduler.removeEventFromPool())
Assert.assertEquals("always leave one event in pool", null,
scheduler.removeEventFromPool())
scheduler.addEventToPool(event1)
Assert.assertEquals("second event in pool", event2, scheduler.removeEventFromPool())
}
@Test
fun testSingleEvent() {
val scheduler = EventScheduler()
val time = 723L
val event = SchedulableEvent(time)
Assert.assertEquals("event time", time, event.timestamp)
scheduler.add(event)
Assert.assertEquals("too soon", null, scheduler.getNextEvent(time - 1))
Assert.assertEquals("right now", event, scheduler.getNextEvent(time))
}
@Test
fun testTwoEvents() {
val scheduler = EventScheduler()
val time1 = 723L
val event1 = SchedulableEvent(time1)
val time2 = 9817L
val event2 = SchedulableEvent(time2)
scheduler.add(event1)
scheduler.add(event2)
Assert.assertEquals("too soon", null, scheduler.getNextEvent(time1 - 1))
Assert.assertEquals("after 1", event1, scheduler.getNextEvent(time1 + 5))
Assert.assertEquals("too soon", null, scheduler.getNextEvent(time1 + 5))
Assert.assertEquals("after 2", event2, scheduler.getNextEvent(time2 + 7))
}
@Test
fun testReverseTwoEvents() {
val scheduler = EventScheduler()
val time1 = 723L
val event1 = SchedulableEvent(time1)
val time2 = 9817L
val event2 = SchedulableEvent(time2)
scheduler.add(event2)
scheduler.add(event1)
Assert.assertEquals("too soon", null, scheduler.getNextEvent(time1 - 1))
Assert.assertEquals("after 1", event1, scheduler.getNextEvent(time1 + 5))
Assert.assertEquals("too soon", null, scheduler.getNextEvent(time1 + 5))
Assert.assertEquals("after 2", event2, scheduler.getNextEvent(time2 + 7))
}
} | MidiTools/src/androidTest/java/com/example/android/miditools/TestEventScheduler.kt | 1656823602 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.micropython.run
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.actions.LazyRunConfigurationProducer
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.facet.FacetManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightVirtualFile
import com.jetbrains.micropython.settings.MicroPythonFacetType
import com.jetbrains.python.run.AbstractPythonRunConfiguration
/**
* @author Mikhail Golubev
*/
class MicroPythonRunConfigurationProducer : LazyRunConfigurationProducer<MicroPythonRunConfiguration>() {
override fun getConfigurationFactory(): ConfigurationFactory {
return MicroPythonConfigurationType.getInstance().factory
}
override fun isConfigurationFromContext(configuration: MicroPythonRunConfiguration, context: ConfigurationContext): Boolean {
val file = context.location?.virtualFile ?: return false
if (!facetEnabledForElement(file, context.project)) return false
if (file is LightVirtualFile) return false
return configuration.path == file.path
}
override fun setupConfigurationFromContext(configuration: MicroPythonRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>): Boolean {
val file = context.location?.virtualFile ?: return false
if (!facetEnabledForElement(file, context.project)) return false
configuration.path = file.path
configuration.setGeneratedName()
configuration.setModule(ModuleUtilCore.findModuleForFile(file, context.project))
return true
}
private fun facetEnabledForElement(virtualFile: VirtualFile, project: Project): Boolean {
val module = ModuleUtilCore.findModuleForFile(virtualFile, project) ?: return false
return FacetManager.getInstance(module)?.getFacetByType(MicroPythonFacetType.ID) != null
}
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext) =
other.configuration is AbstractPythonRunConfiguration<*>
}
| src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfigurationProducer.kt | 1850022162 |
/*
* Copyright 2018 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.tools.build.jetifier.core.rule
import com.android.tools.build.jetifier.core.type.JavaType
/**
* Contains all [RewriteRule]s.
*/
class RewriteRulesMap(val rewriteRules: List<RewriteRule>) {
companion object {
private const val TAG = "RewriteRulesMap"
val EMPTY = RewriteRulesMap(emptyList())
}
constructor(vararg rules: RewriteRule) : this(rules.toList())
val runtimeIgnoreRules = rewriteRules.filter { it.isRuntimeIgnoreRule() }.toSet()
/**
* Tries to rewrite the given given type using the rules. If
*/
fun rewriteType(type: JavaType): JavaType? {
// Try to find a rule
for (rule in rewriteRules) {
if (rule.isIgnoreRule()) {
continue
}
val typeRewriteResult = rule.apply(type)
if (typeRewriteResult.result == null) {
continue
}
return typeRewriteResult.result
}
return null
}
fun reverse(): RewriteRulesMap {
return RewriteRulesMap(rewriteRules
.filter { !it.isIgnoreRule() }
.map { it.reverse() }
.toList())
}
fun appendRules(rules: List<RewriteRule>): RewriteRulesMap {
return RewriteRulesMap(rewriteRules + rules)
}
fun toJson(): JsonData {
return JsonData(rewriteRules.map { it.toJson() }.toSet())
}
/**
* JSON data model for [RewriteRulesMap].
*/
data class JsonData(val rules: Set<RewriteRule.JsonData>)
} | jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/rule/RewriteRulesMap.kt | 1780565977 |
package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.androidpublisher.EditResponse
import com.github.triplet.gradle.androidpublisher.FakeEditManager
import com.github.triplet.gradle.androidpublisher.FakePlayPublisher
import com.github.triplet.gradle.androidpublisher.ReleaseStatus
import com.github.triplet.gradle.androidpublisher.newSuccessEditResponse
import com.github.triplet.gradle.play.helpers.IntegrationTestBase
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.Test
class PromoteReleaseIntegrationTest : IntegrationTestBase() {
override val factoryInstallerStatement = "com.github.triplet.gradle.play.tasks." +
"PromoteReleaseIntegrationTest.installFactories()"
@Test
fun `Promote uses promote track by default`() {
// language=gradle
val config = """
play.promoteTrack = 'foobar'
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=auto-track")
assertThat(result.output).contains("promoteTrackName=foobar")
}
@Test
fun `Promote uses promote track even with track specified`() {
// language=gradle
val config = """
play.track = 'foobar'
play.promoteTrack = 'not-foobar'
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("promoteTrackName=not-foobar")
}
@Test
fun `Promote finds from track dynamically by default`() {
val result = execute("", "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=auto-track")
assertThat(result.output).contains("promoteTrackName=auto-track")
}
@Test
fun `Promote uses from track when specified`() {
// language=gradle
val config = """
play.fromTrack = 'foobar'
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=foobar")
assertThat(result.output).contains("promoteTrackName=foobar")
}
@Test
fun `CLI params can be used to configure task`() {
val result = execute(
"",
"promoteReleaseArtifact",
"--no-commit",
"--from-track=myFromTrack",
"--promote-track=myPromoteTrack",
"--release-name=myRelName",
"--release-status=draft",
"--user-fraction=.88",
"--update-priority=3"
)
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=myFromTrack")
assertThat(result.output).contains("promoteTrackName=myPromoteTrack")
assertThat(result.output).contains("releaseName=myRelName")
assertThat(result.output).contains("releaseStatus=DRAFT")
assertThat(result.output).contains("userFraction=0.88")
assertThat(result.output).contains("updatePriority=3")
assertThat(result.output).contains("insertEdit()")
assertThat(result.output).doesNotContain("commitEdit(")
}
@Test
fun `Global CLI params can be used to configure task`() {
// language=gradle
val config = """
playConfigs {
release {
track.set('unused')
}
}
""".withAndroidBlock()
val result = execute(
config,
"promoteArtifact",
"--no-commit",
"--from-track=myFromTrack",
"--promote-track=myPromoteTrack",
"--release-name=myRelName",
"--release-status=draft",
"--user-fraction=.88",
"--update-priority=3"
)
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=myFromTrack")
assertThat(result.output).contains("promoteTrackName=myPromoteTrack")
assertThat(result.output).contains("releaseName=myRelName")
assertThat(result.output).contains("releaseStatus=DRAFT")
assertThat(result.output).contains("userFraction=0.88")
assertThat(result.output).contains("updatePriority=3")
assertThat(result.output).contains("insertEdit()")
assertThat(result.output).doesNotContain("commitEdit(")
}
@Test
fun `CLI params can be used to update track`() {
val result = execute("", "promoteReleaseArtifact", "--update=myUpdateTrack")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("fromTrackName=myUpdateTrack")
assertThat(result.output).contains("promoteTrackName=myUpdateTrack")
}
@Test
fun `Build succeeds when mapping file is produced but unavailable`() {
// language=gradle
val config = """
buildTypes.release {
shrinkResources true
minifyEnabled true
proguardFiles(getDefaultProguardFile("proguard-android.txt"))
}
""".withAndroidBlock()
val result = execute(config, ":promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
}
@Test
fun `Build uses correct release status`() {
// language=gradle
val config = """
play.releaseStatus = ReleaseStatus.DRAFT
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseStatus=DRAFT")
}
@Test
fun `Build picks default release name when no track specific ones are available`() {
// language=gradle
val config = """
buildTypes {
consoleNames {}
}
""".withAndroidBlock()
val result = execute(config, "promoteConsoleNamesArtifact")
assertThat(result.task(":promoteConsoleNamesArtifact")).isNotNull()
assertThat(result.task(":promoteConsoleNamesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseName=myDefaultName")
}
@Test
fun `Build picks track specific release name when available`() {
// language=gradle
val config = """
android.buildTypes {
consoleNames {}
}
play.promoteTrack = 'custom-track'
"""
val result = execute(config, "promoteConsoleNamesArtifact")
assertThat(result.task(":promoteConsoleNamesArtifact")).isNotNull()
assertThat(result.task(":promoteConsoleNamesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseName=myCustomName")
}
@Test
fun `Build picks promote track specific release name when available`() {
// language=gradle
val config = """
android.buildTypes {
consoleNames {}
}
play.track = 'custom-track'
play.promoteTrack = 'promote-track'
"""
val result = execute(config, "promoteConsoleNamesArtifact")
assertThat(result.task(":promoteConsoleNamesArtifact")).isNotNull()
assertThat(result.task(":promoteConsoleNamesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseName=myPromoteName")
}
@Test
fun `Build picks default release notes when no track specific ones are available`() {
// language=gradle
val config = """
android.buildTypes {
releaseNotes {}
}
System.setProperty("AUTOTRACK", "other")
"""
val result = execute(config, "promoteReleaseNotesArtifact")
assertThat(result.task(":promoteReleaseNotesArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseNotesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseNotes={en-US=My default release notes, " +
"fr-FR=Mes notes de mise à jour}")
}
@Test
fun `Build picks track specific release notes when available`() {
// language=gradle
val config = """
android.buildTypes {
releaseNotes {}
}
play.fromTrack = 'custom-track'
"""
val result = execute(config, "promoteReleaseNotesArtifact")
assertThat(result.task(":promoteReleaseNotesArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseNotesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseNotes={en-US=Custom track release notes, " +
"fr-FR=Mes notes de mise à jour}")
}
@Test
fun `Build picks remote track specific release notes when available`() {
// language=gradle
val config = """
buildTypes {
releaseNotes {}
}
""".withAndroidBlock()
val result = execute(config, "promoteReleaseNotesArtifact")
assertThat(result.task(":promoteReleaseNotesArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseNotesArtifact")!!.outcome)
.isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("releaseNotes={en-US=Auto track release notes, " +
"fr-FR=Mes notes de mise à jour}")
}
@Test
fun `Build uses correct user fraction`() {
// language=gradle
val config = """
play.userFraction = 0.123d
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("userFraction=0.123")
}
@Test
fun `Build uses correct update priority`() {
// language=gradle
val config = """
play.updatePriority = 5
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("updatePriority=5")
}
@Test
fun `Build uses correct retained artifacts`() {
// language=gradle
val config = """
play.retain.artifacts = [1l, 2l, 3l]
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("promoteRelease(")
assertThat(result.output).contains("retainableArtifacts=[1, 2, 3]")
}
@Test
fun `Build is not cacheable`() {
val result1 = execute("", "promoteReleaseArtifact")
val result2 = execute("", "promoteReleaseArtifact")
assertThat(result1.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result1.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result2.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result2.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result1.output).contains("promoteRelease(")
assertThat(result2.output).contains("promoteRelease(")
}
@Test
fun `Build generates and commits edit by default`() {
val result = execute("", "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("insertEdit()")
assertThat(result.output).contains("commitEdit(edit-id)")
}
@Test
fun `Build skips commit when no-commit flag is passed`() {
// language=gradle
val config = """
play.commit = false
"""
val result = execute(config, "promoteReleaseArtifact")
assertThat(result.task(":promoteReleaseArtifact")).isNotNull()
assertThat(result.task(":promoteReleaseArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.output).contains("insertEdit()")
assertThat(result.output).doesNotContain("commitEdit(")
}
companion object {
@JvmStatic
fun installFactories() {
val publisher = object : FakePlayPublisher() {
override fun insertEdit(): EditResponse {
println("insertEdit()")
return newSuccessEditResponse("edit-id")
}
override fun getEdit(id: String): EditResponse {
println("getEdit($id)")
return newSuccessEditResponse(id)
}
override fun commitEdit(id: String) {
println("commitEdit($id)")
}
}
val edits = object : FakeEditManager() {
override fun findLeastStableTrackName(): String? {
println("findLeastStableTrackName()")
return System.getProperty("AUTOTRACK") ?: "auto-track"
}
override fun promoteRelease(
promoteTrackName: String,
fromTrackName: String,
releaseStatus: ReleaseStatus?,
releaseName: String?,
releaseNotes: Map<String, String?>?,
userFraction: Double?,
updatePriority: Int?,
retainableArtifacts: List<Long>?
) {
println("promoteRelease(" +
"promoteTrackName=$promoteTrackName, " +
"fromTrackName=$fromTrackName, " +
"releaseStatus=$releaseStatus, " +
"releaseName=$releaseName, " +
"releaseNotes=$releaseNotes, " +
"userFraction=$userFraction, " +
"updatePriority=$updatePriority, " +
"retainableArtifacts=$retainableArtifacts)")
}
}
publisher.install()
edits.install()
}
}
}
| play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/PromoteReleaseIntegrationTest.kt | 4036023126 |
/*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.web
import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector
import kotlinx.coroutines.coroutineScope
import org.jdom.Content
import org.jdom.Element
import javax.servlet.http.HttpServletRequest
/**
* Handles vm sizes request.
*/
internal class VmSizesHandler : ResourceHandler {
override suspend fun handle(request: HttpServletRequest, context: ResourceHandlerContext) = coroutineScope {
val region = request.getParameter("region")
val sizes = context.apiConnector.getVmSizes(region)
val sizesElement = Element("vmSizes")
for (size in sizes) {
sizesElement.addContent(Element("vmSize").apply {
text = size
})
}
sizesElement
}
}
| plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/web/VmSizesHandler.kt | 2465307918 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action.manager
import android.content.Context
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.action.ActionFile
import jp.hazuki.yuzubrowser.legacy.action.ActionList
import java.io.File
import java.io.IOException
class ActionArrayFile(private val FOLDER_NAME: String, private val id: Int) : ActionFile() {
val list = ActionList()
override fun getFile(context: Context): File {
return File(context.getDir(FOLDER_NAME, Context.MODE_PRIVATE), id.toString() + ".dat")
}
override fun reset() {
list.clear()
}
@Throws(IOException::class)
override fun load(reader: JsonReader): Boolean {
return list.loadAction(reader)
}
@Throws(IOException::class)
override fun write(writer: JsonWriter): Boolean {
list.writeAction(writer)
return true
}
companion object {
private const val serialVersionUID = 6536274056164364431L
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/manager/ActionArrayFile.kt | 2442895652 |
package org.evomaster.core.parser
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.regex.*
/**
* Created by arcuri82 on 12-Jun-19.
*/
class GenePostgresSimilarToVisitor : PostgresSimilarToBaseVisitor<VisitResult>() {
/*
WARNING: lot of code here is similar/adapted from ECMA262 visitor.
But, as the parser objects are different, it does not seem simple to reuse
the code without avoiding copy&paste&adapt :(
*/
override fun visitPattern(ctx: PostgresSimilarToParser.PatternContext): VisitResult {
val res = ctx.disjunction().accept(this)
val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene })
val gene = RegexGene("regex", disjList)
return VisitResult(gene)
}
override fun visitDisjunction(ctx: PostgresSimilarToParser.DisjunctionContext): VisitResult {
val altRes = ctx.alternative().accept(this)
val disj = DisjunctionRxGene("disj", altRes.genes.map { it as Gene }, true, true)
val res = VisitResult(disj)
if(ctx.disjunction() != null){
val disjRes = ctx.disjunction().accept(this)
res.genes.addAll(disjRes.genes)
}
return res
}
override fun visitAlternative(ctx: PostgresSimilarToParser.AlternativeContext): VisitResult {
val res = VisitResult()
for(i in 0 until ctx.term().size){
val resTerm = ctx.term()[i].accept(this)
val gene = resTerm.genes.firstOrNull()
if(gene != null) {
res.genes.add(gene)
}
}
return res
}
override fun visitTerm(ctx: PostgresSimilarToParser.TermContext): VisitResult {
val res = VisitResult()
val resAtom = ctx.atom().accept(this)
val atom = resAtom.genes.firstOrNull()
?: return res
if(ctx.quantifier() != null){
val limits = ctx.quantifier().accept(this).data as Pair<Int,Int>
val q = QuantifierRxGene("q", atom, limits.first, limits.second)
res.genes.add(q)
} else {
res.genes.add(atom)
}
return res
}
override fun visitQuantifier(ctx: PostgresSimilarToParser.QuantifierContext): VisitResult {
val res = VisitResult()
var min = 1
var max = 1
if(ctx.bracketQuantifier() == null){
val symbol = ctx.text
when(symbol){
"*" -> {min=0; max= Int.MAX_VALUE}
"+" -> {min=1; max= Int.MAX_VALUE}
"?" -> {min=0; max=1}
else -> throw IllegalArgumentException("Invalid quantifier symbol: $symbol")
}
} else {
val q = ctx.bracketQuantifier()
when {
q.bracketQuantifierOnlyMin() != null -> {
min = q.bracketQuantifierOnlyMin().decimalDigits().text.toInt()
max = Int.MAX_VALUE
}
q.bracketQuantifierSingle() != null -> {
min = q.bracketQuantifierSingle().decimalDigits().text.toInt()
max = min
}
q.bracketQuantifierRange() != null -> {
val range = q.bracketQuantifierRange()
min = range.decimalDigits()[0].text.toInt()
max = range.decimalDigits()[1].text.toInt()
}
else -> throw IllegalArgumentException("Invalid quantifier: ${ctx.text}")
}
}
res.data = Pair(min,max)
return res
}
override fun visitAtom(ctx: PostgresSimilarToParser.AtomContext): VisitResult {
if(! ctx.patternCharacter().isEmpty()){
val block = ctx.patternCharacter().map { it.text }
.joinToString("")
val gene = PatternCharacterBlockGene("block", block)
return VisitResult(gene)
}
if(ctx.disjunction() != null){
val res = ctx.disjunction().accept(this)
val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene })
//TODO tmp hack until full handling of ^$. Assume full match when nested disjunctions
for(gene in disjList.disjunctions){
gene.extraPrefix = false
gene.extraPostfix = false
gene.matchStart = true
gene.matchEnd = true
}
return VisitResult(disjList)
}
if(ctx.UNDERSCORE() != null){
return VisitResult(AnyCharacterRxGene())
}
if(ctx.PERCENT() != null){
return VisitResult(QuantifierRxGene("q", AnyCharacterRxGene(), 0 , Int.MAX_VALUE))
}
if(ctx.characterClass() != null){
return ctx.characterClass().accept(this)
}
throw IllegalStateException("No valid atom resolver for: ${ctx.text}")
}
override fun visitCharacterClass(ctx: PostgresSimilarToParser.CharacterClassContext): VisitResult {
val negated = ctx.CARET() != null
val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>>
val gene = CharacterRangeRxGene(negated, ranges)
return VisitResult(gene)
}
override fun visitClassRanges(ctx: PostgresSimilarToParser.ClassRangesContext): VisitResult {
val res = VisitResult()
val list = mutableListOf<Pair<Char,Char>>()
if(ctx.nonemptyClassRanges() != null){
val ranges = ctx.nonemptyClassRanges().accept(this).data as List<Pair<Char,Char>>
list.addAll(ranges)
}
res.data = list
return res
}
override fun visitNonemptyClassRanges(ctx: PostgresSimilarToParser.NonemptyClassRangesContext): VisitResult {
val list = mutableListOf<Pair<Char,Char>>()
val startText = ctx.classAtom()[0].text
assert(startText.length == 1) // single chars
val start : Char = startText[0]
val end = if(ctx.classAtom().size == 2){
ctx.classAtom()[1].text[0]
} else {
//single char, not an actual range
start
}
list.add(Pair(start, end))
if(ctx.nonemptyClassRangesNoDash() != null){
val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>>
list.addAll(ranges)
}
if(ctx.classRanges() != null){
val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>>
list.addAll(ranges)
}
val res = VisitResult()
res.data = list
return res
}
override fun visitNonemptyClassRangesNoDash(ctx: PostgresSimilarToParser.NonemptyClassRangesNoDashContext): VisitResult {
val list = mutableListOf<Pair<Char,Char>>()
if(ctx.MINUS() != null){
val start = ctx.classAtomNoDash().text[0]
val end = ctx.classAtom().text[0]
list.add(Pair(start, end))
} else {
val char = (ctx.classAtom() ?: ctx.classAtomNoDash()).text[0]
list.add(Pair(char, char))
}
if(ctx.nonemptyClassRangesNoDash() != null){
val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>>
list.addAll(ranges)
}
if(ctx.classRanges() != null){
val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>>
list.addAll(ranges)
}
val res = VisitResult()
res.data = list
return res
}
} | core/src/main/kotlin/org/evomaster/core/parser/GenePostgresSimilarToVisitor.kt | 160547034 |
package collections
import org.junit.Assert
import org.junit.Test
class SortTest {
@Test
fun testGetCustomersSortedByNumberOfOrders() {
Assert.assertEquals("getCustomersSortedByNumberOfOrders",
sortedCustomers, shop.getCustomersSortedByNumberOfOrders())
}
}
| src/test/kotlin/collections/Sort.kt | 1261698225 |
/*
* Copyright (c) 2017-2018 mikan
*/
package com.github.javatrainingcourse.obogmanager.domain.model
import com.github.javatrainingcourse.obogmanager.Version
import java.io.Serializable
import java.util.*
import javax.persistence.*
/**
* @author mikan
* @since 0.1
*/
@Entity
@Table(name = "attendances")
class Attendance {
@AttributeOverrides(AttributeOverride(name = "convocationId", column = Column(name = "convocation_id")), AttributeOverride(name = "membershipId", column = Column(name = "member_id")))
@EmbeddedId
private var id: AttendanceId? = null
@MapsId("convocationId")
@ManyToOne
var convocation: Convocation? = null
@MapsId("membershipId")
@ManyToOne
var membership: Membership? = null
@Column(nullable = false)
var attend: Boolean? = null
@Column(length = 256)
var comment: String? = null
@Column
@Temporal(TemporalType.TIMESTAMP)
var createdDate: Date? = null
@Column
@Temporal(TemporalType.TIMESTAMP)
var lastUpdateDate: Date? = null
companion object {
fun newAttendance(convocation: Convocation, membership: Membership, comment: String): Attendance {
val id = AttendanceId()
id.convocationId = convocation.id
id.membershipId = membership.id
val attendance = Attendance()
attendance.id = id
attendance.convocation = convocation
attendance.membership = membership
attendance.comment = comment
attendance.attend = true
attendance.createdDate = Date()
attendance.lastUpdateDate = Date()
return attendance
}
}
class AttendanceId : Serializable {
var convocationId: Long? = null
var membershipId: Long? = null
companion object {
private const val serialVersionUID = Version.OBOG_MANAGER_SERIAL_VERSION_UID
}
}
fun isAttend(): Boolean {
return attend ?: true
}
}
| src/main/kotlin/com/github/javatrainingcourse/obogmanager/domain/model/Attendance.kt | 3142313012 |
package szewek.mcflux.items
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.item.EnumAction
import net.minecraft.item.ItemStack
import net.minecraft.network.play.server.SPacketTitle
import net.minecraft.stats.StatList
import net.minecraft.util.ActionResult
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumHand
import net.minecraft.util.text.TextComponentTranslation
import net.minecraft.world.World
import szewek.mcflux.fluxable.FluxableCapabilities
class ItemUpChip : ItemMCFlux() {
override fun getItemUseAction(stack: ItemStack?) = EnumAction.BOW
override fun getMaxItemUseDuration(stack: ItemStack) = 40
override fun onItemRightClick(w: World, p: EntityPlayer, h: EnumHand): ActionResult<ItemStack> {
p.activeHand = h
return ActionResult(EnumActionResult.SUCCESS, p.getHeldItem(h))
}
override fun onItemUseFinish(stk: ItemStack, w: World, elb: EntityLivingBase): ItemStack {
if (!w.isRemote && elb is EntityPlayerMP) {
val mp = elb as EntityPlayerMP?
val pe = mp!!.getCapability(FluxableCapabilities.CAP_PE, null) ?: return stk
val lvl = pe.updateLevel()
if (lvl.toInt() == -1)
return stk
stk.grow(-1)
mp.connection.sendPacket(SPacketTitle(SPacketTitle.Type.TITLE, textInstalled, 50, 500, 50))
mp.connection.sendPacket(SPacketTitle(SPacketTitle.Type.SUBTITLE, if (lvl.toInt() == 30) textLvlMax else TextComponentTranslation(PF + "lvlup", lvl)))
val stat = StatList.getObjectUseStats(this)
if (stat != null) mp.addStat(stat)
}
return stk
}
companion object {
private const val PF = "mcflux.upchip."
private val textInstalled = TextComponentTranslation(PF + "installed")
private val textLvlMax = TextComponentTranslation(PF + "lvlmax")
}
}
| src/main/java/szewek/mcflux/items/ItemUpChip.kt | 970358604 |
package chat.rocket.android.authentication.loginoptions.di
import androidx.lifecycle.LifecycleOwner
import chat.rocket.android.authentication.loginoptions.presentation.LoginOptionsView
import chat.rocket.android.authentication.loginoptions.ui.LoginOptionsFragment
import chat.rocket.android.dagger.scope.PerFragment
import dagger.Module
import dagger.Provides
@Module
class LoginOptionsFragmentModule {
@Provides
@PerFragment
fun loginOptionsView(frag: LoginOptionsFragment): LoginOptionsView = frag
@Provides
@PerFragment
fun provideLifecycleOwner(frag: LoginOptionsFragment): LifecycleOwner = frag
} | app/src/main/java/chat/rocket/android/authentication/loginoptions/di/LoginOptionsFragmentModule.kt | 3906658388 |
package com.bubelov.coins.data
import com.bubelov.coins.TestSuite
import org.junit.Test
import org.koin.core.inject
import java.time.LocalDateTime
import java.util.*
import kotlin.random.Random
class LogEntryQueriesTests : TestSuite() {
private val queries: LogEntryQueries by inject()
@Test
fun emptyByDefault() {
assert(queries.selectCount().executeAsOne() == 0L)
}
@Test
fun insert_insertsItem() {
val item = testItem()
queries.insert(item)
assert(queries.selectCount().executeAsOne() == 1L)
assert(queries.selectByTag(item.tag).executeAsOne() == item)
}
@Test
fun selectAll_selectsAllItems() {
val items = listOf(testItem(), testItem())
queries.transaction {
items.forEach {
queries.insert(it)
}
}
assert(queries.selectAll().executeAsList().size == items.size)
}
@Test
@ExperimentalStdlibApi
fun selectByTag_selectsCorrectItem() {
val items = buildList<LogEntry> {
repeat(100) {
add(testItem())
}
}
queries.transaction {
items.forEach {
queries.insert(it)
}
}
val randomItem = items.random()
assert(queries.selectByTag(randomItem.tag).executeAsOne() == randomItem)
}
@Test
@ExperimentalStdlibApi
fun selectCount_returnsCorrectCount() {
val count = 1 + Random(System.currentTimeMillis()).nextInt(100)
queries.transaction {
repeat(count) {
queries.insert(testItem())
}
}
assert(queries.selectCount().executeAsOne() == count.toLong())
}
private fun testItem() = LogEntry(
datetime = LocalDateTime.now().toString(),
tag = "test_tag_${UUID.randomUUID()}",
message = "test_massage_${UUID.randomUUID()}"
)
} | app/src/test/java/com/bubelov/coins/data/LogEntryQueriesTests.kt | 450950170 |
package wulinpeng.com.framework.base.ui.loadmore
import android.content.Context
/**
* @author wulinpeng
* @datetime: 18/9/22 下午8:35
* @description:
*/
class DefaultFooterViewFactory : IFooterViewFactory {
override fun createFooterView(context: Context): IFooterView {
return DefaultFooterView(context)
}
}
| framework/src/main/java/wulinpeng/com/framework/base/ui/loadmore/DefaultFooterViewFactory.kt | 4219996324 |
package com.antonioleiva.weatherapp.extensions
import java.text.DateFormat
import java.util.*
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
| app/src/main/java/com/antonioleiva/weatherapp/extensions/ExtensionUtils.kt | 1362607144 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.decoder
import com.facebook.imagepipeline.image.EncodedImage
class DecodeException : RuntimeException {
val encodedImage: EncodedImage
constructor(message: String?, encodedImage: EncodedImage) : super(message) {
this.encodedImage = encodedImage
}
constructor(message: String?, t: Throwable?, encodedImage: EncodedImage) : super(message, t) {
this.encodedImage = encodedImage
}
}
| imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DecodeException.kt | 2111687174 |
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.resolver
import org.gradle.internal.classpath.ClassPath
import org.gradle.kotlin.dsl.support.KotlinScriptType
import org.gradle.kotlin.dsl.support.KotlinScriptTypeMatch
import org.gradle.kotlin.dsl.support.filter
import org.gradle.kotlin.dsl.support.isGradleKotlinDslJar
import org.gradle.kotlin.dsl.support.listFilesOrdered
import java.io.File
const val buildSrcSourceRootsFilePath = "build/source-roots/buildSrc/source-roots.txt"
object SourcePathProvider {
fun sourcePathFor(
classPath: ClassPath,
scriptFile: File?,
projectDir: File,
gradleHomeDir: File?,
sourceDistributionResolver: SourceDistributionProvider
): ClassPath {
val gradleKotlinDslJar = classPath.filter(::isGradleKotlinDslJar)
val gradleSourceRoots = gradleHomeDir?.let { sourceRootsOf(it, sourceDistributionResolver) } ?: emptyList()
// If the script file is known, determine its type
val scriptType = scriptFile?.let {
KotlinScriptTypeMatch.forFile(it)?.scriptType
}
// We also add the "buildSrc" sources onto the source path.
// Only exception is the "settings.gradle.kts" script, which is evaluated before "buildSrc", so it shouldn't see the sources
val projectBuildSrcRoots = when (scriptType) {
KotlinScriptType.SETTINGS -> emptyList()
else -> buildSrcRootsOf(projectDir)
}
return gradleKotlinDslJar + projectBuildSrcRoots + gradleSourceRoots
}
/**
* Returns source directories from buildSrc if any.
*/
private
fun buildSrcRootsOf(projectRoot: File): Collection<File> =
projectRoot.resolve("buildSrc/$buildSrcSourceRootsFilePath")
.takeIf { it.isFile }
?.readLines()
?.map { projectRoot.resolve("buildSrc/$it") }
?: buildSrcRootsFallbackFor(projectRoot)
private
fun buildSrcRootsFallbackFor(projectRoot: File) =
subDirsOf(File(projectRoot, "buildSrc/src/main"))
private
fun sourceRootsOf(gradleInstallation: File, sourceDistributionResolver: SourceDistributionProvider): Collection<File> =
gradleInstallationSources(gradleInstallation) ?: downloadedSources(sourceDistributionResolver)
private
fun gradleInstallationSources(gradleInstallation: File) =
File(gradleInstallation, "src").takeIf { it.exists() }?.let { subDirsOf(it) }
private
fun downloadedSources(sourceDistributionResolver: SourceDistributionProvider) =
sourceDistributionResolver.sourceDirs()
}
internal
fun subDirsOf(dir: File): Collection<File> =
if (dir.isDirectory) dir.listFilesOrdered { it.isDirectory }
else emptyList()
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/SourcePathProvider.kt | 3257720628 |
package il.co.kotlintlv.solid.basics.enums
fun main(args: Array<String>) {
println(Person.ALEX.fullName())
println(Person.DOR.fullName())
println(Person.ALEX.fullName)
println(Person.DOR.fullName)
}
private enum class Person(val firstName: String, val lastName: String) {
ALEX("Alex", "Gherschon"), DOR("Dor", "Samet");
// full name as a function
fun fullName() = "$firstName $lastName"
// full name as a property / characteristic
val fullName : String
get() = "$firstName $lastName"
}
| src/main/kotlin/il/co/kotlintlv/solid/basics/enums/Person.kt | 4263183146 |
/*
* Copyright 2017 Alexey Shtanko
*
* 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 io.shtanko.picasagallery.ui.auth
import android.os.Bundle
import dagger.Lazy
import io.shtanko.picasagallery.ui.base.BaseActivity
import javax.inject.Inject
import io.shtanko.picasagallery.R.id.content_frame as content
import io.shtanko.picasagallery.R.layout.container_activity as container
class SignInActivity : BaseActivity() {
// region injection
@Inject lateinit var presenter: SignInPresenter
@Inject lateinit var fragmentProvider: Lazy<SignInFragment>
// endregion
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
setContentView(container)
addFragment(content, fragmentProvider)
}
} | app/src/main/kotlin/io/shtanko/picasagallery/ui/auth/SignInActivity.kt | 1012589362 |
/*************************************************************************/
/* VkThread.kt */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
@file:JvmName("VkThread")
package org.godotengine.godot.vulkan
import android.util.Log
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Thread implementation for the [VkSurfaceView] onto which the vulkan logic is ran.
*
* The implementation is modeled after [android.opengl.GLSurfaceView]'s GLThread.
*/
internal class VkThread(private val vkSurfaceView: VkSurfaceView, private val vkRenderer: VkRenderer) : Thread(TAG) {
companion object {
private val TAG = VkThread::class.java.simpleName
}
/**
* Used to run events scheduled on the thread.
*/
private val eventQueue = ArrayList<Runnable>()
/**
* Used to synchronize interaction with other threads (e.g: main thread).
*/
private val lock = ReentrantLock()
private val lockCondition = lock.newCondition()
private var shouldExit = false
private var exited = false
private var rendererInitialized = false
private var rendererResumed = false
private var resumed = false
private var surfaceChanged = false
private var hasSurface = false
private var width = 0
private var height = 0
/**
* Determine when drawing can occur on the thread. This usually occurs after the
* [android.view.Surface] is available, the app is in a resumed state.
*/
private val readyToDraw
get() = hasSurface && resumed
private fun threadExiting() {
lock.withLock {
exited = true
lockCondition.signalAll()
}
}
/**
* Queue an event on the [VkThread].
*/
fun queueEvent(event: Runnable) {
lock.withLock {
eventQueue.add(event)
lockCondition.signalAll()
}
}
/**
* Request the thread to exit and block until it's done.
*/
fun blockingExit() {
lock.withLock {
shouldExit = true
lockCondition.signalAll()
while (!exited) {
try {
Log.i(TAG, "Waiting on exit for $name")
lockCondition.await()
} catch (ex: InterruptedException) {
currentThread().interrupt()
}
}
}
}
/**
* Invoked when the app resumes.
*/
fun onResume() {
lock.withLock {
resumed = true
lockCondition.signalAll()
}
}
/**
* Invoked when the app pauses.
*/
fun onPause() {
lock.withLock {
resumed = false
lockCondition.signalAll()
}
}
/**
* Invoked when the [android.view.Surface] has been created.
*/
fun onSurfaceCreated() {
// This is a no op because surface creation will always be followed by surfaceChanged()
// which provide all the needed information.
}
/**
* Invoked following structural updates to [android.view.Surface].
*/
fun onSurfaceChanged(width: Int, height: Int) {
lock.withLock {
hasSurface = true
surfaceChanged = true;
this.width = width
this.height = height
lockCondition.signalAll()
}
}
/**
* Invoked when the [android.view.Surface] is no longer available.
*/
fun onSurfaceDestroyed() {
lock.withLock {
hasSurface = false
lockCondition.signalAll()
}
}
/**
* Thread loop modeled after [android.opengl.GLSurfaceView]'s GLThread.
*/
override fun run() {
try {
while (true) {
var event: Runnable? = null
lock.withLock {
while (true) {
// Code path for exiting the thread loop.
if (shouldExit) {
vkRenderer.onVkDestroy()
return
}
// Check for events and execute them outside of the loop if found to avoid
// blocking the thread lifecycle by holding onto the lock.
if (eventQueue.isNotEmpty()) {
event = eventQueue.removeAt(0)
break;
}
if (readyToDraw) {
if (!rendererResumed) {
rendererResumed = true
vkRenderer.onVkResume()
if (!rendererInitialized) {
rendererInitialized = true
vkRenderer.onVkSurfaceCreated(vkSurfaceView.holder.surface)
}
}
if (surfaceChanged) {
vkRenderer.onVkSurfaceChanged(vkSurfaceView.holder.surface, width, height)
surfaceChanged = false
}
// Break out of the loop so drawing can occur without holding onto the lock.
break;
} else if (rendererResumed) {
// If we aren't ready to draw but are resumed, that means we either lost a surface
// or the app was paused.
rendererResumed = false
vkRenderer.onVkPause()
}
// We only reach this state if we are not ready to draw and have no queued events, so
// we wait.
// On state change, the thread will be awoken using the [lock] and [lockCondition], and
// we will resume execution.
lockCondition.await()
}
}
// Run queued event.
if (event != null) {
event?.run()
continue
}
// Draw only when there no more queued events.
vkRenderer.onVkDrawFrame()
}
} catch (ex: InterruptedException) {
Log.i(TAG, "InterruptedException", ex)
} catch (ex: IllegalStateException) {
Log.i(TAG, "IllegalStateException", ex)
} finally {
threadExiting()
}
}
}
| platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt | 1652820671 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.subscene
import com.almasb.fxgl.app.GameApplication
import com.almasb.fxgl.app.GameSettings
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.scene.SubScene
import javafx.event.EventHandler
import javafx.util.Duration
/**
* @author Serge Merzliakov ([email protected])
*/
class SubSceneSampleApp : GameApplication() {
override fun initSettings(settings: GameSettings) {
settings.width = 700
settings.height = 400
settings.title = "SubScene Navigation Demo"
settings.isMainMenuEnabled = false
settings.isGameMenuEnabled = false
settings.isIntroEnabled = false
}
override fun initGame() {
val handler: EventHandler<NavigateEvent> = EventHandler { e: NavigateEvent? ->
handleNavigate(e!!)
}
FXGL.getEventBus().addEventHandler(NAVIGATION, handler)
}
override fun initUI() {
FXGL.run(Runnable {
FXGL.getSceneService().pushSubScene(MainSubScene())
}, Duration.seconds(0.0))
}
private fun handleNavigate(e: NavigateEvent) {
var subScene: SubScene? = null
when (e.eventType) {
MAIN_VIEW -> subScene = MainSubScene()
ABOUT_VIEW -> subScene = AboutSubScene()
OPTIONS_VIEW -> subScene = OptionsSubScene()
PLAY_VIEW -> subScene = PlaySubScene()
}
FXGL.getSceneService().popSubScene()
FXGL.getSceneService().pushSubScene(subScene!!)
}
}
fun main(args: Array<String>) {
GameApplication.launch(SubSceneSampleApp::class.java, args)
}
| fxgl-samples/src/main/kotlin/sandbox/subscene/SubSceneSampleApp.kt | 1053838799 |
package com.binlly.fastpeak.base.rx
import io.reactivex.ObservableTransformer
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by binlly
*
*
* date: 2016/4/29 15:58
* desc: Don't break the chain: use RxJava's compose() operator
*/
object SchedulersCompat {
fun <T> applyComputationSchedulers(): ObservableTransformer<T, T> {
return subscribeOnMain(Schedulers.computation())
}
fun <T> applyIoSchedulers(): ObservableTransformer<T, T> {
return subscribeOnMain(Schedulers.io())
}
fun <T> applyNewSchedulers(): ObservableTransformer<T, T> {
return subscribeOnMain(Schedulers.newThread())
}
fun <T> applyTrampolineSchedulers(): ObservableTransformer<T, T> {
return subscribeOnMain(Schedulers.trampoline())
}
private fun <T> subscribeOnMain(scheduler: Scheduler): ObservableTransformer<T, T> {
return ObservableTransformer { it.subscribeOn(scheduler).observeOn(AndroidSchedulers.mainThread()) }
}
}
| app/src/main/java/com/binlly/fastpeak/base/rx/SchedulersCompat.kt | 4177491162 |
package com.github.timrs2998.pdfbuilder
import org.apache.pdfbox.pdmodel.PDDocument
import java.awt.image.BufferedImage
/**
* A DSL for Kotlin, Groovy or Java 8 consumers of this API.
*/
@DslMarker
annotation class DocumentMarker
/**
* Creates the outermost [Document] [element][Element] representing the pdf, and returns
* the rendered [PDDocument] that can be [saved][PDDocument.save] to a
* [java.io.File] or [java.io.OutputStream].
*
* @return The rendered [PDDocument].
*/
fun document(init: Document.() -> Unit): PDDocument {
val document = Document()
document.init()
return document.render()
}
// Workaround for Groovy disliking kotlin default parameters
@DocumentMarker
fun Document.text(value: String) = this.text(value) {}
@DocumentMarker
fun Document.text(value: String, init: TextElement.() -> Unit = {}): TextElement {
val textElement = TextElement(this, value)
textElement.init()
this.children.add(textElement)
return textElement
}
@DocumentMarker
fun Document.image(imagePath: String) = this.image(imagePath) {}
@DocumentMarker
fun Document.image(imagePath: String, init: ImageElement.() -> Unit = {}): ImageElement {
val imageElement = ImageElement(this, imagePath, null)
imageElement.init()
this.children.add(imageElement)
return imageElement
}
@DocumentMarker
fun Document.image(bufferedImage: BufferedImage): ImageElement = this.image(bufferedImage) {}
@DocumentMarker
fun Document.image(bufferedImage: BufferedImage, init: ImageElement.() -> Unit = {}): ImageElement {
val imageElement = ImageElement(this, "", bufferedImage)
imageElement.init()
this.children.add(imageElement)
return imageElement
}
@DocumentMarker
fun Document.table(init: TableElement.() -> Unit): TableElement {
val tableElement = TableElement(this)
tableElement.init()
this.children.add(tableElement)
return tableElement
}
@DslMarker
annotation class TableMarker
@TableMarker
fun TableElement.header(init: RowElement.() -> Unit): RowElement {
val rowElement = RowElement(this)
rowElement.init()
this.header = rowElement
return rowElement
}
@TableMarker
fun TableElement.row(init: RowElement.() -> Unit): RowElement {
val rowElement = RowElement(this)
rowElement.init()
this.rows.add(rowElement)
return rowElement
}
@DslMarker
annotation class RowMarker
// Workaround for Groovy disliking kotlin default parameters
@RowMarker
fun RowElement.text(value: String) = this.text(value) {}
@RowMarker
fun RowElement.text(value: String, init: TextElement.() -> Unit = {}): TextElement {
val textElement = TextElement(this, value)
textElement.init()
this.columns.add(textElement)
return textElement
}
| src/main/kotlin/com/github/timrs2998/pdfbuilder/KotlinBuilder.kt | 1042942915 |
package net.bms.genera.block
import net.bms.genera.init.GeneraItems
import net.minecraft.block.state.IBlockState
import net.minecraft.item.Item
import java.util.*
/**
* Created by ben on 3/18/17.
*/
class BlockNightshadeCrop: BlockGeneraCrop() {
init {
unlocalizedName = "nightshade"
setRegistryName("nightshade")
}
override fun getItemDropped(state: IBlockState?, rand: Random?, fortune: Int): Item? {
return if (state!!.getValue(AGE) == 2) GeneraItems.ItemSeedNightshade else null
}
} | src/main/kotlin/net/bms/genera/block/BlockNightshadeCrop.kt | 3655072930 |
/*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.service.api
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okio.BufferedSource
import org.assertj.core.api.Assertions
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import universum.studios.gradle.test.kotlin.KotlinArgumentMatchers
import java.nio.charset.Charset
/**
* @author Martin Albedinsky
*/
class ApiCallExceptionTest {
@Test fun testInstantiation() {
// Arrange:
val mockErrorBody = mock(ResponseBody::class.java)
val mockErrorBodySource = mock(BufferedSource::class.java)
`when`(mockErrorBodySource.readString(KotlinArgumentMatchers.any(Charset::class.java))).thenReturn("{ Authorization failed. }")
`when`(mockErrorBody.source()).thenReturn(mockErrorBodySource)
val request = Request.Builder().url("https://github.plugin.test/").build()
val rawResponse = Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(401).message("Unauthorized").build()
// Act:
val exception = ApiCallException(retrofit2.Response.error<Unit>(mockErrorBody, rawResponse))
// Assert:
Assertions.assertThat(exception).hasMessage(
"GitHubPlugin => GitHub API call 'https://github.plugin.test/' failed with an error:\n" +
"HTTP 1.1 401 Unauthorized\n\n" +
"{ Authorization failed. }"
)
}
} | plugin/src/test/kotlin/universum/studios/gradle/github/service/api/ApiCallExceptionTest.kt | 1325948770 |
package assertk.assertions
import assertk.Assert
import assertk.all
import assertk.assertions.support.appendName
import assertk.assertions.support.expected
import assertk.assertions.support.show
/**
* Asserts the iterable contains the expected element, using `in`.
* @see [doesNotContain]
*/
fun Assert<Iterable<*>>.contains(element: Any?) = given { actual ->
if (element in actual) return
expected("to contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the iterable does not contain the expected element, using `!in`.
* @see [contains]
*/
fun Assert<Iterable<*>>.doesNotContain(element: Any?) = given { actual ->
if (element !in actual) return
expected("to not contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the iterable does not contain any of the expected elements.
* @see [containsAll]
*/
fun Assert<Iterable<*>>.containsNone(vararg elements: Any?) = given { actual ->
val notExpected = elements.filter { it in actual }
if (notExpected.isEmpty()) {
return
}
expected("to contain none of:${show(elements)} but was:${show(actual)}\n elements not expected:${show(notExpected)}")
}
/**
* Asserts the iterable contains all the expected elements, in any order. The collection may also
* contain additional elements.
* @see [containsNone]
* @see [containsExactly]
* @see [containsOnly]
*/
fun Assert<Iterable<*>>.containsAll(vararg elements: Any?) = given { actual ->
val notFound = elements.filterNot { it in actual }
if (notFound.isEmpty()) {
return
}
expected("to contain all:${show(elements)} but was:${show(actual)}\n elements not found:${show(notFound)}")
}
/**
* Asserts the iterable contains only the expected elements, in any order. Duplicate values
* in the expected and actual are ignored.
*
* [1, 2] containsOnly [2, 1] passes
* [1, 2, 2] containsOnly [2, 1] passes
* [1, 2] containsOnly [2, 2, 1] passes
*
* @see [containsNone]
* @see [containsExactly]
* @see [containsAll]
* @see [containsExactlyInAnyOrder]
*/
fun Assert<Iterable<*>>.containsOnly(vararg elements: Any?) = given { actual ->
val notInActual = elements.filterNot { it in actual }
val notInExpected = actual.filterNot { it in elements }
if (notInExpected.isEmpty() && notInActual.isEmpty()) {
return
}
expected(StringBuilder("to contain only:${show(elements)} but was:${show(actual)}").apply {
if (notInActual.isNotEmpty()) {
append("\n elements not found:${show(notInActual)}")
}
if (notInExpected.isNotEmpty()) {
append("\n extra elements found:${show(notInExpected)}")
}
}.toString())
}
/**
* Asserts the iterable contains exactly the expected elements, in any order. Each value in expected
* must correspond to a matching value in actual, and visa-versa.
*
* [1, 2] containsExactlyInAnyOrder [2, 1] passes
* [1, 2, 2] containsExactlyInAnyOrder [2, 1] fails
* [1, 2] containsExactlyInAnyOrder [2, 2, 1] fails
*
* @see [containsNone]
* @see [containsExactly]
* @see [containsAll]
* @see [containsOnly]
*/
fun Assert<Iterable<*>>.containsExactlyInAnyOrder(vararg elements: Any?) = given { actual ->
val notInActual = elements.toMutableList()
val notInExpected = actual.toMutableList()
elements.forEach {
if (notInExpected.contains(it)) {
notInExpected.removeFirst(it)
notInActual.removeFirst(it)
}
}
if (notInExpected.isEmpty() && notInActual.isEmpty()) {
return
}
expected(StringBuilder("to contain exactly in any order:${show(elements)} but was:${show(actual)}").apply {
if (notInActual.isNotEmpty()) {
append("\n elements not found:${show(notInActual)}")
}
if (notInExpected.isNotEmpty()) {
append("\n extra elements found:${show(notInExpected)}")
}
}.toString())
}
internal fun MutableList<*>.removeFirst(value: Any?) {
val index = indexOf(value)
if (index > -1) removeAt(index)
}
/**
* Asserts on each item in the iterable. The given lambda will be run for each item.
*
* ```
* assertThat(listOf("one", "two")).each {
* it.hasLength(3)
* }
* ```
*/
fun <E> Assert<Iterable<E>>.each(f: (Assert<E>) -> Unit) = given { actual ->
all {
actual.forEachIndexed { index, item ->
f(assertThat(item, name = appendName(show(index, "[]"))))
}
}
}
/**
* Extracts a value of from each item in the iterable, allowing you to assert on a list of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name)
* .contains("Sue", "Bob")
* ```
*/
fun <E, R> Assert<Iterable<E>>.extracting(f1: (E) -> R): Assert<List<R>> = transform { actual ->
actual.map(f1)
}
/**
* Extracts two values of from each item in the iterable, allowing you to assert on a list of paris of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name, Person::age)
* .contains("Sue" to 20, "Bob" to 22)
* ```
*/
fun <E, R1, R2> Assert<Iterable<E>>.extracting(f1: (E) -> R1, f2: (E) -> R2): Assert<List<Pair<R1, R2>>> =
transform { actual ->
actual.map { f1(it) to f2(it) }
}
/**
* Extracts three values from each item in the iterable, allowing you to assert on a list of triples of those values.
*
* ```
* assertThat(people)
* .extracting(Person::name, Person::age, Person::address)
* .contains(Triple("Sue", 20, "123 Street"), Triple("Bob", 22, "456 Street")
* ```
*/
fun <E, R1, R2, R3> Assert<Iterable<E>>.extracting(
f1: (E) -> R1,
f2: (E) -> R2,
f3: (E) -> R3
): Assert<List<Triple<R1, R2, R3>>> = transform { actual ->
actual.map { Triple(f1(it), f2(it), f3(it)) }
}
/**
* Asserts on each item in the iterable, passing if none of the items pass.
* The given lambda will be run for each item.
*
* ```
* assertThat(listOf("one", "two")).none {
* it.hasLength(2)
* }
* ```
*/
fun <E> Assert<Iterable<E>>.none(f: (Assert<E>) -> Unit) = given { actual ->
if (actual.count() > 0) {
all(message = "expected none to pass",
body = { each { item -> f(item) } },
failIf = { it.isEmpty() })
}
}
/**
* Asserts on each item in the iterable, passing if at least `times` items pass.
* The given lambda will be run for each item.
*
* ```
* assert(listOf(-1, 1, 2)).atLeast(2) { it.isPositive() }
* ```
*/
fun <E, T : Iterable<E>> Assert<T>.atLeast(times: Int, f: (Assert<E>) -> Unit) {
var count = 0
all(message = "expected to pass at least $times times",
body = { each { item -> count++; f(item) } },
failIf = { count - it.size < times })
}
/**
* Asserts on each item in the iterable, passing if at most `times` items pass.
* The given lambda will be run for each item.
*
* ```
* assert(listOf(-2, -1, 1)).atMost(2) { it.isPositive() }
* ```
*/
fun <E, T : Iterable<E>> Assert<T>.atMost(times: Int, f: (Assert<E>) -> Unit) {
var count = 0
all(message = "expected to pass at most $times times",
body = { each { item -> count++; f(item) } },
failIf = { count - it.size > times })
}
/**
* Asserts on each item in the iterable, passing if exactly `times` items pass.
* The given lambda will be run for each item.
*
* ```
* assert(listOf(-1, 1, 2)).exactly(2) { it.isPositive() }
* ```
*/
fun <E, T : Iterable<E>> Assert<T>.exactly(times: Int, f: (Assert<E>) -> Unit) {
var count = 0
all(message = "expected to pass exactly $times times",
body = { each { item -> count++; f(item) } },
failIf = { count - it.size != times })
}
/**
* Asserts on each item in the iterable, passing if any of the items pass.
* The given lambda will be run for each item.
*
* ```
* assert(listOf(-1, -2, 1)).any { it.isPositive() }
* ```
*/
fun <E, T : Iterable<E>> Assert<T>.any(f: (Assert<E>) -> Unit) {
var lastFailureCount = 0
var itemPassed = false
all(message = "expected any item to pass",
body = { failure ->
given { actual ->
actual.forEachIndexed { index, item ->
f(assertThat(item, name = appendName(show(index, "[]"))))
if (lastFailureCount == failure.count) {
itemPassed = true
}
lastFailureCount = failure.count
}
}
},
failIf = {
!itemPassed
})
}
/**
* Asserts the iterable is empty.
* @see [isNotEmpty]
* @see [isNullOrEmpty]
*/
fun Assert<Iterable<*>>.isEmpty() = given { actual ->
if (actual.none()) return
expected("to be empty but was:${show(actual)}")
}
/**
* Asserts the iterable is not empty.
* @see [isEmpty]
*/
fun Assert<Iterable<*>>.isNotEmpty() = given { actual ->
if (actual.any()) return
expected("to not be empty")
}
/**
* Asserts the iterable is not empty, and returns an assert on the first element.
*/
fun <E, T : Iterable<E>> Assert<T>.first(): Assert<E> {
return transform(appendName("first", ".")) { iterable ->
val iterator = iterable.iterator()
if (iterator.hasNext()) {
iterator.next()
} else {
expected("to not be empty")
}
}
}
/**
* Asserts the iterable contains exactly one element, and returns an assert on that element.
*/
fun <E, T : Iterable<E>> Assert<T>.single(): Assert<E> {
return transform(appendName("single", ".")) { iterable ->
val iterator = iterable.iterator()
if (iterator.hasNext()) {
val single = iterator.next()
if (iterator.hasNext()) {
val size = if (iterable is Collection<*>) iterable.size.toString() else "multiple"
expected("to have single element but has $size: ${show(iterable)}")
} else {
single
}
} else {
expected("to have single element but was empty")
}
}
} | assertk/src/commonMain/kotlin/assertk/assertions/iterable.kt | 2326246703 |
package com.mvcoding.mvp
interface DataCache<DATA> : DataSource<DATA>, DataWriter<DATA> | mvp/src/main/kotlin/com/mvcoding/mvp/DataCache.kt | 3321343985 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timecontrol
import com.efficios.jabberwocky.common.TimeRange
import org.junit.jupiter.api.Test
/**
* Tests for [TimeRangeTextFields] specifying a minimum range duration.
*/
class TimeRangeTextFieldsMinimumTest : TimeRangeTextFieldsTest() {
// LIMIT_START = 1000
// LIMIT_END = 2000
// INITIAL_START = 1200
// INITIAL_END = 1800
companion object {
private const val MINIMUM_DURATION = 100L
}
override fun provideFixture() = TimeRangeTextFields(TimeRange.of(LIMIT_START, LIMIT_END), MINIMUM_DURATION)
// ------------------------------------------------------------------------
// Start text field
// ------------------------------------------------------------------------
@Test
fun testNewStartMoveEnd() {
startField.text = "1750"
startField.fireEvent(ENTER_EVENT)
verifyTimeRange(1750, 1850)
}
@Test
fun testNewStarMoveBoth() {
startField.text = "1950"
startField.fireEvent(ENTER_EVENT)
verifyTimeRange(1900, LIMIT_END)
}
@Test
override fun testNewStartBiggerThanEnd() {
startField.text = "1900"
startField.fireEvent(ENTER_EVENT)
verifyTimeRange(1900, LIMIT_END)
}
@Test
override fun testNewStartBiggerThanLimit() {
startField.text = "2200"
startField.fireEvent(ENTER_EVENT)
verifyTimeRange(1900, LIMIT_END)
}
// ------------------------------------------------------------------------
// End text field
// ------------------------------------------------------------------------
@Test
fun testNewEndMoveStart() {
endField.text = "1250"
endField.fireEvent(ENTER_EVENT)
verifyTimeRange(1150, 1250)
}
@Test
fun testNewEndMoveBoth() {
endField.text = "1050"
endField.fireEvent(ENTER_EVENT)
verifyTimeRange(LIMIT_START, 1100)
}
@Test
override fun testNewEndSmallerThanLimit() {
endField.text = "800"
endField.fireEvent(ENTER_EVENT)
verifyTimeRange(LIMIT_START, 1100)
}
@Test
override fun testNewEndSmallerThanStart() {
endField.text = "1150"
endField.fireEvent(ENTER_EVENT)
verifyTimeRange(1050, 1150)
}
// ------------------------------------------------------------------------
// Duration text field
// ------------------------------------------------------------------------
@Test
fun testNewDurationTooSmall() {
durationField.text = "50"
durationField.fireEvent(ENTER_EVENT)
verifyTimeRange(INITIAL_START, INITIAL_START + MINIMUM_DURATION)
}
}
| lttng-scope/src/test/kotlin/org/lttng/scope/views/timecontrol/TimeRangeTextFieldsMinimumTest.kt | 2460163241 |
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.progress.ProgressIndicator
import org.eclipse.jgit.merge.MergeStrategy
import org.jetbrains.jgit.dirCache.deleteAllFiles
import org.jetbrains.settingsRepository.LOG
import org.jetbrains.settingsRepository.MutableUpdateResult
import org.jetbrains.settingsRepository.UpdateResult
class Reset(manager: GitRepositoryManager, indicator: ProgressIndicator) : Pull(manager, indicator) {
fun reset(toTheirs: Boolean, localRepositoryInitializer: (() -> Unit)? = null): UpdateResult {
if (LOG.isDebugEnabled()) {
LOG.debug("Reset to ${if (toTheirs) "theirs" else "my"}")
}
val resetResult = repository.resetHard()
val result = MutableUpdateResult(resetResult.getUpdated().keySet(), resetResult.getRemoved())
indicator.checkCanceled()
val commitMessage = commitMessageFormatter.message(if (toTheirs) "Overwrite local to ${manager.getUpstream()}" else "Overwrite remote ${manager.getUpstream()} to local")
// grab added/deleted/renamed/modified files
val mergeStrategy = if (toTheirs) MergeStrategy.THEIRS else MergeStrategy.OURS
val firstMergeResult = pull(mergeStrategy, commitMessage)
if (localRepositoryInitializer == null) {
if (firstMergeResult == null) {
// nothing to merge, so, we merge latest origin commit
val fetchRefSpecs = remoteConfig.getFetchRefSpecs()
assert(fetchRefSpecs.size() == 1)
val latestUpstreamCommit = repository.getRef(fetchRefSpecs[0].getDestination()!!)
if (latestUpstreamCommit == null) {
if (toTheirs) {
repository.deleteAllFiles(result.deleted)
result.changed.removeAll(result.deleted)
repository.commit(commitMessage)
}
else {
LOG.debug("uninitialized remote (empty) - we don't need to merge")
}
return result
}
val mergeResult = merge(latestUpstreamCommit, mergeStrategy, true, forceMerge = true, commitMessage = commitMessage)
if (!mergeResult.mergeStatus.isSuccessful()) {
throw IllegalStateException(mergeResult.toString())
}
result.add(mergeResult.result)
}
else {
result.add(firstMergeResult)
}
}
else {
assert(!toTheirs)
result.add(firstMergeResult)
// must be performed only after initial pull, so, local changes will be relative to remote files
localRepositoryInitializer()
manager.commit(indicator)
result.add(pull(mergeStrategy, commitMessage))
}
return result
}
} | plugins/settings-repository/src/git/reset.kt | 3485053828 |
package com.zj.example.kotlin.shengshiyuan.helloworld
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
/**
*
* CreateTime: 18/3/7 10:04
* @author 郑炯
*/
class HelloKotlinLambda {
}
fun main(args: Array<String>) {
/**
* 对象表达式的写法
*/
val listener1 = object : ActionListener {
override fun actionPerformed(e: ActionEvent?) {
println("actionPerformed")
}
}
/**
* 对象表达式用lambda表达式实现
*/
val listener2 = ActionListener {
println("actionPerformed")
}
println(listener1.javaClass)
println(listener1.javaClass.superclass)
//这种写法和上面的javaClass是一样的
println(listener1::class.java)
println(listener1::class.java.superclass)
} | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/32.HelloKotlin-Lambda.kt | 3888056898 |
package com.github.kittinunf.reactiveandroid.widget
import android.graphics.drawable.Drawable
import android.widget.Toolbar
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Properties
//================================================================================
val Toolbar.rx_logo: MutableProperty<Drawable>
get() {
val getter = { logo }
val setter: (Drawable) -> Unit = { logo = it }
return createMainThreadMutableProperty(getter, setter)
}
val Toolbar.rx_navigationIcon: MutableProperty<Drawable>
get() {
val getter = { navigationIcon }
val setter: (Drawable) -> Unit = { navigationIcon = it }
return createMainThreadMutableProperty(getter, setter)
}
val Toolbar.rx_subtitle: MutableProperty<CharSequence>
get() {
val getter = { subtitle }
val setter: (CharSequence) -> Unit = { subtitle = it }
return createMainThreadMutableProperty(getter, setter)
}
val Toolbar.rx_title: MutableProperty<CharSequence>
get() {
val getter = { title }
val setter: (CharSequence) -> Unit = { title = it }
return createMainThreadMutableProperty(getter, setter)
}
| reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/ToolbarProperty.kt | 2324957281 |
package com.wayfair.userlist.injection.module
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.wayfair.networking.ApiService
import com.wayfair.userlist.BuildConfig
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
@Module
class NetModule {
@Provides
internal fun provideGson(): Gson {
return GsonBuilder().create()
}
@Provides
internal fun provideApiSevice(gson: Gson): ApiService {
val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) {
interceptor.level = HttpLoggingInterceptor.Level.BASIC
}
val client: OkHttpClient = OkHttpClient.Builder()
.readTimeout(60 * 5, TimeUnit.SECONDS)
.connectTimeout(60 * 5, TimeUnit.SECONDS)
.addInterceptor(interceptor).build()
return Retrofit.Builder()
.baseUrl(BuildConfig.API_BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.callFactory(client)
.build().create(ApiService::class.java)
}
} | android/anko_blogpost/Userlist/app/src/main/java/com/wayfair/userlist/injection/module/NetModule.kt | 1308220746 |
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.event.persistence
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.clouddriver.event.Aggregate
import com.netflix.spinnaker.clouddriver.event.EventMetadata
import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent
import com.netflix.spinnaker.clouddriver.event.config.MemoryEventRepositoryConfigProperties
import com.netflix.spinnaker.clouddriver.event.exceptions.AggregateChangeRejectedException
import com.netflix.spinnaker.kork.exceptions.SystemException
import java.time.Duration
import java.time.Instant
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.max
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationEventPublisher
import org.springframework.scheduling.annotation.Scheduled
/**
* An in-memory only [EventRepository]. This implementation should only be used for testing.
*/
class InMemoryEventRepository(
private val config: MemoryEventRepositoryConfigProperties,
private val applicationEventPublisher: ApplicationEventPublisher,
private val registry: Registry
) : EventRepository {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
private val aggregateCountId = registry.createId("eventing.aggregates")
private val aggregateWriteCountId = registry.createId("eventing.aggregates.writes")
private val aggregateReadCountId = registry.createId("eventing.aggregates.reads")
private val eventCountId = registry.createId("eventing.events")
private val eventWriteCountId = registry.createId("eventing.events.writes")
private val eventReadCountId = registry.createId("eventing.events.reads")
private val events: MutableMap<Aggregate, MutableList<SpinnakerEvent>> = ConcurrentHashMap()
override fun save(
aggregateType: String,
aggregateId: String,
originatingVersion: Long,
newEvents: List<SpinnakerEvent>
) {
registry.counter(aggregateWriteCountId).increment()
val aggregate = getAggregate(aggregateType, aggregateId)
if (aggregate.version != originatingVersion) {
// If this is being thrown, ensure that the originating process is retried on the latest aggregate version
// by re-reading the newEvents list.
throw AggregateChangeRejectedException(aggregate.version, originatingVersion)
}
events.getOrPut(aggregate) { mutableListOf() }.let { aggregateEvents ->
val currentSequence = aggregateEvents.map { it.getMetadata().sequence }.max() ?: 0
newEvents.forEachIndexed { index, newEvent ->
// TODO(rz): Plugin more metadata (provenance, serviceVersion, etc)
newEvent.setMetadata(
EventMetadata(
id = UUID.randomUUID().toString(),
aggregateType = aggregateType,
aggregateId = aggregateId,
sequence = currentSequence + (index + 1),
originatingVersion = originatingVersion
)
)
}
registry.counter(eventWriteCountId).increment(newEvents.size.toLong())
aggregateEvents.addAll(newEvents)
aggregate.version = aggregate.version + 1
}
log.debug(
"Saved $aggregateType/$aggregateId@${aggregate.version}: " +
"[${newEvents.joinToString(",") { it.javaClass.simpleName }}]"
)
newEvents.forEach { applicationEventPublisher.publishEvent(it) }
}
override fun list(aggregateType: String, aggregateId: String): List<SpinnakerEvent> {
registry.counter(eventReadCountId).increment()
return getAggregate(aggregateType, aggregateId)
.let {
events[it]?.toList()
}
?: throw MissingAggregateEventsException(aggregateType, aggregateId)
}
override fun listAggregates(criteria: EventRepository.ListAggregatesCriteria): EventRepository.ListAggregatesResult {
val aggregates = events.keys
val result = aggregates.toList()
.let { list ->
criteria.aggregateType?.let { requiredType -> list.filter { it.type == requiredType } } ?: list
}
.let { list ->
criteria.token?.let { nextPageToken ->
val start = list.indexOf(list.find { "${it.type}/${it.id}" == nextPageToken })
val end = (start + criteria.perPage).let {
if (it > list.size - 1) {
list.size
} else {
criteria.perPage
}
}
list.subList(start, end)
} ?: list
}
return EventRepository.ListAggregatesResult(
aggregates = result,
nextPageToken = result.lastOrNull()?.let { "${it.type}/${it.id}" }
)
}
private fun getAggregate(aggregateType: String, aggregateId: String): Aggregate {
registry.counter(aggregateReadCountId).increment()
val aggregate = Aggregate(
aggregateType,
aggregateId,
0L
)
events.putIfAbsent(aggregate, mutableListOf())
return events.keys.first { it == aggregate }
}
@Scheduled(fixedDelayString = "\${spinnaker.clouddriver.eventing.memory-repository.cleanup-job-delay-ms:60000}")
private fun cleanup() {
registry.counter(eventReadCountId).increment()
config.maxAggregateAgeMs
?.let { Duration.ofMillis(it) }
?.let { maxAge ->
val horizon = Instant.now().minus(maxAge)
log.info("Cleaning up aggregates last updated earlier than $maxAge ($horizon)")
events.entries
.filter { it.value.any { event -> event.getMetadata().timestamp.isBefore(horizon) } }
.map { it.key }
.forEach {
log.trace("Cleaning up $it")
events.remove(it)
}
}
config.maxAggregatesCount
?.let { maxCount ->
log.info("Cleaning up aggregates to max $maxCount items, pruning by earliest updated")
events.entries
// Flatten into pairs of List<Aggregate, SpinnakerEvent>
.flatMap { entry ->
entry.value.map { Pair(entry.key, it) }
}
.sortedBy { it.second.getMetadata().timestamp }
.subList(0, max(events.size - maxCount, 0))
.forEach {
log.trace("Cleaning up ${it.first}")
events.remove(it.first)
}
}
}
@Scheduled(fixedRate = 1_000)
private fun recordMetrics() {
registry.gauge(aggregateCountId).set(events.size.toDouble())
registry.gauge(eventCountId).set(events.flatMap { it.value }.size.toDouble())
}
inner class MissingAggregateEventsException(aggregateType: String, aggregateId: String) : SystemException(
"Aggregate $aggregateType/$aggregateId is missing its internal events list store"
)
}
| clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/persistence/InMemoryEventRepository.kt | 2950630528 |
package net.perfectdreams.loritta.cinnamon.discord.utils.soundboard
enum class SoundboardAudio {
AMONG_US_ROUND_START,
RAPAIZ,
CHAVES_RISADAS,
DANCE_CAT_DANCE,
ESSE_E_O_MEU_PATRAO_HEHE,
IRRA,
RATINHO,
UEPA,
UI,
NICELY_DONE_CHEER
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/soundboard/SoundboardAudio.kt | 1967383782 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.economy
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.AccountUtils
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.GACampaigns
import net.perfectdreams.loritta.morenitta.utils.GenericReplies
import net.perfectdreams.loritta.morenitta.utils.NumberUtils
import net.perfectdreams.loritta.morenitta.utils.sendStyledReply
class EmojiFightBetCommand(val m: LorittaBot) : DiscordAbstractCommandBase(
m,
listOf("emojifight bet", "rinhadeemoji bet", "emotefight bet"),
net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY
) {
override fun command() = create {
localizedDescription("commands.command.emojifightbet.description")
localizedExamples("commands.command.emojifightbet.examples")
usage {
arguments {
argument(ArgumentType.NUMBER) {}
argument(ArgumentType.NUMBER) {
optional = true
}
}
}
this.similarCommands = listOf("EmojiFightCommand")
this.canUseInPrivateChannel = false
executesDiscord {
// Gets the first argument
// If the argument is null (we just show the command explanation and exit)
// If it is not null, we convert it to a Long (if it is a invalid number, it will be null)
// Then, in the ".also" block, we check if it is null and, if it is, we show that the user provided a invalid number!
val totalEarnings = (args.getOrNull(0) ?: explainAndExit())
.let { NumberUtils.convertShortenedNumberToLong(it) }
.let {
if (it == null)
GenericReplies.invalidNumber(this, args[0])
it
}
if (0 >= totalEarnings)
fail(locale["commands.command.flipcoinbet.zeroMoney"], Constants.ERROR)
val selfUserProfile = lorittaUser.profile
if (totalEarnings > selfUserProfile.money) {
sendStyledReply {
this.append {
message = locale["commands.command.flipcoinbet.notEnoughMoneySelf"]
prefix = Constants.ERROR
}
this.append {
message = GACampaigns.sonhosBundlesUpsellDiscordMessage(
"https://loritta.website/", // Hardcoded, woo
"bet-coinflip-legacy",
"bet-not-enough-sonhos"
)
prefix = Emotes.LORI_RICH.asMention
mentionUser = false
}
}
return@executesDiscord
}
// Only allow users to participate in a emoji fight bet if the user got their daily reward today
AccountUtils.getUserTodayDailyReward(loritta, lorittaUser.profile)
?: fail(locale["commands.youNeedToGetDailyRewardBeforeDoingThisAction", serverConfig.commandPrefix], Constants.ERROR)
// Self user check
run {
val epochMillis = user.timeCreated.toEpochSecond() * 1000
// Don't allow users to bet if they are recent accounts
if (epochMillis + (Constants.ONE_WEEK_IN_MILLISECONDS * 2) > System.currentTimeMillis()) // 14 dias
fail(
LorittaReply(
locale["commands.command.pay.selfAccountIsTooNew", 14] + " ${Emotes.LORI_CRYING}",
Constants.ERROR
)
)
}
val maxPlayersInEvent = (
(this.args.getOrNull(1) ?.toIntOrNull() ?: EmojiFight.DEFAULT_MAX_PLAYER_COUNT)
.coerceIn(2, EmojiFight.DEFAULT_MAX_PLAYER_COUNT)
)
val emojiFight = EmojiFight(
this,
totalEarnings,
maxPlayersInEvent
)
emojiFight.start()
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/EmojiFightBetCommand.kt | 3749294319 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.service
import fr.cph.chicago.core.model.dto.BaseDTO
import fr.cph.chicago.core.model.dto.BusArrivalDTO
import fr.cph.chicago.core.model.dto.FavoritesDTO
import fr.cph.chicago.core.model.dto.FirstLoadDTO
import fr.cph.chicago.core.model.dto.TrainArrivalDTO
import fr.cph.chicago.exception.BaseException
import fr.cph.chicago.redux.store
import fr.cph.chicago.rx.RxUtil.handleListError
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import timber.log.Timber
object MixedService {
private val trainService = TrainService
private val busService = BusService
private val bikeService = BikeService
private val preferenceService = PreferenceService
fun baseData(): Single<BaseDTO> {
return Single.zip(
trainService.loadLocalTrainData(),
busService.loadLocalBusData(),
{ trainError, busError ->
if (trainError || busError) throw BaseException()
true
})
.flatMap {
Single.zip(
baseArrivals().observeOn(Schedulers.computation()),
preferenceService.getTrainFavorites().observeOn(Schedulers.computation()),
preferenceService.getBusFavorites().observeOn(Schedulers.computation()),
preferenceService.getBikeFavorites().observeOn(Schedulers.computation()),
{ favoritesDTO, favoritesTrains, favoritesBuses, favoritesBikes ->
val trainArrivals = if (favoritesDTO.trainArrivalDTO.error)
TrainArrivalDTO(store.state.trainArrivalsDTO.trainsArrivals, true)
else
favoritesDTO.trainArrivalDTO
val busArrivals = if (favoritesDTO.busArrivalDTO.error)
BusArrivalDTO(store.state.busArrivalsDTO.busArrivals, true)
else
favoritesDTO.busArrivalDTO
val favoritesBusRoute = busService.extractBusRouteFavorites(favoritesBuses)
BaseDTO(
trainArrivalsDTO = trainArrivals,
busArrivalsDTO = busArrivals,
trainFavorites = favoritesTrains,
busFavorites = favoritesBuses,
busRouteFavorites = favoritesBusRoute,
bikeFavorites = favoritesBikes)
})
}
}
private fun baseArrivals(): Single<FavoritesDTO> {
// Train online favorites
val favoritesTrainArrivals = favoritesTrainArrivalDTO().observeOn(Schedulers.computation())
// Bus online favorites
val favoritesBusArrivals = favoritesBusArrivalDTO().observeOn(Schedulers.computation())
return Single.zip(
favoritesTrainArrivals,
favoritesBusArrivals,
{ trainArrivalsDTO, busArrivalsDTO -> FavoritesDTO(trainArrivalsDTO, busArrivalsDTO, false, listOf()) })
}
fun favorites(): Single<FavoritesDTO> {
// Train online favorites
val trainArrivals = favoritesTrainArrivalDTO().observeOn(Schedulers.computation())
// Bus online favorites
val busArrivals = favoritesBusArrivalDTO().observeOn(Schedulers.computation())
// Bikes online all stations
val bikeStationsObservable = bikeService.allBikeStations().observeOn(Schedulers.computation()).onErrorReturn(handleListError())
return Single.zip(busArrivals, trainArrivals, bikeStationsObservable,
{ busArrivalDTO, trainArrivalsDTO, bikeStations ->
FavoritesDTO(trainArrivalsDTO, busArrivalDTO, bikeStations.isEmpty(), bikeStations)
})
}
fun busRoutesAndBikeStation(): Single<FirstLoadDTO> {
val busRoutesSingle = busService.busRoutes().onErrorReturn(handleListError()).observeOn(Schedulers.computation())
val bikeStationsSingle = bikeService.allBikeStations().onErrorReturn(handleListError()).observeOn(Schedulers.computation())
return Single.zip(
busRoutesSingle,
bikeStationsSingle,
{ busRoutes, bikeStations -> FirstLoadDTO(busRoutes.isEmpty(), bikeStations.isEmpty(), busRoutes, bikeStations) }
)
}
private fun favoritesTrainArrivalDTO(): Single<TrainArrivalDTO> {
return trainService.loadFavoritesTrain()
.onErrorReturn { throwable ->
Timber.e(throwable, "Could not load favorites trains")
TrainArrivalDTO(mutableMapOf(), true)
}
}
private fun favoritesBusArrivalDTO(): Single<BusArrivalDTO> {
return busService.loadFavoritesBuses()
.onErrorReturn { throwable ->
Timber.e(throwable, "Could not load bus arrivals")
BusArrivalDTO(listOf(), true)
}
}
}
| android-app/src/main/kotlin/fr/cph/chicago/service/MixedService.kt | 2998739149 |
package co.geekku.lib
import android.app.Activity
import android.view.View
import android.os.AsyncTask
/**
* Created by mj on 13-12-29.
*/
open class GActivity : Activity() {
fun Int.view<T : View>(): T? {
return findViewById(this) as T?
}
fun getSystemServiceAs<T>(name: String) = this.getSystemService(name) as T
} | lib/src/main/kotlin/co/geekku/lib/GActivtity.kt | 2045047016 |
package com.ragnarok.moviecamera.ui
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.animation.OvershootInterpolator
import android.widget.ImageButton
import com.ragnarok.moviecamera.R
/**
* Created by ragnarok on 15/6/9.
*/
class MainUI : BaseUI() {
override val TAG: String = "MovieCamera.MainUI"
var imageList: RecyclerView? = null
var imageListAdapter: ImageListAdapter? = null
var imageLayoutManager: LinearLayoutManager? = null
var createButton: ImageButton? = null
var revealMaskView: CircularRevealMaskView? = null
val uiHandler = Handler(Looper.getMainLooper())
var isShow = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createButton = findViewById(R.id.create) as ImageButton
revealMaskView = findViewById(R.id.revealView) as CircularRevealMaskView
revealMaskView?.setColor(0xAFF0F8FF.toInt())
val createButtonTransY = getResources().getDimension(R.dimen.fab_size) + getResources().getDimension(R.dimen.fab_bottom_margin) + 100
createButton?.setTranslationY(createButtonTransY)
createButton?.setOnClickListener { v: View ->
if (isShow) {
var location = Array(2, { 0 }).toIntArray()
createButton?.getLocationOnScreen(location)
val x = location[0] + createButton!!.getWidth() / 2
val y = location[1] + createButton!!.getHeight() / 2
showRevealView(x, y)
isShow = false
} else {
isShow = true
hideRevealView()
}
}
initImageList()
}
private fun showRevealView(locX: Int, locY: Int) {
revealMaskView?.resetState()
uiHandler.postDelayed({revealMaskView?.startShow(locX, locY)}, 50)
}
private fun hideRevealView() {
revealMaskView?.resetState()
uiHandler.postDelayed({revealMaskView?.startHide()}, 50)
}
private fun initImageList() {
imageList = findViewById(R.id.images_list) as RecyclerView
imageListAdapter = ImageListAdapter(this)
imageLayoutManager = LinearLayoutManager(this)
imageList?.setLayoutManager(imageLayoutManager)
imageList?.setAdapter(imageListAdapter)
}
override fun onToolbarInitAnimFinish() {
imageListAdapter?.updateItems()
createButton?.animate()!!.translationY(0f).setInterpolator(OvershootInterpolator()).setDuration(300).setStartDelay(250)
}
} | app/src/main/java/com/ragnarok/moviecamera/ui/MainUI.kt | 3814736875 |
package furhatos.app.fortuneteller.setting
import furhatos.records.Location
val maxNumberOfUsers = 2
val distanceToEngage = 1.0 // not used, we use a more complex shape of the interaction space
/** Locations **/
val lookForward = Location(0.0, 0.0, 1.0)
val lookDown = Location(0.0, -10.0, 1.0)
| FortuneTeller/src/main/kotlin/furhatos/app/fortuneteller/setting/engagementParams.kt | 3225778493 |
package com.jiangkang.ktools.web
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.jiangkang.hybrid.Khybrid
import com.jiangkang.ktools.R
import com.jiangkang.ktools.databinding.ActivityHybridBinding
class HybridActivity : AppCompatActivity() {
private val binding by lazy { ActivityHybridBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
handleClick()
}
private fun handleClick() {
binding.btnResourceInterceptor.setOnClickListener {
Khybrid()
.isInterceptResources(true)
.loadUrl(this, "https://www.jiangkang.tech")
}
binding.btnImgLazyLoading.setOnClickListener {
Khybrid()
.isLoadImgLazy(true)
.loadUrl(this, "https://www.jiangkang.tech")
}
binding.btnJsInject.setOnClickListener {
val jsAttack = """
(function(){
for (var obj in window) {
if ("getClass" in window[obj]) {
alert(obj);
return window[obj].getClass().forName("java.lang.Runtime")
.getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs);
}
}
})();
"""
Khybrid()
.injectJs(jsAttack)
.loadUrl(this, "https://www.jiangkang.tech")
}
}
}
| app/src/main/java/com/jiangkang/ktools/web/HybridActivity.kt | 4291169174 |
/*
* Copyright @ 2020 - present 8x8, 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 org.jitsi.videobridge.rest.root.colibri.stats
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import io.mockk.every
import io.mockk.mockk
import jakarta.ws.rs.core.Application
import jakarta.ws.rs.core.MediaType
import jakarta.ws.rs.core.Response
import org.eclipse.jetty.http.HttpStatus
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.test.JerseyTest
import org.glassfish.jersey.test.TestProperties
import org.jitsi.videobridge.rest.MockBinder
import org.jitsi.videobridge.stats.StatsCollector
import org.jitsi.videobridge.stats.VideobridgeStatistics
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import org.junit.Test
class StatsTest : JerseyTest() {
private lateinit var statsCollector: StatsCollector
private val baseUrl = "/colibri/stats"
override fun configure(): Application {
statsCollector = mockk()
enable(TestProperties.LOG_TRAFFIC)
enable(TestProperties.DUMP_ENTITY)
return object : ResourceConfig() {
init {
register(MockBinder(statsCollector, StatsCollector::class.java))
register(Stats::class.java)
}
}
}
@Test
fun testGetStats() {
val fakeStats = mutableMapOf<String, Any>("stat1" to "value1", "stat2" to "value2")
val videobridgeStatistics = mockk<VideobridgeStatistics>()
every { videobridgeStatistics.stats } returns fakeStats
every { statsCollector.statistics } returns videobridgeStatistics
val resp = target(baseUrl).request().get()
resp.status shouldBe HttpStatus.OK_200
resp.mediaType shouldBe MediaType.APPLICATION_JSON_TYPE
resp.getResultAsJson() shouldBe mapOf("stat1" to "value1", "stat2" to "value2")
}
private fun Response.getResultAsJson(): JSONObject {
val obj = JSONParser().parse(readEntity(String::class.java))
obj.shouldBeInstanceOf<JSONObject>()
return obj
}
}
| jvb/src/test/kotlin/org/jitsi/videobridge/rest/root/colibri/stats/StatsTest.kt | 2925388685 |
package com.baulsupp.okurl.services.imgur
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.queryMapValue
import com.baulsupp.okurl.secrets.Secrets
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class ImgurAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition = Oauth2ServiceDefinition(
"api.imgur.com", "Imgur API", "imgur",
"https://api.imgur.com/endpoints", "https://imgur.com/account/settings/apps"
)
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val clientId = Secrets.prompt("Imgur Client Id", "imgur.clientId", "", false)
val clientSecret = Secrets.prompt("Imgur Client Secret", "imgur.clientSecret", "", true)
return ImgurAuthFlow.login(client, outputHandler, clientId, clientSecret)
}
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials =
ValidatedCredentials(
client.queryMapValue<String>(
"https://api.imgur.com/3/account/me",
TokenValue(credentials), "data", "url"
)
)
override fun canRenew(result: Response): Boolean = result.code == 403
override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token {
val body = FormBody.Builder().add("refresh_token", credentials.refreshToken!!)
.add("client_id", credentials.clientId!!)
.add("client_secret", credentials.clientSecret!!)
.add("grant_type", "refresh_token")
.build()
val request = Request.Builder().url("https://api.imgur.com/oauth2/token")
.method("POST", body)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
credentials.refreshToken, credentials.clientId,
credentials.clientSecret
)
}
}
| src/main/kotlin/com/baulsupp/okurl/services/imgur/ImgurAuthInterceptor.kt | 4252520550 |
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R2
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import net.minecraft.world.entity.ai.goal.PathfinderGoal
/**
* Pathfinder NMS proxy to handle native calls.
*/
class Pathfinder(private val pathfinderProxy: PathfinderProxy) : PathfinderGoal() {
/**
* Override ShouldExecute.
*/
override fun a(): Boolean {
return pathfinderProxy.shouldGoalBeExecuted()
}
/**
* Override continue executing.
*/
override fun b(): Boolean {
return pathfinderProxy.shouldGoalContinueExecuting()
}
/**
* Override isInterrupting.
*/
override fun D_(): Boolean {
return pathfinderProxy.isInteruptible
}
/**
* Override startExecuting.
*/
override fun c() {
this.pathfinderProxy.onStartExecuting()
}
/**
* Override reset.
*/
override fun d() {
this.pathfinderProxy.onStopExecuting()
}
/**
* Override update.
*/
override fun e() {
this.pathfinderProxy.onExecute()
}
}
| petblocks-bukkit-plugin/petblocks-bukkit-nms-118R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R2/Pathfinder.kt | 3665486455 |
package io.particle.mesh.setup.flow.setupsteps
import io.particle.mesh.setup.flow.MeshSetupStep
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.context.SetupContexts
import io.particle.mesh.setup.flow.FlowUiDelegate
class StepShowCreateNewMeshNetworkUi(private val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
if (ctxs.mesh.newNetworkCreatedSuccessfully) {
return
}
flowUi.showCreatingMeshNetworkUi()
}
} | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepShowCreateNewMeshNetworkUi.kt | 1270103795 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsIfExpr
import org.rust.lang.core.psi.RsMatchArmGuard
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.parentMatchArm
import org.rust.lang.core.psi.ext.ancestorStrict
class MoveGuardToMatchArmIntention : RsElementBaseIntentionAction<MoveGuardToMatchArmIntention.Context>() {
override fun getText(): String = "Move guard inside the match arm"
override fun getFamilyName(): String = text
data class Context(
val guard: RsMatchArmGuard,
val armBody: RsExpr
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val guard = element.ancestorStrict<RsMatchArmGuard>() ?: return null
val armBody = guard.parentMatchArm.expr ?: return null
return Context(guard, armBody)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (guard, oldBody) = ctx
val caretOffsetInGuard = editor.caretModel.offset - guard.textOffset
val psiFactory = RsPsiFactory(project)
var newBody = psiFactory.createIfExpression(guard.expr, oldBody)
newBody = oldBody.replace(newBody) as RsIfExpr
guard.delete()
editor.caretModel.moveToOffset(newBody.textOffset + caretOffsetInGuard)
}
}
| src/main/kotlin/org/rust/ide/intentions/MoveGuardToMatchArmIntention.kt | 153253859 |
/**
* ownCloud Android client application
*
* @author Abel García de Prada
*
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* 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.owncloud.android.utils.matchers
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.test.espresso.matcher.BoundedMatcher
import org.hamcrest.Description
import org.hamcrest.Matcher
fun withTextColor(
@ColorRes textColor: Int
): Matcher<View> =
object : BoundedMatcher<View, TextView>(TextView::class.java) {
override fun describeTo(description: Description) {
description.appendText("TextView with text color: $textColor")
}
override fun matchesSafely(view: TextView): Boolean {
val expectedColor = ContextCompat.getColor(view.context, textColor)
val actualColor = view.currentTextColor
return actualColor == expectedColor
}
}
| owncloudApp/src/androidTest/java/com/owncloud/android/utils/matchers/TextViewMatcher.kt | 495441234 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview.usecase
import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.Urls
import jp.toastkid.search.SearchCategory
import jp.toastkid.search.UrlFactory
import jp.toastkid.yobidashi.R
class SelectedTextUseCase(
private val urlFactory: UrlFactory = UrlFactory(),
private val stringResolver: (Int, Any) -> String,
private val contentViewModel: ContentViewModel,
private val browserViewModel: BrowserViewModel
) {
fun countCharacters(word: String) {
val codePointCount = word.codePointCount(1, word.length - 1)
val message = stringResolver(R.string.message_character_count, codePointCount)
contentViewModel.snackShort(message)
}
fun search(word: String, searchEngine: String?) {
val url = calculateToUri(word, searchEngine) ?: return
browserViewModel.open(url)
}
fun searchWithPreview(word: String, searchEngine: String?) {
val url = calculateToUri(word, searchEngine) ?: return
browserViewModel.preview(url)
}
private fun calculateToUri(word: String, searchEngine: String?): Uri? {
val cleaned =
if (word.startsWith("\"") && word.length > 10) word.substring(1, word.length - 2)
else word
return if (Urls.isValidUrl(cleaned)) cleaned.toUri()
else makeUrl(word, searchEngine)
}
private fun makeUrl(word: String, searchEngine: String?): Uri? {
if (word.isEmpty() || word == "\"\"") {
contentViewModel.snackShort(R.string.message_failed_query_extraction_from_web_view)
return null
}
return urlFactory(
searchEngine ?: SearchCategory.getDefaultCategoryName(),
word
)
}
companion object {
fun make(context: Context?): SelectedTextUseCase? =
(context as? FragmentActivity)?.let { activity ->
val viewModelProvider = ViewModelProvider(activity)
return SelectedTextUseCase(
stringResolver = { resource, additional -> context.getString(resource, additional) },
contentViewModel = viewModelProvider.get(ContentViewModel::class.java),
browserViewModel = viewModelProvider.get(BrowserViewModel::class.java)
)
}
}
} | app/src/main/java/jp/toastkid/yobidashi/browser/webview/usecase/SelectedTextUseCase.kt | 606996141 |
/*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.transact
open class Position(var sourceIndex: Int) | src/compiler/transact/Position.kt | 2944459051 |
package org.gravidence.gravifon.playlist.item
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("album")
data class AlbumPlaylistItem(val albumPlaylistItems: List<TrackPlaylistItem>) : PlaylistItem() {
} | gravifon/src/main/kotlin/org/gravidence/gravifon/playlist/item/AlbumPlaylistItem.kt | 3514186896 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.ui.debug
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.wear.compose.foundation.CurvedScope
import androidx.wear.compose.foundation.CurvedTextStyle
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.curvedText
import com.google.android.horologist.media3.offload.AudioOffloadStatus
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.DataUsageReport
import com.google.android.horologist.networks.data.NetworkType
import com.google.android.horologist.networks.data.Networks
import com.google.android.horologist.networks.ui.curveDataUsage
@Composable
public fun MediaInfoTimeText(
mediaInfoTimeTextViewModel: MediaInfoTimeTextViewModel,
modifier: Modifier = Modifier
) {
val uiState by mediaInfoTimeTextViewModel.uiState.collectAsStateWithLifecycle()
if (uiState.enabled) {
MediaInfoTimeText(
modifier = modifier,
networkStatus = uiState.networks,
networkUsage = uiState.dataUsageReport,
offloadStatus = uiState.audioOffloadStatus,
pinnedNetworks = uiState.pinnedNetworks
)
} else {
TimeText(modifier = modifier)
}
}
@Composable
public fun MediaInfoTimeText(
networkStatus: Networks,
networkUsage: DataUsageReport?,
offloadStatus: AudioOffloadStatus?,
pinnedNetworks: Set<NetworkType>,
modifier: Modifier = Modifier
) {
val style = CurvedTextStyle(MaterialTheme.typography.caption3)
val context = LocalContext.current
TimeText(
modifier = modifier,
startCurvedContent = {
curveDataUsage(
networkStatus = networkStatus,
networkUsage = networkUsage,
style = style,
context = context,
pinnedNetworks = pinnedNetworks
)
},
endCurvedContent = {
offloadDataStatus(
offloadStatus = offloadStatus,
style = style
)
}
)
}
@ExperimentalHorologistNetworksApi
public fun CurvedScope.offloadDataStatus(
offloadStatus: AudioOffloadStatus?,
style: CurvedTextStyle
) {
if (offloadStatus != null) {
curvedText(
text = offloadStatus.trackOffloadDescription(),
style = style
)
}
}
| media-sample/src/main/java/com/google/android/horologist/mediasample/ui/debug/MediaInfoTimeText.kt | 663227782 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jgit.dirCache
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import org.eclipse.jgit.dircache.BaseDirCacheEditor
import org.eclipse.jgit.dircache.DirCache
import org.eclipse.jgit.dircache.DirCacheEntry
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.FileMode
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.byteBufferToBytes
import org.jetbrains.settingsRepository.removeWithParentsIfEmpty
import java.io.File
import java.io.FileInputStream
import java.text.MessageFormat
import java.util.Comparator
private val EDIT_CMP = object : Comparator<PathEdit> {
override fun compare(o1: PathEdit, o2: PathEdit): Int {
val a = o1.path
val b = o2.path
return DirCache.cmp(a, a.size(), b, b.size())
}
}
/**
* Don't copy edits,
* DeletePath (renamed to DeleteFile) accepts raw path
* Pass repository to apply
*/
public class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) {
private val edits = edits.sortBy(EDIT_CMP)
override fun commit(): Boolean {
if (edits.isEmpty()) {
// No changes? Don't rewrite the index.
//
cache.unlock()
return true
}
return super.commit()
}
override fun finish() {
if (!edits.isEmpty()) {
applyEdits()
replace()
}
}
private fun applyEdits() {
val maxIndex = cache.getEntryCount()
var lastIndex = 0
for (edit in edits) {
var entryIndex = cache.findEntry(edit.path, edit.path.size())
val missing = entryIndex < 0
if (entryIndex < 0) {
entryIndex = -(entryIndex + 1)
}
val count = Math.min(entryIndex, maxIndex) - lastIndex
if (count > 0) {
fastKeep(lastIndex, count)
}
lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex)
if (edit is DeleteFile) {
continue
}
if (edit is DeleteDirectory) {
lastIndex = cache.nextEntry(edit.path, edit.path.size(), entryIndex)
continue
}
if (missing) {
val entry = DirCacheEntry(edit.path)
edit.apply(entry, repository)
if (entry.getRawMode() == 0) {
throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.getPathString()))
}
fastAdd(entry)
}
else if (edit is AddFile || edit is AddLoadedFile) {
// apply to first entry and remove others
var firstEntry = cache.getEntry(entryIndex)
val entry: DirCacheEntry
if (firstEntry.isMerged()) {
entry = firstEntry
}
else {
entry = DirCacheEntry(edit.path)
entry.setCreationTime(firstEntry.getCreationTime())
}
edit.apply(entry, repository)
fastAdd(entry)
}
else {
// apply to all entries of the current path (different stages)
for (i in entryIndex..lastIndex - 1) {
val entry = cache.getEntry(i)
edit.apply(entry, repository)
fastAdd(entry)
}
}
}
val count = maxIndex - lastIndex
if (count > 0) {
fastKeep(lastIndex, count)
}
}
}
public interface PathEdit {
val path: ByteArray
public fun apply(entry: DirCacheEntry, repository: Repository)
}
abstract class PathEditBase(override final val path: ByteArray) : PathEdit
private fun encodePath(path: String): ByteArray {
val bytes = byteBufferToBytes(Constants.CHARSET.encode(path))
if (SystemInfo.isWindows) {
for (i in 0..bytes.size() - 1) {
if (bytes[i].toChar() == '\\') {
bytes[i] = '/'.toByte()
}
}
}
return bytes
}
class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) {
override fun apply(entry: DirCacheEntry, repository: Repository) {
val file = File(repository.getWorkTree(), pathString)
entry.setFileMode(FileMode.REGULAR_FILE)
val length = file.length()
entry.setLength(length)
entry.setLastModified(file.lastModified())
val input = FileInputStream(file)
val inserter = repository.newObjectInserter()
try {
entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input))
inserter.flush()
}
finally {
inserter.close()
input.close()
}
}
}
class AddLoadedFile(path: String, private val content: ByteArray, private val size: Int = content.size(), private val lastModified: Long = System.currentTimeMillis()) : PathEditBase(encodePath(path)) {
override fun apply(entry: DirCacheEntry, repository: Repository) {
entry.setFileMode(FileMode.REGULAR_FILE)
entry.setLength(size)
entry.setLastModified(lastModified)
val inserter = repository.newObjectInserter()
try {
entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content, 0, size))
inserter.flush()
}
finally {
inserter.close()
}
}
}
fun DeleteFile(path: String) = DeleteFile(encodePath(path))
public class DeleteFile(path: ByteArray) : PathEditBase(path) {
override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete)
}
public class DeleteDirectory(entryPath: String) : PathEditBase(encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) {
override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete)
}
public fun Repository.edit(edit: PathEdit) {
edit(listOf(edit))
}
public fun Repository.edit(edits: List<PathEdit>) {
if (edits.isEmpty()) {
return
}
val dirCache = lockDirCache()
try {
DirCacheEditor(edits, this, dirCache, dirCache.getEntryCount() + 4).commit()
}
finally {
dirCache.unlock()
}
}
private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) {
override fun finish() {
replace()
}
}
public fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) {
val dirCache = lockDirCache()
try {
if (deletedSet != null) {
for (i in 0..dirCache.getEntryCount() - 1) {
val entry = dirCache.getEntry(i)
if (entry.getFileMode() == FileMode.REGULAR_FILE) {
deletedSet.add(entry.getPathString())
}
}
}
DirCacheTerminator(dirCache).commit()
}
finally {
dirCache.unlock()
}
if (fromWorkingTree) {
val files = getWorkTree().listFiles { it.getName() != Constants.DOT_GIT }
if (files != null) {
for (file in files) {
FileUtil.delete(file)
}
}
}
}
public fun Repository.writePath(path: String, bytes: ByteArray, size: Int = bytes.size()) {
edit(AddLoadedFile(path, bytes, size))
FileUtil.writeToFile(File(getWorkTree(), path), bytes, 0, size)
}
public fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) {
edit((if (isFile) DeleteFile(path) else DeleteDirectory(path)))
if (fromWorkingTree) {
val workTree = getWorkTree()
val ioFile = File(workTree, path)
if (ioFile.exists()) {
ioFile.removeWithParentsIfEmpty(workTree, isFile)
}
}
} | plugins/settings-repository/src/git/dirCacheEditor.kt | 2930014698 |
package net.yslibrary.monotweety.di
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class FragmentScope
| di-common/src/main/java/net/yslibrary/monotweety/di/FragmentScope.kt | 135191776 |
package net.yslibrary.monotweety.ui.splash
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import net.yslibrary.monotweety.base.CoroutineDispatchers
import net.yslibrary.monotweety.data.session.Session
import net.yslibrary.monotweety.domain.session.ObserveSession
import net.yslibrary.monotweety.ui.arch.Action
import net.yslibrary.monotweety.ui.arch.Effect
import net.yslibrary.monotweety.ui.arch.GlobalAction
import net.yslibrary.monotweety.ui.arch.Intent
import net.yslibrary.monotweety.ui.arch.MviViewModel
import net.yslibrary.monotweety.ui.arch.Processor
import net.yslibrary.monotweety.ui.arch.State
import net.yslibrary.monotweety.ui.arch.ULIEState
import javax.inject.Inject
sealed class SplashIntent : Intent {
object Initialize : SplashIntent()
}
sealed class SplashAction : Action {
object CheckSession : SplashAction()
data class SessionUpdated(
val session: Session?,
) : SplashAction()
}
sealed class SplashEffect : Effect {
object ToLogin : SplashEffect()
object ToMain : SplashEffect()
}
data class SplashState(
val state: ULIEState,
val hasSession: Boolean,
) : State {
companion object {
fun initialState(): SplashState {
return SplashState(
state = ULIEState.UNINITIALIZED,
hasSession = false
)
}
}
}
class SplashProcessor @Inject constructor(
private val observesSession: ObserveSession,
dispatchers: CoroutineDispatchers,
) : Processor<SplashAction>(
dispatchers = dispatchers,
) {
override fun processAction(action: SplashAction) {
when (action) {
SplashAction.CheckSession -> {
doObserveSession()
}
is SplashAction.SessionUpdated -> {
// no-op
}
}
}
private fun doObserveSession() = launch {
val session = observesSession().first()
put(SplashAction.SessionUpdated(session))
}
}
class SplashViewModel @Inject constructor(
dispatchers: CoroutineDispatchers,
processor: SplashProcessor,
) : MviViewModel<SplashIntent, SplashAction, SplashState, SplashEffect>(
initialState = SplashState.initialState(),
dispatchers = dispatchers,
processor = processor,
) {
override fun intentToAction(intent: SplashIntent, state: SplashState): Action {
return when (intent) {
SplashIntent.Initialize -> {
if (state.state == ULIEState.UNINITIALIZED) {
SplashAction.CheckSession
} else {
GlobalAction.NoOp
}
}
}
}
override fun reduce(previousState: SplashState, action: SplashAction): SplashState {
return when (action) {
SplashAction.CheckSession -> {
previousState.copy(state = ULIEState.LOADING)
}
is SplashAction.SessionUpdated -> {
val hasSession = action.session != null
val effect = if (hasSession) SplashEffect.ToMain else SplashEffect.ToLogin
sendEffect(effect)
previousState.copy(
state = ULIEState.IDLE,
hasSession = hasSession
)
}
}
}
}
| app2/src/main/java/net/yslibrary/monotweety/ui/splash/SplashViewModel.kt | 2280614066 |
package remoter.compiler.kbuilder
import com.squareup.kotlinpoet.FunSpec
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.VariableElement
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
/**
* A [ParamBuilder] for float type parameters
*/
internal class FloatParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) {
override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeArrayOutParamsToProxy(param, methodBuilder)
} else {
methodBuilder.addStatement("$DATA.writeFloatArray(" + param.simpleName + ")")
}
} else {
methodBuilder.addStatement("$DATA.writeFloat(" + param.simpleName + ")")
}
}
override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) {
if (resultType.kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeFloatArray($RESULT)")
} else {
methodBuilder.addStatement("$REPLY.writeFloat($RESULT)")
}
}
override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) {
val resultMirror = methodType.getReturnAsTypeMirror()
val resultType = methodType.getReturnAsKotlinType()
if (resultMirror.kind == TypeKind.ARRAY) {
val suffix = if (resultType.isNullable) "" else "!!"
methodBuilder.addStatement("$RESULT = $REPLY.createFloatArray()$suffix")
} else {
methodBuilder.addStatement("$RESULT = $REPLY.readFloat()")
}
}
override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeFloatArray($paramName)")
}
}
override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder)
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeOutParamsToStub(param, paramType, paramName, methodBuilder)
} else {
val suffix = if (param.isNullable()) "" else "!!"
methodBuilder.addStatement("$paramName = $DATA.createFloatArray()$suffix")
}
} else {
methodBuilder.addStatement("$paramName = $DATA.readFloat()")
}
}
override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) {
if (param.isNullable()){
methodBuilder.beginControlFlow("if (${param.simpleName} != null)")
}
methodBuilder.addStatement("$REPLY.readFloatArray(" + param.simpleName + ")")
if (param.isNullable()){
methodBuilder.endControlFlow()
}
}
}
}
| remoter/src/main/java/remoter/compiler/kbuilder/FloatParamBuilder.kt | 2384891473 |
package com.eden.orchid.kotlindoc.page
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.kotlindoc.KotlindocGenerator
import com.eden.orchid.kotlindoc.resources.BaseKotlindocResource
@Archetype(value = ConfigArchetype::class, key = "${KotlindocGenerator.GENERATOR_KEY}.pages")
abstract class BaseKotlindocPage(
resource: BaseKotlindocResource,
key: String,
title: String
) : OrchidPage(resource, key, title)
| plugins/OrchidKotlindoc/src/main/kotlin/com/eden/orchid/kotlindoc/page/BaseKotlindocPage.kt | 1887560703 |
package com.bachhuberdesign.deckbuildergwent.features.deckbuild
import android.database.Cursor
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card
import com.bachhuberdesign.deckbuildergwent.features.shared.model.CardType
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction
import com.bachhuberdesign.deckbuildergwent.util.getBooleanFromColumn
import com.bachhuberdesign.deckbuildergwent.util.getIntFromColumn
import com.bachhuberdesign.deckbuildergwent.util.getLongFromColumn
import com.bachhuberdesign.deckbuildergwent.util.getStringFromColumn
import io.reactivex.functions.Function
import rx.functions.Func1
import java.util.Date
import kotlin.collections.ArrayList
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
data class Deck(var id: Int = 0,
var name: String = "",
var faction: Int = 0,
var leader: Card? = null,
var leaderId: Int = 0,
var cards: MutableList<Card> = ArrayList(),
var isFavorited: Boolean = false,
var createdDate: Date = Date(),
var lastUpdate: Date? = Date()) {
companion object {
const val TABLE = "user_decks"
const val JOIN_CARD_TABLE = "user_decks_cards"
const val ID = "_id"
const val NAME = "name"
const val LEADER_ID = "leader_id"
const val FACTION = "faction"
const val FAVORITED = "favorited"
const val CREATED_DATE = "created_date"
const val LAST_UPDATE = "last_update"
const val MAX_NUM_CARDS = 40
val MAP1 = Func1<Cursor, Deck> { cursor ->
val deck = Deck()
deck.id = cursor.getIntFromColumn(Deck.ID)
deck.name = cursor.getStringFromColumn(Deck.NAME)
deck.faction = cursor.getIntFromColumn(Deck.FACTION)
deck.leaderId = cursor.getIntFromColumn(Deck.LEADER_ID)
deck.isFavorited = cursor.getBooleanFromColumn(Deck.FAVORITED)
deck.createdDate = Date(cursor.getLongFromColumn(Deck.CREATED_DATE))
deck.lastUpdate = Date(cursor.getLongFromColumn(Deck.LAST_UPDATE))
deck
}
val MAPPER = Function<Cursor, Deck> { cursor ->
val deck = Deck()
deck.id = cursor.getIntFromColumn(Deck.ID)
deck.name = cursor.getStringFromColumn(Deck.NAME)
deck.faction = cursor.getIntFromColumn(Deck.FACTION)
deck.leaderId = cursor.getIntFromColumn(Deck.LEADER_ID)
deck.isFavorited = cursor.getBooleanFromColumn(Deck.FAVORITED)
deck.createdDate = Date(cursor.getLongFromColumn(Deck.CREATED_DATE))
deck.lastUpdate = Date(cursor.getLongFromColumn(Deck.LAST_UPDATE))
deck
}
fun isCardAddableToDeck(deck: Deck, card: Card): Boolean {
// Check that deck is not full
if (deck.cards.size >= MAX_NUM_CARDS) {
return false
}
// Check that card is neutral or same faction as deck
if (card.faction != Faction.NEUTRAL) {
if (deck.faction != card.faction) {
return false
}
}
val filteredByCardType = deck.cards.filter {
it.cardType == card.cardType
}
val filteredById = deck.cards.filter {
it.cardId == card.cardId
}
if (card.cardType == CardType.LEADER) return false
if (card.cardType == CardType.BRONZE && filteredById.size >= 3) return false
if (card.cardType == CardType.SILVER && filteredById.isNotEmpty()) return false
if (card.cardType == CardType.SILVER && filteredByCardType.size >= 6) return false
if (card.cardType == CardType.GOLD && filteredById.isNotEmpty()) return false
if (card.cardType == CardType.GOLD && filteredByCardType.size >= 4) return false
return true
}
}
} | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckbuild/Deck.kt | 2249691348 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.presentation.rxpermissions
import android.app.Activity
import android.support.annotation.MainThread
import com.tbruyelle.rxpermissions2.RxPermissions
class RxPermissionsProvider(private val activity: Activity) {
private var rxPermissions: RxPermissions? = null
@MainThread
fun provideRxPermissions(): RxPermissions {
if (rxPermissions == null) {
rxPermissions = RxPermissions(activity)
}
return rxPermissions!!
}
}
| presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/rxpermissions/RxPermissionsProvider.kt | 3868841876 |
/*
* Copyright (C) 2020 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.BuildTask
import org.gradle.testkit.runner.GradleRunner
import org.junit.rules.TemporaryFolder
/**
* Testing utility class that sets up a simple Android project that applies the Hilt plugin.
*/
class GradleTestRunner(val tempFolder: TemporaryFolder) {
private val dependencies = mutableListOf<String>()
private val activities = mutableListOf<String>()
private val additionalAndroidOptions = mutableListOf<String>()
private val hiltOptions = mutableListOf<String>()
private var appClassName: String? = null
private var buildFile: File? = null
private var gradlePropertiesFile: File? = null
private var manifestFile: File? = null
private var additionalTasks = mutableListOf<String>()
init {
tempFolder.newFolder("src", "main", "java", "minimal")
tempFolder.newFolder("src", "test", "java", "minimal")
tempFolder.newFolder("src", "main", "res")
}
// Adds project dependencies, e.g. "implementation <group>:<id>:<version>"
fun addDependencies(vararg deps: String) {
dependencies.addAll(deps)
}
// Adds an <activity> tag in the project's Android Manifest, e.g. "<activity name=".Foo"/>
fun addActivities(vararg activityElements: String) {
activities.addAll(activityElements)
}
// Adds 'android' options to the project's build.gradle, e.g. "lintOptions.checkReleaseBuilds = false"
fun addAndroidOption(vararg options: String) {
additionalAndroidOptions.addAll(options)
}
// Adds 'hilt' options to the project's build.gradle, e.g. "enableExperimentalClasspathAggregation = true"
fun addHiltOption(vararg options: String) {
hiltOptions.addAll(options)
}
// Adds a source package to the project. The package path is relative to 'src/main/java'.
fun addSrcPackage(packagePath: String) {
File(tempFolder.root, "src/main/java/$packagePath").mkdirs()
}
// Adds a source file to the project. The source path is relative to 'src/main/java'.
fun addSrc(srcPath: String, srcContent: String): File {
File(tempFolder.root, "src/main/java/${srcPath.substringBeforeLast(File.separator)}").mkdirs()
return tempFolder.newFile("/src/main/java/$srcPath").apply { writeText(srcContent) }
}
// Adds a test source file to the project. The source path is relative to 'src/test/java'.
fun addTestSrc(srcPath: String, srcContent: String): File {
File(tempFolder.root, "src/test/java/${srcPath.substringBeforeLast(File.separator)}").mkdirs()
return tempFolder.newFile("/src/test/java/$srcPath").apply { writeText(srcContent) }
}
// Adds a resource file to the project. The source path is relative to 'src/main/res'.
fun addRes(resPath: String, resContent: String): File {
File(tempFolder.root, "src/main/res/${resPath.substringBeforeLast(File.separator)}").mkdirs()
return tempFolder.newFile("/src/main/res/$resPath").apply { writeText(resContent) }
}
fun setAppClassName(name: String) {
appClassName = name
}
fun runAdditionalTasks(taskName: String) {
additionalTasks.add(taskName)
}
// Executes a Gradle builds and expects it to succeed.
fun build(): Result {
setupFiles()
return Result(tempFolder.root, createRunner().build())
}
// Executes a Gradle build and expects it to fail.
fun buildAndFail(): Result {
setupFiles()
return Result(tempFolder.root, createRunner().buildAndFail())
}
private fun setupFiles() {
writeBuildFile()
writeGradleProperties()
writeAndroidManifest()
}
private fun writeBuildFile() {
buildFile?.delete()
buildFile = tempFolder.newFile("build.gradle").apply {
writeText(
"""
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.0'
}
}
plugins {
id 'com.android.application'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "plugin.test"
minSdkVersion 21
targetSdkVersion 30
}
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
${additionalAndroidOptions.joinToString(separator = "\n")}
}
allprojects {
repositories {
mavenLocal()
google()
jcenter()
}
}
dependencies {
${dependencies.joinToString(separator = "\n")}
}
hilt {
${hiltOptions.joinToString(separator = "\n")}
}
""".trimIndent()
)
}
}
private fun writeGradleProperties() {
gradlePropertiesFile?.delete()
gradlePropertiesFile = tempFolder.newFile("gradle.properties").apply {
writeText(
"""
android.useAndroidX=true
""".trimIndent()
)
}
}
private fun writeAndroidManifest() {
manifestFile?.delete()
manifestFile = tempFolder.newFile("/src/main/AndroidManifest.xml").apply {
writeText(
"""
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="minimal">
<application
android:name="${appClassName ?: "android.app.Application"}"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
${activities.joinToString(separator = "\n")}
</application>
</manifest>
""".trimIndent()
)
}
}
private fun createRunner() = GradleRunner.create()
.withProjectDir(tempFolder.root)
.withArguments(listOf("--stacktrace", "assembleDebug") + additionalTasks)
.withPluginClasspath()
// .withDebug(true) // Add this line to enable attaching a debugger to the gradle test invocation
.forwardOutput()
// Data class representing a Gradle Test run result.
data class Result(
private val projectRoot: File,
private val buildResult: BuildResult
) {
val tasks: List<BuildTask> get() = buildResult.tasks
// Finds a task by name.
fun getTask(name: String) = buildResult.task(name) ?: error("Task '$name' not found.")
// Gets the full build output.
fun getOutput() = buildResult.output
// Finds a transformed file. The srcFilePath is relative to the app's package.
fun getTransformedFile(srcFilePath: String): File {
val parentDir =
File(projectRoot, "build/intermediates/asm_instrumented_project_classes/debug")
return File(parentDir, srcFilePath).also {
if (!it.exists()) {
error("Unable to find transformed class ${it.path}")
}
}
}
}
}
| java/dagger/hilt/android/plugin/src/test/kotlin/GradleTestRunner.kt | 2746577367 |
package kota.resources
import android.Manifest
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import junit.framework.Assert.assertEquals
import kota.isSelfPermissionsGranted
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author Hendra Anggrian ([email protected])
*/
@RunWith(AndroidJUnit4::class)
class PermissionsTest {
private val context = InstrumentationRegistry.getTargetContext()
@Test
@Throws(Exception::class)
fun isGranted() {
assertEquals(context.isSelfPermissionsGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE), false)
}
} | kota/tests/src/kota/resources/PermissionsTest.kt | 3798691191 |
package io.noties.markwon.app.samples
import android.widget.Toast
import io.noties.markwon.Markwon
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
@MarkwonSampleInfo(
id = "20200627072642",
title = "Markdown in Toast",
description = "Display _static_ markdown content in a `android.widget.Toast`",
artifacts = [MarkwonArtifact.CORE],
tags = [Tag.toast]
)
class ToastSample : MarkwonTextViewSample() {
override fun render() {
// NB! only _static_ content is going to be displayed,
// so, no images, tables or latex in a Toast
val md = """
# Heading is fine
> Even quote if **fine**
```
finally code works;
```
_italic_ to put an end to it
""".trimIndent()
val markwon = Markwon.create(context)
// render raw input to styled markdown
val markdown = markwon.toMarkdown(md)
// Toast accepts CharSequence and allows styling via spans
Toast.makeText(context, markdown, Toast.LENGTH_LONG).show()
}
} | app-sample/src/main/java/io/noties/markwon/app/samples/ToastSample.kt | 2918178477 |
/*
* 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
*
* 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 app.tivi.data.repositories.episodes
import app.tivi.data.daos.LastRequestDao
import app.tivi.data.entities.Request
import app.tivi.data.repositories.lastrequests.EntityLastRequestStore
import javax.inject.Inject
class SeasonsLastRequestStore @Inject constructor(
dao: LastRequestDao
) : EntityLastRequestStore(Request.SHOW_SEASONS, dao)
| data/src/main/java/app/tivi/data/repositories/episodes/SeasonsLastRequestStore.kt | 3613806230 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElementVisitor
abstract class MdPsiElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), MdPsiElement {
override fun accept(visitor: PsiElementVisitor) {
if (visitor is MdPsiVisitor)
visitor.visitPsiElement(this)
else
super.accept(visitor)
}
override fun getName(): String? {
return text
}
// override fun getPresentation(): ItemPresentation {
// return MdPsiImplUtil.getPresentation(this)
// }
companion object {
private val LOG = Logger.getInstance(MdPsiElementImpl::class.java)
}
}
| src/main/java/com/vladsch/md/nav/psi/element/MdPsiElementImpl.kt | 3472289076 |
package xyz.mustafaali.devqstiles.service
import android.graphics.drawable.Icon
import android.service.quicksettings.TileService
import xyz.mustafaali.devqstiles.util.AnimationScaler
/**
* A {@link TileService} for toggling Window Animation Scale, Transition Animation Scale, and Animator Duration Scale.
*/
class ToggleAnimationService : TileService() {
override fun onStartListening() {
super.onStartListening()
updateTile()
}
override fun onClick() {
AnimationScaler.toggleAnimationScale(this)
updateTile()
}
private fun updateTile() {
val scale = AnimationScaler.getAnimationScale(contentResolver)
val tile = qsTile
tile.icon = Icon.createWithResource(applicationContext, AnimationScaler.getIcon(scale))
tile.updateTile()
}
} | app/src/main/kotlin/xyz/mustafaali/devqstiles/service/ToggleAnimationService.kt | 1966441072 |
/*
* Copyright (C) 2018. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.data
import com.openlattice.data.storage.*
import com.openlattice.edm.type.PropertyType
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.junit.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class PostgresLinkedEntityDataQueryServiceTest {
private val logger: Logger = LoggerFactory.getLogger(PostgresLinkedEntityDataQueryServiceTest::class.java)
@Test
fun testLinkingEntitySetQuery() {
val propertyTypes = listOf(
PropertyType(UUID.fromString("c270d705-3616-4abc-b16e-f891e264b784"), FullQualifiedName("im.PersonNickName"), "PersonNickName", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("7b038634-a0b4-4ce1-a04f-85d1775937aa"), FullQualifiedName("nc.PersonSurName"), "PersonSurName", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("8293b7f3-d89d-44f5-bec2-6397a4c5af8b"), FullQualifiedName("nc.PersonHairColorText"), "PersonHairColorText", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("5260cfbd-bfa4-40c1-ade5-cd83cc9f99b2"), FullQualifiedName("nc.SubjectIdentification"), "SubjectIdentification", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("e9a0b4dc-5298-47c1-8837-20af172379a5"), FullQualifiedName("nc.PersonGivenName"), "PersonGivenName", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("d0935a7e-efd3-4903-b673-0869ef527dea"), FullQualifiedName("nc.PersonMiddleName"), "PersonMiddleName", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("45aa6695-a7e7-46b6-96bd-782e6aa9ac13"), FullQualifiedName("publicsafety.mugshot"), "mugshot", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.Binary),
PropertyType(UUID.fromString("1e6ff0f0-0545-4368-b878-677823459e57"), FullQualifiedName("nc.PersonBirthDate"), "PersonBirthDate", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.Date),
PropertyType(UUID.fromString("ac37e344-62da-4b50-b608-0618a923a92d"), FullQualifiedName("nc.PersonEyeColorText"), "PersonEyeColorText", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("481f59e4-e146-4963-a837-4f4e514df8b7"), FullQualifiedName("nc.SSN"), "SSN", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("d9a90e01-9670-46e8-b142-6d0c4871f633"), FullQualifiedName("j.SentenceRegisterSexOffenderIndicator"), "SentenceRegisterSexOffenderIndicator", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.Int32),
PropertyType(UUID.fromString("d3f3f3de-dc1b-40da-9076-683ddbfeb4d8"), FullQualifiedName("nc.PersonSuffix"), "PersonSuffix", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("f0a6a588-aee7-49a2-8f8e-e5209731da30"), FullQualifiedName("nc.PersonHeightMeasure"), "PersonHeightMeasure", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.Int32),
PropertyType(UUID.fromString("fa00bfdb-98ec-487a-b62f-f6614e4c921b"), FullQualifiedName("criminaljustice.persontype"), "persontype", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("5ea6e8d5-93bb-47cf-b054-9faaeb05fb27"), FullQualifiedName("person.stateidstate"), "stateidstate", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("6ec154f8-a4a1-4df2-8c57-d98cbac1478e"), FullQualifiedName("nc.PersonSex"), "PersonSex", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("cf4598e7-5bbe-49f7-8935-4b1a692f6111"), FullQualifiedName("nc.PersonBirthPlace"), "PersonBirthPlace", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("32eba813-7d20-4be1-bc1a-717f99917a5e"), FullQualifiedName("housing.notes"), "notes", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("c7d2c503-651d-483f-8c17-72358bcfc5cc"), FullQualifiedName("justice.xref"), "xref", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("f950d05a-f4f2-451b-8c6d-56e78bba8b42"), FullQualifiedName("nc.PersonRace"), "PersonRace", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String),
PropertyType(UUID.fromString("314d2bfd-e50e-4965-b2eb-422742fa265c"), FullQualifiedName("housing.updatedat"), "updatedat", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.DateTimeOffset),
PropertyType(UUID.fromString("1407ac70-ea63-4879-aca4-6722034f0cda"), FullQualifiedName("nc.PersonEthnicity"), "PersonEthnicity", Optional.empty<String>(), setOf(), EdmPrimitiveTypeKind.String)
)
logger.info(
"Linking entity set query:\n{}",
buildPreparableFiltersSql(
0,
propertyTypes.associateBy { it.id },
mapOf(),
EnumSet.of( MetadataOption.ENTITY_KEY_IDS),
linking = true,
idsPresent = true,
partitionsPresent = true
).first
)
}
}
| src/test/kotlin/com/openlattice/data/PostgresLinkedEntityDataQueryServiceTest.kt | 1415277338 |
package com.openlattice.datastore.configuration
import com.fasterxml.jackson.annotation.JsonProperty
import com.kryptnostic.rhizome.configuration.Configuration
import com.kryptnostic.rhizome.configuration.ConfigurationKey
import com.kryptnostic.rhizome.configuration.SimpleConfigurationKey
import com.kryptnostic.rhizome.configuration.annotation.ReloadableConfiguration
import com.openlattice.conductor.rpc.SearchConfiguration
import java.util.*
const val BUCKET_NAME = "bucketName"
const val REGION_NAME = "regionName"
const val TIME_TO_LIVE = "timeToLive"
const val ACCESS_KEY_ID = "accessKeyId"
const val SECRET_ACCESS_KEY = "secretAccessKey"
const val SEARCH_CONFIGURATION = "searchConfiguration"
@ReloadableConfiguration(uri = "datastore.yaml")
data class DatastoreConfiguration(
@JsonProperty(BUCKET_NAME) val bucketName: String,
@JsonProperty(REGION_NAME) val regionName: String,
@JsonProperty(TIME_TO_LIVE) val timeToLive: Long,
@JsonProperty(ACCESS_KEY_ID) val accessKeyId: String,
@JsonProperty(SECRET_ACCESS_KEY) val secretAccessKey: String,
@JsonProperty("readOnlyReplica") val readOnlyReplica: Properties = Properties(),
@JsonProperty("googleMapsApiKey") val googleMapsApiKey: String = "",
@JsonProperty(SEARCH_CONFIGURATION ) val searchConfiguration: SearchConfiguration
) : Configuration {
companion object {
@JvmStatic
@get:JvmName("key")
val key = SimpleConfigurationKey("datastore.yaml")
}
override fun getKey(): ConfigurationKey {
return DatastoreConfiguration.key
}
} | src/main/java/com/openlattice/datastore/configuration/DatastoreConfiguration.kt | 3855609477 |
package fr.letroll.githubbookmarkmanager.data.model
import java.util.*
/**
* Created by jquievreux on 05/12/14.
*/
public data class RepoAuthorization(
var id: Int,
var url: String,
var app: App,
var token: String,
var note: String,
var note_url: String,
var created_at: String,
var updated_at: String,
var scopes: List<String>)
// public var id: kotlin.Int = -1
//
// public var url: String = ""
//
// public var app: App = App()
//
// public var token: String = ""
//
// public var note: String = ""
//
// public var note_url: String = ""
//
// public var created_at: String = ""
//
// public var updated_at: String = ""
//
// public var scopes: List<String> = ArrayList<String>()
//} | app/src/main/kotlin/fr/letroll/githubbookmarkmanager/data/model/RepoAuthorization.kt | 2203106376 |
@file:Suppress("unused")
package kodando.react.router.dom
/**
* Created by danfma on 04/04/17.
*/
inline var RouteTo.toUrl: String
get() = this.to as String
set(value) {
this.to = value
}
inline var RouteTo.toLocation: Location
get() = this.to as Location
set(value) {
this.to = value
}
inline var PromptProps.messageText: String
get() = this.message as String
set(value) {
this.message = value
}
inline var PromptProps.messageFunc: (Location) -> String
get() = this.message.unsafeCast<(Location) -> String>()
set(value) {
this.message = value.unsafeCast<Any>()
}
| kodando-react-router-dom/src/main/kotlin/kodando/react/router/dom/Extensions.kt | 2293930255 |
/*
* Copyright (C) 2018, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.ui.base.delegate
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import com.andretietz.retroauth.*
/**
* Copied from https://github.com/andretietz/retroauth/blob/master/retroauth-android/src/main/java/com/andretietz/retroauth/AuthenticationActivity.kt
* To extend custom classes
*/
/**
* Your activity that's supposed to create the account (i.e. Login{@link android.app.Activity}) has to implement this.
* It'll provide functionality to {@link #storeCredentials(Account, String, String)} and
* {@link #storeUserData(Account, String, String)} when logging in. In case your service is providing a refresh token,
* use {@link #storeCredentials(Account, String, String, String)}. This will additionally store a refresh token that
* can be used in {@link Authenticator#validateResponse(int, okhttp3.Response, TokenStorage, Object, Object, Object)}
* to update the access-token
*/
abstract class AuthenticationActivity : ComponentActivity() {
private var accountAuthenticatorResponse: AccountAuthenticatorResponse? = null
private lateinit var accountType: String
private lateinit var accountManager: AccountManager
private var credentialType: String? = null
private lateinit var resultBundle: Bundle
private lateinit var credentialStorage: AndroidCredentialStorage
protected val ownerManager by lazy { AndroidOwnerStorage(application) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
accountManager = AccountManager.get(application)
credentialStorage = AndroidCredentialStorage(application)
accountAuthenticatorResponse = intent.getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)
accountAuthenticatorResponse?.onRequestContinued()
val accountType = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)
if (accountType == null) {
accountAuthenticatorResponse?.onError(AccountManager.ERROR_CODE_CANCELED, "canceled")
throw IllegalStateException(
String.format(
"This Activity cannot be started without the \"%s\" extra in the intent! " +
"Use the \"createAccount\"-Method of the \"%s\" for opening the Login manually.",
AccountManager.KEY_ACCOUNT_TYPE, OwnerStorage::class.java.simpleName
)
)
}
this.accountType = accountType
credentialType = intent.getStringExtra("account_credential_type")
resultBundle = Bundle()
resultBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType)
}
/**
* This method stores an authentication Token to a specific account.
*
* @param account Account you want to store the credentials for
* @param credentialType type of the credentials you want to store
* @param credentials the AndroidToken
*/
fun storeCredentials(account: Account, credentialType: AndroidCredentialType, credentials: AndroidCredentials) {
credentialStorage.storeCredentials(account, credentialType, credentials)
}
/**
* With this you can store some additional userdata in key-value-pairs to the account.
*
* @param account Account you want to store information for
* @param key the key for the data
* @param value the actual data you want to store
*/
fun storeUserData(account: Account, key: String, value: String?) {
accountManager.setUserData(account, key, value)
}
/**
* This method will finish the login process. Depending on the finishActivity flag, the activity
* will be finished or not. The account which is reached into this method will be set as
* "current" account.
*
* @param account Account you want to set as current active
* @param finishActivity when `true`, the activity will be finished after finalization.
*/
@JvmOverloads
fun finalizeAuthentication(account: Account, finishActivity: Boolean = true) {
resultBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name)
ownerManager.switchActiveOwner(account.type, account)
if (finishActivity) finish()
}
/**
* Tries finding an existing account with the given name.
* It creates a new Account if it couldn't find it
*
* @param accountName Name of the account you're searching for
* @return The account if found, or a newly created one
*/
fun createOrGetAccount(accountName: String): Account {
// if this is a relogin
val accountList = accountManager.getAccountsByType(accountType)
for (account in accountList) {
if (account.name == accountName)
return account
}
val account = Account(accountName, accountType)
accountManager.addAccountExplicitly(account, null, null)
return account
}
/**
* If for some reason an account was created already and the login couldn't complete successfully, you can user this
* method to remove this account
*
* @param account to remove
*/
@Suppress("DEPRECATION")
fun removeAccount(account: Account) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
accountManager.removeAccount(account, null, null, null)
} else {
accountManager.removeAccount(account, null, null)
}
}
/**
* Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
*/
override fun finish() {
if (accountAuthenticatorResponse != null) {
accountAuthenticatorResponse?.onResult(resultBundle)
accountAuthenticatorResponse = null
} else {
if (resultBundle.containsKey(AccountManager.KEY_ACCOUNT_NAME)) {
val intent = Intent()
intent.putExtras(resultBundle)
setResult(Activity.RESULT_OK, intent)
} else {
setResult(Activity.RESULT_CANCELED)
}
}
super.finish()
}
/**
* @return The requested account type if available. otherwise `null`
*/
fun getRequestedAccountType() = accountType
/**
* @return The requested token type if available. otherwise `null`
*/
fun getRequestedCredentialType() = credentialType
}
| modules/base-android/src/main/java/tm/alashow/base/ui/base/delegate/AuthenticationActivity.kt | 3464140593 |
package src.configuration
import components.progressBar.MenuBar
import components.progressBar.Panel
import components.progressBar.StatusBar
import java.util.*
/**
* Created by vicboma on 02/12/16.
*/
class ConfigurationImpl internal constructor(override val display: Display, override val panel: ArrayList<Panel>, override val menuBar: MenuBar, override val statusBar: StatusBar) : Configuration {
companion object {
fun create(display: Display, panel: ArrayList<Panel>, menuBar: MenuBar, statusBar: StatusBar): Configuration {
return ConfigurationImpl(display, panel, menuBar,statusBar)
}
}
}
| 06-start-async-subMenubar-application/src/main/kotlin/configuration/ConfigurationImpl.kt | 942915128 |
package com.ddiehl.android.htn.di
import android.content.Context
import com.ddiehl.android.htn.BuildConfig
import com.ddiehl.android.htn.identity.IdentityManager
import com.ddiehl.android.htn.identity.IdentityManagerImpl
import com.ddiehl.android.htn.managers.NetworkConnectivityManager
import com.ddiehl.android.htn.settings.SettingsManager
import com.ddiehl.android.htn.settings.SettingsManagerImpl
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import rxreddit.android.AndroidAccessTokenManager
import rxreddit.android.AndroidUtil
import rxreddit.api.RedditService
import rxreddit.util.RxRedditUtil
import java.io.File
import javax.inject.Named
import javax.inject.Singleton
@Module
class ApplicationModule(context: Context) {
private val appContext: Context = context.applicationContext
@Provides
fun providesAppContext(): Context {
return appContext
}
@Singleton
@Provides
fun providesIdentityManager(context: Context?, settingsManager: SettingsManager?): IdentityManager {
return IdentityManagerImpl(context, settingsManager)
}
@Singleton
@Provides
fun providesSettingsManager(context: Context?): SettingsManager {
return SettingsManagerImpl(context!!)
}
@Provides
@Named("RedditServiceScope")
fun providesRedditServiceScope(): List<String> {
return listOf(
"identity",
"mysubreddits",
"privatemessages",
"read",
"report",
"save",
"submit",
"vote",
"history",
"account",
"subscribe",
)
}
@Singleton
@Provides
fun providesRedditService(
context: Context,
@Named("RedditServiceScope") scopeList: List<String>,
): RedditService {
// return new RedditServiceMock();
val cacheSize = 10 * 1024 * 1024 // 10 MiB
val path = File(context.cacheDir, "htn-http-cache")
val userAgent = RxRedditUtil.getUserAgent(
"android", "com.ddiehl.android.htn", BuildConfig.VERSION_NAME, "damien5314"
)
return RedditService.Builder()
.appId(BuildConfig.REDDIT_APP_ID)
.redirectUri(BuildConfig.REDDIT_REDIRECT_URI)
.scopes(scopeList)
.deviceId(AndroidUtil.getDeviceId(context))
.userAgent(userAgent)
.accessTokenManager(AndroidAccessTokenManager(context))
.cache(cacheSize, path)
.loggingEnabled(BuildConfig.DEBUG)
.build()
}
@Provides
fun providesGson(redditService: RedditService): Gson {
return redditService.gson
}
@Provides
fun providesNetworkConnectivityManager(context: Context): NetworkConnectivityManager {
return NetworkConnectivityManager(context)
}
}
| app/src/main/java/com/ddiehl/android/htn/di/ApplicationModule.kt | 945175181 |
package com.easternedgerobotics.rov.value
data class InternalPressureValue(val pressure: Float = 0f)
| src/main/kotlin/com/easternedgerobotics/rov/value/InternalPressureValue.kt | 1750275985 |
package io.envoyproxy.envoymobile
import java.util.concurrent.Executor
/**
* Mock implementation of `StreamPrototype` which is used to produce `MockStream` instances.
*
* @param onStart Closure that will be called each time a new stream is started from the prototype.
*/
class MockStreamPrototype internal constructor(private val onStart: ((stream: MockStream) -> Unit)?) : StreamPrototype(MockEnvoyEngine()) {
override fun start(executor: Executor): Stream {
val callbacks = createCallbacks(executor)
val stream = MockStream(MockEnvoyHTTPStream(callbacks, false))
onStart?.invoke(stream)
return stream
}
}
| mobile/library/kotlin/io/envoyproxy/envoymobile/mocks/MockStreamPrototype.kt | 3940384842 |
package io.gitlab.arturbosch.detekt.api
/**
* Rules can classified into different severity grades. Maintainer can choose
* a grade which is most harmful to their projects.
*/
enum class Severity {
/**
* Represents clean coding violations which may lead to maintainability issues.
*/
CodeSmell,
/**
* Inspections in this category detect violations of code syntax styles.
*/
Style,
/**
* Corresponds to issues that do not prevent the code from working,
* but may nevertheless represent coding inefficiencies.
*/
Warning,
/**
* Corresponds to coding mistakes which could lead to unwanted behavior.
*/
Defect,
/**
* Represents code quality issues which only slightly impact the code quality.
*/
Minor,
/**
* Issues in this category make the source code confusing and difficult to maintain.
*/
Maintainability,
/**
* Places in the source code that can be exploited and possibly result in significant damage.
*/
Security,
/**
* Places in the source code which degrade the performance of the application.
*/
Performance
}
| detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Severity.kt | 2388622403 |
package de.christinecoenen.code.zapp.models.shows
enum class DownloadStatus {
NONE,
QUEUED,
DOWNLOADING,
PAUSED,
COMPLETED,
CANCELLED,
FAILED,
REMOVED,
DELETED,
ADDED;
}
| app/src/main/java/de/christinecoenen/code/zapp/models/shows/DownloadStatus.kt | 3628295246 |
package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.test.KtTestCompiler
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UnnecessaryNotNullOperatorSpec : Spek({
val subject by memoized { UnnecessaryNotNullOperator() }
val wrapper by memoized(
factory = { KtTestCompiler.createEnvironment() },
destructor = { it.dispose() }
)
describe("check unnecessary not null operators") {
it("reports a simple not null operator usage") {
val code = """
val a = 1
val b = a!!
"""
val findings = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(18 to 21)
}
it("reports a chained not null operator usage") {
val code = """
val a = 1
val b = a!!.plus(42)
"""
val findings = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(18 to 21)
}
it("reports multiple chained not null operator usage") {
val code = """
val a = 1
val b = a!!.plus(42)!!
"""
val findings = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(findings).hasSize(2)
assertThat(findings).hasTextLocations(18 to 21, 18 to 32)
}
}
describe("check valid not null operators usage") {
it("does not report a simple not null operator usage on nullable type") {
val code = """
val a : Int? = 1
val b = a!!
"""
val findings = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(findings).isEmpty()
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UnnecessaryNotNullOperatorSpec.kt | 3582679462 |
package com.infinum.dbinspector.domain.schema.table.usecases
import com.infinum.dbinspector.domain.Repositories
import com.infinum.dbinspector.domain.UseCases
import com.infinum.dbinspector.domain.shared.models.Page
import com.infinum.dbinspector.domain.shared.models.parameters.ConnectionParameters
import com.infinum.dbinspector.domain.shared.models.parameters.ContentParameters
internal class GetTableUseCase(
private val connectionRepository: Repositories.Connection,
private val schemaRepository: Repositories.Schema
) : UseCases.GetTable {
override suspend fun invoke(input: ContentParameters): Page {
val connection = connectionRepository.open(ConnectionParameters(input.databasePath))
return schemaRepository.getByName(
input.copy(
connection = connection
)
)
}
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/schema/table/usecases/GetTableUseCase.kt | 444705170 |
package de.westnordost.streetcomplete.user
import android.animation.LayoutTransition
import android.animation.LayoutTransition.APPEARING
import android.animation.LayoutTransition.DISAPPEARING
import android.animation.TimeAnimator
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewPropertyAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import androidx.core.net.toUri
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import de.westnordost.streetcomplete.HandlesOnBackPressed
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.user.achievements.Achievement
import de.westnordost.streetcomplete.databinding.FragmentAchievementInfoBinding
import de.westnordost.streetcomplete.ktx.tryStartActivity
import de.westnordost.streetcomplete.ktx.viewBinding
import de.westnordost.streetcomplete.util.Transforms
import de.westnordost.streetcomplete.util.animateFrom
import de.westnordost.streetcomplete.util.animateTo
import de.westnordost.streetcomplete.util.applyTransforms
/** Shows details for a certain level of one achievement as a fake-dialog.
* There are two modes:
*
* 1. Show details of a newly achieved achievement. The achievement icon animates in in a fancy way
* and some shining animation is played. The unlocked links are shown.
*
* 2. Show details of an already achieved achievement. The achievement icon animates from another
* view to its current position, no shining animation is played. Also, the unlocked links are
* not shown because they can be looked at in the links screen.
*
* It is not a real dialog because a real dialog has its own window, or in other words, has a
* different root view than the rest of the UI. However, for the calculation to animate the icon
* from another view to the position in the "dialog", there must be a common root view.
* */
class AchievementInfoFragment : Fragment(R.layout.fragment_achievement_info),
HandlesOnBackPressed {
private val binding by viewBinding(FragmentAchievementInfoBinding::bind)
/** View from which the achievement icon is animated from (and back on dismissal)*/
private var achievementIconBubble: View? = null
var isShowing: Boolean = false
private set
// need to keep the animators here to be able to clear them on cancel
private val currentAnimators: MutableList<ViewPropertyAnimator> = mutableListOf()
private var shineAnimation: TimeAnimator? = null
private val layoutTransition: LayoutTransition = LayoutTransition()
/* ---------------------------------------- Lifecycle --------------------------------------- */
init {
layoutTransition.disableTransitionType(APPEARING)
layoutTransition.disableTransitionType(DISAPPEARING)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.dialogAndBackgroundContainer.setOnClickListener { dismiss() }
// in order to not show the scroll indicators
binding.unlockedLinksList.isNestedScrollingEnabled = false
binding.unlockedLinksList.layoutManager = object : LinearLayoutManager(requireContext(), VERTICAL, false) {
override fun canScrollVertically() = false
}
}
override fun onBackPressed(): Boolean {
if (isShowing) {
dismiss()
return true
}
return false
}
override fun onDestroyView() {
super.onDestroyView()
achievementIconBubble = null
clearAnimators()
shineAnimation?.cancel()
shineAnimation = null
}
/* ---------------------------------------- Interface --------------------------------------- */
/** Show as details of a tapped view */
fun show(achievement: Achievement, level: Int, achievementBubbleView: View): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = true
this.achievementIconBubble = achievementBubbleView
bind(achievement, level, false)
animateInFromView(achievementBubbleView)
return true
}
/** Show as new achievement achieved/unlocked */
fun showNew(achievement: Achievement, level: Int): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = true
bind(achievement, level, true)
animateIn()
return true
}
fun dismiss(): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = false
animateOut(achievementIconBubble)
return true
}
/* ----------------------------------- Animating in and out --------------------------------- */
private fun bind(achievement: Achievement, level: Int, showLinks: Boolean) {
binding.achievementIconView.icon = context?.getDrawable(achievement.icon)
binding.achievementIconView.level = level
binding.achievementTitleText.setText(achievement.title)
binding.achievementDescriptionText.isGone = achievement.description == null
if (achievement.description != null) {
val arg = achievement.getPointThreshold(level)
binding.achievementDescriptionText.text = resources.getString(achievement.description, arg)
} else {
binding.achievementDescriptionText.text = ""
}
val unlockedLinks = achievement.unlockedLinks[level].orEmpty()
val hasNoUnlockedLinks = unlockedLinks.isEmpty() || !showLinks
binding.unlockedLinkTitleText.isGone = hasNoUnlockedLinks
binding.unlockedLinksList.isGone = hasNoUnlockedLinks
if (hasNoUnlockedLinks) {
binding.unlockedLinksList.adapter = null
} else {
binding.unlockedLinkTitleText.setText(
if (unlockedLinks.size == 1) R.string.achievements_unlocked_link
else R.string.achievements_unlocked_links
)
binding.unlockedLinksList.adapter = LinksAdapter(unlockedLinks, this::openUrl)
}
}
private fun animateIn() {
binding.dialogAndBackgroundContainer.visibility = View.VISIBLE
shineAnimation?.cancel()
val anim = TimeAnimator()
anim.setTimeListener { _, _, deltaTime ->
binding.shineView1.rotation += deltaTime / 50f
binding.shineView2.rotation -= deltaTime / 100f
}
anim.start()
shineAnimation = anim
clearAnimators()
currentAnimators.addAll(
createShineFadeInAnimations() +
createDialogPopInAnimations(DIALOG_APPEAR_DELAY_IN_MS) +
listOf(
createFadeInBackgroundAnimation(),
createAchievementIconPopInAnimation()
)
)
currentAnimators.forEach { it.start() }
}
private fun animateInFromView(questBubbleView: View) {
questBubbleView.visibility = View.INVISIBLE
binding.dialogAndBackgroundContainer.visibility = View.VISIBLE
binding.shineView1.visibility = View.GONE
binding.shineView2.visibility = View.GONE
currentAnimators.addAll(createDialogPopInAnimations() + listOf(
createFadeInBackgroundAnimation(),
createAchievementIconFlingInAnimation(questBubbleView)
))
currentAnimators.forEach { it.start() }
}
private fun animateOut(questBubbleView: View?) {
binding.dialogContainer.layoutTransition = null
val iconAnimator = if (questBubbleView != null) {
createAchievementIconFlingOutAnimation(questBubbleView)
} else {
createAchievementIconPopOutAnimation()
}
currentAnimators.addAll(
createDialogPopOutAnimations() +
createShineFadeOutAnimations() +
listOf(
createFadeOutBackgroundAnimation(),
iconAnimator
)
)
currentAnimators.forEach { it.start() }
}
private fun createAchievementIconFlingInAnimation(sourceView: View): ViewPropertyAnimator {
sourceView.visibility = View.INVISIBLE
val root = sourceView.rootView as ViewGroup
binding.achievementIconView.applyTransforms(Transforms.IDENTITY)
binding.achievementIconView.alpha = 1f
return binding.achievementIconView.animateFrom(sourceView, root)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
private fun createAchievementIconFlingOutAnimation(targetView: View): ViewPropertyAnimator {
val root = targetView.rootView as ViewGroup
return binding.achievementIconView.animateTo(targetView, root)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateDecelerateInterpolator())
.withEndAction {
targetView.visibility = View.VISIBLE
achievementIconBubble = null
}
}
private fun createShineFadeInAnimations(): List<ViewPropertyAnimator> {
return listOf(binding.shineView1, binding.shineView2).map {
it.visibility = View.VISIBLE
it.alpha = 0f
it.animate()
.alpha(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(DecelerateInterpolator())
}
}
private fun createShineFadeOutAnimations(): List<ViewPropertyAnimator> {
return listOf(binding.shineView1, binding.shineView2).map {
it.animate()
.alpha(0f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
.withEndAction {
shineAnimation?.cancel()
shineAnimation = null
it.visibility = View.GONE
}
}
}
private fun createAchievementIconPopInAnimation(): ViewPropertyAnimator {
binding.achievementIconView.alpha = 0f
binding.achievementIconView.scaleX = 0f
binding.achievementIconView.scaleY = 0f
binding.achievementIconView.rotationY = -180f
return binding.achievementIconView.animate()
.alpha(1f)
.scaleX(1f).scaleY(1f)
.rotationY(360f)
.setDuration(ANIMATION_TIME_NEW_ACHIEVEMENT_IN_MS)
.setInterpolator(DecelerateInterpolator())
}
private fun createAchievementIconPopOutAnimation(): ViewPropertyAnimator {
return binding.achievementIconView.animate()
.alpha(0f)
.scaleX(0.5f).scaleY(0.5f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
}
private fun createDialogPopInAnimations(startDelay: Long = 0): List<ViewPropertyAnimator> {
return listOf(binding.dialogContentContainer, binding.dialogBubbleBackground).map {
it.alpha = 0f
it.scaleX = 0.5f
it.scaleY = 0.5f
it.translationY = 0f
/* For the "show new achievement" mode, only the icon is shown first and only after a
* delay, the dialog with the description etc.
* This icon is in the center at first and should animate up while the dialog becomes
* visible. This movement is solved via a (default) layout transition here for which the
* APPEARING transition type is disabled because we animate the alpha ourselves. */
it.isGone = startDelay > 0
it.animate()
.setStartDelay(startDelay)
.withStartAction {
if (startDelay > 0) {
binding.dialogContainer.layoutTransition = layoutTransition
it.visibility = View.VISIBLE
}
}
.alpha(1f)
.scaleX(1f).scaleY(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
}
private fun createDialogPopOutAnimations(): List<ViewPropertyAnimator> {
return listOf(binding.dialogContentContainer, binding.dialogBubbleBackground).map {
it.animate()
.alpha(0f)
.setStartDelay(0)
.scaleX(0.5f).scaleY(0.5f)
.translationYBy(it.height * 0.2f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
}
}
private fun createFadeInBackgroundAnimation(): ViewPropertyAnimator {
binding.dialogBackground.alpha = 0f
return binding.dialogBackground.animate()
.alpha(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(DecelerateInterpolator())
.withEndAction { currentAnimators.clear() }
}
private fun createFadeOutBackgroundAnimation(): ViewPropertyAnimator {
return binding.dialogBackground.animate()
.alpha(0f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
.withEndAction {
binding.dialogAndBackgroundContainer.visibility = View.INVISIBLE
currentAnimators.clear()
}
}
private fun clearAnimators() {
for (anim in currentAnimators) {
anim.cancel()
}
currentAnimators.clear()
}
private fun openUrl(url: String) {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
tryStartActivity(intent)
}
companion object {
const val ANIMATION_TIME_NEW_ACHIEVEMENT_IN_MS = 1000L
const val ANIMATION_TIME_IN_MS = 400L
const val DIALOG_APPEAR_DELAY_IN_MS = 1600L
const val ANIMATION_TIME_OUT_MS = 300L
}
}
| app/src/main/java/de/westnordost/streetcomplete/user/AchievementInfoFragment.kt | 2820812100 |
package fr.insapp.insapp.notifications
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.RingtoneManager
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import fr.insapp.insapp.R
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.NotificationUser
import fr.insapp.insapp.utility.Utils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* Created by thomas on 18/07/2017.
*/
class MyFirebaseMessagingService : FirebaseMessagingService() {
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
override fun onNewToken(token: String) {
Log.d(TAG, "Refreshed token: $token")
sendRegistrationTokenToServer(token)
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Data: " + remoteMessage.data)
val notification = remoteMessage.notification
sendNotification(notification?.title, notification?.body, notification?.clickAction, remoteMessage.data)
}
}
private fun sendNotification(title: String?, body: String?, clickAction: String?, data: Map<String, String>?) {
val intent = Intent(clickAction)
if (data != null) {
for ((key, value) in data) {
intent.putExtra(key, value)
}
}
var channel = "others"
if(body?.contains("news")!!){
channel = "posts"
} else if(body.contains("invite")){
channel = "events"
}
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notifications_$channel", true)){
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, channel)
builder
.setDefaults(Notification.DEFAULT_ALL)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSmallIcon(R.drawable.ic_stat_notify)
.setAutoCancel(true)
.setLights(Color.RED, 500, 1000)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
val manager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(randomNotificationId, builder.build())
}
}
private val randomNotificationId: Int
get() = Random().nextInt(9999 - 1000) + 1000
companion object {
const val TAG = "FA_DEBUG"
private val topics = arrayOf(
"posts-android",
"posts-unknown-class",
"posts-1STPI",
"posts-2STPI",
"posts-3CDTI",
"posts-4CDTI",
"posts-5CDTI",
"posts-3EII",
"posts-4EII",
"posts-5EII",
"posts-3GM",
"posts-4GM",
"posts-5GM",
"posts-3GMA",
"posts-4GMA",
"posts-5GMA",
"posts-3GCU",
"posts-4GCU",
"posts-5GCU",
"posts-3INFO",
"posts-4INFO",
"posts-5INFO",
"posts-3SGM",
"posts-4SGM",
"posts-5SGM",
"posts-3SRC",
"posts-4SRC",
"posts-5SRC",
"posts-STAFF",
"events-android",
"events-unknown-class",
"events-1STPI",
"events-2STPI",
"events-3CDTI",
"events-4CDTI",
"events-5CDTI",
"events-3EII",
"events-4EII",
"events-5EII",
"events-3GM",
"events-4GM",
"events-5GM",
"events-3GMA",
"events-4GMA",
"events-5GMA",
"events-3GCU",
"events-4GCU",
"events-5GCU",
"events-3INFO",
"events-4INFO",
"events-5INFO",
"events-3SGM",
"events-4SGM",
"events-5SGM",
"events-3SRC",
"events-4SRC",
"events-5SRC",
"events-STAFF"
)
fun subscribeToTopic(topic: String, flag: Boolean = true) {
if (flag) {
Log.d(TAG, "Subscribing to topic $topic..")
FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener { task ->
var msg = "Successfully subscribed to topic $topic"
if (!task.isSuccessful) {
msg = "Failed to subscribe to topic $topic"
}
Log.d(TAG, msg)
}
} else {
Log.d(TAG, "Unsubscribing from topic $topic..")
FirebaseMessaging.getInstance().unsubscribeFromTopic(topic).addOnCompleteListener { task ->
var msg = "Successfully unsubscribed from topic $topic"
if (!task.isSuccessful) {
msg = "Failed to unsubscribe from topic $topic"
}
Log.d(TAG, msg)
}
}
}
/**
* Persist token to the server.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by the application.
*
* @param token The new token.
*/
fun sendRegistrationTokenToServer(token: String) {
val user = Utils.user
if (user != null) {
val notificationUser = NotificationUser(null, user.id, token, "android")
val call = ServiceGenerator.client.registerNotification(notificationUser)
call.enqueue(object : Callback<NotificationUser> {
override fun onResponse(call: Call<NotificationUser>, response: Response<NotificationUser>) {
var msg = "Firebase token successfully registered on server: $token"
if (!response.isSuccessful) {
msg = "Failed to register Firebase token on server"
}
Log.d(TAG, msg)
}
override fun onFailure(call: Call<NotificationUser>, t: Throwable) {
Log.d(TAG, "Failed to register Firebase token on server: network failure")
}
})
} else {
Log.d(TAG, "Failed to register Firebase token on server: user is null")
}
}
}
/*
when (notification.type) {
"eventTag", "tag" -> {
val call1 = ServiceGenerator.create().getUserFromId(notification.sender)
call1.enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
if (response.isSuccessful) {
val user = response.body()
val id = resources.getIdentifier(Utils.drawableProfileName(user!!.promotion, user.gender), "drawable", App.getAppContext().packageName)
Glide
.with(App.getAppContext())
.asBitmap()
.load(id)
.into(notificationTarget)
} else {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<User>, t: Throwable) {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
})
}
"post" -> {
val call2 = ServiceGenerator.create().getAssociationFromId(notification.post.association)
call2.enqueue(object : Callback<Association> {
override fun onResponse(call: Call<Association>, response: Response<Association>) {
if (response.isSuccessful) {
val club = response.body()
Glide
.with(App.getAppContext())
.asBitmap()
.load(ServiceGenerator.CDN_URL + club!!.profilePicture)
.into(notificationTarget)
} else {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Association>, t: Throwable) {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
})
}
"event" -> {
val call3 = ServiceGenerator.create().getAssociationFromId(notification.event.association)
call3.enqueue(object : Callback<Association> {
override fun onResponse(call: Call<Association>, response: Response<Association>) {
if (response.isSuccessful) {
val club = response.body()
Glide
.with(App.getAppContext())
.asBitmap()
.load(ServiceGenerator.CDN_URL + club!!.profilePicture)
.into(notificationTarget)
} else {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Association>, t: Throwable) {
Toast.makeText(App.getAppContext(), "FirebaseMessaging", Toast.LENGTH_LONG).show()
}
})
}
else -> {
}
}
*/
}
| app/src/main/java/fr/insapp/insapp/notifications/MyFirebaseMessagingService.kt | 2483604972 |
package io.github.binaryfoo.decoders.apdu
import io.github.binaryfoo.DecodedData
import io.github.binaryfoo.EmvTags
import io.github.binaryfoo.QVsdcTags
import io.github.binaryfoo.decoders.DecodeSession
import io.github.binaryfoo.decoders.annotator.backgroundOf
import io.github.binaryfoo.tlv.Tag
import org.hamcrest.core.Is.`is`
import org.junit.Assert.assertThat
import org.junit.Test
class GetProcessingOptionsCommandAPDUDecoderTest {
@Test
fun testDecodeVisaWithPDOL() {
val session = DecodeSession()
session.tagMetaData = QVsdcTags.METADATA
session.put(EmvTags.PDOL, "9F66049F02069F03069F1A0295055F2A029A039C019F3704")
val input = "80A8000023832136000000000000001000000000000000003600000000000036120315000008E4C800"
val decoded = GetProcessingOptionsCommandAPDUDecoder().decode(input, 0, session)
assertThat(decoded.rawData, `is`("C-APDU: GPO"))
val children = decoded.children
val expectedDecodedTTQ = QVsdcTags.METADATA.get(QVsdcTags.TERMINAL_TX_QUALIFIERS).decoder.decode("36000000", 7, DecodeSession())
assertThat(children.first(), `is`(DecodedData(Tag.fromHex("9F66"), "9F66 (TTQ - Terminal transaction qualifiers)", "36000000", 7, 11, expectedDecodedTTQ)))
assertThat(children.last(), `is`(DecodedData(EmvTags.UNPREDICTABLE_NUMBER, "9F37 (unpredictable number)", "0008E4C8", 36, 40, backgroundReading = backgroundOf("A nonce generated by the terminal for replay attack prevention"))))
}
@Test
fun testDecodeMastercardWithoutPDOL() {
val session = DecodeSession()
val input = "80A8000002830000"
val decoded = GetProcessingOptionsCommandAPDUDecoder().decode(input, 0, session)
assertThat(decoded.rawData, `is`("C-APDU: GPO"))
assertThat(decoded.getDecodedData(), `is`("No PDOL included"))
assertThat(decoded.isComposite(), `is`(false))
}
}
| src/test/java/io/github/binaryfoo/decoders/apdu/GetProcessingOptionsCommandAPDUDecoderTest.kt | 1188081825 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.text
import org.lanternpowered.api.audience.MessageType
import org.lanternpowered.api.entity.player.chat.ChatVisibility
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.TextRepresentable
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.server.registry.internalCatalogTypeRegistry
val ChatVisibilityRegistry = internalCatalogTypeRegistry<ChatVisibility> {
fun register(id: String, isChatVisible: (MessageType) -> Boolean) =
register(LanternChatVisibility(NamespacedKey.minecraft(id), translatableTextOf("options.chat.visibility.$id"), isChatVisible))
register("full") { true }
register("system") { type -> type == MessageType.SYSTEM }
register("hidden") { false }
}
private class LanternChatVisibility(
key: NamespacedKey, text: Text, private val chatTypePredicate: (MessageType) -> Boolean
) : DefaultCatalogType(key), ChatVisibility, TextRepresentable by text {
override fun isVisible(type: net.kyori.adventure.audience.MessageType): Boolean = this.chatTypePredicate(type)
}
| src/main/kotlin/org/lanternpowered/server/registry/type/text/ChatVisibilityRegistry.kt | 1435785506 |
package com.mooveit.library.providers
import com.mooveit.library.Fakeit.Companion.fakeit
import com.mooveit.library.providers.base.BaseProvider
import com.mooveit.library.providers.definition.NameProvider
class NameProviderImpl : BaseProvider(), NameProvider {
override fun name(): String {
return getValue("name", { fakeit!!.fetch("name.name") })
}
override fun nameWithMiddle(): String {
return getValue("nameWithMiddle", { fakeit!!.fetch("name.name_with_middle") })
}
override fun firstName(): String {
return getValue("firstName", { fakeit!!.fetch("name.first_name") })
}
override fun lastName(): String {
return getValue("lastName", { fakeit!!.fetch("name.last_name") })
}
override fun prefix(): String {
return getValue("prefix", { fakeit!!.fetch("name.prefix") })
}
override fun suffix(): String {
return getValue("suffix", { fakeit!!.fetch("name.suffix") })
}
override fun title(): String {
return getValue("title", { fakeit!!.fetch("name.title.job") })
}
} | library/src/main/java/com/mooveit/library/providers/NameProviderImpl.kt | 2237080327 |
package bg.o.sim.colourizmus.view
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.palette.graphics.Palette
import bg.o.sim.colourizmus.R
import bg.o.sim.colourizmus.databinding.ActivityColourDetailsBinding
import bg.o.sim.colourizmus.model.CustomColour
import bg.o.sim.colourizmus.model.LIVE_COLOUR
import bg.o.sim.colourizmus.utils.*
class ColourDetailsActivity : AppCompatActivity() {
private lateinit var binding: ActivityColourDetailsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityColourDetailsBinding.inflate(layoutInflater)
setContentView(binding.root)
val dominantCol: CustomColour = when {
intent.hasExtra(EXTRA_COLOUR) -> intent.getSerializableExtra(EXTRA_COLOUR) as CustomColour
intent.hasExtra(EXTRA_PICTURE_URI) -> loadPassedPhoto(intent)
else -> CustomColour(LIVE_COLOUR.value!!, "")
}
// show the 'dominant' colour at top
bind(binding.colourPreview.root, dominantCol)
// complimentary second
bind(binding.complimentaryPreview.root, getComplimentaryColour(dominantCol))
// and the rest ->
bind(binding.paletteA.root, *getSaturationSwatch(dominantCol))
bind(binding.paletteB.root, *getValueSwatch(dominantCol))
bind(binding.paletteC.root, *getColourTriade(dominantCol))
bind(binding.paletteD.root, *getHueSwatch(dominantCol))
}
private fun loadPassedPhoto(intent: Intent): CustomColour {
val bitmap: Bitmap = MediaStore.Images.Media.getBitmap(contentResolver, intent.getParcelableExtra(EXTRA_PICTURE_URI)!!)
val palette = Palette.Builder(bitmap).generate()
binding.photoPreview.setImageBitmap(bitmap)
@ColorInt
val default = -1
bind(
binding.photoSwatchDefault.root,
CustomColour(palette.getMutedColor(default), ""),
CustomColour(palette.getDominantColor(default), ""),
CustomColour(palette.getVibrantColor(default), ""),
)
bind(
binding.photoSwatchLight.root,
CustomColour(palette.getLightMutedColor(default), ""),
CustomColour(palette.getDominantColor(default), ""),
CustomColour(palette.getLightVibrantColor(default), ""),
)
bind(
binding.photoSwatchDark.root,
CustomColour(palette.getDarkMutedColor(default), ""),
CustomColour(palette.getDominantColor(default), ""),
CustomColour(palette.getDarkVibrantColor(default), ""),
)
return CustomColour(palette.getDominantColor(default), "prime")
}
private fun bind(view: CardView, vararg colours: CustomColour) {
view.findViewById<LinearLayout>(R.id.palette_row).bindColourList(*colours)
}
} | app/src/main/java/bg/o/sim/colourizmus/view/ColourDetailsActivity.kt | 3958022659 |
package com.song.general.gossip.message
import com.song.general.gossip.GossipDigest
import com.song.general.gossip.utils.GsonUtils
import java.io.Serializable
/**
* Created by song on 2017/9/2.
*/
class GossipDigestSynMessage(val gossipDigests: List<GossipDigest>) : Serializable {
override fun toString(): String {
return GsonUtils.toJson(this)
}
} | general-gossip/src/main/java/com/song/general/gossip/message/GossipDigestSynMessage.kt | 4062345113 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.world
import org.spongepowered.api.world.gamerule.GameRule
import java.util.function.Supplier
fun <V> World.getGameRule(gameRule: Supplier<out GameRule<V>>): V =
this.properties.getGameRule(gameRule)
fun <V> World.getGameRule(gameRule: GameRule<V>): V =
this.properties.getGameRule(gameRule)
| src/main/kotlin/org/lanternpowered/api/world/GameRule.kt | 1014194459 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.