repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/CloseProjectAction.kt | 2 | 1534 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.ui.IdeUICustomization
class CloseProjectAction : CloseProjectsActionBase() {
init {
val uiCustomization = IdeUICustomization.getInstance()
templatePresentation.setText(uiCustomization.projectMessagePointer("action.close.project.text"))
templatePresentation.setDescription(uiCustomization.projectMessagePointer("action.close.project.description"))
}
override fun canClose(project: Project, currentProject: Project) = project === currentProject
override fun shouldShow(e: AnActionEvent) = e.project != null
override fun update(e: AnActionEvent) {
super.update(e)
if (ProjectAttachProcessor.canAttachToProject() && e.project != null && ModuleManager.getInstance(e.project!!).modules.size > 1) {
e.presentation.setText(IdeBundle.messagePointer("action.close.projects.in.current.window"))
}
else {
e.presentation.text = templatePresentation.text
e.presentation.description = templatePresentation.description
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
} | apache-2.0 | 87ab51086e089f4b7110bc83f553c9d5 | 41.638889 | 140 | 0.790091 | 4.79375 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/slicer/inflow/secondaryConstructorParameterWithDefault.kt | 3 | 327 | // FLOW: IN
// WITH_RUNTIME
open class A {
@JvmOverloads constructor(n: Int, <caret>s: String = "???")
}
class B1: A(1)
class B2: A(1, "2")
class B3: A(1, s = "2")
class B4: A(n = 1, s = "2")
class B5: A(s = "2", n = 1)
fun test() {
A(1)
A(1, "2")
A(1, s = "2")
A(n = 1, s = "2")
A(s = "2", n = 1)
}
| apache-2.0 | 52d4f261d6b03e752ae9a01678a402c1 | 15.35 | 63 | 0.446483 | 2.06962 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/targets/KotlinUnsupportedModuleBuildTarget.kt | 1 | 2078 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.jps.targets
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.kotlin.build.BuildMetaInfo
import org.jetbrains.kotlin.build.BuildMetaInfoFactory
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.compilerRunner.JpsCompilerEnvironment
import org.jetbrains.kotlin.jps.build.KotlinCompileContext
import org.jetbrains.kotlin.jps.build.KotlinDirtySourceFilesHolder
import org.jetbrains.kotlin.jps.incremental.JpsIncrementalCache
import org.jetbrains.kotlin.jps.model.platform
import org.jetbrains.kotlin.platform.idePlatformKind
class KotlinUnsupportedModuleBuildTarget(
kotlinContext: KotlinCompileContext,
jpsModuleBuildTarget: ModuleBuildTarget
) : KotlinModuleBuildTarget<BuildMetaInfo>(kotlinContext, jpsModuleBuildTarget) {
val kind = module.platform?.idePlatformKind?.name
private fun shouldNotBeCalled(): Nothing = error("Should not be called")
override fun isEnabled(chunkCompilerArguments: CommonCompilerArguments): Boolean {
return false
}
override val isIncrementalCompilationEnabled: Boolean
get() = false
override val hasCaches: Boolean
get() = false
override val globalLookupCacheId: String
get() = shouldNotBeCalled()
override fun compileModuleChunk(
commonArguments: CommonCompilerArguments,
dirtyFilesHolder: KotlinDirtySourceFilesHolder,
environment: JpsCompilerEnvironment
): Boolean {
shouldNotBeCalled()
}
override fun createCacheStorage(paths: BuildDataPaths): JpsIncrementalCache {
shouldNotBeCalled()
}
override val buildMetaInfoFactory: BuildMetaInfoFactory<BuildMetaInfo>
get() = shouldNotBeCalled()
override val buildMetaInfoFileName: String
get() = shouldNotBeCalled()
} | apache-2.0 | ca9f019dfe61820660eb8f191c3ec055 | 36.8 | 158 | 0.783446 | 5.105651 | false | false | false | false |
lucasgomes-eti/KotlinAndroidProjects | FilmesStarWars/app/src/main/java/com/lucas/filmesstarwars/FilmsListActivity.kt | 1 | 1350 | package com.lucas.filmesstarwars
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListAdapter
import android.widget.ListView
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class FilmsListActivity : AppCompatActivity() {
lateinit var listView : ListView
lateinit var movieAdapter : ArrayAdapter<String>
var movies = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
listView = ListView(this)
this.setContentView(listView)
movieAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, movies)
listView.adapter = movieAdapter
val api = StarWarsApi()
api.loadMovies()
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe (
{ (title, episodeId) ->
movies.add("$episodeId - $title")
},
{ e ->
e?.printStackTrace()
},
{
movieAdapter?.notifyDataSetChanged()
}
)
}
}
| cc0-1.0 | c350e93738ad41e6a62141b923758bad | 31.926829 | 86 | 0.577037 | 5.625 | false | false | false | false |
jwren/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitStageCompareWithVersionAction.kt | 2 | 3086 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.actions
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.DiffManager
import com.intellij.diff.chains.SimpleDiffRequestChain
import com.intellij.diff.chains.SimpleDiffRequestProducer
import com.intellij.diff.requests.DiffRequest
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VirtualFile
import git4idea.index.*
import git4idea.index.vfs.GitIndexVirtualFile
import git4idea.index.vfs.filePath
abstract class GitStageCompareWithVersionAction(val currentVersion: ContentVersion,
val compareWithVersion: ContentVersion) : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val project = e.project
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || !isStagingAreaAvailable(project) || file == null
|| (file is GitIndexVirtualFile != (currentVersion == ContentVersion.STAGED))) {
e.presentation.isEnabledAndVisible = false
return
}
val status = GitStageTracker.getInstance(project).status(file)
e.presentation.isVisible = (status != null)
e.presentation.isEnabled = (status?.has(compareWithVersion) == true)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE)
val root = getRoot(project, file) ?: return
val status = GitStageTracker.getInstance(project).status(root, file) ?: return
val producer = SimpleDiffRequestProducer.create(file.filePath(), ThrowableComputable {
createDiffRequest(project, root, status)
})
DiffManager.getInstance().showDiff(e.project, SimpleDiffRequestChain.fromProducer(producer), DiffDialogHints.DEFAULT)
}
abstract fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest
}
class GitStageCompareLocalWithStagedAction : GitStageCompareWithVersionAction(ContentVersion.LOCAL, ContentVersion.STAGED) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareStagedWithLocal(project, root, status)
}
}
class GitStageCompareStagedWithLocalAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.LOCAL) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareStagedWithLocal(project, root, status)
}
}
class GitStageCompareStagedWithHeadAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.HEAD) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareHeadWithStaged(project, root, status)
}
} | apache-2.0 | c88cf6d226e63601a26108aab315b012 | 46.492308 | 124 | 0.782566 | 4.814353 | false | false | false | false |
holisticon/ranked | backend/command/src/main/kotlin/match/Services.kt | 1 | 830 | package de.holisticon.ranked.command.service
import de.holisticon.ranked.model.AbstractMatchSet
import de.holisticon.ranked.model.TeamColor
import de.holisticon.ranked.properties.RankedProperties
import org.springframework.stereotype.Component
@Component
class MatchService(val properties: RankedProperties) {
/**
* Checks that the list of match sets consist of at least of scoreToWinMatch and at most of 2 * scoreToWinMatch - 1
*/
fun validateMatch(matchSets: List<AbstractMatchSet>) =
matchSets.size >= properties.setsToWinMatch && matchSets.size <= properties.setsToWinMatch.times(2).minus(1)
fun winsMatch(numberOfWins: Int) = numberOfWins == properties.setsToWinMatch
fun winsMatchSet(matchSet: AbstractMatchSet) = if (matchSet.goalsRed == properties.scoreToWinSet) TeamColor.RED else TeamColor.BLUE
}
| bsd-3-clause | 47fdbb07f8ab539af938617fdd61c377 | 40.5 | 133 | 0.79759 | 3.896714 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-shared/src/org/jetbrains/kotlin/idea/codeInsight/inspections/shared/RemoveCurlyBracesFromTemplateInspection.kt | 3 | 2355 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.inspections.shared
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.canDropCurlyBrackets
import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry
class RemoveCurlyBracesFromTemplateInspection(@JvmField var reportWithoutWhitespace: Boolean = false) :
AbstractApplicabilityBasedInspection<KtBlockStringTemplateEntry>(KtBlockStringTemplateEntry::class.java) {
override fun inspectionText(element: KtBlockStringTemplateEntry): String =
KotlinBundle.message("redundant.curly.braces.in.string.template")
override fun inspectionHighlightType(element: KtBlockStringTemplateEntry) =
if (reportWithoutWhitespace || element.hasWhitespaceAround()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else ProblemHighlightType.INFORMATION
override val defaultFixText: String get() = KotlinBundle.message("remove.curly.braces")
override fun isApplicable(element: KtBlockStringTemplateEntry): Boolean = element.canDropCurlyBrackets()
override fun applyTo(element: KtBlockStringTemplateEntry, project: Project, editor: Editor?) {
element.dropCurlyBracketsIfPossible()
}
override fun createOptionsPanel() = MultipleCheckboxOptionsPanel(this).apply {
addCheckbox(KotlinBundle.message("report.also.for.a.variables.without.a.whitespace.around"), "reportWithoutWhitespace")
}
}
private fun KtBlockStringTemplateEntry.hasWhitespaceAround(): Boolean =
prevSibling?.isWhitespaceOrQuote(true) == true && nextSibling?.isWhitespaceOrQuote(false) == true
private fun PsiElement.isWhitespaceOrQuote(prev: Boolean): Boolean {
val char = if (prev) text.lastOrNull() else text.firstOrNull()
return char != null && (char.isWhitespace() || char == '"')
}
| apache-2.0 | 256e0f47f82f52329405deac6d0ec03c | 53.767442 | 127 | 0.805945 | 5.221729 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/highlighting/src/org/jetbrains/kotlin/idea/highlighting/highlighters/TypeHighlighter.kt | 4 | 4310 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.highlighting.highlighters
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.highlighting.isNameHighlightingEnabled
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors
internal class TypeHighlighter(
holder: AnnotationHolder,
project: Project,
) : AfterResolveHighlighter(holder, project) {
context(KtAnalysisSession)
override fun highlight(element: KtElement) {
when (element) {
is KtSimpleNameExpression -> highlightSimpleNameExpression(element)
else -> {}
}
}
context(KtAnalysisSession)
private fun highlightSimpleNameExpression(expression: KtSimpleNameExpression) {
if (!expression.project.isNameHighlightingEnabled) return
if (expression.isCalleeExpression()) return
val parent = expression.parent
if (parent is KtInstanceExpressionWithLabel) {
// Do nothing: 'super' and 'this' are highlighted as a keyword
return
}
if (expression.isConstructorCallReference()) {
// Do not highlight constructor call as class reference
return
}
val symbol = expression.mainReference.resolveToSymbol() as? KtClassifierSymbol ?: return
if (isAnnotationCall(expression, symbol)) {
// higlighted by AnnotationEntryHiglightingVisitor
return
}
val color = when (symbol) {
is KtAnonymousObjectSymbol -> Colors.CLASS
is KtNamedClassOrObjectSymbol -> when (symbol.classKind) {
KtClassKind.CLASS -> when (symbol.modality) {
Modality.FINAL, Modality.SEALED , Modality.OPEN -> Colors.CLASS
Modality.ABSTRACT -> Colors.ABSTRACT_CLASS
}
KtClassKind.ENUM_CLASS -> Colors.ENUM
KtClassKind.ANNOTATION_CLASS -> Colors.ANNOTATION
KtClassKind.OBJECT -> Colors.OBJECT
KtClassKind.COMPANION_OBJECT -> Colors.OBJECT
KtClassKind.INTERFACE -> Colors.TRAIT
KtClassKind.ANONYMOUS_OBJECT -> Colors.CLASS
}
is KtTypeAliasSymbol -> Colors.TYPE_ALIAS
is KtTypeParameterSymbol -> Colors.TYPE_PARAMETER
}
highlightName(expression.textRange, color)
}
context(KtAnalysisSession)
private fun isAnnotationCall(expression: KtSimpleNameExpression, target: KtSymbol): Boolean {
val isKotlinAnnotation = target is KtConstructorSymbol
&& target.isPrimary
&& (target.getContainingSymbol() as? KtClassOrObjectSymbol)?.classKind == KtClassKind.ANNOTATION_CLASS
if (!isKotlinAnnotation) {
val targetIsAnnotation = when (val targePsi = target.psi) {
is KtClass -> targePsi.isAnnotation()
is PsiClass -> targePsi.isAnnotationType
else -> false
}
if (!targetIsAnnotation) {
return false
}
}
val annotationEntry = PsiTreeUtil.getParentOfType(
expression, KtAnnotationEntry::class.java, /* strict = */false, KtValueArgumentList::class.java
)
return annotationEntry?.atSymbol != null
}
}
private fun KtSimpleNameExpression.isCalleeExpression() =
(parent as? KtCallExpression)?.calleeExpression == this
private fun KtSimpleNameExpression.isConstructorCallReference(): Boolean {
val type = parent as? KtUserType ?: return false
val typeReference = type.parent as? KtTypeReference ?: return false
val constructorCallee = typeReference.parent as? KtConstructorCalleeExpression ?: return false
return constructorCallee.constructorReferenceExpression == this
} | apache-2.0 | c76855172ecb86a6054e8885ccb92f56 | 40.057143 | 120 | 0.67819 | 5.469543 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinDirtySourceFilesHolder.kt | 1 | 3727 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.jps.build
import com.intellij.openapi.util.io.FileUtilRt
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.builders.DirtyFilesHolder
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget
import java.io.File
/**
* Holding kotlin dirty files list for particular build round.
* Dirty and removed files set are initialized from [delegate].
*
* Additional dirty files should be added only through [FSOperationsHelper.markFilesForCurrentRound]
*/
class KotlinDirtySourceFilesHolder(
val chunk: ModuleChunk,
val context: CompileContext,
delegate: DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>
) {
val byTarget: Map<ModuleBuildTarget, TargetFiles>
inner class TargetFiles(val target: ModuleBuildTarget, val removed: Collection<File>) {
private val _dirty: MutableMap<File, KotlinModuleBuildTarget.Source> = mutableMapOf()
val dirty: Map<File, KotlinModuleBuildTarget.Source>
get() = _dirty
/**
* Should be called only from [FSOperationsHelper.markFilesForCurrentRound]
* and during KotlinDirtySourceFilesHolder initialization.
*/
internal fun _markDirty(file: File, root: JavaSourceRootDescriptor) {
val isCrossCompiled = root is KotlinIncludedModuleSourceRoot
val old = _dirty.put(file.canonicalFile, KotlinModuleBuildTarget.Source(file, isCrossCompiled))
check(old == null || old.isCrossCompiled == isCrossCompiled) {
"`${file.canonicalFile}` already marked as dirty: " +
"old is cross compiled: ${old!!.isCrossCompiled}, " +
"new is cross compiled: $isCrossCompiled"
}
}
}
val hasRemovedFiles: Boolean
get() = byTarget.any { it.value.removed.isNotEmpty() }
val hasDirtyFiles: Boolean
get() = byTarget.any { it.value.dirty.isNotEmpty() }
val hasDirtyOrRemovedFiles: Boolean
get() = hasRemovedFiles || hasDirtyFiles
init {
val byTarget = mutableMapOf<ModuleBuildTarget, TargetFiles>()
chunk.targets.forEach { target ->
val removedFiles = delegate.getRemovedFiles(target)
.map { File(it) }
.filter { it.isKotlinSourceFile }
byTarget[target] = TargetFiles(target, removedFiles)
}
delegate.processDirtyFiles { target, file, root ->
val targetInfo = byTarget[target]
?: error("processDirtyFiles should callback only on chunk `$chunk` targets (`$target` is not)")
if (file.isKotlinSourceFile) {
targetInfo._markDirty(file, root)
}
true
}
this.byTarget = byTarget
}
fun getDirtyFiles(target: ModuleBuildTarget): Map<File, KotlinModuleBuildTarget.Source> =
byTarget[target]?.dirty ?: mapOf()
fun getRemovedFiles(target: ModuleBuildTarget): Collection<File> =
byTarget[target]?.removed ?: listOf()
val allDirtyFiles: Set<File>
get() = byTarget.flatMapTo(mutableSetOf()) { it.value.dirty.keys }
val allRemovedFilesFiles: Set<File>
get() = byTarget.flatMapTo(mutableSetOf()) { it.value.removed }
}
val File.isKotlinSourceFile: Boolean
get() = FileUtilRt.extensionEquals(name, "kt") || FileUtilRt.extensionEquals(name, "kts")
| apache-2.0 | 8636a1379c177fdb4805c532eacda8d1 | 37.42268 | 158 | 0.680977 | 4.578624 | false | false | false | false |
Unic8/retroauth | demoandroid/src/main/java/com/andretietz/retroauth/demo/LoginActivity.kt | 1 | 4495 | package com.andretietz.retroauth.demo
import android.annotation.TargetApi
import android.os.Build
import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.andretietz.retroauth.AndroidCredentials
import com.andretietz.retroauth.AuthenticationActivity
import com.github.scribejava.apis.FacebookApi
import com.github.scribejava.core.builder.ServiceBuilder
import com.github.scribejava.core.model.OAuth2AccessToken
import com.github.scribejava.core.oauth.OAuth20Service
import com.github.scribejava.httpclient.okhttp.OkHttpHttpClient
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_login.webView
//import kotlinx.android.synthetic.main.activity_login.webView
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import timber.log.Timber
import java.util.concurrent.Callable
import java.util.concurrent.TimeUnit
class LoginActivity : AuthenticationActivity() {
private val compositeDisposable = CompositeDisposable()
private val helper = ServiceBuilder(FacebookAuthenticator.CLIENT_ID)
.apiSecret(FacebookAuthenticator.CLIENT_SECRET)
.callback(FacebookAuthenticator.CLIENT_CALLBACK)
.withScope("email")
.httpClient(OkHttpHttpClient())
.build(FacebookApi.instance())
// private val authenticator by lazy { FacebookAuthenticator(application) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
webView.loadUrl(helper.authorizationUrl)
@Suppress("UsePropertyAccessSyntax")
webView.getSettings().setJavaScriptEnabled(true)
webView.webViewClient = object : WebViewClient() {
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
val authorization = helper.extractAuthorization(url)
val code = authorization.code
if (code == null) {
view.loadUrl(url)
} else {
val disposable = Single.fromCallable(TokenVerifier(helper, code))
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val account = createOrGetAccount(result.name)
storeCredentials(
account,
FacebookAuthenticator.createTokenType(application),
result.token.toAndroidCredentials()
)
finalizeAuthentication(account)
}, { error -> Timber.e(error) })
compositeDisposable.add(disposable)
}
return true
}
@Suppress("DEPRECATION")
@TargetApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return shouldOverrideUrlLoading(view, request.url.toString())
}
}
}
override fun onDestroy() {
compositeDisposable.dispose()
super.onDestroy()
}
private class TokenVerifier(private val service: OAuth20Service, private val code: String) : Callable<LoginResult> {
private val api = Retrofit.Builder()
.baseUrl("https://graph.facebook.com/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.build().create(FacebookInfoService::class.java)
override fun call(): LoginResult {
val token = service.getAccessToken(code)
val info = api.getUserInfo("name,email", token.accessToken).blockingGet()
return LoginResult(info.email, token)
}
}
internal interface FacebookInfoService {
@GET("v5.0/me")
fun getUserInfo(@Query("fields") fields: String, @Query("access_token") token: String): Single<UserInfo>
}
internal class UserInfo {
var email: String = ""
}
private class LoginResult(val name: String, val token: OAuth2AccessToken)
fun OAuth2AccessToken.toAndroidCredentials(): AndroidCredentials {
return AndroidCredentials(this.accessToken, mapOf(
FacebookAuthenticator.KEY_TOKEN_VALIDITY
to TimeUnit.MILLISECONDS
// expiry date - 30 seconds (network tolerance)
.convert((this.expiresIn - 30).toLong(), TimeUnit.SECONDS)
.plus(System.currentTimeMillis()).toString()
))
}
}
| apache-2.0 | e37870476bb0a64a141c9390da86572a | 36.458333 | 118 | 0.734594 | 4.812634 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/weighers/basic/expectedType/whileConditionQualified.kt | 11 | 238 | // FIR_COMPARISON
object x {
val b: Boolean = true
val c: String = "true"
val d: Int = 1
val e: Long = 1L
val f: Boolean = true
fun foo(): Boolean = true
}
fun x() {
while(x.<caret>){
}
// ORDER: b, f, foo | apache-2.0 | 954618b781db5e8eca84d3c5a49e657b | 12.277778 | 29 | 0.521008 | 2.938272 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinReferenceImporter.kt | 1 | 4129 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.codeInsight.daemon.ReferenceImporter
import com.intellij.codeInsight.daemon.impl.DaemonListeners
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.actions.createSingleImportAction
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.quickfix.ImportFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class KotlinReferenceImporter : AbstractKotlinReferenceImporter() {
override fun isEnabledFor(file: KtFile): Boolean = KotlinCodeInsightSettings.getInstance().addUnambiguousImportsOnTheFly
override val enableAutoImportFilter: Boolean = false
}
abstract class AbstractKotlinReferenceImporter : ReferenceImporter {
override fun isAddUnambiguousImportsOnTheFlyEnabled(file: PsiFile): Boolean = file is KtFile && isEnabledFor(file)
protected abstract fun isEnabledFor(file: KtFile): Boolean
protected abstract val enableAutoImportFilter: Boolean
private fun filterSuggestions(context: KtFile, suggestions: Collection<FqName>): Collection<FqName> =
KotlinAutoImportsFilter.takeIf { enableAutoImportFilter }
?.filterSuggestionsIfApplicable(context, suggestions)
?: suggestions
override fun autoImportReferenceAtCursor(editor: Editor, file: PsiFile): Boolean {
if (file !is KtFile || !DaemonListeners.canChangeFileSilently(file)) return false
fun hasUnresolvedImportWhichCanImport(name: String): Boolean = file.importDirectives.any {
(it.isAllUnder || it.importPath?.importedName?.asString() == name) && it.targetDescriptors().isEmpty()
}
fun KtSimpleNameExpression.autoImport(): Boolean {
if (hasUnresolvedImportWhichCanImport(getReferencedName())) return false
val bindingContext = analyze(BodyResolveMode.PARTIAL)
if (mainReference.resolveToDescriptors(bindingContext).isNotEmpty()) return false
val suggestions = filterSuggestions(file, ImportFix(this).collectSuggestions())
val suggestion = suggestions.singleOrNull() ?: return false
val descriptors = file.resolveImportReference(suggestion)
// we do not auto-import nested classes because this will probably add qualification into the text and this will confuse the user
if (descriptors.any { it is ClassDescriptor && it.containingDeclaration is ClassDescriptor }) return false
var result = false
CommandProcessor.getInstance().runUndoTransparentAction {
result = createSingleImportAction(project, editor, this, suggestions).execute()
}
return result
}
val caretOffset = editor.caretModel.offset
val document = editor.document
val lineNumber = document.getLineNumber(caretOffset)
val startOffset = document.getLineStartOffset(lineNumber)
val endOffset = document.getLineEndOffset(lineNumber)
return file.elementsInRange(TextRange(startOffset, endOffset))
.flatMap { it.collectDescendantsOfType<KtSimpleNameExpression>() }
.any { it.endOffset != caretOffset && it.autoImport() }
}
}
| apache-2.0 | 888e4df6f40be8750b4d10d832b23a06 | 49.975309 | 158 | 0.76435 | 5.154806 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer-iconics/src/main/java/com/mikepenz/materialdrawer/iconics/IconicsImageHolder.kt | 1 | 2996 | package com.mikepenz.materialdrawer.iconics
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.appcompat.content.res.AppCompatResources
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.utils.actionBar
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.mikepenz.materialdrawer.holder.ImageHolder
import com.mikepenz.materialdrawer.util.DrawerImageLoader
import java.io.FileNotFoundException
class IconicsImageHolder(iicon: IIcon) : ImageHolder() {
var iicon: IIcon? = iicon
internal set
/**
* sets an existing image to the imageView
*
* @param imageView
* @param tag used to identify imageViews and define different placeholders
* @return true if an image was set
*/
override fun applyTo(imageView: ImageView, tag: String?): Boolean {
val ii = iicon
val uri = uri
if (uri != null) {
val consumed = DrawerImageLoader.instance.setImage(imageView, uri, tag)
if (!consumed) {
imageView.setImageURI(uri)
}
} else if (icon != null) {
imageView.setImageDrawable(icon)
} else if (bitmap != null) {
imageView.setImageBitmap(bitmap)
} else if (iconRes != -1) {
imageView.setImageResource(iconRes)
} else if (ii != null) {
imageView.setImageDrawable(IconicsDrawable(imageView.context, ii).actionBar())
} else {
imageView.setImageBitmap(null)
return false
}
return true
}
/**
* this only handles Drawables
*
* @param ctx
* @param iconColor
* @param tint
* @return
*/
override fun decideIcon(ctx: Context, iconColor: ColorStateList, tint: Boolean, paddingDp: Int): Drawable? {
var icon: Drawable? = icon
val ii = iicon
val uri = uri
when {
ii != null -> icon = IconicsDrawable(ctx, ii).apply {
colorList = iconColor
sizeDp = 24
this.paddingDp = paddingDp
}
iconRes != -1 -> icon = AppCompatResources.getDrawable(ctx, iconRes)
uri != null -> try {
val inputStream = ctx.contentResolver.openInputStream(uri)
icon = Drawable.createFromStream(inputStream, uri.toString())
} catch (e: FileNotFoundException) {
//no need to handle this
}
}
//if we got an icon AND we have auto tinting enabled AND it is no IIcon, tint it ;)
if (icon != null && tint && iicon == null) {
icon = icon.mutate()
icon.setColorFilter(iconColor.defaultColor, PorterDuff.Mode.SRC_IN)
}
return icon
}
} | apache-2.0 | e55187c6a0c452cb0abe3508a8d357c2 | 32.674157 | 112 | 0.619493 | 4.778309 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttUserAgentFilter.kt | 1 | 4184 | package com.softmotions.ncms.mtt.http
import com.softmotions.web.HttpUtils
import org.slf4j.LoggerFactory
import javax.servlet.http.HttpServletRequest
/**
* User agent mtt filter.
*
* @author Adamansky Anton ([email protected])
*/
class MttUserAgentFilter : MttFilterHandler {
private val log = LoggerFactory.getLogger(javaClass)
override val type = "useragent"
override fun matched(ctx: MttFilterHandlerContext, req: HttpServletRequest): Boolean {
val ua = req.getHeader("user-agent")?.toLowerCase() ?: return true
val spec = ctx.spec
if (log.isDebugEnabled) {
log.debug("User agent: ${ua}")
log.debug("Spec: ${spec}")
}
if (spec.path("desktop").asBoolean(false)) {
if (ua.contains("mobile")
|| ua.contains("android")
|| ua.contains("iphone")
|| ua.contains("ipad")
|| ua.contains("ipod")
|| ua.contains("arm;")) {
if (log.isDebugEnabled) {
log.debug("desktop=false")
}
return false
}
}
if (spec.path("mobile").asBoolean(false)) {
if (!HttpUtils.isMobile(ua)) {
if (log.isDebugEnabled) {
log.debug("mobile=false")
}
return false
}
}
if (spec.path("tablet").asBoolean(false)) {
if (!HttpUtils.isTablet(ua)) {
if (log.isDebugEnabled) {
log.debug("tablet=false")
}
return false
}
}
if (spec.path("android").asBoolean(false)) {
if (!ua.contains("android")) {
if (log.isDebugEnabled) {
log.debug("android=false")
}
return false
}
}
if (spec.path("ios").asBoolean(false)) {
if (!ua.contains("iphone") && !ua.contains("ipad") && !ua.contains("ipod")) {
if (log.isDebugEnabled) {
log.debug("ios=false")
}
return false
}
}
if (spec.path("osx").asBoolean(false)) {
if (!ua.contains("mac os")) {
if (log.isDebugEnabled) {
log.debug("osx=false")
}
return false;
}
}
if (spec.path("windows").asBoolean(false)) {
if (!ua.contains("windows")) {
if (log.isDebugEnabled) {
log.debug("windows=false")
}
return false;
}
}
if (spec.path("unix").asBoolean(false)) {
if (!ua.contains("unix") && !ua.contains("linux") && !ua.contains("x11")) {
if (log.isDebugEnabled) {
log.debug("unix=false")
}
return false
}
}
if (spec.path("webkit").asBoolean(false)) {
if (!HttpUtils.isWebkit(ua)) {
if (log.isDebugEnabled) {
log.debug("webkit=false")
}
return false
}
}
if (spec.path("gecko").asBoolean(false)) {
if (!HttpUtils.isGecko(ua)) {
if (log.isDebugEnabled) {
log.debug("gecko=false")
}
return false
}
}
if (spec.path("trident").asBoolean(false)) {
if (!HttpUtils.isTrident(ua)) {
if (log.isDebugEnabled) {
log.debug("trident=false")
}
return false
}
}
if (spec.path("edge").asBoolean(false)) {
if (!HttpUtils.isEdge(ua)) {
if (log.isDebugEnabled) {
log.debug("edge=false")
}
return false
}
}
if (log.isDebugEnabled) {
log.debug("User agent test passed")
}
return true
}
} | apache-2.0 | 749b6951d171aa0ae13b913289ab2eb7 | 27.664384 | 90 | 0.439054 | 4.733032 | false | false | false | false |
like5188/Common | common/src/main/java/com/like/common/view/dragview/animation/BaseAnimationManager.kt | 1 | 1206 | package com.like.common.view.dragview.animation
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
abstract class BaseAnimationManager(val config: AnimationConfig) {
private var isStart: Boolean = false
private val animatorSet: AnimatorSet = AnimatorSet().apply {
duration = AnimationConfig.DURATION
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
isStart = true
onStart()
super.onAnimationStart(animation)
}
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
animation?.removeAllListeners()
isStart = false
onEnd()
}
})
}
@Synchronized
fun start() {
if (isStart) {
return
}
fillAnimatorSet(animatorSet)
animatorSet.start()
}
fun cancel() {
animatorSet.cancel()
}
abstract fun fillAnimatorSet(animatorSet: AnimatorSet)
open fun onStart() {}
open fun onEnd() {}
} | apache-2.0 | aed7e2c0bee1cebdde146b018459f71c | 26.431818 | 66 | 0.611111 | 5.583333 | false | true | false | false |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/domain/android/service/TweetService.kt | 1 | 4736 | package net.ketc.numeri.domain.android.service
import android.app.*
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import net.ketc.numeri.R
import net.ketc.numeri.domain.model.TwitterUser
import net.ketc.numeri.domain.service.TwitterClient
import net.ketc.numeri.presentation.view.activity.TweetActivity
import net.ketc.numeri.util.log.i
import net.ketc.numeri.util.rx.AutoDisposable
import net.ketc.numeri.util.rx.AutoDisposableImpl
import net.ketc.numeri.util.rx.MySchedulers
import net.ketc.numeri.util.rx.generalThread
import net.ketc.numeri.util.twitter.createTweetSender
import java.io.File
class TweetService : Service(), ITweetService, AutoDisposable by AutoDisposableImpl() {
private val binder = ITweetService.Binder(this)
override fun onBind(intent: Intent?) = binder
private var count = 0
private var taskCount = 0
private var sending = false
private val notificationId = 200
private val notificationManager: NotificationManager by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }
override fun sendTweet(client: TwitterClient, clientUser: TwitterUser, text: String,
inReplyToStatusId: Long?,
mediaList: List<File>?,
isPossiblySensitive: Boolean) {
fun createNotification(subText: String, progress: Int = 0): Notification {
return NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("${clientUser.screenName} : $text")
.setSubText(subText)
.setColor(getColor(R.color.colorPrimary))
.setProgress(PROGRESS_MAX, progress, false)
.build()
}
if (!sending) {
val intents = Intent(applicationContext, TweetActivity::class.java)
val contentIntent = PendingIntent.getActivity(applicationContext, 0, intents,
PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SOCIAL)
.setContentText(getString(R.string.tweet_sending))
.setSubText("send tweet")
.setColor(getColor(R.color.colorPrimary))
.build()
notification.contentIntent = contentIntent
startForeground(notificationId, notification)
sending = true
}
val currentCount = count
taskCount++
val subText = getString(R.string.sending)
notificationManager.notify(TAG, currentCount, createNotification(subText))
fun finish(text: String) {
taskCount--
if (taskCount == 0) {
stopForeground(true)
sending = false
}
notificationManager.notify(TAG, currentCount, createNotification(text, PROGRESS_MAX))
}
val sender = client.createTweetSender(text, inReplyToStatusId, mediaList, isPossiblySensitive)
val disposable = sender.progressObservable.generalThread()
.subscribe({ progress ->
notificationManager.notify(TAG, currentCount, createNotification(subText, progress))
}, {}, {
finish(getString(R.string.send_success))
})
disposable.autoDispose()
singleTask(MySchedulers.twitter) {
sender.send(applicationContext)
} error {
finish(getString(R.string.send_failure))
it.printStackTrace()
disposable.dispose()
} success {
disposable.dispose()
}
if (count == 100) {
count = 0
} else {
count++
}
}
override fun onDestroy() {
dispose()
i(TAG, "onDestroy")
super.onDestroy()
}
companion object {
val TAG = "tech.ketc.numeri3:TweetService"
val CHANNEL_ID = "tech.ketc.numeri3:TweetService"
val PROGRESS_MAX = 100
}
}
interface ITweetService {
fun sendTweet(client: TwitterClient, clientUser: TwitterUser, text: String = "",
inReplyToStatusId: Long? = null,
mediaList: List<File>? = null,
isPossiblySensitive: Boolean = false)
class Binder(private val tweetService: ITweetService) : android.os.Binder() {
fun getService(): ITweetService {
return tweetService
}
}
}
| mit | d29522f70544f76d95215b45dba6e873 | 36.291339 | 138 | 0.623522 | 4.959162 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/test/kotlin/com/almasb/fxgl/texture/TextureTest.kt | 1 | 6819 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
@file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE")
package com.almasb.fxgl.texture
import com.almasb.fxgl.test.RunWithFX
import javafx.geometry.HorizontalDirection
import javafx.geometry.Rectangle2D
import javafx.geometry.VerticalDirection
import javafx.scene.Node
import javafx.scene.effect.BlendMode
import javafx.scene.image.Image
import javafx.scene.image.WritableImage
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.function.Executable
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
@ExtendWith(RunWithFX::class)
class TextureTest {
private lateinit var texture: Texture
companion object {
private val image: Image = WritableImage(320, 320)
}
@BeforeEach
fun setUp() {
texture = Texture(image)
}
@Test
fun `Width and Height`() {
assertThat(texture.width, `is`(320.0))
assertThat(texture.height, `is`(320.0))
}
@Test
fun `Copy creates new node with same image`() {
val copy = texture.copy()
assertThat(texture !== copy, `is`(true))
assertThat(texture.image === copy.image, `is`(true))
}
@Test
fun `Test subtexture`() {
val sub = texture.subTexture(Rectangle2D(0.0, 0.0, 128.0, 64.0))
assertThat(sub.image.width, `is`(128.0))
assertThat(sub.image.height, `is`(64.0))
}
@Test
fun `Fail if subtexture larger or x y are negative`() {
assertAll(
Executable {
assertThrows(IllegalArgumentException::class.java) {
texture.subTexture(Rectangle2D(0.0, 0.0, 400.0, 300.0))
}
},
Executable {
assertThrows(IllegalArgumentException::class.java) {
texture.subTexture(Rectangle2D(0.0, 0.0, 300.0, 400.0))
}
},
Executable {
assertThrows(IllegalArgumentException::class.java) {
texture.subTexture(Rectangle2D(-10.0, 0.0, 400.0, 300.0))
}
},
Executable {
assertThrows(IllegalArgumentException::class.java) {
texture.subTexture(Rectangle2D(0.0, -10.0, 300.0, 400.0))
}
}
)
}
@Test
fun `Test supertexture`() {
val super1 = texture.superTexture(texture, HorizontalDirection.RIGHT)
assertThat(super1.image.width, `is`(640.0))
assertThat(super1.image.height, `is`(320.0))
val super2 = texture.superTexture(texture, HorizontalDirection.LEFT)
assertThat(super2.image.width, `is`(640.0))
assertThat(super2.image.height, `is`(320.0))
val super3 = texture.superTexture(texture, VerticalDirection.UP)
assertThat(super3.image.width, `is`(320.0))
assertThat(super3.image.height, `is`(640.0))
val super4 = texture.superTexture(texture, VerticalDirection.DOWN)
assertThat(super4.image.width, `is`(320.0))
assertThat(super4.image.height, `is`(640.0))
// now test with different size textures, so transparent pixels will be added to compensate
val diffSizeTexture1 = Texture(WritableImage(10, 320))
val super5 = texture.superTexture(diffSizeTexture1, VerticalDirection.DOWN)
assertThat(super5.image.width, `is`(320.0))
assertThat(super5.image.height, `is`(640.0))
val super6 = diffSizeTexture1.superTexture(texture, VerticalDirection.DOWN)
assertThat(super6.image.width, `is`(320.0))
assertThat(super6.image.height, `is`(640.0))
val diffSizeTexture2 = Texture(WritableImage(320, 10))
val super7 = texture.superTexture(diffSizeTexture2, HorizontalDirection.RIGHT)
assertThat(super7.image.width, `is`(640.0))
assertThat(super7.image.height, `is`(320.0))
val super8 = diffSizeTexture2.superTexture(texture, HorizontalDirection.RIGHT)
assertThat(super8.image.width, `is`(640.0))
assertThat(super8.image.height, `is`(320.0))
}
@Test
fun `Color conversions`() {
assertThat(texture.toGrayscale().image, `is`(not(image)))
assertThat(texture.brighter().image, `is`(not(image)))
assertThat(texture.darker().image, `is`(not(image)))
assertThat(texture.invert().image, `is`(not(image)))
assertThat(texture.desaturate().image, `is`(not(image)))
assertThat(texture.saturate().image, `is`(not(image)))
assertThat(texture.discolor().image, `is`(not(image)))
assertThat(texture.multiplyColor(Color.BLUE).image, `is`(not(image)))
assertThat(texture.toColor(Color.GRAY).image, `is`(not(image)))
assertThat(texture.replaceColor(Color.WHITE, Color.GRAY).image, `is`(not(image)))
assertThat(texture.replaceColor(Color.TRANSPARENT, Color.GRAY).image, `is`(not(image)))
assertThat(texture.transparentColor(Color.PURPLE).image, `is`(not(image)))
assertThat(texture.outline(Color.PURPLE).image, `is`(not(image)))
assertThat(texture.toBlackWhite().image, `is`(not(image)))
}
@ParameterizedTest
@EnumSource(BlendMode::class)
fun `Blending`(blend: BlendMode) {
assertThat(texture.blend(WritableImage(320, 320), blend).image, `is`(not(image)))
assertThat(texture.blend(Rectangle(320.0, 320.0, Color.RED), blend).image, `is`(not(image)))
assertThat(ColoredTexture(320, 320, Color.BLACK).blend(ColoredTexture(320, 320, Color.WHITE).image, blend).image, `is`(not(image)))
assertThat(ColoredTexture(320, 320, Color.WHITE).blend(ColoredTexture(320, 320, Color.BLACK).image, blend).image, `is`(not(image)))
}
@Test
fun `Set from another texture`() {
val newImage = WritableImage(320, 320)
assertThat(texture.image, `is`(image))
texture.set(Texture(newImage))
assertThat(texture.image, `is`<Image>(newImage))
}
@Test
fun `Get renderable node`() {
assertThat(texture.node, `is`<Node>(texture))
}
@Test
fun `Dispose`() {
assertNotNull(texture.image)
texture.dispose()
assertNull(texture.image)
}
} | mit | fadcb91f398667fdf21a7127fad0558d | 33.1 | 139 | 0.64071 | 3.876634 | false | true | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/netease/result/MusicUrlResultBean.kt | 1 | 1665 | package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/23
* desc :
*/
data class MusicUrlResultBean(
@SerializedName("data")
@Expose
val data: List<Datum>?,
@SerializedName("code")
@Expose
val code: Int
) {
data class Datum(
@SerializedName("id")
@Expose
var id: Long,
@SerializedName("url")
@Expose
var url: String?,
@SerializedName("br")
@Expose
var bitrate: Int,
@SerializedName("size")
@Expose
var size: Long,
@SerializedName("md5")
@Expose
var md5: String,
@SerializedName("type")
@Expose
var type: String?
// @SerializedName("code")
// @Expose
// var code: Long? = null,
// @SerializedName("expi")
// @Expose
// var expi: Long? = null,
// @SerializedName("gain")
// @Expose
// var gain: Double? = null,
// @SerializedName("fee")
// @Expose
// var fee: Long? = null,
// @SerializedName("uf")
// @Expose
// var uf: Any? = null,
// @SerializedName("payed")
// @Expose
// var payed: Long? = null,
// @SerializedName("flag")
// @Expose
// var flag: Long? = null,
// @SerializedName("canExtend")
// @Expose
// var canExtend: Boolean? = null
)
}
| gpl-2.0 | 93a896fa50ecb13ca09f861d6eb2a629 | 21.2 | 49 | 0.491892 | 4.021739 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/network/NetworkObserver.kt | 1 | 3611 | package coil.network
import android.Manifest.permission.ACCESS_NETWORK_STATE
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
import android.net.NetworkRequest
import android.util.Log
import androidx.annotation.MainThread
import androidx.core.content.getSystemService
import coil.network.NetworkObserver.Listener
import coil.util.Logger
import coil.util.isPermissionGranted
import coil.util.log
private const val TAG = "NetworkObserver"
/** Create a new [NetworkObserver]. */
internal fun NetworkObserver(
context: Context,
listener: Listener,
logger: Logger?
): NetworkObserver {
val connectivityManager: ConnectivityManager? = context.getSystemService()
if (connectivityManager == null || !context.isPermissionGranted(ACCESS_NETWORK_STATE)) {
logger?.log(TAG, Log.WARN) { "Unable to register network observer." }
return EmptyNetworkObserver()
}
return try {
RealNetworkObserver(connectivityManager, listener)
} catch (e: Exception) {
logger?.log(TAG, RuntimeException("Failed to register network observer.", e))
EmptyNetworkObserver()
}
}
/**
* Observes the device's network state and calls [Listener] if any state changes occur.
*
* This class provides a raw stream of updates from the network APIs. The [Listener] can be
* called multiple times for the same network state.
*/
internal interface NetworkObserver {
/** Synchronously checks if the device is online. */
val isOnline: Boolean
/** Stop observing network changes. */
fun shutdown()
/** Calls [onConnectivityChange] when a connectivity change event occurs. */
fun interface Listener {
@MainThread
fun onConnectivityChange(isOnline: Boolean)
}
}
internal class EmptyNetworkObserver : NetworkObserver {
override val isOnline get() = true
override fun shutdown() {}
}
@SuppressLint("MissingPermission")
@Suppress("DEPRECATION") // TODO: Remove uses of 'allNetworks'.
private class RealNetworkObserver(
private val connectivityManager: ConnectivityManager,
private val listener: Listener
) : NetworkObserver {
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) = onConnectivityChange(network, true)
override fun onLost(network: Network) = onConnectivityChange(network, false)
}
override val isOnline: Boolean
get() = connectivityManager.allNetworks.any { it.isOnline() }
init {
val request = NetworkRequest.Builder()
.addCapability(NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(request, networkCallback)
}
override fun shutdown() {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
private fun onConnectivityChange(network: Network, isOnline: Boolean) {
val isAnyOnline = connectivityManager.allNetworks.any {
if (it == network) {
// Don't trust the network capabilities for the network that just changed.
isOnline
} else {
it.isOnline()
}
}
listener.onConnectivityChange(isAnyOnline)
}
private fun Network.isOnline(): Boolean {
val capabilities = connectivityManager.getNetworkCapabilities(this)
return capabilities != null && capabilities.hasCapability(NET_CAPABILITY_INTERNET)
}
}
| apache-2.0 | 2056c5a5edfea4bf83d49572f15f4239 | 31.531532 | 92 | 0.71393 | 4.953361 | false | false | false | false |
Kotlin/anko | anko/library/generator/src/org/jetbrains/android/anko/generator/viewClassGenerators.kt | 4 | 1678 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.utils.isAbstract
import org.jetbrains.android.anko.utils.isInterface
import org.jetbrains.android.anko.utils.isPublic
import org.objectweb.asm.tree.ClassNode
abstract class AbstractViewGenerator(private val forLayouts: Boolean) : Generator<ViewElement> {
override fun generate(state: GenerationState) = with (state) {
fun ClassNode.isViewGroupWithParams() = isViewGroup && hasLayoutParams(this)
state.availableClasses
.filter { it.isPublic && it.isView && forLayouts == it.isViewGroupWithParams() }
.map { ViewElement(it, if (forLayouts) true else it.isViewGroup, { it.resolveAllMethods() }) }
.sortedBy { it.clazz.name }
}
private fun GenerationState.hasLayoutParams(viewGroup: ClassNode): Boolean {
return !viewGroup.isAbstract && extractLayoutParams(viewGroup) != null
}
}
class ViewGenerator : AbstractViewGenerator(forLayouts = false)
class ViewGroupGenerator : AbstractViewGenerator(forLayouts = true) | apache-2.0 | 2385d549f5a344619adffa37f8c9a0ab | 38.97619 | 110 | 0.736591 | 4.34715 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/ToBeContinuedCommand.kt | 1 | 2957 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.morenitta.api.commands.Command
import net.perfectdreams.loritta.common.utils.image.JVMImage
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.vanilla.images.base.ImageAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.awt.Color
import java.awt.image.BufferedImage
class ToBeContinuedCommand(m: LorittaBot) : ImageAbstractCommandBase(m, listOf("tobecontinued")) {
override fun command() = create {
localizedDescription("commands.command.tobecontinued.description")
localizedExamples(Command.SINGLE_IMAGE_EXAMPLES_KEY)
usage {
argument(ArgumentType.TEXT) {}
}
needsToUploadFiles = true
executes {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "tobecontinued")
// TODO: Multiplatform
val mppImage = validate(image(0))
mppImage as JVMImage
val mppImageArrow = loritta.assets.loadImage("to_be_continued_arrow.png", loadFromCache = true)
val template = (mppImageArrow as JVMImage).handle as BufferedImage
val contextImage = mppImage.handle as BufferedImage
val sepiaEffectImage = BufferedImage(contextImage.width, contextImage.height, BufferedImage.TYPE_INT_ARGB)
val sepiaEffectImageGraphics = sepiaEffectImage.createGraphics()
for (x in 0 until contextImage.width) {
for (y in 0 until contextImage.height) {
val rgb = contextImage.getRGB(x, y)
val color = Color(rgb)
// https://stackoverflow.com/questions/1061093/how-is-a-sepia-tone-created
val sepiaRed = (color.red * .393) + (color.green *.769) + (color.blue * .189)
val sepiaGreen = (color.red * .349) + (color.green *.686) + (color.blue * .168)
val sepiaBlue = (color.red * .272) + (color.green *.534) + (color.blue * .131)
sepiaEffectImage.setRGB(
x, y,
Color(
Math.min(
255,
sepiaRed.toInt()
),
Math.min(
255,
sepiaGreen.toInt()
),
Math.min(
255,
sepiaBlue.toInt()
)
).rgb
)
}
}
// Em 1280x720
// A margem entre a parte esquerda até a seta é 42 pixels
// A margem entre a parte de baixo até a seta também é 42 pixels
// A largura da seta é 664
// Altura é 152
val padding = (42 * sepiaEffectImage.width) / 1280
val arrowWidth = (664 * sepiaEffectImage.width) / 1280
val arrowHeight = (152 * arrowWidth) / 664
sepiaEffectImageGraphics.drawImage(
template
.getScaledInstance(
arrowWidth,
arrowHeight,
BufferedImage.SCALE_SMOOTH
),
padding,
sepiaEffectImage.height - padding - arrowHeight,
null
)
sendImage(JVMImage(sepiaEffectImage), "to_be_continued.png")
}
}
} | agpl-3.0 | fffa295eb740d943bc0f6d724043c6e7 | 30.731183 | 109 | 0.691186 | 3.499407 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/GraphicsFonts.kt | 1 | 628 | package net.perfectdreams.loritta.morenitta.utils
import net.perfectdreams.loritta.morenitta.LorittaBot
import java.awt.Font
class GraphicsFonts {
val m5x7 = loadFont("m5x7.ttf")
val oswaldRegular = loadFont("oswald-regular.ttf")
val latoRegular = loadFont("lato-regular.ttf")
val latoBold = loadFont("lato-bold.ttf")
val latoBlack = loadFont("lato-black.ttf")
val bebasNeueRegular = loadFont("bebas-neue-regular.ttf")
val komikaHand = loadFont("komika.ttf")
private fun loadFont(name: String) = Font.createFont(Font.TRUETYPE_FONT, LorittaBot::class.java.getResourceAsStream("/fonts/$name"))
} | agpl-3.0 | cd5672add00d55ad0f40d078fd1bb518 | 38.3125 | 136 | 0.745223 | 3.376344 | false | false | false | false |
guardianproject/phoneypot | src/main/java/org/havenapp/main/ui/viewholder/EventTriggerVH.kt | 1 | 1188 | package org.havenapp.main.ui.viewholder
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import org.havenapp.main.R
import org.havenapp.main.model.EventTrigger
import org.havenapp.main.resources.IResourceManager
/**
* Created by Arka Prava Basu<[email protected]> on 21/02/19
**/
class EventTriggerVH(private val resourceManager: IResourceManager, viewGroup: ViewGroup)
: RecyclerView.ViewHolder(LayoutInflater.from(viewGroup.context)
.inflate(R.layout.item_event_trigger, viewGroup, false)) {
private val indexNumber = itemView.findViewById<TextView>(R.id.index_number)
private val triggerTitle = itemView.findViewById<TextView>(R.id.title)
private val triggerDesc = itemView.findViewById<TextView>(R.id.item_trigger_desc)
fun bind(eventTrigger: EventTrigger, string: String, position: Int) {
indexNumber.text = "#${position + 1}"
triggerTitle.text = eventTrigger.getStringType(resourceManager)
triggerDesc.text = """${eventTrigger.time?.toLocaleString() ?: ""}
|$string: ${eventTrigger.path}""".trimMargin()
}
}
| gpl-3.0 | 0408015484c0fa08707a872b3dfbd916 | 41.428571 | 89 | 0.752525 | 4.168421 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/view/tree/search.kt | 1 | 2406 | package at.cpickl.gadsu.view.tree
import at.cpickl.gadsu.view.LiveSearchField
import com.github.christophpickl.kpotpourri.common.logging.LOG
// controller logic
class TreeSearcher<G, L>(
private val searchField: LiveSearchField,
simpleTrees: List<MyTree<G, L>>
) {
private val log = LOG {}
private val searchTrees: List<SearchableTree<G, L>> = simpleTrees.map {
SearchableTree(
RetainableSelectionsTree(
RetainableExpansionsTree(
it
)
)
)
}
init {
searchField.addListener { searchText ->
val search = searchText.trim()
if (search.isEmpty()) {
clearSearch()
} else {
doSearch(search.split(" "))
}
}
}
private fun doSearch(terms: List<String>) {
log.debug { "doSearch(terms=$terms)" }
searchTrees.forEach { tree ->
tree.search(terms)
}
}
private fun clearSearch() {
log.debug { "clearSearch()" }
searchTrees.forEach { tree ->
tree.restoreOriginalData()
}
}
}
// TODO during search selection doesnt work
class SearchableTree<G, L>(private val tree: Tree<G, L>) : Tree<G, L> by tree {
private val log = LOG {}
private val originalData: MyTreeModel<G, L> = tree.myModel
fun restoreOriginalData() {
log.debug { "restoreOriginalData()" }
tree.setModel2(originalData)
}
fun search(terms: List<String>) {
// MINOR or also search in group node itself for label?!
@Suppress("UNCHECKED_CAST")
val filtered = originalData.nodes
.map { groupNode -> Pair(groupNode, groupNode.subNodes.filter { it.label.matchSearch(terms) }) }
.filter { (_, subs) -> subs.isNotEmpty() }
.map { (it.first as MyNode.MyGroupNode<G, L>).copy(it.second as List<MyNode.MyLeafNode<G, L>>) }
tree.setModel2(MyTreeModel<G, L>(filtered))
}
private fun String.matchSearch(terms: List<String>): Boolean {
val lowerThis = this.toLowerCase().replaceUmlauts()
return terms.all { term -> lowerThis.contains(term.toLowerCase()) }
}
}
fun String.replaceUmlauts()
= replace("ä", "a").
replace("ö", "o").
replace("ü", "u")
| apache-2.0 | c04c317e7441cc53b7c9e2661da3920d | 27.951807 | 112 | 0.567208 | 4.171875 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/form/field/TextFieldState.kt | 1 | 661 | package mil.nga.giat.mage.form.field
import mil.nga.giat.mage.form.FormField
class TextFieldState(definition: FormField<String>) :
FieldState<String, FieldValue.Text>(
definition,
validator = ::isValid,
errorFor = ::errorMessage,
hasValue = ::hasValue
)
private fun errorMessage(definition: FormField<String>, value: FieldValue.Text?): String {
return "Please enter a value"
}
private fun isValid(definition: FormField<String>, value: FieldValue.Text?): Boolean {
return !definition.required || value?.text?.isNotEmpty() == true
}
private fun hasValue(value: FieldValue.Text?): Boolean {
return value?.text?.isNotEmpty() == true
} | apache-2.0 | 1e6a2bd1518131ceb3ddb109d752077c | 27.782609 | 90 | 0.729198 | 4.006061 | false | false | false | false |
FurhatRobotics/example-skills | Quiz/src/main/kotlin/furhatos/app/quiz/flow/main/idle.kt | 1 | 2366 | package furhatos.app.quiz.flow.main
import furhatos.app.quiz.flow.Parent
import furhatos.app.quiz.setting.interested
import furhatos.app.quiz.setting.playing
import furhatos.app.quiz.setting.quiz
import furhatos.flow.kotlin.*
import furhatos.nlu.common.No
import furhatos.nlu.common.Yes
import furhatos.records.User
val Idle: State = state {
onEntry {
/*
Loop through all (potentially) interested users.
Goto calls are used since users may enter and leave
while we are querying other users and we want to
ask all users before moving on. I.e we want to update the
users.interested() list of users.
*/
users.interested().forEach {
furhat.attend(it)
goto(QueryPerson(it))
}
// Once no more user, start the game with all interested users
if (users.playing().isNotEmpty()) {
furhat.attendAll()
goto(NewGame)
}
}
onUserEnter(instant = true) {
/* Say hi and query a new user if it's the only interested user.
Other interested users would already be greeted at this point.
If not, we glance at the user and keep doing whatever we were doing.
*/
if (users.interested().count() == 1) {
furhat.attend(it.id)
furhat.say("Hello there")
goto(QueryPerson(it))
} else {
furhat.glance(it.id, async=true)
}
}
onUserLeave(instant = true) {
if (users.count > 0) {
furhat.attend(users.other)
} else {
furhat.attendNobody()
}
}
onResponse{
reentry()
}
onNoResponse {
reentry()
}
}
// Variables
val maxRounds = 5
var rounds = 0
var shouldChangeUser = true
var playing = false
fun QueryPerson(user: User) = state(parent = Parent) {
onEntry {
if (!user.quiz.played) {
furhat.ask("Do you want to play?")
} else {
furhat.ask("Do you want to play again? Maybe you can beat your old score of ${user.quiz.lastScore}")
}
}
onResponse<Yes> {
user.quiz.playing = true
furhat.say("great!")
goto(Idle)
}
onResponse<No> {
user.quiz.interested = false
furhat.say("oh well")
goto(Idle)
}
}
| mit | b34e10fc7ec6c430cf74c23e07bcc265 | 25.288889 | 112 | 0.579882 | 4.121951 | false | false | false | false |
wireapp/wire-android | app/src/test/kotlin/com/waz/zclient/core/functional/FallbackOnFailureTest.kt | 1 | 3933 | package com.waz.zclient.core.functional
import com.waz.zclient.UnitTest
import com.waz.zclient.core.exception.Failure
import com.waz.zclient.core.exception.ServerError
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.amshove.kluent.shouldEqual
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
@ExperimentalCoroutinesApi
class FallbackOnFailureTest : UnitTest() {
private interface SuspendHelper {
suspend fun primaryAction(): Either<Failure, Unit>
suspend fun fallbackAction(): Either<Failure, Unit>
suspend fun fallbackSuccessAction(toSave: Unit)
}
@Mock
private lateinit var suspendHelper: SuspendHelper
private lateinit var primaryAction: suspend () -> Either<Failure, Unit>
private lateinit var fallbackAction: suspend () -> Either<Failure, Unit>
private lateinit var fallbackSuccessAction: suspend (Unit) -> Unit
@Before
fun setUp() {
primaryAction = suspendHelper::primaryAction
fallbackAction = suspendHelper::fallbackAction
fallbackSuccessAction = suspendHelper::fallbackSuccessAction
}
@Test
fun `given a suspend function, when fallback method called with a fallbackAction, returns EitherFallbackWrapper`() {
val eitherFallbackWrapper = primaryAction.fallback(fallbackAction)
eitherFallbackWrapper shouldEqual FallbackOnFailure(primaryAction, fallbackAction)
}
@Test
fun `given a primaryAction with success, when execute called, does not execute fallbackAction`() {
runBlockingTest {
`when`(suspendHelper.primaryAction()).thenReturn(Either.Right(Unit))
FallbackOnFailure(primaryAction, fallbackAction).execute()
verify(suspendHelper).primaryAction()
verifyNoMoreInteractions(suspendHelper)
}
}
@Test
fun `given a primaryAction with failure, when execute called, executes fallbackAction`() {
runBlockingTest {
`when`(suspendHelper.primaryAction()).thenReturn(Either.Left(ServerError))
val fallbackResponse = mock(Either.Left::class.java) as Either.Left<Failure>
`when`(suspendHelper.fallbackAction()).thenReturn(fallbackResponse)
FallbackOnFailure(primaryAction, fallbackAction).execute()
verify(suspendHelper).primaryAction()
verify(suspendHelper).fallbackAction()
}
}
@Test
fun `given a fallbackAction with success and fallbackSuccessAction, when execute called, executes fallbackSuccessAction`() {
runBlockingTest {
`when`(suspendHelper.primaryAction()).thenReturn(Either.Left(ServerError))
`when`(suspendHelper.fallbackAction()).thenReturn(Either.Right(Unit))
FallbackOnFailure(primaryAction, fallbackAction)
.finally(fallbackSuccessAction)
.execute()
verify(suspendHelper).primaryAction()
verify(suspendHelper).fallbackAction()
verify(suspendHelper).fallbackSuccessAction(Unit)
}
}
@Test
fun `given a fallbackAction with failure and fallbackSuccessAction, when execute called, does not execute fallbackSuccessAction`() {
runBlockingTest {
`when`(suspendHelper.primaryAction()).thenReturn(Either.Left(ServerError))
`when`(suspendHelper.fallbackAction()).thenReturn(Either.Left(ServerError))
FallbackOnFailure(primaryAction, fallbackAction)
.finally(fallbackSuccessAction)
.execute()
verify(suspendHelper).primaryAction()
verify(suspendHelper).fallbackAction()
verifyNoMoreInteractions(suspendHelper)
}
}
}
| gpl-3.0 | 0af8c6c5d254fb666e893bcbd4819e44 | 35.082569 | 136 | 0.706585 | 5.230053 | false | true | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/Card.kt | 1 | 2403 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.kotlin.widget
import android.graphics.Color
import androidx.annotation.ColorInt
import com.facebook.litho.Component
import com.facebook.litho.Dimen
import com.facebook.litho.ResourcesScope
import com.facebook.litho.Style
import com.facebook.litho.dp
import com.facebook.litho.kotlinStyle
import com.facebook.litho.widget.Card
/** Builder function for creating [CardSpec] components. */
@Suppress("FunctionName")
inline fun ResourcesScope.Card(
style: Style? = null,
@ColorInt cardBackgroundColor: Int = Color.WHITE,
cornerRadius: Dimen = 2.dp,
elevation: Dimen = 2.dp,
@ColorInt clippingColor: Int = Integer.MIN_VALUE,
@ColorInt shadowStartColor: Int = 0x37000000,
@ColorInt shadowEndColor: Int = 0x03000000,
shadowBottomOverride: Dimen? = null,
disableClipTopLeft: Boolean = false,
disableClipTopRight: Boolean = false,
disableClipBottomLeft: Boolean = false,
disableClipBottomRight: Boolean = false,
transparencyEnabled: Boolean = false,
child: ResourcesScope.() -> Component
): Card =
Card.create(context)
.transparencyEnabled(transparencyEnabled)
.cardBackgroundColor(cardBackgroundColor)
.cornerRadiusPx(cornerRadius.toPixels().toFloat())
.elevationPx(elevation.toPixels().toFloat())
.clippingColor(clippingColor)
.shadowStartColor(shadowStartColor)
.shadowEndColor(shadowEndColor)
.shadowBottomOverridePx(shadowBottomOverride?.toPixels() ?: -1)
.disableClipTopLeft(disableClipTopLeft)
.disableClipTopRight(disableClipTopRight)
.disableClipBottomLeft(disableClipBottomLeft)
.disableClipBottomRight(disableClipBottomRight)
.content(child())
.kotlinStyle(style)
.build()
| apache-2.0 | a28afbd5082fbe49e52b5f0ce4b64d50 | 37.758065 | 75 | 0.736579 | 4.369091 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsUseSpeck.kt | 2 | 1099 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.psi.RsUseGroup
import org.rust.lang.core.psi.RsUseSpeck
import org.rust.lang.core.stubs.RsUseSpeckStub
val RsUseSpeck.isStarImport: Boolean get() = stub?.isStarImport ?: (mul != null) // I hate operator precedence
val RsUseSpeck.qualifier: RsPath? get() =
(context as? RsUseGroup)?.parentUseSpeck?.path
val RsUseSpeck.nameInScope: String? get() {
if (useGroup != null) return null
alias?.name?.let { return it }
val baseName = path?.referenceName ?: return null
if (baseName == "self") {
return qualifier?.referenceName
}
return baseName
}
abstract class RsUseSpeckImplMixin : RsStubbedElementImpl<RsUseSpeckStub>, RsUseSpeck {
constructor (node: ASTNode) : super(node)
constructor (stub: RsUseSpeckStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
}
| mit | 3bae1d3d3ff77075062704de2e19fa76 | 33.34375 | 110 | 0.733394 | 3.911032 | false | false | false | false |
square/leakcanary | shark-graph/src/main/java/shark/internal/FieldValuesReader.kt | 2 | 3241 | package shark.internal
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.FieldRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.InstanceDumpRecord
import shark.PrimitiveType
import shark.PrimitiveType.BOOLEAN
import shark.PrimitiveType.BYTE
import shark.PrimitiveType.CHAR
import shark.PrimitiveType.DOUBLE
import shark.PrimitiveType.FLOAT
import shark.PrimitiveType.INT
import shark.PrimitiveType.LONG
import shark.PrimitiveType.SHORT
import shark.ValueHolder
import shark.ValueHolder.BooleanHolder
import shark.ValueHolder.ByteHolder
import shark.ValueHolder.CharHolder
import shark.ValueHolder.DoubleHolder
import shark.ValueHolder.FloatHolder
import shark.ValueHolder.IntHolder
import shark.ValueHolder.LongHolder
import shark.ValueHolder.ReferenceHolder
import shark.ValueHolder.ShortHolder
internal class FieldValuesReader(
private val record: InstanceDumpRecord,
private val identifierByteSize: Int
) {
private var position = 0
fun readValue(field: FieldRecord): ValueHolder {
return when (field.type) {
PrimitiveType.REFERENCE_HPROF_TYPE -> ReferenceHolder(readId())
BOOLEAN_TYPE -> BooleanHolder(readBoolean())
CHAR_TYPE -> CharHolder(readChar())
FLOAT_TYPE -> FloatHolder(readFloat())
DOUBLE_TYPE -> DoubleHolder(readDouble())
BYTE_TYPE -> ByteHolder(readByte())
SHORT_TYPE -> ShortHolder(readShort())
INT_TYPE -> IntHolder(readInt())
LONG_TYPE -> LongHolder(readLong())
else -> throw IllegalStateException("Unknown type ${field.type}")
}
}
private fun readId(): Long {
// As long as we don't interpret IDs, reading signed values here is fine.
return when (identifierByteSize) {
1 -> readByte().toLong()
2 -> readShort().toLong()
4 -> readInt().toLong()
8 -> readLong()
else -> throw IllegalArgumentException("ID Length must be 1, 2, 4, or 8")
}
}
private fun readBoolean(): Boolean {
val value = record.fieldValues[position]
position++
return value != 0.toByte()
}
private fun readByte(): Byte {
val value = record.fieldValues[position]
position++
return value
}
private fun readInt(): Int {
val value = record.fieldValues.readInt(position)
position += 4
return value
}
private fun readShort(): Short {
val value = record.fieldValues.readShort(position)
position += 2
return value
}
private fun readLong(): Long {
val value = record.fieldValues.readLong(position)
position += 8
return value
}
private fun readFloat(): Float {
return Float.fromBits(readInt())
}
private fun readDouble(): Double {
return Double.fromBits(readLong())
}
private fun readChar(): Char {
val string = String(record.fieldValues, position, 2, Charsets.UTF_16BE)
position += 2
return string[0]
}
companion object {
private val BOOLEAN_TYPE = BOOLEAN.hprofType
private val CHAR_TYPE = CHAR.hprofType
private val FLOAT_TYPE = FLOAT.hprofType
private val DOUBLE_TYPE = DOUBLE.hprofType
private val BYTE_TYPE = BYTE.hprofType
private val SHORT_TYPE = SHORT.hprofType
private val INT_TYPE = INT.hprofType
private val LONG_TYPE = LONG.hprofType
}
} | apache-2.0 | c9aeb176b9658a97ede07f4150d6d967 | 27.946429 | 80 | 0.720148 | 4.427596 | false | false | false | false |
google/horologist | media3-backend/src/main/java/com/google/android/horologist/media3/logging/AnalyticsEventLogger.kt | 1 | 6739 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.media3.logging
import android.annotation.SuppressLint
import androidx.media3.common.Format
import androidx.media3.common.MediaMetadata
import androidx.media3.common.PlaybackException
import androidx.media3.exoplayer.DecoderReuseEvaluation
import androidx.media3.exoplayer.analytics.AnalyticsListener
import androidx.media3.exoplayer.source.LoadEventInfo
import androidx.media3.exoplayer.source.MediaLoadData
import androidx.media3.exoplayer.util.EventLogger
import com.google.android.horologist.media3.ExperimentalHorologistMedia3BackendApi
import java.io.IOException
/**
* Simple implementation of EventLogger for logging critical Media3 events.
*
* Most logging behaviour is inherited from EventLogger.
*/
@SuppressLint("UnsafeOptInUsageError")
@ExperimentalHorologistMedia3BackendApi
public class AnalyticsEventLogger(
private val appEventLogger: ErrorReporter
) : EventLogger("ErrorReporter") {
override fun onAudioSinkError(
eventTime: AnalyticsListener.EventTime,
audioSinkError: Exception
) {
appEventLogger.logMessage(
"onAudioSinkError $audioSinkError",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Error
)
}
override fun onAudioCodecError(
eventTime: AnalyticsListener.EventTime,
audioCodecError: Exception
) {
appEventLogger.logMessage(
"onAudioCodecError $audioCodecError",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Error
)
}
override fun onPlaybackStateChanged(eventTime: AnalyticsListener.EventTime, state: Int) {
appEventLogger.logMessage(
"onPlaybackStateChanged $state",
category = ErrorReporter.Category.Playback
)
super.onPlaybackStateChanged(eventTime, state)
}
override fun onPlayWhenReadyChanged(
eventTime: AnalyticsListener.EventTime,
playWhenReady: Boolean,
reason: Int
) {
appEventLogger.logMessage(
"onPlayWhenReadyChanged $playWhenReady $reason",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Debug
)
super.onPlayWhenReadyChanged(eventTime, playWhenReady, reason)
}
override fun onAudioUnderrun(
eventTime: AnalyticsListener.EventTime,
bufferSize: Int,
bufferSizeMs: Long,
elapsedSinceLastFeedMs: Long
) {
appEventLogger.logMessage(
"onAudioUnderrun $elapsedSinceLastFeedMs",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Error
)
super.onAudioUnderrun(eventTime, bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
}
override fun onIsLoadingChanged(eventTime: AnalyticsListener.EventTime, isLoading: Boolean) {
appEventLogger.logMessage(
"onIsLoadingChanged $isLoading",
category = ErrorReporter.Category.Playback
)
super.onIsLoadingChanged(eventTime, isLoading)
}
override fun onLoadError(
eventTime: AnalyticsListener.EventTime,
loadEventInfo: LoadEventInfo,
mediaLoadData: MediaLoadData,
error: IOException,
wasCanceled: Boolean
) {
appEventLogger.logMessage(
"onLoadError $error",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Error
)
super.onLoadError(eventTime, loadEventInfo, mediaLoadData, error, wasCanceled)
}
override fun onMediaMetadataChanged(
eventTime: AnalyticsListener.EventTime,
mediaMetadata: MediaMetadata
) {
appEventLogger.logMessage(
"onMediaMetadataChanged ${mediaMetadata.displayTitle}",
category = ErrorReporter.Category.Playback
)
}
override fun onPlayerError(eventTime: AnalyticsListener.EventTime, error: PlaybackException) {
appEventLogger.logMessage(
"onPlayerError $error",
category = ErrorReporter.Category.Playback,
level = ErrorReporter.Level.Error
)
super.onPlayerError(eventTime, error)
}
override fun onLoadStarted(
eventTime: AnalyticsListener.EventTime,
loadEventInfo: LoadEventInfo,
mediaLoadData: MediaLoadData
) {
appEventLogger.logMessage(
"onLoadStarted",
category = ErrorReporter.Category.Playback
)
}
override fun onLoadCompleted(
eventTime: AnalyticsListener.EventTime,
loadEventInfo: LoadEventInfo,
mediaLoadData: MediaLoadData
) {
appEventLogger.logMessage(
"onLoadCompleted",
category = ErrorReporter.Category.Playback
)
}
override fun onAudioInputFormatChanged(
eventTime: AnalyticsListener.EventTime,
format: Format,
decoderReuseEvaluation: DecoderReuseEvaluation?
) {
appEventLogger.logMessage(
"onAudioInputFormatChanged ${format.codecs.orEmpty()} ${format.bitrate} ${format.containerMimeType.orEmpty()}",
level = ErrorReporter.Level.Debug,
category = ErrorReporter.Category.Playback
)
super.onAudioInputFormatChanged(eventTime, format, decoderReuseEvaluation)
}
override fun onDownstreamFormatChanged(
eventTime: AnalyticsListener.EventTime,
mediaLoadData: MediaLoadData
) {
appEventLogger.logMessage(
"onDownstreamFormatChanged ${mediaLoadData.dataType}",
category = ErrorReporter.Category.Playback
)
super.onDownstreamFormatChanged(eventTime, mediaLoadData)
}
override fun onBandwidthEstimate(
eventTime: AnalyticsListener.EventTime,
totalLoadTimeMs: Int,
totalBytesLoaded: Long,
bitrateEstimate: Long
) {
appEventLogger.logMessage(
"onBandwidthEstimate $bitrateEstimate",
level = ErrorReporter.Level.Debug
)
}
}
| apache-2.0 | 40ea0c8501dbc533cd58bcede98d5c0e | 33.208122 | 123 | 0.688084 | 5.21191 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/theme/ColorSchemeUtils.kt | 1 | 3921 | package app.lawnchair.theme
import androidx.compose.material.Colors
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import dev.kdrag0n.monet.theme.ColorScheme
import kotlin.math.ln
import androidx.compose.material3.ColorScheme as M3ColorScheme
@Composable
fun m3ColorScheme(colorScheme: ColorScheme, isDark: Boolean) = remember(colorScheme, isDark) {
when (isDark) {
false -> lightColorScheme(
primary = colorScheme.primary(40),
onPrimary = colorScheme.primary(100),
primaryContainer = colorScheme.primary(90),
onPrimaryContainer = colorScheme.primary(10),
inversePrimary = colorScheme.primary(80),
secondary = colorScheme.secondary(40),
onSecondary = colorScheme.secondary(100),
secondaryContainer = colorScheme.secondary(90),
onSecondaryContainer = colorScheme.secondary(10),
tertiaryContainer = colorScheme.tertiary(90),
onTertiaryContainer = colorScheme.tertiary(10),
background = colorScheme.neutral(99),
onBackground = colorScheme.neutral(10),
surface = colorScheme.neutral(99),
onSurface = colorScheme.neutral(10),
surfaceVariant = colorScheme.neutralVariant(90),
onSurfaceVariant = colorScheme.neutralVariant(30),
inverseSurface = colorScheme.neutral(20),
inverseOnSurface = colorScheme.neutral(95),
outline = colorScheme.neutralVariant(50),
)
true -> darkColorScheme(
primary = colorScheme.primary(80),
onPrimary = colorScheme.primary(20),
primaryContainer = colorScheme.primary(30),
onPrimaryContainer = colorScheme.primary(90),
inversePrimary = colorScheme.primary(40),
secondary = colorScheme.secondary(80),
onSecondary = colorScheme.secondary(20),
secondaryContainer = colorScheme.secondary(30),
onSecondaryContainer = colorScheme.secondary(90),
tertiaryContainer = colorScheme.tertiary(30),
onTertiaryContainer = colorScheme.tertiary(90),
background = colorScheme.neutral(10),
onBackground = colorScheme.neutral(90),
surface = colorScheme.neutral(10),
onSurface = colorScheme.neutral(90),
surfaceVariant = colorScheme.neutralVariant(30),
onSurfaceVariant = colorScheme.neutralVariant(80),
inverseSurface = colorScheme.neutral(90),
inverseOnSurface = colorScheme.neutral(20),
outline = colorScheme.neutralVariant(60),
)
}
}
internal fun M3ColorScheme.surfaceColorAtElevation(
elevation: Dp,
): Color {
if (elevation == 0.dp) return surface
val alpha = ((4.5f * ln(elevation.value + 1)) + 2f) / 100f
return primary.copy(alpha = alpha).compositeOver(surface)
}
@Composable
fun materialColors(colorScheme: M3ColorScheme, isDark: Boolean) = remember(colorScheme, isDark) {
Colors(
primary = colorScheme.primary,
primaryVariant = colorScheme.primaryContainer,
secondary = colorScheme.primary,
secondaryVariant = colorScheme.primaryContainer,
background = colorScheme.background,
surface = colorScheme.surfaceColorAtElevation(1.dp),
error = colorScheme.error,
onPrimary = colorScheme.onPrimary,
onSecondary = colorScheme.onSecondary,
onBackground = colorScheme.onBackground,
onSurface = colorScheme.onSurface,
onError = colorScheme.onError,
isLight = !isDark
)
}
| gpl-3.0 | 6eb0348bb3670811e5c1b4ee96689257 | 42.087912 | 97 | 0.678653 | 5.033376 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/adapter/GroupPagerAdapter.kt | 2 | 1937 | package com.commit451.gitlab.adapter
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.commit451.gitlab.R
import com.commit451.gitlab.extension.feedUrl
import com.commit451.gitlab.fragment.FeedFragment
import com.commit451.gitlab.fragment.GroupMembersFragment
import com.commit451.gitlab.fragment.ProjectsFragment
import com.commit451.gitlab.model.api.Group
import java.util.*
/**
* Group pager adapter
*/
class GroupPagerAdapter(context: Context, fm: FragmentManager, private val group: Group) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
companion object {
private const val SECTION_COUNT = 3
private const val ACTIVITY_POS = 0
private const val PROJECTS_POS = 1
private const val MEMBERS_POS = 2
}
private val titles: Array<String> = context.resources.getStringArray(R.array.group_tabs)
private val disabledSections = HashSet<Int>()
override fun getItem(position: Int): Fragment {
when (getCorrectPosition(position)) {
ACTIVITY_POS -> return FeedFragment.newInstance(group.feedUrl)
PROJECTS_POS -> return ProjectsFragment.newInstance(group)
MEMBERS_POS -> return GroupMembersFragment.newInstance(group)
}
throw IllegalStateException("Position exceeded on view pager")
}
override fun getCount(): Int {
return SECTION_COUNT - disabledSections.size
}
override fun getPageTitle(position: Int): CharSequence {
return titles[getCorrectPosition(position)]
}
private fun getCorrectPosition(position: Int): Int {
var correctPosition = position
for (i in 0..position) {
if (disabledSections.contains(i)) {
correctPosition++
}
}
return correctPosition
}
}
| apache-2.0 | 1f579d4a51d851d97d31429a54b0e1bc | 31.830508 | 156 | 0.710377 | 4.525701 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/samples/basics/SimpleWalkthrough.kt | 1 | 1337 | package io.noties.markwon.app.samples.basics
import android.text.Spanned
import io.noties.markwon.Markwon
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample
import io.noties.markwon.core.CorePlugin
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
import org.commonmark.node.Node
@MarkwonSampleInfo(
id = "20200626153426",
title = "Simple with walk-through",
description = "Walk-through for simple use case",
artifacts = [MarkwonArtifact.CORE],
tags = [Tag.basics]
)
class SimpleWalkthrough : MarkwonTextViewSample() {
override fun render() {
val md: String = """
# Hello!
> a quote
```
code block
```
""".trimIndent()
// create markwon instance via builder method
val markwon: Markwon = Markwon.builder(context)
// add required plugins
// NB, there is no need to add CorePlugin as it is added automatically
.usePlugin(CorePlugin.create())
.build()
// parse markdown into commonmark representation
val node: Node = markwon.parse(md)
// render commonmark node
val markdown: Spanned = markwon.render(node)
// apply it to a TextView
markwon.setParsedMarkdown(textView, markdown)
}
} | apache-2.0 | 1b5823fb8a658d6368b605a955d9732e | 27.468085 | 76 | 0.709798 | 4.244444 | false | false | false | false |
jtransc/jtransc | jtransc-gradle-plugin/src/com/jtransc/gradle/internal/SemVer.kt | 1 | 609 | package com.jtransc.gradle.internal
import java.util.*
internal data class SemVer(val version: String) : Comparable<SemVer> {
override fun compareTo(other: SemVer): Int = Scanner(this.version).use { s1 ->
Scanner(other.version).use { s2 ->
s1.useDelimiter("\\.")
s2.useDelimiter("\\.")
while (s1.hasNextInt() && s2.hasNextInt()) {
val v1 = s1.nextInt()
val v2 = s2.nextInt()
if (v1 < v2) {
return -1
} else if (v1 > v2) {
return 1
}
}
if (s1.hasNextInt() && s1.nextInt() != 0) return 1
return if (s2.hasNextInt() && s2.nextInt() != 0) -1 else 0
}
}
}
| apache-2.0 | 89594c343794765aa6223e07b31e1ff3 | 23.36 | 79 | 0.596059 | 2.793578 | false | false | false | false |
square/moshi | moshi/src/main/java/com/squareup/moshi/JsonValueSource.kt | 1 | 6913 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.moshi
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ByteString.Companion.EMPTY
import okio.ByteString.Companion.encodeUtf8
import okio.EOFException
import okio.Source
import kotlin.jvm.JvmOverloads
import kotlin.math.min
/**
* This source reads a prefix of another source as a JSON value and then terminates. It can read
* top-level arrays, objects, or strings only.
*
* It implements [lenient parsing][JsonReader.setLenient] and has no mechanism to
* enforce strict parsing. If the input is not valid or lenient JSON the behavior of this source is
* unspecified.
*/
internal class JsonValueSource @JvmOverloads constructor(
private val source: BufferedSource,
/** If non-empty, data from this should be returned before data from [source]. */
private val prefix: Buffer = Buffer(),
/**
* The state indicates what kind of data is readable at [limit]. This also serves
* double-duty as the type of bytes we're interested in while in this state.
*/
private var state: ByteString = STATE_JSON,
/**
* The level of nesting of arrays and objects. When the end of string, array, or object is
* reached, this should be compared against 0. If it is zero, then we've read a complete value and
* this source is exhausted.
*/
private var stackSize: Int = 0
) : Source {
private val buffer: Buffer = source.buffer
/** The number of bytes immediately returnable to the caller. */
private var limit: Long = 0
private var closed = false
/**
* Advance [limit] until any of these conditions are met:
* * Limit is at least `byteCount`. We can satisfy the caller's request!
* * The JSON value is complete. This stream is exhausted.
* * We have some data to return and returning more would require reloading the buffer. We prefer to return some
* data immediately when more data requires blocking.
*
* @throws EOFException if the stream is exhausted before the JSON object completes.
*/
private fun advanceLimit(byteCount: Long) {
while (limit < byteCount) {
// If we've finished the JSON object, we're done.
if (state === STATE_END_OF_JSON) {
return
}
// If we can't return any bytes without more data in the buffer, grow the buffer.
if (limit == buffer.size) {
if (limit > 0L) return
source.require(1L)
}
// Find the next interesting character for the current state. If the buffer doesn't have one,
// then we can read the entire buffer.
val index = buffer.indexOfElement(state, limit)
if (index == -1L) {
limit = buffer.size
continue
}
val b = buffer[index]
when {
state === STATE_JSON -> when (b.toInt().toChar()) {
'[', '{' -> {
stackSize++
limit = index + 1
}
']', '}' -> {
stackSize--
if (stackSize == 0) state = STATE_END_OF_JSON
limit = index + 1
}
'\"' -> {
state = STATE_DOUBLE_QUOTED
limit = index + 1
}
'\'' -> {
state = STATE_SINGLE_QUOTED
limit = index + 1
}
'/' -> {
source.require(index + 2)
when (buffer[index + 1]) {
'/'.code.toByte() -> {
state = STATE_END_OF_LINE_COMMENT
limit = index + 2
}
'*'.code.toByte() -> {
state = STATE_C_STYLE_COMMENT
limit = index + 2
}
else -> {
limit = index + 1
}
}
}
'#' -> {
state = STATE_END_OF_LINE_COMMENT
limit = index + 1
}
}
state === STATE_SINGLE_QUOTED || state === STATE_DOUBLE_QUOTED -> {
if (b == '\\'.code.toByte()) {
source.require(index + 2)
limit = index + 2
} else {
state = if (stackSize > 0) STATE_JSON else STATE_END_OF_JSON
limit = index + 1
}
}
state === STATE_C_STYLE_COMMENT -> {
source.require(index + 2)
if (buffer[index + 1] == '/'.code.toByte()) {
limit = index + 2
state = STATE_JSON
} else {
limit = index + 1
}
}
state === STATE_END_OF_LINE_COMMENT -> {
limit = index + 1
state = STATE_JSON
}
else -> {
throw AssertionError()
}
}
}
}
/**
* Discards any remaining JSON data in this source that was left behind after it was closed. It is
* an error to call [read] after calling this method.
*/
fun discard() {
closed = true
while (state !== STATE_END_OF_JSON) {
advanceLimit(8192)
source.skip(limit)
}
}
override fun read(sink: Buffer, byteCount: Long): Long {
var mutableByteCount = byteCount
check(!closed) { "closed" }
if (mutableByteCount == 0L) return 0L
// If this stream has a prefix, consume that first.
if (!prefix.exhausted()) {
val prefixResult = prefix.read(sink, mutableByteCount)
mutableByteCount -= prefixResult
if (buffer.exhausted()) return prefixResult // Defer a blocking call.
val suffixResult = read(sink, mutableByteCount)
return if (suffixResult != -1L) suffixResult + prefixResult else prefixResult
}
advanceLimit(mutableByteCount)
if (limit == 0L) {
if (state !== STATE_END_OF_JSON) throw AssertionError()
return -1L
}
val result = min(mutableByteCount, limit)
sink.write(buffer, result)
limit -= result
return result
}
override fun timeout() = source.timeout()
override fun close() {
// Note that this does not close the underlying source; that's the creator's responsibility.
closed = true
}
companion object {
val STATE_JSON: ByteString = "[]{}\"'/#".encodeUtf8()
val STATE_SINGLE_QUOTED: ByteString = "'\\".encodeUtf8()
val STATE_DOUBLE_QUOTED: ByteString = "\"\\".encodeUtf8()
val STATE_END_OF_LINE_COMMENT: ByteString = "\r\n".encodeUtf8()
val STATE_C_STYLE_COMMENT: ByteString = "*".encodeUtf8()
val STATE_END_OF_JSON: ByteString = EMPTY
}
}
| apache-2.0 | 0255821cd22318c98a4a6c4e0d53757b | 32.235577 | 115 | 0.596991 | 4.272559 | false | false | false | false |
tutao/tutanota | app-android/app/src/main/java/de/tutao/tutanota/push/NetworkObserver.kt | 1 | 1767 | package de.tutao.tutanota.push
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
class NetworkObserver internal constructor(private val context: Context, lifecycleOwner: LifecycleOwner) :
BroadcastReceiver(), DefaultLifecycleObserver {
private val connectivityManager: ConnectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private var networkConnectivityListener: NetworkConnectivityListener? = null
init {
context.registerReceiver(this, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
lifecycleOwner.lifecycle.addObserver(this)
}
override fun onReceive(context: Context, intent: Intent) {
val hasConnection = hasNetworkConnection()
if (!hasConnection) {
Log.d(TAG, "Network is DOWN")
} else {
Log.d(TAG, "Network is UP")
}
if (networkConnectivityListener != null) {
networkConnectivityListener!!.onNetworkConnectivityChange(hasConnection)
}
}
fun hasNetworkConnection(): Boolean {
val networkInfo = connectivityManager.activeNetworkInfo
return networkInfo != null && networkInfo.isConnectedOrConnecting
}
fun setNetworkConnectivityListener(networkConnectivityListener: NetworkConnectivityListener) {
this.networkConnectivityListener = networkConnectivityListener
}
fun interface NetworkConnectivityListener {
fun onNetworkConnectivityChange(connected: Boolean)
}
override fun onDestroy(owner: LifecycleOwner) {
context.unregisterReceiver(this)
}
companion object {
const val TAG = "NetworkObserver"
}
} | gpl-3.0 | eacec7b94be871a9f32720a1f92020aa | 30.571429 | 106 | 0.812677 | 4.613577 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/clone.kt | 1 | 6595 | package com.binarymonks.jj.core
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.ObjectSet
import com.binarymonks.jj.core.extensions.copy
import com.binarymonks.jj.core.properties.PROP_OVERRIDE_TYPE
import com.binarymonks.jj.core.properties.PropOverride
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty1
import kotlin.reflect.KVisibility
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.jvmErasure
/**
* Something that can make copies of itself. T should be a type or supertype of the implementer for this to make
* sense of course.
*/
interface Copyable<T> {
/**
* The expectation for this function is that only fields that are visible and modifiable will be copied.
* Use [copy] to achieve deep clones of [Copyable] implementations.
*/
fun clone(): T
}
/**
* Makes copies of things.
*
* Will try to copy any visible and modifiable properties.
* Will call [Copyable.clone] on properties that implement it.
* Will check members of the following collections for [Copyable]:
* - [com.badlogic.gdx.utils.ObjectMap]
* - [com.badlogic.gdx.utils.Array]
* - [com.badlogic.gdx.utils.ObjectSet]
*
*/
fun <T: Any> copy(original: T): T {
if(original is Number){
return original
}
if(original is String){
return original
}
if (original is ObjectMap<*,*>){
@Suppress("UNCHECKED_CAST")
return original.copy() as T
}
if (original is Array<*>){
@Suppress("UNCHECKED_CAST")
return original.copy() as T
}
if (original is ObjectSet<*>){
@Suppress("UNCHECKED_CAST")
return original.copy() as T
}
val myClass = original::class
var copy = construct(myClass)
myClass.memberProperties.forEach {
val name = it.name
try {
if (it.visibility == KVisibility.PUBLIC && isPubliclyMutable(it)) {
when {
original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) == null -> copyProperty(original, copy, name)
it.returnType.jvmErasure.isSubclassOf(Copyable::class) -> {
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) as Copyable<*>
val destinationProperty = getMutable(copy, name)
destinationProperty.setter.call(copy, sourceProperty.clone())
}
it.returnType.jvmErasure.isSubclassOf(Array::class) -> {
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) as Array<*>
val destinationProperty = getMutable(copy, name)
destinationProperty.setter.call(copy, sourceProperty.copy())
}
it.returnType.jvmErasure.isSubclassOf(ObjectMap::class) -> {
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) as ObjectMap<*, *>
val destinationProperty = getMutable(copy, name)
destinationProperty.setter.call(copy, sourceProperty.copy())
}
it.returnType.jvmErasure.isSubclassOf(ObjectSet::class) -> {
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) as ObjectSet<*>
val destinationProperty = getMutable(copy, name)
destinationProperty.setter.call(copy, sourceProperty.copy())
}
else -> copyProperty(original, copy, name)
}
}
if (it.visibility == KVisibility.PUBLIC){
@Suppress("UNCHECKED_CAST") // Doing ugly type erasure/overwrite hack to allow copying
if(it.returnType.isSubtypeOf(PROP_OVERRIDE_TYPE)){
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original) as PropOverride<String>
val destinationProperty = copy.javaClass.kotlin.memberProperties.first { it.name == name }.get(copy) as PropOverride<String>
destinationProperty.copyFrom(sourceProperty)
}
}
} catch (e: Exception) {
Gdx.app.log("copy","Could not copy $name in ${myClass.simpleName}. Is it okay to share the same instance?")
val sourceProperty = original.javaClass.kotlin.memberProperties.first { it.name == name }.get(original)
val destinationProperty = getMutable(copy, name)
destinationProperty.setter.call(copy, sourceProperty)
}
}
return copy
}
fun forceCopy(original:Any?):Any?{
if(original==null){
return original
}
val notNull: Any = original
return copy(notNull)
}
fun getMutable(instance: Any, name: String): KMutableProperty<*> {
val property = instance.javaClass.kotlin.memberProperties.first { it.name == name }
if (property is KMutableProperty<*>) {
return property
}
throw Exception("Seems that property is not actually mutable")
}
fun isPubliclyMutable(property: KProperty1<*, *>): Boolean {
if (property is KMutableProperty<*>) {
if (property.setter.visibility == KVisibility.PUBLIC) {
return true
}
return false
} else {
return false
}
}
fun <T : Any> construct(kClass: KClass<T>): T {
kClass.constructors.forEach {
if (it.parameters.isEmpty()) {
return it.call()
} else {
var allParamsHaveDefaults = true
it.parameters.forEach {
if (!it.isOptional) {
allParamsHaveDefaults = false
}
}
if (allParamsHaveDefaults) {
return it.callBy(emptyMap())
}
}
}
throw Exception("No empty or fully optional constructor")
}
fun copyProperty(source: Any, destination: Any, propertyName: String) {
val sourceProperty = source.javaClass.kotlin.memberProperties.first { it.name == propertyName }.get(source)
val destinationProperty = getMutable(destination, propertyName)
destinationProperty.setter.call(destination, sourceProperty)
}
| apache-2.0 | 0197795c1d85decceb9fb502e5b2bd06 | 39.709877 | 148 | 0.62881 | 4.664074 | false | false | false | false |
square/duktape-android | zipline/src/commonMain/kotlin/app/cash/zipline/internal/bridge/throwables.kt | 1 | 3837 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.internal.bridge
import app.cash.zipline.ZiplineApiMismatchException
import app.cash.zipline.ZiplineException
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
internal expect fun stacktraceString(throwable: Throwable): String
internal expect fun toInboundThrowable(
stacktraceString: String,
constructor: (String) -> Throwable,
): Throwable
/**
* Serialize a [Throwable] in two parts:
*
* * A list of types in preference-order. We'll only need one type in almost all cases, but if we
* want to introduce new throwable subtypes in the future this enables backwards=compatibility.
*
* * The throwable message and stacktrace, all together. This may be prefixed with the name
* of the throwable class.
*/
@Serializable
internal class ThrowableSurrogate(
/**
* A list of types in preference order to decode this throwable into. If a type is unrecognized
* it should be skipped, ultimately falling back to [Exception] if no types are recognized.
*/
val types: List<String>,
/**
* The result of [Throwable.stackTraceToString], potentially with code from Zipline's bridges
* stripped.
*/
val stacktraceString: String,
)
internal object ThrowableSerializer : KSerializer<Throwable> {
private val surrogateSerializer = ThrowableSurrogate.serializer()
override val descriptor = surrogateSerializer.descriptor
override fun serialize(encoder: Encoder, value: Throwable) {
val stacktraceString = stacktraceString(value)
val typeNames = knownTypeNames(value)
encoder.encodeSerializableValue(
surrogateSerializer,
ThrowableSurrogate(
types = typeNames,
stacktraceString = stacktraceString,
),
)
}
override fun deserialize(decoder: Decoder): Throwable {
val surrogate = decoder.decodeSerializableValue(surrogateSerializer)
// Find a throwable type to decode as.
val typeNameToConstructor: Pair<String, (String) -> Throwable> =
surrogate.types.firstNotNullOfOrNull { typeName ->
val constructor = knownTypeConstructor(typeName) ?: return@firstNotNullOfOrNull null
typeName to constructor
} ?: ("ZiplineException" to { message -> ZiplineException(message) })
val (typeName, constructor) = typeNameToConstructor
// Strip off "ZiplineApiMismatchException: " prefix (or similar) so it isn't repeated.
var stacktraceString = surrogate.stacktraceString
if (stacktraceString.startsWith(typeName) &&
stacktraceString.regionMatches(typeName.length, ": ", 0, 2)
) {
stacktraceString = stacktraceString.substring(typeName.length + 2)
}
return toInboundThrowable(stacktraceString, constructor)
}
private fun knownTypeNames(throwable: Throwable): List<String> {
return when (throwable) {
is ZiplineApiMismatchException -> listOf("ZiplineApiMismatchException")
else -> listOf()
}
}
private fun knownTypeConstructor(typeName: String): ((String) -> Throwable)? {
return when (typeName) {
"ZiplineApiMismatchException" -> ::ZiplineApiMismatchException
else -> null
}
}
}
| apache-2.0 | d045862549540c527f144edc04051049 | 34.527778 | 98 | 0.737295 | 4.679268 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-nearby-core/src/main/kotlin/org/microg/gms/nearby/exposurenotification/AdvertiserService.kt | 1 | 9639 | /*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.nearby.exposurenotification
import android.annotation.TargetApi
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_ONE_SHOT
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.*
import android.bluetooth.le.AdvertiseSettings.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.*
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.microg.gms.common.ForegroundServiceContext
import java.io.FileDescriptor
import java.io.PrintWriter
import java.nio.ByteBuffer
import java.util.*
@TargetApi(21)
class AdvertiserService : LifecycleService() {
private val version = VERSION_1_0
private var advertising = false
private var wantStartAdvertising = false
private val advertiser: BluetoothLeAdvertiser?
get() = BluetoothAdapter.getDefaultAdapter()?.bluetoothLeAdvertiser
private val alarmManager: AlarmManager
get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager
private val callback: AdvertiseCallback = object : AdvertiseCallback() {
override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) {
Log.d(TAG, "Advertising active for ${settingsInEffect?.timeout}ms")
}
override fun onStartFailure(errorCode: Int) {
Log.w(TAG, "Advertising failed: $errorCode")
stopOrRestartAdvertising()
}
}
@TargetApi(23)
private var setCallback: Any? = null
private val trigger = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == "android.bluetooth.adapter.action.STATE_CHANGED") {
when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> stopOrRestartAdvertising()
BluetoothAdapter.STATE_ON -> startAdvertisingIfNeeded()
}
}
}
}
private val handler = Handler(Looper.getMainLooper())
private val startLaterRunnable = Runnable { startAdvertisingIfNeeded() }
override fun onCreate() {
super.onCreate()
registerReceiver(trigger, IntentFilter().also { it.addAction("android.bluetooth.adapter.action.STATE_CHANGED") })
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
ForegroundServiceContext.completeForegroundService(this, intent, TAG)
super.onStartCommand(intent, flags, startId)
if (intent?.action == ACTION_RESTART_ADVERTISING && advertising) {
stopOrRestartAdvertising()
} else {
startAdvertisingIfNeeded()
}
return START_STICKY
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(trigger)
stopOrRestartAdvertising()
handler.removeCallbacks(startLaterRunnable)
}
private fun startAdvertisingIfNeeded() {
if (ExposurePreferences(this).enabled) {
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO) {
startAdvertising()
}
}
} else {
stopSelf()
}
}
private var lastStartTime = System.currentTimeMillis()
private var sendingBytes = ByteArray(0)
private var starting = false
private suspend fun startAdvertising() {
val advertiser = synchronized(this) {
if (advertising || starting) return
val advertiser = advertiser ?: return
wantStartAdvertising = false
starting = true
advertiser
}
try {
val aemBytes = when (version) {
VERSION_1_0 -> byteArrayOf(
version, // Version and flags
(currentDeviceInfo.txPowerCorrection + TX_POWER_LOW).toByte(), // TX power
0x00, // Reserved
0x00 // Reserved
)
VERSION_1_1 -> byteArrayOf(
(version + currentDeviceInfo.confidence.toByte() * 4).toByte(), // Version and flags
(currentDeviceInfo.txPowerCorrection + TX_POWER_LOW).toByte(), // TX power
0x00, // Reserved
0x00 // Reserved
)
else -> return
}
var nextSend = nextKeyMillis.coerceAtLeast(10000)
val payload = ExposureDatabase.with(this@AdvertiserService) { database ->
database.generateCurrentPayload(aemBytes)
}
val data = AdvertiseData.Builder().addServiceUuid(SERVICE_UUID).addServiceData(SERVICE_UUID, payload).build()
val (uuid, _) = ByteBuffer.wrap(payload).let { UUID(it.long, it.long) to it.int }
Log.i(TAG, "Starting advertiser for RPI $uuid")
if (Build.VERSION.SDK_INT >= 26) {
setCallback = SetCallback()
val params = AdvertisingSetParameters.Builder()
.setInterval(AdvertisingSetParameters.INTERVAL_MEDIUM)
.setLegacyMode(true)
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_LOW)
.setConnectable(false)
.build()
advertiser.startAdvertisingSet(params, data, null, null, null, setCallback as AdvertisingSetCallback)
} else {
nextSend = nextSend.coerceAtMost(180000)
val settings = Builder()
.setTimeout(nextSend.toInt())
.setAdvertiseMode(ADVERTISE_MODE_BALANCED)
.setTxPowerLevel(ADVERTISE_TX_POWER_LOW)
.setConnectable(false)
.build()
advertiser.startAdvertising(settings, data, callback)
}
synchronized(this) { advertising = true }
sendingBytes = payload
lastStartTime = System.currentTimeMillis()
scheduleRestartAdvertising(nextSend)
} finally {
synchronized(this) { starting = false }
}
}
override fun dump(fd: FileDescriptor?, writer: PrintWriter?, args: Array<out String>?) {
writer?.println("Advertising: $advertising")
try {
val startTime = lastStartTime
val bytes = sendingBytes
val (uuid, aem) = ByteBuffer.wrap(bytes).let { UUID(it.long, it.long) to it.int }
writer?.println("""
Last advertising:
Since: ${Date(startTime)}
RPI: $uuid
Version: 0x${version.toString(16)}
TX Power: ${currentDeviceInfo.txPowerCorrection + TX_POWER_LOW}
AEM: 0x${aem.toLong().let { if (it < 0) 0x100000000L + it else it }.toString(16)}
""".trimIndent())
} catch (e: Exception) {
writer?.println("Last advertising: ${e.message ?: e.toString()}")
}
}
private fun scheduleRestartAdvertising(nextSend: Long) {
val intent = Intent(this, AdvertiserService::class.java).apply { action = ACTION_RESTART_ADVERTISING }
val pendingIntent = PendingIntent.getService(this, ACTION_RESTART_ADVERTISING.hashCode(), intent, FLAG_ONE_SHOT and FLAG_UPDATE_CURRENT)
when {
Build.VERSION.SDK_INT >= 23 ->
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + nextSend, pendingIntent)
else ->
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + nextSend, pendingIntent)
}
}
@Synchronized
private fun stopOrRestartAdvertising() {
if (!advertising) return
val (uuid, _) = ByteBuffer.wrap(sendingBytes).let { UUID(it.long, it.long) to it.int }
Log.i(TAG, "Stopping advertiser for RPI $uuid")
advertising = false
if (Build.VERSION.SDK_INT >= 26) {
wantStartAdvertising = true
advertiser?.stopAdvertisingSet(setCallback as AdvertisingSetCallback)
} else {
advertiser?.stopAdvertising(callback)
}
handler.postDelayed(startLaterRunnable, 1000)
}
@TargetApi(26)
inner class SetCallback : AdvertisingSetCallback() {
override fun onAdvertisingSetStarted(advertisingSet: AdvertisingSet?, txPower: Int, status: Int) {
Log.d(TAG, "Advertising active, status=$status")
}
override fun onAdvertisingSetStopped(advertisingSet: AdvertisingSet?) {
Log.d(TAG, "Advertising stopped")
if (wantStartAdvertising) {
startAdvertisingIfNeeded()
} else {
stopOrRestartAdvertising()
}
}
}
companion object {
private const val ACTION_RESTART_ADVERTISING = "org.microg.gms.nearby.exposurenotification.RESTART_ADVERTISING"
fun isNeeded(context: Context): Boolean {
return ExposurePreferences(context).enabled
}
}
}
| apache-2.0 | b2c76a63bfd7b84199c62f85b5ca9d50 | 40.017021 | 149 | 0.61884 | 4.920368 | false | false | false | false |
CodeIntelligenceTesting/jazzer | agent/src/main/java/com/code_intelligence/jazzer/instrumentor/DescriptorUtils.kt | 1 | 4294 | // Copyright 2021 Code Intelligence GmbH
//
// 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.code_intelligence.jazzer.instrumentor
import org.objectweb.asm.Type
import java.lang.reflect.Constructor
import java.lang.reflect.Executable
import java.lang.reflect.Method
val Class<*>.descriptor: String
get() = Type.getDescriptor(this)
val Executable.descriptor: String
get() = if (this is Method)
Type.getMethodDescriptor(this)
else
Type.getConstructorDescriptor(this as Constructor<*>?)
internal fun isPrimitiveType(typeDescriptor: String): Boolean {
return typeDescriptor in arrayOf("B", "C", "D", "F", "I", "J", "S", "V", "Z")
}
private fun isPrimitiveType(typeDescriptor: Char) = isPrimitiveType(typeDescriptor.toString())
internal fun getWrapperTypeDescriptor(typeDescriptor: String): String = when (typeDescriptor) {
"B" -> "Ljava/lang/Byte;"
"C" -> "Ljava/lang/Character;"
"D" -> "Ljava/lang/Double;"
"F" -> "Ljava/lang/Float;"
"I" -> "Ljava/lang/Integer;"
"J" -> "Ljava/lang/Long;"
"S" -> "Ljava/lang/Short;"
"V" -> "Ljava/lang/Void;"
"Z" -> "Ljava/lang/Boolean;"
else -> typeDescriptor
}
// Removes the 'L' and ';' prefix/suffix from signatures to get the full class name.
// Note that array signatures '[Ljava/lang/String;' already have the correct form.
internal fun extractInternalClassName(typeDescriptor: String): String {
return if (typeDescriptor.startsWith("L") && typeDescriptor.endsWith(";")) {
typeDescriptor.substring(1, typeDescriptor.length - 1)
} else {
typeDescriptor
}
}
internal fun extractParameterTypeDescriptors(methodDescriptor: String): List<String> {
require(methodDescriptor.startsWith('(')) { "Method descriptor must start with '('" }
val endOfParameterPart = methodDescriptor.indexOf(')') - 1
require(endOfParameterPart >= 0) { "Method descriptor must contain ')'" }
var remainingDescriptorList = methodDescriptor.substring(1..endOfParameterPart)
val parameterDescriptors = mutableListOf<String>()
while (remainingDescriptorList.isNotEmpty()) {
val nextDescriptor = extractNextTypeDescriptor(remainingDescriptorList)
parameterDescriptors.add(nextDescriptor)
remainingDescriptorList = remainingDescriptorList.removePrefix(nextDescriptor)
}
return parameterDescriptors
}
internal fun extractReturnTypeDescriptor(methodDescriptor: String): String {
require(methodDescriptor.startsWith('(')) { "Method descriptor must start with '('" }
val endBracketPos = methodDescriptor.indexOf(')')
require(endBracketPos >= 0) { "Method descriptor must contain ')'" }
val startOfReturnValue = endBracketPos + 1
return extractNextTypeDescriptor(methodDescriptor.substring(startOfReturnValue))
}
private fun extractNextTypeDescriptor(input: String): String {
require(input.isNotEmpty()) { "Type descriptor must not be empty" }
// Skip over arbitrarily many '[' to support multi-dimensional arrays.
val firstNonArrayPrefixCharPos = input.indexOfFirst { it != '[' }
require(firstNonArrayPrefixCharPos >= 0) { "Array descriptor must contain type" }
val firstTypeChar = input[firstNonArrayPrefixCharPos]
return when {
// Primitive type
isPrimitiveType(firstTypeChar) -> {
input.substring(0..firstNonArrayPrefixCharPos)
}
// Object type
firstTypeChar == 'L' -> {
val endOfClassNamePos = input.indexOf(';')
require(endOfClassNamePos > 0) { "Class type indicated by L must end with ;" }
input.substring(0..endOfClassNamePos)
}
// Invalid type
else -> {
throw IllegalArgumentException("Invalid type: $firstTypeChar")
}
}
}
| apache-2.0 | f165a1a48b4b098c52dc86827c3dce51 | 40.288462 | 95 | 0.702841 | 4.306921 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/manager/transaction/PaymentErrorTask.kt | 1 | 3155 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.manager.transaction
import com.toshi.R
import com.toshi.manager.model.PaymentTask
import com.toshi.model.local.Recipient
import com.toshi.model.local.User
import com.toshi.model.network.SofaError
import com.toshi.model.sofa.SofaAdapters
import com.toshi.model.sofa.SofaMessage
import com.toshi.util.LocaleUtil
import com.toshi.util.logging.LogUtil
import com.toshi.view.BaseApplication
import com.toshi.view.notification.ChatNotificationManager
import com.toshi.view.notification.ExternalPaymentNotificationManager
import retrofit2.HttpException
import java.io.IOException
class PaymentErrorTask {
fun handleOutgoingExternalPaymentError(error: Throwable, paymentTask: PaymentTask) {
LogUtil.exception("Error sending payment.", error)
val payment = paymentTask.payment
val paymentAddress = payment.toAddress
?.let { it }
?: BaseApplication.get().getString(R.string.unknown)
ExternalPaymentNotificationManager.showExternalPaymentFailed(paymentAddress)
}
fun handleOutgoingPaymentError(error: Throwable, receiver: User, storedSofaMessage: SofaMessage) {
val errorMessage = parseErrorResponse(error)
storedSofaMessage.errorMessage = errorMessage
LogUtil.exception("Error creating transaction $error")
showOutgoingPaymentFailedNotification(receiver)
}
private fun parseErrorResponse(error: Throwable): SofaError? {
return if (error is HttpException) parseErrorResponse(error)
else SofaError().createNotDeliveredMessage(BaseApplication.get())
}
private fun parseErrorResponse(error: HttpException): SofaError? {
return try {
val body = error.response().errorBody()?.string() ?: ""
SofaAdapters.get().sofaErrorsFrom(body)
} catch (e: IOException) {
LogUtil.w("Error while parsing payment error response $e")
null
}
}
private fun showOutgoingPaymentFailedNotification(user: User) {
val content = getNotificationContent(user.displayName)
ChatNotificationManager.showChatNotification(Recipient(user), content)
}
private fun getNotificationContent(content: String): String {
return String.format(
LocaleUtil.getLocale(),
BaseApplication.get().getString(R.string.payment_failed_message),
content
)
}
} | gpl-3.0 | 2b5b6d2d74162dd0e47f6358a578478e | 38.45 | 102 | 0.715055 | 4.5791 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientFlyingStateHandler.kt | 1 | 3931 | /*
* 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.network.vanilla.packet.handler.play
import org.lanternpowered.api.data.Keys
import org.lanternpowered.server.data.key.LanternKeys
import org.lanternpowered.server.entity.event.RefreshAbilitiesPlayerEvent
import org.lanternpowered.server.network.NetworkContext
import org.lanternpowered.server.network.packet.PacketHandler
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientFlyingStatePacket
import org.lanternpowered.server.network.vanilla.packet.type.play.EntityVelocityPacket
import org.spongepowered.api.util.Direction
object ClientFlyingStateHandler : PacketHandler<ClientFlyingStatePacket> {
override fun handle(ctx: NetworkContext, packet: ClientFlyingStatePacket) {
val flying = packet.isFlying
val player = ctx.session.player
if (!flying || player.get(Keys.CAN_FLY).orElse(false)) {
player.offer(Keys.IS_FLYING, flying)
} else {
// TODO: Just set velocity once it's implemented
if (player.get(LanternKeys.SUPER_STEVE).orElse(false)) {
ctx.session.send(EntityVelocityPacket(player.networkId, 0.0, 1.0, 0.0))
player.offer(Keys.IS_ELYTRA_FLYING, true)
} else if (player.get(LanternKeys.CAN_WALL_JUMP).orElse(false)) {
val location = player.location
// Get the horizontal direction the player is looking
val direction = player.getHorizontalDirection(Direction.Division.CARDINAL)
// Get the block location the player may step against
var stepLocation = location.add(direction.asOffset().mul(0.6, 0.0, 0.6))
var solidSide = stepLocation.get(direction.opposite, Keys.IS_SOLID).orElse(false)
// Make sure that the side you step against is solid
if (solidSide) {
// Push the player a bit back in the other direction,
// to give a more realistic feeling when pushing off
// against a wall
val pushBack = direction.asBlockOffset().toDouble().mul(-0.1)
// Push the player up
ctx.session.send(EntityVelocityPacket(player.networkId, pushBack.x, 0.8, pushBack.z))
} else {
// Now we try if the player can jump away from the wall
// Get the block location the player may step against
stepLocation = location.add(direction.asOffset().mul(-0.6, 0.0, -0.6))
solidSide = stepLocation.get(direction.opposite, Keys.IS_SOLID).orElse(false)
if (solidSide) {
// Combine the vectors in the direction of the block face
// and the direction the player is looking
val vector = direction.asBlockOffset().toDouble()
.mul(0.25)
.mul(1f, 0f, 1f)
.add(0.0, 0.65, 0.0)
.add(player.getDirectionVector().mul(0.4, 0.25, 0.4))
.mul(20.0, 20.0, 20.0) // Per second to per meter // TODO: Adjust previous values to remove this
// Push the player forward and up
ctx.session.send(EntityVelocityPacket(
player.networkId, vector.x, vector.y, vector.z))
}
}
}
player.triggerEvent(RefreshAbilitiesPlayerEvent.of())
}
}
}
| mit | dd90980aefb5cfc0a9215ddd8b5ebed3 | 50.723684 | 128 | 0.601374 | 4.446833 | false | false | false | false |
sabi0/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/cellReader/ExtendedCellReaders.kt | 1 | 4641 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.cellReader
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findAllWithBFS
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.components.JBList
import org.fest.swing.cell.JComboBoxCellReader
import org.fest.swing.cell.JListCellReader
import org.fest.swing.cell.JTableCellReader
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.driver.BasicJComboBoxCellReader
import org.fest.swing.driver.BasicJListCellReader
import org.fest.swing.driver.BasicJTableCellReader
import org.fest.swing.driver.BasicJTreeCellReader
import org.fest.swing.edt.GuiActionRunner
import org.fest.swing.edt.GuiQuery
import org.fest.swing.exception.ComponentLookupException
import java.awt.Component
import java.awt.Container
import java.lang.Error
import java.util.*
import javax.annotation.Nonnull
import javax.annotation.Nullable
import javax.swing.*
import javax.swing.tree.DefaultMutableTreeNode
/**
* @author Sergey Karashevich
*/
class ExtendedJTreeCellReader : BasicJTreeCellReader(), JTreeCellReader {
override fun valueAt(tree: JTree, modelValue: Any?): String? {
if (modelValue == null) return null
val isLeaf: Boolean = try { modelValue is DefaultMutableTreeNode && modelValue.isLeaf } catch (e: Error) { false }
val cellRendererComponent = tree.cellRenderer.getTreeCellRendererComponent(tree, modelValue, false, false, isLeaf, 0, false)
return getValueWithCellRenderer(cellRendererComponent)
}
}
class ExtendedJListCellReader : BasicJListCellReader(), JListCellReader {
@Nullable
override fun valueAt(@Nonnull list: JList<*>, index: Int): String? {
val element = list.model.getElementAt(index)
val cellRendererComponent = GuiTestUtil.getListCellRendererComponent(list, element, index)
return getValueWithCellRenderer(cellRendererComponent)
}
}
class ExtendedJTableCellReader : BasicJTableCellReader(), JTableCellReader {
override fun valueAt(table: JTable, row: Int, column: Int): String? {
val cellRendererComponent = table.prepareRenderer(table.getCellRenderer(row, column), row, column)
return super.valueAt(table, row, column) ?: getValueWithCellRenderer(cellRendererComponent)
}
}
class ExtendedJComboboxCellReader : BasicJComboBoxCellReader(), JComboBoxCellReader {
private val REFERENCE_JLIST = newJList()
override fun valueAt(comboBox: JComboBox<*>, index: Int): String? {
val item: Any? = comboBox.getItemAt(index)
val listCellRenderer: ListCellRenderer<Any?> = comboBox.renderer as ListCellRenderer<Any?>
val cellRendererComponent = listCellRenderer.getListCellRendererComponent(REFERENCE_JLIST, item, index, true, true)
return getValueWithCellRenderer(cellRendererComponent)
}
@Nonnull
private fun newJList(): JList<out Any?> {
return GuiActionRunner.execute(object : GuiQuery<JList<out Any?>>() {
override fun executeInEDT(): JList<out Any?> = JBList()
})!!
}
}
private fun getValueWithCellRenderer(cellRendererComponent: Component): String? {
val result = when (cellRendererComponent) {
is JLabel -> cellRendererComponent.text
is SimpleColoredComponent -> cellRendererComponent.getText()
else -> cellRendererComponent.findText()
}
return result?.trimEnd()
}
private fun SimpleColoredComponent.getText(): String?
= this.iterator().asSequence().joinToString()
private fun Component.findText(): String? {
try {
assert(this is Container)
val container = this as Container
val resultList = ArrayList<String>()
resultList.addAll(
findAllWithBFS(container, JLabel::class.java)
.filter { !it.text.isNullOrEmpty() }
.map { it.text }
)
resultList.addAll(
findAllWithBFS(container, SimpleColoredComponent::class.java)
.filter { !it.getText().isNullOrEmpty() }
.map { it.getText()!! }
)
return resultList.firstOrNull { !it.isEmpty() }
}
catch (ignored: ComponentLookupException) {
return null
}
}
| apache-2.0 | c2b78d92bdf88674868c3924254c2766 | 34.976744 | 128 | 0.761905 | 4.497093 | false | false | false | false |
dbrant/mandelbrot-android | app/src/main/java/com/dmitrybrant/android/mandelbrot/ColorScheme.kt | 1 | 2851 | package com.dmitrybrant.android.mandelbrot
import android.graphics.Color
object ColorScheme {
private var colorSchemes = mutableListOf<IntArray>()
fun initColorSchemes() {
colorSchemes = ArrayList()
colorSchemes.add(createColorScheme(intArrayOf(Color.BLUE, Color.GREEN, Color.RED, Color.BLUE), 256))
colorSchemes.add(createColorScheme(intArrayOf(Color.YELLOW, Color.MAGENTA, Color.BLUE, Color.GREEN, Color.YELLOW), 256))
colorSchemes.add(createColorScheme(intArrayOf(Color.WHITE, Color.BLACK, Color.WHITE), 256))
colorSchemes.add(createColorScheme(intArrayOf(Color.BLACK, Color.WHITE, Color.BLACK), 256))
colorSchemes.add(intArrayOf(Color.BLACK, Color.WHITE))
}
fun getColorSchemes(): List<IntArray> {
return colorSchemes
}
fun getShiftedScheme(colors: IntArray, shiftAmount: Int): IntArray {
val shifted = IntArray(colors.size)
for (i in colors.indices) {
shifted[i] = colors[(i + shiftAmount) % colors.size]
}
return shifted
}
private fun createColorScheme(colorArray: IntArray, numElements: Int): IntArray {
val elementsPerStep = numElements / (colorArray.size - 1)
val colors = IntArray(numElements)
var r = 0f
var g = 0f
var b = 0f
var rInc = 0f
var gInc = 0f
var bInc = 0f
var cIndex = 0
var cCounter = 0
for (i in 0 until numElements) {
if (cCounter == 0) {
b = (colorArray[cIndex] and 0xff.toFloat().toInt()).toFloat()
g = (colorArray[cIndex] and 0xff00 shr 8.toFloat().toInt()).toFloat()
r = (colorArray[cIndex] and 0xff0000 shr 16.toFloat().toInt()).toFloat()
if (cIndex < colorArray.size - 1) {
bInc = ((colorArray[cIndex + 1] and 0xff).toFloat() - b) / elementsPerStep.toFloat()
gInc = ((colorArray[cIndex + 1] and 0xff00 shr 8).toFloat() - g) / elementsPerStep.toFloat()
rInc = ((colorArray[cIndex + 1] and 0xff0000 shr 16).toFloat() - r) / elementsPerStep.toFloat()
}
cIndex++
cCounter = elementsPerStep
}
colors[i] = -0x1000000 or (b.toInt() shl 16) or (g.toInt() shl 8) or r.toInt()
b += bInc
g += gInc
r += rInc
if (b < 0f) {
b = 0f
}
if (g < 0f) {
g = 0f
}
if (r < 0f) {
r = 0f
}
if (b > 255f) {
b = 255f
}
if (g > 255f) {
g = 255f
}
if (r > 255f) {
r = 255f
}
cCounter--
}
return colors
}
} | gpl-2.0 | e152ca7a14c5309c0f692c1367a7b686 | 35.101266 | 128 | 0.528236 | 4.009845 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/remote/GivenAnItem/AndItDoesNotHaveChildItems/WhenGettingItems.kt | 1 | 4953 | package com.lasthopesoftware.bluewater.client.browsing.remote.GivenAnItem.AndItDoesNotHaveChildItems
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import com.lasthopesoftware.bluewater.client.browsing.items.Item
import com.lasthopesoftware.bluewater.client.browsing.items.access.ProvideItems
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.ProvideFiles
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.browsing.remote.GetMediaItemsFromServiceFiles
import com.lasthopesoftware.bluewater.client.browsing.remote.MediaItemsBrowser
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class `When Getting Items` {
companion object {
private val serviceFileIds by lazy { listOf(549, 140, 985, 411, 565, 513, 485, 621) }
private val expectedMediaItems by lazy {
serviceFileIds.indices.map { i ->
MediaMetadataCompat.Builder()
.apply {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "it:743:$i")
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "eat")
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "load")
putString(MediaMetadataCompat.METADATA_KEY_TITLE, "combine")
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 268)
putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, 240)
}
.build()
.let { metadata ->
MediaBrowserCompat.MediaItem(
metadata.description,
MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
)
}
}
}
private val mediaItems by lazy {
val selectedLibraryId = mockk<ProvideSelectedLibraryId>()
every { selectedLibraryId.selectedLibraryId } returns Promise(LibraryId(22))
val itemsProvider = mockk<ProvideItems>()
every { itemsProvider.promiseItems(LibraryId(22), 743) } returns Promise(emptyList())
val serviceFiles = mockk<GetMediaItemsFromServiceFiles>()
for (id in serviceFileIds) {
every { serviceFiles.promiseMediaItem(ServiceFile(id)) } returns Promise(
MediaMetadataCompat.Builder()
.apply {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "sf:$id")
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "eat")
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "load")
putString(MediaMetadataCompat.METADATA_KEY_TITLE, "combine")
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 268)
putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, 240)
}
.build()
.let { metadata ->
MediaBrowserCompat.MediaItem(
metadata.description,
MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
)
}
)
}
val provideFiles = mockk<ProvideFiles>()
every { provideFiles.promiseFiles(FileListParameters.Options.None, *FileListParameters.getInstance().getFileListParameters(Item(743))) } returns Promise(
serviceFileIds.map(::ServiceFile)
)
val mediaItemsBrowser = MediaItemsBrowser(
selectedLibraryId,
itemsProvider,
provideFiles,
mockk(),
serviceFiles,
)
mediaItemsBrowser
.promiseItems(Item(743))
.toFuture()
.get()
}
}
@Test
fun `then the media item ids are correct`() {
assertThat(mediaItems?.map { i -> i.mediaId }).isEqualTo(expectedMediaItems.map { i -> i.mediaId })
}
@Test
fun `then the media item titles are correct`() {
assertThat(mediaItems?.map { i -> i.description.title }).isEqualTo(expectedMediaItems.map { i -> i.description.title })
}
@Test
fun `then the media item subtitles are correct`() {
assertThat(mediaItems?.map { i -> i.description.subtitle }).isEqualTo(expectedMediaItems.map { i -> i.description.subtitle })
}
@Test
fun `then the media item extras are correct`() {
assertThat(mediaItems?.map { i -> i.description.extras }).isEqualTo(expectedMediaItems.map { i -> i.description.extras })
}
@Test
fun `then the media item descriptions are correct`() {
assertThat(mediaItems?.map { i -> i.description.description }).isEqualTo(expectedMediaItems.map { i -> i.description.description })
}
@Test
fun `then the media items are not browsable`() {
assertThat(mediaItems!!).allMatch { i -> !i.isBrowsable }
}
@Test
fun `then the media items are playable`() {
assertThat(mediaItems!!).allMatch { i -> i.isPlayable }
}
}
| lgpl-3.0 | e65bdbfe05ee4ca427a962e0e871082b | 36.240602 | 156 | 0.749243 | 4.013776 | false | true | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/rest/RestConfig.kt | 1 | 3682 | /*
* 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
import org.jitsi.config.JitsiConfig
import org.jitsi.metaconfig.config
import org.jitsi.videobridge.Videobridge
class RestConfig {
private val colibriRestEnabled: Boolean by config {
// If the value was passed via a command line arg, we set it as a system
// variable at this path, which the new config will pick up
Videobridge.REST_API_PNAME.from(JitsiConfig.newConfig)
"videobridge.apis.rest.enabled".from(JitsiConfig.newConfig)
}
private val legacyColibriRestEnabled: Boolean by config {
"org.jitsi.videobridge.ENABLE_REST_COLIBRI".from(JitsiConfig.legacyConfig)
"default" { true }
}
/**
* Due to historical reasons the COLIBRI REST API is controlled in multiple ways. There is:
* 1. A command line argument (--apis=rest)
* 2. A new config property (videobridge.apis.rest.enabled)
* 3. A legacy config property ENABLE_REST_COLIBRI
*
* The last one defaults to `true` so it is simply an old way to force the API to be disabled. It is implemented
* in [legacyColibriRestEnabled]. The first two are implemented in [colibriRestEnabled], and this property
* implements the combined logic.
*/
private val colibriEnabled
get() = colibriRestEnabled && legacyColibriRestEnabled
/**
* The debug API (query conference state, enable/disable debug features). It currently defaults to being enabled,
* but that might change in the future.
*/
private val debugEnabled: Boolean by config {
"videobridge.rest.debug.enabled".from(JitsiConfig.newConfig)
}
/**
* The health-check API.
*/
private val healthEnabled: Boolean by config {
"videobridge.rest.health.enabled".from(JitsiConfig.newConfig)
}
/**
* The property which enables/disables the graceful shutdown API.
*/
private val shutdownEnabledProperty: Boolean by config {
"org.jitsi.videobridge.ENABLE_REST_SHUTDOWN".from(JitsiConfig.legacyConfig)
"videobridge.rest.shutdown.enabled".from(JitsiConfig.newConfig)
}
/**
* Due to historical reasons the shutdown API is only enabled when the COLIBRI API is enabled.
*/
private val shutdownEnabled
get() = colibriEnabled && shutdownEnabledProperty
private val versionEnabled: Boolean by config {
"videobridge.rest.version.enabled".from(JitsiConfig.newConfig)
}
/**
* Whether any of the REST APIs are enabled by the configuration. If there aren't, the HTTP server doesn't need to
* be started at all.
*/
fun isEnabled() = colibriEnabled || debugEnabled || healthEnabled || shutdownEnabled || versionEnabled
fun isEnabled(api: RestApis) = when (api) {
RestApis.COLIBRI -> colibriEnabled
RestApis.DEBUG -> debugEnabled
RestApis.HEALTH -> healthEnabled
RestApis.SHUTDOWN -> shutdownEnabled
RestApis.VERSION -> versionEnabled
}
companion object {
@JvmField
val config = RestConfig()
}
}
| apache-2.0 | f6ad0d57f4420a7c6d39a5a2323029b9 | 36.571429 | 118 | 0.693916 | 4.468447 | false | true | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/strategy/DefaultStrategies.kt | 1 | 16114 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.strategy
import kotlinx.coroutines.delay
import org.droidmate.deviceInterface.exploration.ActionType
import org.droidmate.deviceInterface.exploration.ExplorationAction
import org.droidmate.deviceInterface.exploration.GlobalAction
import org.droidmate.deviceInterface.exploration.LaunchApp
import org.droidmate.deviceInterface.exploration.isQueueEnd
import org.droidmate.exploration.ExplorationContext
import org.droidmate.exploration.actions.click
import org.droidmate.exploration.actions.closeAndReturn
import org.droidmate.exploration.actions.launchApp
import org.droidmate.exploration.actions.pressBack
import org.droidmate.exploration.actions.resetApp
import org.droidmate.exploration.actions.terminateApp
import org.droidmate.exploration.strategy.manual.Logging
import org.droidmate.exploration.strategy.manual.getLogger
import org.droidmate.explorationModel.factory.AbstractModel
import org.droidmate.explorationModel.interaction.State
import org.droidmate.explorationModel.interaction.Widget
import java.util.HashMap
import java.util.Random
import java.util.UUID
@Suppress("unused")
object DefaultStrategies : Logging {
override val log = getLogger()
/**
* Terminate the exploration after a predefined elapsed time
*/
fun timeBasedTerminate(priority: Int, maxSeconds: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "timeBasedTerminate"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean {
val diff = eContext.getExplorationTimeInMs()
log.info("remaining exploration time: ${"%.1f".format((maxSeconds - diff) / 1000.0)}s")
return maxSeconds in 1..diff
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
return ExplorationAction.terminateApp()
}
}
/**
* Terminate the exploration after a predefined number of actions
*/
fun actionBasedTerminate(priority: Int, maxActions: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "actionBasedTerminate"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
eContext.explorationTrace.size >= maxActions
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
log.debug("Maximum number of actions reached. Terminate")
return ExplorationAction.terminateApp()
}
}
/**
* Restarts the exploration when the current state is an "app not responding" dialog
*/
fun resetOnAppCrash(priority: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "resetOnAppCrash"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
eContext.getCurrentState().isAppHasStoppedDialogBox
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
log.debug("Current screen is 'App has stopped'. Reset")
return eContext.resetApp()
}
}
/**
* Resets the exploration once a predetermined number of non-reset actions has been executed
*/
fun intervalReset(priority: Int, interval: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "intervalReset"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean {
val lastReset = eContext.explorationTrace.P_getActions()
.indexOfLast { it.actionType == LaunchApp.name }
val currAction = eContext.explorationTrace.size
val diff = currAction - lastReset
return diff > interval
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
return eContext.resetApp()
}
}
/**
* Randomly presses back.
*
* Expected bundle: [Probability (Double), java.util.Random].
*
* Passing a different bundle will crash the execution.
*/
fun randomBack(priority: Int, probability: Double, rnd: Random) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "randomBack"
override fun getPriority() = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean {
val value = rnd.nextDouble()
val lastLaunchDistance = with(eContext.explorationTrace.getActions()) {
size - lastIndexOf(findLast { !it.actionType.isQueueEnd() })
}
return (lastLaunchDistance > 3 && value > probability)
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
log.debug("Has triggered back probability and previous action was not to press back. Returning 'Back'")
return ExplorationAction.closeAndReturn()
}
}
private operator fun GlobalAction.times(multiplier: Int) =
(0..multiplier)
.map { GlobalAction(this.actionType) }
.toTypedArray()
/**
* Check the current state for interactive UI elements to interact with,
* if none are available we try to
* 1. close keyboard & press back
* (per default keyboard items would be interactive but the user may use a custom model where this is not the case)
* 2. reset the app (if the last action already was a press-back)
* 3. if there was a reset within the last 3 actions or the last action was a Fetch
* - we try to wait for up to ${maxWaittime}s (default 5s) if any interactive element appears
* - if the app has crashed we terminate
*/
fun handleTargetAbsence(priority: Int, maxWaitTime: Long = 1000, numFetches: Int = 10) = object : AExplorationStrategy() {
private lateinit var launchInstruction: ExplorationAction
override fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> initialize(initialContext: ExplorationContext<M, S, W>) {
super.initialize(initialContext)
launchInstruction = initialContext.launchApp()
}
val defaultAbsenceBehavior: List<ExplorationAction> by lazy {
listOf(
*(GlobalAction(ActionType.FetchGUI) * numFetches),
ExplorationAction.pressBack(),
*(GlobalAction(ActionType.FetchGUI) * numFetches),
launchInstruction,
*(GlobalAction(ActionType.FetchGUI) * numFetches)
)
}
private var pendingActions: MutableList<ExplorationAction> = mutableListOf()
// may be used to terminate if there are no targets after waiting for maxWaitTime
private var terminate = false
override val uniqueStrategyName: String = "handleTargetAbsence"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean {
val canExplore = eContext.explorationCanMoveOn()
// reset the counter if we can proceed
if (canExplore) {
// if can continue, reset list of actions
pendingActions = defaultAbsenceBehavior.toMutableList()
}
return !canExplore
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
return if (eContext.getCurrentState().isHomeScreen && pendingActions.size == defaultAbsenceBehavior.size) {
// if we ended in the homeScreen speedup the process by directly resetting the app
pendingActions.removeAt(0)
eContext.resetApp()
} else if (pendingActions.isNotEmpty()) {
// has action to execute
log.debug("Cannot explore. Following predefined action queue. Remaining actions: ${pendingActions.size}")
val nextAction = pendingActions.removeAt(0)
if (nextAction.isFetch()) {
delay(maxWaitTime)
}
nextAction
} else {
// has no other action. if the app crashed, terminate, otherwise reset
val currState = eContext.getCurrentState()
if (currState.isAppHasStoppedDialogBox) {
log.debug("Cannot explore. Already tried to reset. Currently on an 'App has stopped' dialog. Returning 'Terminate'")
ExplorationAction.terminateApp()
} else {
log.debug("Cannot explore. Out of options. Try restarting the app again")
eContext.resetApp()
}
}
}
}
/**
* Always clicks allow/ok for any runtime permission request
*/
fun allowPermission(priority: Int, maxTries: Int = 5) = object : AExplorationStrategy() {
private var numPermissions =
HashMap<UUID, Int>() // avoid some options which are misinterpreted as permission request to be infinitely triggered
override val uniqueStrategyName: String = "allowPermission"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
numPermissions.compute(eContext.getCurrentState().uid) { _, v -> v?.inc() ?: 0 } ?: 0 < maxTries
&& eContext.getCurrentState().isRequestRuntimePermissionDialogBox
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
// we do not require the element with the text ALLOW or OK to be clickabe since there may be overlaying elements
// which handle the touch event for this button, however as a consequence we may click non-interactive labels
// that is why we restricted this strategy to be executed at most [maxTries] from the same state
val allowButton: Widget = eContext.getCurrentState().widgets.filter { it.isVisible }.let { widgets ->
widgets.firstOrNull { it.resourceId == "com.android.packageinstaller:id/permission_allow_button" }
?: widgets.firstOrNull { it.resourceId == "com.android.permissioncontroller:id/permission_allow_always_button" }
?: widgets.firstOrNull { it.text.toUpperCase() == "ALLOW" }
?: widgets.firstOrNull { it.text.toUpperCase() == "ALLOW ALL THE TIME" }
?: widgets.firstOrNull { it.text.toUpperCase() == "OK" }
?: widgets.first{ it.text.toUpperCase() == "CONTINUE" }
}
return allowButton.click(ignoreClickable = true)
}
}
fun denyPermission(priority: Int) = object : AExplorationStrategy() {
var denyButton: Widget? = null
override val uniqueStrategyName: String = "denyPermission"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean {
denyButton = eContext.getCurrentState().widgets.let { widgets ->
widgets.find { it.resourceId == "com.android.packageinstaller:id/permission_deny_button" }
?: widgets.find { it.resourceId == "com.android.permissioncontroller:id/permission_deny_button" }
?: widgets.find { it.text.toUpperCase() == "DENY" }
}
return denyButton != null
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction =
denyButton?.click(ignoreClickable = true)
?: throw IllegalStateException("Error In denyPermission strategy, strategy was executed but hasNext should be false")
}
/**
* Finishes the exploration once all widgets have been explored
* FIXME this strategy is insanely inefficient right now and should be avoided
*/
fun explorationExhausted(priority: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "explorationExhausted"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
eContext.explorationTrace.size > 2 && eContext.areAllWidgetsExplored()
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction =
ExplorationAction.terminateApp()
}
/** press back if advertisement is detected */
fun handleAdvertisement(priority: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "handleAdvertisement"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
eContext.getCurrentState().widgets.any { it.packageName == "com.android.vending" }
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction =
ExplorationAction.pressBack()
}
/** press back if the app is in google chrome */
fun handleChrome(priority: Int) = object : AExplorationStrategy() {
override val uniqueStrategyName: String = "handleChrome"
override fun getPriority(): Int = priority
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> hasNext(eContext: ExplorationContext<M, S, W>): Boolean =
eContext.getCurrentState().widgets.any { it.packageName == "com.android.chrome" }
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> nextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction =
ExplorationAction.pressBack()
}
} | gpl-3.0 | c02f39a12198eb43586bbfc1951bbb8b | 47.393393 | 151 | 0.661102 | 4.62913 | false | false | false | false |
arturbosch/detekt | detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/PropertiesAwareSpec.kt | 1 | 2190 | package io.gitlab.arturbosch.detekt.api
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatCode
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.random.Random
@OptIn(UnstableApi::class)
class PropertiesAwareSpec : Spek({
describe("PropertiesAware") {
context("Implementations can store and retrieve properties") {
val hash by memoized { Random(1).nextInt() }
val store by memoized {
object : PropertiesAware {
override val properties: MutableMap<String, Any> = HashMap()
override fun register(key: String, value: Any) {
properties[key] = value
}
}.apply {
register("bool", true)
register("string", "test")
register("number", 5)
register("set", setOf(1, 2, 3))
register(
"any",
object : Any() {
override fun equals(other: Any?): Boolean = hashCode() == other.hashCode()
override fun hashCode(): Int = hash
}
)
}
}
it("can retrieve the actual typed values") {
assertThat(store.getOrNull<Boolean>("bool")).isEqualTo(true)
assertThat(store.getOrNull<String>("string")).isEqualTo("test")
assertThat(store.getOrNull<Int>("number")).isEqualTo(5)
assertThat(store.getOrNull<Set<Int>>("set")).isEqualTo(setOf(1, 2, 3))
assertThat(store.getOrNull<Any>("any").hashCode()).isEqualTo(hash)
}
it("returns null on absent values") {
assertThat(store.getOrNull<Boolean>("absent")).isEqualTo(null)
}
it("throws an error on wrong type") {
assertThatCode { store.getOrNull<Double>("bool") }
.isInstanceOf(IllegalStateException::class.java)
}
}
}
})
| apache-2.0 | 355938a1139c9aa348435814fc24bece | 38.107143 | 102 | 0.527397 | 5.214286 | false | false | false | false |
Light-Team/ModPE-IDE-Source | data/src/main/kotlin/com/brackeys/ui/data/storage/database/entity/theme/ThemeEntity.kt | 1 | 3098 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.data.storage.database.entity.theme
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.brackeys.ui.data.storage.database.utils.Tables
@Entity(tableName = Tables.THEMES)
data class ThemeEntity(
@PrimaryKey
@ColumnInfo(name = "uuid")
val uuid: String,
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "author")
val author: String,
@ColumnInfo(name = "description")
val description: String,
@ColumnInfo(name = "text_color")
val textColor: String,
@ColumnInfo(name = "background_color")
val backgroundColor: String,
@ColumnInfo(name = "gutter_color")
val gutterColor: String,
@ColumnInfo(name = "gutter_divider_color")
val gutterDividerColor: String,
@ColumnInfo(name = "gutter_current_line_number_color")
val gutterCurrentLineNumberColor: String,
@ColumnInfo(name = "gutter_text_color")
val gutterTextColor: String,
@ColumnInfo(name = "selected_line_color")
val selectedLineColor: String,
@ColumnInfo(name = "selection_color")
val selectionColor: String,
@ColumnInfo(name = "suggestion_query_color")
val suggestionQueryColor: String,
@ColumnInfo(name = "find_result_background_color")
val findResultBackgroundColor: String,
@ColumnInfo(name = "delimiter_background_color")
val delimiterBackgroundColor: String,
@ColumnInfo(name = "number_color")
val numberColor: String,
@ColumnInfo(name = "operator_color")
val operatorColor: String,
@ColumnInfo(name = "keyword_color")
val keywordColor: String,
@ColumnInfo(name = "type_color")
val typeColor: String,
@ColumnInfo(name = "lang_const_color")
val langConstColor: String,
@ColumnInfo(name = "preprocessor_color")
val preprocessorColor: String,
@ColumnInfo(name = "variable_color")
val variableColor: String,
@ColumnInfo(name = "method_color")
val methodColor: String,
@ColumnInfo(name = "string_color")
val stringColor: String,
@ColumnInfo(name = "comment_color")
val commentColor: String,
@ColumnInfo(name = "tag_color")
val tagColor: String,
@ColumnInfo(name = "tag_name_color")
val tagNameColor: String,
@ColumnInfo(name = "attr_name_color")
val attrNameColor: String,
@ColumnInfo(name = "attr_value_color")
val attrValueColor: String,
@ColumnInfo(name = "entity_ref_color")
val entityRefColor: String
) | apache-2.0 | 081fe33bfde4548e629c55c3cb40d703 | 34.62069 | 75 | 0.706262 | 4.007762 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLInputBuildSearchForm.kt | 1 | 1702 | package net.nemerosa.ontrack.graphql.schema
import graphql.schema.GraphQLInputObjectType
import graphql.schema.GraphQLInputType
import graphql.schema.GraphQLType
import graphql.schema.GraphQLTypeReference
import net.nemerosa.ontrack.graphql.support.getDescription
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.model.structure.BuildSearchForm
import org.springframework.stereotype.Component
@Component
class GQLInputBuildSearchForm : GQLInputType<BuildSearchForm> {
private val typeName: String = BuildSearchForm::class.java.simpleName
override fun getTypeRef(): GraphQLTypeReference = GraphQLTypeReference(typeName)
override fun createInputType(dictionary: MutableSet<GraphQLType>): GraphQLInputType = GraphQLInputObjectType.newInputObject()
.name(typeName)
.description(getDescription(BuildSearchForm::class))
.field(intInputField(BuildSearchForm::maximumCount, nullable = true))
.field(stringInputField(BuildSearchForm::branchName))
.field(stringInputField(BuildSearchForm::buildName))
.field(stringInputField(BuildSearchForm::promotionName))
.field(stringInputField(BuildSearchForm::validationStampName))
.field(stringInputField(BuildSearchForm::property))
.field(stringInputField(BuildSearchForm::propertyValue))
.field(booleanInputField(BuildSearchForm::buildExactMatch, nullable = true))
.field(stringInputField(BuildSearchForm::linkedFrom))
.field(stringInputField(BuildSearchForm::linkedTo))
.build()
override fun convert(argument: Any?): BuildSearchForm = argument?.asJson()?.parse() ?: BuildSearchForm()
} | mit | 96daa8c6680760d2162d472dd59cedc5 | 46.305556 | 129 | 0.785546 | 4.904899 | false | false | false | false |
aglne/mycollab | mycollab-services/src/main/java/com/mycollab/module/user/domain/criteria/UserSearchCriteria.kt | 3 | 1728 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.user.domain.criteria
import com.mycollab.core.utils.DateTimeUtils
import com.mycollab.db.arguments.*
import java.time.LocalDateTime
import java.util.Date
import java.util.Locale
/**
* @author MyCollab Ltd.
* @since 1.0
*/
class UserSearchCriteria : SearchCriteria() {
var displayName: StringSearchField? = null
var username: StringSearchField? = null
var registerStatuses: SetSearchField<String>? = null
var subDomain: StringSearchField? = null
var statuses: SetSearchField<String>? = null
// @NOTE: Only works with method find... not getTotalCount(...)
fun setLastAccessTimeRange(from: LocalDateTime, to: LocalDateTime) {
val expr = "s_user_account.lastAccessedTime >= '${DateTimeUtils.formatDate(from, "yyyy-MM-dd", Locale.US)}' AND s_user_account.lastAccessedTime <='${DateTimeUtils.formatDate(to, "yyyy-MM-dd", Locale.US)}'"
val searchField = NoValueSearchField(SearchField.AND, expr)
this.addExtraField(searchField)
}
}
| agpl-3.0 | 419549b4276438ec9db1f834543b8b0d | 39.162791 | 213 | 0.733063 | 4.111905 | false | false | false | false |
SeunAdelekan/Kanary | src/main/com/iyanuadelekan/kanary/app/handler/RouterHandler.kt | 1 | 1743 | package com.iyanuadelekan.kanary.app.handler
import com.iyanuadelekan.kanary.app.constant.RouteType
import com.iyanuadelekan.kanary.app.framework.consumer.RouterConsumer
import com.iyanuadelekan.kanary.app.framework.router.Router
import com.iyanuadelekan.kanary.app.router.RouteNode
/**
* @author Iyanu Adelekan on 16/08/2018.
*
* Delegate class for the handling of router consumption within
* the framework.
*/
internal class RouterHandler : RouterConsumer {
private val routers: ArrayList<Router> = ArrayList()
private val iterator: Iterator<Router> = routers.iterator()
/**
* Mounts a variable number of routers to [routers].
*
* @param routers - routers to be mounted.
*/
override fun use(vararg routers: Router) {
this.routers.addAll(routers.asList())
}
/**
* Returns the `next` router.
*
* @return [Router] - `next` router.
*/
override fun next(): Router = iterator.next()
/**
* Checks if a next router exists in [routers]
*
* @return [Boolean] - true if `next` router exists and false otherwise.
*/
override fun hasNext(): Boolean = iterator.hasNext()
/**
* Invoked to resolve a route into its corresponding route node - if any.
*
* @param path - Target path.
* @return [Pair] - Returns corresponding Router-RouteNode [Pair] if one exists. null is returned otherwise
*/
override fun resolveRoute(path: String, method: RouteType): Pair<Router, RouteNode>? {
routers.forEach {
val routeNode = it.routeManager.getRouteNode(path, method)
if (routeNode != null) {
return Pair(it, routeNode)
}
}
return null
}
} | apache-2.0 | 37543450f7926bd7247760ff8851c081 | 29.068966 | 111 | 0.650602 | 4.230583 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddTurbofishFix.kt | 1 | 3781 | package org.rust.ide.annotator.fixes
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileFactory
import org.rust.ide.intentions.RsElementBaseIntentionAction
import org.rust.lang.core.psi.*
import org.rust.lang.RsFileType
import org.rust.lang.core.psi.ext.*
class AddTurbofishFix : RsElementBaseIntentionAction<AddTurbofishFix.Context>() {
private val TURBOFISH = "::"
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (matchExpr, insertion) = ctx
val expression = matchExpr.text
val left = expression.substring(0, insertion)
val right = expression.substring(insertion)
val fixed = create<RsExpr>(project, """$left$TURBOFISH$right""") ?: return
matchExpr.replace(fixed)
}
data class Context(
val matchExpr: RsBinaryExpr,
val offset: Int
)
override fun getText() = "Add turbofish operator"
override fun getFamilyName() = text
private fun resolveMatchExpression(element: PsiElement): RsBinaryExpr? {
val base = element.parentOfType<RsBinaryExpr>() ?: return null
if (base.left !is RsBinaryExpr) {
return resolveMatchExpression(base) ?: base
}
val left = base.left as RsBinaryExpr
if (left.operatorType == ArithmeticOp.SHR) {
return resolveMatchExpression(base) ?: base
}
return base
}
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val m = resolveMatchExpression(element) ?: return null
return guessContext(project, m)
}
private fun innerOffset(root: PsiElement, child: PsiElement): Int? {
if (child == root) {
return 0
}
val parent = child.parent ?: return null
val upper = innerOffset(root, parent) ?: return null
return upper + child.startOffsetInParent
}
private fun guessContext(project: Project, binary: RsBinaryExpr): Context? {
val nodes = bfsLeafs(binary)
val called = rightBoundary(nodes) ?: return null
val typeListEndIndex = binary.textLength - called.textLength
val turbofish_offset = nodes.takeWhile { it != called }.map {
val offset = innerOffset(binary, it)!! + it.textLength
val typeListCandidate = binary.text.substring(offset, typeListEndIndex)
if (isTypeArgumentList(project, typeListCandidate)) {
offset
} else {
null
}
}.filterNotNull().firstOrNull() ?: return null
return Context(binary, turbofish_offset)
}
private fun rightBoundary(nodes: List<RsExpr>) = nodes.asReversed().firstOrNull { isCallExpression(it) }
private fun isTypeArgumentList(project: Project, candidate: String) =
create<RsCallExpr>(project, "something$TURBOFISH$candidate()") != null
private fun bfsLeafs(expr: RsExpr?): List<RsExpr> {
return when (expr) {
is RsBinaryExpr -> {
bfsLeafs(expr.left) + bfsLeafs(expr.right)
}
null -> listOf<RsExpr>()
else -> listOf(expr)
}
}
private fun isCallExpression(expr: RsExpr) = expr is RsParenExpr || expr.firstChild is RsParenExpr
private inline fun <reified T : RsCompositeElement> create(project: Project, text: String): T? =
createFromText(project, "fn main() { $text; }")
private inline fun <reified T : RsCompositeElement> createFromText(project: Project, code: String): T? =
PsiFileFactory.getInstance(project)
.createFileFromText("DUMMY.rs", RsFileType, code)
.childOfType<T>()
}
| mit | 798400c900fbb8b5ae406549af4a4711 | 37.191919 | 108 | 0.653002 | 4.495838 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/action/GenerateShadowAction.kt | 1 | 9694 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.findFields
import com.demonwav.mcdev.platform.mixin.util.findMethods
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceField
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceMethod
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.findFirstMember
import com.demonwav.mcdev.util.findLastChild
import com.demonwav.mcdev.util.findNextMember
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.realName
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.GenerationInfo
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.OverrideImplementsAnnotationsHandler
import com.intellij.codeInsight.generation.PsiElementClassMember
import com.intellij.codeInsight.generation.PsiFieldMember
import com.intellij.codeInsight.generation.PsiGenerationInfo
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierList
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
class GenerateShadowAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val fields = findFields(psiClass)?.map { (classNode, fieldNode) ->
fieldNode.findOrConstructSourceField(
classNode,
project,
canDecompile = false
).let(::PsiFieldMember)
} ?: emptySequence()
val methods = findMethods(psiClass, allowClinit = false)?.map { (classNode, fieldNode) ->
fieldNode.findOrConstructSourceMethod(
classNode,
project,
canDecompile = false
).let(::PsiMethodMember)
} ?: emptySequence()
val members = (fields + methods).toTypedArray()
if (members.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No members to shadow have been found")
return
}
val chooser = MemberChooser<PsiElementClassMember<*>>(members, false, true, project)
chooser.title = "Select Members to Shadow"
chooser.setCopyJavadocVisible(false)
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
disableAnnotationWrapping(project) {
runWriteAction {
GenerateMembersUtil.insertMembersAtOffset(
file,
offset,
createShadowMembers(
project,
psiClass,
elements.asSequence().map(PsiElementClassMember<*>::getElement)
)
// Select first element in editor
).firstOrNull()?.positionCaret(editor, false)
}
}
}
}
fun insertShadows(project: Project, psiClass: PsiClass, members: Sequence<PsiMember>) {
insertShadows(psiClass, createShadowMembers(project, psiClass, members))
}
fun insertShadows(psiClass: PsiClass, shadows: List<GenerationInfo>) {
// Find first element after shadow
val lastShadow = psiClass.findLastChild {
(it as? PsiModifierListOwner)?.modifierList?.findAnnotation(MixinConstants.Annotations.SHADOW) != null
}
val anchor = lastShadow?.findNextMember() ?: psiClass.findFirstMember()
// Insert new shadows after last shadow (or at the top of the class)
GenerateMembersUtil.insertMembersBeforeAnchor(psiClass, anchor, shadows)
}
fun createShadowMembers(
project: Project,
psiClass: PsiClass,
members: Sequence<PsiMember>
): List<PsiGenerationInfo<PsiMember>> {
var methodAdded = false
val result = members.map { m ->
val shadowMember: PsiMember = when (m) {
is PsiMethod -> {
methodAdded = true
shadowMethod(psiClass, m)
}
is PsiField -> shadowField(project, m)
else -> throw UnsupportedOperationException("Unsupported member type: ${m::class.java.name}")
}
// Add @Shadow annotation
val annotation = shadowMember.modifierList!!.addAnnotation(MixinConstants.Annotations.SHADOW)
val realName = m.realName
if (realName != null && realName != m.name) {
val elementFactory = JavaPsiFacade.getElementFactory(project)
val value = elementFactory.createExpressionFromText(
"\"${StringUtil.escapeStringCharacters(realName)}\"",
annotation
)
annotation.setDeclaredAttributeValue("aliases", value)
}
PsiGenerationInfo(shadowMember)
}.toList()
// Make the class abstract (if not already)
if (methodAdded && !psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
val classModifiers = psiClass.modifierList!!
if (classModifiers.hasModifierProperty(PsiModifier.FINAL)) {
classModifiers.setModifierProperty(PsiModifier.FINAL, false)
}
classModifiers.setModifierProperty(PsiModifier.ABSTRACT, true)
}
return result
}
private fun shadowMethod(psiClass: PsiClass, method: PsiMethod): PsiMethod {
val newMethod = GenerateMembersUtil.substituteGenericMethod(method, PsiSubstitutor.EMPTY, psiClass)
// Remove Javadocs
OverrideImplementUtil.deleteDocComment(newMethod)
val newModifiers = newMethod.modifierList
// Relevant modifiers are copied by GenerateMembersUtil.substituteGenericMethod
// Copy annotations
copyAnnotations(psiClass.containingFile, method.modifierList, newModifiers)
// If the method was original private, make it protected now
if (newModifiers.hasModifierProperty(PsiModifier.PRIVATE)) {
newModifiers.setModifierProperty(PsiModifier.PROTECTED, true)
}
// Make method abstract
newModifiers.setModifierProperty(PsiModifier.ABSTRACT, true)
// Remove code block
newMethod.body?.delete()
return newMethod
}
private fun shadowField(project: Project, field: PsiField): PsiField {
val newField = JavaPsiFacade.getElementFactory(project).createField(field.name, field.type)
val newModifiers = newField.modifierList!!
val modifiers = field.modifierList!!
// Copy modifiers
copyModifiers(modifiers, newModifiers)
// Copy annotations
copyAnnotations(field.containingFile, modifiers, newModifiers)
if (newModifiers.hasModifierProperty(PsiModifier.FINAL)) {
// If original field was final, add the @Final annotation instead
newModifiers.setModifierProperty(PsiModifier.FINAL, false)
newModifiers.addAnnotation(MixinConstants.Annotations.FINAL)
}
return newField
}
private fun copyModifiers(modifiers: PsiModifierList, newModifiers: PsiModifierList) {
for (modifier in PsiModifier.MODIFIERS) {
if (modifiers.hasExplicitModifier(modifier)) {
newModifiers.setModifierProperty(modifier, true)
}
}
}
private fun copyAnnotations(file: PsiFile, modifiers: PsiModifierList, newModifiers: PsiModifierList) {
// Copy annotations registered by extensions (e.g. @Nullable), based on OverrideImplementUtil.annotateOnOverrideImplement
for (ext in OverrideImplementsAnnotationsHandler.EP_NAME.extensionList) {
for (annotation in ext.getAnnotations(file)) {
copyAnnotation(modifiers, newModifiers, annotation)
}
}
// Copy @Deprecated annotation
copyAnnotation(modifiers, newModifiers, CommonClassNames.JAVA_LANG_DEPRECATED)
}
private fun copyAnnotation(modifiers: PsiModifierList, newModifiers: PsiModifierList, annotation: String) {
// Check if annotation exists
val psiAnnotation = modifiers.findAnnotation(annotation) ?: return
// Have we already added this annotation? If not, copy it
newModifiers.findAnnotation(annotation) ?: newModifiers.addAfter(psiAnnotation, null)
}
inline fun disableAnnotationWrapping(project: Project, func: () -> Unit) {
val settings = CodeStyle.getSettings(project).getCommonSettings(JavaLanguage.INSTANCE)
val methodWrap = settings.METHOD_ANNOTATION_WRAP
val fieldWrap = settings.FIELD_ANNOTATION_WRAP
settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
settings.FIELD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
try {
func()
} finally {
settings.METHOD_ANNOTATION_WRAP = methodWrap
settings.FIELD_ANNOTATION_WRAP = fieldWrap
}
}
| mit | 827a2aff041ab4ef97df6012587399b7 | 37.468254 | 125 | 0.718692 | 4.903389 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/util/TinyUUID.kt | 1 | 8342 | /*
* Copyright (c) 2017-2020 by Oliver Boehm
*
* 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.
*
* (c)reated 11.12.2017 by oboehm ([email protected])
*/
package de.jfachwert.util
import de.jfachwert.AbstractFachwert
import de.jfachwert.pruefung.exception.InvalidValueException
import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.util.*
/**
* Die Klasse TinyUUID ist ein einfacher Wrapper um UUID mit dem Ziel, eine
* kuerzere Praesentation als das Original zur Verfuegung zu stellen. Die
* Original-UUID hat eine Laenge von 35 Zeichen, belegt aber intern nur
* 128 Bits oder 16 Bytes. Damit laeest sich der Speicheraufwand um ueber 50%
* reduzieren.
*
* Die Klasse implementiert die wichtigsten Methoden und Konstruktoren
* der [UUID]-Klasse, sodass sie als Ersatz fuer diese Klasse verwendet
* werden kann.
*
* @author oboehm
* @since 0.6+ (11.12.2017)
*/
open class TinyUUID(uuid: UUID) : AbstractFachwert<UUID, TinyUUID>(uuid) {
/**
* Instantiiert eine eine neue TinyUUID anhand eines Strings. Dieser kann
* sowohl in Form einer UUID ("4e8108fa-e517-41bd-8372-a828843030ba") als
* auch in Form ohne Trennzeichen ("4e8108fae51741bd8372a828843030ba")
* angegeben werden.
*
* @param uuid z.B. "4e8108fa-e517-41bd-8372-a828843030ba"
*/
constructor(uuid: String) : this(toUUID(uuid)) {}
/**
* Instantiiert eine neue TinyUUID. Die uebergebene Zahl wird dabei auf
* 128 Bit normalisiert, damit es beim Vergleich keine Ueberraschungen
* wegen unterschiedlichem Vorzeichen gibt.
*
* @param number 128-Bit-Zahl
*/
constructor(number: BigInteger) : this(toUUID(number)) {}
/**
* Instantiiert eine neue TinyUUID.
*
* @param bytes 16 Bytes
*/
constructor(bytes: ByteArray) : this(toUUID(bytes)) {}
/**
* Liefert die UUID als 128-Bit-Zahl zurueck. Diese kann auch negativ
* sein.
*
* @return Zahl
*/
fun toNumber(): BigInteger {
val uuid = code
return toBigInteger(uuid.toString())
}
/**
* Liefert die 128-Bit-Zahl als Byte-Array zurueck.
*
* @return 16-stelliges Byte-Array
*/
fun toBytes(): ByteArray {
val bytes = toNumber().toByteArray()
return to16Bytes(bytes)
}
/**
* Liefert die [UUID] zurueck. Darueber kann man auf die weniger
* wichtigen Methoden von [UUID] zurueckgreifen, die in dieser Klasse
* fehlen.
*
* @return die [UUID]
*/
val uUID: UUID
get() = code
/**
* Liefert die unteren 64 Bits der 128-bittigen UUID.
*
* @return die ersten 64 Bits
*/
val leastSignificantBits: Long
get() = uUID.leastSignificantBits
/**
* Liefert die oberen 64 Bits der 128-bittigen UUID.
*
* @return die oberen 64 Bits
*/
val mostSignificantBits: Long
get() = uUID.mostSignificantBits
/**
* [TinyUUID] ist zwar als Ersatz fuer die [UUID]-Klasse gedacht,
* liefert aber immer die Kurzform ueber die toString()-Methode zurueck.
* D.h. das Ergebis entspricht der Ausgabe von [.toShortString].
*
* @return z.B. "ix9de14vQgGKwXZUaruCzw"
*/
override fun toString(): String {
return toShortString()
}
/**
* Liefert eine verkuerzte Darstellung einer UUID als String. Die Laenge
* reduziert sich dadurch auf 22 Zeichen. Diese kann z.B. dazu genutzt
* werden, um eine UUID platzsparend abzuspeichern, wenn man dazu nicht
* das Ergebnis aus [.toBytes] (16 Bytes) verwenden will.
*
* Damit der resultierende String auch URL-safe ist, werden die Zeichen
* '/' und '+' durch '_' und '-' ersetzt.
*
* @return 22 Zeichen, z.B. "ix9de14vQgGKwXZUaruCzw"
*/
open fun toShortString(): String {
val s = Base64.getEncoder().withoutPadding().encodeToString(toBytes())
return s.replace('/', '_').replace('+', '-')
}
/**
* Dies ist das Gegenstueck zu [.toShortString].
*
* @return z.B. "4e8108fa-e517-41bd-8372-a828843030ba"
*/
fun toLongString(): String {
return uUID.toString()
}
companion object {
/** Minimale UUID. */
@JvmField
val MIN = TinyUUID("00000000-0000-0000-0000-000000000000")
/** Maximale UUID (die aber als Nummer negativ ist). */
@JvmField
val MAX = TinyUUID("ffffffff-ffff-ffff-ffff-ffffffffffff")
private fun to16Bytes(number: BigInteger): ByteArray {
return to16Bytes(number.toByteArray())
}
private fun to16Bytes(bytes: ByteArray): ByteArray {
return if (bytes.size > 15) {
Arrays.copyOfRange(bytes, bytes.size - 16, bytes.size)
} else {
val bytes16 = ByteArray(16)
System.arraycopy(bytes, 0, bytes16, 16 - bytes.size, bytes.size)
bytes16
}
}
private fun toBigInteger(uuid: String): BigInteger {
return try {
BigInteger(uuid.replace("-".toRegex(), ""), 16)
} catch (nfe: NumberFormatException) {
throw InvalidValueException(uuid, "UUID")
}
}
private fun toString(number: BigInteger): String {
val bytes = to16Bytes(number)
return toString(bytes)
}
private fun toString(bytes: ByteArray): String {
return String.format("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15])
}
/**
* Aehnlich wie [UUID.fromString] wird hier eine
* [TinyUUID] anhand des uebergebenen Strings erzeugt.
* Der uebergebene String kann dabei das Format einer UUID
* besitzen, kann aber auch ein Ergebnis von [.toShortString]
* sein.
*
* @param id z.B. "ix9de14vQgGKwXZUaruCzw"
* @return a TinyUUID
*/
@JvmStatic
fun fromString(id: String): TinyUUID {
return TinyUUID(toUUID(id))
}
private fun toUUID(id: String): UUID {
return when (id.length) {
22 -> {
val base64 = id.replace('-', '+').replace('_', '/')
val bytes = Base64.getDecoder().decode(base64.toByteArray(StandardCharsets.UTF_8))
toUUID(bytes)
}
25 -> {
val n = BigInteger(id, Character.MAX_RADIX)
toUUID(n)
}
else -> try {
UUID.fromString(id)
} catch (ex: IllegalArgumentException) {
throw InvalidValueException(id, "UUID")
}
}
}
private fun toUUID(number: BigInteger): UUID {
return UUID.fromString(toString(number))
}
private fun toUUID(bytes: ByteArray): UUID {
return UUID.fromString(toString(verify(bytes)))
}
private fun verify(bytes: ByteArray): ByteArray {
if (bytes.size != 16) {
throw LocalizedIllegalArgumentException(bytes, 16)
}
return bytes
}
/**
* Dies ist das Gegenstueck zur [UUID.randomUUID], nur dass hier
* bereits eine [TinyUUID] erzeugt wird.
*
* @return zufaellige UUID
*/
@JvmStatic
fun randomUUID(): TinyUUID {
return TinyUUID(UUID.randomUUID())
}
}
} | apache-2.0 | 32e0a522c0db787ece5ebf5df6aeed57 | 31.212355 | 105 | 0.597698 | 3.791818 | false | false | false | false |
austinv11/OpenPlanner | Core/src/main/kotlin/com/austinv11/planner/core/db/DatabaseManager.kt | 1 | 3176 | package com.austinv11.planner.core.db
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.dao.DaoManager
import com.j256.ormlite.field.DataType
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.jdbc.JdbcConnectionSource
import com.j256.ormlite.table.DatabaseTable
import com.j256.ormlite.table.TableUtils
/**
* This manages databases accessed by the server.
*/
object DatabaseManager {
/**
* This is the url leading to the database.
*/
const val DATABASE_URL = "jdbc:sqlite:database.db"
val CONNECTION_SOURCE = JdbcConnectionSource(DATABASE_URL)
val ACCOUNT_DAO: Dao<Account, Int> = DaoManager.createDao(CONNECTION_SOURCE, Account::class.java)
init {
TableUtils.createTableIfNotExists(CONNECTION_SOURCE, Account::class.java)
Runtime.getRuntime().addShutdownHook(Thread({ CONNECTION_SOURCE.close() })) //TODO: Scale connection sources better
}
@DatabaseTable(tableName = "accounts")
class Account {
constructor()
constructor(username: String, email: String, hash: ByteArray, salt: ByteArray) {
this.username = username
this.email = email
this.hash = hash
this.salt = salt
//This constructor is only used by OpenPlanner, so its safe to immediately create in the DAO
ACCOUNT_DAO.create(this)
}
companion object Columns {
const val ID = "id"
const val USERNAME = "user"
const val EMAIL = "email"
const val PASSWORD_HASH = "hash"
const val PASSWORD_SALT = "salt"
const val VERIFIED = "verified"
const val PLUGINS = "plugins"
}
@DatabaseField(columnName = ID, generatedId = true)
var id: Int = 0
@DatabaseField(columnName = USERNAME, canBeNull = false)
var username: String = ""
@DatabaseField(columnName = EMAIL, canBeNull = false)
var email: String = ""
@DatabaseField(columnName = PASSWORD_HASH, canBeNull = false, dataType = DataType.BYTE_ARRAY)
var hash: ByteArray = byteArrayOf()
@DatabaseField(columnName = PASSWORD_SALT, canBeNull = false, dataType = DataType.BYTE_ARRAY)
var salt: ByteArray = byteArrayOf()
@DatabaseField(columnName = VERIFIED, canBeNull = false)
var verified: Boolean = false
@DatabaseField(columnName = PLUGINS, canBeNull = false, dataType = DataType.BYTE_ARRAY, useGetSet = true)
var plugins: ByteArray = byteArrayOf()
get() {
field = ByteArray(_plugins.size)
_plugins.forEachIndexed { i, plugin -> field[i] = plugin.toByte() }
return field
}
set(value) {
val pluginArray = kotlin.arrayOfNulls<String>(value.size)
value.forEachIndexed { i, byte -> pluginArray[i] = byte.toString() }
_plugins = pluginArray as Array<String>
field = value
}
var _plugins: Array<String> = arrayOf()
}
}
| gpl-3.0 | 2060733702fdc5c3487f48db81fd285b | 34.288889 | 123 | 0.609257 | 4.569784 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_string.kt | 3 | 3183 | import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`string`,`nullableString`) VALUES (?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindString(1, entity.string)
if (entity.nullableString == null) {
statement.bindNull(2)
} else {
statement.bindString(2, entity.nullableString)
}
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfString: Int = getColumnIndexOrThrow(_cursor, "string")
val _cursorIndexOfNullableString: Int = getColumnIndexOrThrow(_cursor, "nullableString")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpString: String
_tmpString = _cursor.getString(_cursorIndexOfString)
val _tmpNullableString: String?
if (_cursor.isNull(_cursorIndexOfNullableString)) {
_tmpNullableString = null
} else {
_tmpNullableString = _cursor.getString(_cursorIndexOfNullableString)
}
_result = MyEntity(_tmpString,_tmpNullableString)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | ff579c64941385585b2e4267247d9ba8 | 35.597701 | 100 | 0.621426 | 5.084665 | false | false | false | false |
AndroidX/androidx | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/RemoteViewsTranslator.kt | 3 | 17928 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.util.Log
import android.util.SizeF
import android.view.Gravity
import android.view.View
import android.widget.RemoteViews
import androidx.annotation.DoNotInline
import androidx.annotation.LayoutRes
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.core.widget.RemoteViewsCompat.setLinearLayoutGravity
import androidx.glance.Emittable
import androidx.glance.EmittableButton
import androidx.glance.EmittableImage
import androidx.glance.GlanceModifier
import androidx.glance.appwidget.lazy.EmittableLazyColumn
import androidx.glance.appwidget.lazy.EmittableLazyListItem
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGrid
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGridListItem
import androidx.glance.appwidget.translators.translateEmittableCheckBox
import androidx.glance.appwidget.translators.translateEmittableCircularProgressIndicator
import androidx.glance.appwidget.translators.translateEmittableImage
import androidx.glance.appwidget.translators.translateEmittableLazyColumn
import androidx.glance.appwidget.translators.translateEmittableLazyListItem
import androidx.glance.appwidget.translators.translateEmittableLazyVerticalGrid
import androidx.glance.appwidget.translators.translateEmittableLazyVerticalGridListItem
import androidx.glance.appwidget.translators.translateEmittableLinearProgressIndicator
import androidx.glance.appwidget.translators.translateEmittableRadioButton
import androidx.glance.appwidget.translators.translateEmittableSwitch
import androidx.glance.appwidget.translators.translateEmittableText
import androidx.glance.layout.Alignment
import androidx.glance.layout.EmittableBox
import androidx.glance.layout.EmittableColumn
import androidx.glance.layout.EmittableRow
import androidx.glance.layout.EmittableSpacer
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.padding
import androidx.glance.text.EmittableText
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
internal fun translateComposition(
context: Context,
appWidgetId: Int,
element: RemoteViewsRoot,
layoutConfiguration: LayoutConfiguration?,
rootViewIndex: Int,
layoutSize: DpSize,
actionBroadcastReceiver: ComponentName? = null,
) =
translateComposition(
TranslationContext(
context,
appWidgetId,
context.isRtl,
layoutConfiguration,
itemPosition = -1,
layoutSize = layoutSize,
actionBroadcastReceiver = actionBroadcastReceiver,
),
element.children,
rootViewIndex,
)
@VisibleForTesting
internal var forceRtl: Boolean? = null
private val Context.isRtl: Boolean
get() = forceRtl
?: (resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
@RequiresApi(Build.VERSION_CODES.S)
private object Api31Impl {
@DoNotInline
fun createRemoteViews(sizeMap: Map<SizeF, RemoteViews>): RemoteViews = RemoteViews(sizeMap)
}
internal fun translateComposition(
translationContext: TranslationContext,
children: List<Emittable>,
rootViewIndex: Int
): RemoteViews {
if (children.all { it is EmittableSizeBox }) {
// If the children of root are all EmittableSizeBoxes, then we must translate each
// EmittableSizeBox into a distinct RemoteViews object. Then, we combine them into one
// multi-sized RemoteViews (a RemoteViews that contains either landscape & portrait RVs or
// multiple RVs mapped by size).
val sizeMode = (children.first() as EmittableSizeBox).sizeMode
val views = children.map { child ->
val size = (child as EmittableSizeBox).size
val remoteViewsInfo = createRootView(translationContext, child.modifier, rootViewIndex)
val rv = remoteViewsInfo.remoteViews.apply {
translateChild(translationContext.forRoot(root = remoteViewsInfo), child)
}
size.toSizeF() to rv
}
return when (sizeMode) {
is SizeMode.Single -> views.single().second
is SizeMode.Responsive, SizeMode.Exact -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
Api31Impl.createRemoteViews(views.toMap())
} else {
require(views.size == 1 || views.size == 2)
combineLandscapeAndPortrait(views.map { it.second })
}
}
}
} else {
return children.single().let { child ->
val remoteViewsInfo = createRootView(translationContext, child.modifier, rootViewIndex)
remoteViewsInfo.remoteViews.apply {
translateChild(translationContext.forRoot(root = remoteViewsInfo), child)
}
}
}
}
private fun combineLandscapeAndPortrait(views: List<RemoteViews>): RemoteViews =
when (views.size) {
2 -> RemoteViews(views[0], views[1])
1 -> views[0]
else -> throw IllegalArgumentException("There must be between 1 and 2 views.")
}
internal data class TranslationContext(
val context: Context,
val appWidgetId: Int,
val isRtl: Boolean,
val layoutConfiguration: LayoutConfiguration?,
val itemPosition: Int,
val isLazyCollectionDescendant: Boolean = false,
val lastViewId: AtomicInteger = AtomicInteger(0),
val parentContext: InsertedViewInfo = InsertedViewInfo(),
val isBackgroundSpecified: AtomicBoolean = AtomicBoolean(false),
val layoutSize: DpSize = DpSize.Zero,
val layoutCollectionViewId: Int = View.NO_ID,
val layoutCollectionItemId: Int = -1,
val canUseSelectableGroup: Boolean = false,
val actionTargetId: Int? = null,
val actionBroadcastReceiver: ComponentName? = null
) {
fun nextViewId() = lastViewId.incrementAndGet()
fun forChild(parent: InsertedViewInfo, pos: Int): TranslationContext =
copy(itemPosition = pos, parentContext = parent)
fun forRoot(root: RemoteViewsInfo): TranslationContext =
forChild(pos = 0, parent = root.view)
.copy(
isBackgroundSpecified = AtomicBoolean(false),
lastViewId = AtomicInteger(0),
)
fun resetViewId(newViewId: Int = 0) = copy(lastViewId = AtomicInteger(newViewId))
fun forLazyCollection(viewId: Int) =
copy(isLazyCollectionDescendant = true, layoutCollectionViewId = viewId)
fun forLazyViewItem(itemId: Int, newViewId: Int = 0) =
copy(lastViewId = AtomicInteger(newViewId), layoutCollectionViewId = itemId)
fun canUseSelectableGroup() = copy(canUseSelectableGroup = true)
fun forActionTargetId(viewId: Int) = copy(actionTargetId = viewId)
}
internal fun RemoteViews.translateChild(
translationContext: TranslationContext,
element: Emittable
) {
when (element) {
is EmittableBox -> translateEmittableBox(translationContext, element)
is EmittableButton -> translateEmittableButton(translationContext, element)
is EmittableRow -> translateEmittableRow(translationContext, element)
is EmittableColumn -> translateEmittableColumn(translationContext, element)
is EmittableText -> translateEmittableText(translationContext, element)
is EmittableLazyListItem -> translateEmittableLazyListItem(translationContext, element)
is EmittableLazyColumn -> translateEmittableLazyColumn(translationContext, element)
is EmittableAndroidRemoteViews -> {
translateEmittableAndroidRemoteViews(translationContext, element)
}
is EmittableCheckBox -> translateEmittableCheckBox(translationContext, element)
is EmittableSpacer -> translateEmittableSpacer(translationContext, element)
is EmittableSwitch -> translateEmittableSwitch(translationContext, element)
is EmittableImage -> translateEmittableImage(translationContext, element)
is EmittableLinearProgressIndicator -> {
translateEmittableLinearProgressIndicator(translationContext, element)
}
is EmittableCircularProgressIndicator -> {
translateEmittableCircularProgressIndicator(translationContext, element)
}
is EmittableLazyVerticalGrid -> {
translateEmittableLazyVerticalGrid(translationContext, element)
}
is EmittableLazyVerticalGridListItem -> {
translateEmittableLazyVerticalGridListItem(translationContext, element)
}
is EmittableRadioButton -> translateEmittableRadioButton(translationContext, element)
is EmittableSizeBox -> translateEmittableSizeBox(translationContext, element)
else -> {
throw IllegalArgumentException(
"Unknown element type ${element.javaClass.canonicalName}"
)
}
}
}
internal fun RemoteViews.translateEmittableSizeBox(
translationContext: TranslationContext,
element: EmittableSizeBox
) {
require(element.children.size <= 1) {
"Size boxes can only have at most one child ${element.children.size}. " +
"The normalization of the composition tree failed."
}
element.children.firstOrNull()?.let { translateChild(translationContext, it) }
}
internal fun remoteViews(translationContext: TranslationContext, @LayoutRes layoutId: Int) =
RemoteViews(translationContext.context.packageName, layoutId)
internal fun Alignment.Horizontal.toGravity(): Int =
when (this) {
Alignment.Horizontal.Start -> Gravity.START
Alignment.Horizontal.End -> Gravity.END
Alignment.Horizontal.CenterHorizontally -> Gravity.CENTER_HORIZONTAL
else -> {
Log.w(GlanceAppWidgetTag, "Unknown horizontal alignment: $this")
Gravity.START
}
}
internal fun Alignment.Vertical.toGravity(): Int =
when (this) {
Alignment.Vertical.Top -> Gravity.TOP
Alignment.Vertical.Bottom -> Gravity.BOTTOM
Alignment.Vertical.CenterVertically -> Gravity.CENTER_VERTICAL
else -> {
Log.w(GlanceAppWidgetTag, "Unknown vertical alignment: $this")
Gravity.TOP
}
}
internal fun Alignment.toGravity() = horizontal.toGravity() or vertical.toGravity()
private fun RemoteViews.translateEmittableBox(
translationContext: TranslationContext,
element: EmittableBox
) {
val viewDef = insertContainerView(
translationContext,
LayoutType.Box,
element.children.size,
element.modifier,
element.contentAlignment.horizontal,
element.contentAlignment.vertical,
)
applyModifiers(
translationContext,
this,
element.modifier,
viewDef
)
element.children.forEach {
it.modifier = it.modifier.then(AlignmentModifier(element.contentAlignment))
}
setChildren(
translationContext,
viewDef,
element.children
)
}
private fun RemoteViews.translateEmittableRow(
translationContext: TranslationContext,
element: EmittableRow
) {
val layoutType = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && element.modifier.isSelectableGroup
) {
LayoutType.RadioRow
} else {
LayoutType.Row
}
val viewDef = insertContainerView(
translationContext,
layoutType,
element.children.size,
element.modifier,
horizontalAlignment = null,
verticalAlignment = element.verticalAlignment,
)
setLinearLayoutGravity(
viewDef.mainViewId,
Alignment(element.horizontalAlignment, element.verticalAlignment).toGravity()
)
applyModifiers(
translationContext.canUseSelectableGroup(),
this,
element.modifier,
viewDef
)
setChildren(
translationContext,
viewDef,
element.children
)
if (element.modifier.isSelectableGroup) checkSelectableGroupChildren(element.children)
}
private fun RemoteViews.translateEmittableColumn(
translationContext: TranslationContext,
element: EmittableColumn
) {
val layoutType = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && element.modifier.isSelectableGroup
) {
LayoutType.RadioColumn
} else {
LayoutType.Column
}
val viewDef = insertContainerView(
translationContext,
layoutType,
element.children.size,
element.modifier,
horizontalAlignment = element.horizontalAlignment,
verticalAlignment = null,
)
setLinearLayoutGravity(
viewDef.mainViewId,
Alignment(element.horizontalAlignment, element.verticalAlignment).toGravity()
)
applyModifiers(
translationContext.canUseSelectableGroup(),
this,
element.modifier,
viewDef
)
setChildren(
translationContext,
viewDef,
element.children
)
if (element.modifier.isSelectableGroup) checkSelectableGroupChildren(element.children)
}
private fun checkSelectableGroupChildren(children: List<Emittable>) {
check(children.count { it is EmittableRadioButton && it.checked } <= 1) {
"When using GlanceModifier.selectableGroup(), no more than one RadioButton " +
"may be checked at a time."
}
}
private fun RemoteViews.translateEmittableAndroidRemoteViews(
translationContext: TranslationContext,
element: EmittableAndroidRemoteViews
) {
val rv = if (element.children.isEmpty()) {
element.remoteViews
} else {
check(element.containerViewId != View.NO_ID) {
"To add children to an `AndroidRemoteViews`, its `containerViewId` must be set."
}
element.remoteViews.copy().apply {
removeAllViews(element.containerViewId)
element.children.forEachIndexed { index, child ->
val rvInfo = createRootView(translationContext, child.modifier, index)
val rv = rvInfo.remoteViews
rv.translateChild(translationContext.forRoot(rvInfo), child)
addChildView(element.containerViewId, rv, index)
}
}
}
val viewDef = insertView(translationContext, LayoutType.Frame, element.modifier)
applyModifiers(translationContext, this, element.modifier, viewDef)
removeAllViews(viewDef.mainViewId)
addChildView(viewDef.mainViewId, rv, stableId = 0)
}
private fun RemoteViews.translateEmittableButton(
translationContext: TranslationContext,
element: EmittableButton
) {
// Separate the button into a wrapper and the text, this allows us to set the color of the text
// background, while maintaining the ripple for the click indicator.
// TODO: add Image button
val content = EmittableText().apply {
text = element.text
style = element.style
maxLines = element.maxLines
modifier =
GlanceModifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 8.dp)
}
translateEmittableText(translationContext, content)
}
private fun RemoteViews.translateEmittableSpacer(
translationContext: TranslationContext,
element: EmittableSpacer
) {
val viewDef = insertView(translationContext, LayoutType.Frame, element.modifier)
applyModifiers(translationContext, this, element.modifier, viewDef)
}
// Sets the emittables as children to the view. This first remove any previously added view, the
// add a view per child, with a stable id if of Android S+. Currently the stable id is the index
// of the child in the iterable.
internal fun RemoteViews.setChildren(
translationContext: TranslationContext,
parentDef: InsertedViewInfo,
children: Iterable<Emittable>
) {
children.forEachIndexed { index, child ->
translateChild(
translationContext.forChild(parent = parentDef, pos = index),
child,
)
}
}
/**
* Add stable view if on Android S+, otherwise simply add the view.
*/
internal fun RemoteViews.addChildView(viewId: Int, childView: RemoteViews, stableId: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
RemoteViewsTranslatorApi31Impl.addChildView(this, viewId, childView, stableId)
return
}
addView(viewId, childView)
}
/**
* Copy a RemoteViews (the exact method depends on the version of Android)
*/
@Suppress("DEPRECATION") // RemoteViews.clone must be used before Android P.
private fun RemoteViews.copy(): RemoteViews =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
RemoteViewsTranslatorApi28Impl.copyRemoteViews(this)
} else {
clone()
}
@RequiresApi(Build.VERSION_CODES.P)
private object RemoteViewsTranslatorApi28Impl {
@DoNotInline
fun copyRemoteViews(rv: RemoteViews) = RemoteViews(rv)
}
@RequiresApi(Build.VERSION_CODES.S)
private object RemoteViewsTranslatorApi31Impl {
@DoNotInline
fun addChildView(rv: RemoteViews, viewId: Int, childView: RemoteViews, stableId: Int) {
rv.addStableView(viewId, childView, stableId)
}
}
| apache-2.0 | f19f986626509b827f94bda95cab4766 | 36.272349 | 99 | 0.711736 | 4.787183 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/AddAssocTypeBindingsFix.kt | 2 | 2084 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.utils.template.buildAndRunTemplate
import org.rust.lang.core.psi.RsPathType
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsTraitRef
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.startOffset
import org.rust.openapiext.createSmartPointer
class AddAssocTypeBindingsFix(
element: PsiElement,
@SafeFieldForPreview
private val missingTypes: List<String>
) : LocalQuickFixAndIntentionActionOnPsiElement(element) {
override fun getText(): String = "Add missing associated types"
override fun getFamilyName() = text
override fun invoke(
project: Project,
file: PsiFile,
editor: Editor?,
startElement: PsiElement,
endElement: PsiElement
) {
val element = startElement as? RsElement ?: return
val path = when (element) {
is RsTraitRef -> element.path
is RsPathType -> element.path
else -> return
}
val factory = RsPsiFactory(project)
val defaultType = "()"
val arguments = path.typeArgumentList ?: path.addEmptyTypeArguments(factory)
val lastArgument = with(arguments) {
(assocTypeBindingList + typeReferenceList + lifetimeList).maxByOrNull { it.startOffset } ?: lt
}
val missingTypes = missingTypes.map { factory.createAssocTypeBinding(it, defaultType) }
val addedArguments = arguments.addElements(missingTypes, lastArgument, factory)
editor?.buildAndRunTemplate(element, addedArguments.mapNotNull { it.typeReference?.createSmartPointer() })
}
}
| mit | 15f6309b4c542ac091896fadfbb65203 | 36.214286 | 114 | 0.728407 | 4.641425 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/test/java/com/habitrpg/android/habitica/models/inventory/PetTest.kt | 2 | 918 | package com.habitrpg.android.habitica.models.inventory
import com.habitrpg.android.habitica.BaseAnnotationTestCase
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.getTranslatedType
import io.kotest.matchers.shouldBe
import io.mockk.every
private const val FAKE_STANDARD = "Standard"
private const val FAKE_PREMIUM = "premium"
class PetTest : BaseAnnotationTestCase() {
private var pet: Pet = Pet()
@Test
fun testGetTranslatedStringReturnsStandard() {
pet.type = "drop"
every { mockContext.getString(R.string.standard) } returns FAKE_STANDARD
val result = pet.getTranslatedType(mockContext)
result shouldBe FAKE_STANDARD
}
@Test
fun testGetTranslatedStringReturnsPremiumWhenContextIsNull() {
pet.type = "premium"
val result = pet.getTranslatedType(null)
result shouldBe FAKE_PREMIUM
}
}
| gpl-3.0 | a09a00e5f468f1f247aa54f5f8503028 | 26.818182 | 80 | 0.737473 | 4.330189 | false | true | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/crash/DTCrashHandler.kt | 1 | 712 | package com.exyui.android.debugbottle.components.crash
/**
* Created by yuriel on 9/13/16.
*/
internal object DTCrashHandler: Thread.UncaughtExceptionHandler {
private var defaultExceptionHandler: Thread.UncaughtExceptionHandler? = null
override fun uncaughtException(thread: Thread?, ex: Throwable?) {
if (null != thread && null != ex) {
val log = CrashBlock.newInstance(thread, ex)
CrashReportFileMgr.saveLog(log.toString())
}
defaultExceptionHandler?.uncaughtException(thread, ex)
}
fun install() {
defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler(this)
}
} | apache-2.0 | 4214517fdf28ae0bdfad2a422ef43b2d | 32.952381 | 80 | 0.702247 | 5.085714 | false | false | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/ui/SwingGroupingInputHarvester.kt | 1 | 7941 | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2021 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.ui
import org.scijava.`object`.ObjectService
import org.scijava.convert.ConvertService
import org.scijava.log.LogService
import org.scijava.module.Module
import org.scijava.module.ModuleException
import org.scijava.module.ModuleItem
import org.scijava.plugin.Parameter
import org.scijava.plugin.Plugin
import org.scijava.ui.swing.widget.SwingInputHarvester
import org.scijava.ui.swing.widget.SwingInputPanel
import org.scijava.widget.*
import sc.iview.commands.edit.Properties
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.util.*
import javax.swing.JLabel
import javax.swing.JPanel
@Plugin(type = org.scijava.module.process.PreprocessorPlugin::class, priority = InputHarvester.PRIORITY)
class SwingGroupingInputHarvester : SwingInputHarvester() {
@Parameter
private lateinit var log: LogService
@Parameter
private lateinit var widgetService: WidgetService
@Parameter
private lateinit var objectService: ObjectService
@Parameter
private lateinit var convertService: ConvertService
// -- InputHarvester methods --
@Throws(ModuleException::class)
override fun buildPanel(inputPanel: InputPanel<JPanel, JPanel>, module: Module) {
val inputs = module.info.inputs()
val models = ArrayList<WidgetModel>()
val sortedInputs = inputs.groupBy {
val sortKey = it.widgetStyle.substringAfter("group:").substringBefore(",")
sortKey
}
sortedInputs.forEach { group ->
// no empty groups, and skip resolved inputs, aka services
if(group.value.isEmpty() || group.value.all { module.isInputResolved(it.name) }) {
return@forEach
}
val panel = SwingInputPanel()
val labelPanel = SwingInputPanel()
val label = JLabel("<html><strong>▼ ${group.key}</strong></html>")
label.addMouseListener(object: MouseListener {
/**
* Invoked when the mouse button has been clicked (pressed
* and released) on a component.
* @param e the event to be processed
*/
override fun mouseClicked(e: MouseEvent?) {
if(e?.clickCount == 1) {
panel.component.isVisible = !panel.component.isVisible
if(panel.component.isVisible) {
label.text = "<html><strong>▼ ${group.key}</strong></html>"
} else {
label.text = "<html><strong>▶ ${group.key}</strong></html>"
}
inputPanel.component.revalidate()
}
}
/**
* Invoked when a mouse button has been pressed on a component.
* @param e the event to be processed
*/
override fun mousePressed(e: MouseEvent?) {
}
/**
* Invoked when a mouse button has been released on a component.
* @param e the event to be processed
*/
override fun mouseReleased(e: MouseEvent?) {
}
/**
* Invoked when the mouse enters a component.
* @param e the event to be processed
*/
override fun mouseEntered(e: MouseEvent?) {
}
/**
* Invoked when the mouse exits a component.
* @param e the event to be processed
*/
override fun mouseExited(e: MouseEvent?) {
}
})
labelPanel.component.add(label)
inputPanel.component.add(labelPanel.component, "wrap")
// hidemode 3 ignores the space taken up by components when rendered
inputPanel.component.add(panel.component, "wrap,hidemode 3")
for (item in group.value) {
val model = addInput(panel, module, item)
if (model != null) {
log.info("Adding input ${item.name}/${item.label}")
models.add(model)
} else {
log.error("Model for ${item.name}/${item.label} is null!")
}
}
}
// mark all models as initialized
for (model in models) model.isInitialized = true
// compute initial preview
module.preview()
}
// -- Helper methods --
@Throws(ModuleException::class)
private fun <T, P, W> addInput(inputPanel: InputPanel<P, W>,
m: Module, item: ModuleItem<T>): WidgetModel? {
val module = if(m is Properties) {
m.getCustomModuleForModuleItem(item) ?: m
} else {
m
}
val name = item.name
if(item.label.contains("[") && item.label.contains("]")) {
item.label = item.label.substringAfterLast("]")
}
val resolved = module.isInputResolved(name)
if (resolved && module == m) {
log.warn("Input ${item.name} is resolved, skipping")
return null
} // skip resolved inputs
val type = item.type
val model = widgetService.createModel(inputPanel, module, item, getObjects(type))
val widgetType = inputPanel.widgetComponentType
val widget = widgetService.create(model)
if (widget == null) {
log.warn("No widget found for input: " + model.item.name)
}
if (widget != null && widget.componentType == widgetType) {
@Suppress("UNCHECKED_CAST")
val typedWidget = widget as InputWidget<*, W>
inputPanel.addWidget(typedWidget)
return model
}
if (item.isRequired) {
log.warn("${item.name} is required but doesn't exist")
throw ModuleException("A " + type.simpleName +
" is required but none exist.")
}
// item is not required; we can skip it
return null
}
/** Asks the object service and convert service for valid choices */
private fun getObjects(type: Class<*>): List<*> {
val compatibleInputs = ArrayList(convertService.getCompatibleInputs(type))
compatibleInputs.addAll(objectService.getObjects(type))
return compatibleInputs
}
}
| bsd-2-clause | 0596d50a29b566621f3b745273782ebd | 37.707317 | 104 | 0.600504 | 4.806178 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/completion/ElmRecordExprSuggestor.kt | 1 | 2143 | package org.elm.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import org.elm.lang.core.psi.elements.ElmField
import org.elm.lang.core.psi.elements.ElmRecordExpr
import org.elm.lang.core.psi.outermostDeclaration
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.findInference
import org.elm.lang.core.types.renderedText
object ElmRecordExprSuggestor : Suggestor {
override fun addCompletions(parameters: CompletionParameters, result: CompletionResultSet) {
val pos = parameters.position
val field = pos.parent as? ElmField ?: return
val record = field.parent as? ElmRecordExpr ?: return
val diff = record.findInference()?.recordDiffs?.get(record) ?: return
// HACK: for some reason, subsequent completions can return stale results if you edit a
// record after triggering completion. This forces the results to update. Note that even
// without this, type errors and hints update as expected, which means the inference _is_
// being invalidated correctly. The stale completion results probably have something to do
// with the fact that completion runs on a shadow copy of the actual file.
record.outermostDeclaration(strict = true)?.modificationTracker?.incModificationCount()
val needsEquals = field.lowerCaseIdentifier.text.endsWith(EMPTY_RECORD_FIELD_DUMMY_IDENTIFIER)
for ((f, t) in diff.missing) {
result.add(needsEquals, f, t)
}
}
}
private fun CompletionResultSet.add(needsEquals: Boolean, str: String, field: Ty) {
addElement(LookupElementBuilder.create(str)
.withTypeText(field.renderedText())
.withInsertHandler { context, _ ->
if (needsEquals) {
val tailOffset = context.tailOffset
context.document.insertString(tailOffset, " = ")
context.editor.caretModel.moveToOffset(tailOffset + 3)
}
})
}
| mit | e2dd8909758f0b0e048bd26b799c1943 | 46.622222 | 102 | 0.70742 | 4.62851 | false | false | false | false |
crabzilla/crabzilla | crabzilla-stack/src/test/kotlin/io/github/crabzilla/example1/customer/customerStack.kt | 1 | 4923 | package io.github.crabzilla.example1.customer
import io.github.crabzilla.stack.EventProjector
import io.github.crabzilla.stack.EventRecord
import io.github.crabzilla.stack.JsonObjectSerDer
import io.github.crabzilla.stack.command.CommandServiceConfig
import io.vertx.core.Future
import io.vertx.core.json.JsonObject
import io.vertx.sqlclient.SqlConnection
import io.vertx.sqlclient.Tuple
import java.util.*
val customerConfig = CommandServiceConfig(
Customer::class,
CustomerCommand::class,
CustomerEvent::class,
customerEventHandler,
CustomerCommandHandler()
)
class CustomerJsonObjectSerDer: JsonObjectSerDer<Customer, CustomerCommand, CustomerEvent> {
override fun eventFromJson(json: JsonObject): CustomerEvent {
return when (val eventType = json.getString("type")) {
"CustomerRegistered" -> CustomerEvent.CustomerRegistered(UUID.fromString(json.getString("id")))
"CustomerRegisteredPrivate" -> CustomerEvent.CustomerRegisteredPrivate(json.getString("name"))
"CustomerActivated" -> CustomerEvent.CustomerActivated(json.getString("reason"))
"CustomerDeactivated" -> CustomerEvent.CustomerDeactivated(json.getString("reason"))
else -> throw IllegalArgumentException("Unknown event $eventType")
}
}
override fun eventToJson(event: CustomerEvent): JsonObject {
return when (event) {
is CustomerEvent.CustomerRegistered -> JsonObject()
.put("type", event::class.simpleName)
.put("id", event.id.toString())
is CustomerEvent.CustomerRegisteredPrivate -> JsonObject()
.put("type", event::class.simpleName)
.put("name", event.name)
is CustomerEvent.CustomerActivated ->
JsonObject()
.put("type", event::class.simpleName)
.put("reason", event.reason)
is CustomerEvent.CustomerDeactivated -> JsonObject()
.put("type", event::class.simpleName)
.put("reason", event.reason)
}
}
override fun commandToJson(command: CustomerCommand): JsonObject {
return when (command) {
is CustomerCommand.RegisterCustomer -> JsonObject()
.put("type", command::class.simpleName)
.put("id", command.customerId.toString())
.put("name", command.name)
is CustomerCommand.ActivateCustomer -> JsonObject()
.put("type", command::class.simpleName)
.put("reason", command.reason)
is CustomerCommand.DeactivateCustomer -> JsonObject()
.put("type", command::class.simpleName)
.put("reason", command.reason)
is CustomerCommand.RegisterAndActivateCustomer -> JsonObject()
.put("type", command::class.simpleName)
.put("id", command.customerId.toString())
.put("name", command.name)
.put("reason", command.reason)
}
}
override fun commandFromJson(json: JsonObject): CustomerCommand {
return when (val commandType = json.getString("type")) {
"RegisterCustomer" -> CustomerCommand.RegisterCustomer(UUID.fromString(json.getString("ID")), json.getString("name"))
"ActivateCustomer" -> CustomerCommand.ActivateCustomer(json.getString("reason"))
"DeactivateCustomer" -> CustomerCommand.DeactivateCustomer(json.getString("reason"))
"RegisterAndActivateCustomer" -> CustomerCommand.RegisterAndActivateCustomer(UUID.fromString(json.getString("ID")),
json.getString("name"), json.getString("reason"))
else -> throw IllegalArgumentException("Unknown command $commandType")
}
}
}
class CustomersEventProjector : EventProjector {
private val serDer = CustomerJsonObjectSerDer()
override fun project(conn: SqlConnection, record: EventRecord): Future<Void> {
val (payload, _, id) = record.extract()
return when (val event = serDer.eventFromJson(payload)) {
is CustomerEvent.CustomerRegistered ->
CustomersWriteDao.upsert(conn, id, false)
is CustomerEvent.CustomerRegisteredPrivate ->
CustomersWriteDao.updateName(conn, id, event.name)
is CustomerEvent.CustomerActivated ->
CustomersWriteDao.updateStatus(conn, id, true)
is CustomerEvent.CustomerDeactivated ->
CustomersWriteDao.updateStatus(conn, id, false)
}
}
}
object CustomersWriteDao {
fun upsert(conn: SqlConnection, id: UUID, isActive: Boolean): Future<Void> {
return conn
.preparedQuery("INSERT INTO customer_summary (id, is_active) VALUES ($1, $2)")
.execute(Tuple.of(id, isActive))
.mapEmpty()
}
fun updateName(conn: SqlConnection, id: UUID, name: String): Future<Void> {
return conn
.preparedQuery("UPDATE customer_summary set name = $2 WHERE id = $1")
.execute(Tuple.of(id, name))
.mapEmpty()
}
fun updateStatus(conn: SqlConnection, id: UUID, isActive: Boolean): Future<Void> {
return conn
.preparedQuery("UPDATE customer_summary set is_active = $2 where id = $1")
.execute(Tuple.of(id, isActive))
.mapEmpty()
}
}
| apache-2.0 | 19275b2e5b59917cea1a4bc14d9ceb13 | 38.701613 | 123 | 0.704449 | 4.383793 | false | false | false | false |
tasomaniac/OpenLinkWith | app/src/main/java/com/tasomaniac/openwith/settings/advanced/features/Feature.kt | 1 | 1926 | package com.tasomaniac.openwith.settings.advanced.features
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.tasomaniac.openwith.R
enum class Feature(
@StringRes val titleRes: Int,
@StringRes val detailsRes: Int,
@DrawableRes val imageRes: Int? = null,
val className: String? = null,
val prefKey: String,
val defaultValue: Boolean = true
) {
ADD_TO_HOMESCREEN(
R.string.pref_title_feature_add_to_homescreen,
R.string.pref_details_feature_add_to_homescreen,
R.drawable.tutorial_4,
"com.tasomaniac.openwith.homescreen.AddToHomeScreen",
"pref_feature_add_to_homescreen"
),
TEXT_SELECTION(
R.string.pref_title_feature_text_selection,
R.string.pref_details_feature_text_selection,
R.drawable.feature_text_selection,
"com.tasomaniac.openwith.TextSelectionActivity",
"pref_feature_text_selection"
),
DIRECT_SHARE(
R.string.pref_title_feature_direct_share,
R.string.pref_details_feature_direct_share,
R.drawable.feature_direct_share,
"androidx.sharetarget.ChooserTargetServiceCompat",
"pref_feature_direct_share"
),
BROWSER(
R.string.pref_title_feature_browser,
R.string.pref_details_feature_browser,
className = "com.tasomaniac.openwith.BrowserActivity",
prefKey = "pref_feature_browser",
defaultValue = false
),
CLEAN_URLS(
R.string.pref_title_feature_clean_urls,
R.string.pref_details_feature_clean_urls,
prefKey = "pref_feature_clean_urls",
defaultValue = false
),
CALLER_APP(
R.string.pref_title_feature_caller_app,
R.string.pref_details_feature_caller_app,
prefKey = "pref_feature_caller_app",
defaultValue = false
)
}
fun String.toFeature() = Feature.values().find { it.prefKey == this }!!
| apache-2.0 | a1fa8b3a30dfbd12fbffb1848a52c71c | 32.206897 | 71 | 0.668224 | 3.791339 | false | false | false | false |
daniloqueiroz/nsync | src/main/kotlin/ui/cli/SyncCommands.kt | 1 | 1763 | package ui.cli
import commons.Failure
import commons.Success
import picocli.CommandLine
import ui.rest.FSBody
@CommandLine.Command(description = arrayOf("Add a new FS to sync"), name = "add")
internal class AddFS : CliCommand {
@CommandLine.Parameters(index = "0", description = arrayOf("Local folder URI. eg.: 'file:///tmp'"))
var localUri: String? = null
@CommandLine.Parameters(index = "1", description = arrayOf("Remote folder URI. eg.: 'file:///tmp'"))
var remoteUri: String? = null
override fun invoke(ctx: BaseCommand) {
ctx.client(ctx.api.addFS(FSBody(localUri = localUri!!, remoteUri = remoteUri!!))).then {
when (it) {
is Success -> {
ctx.exit("FS added ${it.value}")
}
is Failure -> {
ctx.exit("Unable to add fs: ${it.message}", 1)
}
}
}
}
}
@CommandLine.Command(description = arrayOf("List existing FS"), name = "list")
internal class ListFS : CliCommand {
override fun invoke(ctx: BaseCommand) {
ctx.client(ctx.api.listFS()).then {
when (it) {
is Success -> {
val filesystems = it.value
if (filesystems.size == 0) {
println("No Filesystems added.")
} else {
println("Existing Filesystems:")
filesystems.forEach {
println("\t$it")
}
}
ctx.exit()
}
is Failure -> {
ctx.exit("Unable to list fs: ${it.message}", 1)
}
}
}
}
} | gpl-3.0 | 5f2410305eebae96bafad156b9b7c388 | 31.666667 | 104 | 0.486103 | 4.603133 | false | false | false | false |
felipebz/sonar-plsql | sonar-zpa-plugin/src/main/kotlin/org/sonar/plsqlopen/rules/SonarQubeRuleKeyAdapter.kt | 1 | 1510 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.rules
import org.sonar.api.rule.RuleKey
class SonarQubeRuleKeyAdapter(val ruleKey: RuleKey) : ZpaRuleKey {
override val rule: String
get() = ruleKey.rule()
override val repository: String
get() = ruleKey.repository()
override fun toString(): String = ruleKey.toString()
override fun equals(other: Any?): Boolean = ruleKey == (other as SonarQubeRuleKeyAdapter).ruleKey
override fun hashCode(): Int = ruleKey.hashCode()
companion object {
fun of(repository: String, rule: String): ZpaRuleKey =
SonarQubeRuleKeyAdapter(RuleKey.of(repository, rule))
}
}
| lgpl-3.0 | 4bcf7035f240651db50356030b600108 | 34.116279 | 101 | 0.721192 | 4.148352 | false | false | false | false |
BenjaminEarley/DroidBot | app/src/main/java/com/benjaminearley/droidbot/Omni.kt | 1 | 3651 | package com.benjaminearley.droidbot
import java.lang.Math.PI
import java.lang.Math.abs
import java.lang.Math.cos
import java.lang.Math.sin
import java.lang.Math.sqrt
val tau = PI.toFloat() * 2.0f
val numWheels = 3
val xUnit = Vector3(1.0f, 0.0f, 0.0f)
val yUnit = Vector3(0.0f, 1.0f, 0.0f)
val zUnit = Vector3(0.0f, 0.0f, 1.0f)
data class Vector2(val x: Float, val y: Float) {
operator fun plus(v: Vector2): Vector2 = Vector2(x + v.x, y + v.y)
fun scale(s: Float): Vector2 = Vector2(x * s, y * s)
private fun divide(s: Float): Vector2 = Vector2(x / s, y / s)
infix fun dot(v: Vector2): Float = (x * v.x) + (y * v.y)
val clipToUnit: Vector2
get() = dot(this).let { lengthSquared ->
if (lengthSquared <= 1.0) this
else divide(sqrt(lengthSquared.toDouble()).toFloat())
}
}
data class Vector3(val x: Float, val y: Float, val z: Float) {
fun scale(s: Float): Vector3 = Vector3(x * s, y * s, z * s)
infix fun dot(v: Vector3): Float = x * v.x + y * v.y + z * v.z
fun cross(v: Vector3): Vector3 = Vector3(
y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x)
operator fun unaryMinus(): Vector3 = Vector3(-x, -y, -z)
}
data class Quaternion(private val s: Float, private val v: Vector3) {
private val conjugate: Quaternion get() = Quaternion(s, -v)
private infix fun mul(q: Quaternion): Quaternion = Quaternion(
s * q.s - (v dot q.v),
Vector3(
v.y * q.v.z - v.z * q.v.y + s * q.v.x + v.x * q.s,
v.z * q.v.x - v.x * q.v.z + s * q.v.y + v.y * q.s,
v.x * q.v.y - v.y * q.v.x + s * q.v.z + v.z * q.s))
fun rotate(v: Vector3): Vector3 = (this mul Quaternion(0.0f, v) mul conjugate).v
}
fun quaternionFromVector(axis: Vector3, r: Float): Quaternion = Quaternion(
cos((r / 2.0f).toDouble()).toFloat(),
axis.scale(sin((r / 2.0f).toDouble()).toFloat()))
typealias Wheels = List<Vector3>
val wheels: List<Vector3> = (0 until numWheels).map {
quaternionFromVector(zUnit, (it.toFloat() / numWheels.toFloat()) * tau).rotate(xUnit)
}
typealias Speeds = List<Float>
fun lateralSpeeds(wheels: Wheels, x: Float, y: Float): Speeds =
Vector3(x, y, 0.0f).let { direction -> wheels.map { wheel -> direction.cross(wheel).z } }
fun rotationalSpeeds(wheels: Wheels, turnRate: Float): Speeds = wheels.map { -turnRate }
fun combineSpeeds(lateral: Speeds, rotational: Speeds): Speeds =
lateral.zip(rotational).map { (lat, rot) -> lat + rot }
fun scaleToWithinMaxSpeed(speeds: Speeds): Speeds =
speeds.map(::abs).max()!!.let { max -> if (max > 1.0) speeds.map { it / max } else speeds }
val maxSum = 1.25f
fun scaleToWithinMaxSum(speeds: Speeds): Speeds =
speeds.map(::abs).sum().let { sum -> if (sum > maxSum) speeds.map { it * (maxSum / sum) } else speeds }
// Magnitude of direction should not exceed 1.0
// direction x axis is pointed in the direction of the first wheel.
// direction y axis is pointed such that the z axis is pointed upward in a right handed coordinate system.
// turnDirection: range from -1.0 to 1.0
// When turnDirection is positive it is CCW.
// Speed is positive it is CCW when facing toward the center of robot.
fun getSpeeds(direction: Vector2, turnDirection: Float): Speeds =
direction.clipToUnit.let { (xDir, yDir) ->
combineSpeeds(
lateralSpeeds(wheels, xDir, yDir),
rotationalSpeeds(wheels, turnDirection)
) pipe
::scaleToWithinMaxSpeed pipe
// Scale down the sum of all wheel speeds to ensure max power draw is not exceeded.
::scaleToWithinMaxSum
}
| mit | 2d1bfe071b96d818b70b6d022728356c | 35.51 | 107 | 0.626404 | 2.911483 | false | false | false | false |
frendyxzc/KHttp | app/src/main/java/vip/frendy/khttpdemo/net/Constants.kt | 1 | 372 | package vip.frendy.khttpdemo.net
/**
* Created by iiMedia on 2017/6/8.
*/
object Constants {
val APP_ID = "5225"
val APP_KEY = "9b836682f204ac0503980acd48b4df21"
val APP_INFO = "app_id=" + APP_ID + "&app_key=" + APP_KEY
val DEFAULT_URL: String = "http://frendy.vip/"
val XW_BASE_URL: String = "http://www.myxianwen.cn/newsapp/pureArticle.action?"
} | mit | d1d0f0e6589c256828edb9ddbe4ea130 | 27.692308 | 83 | 0.655914 | 2.657143 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/crdt/routing/allocation/DefaultAllocationStrategy.kt | 1 | 4353 | package org.mitallast.queue.crdt.routing.allocation
import io.vavr.control.Option
import org.apache.logging.log4j.LogManager
import org.mitallast.queue.common.codec.Message
import org.mitallast.queue.crdt.routing.RoutingTable
import org.mitallast.queue.crdt.routing.fsm.AddReplica
import org.mitallast.queue.crdt.routing.fsm.CloseReplica
import org.mitallast.queue.transport.DiscoveryNode
class DefaultAllocationStrategy : AllocationStrategy {
override fun update(routingTable: RoutingTable): Option<Message> {
val members = routingTable.members
val stats = routingTable.buckets
.flatMap { it.replicas.values() }
.groupBy<DiscoveryNode> { it.member }
var rebalance = false
for (routingBucket in routingTable.buckets) {
// check for new allocations
val open = routingBucket.replicas.values().count { it.isOpened }
if (open < routingTable.replicas) {
logger.info("bucket {} has open {} < {} replicas", routingBucket.index, open, routingTable.replicas)
val bucketMembers = routingBucket.replicas.values().map<DiscoveryNode> { it.member }.toSet()
val available = members.diff(bucketMembers).minBy { a, b ->
val sizeA = stats.get(a).map { it.size() }.getOrElse(0)
val sizeB = stats.get(b).map { it.size() }.getOrElse(0)
Integer.compare(sizeA, sizeB)
}
if (!available.isEmpty) {
val node = available.get()
logger.info("add replica bucket {} {}", routingBucket.index, node)
val request = AddReplica(routingBucket.index, node)
return Option.some(request)
} else {
logger.warn("no available nodes")
}
}
if (routingBucket.replicas.values().exists { it.isClosed }) {
rebalance = true
}
}
if (!rebalance && members.nonEmpty()) {
val minimumBuckets = routingTable.buckets.size() / members.size()
for (m in members) {
val count = routingTable.bucketsCount(m)
if (routingTable.bucketsCount(m) < minimumBuckets) {
logger.warn("node {} buckets {} < min {}", m, count, minimumBuckets)
val memberBuckets = routingTable.buckets.filter { it.exists(m) }
val availableBuckets = routingTable.buckets
.removeAll(memberBuckets)
.filter { bucket ->
bucket.replicas
.values()
.filter { it.member != m } // without current node
.exists { rm -> routingTable.bucketsCount(rm.member) > minimumBuckets }
}
val available = members.filter { t -> availableBuckets.exists { b -> b.exists(t) } }
.maxBy { a, b ->
val sizeA = stats.get(a).map { it.size() }.getOrElse(0)
val sizeB = stats.get(b).map { it.size() }.getOrElse(0)
Integer.compare(sizeA, sizeB)
}
if (available.isDefined) {
val last = available.get()
val closeOpt = availableBuckets.find { bucket -> bucket.exists(last) }
if (closeOpt.isDefined) {
val close = closeOpt.get()
val replica = close.replica(last).get()
logger.info("close replica bucket {} {}", close.index, replica.id)
val request = CloseReplica(close.index, replica.id)
return Option.some(request)
} else {
logger.warn("no bucket to close found")
}
} else {
logger.warn("no available buckets")
}
}
}
}
return Option.none()
}
companion object {
private val logger = LogManager.getLogger(AllocationStrategy::class.java)
}
}
| mit | 5f2da6147c7c1210c6ff04cabbdee9f3 | 45.806452 | 116 | 0.515277 | 5.049884 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/adaptive/ui/activities/AdaptiveStatsActivity.kt | 2 | 2771 | package org.stepic.droid.adaptive.ui.activities
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatDelegate
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.android.synthetic.main.activity_adaptive_stats.*
import org.stepic.droid.R
import org.stepic.droid.adaptive.model.AdaptiveStatsTabs
import org.stepic.droid.adaptive.ui.adapters.AdaptiveStatsViewPagerAdapter
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.base.FragmentActivityBase
import org.stepic.droid.ui.util.initCenteredToolbar
import org.stepic.droid.util.AppConstants
class AdaptiveStatsActivity : FragmentActivityBase() {
companion object {
init {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
private var courseId: Long = 0
private var hasSavedInstanceState: Boolean = false
private lateinit var adapter: AdaptiveStatsViewPagerAdapter
private val onPageChangeListener = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(page: Int) {
if (page == AdaptiveStatsTabs.RATING.ordinal) {
analytic
.reportAmplitudeEvent(
AmplitudeAnalytic.Adaptive.RATING_OPENED,
mapOf(AmplitudeAnalytic.Adaptive.Params.COURSE to courseId.toString())
)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_adaptive_stats)
initCenteredToolbar(R.string.adaptive_stats_title, true)
courseId = intent.getLongExtra(AppConstants.KEY_COURSE_LONG_ID, 0)
hasSavedInstanceState = savedInstanceState != null
adapter = AdaptiveStatsViewPagerAdapter(this, courseId)
pager.adapter = adapter
pager.offscreenPageLimit = adapter.itemCount
TabLayoutMediator(tabLayout, pager) { tab, position ->
tab.setText(AdaptiveStatsTabs.values()[position].fragmentTitleRes)
}.attach()
}
override fun onResume() {
super.onResume()
pager.registerOnPageChangeCallback(onPageChangeListener)
if (!hasSavedInstanceState && pager.currentItem == 0) {
onPageChangeListener.onPageSelected(0)
}
}
override fun onPause() {
pager.unregisterOnPageChangeCallback(onPageChangeListener)
super.onPause()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | a823edb7533a2d88c1683509f52e434b | 35 | 94 | 0.698665 | 5.056569 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/coroutines/suspendFunctionTypeCall/simple.kt | 2 | 934 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
suspend fun suspendHere(v: String): String = suspendCoroutineOrReturn { x ->
x.resume(v)
COROUTINE_SUSPENDED
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
suspend fun foo1(c: suspend () -> Unit) = c()
suspend fun foo2(c: suspend String.() -> Int) = "2".c()
suspend fun foo3(c: suspend (String) -> Int) = c("3")
fun box(): String {
var result = ""
builder {
foo1 {
result = suspendHere("begin#")
}
val q2 = foo2 { result += suspendHere(this) + "#"; 1 }
val q3 = foo3 { result += suspendHere(it); 2 }
if (q2 != 1) throw RuntimeException("fail q2")
if (q3 != 2) throw RuntimeException("fail q3")
}
if (result != "begin#2#3") return "fail: $result"
return "OK"
}
| apache-2.0 | af451266ec4c55d3c9b1d1af91a58b04 | 23.578947 | 76 | 0.604925 | 3.578544 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/magic_links/ui/dialog/MagicLinkDialogFragment.kt | 2 | 2597 | package org.stepik.android.view.magic_links.ui.dialog
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepik.android.presentation.magic_links.MagicLinkPresenter
import org.stepik.android.presentation.magic_links.MagicLinkView
import ru.nobird.android.view.base.ui.extension.argument
import javax.inject.Inject
class MagicLinkDialogFragment : DialogFragment(), MagicLinkView {
companion object {
fun newInstance(url: String, handleUrlInParent: Boolean = false): DialogFragment =
MagicLinkDialogFragment()
.apply {
this.url = url
this.returnUrlToParent = handleUrlInParent
}
const val TAG = "MagicLinkDialogFragment"
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
private val magicLinkPresenter: MagicLinkPresenter by viewModels { viewModelFactory }
private var url: String by argument()
private var returnUrlToParent: Boolean by argument()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
isCancelable = false
return MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.loading)
.setView(R.layout.dialog_progress)
.setCancelable(false)
.create()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
magicLinkPresenter.onData(url)
}
private fun injectComponent() {
App.component()
.magicLinksComponentBuilder()
.build()
.inject(this)
}
override fun onStart() {
super.onStart()
magicLinkPresenter.attachView(this)
}
override fun setState(state: MagicLinkView.State) {
if (state is MagicLinkView.State.Success) {
if (returnUrlToParent) {
(activity as Callback).handleUrl(state.url)
} else {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(state.url)))
}
dismiss()
}
}
override fun onStop() {
magicLinkPresenter.detachView(this)
super.onStop()
}
interface Callback {
fun handleUrl(url: String)
}
} | apache-2.0 | d4454c63eb18daf00bfc1efb27b64a0e | 29.564706 | 90 | 0.671159 | 4.937262 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/notifications/NotificationIDs.kt | 1 | 563 | package org.walleth.notifications
const val NOTIFICATION_ID_DATA_SERVICE = 1247
const val NOTIFICATION_ID_TRANSACTION_NOTIFICATIONS = NOTIFICATION_ID_DATA_SERVICE + 1
const val NOTIFICATION_ID_GETH = NOTIFICATION_ID_TRANSACTION_NOTIFICATIONS +1
const val NOTIFICATION_ID_WALLETCONNECT = NOTIFICATION_ID_GETH +1
const val NOTIFICATION_CHANNEL_ID_DATA_SERVICE = "dataservice"
const val NOTIFICATION_CHANNEL_ID_TRANSACTION_NOTIFICATIONS = "txnotify"
const val NOTIFICATION_CHANNEL_ID_GETH = "geth"
const val NOTIFICATION_CHANNEL_ID_WALLETCONNECT = "walletconnect" | gpl-3.0 | fd648d64246ac3dc1f8535e1daf61dd7 | 46 | 86 | 0.820604 | 3.964789 | false | false | false | false |
da1z/intellij-community | plugins/devkit/testSources/build/PluginModuleCompilationTest.kt | 5 | 5248 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.devkit.build
import com.intellij.compiler.BaseCompilerTestCase
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.util.SmartList
import com.intellij.util.io.TestFileSystemBuilder.fs
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.projectRoots.IdeaJdk
import org.jetbrains.idea.devkit.projectRoots.Sandbox
import java.io.File
import java.util.*
/**
* @author nik
*/
class PluginModuleCompilationTest : BaseCompilerTestCase() {
override fun setUpJdk() {
super.setUpJdk()
runWriteAction {
val table = ProjectJdkTable.getInstance()
var pluginSdk: Sdk = table.createSdk("IDEA plugin SDK", SdkType.findInstance(IdeaJdk::class.java))
val modificator = pluginSdk.sdkModificator
modificator.sdkAdditionalData = Sandbox(getSandboxPath(), testProjectJdk, pluginSdk)
val rootPath = FileUtil.toSystemIndependentName(PathManager.getJarPathForClass(FileUtilRt::class.java)!!)
modificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(rootPath)!!, OrderRootType.CLASSES)
modificator.commitChanges()
table.addJdk(pluginSdk, testRootDisposable)
}
}
private fun getSandboxPath() = "$projectBasePath/sandbox"
fun testMakeSimpleModule() {
val module = setupSimplePluginProject()
make(module)
BaseCompilerTestCase.assertOutput(module, fs().dir("xxx").file("MyAction.class"))
val sandbox = File(getSandboxPath())
assertThat(sandbox).isDirectory()
fs()
.dir("plugins")
.dir("pluginProject")
.dir("META-INF").file("plugin.xml").end()
.dir("classes")
.dir("xxx").file("MyAction.class")
.build().assertDirectoryEqual(sandbox)
}
fun testRebuildSimpleProject() {
setupSimplePluginProject()
val log = rebuild()
assertThat(log.warnings).`as`("Rebuild finished with warnings: ${Arrays.toString(log.warnings)}").isEmpty()
}
fun testPrepareSimpleProjectForDeployment() {
val module = setupSimplePluginProject()
rebuild()
prepareForDeployment(module)
val outputFile = File("$projectBasePath/pluginProject.jar")
assertThat(outputFile).isFile()
fs()
.archive("pluginProject.jar")
.dir("META-INF").file("plugin.xml").file("MANIFEST.MF").end()
.dir("xxx").file("MyAction.class")
.build().assertFileEqual(outputFile)
}
fun testBuildProjectWithJpsModule() {
val module = setupPluginProjectWithJpsModule()
rebuild()
prepareForDeployment(module)
val outputFile = File("$projectBasePath/pluginProject.zip")
assertThat(outputFile).isFile()
fs()
.archive("pluginProject.zip")
.dir("pluginProject")
.dir("lib")
.archive("pluginProject.jar")
.dir("META-INF").file("plugin.xml").file("MANIFEST.MF").end()
.dir("xxx").file("MyAction.class").end()
.end()
.dir("jps")
.archive("jps-plugin.jar").file("Builder.class")
.build().assertFileEqual(outputFile)
}
private fun prepareForDeployment(module: Module) {
val errorMessages = SmartList<String>()
PrepareToDeployAction.doPrepare(module, errorMessages, SmartList<String>())
assertThat(errorMessages).`as`("Building plugin zip finished with errors: $errorMessages").isEmpty()
}
private fun setupSimplePluginProject() = copyAndCreateModule("plugins/devkit/testData/build/simple")
private fun copyAndCreateModule(relativePath: String): Module {
copyToProject(relativePath)
val module = loadModule("$projectBasePath/pluginProject.iml")
assertThat(ModuleType.get(module)).isEqualTo(PluginModuleType.getInstance())
return module
}
private fun setupPluginProjectWithJpsModule(): Module {
val module = copyAndCreateModule("plugins/devkit/testData/build/withJpsModule")
val jpsModule = loadModule("$projectBasePath/jps-plugin/jps-plugin.iml")
ModuleRootModificationUtil.setModuleSdk(jpsModule, testProjectJdk)
return module
}
}
| apache-2.0 | 8a5c5ed400ed90b0238fda6eb85ded07 | 37.028986 | 116 | 0.733232 | 4.424958 | false | true | false | false |
jriley/HackerNews | mobile/src/main/kotlin/dev/jriley/hackernews/splash/SplashViewModel.kt | 1 | 1229 | package dev.jriley.hackernews.splash
import androidx.lifecycle.ViewModel
import dev.jriley.hackernews.data.StoryRepository
import dev.jriley.hackernews.data.StoryRepositoryFactory
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import timber.log.Timber
import java.util.concurrent.TimeUnit
class SplashViewModel(background: Scheduler = Schedulers.io(),
storyRepository: StoryRepository = StoryRepositoryFactory.storyRepository,
private val compositeDisposable: CompositeDisposable = CompositeDisposable(),
private val behaviorSubject: BehaviorSubject<Boolean> = BehaviorSubject.create(),
val loadingObservable: Observable<Boolean> = behaviorSubject) : ViewModel() {
init {
compositeDisposable.add(storyRepository.isLoaded()
.subscribeOn(background)
.delay(3, TimeUnit.SECONDS, background)
.doFinally { compositeDisposable.clear() }
.subscribe({ b -> behaviorSubject.onNext(b) }, { t -> Timber.e(t) }))
}
}
| mpl-2.0 | ca360922706a0d2a3b36d8cb4d3cc266 | 44.518519 | 103 | 0.714402 | 5.185654 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt | 1 | 1704 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder
import java.nio.ByteBuffer
class GetVersionCommand private constructor(
uniqueId: Int,
sequenceNumber: Short,
multiCommandFlag: Boolean
) : HeaderEnabledCommand(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag) {
override val encoded: ByteArray
get() = appendCrc(
ByteBuffer.allocate(LENGTH + HEADER_LENGTH)
.put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag))
.put(commandType.value)
.put(BODY_LENGTH)
.putInt(uniqueId)
.array()
)
override fun toString(): String {
return "GetVersionCommand{" +
"commandType=" + commandType +
", uniqueId=" + uniqueId +
", sequenceNumber=" + sequenceNumber +
", multiCommandFlag=" + multiCommandFlag +
'}'
}
class Builder : HeaderEnabledCommandBuilder<Builder, GetVersionCommand>() {
override fun buildCommand(): GetVersionCommand {
return GetVersionCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag)
}
}
companion object {
const val DEFAULT_UNIQUE_ID = -1 // FIXME move
private const val LENGTH: Short = 6
private const val BODY_LENGTH: Byte = 4
}
}
| agpl-3.0 | 6eb03044315e82478d5c795b7673a9ae | 36.043478 | 119 | 0.671948 | 4.694215 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertJavaCopyPasteProcessor.kt | 1 | 14527 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.conversion.copy
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor
import org.jetbrains.kotlin.idea.codeInsight.KotlinReferenceData
import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.idea.statistics.ConversionType
import org.jetbrains.kotlin.idea.statistics.J2KFusCollector
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.j2k.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import java.awt.datatransfer.Transferable
import kotlin.system.measureTimeMillis
class ConvertJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() {
private val LOG = Logger.getInstance(ConvertJavaCopyPasteProcessor::class.java)
override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> {
try {
if (content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)) {
return listOf(content.getTransferData(CopiedJavaCode.DATA_FLAVOR) as TextBlockTransferableData)
}
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
return listOf()
}
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<TextBlockTransferableData> {
if (file !is PsiJavaFile) return listOf()
return listOf(CopiedJavaCode(file.getText()!!, startOffsets, endOffsets))
}
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<TextBlockTransferableData>
) {
if (DumbService.getInstance(project).isDumb) return
if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return
val data = values.single() as CopiedJavaCode
val document = editor.document
val targetFile = PsiDocumentManager.getInstance(project).getPsiFile(document) as? KtFile ?: return
val useNewJ2k = checkUseNewJ2k(targetFile)
val targetModule = targetFile.module
if (isNoConversionPosition(targetFile, bounds.startOffset)) return
data class Result(
val text: String?,
val referenceData: Collection<KotlinReferenceData>,
val explicitImports: Set<FqName>,
val converterContext: ConverterContext?
)
val dataForConversion = DataForConversion.prepare(data, project)
fun doConversion(): Result {
val result = dataForConversion.elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k)
val referenceData = buildReferenceData(result.text, result.parseContext, dataForConversion.importsAndPackage, targetFile)
val text = if (result.textChanged) result.text else null
return Result(text, referenceData, result.importsToAdd, result.converterContext)
}
fun insertImports(
bounds: TextRange,
referenceData: Collection<KotlinReferenceData>,
explicitImports: Collection<FqName>
): TextRange? {
if (referenceData.isEmpty() && explicitImports.isEmpty()) return bounds
PsiDocumentManager.getInstance(project).commitDocument(document)
val rangeMarker = document.createRangeMarker(bounds)
rangeMarker.isGreedyToLeft = true
rangeMarker.isGreedyToRight = true
KotlinCopyPasteReferenceProcessor()
.processReferenceData(project, editor, targetFile, bounds.startOffset, referenceData.toTypedArray())
runWriteAction {
explicitImports.forEach { fqName ->
targetFile.resolveImportReference(fqName).firstOrNull()?.let {
ImportInsertHelper.getInstance(project).importDescriptor(targetFile, it)
}
}
}
return rangeMarker.range
}
var conversionResult: Result? = null
fun doConversionAndInsertImportsIfUnchanged(): Boolean {
conversionResult = doConversion()
if (conversionResult!!.text != null) return false
insertImports(
bounds.range ?: return true,
conversionResult!!.referenceData,
conversionResult!!.explicitImports
)
return true
}
val textLength = data.startOffsets.indices.sumBy { data.endOffsets[it] - data.startOffsets[it] }
// if the text to convert is short enough, try to do conversion without permission from user and skip the dialog if nothing converted
if (textLength < 1000 && doConversionAndInsertImportsIfUnchanged()) return
fun convert() {
if (conversionResult == null && doConversionAndInsertImportsIfUnchanged()) return
val (text, referenceData, explicitImports) = conversionResult!!
text!! // otherwise we should get true from doConversionAndInsertImportsIfUnchanged and return above
val boundsAfterReplace = runWriteAction {
val startOffset = bounds.startOffset
document.replaceString(startOffset, bounds.endOffset, text)
val endOffsetAfterCopy = startOffset + text.length
editor.caretModel.moveToOffset(endOffsetAfterCopy)
TextRange(startOffset, endOffsetAfterCopy)
}
val newBounds = insertImports(boundsAfterReplace, referenceData, explicitImports)
PsiDocumentManager.getInstance(project).commitDocument(document)
runPostProcessing(project, targetFile, newBounds, conversionResult?.converterContext, useNewJ2k)
conversionPerformed = true
}
if (confirmConvertJavaOnPaste(project, isPlainText = false)) {
val conversionTime = measureTimeMillis {
convert()
}
J2KFusCollector.log(
ConversionType.PSI_EXPRESSION,
ExperimentalFeatures.NewJ2k.isEnabled,
conversionTime,
dataForConversion.elementsAndTexts.linesCount(),
filesCount = 1
)
}
}
private fun buildReferenceData(
text: String,
parseContext: ParseContext,
importsAndPackage: String,
targetFile: KtFile
): Collection<KotlinReferenceData> {
var blockStart: Int
var blockEnd: Int
val fileText = buildString {
append(importsAndPackage)
val (contextPrefix, contextSuffix) = when (parseContext) {
ParseContext.CODE_BLOCK -> "fun ${generateDummyFunctionName(text)}() {\n" to "\n}"
ParseContext.TOP_LEVEL -> "" to ""
}
append(contextPrefix)
blockStart = length
append(text)
blockEnd = length
append(contextSuffix)
}
val dummyFile = KtPsiFactory(targetFile.project).createAnalyzableFile("dummy.kt", fileText, targetFile)
val startOffset = blockStart
val endOffset = blockEnd
return KotlinCopyPasteReferenceProcessor().collectReferenceData(dummyFile, intArrayOf(startOffset), intArrayOf(endOffset)).map {
it.copy(startOffset = it.startOffset - startOffset, endOffset = it.endOffset - startOffset)
}
}
private fun generateDummyFunctionName(convertedCode: String): String {
var i = 0
while (true) {
val name = "dummy$i"
if (convertedCode.indexOf(name) < 0) return name
i++
}
}
companion object {
@get:TestOnly
var conversionPerformed: Boolean = false
}
}
internal class ConversionResult(
val text: String,
val parseContext: ParseContext,
val importsToAdd: Set<FqName>,
val textChanged: Boolean,
val converterContext: ConverterContext?
)
internal fun ElementAndTextList.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult {
val converter =
J2kConverterExtension.extension(useNewJ2k).createJavaToKotlinConverter(
project,
targetModule,
ConverterSettings.defaultSettings,
IdeaJavaToKotlinServices
)
val inputElements = toList().filterIsInstance<PsiElement>()
val (results, _, converterContext) =
ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable<Result, Exception> {
runReadAction { converter.elementsToKotlin(inputElements) }
},
JavaToKotlinAction.title,
false,
project
)
val importsToAdd = LinkedHashSet<FqName>()
var resultIndex = 0
val convertedCodeBuilder = StringBuilder()
val originalCodeBuilder = StringBuilder()
var parseContext: ParseContext? = null
this.process(object : ElementsAndTextsProcessor {
override fun processElement(element: PsiElement) {
val originalText = element.text
originalCodeBuilder.append(originalText)
val result = results[resultIndex++]
if (result != null) {
convertedCodeBuilder.append(result.text)
if (parseContext == null) { // use parse context of the first converted element as parse context for the whole text
parseContext = result.parseContext
}
importsToAdd.addAll(result.importsToAdd)
} else { // failed to convert element to Kotlin, insert "as is"
convertedCodeBuilder.append(originalText)
}
}
override fun processText(string: String) {
originalCodeBuilder.append(string)
convertedCodeBuilder.append(string)
}
})
val convertedCode = convertedCodeBuilder.toString()
val originalCode = originalCodeBuilder.toString()
return ConversionResult(
convertedCode,
parseContext ?: ParseContext.CODE_BLOCK,
importsToAdd,
convertedCode != originalCode,
converterContext
)
}
internal fun isNoConversionPosition(file: KtFile, offset: Int): Boolean {
if (offset == 0) return false
val token = file.findElementAt(offset - 1) ?: return true
if (token !is PsiWhiteSpace && token.endOffset != offset) return true // pasting into the middle of token
for (element in token.parentsWithSelf) {
when (element) {
is PsiComment -> return element.node.elementType == KtTokens.EOL_COMMENT || offset != element.endOffset
is KtStringTemplateEntryWithExpression -> return false
is KtStringTemplateExpression -> return true
}
}
return false
}
internal fun confirmConvertJavaOnPaste(project: Project, isPlainText: Boolean): Boolean {
if (KotlinEditorOptions.getInstance().isDonTShowConversionDialog) return true
val dialog = KotlinPasteFromJavaDialog(project, isPlainText)
dialog.show()
return dialog.isOK
}
fun ElementAndTextList.linesCount() =
toList()
.filterIsInstance<PsiElement>()
.sumBy { StringUtil.getLineBreakCount(it.text) }
fun checkUseNewJ2k(targetFile: KtFile): Boolean {
if (targetFile is KtCodeFragment) return false
return ExperimentalFeatures.NewJ2k.isEnabled
}
fun runPostProcessing(
project: Project,
file: KtFile,
bounds: TextRange?,
converterContext: ConverterContext?,
useNewJ2k: Boolean
) {
val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true)
if (useNewJ2k) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val processor =
J2kConverterExtension.extension(useNewJ2k).createWithProgressProcessor(
ProgressManager.getInstance().progressIndicator!!,
emptyList(),
postProcessor.phasesCount
)
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
) { phase, description ->
processor.updateState(0, phase, description)
}
},
@Suppress("DialogTitleCapitalization") KotlinBundle.message("copy.text.convert.java.to.kotlin.title"),
true,
project
)
} else {
AfterConversionPass(project, postProcessor)
.run(
file,
converterContext,
bounds
)
}
} | apache-2.0 | 03163036ff2fafa2fde94d2f43ac78d0 | 37.332454 | 141 | 0.668479 | 5.412444 | false | false | false | false |
aw3s0me/countries | server/src/main/kotlin/de/korovin/countries/controllers/CountryController.kt | 1 | 1439 | package de.korovin.countries.controllers
import de.korovin.countries.models.Country
import de.korovin.countries.services.CSVService
import de.korovin.countries.services.CountryService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
/**
* Created by aw3s0 on 10/11/2017.
* Main controller for countries
*/
@RestController
@CrossOrigin(origins = arrayOf("http://localhost:4200"))
@RequestMapping("/country")
class CountryController(
private @Autowired var service: CountryService,
private @Autowired var csvService: CSVService) {
/**
* Fetch all countries as list
*/
@RequestMapping("/",
method = arrayOf(RequestMethod.GET))
@ResponseStatus(HttpStatus.OK)
fun findAll(): List<Country> {
return service.getAll()
}
@RequestMapping("/csv",
method = arrayOf(RequestMethod.GET))
@ResponseStatus(HttpStatus.OK)
fun findAllCSV(): ResponseEntity<String> {
val res = service.getAll()
val csv = csvService.convertList(res.toMutableList())
val headers = HttpHeaders()
headers.contentType = MediaType("text", "csv")
return ResponseEntity(csv, headers, HttpStatus.OK)
}
}
| apache-2.0 | 0748015d1488e3aaa766e60c83403d61 | 30.282609 | 61 | 0.720639 | 4.482866 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/tree/Func.kt | 1 | 3957 | package com.bajdcc.LALR1.grammar.tree
import com.bajdcc.LALR1.grammar.codegen.ICodegen
import com.bajdcc.LALR1.grammar.runtime.RuntimeInst
import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder
import com.bajdcc.LALR1.grammar.tree.closure.IClosureScope
import com.bajdcc.util.lexer.token.KeywordType
import com.bajdcc.util.lexer.token.Token
/**
* 【语义分析】函数
* [name]:名称(Lambda记号)
*
* @author bajdcc
*/
class Func(var name: Token) : IExp {
/**
* 真实名称(变量名)
*/
var realName: String = ""
/**
* 类方法名
*/
private var methodName: String = ""
/**
* 参数
*/
var params = mutableListOf<Token>()
/**
* 函数主体Block
*/
var block: Block? = null
/**
* 文档
*/
private var doc: List<Token>? = null
/**
* 外部化
*/
var isExtern = false
/**
* 是否支持YIELD
*/
var isYield = false
val refName: String
get() = if (name.toRealString() == realName) {
if (methodName.isNotEmpty()) "$realName#$methodName" else realName
} else name.toRealString() + "$" + realName
fun setMethodName(methodName: String) {
this.methodName = methodName
}
fun getDoc(): String {
if (doc == null || doc!!.isEmpty()) {
return "过程无文档"
}
val sb = StringBuilder()
for (token in doc!!) {
sb.append(token.obj.toString())
sb.append(System.lineSeparator())
}
return sb.toString()
}
fun setDoc(doc: List<Token>) {
this.doc = doc
}
override fun isConstant(): Boolean {
return false
}
override fun isEnumerable(): Boolean {
return isYield
}
override fun simplify(recorder: ISemanticRecorder): IExp {
return this
}
override fun analysis(recorder: ISemanticRecorder) {
block!!.analysis(recorder)
}
override fun genCode(codegen: ICodegen) {
codegen.genFuncEntry(refName)
codegen.genCode(RuntimeInst.inop)
if (name.toRealString() == realName) {
codegen.genCode(RuntimeInst.ipush, codegen.genDataRef(realName))
codegen.genCode(RuntimeInst.irefun)
}
val start = codegen.codeIndex
var i = 0
for (token in params) {
codegen.genCode(RuntimeInst.iloada, i)
codegen.genCode(RuntimeInst.ipush, codegen.genDataRef(token.obj!!))
codegen.genCode(RuntimeInst.ialloc)
codegen.genCode(RuntimeInst.ipop)
i++
}
block!!.genCode(codegen)
val end = codegen.codeIndex - 1
if (start <= end) {
codegen.genDebugInfo(start, end, this.toString())
}
codegen.genCode(RuntimeInst.inop)
}
override fun toString(): String {
return print(StringBuilder())
}
override fun print(prefix: StringBuilder): String {
val sb = StringBuilder()
if (isYield) {
sb.append(KeywordType.YIELD.desc)
sb.append(" ")
}
sb.append(KeywordType.FUNCTION.desc)
sb.append(" ")
sb.append(realName)
if (methodName.isNotEmpty())
sb.append(" [ ").append(methodName).append(" ] ")
sb.append("(")
for (param in params) {
sb.append(param.toRealString())
sb.append(", ")
}
if (!params.isEmpty()) {
sb.deleteCharAt(sb.length - 1)
sb.deleteCharAt(sb.length - 1)
}
sb.append(") ")
if (block != null) {
sb.append(block!!.print(prefix))
}
return sb.toString()
}
override fun addClosure(scope: IClosureScope) {
for (param in params) {
scope.addDecl(param.obj!!)
}
block!!.addClosure(scope)
}
override fun setYield() {
}
}
| mit | fe1c2382d484185da28d57e5a4a4d1b8 | 23.283019 | 79 | 0.558664 | 4.051417 | false | false | false | false |
75py/Aplin | app/src/main/java/com/nagopy/android/aplin/ui/prefs/UserDataStore.kt | 1 | 1197 | package com.nagopy.android.aplin.ui.prefs
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class UserDataStore(dataStore: DataStore<Preferences>) {
private val displayItemsKey = stringSetPreferencesKey(DisplayItem.KEY)
private val sortOrderKey = stringPreferencesKey(SortOrder.KEY)
val displayItems: Flow<List<DisplayItem>> =
dataStore.data.map { it[displayItemsKey] ?: emptySet() }.map {
it.mapNotNull { v ->
DisplayItem.values().firstOrNull { item -> item.name == v }
}
}
val sortOrder: Flow<SortOrder> =
dataStore.data.map { it[sortOrderKey] ?: SortOrder.DEFAULT.name }.map {
SortOrder.values().firstOrNull { item -> item.name == it } ?: SortOrder.DEFAULT
}
}
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
| apache-2.0 | 5e348d641641aeb002e8437706ac4039 | 38.9 | 91 | 0.737678 | 4.603846 | false | false | false | false |
android/architecture-components-samples | LiveDataSample/app/src/androidTest/java/com/android/example/livedata/DataBindingIdlingResource.kt | 1 | 3956 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.livedata
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentActivity
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.IdlingResource
import androidx.test.ext.junit.rules.ActivityScenarioRule
import java.util.UUID
/**
* An espresso idling resource implementation that reports idle status for all data binding
* layouts. Data Binding uses a mechanism to post messages which Espresso doesn't track yet.
*
* Since this application only uses fragments, the resource only checks the fragments and their
* children instead of the whole view tree.
*
* Tracking bug: https://github.com/android/android-test/issues/317
*/
class DataBindingIdlingResource(
activityScenarioRule: ActivityScenarioRule<out FragmentActivity>
) : IdlingResource {
// list of registered callbacks
private val idlingCallbacks = mutableListOf<IdlingResource.ResourceCallback>()
// give it a unique id to workaround an espresso bug where you cannot register/unregister
// an idling resource w/ the same name.
private val id = UUID.randomUUID().toString()
// holds whether isIdle is called and the result was false. We track this to avoid calling
// onTransitionToIdle callbacks if Espresso never thought we were idle in the first place.
private var wasNotIdle = false
lateinit var activity: FragmentActivity
override fun getName() = "DataBinding $id"
init {
monitorActivity(activityScenarioRule.scenario)
}
override fun isIdleNow(): Boolean {
val idle = !getBindings().any { it.hasPendingBindings() }
@Suppress("LiftReturnOrAssignment")
if (idle) {
if (wasNotIdle) {
// notify observers to avoid espresso race detector
idlingCallbacks.forEach { it.onTransitionToIdle() }
}
wasNotIdle = false
} else {
wasNotIdle = true
// check next frame
activity.findViewById<View>(android.R.id.content).postDelayed({
isIdleNow
}, 16)
}
return idle
}
override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) {
idlingCallbacks.add(callback)
}
/**
* Sets the activity from an [ActivityScenario] to be used from [DataBindingIdlingResource].
*/
private fun monitorActivity(
activityScenario: ActivityScenario<out FragmentActivity>
) {
activityScenario.onActivity {
this.activity = it
}
}
/**
* Find all binding classes in all currently available fragments.
*/
private fun getBindings(): List<ViewDataBinding> {
val fragments = (activity as? FragmentActivity)
?.supportFragmentManager
?.fragments
val bindings =
fragments?.mapNotNull {
it.view?.getBinding()
} ?: emptyList()
val childrenBindings = fragments?.flatMap { it.childFragmentManager.fragments }
?.mapNotNull { it.view?.getBinding() } ?: emptyList()
return bindings + childrenBindings
}
}
private fun View.getBinding(): ViewDataBinding? = DataBindingUtil.getBinding(this)
| apache-2.0 | 13832681893d1dc02924fb005bc69c25 | 34.963636 | 96 | 0.69186 | 5.03949 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentMultipleEntityImpl.kt | 1 | 9280 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentMultipleEntityImpl : ParentMultipleEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentMultipleEntity::class.java,
ChildMultipleEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField
var _parentData: String? = null
override val parentData: String
get() = _parentData!!
override val children: List<ChildMultipleEntity>
get() = snapshot.extractOneToManyChildren<ChildMultipleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentMultipleEntityData?) : ModifiableWorkspaceEntityBase<ParentMultipleEntity>(), ParentMultipleEntity.Builder {
constructor() : this(ParentMultipleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentMultipleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isParentDataInitialized()) {
error("Field ParentMultipleEntity#parentData should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field ParentMultipleEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field ParentMultipleEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ParentMultipleEntity
this.entitySource = dataSource.entitySource
this.parentData = dataSource.parentData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentData: String
get() = getEntityData().parentData
set(value) {
checkModificationAllowed()
getEntityData().parentData = value
changedProperty.add("parentData")
}
// List of non-abstract referenced types
var _children: List<ChildMultipleEntity>? = emptyList()
override var children: List<ChildMultipleEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildMultipleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<ChildMultipleEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildMultipleEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): ParentMultipleEntityData = result ?: super.getEntityData() as ParentMultipleEntityData
override fun getEntityClass(): Class<ParentMultipleEntity> = ParentMultipleEntity::class.java
}
}
class ParentMultipleEntityData : WorkspaceEntityData<ParentMultipleEntity>() {
lateinit var parentData: String
fun isParentDataInitialized(): Boolean = ::parentData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentMultipleEntity> {
val modifiable = ParentMultipleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentMultipleEntity {
val entity = ParentMultipleEntityImpl()
entity._parentData = parentData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentMultipleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ParentMultipleEntity(parentData, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentMultipleEntityData
if (this.entitySource != other.entitySource) return false
if (this.parentData != other.parentData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentMultipleEntityData
if (this.parentData != other.parentData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 31b2cee563759e9e3e0e332200b968e3 | 35.679842 | 188 | 0.684698 | 5.417396 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/HistoryFloat.kt | 1 | 712 | package org.snakeskin.utility.value
class HistoryFloat(initialValue: Float = Float.NaN) {
var last = initialValue
@Synchronized get
private set
var current = initialValue
@Synchronized get
private set
@Synchronized
fun update(newValue: Float) {
last = current
current = newValue
}
/**
* Returns true if the value changed from its previous value since the last call to "update"
*/
fun changed(): Boolean {
return current != last
}
//Numeric operations
/**
* Returns the difference between the current value and the last value
*/
fun delta(): Float {
return current - last
}
} | gpl-3.0 | a73093ceec27b9512853f88cd41cfa1e | 20.606061 | 96 | 0.609551 | 5.014085 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/podorozhnik/PodorozhnikTrip.kt | 1 | 3250 | package au.id.micolous.metrodroid.transit.podorozhnik
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReader
@Parcelize
internal class PodorozhnikTrip(private val mTimestamp: Int,
private val mFare: Int?,
private val mLastTransport: Int,
private val mLastValidator: Int): Trip() {
override val startTimestamp: Timestamp?
get() = PodorozhnikTransitData.convertDate(mTimestamp)
override val fare: TransitCurrency?
get() = if (mFare != null) {
TransitCurrency.RUB(mFare)
} else {
null
}
// TODO: Handle trams
override val mode: Trip.Mode
get() {
if (mLastTransport == TRANSPORT_METRO && mLastValidator == 0)
return Trip.Mode.BUS
return if (mLastTransport == TRANSPORT_METRO) Trip.Mode.METRO else Trip.Mode.BUS
}
// TODO: handle other transports better.
override val startStation: Station?
get() {
var stationId = mLastValidator or (mLastTransport shl 16)
if (mLastTransport == TRANSPORT_METRO && mLastValidator == 0)
return null
if (mLastTransport == TRANSPORT_METRO) {
val gate = stationId and 0x3f
stationId = stationId and 0x3f.inv()
return StationTableReader.getStation(PODOROZHNIK_STR, stationId, (mLastValidator shr 6).toString()).addAttribute(Localizer.localizeString(R.string.podorozhnik_gate, gate))
}
return StationTableReader.getStation(PODOROZHNIK_STR, stationId,
"$mLastTransport/$mLastValidator")
}
override fun getAgencyName(isShort: Boolean) =
// Always include "Saint Petersburg" in names here to distinguish from Troika (Moscow)
// trips on hybrid cards
when (mLastTransport) {
// Some validators are misconfigured and show up as Metro, station 0, gate 0.
// Assume bus.
TRANSPORT_METRO -> if (mLastValidator == 0) Localizer.localizeFormatted(R.string.led_bus) else Localizer.localizeFormatted(R.string.led_metro)
TRANSPORT_BUS, TRANSPORT_BUS_MOBILE -> Localizer.localizeFormatted(R.string.led_bus)
TRANSPORT_SHARED_TAXI -> Localizer.localizeFormatted(R.string.led_shared_taxi)
// TODO: Handle trams
else -> Localizer.localizeFormatted(R.string.unknown_format, mLastTransport)
}
companion object {
const val PODOROZHNIK_STR = "podorozhnik"
const val TRANSPORT_METRO = 1
// Some buses use fixed validators while others
// have a fixed validator and they have different codes
private const val TRANSPORT_BUS_MOBILE = 3
private const val TRANSPORT_BUS = 4
private const val TRANSPORT_SHARED_TAXI = 7
}
}
| gpl-3.0 | 1dc3a1b9234c28c4fe5cfc4a426a2299 | 43.520548 | 187 | 0.648923 | 4.310345 | false | false | false | false |
hermantai/samples | android/AskQuestion/app/src/main/java/com/longgamemindset/askquestion/ui/theme/Type.kt | 1 | 808 | package com.longgamemindset.askquestion.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | apache-2.0 | 58364c65b6ed214a982985ca796fc17d | 27.892857 | 50 | 0.695545 | 4.391304 | false | false | false | false |
elpassion/cloud-timer-android | app/src/main/java/pl/elpassion/cloudtimer/signin/SignInActivity.kt | 1 | 2977 | package pl.elpassion.cloudtimer.signin
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import pl.elpassion.cloudtimer.R
import pl.elpassion.cloudtimer.base.CloudTimerActivity
import pl.elpassion.cloudtimer.common.applySchedulers
import pl.elpassion.cloudtimer.common.emailRegex
import pl.elpassion.cloudtimer.domain.Timer
import pl.elpassion.cloudtimer.groups.GroupActivity
import pl.elpassion.cloudtimer.login.authtoken.AuthTokenSharedPreferences.isLoggedIn
class SignInActivity : CloudTimerActivity() {
companion object {
private val timerToShareKey = "timerToShareKey"
fun start(context: Context, timer: Timer) {
val intent = Intent(context, SignInActivity::class.java)
intent.putExtra(timerToShareKey, timer)
context.startActivity(intent)
}
}
private val emailInput by lazy { findViewById(R.id.email_input) as EditText }
private val loginButton by lazy { findViewById(R.id.send_activation_email) as Button }
private val errorMessageTextView by lazy { findViewById(R.id.error_message) as TextView }
private val timer by lazy { intent.getParcelableExtra<Timer>(timerToShareKey) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signin)
loginButton.setOnClickListener {
handleInsertedEmail(emailInput.text.toString())
}
}
override fun onResume() {
if (isLoggedIn()) {
GroupActivity.start(this)
finish()
}
super.onResume()
}
private fun handleInsertedEmail(email: String) {
if (emailRegex.matches(email))
signIn(email)
else
displayError(incorrectEmail)
}
private fun signIn(email: String) {
loginButton.isEnabled = false
val signInObject = SignInViaEmail(email)
signInViaEmailService.singIn(signInObject).applySchedulers().subscribe(onSigninSuccess, onSigninFailure)
}
private val onSigninSuccess = { any: Any ->
loginButton.isEnabled = true
val emailWasSentMessage = getString(R.string.email_was_sent_message)
Snackbar.make(emailInput, emailWasSentMessage, Snackbar.LENGTH_INDEFINITE).show()
}
private val onSigninFailure = { ex: Throwable ->
loginButton.isEnabled = true
displayError(connectionError)
}
private val connectionError: String
get() = this.getString(R.string.connection_error)
private val incorrectEmail: String
get() = this.getString(R.string.incorrect_email)
private fun displayError(errorMessage: String) {
errorMessageTextView.visibility = View.VISIBLE
errorMessageTextView.text = errorMessage
}
} | apache-2.0 | cd1ee92424077db9baf1a66644678d69 | 34.035294 | 112 | 0.715485 | 4.587057 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/card/iso7816/ISO7816File.kt | 1 | 3030 | /*
* ISO7816File.kt
*
* Copyright 2018 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.card.iso7816
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.serializers.XMLId
import au.id.micolous.metrodroid.serializers.XMLIgnore
import au.id.micolous.metrodroid.serializers.XMLListIdx
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.ui.ListItemRecursive
import au.id.micolous.metrodroid.util.ImmutableByteArray
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* Represents a file on a Calypso card.
*/
@Serializable
@XMLIgnore("selector")
data class ISO7816File internal constructor(
@XMLId("data")
val binaryData: ImmutableByteArray? = null,
@XMLListIdx("index")
private val records: Map<Int, ImmutableByteArray> = emptyMap(),
val fci: ImmutableByteArray? = null) {
@Transient
val recordList get() = records.entries.sortedBy { it.key }.map { it.value }.toList()
/**
* Gets a record for a given index.
* @param index Record index to retrieve.
* @return ISO7816Record with that index, or null if not present.
*/
fun getRecord(index: Int): ImmutableByteArray? = records[index]
fun showRawData(selectorStr: String): ListItem {
val recList = mutableListOf<ListItem>()
if (binaryData != null)
recList.add(ListItemRecursive.collapsedValue(Localizer.localizeString(R.string.binary_title_format),
binaryData.toHexDump()))
if (fci != null)
recList.add(ListItemRecursive(Localizer.localizeString(R.string.file_fci), null,
ISO7816TLV.infoWithRaw(fci)))
for ((idx, data) in records)
recList.add(ListItemRecursive.collapsedValue(Localizer.localizeString(R.string.record_title_format, idx),
data.toHexDump()))
return ListItemRecursive(Localizer.localizeString(R.string.file_title_format, selectorStr),
Localizer.localizePlural(R.plurals.record_count, records.size, records.size),
recList)
}
override fun toString() = "<$TAG: data=$binaryData, records=$records>"
companion object {
private const val TAG = "ISO7816File"
}
}
| gpl-3.0 | 21744653b2d6ef2e887ec3d673769529 | 39.4 | 117 | 0.708581 | 4.150685 | false | false | false | false |
hermantai/samples | kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/Aquarium/main.kt | 1 | 448 | package Aquarium
fun main (args: Array<String>) {
buildAquarium()
}
fun buildAquarium() {
val myAquarium = Aquarium()
println("Length: ${myAquarium.length}")
myAquarium.length = 20
println("Length: ${myAquarium.length}")
println("Length: ${myAquarium.volume}")
val smallAquarium = Aquarium(length = 20, width = 15, height = 30)
print("Volume: ${smallAquarium.volume} litres")
val myAquarium2 = Aquarium(numberOfFish = 30)
} | apache-2.0 | 4693574cdeabe804842bb0d94d40ee11 | 20.380952 | 68 | 0.694196 | 3.068493 | false | false | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/ui/viewModel/ListColumnViewModel.kt | 1 | 1963 | package io.github.bkmioa.nexusrss.ui.viewModel
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import io.github.bkmioa.nexusrss.R
import io.github.bkmioa.nexusrss.base.BaseEpoxyHolder
import kotlinx.android.synthetic.main.item_list_column.view.*
@EpoxyModelClass(layout = R.layout.item_list_column)
abstract class ListColumnViewModel(
@EpoxyAttribute @JvmField val title: String,
@EpoxyAttribute @JvmField val selectedIndex: Int,
@EpoxyAttribute @JvmField val data: List<String>
) : EpoxyModelWithHolder<ListColumnViewModel.ViewHolder>() {
@EpoxyAttribute(hash = false)
var onItemClickListener: OnItemSelectedListener? = null
override fun bind(holder: ViewHolder) {
super.bind(holder)
with(holder) {
textView.text = title
spinner.adapter = ArrayAdapter(itemView.context, android.R.layout.simple_spinner_dropdown_item, data)
spinner.setSelection(selectedIndex)
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
onItemClickListener?.onItemSelected(position)
}
}
}
}
override fun getSpanSize(totalSpanCount: Int, position: Int, itemCount: Int): Int {
return totalSpanCount
}
interface OnItemSelectedListener {
fun onItemSelected(index: Int)
}
class ViewHolder : BaseEpoxyHolder() {
val textView: TextView by lazy { itemView.textViewName }
val spinner: Spinner by lazy { itemView.spinner }
}
}
| apache-2.0 | e1122e93304d0ed9999b7ae2de89517b | 34.053571 | 113 | 0.705553 | 4.823096 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/di/ViewModelDagger.kt | 1 | 1572 | package csumissu.weatherforecast.di
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import csumissu.weatherforecast.ui.forecasts.ForecastsViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
/**
* @author yxsun
* @since 07/08/2017
*/
@Module
abstract class ViewModelModule {
@Binds
abstract fun bindViewModelFactory(viewModelFactory: ViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(ForecastsViewModel::class)
abstract fun bindForecastListViewModel(forecastListViewMode: ForecastsViewModel): ViewModel
}
@Singleton
class ViewModelFactory
@Inject constructor(private val mCreators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>)
: ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = mCreators[modelClass]
if (creator == null) {
for ((key, value) in mCreators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class " + modelClass)
}
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
} | mit | 968699209c96ef6b577fe0af6ad16200 | 27.6 | 112 | 0.674936 | 4.807339 | false | false | false | false |
jtlalka/imager | src/test/kotlin/net/tlalka/imager/utils/GeoUtilsTest.kt | 1 | 3537 | package net.tlalka.imager.utils
import net.tlalka.imager.data.GeoImage
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.jupiter.api.Assertions.assertEquals
import java.io.File
object GeoUtilsTest: Spek({
val DISTANCE_DELTA = 0.00001
given("two images with the same location") {
val image1 = GeoImage(File("."), 55.0, 22.1, 1)
val image2 = GeoImage(File("."), 55.0, 22.1, 1)
on("calculate distance in kilometers") {
val result = GeoUtils.distanceInKm(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return 0") {
assertEquals(0.0, result, DISTANCE_DELTA)
}
}
on("calculate distance in meters") {
val result = GeoUtils.distanceInM(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return 0") {
assertEquals(0.0, result, DISTANCE_DELTA)
}
}
on("calculate bearing in degrees") {
val result = GeoUtils.bearingInDeg(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return 0") {
assertEquals(0.0, result, DISTANCE_DELTA)
}
}
on("calculate bearing in radians") {
val result = GeoUtils.bearingInRad(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return 0") {
assertEquals(0.0, result, DISTANCE_DELTA)
}
}
}
given("two images with different location") {
val image1 = GeoImage(File("."), 52.2297, 21.0122, 1)
val image2 = GeoImage(File("."), 52.2296, 21.0122, 1)
on("calculate distance in meters") {
val result = GeoUtils.distanceInM(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return distance in meters") {
assertEquals(11.11949, result, DISTANCE_DELTA)
}
}
on("calculate distance in kilometers") {
val result = GeoUtils.distanceInKm(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return distance in kilometers") {
assertEquals(0.01111, result, DISTANCE_DELTA)
}
}
on("calculate bearing in degrees") {
val result = GeoUtils.bearingInDeg(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should bearing value") {
assertEquals(180.0, result, DISTANCE_DELTA)
}
}
on("calculate bearing in radians") {
val result = GeoUtils.bearingInRad(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should bearing value") {
assertEquals(Math.PI, result, DISTANCE_DELTA)
}
}
}
given("two images with large distance location") {
val image1 = GeoImage(File("."), 52.2297, 21.0122, 1)
val image2 = GeoImage(File("."), 35.6895, 139.6917, 1)
on("calculate distance in kilometers") {
val result = GeoUtils.distanceInKm(image1.latitude, image1.longitude, image2.latitude, image2.longitude)
it("should return distance in kilometers") {
assertEquals(8578.56907, result, DISTANCE_DELTA)
}
}
}
}) | mit | 63b5f7303cdaab39dd2e43307b02a288 | 33.019231 | 116 | 0.605315 | 4.103248 | false | false | false | false |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/framework/WebSymbolsFramework.kt | 2 | 2288 | // 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.webSymbols.framework
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.KeyedExtensionCollector
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.webSymbols.SymbolKind
import com.intellij.webSymbols.SymbolNamespace
import com.intellij.webSymbols.query.WebSymbolNamesProvider
import com.intellij.webSymbols.context.WebSymbolsContext
import com.intellij.webSymbols.context.WebSymbolsContext.Companion.KIND_FRAMEWORK
import javax.swing.Icon
abstract class WebSymbolsFramework {
lateinit var id: String
internal set
abstract val displayName: String
open val icon: Icon? get() = null
open fun getNames(namespace: SymbolNamespace,
kind: SymbolKind,
name: String,
target: WebSymbolNamesProvider.Target): List<String> = emptyList()
fun isInContext(location: PsiElement): Boolean = WebSymbolsContext.get(KIND_FRAMEWORK, location) == id
fun isInContext(location: VirtualFile, project: Project): Boolean = WebSymbolsContext.get(KIND_FRAMEWORK, location, project) == id
companion object {
private val WEB_FRAMEWORK_EP = object : KeyedExtensionCollector<WebSymbolsFramework, String>("com.intellij.webSymbols.framework") {
val all get() = extensions.asSequence().map { it.instance }
}
@JvmStatic
fun get(id: String): WebSymbolsFramework = WEB_FRAMEWORK_EP.findSingle(id) ?: UnregisteredWebFramework(id)
@JvmStatic
fun inLocation(location: VirtualFile, project: Project) = WebSymbolsContext.get(KIND_FRAMEWORK, location, project)?.let { get(it) }
@JvmStatic
fun inLocation(location: PsiElement) = WebSymbolsContext.get(KIND_FRAMEWORK, location)?.let { get(it) }
@JvmStatic
val all: List<WebSymbolsFramework>
get() = WEB_FRAMEWORK_EP.all.toList()
@JvmStatic
internal val allAsSequence: Sequence<WebSymbolsFramework>
get() = WEB_FRAMEWORK_EP.all
}
private class UnregisteredWebFramework(id: String) : WebSymbolsFramework() {
init {
this.id = id
}
override val displayName: String
get() = id
}
} | apache-2.0 | edb1cb0bc0cf5aba24580bb189850215 | 32.661765 | 135 | 0.738199 | 4.4 | false | false | false | false |
GunoH/intellij-community | plugins/repository-search/src/main/java/org/jetbrains/idea/maven/onlinecompletion/model/MavenRepositoryArtifactInfo.kt | 2 | 1440 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.onlinecompletion.model
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.maven.model.MavenCoordinate
import org.jetbrains.idea.reposearch.RepositoryArtifactData
class MavenRepositoryArtifactInfo(
private val groupId: String,
private val artifactId: String,
val items: Array<MavenDependencyCompletionItem>
) : MavenCoordinate, RepositoryArtifactData {
constructor(
groupId: String,
artifactId: String,
versions: Collection<String>
) : this(
groupId = groupId,
artifactId = artifactId,
items = versions.map { MavenDependencyCompletionItem(groupId, artifactId, it) }.toTypedArray()
)
@NlsSafe
override fun getGroupId() = groupId
@NlsSafe
override fun getArtifactId() = artifactId
@NlsSafe
override fun getVersion() = items.firstOrNull()?.version
@NlsSafe
override fun getKey() = "$groupId:$artifactId"
@NonNls
override fun toString() = "maven($groupId:$artifactId:$version ${items.size} total)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as MavenRepositoryArtifactInfo
return key == other.key
}
override fun hashCode() = key.hashCode()
} | apache-2.0 | e8b74237375b25aea13afca660a34e40 | 29.020833 | 140 | 0.744444 | 4.5 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/test-src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageVersionComparator.kt | 6 | 1964 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.PackageVersionNormalizer
import kotlinx.coroutines.runBlocking
internal object PackageVersionComparator : Comparator<PackageVersion> {
val normalizer = PackageVersionNormalizer()
override fun compare(first: PackageVersion?, second: PackageVersion?): Int {
when {
first == null && second != null -> return -1
first != null && second == null -> return 1
first == null && second == null -> return 0
first is PackageVersion.Missing && second !is PackageVersion.Missing -> return -1
first !is PackageVersion.Missing && second is PackageVersion.Missing -> return 1
first is PackageVersion.Missing && second is PackageVersion.Missing -> return 0
}
return compareNamed(first as PackageVersion.Named, second as PackageVersion.Named)
}
private fun compareNamed(first: PackageVersion.Named, second: PackageVersion.Named): Int {
return runBlocking { normalizer.parse(first).compareTo(normalizer.parse(second)) }
}
}
| apache-2.0 | e5c5c675042ea490c68490bba3fb8082 | 45.761905 | 105 | 0.661405 | 5.154856 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryBackgroundColors.kt | 1 | 2983 | package org.thoughtcrime.securesms.mediasend.v2.text
import org.thoughtcrime.securesms.conversation.colors.ChatColors
object TextStoryBackgroundColors {
private val backgroundColors: List<ChatColors> = listOf(
ChatColors.forGradient(
id = ChatColors.Id.NotSet,
linearGradient = ChatColors.LinearGradient(
degrees = 191.41f,
colors = intArrayOf(0xFFF53844.toInt(), 0xFF42378F.toInt()),
positions = floatArrayOf(0f, 1.0f)
)
),
ChatColors.forGradient(
id = ChatColors.Id.NotSet,
linearGradient = ChatColors.LinearGradient(
degrees = 192.04f,
colors = intArrayOf(0xFFF04CE6.toInt(), 0xFF0E2FDD.toInt()),
positions = floatArrayOf(0.0f, 1.0f)
),
),
ChatColors.forGradient(
id = ChatColors.Id.NotSet,
linearGradient = ChatColors.LinearGradient(
degrees = 175.46f,
colors = intArrayOf(0xFFFFC044.toInt(), 0xFFFE5C38.toInt()),
positions = floatArrayOf(0f, 1f)
)
),
ChatColors.forGradient(
id = ChatColors.Id.NotSet,
linearGradient = ChatColors.LinearGradient(
degrees = 180f,
colors = intArrayOf(0xFF0093E9.toInt(), 0xFF80D0C7.toInt()),
positions = floatArrayOf(0.0f, 1.0f)
)
),
ChatColors.forGradient(
id = ChatColors.Id.NotSet,
linearGradient = ChatColors.LinearGradient(
degrees = 180f,
colors = intArrayOf(0xFF65CDAC.toInt(), 0xFF0A995A.toInt()),
positions = floatArrayOf(0.0f, 1.0f)
)
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFFFC153.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFCCBD33.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFF84712E.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFF09B37B.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFF8B8BF9.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFF5151F6.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFF76E6E.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFC84641.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFC6C4A5.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFFA49595.toInt()
),
ChatColors.forColor(
id = ChatColors.Id.NotSet,
color = 0xFF292929.toInt()
),
)
fun getInitialBackgroundColor(): ChatColors = backgroundColors.first()
fun cycleBackgroundColor(chatColors: ChatColors): ChatColors {
val indexOfNextColor = (backgroundColors.indexOf(chatColors) + 1) % backgroundColors.size
return backgroundColors[indexOfNextColor]
}
@JvmStatic
fun getRandomBackgroundColor() = backgroundColors.random()
}
| gpl-3.0 | 264ed4eea4eb1f327ebb649e3c5a7a6b | 27.682692 | 93 | 0.642977 | 3.615758 | false | false | false | false |
walleth/kethereum | rlp/src/main/kotlin/org/kethereum/functions/rlp/RLPEncoder.kt | 1 | 847 | package org.kethereum.functions.rlp
import org.kethereum.extensions.toMinimalByteArray
/**
RLP as of Appendix B. Recursive Length Prefix at https://github.com/ethereum/yellowpaper
*/
fun RLPType.encode(): ByteArray = when (this) {
is RLPElement -> bytes.encodeRLP(ELEMENT_OFFSET)
is RLPList -> element.asSequence().map { it.encode() }
.fold(ByteArray(0)) { acc, bytes -> acc + bytes } // this can be speed optimized when needed
.encodeRLP(LIST_OFFSET)
}
internal fun ByteArray.encodeRLP(offset: Int) = when {
size == 1 && ((first().toInt() and 0xff) < ELEMENT_OFFSET) && offset == ELEMENT_OFFSET -> this
size <= 55 -> ByteArray(1) { (size + offset).toByte() }.plus(this)
else -> size.toMinimalByteArray().let { arr ->
ByteArray(1) { (offset + 55 + arr.size).toByte() } + arr + this
}
}
| mit | 7bcbeeec27cd69fe4b5ac1dea82767f8 | 37.5 | 104 | 0.649351 | 3.635193 | false | false | false | false |
chkpnt/truststorebuilder-gradle-plugin | src/main/kotlin/de/chkpnt/gradle/plugin/truststorebuilder/CheckCertsSpec.kt | 1 | 2598 | /*
* Copyright 2016 - 2022 Gregor Dschung
*
* 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 de.chkpnt.gradle.plugin.truststorebuilder
import org.gradle.api.Project
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import java.nio.file.Path
class CheckCertsSpec(private val project: Project) {
internal val source: Property<Path> = project.objects.property(Path::class.java)
.convention(project.layout.projectDirectory.dir("src/main/certs").asFile.toPath())
internal val includes: ListProperty<String> = project.objects.listProperty(String::class.java)
.convention(listOf("**/*.crt", "**/*.cer", "**/*.pem"))
internal val excludes: ListProperty<String> = project.objects.listProperty(String::class.java)
/**
* Number of days the certificates have to be at least valid. Defaults to 90 days.
*/
var atLeastValidDays: Property<Int> = project.objects.property(Int::class.java)
.convention(90)
/**
* Should the `check`-task depend on `checkCertificates<Name>`? Defaults to true.
*/
var checkEnabled: Property<Boolean> = project.objects.property(Boolean::class.java)
.convention(true)
/**
* The directory which is scanned for certificates and bundles, which is resolved using `project.file(...)`.
*
* Defaults to '$projectDir/src/main/certs'.
*
* {@see https://docs.gradle.org/current/dsl/org.gradle.api.Project.html#org.gradle.api.Project:file(java.lang.Object)}
*/
fun source(directory: Any) {
source.set(project.file(directory).toPath())
}
/**
* Filter for the source directory, can be called multiple times.
*
* Defaults to ['**/*.crt', '**/*.cer', '**/*.pem'].
*/
fun include(vararg patterns: String) {
includes.addAll(patterns.toList())
}
/**
* Exclusions for the source directory, can be called multiple times.
*
* Defaults to [].
*/
fun exclude(vararg patterns: String) {
excludes.addAll(patterns.toList())
}
}
| apache-2.0 | 6148b86b1d44cdbb26821ebcb02d5899 | 35.083333 | 123 | 0.678214 | 3.972477 | false | false | false | false |
mezpahlan/jivecampaign | src/main/kotlin/co/uk/jiveelection/campaign/input/twitter/TwitterInput.kt | 1 | 4105 | package co.uk.jiveelection.campaign.input.twitter
import co.uk.jiveelection.campaign.input.Input
import co.uk.jiveelection.campaign.jive.Jive
import co.uk.jiveelection.campaign.output.twitter.TranslationEntity
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import twitter4j.*
import java.util.*
/**
* Configures a Twitter user and listens to a tweet timeline.
*
*
* Does not follow retweets.
*/
@AutoFactory
class TwitterInput(private val jiveBot: Jive<*, *, *>, @Provided private val realUserName: String, @Provided private val twitter: Twitter, @Provided private val twitterStream: TwitterStream) : Input<Status> {
private val logger: Logger = LoggerFactory.getLogger(TwitterInput::class.java)
@Throws(TwitterException::class)
fun init() {
val realId = twitter.showUser(realUserName).id
val tweetFilterQuery = FilterQuery()
tweetFilterQuery.follow(realId)
twitterStream
.onStatus { status ->
if (status.user.id == realId) {
if (!status.isRetweet) {
logger.info("Received status from: $realUserName.")
val translationEntities = extractEntities(status)
jiveBot.onInputReceived(translationEntities)
}
}
}
.filter(tweetFilterQuery)
}
override fun extractEntities(input: Status): List<TranslationEntity> {
// Original status length
val text = input.text
val length = text.length
// Begin entity extract
val verbatimEntities = ArrayList<TranslationEntity>()
val entities = ArrayList<TranslationEntity>()
// Get URL Entities
for (i in 0 until input.urlEntities.size) {
val urlEntities = input.urlEntities[i]
val start = urlEntities.start
val end = urlEntities.end
verbatimEntities.add(TranslationEntity.verbatim(start, end, text.substring(start, end)))
}
// Get Media Entities
for (i in 0 until input.mediaEntities.size) {
val mediaEntities = input.mediaEntities[i]
val start = mediaEntities.start
val end = mediaEntities.end
verbatimEntities.add(TranslationEntity.verbatim(start, end, text.substring(start, end)))
}
// Get UserMentionEntity if they exists
for (i in 0 until input.userMentionEntities.size) {
val userMentionEntities = input.userMentionEntities[i]
val start = userMentionEntities.start
val end = userMentionEntities.end
verbatimEntities.add(TranslationEntity.verbatim(start, end, text.substring(start, end)))
}
// Get HashtagEntity if they exists
for (i in 0 until input.hashtagEntities.size) {
val hashTagEntities = input.hashtagEntities[i]
val start = hashTagEntities.start
val end = hashTagEntities.end
verbatimEntities.add(TranslationEntity.verbatim(start, end, text.substring(start, end)))
}
// Order verbatim entities by start position
verbatimEntities.sortWith(Comparator.comparingInt { it.start })
// Add translatable entities
var position = 0
for (verbatimEntity in verbatimEntities) {
if (verbatimEntity.start != 0) {
entities.add(TranslationEntity.translate(position, verbatimEntity.start, text.substring(position, verbatimEntity.start)))
}
entities.add(verbatimEntity)
position = verbatimEntity.end
}
// Collect the rest of the string to translate
if (position < length) {
entities.add(TranslationEntity.translate(position, length, text.substring(position, length)))
}
// Order all entities by start position
entities.sortWith(Comparator.comparingInt { it.start })
return entities
}
}
| mit | 12d16ccec75f53e1363f21f4dd5651cc | 37.009259 | 208 | 0.638733 | 4.68073 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.