path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/kickstarter/ui/viewholders/projectcampaign/ExternalViewViewHolder.kt
|
kickstarter
| 76,278,501
| false
|
{"Kotlin": 5269841, "Java": 317201, "Ruby": 22177, "Shell": 6325, "Makefile": 3750}
|
package com.kickstarter.ui.viewholders.projectcampaign
import android.annotation.SuppressLint
import androidx.fragment.app.FragmentActivity
import com.kickstarter.databinding.ViewElementExternalSourceFromHtmlBinding
import com.kickstarter.libs.htmlparser.ExternalSourceViewElement
import com.kickstarter.ui.adapters.projectcampaign.ViewElementAdapter
import com.kickstarter.ui.viewholders.KSViewHolder
import com.kickstarter.ui.views.WebChromeVideoFullScreenClient
class ExternalViewViewHolder(
val binding: ViewElementExternalSourceFromHtmlBinding,
private val fullScreenDelegate: ViewElementAdapter.FullScreenDelegate,
val requireActivity: FragmentActivity
) : KSViewHolder(binding.root) {
private val webView = binding.externalSourceWebView
fun configure(element: ExternalSourceViewElement) {
setupWebView()
val htmlContent = "<body style=\"margin: 0; padding: 0\">${element.htmlContent}</body>"
webView.loadData(htmlContent, "text/html", "utf-8")
}
@SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() {
webView.settings.javaScriptEnabled = true
webView.webChromeClient = WebChromeVideoFullScreenClient(
requireActivity,
fullScreenDelegate, absoluteAdapterPosition
)
}
override fun bindData(data: Any?) {
(data as? ExternalSourceViewElement).apply {
this?.let { configure(it) }
}
}
}
| 8
|
Kotlin
|
989
| 5,752
|
a9187fb484c4d12137c7919a2a53339d67cab0cb
| 1,449
|
android-oss
|
Apache License 2.0
|
js/js.translator/testData/incremental/invalidation/genericInlineFunctions/lib1/l1.0.kt
|
JetBrains
| 3,432,266
| false
|
{"Markdown": 192, "Gradle": 401, "Gradle Kotlin DSL": 1182, "Java Properties": 29, "Shell": 45, "Ignore List": 20, "Batchfile": 21, "Git Attributes": 8, "JSON": 203, "XML": 833, "Kotlin": 56096, "INI": 200, "Java": 3899, "Text": 25219, "JavaScript": 316, "JAR Manifest": 2, "Roff": 256, "Roff Manpage": 56, "Protocol Buffer": 16, "Proguard": 15, "TOML": 1, "AsciiDoc": 1, "YAML": 8, "EditorConfig": 2, "OpenStep Property List": 24, "C": 216, "C++": 368, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 19, "Objective-C": 237, "Groovy": 10, "Dockerfile": 5, "Diff": 4, "EJS": 1, "CSS": 6, "HTML": 11, "Swift": 161, "LLVM": 1, "Reason": 1, "JSON with Comments": 62, "TypeScript": 8, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 102, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 77, "FreeMarker": 1, "Fluent": 2, "Ruby": 19, "Scala": 1}
|
inline fun <reified T> foo(x: T) = 123
| 179
|
Kotlin
|
5640
| 48,055
|
e3542ec7d0ffb0a27b189cadc323e88e4cb8ba4f
| 39
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/org/rust/ide/formatter/RsReturnStatementFormatProcessor.kt
|
mattsse
| 103,789,734
| false
|
{"Gradle": 1, "Shell": 3, "YAML": 2, "Gradle Kotlin DSL": 1, "INI": 2, "Markdown": 5, "TOML": 5, "Text": 86, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 642, "Rust": 226, "XML": 62, "RenderScript": 1, "Java": 2, "HTML": 75, "SVG": 2, "JFlex": 3}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.RsMatchArm
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsRetExpr
import org.rust.lang.core.psi.ext.elementType
import org.rust.lang.core.psi.ext.getNextNonCommentSibling
import java.util.*
class RsReturnStatementFormatProcessor : PreFormatProcessor {
override fun process(element: ASTNode, range: TextRange): TextRange {
val returnElements = ArrayList<RsRetExpr>()
element.psi.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.textRange in range) {
super.visitElement(element)
}
if (element is RsRetExpr && element.parent !is RsMatchArm) {
returnElements.add(element)
}
}
})
var nAddedSemicolons = 0
for (returnElement in returnElements) {
if (tryAddSemicolonAfterReturnExpression(returnElement)) {
nAddedSemicolons++
}
}
return range.grown(nAddedSemicolons)
}
private fun tryAddSemicolonAfterReturnExpression(element: RsRetExpr): Boolean {
val nextSibling = element.getNextNonCommentSibling();
if (nextSibling == null || nextSibling.elementType != SEMICOLON) {
val psiFactory = RsPsiFactory(element.project)
element.parent.addAfter(psiFactory.createSemicolon(), element)
return true
}
return false
}
}
| 1
| null |
1
| 1
|
fd96ed4524a6365ea89bfad3e761954a1361edbc
| 1,948
|
intellij-rust
|
MIT License
|
app/src/main/java/hive/com/paradiseoctopus/awareness/MainActivity.kt
|
cliffroot
| 68,677,882
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 39, "Kotlin": 34}
|
package hive.com.paradiseoctopus.awareness
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import hive.com.paradiseoctopus.awareness.showplaces.ShowPlacesView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, ShowPlacesView()).commitNow()
}
}
| 0
|
Kotlin
|
0
| 0
|
77bd018fd938ebebe804ecceca9315112564246b
| 503
|
awareness
|
Apache License 2.0
|
sample/src/main/java/ro/andreidobrescu/declarativeadapterktsample/model/CommentsHeader.kt
|
fossabot
| 221,451,438
| true
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "XML": 15, "Markdown": 1, "Proguard": 2, "Kotlin": 17, "Java": 3}
|
package ro.andreidobrescu.declarativeadapterktsample.model
class CommentsHeader
| 0
|
Kotlin
|
0
| 0
|
ceeb83a1cd67cc6d87c96a6e5702d68ddd3fb8ef
| 80
|
DeclarativeAdapter-kt
|
Apache License 2.0
|
android/DartsScorecard/domain/src/main/java/nl/entreco/domain/mastercaller/ToggleSoundUsecase.kt
|
Entreco
| 110,022,468
| false
| null |
package nl.entreco.domain.mastercaller
import nl.entreco.domain.repository.AudioPrefRepository
import nl.entreco.libcore.BaseUsecase
import nl.entreco.libcore.threading.Background
import nl.entreco.libcore.threading.Foreground
import javax.inject.Inject
/**
* Created by entreco on 14/03/2018.
*/
class ToggleSoundUsecase @Inject constructor(
private val audioPrefRepository: AudioPrefRepository,
bg: Background, fg: Foreground,
) : BaseUsecase(bg, fg) {
fun toggle() {
onBackground({
val toggled = !audioPrefRepository.isMasterCallerEnabled()
audioPrefRepository.setMasterCallerEnabled(toggled)
}, {})
}
}
| 4
| null |
1
| 1
|
a031a0eeadd0aa21cd587b5008364a16f890b264
| 667
|
Darts-Scorecard
|
Apache License 2.0
|
common/src/main/java/com/ruzhan/lion/App.kt
|
ckrgithub
| 150,102,569
| false
| null |
package com.ruzhan.lion
import android.app.Application
import android.content.Context
import android.support.multidex.MultiDex
import com.blankj.utilcode.util.Utils
import com.crashlytics.android.Crashlytics
import com.ruzhan.common.BuildConfig
import com.ruzhan.lion.util.LionUtils
import io.fabric.sdk.android.Fabric
/**
* Created by ruzhan123 on 2018/7/4.
*/
class App : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
if (BuildConfig.BUILD_TYPE.equals(LionUtils.RELEASE)) {
Fabric.with(this, Crashlytics())
}
Utils.init(this)
}
companion object {
private lateinit var INSTANCE: Application
@JvmStatic
fun get(): Application {
return this.INSTANCE
}
@JvmStatic
fun setApp(application: Application) {
INSTANCE = application
}
}
}
| 1
| null |
1
| 1
|
e73bcaf999e3de04905e781004f02ede6d85eaea
| 1,045
|
Lion
|
Apache License 2.0
|
src/test/kotlin/no/skotbuvel/portal/config/HerokuPostgresConfigTest.kt
|
apgv
| 92,088,012
| false
|
{"Java": 113114, "Vue": 61421, "Kotlin": 42367, "JavaScript": 12781, "HTML": 352, "CSS": 63}
|
package no.skotbuvel.portal.config
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.net.URI
internal class HerokuPostgresConfigTest {
private val pgDatabaseConfig = HerokuPostgresConfig(uri = URI("postgres://user:password@localhost:5432/database"))
@Test
internal fun name() {
assertThat(pgDatabaseConfig.username()).isEqualTo("user")
}
@Test
internal fun password() {
assertThat(pgDatabaseConfig.password()).isEqualTo("<PASSWORD>")
}
@Test
internal fun host() {
assertThat(pgDatabaseConfig.host()).isEqualTo("localhost")
}
@Test
internal fun port() {
assertThat(pgDatabaseConfig.port()).isEqualTo(5432)
}
@Test
internal fun database() {
assertThat(pgDatabaseConfig.database()).isEqualTo("database")
}
}
| 1
| null |
1
| 1
|
d511cb0f187ccba6a1bc7a498fd948f6de8729e5
| 862
|
skotbuvel-portal
|
MIT License
|
src/main/kotlin/com/getkeepsafe/dexcount/ColorConsole.kt
|
cywudia
| 160,515,202
| true
|
{"Kotlin": 62803, "Java": 42535, "Groovy": 38761, "JavaScript": 8847, "Shell": 4301, "HTML": 440, "CSS": 438}
|
package com.getkeepsafe.dexcount
import org.gradle.api.DefaultTask
import org.gradle.api.logging.LogLevel
import java.io.PrintWriter
import java.io.Writer
import java.lang.reflect.Method
enum class Color {
DEFAULT,
GREEN,
YELLOW,
RED
}
private fun Color.toStyle() = when (this) {
Color.DEFAULT -> Style.Normal
Color.GREEN -> Style.Identifier
Color.YELLOW -> Style.Info
Color.RED -> Style.Error
}
/**
* Various styles that can be applied to text output.
*
* These names match the Gradle StyledTextOutput.Style enums exactly.
*/
private enum class Style {
Normal,
Header,
UserInput,
Identifier,
Description,
ProgressStatus,
Success,
SuccessHeader,
Failure,
FailureHeader,
Info,
Error
}
fun DefaultTask.withStyledOutput(color: Color = Color.DEFAULT, level: LogLevel? = null, fn: (PrintWriter) -> Unit) {
val style = color.toStyle()
val factory = this.createStyledOutputFactory()
val output = factory.create("dexcount", level)
val styledOutput = output.withStyle(style)
val printWriter = styledOutput.asPrintWriter()
fn(printWriter)
}
private fun DefaultTask.createStyledOutputFactory(): StyledTextOutputFactoryWrapper {
val registry = DefaultTask_getServices(this)
val factory = ServiceRegistry_get(registry, styledTextOutputFactoryClass)
return StyledTextOutputFactoryWrapper(factory)
}
private class StyledTextOutputFactoryWrapper(val factory: Any) {
fun create(label: String, level: LogLevel? = null): StyledTextOutputWrapper {
val sto = if (level == null) {
StyledTextOutputFactory_create(factory, label)
} else {
StyledTextOutputFactory_createWithLevel(factory, label, level)
}
return StyledTextOutputWrapper(sto)
}
}
private class StyledTextOutputWrapper(private var sto: Any) {
fun withStyle(style: Style): StyledTextOutputWrapper {
val platformStyle = style.toPlatformStyle()
this.sto = StyledTextOutput_withStyle(sto, platformStyle)
return this
}
fun asPrintWriter(): PrintWriter {
val appendable = sto as Appendable
val writer = AppendablePrintWriterAdapter(appendable)
return PrintWriter(writer)
}
}
private fun Style.toPlatformStyle(): Any {
val name = this.name
return styleClass.enumConstants.single { it.name == name }
}
private class AppendablePrintWriterAdapter(private val appendable: Appendable) : Writer() {
override fun append(csq: CharSequence?): Writer {
appendable.append(csq)
return this
}
override fun append(csq: CharSequence?, start: Int, end: Int): Writer {
appendable.append(csq, start, end)
return this
}
override fun append(c: Char): Writer {
appendable.append(c)
return this
}
override fun write(c: Int) {
super.write(c)
}
override fun write(cbuf: CharArray?) {
}
override fun write(cbuf: CharArray?, off: Int, len: Int) {
val str = String(cbuf!!, off, len)
appendable.append(str)
}
override fun write(str: String?) {
appendable.append(str)
}
override fun write(str: String?, off: Int, len: Int) {
val substr = str?.substring(off, off + len)
appendable.append(substr)
}
override fun flush() {
}
override fun close() {
}
}
private val styledTextOutputFactoryClass: Class<*> by lazy {
getClassWithFallback(
"org.gradle.internal.logging.text.StyledTextOutputFactory",
"org.gradle.logging.StyledTextOutputFactory"
)
}
private val styledTextOutputClass: Class<*> by lazy {
getClassWithFallback(
"org.gradle.internal.logging.text.StyledTextOutput",
"org.gradle.logging.StyledTextOutput"
)
}
@Suppress("UNCHECKED_CAST")
private val styleClass: Class<Enum<*>> by lazy {
getClassWithFallback(
"org.gradle.internal.logging.text.StyledTextOutput\$Style",
"org.gradle.logging.StyledTextOutput\$Style"
) as Class<Enum<*>>
}
private val serviceRegistryClass: Class<*> by lazy {
getClassWithFallback(
"org.gradle.internal.service.ServiceRegistry",
"org.gradle.api.internal.project.ServiceRegistry"
)
}
private val DefaultTask_getServices: Method by lazy {
var clazz: Class<*>? = DefaultTask::class.java
var method: Method? = null
while (clazz != Any::class.java && clazz != null) {
try {
method = clazz.getDeclaredMethod("getServices")
method.isAccessible = true
break
} catch (e: NoSuchMethodException) {
clazz = clazz.superclass
}
}
method!!
}
private val ServiceRegistry_get: Method by lazy {
serviceRegistryClass.method("get", Class::class.java)
}
private val StyledTextOutputFactory_create: Method by lazy {
styledTextOutputFactoryClass.method("create", String::class.java)
}
private val StyledTextOutputFactory_createWithLevel: Method by lazy {
styledTextOutputFactoryClass.method("create", String::class.java, LogLevel::class.java)
}
private val StyledTextOutput_withStyle: Method by lazy {
styledTextOutputClass.method("withStyle", styleClass)
}
private fun Class<*>.method(name: String, vararg paramTypes: Class<*>): Method {
return getMethod(name, *paramTypes).apply {
isAccessible = true
}
}
private fun getClassWithFallback(name: String, fallbackName: String): Class<*> {
return try {
Class.forName(name)
} catch (ignored: ClassNotFoundException) {
// We're probably on Gradle 2.X; if not, oh well - another bug for
// us to fix!
Class.forName(fallbackName)
}
}
| 1
|
Kotlin
|
1
| 1
|
cae0e1ebb1704842d37d74c4dc07ab8ff90fa8e9
| 5,727
|
dexcount-gradle-plugin
|
Apache License 2.0
|
app/src/main/java/com/mutlak/metis/wordmem/data/model/pojo/ExamSession.kt
|
MahdiHatami
| 213,575,863
| false
|
{"Kotlin": 178738}
|
package com.mutlak.metis.wordmem.data.model.pojo
import java.io.Serializable
data class ExamSession(
var id: Int = 0,
var questions: List<Question>? = null,
var time: Int = 0
) : Serializable
| 0
|
Kotlin
|
0
| 0
|
aeff75c3dbc5cea54f1e1c49285af8df064207be
| 207
|
flashcard-mobile
|
The Unlicense
|
app/src/main/java/com/dede/sonimei/module/db/DatabaseOpenHelper.kt
|
hushenghao
| 133,592,946
| false
| null |
package com.dede.sonimei.module.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*
/**
* Created by hsh on 2018/6/6.
*/
class DatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "sonimei_db", null, 1) {
companion object {
private var instance: DatabaseOpenHelper? = null
@Synchronized
fun getInstance(ctx: Context): DatabaseOpenHelper {
if (instance == null) {
instance = DatabaseOpenHelper(ctx.applicationContext)
}
return instance!!
}
const val TABLE_SEARCH_HIS = "search_his"
const val COLUMNS_ID = "_id"
const val COLUMNS_TEXT = "text"
const val COLUMNS_TIMESTAMP = "times_tamp"
// const val TABLE_LOCAL_MUSIC = "local_music"
// const val COLUMNS_MUSIC_ID = "_id"
// const val COLUMNS_MUSIC_TITLE = "title"
// const val COLUMNS_MUSIC_AUTHOR = "author"
// const val COLUMNS_MUSIC_ALBUM = "album"
// const val COLUMNS_MUSIC_DURATION = "duration"
// const val COLUMNS_MUSIC_PATH = "path"
}
override fun onCreate(db: SQLiteDatabase) {
db.createTable(TABLE_SEARCH_HIS, true,
COLUMNS_ID to INTEGER + PRIMARY_KEY + UNIQUE,
COLUMNS_TEXT to TEXT + NOT_NULL,
// 默认值时间戳,单位为秒
COLUMNS_TIMESTAMP to SqlType.create("TIMESTAMP NOT NULL DEFAULT (strftime('%s',datetime('now')))")
)
// db.createTable(TABLE_LOCAL_MUSIC, true,
// COLUMNS_MUSIC_ID to INTEGER + PRIMARY_KEY + UNIQUE,
// COLUMNS_MUSIC_TITLE to TEXT + NOT_NULL,
// COLUMNS_MUSIC_AUTHOR to TEXT,
// COLUMNS_MUSIC_ALBUM to TEXT,
// COLUMNS_MUSIC_DURATION to INTEGER,
// COLUMNS_MUSIC_PATH to TEXT + NOT_NULL
// )
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// if (newVersion >= 2) {// 2 版本添加了本地音乐数据表
// db.createTable(TABLE_LOCAL_MUSIC, true,
// COLUMNS_MUSIC_ID to INTEGER + PRIMARY_KEY + UNIQUE,
// COLUMNS_MUSIC_TITLE to TEXT + NOT_NULL,
// COLUMNS_MUSIC_AUTHOR to TEXT,
// COLUMNS_MUSIC_ALBUM to TEXT,
// COLUMNS_MUSIC_DURATION to INTEGER,
// COLUMNS_MUSIC_PATH to TEXT + NOT_NULL
// )
// }
}
}
// Access property for Context
val Context.database: DatabaseOpenHelper
get() = DatabaseOpenHelper.getInstance(applicationContext)
val Context.db: SQLiteDatabase
get() = database.writableDatabase
| 0
| null |
18
| 99
|
5ddce06b4cfde3472156aed0693893e3ada7c09c
| 2,690
|
music
|
Apache License 2.0
|
castled-notifications/src/main/java/io/castled/android/notifications/tracking/device/DeviceInfotUtils.kt
|
castledio
| 525,047,434
| false
|
{"Kotlin": 326016, "HTML": 28150, "Java": 18371, "JavaScript": 1717}
|
package io.castled.android.notifications.tracking.device
import io.castled.android.notifications.store.CastledSharedStore
import io.castled.android.notifications.tracking.events.extensions.toJsonElement
import io.castled.android.notifications.workmanager.models.CastledDeviceInfoRequest
import kotlinx.serialization.json.JsonObject
internal object DeviceInfotUtils {
fun getDeviceInfoRequest(
deviceInfo: Map<String, Any>
): CastledDeviceInfoRequest {
val event = CastledDeviceInfoRequest(
type = "track",
userId = CastledSharedStore.getUserId() ?: "",
deviceInfo = JsonObject(deviceInfo.map { (key, value) ->
key to value.toJsonElement()
}.toMap())
)
return event
}
}
| 0
|
Kotlin
|
2
| 3
|
fbde3e243f65fd2d2e5cec364e9e86b33cd38267
| 780
|
castled-notifications-android
|
MIT License
|
app/src/main/java/com/jmoraes/componentizationsample/PlayerActivity.kt
|
julianomoraes
| 144,759,971
| false
| null |
package com.jmoraes.componentizationsample
import android.annotation.SuppressLint
import android.net.Uri
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.upstream.TransferListener
import com.google.android.exoplayer2.util.Util
import com.jmoraes.componentizationsample.basic.components.LoadingComponent
import com.jmoraes.componentizationsample.basic.eventTypes.ScreenStateEvent
import com.netflix.componentizationV1.EventBusFactory
import com.jmoraes.componentizationsample.player.components.PlayerEvents
import com.netflix.elfo.components.PlayerUserInteractionEvents
import com.jmoraes.componentizationsample.player.components.PrimaryControlsComponent
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit
class PlayerActivity : AppCompatActivity(), LifecycleOwner {
private var player: SimpleExoPlayer? = null
private val playerView: PlayerView by lazy { findViewById<PlayerView>(R.id.player_view) }
private lateinit var primaryControlsComponent: PrimaryControlsComponent
private lateinit var lifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleRegistry = LifecycleRegistry(this)
lifecycleRegistry.markState(Lifecycle.State.CREATED)
setContentView(R.layout.activity_player)
val container = findViewById<ConstraintLayout>(R.id.player_root)
initializeUIComponents(container)
layoutUIComponents(container)
}
@SuppressLint("CheckResult")
private fun initializeUIComponents(container: ViewGroup) {
// Reusing this component from the Basic Sample package
LoadingComponent(container, EventBusFactory.get(this))
primaryControlsComponent = PrimaryControlsComponent(container, EventBusFactory.get(this))
primaryControlsComponent.getUserInteractionEvents()
.subscribe {
when (it) {
PlayerUserInteractionEvents.IntentPlayPauseClicked -> {
player?.playWhenReady = !player?.playWhenReady!!
}
PlayerUserInteractionEvents.IntentRwClicked -> {
player?.seekTo(player?.currentPosition!! / 2)
}
PlayerUserInteractionEvents.IntentFwClicked -> {
player?.seekTo(player?.currentPosition!! * 2)
}
}
}
}
private fun layoutUIComponents(rootViewContainer: ConstraintLayout) {
// Create a constraintSet and clone it from the main container
val mainContainerConstraintSet = ConstraintSet()
mainContainerConstraintSet.clone(rootViewContainer)
mainContainerConstraintSet.connect(
primaryControlsComponent.getContainerId(),
ConstraintSet.TOP,
ConstraintSet.PARENT_ID,
ConstraintSet.TOP
)
mainContainerConstraintSet.connect(
primaryControlsComponent.getContainerId(),
ConstraintSet.BOTTOM,
ConstraintSet.PARENT_ID,
ConstraintSet.BOTTOM
)
// Apply the constraints from all UI components to the parent
mainContainerConstraintSet.applyTo(rootViewContainer)
}
override fun onStart() {
super.onStart()
initializePlayer()
}
override fun onStop() {
super.onStop()
releasePlayer()
}
private fun initializePlayer() {
playerView.requestFocus()
player = ExoPlayerFactory.newSimpleInstance(
this,
DefaultTrackSelector(AdaptiveTrackSelection.Factory(DefaultBandwidthMeter()))
)
player?.let {
playerView.player = it
it.addListener(PlayerEventListener(EventBusFactory.get(this)))
}
// artificial delay to simulate a network request
Observable.just(Any())
.delay(5, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
val mediaSource = ExtractorMediaSource.Factory(
DefaultDataSourceFactory(
this, Util.getUserAgent(this, "mediaPlayerSample"),
DefaultBandwidthMeter() as TransferListener<in DataSource>
)
).createMediaSource(Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"))
player?.prepare(mediaSource, false, false)
}
.subscribe()
player?.playWhenReady = true
}
private fun releasePlayer() {
player?.let {
it.release()
player = null
}
}
private inner class PlayerEventListener(val eventBusFactory: EventBusFactory) : Player.DefaultEventListener() {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
// The player does not have any media to play yet.
Player.STATE_IDLE -> {
eventBusFactory.emit(ScreenStateEvent::class.java, ScreenStateEvent.Loading)
}
// The player is buffering (loading the content)
Player.STATE_BUFFERING -> {
eventBusFactory.emit(ScreenStateEvent::class.java, ScreenStateEvent.Loading)
eventBusFactory.emit(PlayerEvents::class.java, PlayerEvents.Buffering)
}
// The player is able to immediately play
Player.STATE_READY -> {
eventBusFactory.emit(ScreenStateEvent::class.java, ScreenStateEvent.Loaded)
if (playWhenReady) {
eventBusFactory.emit(PlayerEvents::class.java, PlayerEvents.PlayStarted)
} else {
eventBusFactory.emit(PlayerEvents::class.java, PlayerEvents.Paused)
}
}
// The player has finished playing the media
Player.STATE_ENDED -> {
// TODO
}
}
}
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
| 2
|
Kotlin
|
41
| 268
|
f9eb6987cd4c3d3630d42a85e69c6f74248abab6
| 7,226
|
componentizationArch
|
Apache License 2.0
|
app/src/main/kotlin/dev/mbo/dbq/db/model/types/retrystrategy/RetryDelay.kt
|
mbogner
| 487,622,806
| false
|
{"Kotlin": 77379, "PLpgSQL": 4569}
|
/*
* Copyright 2022 mbo.dev
*
* 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 dev.mbo.dbq.db.model.types.retrystrategy
import dev.mbo.dbq.db.model.types.QueueMeta
import dev.mbo.dbq.db.model.types.RetryDelayStrategy
import java.time.Instant
interface RetryDelay {
fun supportedStrategy(): RetryDelayStrategy
fun update(queueMeta: QueueMeta, exc: Exception?, overrideNextAfter: Instant?): QueueMeta
}
| 0
|
Kotlin
|
0
| 0
|
d89d18513f04f69a61e2a955db496548349e19a1
| 935
|
dbq
|
Apache License 2.0
|
core/src/main/kotlin/com/marekkwiecien/sapper/Model.kt
|
holowizor
| 139,164,159
| false
|
{"Kotlin": 6318}
|
package com.marekkwiecien.sapper
interface WithCoordinates {
val x: Int
val y: Int
}
data class Point(override val x: Int, override val y: Int) : WithCoordinates
data class Field(override val x: Int, override val y: Int, val mine: Boolean, val neighbourMines: Int) : WithCoordinates
typealias Mine = Point
| 0
|
Kotlin
|
0
| 0
|
ea4ec0618ff82d41bced075120c705d95992639c
| 318
|
sapper
|
Apache License 2.0
|
app/src/main/java/com/srg/pruebamarvel/common/di/injections/FragmentInjectionFactory.kt
|
sebrodgar
| 353,656,877
| false
| null |
package com.srg.codetestrickmorty.common.di.injections
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import javax.inject.Inject
import javax.inject.Provider
class FragmentInjectionFactory @Inject constructor(
private val creators: @JvmSuppressWildcards Map<Class<out Fragment>, Provider<Fragment>>
) : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
val fragmentClass = loadFragmentClass(classLoader, className)
val creator = creators[fragmentClass]
return creator?.get() ?: super.instantiate(classLoader, className)
}
}
| 0
|
Kotlin
|
0
| 0
|
dfb2f16f8d12809bc97f17cbe4a267df46bf3ffa
| 651
|
code-test-rick-morty
|
Apache License 2.0
|
src/main/kotlin/com/github/huifer/ideapluginsdemo/services/MyProjectService.kt
|
huifer
| 293,477,053
| false
| null |
package com.github.huifer.ideapluginsdemo.services
import com.intellij.openapi.project.Project
import com.github.huifer.ideapluginsdemo.MyBundle
class MyProjectService(project: Project) {
init {
println(MyBundle.message("projectService", project.name))
}
}
| 0
|
Kotlin
|
0
| 1
|
2c0dba619dc7480ff43d62ff709855b6b19d0521
| 276
|
gitee-todo-list
|
Apache License 2.0
|
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/structuredconcurrency/4_cancelling_parents_and_children.kt
|
LukasLechnerDev
| 248,218,113
| false
| null |
package com.demo.code.playground.structuredconcurrency
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val scope = CoroutineScope(Dispatchers.Default)
scope.coroutineContext[Job]!!.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Parent job was cancelled")
}
}
val childCoroutine1Job = scope.launch {
delay(1000)
println("Coroutine 1 completed")
}
childCoroutine1Job.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Coroutine 1 was cancelled!")
}
}
scope.launch {
delay(1000)
println("Coroutine 2 completed")
}.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Coroutine 2 was cancelled!")
}
}
delay(200)
childCoroutine1Job.cancelAndJoin()
// scope.coroutineContext[Job]!!.cancelAndJoin()
}
| 5
| null |
436
| 2,664
|
636b1038c42073a45bfccb25afbedc294b0f032d
| 987
|
Kotlin-Coroutines-and-Flow-UseCases-on-Android
|
Apache License 2.0
|
app/src/test/java/org/simple/clinic/home/overdue/OverdueEffectHandlerTest.kt
|
appdev-academy
| 292,263,031
| true
|
{"Kotlin": 4738177, "Shell": 3719, "Python": 3162}
|
package org.simple.clinic.home.overdue
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import org.junit.After
import org.junit.Test
import org.simple.clinic.TestData
import org.simple.clinic.mobius.EffectHandlerTestCase
import org.simple.clinic.util.scheduler.TestSchedulersProvider
import java.util.UUID
class OverdueEffectHandlerTest {
private val facility = TestData.facility(
uuid = UUID.fromString("251deca2-d219-4863-80fc-e7d48cb22b1b"),
name = "PHC Obvious"
)
private val uiActions = mock<OverdueUiActions>()
private val effectHandler = OverdueEffectHandler(
schedulers = TestSchedulersProvider.trampoline(),
appointmentRepository = mock(),
currentFacility = { facility },
dataSourceFactory = mock(),
uiActions = uiActions
).build()
private val effectHandlerTestCase = EffectHandlerTestCase(effectHandler)
@After
fun tearDown() {
effectHandlerTestCase.dispose()
}
@Test
fun `when open patient summary effect is received, then open patient summary`() {
// given
val patientUuid = UUID.fromString("e6794bf5-447e-4588-8df2-5e2a07d23bc4")
// when
effectHandlerTestCase.dispatch(OpenPatientSummary(patientUuid))
// then
effectHandlerTestCase.assertNoOutgoingEvents()
verify(uiActions).openPatientSummary(patientUuid)
verifyNoMoreInteractions(uiActions)
}
@Test
fun `when the load current facility effect is received, then the current facility must be loaded`() {
// when
effectHandlerTestCase.dispatch(LoadCurrentFacility)
// then
effectHandlerTestCase.assertOutgoingEvents(CurrentFacilityLoaded(facility))
verifyZeroInteractions(uiActions)
}
}
| 0
|
Kotlin
|
0
| 0
|
2c7cc71a824bbe4a809bebaa95aef9555c6e7a18
| 1,837
|
simple-app-cameroon-android
|
MIT License
|
common/src/test/kotlin/com/github/niuhf0452/exile/common/BytesTest.kt
|
niuhf0452
| 240,633,641
| false
| null |
package com.github.niuhf0452.exile.common
import io.kotlintest.shouldBe
import io.kotlintest.specs.FunSpec
class BytesTest : FunSpec({
test("Bytes should convert ByteArray and hex") {
Bytes.toHex(Bytes.fromHex("a0c2")) shouldBe "a0c2"
}
})
| 0
|
Kotlin
|
1
| 2
|
8020cb1ab799f7b1e75c73f762a9ee1ed493a003
| 257
|
exile
|
Apache License 2.0
|
src/main/kotlin/org/ivcode/gradle/www/util/StringUtils.kt
|
iv-cores
| 852,529,095
| false
|
{"Kotlin": 42182, "Mustache": 1015}
|
package org.ivcode.gradle.www.util
/**
* Requires that the string is not null or blank.
*
* @param msg the message to use if the requirement fails
* @return the string if it is not null or blank
* @throws IllegalArgumentException if the string is null or blank
*/
fun String?.requireNotNullOrBlank(msg: String = "value failed requirement to not be blank"): String {
require(!this.isNullOrBlank()) { msg }
return this
}
/**
* Returns the string if it is not null or blank, otherwise returns the default value.
*
* @param default the default value to return if the string is null or blank
* @return the string if it is not null or blank, otherwise the default value
*/
fun String?.ifNullOrBlank(default: String): String =
if (this.isNullOrBlank()) default else this
/**
* Returns the string if it is not null or blank, otherwise returns the result of the block.
*
* @param block the block to execute if the string is null or blank
* @return the string if it is not null or blank, otherwise the result of the block
*/
fun String?.ifNullOrBlank(block: () -> String): String =
if (this.isNullOrBlank()) block() else this
| 0
|
Kotlin
|
0
| 0
|
dc12e89cd82b4f1d38b8faa6af9fc22b4d216d21
| 1,151
|
gradle-www
|
Apache License 2.0
|
idea/idea-completion/testData/basic/common/smartCast/SmartCastForThis.kt
|
JakeWharton
| 99,388,807
| false
| null |
// FIR_IDENTICAL
// FIR_COMPARISON
interface Expr {
public fun testThis() {
if (this is Num) {
this.<caret>
}
}
}
class Num(val toCheck : Int) : Expr
// EXIST: toCheck
| 1
| null |
30
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 205
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/nimbusnote/data/model/WeatherData.kt
|
MarcelFN88
| 773,023,776
| false
|
{"Kotlin": 60673}
|
package com.example.nimbusnote.data.model
/**
* Enthält detaillierte Wetterdaten für einen spezifischen Ort.
*
* @property coord Die geografischen Koordinaten des Ortes, für den die Wetterdaten gelten.
* @property weather Eine Liste von `Weather`-Objekten, die die allgemeinen Wetterbedingungen beschreiben.
* @property main Ein `Main`-Objekt, das Kerninformationen wie Temperatur und Luftfeuchtigkeit hält.
* @property sys Ein `Sys`-Objekt mit systembezogenen Informationen, z.B. zum Land und zu Sonnenauf- und -untergangszeiten.
* @property id Die eindeutige ID der Wetterstation oder des Ortes, von dem die Daten stammen.
* @property name Der Name des Ortes, für den die Wetterdaten gelten.
* @property cod Der HTTP-Statuscode der API-Antwort, der den Erfolg der Anfrage anzeigt.
*/
data class WeatherData(
val coord: Coord?,
val weather: List<Weather>?,
val main: Main?,
val sys: Sys?,
val id: Int?,
val name: String?,
val cod: Int?
)
| 0
|
Kotlin
|
0
| 0
|
222a165f6297b4597a97af7b09792a7eae984ce6
| 978
|
NimbusNote
|
MIT License
|
code/codeplugin/transform/src/main/java/com/qxml/transform/generate/CreateClassFile.kt
|
duduhuang88
| 375,209,225
| false
| null |
package com.qxml.transform.generate
import com.google.common.io.Files
import com.google.gson.Gson
import com.qxml.QxmlConfigExtension
import com.qxml.constant.Constants
import com.qxml.tools.GenClassNameTool
import com.qxml.tools.LayoutTypeNameCorrect
import com.qxml.tools.log.LogUtil
import com.qxml.transform.collect.ViewGenInfoHolderImpl
import com.qxml.transform.pool.PoolManager
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.TypeName
import javassist.ClassPool
import javassist.CtMethod
import javassist.CtNewMethod
import javassist.compiler.Javac
import java.lang.StringBuilder
import javax.lang.model.element.Modifier
private object MethodCreateClassHolder {
val viewClass = ClassName.bestGuess(Constants.ANDROID_VIEW_CLASS_NAME)!!
val contextClass = ClassName.bestGuess(Constants.ANDROID_CONTEXT_CLASS_NAME)!!
val inflateClass = ClassName.bestGuess(Constants.ANDROID_INFLATER_CLASS_NAME)!!
val viewGroupClass = ClassName.bestGuess(Constants.ANDROID_VIEW_GROUP_CLASS_NAME)!!
}
interface CreateClassFile {
/**
* 生成class文件并缓存
*/
fun createClassFile(layoutName: String, classGenCacheInfo: ClassGenCacheInfo, packageName: String
, finalUsedLocalVarMap: HashMap<String, String>
, usedImportPackageMap: HashMap<String, String>
, viewGenInfoHolder: ViewGenInfoHolderImpl
, qxmlExtension: QxmlConfigExtension, gson: Gson) {
if (!classGenCacheInfo.cacheValid) {
val className = GenClassNameTool.genClassName(layoutName)
val methodBuilder = MethodSpec.methodBuilder(Constants.GENERATE_METHOD_NAME)
val stringBuilder = StringBuilder()
stringBuilder.append("generate success type: \n")
classGenCacheInfo.successLayoutTypeGenInfoList.forEach {
stringBuilder.append(LayoutTypeNameCorrect.toDisplayText(it.layoutType)).append(" ")
}
stringBuilder.append("\n")
if (classGenCacheInfo.failedLayoutTypeGenInfoList.isNotEmpty()) {
stringBuilder.append("generate failed type: \n")
classGenCacheInfo.failedLayoutTypeGenInfoList.forEach {
stringBuilder.append(LayoutTypeNameCorrect.toDisplayText(it.layoutType)).append(" ")
}
stringBuilder.append("\n")
}
methodBuilder.addJavadoc("generated code of ${layoutName}.xml\n$stringBuilder")
methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
methodBuilder.returns(MethodCreateClassHolder.viewClass)
methodBuilder.addParameter(MethodCreateClassHolder.inflateClass, Constants.GEN_PARAM_INFLATE_NAME)
methodBuilder.addParameter(MethodCreateClassHolder.contextClass, Constants.GEN_PARAM_CONTEXT_NAME)
methodBuilder.addParameter(MethodCreateClassHolder.viewGroupClass, Constants.GEN_PARAM_VIEW_GROUP_ROOT_NAME)
methodBuilder.addParameter(TypeName.BOOLEAN, Constants.GEN_PARAM_ATTACH_TO_NAME)
methodBuilder.addStatement("${Constants.ANDROID_VIEW_GROUP_LAYOUT_PARAM_CLASS_NAME} ${Constants.GEN_FIELD_LAYOUT_PARAMS_ROOT} = null")
methodBuilder.addStatement("${Constants.ANDROID_VIEW_GROUP_LAYOUT_PARAM_CLASS_NAME} ${Constants.GEN_FIELD_LAYOUT_PARAMS} = null")
methodBuilder.addStatement("${Constants.QXML_VALUE_INFO_CLASS_NAME} ${Constants.GEN_FIELD_VALUE_INFO_NAME} = new ${Constants.QXML_VALUE_INFO_CLASS_NAME}()")
if (classGenCacheInfo.layoutTypeAmount != 1 || classGenCacheInfo.generateClassInfo.methodContent.contains(Constants.GEN_FIELD_TYPED_VALUE_NAME)) {
methodBuilder.addStatement("${Constants.ANDROID_TYPED_VALUE_CLASS_NAME} ${Constants.GEN_FIELD_TYPED_VALUE_NAME} = new ${Constants.ANDROID_TYPED_VALUE_CLASS_NAME}()")
}
//methodBuilder.addStatement("${Constants.ANDROID_TYPED_VALUE_CLASS_NAME} ${Constants.GEN_FIELD_TYPED_VALUE_NAME} = new ${Constants.ANDROID_TYPED_VALUE_CLASS_NAME}()")
methodBuilder.addStatement("${Constants.ANDROID_RESOURCE_CLASS_NAME} ${Constants.GEN_FIELD_RESOURCE} = ${Constants.GEN_PARAM_CONTEXT_NAME}.getResources()")
if (qxmlExtension.useFactory) {
methodBuilder.addStatement("${Constants.ANDROID_LAYOUT_INFLATE_FACTORY_CLASS_NAME} ${Constants.GEN_FIELD_FACTORY} = ${Constants.GEN_PARAM_INFLATE_NAME}.getFactory()")
methodBuilder.addStatement("${Constants.ANDROID_LAYOUT_INFLATE_FACTORY2_CLASS_NAME} ${Constants.GEN_FIELD_FACTORY_2} = ${Constants.GEN_PARAM_INFLATE_NAME}.getFactory2()")
methodBuilder.addStatement("${Constants.ANDROID_ACTIVITY_CLASS_NAME} ${Constants.GEN_FIELD_CUR_CONTEXT_ACT} = null")
methodBuilder.beginControlFlow("if (${Constants.GEN_PARAM_CONTEXT_NAME} instanceof ${Constants.ANDROID_ACTIVITY_CLASS_NAME})")
methodBuilder.addStatement("${Constants.GEN_FIELD_CUR_CONTEXT_ACT} = (${Constants.ANDROID_ACTIVITY_CLASS_NAME}) ${Constants.GEN_PARAM_CONTEXT_NAME}")
methodBuilder.endControlFlow()
}
//layout不止一种type
if (classGenCacheInfo.layoutTypeAmount != 1) {
methodBuilder.addStatement("${Constants.GEN_FIELD_RESOURCE}.getValue(${packageName}.R.layout.${layoutName}, ${Constants.GEN_FIELD_TYPED_VALUE_NAME}, true)")
//默认为layout -> "".hashCode = 0
val suffixLength = layoutName.length + 5 // '.' + '.xml'
methodBuilder.addComment("默认为layout")
methodBuilder.addStatement("int ${Constants.GEN_FIELD_LAYOUT_TYPE_HASHCODE_NAME} = 0")
methodBuilder.addStatement("CharSequence ${Constants.GEN_FIELD_LAYOUT_TYPE_STRING_NAME} = ${Constants.GEN_FIELD_TYPED_VALUE_NAME}.string")
methodBuilder.beginControlFlow("if(${Constants.GEN_FIELD_LAYOUT_TYPE_STRING_NAME}.charAt(10) == '-')")
methodBuilder.addStatement("${Constants.GEN_FIELD_LAYOUT_TYPE_HASHCODE_NAME} = ${Constants.GEN_FIELD_LAYOUT_TYPE_STRING_NAME}.subSequence(11, ${Constants.GEN_FIELD_LAYOUT_TYPE_STRING_NAME}.length() - $suffixLength).toString().hashCode()")
//methodBuilder.addStatement("android.util.Log.e(\"touch\", \"f layout type info: \"+___layoutTypeHashCode+\" \"+___layoutTypeStr)")
methodBuilder.endControlFlow()
}
methodBuilder.addStatement(viewGenInfoHolder.localVarDefContent(finalUsedLocalVarMap))
//用到了size
if (classGenCacheInfo.generateFieldInfoMap.allSizeMap.isNotEmpty()) {
methodBuilder.addStatement("android.util.DisplayMetrics ___displayMetrics = ${Constants.GEN_FIELD_RESOURCE}.getDisplayMetrics()")
methodBuilder.addStatement("float ${Constants.GEN_FIELD_DENSITY} = ___displayMetrics.density")
methodBuilder.addStatement("float ${Constants.GEN_FIELD_SCALE_DENSITY} = ___displayMetrics.scaledDensity")
methodBuilder.addStatement("float ${Constants.GEN_FIELD_X_DPI} = ___displayMetrics.xdpi")
}
methodBuilder.addStatement(classGenCacheInfo.generateClassInfo.methodContent)
//cacheInfoFile.writeText(gson.toJson(classGenInfo))
val methodContent = methodBuilder.build().toString()
classGenCacheInfo.generateClassInfo.methodContent = ""
//LogUtil.pl("make class suc: "+layoutName)
//LogUtil.pl("make class "+layoutName +" \n"+methodContent)
//LogUtil.pl("make class "+layoutName +" \n"+classResult.classCacheFile.absolutePath)
PoolManager.pool.clearImportedPackages()
val importPackagePool = PoolManager.pool
usedImportPackageMap.forEach { (importPackage, _) ->
importPackagePool.importPackage(importPackage)
}
val ctClass = importPackagePool.makeClass(className)
try {
val method = CtNewMethod.make(methodContent, ctClass, null, null)
ctClass.addMethod(method)
} catch (e: Exception) {
classGenCacheInfo.generateClassInfo.methodContent = methodContent
LogUtil.pl("make class err:\n"+layoutName+"\n"+e)
throw e
}
classGenCacheInfo.classCacheFile.also { cacheFile->
Files.createParentDirs(cacheFile)
cacheFile.createNewFile()
cacheFile.writeBytes(ctClass.toBytecode())
}
classGenCacheInfo.cacheInfoFile.parentFile.resolve(Constants.QXML_METHOD_CONTENT_CACHE_FILE_NAME).also { cacheFile->
Files.createParentDirs(cacheFile)
cacheFile.createNewFile()
cacheFile.writeText(methodContent)
}
classGenCacheInfo.cacheInfoFile.also { cacheInfoFile ->
Files.createParentDirs(cacheInfoFile)
cacheInfoFile.createNewFile()
cacheInfoFile.writeText(gson.toJson(classGenCacheInfo.generateClassInfo))
}
ctClass.defrost()
ctClass.detach()
}
//添加到pool
PoolManager.pool.appendClassPath(classGenCacheInfo.cacheRootDir.absolutePath)
}
fun createClassFileWithCache(layoutName: String, classGenCacheInfo: ClassGenCacheInfo) {
if (classGenCacheInfo.cacheValid) {
val className = GenClassNameTool.genClassName(layoutName)
PoolManager.pool.clearImportedPackages()
val importPackagePool = PoolManager.pool
classGenCacheInfo.generateClassInfo.usedImportPackageMap.forEach { (importPackage, _) ->
importPackagePool.importPackage(importPackage)
}
val ctClass = importPackagePool.makeClass(className)
//cacheInfoFile.writeText(gson.toJson(classGenInfo))
val methodContent = classGenCacheInfo.generateClassInfo.methodContent
classGenCacheInfo.generateClassInfo.methodContent = ""
//LogUtil.pl("make class suc: "+layoutName)
//LogUtil.pl("make class "+layoutName +" \n"+methodContent)
//LogUtil.pl("make class "+layoutName +" \n"+classResult.classCacheFile.absolutePath)
try {
ctClass.addMethod(CtNewMethod.make(methodContent, ctClass))
} catch (e: Exception) {
classGenCacheInfo.generateClassInfo.methodContent = methodContent
LogUtil.pl("make class err:\n"+layoutName+"\n"+e)
throw e
}
classGenCacheInfo.classCacheFile.also { cacheFile->
Files.createParentDirs(cacheFile)
cacheFile.createNewFile()
cacheFile.writeBytes(ctClass.toBytecode())
}
ctClass.defrost()
ctClass.detach()
}
//添加到pool
PoolManager.pool.appendClassPath(classGenCacheInfo.cacheRootDir.absolutePath)
}
}
| 3
| null |
14
| 77
|
7dd510e477f9d4658f27b09c486171b360a7165c
| 11,080
|
qxml
|
Apache License 2.0
|
app/src/main/java/ru/glindaqu/ejournal/viewModel/implementation/JournalViewModel.kt
|
glindaqu
| 789,473,966
| false
|
{"Kotlin": 62964}
|
package ru.glindaqu.ejournal.viewModel.implementation
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import ru.glindaqu.ejournal.dataModels.AcademicPair
import ru.glindaqu.ejournal.dataModels.AcademicPairInfo
import ru.glindaqu.ejournal.dataModels.JournalRowData
import ru.glindaqu.ejournal.dataModels.StudentDay
import ru.glindaqu.ejournal.dataModels.TeacherInfo
import ru.glindaqu.ejournal.viewModel.api.IJournalViewModel
class JournalViewModel(
app: Application,
) : AndroidViewModel(app),
IJournalViewModel {
override val studentsList =
listOf(
JournalRowData(
id = 1,
studentName = "Дарья",
studentLastname = "Воробьева",
studentPatronymic = "Алексеевна",
data =
arrayOf(
StudentDay(
date = 1707350400000,
pairs =
arrayOf(
AcademicPair(
uid = 1,
pairInfo =
AcademicPairInfo(
id = 1,
teacher =
TeacherInfo(
id = 1,
name = "Виктория",
lastname = "Васечко",
patronymic = "Николаевна",
),
title = "Математика",
),
isStudentAbsence = false,
marks = arrayOf(5, 5),
),
),
),
StudentDay(
date = 1706918400000,
pairs =
arrayOf(
AcademicPair(
uid = 1,
pairInfo =
AcademicPairInfo(
id = 1,
teacher =
TeacherInfo(
id = 1,
name = "Виктория",
lastname = "Васечко",
patronymic = "Николаевна",
),
title = "Математика",
),
isStudentAbsence = false,
marks = arrayOf(5),
),
),
),
),
),
JournalRowData(
id = 2,
studentName = "Анастасия",
studentLastname = "Литвинцева",
studentPatronymic = "Павловна",
data =
arrayOf(
StudentDay(
date = 1707350400000,
pairs =
arrayOf(
AcademicPair(
uid = 1,
pairInfo =
AcademicPairInfo(
id = 1,
teacher =
TeacherInfo(
id = 1,
name = "Виктория",
lastname = "Васечко",
patronymic = "Николаевна",
),
title = "Математика",
),
isStudentAbsence = false,
marks = arrayOf(5, 5),
),
),
),
StudentDay(
date = 1706918400000,
pairs =
arrayOf(
AcademicPair(
uid = 1,
pairInfo =
AcademicPairInfo(
id = 1,
teacher =
TeacherInfo(
id = 1,
name = "Виктория",
lastname = "Васечко",
patronymic = "Николаевна",
),
title = "Математика",
),
isStudentAbsence = false,
marks = arrayOf(5),
),
),
),
),
),
)
}
| 0
|
Kotlin
|
0
| 0
|
bca1da2b4dbeebc72d445a9cfbe33971010ecd54
| 6,187
|
EJournal
|
MIT License
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/base/navigation/NavigationPanelDelegateAdapter.kt
|
djkovrik
| 98,050,611
| false
|
{"Gradle": 7, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 6, "Proguard": 14, "XML": 201, "Kotlin": 418, "Java Properties": 1, "JSON": 2, "Java": 2, "CSS": 1, "INI": 1, "YAML": 1}
|
package com.sedsoftware.yaptalker.presentation.base.navigation
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.extensions.inflate
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemModel
import com.sedsoftware.yaptalker.presentation.model.base.NavigationPanelModel
import kotlinx.android.synthetic.main.item_navigation_panel.view.navigation_go_first
import kotlinx.android.synthetic.main.item_navigation_panel.view.navigation_go_last
import kotlinx.android.synthetic.main.item_navigation_panel.view.navigation_go_next
import kotlinx.android.synthetic.main.item_navigation_panel.view.navigation_go_previous
import kotlinx.android.synthetic.main.item_navigation_panel.view.navigation_pages_label
class NavigationPanelDelegateAdapter(
val navigationClick: NavigationPanelClickListener
) : YapEntityDelegateAdapter {
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder = NavigationViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, item: DisplayedItemModel) {
holder as NavigationViewHolder
holder.bindTo(item as NavigationPanelModel)
}
inner class NavigationViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(parent.inflate(R.layout.item_navigation_panel)) {
fun bindTo(navigation: NavigationPanelModel) {
with(itemView) {
navigation_pages_label.text = navigation.navigationLabel
navigation_go_first.isEnabled = (navigation.currentPage != 1)
navigation_go_previous.isEnabled = (navigation.currentPage != 1)
navigation_go_next.isEnabled = (navigation.currentPage < navigation.totalPages)
navigation_go_last.isEnabled = (navigation.currentPage != navigation.totalPages)
navigation_pages_label.setOnClickListener { navigationClick.goToSelectedPage() }
navigation_go_first.setOnClickListener { navigationClick.goToFirstPage() }
navigation_go_previous.setOnClickListener { navigationClick.goToPreviousPage() }
navigation_go_next.setOnClickListener { navigationClick.goToNextPage() }
navigation_go_last.setOnClickListener { navigationClick.goToLastPage() }
}
}
}
}
| 0
|
Kotlin
|
4
| 9
|
465c34c3dc0dd0488b637073fddf6cd797e78613
| 2,515
|
YapTalker
|
Apache License 2.0
|
kwamp-test-router-conversations/src/test/kotlin/com/laurencegarmstrong/kwamp/router/core/conversations/scripts/SubscribeAndUnsubscribe.kt
|
LaurenceGA
| 142,422,320
| false
| null |
package com.laurencegarmstrong.kwamp.router.core.conversations.scripts
import com.laurencegarmstrong.kwamp.conversations.core.TestConnection
import com.laurencegarmstrong.kwamp.conversations.core.defaultRouter
import com.laurencegarmstrong.kwamp.core.Uri
import com.laurencegarmstrong.kwamp.core.messages.Subscribe
import com.laurencegarmstrong.kwamp.core.messages.Subscribed
import com.laurencegarmstrong.kwamp.core.messages.Unsubscribe
import com.laurencegarmstrong.kwamp.core.messages.Unsubscribed
import com.laurencegarmstrong.kwamp.router.core.conversations.infrastructure.RouterConversation
import io.kotlintest.be
import io.kotlintest.should
import io.kotlintest.specs.StringSpec
class SubUnSub : StringSpec({
"Test Subscribing and unsubscribing" {
val client = TestConnection()
RouterConversation(
defaultRouter(),
client
) {
client.startsASession()
var subscription: Long? = null
client willSend {
Subscribe(
123L,
emptyMap(),
Uri("sub.topic")
)
}
client shouldReceiveMessage { message: Subscribed ->
message.requestId should be(123L)
subscription = message.subscription
}
client willSend { Unsubscribe(456L, subscription!!) }
client shouldReceiveMessage { message: Unsubscribed ->
message.requestId should be(456L)
}
}
}
})
| 0
|
Kotlin
|
2
| 12
|
aac34f83adc1fcc753637e088a75d2e84997a67a
| 1,551
|
kwamp
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/dto/visitnotification/NotificationGroupDto.kt
|
ministryofjustice
| 409,259,375
| false
|
{"Kotlin": 1555306, "PLpgSQL": 154405, "FreeMarker": 14114, "Dockerfile": 1541, "Shell": 238}
|
package uk.gov.justice.digital.hmpps.visitscheduler.dto.visitnotification
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotEmpty
import jakarta.validation.constraints.NotNull
import uk.gov.justice.digital.hmpps.visitscheduler.dto.enums.NotificationEventType
class NotificationGroupDto(
@Schema(description = "notification group Reference", example = "v9*d7*ed*7u", required = true)
@field:NotBlank
val reference: String,
@Schema(description = "notification event type", example = "NON_ASSOCIATION_EVENT", required = true)
@field:NotNull
val type: NotificationEventType,
@Schema(description = "List of details of affected visits", required = true)
@field:NotEmpty
val affectedVisits: List<PrisonerVisitsNotificationDto>,
)
| 4
|
Kotlin
|
2
| 6
|
e2166e8bf546d8792c56ecb3d8d4d838ce63a7c2
| 831
|
visit-scheduler
|
MIT License
|
src/main/java/com/matamercer/microblog/storage/StorageException.kt
|
MataMercer
| 255,196,856
| false
|
{"Kotlin": 166973, "Dockerfile": 626}
|
package com.matamercer.microblog.storage
open class StorageException : RuntimeException {
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
}
| 8
|
Kotlin
|
2
| 2
|
5af13938afc405b398e1589a4a9cac2040556910
| 220
|
matablog
|
MIT License
|
sample/src/main/java/com/zhihu/matisse/sample/SampleActivity.kt
|
REBOOTERS
| 127,521,767
| false
| null |
/*
* Copyright 2017 Zhihu Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhihu.matisse.sample
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.switchmaterial.SwitchMaterial
import com.permissionx.guolindev.PermissionX
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.engine.impl.PicassoEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.CaptureStrategy
private const val TAG = "SampleActivity_TAG"
class SampleActivity : AppCompatActivity(), View.OnClickListener {
private var mAdapter: UriAdapter? = null
private lateinit var switcher: SwitchMaterial
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.zhihu).setOnClickListener(this)
findViewById<View>(R.id.dracula).setOnClickListener(this)
findViewById<View>(R.id.material_design_3).setOnClickListener(this)
findViewById<View>(R.id.only_gif).setOnClickListener(this)
findViewById<View>(R.id.use_official).setOnClickListener(this)
findViewById<View>(R.id.use_official_multi).setOnClickListener(this)
val recyclerView = findViewById<View>(R.id.recyclerview) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = UriAdapter().also { mAdapter = it }
switcher = findViewById(R.id.switcher)
switcher.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
switcher.text = "切竖屏"
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else {
switcher.text = "切横屏"
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
}
// <editor-fold defaultstate="collapsed" desc="onClick">
@SuppressLint("CheckResult")
override fun onClick(v: View) {
val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
listOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO)
} else {
listOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
PermissionX.init(this).permissions(permission).request { allGranted, _, _ ->
if (allGranted) {
startAction(v)
} else {
Toast.makeText(
this@SampleActivity, R.string.permission_request_denied, Toast.LENGTH_LONG
).show()
}
}
}
// </editor-fold>
private fun startAction(v: View) {
var type = ZHIHU_THEME
when (v.id) {
R.id.zhihu -> type = ZHIHU_THEME
R.id.dracula -> type = DRACULA_THEME
R.id.material_design_3 -> type = MATERIAL_DESIGN_3_THEME
R.id.only_gif -> type = ONLY_GIF
R.id.use_official -> type = USE_OFFICIAL
R.id.use_official_multi -> type = USE_OFFICIAL_MULTI
else -> {}
}
mAdapter?.setData(null, null)
if (type == USE_OFFICIAL) {
if (isAndroidS()) {
val intent = Intent(MediaStore.ACTION_PICK_IMAGES)
pickOfficialLauncher.launch(intent)
} else {
val msg = "only supported on Android 13 platform"
Toast.makeText(this@SampleActivity, msg, Toast.LENGTH_LONG).show()
}
return
} else if (type == USE_OFFICIAL_MULTI) {
if (isAndroidS()) {
val intent = Intent(MediaStore.ACTION_PICK_IMAGES)
intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, 10)
pickOfficialMultiLauncher.launch(intent)
} else {
val msg = "only supported on Android 13 platform"
Toast.makeText(this@SampleActivity, msg, Toast.LENGTH_LONG).show()
}
return
}
pickImageLauncher.launch(type)
}
private val pickOfficialLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
val resultCode = it.resultCode
val data = it.data
if (resultCode == Activity.RESULT_OK) {
val uri = data?.data
val path = AndroidFileUtils.getFilePathByUri(this, uri)
val pathList = arrayOf(path).toList()
Log.e(TAG, "uri: $uri")
Log.e(TAG, "path: $path")
val uriList = arrayOf(uri).toList()
mAdapter?.setData(uriList, pathList)
}
}
private val pickOfficialMultiLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
val resultCode = it.resultCode
val data = it.data
if (resultCode == Activity.RESULT_OK) {
Log.e(TAG, ": ${data?.clipData}")
data?.clipData?.let {
Log.e(TAG, "clipData $it")
val uriList = ArrayList<Uri>()
val pathList = ArrayList<String>()
for (i in 0 until it.itemCount) {
Log.e(TAG, ": ${it.getItemAt(i)}")
val uri = it.getItemAt(i).uri
val path = AndroidFileUtils.getFilePathByUri(this, uri) ?: ""
Log.e(TAG, ": $path")
uriList.add(uri)
pathList.add(path)
}
mAdapter?.setData(uriList, pathList)
}
}
}
private val pickImageLauncher = registerForActivityResult(PickImageUriContract()) {
it.let {
if (it.first.isEmpty() || it.second.isEmpty()) {
return@let
}
Log.d(TAG, "paths = ${it.first},urls = ${it.second}")
mAdapter?.setData(it.second, it.first)
}
}
private inner class PickImageUriContract : ActivityResultContract<Any, Pair<List<String>, List<Uri>>>() {
override fun createIntent(context: Context, input: Any): Intent {
val intent: Intent?
when (input) {
DRACULA_THEME -> {
intent = Matisse.from(this@SampleActivity).choose(MimeType.ofImage()).theme(R.style.SimpleMatisse)
.countable(true)
.maxSelectable(1)
.createIntent()
}
MATERIAL_DESIGN_3_THEME -> {
intent = Matisse.from(this@SampleActivity).choose(MimeType.ofImage()).theme(R.style.Matisse_M3)
.restrictOrientation(requestedOrientation).countable(false)
.maxSelectable(9)
.autoHideToolbarOnSingleTap(true).originalEnable(true).maxOriginalSize(10)
.imageEngine(PicassoEngine()).createIntent()
}
ONLY_GIF -> {
intent = Matisse.from(this@SampleActivity).choose(MimeType.of(MimeType.GIF), false)
.restrictOrientation(requestedOrientation).countable(false).theme(R.style.Matisse_Dracula)
.maxSelectable(1) //
// .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
.gridExpectedSize(
resources.getDimensionPixelSize(R.dimen.grid_expected_size)
).restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).thumbnailScale(0.85f)
.imageEngine(GlideEngine()).showSingleMediaType(true) //
// .originalEnable(true)
.maxOriginalSize(10).autoHideToolbarOnSingleTap(true).createIntent()
}
else -> {
intent = Matisse.from(this@SampleActivity).choose(MimeType.ofImage(), false)
.restrictOrientation(requestedOrientation).countable(true).capture(true).captureStrategy(
CaptureStrategy(true, "com.zhihu.matisse.sample.fileprovider", "test")
).maxSelectable(9).addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
.gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
.thumbnailScale(0.85f).imageEngine(GlideEngine())
.setOnSelectedListener { uriList: List<Uri?>?, pathList: List<String?> ->
Log.e(
"onSelected", "onSelected: pathList=$pathList"
)
}.showSingleMediaType(true).originalEnable(true).maxOriginalSize(10)
.autoHideToolbarOnSingleTap(true).setOnCheckedListener { isChecked: Boolean ->
Log.e(
"isChecked", "onCheck: isChecked=$isChecked"
)
}.createIntent()
}
}
return intent!!
}
override fun parseResult(resultCode: Int, intent: Intent?): Pair<List<String>, List<Uri>> {
if (resultCode == Activity.RESULT_OK) {
val paths = Matisse.obtainPathResult(intent)
val uris = Matisse.obtainResult(intent)
return Pair(paths, uris)
}
return Pair(emptyList(), emptyList())
}
}
private fun isAndroidS(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
}
companion object {
private const val ZHIHU_THEME = 1
private const val DRACULA_THEME = ZHIHU_THEME + 1
private const val MATERIAL_DESIGN_3_THEME = DRACULA_THEME + 1
private const val ONLY_GIF = MATERIAL_DESIGN_3_THEME + 1
private const val USE_OFFICIAL = ONLY_GIF + 1
private const val USE_OFFICIAL_MULTI = USE_OFFICIAL + 1
}
}
| 3
| null |
7
| 30
|
f7fcf8548eda01acbc37aa02fde08ced85330018
| 11,204
|
Matisse
|
Apache License 2.0
|
processors/crypto-processor/src/integrationTest/kotlin/net/corda/processors/crypto/tests/CryptoProcessorTests.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.processors.crypto.tests
import com.typesafe.config.ConfigRenderOptions
import net.corda.avro.serialization.CordaAvroSerializationFactory
import net.corda.crypto.cipher.suite.CipherSchemeMetadata
import net.corda.crypto.cipher.suite.SignatureSpecImpl
import net.corda.crypto.cipher.suite.SignatureSpecs
import net.corda.crypto.cipher.suite.SignatureVerificationService
import net.corda.crypto.cipher.suite.publicKeyId
import net.corda.crypto.cipher.suite.sha256Bytes
import net.corda.crypto.client.CryptoOpsClient
import net.corda.crypto.client.SessionEncryptionOpsClient
import net.corda.crypto.client.hsm.HSMRegistrationClient
import net.corda.crypto.core.CryptoConsts
import net.corda.crypto.core.CryptoTenants
import net.corda.crypto.core.SecureHashImpl
import net.corda.crypto.core.ShortHash
import net.corda.crypto.core.publicKeyIdFromBytes
import net.corda.crypto.flow.CryptoFlowOpsTransformer
import net.corda.crypto.flow.factory.CryptoFlowOpsTransformerFactory
import net.corda.crypto.hes.EphemeralKeyPairEncryptor
import net.corda.crypto.hes.HybridEncryptionParams
import net.corda.crypto.hes.StableKeyPairDecryptor
import net.corda.crypto.persistence.db.model.CryptoEntities
import net.corda.data.config.Configuration
import net.corda.data.config.ConfigurationSchemaVersion
import net.corda.data.crypto.wire.ops.flow.FlowOpsResponse
import net.corda.data.crypto.wire.ops.rpc.queries.CryptoKeyOrderBy
import net.corda.data.flow.event.FlowEvent
import net.corda.db.admin.LiquibaseSchemaMigrator
import net.corda.db.connection.manager.VirtualNodeDbType
import net.corda.db.core.DbPrivilege
import net.corda.db.messagebus.testkit.DBSetup
import net.corda.db.schema.CordaDb
import net.corda.db.testkit.DatabaseInstaller
import net.corda.db.testkit.TestDbInfo
import net.corda.libs.configuration.datamodel.ConfigurationEntities
import net.corda.libs.configuration.datamodel.DbConnectionConfig
import net.corda.libs.packaging.core.CpiIdentifier
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.lifecycle.registry.LifecycleRegistry
import net.corda.messaging.api.publisher.Publisher
import net.corda.messaging.api.publisher.config.PublisherConfig
import net.corda.messaging.api.publisher.factory.PublisherFactory
import net.corda.messaging.api.records.Record
import net.corda.messaging.api.subscription.Subscription
import net.corda.messaging.api.subscription.config.SubscriptionConfig
import net.corda.messaging.api.subscription.factory.SubscriptionFactory
import net.corda.orm.EntityManagerFactoryFactory
import net.corda.orm.JpaEntitiesRegistry
import net.corda.orm.utils.transaction
import net.corda.processors.crypto.CryptoProcessor
import net.corda.processors.crypto.tests.infra.FlowOpsResponses
import net.corda.processors.crypto.tests.infra.RESPONSE_TOPIC
import net.corda.processors.crypto.tests.infra.TestDependenciesTracker
import net.corda.processors.crypto.tests.infra.makeBootstrapConfig
import net.corda.processors.crypto.tests.infra.makeClientId
import net.corda.processors.crypto.tests.infra.makeCryptoConfig
import net.corda.processors.crypto.tests.infra.makeMessagingConfig
import net.corda.processors.crypto.tests.infra.makeStateManagerConfig
import net.corda.processors.crypto.tests.infra.publishVirtualNodeInfo
import net.corda.processors.crypto.tests.infra.randomDataByteArray
import net.corda.processors.crypto.tests.infra.webServerPort
import net.corda.schema.Schemas
import net.corda.schema.Schemas.Config.CONFIG_TOPIC
import net.corda.schema.configuration.ConfigKeys.CRYPTO_CONFIG
import net.corda.schema.configuration.ConfigKeys.MESSAGING_CONFIG
import net.corda.schema.configuration.ConfigKeys.STATE_MANAGER_CONFIG
import net.corda.test.util.TestRandom
import net.corda.test.util.eventually
import net.corda.test.util.identity.createTestHoldingIdentity
import net.corda.v5.crypto.DigestAlgorithmName
import net.corda.v5.crypto.KeySchemeCodes.ECDSA_SECP256R1_CODE_NAME
import net.corda.v5.crypto.SecureHash
import net.corda.virtualnode.VirtualNodeInfo
import net.corda.virtualnode.read.VirtualNodeInfoReadService
import net.corda.web.api.WebServer
import org.assertj.core.api.Assertions.assertThat
import org.bouncycastle.jcajce.provider.util.DigestFactory
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import org.osgi.test.common.annotation.InjectService
import org.osgi.test.junit5.service.ServiceExtension
import org.slf4j.LoggerFactory
import java.security.PublicKey
import java.time.Duration
import java.time.Instant
import java.util.UUID
import java.util.stream.Stream
import javax.persistence.EntityManagerFactory
@ExtendWith(ServiceExtension::class, DBSetup::class)
class CryptoProcessorTests {
companion object {
private val logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
private val CLIENT_ID = makeClientId<CryptoProcessorTests>()
@InjectService(timeout = 5000L)
lateinit var lifecycleRegistry: LifecycleRegistry
@InjectService(timeout = 5000L)
lateinit var coordinatorFactory: LifecycleCoordinatorFactory
@InjectService(timeout = 5000L)
lateinit var publisherFactory: PublisherFactory
@InjectService(timeout = 5000L)
lateinit var subscriptionFactory: SubscriptionFactory
@InjectService(timeout = 5000L)
lateinit var ephemeralEncryptor: EphemeralKeyPairEncryptor
@InjectService(timeout = 5000L)
lateinit var stableDecryptor: StableKeyPairDecryptor
@InjectService(timeout = 5000L)
lateinit var cryptoFlowOpsTransformerFactory: CryptoFlowOpsTransformerFactory
@InjectService(timeout = 5000L)
lateinit var opsClient: CryptoOpsClient
@InjectService(timeout = 5000L)
lateinit var sessionEncryptionOpsClient: SessionEncryptionOpsClient
@InjectService(timeout = 5000L)
lateinit var verifier: SignatureVerificationService
@InjectService(timeout = 5000L)
lateinit var schemeMetadata: CipherSchemeMetadata
@InjectService(timeout = 5000)
lateinit var entitiesRegistry: JpaEntitiesRegistry
@InjectService(timeout = 5000)
lateinit var entityManagerFactoryFactory: EntityManagerFactoryFactory
@InjectService(timeout = 5000L)
lateinit var hsmRegistrationClient: HSMRegistrationClient
@InjectService(timeout = 5000)
lateinit var lbm: LiquibaseSchemaMigrator
@InjectService(timeout = 5000)
lateinit var virtualNodeInfoReader: VirtualNodeInfoReadService
@InjectService(timeout = 5000L)
lateinit var cryptoProcessor: CryptoProcessor
@InjectService(timeout = 5000L)
lateinit var cordaAvroSerializationFactory: CordaAvroSerializationFactory
@InjectService(timeout = 5000L)
lateinit var webServer: WebServer
private lateinit var publisher: Publisher
private lateinit var flowOpsResponses: FlowOpsResponses
private lateinit var flowOpsResponsesSub: Subscription<String, FlowEvent>
private lateinit var transformer: CryptoFlowOpsTransformer
private val vnodeIdentity =
createTestHoldingIdentity("CN=Alice, O=Alice Corp, L=LDN, C=GB", UUID.randomUUID().toString())
private val vnodeId: String = vnodeIdentity.shortHash.value
private val vnodeDb = TestDbInfo(
name = VirtualNodeDbType.CRYPTO.getConnectionName(vnodeIdentity.shortHash),
schemaName = "vnode_crypto"
)
private val vnodeIdentity2 =
createTestHoldingIdentity("CN=Bob, O=Bob Corp, L=LDN, C=GB", UUID.randomUUID().toString())
private val vnodeId2: String = vnodeIdentity2.shortHash.value
private val vnodeDb2 = TestDbInfo(
name = VirtualNodeDbType.CRYPTO.getConnectionName(vnodeIdentity2.shortHash),
schemaName = "vnode_crypto"
)
private val clusterDb = TestDbInfo.createConfig()
private val cryptoDb = TestDbInfo(
name = CordaDb.Crypto.persistenceUnitName
)
private val boostrapConfig = makeBootstrapConfig(clusterDb.config)
private val messagingConfig = makeMessagingConfig()
private val cryptoConfig = makeCryptoConfig()
private val statemanagerConfig = makeStateManagerConfig(clusterDb.config)
private lateinit var connectionIds: Map<String, UUID>
private lateinit var tracker: TestDependenciesTracker
@JvmStatic
@BeforeAll
fun setup() {
setupPrerequisites()
setupDatabases()
setupVirtualNodeInfo()
startDependencies()
waitForVirtualNodeInfoReady()
assignHSMs()
}
@JvmStatic
@AfterAll
fun cleanup() {
webServer.stop()
if (::flowOpsResponsesSub.isInitialized) {
flowOpsResponsesSub.close()
}
cryptoProcessor.stop()
tracker.waitUntilStopped(Duration.ofSeconds(5))
}
private fun setupPrerequisites() {
// Creating this publisher first (using the messagingConfig) will ensure we're forcing
// the in-memory message bus. Otherwise, we may attempt to use a real database for the test
// and that can cause message bus conflicts when the tests are run in parallel.
publisher = publisherFactory.createPublisher(PublisherConfig(CLIENT_ID), messagingConfig)
logger.info("Publishing prerequisite config")
publisher.publish(
listOf(
Record(
CONFIG_TOPIC,
MESSAGING_CONFIG,
Configuration(
messagingConfig.root().render(),
messagingConfig.root().render(),
0,
ConfigurationSchemaVersion(1, 0)
)
),
Record(
CONFIG_TOPIC,
CRYPTO_CONFIG,
Configuration(
cryptoConfig.root().render(),
cryptoConfig.root().render(),
0,
ConfigurationSchemaVersion(1, 0)
)
),
Record(
CONFIG_TOPIC,
STATE_MANAGER_CONFIG,
Configuration(
statemanagerConfig.root().render(),
statemanagerConfig.root().render(),
0,
ConfigurationSchemaVersion(1, 0)
)
)
)
)
flowOpsResponses = FlowOpsResponses(
cordaAvroSerializationFactory.createAvroDeserializer({}, FlowOpsResponse::class.java)
)
flowOpsResponsesSub = subscriptionFactory.createDurableSubscription(
subscriptionConfig = SubscriptionConfig(
groupName = "TEST",
eventTopic = Schemas.Flow.FLOW_SESSION
),
processor = flowOpsResponses,
messagingConfig = messagingConfig,
partitionAssignmentListener = null
).also { it.start() }
transformer = cryptoFlowOpsTransformerFactory.create(
requestingComponent = "test",
responseTopic = RESPONSE_TOPIC
)
}
private fun setupDatabases() {
val databaseInstaller = DatabaseInstaller(entityManagerFactoryFactory, lbm, entitiesRegistry)
val configEmf = databaseInstaller.setupClusterDatabase(
clusterDb,
"config",
ConfigurationEntities.classes
)
databaseInstaller.setupDatabase(
cryptoDb,
"crypto"
).close()
databaseInstaller.setupDatabase(
vnodeDb,
"vnode-crypto",
CryptoEntities.classes
).close()
databaseInstaller.setupDatabase(
vnodeDb2,
"vnode-crypto",
CryptoEntities.classes
).close()
connectionIds = addDbConnectionConfigs(configEmf, cryptoDb, vnodeDb, vnodeDb2)
configEmf.close()
}
private fun addDbConnectionConfigs(
configEmf: EntityManagerFactory,
vararg dbs: TestDbInfo
): Map<String, UUID> {
val ids = mutableMapOf<String, UUID>()
dbs.forEach { db ->
val configAsString = db.config.root().render(ConfigRenderOptions.concise())
configEmf.transaction {
val existing = it.createQuery(
"""
SELECT c FROM DbConnectionConfig c WHERE c.name=:name AND c.privilege=:privilege
""".trimIndent(), DbConnectionConfig::class.java
)
.setParameter("name", db.name)
.setParameter("privilege", DbPrivilege.DML)
.resultList
ids[db.name] = if (existing.isEmpty()) {
val record = DbConnectionConfig(
UUID.randomUUID(),
db.name,
DbPrivilege.DML,
Instant.now(),
"sa",
"Test ${db.name}",
configAsString
)
it.persist(record)
record.id
} else {
existing.first().id
}
}
}
return ids
}
private fun setupVirtualNodeInfo() {
publisher.publishVirtualNodeInfo(
VirtualNodeInfo(
holdingIdentity = vnodeIdentity,
cpiIdentifier = CpiIdentifier(
name = "cpi",
version = "1",
signerSummaryHash = TestRandom.secureHash()
),
cryptoDmlConnectionId = connectionIds.getValue(vnodeDb.name),
uniquenessDmlConnectionId = UUID.randomUUID(),
vaultDmlConnectionId = UUID.randomUUID(),
timestamp = Instant.now()
)
)
publisher.publishVirtualNodeInfo(
VirtualNodeInfo(
holdingIdentity = vnodeIdentity2,
cpiIdentifier = CpiIdentifier(
name = "cpi",
version = "1",
signerSummaryHash = TestRandom.secureHash()
),
cryptoDmlConnectionId = connectionIds.getValue(vnodeDb2.name),
uniquenessDmlConnectionId = UUID.randomUUID(),
vaultDmlConnectionId = UUID.randomUUID(),
timestamp = Instant.now()
)
)
}
private fun startDependencies() {
webServer.start(webServerPort)
cryptoProcessor.start(boostrapConfig)
opsClient.start()
sessionEncryptionOpsClient.start()
hsmRegistrationClient.start()
stableDecryptor.start()
tracker = TestDependenciesTracker(
coordinatorFactory,
lifecycleRegistry,
setOf(
LifecycleCoordinatorName.forComponent<CryptoProcessor>(),
LifecycleCoordinatorName.forComponent<HSMRegistrationClient>(),
LifecycleCoordinatorName.forComponent<StableKeyPairDecryptor>(),
LifecycleCoordinatorName.forComponent<SessionEncryptionOpsClient>(),
LifecycleCoordinatorName.forComponent<WebServer>(),
)
).also {
it.start()
}
tracker.waitUntilAllUp(Duration.ofSeconds(60))
}
private fun waitForVirtualNodeInfoReady() {
eventually {
val info = virtualNodeInfoReader.get(vnodeIdentity)
assertNotNull(info)
assertEquals(connectionIds.getValue(vnodeDb.name), info!!.cryptoDmlConnectionId)
}
}
private fun assignHSMs() {
val cryptoCategories = setOf(
CryptoConsts.Categories.CI,
CryptoConsts.Categories.LEDGER,
CryptoConsts.Categories.TLS,
CryptoConsts.Categories.SESSION_INIT,
)
cryptoCategories.forEach {
// cluster is assigned in the crypto processor
if (hsmRegistrationClient.findHSM(vnodeId, it) == null) {
hsmRegistrationClient.assignSoftHSM(vnodeId, it)
}
}
hsmRegistrationClient.assignSoftHSM(vnodeId2, CryptoConsts.Categories.LEDGER)
}
@JvmStatic
fun testCategories(): Stream<Arguments> = Stream.of(
Arguments.of(CryptoConsts.Categories.LEDGER, vnodeId),
Arguments.of(CryptoConsts.Categories.TLS, vnodeId),
Arguments.of(CryptoConsts.Categories.SESSION_INIT, vnodeId),
Arguments.of(CryptoConsts.Categories.JWT_KEY, CryptoTenants.REST),
Arguments.of(CryptoConsts.Categories.TLS, CryptoTenants.P2P)
)
@JvmStatic
fun testTenants(): Stream<Arguments> = Stream.of(
Arguments.of(vnodeId),
Arguments.of(CryptoTenants.P2P),
Arguments.of(CryptoTenants.REST)
)
}
@ParameterizedTest
@MethodSource("testCategories")
fun `Should be able to get supported schemes`(
category: String,
tenantId: String
) {
val supportedSchemes = opsClient.getSupportedSchemes(tenantId, category)
assertTrue(supportedSchemes.isNotEmpty())
}
@ParameterizedTest
@MethodSource("testTenants")
fun `Should not find unknown public key by its id`(
tenantId: String,
) {
val found = opsClient.lookupKeysByIds(
tenantId = tenantId,
keyIds = listOf(ShortHash.of(publicKeyIdFromBytes(UUID.randomUUID().toString().toByteArray())))
)
assertEquals(0, found.size)
}
@Test
fun `test encrypt and decrypt`() {
val data = "hello world".toByteArray()
val encrypted = sessionEncryptionOpsClient.encryptSessionData(data)
assertThat(encrypted).isNotEqualTo(data)
val decrypted = sessionEncryptionOpsClient.decryptSessionData(encrypted)
assertThat(decrypted).isEqualTo(data)
}
//
// @ParameterizedTest
// @MethodSource("testTenants")
// fun `Should return empty collection when lookp filter does not match`(
// tenantId: String
// ) {
// val found = opsClient.lookup(
// tenantId = tenantId,
// skip = 0,
// take = 20,
// orderBy = CryptoKeyOrderBy.NONE,
// filter = mapOf(
// CryptoConsts.SigningKeyFilters.ALIAS_FILTER to UUID.randomUUID().toString()
// )
// )
// assertEquals(0, found.size)
// }
//
// @ParameterizedTest
// @MethodSource("testTenants")
// fun `Should generate a new key pair using alias then find it and use for hybrid encryption`(
// tenantId: String
// ) {
// val alias = UUID.randomUUID().toString()
//
// val category = CryptoConsts.Categories.SESSION_INIT
//
// val original = opsClient.generateKeyPair(
// tenantId = tenantId,
// category = category,
// alias = alias,
// scheme = X25519_CODE_NAME
// )
//
// `Should find existing public key by its id`(tenantId, alias, original, category, null)
//
// `Should find existing public key by its alias`(tenantId, alias, original, category)
//
// `Should be able to derive secret and encrypt`(tenantId, original)
// }
//
// @ParameterizedTest
// @MethodSource("testTenants")
// fun `Should generate a new a new fresh key pair then find it and use for hybrid encryption`(
// tenantId: String
// ) {
// val category = CryptoConsts.Categories.SESSION_INIT
//
// val original = opsClient.freshKey(
// tenantId = tenantId,
// category = category,
// scheme = X25519_CODE_NAME,
// context = CryptoOpsClient.EMPTY_CONTEXT
// )
//
// `Should find existing public key by its id`(tenantId, null, original, category, null)
//
// `Should be able to derive secret and encrypt`(tenantId, original)
// }
//
// @ParameterizedTest
// @MethodSource("testCategories")
// fun `Should generate a new key pair using alias then find it and use for signing`(
// category: String,
// tenantId: String
// ) {
// val alias = UUID.randomUUID().toString()
//
// val original = opsClient.generateKeyPair(
// tenantId = tenantId,
// category = category,
// alias = alias,
// scheme = ECDSA_SECP256R1_CODE_NAME
// )
//
// `Should find existing public key by its id`(tenantId, alias, original, category, null)
//
// `Should find existing public key by its alias`(tenantId, alias, original, category)
//
// `Should be able to sign and verify`(tenantId, original)
//
// `Should be able to sign and verify by inferring signtaure spec`(tenantId, original)
//
// `Should be able to sign using custom signature spec`(tenantId, original)
//
// `Should be able to sign by flow ops and verify`(tenantId, original)
//
// `Should be able to sign by flow ops and verify bu inferring signature spec`(tenantId, original)
// }
//
// @ParameterizedTest
// @MethodSource("testTenants")
// fun `Should generate a new fresh key pair with external id then find it and use for signing`(
// tenantId: String
// ) {
// val externalId = UUID.randomUUID().toString()
//
// val original = opsClient.freshKey(
// tenantId = tenantId,
// category = CryptoConsts.Categories.CI,
// externalId = externalId,
// scheme = ECDSA_SECP256R1_CODE_NAME,
// context = CryptoOpsClient.EMPTY_CONTEXT
// )
//
// `Should find existing public key by its id`(
// tenantId,
// null,
// original,
// CryptoConsts.Categories.CI,
// externalId
// )
//
// `Should be able to sign and verify`(tenantId, original)
//
// `Should be able to sign and verify by inferring signtaure spec`(tenantId, original)
//
// `Should be able to sign using custom signature spec`(tenantId, original)
//
// `Should be able to sign by flow ops and verify`(tenantId, original)
//
// `Should be able to sign by flow ops and verify bu inferring signature spec`(tenantId, original)
// }
//
// @ParameterizedTest
// @MethodSource("testTenants")
// fun `Should generate a new fresh key pair without external id then find it and use for signing`(
// tenantId: String
// ) {
// val original = opsClient.freshKey(
// tenantId = tenantId,
// category = CryptoConsts.Categories.CI,
// scheme = ECDSA_SECP256R1_CODE_NAME,
// context = CryptoOpsClient.EMPTY_CONTEXT
// )
//
// `Should find existing public key by its id`(
// tenantId,
// null,
// original,
// CryptoConsts.Categories.CI,
// null
// )
//
// `Should be able to sign and verify`(tenantId, original)
//
// `Should be able to sign and verify by inferring signtaure spec`(tenantId, original)
//
// `Should be able to sign using custom signature spec`(tenantId, original)
//
// `Should be able to sign by flow ops and verify`(tenantId, original)
//
// `Should be able to sign by flow ops and verify bu inferring signature spec`(tenantId, original)
// }
private fun `Should find existing public key by its id`(
tenantId: String,
alias: String?,
publicKey: PublicKey,
category: String,
externalId: String?,
) {
val found = opsClient.lookupKeysByIds(
tenantId = tenantId,
keyIds = listOf(ShortHash.of(publicKey.publicKeyId()))
)
assertEquals(1, found.size)
assertEquals(publicKey.publicKeyId(), found[0].id)
assertEquals(tenantId, found[0].tenantId)
if (alias.isNullOrBlank()) {
assertNull(found[0].alias)
} else {
assertEquals(alias, found[0].alias)
}
assertEquals(category, found[0].category)
assertTrue(publicKey.encoded.contentEquals(found[0].publicKey.array()))
assertNotNull(found[0].schemeCodeName)
assertNotNull(found[0].masterKeyAlias)
if (externalId.isNullOrBlank()) {
assertNull(found[0].externalId)
} else {
assertEquals(externalId, found[0].externalId)
}
assertNull(found[0].hsmAlias)
}
private fun `Should find existing public key by its alias`(
tenantId: String,
alias: String,
publicKey: PublicKey,
category: String
) {
val found = opsClient.lookup(
tenantId = tenantId,
skip = 0,
take = 20,
orderBy = CryptoKeyOrderBy.NONE,
filter = mapOf(
CryptoConsts.SigningKeyFilters.ALIAS_FILTER to alias
)
)
assertEquals(1, found.size)
assertEquals(publicKey.publicKeyId(), found[0].id)
assertEquals(tenantId, found[0].tenantId)
assertEquals(alias, found[0].alias)
assertEquals(category, found[0].category)
assertTrue(publicKey.encoded.contentEquals(found[0].publicKey.array()))
assertNotNull(found[0].schemeCodeName)
assertNotNull(found[0].masterKeyAlias)
assertNull(found[0].externalId)
assertNull(found[0].hsmAlias)
}
private fun `Should be able to sign and verify`(
tenantId: String,
publicKey: PublicKey
) {
schemeMetadata.supportedSignatureSpec(schemeMetadata.findKeyScheme(publicKey)).forEach { spec ->
val data = randomDataByteArray()
val signature = opsClient.sign(
tenantId = tenantId,
publicKey = publicKey,
signatureSpec = spec,
data = data
)
assertEquals(publicKey, signature.by)
assertTrue(signature.bytes.isNotEmpty())
verifier.verify(
originalData = data,
signatureData = signature.bytes,
publicKey = publicKey,
signatureSpec = spec
)
}
}
private fun `Should be able to derive secret and encrypt`(tenantId: String, publicKey: PublicKey) {
val plainText = "Hello World!".toByteArray()
val cipherText = ephemeralEncryptor.encrypt(
otherPublicKey = publicKey,
plainText = plainText
) { _, _ ->
HybridEncryptionParams(ByteArray(DigestFactory.getDigest("SHA-256").digestSize).apply {
schemeMetadata.secureRandom.nextBytes(this)
}, null)
}
val decryptedPlainTex = stableDecryptor.decrypt(
tenantId = tenantId,
salt = cipherText.params.salt,
publicKey = publicKey,
otherPublicKey = cipherText.publicKey,
cipherText = cipherText.cipherText,
aad = null
)
assertArrayEquals(plainText, decryptedPlainTex)
}
private fun `Should be able to sign and verify by inferring signtaure spec`(
tenantId: String,
publicKey: PublicKey
) {
schemeMetadata.inferableDigestNames(schemeMetadata.findKeyScheme(publicKey)).forEach { digest ->
val data = randomDataByteArray()
val signature = opsClient.sign(
tenantId = tenantId,
publicKey = publicKey,
signatureSpec = schemeMetadata.inferSignatureSpec(publicKey, digest)!!,
data = data
)
assertEquals(publicKey, signature.by)
assertTrue(signature.bytes.isNotEmpty())
verifier.verify(
originalData = data,
signatureData = signature.bytes,
publicKey = publicKey,
digest = digest
)
}
}
private fun `Should be able to sign using custom signature spec`(
tenantId: String,
publicKey: PublicKey
) {
val data = randomDataByteArray()
val signatureSpec = when (publicKey.algorithm) {
"EC" -> SignatureSpecImpl("SHA512withECDSA")
"RSA" -> SignatureSpecs.RSASSA_PSS_SHA256
else -> throw IllegalArgumentException("Test supports only RSA or ECDSA")
}
val signature = opsClient.sign(
tenantId = tenantId,
publicKey = publicKey,
signatureSpec = signatureSpec,
data = data
)
assertEquals(publicKey, signature.by)
assertTrue(signature.bytes.isNotEmpty())
verifier.verify(
originalData = data,
signatureData = signature.bytes,
publicKey = publicKey,
signatureSpec = signatureSpec
)
}
// private fun `Should be able to sign by flow ops and verify`(
// tenantId: String,
// publicKey: PublicKey
// ) {
// schemeMetadata.supportedSignatureSpec(schemeMetadata.findKeyScheme(publicKey)).forEach { spec ->
// val data = randomDataByteArray()
// val key = UUID.randomUUID().toString()
// val requestId = UUID.randomUUID().toString()
// val event = transformer.createSign(
// requestId = requestId,
// tenantId = tenantId,
// encodedPublicKeyBytes = publicKey.encoded,
// signatureSpec = spec,
// data = data,
// flowExternalEventContext = ExternalEventContext(requestId, key, KeyValuePairList(emptyList()))
// )
// logger.info(
// "Publishing: createSign({}, {}, {}), request id: $requestId, flow id: $key",
// tenantId,
// publicKey.publicKeyId(),
// spec
// )
// publisher.publish(
// listOf(
// Record(
// topic = FLOW_OPS_MESSAGE_TOPIC,
// key = key,
// value = event
// )
// )
// ).forEach { it.get() }
// logger.info("Waiting for response for createSign")
// val response = flowOpsResponses.waitForResponse(key)
// val signature = transformer.transform(response) as DigitalSignatureWithKey
// assertEquals(publicKey, signature.by)
// assertTrue(signature.bytes.isNotEmpty())
// verifier.verify(
// originalData = data,
// signatureData = signature.bytes,
// publicKey = publicKey,
// signatureSpec = spec
// )
// }
// }
//
// private fun `Should be able to sign by flow ops and verify bu inferring signature spec`(
// tenantId: String,
// publicKey: PublicKey
// ) {
// schemeMetadata.inferableDigestNames(schemeMetadata.findKeyScheme(publicKey)).forEach { digest ->
// val data = randomDataByteArray()
// val key = UUID.randomUUID().toString()
// val spec = schemeMetadata.inferSignatureSpec(publicKey, digest)!!
// val requestId = UUID.randomUUID().toString()
// val event = transformer.createSign(
// requestId = requestId,
// tenantId = tenantId,
// encodedPublicKeyBytes = publicKey.encoded,
// signatureSpec = spec,
// data = data,
// flowExternalEventContext = ExternalEventContext(requestId, key, KeyValuePairList(emptyList()))
// )
// logger.info(
// "Publishing: createSign({}, {}, {})",
// tenantId,
// publicKey.publicKeyId(),
// spec
// )
// publisher.publish(
// listOf(
// Record(
// topic = FLOW_OPS_MESSAGE_TOPIC,
// key = key,
// value = event
// )
// )
// ).forEach { it.get() }
// logger.info("Waiting for response for createSign")
// val response = flowOpsResponses.waitForResponse(key)
// val signature = transformer.transform(response) as DigitalSignatureWithKey
// assertEquals(publicKey, signature.by)
// assertTrue(signature.bytes.isNotEmpty())
// verifier.verify(
// originalData = data,
// signatureData = signature.bytes,
// publicKey = publicKey,
// digest = digest
// )
// }
// }
//
// @Test
// fun `filterMyKeys filters and returns keys owned by the specified vnode`() {
// val randomId = UUID.randomUUID()
// val vnodeKey1 = generateLedgerKey(vnodeId, "vnode-key-1-$randomId")
// val vnodeKey2 = generateLedgerKey(vnodeId, "vnode-key-2-$randomId")
// val vnode2Key1 = generateLedgerKey(vnodeId2, "vnode2-key-1-$randomId")
// val vnode2Key2 = generateLedgerKey(vnodeId2, "vnode2-key-2-$randomId")
// val vnode2Key3 = generateLedgerKey(vnodeId2, "vnode2-key-3-$randomId")
//
// val vnodeKeys = listOf(vnodeKey1, vnodeKey2)
// val vnode2Keys = listOf(vnode2Key1, vnode2Key2, vnode2Key3)
// val allKeys = vnodeKeys + vnode2Keys
//
// assertEquals(vnodeKeys, opsClient.filterMyKeys(vnodeId, allKeys))
// assertEquals(vnode2Keys, opsClient.filterMyKeys(vnodeId2, allKeys))
// }
//
// @Test
// fun `filterMyKeys works for both short key ids and full key ids`() {
// val randomId = UUID.randomUUID()
// val vnodeKey1 = generateLedgerKey(vnodeId, "vnode-key-1-$randomId")
// val vnodeKey2 = generateLedgerKey(vnodeId, "vnode-key-2-$randomId")
// val vnode2Key1 = generateLedgerKey(vnodeId2, "vnode2-key-1-$randomId")
// val vnode2Key2 = generateLedgerKey(vnodeId2, "vnode2-key-2-$randomId")
// val vnode2Key3 = generateLedgerKey(vnodeId2, "vnode2-key-3-$randomId")
//
// val vnodeKeys = listOf(vnodeKey1, vnodeKey2)
// val vnode2Keys = listOf(vnode2Key1, vnode2Key2, vnode2Key3)
// val allKeys = vnodeKeys + vnode2Keys
//
// assertEquals(vnodeKeys, opsClient.filterMyKeys(vnodeId, allKeys))
// assertEquals(vnode2Keys, opsClient.filterMyKeys(vnodeId2, allKeys))
// assertEquals(vnodeKeys, opsClient.filterMyKeys(vnodeId, allKeys, usingFullIds = true))
// assertEquals(vnode2Keys, opsClient.filterMyKeys(vnodeId2, allKeys, usingFullIds = true))
// }
//
// @Test
// fun `lookup works for both short key ids and full key ids`() {
// val randomId = UUID.randomUUID()
// val vnodeKey1 = generateLedgerKey(vnodeId, "vnode-key-1-$randomId")
// val vnodeKey2 = generateLedgerKey(vnodeId, "vnode-key-2-$randomId")
// val vnode2Key1 = generateLedgerKey(vnodeId2, "vnode2-key-1-$randomId")
// val vnode2Key2 = generateLedgerKey(vnodeId2, "vnode2-key-2-$randomId")
// val vnode2Key3 = generateLedgerKey(vnodeId2, "vnode2-key-3-$randomId")
//
// val vnodeKeys = listOf(vnodeKey1, vnodeKey2)
// val vnode2Keys = listOf(vnode2Key1, vnode2Key2, vnode2Key3)
// val vnodeKeysEncoded = vnodeKeys.map { it.encoded }
// val vnode2KeysEncoded = vnode2Keys.map { it.encoded }
//
// val allKeys = vnodeKeys + vnode2Keys
// val allKeyIds = allKeys.map { it.publicKeyId() }.map { ShortHash.of(it) }
// val allKeyFullIds = allKeys.map { it.fullId() }
//
// val queriedVnodeKeysEncoded = opsClient.lookupKeysByIds(vnodeId, allKeyIds).map { it.publicKey.toBytes() }
// val queriedVnode2KeysEncoded = opsClient.lookupKeysByIds(vnodeId2, allKeyIds).map { it.publicKey.toBytes() }
// val queriedByFullIdsVnodeKeysEncoded = opsClient.lookupKeysByFullIds(vnodeId, allKeyFullIds).map { it.publicKey.toBytes() }
// val queriedByFullIdsVnode2KeysEncoded = opsClient.lookupKeysByFullIds(vnodeId2, allKeyFullIds).map { it.publicKey.toBytes() }
//
// assertTrue(listsOfBytesAreEqual(vnodeKeysEncoded, queriedVnodeKeysEncoded))
// assertTrue(listsOfBytesAreEqual(vnode2KeysEncoded, queriedVnode2KeysEncoded))
// assertTrue(listsOfBytesAreEqual(queriedVnodeKeysEncoded, queriedByFullIdsVnodeKeysEncoded))
// assertTrue(listsOfBytesAreEqual(queriedVnode2KeysEncoded, queriedByFullIdsVnode2KeysEncoded))
// }
private fun generateLedgerKey(tenantId: String, keyAlias: String): PublicKey =
opsClient.generateKeyPair(
tenantId = tenantId,
category = CryptoConsts.Categories.LEDGER,
alias = keyAlias,
scheme = ECDSA_SECP256R1_CODE_NAME
)
}
private fun java.nio.ByteBuffer.toBytes(): ByteArray {
val bytes = ByteArray(this.remaining())
this.get(bytes)
return bytes
}
private fun listsOfBytesAreEqual(bytesList0: List<ByteArray>, bytesList1: List<ByteArray>): Boolean =
bytesList0.size == bytesList1.size &&
bytesList0.all { outer ->
bytesList1.any { inner ->
outer.contentEquals(inner)
}
} &&
bytesList1.all { outer ->
bytesList0.any { inner ->
outer.contentEquals(inner)
}
}
fun PublicKey.fullId(): SecureHash =
SecureHashImpl(DigestAlgorithmName.SHA2_256.name, this.sha256Bytes())
| 82
| null |
9
| 69
|
d478e119ab288af663910f9a2df42a7a7b9f5bce
| 39,202
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/com/capyreader/app/ui/settings/panels/UnreadSortOrderSelect.kt
|
jocmp
| 610,083,236
| false
| null |
package com.capyreader.app.ui.settings
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.capyreader.app.R
import com.jocmp.capy.articles.UnreadSortOrder
@Composable
fun UnreadSortOrderSelect(
selected: UnreadSortOrder,
update: (UnreadSortOrder) -> Unit = {},
) {
PreferenceSelect(
selected = selected,
update = update,
options = UnreadSortOrder.entries,
optionText = { stringResource(translationKey(it)) },
label = R.string.article_list_unread_sort_title
)
}
private fun translationKey(sortOrder: UnreadSortOrder) =
when (sortOrder) {
UnreadSortOrder.NEWEST_FIRST -> R.string.article_list_unread_sort_newest_first
UnreadSortOrder.OLDEST_FIRST -> R.string.article_list_unread_sort_oldest_first
}
| 33
| null |
4
| 147
|
196690b776eebdecd4562e357a629277fec9cfe9
| 828
|
capyreader
|
MIT License
|
src/test/kotlin/ru/yoomoney/gradle/plugins/backend/kotlin/KotlinPluginTest.kt
|
yoomoney
| 334,236,333
| false
| null |
package ru.yoomoney.gradle.plugins.backend.kotlin
import org.gradle.testkit.runner.TaskOutcome
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.Before
import org.junit.Test
import ru.yoomoney.gradle.plugins.backend.build.AbstractPluginTest
import java.nio.file.Files
/**
* @author Valerii Zhirnov
* @since 13.05.2019
*/
class KotlinPluginTest : AbstractPluginTest() {
@Before
fun before() {
buildFile.writeText("""
buildscript {
repositories {
mavenCentral()
}
}
plugins {
id 'ru.yoomoney.gradle.plugins.kotlin-plugin'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.testng:testng:6.14.3'
}
""".trimIndent())
}
@Test
fun `should fail with detekt errors`() {
val sourceFile = writeSourceFile("src/main/kotlin", "Sample.kt", "class InvalidClass {}")
val staticAnalysis = projectDir.newFile("static-analysis.properties")
staticAnalysis.writeText("""
detekt=0
""".trimIndent())
val buildResult = runTasksFail("build", "check")
val detektTask = buildResult.tasks.find { it.path.contains(":detekt") }
MatcherAssert.assertThat("Detekt task exists", detektTask, CoreMatchers.notNullValue())
MatcherAssert.assertThat("Detekt task failed", detektTask?.outcome, CoreMatchers.equalTo(TaskOutcome.FAILED))
MatcherAssert.assertThat(
"Output contains Detekt failure",
buildResult.output,
CoreMatchers.containsString("Build failed with 3 weighted issues")
)
Files.delete(sourceFile.toPath())
Files.delete(staticAnalysis.toPath())
}
@Test
fun `should not fail with detekt errors`() {
val sourceFile = writeSourceFile("src/main/kotlin", "Sample.kt", "class InvalidClass {}")
val staticAnalysis = projectDir.newFile("static-analysis.properties")
staticAnalysis.writeText("""
detekt=3
""".trimIndent())
val buildResult = runTasksFail("build", "check")
println(buildResult.output)
val detektTask = buildResult.tasks.find { it.path.contains(":detekt") }
MatcherAssert.assertThat("Detekt task exists", detektTask, CoreMatchers.notNullValue())
MatcherAssert.assertThat("Detekt task succeeded", detektTask?.outcome, CoreMatchers.equalTo(TaskOutcome.SUCCESS))
Files.delete(sourceFile.toPath())
Files.delete(staticAnalysis.toPath())
}
@Test
fun `should fail with ktlint errors`() {
val sourceFile = writeSourceFile(
"src/main/kotlin",
"Sample.kt",
"""
fun main(args: Array<String>) {
(1..2).map { v -> "Value: " + v }.forEach { v -> println("Gradle " + v) };
}
""".trimIndent() + '\n'
)
val buildResult = runTasksFail("build", "check")
val ktlintTask = buildResult.tasks.find { it.path.contains(":ktlintMainSourceSetCheck") }
MatcherAssert.assertThat("ktlint task exists", ktlintTask, CoreMatchers.notNullValue())
MatcherAssert.assertThat("ktlint task failed", ktlintTask?.outcome, CoreMatchers.equalTo(TaskOutcome.FAILED))
MatcherAssert.assertThat(
"Output contains ktlint failure",
buildResult.output,
CoreMatchers.containsString("Unnecessary semicolon")
)
Files.delete(sourceFile.toPath())
}
@Test
fun `should pass all checks`() {
val sourceFile = writeSourceFile(
"src/main/kotlin",
"Sample.kt",
"""
fun main(args: Array<String>) {
(1..2).map { v -> "Value: " + v }.forEach { v -> println("Gradle " + v) }
}
""".trimIndent() + '\n'
)
runTasksSuccessfully("build", "check")
Files.delete(sourceFile.toPath())
}
}
| 0
| null |
2
| 3
|
9cd5e40a523bf67a089b4c1b5746d8ce20cc13e7
| 4,171
|
java-plugin
|
MIT License
|
app/src/main/java/com/anytypeio/anytype/ui/sets/ObjectSetIconPickerFragment.kt
|
anyproto
| 647,371,233
| false
|
{"Kotlin": 10338336, "Java": 69306, "Shell": 11187, "Makefile": 1334}
|
package com.anytypeio.anytype.ui.sets
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_utils.ext.argBoolean
import com.anytypeio.anytype.core_utils.ext.setVisible
import com.anytypeio.anytype.di.common.componentManager
import com.anytypeio.anytype.presentation.picker.IconPickerViewModel
import com.anytypeio.anytype.presentation.editor.picker.ObjectSetIconPickerViewModelFactory
import com.anytypeio.anytype.ui.editor.modals.IconPickerFragmentBase
import javax.inject.Inject
class ObjectSetIconPickerFragment : IconPickerFragmentBase<Id>() {
@Inject
lateinit var factory: ObjectSetIconPickerViewModelFactory
override val vm by viewModels<IconPickerViewModel<Id>> { factory }
override val target: Id
get() = context
private val showRemoveButton: Boolean
get() = argBoolean(ARG_SHOW_REMOVE_BUTTON)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnRemoveIcon.setVisible(showRemoveButton)
}
override fun injectDependencies() {
componentManager().objectSetIconPickerComponent.get(context).inject(this)
}
override fun releaseDependencies() {
componentManager().objectSetIconPickerComponent.release(context)
}
}
const val ARG_SHOW_REMOVE_BUTTON = "arg.show_remove_button"
| 35
|
Kotlin
|
30
| 356
|
fd94eba92c6c09d0315cf7e2c3620f0e5422c9f1
| 1,463
|
anytype-kotlin
|
RSA Message-Digest License
|
app/src/main/java/com/wjx/android/wanandroidmvvm/ui/collect/repository/CollectRepository.kt
|
LoveLifeEveryday
| 258,932,329
| true
|
{"Kotlin": 306312}
|
package com.wjx.android.wanandroidmvvm.ui.collect.repository
import androidx.lifecycle.MutableLiveData
import com.wjx.android.wanandroidmvvm.ui.common.repository.ArticleRepository
import com.wjx.android.wanandroidmvvm.base.observer.BaseObserver
import com.wjx.android.wanandroidmvvm.network.response.BaseResponse
import com.wjx.android.wanandroidmvvm.network.response.EmptyResponse
import com.wjx.android.wanandroidmvvm.common.state.State
import com.wjx.android.wanandroidmvvm.ui.collect.data.CollectResponse
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created with Android Studio.
* Description:
* @author: Wangjianxian
* @date: 2020/03/03
* Time: 14:42
*/
class CollectRepository(loadState: MutableLiveData<State>) : ArticleRepository(loadState) {
fun loadCollectArticle(pageNum: Int, liveData: MutableLiveData<BaseResponse<CollectResponse>>) {
apiService.loadCollectArticle(pageNum)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
BaseObserver(
liveData,
loadState,
this
)
)
}
fun addCollectArticle(
title: String,
author: String,
link: String,
liveData: MutableLiveData<BaseResponse<EmptyResponse>>
) {
apiService.addCollectArticle(title, author, link)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
BaseObserver(
liveData,
loadState,
this
)
)
}
fun unCollect(id: Int, originId: Int, liveData: MutableLiveData<BaseResponse<EmptyResponse>>) {
apiService.unCollect(id, originId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
BaseObserver(
liveData,
loadState,
this
)
)
}
}
| 3
| null |
44
| 3
|
c681db14548fce716cd5baab31bf704ce344bf1b
| 2,164
|
WanAndroidMVVM
|
Apache License 2.0
|
feature/edittask/src/main/java/easydone/feature/edittask/EditTaskViewModel.kt
|
kamerok
| 192,063,678
| false
|
{"Kotlin": 200991}
|
package easydone.feature.edittask
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import easydone.core.domain.DomainRepository
import easydone.core.domain.model.Markers
import easydone.core.domain.model.Task
import easydone.core.domain.model.TaskTemplate
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.flow.stateIn
import java.io.Serializable
internal class EditTaskViewModel(
private val args: Args,
private val repository: DomainRepository,
private val navigator: EditTaskNavigator
) : ViewModel() {
private val eventChannel = Channel<Event>(Channel.UNLIMITED)
private val actionChannel: Channel<Action> = Channel(capacity = Channel.UNLIMITED)
@OptIn(ExperimentalCoroutinesApi::class)
val state: StateFlow<State> = flow {
if (args is Args.Edit) {
emit(repository.getTask(args.id))
} else {
emit(null)
}
}
.flatMapConcat { originalTask ->
actionChannel
.consumeAsFlow()
.scan(
ContentState(
isCreate = originalTask == null,
type = originalTask?.type ?: (args as? Args.Create)?.type ?: Task.Type.Inbox,
title = originalTask?.title ?: "",
titleError = null,
description = originalTask?.description ?: (args as? Args.Create)?.title
?: "",
isUrgent = originalTask?.markers?.isUrgent ?: false,
isImportant = originalTask?.markers?.isImportant ?: false
)
) { state, action -> reduce(originalTask, state, action) }
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = IdleState
)
val events: Flow<Event> get() = eventChannel.receiveAsFlow()
fun onTypeClick() {
actionChannel.trySend(Action.TypeClick)
}
fun onTypeSelected(type: Task.Type) {
actionChannel.trySend(Action.TypeSelected(type))
}
fun onTitleChange(title: String) {
actionChannel.trySend(Action.TitleChange(title.replace(Regex("[\n\r]"), " ")))
}
fun onDescriptionChange(description: String) {
actionChannel.trySend(Action.DescriptionChange(description))
}
fun onUrgentClick() {
actionChannel.trySend(Action.UrgentClick)
}
fun onImportantClick() {
actionChannel.trySend(Action.ImportantClick)
}
fun onSave() {
actionChannel.trySend(Action.Save)
}
private suspend fun reduce(
originalTask: Task?,
state: ContentState,
action: Action
): ContentState = when (action) {
is Action.TypeClick -> {
eventChannel.trySend(OpenSelectType(state.type))
state
}
is Action.TypeSelected -> {
eventChannel.trySend(CloseSelectType)
state.copy(type = action.type)
}
is Action.TitleChange -> state.copy(title = action.title, titleError = null)
is Action.DescriptionChange -> state.copy(description = action.description)
is Action.UrgentClick -> state.copy(isUrgent = !state.isUrgent)
is Action.ImportantClick -> state.copy(isImportant = !state.isImportant)
is Action.Save -> {
if (state.title.isBlank()) {
//todo extract resources
state.copy(titleError = "Should not be empty")
} else {
val hasChanges =
state.title != (originalTask?.title ?: "") ||
state.description != (originalTask?.description ?: "") ||
state.type != (originalTask?.type ?: Task.Type.Inbox) ||
state.isUrgent != (originalTask?.markers?.isUrgent ?: false) ||
state.isImportant != (originalTask?.markers?.isImportant ?: false)
if (!hasChanges) {
navigator.close()
} else {
if (originalTask == null) {
repository.createTask(
TaskTemplate.create(
type = state.type,
title = state.title,
description = state.description,
isUrgent = state.isUrgent,
isImportant = state.isImportant
).getOrThrow()
)
} else {
repository.saveTask(
originalTask.copy(
type = state.type,
title = state.title,
description = state.description,
markers = Markers(
isUrgent = state.isUrgent,
isImportant = state.isImportant
)
)
)
}
navigator.close()
}
state
}
}
}
private sealed class Action {
data object TypeClick : Action()
data class TypeSelected(val type: Task.Type) : Action()
data class TitleChange(val title: String) : Action()
data class DescriptionChange(val description: String) : Action()
data object UrgentClick : Action()
data object ImportantClick : Action()
data object Save : Action()
}
internal sealed class Args : Serializable {
data class Create(
val title: String = "",
val type: Task.Type = Task.Type.Inbox
) : Args()
data class Edit(val id: String) : Args()
}
}
| 0
|
Kotlin
|
0
| 4
|
55b69474c7cc421c084bba5896b31d38eee0bc24
| 6,374
|
EasyDone
|
Apache License 2.0
|
src/me/anno/utils/test/FindWords.kt
|
AntonioNoack
| 266,471,164
| false
| null |
package me.anno.utils.test
import org.apache.logging.log4j.LogManager
import kotlin.math.min
val minLength = 4
fun main() {
// with a dictionary, it could find words automatically
// so it can just display all substrings in the field nicely,
// which is already a great help
/*findWords(
listOf(
"012",
"345",
"678"
)
)*/
/*findWords(
listOf(
"012a",
"345b",
"678c"
)
)*/
/*findWords(
listOf(
"012",
"345",
"678",
"abc",
"def"
)
)*/
// (homework of my (girl)friend)
findWords(
listOf(
"mdyeersgdwtjgng",
"bjrsmoedrnanrrr",
"lluihifteyisyae",
"layerssmugretye",
"crqnacnsararyen",
"zoeygozkicnbkph",
"destructionaoko",
"anoitaidarnlbnu",
"oevppiiodwlmyls",
"sncrdcliwuaujye",
"eokoxhqjtceffec",
"uzatuckikwitvli",
"voqefgohyigknjh",
"gjtcpndissolved",
"psvteprdyjjolvj"
)
)
}
fun findWords(text: List<String>) {
val logger = LogManager.getLogger("FindWords")
val lines = text
.map { it.trim() }
.filter { it.isNotEmpty() }
val sizeX = lines[0].length
val sizeY = lines.size
// for all directions
// 01 11 10
// and reversed
// check if it contains a word
logger.info(0)
lines.forEach { checkSubWords(it) }
logger.info(1)
for (i in 0 until sizeX) {
checkSubWords(String(CharArray(sizeY) { lines[it][i] }))
}
logger.info(2)
checkCrossSections(lines, sizeX, sizeY)
logger.info(3)
checkCrossSections(lines.reversed(), sizeX, sizeY) // to go left
}
fun checkCrossSections(lines: List<String>, sizeX: Int, sizeY: Int) {
// all cross sections...
for (startIndex in 0 until sizeX) {
val length = min(sizeX - startIndex, sizeY)
if (length >= minLength) {
val words = String(CharArray(length) {
lines[it][startIndex + it]
})
checkSubWords(words)
}
}
for (startIndex in 1 until sizeY) {
val length = min(sizeY - startIndex, sizeX)
if (length >= minLength) {
val words = String(CharArray(length) {
lines[startIndex + it][it]
})
checkSubWords(words)
}
}
}
fun checkSubWords(total: String) {
val logger = LogManager.getLogger("FindWords")
logger.info("V $total")
logger.info("R ${total.reversed()}")
/*if (total.length == minLength) checkWord(total)
else if (total.length > minLength) {
for (startIndex in 0 until total.length - minLength) {
for (endIndex in startIndex + minLength until total.length) {
val word = total.substring(startIndex, endIndex)
if (word.length < minLength) throw RuntimeException()
checkWord(word)
checkWord(word.reversed())
}
}
}*/
}
val processed = HashSet<String>()
fun checkWord(word: String) {
val logger = LogManager.getLogger("FindWords")
if (word !in processed) {
processed += word
logger.info(word)
}
}
| 0
|
Kotlin
|
1
| 8
|
421ba71c93c2b660476f96ffb6f4332fa07bd2b3
| 3,372
|
RemsStudio
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/TriangleCenter.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: TriangleCenter
*
* Full name: System`TriangleCenter
*
* TriangleCenter[tri, type] gives the specified type of center for the triangle tri.
* Usage: TriangleCenter[tri] gives the centroid of the triangle.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/TriangleCenter
* Documentation: web: http://reference.wolfram.com/language/ref/TriangleCenter.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun triangleCenter(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("TriangleCenter", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,101
|
mathemagika
|
Apache License 2.0
|
viewer/src/main/java/com/viewer/ListActivity.kt
|
adarshsingh994
| 282,007,779
| false
| null |
package com.viewer
import android.app.Activity
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.viewer.adapter.FileListAdapter
import com.viewer.adapter.ViewPagerAdapter
import com.viewer.core.Viewer
import com.viewer.fragment.ListFragment
import com.viewer.model.File
class ListActivity : AppCompatActivity(), ListFragment.Listener {
private var viewPager : ViewPager2? = null
private var adapter : ViewPagerAdapter? = null
private var tabLayout : TabLayout? = null
private var toolbar : Toolbar? = null
private var datasetMap = HashMap<String, ArrayList<File>>()
private var mimeTypeIndex = ArrayList<String>()
private val selectedFiles = ArrayList<File>()
private val fileApkDirMap = HashMap<File, String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
initViews()
initActionBar()
createDataset()
setupViewPager()
}
override fun onDestroy() {
super.onDestroy()
FileListAdapter.selectedFiles.clear()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.main_menu_done -> {
sendResult()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onFileClicked(file: File, isSelected: Boolean) {
if(isSelected){
selectedFiles.add(file)
}else{
selectedFiles.remove(file)
}
setActionBarTitle()
}
private fun initViews(){
viewPager = findViewById(R.id.main_view_pager)
tabLayout = findViewById(R.id.main_tab_layout)
toolbar = findViewById(R.id.main_toolbar)
}
private fun initActionBar(){
toolbar?.let{
setSupportActionBar(it)
setActionBarTitle()
}
}
private fun setupViewPager(){
try{
adapter = ViewPagerAdapter(this, datasetMap, mimeTypeIndex)
viewPager?.adapter = adapter
TabLayoutMediator(tabLayout!!, viewPager!!) { tab, position ->
tab.text = mimeTypeIndex[position]
}.attach()
}catch (e : KotlinNullPointerException){
e.printStackTrace()
}
}
private fun setActionBarTitle(){
supportActionBar?.title = resources.getQuantityString(
R.plurals.num_files_selected_text,
selectedFiles.size,
selectedFiles.size
)
}
private fun createDataset(){
val cr: ContentResolver = contentResolver
val uri: Uri = MediaStore.Files.getContentUri("external")
val projection: Array<String>? = null
val selection : String? = null
val selectionArgs: Array<String>? = null
val sortOrder: String? = null // unordered
val mimeTypeCache = HashMap<String, Boolean>()
cr.query(uri, projection, selection, selectionArgs, sortOrder).use {cur ->
if(cur != null){
while(cur.moveToNext()){
val path = cur.getString(cur.getColumnIndex(MediaStore.Files.FileColumns.DATA))
val title = java.io.File(path).name
val mimeType = cur.getString(cur.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE))
if(mimeType != null){
val file = getFile(path, title, mimeType, null)
if(!mimeTypeCache.contains(file.type.name)){
mimeTypeCache[file.type.name] = true
mimeTypeIndex.add(file.type.name)
datasetMap[file.type.name] = arrayListOf(file)
}else{
datasetMap[file.type.name]?.add(file)
}
}
}
}
}
val mainIntent = Intent(Intent.ACTION_MAIN, null)
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER)
packageManager.getInstalledApplications(PackageManager.GET_META_DATA)?.let{
it.forEach{applicationInfo ->
val icon = applicationInfo.loadIcon(packageManager)
if(!isSystemPackage(applicationInfo)){
val appName = packageManager.getApplicationLabel(applicationInfo)
val file = getFile("", appName.toString(), "APK", icon)
fileApkDirMap[file] = getApkDir(applicationInfo)
if(!mimeTypeCache.contains(file.type.name)){
mimeTypeCache[file.type.name] = true
mimeTypeIndex.add(file.type.name)
datasetMap[file.type.name] = arrayListOf(file)
}else{
datasetMap[file.type.name]?.add(file)
}
}
}
}
}
private fun getFile(path : String, title : String, mimeType : String, icon : Drawable?) : File{
val type = when {
mimeType.contains("pdf", true) -> {
File.Type.Pdf
}
mimeType.contains("jpg", true)
|| mimeType.contains("png", true)
|| mimeType.contains("jpeg", true)
|| mimeType.contains("webp", true)
|| mimeType.contains("dng", true)-> {
File.Type.Photo
}
mimeType.contains("mp4", true) -> {
File.Type.Video
}
mimeType.contains("mp3", true)
|| mimeType.contains("mpeg", true)
|| mimeType.contains("aac-adts", true)
|| mimeType.contains("ogg", true)-> {
File.Type.Audio
}
mimeType.contains("APK", true) -> {
File.Type.App
}
else -> {
File.Type.Other
}
}
return File(type, title, path, icon)
}
private fun isSystemPackage(applicationInfo: ApplicationInfo): Boolean {
return applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
}
private fun getApkDir(applicationInfo : ApplicationInfo) : String{
return applicationInfo.sourceDir
}
private fun sendResult(){
val returnIntent = Intent()
returnIntent.putStringArrayListExtra(Viewer.KEY_VIEWER_SELECTED_LIST, getResultList())
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
private fun getResultList() : ArrayList<String>{
val resultList = ArrayList<String>()
selectedFiles.forEach{file ->
when(file.type){
File.Type.App -> {
fileApkDirMap[file]?.let{apkDir ->
resultList.add(apkDir)
}
}
else -> {
file.path?.let{path ->
resultList.add(path)
}
}
}
}
return resultList
}
}
| 0
|
Kotlin
|
0
| 0
|
3c7fef601898f9a32142653bdd634d19e15157df
| 7,900
|
Viewer
|
Apache License 2.0
|
src/main/kotlin/Versioning.kt
|
kordlib
| 624,827,432
| false
|
{"Kotlin": 12810}
|
package dev.kord.gradle.tools
import dev.kord.gradle.tools.util.libraryVersion
import org.gradle.api.Project
import org.gradle.api.provider.Provider
/**
* This uses [Project.afterEvaluate] to account for changes to [KordExtension.mainBranchName] which is used by
* [libraryVersion].
*/
internal fun Project.applyVersioning() = afterEvaluate {
version = libraryVersion
}
/**
* Lazy accessor of the Project version.
*/
public val Project.lazyVersion: Provider<String>
get() = provider { version.toString() }
| 0
|
Kotlin
|
0
| 1
|
2eb93e6e995c38cef65af41604305f806a7c755a
| 522
|
gradle-tools
|
MIT License
|
src/main/kotlin/ru/yandex/money/tools/grafana/dsl/metrics/Metrics.kt
|
arodrime
| 176,972,313
| true
|
{"Kotlin": 92104, "Shell": 5947, "Batchfile": 2183, "Groovy": 25}
|
package ru.yandex.money.tools.grafana.dsl.metrics
import org.json.JSONArray
import ru.yandex.money.tools.grafana.dsl.json.Json
import ru.yandex.money.tools.grafana.dsl.json.JsonArray
/**
* Metrics collection.
*
* @author Dmitry Komarov (komarovdmitry@yamoney.ru)
* @since 7/23/18
*/
class Metrics(dashboardMetrics: Collection<DashboardMetric>) : Json<JSONArray> by JsonArray(dashboardMetrics)
| 0
|
Kotlin
|
0
| 0
|
0eca3e89a579da88fe1ccd4f4794ff114fef7f3d
| 400
|
grafana-dashboard-dsl
|
MIT License
|
kotlin-leetcode/src/main/kotlin/io/github/dreamylost/Leetcode_1457.kt
|
jxnu-liguobin
| 123,690,567
| false
| null |
/* Licensed under Apache-2.0 @梦境迷离 */
package io.github.dreamylost
/**
* 1457. 二叉树中的伪回文路径
*
* 给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。
* 请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。
* @see [[https://github.com/jxnu-liguobin]]
* @author 梦境迷离
* @since 2020-10-07
* @version 1.0
*/
class Leetcode_1457 {
companion object {
/**
* 512 ms,100.00%
* 52.9 MB,100.00%
*/
fun pseudoPalindromicPaths(root: TreeNode?): Int {
var ret = 0
fun dfsPaths(r: TreeNode?, paths: MutableList<Int>) {
if (r == null) return
paths.add(r.`val`)
val cnt = Array(10) { 0 }
if (r.left == null && r.right == null) {
for (e in paths) {
cnt[e] += 1
}
val count = cnt.count { it and 1 == 1 } // 奇数
if (count <= 1) {
ret++
}
println(paths)
} else {
dfsPaths(r.left, paths)
dfsPaths(r.right, paths)
}
paths.removeAt(paths.size - 1)
}
dfsPaths(root, mutableListOf())
return ret
}
@JvmStatic
fun main(args: Array<String>) {
val ret = pseudoPalindromicPaths(TreeNodeData.treeNode6_1())
println(ret)
}
}
}
| 13
| null |
189
| 534
|
a97159e99fc6592bec5032d18391d18b84708175
| 1,490
|
Java-Learning-Summary
|
Apache License 2.0
|
brightcove-exoplayer-kotlin/BasicSsaiSampleApp/src/main/java/com/brightcove/ssai/sample/BasicSsaiSampleAppActivity.kt
|
BrightcoveOS
| 14,517,858
| false
|
{"Java": 197778, "Kotlin": 77053}
|
package com.brightcove.ssai.sample
import android.os.Bundle
import android.util.Log
import com.brightcove.player.Sdk
import com.brightcove.player.appcompat.BrightcovePlayerActivity
import com.brightcove.player.edge.Catalog
import com.brightcove.player.edge.VideoListener
import com.brightcove.player.event.Event
import com.brightcove.player.event.EventType
import com.brightcove.player.model.Video
import com.brightcove.player.network.HttpRequestConfig
import com.brightcove.ssai.SSAIComponent
import com.brightcove.ssai.omid.AdEventType
import com.brightcove.ssai.omid.OpenMeasurementTracker
import com.brightcove.ssai.sample.databinding.ActivityBasicSsaiSampleBinding
import com.iab.omid.library.brightcove.adsession.FriendlyObstructionPurpose
class BasicSsaiSampleAppActivity : BrightcovePlayerActivity() {
private var plugin: SSAIComponent? = null
private var tracker: OpenMeasurementTracker? = null
private lateinit var binding: ActivityBasicSsaiSampleBinding
override fun onCreate(savedInstanceState: Bundle?) {
// When extending the BrightcovePlayer, we must assign brightcoveVideoView before
// entering the superclass. This allows for some stock video player lifecycle
// management.
binding = ActivityBasicSsaiSampleBinding.inflate(layoutInflater)
setContentView(binding.root)
baseVideoView = binding.brightcoveVideoView
super.onCreate(savedInstanceState)
val eventEmitter = baseVideoView.eventEmitter
val catalog = Catalog.Builder(eventEmitter, getString(R.string.sdk_demo_account))
.setBaseURL(Catalog.DEFAULT_EDGE_BASE_URL)
.setPolicy(getString(R.string.sdk_demo_policy_key))
.build()
// Setup the error event handler for the SSAI plugin.
registerErrorEventHandler()
setupOpenMeasurement()
plugin = SSAIComponent(this, baseVideoView)
// Set the companion ad container.
plugin?.addCompanionContainer(binding.adFrame)
// Set the HttpRequestConfig with the Ad Config Id configured in
// your https://studio.brightcove.com account.
val httpRequestConfig = HttpRequestConfig.Builder()
.addQueryParameter(HttpRequestConfig.KEY_AD_CONFIG_ID, AD_CONFIG_ID_QUERY_PARAM_VALUE)
.build()
catalog.findVideoByID(getString(R.string.sdk_demo_video_id), httpRequestConfig, object : VideoListener() {
override fun onVideo(video: Video) {
// The Video Sources will have a VMAP url which will be processed by the SSAI plugin,
// If there is not a VMAP url, or if there are any requesting or parsing error,
// an EventType.ERROR event will be emitted.
plugin?.processVideo(video)
}
})
}
override fun onDestroy() {
super.onDestroy()
if (tracker != null && isFinishing) {
tracker?.stop()
}
}
private fun setupOpenMeasurement() {
binding.omToggle.setOnCheckedChangeListener { _, isChecked: Boolean ->
if (isChecked) {
tracker?.start()
} else {
tracker?.stop()
}
}
// Initialize the OpenMeasurementTracker
tracker = OpenMeasurementTracker.Factory(PARTNER_NAME, PARTNER_VERSION, baseVideoView).create()
// NOTE: The ad used in the sample does not have an `AdVerification` element and will not
// send tracking events. You may verify OpenMeasurement via the following listener:
tracker?.addListener(object : OpenMeasurementTracker.Listener {
override fun onEvent(adEventType: AdEventType) {
Log.d(TAG, "onEvent() called with: adEventType = [$adEventType]")
}
override fun onStartTracking() {
Log.d(TAG, "onStartTracking() called")
}
override fun onStoppedTracking() {
Log.d(TAG, "onStoppedTracking() called")
}
})
// Example to register a view that should be considered as a friendly obstruction
tracker?.addFriendlyObstruction(binding.adFrame, FriendlyObstructionPurpose.OTHER, "Ad frame")
// Start the tracker, if enabled.
if (binding.omToggle.isChecked) {
tracker?.start()
}
}
private fun registerErrorEventHandler() {
// Handle the case where the ad data URL has not been supplied to the plugin.
val eventEmitter = baseVideoView.eventEmitter
eventEmitter.on(EventType.ERROR) { event: Event ->
Log.e(TAG, event.type)
}
}
companion object {
private const val TAG = "MainActivity"
private const val AD_CONFIG_ID_QUERY_PARAM_VALUE = "ba5e4879-77f0-424b-8c98-706ae5ad7eec"
private const val PARTNER_NAME = "dummyVendor"
private val PARTNER_VERSION = Sdk.getVersionName()
}
}
| 2
|
Java
|
131
| 132
|
050f9e72cdb7957b9a0a0187fa35c1ca731e40bb
| 4,964
|
android-player-samples
|
Apache License 2.0
|
api/src/main/kotlin/com/ford/internalprojects/peoplemover/person/Person.kt
|
FordLabs
| 260,303,075
| false
|
{"TypeScript": 1000307, "Kotlin": 534941, "SCSS": 109291, "JavaScript": 11743, "HTML": 3768, "Shell": 677}
|
/*
* Copyright (c) 2021 Ford Motor Company
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ford.internalprojects.peoplemover.person
import com.ford.internalprojects.peoplemover.space.NamedSpaceComponent
import com.ford.internalprojects.peoplemover.tag.person.PersonTag
import com.ford.internalprojects.peoplemover.tag.role.SpaceRole
import java.time.LocalDate
import javax.persistence.*
@Entity
data class Person(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
override val id: Int? = null,
override val name: String,
@ManyToOne
@JoinColumn(name = "space_role_id")
val spaceRole: SpaceRole? = null,
@ManyToMany(fetch = FetchType.EAGER, cascade = [CascadeType.REFRESH])
@JoinTable(name = "person_tag_mapping", joinColumns = [JoinColumn(name = "person_id", referencedColumnName = "id")], inverseJoinColumns = [JoinColumn(name = "person_tag_id", referencedColumnName = "id")])
val tags: Set<PersonTag> = HashSet(),
val notes: String? = "",
@Column(name = "new_person")
var newPerson: Boolean = false,
@Column()
var newPersonDate: LocalDate? = null,
@Column(name = "space_uuid")
override val spaceUuid: String,
val customField1: String? = null,
var archiveDate: LocalDate? = null
): NamedSpaceComponent {
constructor(name: String, spaceUuid: String) :
this(id = null, name = name, spaceRole = null, tags = HashSet(), notes = "", newPerson = false, newPersonDate = null, spaceUuid = spaceUuid, customField1 = null, archiveDate = null)
}
| 24
|
TypeScript
|
6
| 7
|
8c9a335048d40dd50612de11633b48a73f337535
| 2,169
|
peoplemover
|
Apache License 2.0
|
fns-hl7-pipeline/fn-receiver-debatcher/src/test/kotlin/DebatcherTest.kt
|
CDCgov
| 510,836,864
| false
|
{"Kotlin": 750786, "Scala": 208820, "Python": 44391, "Java": 18075, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979}
|
import gov.cdc.dex.azure.EventHubMetadata
import gov.cdc.dex.hl7.Function
import gov.cdc.dex.hl7.Function.Companion.UTF_BOM
import gov.cdc.dex.hl7.ReceiverProcessMetadata
import gov.cdc.dex.metadata.*
import gov.cdc.dex.util.DateHelper.toIsoString
import gov.cdc.dex.util.StringUtils.Companion.hashMD5
import gov.cdc.dex.util.StringUtils.Companion.normalize
import gov.cdc.hl7.HL7StaticParser
import org.junit.jupiter.api.Test
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.*
class DebatcherTest {
@Test
fun testRemoveBom() {
//val testFile = this::class.java.getResource("/Genv2_2-0-1_TC08.txt")
val reader = File("src/test/resources/Genv2_2-0-1_TC08.txt").bufferedReader()
BufferedReader(reader).use { br ->
br.forEachLine { line ->
//while ( br.readLine().also { line = it } != null) {
//println(line)
var lineClean = line.trim()
while (lineClean.startsWith(UTF_BOM)) {
//if (lineClean.startsWith(UTF_BOM)) {
println("Found BOM...")
lineClean = lineClean.substring(1)
println(line.length)
println(lineClean.length)
}
}
}
}
@Test
fun testDebatcher() {
println("Starting debatcher test")
val filePath = "genV1/Genv1-Case-TestMessage1.HL7"
val startTime = Date().toIsoString()
val metaDataMap: Map<String, String?> = mapOf(
Pair("message_type", "CASE"),
Pair("route", null),
Pair("reporting_jurisdiction", "16"),
Pair("original_file_name", "Genv1-Case-TestMessage1.HL7"),
Pair("meta_destination_id", "arboviral diseases"),
Pair("meta_ext_event", "case notification"),
Pair("tus_tguid", UUID.randomUUID().toString()),
Pair("meta_ext_uploadid", UUID.randomUUID().toString()),
Pair("trace_id", "unknown"),
Pair("parent_span_id", "unknown")
)
val testFileIS = this::class.java.getResource(filePath).openStream()
val provenance = Provenance(
eventId = "123",
eventTimestamp = startTime,
filePath = filePath,
fileTimestamp = startTime,
fileSize = 1234,
singleOrBatch = Provenance.SINGLE_FILE,
originalFileName = "blobName",
systemProvider = "BLOB",
originalFileTimestamp = startTime,
)
// Read Blob File by Lines
// -------------------------------------
val reader = InputStreamReader(testFileIS)
val currentLinesArr = arrayListOf<String>()
var mshCount = 0
val eventHubMD = EventHubMetadata(1, 1, null, "20230101")
BufferedReader(reader).use { br ->
br.forEachLine { line ->
val lineClean = line.trim().let { if (it.startsWith(UTF_BOM)) it.substring(1) else it }
if (lineClean.startsWith("FHS") || lineClean.startsWith("BHS") || lineClean.startsWith("BTS") || lineClean.startsWith(
"FTS"
)
) {
// batch line --Nothing to do here
provenance.singleOrBatch = Provenance.BATCH_FILE
} else {
if (lineClean.startsWith("MSH")) {
mshCount++
if (mshCount > 1) {
provenance.singleOrBatch = Provenance.BATCH_FILE
provenance.messageHash = currentLinesArr.joinToString("\n").hashMD5()
val messageInfo = getMessageInfo(metaDataMap, currentLinesArr.joinToString("\n"))
val (metadata, summary) = buildMetadata(
Function.STATUS_SUCCESS,
eventHubMD,
startTime,
provenance
)
prepareAndSend(currentLinesArr, messageInfo, metadata, summary, metaDataMap)
provenance.messageIndex++
}
currentLinesArr.clear()
} // .if
currentLinesArr.add(lineClean)
} // .else
} // .forEachLine
} // .BufferedReader
// Send last message
provenance.messageHash = currentLinesArr.joinToString("\n").hashMD5()
if (mshCount > 0) {
val messageInfo = getMessageInfo(metaDataMap, currentLinesArr.joinToString("\n"))
val (metadata, summary) = buildMetadata(Function.STATUS_SUCCESS, eventHubMD, startTime, provenance)
prepareAndSend(currentLinesArr, messageInfo, metadata, summary, metaDataMap)
} else {
// no valid message -- send to error queue
val (metadata, summary) = buildMetadata(
Function.STATUS_ERROR,
eventHubMD,
startTime,
provenance,
"No valid message found."
)
prepareAndSend(
arrayListOf(),
DexMessageInfo(null, null, null, null, HL7MessageType.CASE),
metadata,
summary,
metaDataMap
)
}
} // .test
private fun extractValue(msg: String, path: String): String {
val value = HL7StaticParser.getFirstValue(msg, path)
return if (value.isDefined) value.get()
else ""
}
private fun buildMetadata(
status: String,
eventHubMD: EventHubMetadata,
startTime: String,
provenance: Provenance,
errorMessage: String? = null
): Pair<DexMetadata, SummaryInfo> {
val processMD = ReceiverProcessMetadata(status, eventHubMD)
processMD.startProcessTime = startTime
processMD.endProcessTime = Date().toIsoString()
var summary = SummaryInfo("RECEIVED")
if (status == Function.STATUS_ERROR) {
summary = SummaryInfo("REJECTED")
summary.problem = Problem(ReceiverProcessMetadata.RECEIVER_PROCESS, null, null, errorMessage, false, 0, 0)
}
return DexMetadata(provenance, processMD) to summary
}
private fun getRoutingData(metaDataMap: Map<String, String?>): RoutingMetadata {
val uploadID = if (!metaDataMap["meta_ext_uploadid"].isNullOrEmpty()) {
metaDataMap["meta_ext_uploadid"]
} else if (!metaDataMap["tus_tguid"].isNullOrEmpty()) {
metaDataMap["tus_tguid"]
} else "UNKNOWN"
val traceID = metaDataMap["trace_id"]
val parentSpanID = metaDataMap["parent_span_id"]
return RoutingMetadata(
uploadID = uploadID,
traceID = traceID,
parentSpanID = parentSpanID,
destinationID = metaDataMap["meta_destination_id"],
destinationEvent = metaDataMap["meta_ext_event"]
)
}
private fun prepareAndSend(
messageContent: ArrayList<String>,
messageInfo: DexMessageInfo,
metadata: DexMetadata,
summary: SummaryInfo,
metaDataMap: Map<String, String?>
): DexEventPayload {
val msgEvent = DexEventPayload(
messageInfo = messageInfo,
metadata = metadata,
summary = summary,
routingMetadata = getRoutingData(metaDataMap),
content = Base64.getEncoder().encodeToString(messageContent.joinToString("\n").toByteArray())
)
val jsonMessage = Function.gson.toJson(msgEvent)
println(jsonMessage)
println("Simulating Sending new Event to event hub Message: --> messageUUID: ${msgEvent.messageUUID}, messageIndex: ${msgEvent.metadata.provenance.messageIndex}, fileName: ${msgEvent.metadata.provenance.filePath}")
println("Processed and Sent to console Message: --> messageUUID: ${msgEvent.messageUUID}, messageIndex: ${msgEvent.metadata.provenance.messageIndex}, fileName: ${msgEvent.metadata.provenance.filePath}")
return msgEvent
}
private fun getMessageInfo(metaDataMap: Map<String, String?>, message: String): DexMessageInfo {
val eventCode = extractValue(message, Function.EVENT_CODE_PATH)
val localRecordID = extractValue(message, Function.LOCAL_RECORD_ID_PATH)
val messageType = metaDataMap["message_type"]
//READ FROM METADATA FOR ELR
if (messageType == HL7MessageType.ELR.name) {
val route = metaDataMap["route"]?.normalize()
val reportingJurisdiction = metaDataMap["reporting_jurisdiction"]
return DexMessageInfo(eventCode, route, null, reportingJurisdiction, HL7MessageType.ELR, localRecordID)
}
var jurisdictionCode = extractValue(message, Function.JURISDICTION_CODE_PATH)
if (jurisdictionCode.isEmpty()) {
jurisdictionCode = extractValue(message, Function.ALT_JURISDICTION_CODE_PATH)
}
return DexMessageInfo(
eventCode = eventCode,
route = Function.fnConfig.eventCodes[eventCode]?.get("category"),
mmgKeyList = null,
jurisdictionCode = jurisdictionCode,
type = HL7MessageType.CASE,
localRecordID = localRecordID
)
}
}
| 122
|
Kotlin
|
14
| 9
|
dccefbb2c3cabc5170d09f9cc20f66792af179b6
| 9,475
|
data-exchange-hl7
|
Apache License 2.0
|
app/src/main/java/ru/iteco/fmhandroid/ui/NewsListFragment.kt
|
YuriKopshev
| 594,466,644
| false
| null |
package ru.iteco.fmhandroid.ui
import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.widget.PopupMenu
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import ru.iteco.fmhandroid.R
import ru.iteco.fmhandroid.adapter.NewsListAdapter
import ru.iteco.fmhandroid.databinding.FragmentNewsListBinding
import ru.iteco.fmhandroid.dto.NewsFilterArgs
import ru.iteco.fmhandroid.enum.FragmentsTags
import ru.iteco.fmhandroid.idle.IdleService
import ru.iteco.fmhandroid.utils.Utils.convertNewsCategory
import ru.iteco.fmhandroid.viewmodel.AuthViewModel
import ru.iteco.fmhandroid.viewmodel.NewsViewModel
@AndroidEntryPoint
class NewsListFragment : Fragment(R.layout.fragment_news_list) {
private lateinit var binding: FragmentNewsListBinding
private val viewModel: NewsViewModel by viewModels()
private val authViewModel: AuthViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
IdleService.incr()
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
lifecycleScope.launchWhenCreated {
viewModel.onRefresh()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentNewsListBinding.bind(view)
val mainMenu = PopupMenu(
context,
binding.containerCustomAppBarIncludeOnFragmentNewsList.mainMenuImageButton
)
mainMenu.inflate(R.menu.menu_main)
val menuItemNews = mainMenu.menu.getItem(2)
menuItemNews.isEnabled = false
mainMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_item_main -> {
findNavController().navigate(R.id.action_newsListFragment_to_mainFragment)
true
}
R.id.menu_item_about -> {
findNavController().navigate(R.id.action_newsListFragment_to_aboutFragment)
true
}
else -> {
false
}
}
}
binding.containerCustomAppBarIncludeOnFragmentNewsList.ourMissionImageButton.setOnClickListener {
findNavController().navigate(R.id.action_newsListFragment_to_our_mission_fragment)
}
val authorizationMenu = PopupMenu(
context,
binding.containerCustomAppBarIncludeOnFragmentNewsList.authorizationImageButton
)
authorizationMenu.inflate(R.menu.authorization)
binding.containerCustomAppBarIncludeOnFragmentNewsList.authorizationImageButton.setOnClickListener {
authorizationMenu.show()
}
authorizationMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.authorization_logout_menu_item -> {
authViewModel.logOut()
findNavController().navigate(R.id.action_newsListFragment_to_authFragment)
true
}
else -> false
}
}
binding.apply {
containerListNewsInclude.allNewsTextView.visibility = View.GONE
containerListNewsInclude.expandMaterialButton.visibility = View.GONE
}
val adapter = NewsListAdapter(viewModel)
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.data.collectLatest {
binding.newsListSwipeRefresh.isRefreshing = false
adapter.submitList(it)
if (it.isEmpty()) {
binding.containerListNewsInclude.emptyNewsListGroup.isVisible = true
binding.containerListNewsInclude.newsRetryMaterialButton.setOnClickListener {
binding.newsListSwipeRefresh.isRefreshing = true
viewModel.onRefresh()
binding.newsListSwipeRefresh.isRefreshing = false
}
}
}
}
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.loadNewsExceptionEvent.collect {
val activity = activity ?: return@collect
val dialog = AlertDialog.Builder(activity)
dialog.setMessage(R.string.error)
.setPositiveButton(R.string.fragment_positive_button) { alertDialog, _ ->
alertDialog.cancel()
}
.create()
.show()
}
}
binding.newsListSwipeRefresh.setOnRefreshListener {
viewLifecycleOwner.lifecycleScope.launch {
viewModel.onRefresh()
delay(200)
binding.containerListNewsInclude.newsListRecyclerView.scrollToPosition(
0
)
}
}
with(binding) {
containerListNewsInclude.editNewsMaterialButton.setOnClickListener {
if (viewModel.currentUser.admin) {
findNavController().navigate(
R.id.action_newsListFragment_to_newsControlPanelFragment
)
} else {
Toast.makeText(
requireContext(),
R.string.no_rules_for_news_control_panel,
Toast.LENGTH_LONG
).show()
}
}
containerListNewsInclude.sortNewsMaterialButton.setOnClickListener {
viewModel.onSortDirectionButtonClicked()
}
containerCustomAppBarIncludeOnFragmentNewsList.mainMenuImageButton.setOnClickListener {
mainMenu.show()
}
containerListNewsInclude.filterNewsMaterialButton.setOnClickListener {
val action = NewsListFragmentDirections.actionNewsListFragmentToFilterNewsFragment(
FragmentsTags.NEWS_LIST_FRAGMENT
)
findNavController().navigate(action)
}
}
binding.containerListNewsInclude.newsListRecyclerView.adapter = adapter
setFragmentResultListener("requestKey") { _, bundle ->
val args = bundle.getParcelable<NewsFilterArgs>("filterArgs")
viewModel.onFilterNewsClicked(
args?.category?.let { convertNewsCategory(it) },
args?.dates?.get(0),
args?.dates?.get(1)
)
}
IdleService.decr()
}
}
| 1
| null |
1
| 1
|
8ef698dc36b6621a250c0d8826e4f45677acc7b2
| 7,025
|
QA_middle_finalWork
|
Apache License 2.0
|
app/src/main/java/pl/marianjureczko/poszukiwacz/permissions/PermissionActivity.kt
|
mjureczko
| 720,519,840
| false
|
{"Kotlin": 290233}
|
package pl.marianjureczko.poszukiwacz.permissions
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import pl.marianjureczko.poszukiwacz.shared.ActivityWithAdsAndBackButton
abstract class PermissionActivity : ActivityWithAdsAndBackButton() {
private lateinit var permissionManager: PermissionManager
private lateinit var activityRequirements: ActivityRequirements
private var isComingFromSettings = false
private var exitOnDenied = false
abstract fun onPermissionsGranted(activityRequirements: ActivityRequirements)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val permissionListener = object : PermissionListener {
override fun permissionsGranted(activityRequirements: ActivityRequirements) {
onPermissionsGranted(activityRequirements)
}
override fun navigateToSettings() {
isComingFromSettings = true
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null))
startActivity(intent)
}
override fun deny() {
onPermissionsDenied()
}
override fun retry() {
assurePermissionsAreGranted(activityRequirements, exitOnDenied)
}
}
permissionManager = PermissionManager(permissionListener)
}
/**
* Checks whether user granted necessary permissions for [activityRequirements]. If the user already
* granted that permissions, it will call [onPermissionsGranted] method, otherwise it will make preparations to take permissions from user.
* @param activityRequirements It is actually an answer to the question 'What are you going to do with these permissions?'.
* @param exitOnDenied An optional parameter. It will make your activity finish when user denies permissions.
* Pass it **true** if your activity cannot live without permissions. Default is **false**
*/
fun assurePermissionsAreGranted(activityRequirements: ActivityRequirements, exitOnDenied: Boolean = false) {
this.activityRequirements = activityRequirements
this.exitOnDenied = exitOnDenied
if (::permissionManager.isInitialized) {
val permissions = activityRequirements.getSpecsArray()
if (PermissionManager.areAllPermissionsGranted(this, permissions)) {
onPermissionsGranted(activityRequirements)
} else {
permissionManager.requestAllPermissions(this, activityRequirements)
}
}
}
open fun onPermissionsDenied() {
if (exitOnDenied) {
finish()
}
}
@SuppressLint("MissingSuperCall")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (::activityRequirements.isInitialized) {
permissionManager.handleRequestPermissionsResult(this, activityRequirements, permissions, grantResults)
}
}
override fun onResume() {
super.onResume()
if (isComingFromSettings && ::activityRequirements.isInitialized) {
isComingFromSettings = false
permissionManager.handleResume(this)
}
}
}
| 22
|
Kotlin
|
0
| 1
|
7f74a19dac0ebbbb6cc70a453c674a728946e686
| 3,430
|
maly-poszukiwacz-skarbow
|
W3C Software Notice and License (2002-12-31)
|
console-framework-client/src/main/java/io/axoniq/console/framework/client/ServerProcessorReporter.kt
|
AxonIQ
| 682,516,729
| false
|
{"Kotlin": 203036, "Java": 34400}
|
/*
* Copyright (c) 2022-2024. AxonIQ B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.console.framework.client
import io.axoniq.console.framework.api.ClientSettingsV2
import io.axoniq.console.framework.eventprocessor.ProcessorReportCreator
import mu.KotlinLogging
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class ServerProcessorReporter(
private val client: AxoniqConsoleRSocketClient,
private val processorReportCreator: ProcessorReportCreator,
private val clientSettingsService: ClientSettingsService,
private val executor: ScheduledExecutorService,
) : ClientSettingsObserver {
private var reportTask: ScheduledFuture<*>? = null
private val logger = KotlinLogging.logger { }
init {
clientSettingsService.subscribeToSettings(this)
}
override fun onConnectedWithSettings(settings: ClientSettingsV2) {
logger.debug { "Sending processor information every ${settings.processorReportInterval}ms to AxonIQ console" }
this.reportTask = executor.scheduleWithFixedDelay({
try {
this.report()
} catch (e: Exception) {
logger.debug("Was unable to report processor metrics: {}", e.message, e)
}
}, 0, settings.processorReportInterval, TimeUnit.MILLISECONDS)
}
private fun report() {
client.sendReport(io.axoniq.console.framework.api.Routes.EventProcessor.REPORT, processorReportCreator.createReport()).block()
}
override fun onDisconnected() {
reportTask?.cancel(true)
reportTask = null
}
}
| 4
|
Kotlin
|
0
| 0
|
fc1bcaf4baf0bdcf9fc6a00c1114e19c0ed3635f
| 2,212
|
console-framework-client
|
Apache License 2.0
|
app/src/main/java/com/example/mycheesecakes/data/network/api/model/ApiQuizResult.kt
|
dfirestone21
| 389,194,985
| false
| null |
package com.example.mycheesecakes.data.network.api.model
import com.google.gson.annotations.SerializedName
data class ApiQuizResult(
@SerializedName("createdTime")
val createdTime: String? = null,
@SerializedName("fields")
val fields: Fields?,
@SerializedName("id")
val id: String? = null
) {
data class Fields(
@SerializedName("correct")
val correct: Int?,
@SerializedName("date")
val date: Long?,
@SerializedName("id")
val id: Int? = null,
@SerializedName("incorrect")
val incorrect: Int?,
@SerializedName("quiz_id")
val quizId: String?
)
}
| 0
|
Kotlin
|
0
| 0
|
8f87fe6439e9256d90d789bf453be802a26241b4
| 656
|
CheesecakeApp
|
MIT License
|
build-logic/src/main/kotlin/AndroidConfig.kt
|
nisrulz
| 772,818,568
| false
|
{"Kotlin": 16370}
|
internal object BuildSdkInfo {
const val COMPILE_SDK_VERSION = 34
const val MIN_SDK_VERSION = 21
const val TARGET_SDK_VERSION = 34
const val JVM_TARGET = 8
// https://developer.android.com/jetpack/androidx/releases/compose-kotlin#pre-release_kotlin_compatibility
const val COMPOSE_COMPILER_VERSION = "1.5.13"
}
object ApplicationInfo {
const val APPLICATION_VERSION_NAME = "1.0"
const val APPLICATION_VERSION_CODE = 1
}
object LibraryInfo {
const val POM_VERSION = "1.0.2"
const val POM_ARTIFACT_ID = "devicetypektx"
const val POM_NAME = "Device Type KTX"
const val POM_DESCRIPTION =
"Android library to provide Kotlin extensions for working with specific device types."
const val POM_INCEPTION_YEAR = "2024"
private const val GITHUB_REPO_NAME = "device-type-ktx"
const val POM_URL = "https://github.com/nisrulz/$GITHUB_REPO_NAME/"
const val POM_SCM_URL = "https://github.com/nisrulz/$GITHUB_REPO_NAME/"
const val POM_SCM_CONNECTION = "scm:git:git://github.com/nisrulz/$GITHUB_REPO_NAME.git"
const val POM_SCM_DEV_CONNECTION = "scm:git:ssh://git@github.com/nisrulz/$GITHUB_REPO_NAME.git"
}
| 1
|
Kotlin
|
0
| 2
|
c5fe65e6316c3572026c102ee4c59d6b7931f801
| 1,174
|
device-type-ktx
|
Apache License 2.0
|
kmp-modifier/src/main/kotlin/com/intellij/packageSearch/mppDependencyUpdater/dsl/KotlinDslProvider.kt
|
JetBrains
| 724,588,585
| false
|
{"Kotlin": 575593, "Java": 146346, "HTML": 1589, "Batchfile": 209, "Shell": 86}
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.packageSearch.mppDependencyUpdater.dsl
import com.android.tools.idea.gradle.dsl.api.GradleBuildModel
import com.android.tools.idea.gradle.dsl.api.util.GradleDslModel
import com.android.tools.idea.gradle.dsl.model.GradleBlockModelMap
import com.android.tools.idea.gradle.dsl.parser.elements.GradlePropertiesDslElement
import com.android.tools.idea.gradle.dsl.parser.files.GradleDslFile
import com.android.tools.idea.gradle.dsl.parser.semantics.PropertiesElementDescription
import com.intellij.packageSearch.mppDependencyUpdater.dsl.elements.KotlinDslElement
import com.intellij.packageSearch.mppDependencyUpdater.dsl.models.KotlinDslModel
class KotlinDslProvider : GradleBlockModelMap.BlockModelProvider<GradleBuildModel, GradleDslFile> {
private val KOTLIN_ELEMENTS = mapOf(
"kotlin" to KotlinDslElement.KOTLIN
)
private val KOTLIN_MODELS = listOf<GradleBlockModelMap.BlockModelBuilder<*, GradleDslFile>>(
KotlinDslModel::class.java from {
KotlinDslModel(it.ensurePropertyElement(KotlinDslElement.KOTLIN))
},
)
override fun getParentClass() = GradleBuildModel::class.java
override fun availableModels(): List<GradleBlockModelMap.BlockModelBuilder<*, GradleDslFile>> {
return KOTLIN_MODELS
}
override fun elementsMap(): Map<String, PropertiesElementDescription<*>> {
return KOTLIN_ELEMENTS
}
}
private infix fun <M, P> Class<M>.from(action: (P) -> M): GradleBlockModelMap.BlockModelBuilder<M, P> where M : GradleDslModel, P : GradlePropertiesDslElement {
return object : GradleBlockModelMap.BlockModelBuilder<M, P> {
override fun modelClass() = this@from
override fun create(p: P): M = action(p)
}
}
| 1
|
Kotlin
|
0
| 9
|
269d18727cc51aa446478c3aac86a6e605f1d481
| 1,803
|
package-search-intellij-plugin
|
Apache License 2.0
|
libs/serialization/json-validator/src/main/kotlin/net/corda/common/json/validation/WrappedJsonSchema.kt
|
corda
| 346,070,752
| false
|
{"Kotlin": 20579329, "Java": 307325, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
|
package net.corda.common.json.validation
import com.networknt.schema.JsonSchema
data class WrappedJsonSchema(val schema: JsonSchema)
| 10
|
Kotlin
|
26
| 67
|
b7b4125bd3fbe9869c0f0b1ca7e286ca865901ab
| 134
|
corda-runtime-os
|
Apache License 2.0
|
src/main/kotlin/br/com/iphoneswapcenter/config/WebServerConfiguration.kt
|
harlanpierre
| 743,768,553
| false
|
{"Kotlin": 60633}
|
package br.com.iphoneswapcenter.config
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration
class WebServerConfiguration : WebMvcConfigurer {
@Value("\${cors.originPatterns:default}")
private val corsOriginPatterns: String = ""
override fun addCorsMappings(registry: CorsRegistry) {
val allowedOrigins = corsOriginPatterns.split(",").toTypedArray()
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins(*allowedOrigins)
.allowCredentials(true)
}
}
| 0
|
Kotlin
|
0
| 0
|
0e031141137f03e344e6e83e87599a6afdfd277c
| 754
|
spring-boot-and-kotlin-iphoneswapcenter
|
Apache License 2.0
|
_pending/android-super-hero-app/features/characters/characters-framework/src/main/java/com/carlosrd/superhero/data/characters/framework/room/SuperHeroRoomDatabase.kt
|
luannguyen252
| 371,359,679
| false
| null |
package com.carlosrd.superhero.data.characters.framework.room
import androidx.room.Database
import androidx.room.RoomDatabase
import com.carlosrd.superhero.data.characters.datasource.local.room.dao.CharacterDao
import com.carlosrd.superhero.data.characters.datasource.local.room.dao.CharactersCacheControlDao
import com.carlosrd.superhero.data.characters.datasource.local.room.model.CharacterEntity
import com.carlosrd.superhero.data.characters.datasource.local.room.model.CharactersCacheControlEntity
@Database(
entities = [
CharacterEntity::class,
CharactersCacheControlEntity::class],
version = 1,
exportSchema = false
)
abstract class SuperHeroRoomDatabase : RoomDatabase() {
abstract fun charactersDao(): CharacterDao
abstract fun charactersCacheControlDao(): CharactersCacheControlDao
}
| 0
|
Kotlin
|
0
| 1
|
a9b5aef8662a1808042c820c3dfac02e1efd5800
| 834
|
my-android-journey
|
MIT License
|
billing-v6/src/test/java/io/appmetrica/analytics/billingv6/impl/ProductTypeParserTest.kt
|
appmetrica
| 650,662,094
| false
| null |
package io.appmetrica.analytics.billingv6.impl
import com.android.billingclient.api.BillingClient
import io.appmetrica.analytics.billinginterface.internal.ProductType
import io.appmetrica.analytics.billingv6.impl.ProductTypeParser.parse
import io.appmetrica.analytics.testutils.CommonTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
@RunWith(ParameterizedRobolectricTestRunner::class)
class ProductTypeParserTest(
private val productType: String,
private val expected: ProductType
) : CommonTest() {
companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "{0}")
fun data(): Collection<Array<Any>> {
return listOf(
arrayOf(BillingClient.ProductType.INAPP, ProductType.INAPP),
arrayOf(BillingClient.ProductType.SUBS, ProductType.SUBS),
arrayOf("type", ProductType.UNKNOWN),
arrayOf("", ProductType.UNKNOWN)
)
}
}
@Test
fun parse() {
assertThat(
parse(
productType
)
).isEqualTo(expected)
}
}
| 1
| null |
5
| 54
|
472d3dfb1e09f4e7f35497e5049f53287ccce7d1
| 1,246
|
appmetrica-sdk-android
|
MIT License
|
Kotlin Koans/Collections/Fold/Solution.kt
|
Kotlin
| 50,311,744
| false
| null |
package collections.fold
import collections.*
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
/*<taskWindow>*/val allProducts = customers.flatMap { it.orders.flatMap { it.products }}.toSet()
return customers.fold(allProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})/*</taskWindow>*/
}
| 14
|
Kotlin
|
18
| 55
|
9028a7b3d5c7fc6f9b669deee4596f97f4272b8b
| 395
|
kotlin-koans-edu-obsolete
|
MIT License
|
server/src/main/kotlin/io/tuzzy/portal/domain/DUser.kt
|
maxtuzz
| 225,085,025
| false
|
{"TypeScript": 118399, "Kotlin": 59202, "HTML": 1815, "CSS": 358, "Dockerfile": 207}
|
//package io.tuzzy.portal.domain
//
//import javax.persistence.Column
//import javax.persistence.Entity
//import javax.persistence.Table
//
//@Entity
//@Table(name = "user")
//class DUser(
// // Users external id
// extId: String,
// username: String,
// email: String,
// pictureUrl: String? = null
//) : BaseDomain() {
// @Column(unique = true, nullable = false, length = 45)
// var extId: String = extId
// @Column(unique = true, nullable = false, length = 25)
// var username: String = username
//
// var email = email
// var pictureUrl = pictureUrl
//}
| 22
|
TypeScript
|
0
| 2
|
60da9d67452bf040d8659a7e4cfb6e237602dc5b
| 590
|
tuzhub
|
Apache License 2.0
|
ncalcapp/src/main/java/io/jopitel/android/ncalc/napp/MainActivity.kt
|
countrydev76project
| 165,411,056
| false
|
{"Gradle": 21, "Java Properties": 1, "Shell": 2, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Java": 12, "Kotlin": 21, "XML": 33, "CMake": 2, "C++": 2, "INI": 1}
|
package io.jopitel.android.ncalc.napp
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import io.jopitel.android.ncalc.ncore.hjCalcMain
import io.jopitel.android.ncalc.nnative.hjCalcNative
import io.jopitel.android.ncalc.nwrap.hjCalcWrapMain
class MainActivity : AppCompatActivity() {
val TAG = "[hjjo]"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
test_ncalcnative()
test_ncalccore()
test_ncalcwrap()
}
fun test_ncalcnative() {
var calcNative = hjCalcNative()
Log.d(TAG, calcNative.stringFrom())
}
fun test_ncalccore() {
hjCalcMain.main(arrayOf("hello", "world"))
}
fun test_ncalcwrap() {
hjCalcWrapMain.main(arrayOf("hello", "world"))
}
}
| 1
| null |
1
| 1
|
1a32997bb3eb057fb8e29a82fd22af65d0a5d3b4
| 832
|
ncalc-android
|
MIT License
|
examples/GiantExplorer/giant-explorer/src/main/java/com/storyteller_f/giant_explorer/dialog/TaskConfirmDialog.kt
|
storytellerF
| 576,917,592
| false
| null |
package com.storyteller_f.giant_explorer.dialog
import android.os.Parcelable
import android.widget.LinearLayout
import android.widget.TextView
import com.storyteller_f.common_ui.SimpleDialogFragment
import com.storyteller_f.common_ui.setFragmentResult
import com.storyteller_f.common_ui.setOnClick
import com.storyteller_f.common_vm_ktx.keyPrefix
import com.storyteller_f.common_vm_ktx.pvm
import com.storyteller_f.giant_explorer.control.TempVM
import com.storyteller_f.giant_explorer.databinding.DialogTaskConfirmBinding
import com.storyteller_f.giant_explorer.databinding.ViewHolderTaskConfirmItemBinding
import kotlinx.parcelize.Parcelize
import java.io.File
class TaskConfirmDialog : SimpleDialogFragment<DialogTaskConfirmBinding>(DialogTaskConfirmBinding::inflate) {
private val tempVM by keyPrefix({ "temp" }, pvm({}) {
TempVM()
})
override fun onBindViewEvent(binding: DialogTaskConfirmBinding) {
binding.labelDest.text = tempVM.dest
tempVM.list.forEach {
val file = File(it)
val inflate = ViewHolderTaskConfirmItemBinding.inflate(layoutInflater, binding.selected, true)
inflate.name.text = file.name
inflate.path.text = it
}
binding.include.negative.setOnClick {
dismiss()
}
binding.include.positive.setOnClick {
setFragmentResult(Result(true))
dismiss()
}
}
@Parcelize
class Result(val confirm: Boolean) : Parcelable
}
| 3
| null |
0
| 2
|
0b088479098ad02b083f6396f061f2988f3f817d
| 1,503
|
common-ui-list-structure
|
MIT License
|
breeze-dsl/src/main/kotlin/dsl/cmd/CmdDslExtensions.kt
|
DragonKnightOfBreeze
| 205,561,109
| false
| null |
// Copyright (c) 2020-2021 DragonKnightOfBreeze Windea
// Breeze is blowing...
@file:JvmName("CmdDslExtensions")
package icu.windea.breezeframework.dsl.cmd
@CmdDslMarker
inline fun cmdDsl(block: CmdDslDocument.() -> CharSequence): CmdDslDocument {
return CmdDslDocument().apply { text = block() }
}
@CmdDslMarker
fun CmdDslInlinePoint.bold(text: CharSequence): CmdBoldText {
return CmdBoldText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.light(text: CharSequence): CmdLightText {
return CmdLightText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.italic(text: CharSequence): CmdItalicText {
return CmdItalicText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.underline(text: CharSequence): CmdUnderlineText {
return CmdUnderlineText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.blink(text: CharSequence): CmdBlinkText {
return CmdBlinkText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.invert(text: CharSequence): CmdInvertText {
return CmdInvertText(text)
}
@CmdDslMarker
fun CmdDslInlinePoint.color(text: CharSequence, color: CmdColor): CmdColoredText {
return CmdColoredText(text, color)
}
@CmdDslMarker
fun CmdDslInlinePoint.bgColor(text: CharSequence, color: CmdColor): CmdBgColoredText {
return CmdBgColoredText(text, color)
}
@CmdDslMarker
fun CmdDslInlinePoint.style(text: CharSequence, vararg styles: CmdStyle): CmdStyledText {
return CmdStyledText(text, *styles)
}
| 1
| null |
1
| 8
|
e067f9e676fbb2fe2d4b5076e522edea63ce5a0f
| 1,388
|
Breeze-Framework
|
MIT License
|
src/test/kotlin/dynamicProgramming/UnboundedKnapsackTest.kt
|
TheAlgorithms
| 177,334,737
| false
| null |
package dynamicProgramming
import org.junit.Test
class UnboundedKnapsackTest {
@Test
fun testBothWeightAndValueArrayHasDifferentValuesGivesExpectedOutput() {
assert(unboundedKnapsack(5, intArrayOf(1, 2, 3), intArrayOf(20, 50, 30), 3) == 120)
}
@Test
fun testBothWeightAndValueArrayHasSameValuesGivesExpectedOutput() {
assert(unboundedKnapsack(3, intArrayOf(2, 2), intArrayOf(3, 3), 2) == 3)
}
@Test
fun testNegativeCapacityGivesZero() {
assert(unboundedKnapsack(-3, intArrayOf(2, 2), intArrayOf(3, 3), 2) == 0)
}
@Test
fun testZeroCapacityGivesZero() {
assert(unboundedKnapsack(0, intArrayOf(2, 2), intArrayOf(3, 3), 2) == 0)
}
}
| 57
|
Kotlin
|
293
| 977
|
e57a8888dec4454d39414082bbe6a672a9d27ad1
| 714
|
Kotlin
|
MIT License
|
src/test/kotlin/net/starlegacy/feature/multiblock/particleshield/ShieldMultiblockClass08iTest.kt
|
hafarooki
| 437,384,015
| false
| null |
package net.starlegacy.feature.multiblock.particleshield
import net.starlegacy.feature.multiblock.Multiblock
import net.starlegacy.feature.progression.advancement.SLAdvancement
internal class ShieldMultiblockClass08iTest : ShieldMultiblockTest() {
override fun getMultiblock(): Multiblock = ShieldMultiblockClass08i
override fun getExpectedAdvancement(): SLAdvancement = SLAdvancement.PARTICLE_SHIELD_08I
override fun getClassText(): String = "&d0.8i"
}
| 0
|
Kotlin
|
16
| 4
|
c830eb40180c935e8bfff599da0f9310eeccfb5c
| 468
|
StarLegacy
|
MIT License
|
archive/src/main/kotlin/org/openrs2/archive/key/JsonKeyDownloader.kt
|
openrs2
| 315,027,372
| false
| null |
package org.openrs2.archive.key
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.future.await
import kotlinx.coroutines.withContext
import org.openrs2.crypto.XteaKey
import org.openrs2.http.checkStatusCode
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
public abstract class JsonKeyDownloader(
private val client: HttpClient,
private val jsonKeyReader: JsonKeyReader
) : KeyDownloader {
override suspend fun download(url: String): Sequence<XteaKey> {
val request = HttpRequest.newBuilder(URI(url))
.GET()
.timeout(Duration.ofSeconds(30))
.build()
val response = client.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()).await()
response.checkStatusCode()
return withContext(Dispatchers.IO) {
response.body().use { input ->
jsonKeyReader.read(input)
}
}
}
}
| 0
|
Kotlin
|
2
| 8
|
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
| 1,017
|
openrs2
|
ISC License
|
common/core/src/main/java/com/cryart/sabbathschool/core/navigation/Destination.kt
|
Adventech
| 65,243,816
| false
| null |
/*
* Copyright (c) 2021. Adventech <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.core.navigation
import android.net.Uri
import androidx.core.net.toUri
enum class Destination(val key: String) {
ABOUT("about"),
ACCOUNT("account"),
LESSONS("lessons"),
LOGIN("login"),
READ("read"),
READ_WEB("sabbath-school.adventech.io"),
SETTINGS("settings");
companion object {
private val map = values().associateBy(Destination::key)
fun fromKey(type: String) = map[type]
}
}
private const val SCHEME = "ss_app://"
/**
* Builds a navigation [Uri] from a [Destination]
*
* Example:
* Passing [Destination.READ] with extras [Pair("lesson_index", "index")]
* will return `ss_app://read?lesson_index=index`
*
*/
fun Destination.toUri(vararg extras: Pair<String, String> = emptyArray()): Uri {
val query = if (extras.isNotEmpty()) {
extras.joinToString(separator = "&", prefix = "?") { pair ->
"${pair.first}=${pair.second}"
}
} else {
""
}
return "$SCHEME$key$query".toUri()
}
| 7
| null |
49
| 80
|
e7bab11541edea65864616c7e8c72569dc8b810a
| 2,153
|
sabbath-school-android
|
MIT License
|
app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt
|
mohammadjannaser
| 356,254,420
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelabs.paging.ui
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import com.example.android.codelabs.paging.Injection
import com.example.android.codelabs.paging.databinding.ActivitySearchRepositoriesBinding
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class SearchRepositoriesActivity : AppCompatActivity() {
private lateinit var binding: ActivitySearchRepositoriesBinding
private lateinit var viewModel: SearchRepositoriesViewModel
private val adapter = ReposAdapter()
private var searchJob : Job? = null
private lateinit var mContext : Context
/***********************************************************************************************
* Sometimes, the collect function might not be automatically detected by Android Studio.
* In this case, make sure you import kotlinx.coroutines.flow.collect.
**********************************************************************************************/
private fun search(query : String){
searchJob?.cancel()
searchJob = lifecycleScope.launch {
viewModel.searchRepo(query).collectLatest { adapter.submitData(it) }
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySearchRepositoriesBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
mContext = this
// get the view model
viewModel = ViewModelProvider(this, Injection.provideViewModelFactory(mContext)).get(SearchRepositoriesViewModel::class.java)
// add dividers between RecyclerView's row items
val decoration = DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL)
binding.list.addItemDecoration(decoration)
initAdapter()
val query = savedInstanceState?.getString(LAST_SEARCH_QUERY) ?: DEFAULT_QUERY
search(query)
initSearch(query)
binding.retryButton.setOnClickListener { adapter.retry() }
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(LAST_SEARCH_QUERY, binding.searchRepo.text.trim().toString())
}
private fun initAdapter() {
binding.list.adapter = adapter.withLoadStateHeaderAndFooter(
header = ReposLoadStateAdapter { adapter.retry()},
footer = ReposLoadStateAdapter { adapter.retry()}
)
// Show loading spinner during initial load or refresh
// This section is used to show loading bar in the main page if you are using room database
// there is no need for this loading cause the database is fast enough to load the data.
// adapter.addLoadStateListener { combinedLoadStates ->
// // Only show the list if refresh succeeds.
// binding.list.isVisible = combinedLoadStates.source.refresh is LoadState.NotLoading
// // Show loading spinner during initial load or refresh
// // binding.progressBar.isVisible = combinedLoadStates.source.refresh is LoadState.Loading
// // Show the retry state if initial load or refresh fails
// binding.retryButton.isVisible = combinedLoadStates.source.refresh is LoadState.Error
//
// val errorState = combinedLoadStates.source.append as? LoadState.Error
// ?: combinedLoadStates.source.prepend as? LoadState.Error
// ?: combinedLoadStates.append as? LoadState.Error
// ?: combinedLoadStates.prepend as? LoadState.Error
//
// errorState?.let { Toast.makeText(this,"\uD83D\uDE28 Wooops ${it.error}",Toast.LENGTH_LONG).show() }
// }
}
private fun initSearch(query: String) {
binding.searchRepo.setText(query)
binding.searchRepo.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
updateRepoListFromInput()
true
} else false
}
binding.searchRepo.setOnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
updateRepoListFromInput()
true
} else false
}
// Scroll to top when the list is refreshed from network.
lifecycleScope.launch {
adapter.loadStateFlow
// Only emit when REFRESH LoadState Changes.
.distinctUntilChangedBy {it.refresh}
// Only react to cases where REFRESH completes. i.e., NotLoading.
.filter { it.refresh is LoadState.NotLoading}
.collect { binding.list.scrollToPosition(0) }
}
}
private fun updateRepoListFromInput(){
binding.searchRepo.text.trim().let {
if (it.isNotEmpty()){
binding.list.scrollToPosition(0)
search(it.toString())
}
}
}
companion object {
private const val LAST_SEARCH_QUERY: String = "last_search_query"
private const val DEFAULT_QUERY = "Android"
}
}
| 0
|
Kotlin
|
0
| 0
|
8e0d058ff85a10a35d876553f07ad3c9035cb9f1
| 6,345
|
android-paging-master
|
Apache License 2.0
|
protocol/push/src/main/kotlin/com/walletconnect/push/common/data/jwt/PushJwtClaims.kt
|
WalletConnect
| 435,951,419
| false
| null |
package com.walletconnect.push.common.data.jwt
import com.walletconnect.foundation.util.jwt.JwtClaims
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class PushSubscriptionJwtClaim(
@Json(name = "iss") override val issuer: String,
@Json(name = "sub") val subject: String,
@Json(name = "aud") val audience: String,
@Json(name = "iat") val issuedAt: Long,
@Json(name = "exp") val expiration: Long,
@Json(name = "ksu") val keyserverUrl: String,
@Json(name = "act") val action: String = "push_subscription",
@Json(name = "scp") val scope: String,
) : JwtClaims
| 147
|
Kotlin
|
59
| 157
|
e34c0e716ca68021602463773403d8d7fd558b34
| 649
|
WalletConnectKotlinV2
|
Apache License 2.0
|
src/main/kotlin/me/devoxin/flight/internal/utils/MessageCommandUtil.kt
|
mixtape-oss
| 331,475,215
| true
|
{"Kotlin": 120308}
|
package me.devoxin.flight.internal.utils
import me.devoxin.flight.api.annotations.Name
import me.devoxin.flight.api.annotations.RateLimit
import me.devoxin.flight.api.command.Context
import me.devoxin.flight.api.command.message.MessageCommandFunction
import me.devoxin.flight.api.command.message.MessageContext
import me.devoxin.flight.api.command.message.MessageSubCommandFunction
import me.devoxin.flight.api.command.message.annotations.*
import me.devoxin.flight.api.entities.Cog
import me.devoxin.flight.internal.arguments.CommandArgument
import org.slf4j.LoggerFactory
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.*
import kotlin.reflect.jvm.javaMethod
import kotlin.reflect.jvm.jvmErasure
import kotlin.reflect.typeOf
object MessageCommandUtil {
private val logger = LoggerFactory.getLogger(MessageCommandUtil::class.java)
fun loadCommand(meth: KFunction<*>, cog: Cog): MessageCommandFunction {
val name = meth.findAnnotation<Name>()?.name
?: meth.name
check(meth.javaMethod!!.declaringClass == cog::class.java) {
"$name is not from ${cog::class.simpleName}"
}
require(meth.hasAnnotation<MessageCommand>()) {
"$name is not annotated with Command!"
}
val category = cog.name()
?: cog::class.java.`package`.name.split('.')
.last()
.replace('_', ' ')
.lowercase()
.replaceFirstChar { it.uppercase() }
val properties = meth.findAnnotation<MessageCommand>()!!
val rateLimit = meth.findAnnotation<RateLimit>()
val ctxParam = meth.valueParameters.firstOrNull {
it.type.isSubtypeOf(typeOf<Context>())
}
require(ctxParam != null) {
"${meth.name} is missing the Context parameter!"
}
val parameters = meth.valueParameters.filterNot {
it.type.isSubtypeOf(typeOf<Context>())
}
val arguments = loadParameters(parameters)
val subcommands = getSubCommands(cog)
val cogParentCommands = cog::class.functions.filter {
it.hasAnnotation<MessageCommand>()
}
if (subcommands.isNotEmpty() && cogParentCommands.size > 1) {
throw IllegalStateException("SubCommands are present within ${cog::class.simpleName} however there are multiple top-level commands!")
}
return MessageCommandFunction(
name,
meth,
cog,
arguments,
ctxParam,
category,
properties,
rateLimit,
subcommands
)
}
fun getSubCommands(cog: Cog): List<MessageSubCommandFunction> {
logger.debug("Scanning ${cog::class.simpleName} for sub-commands...")
val cogClass = cog::class
val subcommands = cogClass.members
.filterIsInstance<KFunction<*>>()
.filter { it.hasAnnotation<MessageSubCommand>() }
.map { loadSubCommand(it, cog) }
logger.debug("Found ${subcommands.size} sub-commands in cog ${cogClass.simpleName}")
return subcommands.toList()
}
private fun loadSubCommand(meth: KFunction<*>, cog: Cog): MessageSubCommandFunction {
/* get the name of this sub-command */
val name = meth.findAnnotation<Name>()?.name
?: meth.name.lowercase()
/* do some checks */
check(meth.javaMethod!!.declaringClass == cog::class.java) {
"${meth.name} is not from ${cog::class.simpleName}"
}
require(meth.hasAnnotation<MessageSubCommand>()) {
"${meth.name} is not annotated with MessageSubCommand!"
}
/* load properties */
val properties = meth.findAnnotation<MessageSubCommand>()!!
/* find the message context parameter. */
val ctxParam = meth.valueParameters.firstOrNull {
it.type.isSubtypeOf(typeOf<Context>())
}
require(ctxParam != null) {
"${meth.name} is missing the MessageContext parameter!"
}
/* find arguments */
val parameters = meth.valueParameters.filterNot {
it.type.isSubtypeOf(typeOf<Context>())
}
val arguments = loadParameters(parameters)
/* return sub command function */
return MessageSubCommandFunction(name, properties, meth, cog, arguments, ctxParam)
}
private fun loadParameters(parameters: List<KParameter>): List<CommandArgument> {
val arguments = mutableListOf<CommandArgument>()
for (p in parameters) {
val pName = p.findAnnotation<Name>()?.name ?: p.name ?: p.index.toString()
var type = p.type.jvmErasure.javaObjectType
var greedy = p.findAnnotation<Greedy>()?.let { GreedyInfo(it.type, it.min..it.max) }
val isOptional = p.isOptional
val isNullable = p.type.isMarkedNullable
val isTentative = p.hasAnnotation<Tentative>()
if (p.type.jvmErasure.isSubclassOf(Collection::class)) {
type = p.type.arguments.first().type!!.jvmErasure.javaObjectType
greedy = GreedyInfo(GreedyType.Regular, greedy?.range ?: 1..Int.MAX_VALUE)
} else if (greedy != null) {
greedy = GreedyInfo(GreedyType.Computed, greedy.range)
}
if (isTentative && !(isNullable || isOptional)) {
throw IllegalStateException("${p.name} is marked as tentative, but does not have a default value and is not marked nullable!")
}
arguments.add(CommandArgument(pName, type, greedy, isOptional, isNullable, isTentative, null, p))
}
return arguments
}
}
| 0
|
Kotlin
|
0
| 3
|
70c2ba879fe1d67959d9c125479cced9dea38ed2
| 5,778
|
flight
|
Apache License 2.0
|
common/common_base/src/main/java/com/cl/common_base/BaseBinding.kt
|
aaaaaaaazmx
| 528,318,389
| false
|
{"Kotlin": 3795613, "Java": 743721}
|
package com.cl.common_base
import androidx.databinding.ViewDataBinding
interface BaseBinding<VB : ViewDataBinding> {
fun VB.initBinding()
}
| 0
|
Kotlin
|
0
| 0
|
247e94565fc8418fc8c43e543dc52dcd541842b4
| 145
|
abby
|
Apache License 2.0
|
modo-compose/src/main/java/com/github/terrakok/modo/ContainerScreen.kt
|
ikarenkov
| 336,628,876
| false
| null |
package com.github.terrakok.modo
import android.os.Parcel
import android.os.Parcelable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ProvidedValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
val LocalContainerScreen = staticCompositionLocalOf<ContainerScreen<*, *>?> { null }
fun interface ReducerAction<State : NavigationState> : NavigationAction<State> {
fun reduce(oldState: State): State
}
abstract class ContainerScreen<State : NavigationState, Action : NavigationAction<State>>(
private val navModel: NavModel<State, Action>
) : Screen, NavigationContainer<State, Action> by navModel {
/**
* The reducer that can be used to control state updates.
*/
open val reducer: NavigationReducer<State, Action>? = null
internal val renderer: NavigationRenderer<State>?
get() = navModel.renderer
final override val screenKey: ScreenKey = navModel.screenKey
init {
navModel.init(
reducerProvider = { reducer },
renderer = ComposeRenderer(this)
)
}
/**
* This function can be used to provide composition locals for inner screens.
* This is used in implementations of ContainerScreen to provide typed composition locals to container.
* @see com.github.terrakok.modo.stack.LocalStackNavigation
*/
open fun provideCompositionLocals(): Array<ProvidedValue<*>> =
provideNavigationContainer()
?.let { arrayOf(it) }
?: emptyArray()
/**
* Provides composition local for the nested hierarchy to receive NavigationContainer.
* @see com.github.terrakok.modo.stack.LocalStackNavigation
*/
open fun provideNavigationContainer(): ProvidedValue<out NavigationContainer<*, *>>? = null
@Composable
protected fun InternalContent(
screen: Screen,
modifier: Modifier = Modifier,
content: RendererContent<State> = defaultRendererContent
) {
val composeRenderer = renderer as ComposeRenderer
composeRenderer.Content(screen, modifier, provideCompositionLocals(), content)
}
override fun toString(): String = this::class.java.simpleName + "(navModel: $navModel)"
}
typealias ReducerProvider<State, Action> = () -> NavigationReducer<State, Action>?
/**
* Container for simple using [ContainerScreen] with [Parcelize]
*/
class NavModel<State : NavigationState, Action : NavigationAction<State>>(
initialState: State,
val screenKey: ScreenKey = generateScreenKey()
) : NavigationContainer<State, Action>, Parcelable {
override var navigationState: State = initialState
get() = renderer?.state ?: field
set(value) {
field = value
renderer?.render(value)
}
private var reducerProvider: ReducerProvider<State, Action>? = null
internal var renderer: ComposeRenderer<State>? = null
private set
internal fun init(
reducerProvider: ReducerProvider<State, Action>,
renderer: ComposeRenderer<State>
) {
assert(this.reducerProvider == null && this.renderer == null) {
"Trying to initialize navigation model again"
}
this.reducerProvider = reducerProvider
this.renderer = renderer.also { it.render(navigationState) }
}
override fun dispatch(action: Action, vararg actions: Action) {
val reducer = reducerProvider!!()
var state = reduce(reducer, navigationState, action)
for (varargAction in actions) {
state = reduce(reducer, state, varargAction)
}
navigationState = state
}
override fun describeContents(): Int = 0
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeParcelable(navigationState, flags)
parcel.writeString(screenKey.value)
}
private fun reduce(reducer: NavigationReducer<State, Action>?, state: State, action: Action): State =
reducer?.reduce(action, state)
?: when (action) {
is ReducerAction<*> -> (action as? ReducerAction<State>)?.reduce(state)
else -> null
}
// TODO: print logs when fallback to state
?: state
override fun toString(): String = "NavModel(navigationState=$navigationState, screenKey=$screenKey)"
companion object CREATOR : Parcelable.Creator<NavModel<*, *>> {
override fun createFromParcel(parcel: Parcel): NavModel<NavigationState, *> {
val state = parcel.readParcelable<NavigationState>(NavModel::class.java.classLoader)!!
val screenKey = parcel.readString()!!
return NavModel(state, ScreenKey(screenKey))
}
override fun newArray(size: Int): Array<NavModel<*, *>?> = arrayOfNulls(size)
}
}
| 9
| null |
18
| 301
|
6dff8e7281e7a8a04bb19de997037192530f704a
| 4,838
|
Modo
|
The Unlicense
|
carp.deployment.core/src/commonTest/kotlin/dk/cachet/carp/deployment/infrastructure/DeploymentServiceRequestsTest.kt
|
cortinico
| 333,548,384
| true
|
{"Kotlin": 877308, "TypeScript": 30334}
|
package dk.cachet.carp.deployment.infrastructure
import dk.cachet.carp.common.DateTime
import dk.cachet.carp.common.UUID
import dk.cachet.carp.common.ddd.ServiceInvoker
import dk.cachet.carp.deployment.application.DeploymentService
import dk.cachet.carp.deployment.application.DeploymentServiceMock
import dk.cachet.carp.protocols.domain.devices.DefaultDeviceRegistration
import dk.cachet.carp.protocols.infrastructure.test.createEmptyProtocol
import dk.cachet.carp.test.runSuspendTest
import kotlin.test.*
/**
* Tests for [DeploymentServiceRequest]'s.
*/
class DeploymentServiceRequestsTest
{
companion object
{
val requests: List<DeploymentServiceRequest> = listOf(
DeploymentServiceRequest.CreateStudyDeployment( createEmptyProtocol().getSnapshot() ),
DeploymentServiceRequest.GetStudyDeploymentStatus( UUID.randomUUID() ),
DeploymentServiceRequest.GetStudyDeploymentStatusList( setOf( UUID.randomUUID() ) ),
DeploymentServiceRequest.RegisterDevice( UUID.randomUUID(), "Test role", DefaultDeviceRegistration( "Device ID" ) ),
DeploymentServiceRequest.UnregisterDevice( UUID.randomUUID(), "Test role" ),
DeploymentServiceRequest.GetDeviceDeploymentFor( UUID.randomUUID(), "Test role" ),
DeploymentServiceRequest.DeploymentSuccessful( UUID.randomUUID(), "Test role", DateTime.now() ),
DeploymentServiceRequest.Stop( UUID.randomUUID() )
)
}
private val mock = DeploymentServiceMock()
@Test
fun can_serialize_and_deserialize_requests()
{
requests.forEach { request ->
val serializer = DeploymentServiceRequest.serializer()
val serialized = JSON.encodeToString( serializer, request )
val parsed = JSON.decodeFromString( serializer, serialized )
assertEquals( request, parsed )
}
}
@Suppress( "UNCHECKED_CAST" )
@Test
fun invokeOn_requests_call_service() = runSuspendTest {
requests.forEach { request ->
val serviceInvoker = request as ServiceInvoker<DeploymentService, *>
val function = serviceInvoker.function
serviceInvoker.invokeOn( mock )
assertTrue( mock.wasCalled( function, serviceInvoker.overloadIdentifier ) )
mock.reset()
}
}
}
| 7
| null |
0
| 0
|
9ed082ee919066a0e4774863cf7ecc3b6d00daf1
| 2,345
|
carp.core-kotlin
|
MIT License
|
src/main/java/xyz/nulldev/stubit/StubIt.kt
|
null-dev
| 77,108,491
| false
| null |
package xyz.nulldev.stubit
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.body.ConstructorDeclaration
import com.github.javaparser.ast.body.FieldDeclaration
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.expr.*
import com.github.javaparser.ast.stmt.BlockStmt
import com.github.javaparser.ast.stmt.ThrowStmt
import com.github.javaparser.ast.type.PrimitiveType
import com.github.javaparser.ast.visitor.VoidVisitorAdapter
import java.io.File
import java.util.*
class StubIt {
companion object {
@JvmStatic fun main(args: Array<String>) {
StubIt().run(args)
}
}
fun run(args: Array<String>) {
var print = false
var extension = "stub.java"
var stdin = false
val files = mutableListOf<File>()
var expectExtension = false
for(arg in args) {
if(expectExtension) {
extension = arg
expectExtension = false
} else if(arg == "--stdin") {
stdin = true
} else if(arg == "--print") {
print = true
} else if(arg == "--extension") {
expectExtension = true
} else {
files += File(arg)
}
}
if(expectExtension) {
println("Error: Expecting file extension!")
return
}
val visitor = StubVisitor()
fun processCu(cu: CompilationUnit, output: File? = null) {
visitor.visit(cu, null)
if(output != null) {
output.writeText(cu.toString())
} else {
System.out.println(cu)
}
}
if(stdin) {
val list = mutableListOf<String>()
val s = Scanner(System.`in`)
while(s.hasNextLine()) {
list += s.nextLine()
}
val string = list.joinToString("\n")
val cu = JavaParser.parse(string)
processCu(cu)
} else {
for(file in files) {
val cu = JavaParser.parse(file)
processCu(cu, if(!print)
File(file.parentFile, "${file.nameWithoutExtension}.$extension")
else
null)
}
}
}
class StubVisitor : VoidVisitorAdapter<Void>() {
val RUNTIME_EXCEPTION_STMT = ThrowStmt(ObjectCreationExpr()
.setType(RuntimeException::class.java)
.addArgument(StringLiteralExpr("Stub!")))
val RUNTIME_EXCEPTION_BLK = BlockStmt().addStatement(RUNTIME_EXCEPTION_STMT)!!
override fun visit(n: MethodDeclaration, arg: Void?) {
if(n.body.isPresent) n.setBody(RUNTIME_EXCEPTION_BLK)
}
override fun visit(n: FieldDeclaration, arg: Void?) {
if(n.variables.isEmpty()) return
for(variable in n.variables) {
if(!variable.initializer.isPresent) {
continue
}
val init = variable.initializer.get()
//Null out any dynamic initializer
if(isDynamic(init)) {
val expr = if(n.commonType is PrimitiveType) {
when(n.commonType) {
PrimitiveType.BOOLEAN_TYPE -> BooleanLiteralExpr()
PrimitiveType.CHAR_TYPE -> CharLiteralExpr()
else -> IntegerLiteralExpr()
}
} else {
NullLiteralExpr()
}
variable.setInitializer(expr)
}
}
}
override fun visit(n: ConstructorDeclaration, arg: Void?) {
n.body = RUNTIME_EXCEPTION_BLK
}
override fun visit(n: BlockStmt, arg: Void?) {
n.statements.clear()
}
fun isDynamic(n: Expression?): Boolean {
if(n == null) {
return false
} else if(n is BinaryExpr) {
return isDynamic(n.left) || isDynamic(n.right)
} else if(n is CastExpr) {
return isDynamic(n.expression)
} else if(n is ArrayCreationExpr) {
if(n.initializer.isPresent)
return isDynamic(n.initializer.get())
} else if(n is ArrayInitializerExpr) {
n.values
.filter { isDynamic(it) }
.forEach { return true }
} else if(n is ClassExpr) {
return false
} else if(n is ConditionalExpr) {
return isDynamic(n.condition) || isDynamic(n.elseExpr) || isDynamic(n.thenExpr)
} else if(n is EnclosedExpr) {
if(n.inner.isPresent) return isDynamic(n.inner.get())
} else if(n is ArrayAccessExpr) {
return isDynamic(n.name) || isDynamic(n.index)
} else if(n is UnaryExpr) {
when(n.operator) {
UnaryExpr.Operator.PREFIX_DECREMENT,
UnaryExpr.Operator.POSTFIX_DECREMENT,
UnaryExpr.Operator.PREFIX_INCREMENT,
UnaryExpr.Operator.POSTFIX_INCREMENT -> return false
else -> return isDynamic(n.expression)
}
} else return n !is LiteralExpr
return false
}
}
}
| 1
| null |
1
| 1
|
b95a174f898767217bcbe544b2293a8cadc1482c
| 5,551
|
stub-it
|
MIT License
|
app/src/main/java/com/feechan/footballapps/presenter/matches/nextmatch/NextMatchContract.kt
|
feechanz
| 194,433,053
| false
| null |
package com.feechan.footballapps.presenter.matches.nextmatch
import com.feechan.footballapps.base.BasePresenter
import com.feechan.footballapps.base.BaseView
import com.feechan.footballapps.data.network.response.Event
interface NextMatchContract {
interface View : BaseView {
fun loadMatchData(data: List<Event>)
}
interface Presenter : BasePresenter {
fun loadData(leagueId: String)
}
}
| 0
|
Kotlin
|
0
| 0
|
d83b5a3c00ab005d7daaa061f12dd8fb59a76941
| 423
|
FootballApps
|
Apache License 2.0
|
brazilian-utils-koltin/src/main/java/br/com/lib/brazilian_utils_koltin/currency/CurrencyUtil.kt
|
letsgosh
| 213,450,978
| false
| null |
package br.com.lib.brazilian_utils_koltin.currency
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.*
object CurrencyUtil {
fun formatRealCurrency(value: Double)=
NumberFormat.getCurrencyInstance(Locale("pt", "BR"))
.format(value)
fun formatRealCurrency(value: BigDecimal)=
NumberFormat.getCurrencyInstance(Locale("pt", "BR"))
.format(value)
fun formatRealCurrency(value: Float)=
NumberFormat.getCurrencyInstance(Locale("pt", "BR"))
.format(value)
}
| 0
|
Kotlin
|
1
| 1
|
cdfaad432182085117dbda92934079da45ab019f
| 552
|
brazilian-utils-kotlin
|
MIT License
|
src/main/kotlin/com/hotels/intellij/plugins/network/Preferences.kt
|
ExpediaGroup
| 97,828,016
| false
|
{"Kotlin": 52256}
|
/*
* Copyright 2017 Expedia Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hotels.intellij.plugins.network
/**
* Constants for preferences.
*/
object Preferences {
const val HTTP_PORT_DEFAULT = 8080
const val HTTP_PORT_KEY = "com.hotels.intellij.plugins.network.http_port"
}
| 5
|
Kotlin
|
4
| 3
|
7e0f0d8860c905077b4a4c01240e74dfd52bd082
| 818
|
network-plugin
|
Apache License 2.0
|
tools/entry-generator/src/main/kotlin/godot/tools/entry_generator/parser/XMLParser.kt
|
mrakakuy
| 143,293,552
| false
|
{"Kotlin": 282011, "C": 6051, "Shell": 1222}
|
package godot.tools.entry_generator.parser
import godot.tools.entry_generator.model.*
import org.w3c.dom.*
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.parsers.DocumentBuilderFactory
class XMLParser : Parser {
override fun parseConfig(content: String): Classes {
val reader = InputSource(StringReader(content))
val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
val doc = builder.parse(reader)
doc.documentElement.normalize()
return Classes(doc.documentElement.parseNodes("class") {
parseClass(it)
})
}
private fun parseClass(elem: Element): Class {
val name = elem.criticalValue("name")
val parent = elem.value("extends", "Object")
val classPath = elem.value("class", name)
val tool = elem.value("tool").toBoolean() // no NPE here (should be)
val methods = elem.parseNodes("method") { parseMethod(it) }
val properties = elem.parseNodes("property") { parseProperty(it) }
val signals = elem.parseNodes("signal") { parseSignal(it) }
return Class(name, parent, classPath, tool, methods, properties, signals)
}
private fun parseMethod(elem: Element): Method {
val name = elem.criticalValue("name")
val returnType = elem.value("returnType", "Unit")
val isVararg = elem.value("vararg", "false").toBoolean()
val arguments = elem.parseNodes("argument") { it.criticalValue("type") }
return Method(name, returnType, isVararg, arguments)
}
private fun parseProperty(elem: Element): Property {
val name = elem.criticalValue("name")
val type = elem.criticalValue("type")
val defaultValue = elem.criticalValue("defaultValue")
val export = elem.value("export", "true").toBoolean()
return Property(name, type, defaultValue, export)
}
private fun parseSignal(elem: Element): Signal {
val name = elem.criticalValue("name")
val arguments = elem.parseNodes("argument") {
SignalArgument(it.criticalValue("name"), it.criticalValue("type"))
}
val defaultValues = elem.parseNodes("defaultValue") { it.criticalValue("value") }
return Signal(name, arguments, defaultValues)
}
// Utils
private fun <T> Element.parseNodes(nodeName: String, constructor: (Element) -> T): List<T> {
val result = mutableListOf<T>()
val content = this.getElementsByTagName(nodeName)
for (i in 0 until content.length) {
val it = content.item(i)
if (it.nodeType == Node.ELEMENT_NODE)
result.add(constructor(it as Element))
}
return result
}
private fun Element.criticalValue(name: String): String {
val value = this.getAttribute(name)
if (value == "")
error("Value $name should have be specified!")
return value
}
private fun Element.value(name: String, defaultValue: String = ""): String {
val value = this.getAttribute(name)
return if (value == "") defaultValue else value
}
}
| 5
|
Kotlin
|
12
| 58
|
8079212873d5214ead4b99ce284f56126926a207
| 3,161
|
kotlin-godot-wrapper
|
Apache License 2.0
|
app/src/main/java/com/mrebollob/situmdemo/utils/Extensions.kt
|
mrebollob
| 94,177,439
| false
| null |
package com.mrebollob.situmdemo.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.Toast
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
fun Context.toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.invisible() {
this.visibility = View.INVISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
fun View.isVisible(): Boolean {
return this.visibility == View.VISIBLE
}
fun View.isNotVisible(): Boolean {
return !this.isVisible()
}
fun Context.getBitmapDescriptor(id: Int): BitmapDescriptor {
val vectorDrawable = ContextCompat.getDrawable(this, id)
val size = 70
vectorDrawable.setBounds(0, 0, size, size)
val bm = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bm)
vectorDrawable.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bm)
}
| 1
|
Kotlin
|
0
| 0
|
d614565cb5ced777ee8f830f4be75d5cae143ec8
| 1,134
|
situm-demo
|
Apache License 2.0
|
android/src/main/java/deckyfx/reactnative/printer/worker/JobBuilder.kt
|
deckyfx
| 663,502,538
| false
|
{"Kotlin": 283454, "TypeScript": 61671, "Java": 7149, "C": 5445, "Ruby": 3954, "JavaScript": 3698, "Objective-C": 2368, "Objective-C++": 1066, "Makefile": 817, "CMake": 317, "Swift": 282, "Shell": 89}
|
package deckyfx.reactnative.printer.worker
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import deckyfx.reactnative.printer.escposprinter.PrinterSelectorArgument
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.util.UUID
class JobBuilder(private val reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
private val files = mutableMapOf<UUID, File>()
override fun getName(): String {
return LOG_TAG
}
companion object {
private val LOG_TAG = JobBuilder::class.java.simpleName
const val COMMAND_SELECT_PRINTER = "SELECT_PRINTER:"
const val COMMAND_INITIALIZE = "INITIALIZE:"
const val COMMAND_SET_AS_DOT_MATRIX = "IS_DOT_MATRIX:"
const val COMMAND_USE_ESC_ASTERISK = "USE_ESC_ASTERISK:"
const val COMMAND_PRINT = "PRINT:"
const val COMMAND_FEED_PRINTER = "FEED_PRINTER:"
const val COMMAND_CUT_PAPER = "CUT_PAPER:"
const val COMMAND_OPEN_CASH_BOX = "OPEN_CASH_BOX:"
}
override fun getConstants(): Map<String, Any> {
val constants: MutableMap<String, Any> = HashMap()
constants["LOG_TAG"] = LOG_TAG
return constants
}
private val dirPath: String
get() {
return "${reactContext.filesDir.absolutePath}/printing"
}
private fun appendToFile(uuidString: String, contents: String) {
val uuid = UUID.fromString(uuidString)
val file = files[uuid] ?: throw IllegalArgumentException("File with UUID $uuid does not exist")
// Here true is to append the content to file
// BufferedWriter writer give better performance
with(BufferedWriter(FileWriter(file, true))) {
write(contents)
close()
}
}
@ReactMethod
@Suppress("unused")
fun begin(promise: Promise) {
val uuid = UUID.randomUUID()
val directory = File(dirPath)
val path = "${dirPath}/${uuid}"
if (!directory.exists()) {
directory.mkdirs()
}
val file = File(path)
// If the file doesn't exist, create it.
if (!file.exists()) {
file.createNewFile()
}
// reset it's contents
val fos = FileOutputStream(file)
fos.write("".toByteArray())
fos.close()
files[uuid] = file
promise.resolve(uuid.toString())
}
@ReactMethod
@Suppress("unused")
fun build(uuidString: String, promise: Promise) {
val uuid = UUID.fromString(uuidString)
val path = "${dirPath}/${uuid}"
val file = files[uuid] ?: throw IllegalArgumentException("File with UUID $uuid does not exist")
files.remove(uuid)
promise.resolve(JobBuilderData(uuid.toString(), path).readableMap)
}
@ReactMethod
@Suppress("unused")
fun discard(uuidString: String, promise: Promise) {
val uuid = UUID.fromString(uuidString)
val path = "${dirPath}/${uuid}"
val file = File(path)
if (file.exists()) {
file.delete()
}
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun selectPrinter(uuid: String, selector: ReadableMap, promise: Promise) {
val selectorArg = PrinterSelectorArgument(selector)
appendToFile(uuid, "${COMMAND_SELECT_PRINTER}${selectorArg.json}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun initializePrinter(uuid: String, promise: Promise) {
appendToFile(uuid, "${COMMAND_INITIALIZE}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun printLine(uuid: String, line: String, promise: Promise) {
var lineAdd = line
if (!line.endsWith("\n")) {
lineAdd += "\n"
}
appendToFile(uuid, "${COMMAND_PRINT}${lineAdd}")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun feedPaper(uuid: String, dots: Int = 0, promise: Promise) {
appendToFile(uuid, "${COMMAND_FEED_PRINTER}${dots}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun cutPaper(uuid: String, promise: Promise) {
appendToFile(uuid, "${COMMAND_CUT_PAPER}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun openCashBox(uuid: String, promise: Promise) {
appendToFile(uuid, "${COMMAND_OPEN_CASH_BOX}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun setAsDotMatrix(uuid: String, promise: Promise) {
appendToFile(uuid, "${COMMAND_SET_AS_DOT_MATRIX}\n")
promise.resolve(true)
}
@ReactMethod
@Suppress("unused")
fun useEscAsterisk(uuid: String, promise: Promise) {
appendToFile(uuid, "${COMMAND_USE_ESC_ASTERISK}\n")
promise.resolve(true)
}
@ReactMethod(isBlockingSynchronousMethod = true)
@Suppress("unused")
fun building(uuidString: String): Boolean {
val uuid = UUID.fromString(uuidString)
val file = files[uuid] ?: return false
return true
}
@ReactMethod
@Suppress("unused")
fun preview(uuid: String, promise: Promise) {
val uuidData = UUID.fromString(uuid)
val file = files[uuidData] ?: return promise.resolve("")
val text = file.readText()
promise.resolve(text)
}
}
| 0
|
Kotlin
|
0
| 0
|
4edce0748f1a2e647eca5648c533b8b6a588ba77
| 5,189
|
react-native-printer
|
MIT License
|
features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStateProvider.kt
|
element-hq
| 546,522,002
| false
| null |
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.features.login.impl.screens.confirmaccountprovider
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import io.element.android.features.login.impl.accountprovider.anAccountProvider
import io.element.android.libraries.architecture.Async
open class ConfirmAccountProviderStateProvider : PreviewParameterProvider<ConfirmAccountProviderState> {
override val values: Sequence<ConfirmAccountProviderState>
get() = sequenceOf(
aConfirmAccountProviderState(),
// Add other state here
)
}
fun aConfirmAccountProviderState() = ConfirmAccountProviderState(
accountProvider = anAccountProvider(),
isAccountCreation = false,
loginFlow = Async.Uninitialized,
eventSink = {}
)
| 263
| null |
129
| 955
|
31d0621fa15fe153bfd36104e560c9703eabe917
| 1,373
|
element-x-android
|
Apache License 2.0
|
compiler/tests-spec/testData/diagnostics/linked/overload-resolution/building-the-overload-candidate-set-ocs/call-with-an-explicit-receiver/call-with-an-explicit-type-receiver/p-3/pos/2.1.fir.kt
|
JetBrains
| 3,432,266
| false
| null |
// !DIAGNOSTICS: -UNUSED_VARIABLE -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_VALUE -UNUSED_PARAMETER -UNUSED_EXPRESSION
// SKIP_TXT
/*
* TESTCASE NUMBER: 1
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-39129
*/
fun case1() {
C1.<!UNRESOLVED_REFERENCE!>V<!>()
C1.Companion.<!DEBUG_INFO_CALL("fqName: C1.Companion.V.V; typeCall: function")!>V()<!>
}
class C1(){
companion object {
class V(){
}
}
}
/*
* TESTCASE NUMBER: 2
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-39129
*/
fun case2() {
C2.<!DEBUG_INFO_CALL("fqName: L.invoke; typeCall: variable&invoke")!>V()<!> // to (2)
C2.Companion.<!DEBUG_INFO_CALL("fqName: C2.Companion.V.V; typeCall: function")!>V()<!> // to (1)
}
open class C2(){
companion object {
class V //(1)
}
object V : L()
}
open class L {
operator fun invoke() {} //(2)
}
/*
* TESTCASE NUMBER: 3
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-39129
*/
fun case3() {
C3.<!DEBUG_INFO_CALL("fqName: L3.invoke; typeCall: variable&invoke")!>V()<!> // to (2)
C3.Companion.<!DEBUG_INFO_CALL("fqName: C3.Companion.V.V; typeCall: function")!>V()<!> // to (1)
}
open class C3(){
companion object {
class V //(1)
}
object V : L3()
}
open class L3 {
operator fun invoke(s : String ="") {} //(2)
}
| 157
| null |
5563
| 44,965
|
e6633d3d9214402fcf3585ae8c24213a4761cc8b
| 1,302
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/chessgo/frontend/navigation/AppNavHost.kt
|
buldosik
| 709,015,549
| false
|
{"Kotlin": 179758}
|
package com.example.chessgo.frontend.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
@Composable
fun AppNavHost(isLogged: Boolean) {
val navController = rememberNavController()
// Use the SetupNavigation composable from AppNavigation.kt
SetupNavigation(navController = navController, isLogged)
// Add any additional UI elements or composables here
}
@Composable
fun SetupNavigation(navController: NavHostController, isLogged: Boolean) {
var initScreen = screens.first().route
if(isLogged){
initScreen = screens[4].route
}
NavHost(
navController = navController,
startDestination = initScreen
) {
// Use a loop to set up composable destinations
screens.forEach { screen ->
composable(screen.route) {
// Call a function to handle each screen
HandleScreen(screen, navController)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a20f0f07c34daffce542c3c66e13c8ffa0e66fee
| 1,130
|
Chess-Go
|
MIT License
|
src/aws/lambdas/incremental_distribution/cta/src/main/java/uk/nhs/nhsx/keyfederation/download/KeyFederationDownloadConfig.kt
|
turlodales
| 289,705,241
| true
|
{"Kotlin": 1762543, "HCL": 516174, "Ruby": 402118, "Python": 95997, "HTML": 10538, "Java": 6060, "Shell": 5028, "Dockerfile": 3728, "Makefile": 780, "JavaScript": 554}
|
package uk.nhs.nhsx.keyfederation.download
import uk.nhs.nhsx.core.Environment
import uk.nhs.nhsx.core.Environment.Companion.WORKSPACE
import uk.nhs.nhsx.core.Environment.EnvironmentKey
import uk.nhs.nhsx.core.FeatureFlag
import uk.nhs.nhsx.core.StandardSigning
import uk.nhs.nhsx.core.WorkspaceFeatureFlag
import uk.nhs.nhsx.core.aws.dynamodb.TableName
import uk.nhs.nhsx.core.aws.s3.BucketName
import uk.nhs.nhsx.core.aws.secretsmanager.SecretName
import uk.nhs.nhsx.core.aws.ssm.ParameterName
class KeyFederationDownloadConfig(
val maxSubsequentBatchDownloadCount: Int,
val initialDownloadHistoryDays: Int,
val downloadFeatureFlag: FeatureFlag,
val downloadRiskLevelDefaultEnabled: Boolean,
val downloadRiskLevelDefault: Int,
val submissionBucketName: BucketName,
val interopBaseUrl: String,
val interopAuthTokenSecretName: SecretName,
val signingKeyParameterName: ParameterName,
val federatedKeyDownloadPrefix: String,
val stateTableName: TableName,
val validOrigins: List<String>
) {
companion object {
private val MAX_SUBSEQUENT_BATCH_DOWNLOAD_COUNT = EnvironmentKey.integer("MAX_SUBSEQUENT_BATCH_DOWNLOAD_COUNT")
private val INITIAL_DOWNLOAD_HISTORY_DAYS = EnvironmentKey.integer("INITIAL_DOWNLOAD_HISTORY_DAYS")
private val DOWNLOAD_ENABLED_WORKSPACES = EnvironmentKey.strings("DOWNLOAD_ENABLED_WORKSPACES")
private val DOWNLOAD_RISK_LEVEL_DEFAULT_ENABLED = EnvironmentKey.bool("DOWNLOAD_RISK_LEVEL_DEFAULT_ENABLED")
private val DOWNLOAD_RISK_LEVEL_DEFAULT = EnvironmentKey.integer("DOWNLOAD_RISK_LEVEL_DEFAULT")
private val SUBMISSION_BUCKET_NAME = EnvironmentKey.value("SUBMISSION_BUCKET_NAME", BucketName)
private val INTEROP_BASE_URL = EnvironmentKey.string("INTEROP_BASE_URL")
private val INTEROP_AUTH_TOKEN_SECRET_NAME = EnvironmentKey.value("INTEROP_AUTH_TOKEN_SECRET_NAME", SecretName)
private val FEDERATED_KEY_DOWNLOAD_PREFIX = EnvironmentKey.string("FEDERATED_KEY_DOWNLOAD_PREFIX")
private val PROCESSOR_STATE_TABLE = EnvironmentKey.value("PROCESSOR_STATE_TABLE", TableName)
private val VALID_DOWNLOAD_ORIGINS = EnvironmentKey.strings("VALID_DOWNLOAD_ORIGINS")
fun fromEnvironment(e: Environment) = KeyFederationDownloadConfig(
maxSubsequentBatchDownloadCount = e.access.required(MAX_SUBSEQUENT_BATCH_DOWNLOAD_COUNT),
initialDownloadHistoryDays = e.access.required(INITIAL_DOWNLOAD_HISTORY_DAYS),
downloadFeatureFlag = WorkspaceFeatureFlag(e.access.required(WORKSPACE), e.access.required(DOWNLOAD_ENABLED_WORKSPACES)),
downloadRiskLevelDefaultEnabled = e.access.required(DOWNLOAD_RISK_LEVEL_DEFAULT_ENABLED),
downloadRiskLevelDefault = e.access.required(DOWNLOAD_RISK_LEVEL_DEFAULT),
submissionBucketName = e.access.required(SUBMISSION_BUCKET_NAME),
interopBaseUrl = e.access.required(INTEROP_BASE_URL),
interopAuthTokenSecretName = e.access.required(INTEROP_AUTH_TOKEN_SECRET_NAME),
signingKeyParameterName = e.access.required(StandardSigning.SSM_KEY_ID_PARAMETER_NAME),
federatedKeyDownloadPrefix = e.access.required(FEDERATED_KEY_DOWNLOAD_PREFIX),
stateTableName = e.access.required(PROCESSOR_STATE_TABLE),
validOrigins = e.access.required(VALID_DOWNLOAD_ORIGINS),
)
}
}
| 0
|
Kotlin
|
0
| 0
|
8c67d6e23c7fc79f039c4012238d82131900a4d4
| 3,400
|
covid19-app-system-public
|
MIT License
|
src/com/price_of_command/conditions/Death.kt
|
atlanticaccent
| 409,181,802
| false
| null |
package com.price_of_command.conditions
import com.fs.starfarer.api.campaign.SectorEntityToken
import com.fs.starfarer.api.characters.PersonAPI
import com.fs.starfarer.api.fleet.FleetMemberAPI
import com.price_of_command.clock
import com.price_of_command.memorial.DeathData
class Death(target: PersonAPI, startDate: Long, rootConditions: List<Condition>, var cause: String? = null) :
Condition(target, startDate, rootConditions) {
override fun precondition(): Outcome = if (target.isPlayer) Outcome.NOOP
else Outcome.Applied(this)
@NonPublic
override fun inflict(): Outcome = Outcome.Terminal(this)
override fun pastTense(): String = "dead"
fun toDeathData(ship: FleetMemberAPI?, location: SectorEntityToken) =
DeathData(target, clock().createClock(startDate), ship, location, cause)
}
| 0
|
Kotlin
|
0
| 0
|
5bed23562e783c79d9396674dc94e7f8fa237cfa
| 826
|
officer-expansion
|
The Unlicense
|
app/src/main/java/com/pebbles/obsidiancompanion/OCWidget.kt
|
pebblesoft
| 547,498,004
| false
|
{"Kotlin": 6352}
|
package com.pebbles.obsidiancompanion
import androidx.compose.runtime.Composable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.text.Text
class OCWidget: GlanceAppWidget() {
@Composable
override fun Content() {
Text("hi")
}
}
| 0
|
Kotlin
|
0
| 0
|
d7bdc63568535730bfec7b3645efb270354a1ef5
| 273
|
obsidian-viewer
|
MIT License
|
ground/src/main/java/com/google/android/ground/persistence/remote/firebase/FirebaseMessagingService.kt
|
google
| 127,777,820
| false
| null |
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firebase
import com.google.android.ground.persistence.sync.SurveySyncService
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import timber.log.Timber
/**
* Listens to messages from Firebase Cloud Messaging, and enqueuing re-sync of survey metadata when
* receiving.
*/
@AndroidEntryPoint
class FirebaseMessagingService : FirebaseMessagingService() {
@Inject lateinit var surveySyncService: SurveySyncService
/**
* Processes new messages, enqueuing a worker to sync the survey with the id specified in the
* message topic.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val surveyId = remoteMessage.from?.removePrefix("/topic/")
if (surveyId.isNullOrEmpty()) {
Timber.w("Invalid topic: ${remoteMessage.from}")
return
}
surveySyncService.enqueueSync(surveyId)
}
override fun onNewToken(token: String) {
// no-op: The server doesn't target single devices or device groups, so there's no need to
// re-register the app with the server when the token changes.
}
}
| 235
| null |
115
| 245
|
bb5229149eb3687923a8391f30f7279e477562a8
| 1,830
|
ground-android
|
Apache License 2.0
|
app/src/main/java/ph/mart/shopmart/di/RepositoryModule.kt
|
jaymart7
| 271,985,987
| false
| null |
package ph.mart.shopmart.di
import android.content.SharedPreferences
import ph.mart.shopmart.data.repository.account.AccountRepository
import ph.mart.shopmart.data.repository.account.AccountRepositoryImpl
import ph.mart.shopmart.data.repository.cart.CartRepository
import ph.mart.shopmart.data.repository.cart.CartRepositoryImpl
import ph.mart.shopmart.data.repository.product.ProductRepository
import ph.mart.shopmart.data.repository.product.ProductRepositoryImpl
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
object RepositoryModule {
@ExperimentalCoroutinesApi
@Singleton
@Provides
fun provideProductRepository(
@ProductReference productReference: CollectionReference
): ProductRepository =
ProductRepositoryImpl(productReference)
@Singleton
@Provides
fun provideCartRepository(
@ProductReference productReference: CollectionReference,
firebaseFirestore: FirebaseFirestore
): CartRepository =
CartRepositoryImpl(firebaseFirestore, productReference)
@Singleton
@Provides
fun provideAccountRepository(
sharedPreferences: SharedPreferences
): AccountRepository =
AccountRepositoryImpl(sharedPreferences)
}
| 0
|
Kotlin
|
1
| 0
|
146870ff030023a15f66e303ece5dfa4717f0c79
| 1,547
|
shop-mart
|
MIT License
|
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/profile/components/ChangeManagingEntityView.kt
|
opensrp
| 339,242,809
| false
| null |
/*
* Copyright 2021-2024 Ona Systems, 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.smartregister.fhircore.quest.ui.profile.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.RadioButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.hl7.fhir.r4.model.ResourceType
import org.smartregister.fhircore.engine.configuration.profile.ManagingEntityConfig
import org.smartregister.fhircore.engine.ui.theme.DefaultColor
import org.smartregister.fhircore.engine.ui.theme.DividerColor
import org.smartregister.fhircore.engine.util.annotation.PreviewWithBackgroundExcludeGenerated
import org.smartregister.fhircore.quest.R
import org.smartregister.fhircore.quest.ui.profile.model.EligibleManagingEntity
const val TEST_TAG_SAVE = "saveTestTag"
const val TEST_TAG_CANCEL = "cancelTestTag"
@Composable
fun ChangeManagingEntityView(
modifier: Modifier = Modifier,
eligibleManagingEntities: List<EligibleManagingEntity> = emptyList(),
onSaveClick: (EligibleManagingEntity) -> Unit,
managingEntity: ManagingEntityConfig? = null,
onDismiss: () -> Unit,
) {
var isEnabled by remember { mutableStateOf(false) }
var selectedEligibleManagingEntity by remember { mutableStateOf<EligibleManagingEntity?>(null) }
val onEligibleManagingEntitySelection = { eligibleManagingEntity: EligibleManagingEntity ->
selectedEligibleManagingEntity = eligibleManagingEntity
}
Surface(modifier = modifier.wrapContentHeight().verticalScroll(rememberScrollState())) {
Column(modifier = modifier.fillMaxWidth().wrapContentHeight()) {
// Top section with titles
ChangeManagingEntityTopBar(
modifier = modifier,
managingEntity = managingEntity,
onDismiss = onDismiss,
)
// Main content to display eligible members
eligibleManagingEntities.forEachIndexed { _, item ->
BottomListItem(
modifier = modifier,
currentEligibleManagingEntity = item,
selectedEligibleManagingEntity = selectedEligibleManagingEntity,
enableButton = { isEnabled = it },
onEligibleManagingEntitySelection = onEligibleManagingEntitySelection,
)
}
Divider(color = DividerColor, thickness = 1.dp)
// Bottom section with actions
ChangeManagingEntityBottomBar(
modifier = modifier,
onDismiss = onDismiss,
isEnabled = isEnabled,
onSaveClick = onSaveClick,
selectedEligibleManagingEntity = selectedEligibleManagingEntity,
)
}
}
}
@Composable
private fun ChangeManagingEntityBottomBar(
modifier: Modifier,
onDismiss: () -> Unit,
isEnabled: Boolean,
onSaveClick: (EligibleManagingEntity) -> Unit,
selectedEligibleManagingEntity: EligibleManagingEntity?,
) {
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier =
modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.padding(horizontal = 16.dp, vertical = 16.dp),
) {
TextButton(
onClick = { onDismiss() },
modifier = modifier.fillMaxWidth().weight(1F).testTag(TEST_TAG_CANCEL),
) {
Text(
fontSize = 14.sp,
color = colorResource(id = org.smartregister.fhircore.engine.R.color.black),
text = stringResource(id = org.smartregister.fhircore.engine.R.string.cancel),
)
}
TextButton(
enabled = isEnabled,
onClick = {
selectedEligibleManagingEntity?.let { onSaveClick(it) }
onDismiss()
},
modifier = modifier.fillMaxWidth().weight(1F).testTag(TEST_TAG_SAVE),
colors =
ButtonDefaults.textButtonColors(
backgroundColor =
colorResource(
id =
if (isEnabled) {
org.smartregister.fhircore.engine.R.color.colorPrimary
} else {
org.smartregister.fhircore.engine.R.color.white
},
),
),
) {
Text(
fontSize = 14.sp,
color =
colorResource(
id =
if (isEnabled) {
org.smartregister.fhircore.engine.R.color.white
} else {
org.smartregister.fhircore.engine.R.color.colorPrimary
},
),
text = stringResource(id = org.smartregister.fhircore.engine.R.string.str_save).uppercase(),
)
}
}
}
@Composable
private fun ChangeManagingEntityTopBar(
modifier: Modifier,
managingEntity: ManagingEntityConfig?,
onDismiss: () -> Unit,
) {
Column(modifier = modifier.fillMaxWidth()) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier =
modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.padding(horizontal = 16.dp, vertical = 16.dp),
) {
Text(
text = managingEntity?.dialogTitle ?: "",
textAlign = TextAlign.Start,
fontWeight = FontWeight.Light,
fontSize = 20.sp,
)
Icon(
imageVector = Icons.Filled.Clear,
contentDescription = null,
tint = DefaultColor.copy(0.8f),
modifier = modifier.clickable { onDismiss() },
)
}
Divider()
Row(
verticalAlignment = Alignment.CenterVertically,
modifier =
modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.padding(horizontal = 12.dp, vertical = 18.dp)
.background(
color =
colorResource(id = org.smartregister.fhircore.engine.R.color.background_warning),
shape = RoundedCornerShape(8.dp),
),
) {
Image(
painter = painterResource(id = R.drawable.ic_alert_triangle),
contentDescription = null,
modifier = modifier.padding(horizontal = 12.dp),
)
Text(
text = managingEntity?.dialogWarningMessage ?: "",
textAlign = TextAlign.Start,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
modifier = modifier.padding(vertical = 12.dp),
)
}
Text(
text = managingEntity?.dialogContentMessage?.uppercase() ?: "",
modifier = modifier.padding(horizontal = 12.dp),
textAlign = TextAlign.Start,
fontWeight = FontWeight.Light,
fontSize = 16.sp,
)
}
}
@Composable
fun BottomListItem(
modifier: Modifier = Modifier,
currentEligibleManagingEntity: EligibleManagingEntity,
selectedEligibleManagingEntity: EligibleManagingEntity?,
onEligibleManagingEntitySelection: (EligibleManagingEntity) -> Unit,
enableButton: (Boolean) -> Unit,
) {
val onClick = remember {
{
onEligibleManagingEntitySelection(currentEligibleManagingEntity)
enableButton(true)
}
}
Row(
modifier = modifier.fillMaxWidth().clickable { onClick() },
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = currentEligibleManagingEntity == selectedEligibleManagingEntity,
onClick = onClick,
)
Text(
text = currentEligibleManagingEntity.memberInfo,
modifier = modifier.clickable { onClick() },
)
}
}
@PreviewWithBackgroundExcludeGenerated
@Composable
fun ChangeManagingEntityViewPreview() {
ChangeManagingEntityView(
onSaveClick = {},
eligibleManagingEntities =
listOf(
EligibleManagingEntity(
groupId = "group-1",
logicalId = "patient-1",
memberInfo = "Jane Doe",
),
EligibleManagingEntity(
groupId = "group-1",
logicalId = "patient-2",
memberInfo = "James Doe",
),
),
onDismiss = {},
managingEntity =
ManagingEntityConfig(
nameFhirPathExpression = "Patient.name",
eligibilityCriteriaFhirPathExpression = "Patient.active",
resourceType = ResourceType.Patient,
dialogTitle = "Assign new family head",
dialogWarningMessage =
"Please assign a new household head, family no longer has a household head",
dialogContentMessage = "Select a new family head",
),
)
}
| 192
| null |
56
| 56
|
64a55e6920cb6280cf02a0d68152d9c03266518d
| 10,298
|
fhircore
|
Apache License 2.0
|
node/src/main/kotlin/net/corda/node/services/transactions/ValidatingNotaryFlow.kt
|
tomtau
| 141,038,868
| false
| null |
package net.corda.node.services.transactions
import co.paralleluniverse.fibers.Suspendable
import net.corda.core.contracts.TimeWindow
import net.corda.core.contracts.TransactionVerificationException
import net.corda.core.flows.*
import net.corda.core.internal.ResolveTransactionsFlow
import net.corda.core.internal.validateRequestSignature
import net.corda.core.node.services.TrustedAuthorityNotaryService
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionWithSignatures
import net.corda.core.transactions.WireTransaction
import java.security.SignatureException
/**
* A notary commit flow that makes sure a given transaction is valid before committing it. This does mean that the calling
* party has to reveal the whole transaction history; however, we avoid complex conflict resolution logic where a party
* has its input states "blocked" by a transaction from another party, and needs to establish whether that transaction was
* indeed valid.
*/
class ValidatingNotaryFlow(otherSideSession: FlowSession, service: TrustedAuthorityNotaryService) : NotaryFlow.Service(otherSideSession, service) {
/**
* Fully resolves the received transaction and its dependencies, runs contract verification logic and checks that
* the transaction in question has all required signatures apart from the notary's.
*/
@Suspendable
override fun validateRequest(requestPayload: NotarisationPayload): TransactionParts {
try {
val stx = requestPayload.signedTransaction
validateRequestSignature(NotarisationRequest(stx.inputs, stx.id), requestPayload.requestSignature)
val notary = stx.notary
checkNotary(notary)
resolveAndContractVerify(stx)
verifySignatures(stx)
val timeWindow: TimeWindow? = if (stx.coreTransaction is WireTransaction) stx.tx.timeWindow else null
return TransactionParts(stx.id, stx.inputs, timeWindow, notary!!)
} catch (e: Exception) {
throw when (e) {
is TransactionVerificationException,
is SignatureException -> NotaryInternalException(NotaryError.TransactionInvalid(e))
else -> e
}
}
}
@Suspendable
private fun resolveAndContractVerify(stx: SignedTransaction) {
subFlow(ResolveTransactionsFlow(stx, otherSideSession))
stx.verify(serviceHub, false)
}
private fun verifySignatures(stx: SignedTransaction) {
val transactionWithSignatures = stx.resolveTransactionWithSignatures(serviceHub)
checkSignatures(transactionWithSignatures)
}
private fun checkSignatures(tx: TransactionWithSignatures) {
try {
tx.verifySignaturesExcept(service.notaryIdentityKey)
} catch (e: SignatureException) {
throw NotaryInternalException(NotaryError.TransactionInvalid(e))
}
}
}
| 1
| null |
1
| 1
|
f524ed9af7027004abfa91c0bd3a31d645ef0b3b
| 2,949
|
corda
|
Apache License 2.0
|
app/src/main/java/dev/zabolotskikh/authguard/domain/model/AppState.kt
|
kanefron5
| 635,099,229
| false
| null |
package dev.zabolotskikh.authguard.domain.model
data class AppState(
val isStarted: Boolean,
val isAuthenticated: Boolean,
val isPrivateMode: Boolean
)
| 2
|
Kotlin
|
0
| 0
|
3c4e206b6c24017599ebbab8c0fd99f5a1fa687a
| 165
|
authguard
|
MIT License
|
libtulip/src/jsMain/kotlin/com/tajmoti/multiplatform/store/TStoreFactory.kt
|
Tajmoti
| 391,138,914
| false
| null |
package com.tajmoti.multiplatform.store
import com.tajmoti.libtulip.TulipConfiguration
import com.tajmoti.libtulip.misc.job.NetworkResult
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
actual object TStoreFactory {
actual fun <Key : Any, Output : Any> createStore(
cache: TulipConfiguration.CacheParameters,
source: (Key) -> Flow<Result<Output>>,
reader: ((Key) -> Flow<Output?>)?,
writer: (suspend (Key, Output) -> Unit)?
): TStore<Key, Output> {
return object : TStore<Key, Output> {
override fun stream(key: Key): Flow<NetworkResult<Output>> {
return source(key).map(::toNetworkResult)
}
}
}
private fun <Output : Any> toNetworkResult(it: Result<Output>): NetworkResult<Output> {
return it.fold(
{ NetworkResult.Success(it) },
{ NetworkResult.Error(NetworkResult.ErrorType.CONVERSION_FAILED) }
)
}
}
| 6
|
Kotlin
|
0
| 0
|
3ead4965a4a6febbd7bbd4f66dc75958b3c68ca5
| 977
|
Tulip
|
MIT License
|
ui/common/src/main/java/ly/david/ui/common/place/PlaceListItem.kt
|
lydavid
| 458,021,427
| false
|
{"Kotlin": 1354694, "HTML": 674577, "Python": 3489, "Shell": 1543, "Ruby": 955}
|
package ly.david.ui.common.place
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ListItem
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.compose.ui.unit.dp
import ly.david.data.LifeSpan
import ly.david.data.common.ifNotNull
import ly.david.data.common.ifNotNullOrEmpty
import ly.david.data.domain.listitem.PlaceListItemModel
import ly.david.data.getLifeSpanForDisplay
import ly.david.ui.common.listitem.DisambiguationText
import ly.david.ui.common.preview.DefaultPreviews
import ly.david.ui.common.theme.PreviewTheme
import ly.david.ui.common.theme.TextStyles
@Composable
fun PlaceListItem(
place: PlaceListItemModel,
modifier: Modifier = Modifier,
onPlaceClick: PlaceListItemModel.() -> Unit = {}
) {
ListItem(
headlineContent = {
Column {
place.run {
Text(
text = name,
style = TextStyles.getCardBodyTextStyle()
)
DisambiguationText(disambiguation = disambiguation)
type.ifNotNullOrEmpty {
Text(
text = it,
modifier = Modifier.padding(top = 4.dp),
style = TextStyles.getCardBodySubTextStyle(),
)
}
address.ifNotNullOrEmpty {
Text(
modifier = Modifier.padding(top = 4.dp),
text = it,
style = TextStyles.getCardBodySubTextStyle(),
)
}
// TODO: too much information on list item?
// area.ifNotNull {
// Text(
// modifier = Modifier.padding(top = 4.dp),
// text = it.name,
// style = TextStyles.getCardBodyTextStyle(),
// )
// }
lifeSpan.ifNotNull {
Text(
modifier = Modifier.padding(top = 4.dp),
text = it.getLifeSpanForDisplay(),
style = TextStyles.getCardBodySubTextStyle(),
)
}
}
}
},
modifier = modifier.clickable { onPlaceClick(place) }
)
}
internal class PlacePreviewParameterProvider : PreviewParameterProvider<PlaceListItemModel> {
override val values = sequenceOf(
PlaceListItemModel(
id = "2",
name = "Place Name",
address = "123 Fake St"
),
PlaceListItemModel(
id = "ed121457-87f6-4df9-a24b-d3f1bab1fdad",
name = "Sony Music Studios",
disambiguation = "NYC, closed 2007",
type = "Studio",
address = "460 W. 54th St., at 10th Avenue, Manhatten, NY",
lifeSpan = LifeSpan(begin = "1993", end = "2007-08", ended = true)
),
PlaceListItemModel(
id = "4d43b9d8-162d-4ac5-8068-dfb009722484",
name = "日本武道館",
type = "Indoor arena",
address = "〒102-8321 東京都千代田区北の丸公園2-3",
lifeSpan = LifeSpan(begin = "1964-10-03")
),
)
}
@DefaultPreviews
@Composable
private fun Preview(
@PreviewParameter(PlacePreviewParameterProvider::class) place: PlaceListItemModel
) {
PreviewTheme {
Surface {
PlaceListItem(place)
}
}
}
| 54
|
Kotlin
|
0
| 6
|
5e15119a3c55efa932e37afced1b56609e988fe6
| 3,950
|
MusicSearch
|
Apache License 2.0
|
plugins/git4idea/src/git4idea/branch/GitCompareBranchesVirtualFileSystem.kt
|
hieuprogrammer
| 284,920,751
| true
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.branch
import com.google.gson.*
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.vcs.editor.ComplexPathVirtualFileSystem
import com.intellij.vcs.log.VcsLogRangeFilter
import java.lang.reflect.Type
internal class GitCompareBranchesVirtualFileSystem : ComplexPathVirtualFileSystem<GitCompareBranchesVirtualFileSystem.Path>() {
override val pathClass: Class<Path> = Path::class.java
override val gson: Gson = GsonBuilder().registerTypeAdapter(VirtualFile::class.java, VirtualFileSerializer()).create()
override fun getProtocol(): String = PROTOCOL
override fun findFile(project: Project, path: Path): VirtualFile? {
return GitCompareBranchesFilesManager.getInstance(project).findFile(path)
}
data class Path(override val sessionId: String,
override val projectHash: String,
val ranges: List<VcsLogRangeFilter.RefRange>,
val root: Collection<VirtualFile>?) : ComplexPathVirtualFileSystem.Path
companion object {
private const val PROTOCOL = "git-compare-branches"
@JvmStatic
fun getInstance() = service<VirtualFileManager>().getFileSystem(PROTOCOL) as GitCompareBranchesVirtualFileSystem
}
}
private class VirtualFileSerializer : JsonSerializer<VirtualFile>, JsonDeserializer<VirtualFile> {
override fun serialize(src: VirtualFile, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
return JsonObject().also { it.addProperty(pathProperty, src.path) }
}
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): VirtualFile {
val path = json.asJsonObject.get(pathProperty).asString
return LocalFileSystem.getInstance().findFileByPath(path) ?: throw JsonParseException("Could not find file by $path")
}
companion object {
private const val pathProperty = "path"
}
}
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 2,201
|
intellij-community
|
Apache License 2.0
|
src/main/kotlin/org/gradle/plugins/fsm/descriptor/WebAppComponents.kt
|
e-Spirit
| 579,945,778
| false
|
{"Kotlin": 318290, "Java": 19302}
|
package org.gradle.plugins.fsm.descriptor
import com.espirit.moddev.components.annotations.WebAppComponent
import de.espirit.firstspirit.module.AbstractWebApp
import de.espirit.firstspirit.module.Configuration
import de.espirit.firstspirit.module.WebApp
import io.github.classgraph.AnnotationInfo
import io.github.classgraph.ClassInfo
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.artifacts.ResolvedArtifact
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import org.gradle.api.plugins.JavaPlugin
import org.gradle.plugins.fsm.DeclaredWebAppChecker
import org.gradle.plugins.fsm.FSMPluginExtension
import org.gradle.plugins.fsm.configurations.FSMConfigurationsPlugin
import org.redundent.kotlin.xml.Node
import org.redundent.kotlin.xml.xml
import java.io.File
import java.util.*
class WebAppComponents(project: Project, private val scanResult: ComponentScan): ComponentsWithResources(project) {
lateinit var webXmlPaths: List<String>
val nodes by lazy {
val webAppClasses = scanResult.getClassesWithAnnotation(WebAppComponent::class)
verify(webAppClasses)
nodesForWebApp(webAppClasses)
}
private fun verify(webAppClasses: List<ClassInfo>) {
val webAppChecker = DeclaredWebAppChecker(project, webAppClasses)
val declaredWebApps = project.extensions.getByType(FSMPluginExtension::class.java).getWebApps()
// Check if web-apps are complete
// Warn if there is a @WebAppComponent annotation not defined in the `firstSpiritModule` block
val undeclaredWebAppComponents = webAppChecker.webAppAnnotationsWithoutDeclaration
if (declaredWebApps.isNotEmpty() && !undeclaredWebAppComponents.isNullOrEmpty()) {
val warningStringBuilder = StringBuilder()
warningStringBuilder.append("@WebAppComponent annotations found that are not registered in the firstSpiritModule configuration block:\n")
undeclaredWebAppComponents.forEach {
val displayName = it.getStringOrNull("displayName", "")?.let { name -> " ($name)" } ?: ""
warningStringBuilder.append("- ${it.getString("name")}${displayName}\n")
}
LOGGER.warn(warningStringBuilder.toString())
}
// ... or if there is a web-app defined in the `firstSpiritModule` block we cannot find a @WebAppComponent annotation for, throw an error
val declaredWebAppNames = webAppChecker.declaredProjectsWithoutAnnotation
if (!declaredWebAppNames.isNullOrEmpty()) {
val errorStringBuilder = StringBuilder()
errorStringBuilder.append("No @WebAppComponent annotation found for the following web-apps registered in the firstSpiritModule configuration block:\n")
declaredWebAppNames.forEach {
errorStringBuilder.append("- ${it}\n")
}
throw GradleException(errorStringBuilder.toString())
}
}
private fun nodesForWebApp(webAppClasses: List<ClassInfo>): List<Node> {
// We might find the same dependencies in different subprojects / configurations, but with different versions
// Because only one version ends up in the FSM archive, we need to make sure we always use the correct version
val allCompileDependencies = project.configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)
.resolvedConfiguration.resolvedArtifacts
val sharedWebCompileDependencies = getResolvedDependencies(project,
FSMConfigurationsPlugin.FS_WEB_COMPILE_CONFIGURATION_NAME, allCompileDependencies)
val webXmlPaths = mutableListOf<String>()
val extension = project.extensions.getByType(FSMPluginExtension::class.java)
val declaredWebApps = extension.getWebApps()
val nodes = mutableListOf<Node>()
webAppClasses.forEach { webAppClass ->
// Report if WebApp does not seem to implement WebApp or AbstractWebApp
if (webAppClass.superclass?.name !in WEB_APP_TYPES) {
LOGGER.info("Web App '${webAppClass.name}' does not appear to implement interface '${WebApp::class.qualifiedName}'.")
LOGGER.info("This might be because the class implements or extends an intermediary type inheriting from ${WebApp::class.simpleName}.")
}
val annotation = webAppClass.annotationInfo
.filter { it.isClass(WebAppComponent::class) }
.first()
val webCompileConfiguration = project.configurations.getByName(FSMConfigurationsPlugin.FS_WEB_COMPILE_CONFIGURATION_NAME)
val projectDependencies = webCompileConfiguration.allDependencies.withType(ProjectDependency::class.java)
val webResources = mutableListOf<Node>()
// fsm-resources directory of root project and fsWebCompile subprojects (shared between all webapps)
webResources.addAll(projectDependencies
.map(ProjectDependency::getDependencyProject)
.flatMap(this::fsmResources)
)
val webAppName = annotation.getString("name")
if (declaredWebApps.containsKey(webAppName)) {
val webAppProject = declaredWebApps[webAppName]!!
// fsm-resources directory of current web-app
// - safety check to avoid duplicates
if (!projectDependencies.map(ProjectDependency::getDependencyProject).contains(webAppProject)) {
webResources.addAll(fsmResources(webAppProject))
}
// compile dependencies of web-app subproject -
// If we registered a subproject for a given web-app, evaluate its compile dependencies
val webAppProjectDependencies = getResolvedDependencies(webAppProject, JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME, allCompileDependencies)
// Don't want duplicate resources
webAppProjectDependencies.removeAll(sharedWebCompileDependencies)
val jarFile = webAppProject.buildJar()
if (!jarFile.exists()) {
Resources.LOGGER.warn("Jar file '$jarFile' not found!")
} else if (Resources.isEmptyJarFile(jarFile)) {
Resources.LOGGER.info("Skipping empty Jar file.")
} else {
webResources.add(xml("resource") {
attribute("name", "${webAppProject.group}:${webAppProject.name}")
attribute("version", webAppProject.version)
-"lib/${jarFile.name}"
})
}
// Add dependencies
webAppProjectDependencies
.map { Resource(project, it, "", false).node }
.forEach(webResources::add)
}
// fsWebCompile for all subprojects
sharedWebCompileDependencies
.map { Resource(project, it, "", false).node }
.forEach(webResources::add)
val webXmlPath = annotation.getString("webXml")
webXmlPaths.add(webXmlPath)
nodes.add(xml("web-app") {
val scopes = annotation.getEnumValues("scope")
if (scopes.isNotEmpty()) {
attribute("scopes", scopes.joinToString(",") { it.valueName })
}
val xmlSchemaVersion = annotation.getString("xmlSchemaVersion")
if (xmlSchemaVersion.isNotEmpty()) {
attribute("xml-schema-version", xmlSchemaVersion)
}
"name" { -webAppName }
"displayname" { -annotation.getString("displayName") }
"description" { -annotation.getString("description") }
"class" { -webAppClass.name }
annotation.getClassNameOrNull("configurable", Configuration::class)?.let { "configurable" { -it } }
"web-xml" { -webXmlPath }
"web-resources" {
val jarFile = project.buildJar()
if (extension.addDefaultJarTaskOutputToWebResources && !Resources.isEmptyJarFile(jarFile)) {
"resource" {
attribute("name", "${project.group}:${project.name}")
attribute("version", project.version)
-"lib/${jarFile.name}"
}
}
nodesForWebResources(annotation).forEach(this::addElement)
webResources.forEach(this::addElement)
}
if (annotation.getString("hidden").toBoolean()) {
"hidden" { -"true" }
}
})
}
this.webXmlPaths = webXmlPaths
return nodes
}
/**
* Finds all dependencies of a given configuration and finds the global version of each dependency
*
* @param project The project
* @param configurationName The configuration to fetch the dependencies for
* @param allDependencies All dependencies of the project, with the correct version
* @return The dependencies of `configurationName`, with the correct version
*/
private fun getResolvedDependencies(project: Project, configurationName: String, allDependencies: Set<ResolvedArtifact>): MutableSet<ResolvedArtifact> {
val configuration = project.configurations.findByName(configurationName) ?: return Collections.emptySet()
val resolvedArtifacts = configuration.resolvedConfiguration.resolvedArtifacts
return allDependencies.filter { resource ->
resolvedArtifacts.any { it.hasSameModuleAs(resource) }
}.toMutableSet()
}
private fun fsmResources(project: Project): List<Node> {
val fsmWebResourcesPath = project.projectDir.resolve(FSMConfigurationsPlugin.FSM_RESOURCES_PATH).absolutePath
val fsmWebResourcesFolder = File(fsmWebResourcesPath)
return if (fsmWebResourcesFolder.exists()) {
fsmWebResourcesFolder.listFiles()?.map { file ->
val relPath = fsmWebResourcesFolder.toPath().relativize(file.toPath())
xml("resource") {
attribute("name", relPath)
attribute("version", project.version)
-relPath.toString()
}
}.orEmpty()
} else {
emptyList()
}
}
private fun nodesForWebResources(annotation: AnnotationInfo): List<Node> {
val resources = annotation.getAnnotationValues("webResources")
val nodes = mutableListOf<Node>()
resources.forEach { resource ->
val nameFromAnnotation = expand(resource.getString("name"), mutableMapOf("project" to project))
val dependencyForName = getCompileDependencyForName(nameFromAnnotation)
val context = getContextForCurrentResource(dependencyForName)
val versionFromAnnotation = expandVersion(resource.getString("version"), context, nameFromAnnotation, annotation.getString("name"))
val pathFromAnnotation = expand(resource.getString("path"), context)
nodes.add(xml("resource") {
attribute("name", nameFromAnnotation)
attribute("version", versionFromAnnotation)
resource.getStringOrNull("minVersion", "")?.let { attribute("minVersion", it) }
resource.getStringOrNull("maxVersion", "")?.let { attribute("maxVersion", it) }
resource.getStringOrNull("targetPath", "")?.let { attribute("target", it) }
-pathFromAnnotation
})
}
return nodes
}
companion object {
private val LOGGER: Logger = Logging.getLogger(WebAppComponents::class.java)
private val WEB_APP_TYPES = setOf(
WebApp::class.qualifiedName,
AbstractWebApp::class.qualifiedName
)
}
}
| 0
|
Kotlin
|
0
| 0
|
fb04820e6514d7e173d6a48e13d44b8a5a505959
| 12,147
|
firstspirit-module-gradle-plugin
|
Apache License 2.0
|
app/src/main/java/com/hadiyarajesh/marvel_heroes/data/local/dao/ComicCharacterDao.kt
|
hadiyarajesh
| 748,514,337
| false
| null |
package com.demo.marvel_heroes.data.local.dao
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Upsert
import com.demo.marvel_heroes.data.local.entity.ComicCharacterEntity
import com.demo.marvel_heroes.data.model.CharacterAndComics
@Dao
interface ComicCharacterDao {
@Upsert
suspend fun upsertCharacter(comicCharacter: ComicCharacterEntity)
@Upsert
suspend fun upsertCharacters(comicCharacter: List<ComicCharacterEntity>)
@Query("SELECT * FROM ComicCharacter ORDER BY id ASC")
fun getAllCharacters(): PagingSource<Int, ComicCharacterEntity>
@Query("SELECT * FROM ComicCharacter WHERE characterId IN (:characterIds)")
suspend fun getAllCharactersByIdIn(characterIds: List<Int>): List<ComicCharacterEntity>
@Query("SELECT * FROM ComicCharacter WHERE characterId = :id")
suspend fun getComicCharacter(id: Int): ComicCharacterEntity?
@Delete
suspend fun deleteCharacter(comicCharacter: ComicCharacterEntity)
@Query("DELETE FROM ComicCharacter")
suspend fun deleteAllCharacters()
@Query("SELECT * FROM ComicCharacter WHERE characterId = :characterId")
suspend fun getCharacterAndComic(characterId: Int): CharacterAndComics?
@Query("SELECT * FROM ComicCharacter WHERE name LIKE '%' || :characterName || '%'")
suspend fun searchCharacters(characterName: String): List<ComicCharacterEntity>
}
| 0
| null |
0
| 8
|
cd7da79d3b567eff5c66dc3a701a9015cf90bd04
| 1,454
|
marvel-heroes
|
MIT License
|
src/main/kotlin/org/wahlen/spasecurity/dto/UserRegisterDTO.kt
|
owahlen
| 712,925,882
| false
|
{"Kotlin": 62172}
|
package org.wahlen.spasecurity.dto
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Size
data class UserRegisterDTO(
@Schema(example = "<EMAIL>")
@field:NotBlank
@field:Size(max = 256)
@field:Email
val email: String? = null,
@Schema(example = "John")
@field:NotBlank
@field:Size(max = 100)
val firstName: String? = null,
@Schema(example = "Doe")
@field:NotBlank
@field:Size(max = 100)
val lastName: String? = null,
@Schema(example = "<PASSWORD>")
@field:NotBlank
@field:Size(min=4, max = 256)
val password: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
40f965547c0b9350cd9890052ef3348b52ec8fc8
| 728
|
spa-security
|
Apache License 2.0
|
ModuleBase/src/main/java/simple/code/base/ui/BaseTabContainerFragment.kt
|
Danil4ever
| 217,051,577
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "XML": 33, "Kotlin": 60, "Java": 2, "Proguard": 1}
|
package simple.code.base.ui
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import ru.terrakok.cicerone.Cicerone
import ru.terrakok.cicerone.Navigator
import ru.terrakok.cicerone.Router
import ru.terrakok.cicerone.Screen
import ru.terrakok.cicerone.android.support.SupportAppNavigator
import simple.code.base.R
import simple.code.base.navigation.BackButtonListener
import simple.code.base.navigation.LocalCiceroneHolder
import simple.code.base.navigation.RouterProvider
abstract class BaseTabContainerFragment : Fragment(), RouterProvider,
BackButtonListener {
private var navigator: Navigator? = null
protected abstract val mainScreen: Screen
private var ciceroneHolder = LocalCiceroneHolder
private val cicerone: Cicerone<Router>
get() = ciceroneHolder.getCicerone(this::class.java.simpleName)
private fun getNavigator(): Navigator {
if (navigator == null) {
navigator = SupportAppNavigator(activity, childFragmentManager, R.id.ftc_container)
}
return navigator!!
}
override fun getRouter(): Router {
return cicerone.router
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_tab_container, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onShow()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (childFragmentManager.findFragmentById(R.id.ftc_container) == null) {
cicerone.router.replaceScreen(mainScreen)
}
}
open fun onShow() {
for (f in childFragmentManager.fragments) {
if (f.isVisible && f is BaseMvpFragment<*>) {
f.onShow()
break
}
}
}
override fun onResume() {
cicerone.navigatorHolder.setNavigator(getNavigator())
super.onResume()
}
override fun onPause() {
cicerone.navigatorHolder.removeNavigator()
super.onPause()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
for (fragment in childFragmentManager.fragments) {
if (fragment.isVisible) fragment.onActivityResult(requestCode, resultCode, data)
}
}
override fun onBackPressed(): Boolean {
val fm = childFragmentManager
var fragment: Fragment? = null
val fragments = fm.fragments
for (f in fragments) {
if (f.isVisible) {
fragment = f
break
}
}
if (fragment != null
&& fragment is BackButtonListener
&& (fragment as BackButtonListener).onBackPressed()) {
return true
}
if (childFragmentManager.backStackEntryCount > 0) {
router.exit()
return true
}
return false
}
}
| 0
|
Kotlin
|
0
| 1
|
d1925923043cfe7f9df94145b40811fae0dde8d2
| 3,281
|
SampleProject
|
The Unlicense
|
vocadb-apiclient-fixer/src/main/kotlin/mikufan/cx/vocadbapiclientfixer/VocaDbApiClientFixerApplication.kt
|
CXwudi
| 368,331,904
| false
|
{"Git Config": 1, "OASv3-json": 1, "Text": 2, "Ignore List": 3, "Markdown": 170, "Shell": 4, "Gradle": 2, "INI": 4, "Batchfile": 2, "YAML": 6, "Java": 344, "XML": 2, "OASv3-yaml": 1, "Maven POM": 1, "Kotlin": 15}
|
package mikufan.cx.vocadbapiclientfixer
import mikufan.cx.vocadbapiclientfixer.service.MainService
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
@SpringBootApplication
@ConfigurationPropertiesScan
class VocaDbApiClientFixerApplication
fun main(args: Array<String>) {
val context = runApplication<VocaDbApiClientFixerApplication>(*args)
context.getBean(MainService::class.java).run()
}
| 0
|
Java
|
0
| 0
|
605a2e74e8444f5ca3f2c12b5fc98e965cd1a973
| 540
|
vocadb-openapi-java-client-autofixer
|
Do What The F*ck You Want To Public License
|
src/main/kotlin/com/mystery2099/wooden_accents_mod/block/custom/enums/CoffeeTableTypes.kt
|
Mystery2099
| 661,436,370
| false
|
{"Kotlin": 284868, "Java": 16936}
|
package com.mystery2099.wooden_accents_mod.block.custom.enums
import net.minecraft.util.StringIdentifiable
/**
* Coffee table types
*
* @property string
* @constructor Create empty Coffee table types
*/
enum class CoffeeTableTypes(private val string: String) : StringIdentifiable {
/**
* Short
*
* @constructor Create empty Short
*/
SHORT("short"),
/**
* Tall
*
* @constructor Create empty Tall
*/
TALL("tall");
override fun asString() = string
companion object {
//To be used for things like NBT
const val TAG = "coffee_table_type"
}
}
| 0
|
Kotlin
|
0
| 0
|
cbaadec822bd9bf876387663d5d4f502e9a2db87
| 633
|
WoodenAccentsMod-1.19.4
|
Creative Commons Zero v1.0 Universal
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/SetSharedFunction.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: SetSharedFunction
*
* Full name: System`SetSharedFunction
*
* SetSharedFunction[f , f , …] declares the symbols f as shared functions whose downvalues are synchronized among all parallel kernels.
* Usage: 1 2 i
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/SetSharedFunction
* Documentation: web: http://reference.wolfram.com/language/ref/SetSharedFunction.html
*
* SetSharedFunction[{___, Parallel`VirtualShared`Private`s_Symbol, ___}] /; MemberQ[Attributes[Parallel`VirtualShared`Private`s], Locked] || MemberQ[Attributes[Parallel`VirtualShared`Private`s], ReadProtected] || MemberQ[Parallel`VirtualShared`Private`$badsyms, Unevaluated[Parallel`VirtualShared`Private`s]] := (Message[SetSharedFunction::badsym, HoldForm[Parallel`VirtualShared`Private`s]]; )
* SetSharedFunction[Parallel`VirtualShared`Private`l:{Parallel`VirtualShared`Private`s___Symbol}] := Catch[With[{Parallel`VirtualShared`Private`varDefs = Join @@ Parallel`VirtualShared`Private`downDef /@ Parallel`VirtualShared`Private`l}, Parallel`Protected`AddInitCode[Parallel`VirtualShared`Private`varDefs]; Parallel`VirtualShared`Private`$sharedDownValues = Union[Parallel`VirtualShared`Private`$sharedDownValues, Hold[Parallel`VirtualShared`Private`s]]; Parallel`Protected`removeDistributedSymbol[Parallel`VirtualShared`Private`s]; Parallel`VirtualShared`Private`checkSharing; ], Parallel`VirtualShared`Private`badsym]
* Definitions: SetSharedFunction[Parallel`VirtualShared`Private`s___Symbol] := SetSharedFunction[{Parallel`VirtualShared`Private`s}]
*
* Own values: None
*
* SetSharedFunction[{___, Parallel`VirtualShared`Private`s_Symbol, ___}] /; MemberQ[Attributes[Parallel`VirtualShared`Private`s], Locked] || MemberQ[Attributes[Parallel`VirtualShared`Private`s], ReadProtected] || MemberQ[Parallel`VirtualShared`Private`$badsyms, Unevaluated[Parallel`VirtualShared`Private`s]] := (Message[SetSharedFunction::badsym, HoldForm[Parallel`VirtualShared`Private`s]]; )
* SetSharedFunction[Parallel`VirtualShared`Private`l:{Parallel`VirtualShared`Private`s___Symbol}] := Catch[With[{Parallel`VirtualShared`Private`varDefs = Join @@ Parallel`VirtualShared`Private`downDef /@ Parallel`VirtualShared`Private`l}, Parallel`Protected`AddInitCode[Parallel`VirtualShared`Private`varDefs]; Parallel`VirtualShared`Private`$sharedDownValues = Union[Parallel`VirtualShared`Private`$sharedDownValues, Hold[Parallel`VirtualShared`Private`s]]; Parallel`Protected`removeDistributedSymbol[Parallel`VirtualShared`Private`s]; Parallel`VirtualShared`Private`checkSharing; ], Parallel`VirtualShared`Private`badsym]
* Down values: SetSharedFunction[Parallel`VirtualShared`Private`s___Symbol] := SetSharedFunction[{Parallel`VirtualShared`Private`s}]
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun setSharedFunction(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("SetSharedFunction", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 3,473
|
mathemagika
|
Apache License 2.0
|
modelql-core/src/commonMain/kotlin/org/modelix/modelql/core/CountingStep.kt
|
modelix
| 533,211,353
| false
|
{"Kotlin": 2236130, "JetBrains MPS": 274458, "TypeScript": 47718, "Java": 25036, "Gherkin": 7693, "JavaScript": 5004, "Mustache": 2915, "CSS": 2812, "Shell": 2420, "Dockerfile": 378, "Procfile": 76}
|
/*
* 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.modelix.modelql.core
import kotlinx.coroutines.flow.count
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.serializer
class CountingStep() : AggregationStep<Any?, Int>() {
override suspend fun aggregate(input: StepFlow<Any?>): IStepOutput<Int> {
return input.count().asStepOutput(this)
}
override fun createDescriptor(context: QueryGraphDescriptorBuilder) = CountDescriptor()
@Serializable
@SerialName("count")
class CountDescriptor() : CoreStepDescriptor() {
override fun createStep(context: QueryDeserializationContext): IStep {
return CountingStep()
}
}
override fun getOutputSerializer(serializationContext: SerializationContext): KSerializer<out IStepOutput<Int>> {
return serializationContext.serializer<Int>().stepOutputSerializer(this)
}
override fun toString(): String {
return "${getProducers().single()}.count()"
}
}
fun IFluxStep<*>.count(): IMonoStep<Int> = CountingStep().also { connect(it) }
| 49
|
Kotlin
|
9
| 6
|
48aa04bf386063b4093424166a263cee7cc69983
| 1,683
|
modelix.core
|
Apache License 2.0
|
sdk/sync/sync-android-java/src/commonMain/kotlin/com/twilio/sync/client/java/utils/CancellationTokenImpl.kt
|
twilio
| 790,341,870
| false
|
{"Kotlin": 1150573, "Swift": 178357, "Python": 44263, "Java": 35577, "TypeScript": 26195, "Shell": 21097, "Rust": 5989, "Ruby": 4047, "Makefile": 1384, "Just": 734, "HTML": 533, "Objective-C": 462, "CSS": 331}
|
//
// Twilio Sync Client
//
// Copyright © Twilio, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
package com.twilio.sync.client.java.utils
internal fun CancellationToken(onCancel: () -> Unit): CancellationToken = CancellationTokenImpl(onCancel)
private class CancellationTokenImpl(private val onCancel: () -> Unit) : CancellationToken {
override fun cancel() = onCancel()
}
| 0
|
Kotlin
|
1
| 4
|
ac345352614263f7559cba66362bfe008155a3b0
| 403
|
twilio-sync-sdk
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.