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
Client/app/src/main/java/com/t3ddyss/clother/domain/chat/ChatInteractor.kt
t3ddyss
337,083,750
false
{"Kotlin": 343621, "Python": 38739, "Jupyter Notebook": 22857, "HTML": 11031, "Dockerfile": 439, "Shell": 405}
package com.t3ddyss.clother.domain.chat import android.net.Uri import arrow.core.Either import com.t3ddyss.clother.domain.chat.models.ChatsState import com.t3ddyss.clother.domain.chat.models.CloudEvent import com.t3ddyss.clother.domain.chat.models.Message import com.t3ddyss.clother.domain.common.common.models.LoadResult import com.t3ddyss.core.domain.models.ApiCallError import kotlinx.coroutines.flow.Flow interface ChatInteractor { fun initialize() fun observeChats(): Flow<ChatsState> fun observeMessagesForChat(interlocutorId: Int): Flow<List<Message>> suspend fun fetchNextPortionOfMessagesForChat(interlocutorId: Int): LoadResult suspend fun sendMessage(body: String?, image: Uri?, interlocutorId: Int) suspend fun retryToSendMessage(messageLocalId: Int) suspend fun deleteMessage(messageLocalId: Int): Either<ApiCallError, Unit> fun onNewToken(token: String) fun onNewCloudEvent(cloudEvent: CloudEvent) }
0
Kotlin
1
23
d18048ac5b354d3c499003ef73afd088c9076e19
951
Clother
MIT License
app/src/main/java/com/wuyr/jdwp_injector_test/activity/MainActivity.kt
wuyr
752,326,309
false
{"Kotlin": 109812, "C++": 3346, "C": 475, "CMake": 229}
package com.wuyr.jdwp_injector_test.activity import android.content.ComponentName import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.provider.Settings import android.view.View import android.widget.Toast import com.wuyr.jdwp_injector.adb.AdbClient import com.wuyr.jdwp_injector.adb.AdbWirelessPairing import com.wuyr.jdwp_injector.adb.AdbWirelessPortResolver import com.wuyr.jdwp_injector.adb.AdbWirelessPortResolver.Companion.resolveAdbPairingPort import com.wuyr.jdwp_injector.adb.AdbWirelessPortResolver.Companion.resolveAdbTcpConnectPort import com.wuyr.jdwp_injector.adb.AdbWirelessPortResolver.Companion.resolveAdbWirelessConnectPort import com.wuyr.jdwp_injector.debugger.JdwpInjector import com.wuyr.jdwp_injector.exception.AdbCommunicationException import com.wuyr.jdwp_injector.exception.ProcessNotFoundException import com.wuyr.jdwp_injector_test.BuildConfig import com.wuyr.jdwp_injector_test.Drug import com.wuyr.jdwp_injector_test.R import com.wuyr.jdwp_injector_test.adapter.AppItem import com.wuyr.jdwp_injector_test.adapter.AppListAdapter import com.wuyr.jdwp_injector_test.databinding.ActivityMainBinding import com.wuyr.jdwp_injector_test.log.logE import java.net.SocketTimeoutException import java.util.concurrent.Executors import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.thread /** * @author wuyr * @github https://github.com/wuyr/jdwp-injector-for-android * @since 2024-04-13 3:33 PM */ class MainActivity(override val viewBindingClass: Class<ActivityMainBinding> = ActivityMainBinding::class.java) : BaseActivity<ActivityMainBinding>() { private var tcpConnectPortResolver: AdbWirelessPortResolver? = null private var wirelessConnectPortResolver: AdbWirelessPortResolver? = null private var wirelessPairingPortResolver: AdbWirelessPortResolver? = null private val handle = Handler(Looper.getMainLooper()) private var globalDebuggable = false private var connectHost = "" private var connectPort = 0 private var pairingHost = "" private var pairingPort = 0 override fun onCreate() { binding.apply { connectButton.setOnClickListener { tryConnect() } performPairingButton.setOnClickListener { doPairing() } } } private fun tryConnect() { if (Settings.Global.getInt(contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, if (Build.TYPE == "eng") 1 else 0) == 0) { Toast.makeText(this, R.string.development_settings_has_been_disabled_please_reopen_it, Toast.LENGTH_LONG).show() startActivity(Intent(Settings.ACTION_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) return } setupConnectPortResolver() handle.removeCallbacks(resolveTimeoutTask) handle.postDelayed(resolveTimeoutTask, 2000L) } private fun setupConnectPortResolver() { tcpConnectPortResolver?.stop() tcpConnectPortResolver = resolveAdbTcpConnectPort { host, port -> onConnectPortDetected(host, port) } wirelessConnectPortResolver?.stop() wirelessConnectPortResolver = resolveAdbWirelessConnectPort(onLost = { handle.removeCallbacks(resolveTimeoutTask) runOnUiThread { Toast.makeText(this, R.string.wireless_debugging_not_available, Toast.LENGTH_LONG).show() } }) { host, port -> onConnectPortDetected(host, port) } } private val resolveTimeoutTask = Runnable { Toast.makeText(this, R.string.wireless_debugging_not_available_have_you_opened_it, Toast.LENGTH_LONG).show() goToDevelopmentSettings(false) } private val connectFailedTask = Runnable { goToDevelopmentSettings(handshakeFailed) } private var handshakeFailed = false private var triedConnectPort = HashSet<Int>() private var connected = false private fun onConnectPortDetected(host: String, port: Int) { if (connected) return if (!triedConnectPort.add(port)) return handle.removeCallbacks(resolveTimeoutTask) handle.removeCallbacks(connectFailedTask) runCatching { if (AdbClient.openShell(host, port).use { it.sendShellCommand("getprop ro.debuggable") }.also { response -> globalDebuggable = response.split("\r\n").filterNot { it.isEmpty() }.run { if (size > 1) this[1] else "" } == "1" }.isNotEmpty()) { connected = true handle.removeCallbacks(connectFailedTask) stopPortResolver() connectHost = host connectPort = port runOnUiThread { loadDebuggableAppList() } } }.onFailure { handle.removeCallbacks(connectFailedTask) handle.postDelayed(connectFailedTask, 1000L) handshakeFailed = it is SSLHandshakeException } } private fun doPairing() { thread { val pairingCode = binding.pairingCodeView.text.toString() if (pairingCode.isEmpty()) { return@thread } runCatching { AdbWirelessPairing(pairingHost, pairingPort, pairingCode).use { it.start() runOnUiThread { binding.apply { connectHintView.setText(R.string.wireless_debugging_pairing_successful) pairingCodeView.visibility = View.GONE performPairingButton.visibility = View.GONE } } triedConnectPort.clear() tryConnect() } }.onFailure { it.stackTraceToString().logE() runOnUiThread { binding.apply { connectHintView.setText(R.string.entered_an_incorrect_pairing_code) pairingCodeView.setText("") } } } } } private var developmentSettingsStarted = false private fun goToDevelopmentSettings(pairingNeeded: Boolean) { binding.apply { connectButton.visibility = View.GONE wirelessPairingRoot.visibility = View.VISIBLE if (pairingNeeded) { setupPairingPortResolver() } else { connectHintView.setText(R.string.please_open_the_wireless_debugging) } } if (developmentSettingsStarted) return developmentSettingsStarted = true startActivity(runCatching { Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) }.getOrDefault(Intent(Settings.ACTION_SETTINGS)).apply { flags = Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }, Bundle().apply { putInt("android.activity.windowingMode", 3) }) } private fun setupPairingPortResolver() { binding.apply { connectHintView.setText(R.string.please_show_the_pairing_code) wirelessPairingPortResolver?.stop() wirelessPairingPortResolver = resolveAdbPairingPort(onLost = { runOnUiThread { connectHintView.setText(R.string.the_pairing_code_has_been_closed_please_reopen_it) pairingCodeView.visibility = View.GONE performPairingButton.visibility = View.GONE } }) { host, port -> pairingHost = host pairingPort = port runOnUiThread { connectHintView.setText(R.string.please_enter_pairing_code) pairingCodeView.visibility = View.VISIBLE performPairingButton.visibility = View.VISIBLE } } } } private lateinit var adapter: AppListAdapter private val threadPool = Executors.newSingleThreadExecutor() private fun loadDebuggableAppList() { binding.connectButton.visibility = View.GONE binding.wirelessPairingRoot.visibility = View.GONE binding.appList.visibility = View.VISIBLE binding.appList.adapter = AppListAdapter(this).apply { adapter = this onOpenButtonClick = { item -> openApplication(item.packageName, item.activityClassName) } onShowDialogButtonClick = { item -> doInject(item.packageName, "showDialog") } onShowToastButtonClick = { item -> doInject(item.packageName, "showToast") } } loadList() } private fun loadList() { adapter.items = packageManager.queryIntentActivities( Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), PackageManager.GET_META_DATA ).mapNotNull { resolveInfo -> val applicationInfo = (resolveInfo.activityInfo ?: resolveInfo.serviceInfo ?: resolveInfo.providerInfo)?.applicationInfo if (applicationInfo != null && applicationInfo.packageName != BuildConfig.APPLICATION_ID && (globalDebuggable || (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0) ) { AppItem( resolveInfo.loadIcon(packageManager).apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) }, "${resolveInfo.loadLabel(packageManager)}\n(${resolveInfo.activityInfo.packageName})", resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name ) } else null }.sortedBy { it.appName }.toMutableList() } private fun openApplication(packageName: String, activityClassName: String) { threadPool.execute { runCatching { AdbClient.openShell(connectHost, connectPort).use { adb -> adb.sendShellCommand("am force-stop $packageName") Thread.sleep(250) startActivity(Intent().apply { component = ComponentName(packageName, activityClassName) flags = Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }, Bundle().apply { putInt("android.activity.windowingMode", 3) }) } } } } private fun doInject(packageName: String, injectMethodName: String) { threadPool.execute { runCatching { JdwpInjector.start(connectHost, connectPort, packageName, packageName, packageResourcePath, Drug::class.java.name, injectMethodName) }.onFailure { val message = getString( when (it) { is ProcessNotFoundException -> R.string.target_process_not_found_please_open_it_first is SocketTimeoutException -> R.string.time_out_to_connect_to_target_process is AdbCommunicationException -> R.string.adb_communication_failure else -> { it.stackTraceToString().logE() R.string.unknown_error } } ) runOnUiThread { Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show() } } } } override fun onDestroy() { super.onDestroy() stopPortResolver() } private fun stopPortResolver() { tcpConnectPortResolver?.stop() wirelessConnectPortResolver?.stop() wirelessPairingPortResolver?.stop() } }
0
Kotlin
0
10
1d33400e17fc5bb3e11014032bdb7d0cb0551935
11,939
jdwp-injector-for-android
Apache License 2.0
buildSrc/src/main/kotlin/androidx/build/ErrorProneConfiguration.kt
FYI-Google
258,765,297
false
null
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import com.android.build.gradle.api.BaseVariant import com.android.builder.core.BuilderConstants import net.ltgt.gradle.errorprone.ErrorProneBasePlugin import net.ltgt.gradle.errorprone.ErrorProneToolChain import org.gradle.api.DomainObjectSet import org.gradle.api.Project import org.gradle.api.logging.Logging import org.gradle.api.plugins.JavaPlugin.COMPILE_JAVA_TASK_NAME import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.compile.JavaCompile import org.gradle.kotlin.dsl.apply const val ERROR_PRONE_TASK = "runErrorProne" private const val ERROR_PRONE_VERSION = "com.google.errorprone:error_prone_core:2.3.3" private val log = Logging.getLogger("ErrorProneConfiguration") fun Project.configureErrorProneForJava() { val toolChain = createErrorProneToolChain() val javaCompileProvider = project.tasks.named(COMPILE_JAVA_TASK_NAME, JavaCompile::class.java) log.info("Configuring error-prone for ${project.path}") makeErrorProneTask(javaCompileProvider, toolChain) } fun Project.configureErrorProneForAndroid(variants: DomainObjectSet<out BaseVariant>) { val toolChain = createErrorProneToolChain() variants.all { variant -> if (variant.buildType.name == BuilderConstants.DEBUG) { val task = variant.javaCompileProvider log.info("Configuring error-prone for ${variant.name}'s java compile") makeErrorProneTask(task, toolChain) } } } private fun Project.createErrorProneToolChain(): ErrorProneToolChain { apply<ErrorProneBasePlugin>() val toolChain = ErrorProneToolChain.create(this) // Pin a specific version of the compiler. By default a dependency wildcard is used. dependencies.add(ErrorProneBasePlugin.CONFIGURATION_NAME, ERROR_PRONE_VERSION) return toolChain } // Given an existing JavaCompile task, reconfigures the task to use the ErrorProne compiler private fun JavaCompile.configureWithErrorProne(toolChain: ErrorProneToolChain) { this.toolChain = toolChain val compilerArgs = this.options.compilerArgs compilerArgs += listOf( "-XDcompilePolicy=simple", // Workaround for b/36098770 "-XepExcludedPaths:.*/(build/generated|build/errorProne|external)/.*", // Disable the following checks. "-Xep:RestrictTo:OFF", "-Xep:ObjectToString:OFF", "-Xep:CatchAndPrintStackTrace:OFF", // Enforce the following checks. "-Xep:ParameterNotNullable:ERROR", "-Xep:MissingOverride:ERROR", "-Xep:JdkObsolete:ERROR", "-Xep:EqualsHashCode:ERROR", "-Xep:NarrowingCompoundAssignment:ERROR", "-Xep:ClassNewInstance:ERROR", "-Xep:ClassCanBeStatic:ERROR", "-Xep:SynchronizeOnNonFinalField:ERROR", "-Xep:OperatorPrecedence:ERROR", "-Xep:IntLongMath:ERROR", "-Xep:MissingFail:ERROR", "-Xep:JavaLangClash:ERROR", "-Xep:PrivateConstructorForUtilityClass:ERROR", "-Xep:TypeParameterUnusedInFormals:ERROR", "-Xep:StringSplitter:ERROR", "-Xep:ReferenceEquality:ERROR", "-Xep:AssertionFailureIgnored:ERROR", // Nullaway "-XepIgnoreUnknownCheckNames", // https://github.com/uber/NullAway/issues/25 "-Xep:NullAway:ERROR", "-XepOpt:NullAway:AnnotatedPackages=android.arch,android.support,androidx" ) } /** * Given a [JavaCompile] task, creates a task that runs the ErrorProne compiler with the same * settings. */ private fun Project.makeErrorProneTask( compileTaskProvider: TaskProvider<JavaCompile>, toolChain: ErrorProneToolChain ) { maybeRegister<JavaCompile>( name = ERROR_PRONE_TASK, onConfigure = { val compileTask = compileTaskProvider.get() it.classpath = compileTask.classpath it.source = compileTask.source it.destinationDir = file(buildDir.resolve("errorProne")) it.options.compilerArgs = compileTask.options.compilerArgs.toMutableList() it.options.annotationProcessorPath = compileTask.options.annotationProcessorPath it.options.bootstrapClasspath = compileTask.options.bootstrapClasspath it.sourceCompatibility = compileTask.sourceCompatibility it.targetCompatibility = compileTask.targetCompatibility it.configureWithErrorProne(toolChain) it.dependsOn(compileTask.dependsOn) }, onRegister = { errorProneProvider -> tasks.named("check").configure { it.dependsOn(errorProneProvider) } } ) }
8
null
0
6
b9cd83371e928380610719dfbf97c87c58e80916
5,333
platform_frameworks_support
Apache License 2.0
plugins/devkit/intellij.devkit.workspaceModel/tests/testData/codeGen/addCopyrightComment/before/entity.kt
ingokegel
72,937,917
true
null
//some copyright comment package com.intellij.workspaceModel.test.api import com.intellij.platform.workspace.storage.WorkspaceEntity interface SimpleEntity : WorkspaceEntity { val name: String }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
199
intellij-community
Apache License 2.0
app/src/main/java/com/delminius/electroero/presentation/ui/components/LoadingAndErrorCard.kt
MilicTG
446,479,382
false
{"Kotlin": 84647}
package com.delminius.electroero.presentation.ui.components import androidx.compose.foundation.layout.* import androidx.compose.material.Card import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import com.delminius.electroero.presentation.ui.theme.* @Composable fun LoadingAndErrorCard( isDownloading: Boolean, isError: Boolean, errorMessage: String, ) { Card( modifier = Modifier .padding( horizontal = LARGE_PADDING, vertical = NORMAL_PADDING ) .fillMaxWidth(), shape = Shapes.large, backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary, elevation = CARD_ELEVATION ) { val text = when { isDownloading -> { "Preuzimanje molimo pričekajte." } isError -> { errorMessage } else -> { "Nepoznata greška" } } Row( modifier = Modifier .fillMaxWidth() .padding( horizontal = NORMAL_PADDING, vertical = SMALL_PADDING ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start ) { CircularProgressIndicator( modifier = Modifier .padding( vertical = LARGE_PADDING, horizontal = NORMAL_PADDING ), color = MaterialTheme.colors.secondary ) Text( text = text, style = TextStyle( fontWeight = FontWeight.Medium, fontSize = MaterialTheme.typography.subtitle1.fontSize ), overflow = TextOverflow.Ellipsis, modifier = Modifier .padding( start = NORMAL_PADDING, end = NORMAL_PADDING, top = NORMAL_PADDING, ) ) } } }
0
Kotlin
0
0
4de000e83e798bd6af06cdfe2c3cd8f6c5c7a635
2,541
ElectroEro
MIT License
app/src/main/java/com/example/permission_helper/ui/demo_recycler_view/item_decoration/CanvasDrawLine.kt
vnvuongducnghia
200,756,802
false
{"Kotlin": 134466}
package com.example.permission_helper.ui.demo_recycler_view.item_decoration import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import androidx.annotation.ColorInt import android.view.View import androidx.recyclerview.widget.RecyclerView class CanvasDrawLine(@ColorInt color: Int, width: Float) : RecyclerView.ItemDecoration() { private val mBrush: Paint = Paint() private val mAlpha: Int init { mBrush.color = color mBrush.strokeWidth = width mAlpha = mBrush.alpha } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val params = view.layoutParams as RecyclerView.LayoutParams val position = params.viewAdapterPosition if (position < state.itemCount) { outRect.set(0, 0, 0, mBrush.strokeWidth.toInt()) } else { outRect.setEmpty() } } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val offset = (mBrush.strokeWidth / 2).toInt() // position at center offset for (i in 0 until parent.childCount) { val childView = parent.getChildAt(i) val childParams = childView.layoutParams as RecyclerView.LayoutParams val childPosition = childParams.viewAdapterPosition if (childPosition < state.itemCount) { mBrush.alpha = (childView.alpha * mAlpha).toInt() val startX = childView.left.toFloat() + childView.translationX // + value move val startY = childView.bottom.toFloat() + offset.toFloat() + childView.translationY val stopX = childView.right + childView.translationX val stopY = childView.bottom.toFloat() + offset.toFloat() + childView.translationY c.drawLine(startX, startY, stopX, stopY, mBrush) } } } }
1
Kotlin
0
0
593005744a44bf81177eadf8463ca388485360ac
1,935
android_permission
Apache License 2.0
src/main/kotlin/sudoku/solver/SudokuGenerator.kt
Marconymous
471,797,305
false
{"Kotlin": 84990}
package sudoku.solver import sudoku.model.Sudoku object SudokuGenerator { fun generate(): Sudoku { return Sudoku(puzzles[(Math.random() * puzzles.size).toInt()]) } private val puzzles = arrayOf( arrayOf( 2, 0, 0, 0, 8, 0, 3, 0, 0, 0, 6, 0, 0, 7, 0, 0, 8, 4, 0, 3, 0, 5, 0, 0, 2, 0, 9, 0, 0, 0, 1, 0, 5, 4, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 2, 7, 0, 6, 0, 0, 0, 3, 0, 1, 0, 0, 7, 0, 4, 0, 7, 2, 0, 0, 4, 0, 0, 6, 0, 0, 0, 4, 0, 1, 0, 0, 0, 3 ), arrayOf( 0, 0, 0, 0, 0, 0, 9, 0, 7, 0, 0, 0, 4, 2, 0, 1, 8, 0, 0, 0, 0, 7, 0, 5, 0, 2, 6, 1, 0, 0, 9, 0, 4, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5, 0, 7, 0, 0, 9, 9, 2, 0, 1, 0, 8, 0, 0, 0, 0, 3, 4, 0, 5, 9, 0, 0, 0, 5, 0, 7, 0, 0, 0, 0, 0, 0 ), arrayOf( 0, 3, 0, 0, 5, 0, 0, 4, 0, 0, 0, 8, 0, 1, 0, 5, 0, 0, 4, 6, 0, 0, 0, 0, 0, 1, 2, 0, 7, 0, 5, 0, 2, 0, 8, 0, 0, 0, 0, 6, 0, 3, 0, 0, 0, 0, 4, 0, 1, 0, 9, 0, 3, 0, 2, 5, 0, 0, 0, 0, 0, 9, 8, 0, 0, 1, 0, 2, 0, 6, 0, 0, 0, 8, 0, 0, 6, 0, 0, 2, 0 ), arrayOf( 0, 2, 0, 8, 1, 0, 7, 4, 0, 7, 0, 0, 0, 0, 3, 1, 0, 0, 0, 9, 0, 0, 0, 2, 8, 0, 5, 0, 0, 9, 0, 4, 0, 0, 8, 7, 4, 0, 0, 2, 0, 8, 0, 0, 3, 1, 6, 0, 0, 3, 0, 2, 0, 0, 3, 0, 2, 7, 0, 0, 0, 6, 0, 0, 0, 5, 6, 0, 0, 0, 0, 8, 0, 7, 6, 0, 5, 1, 0, 9, 0 ), arrayOf( 1, 0, 0, 9, 2, 0, 0, 0, 0, 5, 2, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 5, 0, 0, 0, 8, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 2, 7, 0, 0, 0, 9, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 9, 4, 5, 0, 0, 0, 0, 7, 1, 0, 0, 6 ), arrayOf( 0, 4, 3, 0, 8, 0, 2, 5, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 9, 4, 9, 0, 0, 0, 0, 4, 0, 7, 0, 0, 0, 0, 6, 0, 8, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 3, 8, 2, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 3, 4, 0, 9, 0, 7, 1, 0 ), arrayOf( 4, 8, 0, 0, 0, 6, 9, 0, 2, 0, 0, 2, 0, 0, 8, 0, 0, 1, 9, 0, 0, 3, 7, 0, 0, 6, 0, 8, 4, 0, 0, 1, 0, 2, 0, 0, 0, 0, 3, 7, 0, 4, 1, 0, 0, 0, 0, 1, 0, 6, 0, 0, 4, 9, 0, 2, 0, 0, 8, 5, 0, 0, 7, 7, 0, 0, 9, 0, 0, 6, 0, 0, 6, 0, 9, 2, 0, 0, 0, 1, 8 ), arrayOf( 0, 0, 0, 9, 0, 0, 0, 0, 2, 0, 5, 0, 1, 2, 3, 4, 0, 0, 0, 3, 0, 0, 0, 0, 1, 6, 0, 9, 0, 8, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 0, 9, 1, 0, 0, 0, 0, 5, 0, 0, 0, 7, 4, 3, 9, 0, 2, 0, 4, 0, 0, 0, 0, 7, 0, 0, 0 ), arrayOf( 0, 0, 1, 9, 0, 0, 0, 0, 3, 9, 0, 0, 7, 0, 0, 1, 6, 0, 0, 3, 0, 0, 0, 5, 0, 0, 7, 0, 5, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 3, 0, 2, 6, 0, 0, 2, 0, 0, 0, 0, 0, 0, 7, 0, 6, 0, 0, 1, 0, 0, 0, 3, 0, 0, 4, 2, 0, 0, 7, 0, 0, 6, 5, 0, 0, 0, 0, 6, 8, 0, 0 ), arrayOf( 0, 0, 0, 1, 2, 5, 4, 0, 0, 0, 0, 8, 4, 0, 0, 0, 0, 0, 4, 2, 0, 8, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 9, 5, 0, 6, 0, 9, 0, 2, 0, 1, 0, 5, 1, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 3, 0, 4, 9, 0, 0, 0, 0, 0, 7, 2, 0, 0, 0, 0, 1, 2, 9, 8, 0, 0, 0 ), arrayOf( 0, 6, 2, 3, 4, 0, 7, 5, 0, 1, 0, 0, 0, 0, 5, 6, 0, 0, 5, 7, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 9, 4, 8, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 5, 8, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 9, 1, 0, 0, 6, 4, 0, 0, 0, 0, 7, 0, 5, 9, 0, 8, 3, 2, 6, 0 ), arrayOf( 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 9, 0, 0, 0, 2, 0, 0, 5, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 0, 7, 0, 0, 1, 6, 0, 0, 0, 0, 0, 5, 8, 7, 0, 4, 3, 1, 0, 6, 0, 0, 0, 0, 0, 8, 9, 0, 1, 0, 0, 0, 0, 0, 0, 6, 7, 0, 8, 0, 0, 0, 0, 0, 0, 5, 4, 3, 7 ), arrayOf( 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 8, 0, 0, 5, 6, 7, 4, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 4, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 4, 5, 0, 0, 0, 0, 0, 7, 0, 0, 4, 0, 8, 0, 3, 0, 0, 9, 0, 2, 9, 4, 7, 1, 0, 0, 0, 8, 0 ), arrayOf( 0, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 8, 0, 3, 5, 0, 0, 0, 0, 0, 0, 0, 7, 0, 6, 0, 2, 0, 3, 1, 0, 4, 6, 9, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 1, 2, 0, 3, 0, 4, 9, 0, 0, 0, 7, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 8, 0, 0, 0, 0, 4, 0, 0, 0 ), arrayOf( 3, 6, 1, 0, 2, 5, 9, 0, 0, 0, 8, 0, 9, 6, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 5, 7, 0, 0, 8, 0, 0, 0, 4, 7, 1, 0, 0, 0, 6, 0, 3, 0, 0, 0, 2, 5, 9, 0, 0, 0, 8, 0, 0, 7, 4, 0, 0, 0, 0, 0, 0, 5, 0, 2, 0, 0, 1, 8, 0, 6, 0, 0, 0, 5, 4, 7, 0, 3, 2, 9 ), arrayOf( 0, 5, 0, 8, 0, 7, 0, 2, 0, 6, 0, 0, 0, 1, 0, 0, 9, 0, 7, 0, 2, 5, 4, 0, 0, 0, 6, 0, 7, 0, 0, 2, 0, 3, 0, 1, 5, 0, 4, 0, 0, 0, 9, 0, 8, 1, 0, 3, 0, 8, 0, 0, 7, 0, 9, 0, 0, 0, 7, 6, 2, 0, 5, 0, 6, 0, 0, 9, 0, 0, 0, 3, 0, 8, 0, 1, 0, 3, 0, 4, 0 ), arrayOf( 0, 8, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 5, 7, 0, 0, 0, 0, 7, 0, 8, 0, 9, 0, 6, 0, 4, 0, 0, 9, 0, 3, 0, 0, 7, 0, 1, 0, 5, 0, 0, 4, 0, 8, 0, 0, 7, 0, 2, 0, 9, 0, 1, 0, 2, 0, 0, 0, 0, 8, 4, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 8, 0 ), arrayOf( 0, 0, 3, 5, 0, 2, 9, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 6, 0, 0, 0, 3, 0, 5, 9, 0, 0, 2, 5, 1, 0, 0, 8, 0, 7, 0, 4, 0, 8, 0, 3, 0, 8, 0, 0, 7, 6, 3, 0, 0, 1, 3, 0, 8, 0, 0, 0, 1, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 5, 1, 0, 4, 8, 0, 0 ), arrayOf( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 5, 1, 0, 0, 0, 5, 1, 9, 0, 7, 4, 2, 0, 2, 9, 0, 4, 0, 1, 0, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 0, 5, 0, 8, 0, 9, 3, 0, 2, 6, 7, 0, 9, 5, 8, 0, 0, 0, 5, 1, 0, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ), arrayOf( 0, 2, 0, 0, 3, 0, 0, 9, 0, 0, 0, 0, 9, 0, 7, 0, 0, 0, 9, 0, 0, 2, 0, 8, 0, 0, 5, 0, 0, 4, 8, 0, 6, 5, 0, 0, 6, 0, 7, 0, 0, 0, 2, 0, 8, 0, 0, 3, 1, 0, 2, 9, 0, 0, 8, 0, 0, 6, 0, 5, 0, 0, 7, 0, 0, 0, 3, 0, 9, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 5, 0 ), arrayOf( 0, 0, 5, 0, 0, 0, 0, 0, 6, 0, 7, 0, 0, 0, 9, 0, 2, 0, 0, 0, 0, 5, 0, 0, 1, 0, 7, 8, 0, 4, 1, 5, 0, 0, 0, 0, 0, 0, 0, 8, 0, 3, 0, 0, 0, 0, 0, 0, 0, 9, 2, 8, 0, 5, 9, 0, 7, 0, 0, 6, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 6, 0, 0 ), arrayOf( 0, 4, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 9, 4, 3, 6, 0, 0, 0, 0, 9, 0, 0, 0, 3, 0, 0, 6, 0, 0, 0, 5, 0, 0, 0, 2, 1, 0, 3, 0, 0, 0, 5, 0, 6, 8, 0, 0, 0, 2, 0, 0, 0, 7, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 2, 4, 3, 6, 7, 0, 0, 0, 3, 0, 0, 0, 0, 0, 4, 0 ), arrayOf( 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 3, 9, 0, 7, 0, 0, 0, 8, 0, 4, 0, 0, 0, 0, 9, 0, 0, 1, 2, 0, 9, 8, 0, 1, 3, 0, 7, 6, 0, 0, 2, 0, 0, 0, 0, 8, 0, 1, 0, 0, 0, 8, 0, 5, 3, 9, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0 ), arrayOf( 3, 6, 0, 0, 2, 0, 0, 8, 9, 0, 0, 0, 3, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 3, 0, 0, 0, 6, 0, 2, 4, 0, 0, 6, 0, 3, 0, 0, 7, 6, 0, 7, 0, 0, 0, 1, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 8, 0, 0, 0, 9, 7, 0, 0, 3, 0, 0, 1, 4 ), arrayOf( 5, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 9, 0, 0, 0, 8, 0, 0, 6, 4, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 8, 2, 0, 8, 0, 0, 0, 5, 0, 1, 7, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 8, 4, 0, 0, 3, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 3, 0, 0, 2 ), arrayOf( 0, 0, 7, 2, 5, 6, 4, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 1, 0, 0, 3, 0, 0, 6, 0, 0, 0, 0, 5, 0, 8, 0, 0, 0, 0, 0, 8, 0, 6, 0, 2, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 0, 0, 3, 0, 0, 7, 0, 0, 9, 0, 2, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 6, 3, 1, 2, 7, 0, 0 ), arrayOf( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 0, 5, 0, 1, 8, 0, 8, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 7, 3, 0, 6, 8, 0, 0, 4, 5, 0, 7, 0, 8, 0, 9, 6, 0, 0, 3, 5, 0, 2, 7, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 5, 0, 1, 6, 0, 3, 0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ), arrayOf( 0, 3, 0, 0, 0, 0, 0, 8, 0, 0, 0, 9, 0, 0, 0, 5, 0, 0, 0, 0, 7, 5, 0, 9, 2, 0, 0, 7, 0, 0, 1, 0, 5, 0, 0, 8, 0, 2, 0, 0, 9, 0, 0, 3, 0, 9, 0, 0, 4, 0, 2, 0, 0, 1, 0, 0, 4, 2, 0, 7, 1, 0, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 7, 0, 0, 0, 0, 0, 9, 0 ), arrayOf( 2, 0, 0, 1, 7, 0, 6, 0, 3, 0, 5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 7, 9, 0, 0, 0, 0, 4, 0, 7, 0, 0, 0, 0, 0, 8, 0, 1, 0, 0, 0, 0, 0, 9, 0, 5, 0, 0, 0, 0, 3, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 9, 0, 6, 0, 3, 7, 0, 0, 2 ), arrayOf( 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 0, 7, 0, 1, 0, 4, 0, 0, 4, 0, 0, 2, 0, 0, 3, 0, 3, 7, 4, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 3, 2, 1, 0, 1, 0, 0, 6, 0, 0, 5, 0, 0, 5, 0, 8, 0, 2, 0, 0, 6, 0, 8, 0, 0, 0, 0, 0, 0, 0 ), arrayOf( 0, 0, 0, 0, 0, 0, 0, 8, 5, 0, 0, 0, 2, 1, 0, 0, 0, 9, 9, 6, 0, 0, 8, 0, 1, 0, 0, 5, 0, 0, 8, 0, 0, 0, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 6, 0, 0, 7, 0, 0, 9, 0, 7, 0, 0, 5, 2, 3, 0, 0, 0, 5, 4, 0, 0, 0, 4, 8, 0, 0, 0, 0, 0, 0, 0 ), arrayOf( 6, 0, 8, 0, 7, 0, 5, 0, 2, 0, 5, 0, 6, 0, 8, 0, 7, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 5, 0, 0, 0, 9, 0, 0, 0, 6, 0, 4, 0, 3, 0, 2, 0, 5, 0, 8, 0, 0, 0, 5, 0, 0, 0, 3, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 1, 0, 7, 0, 4, 0, 9, 0, 4, 0, 9, 0, 6, 0, 7, 0, 1 ), arrayOf( 0, 5, 0, 0, 1, 0, 0, 4, 0, 1, 0, 7, 0, 0, 0, 6, 0, 2, 0, 0, 0, 9, 0, 5, 0, 0, 0, 2, 0, 8, 0, 3, 0, 5, 0, 1, 0, 4, 0, 0, 7, 0, 0, 2, 0, 9, 0, 1, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 1, 0, 0, 0, 3, 0, 4, 0, 0, 0, 7, 0, 9, 0, 2, 0, 0, 6, 0, 0, 1, 0 ), arrayOf( 0, 5, 3, 0, 0, 0, 7, 9, 0, 0, 0, 9, 7, 5, 3, 4, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 9, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 9, 0, 7, 0, 0, 0, 0, 8, 0, 0, 3, 0, 0, 7, 0, 5, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 7, 6, 4, 1, 2, 0, 0, 0, 6, 1, 0, 0, 0, 9, 4, 0 ), arrayOf( 0, 0, 6, 0, 8, 0, 3, 0, 0, 0, 4, 9, 0, 7, 0, 2, 5, 0, 0, 0, 0, 4, 0, 5, 0, 0, 0, 6, 0, 0, 3, 1, 7, 0, 0, 4, 0, 0, 7, 0, 0, 0, 8, 0, 0, 1, 0, 0, 8, 2, 6, 0, 0, 9, 0, 0, 0, 7, 0, 2, 0, 0, 0, 0, 7, 5, 0, 4, 0, 1, 9, 0, 0, 0, 3, 0, 9, 0, 6, 0, 0 ), arrayOf( 0, 0, 5, 0, 8, 0, 7, 0, 0, 7, 0, 0, 2, 0, 4, 0, 0, 5, 3, 2, 0, 0, 0, 0, 0, 8, 4, 0, 6, 0, 1, 0, 5, 0, 4, 0, 0, 0, 8, 0, 0, 0, 5, 0, 0, 0, 7, 0, 8, 0, 3, 0, 1, 0, 4, 5, 0, 0, 0, 0, 0, 9, 1, 6, 0, 0, 5, 0, 8, 0, 0, 7, 0, 0, 3, 0, 1, 0, 6, 0, 0 ), arrayOf( 0, 0, 0, 9, 0, 0, 8, 0, 0, 1, 2, 8, 0, 0, 6, 4, 0, 0, 0, 7, 0, 8, 0, 0, 0, 6, 0, 8, 0, 0, 4, 3, 0, 0, 0, 7, 5, 0, 0, 0, 0, 0, 0, 0, 9, 6, 0, 0, 0, 7, 9, 0, 0, 8, 0, 9, 0, 0, 0, 4, 0, 1, 0, 0, 0, 3, 6, 0, 0, 2, 8, 4, 0, 0, 1, 0, 0, 7, 0, 0, 0 ), arrayOf( 0, 0, 0, 0, 8, 0, 0, 0, 0, 2, 7, 0, 0, 0, 0, 0, 5, 4, 0, 9, 5, 0, 0, 0, 8, 1, 0, 0, 0, 9, 8, 0, 6, 4, 0, 0, 0, 2, 0, 4, 0, 3, 0, 6, 0, 0, 0, 6, 9, 0, 5, 1, 0, 0, 0, 1, 7, 0, 0, 0, 6, 2, 0, 4, 6, 0, 0, 0, 0, 0, 3, 8, 0, 0, 0, 0, 9, 0, 0, 0, 0 ), arrayOf( 0, 0, 0, 6, 0, 2, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 1, 0, 8, 5, 0, 1, 0, 6, 2, 0, 0, 3, 8, 2, 0, 6, 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 9, 4, 0, 7, 3, 5, 0, 0, 2, 6, 0, 4, 0, 5, 3, 0, 9, 0, 0, 0, 2, 0, 0, 0, 7, 0, 0, 0, 8, 0, 9, 0, 0, 0 ), arrayOf( 0, 0, 0, 9, 0, 0, 0, 0, 2, 0, 5, 0, 1, 2, 3, 4, 0, 0, 0, 3, 0, 0, 0, 0, 1, 6, 0, 9, 0, 8, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 0, 9, 1, 0, 0, 0, 0, 5, 0, 0, 0, 7, 4, 3, 9, 0, 2, 0, 4, 0, 0, 0, 0, 7, 0, 0, 0 ), arrayOf( 3, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 7, 8, 5, 0, 0, 9, 0, 2, 0, 3, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 8, 0, 0, 3, 0, 2, 0, 0, 9, 0, 0, 0, 0, 4, 0, 0, 7, 0, 0, 0, 1, 0, 7, 0, 5, 0, 0, 4, 9, 5, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2 ), arrayOf( 0, 0, 0, 1, 5, 8, 0, 0, 0, 0, 0, 2, 0, 6, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0, 0, 4, 0, 0, 2, 7, 0, 3, 0, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 0, 8, 0, 7, 9, 0, 0, 5, 0, 0, 0, 0, 0, 8, 0, 0, 0, 4, 0, 7, 0, 1, 0, 0, 0, 0, 0, 3, 2, 5, 0, 0, 0 ), arrayOf( 0, 1, 0, 5, 0, 0, 2, 0, 0, 9, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 8, 0, 3, 0, 5, 0, 0, 0, 3, 0, 0, 0, 7, 0, 0, 8, 0, 0, 0, 5, 0, 0, 6, 0, 0, 0, 8, 0, 0, 0, 4, 0, 4, 0, 1, 0, 0, 7, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 6, 0, 0, 3, 0, 0, 4, 0, 5, 0 ), arrayOf( 0, 8, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 6, 9, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 5, 9, 0, 4, 6, 0, 0, 0, 7, 0, 6, 0, 8, 0, 3, 0, 0, 0, 8, 5, 0, 2, 1, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 7, 8, 1, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 1, 0 ), arrayOf( 9, 0, 4, 2, 0, 0, 0, 0, 7, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 6, 5, 0, 0, 0, 0, 0, 8, 0, 0, 0, 9, 0, 0, 2, 0, 9, 0, 4, 0, 6, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 6, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 0, 0, 0, 0, 5, 7, 0, 2 ), arrayOf( 0, 0, 0, 7, 0, 0, 8, 0, 0, 0, 0, 6, 0, 0, 0, 0, 3, 1, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 2, 4, 0, 7, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 8, 0, 0, 0, 0, 0, 6, 0, 2, 9, 0, 0, 0, 0, 8, 0, 0, 0, 7, 0, 8, 6, 0, 0, 0, 0, 5, 0, 0, 0, 0, 2, 0, 0, 6, 0, 0, 0 ), arrayOf( 0, 0, 1, 0, 0, 7, 0, 9, 0, 5, 9, 0, 0, 8, 0, 0, 0, 1, 0, 3, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 5, 8, 0, 0, 0, 5, 0, 0, 6, 0, 0, 2, 0, 0, 0, 4, 1, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 3, 0, 1, 0, 0, 0, 2, 0, 0, 7, 9, 0, 2, 0, 7, 0, 0, 4, 0, 0 ), arrayOf( 0, 0, 0, 0, 0, 3, 0, 1, 7, 0, 1, 5, 0, 0, 9, 0, 0, 8, 0, 6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 9, 0, 0, 0, 2, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 0, 0, 6, 0, 0, 3, 4, 0, 3, 4, 0, 2, 0, 0, 0, 0, 0 ) ) }
0
Kotlin
0
4
fabf1111cbbf4bf63b70483699241cd0e865465a
59,841
sudoku
MIT License
droid-app/CoffeeDose/app/src/main/java/com/office14/coffeedose/bindings/BindingConverters.kt
sofinms
249,805,970
true
{"Kotlin": 102441, "C#": 99646, "TypeScript": 65904, "HTML": 11001, "JavaScript": 1831, "Dockerfile": 1083, "CSS": 299}
package com.office14.coffeedose.bindings import android.view.View import androidx.databinding.BindingConversion object BindingConverters { @BindingConversion @JvmStatic fun booleanToVisibility(visible: Boolean): Int { return if (!visible) View.GONE else View.VISIBLE } }
0
null
0
0
109a16dbce748a363eeb290ebba46c4b9dbbf357
297
Drinks
MIT License
feature/graph/src/main/kotlin/com/mmoczkowski/zynth2/feature/graph/ui/GraphRoute.kt
mmoczkowski
505,812,011
false
null
package com.mmoczkowski.zynth2.feature.graph.ui import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.ControlledComposition import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.currentComposer import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PointMode import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.mmoczkowski.zynth2.feature.compose.R import com.mmoczkowski.zynth2.feature.graph.state.GraphViewState import com.mmoczkowski.zynth2.feature.graph.state.NodeViewState import com.mmoczkowski.zynth2.feature.graph.vm.GraphViewModel import com.mmoczkowski.zynth2.ui.BoardView import com.mmoczkowski.zynth2.ui.angle import com.mmoczkowski.zynth2.ui.div import com.mmoczkowski.zynth2.ui.length import kotlinx.coroutines.android.awaitFrame import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.isActive import kotlin.math.pow @Composable fun GraphRoute( viewModel: GraphViewModel = hiltViewModel(), onBoardTapped: (position: Offset) -> Unit, onNodeSelected: (nodeId: Long) -> Unit, onOpenKeyboard: () -> Unit ) { val state: GraphViewState by viewModel.state.collectAsState() GraphScreen( nodes = state.nodes, onBoardTapped = onBoardTapped, onNodeDragged = viewModel::onUpdateNodePosition, onNodeSelected = onNodeSelected, onNodeDeleted = viewModel::onDeleteNode, onOpenKeyboard = onOpenKeyboard ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun GraphScreen( nodes: List<NodeViewState>, onBoardTapped: (position: Offset) -> Unit, onNodeDragged: (nodeId: Long, position: Offset) -> Unit, onNodeSelected: (nodeId: Long) -> Unit, onNodeDeleted: (Long) -> Unit, onOpenKeyboard: () -> Unit ) { val currentComposition: ControlledComposition = currentComposer.composition LaunchedEffect(currentComposition) { while (currentCoroutineContext().isActive) { currentComposition.invalidateAll() awaitFrame() } } val primaryColor: Color = MaterialTheme.colorScheme.primary val strokeWidthPx: Float = with(LocalDensity.current) { 2.dp.toPx() } val maxAmplitudeHeightPx: Float = with(LocalDensity.current) { 24.dp.toPx() } Scaffold( floatingActionButton = { FloatingActionButton(onClick = onOpenKeyboard) { Icon( painter = painterResource(id = R.drawable.ic_keyboard), contentDescription = null ) } } ) { padding -> var boardSize: IntSize by remember { mutableStateOf(IntSize.Zero) } BoardView( nodes = nodes, nodePosition = { node -> node.position }, onBoardTapped = onBoardTapped, modifier = Modifier .padding(padding) .fillMaxSize() .background(MaterialTheme.colorScheme.surface) .onGloballyPositioned { coords -> boardSize = coords.size } .drawBehind { translate(left = size.width / 2, top = size.height / 2) { scale(scaleX = -size.width, scaleY = -size.height, pivot = Offset.Zero) { nodes.forEach { state -> val end: Offset = state.outputConnection ?: return@forEach val start: Offset = state.position val absoluteVector: Offset = (end - start) val angle: Float = absoluteVector.angle translate(left = start.x, top = start.y) { rotate(degrees = angle, pivot = Offset.Zero) { val length: Float = absoluteVector.length val audio: Collection<Double> = state.audio.toList() val stepX: Float = length / audio.size val points: List<Offset> = audio.mapIndexed { index, amplitude -> val progress: Float = index / audio.size.toFloat() val heightCoefficient: Float = -(2 * progress - 1).pow(2) + 1 Offset( x = stepX * index, y = amplitude.toFloat() * maxAmplitudeHeightPx / size.maxDimension * heightCoefficient ) } drawPoints( points = points, pointMode = PointMode.Polygon, color = primaryColor, strokeWidth = strokeWidthPx / size.maxDimension ) } } } } } } ) { node -> var dragOffset: Offset = remember(node.position) { Offset.Zero } NodeView( node = node, modifier = Modifier .pointerInput(node.nodeId) { detectTapGestures( onTap = { onNodeSelected(node.nodeId) }, onLongPress = { onNodeDeleted(node.nodeId) } ) } .pointerInput(node.nodeId) { detectDragGestures( onDrag = { _, offset -> val delta = offset / boardSize dragOffset += delta onNodeDragged(node.nodeId, node.position - dragOffset) } ) }) } } }
15
Kotlin
0
25
0fa70fae9bb25f3fe7156734c132f44dbf6adc53
7,622
zynth2
MIT License
presentation/src/main/java/com/danielwaiguru/touristnews/presentation/common/ErrorView.kt
daniel-waiguru
680,273,793
false
{"Kotlin": 123694, "Shell": 254}
package com.danielwaiguru.touristnews.presentation.common import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import com.danielwaiguru.touristnews.designsystem.previews.OctoKitDevicePreviews import com.danielwaiguru.touristnews.presentation.R @Composable fun ErrorView( modifier: Modifier = Modifier, title: String = stringResource(id = R.string.error_title), description: String? ) { Column( modifier = modifier .testTag("error_view"), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = title, style = MaterialTheme.typography.headlineSmall ) Text(text = description ?: stringResource(id = R.string.an_error_occured)) } } @OctoKitDevicePreviews @Composable fun EmptyViewPreview() { ErrorView( title = "No Data FOund", description = "Data will appear here", modifier = Modifier.fillMaxSize() ) }
11
Kotlin
0
0
83cdab29d47c16554f15eacc3c03f210b9524443
1,396
Tourist-App
The Unlicense
app/src/main/kotlin/com/pnuema/bible/android/database/VersionOfflineDao.kt
barnhill
98,140,541
false
{"Kotlin": 130313, "Java": 2781}
package com.pnuema.bible.android.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction @Dao interface VersionOfflineDao { @Transaction @Query("select * from offlineVersion") suspend fun getVersions(): List<VersionOffline> @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun putVersions(version: List<VersionOffline>) @Transaction @Query("update offlineVersion set completeOffline = :isAvailableOffline where abbreviation = :version") suspend fun markCompleteOfflineAvailable(version: String, isAvailableOffline: Boolean) }
0
Kotlin
4
18
2ec6e0113ba6d8cb97ee63b4f5a26834e441314c
675
Bible
Apache License 2.0
library/src/linuxMain/kotlin/us/q3q/fidok/LinuxBluetoothDevice.kt
BryanJacobs
684,573,020
false
{"Kotlin": 780971}
package us.q3q.fidok import co.touchlab.kermit.Logger import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import us.q3q.fidok.ble.CTAPBLE import us.q3q.fidok.ble.CTAPBLECommand import us.q3q.fidok.ble.FIDO_BLE_SERVICE_UUID import us.q3q.fidok.ble.FIDO_CONTROL_POINT_ATTRIBUTE import us.q3q.fidok.ble.FIDO_CONTROL_POINT_LENGTH_ATTRIBUTE import us.q3q.fidok.ble.FIDO_SERVICE_REVISION_BITFIELD_ATTRIBUTE import us.q3q.fidok.ble.FIDO_STATUS_ATTRIBUTE import us.q3q.fidok.ctap.AuthenticatorDevice import us.q3q.fidok.ctap.AuthenticatorTransport import us.q3q.fidok.ctap.DeviceCommunicationException import us.q3q.fidok.ctap.IncorrectDataException import us.q3q.fidok.ctap.InvalidDeviceException import kotlin.time.Duration.Companion.seconds private val READ_TIMEOUT = 5.seconds /** * An [AuthenticatorDevice] implementation for Bluetooth Low Energy (BLE) on Linux. * * This uses the BlueZ bluetooth stack (over D-Bus) via a library called bluez_inc. * This can only work on Linux. * * @property name The human-readable name of the BLE device * @property listing A reference to a BLE manager stack for communicating with the device */ class LinuxBluetoothDevice( val address: String, val name: String, private val listing: LinuxBluetoothDeviceListing, ) : AuthenticatorDevice { init { listing.ref() } protected fun finalize() { listing.unref() } private var connected: Boolean = false private var cpLen: Int = 0 @Throws( DeviceCommunicationException::class, CancellationException::class, IncorrectDataException::class, InvalidDeviceException::class, ) private suspend fun connect() { if (!connected) { try { connected = listing.connect(address) } catch (e: Exception) { throw DeviceCommunicationException(e.message) } val cpLenArr = listing.read(address, FIDO_BLE_SERVICE_UUID, FIDO_CONTROL_POINT_LENGTH_ATTRIBUTE) ?: throw DeviceCommunicationException("Could not read FIDO control point length") if (cpLenArr.size != 2) { throw IncorrectDataException("Control point length was not itself two bytes long: ${cpLenArr.size}") } cpLen = cpLenArr[0].toByte() * 256 + cpLenArr[1].toByte() if (cpLen < 20 || cpLen > 512) { throw IncorrectDataException("Control point length on '$name' out of bounds: $cpLen") } val rev = listing.read(address, FIDO_BLE_SERVICE_UUID, FIDO_SERVICE_REVISION_BITFIELD_ATTRIBUTE) ?: throw DeviceCommunicationException("BLE device '$name' could not read service revision chara") if (rev.isEmpty() || (rev[0] and 0x20u.toUByte()) != 0x20u.toUByte()) { throw InvalidDeviceException("BLE device '$name' does not support FIDO2-BLE") } listing.write(address, FIDO_BLE_SERVICE_UUID, FIDO_SERVICE_REVISION_BITFIELD_ATTRIBUTE, ubyteArrayOf(0x20u), true) ?: throw DeviceCommunicationException("BLE device '$name' could not be set to FIDO2-BLE") } } @Throws(DeviceCommunicationException::class) override fun sendBytes(bytes: ByteArray): ByteArray { return runBlocking { connect() val readResult = Channel<UByteArray>(Channel.BUFFERED) listing.setNotify(address, FIDO_BLE_SERVICE_UUID, FIDO_STATUS_ATTRIBUTE, readResult) Logger.v { "Notify ready, beginning CTAP send/recv loop on '$name'" } try { return@runBlocking CTAPBLE.sendAndReceive({ runBlocking { if (listing.write( address, FIDO_BLE_SERVICE_UUID, FIDO_CONTROL_POINT_ATTRIBUTE, it, true, ) == null ) { throw DeviceCommunicationException("Could not write message to peripheral '$name'") } } }, { runBlocking { withTimeout(READ_TIMEOUT) { readResult.receive() } } }, CTAPBLECommand.MSG, bytes.toUByteArray(), cpLen).toByteArray() } finally { listing.setNotify(address, FIDO_BLE_SERVICE_UUID, FIDO_STATUS_ATTRIBUTE, null) } } } override fun getTransports(): List<AuthenticatorTransport> { return listOf(AuthenticatorTransport.BLE) } override fun toString(): String { return "BT:$name ($address)" } }
0
Kotlin
1
9
459274c1808bd5d733757c371e927f6d806ab7bb
4,992
FIDOk
MIT License
app/src/main/java/com/albino/restaurantapp/model/RestaurantMenu.kt
DevelopmentAndroidTools
284,491,320
false
null
package com.itisakdesigns.foodbit.model data class RestaurantMenu ( var id:String, var name:String, var cost_for_one:String )
1
Kotlin
2
3
6740cc7a3418fb1096354d8ca49836fa46da3e57
138
RestaurantApp
MIT License
app/src/main/java/com/siju/acexplorer/storage/model/operations/OperationData.kt
siju-s
427,592,750
false
null
package com.siju.acexplorer.storage.model.operations import com.siju.acexplorer.common.types.FileInfo class OperationData private constructor(var arg1: String, var arg2: String) { var paths = arrayListOf<String>() private set var filesList = arrayListOf<FileInfo>() private set constructor(paths: ArrayList<String>) : this("null", "null") { this.paths = paths } constructor(destinationDir: String, filesToCopy: java.util.ArrayList<FileInfo>) : this( destinationDir, "null") { this.arg1 = destinationDir this.filesList = filesToCopy } companion object { fun createRenameOperation(filePath: String, fileName: String): OperationData { return OperationData(filePath, fileName) } fun createNewFolderOperation(filePath: String, name: String): OperationData { return OperationData(filePath, name) } fun createNewFileOperation(filePath: String, name: String): OperationData { return OperationData(filePath, name) } fun createDeleteOperation(filePaths: ArrayList<String>): OperationData { return OperationData(filePaths) } fun createCopyOperation(destinationDir: String, filesToCopy: ArrayList<FileInfo>): OperationData { return OperationData(destinationDir, filesToCopy) } fun createExtractOperation(sourceFilePath: String, destinationDir: String): OperationData { return OperationData(sourceFilePath, destinationDir) } fun createArchiveOperation(destinationDir: String, filesToArchive: ArrayList<FileInfo>): OperationData { return OperationData(destinationDir, filesToArchive) } fun createFavoriteOperation(favList: ArrayList<String>): OperationData { return OperationData(favList) } fun createPermissionOperation(path : String) : OperationData { return OperationData(path, "null") } } }
4
Kotlin
5
2
68338f005f8365609f115390e7d770197b807763
2,092
AceExplorer
Apache License 2.0
src/main/kotlin/com/mineinabyss/blocky/components/core/BlockyInfo.kt
MineInAbyss
468,482,997
false
null
@file:UseSerializers(IntRangeSerializer::class) package com.mineinabyss.blocky.components.core import com.mineinabyss.idofront.serialization.IntRangeSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers @Serializable @SerialName("blocky:info") data class BlockyInfo( val blockModel: String? = null, val isUnbreakable: Boolean = false )
7
Kotlin
0
2
af55c5d37ad54935da56a8ce54905d904f864ffe
430
Blocky
MIT License
kanarinho-core/src/commonMain/kotlin/net/rafaeltoledo/kanarinho/formatter/CepFormatter.kt
rafaeltoledo
619,258,647
false
null
package net.rafaeltoledo.kanarinho.formatter import net.rafaeltoledo.kanarinho.formatter.Formatter.Patterns.CEP_FORMATTED import net.rafaeltoledo.kanarinho.formatter.Formatter.Patterns.CEP_UNFORMATTED class CepFormatter : Formatter { private val delegateFormatter = BaseFormatter( CEP_FORMATTED, "$1-$2", CEP_UNFORMATTED, "$1$2" ) override fun format(rawValue: String): String = delegateFormatter.format(rawValue) override fun unformat(formattedValue: String): String = delegateFormatter.unformat(formattedValue) override fun isFormatted(value: String): Boolean = delegateFormatter.isFormatted(value) override fun canBeFormatted(value: String): Boolean = delegateFormatter.canBeFormatted(value) }
2
Kotlin
0
0
cd5d184920b5ec88e77a3c7d72064e0ec40fbc12
720
kanarinho
Apache License 2.0
nebulosa-indi-device/src/main/kotlin/nebulosa/indi/device/filterwheel/FilterWheelCountChanged.kt
tiagohm
568,578,345
false
{"Kotlin": 2712371, "TypeScript": 513759, "HTML": 249483, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 445}
package nebulosa.indi.device.filterwheel import nebulosa.indi.device.PropertyChangedEvent data class FilterWheelCountChanged(override val device: FilterWheel) : FilterWheelEvent, PropertyChangedEvent
26
Kotlin
2
4
2099c6f2d7453507289a43efe903c7f92f65f770
202
nebulosa
MIT License
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/arrows/CornerUpRightLine.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.arrows import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.remix.remix.ArrowsGroup public val ArrowsGroup.CornerUpRightLine: ImageVector get() { if (_cornerUpRightLine != null) { return _cornerUpRightLine!! } _cornerUpRightLine = Builder(name = "CornerUpRightLine", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 10.0f) lineTo(5.0f, 19.0f) lineTo(7.0f, 19.0f) lineTo(7.0f, 12.0f) lineTo(17.172f, 12.0f) lineTo(13.222f, 15.95f) lineTo(14.636f, 17.364f) lineTo(21.0f, 11.0f) lineTo(14.636f, 4.636f) lineTo(13.222f, 6.05f) lineTo(17.172f, 10.0f) lineTo(5.0f, 10.0f) close() } } .build() return _cornerUpRightLine!! } private var _cornerUpRightLine: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
1,801
compose-icon-collections
MIT License
core/src/com/broll/voxeldungeon/map/HorizontalChunkLane.kt
Rolleander
476,822,126
false
{"Kotlin": 97514, "GLSL": 3666, "Java": 1305}
package com.broll.voxeldungeon.map import com.badlogic.gdx.utils.Array class HorizontalChunkLane { /** * chunksForwad contains vertical chunks from 0 to +z max chunksBackward * contains vertical cunks from -1 to -z max */ private val laneForwad = Array<VerticalChunkLane>() private val laneBackward = Array<VerticalChunkLane>() var x = 0 private set fun init(x: Int) { this.x = x } fun existsLane(z: Int): Boolean { return z < laneForwad.size && z >= laneBackward.size * -1 } fun getLaneEndZ(forward: Boolean): Int { return if (forward) { laneForwad.size - 1 } else laneBackward.size * -1 } fun getNextLaneZ(forward: Boolean): Int { val nextZ = getLaneEndZ(forward) return if (forward) { nextZ + 1 } else nextZ - 1 } fun addVerticalChunkLine(chunkLane: VerticalChunkLane, forward: Boolean) { if (forward) { laneForwad.add(chunkLane) chunkLane.init(x, getLaneEndZ(true)) } else { laneBackward.add(chunkLane) chunkLane.init(x, getLaneEndZ(false)) } } @Throws(ChunkNotFoundException::class) fun getVerticalChunkLane(z: Int): VerticalChunkLane { if (z >= 0) { if (z < laneForwad.size) { return laneForwad[z] } } else { val chunkNr = z * -1 - 1 if (chunkNr < laneBackward.size) { return laneBackward[chunkNr] } } throw ChunkNotFoundException("No vertical chunk lane found for z=$z") } }
0
Kotlin
0
0
6bce2fb21620d91c171d82e5a5db6dc1fb3a5a7c
1,657
voxel-dungeon
MIT License
src/main/kotlin/structures/MyArrayList.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 221468}
package structures import java.lang.IllegalStateException /** * * data structure: simple java.util.ArrayList implementation * * description: wrapper over a regular array, in which indexes are checked and * when the array overflows, its size increases dynamically * * @property capacity initial array size * * P.S. Kotlin lists use under the hood java.util.ArrayList * for example: * val numbers = listOf(1, 2, 3) // java.util.ArrayList * val symbols = mutableListOf('a', 'b', 'c') // also java.util.ArrayList */ class MyArrayList(private var capacity: Int = 10) { private var data = Array(capacity) { 0 } private var index = 0 /** * adds a new element [value] in array, if the array cannot accommodate the new element, then its size is dynamically increased */ fun add(value: Int) { if (index < data.size - 1) { data[index++] = value } else { increaseSize() data[index++] = value } } /** * removes an element [value] from the array and shifts subsequent elements in its place */ fun remove(value: Int) : Boolean { val foundedIndex = data.indexOf(value) if (foundedIndex == -1) { return false } for (i in foundedIndex until data.size - 1) { data[i] = data[i + 1] } return true } /** * checks for the existence of an element [value] in an array, returns true if the element is present in the array */ fun contains(value: Int) = data.contains(value) /** * sets the new element [value] at the specified index [index], returns true if the element was successfully modified */ fun set(index: Int, value: Int) : Boolean { if (isBound(index)) { data[index] = value return true } return false } /** * returns the value of the element by index [index], or throws an exception if the index is invalid */ fun get(index: Int) : Int { if (isBound(index)) { return data[index] } else { throw IllegalStateException("index is out of bounds!") } } /** * returns the size of the array */ fun capacity() = capacity /** * checks for correct index, returns true if the index is within the range of available indexes */ private fun isBound(i: Int) = i in 0 until index override fun toString() = data.joinToString(", ") /** * increases the size of an array when there is not enough to add new elements */ private fun increaseSize() { capacity *= 2 val newArray = Array(capacity) { 0 } for ((index, element) in data.withIndex()) { newArray[index] = element } data = newArray } }
0
Kotlin
135
763
de0f65c8f774cdca6bd88421cad83eb50e693ccf
2,843
Kotlin-Algorithms-and-Design-Patterns
MIT License
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/BuildListeners.kt
rhencke
87,652,864
true
{"Kotlin": 726994, "Java": 23612, "HTML": 1694, "Shell": 447, "Batchfile": 126}
package com.beust.kobalt.internal import com.beust.kobalt.Args import com.beust.kobalt.AsciiArt import com.beust.kobalt.api.* import com.beust.kobalt.misc.kobaltLog import java.util.concurrent.ConcurrentHashMap /** * Record timings and statuses for tasks and projects and display them at the end of the build. */ class BuildListeners : IBuildListener, IBuildReportContributor { class ProfilerInfo(val taskName: String, val durationMillis: Long) class ProjectInfo(val projectName: String, var durationMillis: Long = 0) private val startTimes = ConcurrentHashMap<String, Long>() private val timings = arrayListOf<ProfilerInfo>() private val projectInfos = hashMapOf<String, ProjectInfo>() private var hasFailures = false private val args: Args get() = Kobalt.INJECTOR.getInstance(Args::class.java) private var buildStartTime: Long? = null // IBuildListener override fun taskStart(project: Project, context: KobaltContext, taskName: String) { startTimes.put(taskName, System.currentTimeMillis()) if (! projectInfos.containsKey(project.name)) { projectInfos.put(project.name, ProjectInfo(project.name)) } } // IBuildListener override fun taskEnd(project: Project, context: KobaltContext, taskName: String, success: Boolean) { if (! success) hasFailures = true startTimes[taskName]?.let { val taskTime = System.currentTimeMillis() - it timings.add(ProfilerInfo(taskName, taskTime)) projectInfos[project.name]?.let { it.durationMillis += taskTime.toLong() } } } private val projectStatuses = arrayListOf<Pair<Project, ProjectBuildStatus>>() // IBuildListener override fun projectStart(project: Project, context: KobaltContext) { if (buildStartTime == null) buildStartTime = System.currentTimeMillis() } // IBuildListener override fun projectEnd(project: Project, context: KobaltContext, status: ProjectBuildStatus) { projectStatuses.add(Pair(project, status)) } // IBuildReportContributor override fun generateReport(context: KobaltContext) { fun formatMillis(millis: Long, format: String) = String.format(format, millis.toDouble() / 1000) fun formatMillisRight(millis: Long, length: Int) = formatMillis(millis, "%1\$$length.2f") fun formatMillisLeft(millis: Long, length: Int) = formatMillis(millis, "%1\$-$length.2f") fun millisToSeconds(millis: Long) = (millis.toDouble() / 1000).toInt() val profiling = args.profiling if (profiling) { kobaltLog(1, "\n" + AsciiArt.horizontalSingleLine + " Timings (in seconds)") timings.sortedByDescending { it.durationMillis }.forEach { kobaltLog(1, formatMillisRight(it.durationMillis, 10) + " " + it.taskName) } kobaltLog(1, "\n") } fun col1(s: String) = String.format(" %1\$-30s", s) fun col2(s: String) = String.format(" %1\$-13s", s) fun col3(s: String) = String.format(" %1\$-8s", s) // Only print the build report if there is more than one project and at least one of them failed if (timings.any()) { // if (timings.size > 1 && hasFailures) { val line = listOf(col1("Project"), col2("Build status"), col3("Time")) .joinToString(AsciiArt.verticalBar) val table = StringBuffer() table.append(AsciiArt.logBox(listOf(line), AsciiArt.bottomLeft2, AsciiArt.bottomRight2, indent = 10) + "\n") projectStatuses.forEach { pair -> val projectName = pair.first.name val cl = listOf(col1(projectName), col2(pair.second.toString()), col3(formatMillisLeft(projectInfos[projectName]!!.durationMillis, 8))) .joinToString(AsciiArt.verticalBar) table.append(" " + AsciiArt.verticalBar + " " + cl + " " + AsciiArt.verticalBar + "\n") } table.append(" " + AsciiArt.lowerBox(line.length)) kobaltLog(1, table.toString()) // } } val buildTime = if (buildStartTime != null) millisToSeconds(System.currentTimeMillis() - buildStartTime!!) else 0 // BUILD SUCCESSFUL / FAILED message val message = if (hasFailures) { String.format("BUILD FAILED", buildTime) } else if (! args.sequential) { val sequentialBuildTime = ((projectInfos.values.sumByDouble { it.durationMillis.toDouble() }) / 1000) .toInt() String.format("PARALLEL BUILD SUCCESSFUL (%d SECONDS), sequential build would have taken %d seconds", buildTime, sequentialBuildTime) } else { String.format("BUILD SUCCESSFUL (%d SECONDS)", buildTime) } kobaltLog(1, message) } }
0
Kotlin
0
0
f7cb803edcfd58a86cea8edb80c990f266d3a0bb
5,040
kobalt
Apache License 2.0
core/src/commonMain/kotlin/dev/schlaubi/lavakord/audio/internal/AbstractLink.kt
kordlib
295,040,489
false
{"Kotlin": 244066, "Java": 4794}
package dev.schlaubi.lavakord.audio.internal import dev.arbjerg.lavalink.protocol.v4.PlayerUpdate import dev.arbjerg.lavalink.protocol.v4.VoiceState import dev.arbjerg.lavalink.protocol.v4.toOmissible import dev.schlaubi.lavakord.audio.Link import dev.schlaubi.lavakord.audio.Node import dev.schlaubi.lavakord.audio.player.Player import dev.schlaubi.lavakord.audio.player.node import dev.schlaubi.lavakord.rest.destroyPlayer import dev.schlaubi.lavakord.rest.updatePlayer /** * Abstract implementation of [Link]. */ public abstract class AbstractLink(node: Node, final override val guildId: ULong) : Link { final override var node: Node = node private set override val player: Player = WebsocketPlayer(node as NodeImpl, guildId) abstract override val lavakord: AbstractLavakord override var lastChannelId: ULong? = null override var state: Link.State = Link.State.NOT_CONNECTED private var cachedVoiceState: VoiceState? = null override suspend fun onDisconnected() { state = Link.State.NOT_CONNECTED node.destroyPlayer(guildId) cachedVoiceState = null } override suspend fun onNewSession(node: Node) { this.node = node player.node cachedVoiceState?.let { node.updatePlayer(guildId, request = PlayerUpdate(voice = it.toOmissible())) } (player as WebsocketPlayer).recreatePlayer(node as NodeImpl) } override suspend fun destroy() { val shouldDisconnect = state !== Link.State.DISCONNECTING && state !== Link.State.NOT_CONNECTED state = Link.State.DESTROYING if (shouldDisconnect) { disconnectAudio() } node.destroyPlayer(guildId) lavakord.removeDestroyedLink(this) state = Link.State.DESTROYED } internal suspend fun onVoiceServerUpdate(update: VoiceState) { cachedVoiceState = update node.updatePlayer(guildId, request = PlayerUpdate(voice = update.toOmissible())) } }
5
Kotlin
9
36
521b9c63a558c84be829cefd774f88c2188fe533
2,003
Lavalink.kt
MIT License
app-main/src/main/kotlin/com/flab/hsw/endpoint/auth/AuthenticationController.kt
f-lab-edu
545,756,758
false
{"Kotlin": 249863, "Vim Snippet": 765}
package com.flab.hsw.endpoint.auth import com.flab.hsw.endpoint.ApiPaths import com.flab.hsw.endpoint.v1.user.login.UserLoginResponse import com.flab.hsw.util.JwtTokenManager import com.flab.hsw.util.JwtTokenManager.Companion.AUTHORIZATION_HEADER import org.springframework.http.MediaType import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.security.auth.login.CredentialNotFoundException import javax.servlet.http.HttpServletRequest /** * ``` * POST /auth/refresh * * Content-Type: application/json * ``` */ @RequestMapping( produces = [MediaType.APPLICATION_JSON_VALUE], ) interface AuthenticationController { val jwtTokenManager: JwtTokenManager @RequestMapping( path = [ApiPaths.REFRESH_TOKEN], method = [RequestMethod.POST] ) fun recreateAccessToken(request: HttpServletRequest): UserLoginResponse } @RestController internal class AuthenticationControllerImpl( override val jwtTokenManager: JwtTokenManager ) : AuthenticationController { override fun recreateAccessToken(request: HttpServletRequest): UserLoginResponse { val claimsFromRefreshToken = jwtTokenManager.validAndReturnClaims( request.getHeader(AUTHORIZATION_HEADER) ?: throw CredentialNotFoundException() ) return UserLoginResponse( authorizedToken = jwtTokenManager.createAccessTokenBy(claimsFromRefreshToken.body.subject), expiredIn = jwtTokenManager.returnAccessTokenExpiredIn() ) } }
2
Kotlin
4
5
90dd69cbef256eff7cb852abfc2573719a1fb5f1
1,620
hello-study-world
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/Update.kt
karakum-team
387,062,541
false
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/Update") package mui.icons.material @JsName("default") external val Update: SvgIconComponent
1
Kotlin
5
35
7c4376ba64ea84a5c40255d83c8c046978c3843d
176
mui-kotlin
Apache License 2.0
starter/sisyphus-grpc-transcoding-starter/src/main/kotlin/com/bybutter/sisyphus/starter/grpc/transcoding/support/swagger/authentication/DefaultSwaggerValidate.kt
zhi-re
283,650,568
true
{"Kotlin": 970649, "ANTLR": 10895}
package com.bybutter.sisyphus.starter.grpc.transcoding.support.swagger.authentication import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.web.reactive.function.server.ServerRequest class DefaultSwaggerValidate : SwaggerValidate { override fun validate(request: ServerRequest, validateContent: Map<String, String>?) { for ((key, value) in validateContent ?: mapOf()) { if (!request.headers().header(key).contains(value)) { throw IllegalArgumentException("Authentication failed.") } } } } class DefaultSwaggerConfig { @Bean @ConditionalOnMissingBean(value = [SwaggerValidate::class]) fun defaultSwaggerAuthentication(): SwaggerValidate { return DefaultSwaggerValidate() } }
0
null
0
0
67f534e9c62833d32ba93bfd03fbc3c1f81f52e6
870
sisyphus
MIT License
shared/data/src/commonMain/kotlin/com/moonlightbutterfly/rigplay/data/repository/GamesDataSourceImpl.kt
Dragoonov
653,808,838
false
null
package com.moonlightbutterfly.rigplay.data.repository import com.moonlightbutterfly.rigplay.data.apiKey import com.moonlightbutterfly.rigplay.data.dto.GamesDTO import com.moonlightbutterfly.rigplay.data.dto.toGames import com.moonlightbutterfly.rigplay.model.Game import com.moonlightbutterfly.rigplay.repository.GamesDataSource import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* class GamesDataSourceImpl(private val httpClient: HttpClient): GamesDataSource { override suspend fun getGames(): List<Game> { val response: GamesDTO = httpClient.get("$API_URL/games") { parameter("key", apiKey()) parameter("page", 1) parameter("page_size", 10) }.body() return response.toGames() } private companion object { private const val API_URL = "https://api.rawg.io/api" } }
0
Kotlin
0
0
d4f7417e3cd3c34bda9c28c35d3056c3aba7d85e
887
RigPlay
Apache License 2.0
shared/src/macosMain/kotlin/kmm/utils/library/Platform.macos.kt
kmm-utils
666,391,610
false
null
package kmm.utils.library import platform.Foundation.NSProcessInfo class MacOSPlatform : Platform { override val name: String = "Native Apple macOS ${NSProcessInfo.processInfo().operatingSystemVersionString}" } actual fun getPlatform(): Platform = MacOSPlatform()
0
Kotlin
0
0
2f491bde627c207336b7cfefc206a2d183ae578d
278
kmm-library-template
MIT License
app/src/main/java/com/invictus/kidsGrowthTracker/utils/composeUtils/commonUi/PageTitleBar.kt
Mr-Ajay-Singh
834,828,457
false
{"Kotlin": 339334}
package com.invictus.kidsGrowthTracker.utils.composeUtils.commonUi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import com.invictus.kidsGrowthTracker.R import com.invictus.kidsGrowthTracker.utils.composeUtils.theme.extensions.rippleClickable import com.invictus.kidsGrowthTracker.utils.displayUnitConverter.UnitConverter.DP import com.invictus.kidsGrowthTracker.utils.displayUnitConverter.UnitConverter.SP @Composable fun PageTitleBar( pageTitle: String, textButton: String = "", onTextButtonClick: (() -> Unit)? = null, onImageButtonClick: (() -> Unit)? = null, backButtonImageId: Int = R.drawable.ic_back_with_bg, imageButton: Int?= null, backgroundColor: Color = colorResource(id = R.color.inner_page_status_bar), titleTextColor: Color = colorResource(id = R.color.progress_page_section_tag), onBackClick: (() -> Unit) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(56.DP) .background(backgroundColor) .padding(16.DP) ) { Image( painter = painterResource(id = backButtonImageId), modifier = Modifier .size(40.DP) .padding(0.DP) .clickable { onBackClick.invoke() }.semantics { this.contentDescription = "Back" }, contentDescription = "Back Image" ) Text( text = pageTitle, style = MaterialTheme.typography.headlineSmall.copy( textAlign = TextAlign.Center, fontWeight = FontWeight.Bold, fontSize = 16.SP, ), maxLines = 1, overflow = TextOverflow.Ellipsis, color = titleTextColor, modifier = Modifier.weight(1f) ) if (textButton.isNotEmpty()) { Text( text = textButton, style = MaterialTheme.typography.headlineSmall.copy( textAlign = TextAlign.Center, fontWeight = FontWeight.SemiBold, fontSize = 16.SP, ), color = colorResource(id = R.color.nav_item_active), modifier = Modifier.clickable { onTextButtonClick?.invoke() }.semantics { this.contentDescription = "TextButton" } ) } else if(imageButton != null){ Icon( painter = painterResource(id = R.drawable.delete_icon), contentDescription = "Delete", tint = Color.Red, modifier = Modifier.size(24.DP) .rippleClickable { onImageButtonClick?.invoke() } ) } else { Box(modifier = Modifier.size(40.DP)) } } }
0
Kotlin
0
0
613e5e357c3cdc3138d2840eebe26f3e022483f8
3,864
App-Boilerplate
MIT License
feature/match/src/main/java/com/eshc/goonersapp/feature/match/detail/MatchScoreBoard.kt
eshc123
640,451,475
false
{"Kotlin": 479460}
package com.eshc.goonersapp.feature.match.detail import androidx.compose.foundation.layout.Arrangement 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.size import androidx.compose.foundation.lazy.LazyItemScope import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.eshc.goonersapp.core.domain.model.match.MatchDetail import com.eshc.goonersapp.core.domain.model.match.getScoreHistoryList import com.eshc.goonersapp.feature.match.model.MatchUiModel @Composable fun LazyItemScope.MatchScoreBoard( match: MatchUiModel, matchDetailList: List<MatchDetail> ) { if(match.isScorelessMatch) return Row( modifier = Modifier .fillMaxWidth() .padding( top = 20.dp ) .height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(15.dp, Alignment.CenterHorizontally), content = { MatchScoredHistory( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.End, matchScoreHistoryList = matchDetailList.getScoreHistoryList( match.homeTeamId ) ) Icon( modifier = Modifier.size(12.dp), painter = painterResource(id = com.eshc.goonersapp.core.designsystem.R.drawable.ic_ball), contentDescription = "ball" ) MatchScoredHistory( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.Start, matchScoreHistoryList = matchDetailList.getScoreHistoryList( match.awayTeamId ) ) } ) }
2
Kotlin
1
1
98e66508d91dcebe147d4b9a9857c359dd212c47
2,135
GoonersApp
Apache License 2.0
src/main/kotlin/no/nav/lydia/ia/sak/domene/spørreundersøkelse/Tema.kt
navikt
444,072,054
false
{"Kotlin": 1078963, "Python": 8913, "Shell": 1074, "Dockerfile": 207}
package no.nav.lydia.ia.sak.domene.spørreundersøkelse data class Tema( val tema: TemaInfo, val stengtForSvar: Boolean, val spørsmål: List<Spørsmål>, )
1
Kotlin
0
1
0817215f6bae9920ffd2383cd8c80c26801a3255
163
lydia-api
MIT License
app/src/main/java/br/com/chicorialabs/listadetarefas/ui/activity/MainActivity.kt
chicorasia
348,717,282
false
null
package br.com.chicorialabs.listadetarefas.ui.activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import br.com.chicorialabs.listadetarefas.R import br.com.chicorialabs.listadetarefas.adapter.ClickItemTarefaListener import br.com.chicorialabs.listadetarefas.adapter.TarefaAdapter import br.com.chicorialabs.listadetarefas.databinding.DrawerMenuBinding import br.com.chicorialabs.listadetarefas.model.Tarefa import br.com.chicorialabs.listadetarefas.ui.activity.DetalheTarefaActivity.Companion.EXTRA_TAREFA import br.com.chicorialabs.listadetarefas.viewmodel.ListaTarefasViewModel class MainActivity : AppCompatActivity(), ClickItemTarefaListener { private val listaTarefaViewModel by lazy { ListaTarefasViewModel(getInstanceSharedPreferences()) } private lateinit var binding: DrawerMenuBinding private lateinit var adapter: TarefaAdapter private val rvList: RecyclerView by lazy { binding.drawerInclude.mainRecyclerview } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DrawerMenuBinding.inflate(layoutInflater) val view = binding.root setContentView(view) inicializaToolbar() inicializaRecyclerView() inicializaTouchHelper() } private fun inicializaTouchHelper() { val swipeHandler = object : ItemTouchHelper.SimpleCallback( ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.START or ItemTouchHelper.END ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val origem = viewHolder.adapterPosition val destino = target.adapterPosition adapter.swap(origem, destino) listaTarefaViewModel.save() return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { adapter.removeAt(viewHolder.adapterPosition) listaTarefaViewModel.save() } } val itemTouchHelper = ItemTouchHelper(swipeHandler) itemTouchHelper.attachToRecyclerView(rvList) } private fun inicializaToolbar() { val drawerLayout = binding.root setSupportActionBar(binding.drawerInclude.mainToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val actionBarToggle = ActionBarDrawerToggle( this, drawerLayout, R.string.open_drawer, R.string.close_drawer ) drawerLayout.addDrawerListener(actionBarToggle) actionBarToggle.syncState() } private fun inicializaRecyclerView() { listaTarefaViewModel.listaTarefas.observe(this) { adapter = TarefaAdapter(it, this) rvList.adapter = adapter rvList.layoutManager = LinearLayoutManager(this) } } private fun updateList() { adapter.updateList() } fun getListTarefa() = listaTarefaViewModel.getListTarefa() private fun getInstanceSharedPreferences(): SharedPreferences = getSharedPreferences( "br.com.chicorialabs.listadetarefas.PREFERENCES", Context.MODE_PRIVATE ) override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.menu, menu) Log.i("listatarefas", "onCreateOptionsMenu: Inflando o menu") return true } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_item_1 -> { showToast("Clicou no item 1") true } R.id.menu_item_2 -> { showToast("Clicou no item 2") true } else -> super.onOptionsItemSelected(item) } } override fun onSupportNavigateUp(): Boolean { val actionBarToggle = ActionBarDrawerToggle( this, binding.root, R.string.open_drawer, R.string.close_drawer ) binding.root.addDrawerListener(actionBarToggle) actionBarToggle.syncState() showToast("Clicou no hamburger!") return true } override fun onItemClickListener(tarefa: Tarefa) { val intent = Intent(this, DetalheTarefaActivity::class.java) intent.putExtra(EXTRA_TAREFA, tarefa) startActivity(intent) } override fun onItemLongClickListener(tarefa: Tarefa) { // listaTarefaViewModel.remove(tarefa) // updateList() } override fun onItemCheckedChangeListener(tarefa: Tarefa, isChecked: Boolean, position: Int) { listaTarefaViewModel.atualiza(tarefa, isChecked, position) } }
0
Kotlin
0
0
42e36471a523734aa412d9361752347566fba808
5,498
bootcamp-lista-tarefas
MIT License
app/src/main/java/com/abner/base/repository/TestRepositoryActivity.kt
AbnerMing888
532,184,408
false
{"Kotlin": 74663}
package com.abner.base.repository import android.widget.Toast import com.abner.base.R import com.abner.base.databinding.ActivityRepositoryBinding import com.vip.base.activity.BaseVMActivity /** *AUTHOR:AbnerMing *DATE:2022/9/1 *INTRODUCE:Repository模拟使用,和单ViewModel使用区别是,把数据请求放到Repository里,可以实现数据 * 请求复用 */ class TestRepositoryActivity : BaseVMActivity<ActivityRepositoryBinding, TestRepositoryViewModel>(R.layout.activity_repository) { override fun initVMData() { setBarTitle("结合Repository使用") mBinding.btnLiveData.setOnClickListener { //liveData方式模拟 mViewModel.doHttpLiveData() } mBinding.btnCallBack.setOnClickListener { //回调方式模拟 mViewModel.doHttpCallback({ //成功 Toast.makeText(this, it, Toast.LENGTH_SHORT).show() }, { //失败 Toast.makeText(this, it, Toast.LENGTH_SHORT).show() }) } } /** * AUTHOR:AbnerMing * INTRODUCE:重写observeLiveData方法,监听LiveData发生的改变 */ override fun observeLiveData() { super.observeLiveData() mViewModel.getLiveData()?.observe(this) { Toast.makeText(this, it, Toast.LENGTH_SHORT).show() } } }
1
Kotlin
13
56
556b83573bc11c01144b4ece9f4d2fe4425ad465
1,282
VipBase
Apache License 2.0
idea/tests/testData/quickfix/deprecatedSymbolUsage/classUsages/constructorUsageWithTypeArgument3.kt
JetBrains
278,369,660
false
null
// "Replace with 'NewClass'" "true" package ppp @Deprecated("", ReplaceWith("NewClass")) class OldClass<T, V> class NewClass fun foo() { <caret>OldClass<Int, String>() } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
271
intellij-kotlin
Apache License 2.0
app/src/main/java/com/nexus/farmap/data/repository/GraphImpl.kt
hanzamzamy
737,138,438
false
{"Kotlin": 137282}
package com.nexus.farmap.data.repository import com.nexus.farmap.data.App import com.nexus.farmap.data.model.TreeNodeDto import com.nexus.farmap.domain.repository.GraphRepository import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.domain.use_cases.convert import com.nexus.farmap.domain.use_cases.opposite import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toOldQuaternion import io.github.sceneview.math.toVector3 class GraphImpl : GraphRepository { private val dao = App.instance?.getDatabase()?.graphDao!! override suspend fun getNodes(): List<TreeNodeDto> { return dao.getNodes() ?: listOf() } override suspend fun insertNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) { val transNodes = nodes.toMutableList() val undoTranslocation = translocation * -1f val undoQuaternion = rotation.opposite() dao.insertNodes(transNodes.map { node -> when (node) { is TreeNode.Entry -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuaternion, pivotPosition ), forwardVector = node.forwardVector.convert(undoQuaternion) ) } is TreeNode.Path -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuaternion, pivotPosition ) ) } } }) } override suspend fun deleteNodes(nodes: List<TreeNode>) { dao.deleteNodes(nodes.map { node -> TreeNodeDto.fromTreeNode(node) }) } override suspend fun updateNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) { val transNodes = nodes.toMutableList() val undoTranslocation = translocation * -1f val undoQuarterion = rotation.opposite() dao.updateNodes(transNodes.map { node -> when (node) { is TreeNode.Entry -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuarterion, pivotPosition ), forwardVector = node.forwardVector.convert(undoQuarterion) ) } is TreeNode.Path -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuarterion, pivotPosition ) ) } } }) } override suspend fun clearNodes() { dao.clearNodes() } private fun undoPositionConvert( position: Float3, translocation: Float3, quaternion: Quaternion, pivotPosition: Float3 ): Float3 { return (com.google.ar.sceneform.math.Quaternion.rotateVector( quaternion.toOldQuaternion(), (position - pivotPosition - translocation).toVector3() ).toFloat3() + pivotPosition) } }
0
Kotlin
0
0
350aa90909444276a0af79e4ed962915b88cf4dd
3,493
nexus-farmap
Apache License 2.0
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/observation/ObservationOperationResponse.kt
suomenriistakeskus
78,840,058
false
{"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1}
package fi.riista.common.domain.observation import fi.riista.common.domain.observation.model.CommonObservation sealed class ObservationOperationResponse { /** * The operation succeeded completely i.e. observation was saved to database * and possible network operation succeeded as well (if required to be performed). */ data class Success(val observation: CommonObservation): ObservationOperationResponse() /** * The observation was saved to database but the following network operation failed either * because of a network error (not reachable) or with given [statusCode] * * The optionally produced [errorMessage] may be useful in debugging the situation but * it is not intended for user to see. */ data class NetworkFailure(val statusCode: Int?, val errorMessage: String?): ObservationOperationResponse() /** * The operation failed i.e. observation was not saved to database. * * The optionally produced [errorMessage] may be useful in debugging the situation but * it is not intended for user to see. */ data class SaveFailure(val errorMessage: String?): ObservationOperationResponse() /** * The observation data was invalid or some other precondition failed. */ data class Error(val errorMessage: String?): ObservationOperationResponse() } data class SaveObservationResponse( val databaseSaveResponse: ObservationOperationResponse, val networkSaveResponse: ObservationOperationResponse? = null, ) { val errorMessage: String? get() { val databaseErrorMessage = when (databaseSaveResponse) { is ObservationOperationResponse.Error -> databaseSaveResponse.errorMessage is ObservationOperationResponse.NetworkFailure -> databaseSaveResponse.errorMessage is ObservationOperationResponse.SaveFailure -> databaseSaveResponse.errorMessage is ObservationOperationResponse.Success -> null } val networkErrorMessage = when (networkSaveResponse) { is ObservationOperationResponse.Error -> networkSaveResponse.errorMessage is ObservationOperationResponse.NetworkFailure -> networkSaveResponse.errorMessage is ObservationOperationResponse.SaveFailure -> networkSaveResponse.errorMessage is ObservationOperationResponse.Success -> null null -> null } if (databaseErrorMessage == null && networkErrorMessage == null) { return null } return "databaseErrorMessage=$databaseErrorMessage, networkErrorMessage=$networkErrorMessage" } }
0
Kotlin
0
3
23645d1abe61c68d649b6d0ca1d16556aa8ffa16
2,710
oma-riista-android
MIT License
app/src/main/java/br/com/dnassuncao/movieapp/features/movie_detail/domain/repository/MovieDetailsRepository.kt
dnassuncao
765,808,513
false
{"Kotlin": 67666}
package br.com.dnassuncao.movieapp.features.movie_detail.domain.repository import androidx.paging.PagingConfig import androidx.paging.PagingData import br.com.dnassuncao.movieapp.features.movie_popular.domain.Movie import br.com.dnassuncao.movieapp.features.movie_detail.domain.MovieDetails import kotlinx.coroutines.flow.Flow interface MovieDetailsRepository { suspend fun getMovieDetails(movieId: Int): MovieDetails suspend fun getMoviesSimilar(movieId: Int, pagingConfig: PagingConfig): Flow<PagingData<Movie>> }
0
Kotlin
0
0
c1728e432704fdd32d410a7ee89c898538138f52
526
movies-compose
MIT License
src/main/java/com/pikolive/module/lifecycle/LifecycleCallbacks.kt
InternetED
299,563,216
false
null
package com.pikolive.module.lifecycle import android.app.Activity import android.app.Application import java.lang.ref.WeakReference import java.util.* /** * Creator: ED * Date: 2020/4/21 2:57 PM * Mail: <EMAIL> * * 負責管理所有此應用的 Activities,將之存於 activityStack * **/ interface LifecycleCallbacks : Application.ActivityLifecycleCallbacks { val activityStack: Stack<WeakReference<Activity>> fun bindApplication(application: Application) fun unBindApplication(application: Application) }
0
Kotlin
0
0
19db240c66c86ab7e342c00fe397aa121c998bcc
503
Thrid_Part_Plugin
Apache License 2.0
android/src/main/java/com/reactnativesharingdata/SharingDataModule.kt
treesen
318,053,607
false
{"Java": 13466, "Objective-C": 6630, "Ruby": 4171, "Kotlin": 3143, "TypeScript": 2215, "JavaScript": 1483, "C": 103, "Swift": 63}
package com.reactnativesharingdata import android.net.Uri import android.content.ContentValues import com.facebook.react.bridge.* class SharingDataModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { var baseReactContext = reactContext override fun getName(): String { return "SharingData" } // Example method // See https://facebook.github.io/react-native/docs/native-modules-android @ReactMethod fun multiply(a: Int, b: Int, promise: Promise) { promise.resolve(a * b) } @ReactMethod fun checkContentExist(url: String, promise: Promise) { var data = this.query(url, null, null, null, Constants.Content.CONTENT_KEY) promise.resolve(data !== null) } @ReactMethod fun queryAllData(url: String, promise: Promise) { var data = this.query(url, null, null, null, Constants.Content.CONTENT_KEY) promise.resolve(data) } @ReactMethod fun queryDataByKey(url: String, key: String?, promise: Promise) { var data = this.query(url, null, Constants.Content.CONTENT_KEY + " = '$key'", null, Constants.Content.CONTENT_KEY) promise.resolve(data) } /* * return map to keep key unique * */ private fun query(url: String, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String ): WritableMap? { var uri = Uri.parse(url) var c = baseReactContext.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) if (c != null && c.count > 0 && c.moveToFirst()) { var data = Arguments.createMap() do { var key = c.getString(c.getColumnIndex(Constants.Content.CONTENT_KEY)) var value = c.getString(c.getColumnIndex(Constants.Content.CONTENT_VALUE)) data.putString(key, value) } while (c.moveToNext()); return data } return null } @ReactMethod fun insertData(url: String, key: String, value: String, promise: Promise) { var CONTENT_URI = Uri.parse(url) var values = ContentValues() values.put(Constants.Content.CONTENT_KEY, key) values.put(Constants.Content.CONTENT_VALUE, value) baseReactContext.contentResolver.insert(CONTENT_URI, values) var mUri = baseReactContext.contentResolver.insert(CONTENT_URI, values) promise.resolve(mUri != null) } }
1
Java
1
1
0e1b6cb1466680c631220854d9d4ad4c96a7c7d2
2,433
react-native-sharing-data
MIT License
src/main/kotlin/no/nav/syfo/sfs/Person.kt
navikt
198,372,403
false
{"Kotlin": 82833, "Dockerfile": 276}
package no.nav.syfo.sfs data class Person( val erSykmelder: Boolean, val navn: String, )
0
Kotlin
2
0
3d5b34928e6664cd189b1dadaca0361fe4837bce
98
syfohelsenettproxy
MIT License
compose/src/main/java/com/example/compose/ComposeFlowActivity.kt
vshpyrka
784,094,872
false
{"Kotlin": 213814}
package com.example.compose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ContextualFlowRow import androidx.compose.foundation.layout.ContextualFlowRowOverflow import androidx.compose.foundation.layout.ContextualFlowRowOverflowScope import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowColumn import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.width 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.material3.AssistChip import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.datasource.LoremIpsum import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.compose.ui.theme.AndroidPlaygroundTheme class ComposeFlowActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AndroidPlaygroundTheme { Column { FlowExample() ContextualFlow() WeightFlowExample() RandomWeightFlowExample() } } } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun FlowExample() { FlowRow( modifier = Modifier.padding(8.dp), horizontalArrangement = Arrangement.SpaceAround, verticalArrangement = Arrangement.Center, maxItemsInEachRow = 3, ) { List(10) { LoremIpsum((1..3).random()).values.joinToString() }.forEach { AssistChip( modifier = Modifier.align(Alignment.CenterVertically), onClick = {}, label = { Text(it) } ) } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun ContextualFlow() { val totalCount = 40 var maxLines by remember { mutableIntStateOf(2) } val moreOrCollapseIndicator = @Composable { scope: ContextualFlowRowOverflowScope -> val remainingItems = totalCount - scope.shownItemCount AssistChip( onClick = { if (remainingItems == 0) { maxLines = 2 } else { maxLines += 5 } }, label = { Text( if (remainingItems == 0) "Less" else "+$remainingItems" ) } ) } ContextualFlowRow( modifier = Modifier .safeDrawingPadding() .fillMaxWidth(1f) .padding(16.dp) .wrapContentHeight(align = Alignment.Top) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), maxLines = maxLines, overflow = ContextualFlowRowOverflow.expandOrCollapseIndicator( minRowsToShowCollapse = 4, expandIndicator = moreOrCollapseIndicator, collapseIndicator = moreOrCollapseIndicator ), itemCount = totalCount ) { index -> AssistChip( onClick = {}, label = { Text("Item $index") } ) } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun WeightFlowExample() { AndroidPlaygroundTheme { val rows = 3 val columns = 3 FlowRow( modifier = Modifier.padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), maxItemsInEachRow = rows ) { val itemModifier = Modifier .padding(4.dp) .weight(1f) .aspectRatio(1f) .clip(RoundedCornerShape(8.dp)) .background(Color.Magenta) repeat(rows * columns) { Spacer(modifier = itemModifier) } } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun RandomWeightFlowExample() { FlowRow( modifier = Modifier.padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), maxItemsInEachRow = 2, ) { val itemModifier = Modifier .padding(4.dp) .height(80.dp) .clip(RoundedCornerShape(8.dp)) .background(Color.Green) repeat(6) { item -> if ((item + 1) % 3 == 0) { Box( modifier = itemModifier.fillMaxWidth() ) } else { Box( modifier = itemModifier.weight(0.5f) ) } } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun FractionalExample() { FlowRow( modifier = Modifier.padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), maxItemsInEachRow = 3, ) { val itemModifier = Modifier .clip(RoundedCornerShape(8.dp)) .height(300.dp) Box( itemModifier .width(60.dp) .background(Color.Red) ) Box( itemModifier .fillMaxWidth(0.7f) .background(Color.Green) ) Box( itemModifier .weight(1f) .background(Color.Blue) ) } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun FillMaxWidthFlowExample() { AndroidPlaygroundTheme { FlowColumn( Modifier .padding(20.dp) .fillMaxHeight() .fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), maxItemsInEachColumn = 5, ) { List(10) { LoremIpsum((1..3).random()).values.joinToString() }.forEach { Box( Modifier .fillMaxColumnWidth() .border(1.dp, Color.DarkGray, RoundedCornerShape(8.dp)) .padding(8.dp) ) { Text( text = it, fontSize = 18.sp, modifier = Modifier.padding(3.dp) ) } } } } } @Preview(showBackground = true) @Composable private fun FlowExamplePreview() { AndroidPlaygroundTheme { FlowExample() } } @Preview(showBackground = true) @Composable private fun ContextualFlowPreview() { AndroidPlaygroundTheme { ContextualFlow() } } @Preview(showBackground = true) @Composable private fun WeightFlowPreview() { AndroidPlaygroundTheme { WeightFlowExample() } } @Preview(showBackground = true) @Composable private fun RandomWeightFlowPreview() { AndroidPlaygroundTheme { RandomWeightFlowExample() } } @Preview(showBackground = true) @Composable private fun FractionalPreview() { AndroidPlaygroundTheme { FractionalExample() } } @Preview(showBackground = true) @Composable private fun FillMaxWidthFlowPreview() { AndroidPlaygroundTheme { FillMaxWidthFlowExample() } }
0
Kotlin
0
0
625b49f16bbef4c4436d6ea760442107fd39e751
8,628
android-compose-playground
Apache License 2.0
plugin/src/main/kotlin/ru/astrainteractive/aspekt/adminprivate/controller/di/AdminPrivateControllerDependencies.kt
Astra-Interactive
588,890,842
false
{"Kotlin": 144242}
package ru.astrainteractive.aspekt.adminprivate.controller.di import ru.astrainteractive.aspekt.adminprivate.data.AdminPrivateRepository import ru.astrainteractive.aspekt.adminprivate.data.AdminPrivateRepositoryImpl import ru.astrainteractive.astralibs.filemanager.FileManager import ru.astrainteractive.klibs.kdi.Module import ru.astrainteractive.klibs.kdi.Provider import ru.astrainteractive.klibs.kdi.getValue import ru.astrainteractive.klibs.mikro.core.dispatchers.KotlinDispatchers interface AdminPrivateControllerDependencies : Module { val repository: AdminPrivateRepository val dispatchers: KotlinDispatchers class Default( adminChunksYml: Provider<FileManager>, dispatchers: Provider<KotlinDispatchers> ) : AdminPrivateControllerDependencies { override val repository: AdminPrivateRepository by Provider { AdminPrivateRepositoryImpl( fileManager = adminChunksYml.provide(), dispatchers = dispatchers.provide() ) } override val dispatchers: KotlinDispatchers by dispatchers } }
0
Kotlin
0
0
584428a90c0e1c32479e7b26bcd96e7505f9e657
1,105
AspeKt
MIT License
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/presentation/mnemonic/backup/BackupMnemonicViewModel.kt
novasamatech
415,834,480
false
{"Kotlin": 7667438, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_account_impl.presentation.mnemonic.backup import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.novafoundation.nova.common.base.BaseViewModel import io.novafoundation.nova.common.resources.ResourceManager import io.novafoundation.nova.common.utils.Event import io.novafoundation.nova.common.utils.flowOf import io.novafoundation.nova.common.utils.inBackground import io.novafoundation.nova.common.utils.sendEvent import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountInteractor import io.novafoundation.nova.feature_account_impl.R import io.novafoundation.nova.feature_account_impl.domain.account.advancedEncryption.AdvancedEncryptionInteractor import io.novafoundation.nova.feature_account_impl.domain.account.export.mnemonic.ExportMnemonicInteractor import io.novafoundation.nova.feature_account_impl.presentation.AccountRouter import io.novafoundation.nova.feature_account_impl.presentation.AdvancedEncryptionRequester import io.novafoundation.nova.feature_account_impl.presentation.account.advancedEncryption.AdvancedEncryptionPayload import io.novafoundation.nova.feature_account_impl.presentation.common.mnemonic.spacedWords import io.novafoundation.nova.feature_account_impl.presentation.lastResponseOrDefault import io.novafoundation.nova.feature_account_impl.presentation.mnemonic.confirm.ConfirmMnemonicPayload import io.novafoundation.nova.feature_account_impl.presentation.mnemonic.confirm.ConfirmMnemonicPayload.CreateExtras import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch class BackupMnemonicViewModel( private val interactor: AccountInteractor, private val exportMnemonicInteractor: ExportMnemonicInteractor, private val router: AccountRouter, private val payload: BackupMnemonicPayload, private val advancedEncryptionInteractor: AdvancedEncryptionInteractor, private val resourceManager: ResourceManager, private val advancedEncryptionRequester: AdvancedEncryptionRequester ) : BaseViewModel() { private val mnemonicFlow = flowOf { when (payload) { is BackupMnemonicPayload.Confirm -> exportMnemonicInteractor.getMnemonic(payload.metaAccountId, payload.chainId) is BackupMnemonicPayload.Create -> interactor.generateMnemonic() } } .inBackground() .share() private val _showMnemonicWarningDialog = MutableLiveData<Event<Unit>>() val showMnemonicWarningDialog: LiveData<Event<Unit>> = _showMnemonicWarningDialog private val warningAcceptedFlow = MutableStateFlow(false) val mnemonicDisplay = combine( mnemonicFlow, warningAcceptedFlow ) { mnemonic, warningAccepted -> mnemonic.spacedWords().takeIf { warningAccepted } } val continueText = flowOf { val stringRes = when (payload) { is BackupMnemonicPayload.Confirm -> R.string.account_confirm_mnemonic is BackupMnemonicPayload.Create -> R.string.common_continue } resourceManager.getString(stringRes) } .inBackground() .share() init { _showMnemonicWarningDialog.sendEvent() } fun homeButtonClicked() { router.back() } fun optionsClicked() { val advancedEncryptionPayload = when (payload) { is BackupMnemonicPayload.Confirm -> AdvancedEncryptionPayload.View(payload.metaAccountId, payload.chainId) is BackupMnemonicPayload.Create -> AdvancedEncryptionPayload.Change(payload.addAccountPayload) } advancedEncryptionRequester.openRequest(advancedEncryptionPayload) } fun warningAccepted() { warningAcceptedFlow.value = true } fun warningDeclined() { router.back() } fun nextClicked() = launch { val createExtras = (payload as? BackupMnemonicPayload.Create)?.let { val advancedEncryptionResponse = advancedEncryptionRequester.lastResponseOrDefault(it.addAccountPayload, advancedEncryptionInteractor) CreateExtras( accountName = it.newWalletName, addAccountPayload = it.addAccountPayload, advancedEncryptionPayload = advancedEncryptionResponse ) } val payload = ConfirmMnemonicPayload( mnemonic = mnemonicFlow.first().wordList, createExtras = createExtras ) router.openConfirmMnemonicOnCreate(payload) } }
13
Kotlin
6
9
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
4,571
nova-wallet-android
Apache License 2.0
app/src/main/java/com/hudson/customview/diagramview/percentview/type/sector/entity/indicator/CakeIndicator.kt
HudsonAndroid
323,793,913
false
null
package com.hudson.customview.diagramview.percentview.type.sector.entity.indicator import android.graphics.* import com.hudson.customview.diagramview.percentview.type.sector.entity.indicator.IIndicator.Companion.COLOR_TIPS import com.hudson.customview.diagramview.percentview.type.sector.entity.indicator.IIndicator.Companion.MAX_CAKE_WIDTH import com.hudson.customview.diagramview.percentview.type.sector.entity.indicator.IIndicator.Companion.RATE_CAKE_TEXT_SPACE import com.hudson.customview.diagramview.percentview.type.sector.entity.indicator.IIndicator.Companion.RATE_COLOR_CAKE import com.hudson.customview.diagramview.percentview.type.sector.entity.percent.BasePercentEntity import com.hudson.customview.diagramview.percentview.type.sector.entity.percent.IPercentageEntity import com.hudson.customview.diagramview.percentview.type.sector.entity.percent.LineShadeCreator import com.hudson.customview.diagramview.percentview.type.sector.percentinfo.PercentInfo /** * 普通的块状颜色指示器 * Created by Hudson on 2020/12/29. */ open class CakeIndicator<T: PercentInfo>(percentageEntity: IPercentageEntity<T>) : AbsIndicator<T>(percentageEntity) { override fun drawIndicator(canvas: Canvas, paint: Paint) { if (mRange != null) { val extendInfo: PercentInfo = mPercentageEntity.getExtendInfo() val drawTip: String = extendInfo.name + ":" + (extendInfo.percentage * 100 + 0.5f).toInt() + "%" paint.color = extendInfo.color var saveId = -1 if (mPercentageEntity is BasePercentEntity && (mPercentageEntity as BasePercentEntity).isLineShadeShow() ) { val lineShadePath: Path = LineShadeCreator.lineShadePath!! if (lineShadePath != null) { saveId = canvas.save() canvas.clipPath(lineShadePath, Region.Op.DIFFERENCE) } } val drawX = drawTypeCake(mRange!!,canvas, paint) if (saveId != -1) { canvas.restore() } drawTips(mRange!!, canvas, paint, drawTip, drawX + mRange!!.width() * RATE_CAKE_TEXT_SPACE) } } open fun drawTypeCake( range: RectF, canvas: Canvas, paint: Paint ): Float { val cakeHeight: Float = range.height() * RATE_COLOR_CAKE val top: Float = (range.height() - cakeHeight) / 2 + range.top var cakeWidth: Float = range.width() * RATE_COLOR_CAKE cakeWidth = if (cakeWidth > MAX_CAKE_WIDTH) MAX_CAKE_WIDTH else cakeWidth val right: Float = range.left + cakeWidth canvas.drawRect(range.left, top, right, top + cakeHeight, paint) return right } private fun drawTips( range: RectF, canvas: Canvas, paint: Paint, str: String, drawX: Float ) { paint.color = COLOR_TIPS val fontMetrics = paint.fontMetrics val baseLine = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom canvas.drawText(str, drawX, range.height() / 2 + range.top + baseLine, paint) } }
0
Kotlin
0
0
d633858654b382dc7765e7ffdcc75dbfb2446d41
3,123
CustomViewSet
Apache License 2.0
skellig-test-step-processing/src/test/kotlin/org/skellig/teststep/processing/invalid/InvalidCustomFunctions.kt
skellig-framework
263,021,995
false
{"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165}
package org.skellig.teststep.processing.invalid class InvalidCustomFunctions(val randomParam: Any) { @org.skellig.teststep.processing.value.function.Function fun runSomething() { } }
8
Kotlin
0
3
ed375268b0e444f1928f22f4ac27603e9d1fb66b
196
skellig-core
Apache License 2.0
buildSrc/src/main/kotlin/ClientTools.kt
PizzaCrust
249,545,446
false
null
import org.apache.commons.exec.CommandLine import org.apache.commons.exec.DefaultExecutor import org.apache.commons.io.FileUtils import org.eclipse.jgit.api.Git import java.io.File private fun File.exec(cmd: String) { val exec = DefaultExecutor() exec.workingDirectory = this exec.execute(CommandLine.parse(cmd)) } private fun File.extractFrom(str: String) { val target = File(this, str) FileUtils.copyInputStreamToFile(Thread.currentThread().contextClassLoader.getResourceAsStream(str), target) } private fun File.build(runtime: String): File { exec("dotnet publish -r $runtime -c Release /p:PublishSingleFile=true /p:PublishTrimmed=true") return File(this, "bin/Release/netcoreapp3.1/$runtime/publish/") } private fun File.move(dest: File) { this.listFiles()?.forEach { FileUtils.moveFileToDirectory(it, dest, true) } } private fun File.deleteAll() { this.listFiles()?.forEach { if (it.isDirectory) { it.deleteAll() } else { it.delete() } } delete() } /** * NOT INTENDED FOR PRODUCTION */ fun build(root: File) { val tmp = File(root, "build/nativeTmp").apply { if (exists()) deleteAll() mkdir() } println("Cloning latest FortniteReplayDecompressor repository") Git .cloneRepository() .setURI("https://github.com/Shiqan/FortniteReplayDecompressor.git") .setDirectory(File(tmp, "FortniteReplayDecompressor")) .call().apply { repository.close() close() } println("Building FortniteReplayDecompressor") File(tmp, "FortniteReplayDecompressor/src/FortniteReplayReader").extractFrom("FRR.csproj") File(tmp, "FortniteReplayDecompressor/src/FortniteReplayReader").exec("dotnet build FRR.csproj") println("Transpiling models to kotlin") val frrModels = File(tmp, "FortniteReplayDecompressor/src/FortniteReplayReader/Models") val unrealCoreModels = File(tmp, "FortniteReplayDecompressor/src/Unreal.Core/Models") File(root, "ReplayModel.kt").writeText(generateKotlinDirSrc(listOf(frrModels, unrealCoreModels)).replace ("ActorGuid", "NetworkGUID")) println("Extracting client") val replayClient = File(tmp, "ReplayClient") replayClient.mkdir() replayClient.extractFrom("Program.cs") replayClient.extractFrom("ReplayClient.csproj") val targetBuild = File(root, "src/commonMain/resources") println("Building windows client") replayClient.build("win-x64").move(File(targetBuild, "win")) println("Building linux client") replayClient.build("linux-x64").move(File(targetBuild, "linux")) println("Building mac os client") replayClient.build("osx-x64").move(File(targetBuild, "mac")) tmp.deleteAll() }
1
Kotlin
0
0
ca9d567b86766abee3482041541a729f1349015f
2,815
NativeReplayReader
MIT License
sphereon-kmp-cbor/src/commonMain/kotlin/com/sphereon/cbor/CborNumber.kt
Sphereon-Opensource
832,677,457
false
{"Kotlin": 413127, "JavaScript": 3918}
package com.sphereon.cbor import com.sphereon.kmp.bigIntFromNumber abstract class CborNumber<Type : Number>(value: Type, cddl: CDDLType) : CborItem<Type>(value, cddl) fun Long.toCborIntFromLong() = run { if (this >= 0) { CborUInt(this.bigIntFromNumber()) } else { CborNInt((-this).bigIntFromNumber()) } }
0
Kotlin
0
1
db8cd778a8320f8278ef47fd332cffed66f75e1d
335
mDL-mdoc-multiplatform
Apache License 2.0
src/test/kotlin/org/rust/ide/annotator/RsAtLeastOneTraitForObjectTypeTest.kt
intellij-rust
42,619,487
false
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator class RsAtLeastOneTraitForObjectTypeTest : RsAnnotatorTestBase(RsSyntaxErrorsAnnotator::class) { fun `test E0224 lifetime without any traits`() = checkByText(""" type Foo = <error descr="At least one trait is required for an object type [E0224]">dyn 'static</error>; """) fun `test E0224 lifetime with one trait`() = checkByText(""" type Foo = dyn 'static + Copy; """) fun `test E0224 lifetime with many traits`() = checkByText(""" type Foo = dyn 'static + Copy + Send; """) fun `test E0224 only trait`() = checkByText(""" type Foo = Copy; """) }
1,841
Kotlin
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
753
intellij-rust
MIT License
core/designsystem/src/main/java/com/greenie/app/core/designsystem/icon/AppIcons.kt
Greenie-crew
645,248,480
false
null
package com.greenie.app.core.designsystem.icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBackIos import androidx.compose.material.icons.outlined.ArrowForwardIos import androidx.compose.material.icons.rounded.Pause import androidx.compose.material.icons.rounded.PlayArrow object AppIcons { val ArrowBack = Icons.Outlined.ArrowBackIos val ArrowForward = Icons.Outlined.ArrowForwardIos val Play = Icons.Rounded.PlayArrow val Pause = Icons.Rounded.Pause }
0
Kotlin
2
2
85b83cc81982acf90c7af01d1e9fe0cfa9efc382
525
greenie-android
The Unlicense
src/test/kotlin/no/nav/su/journal/EmbeddedKafka.kt
navikt
242,120,692
false
null
package no.nav.su.journal import io.ktor.util.KtorExperimentalAPI import no.nav.common.KafkaEnvironment import no.nav.su.meldinger.kafka.Topics.SØKNAD_TOPIC import org.apache.kafka.clients.CommonClientConfigs import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.config.SaslConfigs import org.apache.kafka.common.serialization.StringDeserializer import org.apache.kafka.common.serialization.StringSerializer import java.util.* @KtorExperimentalAPI class EmbeddedKafka { companion object { val kafkaInstance = KafkaEnvironment( autoStart = false, noOfBrokers = 1, topicInfos = listOf(KafkaEnvironment.TopicInfo(name = SØKNAD_TOPIC, partitions = 1)), withSchemaRegistry = false, withSecurity = false, brokerConfigOverrides = Properties().apply { this["auto.leader.rebalance.enable"] = "false" this["group.initial.rebalance.delay.ms"] = "1" //Avoid waiting for new consumers to join group before first rebalancing (default 3000ms) } ).also { it.start() } val kafkaProducer = KafkaProducer(producerProperties(), StringSerializer(), StringSerializer()) private fun producerProperties(): MutableMap<String, Any>? { return HashMap<String, Any>().apply { put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaInstance.brokersURL) put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "PLAINTEXT") put(SaslConfigs.SASL_MECHANISM, "PLAIN") put(ProducerConfig.ACKS_CONFIG, "all") put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1") } } val kafkaConsumer = KafkaConsumer( consumerProperties(), StringDeserializer(), StringDeserializer()).also { it.subscribe(listOf(SØKNAD_TOPIC)) } private fun consumerProperties(): MutableMap<String, Any>? { return HashMap<String, Any>().apply { put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaInstance.brokersURL) put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "PLAINTEXT") put(SaslConfigs.SASL_MECHANISM, "PLAIN") put(ConsumerConfig.GROUP_ID_CONFIG, "test") put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest") } } } }
0
Kotlin
0
0
f6bb21b0fc22e9922c3ef269c3822c2cbc5ae56e
2,692
su-journal
MIT License
src/Day04.kt
ezeferex
575,216,631
false
null
fun String.getSections() = this.split(",") .map { it.split("-").let { section -> Pair(section[0].toInt(), section[1].toInt()) }} .let { pairSection -> Pair(pairSection[0], pairSection[1]) } fun main() { fun part1() = readInput("04").split("\n") .count { val sections = it.getSections() (sections.second.first in sections.first.first..sections.first.second && sections.second.second in sections.first.first..sections.first.second) || (sections.first.first in sections.second.first..sections.second.second && sections.first.second in sections.second.first..sections.second.second) } fun part2() = readInput("04").split("\n") .count { val sections = it.getSections() !(sections.second.first > sections.first.second || sections.first.first > sections.second.second) } println("Part 1: " + part1()) println("Part 2: " + part2()) }
0
Kotlin
0
0
f06f8441ad0d7d4efb9ae449c9f7848a50f3f57c
984
advent-of-code-2022
Apache License 2.0
calendar/src/test/java/com/github/primodev23/calendar/models/MonthTest.kt
PrimoDev23
780,809,219
false
{"Kotlin": 59493}
package com.github.primodev23.calendar.models import org.junit.Assert.assertEquals import org.junit.Test import java.time.DayOfWeek import java.time.LocalDate class MonthTest { private val testDate = LocalDate.of(2024, 2, 1) @Test fun days_hasAllDaysOfMonth() { val month = Month(testDate) val rangeStart = Day( date = LocalDate.of(2024, 1, 29), month = month ) val rangeEnd = Day( date = LocalDate.of(2024, 3, 3), month = month ) val range = rangeStart..rangeEnd assertEquals(range.toList(), month.days) } @Test fun days_calculateWithStartOfWeek() { DayOfWeek.entries.forEach { val month = Month( date = testDate, startOfWeek = it ) assertEquals(month.days.first().date.dayOfWeek, it) } } @Test fun startDate() { val month = Month(date = LocalDate.of(2024, 4, 16)) assertEquals(month.startDate, LocalDate.of(2024, 4, 1)) } }
0
Kotlin
0
0
ce7dcc673760e08bc79500953a1f41cbbe794b62
1,080
Calendar
Apache License 2.0
convert/src/main/kotlin/com/github/zeldigas/text2confl/convert/asciidoc/AsciidocFileConverter.kt
zeldigas
425,511,098
false
null
package com.github.zeldigas.text2confl.convert.asciidoc import com.github.zeldigas.text2confl.convert.* import com.github.zeldigas.text2confl.convert.confluence.ReferenceProvider import com.vladsch.flexmark.util.sequence.Escaping import org.asciidoctor.ast.Document import java.nio.file.Path class AsciidocFileConverter(private val asciidocParser: AsciidocParser, private val workdirRoot: Path) : FileConverter { constructor(config: AsciidoctorConfiguration): this(AsciidocParser(config), config.workdir) override fun readHeader(file: Path, context: HeaderReadingContext): PageHeader { val document = asciidocParser.parseDocumentHeader(file) return toHeader(file, document, context.titleTransformer) } private fun toHeader(file: Path, document: Document, titleTransformer: (Path, String) -> String): PageHeader { return PageHeader(titleTransformer(file, computeTitle(document, file)), document.attributes) } private fun computeTitle(doc: Document, file: Path): String = doc.attributes["title"]?.toString() ?: documentTitle(doc) ?: file.toFile().nameWithoutExtension private fun documentTitle(doc: Document): String? { val title = doc.structuredDoctitle?.combined ?: return null return Escaping.unescapeHtml(doc.attributes.entries.fold(title) { current, (key, value) -> current.replace("{$key}", value.toString()) }) } override fun convert(file: Path, context: ConvertingContext): PageContent { val workdir = fileWorkdir(file, context.referenceProvider) val attachmentsRegistry = AttachmentsRegistry() val document = try { asciidocParser.parseDocument(file, createAttributes(file, context, attachmentsRegistry, workdir)) }catch (ex: Exception) { throw ConversionFailedException(file, "Document parsing failed", ex) } val body = try { document.convert() } catch (ex: Exception) { throw ConversionFailedException(file, "Document conversion failed", ex) } return PageContent( toHeader(file, document, context.titleTransformer), body, attachmentsRegistry.collectedAttachments.values.toList() ) } private fun fileWorkdir(file: Path, referenceProvider: ReferenceProvider): Path { return workdirRoot.resolve(referenceProvider.pathFromDocsRoot(file)) } private fun createAttributes(file: Path, context: ConvertingContext, registry: AttachmentsRegistry, workdir: Path) = AsciidocRenderingParameters( context.languageMapper, AsciidocReferenceProvider(file, context.referenceProvider), context.autotextFor(file), context.conversionParameters.addAutogeneratedNote, context.targetSpace, AsciidocAttachmentCollector(file, AttachmentCollector(context.referenceProvider, registry), workdir), extraAttrs = mapOf( "outdir" to workdir.toString(), "imagesoutdir" to workdir.toString() ) ) }
7
Kotlin
0
6
af61a5facb45aa6a08846314684c2f4d6d68b2be
3,046
text2confl
Apache License 2.0
convert/src/main/kotlin/com/github/zeldigas/text2confl/convert/asciidoc/AsciidocFileConverter.kt
zeldigas
425,511,098
false
null
package com.github.zeldigas.text2confl.convert.asciidoc import com.github.zeldigas.text2confl.convert.* import com.github.zeldigas.text2confl.convert.confluence.ReferenceProvider import com.vladsch.flexmark.util.sequence.Escaping import org.asciidoctor.ast.Document import java.nio.file.Path class AsciidocFileConverter(private val asciidocParser: AsciidocParser, private val workdirRoot: Path) : FileConverter { constructor(config: AsciidoctorConfiguration): this(AsciidocParser(config), config.workdir) override fun readHeader(file: Path, context: HeaderReadingContext): PageHeader { val document = asciidocParser.parseDocumentHeader(file) return toHeader(file, document, context.titleTransformer) } private fun toHeader(file: Path, document: Document, titleTransformer: (Path, String) -> String): PageHeader { return PageHeader(titleTransformer(file, computeTitle(document, file)), document.attributes) } private fun computeTitle(doc: Document, file: Path): String = doc.attributes["title"]?.toString() ?: documentTitle(doc) ?: file.toFile().nameWithoutExtension private fun documentTitle(doc: Document): String? { val title = doc.structuredDoctitle?.combined ?: return null return Escaping.unescapeHtml(doc.attributes.entries.fold(title) { current, (key, value) -> current.replace("{$key}", value.toString()) }) } override fun convert(file: Path, context: ConvertingContext): PageContent { val workdir = fileWorkdir(file, context.referenceProvider) val attachmentsRegistry = AttachmentsRegistry() val document = try { asciidocParser.parseDocument(file, createAttributes(file, context, attachmentsRegistry, workdir)) }catch (ex: Exception) { throw ConversionFailedException(file, "Document parsing failed", ex) } val body = try { document.convert() } catch (ex: Exception) { throw ConversionFailedException(file, "Document conversion failed", ex) } return PageContent( toHeader(file, document, context.titleTransformer), body, attachmentsRegistry.collectedAttachments.values.toList() ) } private fun fileWorkdir(file: Path, referenceProvider: ReferenceProvider): Path { return workdirRoot.resolve(referenceProvider.pathFromDocsRoot(file)) } private fun createAttributes(file: Path, context: ConvertingContext, registry: AttachmentsRegistry, workdir: Path) = AsciidocRenderingParameters( context.languageMapper, AsciidocReferenceProvider(file, context.referenceProvider), context.autotextFor(file), context.conversionParameters.addAutogeneratedNote, context.targetSpace, AsciidocAttachmentCollector(file, AttachmentCollector(context.referenceProvider, registry), workdir), extraAttrs = mapOf( "outdir" to workdir.toString(), "imagesoutdir" to workdir.toString() ) ) }
7
Kotlin
0
6
af61a5facb45aa6a08846314684c2f4d6d68b2be
3,046
text2confl
Apache License 2.0
app/src/main/java/com/aa/slangapp/search/api/SearchResult.kt
tlacahuepec
285,929,318
false
null
package com.aa.slangapp.search.api import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "searchResults") data class SearchResult( @PrimaryKey @field:SerializedName("defid") val id: Int, @field:SerializedName("definition") val definition: String, @field:SerializedName("thumbs_up") val thumbsUp: Int, @field:SerializedName("word") val word: String, @field:SerializedName("thumbs_down") val thumbsDown: Int )
1
null
1
1
808f6071a104073671ad19f143b6769ac386d290
530
SlangApp
MIT License
tests/features-utils/src/main/kotlin/br/com/mob1st/tests/featuresutils/FakeErrorHandler.kt
mob1st
526,655,668
false
{"Kotlin": 659501, "Shell": 1558}
package br.com.mob1st.tests.featuresutils import br.com.mob1st.core.state.managers.ErrorHandler class FakeErrorHandler : ErrorHandler() { var error: Throwable? = null override fun catch(throwable: Throwable) { this.error = throwable } }
11
Kotlin
0
3
89e55a76a6d368c9f3e8f6a0b7ed4d158665f424
260
bet-app-android
Apache License 2.0
j2k/tests/testData/ast/function/extendsBaseWhichExtendsObject.kt
craastad
18,462,025
false
{"Markdown": 18, "XML": 405, "Ant Build System": 23, "Ignore List": 7, "Maven POM": 34, "Kotlin": 10194, "Java": 3675, "CSS": 10, "Shell": 6, "Batchfile": 6, "Java Properties": 9, "Gradle": 61, "INI": 6, "JavaScript": 42, "HTML": 77, "Text": 875, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "JAR Manifest": 1, "Protocol Buffer": 2}
package test open class Test() : Base() { override fun hashCode(): Int { return super.hashCode() } override fun equals(o: Any?): Boolean { return super.equals(o) } override fun clone(): Any? { return super.clone() } override fun toString(): String? { return super.toString() } override fun finalize() { super.finalize() } } open class Base() { public open fun hashCode(): Int { return System.identityHashCode(this) } public open fun equals(o: Any?): Boolean { return this.identityEquals(o) } protected open fun clone(): Any? { return super.clone() } public open fun toString(): String? { return getJavaClass<Base>.getName() + '@' + Integer.toHexString(hashCode()) } protected open fun finalize() { super.finalize() } }
1
null
1
1
f41f48b1124e2f162295718850426193ab55f43f
888
kotlin
Apache License 2.0
lassi/src/main/java/com/lassi/presentation/mediadirectory/LassiMediaPickerActivity.kt
Mindinventory
194,615,149
false
null
package com.lassi.presentation.mediadirectory import android.app.Activity import android.content.Intent import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.WindowManager import android.webkit.MimeTypeMap import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.ViewModelProvider import com.lassi.R import com.lassi.common.extenstions.getFileName import com.lassi.common.extenstions.getFileSize import com.lassi.common.utils.CropUtils import com.lassi.common.utils.DrawableUtils.changeIconColor import com.lassi.common.utils.FilePickerUtils.getFilePathFromUri import com.lassi.common.utils.KeyUtils import com.lassi.common.utils.ToastUtils import com.lassi.data.media.MiMedia import com.lassi.domain.common.SafeObserver import com.lassi.domain.media.LassiConfig import com.lassi.domain.media.LassiOption import com.lassi.domain.media.MediaType import com.lassi.presentation.camera.CameraFragment import com.lassi.presentation.common.LassiBaseViewModelActivity import com.lassi.presentation.cropper.CropImage import com.lassi.presentation.docs.DocsFragment import com.lassi.presentation.media.SelectedMediaViewModel import com.lassi.presentation.videopreview.VideoPreviewActivity import com.livefront.bridge.Bridge import com.livefront.bridge.SavedStateHandler import io.reactivex.annotations.NonNull import io.reactivex.annotations.Nullable import kotlinx.android.synthetic.main.activity_media_picker.* import java.io.File class LassiMediaPickerActivity : LassiBaseViewModelActivity<SelectedMediaViewModel>() { private var menuDone: MenuItem? = null private var menuCamera: MenuItem? = null private val getContent = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uri -> uri?.let { uris -> val list = ArrayList<MiMedia>() uris.map { uri -> val miMedia = MiMedia() miMedia.name = getFileName(uri) miMedia.doesUri = false miMedia.fileSize = getFileSize(uri) miMedia.path = getFilePathFromUri(this, uri, true) list.add(miMedia) } setResultOk(list) } } override fun getContentResource() = R.layout.activity_media_picker override fun buildViewModel(): SelectedMediaViewModel { return ViewModelProvider( this, SelectedMediaViewModelFactory(this) )[SelectedMediaViewModel::class.java] } private val folderViewModel by lazy { ViewModelProvider( this, FolderViewModelFactory(this) )[FolderViewModel::class.java] } override fun initLiveDataObservers() { super.initLiveDataObservers() viewModel.selectedMediaLiveData.observe(this, SafeObserver(this::handleSelectedMedia)) } override fun initViews() { super.initViews() Bridge.initialize(applicationContext, object : SavedStateHandler { override fun saveInstanceState(@NonNull target: Any, @NonNull state: Bundle) { } override fun restoreInstanceState(@NonNull target: Any, @Nullable state: Bundle?) { } }) setToolbarTitle(LassiConfig.getConfig().selectedMedias) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) setThemeAttributes() initiateFragment() } private fun setToolbarTitle(selectedMedias: ArrayList<MiMedia>) { val maxCount = LassiConfig.getConfig().maxCount if (maxCount > 1) { toolbar.title = String.format( getString(R.string.selected_items), selectedMedias.size, maxCount ) } else { toolbar.title = "" } } private fun initiateFragment() { if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA) { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, CameraFragment() ) .commitAllowingStateLoss() } else { LassiConfig.getConfig().mediaType.let { mediaType -> when (mediaType) { MediaType.DOC -> { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, DocsFragment() ) .commitAllowingStateLoss() } MediaType.FILE_TYPE_WITH_SYSTEM_VIEW -> { browseFile() } else -> { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, FolderFragment.newInstance() ) .commitAllowingStateLoss() } } } } } private fun browseFile() { val mimeTypesList = ArrayList<String>() LassiConfig.getConfig().supportedFileType.forEach { mimeType -> MimeTypeMap .getSingleton() .getMimeTypeFromExtension(mimeType)?.let { mimeTypesList.add(it) } } var mMimeTypeArray = arrayOf<String>() mMimeTypeArray = mimeTypesList.toArray(mMimeTypeArray) getContent.launch(mMimeTypeArray) } private fun setThemeAttributes() { with(LassiConfig.getConfig()) { toolbar.background = ColorDrawable(toolbarColor) toolbar.setTitleTextColor(toolbarResourceColor) supportActionBar?.setHomeAsUpIndicator( changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_back_white, toolbarResourceColor ) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = statusBarColor } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.media_picker_menu, menu) menuDone = menu.findItem(R.id.menuDone) menuCamera = menu.findItem(R.id.menuCamera) menuDone?.isVisible = false menuDone?.icon = changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_done_white, LassiConfig.getConfig().toolbarResourceColor ) menuCamera?.icon = changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_camera_white, LassiConfig.getConfig().toolbarResourceColor ) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menuDone?.isVisible = !viewModel.selectedMediaLiveData.value.isNullOrEmpty() return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuCamera -> initCamera() R.id.menuDone -> setSelectedMediaResult() android.R.id.home -> onBackPressed() } return super.onOptionsItemSelected(item) } private fun setSelectedMediaResult() { // Allow crop for single image when (LassiConfig.getConfig().mediaType) { MediaType.IMAGE -> { if (LassiConfig.isSingleMediaSelection() && LassiConfig.getConfig().isCrop) { val uri = Uri.fromFile(File(viewModel.selectedMediaLiveData.value!![0].path!!)) CropUtils.beginCrop(this, uri) } else { setResultOk(viewModel.selectedMediaLiveData.value) } } MediaType.VIDEO, MediaType.AUDIO, MediaType.DOC -> { if (LassiConfig.isSingleMediaSelection()) { VideoPreviewActivity.startVideoPreview( this, viewModel.selectedMediaLiveData.value!![0].path!! ) } else { setResultOk(viewModel.selectedMediaLiveData.value) } } } } private fun initCamera() { if (viewModel.selectedMediaLiveData.value?.size == LassiConfig.getConfig().maxCount) { ToastUtils.showToast(this, R.string.already_selected_max_items) } else { supportFragmentManager.beginTransaction() .add(R.id.ftContainer, CameraFragment()) .addToBackStack(CameraFragment::class.java.simpleName) .commitAllowingStateLoss() } } private fun handleSelectedMedia(selectedMedias: ArrayList<MiMedia>) { setToolbarTitle(selectedMedias) menuDone?.isVisible = !selectedMedias.isNullOrEmpty() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK ) { if (data != null) { if (data.hasExtra(KeyUtils.SELECTED_MEDIA)) { val selectedMedia = data.getSerializableExtra(KeyUtils.SELECTED_MEDIA) as ArrayList<MiMedia> LassiConfig.getConfig().selectedMedias.addAll(selectedMedia) viewModel.addAllSelectedMedia(selectedMedia) folderViewModel.checkInsert() if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA_AND_GALLERY) { supportFragmentManager.popBackStack() } } else if (data.hasExtra(KeyUtils.MEDIA_PREVIEW)) { val selectedMedia = data.getParcelableExtra<MiMedia>(KeyUtils.MEDIA_PREVIEW) if (LassiConfig.isSingleMediaSelection()) { setResultOk(arrayListOf(selectedMedia!!)) } else { LassiConfig.getConfig().selectedMedias.add(selectedMedia!!) viewModel.addSelectedMedia(selectedMedia) folderViewModel.checkInsert() if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA_AND_GALLERY) { supportFragmentManager.popBackStack() } } } } } } private fun setResultOk(selectedMedia: ArrayList<MiMedia>?) { val intent = Intent().apply { putExtra(KeyUtils.SELECTED_MEDIA, selectedMedia) } setResult(Activity.RESULT_OK, intent) finish() } }
14
null
40
151
200db7fe50853ec13bbb3ad483c56bcd4bd92b82
11,293
Lassi-Android
MIT License
lassi/src/main/java/com/lassi/presentation/mediadirectory/LassiMediaPickerActivity.kt
Mindinventory
194,615,149
false
null
package com.lassi.presentation.mediadirectory import android.app.Activity import android.content.Intent import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.WindowManager import android.webkit.MimeTypeMap import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.ViewModelProvider import com.lassi.R import com.lassi.common.extenstions.getFileName import com.lassi.common.extenstions.getFileSize import com.lassi.common.utils.CropUtils import com.lassi.common.utils.DrawableUtils.changeIconColor import com.lassi.common.utils.FilePickerUtils.getFilePathFromUri import com.lassi.common.utils.KeyUtils import com.lassi.common.utils.ToastUtils import com.lassi.data.media.MiMedia import com.lassi.domain.common.SafeObserver import com.lassi.domain.media.LassiConfig import com.lassi.domain.media.LassiOption import com.lassi.domain.media.MediaType import com.lassi.presentation.camera.CameraFragment import com.lassi.presentation.common.LassiBaseViewModelActivity import com.lassi.presentation.cropper.CropImage import com.lassi.presentation.docs.DocsFragment import com.lassi.presentation.media.SelectedMediaViewModel import com.lassi.presentation.videopreview.VideoPreviewActivity import com.livefront.bridge.Bridge import com.livefront.bridge.SavedStateHandler import io.reactivex.annotations.NonNull import io.reactivex.annotations.Nullable import kotlinx.android.synthetic.main.activity_media_picker.* import java.io.File class LassiMediaPickerActivity : LassiBaseViewModelActivity<SelectedMediaViewModel>() { private var menuDone: MenuItem? = null private var menuCamera: MenuItem? = null private val getContent = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uri -> uri?.let { uris -> val list = ArrayList<MiMedia>() uris.map { uri -> val miMedia = MiMedia() miMedia.name = getFileName(uri) miMedia.doesUri = false miMedia.fileSize = getFileSize(uri) miMedia.path = getFilePathFromUri(this, uri, true) list.add(miMedia) } setResultOk(list) } } override fun getContentResource() = R.layout.activity_media_picker override fun buildViewModel(): SelectedMediaViewModel { return ViewModelProvider( this, SelectedMediaViewModelFactory(this) )[SelectedMediaViewModel::class.java] } private val folderViewModel by lazy { ViewModelProvider( this, FolderViewModelFactory(this) )[FolderViewModel::class.java] } override fun initLiveDataObservers() { super.initLiveDataObservers() viewModel.selectedMediaLiveData.observe(this, SafeObserver(this::handleSelectedMedia)) } override fun initViews() { super.initViews() Bridge.initialize(applicationContext, object : SavedStateHandler { override fun saveInstanceState(@NonNull target: Any, @NonNull state: Bundle) { } override fun restoreInstanceState(@NonNull target: Any, @Nullable state: Bundle?) { } }) setToolbarTitle(LassiConfig.getConfig().selectedMedias) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) setThemeAttributes() initiateFragment() } private fun setToolbarTitle(selectedMedias: ArrayList<MiMedia>) { val maxCount = LassiConfig.getConfig().maxCount if (maxCount > 1) { toolbar.title = String.format( getString(R.string.selected_items), selectedMedias.size, maxCount ) } else { toolbar.title = "" } } private fun initiateFragment() { if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA) { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, CameraFragment() ) .commitAllowingStateLoss() } else { LassiConfig.getConfig().mediaType.let { mediaType -> when (mediaType) { MediaType.DOC -> { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, DocsFragment() ) .commitAllowingStateLoss() } MediaType.FILE_TYPE_WITH_SYSTEM_VIEW -> { browseFile() } else -> { supportFragmentManager.beginTransaction() .replace( R.id.ftContainer, FolderFragment.newInstance() ) .commitAllowingStateLoss() } } } } } private fun browseFile() { val mimeTypesList = ArrayList<String>() LassiConfig.getConfig().supportedFileType.forEach { mimeType -> MimeTypeMap .getSingleton() .getMimeTypeFromExtension(mimeType)?.let { mimeTypesList.add(it) } } var mMimeTypeArray = arrayOf<String>() mMimeTypeArray = mimeTypesList.toArray(mMimeTypeArray) getContent.launch(mMimeTypeArray) } private fun setThemeAttributes() { with(LassiConfig.getConfig()) { toolbar.background = ColorDrawable(toolbarColor) toolbar.setTitleTextColor(toolbarResourceColor) supportActionBar?.setHomeAsUpIndicator( changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_back_white, toolbarResourceColor ) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = statusBarColor } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.media_picker_menu, menu) menuDone = menu.findItem(R.id.menuDone) menuCamera = menu.findItem(R.id.menuCamera) menuDone?.isVisible = false menuDone?.icon = changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_done_white, LassiConfig.getConfig().toolbarResourceColor ) menuCamera?.icon = changeIconColor( this@LassiMediaPickerActivity, R.drawable.ic_camera_white, LassiConfig.getConfig().toolbarResourceColor ) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menuDone?.isVisible = !viewModel.selectedMediaLiveData.value.isNullOrEmpty() return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuCamera -> initCamera() R.id.menuDone -> setSelectedMediaResult() android.R.id.home -> onBackPressed() } return super.onOptionsItemSelected(item) } private fun setSelectedMediaResult() { // Allow crop for single image when (LassiConfig.getConfig().mediaType) { MediaType.IMAGE -> { if (LassiConfig.isSingleMediaSelection() && LassiConfig.getConfig().isCrop) { val uri = Uri.fromFile(File(viewModel.selectedMediaLiveData.value!![0].path!!)) CropUtils.beginCrop(this, uri) } else { setResultOk(viewModel.selectedMediaLiveData.value) } } MediaType.VIDEO, MediaType.AUDIO, MediaType.DOC -> { if (LassiConfig.isSingleMediaSelection()) { VideoPreviewActivity.startVideoPreview( this, viewModel.selectedMediaLiveData.value!![0].path!! ) } else { setResultOk(viewModel.selectedMediaLiveData.value) } } } } private fun initCamera() { if (viewModel.selectedMediaLiveData.value?.size == LassiConfig.getConfig().maxCount) { ToastUtils.showToast(this, R.string.already_selected_max_items) } else { supportFragmentManager.beginTransaction() .add(R.id.ftContainer, CameraFragment()) .addToBackStack(CameraFragment::class.java.simpleName) .commitAllowingStateLoss() } } private fun handleSelectedMedia(selectedMedias: ArrayList<MiMedia>) { setToolbarTitle(selectedMedias) menuDone?.isVisible = !selectedMedias.isNullOrEmpty() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK ) { if (data != null) { if (data.hasExtra(KeyUtils.SELECTED_MEDIA)) { val selectedMedia = data.getSerializableExtra(KeyUtils.SELECTED_MEDIA) as ArrayList<MiMedia> LassiConfig.getConfig().selectedMedias.addAll(selectedMedia) viewModel.addAllSelectedMedia(selectedMedia) folderViewModel.checkInsert() if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA_AND_GALLERY) { supportFragmentManager.popBackStack() } } else if (data.hasExtra(KeyUtils.MEDIA_PREVIEW)) { val selectedMedia = data.getParcelableExtra<MiMedia>(KeyUtils.MEDIA_PREVIEW) if (LassiConfig.isSingleMediaSelection()) { setResultOk(arrayListOf(selectedMedia!!)) } else { LassiConfig.getConfig().selectedMedias.add(selectedMedia!!) viewModel.addSelectedMedia(selectedMedia) folderViewModel.checkInsert() if (LassiConfig.getConfig().lassiOption == LassiOption.CAMERA_AND_GALLERY) { supportFragmentManager.popBackStack() } } } } } } private fun setResultOk(selectedMedia: ArrayList<MiMedia>?) { val intent = Intent().apply { putExtra(KeyUtils.SELECTED_MEDIA, selectedMedia) } setResult(Activity.RESULT_OK, intent) finish() } }
14
null
40
151
200db7fe50853ec13bbb3ad483c56bcd4bd92b82
11,293
Lassi-Android
MIT License
library/src/main/java/com/thesurix/gesturerecycler/LayoutFlags.kt
mozomig
239,997,487
true
{"Kotlin": 46099, "Java": 29602}
package com.thesurix.gesturerecycler import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.support.v7.widget.helper.ItemTouchHelper /** * Enum with predefined gesture flags for various layout managers, see [RecyclerView.LayoutManager] * @author thesurix */ internal enum class LayoutFlags { LINEAR { override fun getDragFlags(layout: RecyclerView.LayoutManager): Int { val linearLayout = layout as LinearLayoutManager return when(linearLayout.orientation) { LinearLayoutManager.HORIZONTAL -> ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT else -> ItemTouchHelper.UP or ItemTouchHelper.DOWN } } override fun getSwipeFlags(layout: RecyclerView.LayoutManager): Int { val linearLayout = layout as LinearLayoutManager return when(linearLayout.orientation) { LinearLayoutManager.HORIZONTAL -> ItemTouchHelper.UP else -> ItemTouchHelper.RIGHT } } }, GRID { override fun getDragFlags(layout: RecyclerView.LayoutManager): Int { return ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT } override fun getSwipeFlags(layout: RecyclerView.LayoutManager): Int { val gridLayout = layout as GridLayoutManager return when(gridLayout.orientation) { GridLayoutManager.HORIZONTAL -> ItemTouchHelper.UP or ItemTouchHelper.DOWN else -> ItemTouchHelper.RIGHT } } }, STAGGERED { override fun getDragFlags(layout: RecyclerView.LayoutManager): Int { return ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT } override fun getSwipeFlags(layout: RecyclerView.LayoutManager): Int { val staggeredGridLayout = layout as StaggeredGridLayoutManager return when(staggeredGridLayout.orientation) { StaggeredGridLayoutManager.HORIZONTAL -> ItemTouchHelper.UP or ItemTouchHelper.DOWN else -> ItemTouchHelper.RIGHT } } }; /** * Returns drag flags for the given layout manager. * @param layout layout manager instance * @return drag flags */ internal abstract fun getDragFlags(layout: RecyclerView.LayoutManager): Int /** * Returns swipe flags for the given layout manager. * @param layout layout manager instance * @return swipe flags */ internal abstract fun getSwipeFlags(layout: RecyclerView.LayoutManager): Int }
0
Kotlin
0
0
7ac23128ea5fe0872f588a86cdbd09acb0639002
2,816
gesture-recycler
Apache License 2.0
golemiokotlinlib/src/commonMain/kotlin/io/github/martinjelinek/golemiokotlinlib/v2/service/impl/cache/MunicipalLibrariesCachingRepository.kt
martinjelinek
763,563,087
false
{"Kotlin": 225850}
package io.github.martinjelinek.golemiokotlinlib.v2.service.impl.cache import io.github.martinjelinek.golemiokotlinlib.common.entity.featurescollection.MunicipalLibrary import io.github.martinjelinek.golemiokotlinlib.common.network.GolemioApi import io.github.martinjelinek.golemiokotlinlib.common.service.impl.cache.CachingRepository import io.github.martinjelinek.golemiokotlinlib.v2.service.IMunicipalLibrariesRepository import io.github.martinjelinek.golemiokotlinlib.v2.service.impl.remote.MunicipalLibrariesRemoteRepository internal class MunicipalLibrariesCachingRepository( private val remoteRepository: IMunicipalLibrariesRepository ) : IMunicipalLibrariesRepository, CachingRepository() { private var municipalLibraries: MutableMap<String, List<MunicipalLibrary>> = mutableMapOf() private var municipalLibrariesById: MutableMap<String, MunicipalLibrary> = mutableMapOf() override suspend fun getAllMunicipalLibraries( latlng: Pair<String, String>?, range: Int?, districts: List<String>?, limit: Int?, offset: Int?, updatedSince: String? ): List<MunicipalLibrary> { return fetchDataAndCache( municipalLibraries, latlng, range, districts, offset, updatedSince, ) { remoteRepository.getAllMunicipalLibraries( latlng, range, districts, limit, offset, updatedSince ) } } override suspend fun getMunicipalLibraryById(id: String): MunicipalLibrary { return fetchDataAndCache(municipalLibrariesById, id) { remoteRepository.getMunicipalLibraryById(id) } } companion object Factory { /** * Creates [MunicipalLibrariesCachingRepository] over [MunicipalLibrariesRemoteRepository] with [GolemioApi] handling the api calls. */ fun create(apiKey: String) = MunicipalLibrariesCachingRepository( MunicipalLibrariesRemoteRepository( GolemioApi( apiKey ) ) ) } }
0
Kotlin
0
2
b49495579ed1de62068fcccd8393357f2b386701
2,263
golemiokotlin
MIT License
marker/src/main/kotlin/com/sourceplusplus/marker/plugin/FileActivityListener.kt
kaizhiyu
327,907,510
false
null
package com.sourceplusplus.marker.plugin import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseEventArea import com.intellij.openapi.editor.event.EditorMouseMotionListener import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.project.DumbService import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.sourceplusplus.marker.source.SourceMarkerUtils import com.sourceplusplus.marker.SourceMarker import com.sourceplusplus.marker.source.SourceFileMarker import com.sourceplusplus.marker.source.mark.gutter.GutterMark import org.slf4j.LoggerFactory /** * todo: description. * * @since 0.1.0 * @author [Brandon Fergerson](mailto:[email protected]) */ class FileActivityListener : FileEditorManagerListener { override fun fileOpened(source: FileEditorManager, file: VirtualFile) { if (DumbService.isDumb(source.project)) { log.debug("Ignoring file opened: $file") } else { triggerFileOpened(source, file) } } override fun fileClosed(source: FileEditorManager, file: VirtualFile) { if (DumbService.isDumb(source.project)) { log.debug("Ignoring file closed: $file") } else { log.debug("File closed: $file") val psiFile = PsiManager.getInstance(source.project).findFile(file)!! val fileMarker = psiFile.getUserData(SourceFileMarker.KEY) if (fileMarker != null) { SourceMarker.deactivateSourceFileMarker(fileMarker) } } } companion object { private val log = LoggerFactory.getLogger(FileActivityListener::class.java) @JvmStatic fun triggerFileOpened(source: FileEditorManager, file: VirtualFile) { log.debug("File opened: $file") //display gutter mark popups on hover over gutter mark val editor = EditorUtil.getEditorEx(source.getSelectedEditor(file)) if (editor != null) { val psiFile = PsiManager.getInstance(source.project).findFile(file)!! val editorMouseMotionListener = makeMouseMotionListener(editor, psiFile) editor.addEditorMouseMotionListener(editorMouseMotionListener) } else { log.error("Selected editor was null. Failed to add mouse motion listener") } } //todo: belongs closer to gutter mark code private fun makeMouseMotionListener(editor: Editor, psiFile: PsiFile): EditorMouseMotionListener { return object : EditorMouseMotionListener { override fun mouseMoved(e: EditorMouseEvent) { if (e.area != EditorMouseEventArea.LINE_MARKERS_AREA || e.isConsumed) { return } val lineNumber = SourceMarkerUtils.convertPointToLineNumber(psiFile.project, e.mouseEvent.point) if (lineNumber == -1) { return } var syncViewProvider = false var gutterMark: GutterMark? = null val fileMarker = psiFile.getUserData(SourceFileMarker.KEY) if (fileMarker != null) { gutterMark = fileMarker.getSourceMarks().find { if (it is GutterMark) { if (it.configuration.activateOnMouseHover && it.configuration.icon != null) { if (it.viewProviderBound) { it.lineNumber == lineNumber } else { syncViewProvider = true false } } else { false } } else { false } } as GutterMark? if (syncViewProvider) { //todo: better fix (prevents #8) ApplicationManager.getApplication().invokeLater { val fileEditorManager = FileEditorManager.getInstance(fileMarker.project) fileEditorManager.closeFile(fileMarker.psiFile.virtualFile) fileEditorManager.openFile(fileMarker.psiFile.virtualFile, true) } } } if (gutterMark != null) { e.consume() gutterMark.displayPopup(editor) } } } } } }
0
Kotlin
0
0
f5f1549c1e0d5a65bf1745bbbef69702854e99ee
5,160
SourceMarker-Alpha
Apache License 2.0
integration-tests/general/common-test/src/main/kotlin/com/r3/conclave/integrationtests/general/commontest/AbstractEnclaveActionTest.kt
R3Conclave
526,690,075
false
null
package com.r3.conclave.integrationtests.general.commontest import com.r3.conclave.host.AttestationParameters import com.r3.conclave.host.EnclaveHost import com.r3.conclave.integrationtests.general.common.tasks.EnclaveTestAction import com.r3.conclave.integrationtests.general.common.tasks.decode import com.r3.conclave.integrationtests.general.common.tasks.encode import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.io.TempDir import java.nio.file.Path abstract class AbstractEnclaveActionTest( private val defaultEnclaveClassName: String = "com.r3.conclave.integrationtests.general.defaultenclave.DefaultEnclave" ) { /** * Set this to null if a test needs to initialise a host without the enclave file system path. */ @TempDir @JvmField var fileSystemFileTempDir: Path? = null var useKds = false // Used to disable teardown for the `exception is thrown if too many threads are requested` test // TODO: CON-1244 Figure out why this test hangs, then remove this teardown logic. var doEnclaveTeardown = true companion object { fun <R> callEnclave( enclaveHost: EnclaveHost, action: EnclaveTestAction<R>, callback: ((ByteArray) -> ByteArray?)? = null ): R { val encodedAction = encode(EnclaveTestAction.serializer(action.resultSerializer()), action) val encodedResult = if (callback != null) { enclaveHost.callEnclave(encodedAction, callback) } else { enclaveHost.callEnclave(encodedAction) } assertThat(encodedResult).isNotNull return decode(action.resultSerializer(), encodedResult!!) } } private val enclaveTransports = HashMap<String, TestEnclaveTransport>() @AfterEach fun closeEnclaves() { // Disable teardown for the `exception is thrown if too many threads are requested` test // TODO: CON-1244 Figure out why this test hangs, then remove this teardown logic. if (doEnclaveTeardown) { synchronized(enclaveTransports) { enclaveTransports.values.forEach { it.close() } enclaveTransports.clear() } } } fun enclaveHost(enclaveClassName: String = defaultEnclaveClassName): EnclaveHost { return getEnclaveTransport(enclaveClassName).enclaveHost } fun restartEnclave(enclaveClassName: String = defaultEnclaveClassName) { synchronized(enclaveTransports) { enclaveTransports.getValue(enclaveClassName).restartEnclave() } } fun <R> callEnclave( action: EnclaveTestAction<R>, enclaveClassName: String = defaultEnclaveClassName, callback: ((ByteArray) -> ByteArray?)? = null ): R { return callEnclave(enclaveHost(enclaveClassName), action, callback) } fun newMailClient(enclaveClassName: String = defaultEnclaveClassName): MailClient { return MailClientImpl(getEnclaveTransport(enclaveClassName)) } interface MailClient { fun <R> deliverMail(action: EnclaveTestAction<R>, callback: ((ByteArray) -> ByteArray?)? = null): R } fun getFileSystemFilePath(enclaveClassName: String): Path? { return fileSystemFileTempDir?.resolve("$enclaveClassName.disk") } private fun getEnclaveTransport(enclaveClassName: String): TestEnclaveTransport { return synchronized(enclaveTransports) { enclaveTransports.computeIfAbsent(enclaveClassName) { val enclaveFileSystemFile = getFileSystemFilePath(enclaveClassName) val kdsUrl = if (useKds) "http://localhost:${TestKds.testKdsPort}" else null val transport = object : TestEnclaveTransport(enclaveClassName, enclaveFileSystemFile, kdsUrl) { override val attestationParameters: AttestationParameters? get() = TestUtils.getAttestationParams(enclaveHost) } transport.startEnclave() transport } } } private class MailClientImpl(private val enclaveTransport: TestEnclaveTransport) : MailClient { private val enclaveClient = enclaveTransport.startNewClient() private val clientConnection = enclaveClient.clientConnection as TestEnclaveTransport.ClientConnection override fun <R> deliverMail(action: EnclaveTestAction<R>, callback: ((ByteArray) -> ByteArray?)?): R { val encodedAction = encode(EnclaveTestAction.serializer(action.resultSerializer()), action) val resultMail = if (callback == null) { enclaveClient.sendMail(encodedAction) } else { // This is a bit of a hack. EnclaveClient doesn't support a callback, for obvious reasons, and so we // have to manually encrypt the request and decrypt any response. By not using the EnclaveClient here // means we're not exercising rollback detection, for example. val postOffice = enclaveClient.postOffice("default") val mailRequestBytes = postOffice.encryptMail(encodedAction) val mailResponseBytes = enclaveTransport.enclaveHostService.deliverMail( mailRequestBytes, clientConnection.id, callback ) mailResponseBytes?.let(postOffice::decryptMail) } checkNotNull(resultMail) return decode(action.resultSerializer(), resultMail.bodyAsBytes) } } }
0
C++
8
41
9b49a00bb33a22f311698d7ed8609a189f38d6ae
5,640
conclave-core-sdk
Apache License 2.0
ee/backend/tests/src/test/kotlin/io/tolgee/ee/slack/MockedSlackClient.kt
tolgee
303,766,501
false
{"Kotlin": 3960934, "TypeScript": 2743868, "JavaScript": 19265, "MDX": 15316, "Shell": 12678, "Java": 9890, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.ee.slack import com.slack.api.RequestConfigurator import com.slack.api.methods.MethodsClient import com.slack.api.methods.request.chat.ChatPostMessageRequest import org.mockito.Mockito class MockedSlackClient(val methodsClientMock: MethodsClient) { val chatPostMessageRequests: List<ChatPostMessageRequest> get() = Mockito.mockingDetails(methodsClientMock).invocations.flatMap { invocation -> invocation.arguments.mapNotNull { argument -> try { @Suppress("UNCHECKED_CAST") val configurator = argument as RequestConfigurator<ChatPostMessageRequest.ChatPostMessageRequestBuilder> configurator.configure(ChatPostMessageRequest.builder()).build() } catch (e: Exception) { null } } } }
125
Kotlin
105
1,355
2df861e1530cb46ac5810e3255678273f8b584a3
813
tolgee-platform
Apache License 2.0
moon/ktx/src/main/java/com/adkhambek/moon/MoonX.kt
MrAdkhambek
459,882,961
false
null
@file:Suppress("NOTHING_TO_INLINE") package com.adkhambek.moon import com.adkhambek.moon.convertor.EventConvertor import io.socket.client.IO import io.socket.client.IO.Options import java.net.URI public inline fun Moon.Companion.factory(): Moon.Factory { return Moon.Factory() } public fun Moon.Factory.create( uri: String, logger: Logger, vararg converterFactories: EventConvertor.Factory, ): Moon = create( socket = IO.socket(uri), logger = logger, *converterFactories ) public fun Moon.Factory.create( uri: String, opts: Options, logger: Logger, vararg converterFactories: EventConvertor.Factory, ): Moon = create( socket = IO.socket(uri, opts), logger = logger, *converterFactories ) public fun Moon.Factory.create( uri: URI, logger: Logger, vararg converterFactories: EventConvertor.Factory, ): Moon = create( socket = IO.socket(uri), logger = logger, *converterFactories ) public fun Moon.Factory.create( uri: URI, opts: Options, logger: Logger, vararg converterFactories: EventConvertor.Factory, ): Moon = create( socket = IO.socket(uri, opts), logger = logger, *converterFactories )
1
null
2
9
779423c6807a78552d6d810f747c2dac8e4eaa8e
1,205
Moon
Apache License 2.0
core/src/Game/com/lyeeedar/Components/AIComponent.kt
Lyeeedar
128,124,056
false
{"Kotlin": 644727}
package com.lyeeedar.Components import com.lyeeedar.Board.Grid import com.lyeeedar.Util.XmlData abstract class AbstractGridAI { abstract fun onTurn(entity: Entity, grid: Grid) } inline fun Entity.ai(): AIComponent? = this.components[ComponentType.AI] as AIComponent? class AIComponent : AbstractComponent() { override val type: ComponentType = ComponentType.AI lateinit var ai: AbstractGridAI override fun parse(xml: XmlData, entity: Entity, parentPath: String) { } }
1
Kotlin
1
2
c35a65d458591b1508c6db499583391151c2db05
476
MatchDungeon
Apache License 2.0
features/feature-list/src/main/kotlin/com/maximillianleonov/cinemax/feature/list/util/Utils.kt
AfigAliyev
523,245,537
false
null
/* * Copyright 2022 Afig Aliyev * * 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.maximillianleonov.cinemax.feature.list.util import androidx.annotation.StringRes import com.maximillianleonov.cinemax.core.model.MediaType import com.maximillianleonov.cinemax.core.model.MediaType.Common.Discover import com.maximillianleonov.cinemax.core.model.MediaType.Common.NowPlaying import com.maximillianleonov.cinemax.core.model.MediaType.Common.Popular import com.maximillianleonov.cinemax.core.model.MediaType.Common.TopRated import com.maximillianleonov.cinemax.core.model.MediaType.Common.Trending import com.maximillianleonov.cinemax.core.model.MediaType.Common.Upcoming import com.maximillianleonov.cinemax.core.ui.R @StringRes internal fun MediaType.Common.asTitleResourceId() = mediaTypesTitleResources.getValue(this) private val mediaTypesTitleResources = mapOf( Upcoming to R.string.upcoming_movies, TopRated to R.string.top_rated, Popular to R.string.most_popular, NowPlaying to R.string.now_playing, Discover to R.string.discover, Trending to R.string.trending )
8
Kotlin
2
89
02e65e899394753e537c6613de6fe4da49bd08f6
1,618
Cinemax
Apache License 2.0
app/main/bigquery/tables/TableInserter.kt
navikt
590,445,262
false
null
package bigquery.tables import com.google.cloud.bigquery.BigQuery import com.google.cloud.bigquery.InsertAllRequest import com.google.cloud.bigquery.TableId import org.slf4j.LoggerFactory class TableInserter( private val bigQuery: BigQuery ) { private val log = LoggerFactory.getLogger("TableInserter") fun insert(dataset: String, tableName: String, data: Map<String, Any>) { val insertAll = bigQuery.insertAll( InsertAllRequest.newBuilder(TableId.of(dataset, tableName)) .also { builder -> builder.addRow(data) } .build() ) if (insertAll != null && insertAll.hasErrors()) { insertAll.insertErrors.forEach { (t, u) -> log.error("$t - $u") } throw RuntimeException("Bigquery insert har errors") } } }
0
Kotlin
0
0
fb1b8c3417ef71d507c4f93f6eeda1a39cdea7b2
858
aap-bigquery
MIT License
src/commonMain/kotlin/data/gems/Dawnstone.kt
marisa-ashkandi
332,658,265
false
null
package data.gems import data.model.Color import data.model.Gem import data.model.Prefix import data.model.Quality import kotlin.js.JsExport @JsExport class Dawnstone(id: Int, prefix: Prefix) : Gem(id, "Dawnstone", "inv_jewelcrafting_dawnstone_03.jpg", prefix, Color.YELLOW, Quality.RARE)
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
291
tbcsim
MIT License
step-http/src/main/kotlin/com/github/lemfi/kest/http/executor/HttpExecution.kt
lemfi
316,065,076
false
null
@file:Suppress("unused") package com.github.lemfi.kest.http.executor import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.github.lemfi.kest.core.model.Execution import com.github.lemfi.kest.http.model.DeserializeException import com.github.lemfi.kest.http.model.FilePart import com.github.lemfi.kest.http.model.HttpResponse import com.github.lemfi.kest.http.model.MultipartBody import com.github.lemfi.kest.http.model.ParameterPart import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.InputStream import java.util.concurrent.TimeUnit object KestHttp { /** * Register a content type decoder for HTTP calls * @param contentType Content-Type for decoder * @param transformer function to decode InputStream with given Content-Type into an Object */ fun registerContentTypeDecoder(contentType: String, transformer: InputStream?.(cls: TypeReference<*>) -> Any?) = HttpExecution.addMapper(contentType) { cls -> this?.run { ByteArrayInputStream(readAllBytes()).run { use { inputStream -> inputStream.transformer(cls) to inputStream.let { try { it.reset() it.readAllBytes().toString(Charsets.UTF_8).trim() } catch (e: Throwable) { "" } } } } } ?: (null to "null") } } internal data class HttpExecution<T>( val url: String, val method: String, val returnType: TypeReference<T>, val body: Any? = null, val headers: MutableMap<String, String>, val contentType: String?, val followRedirect: Boolean, val timeout: Long?, ) : Execution<HttpResponse<T>>() { private val accept = headers.getOrDefault("Accept", null) companion object { private val mappers = mutableMapOf<String, InputStream?.(cls: TypeReference<*>) -> Pair<Any?, String?>>() .apply { put("application/json") { this?.readAllBytes()?.toString(Charsets.UTF_8)?.trim()?.let { data -> try { jacksonObjectMapper().readValue(data, it) } catch (e: Throwable) { throw DeserializeException(it.type.javaClass, data, e) } to data } ?: (null to null) } put("text") { readText() } } private fun InputStream?.readText() = this?.readAllBytes()?.toString(Charsets.UTF_8)?.trim()?.let { data -> data to data } ?: (null to null) fun addMapper(contentType: String, mapper: InputStream?.(cls: TypeReference<*>) -> Pair<Any?, String?>) { mappers[contentType] = mapper } fun getMapper(contentType: String) = mappers[contentType.substringBefore(";").trim()] ?: mappers[contentType.substringBefore(";").trim().substringBefore("/")] ?: throw IllegalArgumentException("""no decoder found for content type "$contentType", please register one by calling `KestHttp.registerContentTypeDecoder("$contentType") { ... }""") } @Suppress("unchecked_cast") override fun execute(): HttpResponse<T> { LoggerFactory.getLogger("HTTP-kest").info( """ | Request | | $method $url | $headers | $body | | """.trimMargin() ) return if (body is MultipartBody) { OkHttpClient.Builder() .followRedirects(followRedirect) .readTimeout(timeout ?: 0, TimeUnit.MILLISECONDS) .build().newCall( Request.Builder() .url(url) .apply { headers.forEach { addHeader(it.key, it.value) } } .method(method, okhttp3.MultipartBody.Builder() .apply { body.parts.forEach { when (it) { is FilePart -> addFormDataPart( it.name, it.filename, it.file.asRequestBody(it.contentType?.toMediaTypeOrNull()) ) is ParameterPart -> addFormDataPart(it.name, it.value) } } } .setType("multipart/form-data".toMediaType()) .build()) .build() ) .execute() .toHttpResponse() } else { OkHttpClient.Builder() .followRedirects(followRedirect) .readTimeout(timeout ?: 0, TimeUnit.MILLISECONDS) .build().newCall( Request.Builder() .url(url) .apply { contentType?.also { headers["Content-Type"] = it } headers.forEach { addHeader(it.key, it.value) } } .method(method, body?.toString()?.toRequestBody(contentType?.toMediaTypeOrNull())) .build() ).execute().toHttpResponse() } } @Suppress("unchecked_cast") private fun Response.toHttpResponse(): HttpResponse<T> { var content: String? = null return try { (header("Content-Type") ?: accept ?: "text/plain") .let { contentType -> (getMapper(contentType).invoke(body?.byteStream(), returnType)) }.let { body -> HttpResponse( body = body.first as T, status = code, headers = headers .let { headers -> headers.map { it.first } } .toSet() .associateWith { key -> headers(key) } ).also { content = body.second } } } catch (e: DeserializeException) { content = e.data throw e } finally { LoggerFactory.getLogger("HTTP-kest").info( """ | Response | $code | ${headers.joinToString("\n") { "${it.first}: ${it.second}" }} | | $content | |""".trimMargin() ) } } }
3
null
0
8
b6cb85abb86844b1a589a5567f5f1eaf6aa049db
7,309
kest
Apache License 2.0
core/src/main/kotlin/com/github/quillraven/quillycrawler/screen/TutorialScreen.kt
Quillraven
336,620,410
false
{"Kotlin": 395446}
package com.github.quillraven.quillycrawler.screen import com.github.quillraven.commons.game.AbstractScreen import com.github.quillraven.quillycrawler.QuillyCrawler import com.github.quillraven.quillycrawler.assets.I18NAssets import com.github.quillraven.quillycrawler.ui.model.TutorialViewModel import com.github.quillraven.quillycrawler.ui.view.TutorialView class TutorialScreen(game: QuillyCrawler) : AbstractScreen(game) { private val viewModel = TutorialViewModel(assetStorage[I18NAssets.DEFAULT.descriptor], audioService, game) private val view = TutorialView(viewModel) override fun show() { super.show() stage.addActor(view) } }
1
Kotlin
8
28
1c528e533709cfb6437d088c459402014b8f9475
656
Quilly-Crawler
MIT License
KotlinToSwift/src/main/kotlin/fr/jhelp/kotlinToSwift/postTreatment/ConstructorPostTreatment.kt
jhelpgg
600,408,546
false
null
package fr.jhelp.kotlinToSwift.postTreatment import fr.jhelp.kotlinToSwift.endCurlyIndex import java.util.regex.Pattern private val startConstructorPattern = Pattern.compile("(init\\s*\\([^{]*\\{)(\\s*)(super.init\\s*\\([^)]*\\))") private const val GROUP_CONSTRUCTOR = 1 private const val GROUP_SPACE = 2 private const val GROUP_SUPER = 3 private const val SUPER = "@Super" private const val SUPER_LENGTH = SUPER.length fun parseConstructorInFile(file: String): String { val matcher = startConstructorPattern.matcher(file) var first = 0 var before: Int var start: Int var end = 0 var superIndex : Int val transformed = StringBuilder() while (matcher.find()) { before = matcher.start() start = matcher.end() end = endCurlyIndex(file, start) transformed.append(file.substring(first, before)) transformed.append(matcher.group(GROUP_CONSTRUCTOR)) superIndex = file.indexOf(SUPER, start) if (superIndex in 0 until end) { transformed.append(file.substring(start, superIndex)) transformed.append(matcher.group(GROUP_SUPER)) transformed.append(file.substring(superIndex + SUPER_LENGTH, end)) } else { transformed.append(file.substring(start, end - 1)) transformed.append(matcher.group(GROUP_SUPER)) transformed.append(matcher.group(GROUP_SPACE)) transformed.append("}") } first = end } transformed.append(file.substring(end)) return transformed.toString() }
0
Kotlin
0
0
6ab79ff8f826b8c6fbf059b4ca68b9ec1da965e8
1,594
Kotlwift
Apache License 2.0
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/util/FileUtils.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("FileUtils") package org.jetbrains.kotlin.idea.util import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.KotlinFileType fun VirtualFile.isKotlinFileType(): Boolean = extension == KotlinFileType.EXTENSION || FileTypeRegistry.getInstance().isFileOfType(this, KotlinFileType.INSTANCE) fun VirtualFile.isJavaFileType(): Boolean = extension == JavaFileType.DEFAULT_EXTENSION || FileTypeRegistry.getInstance().isFileOfType(this, JavaFileType.INSTANCE)
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
720
intellij-community
Apache License 2.0
app/src/main/java/com/mgpersia/androidbox/data/implement/MainRepositoryImplement.kt
mahsak01
596,924,815
false
null
package com.mgpersia.androidbox.data.implement import com.mgpersia.androidbox.data.model.ActorFilmDetailInformation import com.mgpersia.androidbox.data.model.Country import com.mgpersia.androidbox.data.model.information.* import com.mgpersia.androidbox.data.repository.MainRepository import com.mgpersia.androidbox.data.source.MainDataSource import io.reactivex.Single class MainRepositoryImplement(private val mainRemoteDataSource: MainDataSource) : MainRepository { override fun getOpt(phone: String, country: String): Single<GetOptInformation> = mainRemoteDataSource.getOpt(phone, country) override fun checkOpt(information: CheckOptInformation): Single<GetCheckOptInformation> = mainRemoteDataSource.checkOpt(information) override fun getLocation(): Single<CheckLocationInformation> = mainRemoteDataSource.getLocation() override fun registerUser( registerUserInformation: RegisterUserInformation ): Single<GetRegisterUserResultInformation> = mainRemoteDataSource.registerUser( registerUserInformation ) override fun getAllGenre(): Single<GetAllGenreInformation> = mainRemoteDataSource.getAllGenre() override fun getAllTag(): Single<GetAllGenreInformation> = mainRemoteDataSource.getAllTag() override fun getAllCountries(): Single<List<Country>> = mainRemoteDataSource.getAllCountries() override fun getAllCountriesFilms(): Single<List<Country>> = mainRemoteDataSource.getAllCountriesFilms() override fun getLives(): Single<GetLiveInformation> = mainRemoteDataSource.getLives() override fun getFilmDetail(id: String): Single<GetFilmDetailInformation> = mainRemoteDataSource.getFilmDetail(id) override fun getBannerHome(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getBannerHome() override fun getNewFilm(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getNewFilm() override fun getNewSeries(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getNewSeries() override fun getNewlySeries(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getNewlySeries() override fun getCommingSoon(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getCommingSoon() override fun getPopularActor(): Single<List<ActorFilmDetailInformation>> = mainRemoteDataSource.getPopularActor() override fun getPopularDirector(): Single<List<ActorFilmDetailInformation>> = mainRemoteDataSource.getPopularDirector() override fun getAllActor(): Single<GetAllActorInformation> = mainRemoteDataSource.getAllActor() override fun getAllDirector(): Single<GetAllActorInformation> = mainRemoteDataSource.getAllDirector() override fun getPopularFilm(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getPopularFilm() override fun getPopularMovie(): Single<GetAllImageFilmHomeInformation> = mainRemoteDataSource.getPopularMovie() override fun getActorDetail(id: String): Single<GetActorDetailInformation> = mainRemoteDataSource.getActorDetail(id) override fun getAllComment(id: String): Single<GetAllCommentOfFilmInformation> = mainRemoteDataSource.getAllComment(id) override fun getAge(): Single<GetAgeLimitInformation> = mainRemoteDataSource.getAge() override fun getSearch( dubbed: String, type: String, subtitle: String, age: String, toyear: String, fromyear: String, tag: String, genre: String, country: String, page: String, page_size: String, text: String ): Single<GetFilterInformation> = mainRemoteDataSource.getSearch( dubbed, type, subtitle, age, toyear, fromyear, tag, genre, country, page, page_size, text ) }
0
Kotlin
0
0
e1ef9a8a316f76446718489f458e3a088ae55d15
3,992
ArianaFilm
The Unlicense
query/src/main/kotlin/com/linecorp/kotlinjdsl/query/spec/Froms.kt
line
442,633,985
false
null
package com.linecorp.kotlinjdsl.query.spec import com.linecorp.kotlinjdsl.query.spec.expression.EntitySpec import jakarta.persistence.criteria.Path import jakarta.persistence.criteria.Root class Froms internal constructor( val root: Root<*>, private val map: Map<EntitySpec<*>, Path<*>> ) { @Suppress("UNCHECKED_CAST") operator fun <T> get(key: EntitySpec<T>): Path<T> = map[key] as? Path<T> ?: throw IllegalStateException("There is no $key in from or join clause. contains: ${map.keys}") operator fun plus(other: Froms): Froms { val duplicatedEntities = map.keys.intersect(other.map.keys) if (duplicatedEntities.isNotEmpty()) { throw IllegalStateException( "Other froms has duplicated entitySpec. Please alias the duplicated entities: $duplicatedEntities" ) } return Froms(root, map + other.map) } }
26
Kotlin
60
504
f28908bf432cf52f73a9573b1ac2be5eb4b2b7dc
922
kotlin-jdsl
Apache License 2.0
app/src/test/java/ru/rznnike/eyehealthmanager/app/presentation/nearfar/test/NearFarTestPresenterTest.kt
RznNike
207,148,781
false
{"Kotlin": 903281}
package ru.rznnike.eyehealthmanager.app.presentation.nearfar.test import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.only import org.mockito.kotlin.verify import ru.rznnike.eyehealthmanager.app.ui.fragment.nearfar.answer.NearFarAnswerFragment import ru.rznnike.eyehealthmanager.app.utils.screenMatcher @ExtendWith(MockitoExtension::class) class NearFarTestPresenterTest { @Mock private lateinit var mockView: NearFarTestView @Test fun openAnswerForm_openNearFarAnswerScreen() { val presenter = NearFarTestPresenter() presenter.attachView(mockView) presenter.openAnswerForm() verify(mockView, only()).routerNavigateTo(screenMatcher(NearFarAnswerFragment::class)) } }
0
Kotlin
1
5
ea21e191ea3d6797be32f7f5e66e8e0ebae30ab6
855
EyeHealthManager
MIT License
simplified-ui-tutorial/src/main/java/org/librarysimplified/ui/login/LoginMainFragment.kt
NatLibFi
730,988,035
false
{"Kotlin": 3535599, "JavaScript": 853788, "Java": 396475, "CSS": 65407, "HTML": 49894, "Shell": 7775, "Ruby": 121}
package org.librarysimplified.ui.login import android.content.Context import android.os.Bundle import android.view.View import android.widget.FrameLayout import androidx.activity.addCallback import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.lifecycle.ViewModelProvider import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.librarysimplified.services.api.Services import org.librarysimplified.ui.tutorial.R import org.nypl.simplified.accounts.api.AccountID import org.nypl.simplified.accounts.api.AccountLoginState import org.nypl.simplified.accounts.api.AccountProviderAuthenticationDescription import org.nypl.simplified.accounts.api.AccountProviderType import org.nypl.simplified.accounts.database.api.AccountType import org.nypl.simplified.accounts.registry.api.AccountProviderRegistryType import org.nypl.simplified.android.ktx.supportActionBar import org.nypl.simplified.android.ktx.tryPopBackStack import org.nypl.simplified.listeners.api.FragmentListenerType import org.nypl.simplified.listeners.api.ListenerRepository import org.nypl.simplified.listeners.api.fragmentListeners import org.nypl.simplified.listeners.api.listenerRepositories import org.nypl.simplified.profiles.controller.api.ProfileAccountLoginRequest import org.nypl.simplified.profiles.controller.api.ProfilesControllerType import org.nypl.simplified.ui.accounts.ekirjasto.passkey.AccountEkirjastoPasskeyFragment import org.nypl.simplified.ui.accounts.ekirjasto.passkey.AccountEkirjastoPasskeyFragmentParameters import org.nypl.simplified.ui.accounts.ekirjasto.suomifi.AccountEkirjastoSuomiFiEvent import org.nypl.simplified.ui.accounts.ekirjasto.suomifi.AccountEkirjastoSuomiFiFragment import org.nypl.simplified.ui.accounts.ekirjasto.suomifi.AccountEkirjastoSuomiFiFragmentParameters import org.nypl.simplified.ui.accounts.ekirjasto.suomifi.EkirjastoLoginMethod import org.nypl.simplified.ui.errorpage.ErrorPageEvent import org.nypl.simplified.ui.errorpage.ErrorPageFragment import org.nypl.simplified.ui.errorpage.ErrorPageParameters import org.slf4j.LoggerFactory class LoginMainFragment : Fragment(R.layout.login_main_fragment) { private val logger = LoggerFactory.getLogger(LoginMainFragment::class.java) private lateinit var mainContainer: FrameLayout //TODO login events listener private val listenerRepository: ListenerRepository<LoginListenedEvent, Unit> by listenerRepositories() private val listener: FragmentListenerType<MainLoginEvent> by fragmentListeners() private val defaultViewModelFactory: ViewModelProvider.Factory by lazy { LoginMainFragmentViewModelFactory(super.defaultViewModelProviderFactory) } val services = Services.serviceDirectory() val profilesController = services.requireService(ProfilesControllerType::class.java) val accountProviders = services.requireService(AccountProviderRegistryType::class.java) override val defaultViewModelProviderFactory: ViewModelProvider.Factory get() = this.defaultViewModelFactory override fun onViewCreated(view: View, savedInstanceState: Bundle?) { logger.debug("onViewCreated(), recreating: {}", (savedInstanceState != null)) super.onViewCreated(view, savedInstanceState) mainContainer = view.findViewById(R.id.login_main_container) if (!checkIsLoggedIn()) { openLoginUi() } } override fun onAttach(context: Context) { super.onAttach(context) this.logger.debug("On Attach - should register backpressed callback") val activity = requireActivity() as AppCompatActivity activity.onBackPressedDispatcher.addCallback(this, true){ logger.debug("Handle Back Pressed from Callback") if (childFragmentManager.tryPopBackStack()){ return@addCallback } try { isEnabled = false activity.onBackPressed() } finally { isEnabled = true } } } override fun onStart() { super.onStart() this.listenerRepository.registerHandler(this::handleEvent) if (checkIsLoggedIn()) { this.listener.post(MainLoginEvent.LoginSuccess) } } private fun checkIsLoggedIn(): Boolean { this.logger.warn("Current Accounts: "+profilesController.profileCurrent().accounts().count()) this.logger.warn("Current Providers: "+accountProviders.resolvedProviders.count()) val account = pickDefaultAccount(profilesController, accountProviders.defaultProvider) return account.loginState is AccountLoginState.AccountLoggedIn } override fun onStop() { super.onStop() this.listenerRepository.unregisterHandler() } private fun configureToolbar(){ val actionBar = this.supportActionBar ?: return actionBar.hide() actionBar.title = "" } private fun openLoginUi() { this.logger.debug("open Login UI") configureToolbar() childFragmentManager.commit { replace(R.id.login_main_container, LoginUiFragment()) } } private fun handleEvent(event: LoginListenedEvent, unit: Unit) { this.logger.debug("Handle Login Event: $event") when (event){ is LoginListenedEvent.LoginEvent -> { when (event.event){ is LoginEvent.SkipLogin -> this.listener.post(MainLoginEvent.SkipLoginEvent) is LoginEvent.StartLoginPasskey -> openEkirjastoLogin(EkirjastoLoginMethod.Passkey(EkirjastoLoginMethod.Passkey.LoginState.LoggingIn, null)) is LoginEvent.StartLoginSuomiFi -> openEkirjastoLogin(EkirjastoLoginMethod.SuomiFi()) } } is LoginListenedEvent.AccountDetailEvent -> { this.logger.warn("Received Account Detail Event: ${event.event}") } is LoginListenedEvent.SuomiFiEvent -> { this.logger.warn("Received Suomi.Fi event: ${event.event}") when(val suomiFiEvent = event.event) { is AccountEkirjastoSuomiFiEvent.PasskeySuccessful, is AccountEkirjastoSuomiFiEvent.AccessTokenObtained -> this.listener.post(MainLoginEvent.LoginSuccess) is AccountEkirjastoSuomiFiEvent.OpenErrorPage -> openErrorPage(suomiFiEvent.parameters) is AccountEkirjastoSuomiFiEvent.Cancel -> this.childFragmentManager.popBackStack() } } is LoginListenedEvent.ErrorPageEvent -> { this.logger.warn("Received Error Page Event: ${event.event}") when (val errorPageEvent = event.event){ is ErrorPageEvent.GoUpwards -> { this.configureToolbar() this.childFragmentManager.popBackStack() } } } } } private fun openErrorPage(parameters: ErrorPageParameters) { this.logger.warn("Open Error Page. Should pop backstack and then create a new fragment") this.childFragmentManager.popBackStackImmediate() val fragment = ErrorPageFragment.create(parameters) this.childFragmentManager.commit { replace(R.id.login_main_container, fragment) setReorderingAllowed(true) addToBackStack(null) } } private fun checkAccountProviders() { this.logger.debug("Checking all account providers") for (provider in accountProviders.resolvedProviders){ this.logger.debug("- Found AccountProvider: ${provider.value.displayName}") } this.logger.debug("Checking all profiles") for (profile in profilesController.profiles()){ val props: MutableList<String> = mutableListOf() if (profile.value.displayName.isEmpty()){ props.add("No profile name") } else { props.add("Name=${profile.value.displayName}") } if (profile.value.isAnonymous){ props.add("Anonymous Profile") } if (profile.value.isCurrent){ props.add("Current Profile") } props.add("Account=${profile.value.mostRecentAccount().provider.displayName}") this.logger.debug("- Found Profile: ${props.joinToString(separator = ", ")}") } } private fun pickDefaultAccount( profilesController: ProfilesControllerType, defaultProvider: AccountProviderType ): AccountType { checkAccountProviders() val profile = profilesController.profileCurrent() val mostRecentId = profile.preferences().mostRecentAccount if (mostRecentId != null) { try { return profile.account(mostRecentId) } catch (e: Exception) { this.logger.error("stale account: ", e) } } val accounts = profile.accounts().values return when { accounts.size > 1 -> { // Return the first account created from a non-default provider accounts.first { it.provider.id != defaultProvider.id } } accounts.size == 1 -> { // Return the first account accounts.first() } else -> { // There should always be at least one account throw Exception("Unreachable code") } } } private fun openEkirjastoLogin(method: EkirjastoLoginMethod) { try { val account = pickDefaultAccount(profilesController, accountProviders.defaultProvider) val authentication = account.provider.authentication as AccountProviderAuthenticationDescription.Ekirjasto when (method) { is EkirjastoLoginMethod.SuomiFi -> openSuomiFiLogin( profilesController, account.id, authentication ) is EkirjastoLoginMethod.Passkey -> openPasskeyLogin( profilesController, account.id, authentication ) } } catch (e: ClassCastException) { this.logger.error("Failed to obtain EKirjasto authentication description",e) showErrorAlert(requireContext().getString(R.string.error_login_account_not_found)) } catch (e: Exception) { this.logger.error("Ekirjasto Login Unknown error",e) } } private fun showErrorAlert(message: String) { MaterialAlertDialogBuilder(requireContext()) .setMessage(message) .show() } private fun openSuomiFiLogin( profilesController: ProfilesControllerType, accountId: AccountID, description: AccountProviderAuthenticationDescription.Ekirjasto ) { this.logger.debug("From Login Screen open Suomi.Fi login") profilesController.profileAccountLogin( ProfileAccountLoginRequest.EkirjastoInitiateSuomiFi( accountId = accountId, description = description ) ) val fragment = AccountEkirjastoSuomiFiFragment.create( AccountEkirjastoSuomiFiFragmentParameters( accountId, description ) ) this.childFragmentManager.commit { replace(R.id.login_main_container, fragment) setReorderingAllowed(true) addToBackStack("suomifiFragment") } } private fun openPasskeyLogin( profilesController: ProfilesControllerType, accountId: AccountID, description: AccountProviderAuthenticationDescription.Ekirjasto ) { this.logger.debug("From Login Screen open Passkey login") profilesController.profileAccountLogin( ProfileAccountLoginRequest.EkirjastoInitiatePassKey( accountId = accountId, description = description ) ) val fragment = AccountEkirjastoPasskeyFragment.create( AccountEkirjastoPasskeyFragmentParameters( accountId, description, EkirjastoLoginMethod.Passkey(EkirjastoLoginMethod.Passkey.LoginState.LoggingIn, null) ) ) this.childFragmentManager.commit { replace(R.id.login_main_container, fragment) setReorderingAllowed(true) addToBackStack("passkeyLogin") } } }
6
Kotlin
0
0
06730bdf00f00b35d6943f2e1d3896534ff05595
11,548
ekirjasto-android-core
Apache License 2.0
app/src/main/java/in/naveens/mqttbroker/utils/NetworkCallBack.kt
TeamDotworld
228,824,734
false
{"Kotlin": 28369, "Java": 1162}
package `in`.naveens.mqttbroker.utils import android.content.Intent import android.net.ConnectivityManager import android.net.Network import `in`.naveens.mqttbroker.MQTTBrokerApp class NetworkCallBack() : ConnectivityManager.NetworkCallback() { private val TAG = "NetworkCallBack" // Got network connection override fun onAvailable(network: Network) { super.onAvailable(network) val intent = Intent(Utils.NETWORK_BROADCAST_ACTION) intent.putExtra("status", true) MQTTBrokerApp.instance.sendBroadcast(intent) } // Lost network connection override fun onLost(network: Network) { super.onLost(network) val intent = Intent(Utils.NETWORK_BROADCAST_ACTION) intent.putExtra("status", false) MQTTBrokerApp.instance.sendBroadcast(intent) } }
1
Kotlin
10
18
d236bc6a331fec72ef5f8470f6e8522122de43f7
830
android-mqtt-broker
MIT License
demo/src/main/java/com/bytedance/danmaku/render/engine/demo/view/ConsoleRecyclerView.kt
bytedance
530,649,521
false
null
package com.bytedance.danmaku.render.engine.demo.view import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bytedance.danmaku.render.engine.demo.R import com.bytedance.danmaku.render.engine.demo.utils.toDisplayDateTime import kotlin.time.ExperimentalTime /** * Created by dss886 on 2021/04/27. */ class ConsoleRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle) { private var mData: MutableList<Info> = mutableListOf() init { layoutManager = LinearLayoutManager(context) adapter = ConsoleAdapter() } fun log(tag: String, content: String) { mData.add(Info(System.currentTimeMillis(), "[${tag}]", content)) adapter?.notifyDataSetChanged() } data class Info(val timestamp: Long, val tag: String, val content: String) inner class ConsoleViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) inner class ConsoleAdapter: RecyclerView.Adapter<ConsoleViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConsoleViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.view_console_list_item, parent, false) return ConsoleViewHolder(view) } @ExperimentalTime @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ConsoleViewHolder, position: Int) { val data = mData.asReversed()[position] holder.itemView.findViewById<TextView>(R.id.time)?.let { it.text = data.timestamp.toDisplayDateTime() } holder.itemView.findViewById<TextView>(R.id.tag)?.let { it.text = data.tag } holder.itemView.findViewById<TextView>(R.id.content)?.let { it.text = data.content } } override fun getItemCount(): Int { return mData.size } } }
0
Kotlin
8
68
577d3f4e170283a5bdb198af3ca924b8c32d1ab4
2,396
DanmakuRenderEngine
Apache License 2.0
macfiles/src/test/kotlin/garden/ephemeral/macfiles/dsstore/IconViewOptionsTests.kt
ephemeral-laboratories
564,594,150
false
null
package garden.ephemeral.macfiles.dsstore import assertk.assertThat import assertk.assertions.isCloseTo import assertk.assertions.isEqualTo import assertk.assertions.isNotNull import garden.ephemeral.macfiles.alias.AliasReadTests import garden.ephemeral.macfiles.dsstore.types.DoublePoint import garden.ephemeral.macfiles.dsstore.types.DoubleRgbColor import garden.ephemeral.macfiles.dsstore.types.IconViewOptions import garden.ephemeral.macfiles.dsstore.types.IntPoint import org.junit.jupiter.api.Test class IconViewOptionsTests { @Test fun `can read`() { DSStore.open(getFilePath("from-dmg.DS_Store")).use { store -> val options = store[".", DSStoreProperties.IconViewOptionsPList] as IconViewOptions assertThat(options.viewOptionsVersion).isEqualTo(1) assertThat(options.backgroundType).isEqualTo(2) assertThat(options.backgroundImageAlias).isEqualTo(AliasReadTests.FROM_DMG_ALIAS) assertThat(options.backgroundColor).isEqualTo(DoubleRgbColor.White) assertThat(options.gridOffset).isEqualTo(IntPoint(0, 0)) assertThat(options.gridSpacing).isNotNull().isCloseTo(100.0, 0.0001) assertThat(options.arrangeBy).isEqualTo("none") assertThat(options.showIconPreview).isEqualTo(false) assertThat(options.showItemInfo).isEqualTo(false) assertThat(options.labelOnBottom).isEqualTo(true) assertThat(options.textSize).isNotNull().isCloseTo(11.0, 0.0001) assertThat(options.iconSize).isNotNull().isCloseTo(72.0, 0.0001) assertThat(options.scrollPosition).isEqualTo(DoublePoint(0.0, 0.0)) } } @Test fun `can write`() { val options = IconViewOptions.build { viewOptionsVersion = 1 backgroundType = 2 backgroundImageAlias = AliasReadTests.FROM_DMG_ALIAS backgroundColor = DoubleRgbColor.White gridOffset = IntPoint(0, 0) gridSpacing = 100.0 arrangeBy = "none" showIconPreview = false showItemInfo = false labelOnBottom = true textSize = 11.0 iconSize = 72.0 scrollPosition = DoublePoint(0.0, 0.0) } val blob = options.toBlob() // The dictionary shuffles data so we can't use exact byte matching assertThat(IconViewOptions.fromBlob(blob)).isEqualTo(options) } }
0
Kotlin
0
0
755f6d065750be6637a1b953cf4ae02413a6ca7c
2,466
dsstore-kotlin
MIT License
android/rctmgl/src/main/java-v10/com/mapbox/rctmgl/components/styles/RCTMGLStyle.kt
AhmedrAshraf
514,372,026
false
null
package com.mapbox.rctmgl.components.styles import android.content.Context import com.facebook.react.bridge.ReadableMap import com.mapbox.maps.MapboxMap import com.mapbox.rctmgl.components.images.ImageInfo import com.mapbox.rctmgl.utils.ImageEntry import com.mapbox.rctmgl.utils.DownloadMapImageTask import com.mapbox.rctmgl.utils.Logger import java.util.AbstractMap import java.util.ArrayList class RCTMGLStyle(private val mContext: Context, reactStyle: ReadableMap?, map: MapboxMap) { private val mReactStyle: ReadableMap? private val mMap: MapboxMap val allStyleKeys: List<String> get() { if (mReactStyle == null) { return ArrayList() } val it = mReactStyle.keySetIterator() val keys: MutableList<String> = ArrayList() while (it.hasNextKey()) { val key = it.nextKey() if (key != "__MAPBOX_STYLESHEET__") { keys.add(key) } } return keys } fun getStyleValueForKey(styleKey: String?): RCTMGLStyleValue? { val styleValueConfig = mReactStyle!!.getMap(styleKey!!) ?: // TODO: throw exeception here return null return RCTMGLStyleValue(styleValueConfig) } fun imageEntry(styleValue: RCTMGLStyleValue): ImageEntry { return ImageEntry(styleValue.imageURI!!, ImageInfo(scale=styleValue.imageScale, name=styleValue.imageURI!!)) } @JvmOverloads fun addImage(styleValue: RCTMGLStyleValue, styleKey: String, callback: DownloadMapImageTask.OnAllImagesLoaded? = null) { if (!styleValue.shouldAddImage()) { callback?.onAllImagesLoaded() return } Logger.w(LOG_TAG,"Deprecated: Image in style is deprecated, use images component instead. key: $styleKey [image-in-style-deprecated]") val uriStr = styleValue.imageURI!! val images = arrayOf<Map.Entry<String, ImageEntry>>( AbstractMap.SimpleEntry<String, ImageEntry>( uriStr, imageEntry(styleValue) ) ) val task = DownloadMapImageTask(mContext, mMap, callback) task.execute(*images) } init { mReactStyle = reactStyle mMap = map } companion object { const val LOG_TAG = "RCTMGLStyle" } }
34
null
786
2
f7f39af71c287b6cab7874b24bcfec13323d158a
2,380
maps
MIT License
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/commonizeHierarchicallyMultiModule/p2/src/nativeMain/kotlin/NativeMain.kt
JetBrains
3,432,266
false
null
@file:Suppress("unused") import kotlinx.cinterop.pointed import platform.posix.stat import withPosixOther.getMyStructPointer import withPosixOther.getStructFromPosix import withPosixOther.getStructPointerFromPosix object NativeMain { val structFromPosix = getStructFromPosix() val structPointerFromPosix = getStructPointerFromPosix() object MyStruct { val struct = getMyStructPointer()?.pointed ?: error("Missing my struct") val posixProperty: stat = struct.posixProperty val longProperty: Long = struct.longProperty val doubleProperty: Double = struct.doubleProperty } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
623
kotlin
Apache License 2.0
src/main/kotlin/com/ohforbidden/bugreport/infrastructure/config/JpaConfig.kt
Oh-Forbidden
751,459,331
false
{"Kotlin": 13527}
package com.ohforbidden.bugreport.infrastructure.config import org.springframework.context.annotation.Configuration import org.springframework.data.jpa.repository.config.EnableJpaAuditing @Configuration @EnableJpaAuditing class JpaConfig
0
Kotlin
0
0
5a4b3a4052bb510ce8c046a005349b1f90f1f3e1
239
oh-forbidden-backend
MIT License
src/main/kotlin/dev/jonaz/vured/bot/web/configuration/OriginPolicy.kt
vured
319,162,419
false
{"Kotlin": 93055, "Dockerfile": 462, "Procfile": 62}
package dev.jonaz.vured.bot.web.configuration import io.ktor.features.* import io.ktor.http.* fun configureCors(configure: CORS.Configuration) { configure.header("Authorization") configure.method(HttpMethod.Patch) configure.method(HttpMethod.Get) configure.allowNonSimpleContentTypes = true configure.host( host = "localhost:4200", schemes = listOf("http") ) configure.host( host = "jonaz.dev", subDomains = listOf("vured-ui"), schemes = listOf("https") ) configure.anyHost() }
8
Kotlin
15
52
121962151284a2f9c8db5094a71aa29b4402712e
561
vured-bot
Apache License 2.0
app/src/main/java/com/ghstudios/android/features/monsters/detail/MonsterRewardFragment.kt
gatheringhallstudios
60,881,315
false
null
package com.ghstudios.android.features.monsters.detail import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle import android.support.v4.app.ListFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.ghstudios.android.AssetLoader import com.ghstudios.android.ClickListeners.BasicItemClickListener import com.ghstudios.android.SectionArrayAdapter import com.ghstudios.android.data.classes.HuntingReward import com.ghstudios.android.loader.HuntingRewardListCursorLoader import com.ghstudios.android.mhgendatabase.R import java.io.IOException class MonsterRewardFragment : ListFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_generic_list,container,false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewModel = ViewModelProviders.of(activity!!).get(MonsterDetailViewModel::class.java) val rank = this.arguments?.get(ARG_RANK) if(rank == HuntingRewardListCursorLoader.RANK_LR) viewModel.rewardLRData.observe(this, Observer<List<HuntingReward>>{this.populateRewards(it)}) if(rank == HuntingRewardListCursorLoader.RANK_HR) viewModel.rewardHRData.observe(this, Observer<List<HuntingReward>>{this.populateRewards(it)}) if(rank == HuntingRewardListCursorLoader.RANK_G) viewModel.rewardGData.observe(this, Observer<List<HuntingReward>>{this.populateRewards(it)}) } private fun populateRewards(rewards:List<HuntingReward>?){ listAdapter = RewardAdapter(this.context!!,rewards!!) } private class RewardAdapter(context: Context, items:List<HuntingReward>) : SectionArrayAdapter<HuntingReward>(context,items,R.layout.listview_generic_header){ override fun getGroupName(item: HuntingReward?): String { return item?.condition ?: "" } override fun newView(context: Context?, item: HuntingReward?, parent: ViewGroup?): View { return LayoutInflater.from(context!!).inflate(R.layout.fragment_monster_reward_listitem,parent,false) } override fun bindView(view: View?, context: Context?, huntingReward: HuntingReward?) { if(view == null || huntingReward == null) return val itemLayout = view.findViewById<View>(R.id.listitem) as RelativeLayout val itemImageView = view.findViewById<View>(R.id.item_image) as ImageView val itemTextView = view.findViewById<View>(R.id.item) as TextView val amountTextView = view.findViewById<View>(R.id.amount) as TextView val percentageTextView = view.findViewById<View>(R.id.percentage) as TextView val cellItemText = huntingReward.item!!.name val cellAmountText = huntingReward.stackSize val cellPercentageText = huntingReward.percentage itemTextView.text = cellItemText amountTextView.text = "x$cellAmountText" val percent = "$cellPercentageText%" percentageTextView.text = percent AssetLoader.setIcon(itemImageView,huntingReward.item!!) itemLayout.tag = huntingReward.item!!.id itemLayout.setOnClickListener(BasicItemClickListener(context, huntingReward.item!!.id)) } } companion object { private val ARG_MONSTER_ID = "MONSTER_ID" private val ARG_RANK = "RANK" @JvmStatic fun newInstance(monsterId: Long, rank: String): MonsterRewardFragment { val args = Bundle() args.putLong(ARG_MONSTER_ID, monsterId) args.putString(ARG_RANK, rank) val f = MonsterRewardFragment() f.arguments = args return f } } }
12
null
37
90
572ede48d78b9f61a91c7ef1fc64f87c9743b162
4,093
MHGenDatabase
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/coop/StartCoopPointReq.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package data.coop import org.anime_game_servers.core.base.Version.GI_1_4_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand @AddedIn(GI_1_4_0) @ProtoCommand(REQUEST) internal interface StartCoopPointReq { var coopPoint: Int }
1
Kotlin
3
6
b342ff34dfb0f168a902498b53682c315c40d44e
386
anime-game-multi-proto
MIT License
app/src/main/java/foodapp/com/foodapp/main/ui/HeroImageFragment.kt
ahamedcool
164,127,093
true
{"Kotlin": 53248, "Java": 5539}
package foodapp.com.foodapp.main.ui import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.core.app.ActivityOptionsCompat import androidx.core.view.ViewCompat import androidx.fragment.app.Fragment import com.squareup.picasso.Picasso import foodapp.com.foodapp.R class HeroImageFragment : Fragment() { companion object { const val ARG_IMAGE_RES = "image_res" const val ARG_IMAGE_URL = "image_url" fun newInstance(@DrawableRes imageRes: Int = -1, imageUrl: String = ""): HeroImageFragment { val fragment = HeroImageFragment() val bundle = Bundle() if (imageRes != -1) { bundle.putInt(ARG_IMAGE_RES, imageRes) } if (!TextUtils.isEmpty(imageUrl)) { bundle.putString(ARG_IMAGE_URL, imageUrl) } fragment.arguments = bundle return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_hero_image, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val imageView = view.findViewById<ImageView>(R.id.heroImageView) if (arguments!!.containsKey(ARG_IMAGE_RES)) { val imageRes = arguments!!.getInt(ARG_IMAGE_RES) Picasso.get().load(imageRes).fit().noFade().centerCrop().into(imageView) return } if (arguments!!.containsKey(ARG_IMAGE_URL)) { val imageUrl = arguments!!.getString(ARG_IMAGE_URL) ViewCompat.setTransitionName(imageView, imageUrl) Picasso.get().load(imageUrl).fit().noFade().centerCrop().into(imageView) view.setOnClickListener { activity?.let { val p1 = androidx.core.util.Pair.create<View, String>(imageView, imageUrl) val options = ActivityOptionsCompat.makeSceneTransitionAnimation(it, p1) //startActivity(DishDetailsActivity.newInstance(it, imageUrl), options.toBundle()) } } return } } }
0
Kotlin
0
0
a1d19351b51ac54294a078fee268ef84f4f81d4b
2,418
FoodApp
Apache License 2.0
app/src/main/java/com/boreal/ultimatetest/domain/model/characters/Origin.kt
baudelioandalon
853,655,370
false
{"Kotlin": 129014}
package com.boreal.ultimatetest.domain.model.characters import androidx.compose.runtime.Immutable @kotlinx.serialization.Serializable @Immutable data class Origin( val name: String = "", val url: String = "" )
0
Kotlin
0
0
29d5733fb3b9949665ef0da28df9bfc4c8b69b7d
219
UltimateTest
Apache License 2.0
app/src/main/java/com/cyberwalker/fashionstore/ui/theme/Type.kt
cyph3rcod3r
535,256,550
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cyberwalker.fashionstore.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.cyberwalker.fashionstore.R val poppinsFamily = FontFamily(Font(R.font.poppins, FontWeight.Normal)) // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) ) val Typography.large: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W500, fontSize = 24.sp, ) val Typography.medium_14: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W500, fontSize = 14.sp, ) val Typography.medium_18: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W500, fontSize = 18.sp, ) val Typography.medium_18_bold: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W600, fontSize = 18.sp, ) val Typography.small_caption: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W400, fontSize = 12.sp, color = gray ) val Typography.small_caption2: TextStyle get() = TextStyle( fontFamily = poppinsFamily, fontWeight = FontWeight.W500, fontSize = 12.sp, )
0
null
8
87
90a375503c0e4aa08dac97154f5257101e3a780b
2,320
FashionStore
Apache License 2.0
birdo/src/main/java/com/prolificinteractive/birdo/ShakerDetector.kt
prolificinteractive
141,630,863
false
null
package com.prolificinteractive.birdo import android.content.Context import android.content.Context.SENSOR_SERVICE import android.hardware.SensorManager import com.squareup.seismic.ShakeDetector /** * One of the detector for starting Birdo. * * It will listen to shakes from the user and start Birdo upon shake. This listener needs to be * initialized in the application class of your app. */ open class ShakerDetector( private val context: Context, initializer: Initializer ) : Detector(initializer), ShakeDetector.Listener { /** * Start the detector. */ open fun detect() { ShakeDetector(this).start(context.getSystemService(SENSOR_SERVICE) as SensorManager?) } override fun hearShake() { initializer.start(context) } }
1
Kotlin
0
1
477a03de11b3fb0bb7da44d86b6aad206389dcbb
762
Birdo
MIT License
app/src/main/java/com/e444er/cleanmovie/feature_splash/presentation/splash/event/SplashEvent.kt
e444er
597,756,971
false
null
package com.e444er.cleanmovie.feature_splash.presentation.splash.event import androidx.navigation.NavDirections import com.e444er.cleanmovie.core.presentation.util.UiText sealed class SplashEvent { data class NavigateTo(val directions: NavDirections) : SplashEvent() data class UpdateAppLanguage(val language: String) : SplashEvent() data class UpdateUiMode(val uiMode: Int) : SplashEvent() }
0
Kotlin
0
0
1c939de424b4eb254fd4258f4e56e4399bdfb3cd
406
KinoGoClean
Apache License 2.0
widget/src/main/java/com/lxj/widget/ShapeImageView.kt
junixapp
160,308,163
false
null
package com.lxj.androidktx.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Outline import android.graphics.Paint import android.graphics.drawable.ColorDrawable import android.graphics.drawable.GradientDrawable import android.os.Build import android.util.AttributeSet import android.view.View import android.view.ViewOutlineProvider import androidx.appcompat.widget.AppCompatImageView import com.lxj.androidktx.R import com.lxj.androidktx.core.createDrawable /** * Description: 能设置Shape的TextView * Create by dance, at 2019/5/21 */ open class ShapeImageView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatImageView(context, attributeSet, defStyleAttr) { private var mSolid = 0 //填充色 private var mStroke = 0 //边框颜色 private var mStrokeWidth = 0 //边框大小 private var mCorner = 0 //圆角 private var mEnableRipple = false private var mRound = false private var mRippleColor = Color.parseColor("#88999999") private var mGradientStartColor = 0 private var mGradientCenterColor = 0 private var mGradientEndColor = 0 private var mGradientOrientation = GradientDrawable.Orientation.LEFT_RIGHT //从左到右 private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG) init { val ta = context.obtainStyledAttributes(attributeSet, R.styleable.ShapeImageView) mSolid = ta.getColor(R.styleable.ShapeImageView_siv_solid, mSolid) mStroke = ta.getColor(R.styleable.ShapeImageView_siv_stroke, mStroke) mStrokeWidth = ta.getDimensionPixelSize(R.styleable.ShapeImageView_siv_strokeWidth, mStrokeWidth) mCorner = ta.getDimensionPixelSize(R.styleable.ShapeImageView_siv_corner, mCorner) mRound = ta.getBoolean(R.styleable.ShapeImageView_siv_round, mRound) mEnableRipple = ta.getBoolean(R.styleable.ShapeImageView_siv_enableRipple, mEnableRipple) mRippleColor = ta.getColor(R.styleable.ShapeImageView_siv_rippleColor, mRippleColor) mGradientStartColor = ta.getColor(R.styleable.ShapeImageView_siv_gradientStartColor, mGradientStartColor) mGradientCenterColor = ta.getColor(R.styleable.ShapeImageView_siv_gradientCenterColor, mGradientCenterColor) mGradientEndColor = ta.getColor(R.styleable.ShapeImageView_siv_gradientEndColor, mGradientEndColor) val orientation = ta.getInt(R.styleable.ShapeImageView_siv_gradientOrientation, GradientDrawable.Orientation.LEFT_RIGHT.ordinal) mGradientOrientation = when(orientation){ 0 -> GradientDrawable.Orientation.TOP_BOTTOM 1 -> GradientDrawable.Orientation.TR_BL 2 -> GradientDrawable.Orientation.RIGHT_LEFT 3 -> GradientDrawable.Orientation.BR_TL 4 -> GradientDrawable.Orientation.BOTTOM_TOP 5 -> GradientDrawable.Orientation.BL_TR 6 -> GradientDrawable.Orientation.LEFT_RIGHT else -> GradientDrawable.Orientation.TL_BR } ta.recycle() applySelf() if(Build.VERSION.SDK_INT >= 21){ clipToOutline = true } } fun applySelf() { var color : Int? = null if (background !=null && background is ColorDrawable && mSolid==Color.TRANSPARENT){ color = ( background as ColorDrawable) .color } val drawable = createDrawable(color = color ?: mSolid, radius = mCorner.toFloat(), strokeColor = mStroke, strokeWidth = mStrokeWidth, enableRipple = mEnableRipple, rippleColor = mRippleColor, gradientStartColor = mGradientStartColor, gradientEndColor = mGradientEndColor, gradientOrientation = mGradientOrientation) setBackgroundDrawable(drawable) if(Build.VERSION.SDK_INT >= 21){ outlineProvider = object : ViewOutlineProvider(){ override fun getOutline(view: View, outline: Outline) { outline.setRoundRect(0, 0, view.width, view.height, mCorner.toFloat()) } } strokePaint.strokeWidth = mStrokeWidth.toFloat() strokePaint.color = mStroke strokePaint.style = Paint.Style.STROKE } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if(mRound){ mCorner = Math.min(measuredWidth, measuredHeight)/2 } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas!!.drawRoundRect(0f,0f, measuredWidth.toFloat(), measuredHeight.toFloat(), mCorner.toFloat(),mCorner.toFloat(), strokePaint) } } fun setup(solid: Int = mSolid, stroke: Int = mStroke, strokeWidth: Int = mStrokeWidth, corner: Int = mCorner, enableRipple: Boolean = mEnableRipple, rippleColor: Int = mRippleColor, gradientStartColor: Int = mGradientStartColor, gradientEndColor: Int = mGradientEndColor, gradientOrientation: GradientDrawable.Orientation = mGradientOrientation, round: Boolean = mRound){ mSolid = solid mStroke = stroke mStrokeWidth = strokeWidth mCorner = corner mEnableRipple = enableRipple mRippleColor = rippleColor mGradientStartColor = gradientStartColor mGradientEndColor = gradientEndColor mGradientOrientation = gradientOrientation mRound = round applySelf() } }
2
null
69
770
b1f3f0cee86efd43fe7c8c763533762db9420d15
5,585
AndroidKTX
Apache License 2.0
app/src/main/java/com/example/currencyconverter/api/ApiClient.kt
jukka413
186,253,140
false
null
package com.example.currencyconverter.api import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import com.example.currencyconverter.api.model.LatestRates object ApiClient { private val BASE_URL: String = "https://api.exchangeratesapi.io" private val service: ApiInterface private val latestRates: MutableLiveData<LatestRates> = MutableLiveData() init { val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() service = retrofit.create(ApiInterface::class.java) } fun getLatestRates() : LiveData<LatestRates> = latestRates fun refreshLatestRates(baseCurrency : String) { service.getLatestRates(baseCurrency).enqueue(object : Callback<LatestRates> { override fun onFailure(call: Call<LatestRates>?, t: Throwable?) { } override fun onResponse(call: Call<LatestRates>, response: Response<LatestRates>) { if (response.isSuccessful) latestRates.value = response.body() } }) } }
0
Kotlin
0
0
de7cf658b2292c66760a42867c5faae3998521ed
1,321
Currency-converter
Apache License 2.0
umbrella-framework/src/iosMain/kotlin/CrashIntegration.kt
allegro
439,312,455
false
{"Kotlin": 450883, "Ruby": 849, "Swift": 668}
package sample import co.touchlab.crashkios.CrashHandler import co.touchlab.crashkios.setupCrashHandler fun crashInit(handler: CrashHandler){ setupCrashHandler(handler) }
2
Kotlin
5
19
026afe67f6dda91f2500663ff5f157603d58f29e
176
json-logic-kmp
Apache License 2.0
agp-7.1.0-alpha01/tools/base/build-system/gradle-api/src/main/java/com/android/build/api/variant/JniLibsApkPackaging.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.variant import org.gradle.api.provider.Provider /** * Defines an APK variant's packaging options for native library (.so) files. */ interface JniLibsApkPackaging : JniLibsPackaging { /** * Whether to use the legacy convention of compressing all .so files in the APK. This does not * affect APKs generated from the app bundle; see [useLegacyPackagingFromBundle]. */ val useLegacyPackaging: Provider<Boolean> /** * Whether to use the legacy convention of compressing all .so files when generating APKs from * the app bundle. If true, .so files will always be compressed when generating APKs from the * app bundle, regardless of the API level of the target device. If false, .so files will be * compressed only when targeting devices with API level < M. */ val useLegacyPackagingFromBundle: Provider<Boolean> }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
1,521
CppBuildCacheWorkInProgress
Apache License 2.0
src/main/kotlin/org/crystal/intellij/references/CrRequireReference.kt
asedunov
353,165,557
false
null
package org.crystal.intellij.references import com.intellij.analysis.AnalysisBundle import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.ResolveResult import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileInfoManager import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.util.containers.map2Array import com.intellij.util.indexing.IndexingBundle import org.crystal.intellij.psi.CrFile import org.jetbrains.annotations.Nls class CrRequireReference( referenceSet: CrRequireReferenceSet, range: TextRange, index: Int, text: String ) : FileReference(referenceSet, range, index, text) { override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { return (fileReferenceSet as CrRequireReferenceSet).resolveResults.getOrNull(index) ?: ResolveResult.EMPTY_ARRAY } override fun getUnresolvedMessagePattern(): @Nls(capitalization = Nls.Capitalization.Sentence) String { val fileName = StringUtil.escapePattern(decode(canonicalText)) return AnalysisBundle.message( "error.cannot.resolve.file.or.dir", IndexingBundle.message(if (isLast) "terms.file" else "terms.directory"), if (isLast && !fileName.endsWith(".cr")) "$fileName.cr" else fileName ) } override fun createLookupItem(candidate: PsiElement?): Any? { if (candidate is CrFile) { return FileInfoManager._getLookupItem( candidate, FileUtil.getNameWithoutExtension(candidate.name), candidate.getIcon(0) ) } return super.createLookupItem(candidate) } }
11
Kotlin
4
7
98863bdd951c4b40124ce26e0849bfe1c7c226f1
1,921
intellij-crystal-lang
Apache License 2.0
app/src/main/java/com/example/android/navigation/GameWonFragment.kt
Ro-MP
583,744,745
false
{"Kotlin": 23086}
/* * Copyright 2018, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.navigation import android.content.Intent import android.os.Bundle import android.view.* import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.activity.addCallback import androidx.core.content.ContextCompat.startActivity import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.navigation.findNavController import androidx.navigation.ui.NavigationUI import com.example.android.navigation.databinding.FragmentGameWonBinding class GameWonFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding: FragmentGameWonBinding = DataBindingUtil.inflate( inflater, R.layout.fragment_game_won, container, false) binding.nextMatchButton.setOnClickListener { view?.findNavController() ?.navigate(GameWonFragmentDirections.actionGameWonFragmentToGameFragment()) } setupMenu() val args = GameWonFragmentArgs.fromBundle(requireArguments()) val text = "NumCorrect: ${args.numCorrect} \nQuestions answered: ${args.questionsAnswered}" Toast.makeText(context, text, Toast.LENGTH_LONG) .show() return binding.root } // Build implicit Intent to share the score private fun getShareintent() : Intent { val args = GameWonFragmentArgs.fromBundle(requireArguments()) val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType("text/plain") .putExtra(Intent.EXTRA_TEXT, getString(R.string.share_success_text, args.numCorrect, args.questionsAnswered)) return shareIntent } // Run the Intent private fun shareSucces(): Boolean { startActivity(getShareintent()) return true } private fun setupMenu() { (requireActivity() as MenuHost).addMenuProvider(object: MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.winner_menu, menu) // ResolveActivity - Make sure the shareIntent resolves to an Activity if (getShareintent().resolveActivity(requireActivity().packageManager) == null) { menu.findItem(R.id.share).isVisible = false } } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { when(menuItem.itemId){ R.id.share -> shareSucces() } return true } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } }
0
Kotlin
0
0
eacf9bb1b8d83e9647b8bec19c94e6b4e7ee101e
3,493
GCodelab_Navigation_Trivia
Apache License 2.0
src/main/kotlin/org/teamvoided/nullium/data/gen/tags/BlockTagsProvider.kt
TeamVoided
788,995,006
false
{"Kotlin": 12309, "Java": 1586}
package org.teamvoided.nullium.data.gen.tags import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider import net.minecraft.block.Blocks import net.minecraft.registry.HolderLookup import net.minecraft.registry.tag.BlockTags import org.teamvoided.nullium.data.NulliumBlockTags import java.util.concurrent.CompletableFuture class BlockTagsProvider(output: FabricDataOutput, registriesFuture: CompletableFuture<HolderLookup.Provider>) : FabricTagProvider.BlockTagProvider(output, registriesFuture) { override fun configure(arg: HolderLookup.Provider) { //Cane Tags getOrCreateTagBuilder(NulliumBlockTags.CANE_HYDRATION) .add(Blocks.ICE) .add(Blocks.FROSTED_ICE) getOrCreateTagBuilder(NulliumBlockTags.CANE_SUPPORT) .forceAddTag(BlockTags.DIRT) .forceAddTag(BlockTags.SAND) .add(Blocks.SOUL_SOIL) .add(Blocks.SOUL_SAND) } }
0
Kotlin
0
1
ff060b56d644b4636b30a42113168422f0f223f7
1,000
Nullium
MIT License
app/src/main/java/xyz/dean/androiddemos/demos/infinite_list/ScrollCenterRecyclerView.kt
deanssss
203,539,447
false
null
package xyz.dean.androiddemos.demos.infinite_list import android.content.Context import android.util.AttributeSet import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView class ScrollCenterRecyclerView @JvmOverloads constructor ( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : RecyclerView(context, attrs, defStyle) { fun scrollToCenter(position: Int) { val smoothScroller = CenterSmoothScroller(context) smoothScroller.targetPosition = position layoutManager?.startSmoothScroll(smoothScroller) } } private class CenterSmoothScroller(context: Context) : LinearSmoothScroller(context) { override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int) = (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2) }
1
null
1
1
41020b7639c96b7d8d0a84edf63610153f07e2c3
908
AndroidDemos
Apache License 2.0
src/test/kotlin/apps/games/serious/preferans/PreferansScoreCounterTest.kt
JetBrains
61,370,887
false
null
package apps.games.serious.preferans import Settings import entity.User import org.junit.Assert.* import org.junit.Test /** * Created by user on 7/27/16. */ class PreferansScoreCounterTest { val user1 = User(Settings.hostAddress, "Alice") val user2 = User(Settings.hostAddress, "Bob") val user3 = User(Settings.hostAddress, "Charlie") /** * Simulate two rounds played in both rounds * first playerId takes 10 hands with other users just passing */ @Test fun checkOneUserBullet() { val scoreCounter = PreferansScoreCounter(listOf(user1, user2, user3), maxBulletPerUser = 5) val handsTaken = mutableMapOf(user1 to 0, user2 to 0, user3 to 0) val whists = mapOf(user1 to Whists.UNKNOWN, user2 to Whists.PASS, user3 to Whists.PASS) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) //Now user1 has 10 in bullet. game is played until 15 assertFalse(scoreCounter.endOfGameReached()) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) //Now user1 has 20 in bullet. assertTrue(scoreCounter.endOfGameReached()) assertEquals(20, scoreCounter.bullet[user1]) assertEquals(0, scoreCounter.bullet[user2]) assertEquals(0, scoreCounter.bullet[user3]) assertEquals(0, scoreCounter.heap[user1]) assertEquals(0, scoreCounter.heap[user2]) assertEquals(0, scoreCounter.heap[user3]) val res = scoreCounter.getFinalScores() assertEquals(266, res[user1]) assertEquals(-133, res[user2]) assertEquals(-133, res[user3]) } /** * Simulate following game flow: * -user1 successfully played 10 NO TRUMP * -user2 successfully played 6 NO TRUMP * -user3 successfully played MIZER * -user1 successfully played 10 NO TRUMP */ @Test fun checkEveryoneBullet() { val scoreCounter = PreferansScoreCounter(listOf(user1, user2, user3), maxBulletPerUser = 10) val handsTaken = mutableMapOf(user1 to 0, user2 to 0, user3 to 0) val whists = mapOf(user1 to Whists.PASS, user2 to Whists.PASS, user3 to Whists.PASS) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) scoreCounter.updateScore(handsTaken, Bet.SIX_NO_TRUMP, whists, user2) scoreCounter.updateScore(handsTaken, Bet.MIZER, whists, user3) //Now user1 has 10 in bullet. user2 has 2, user3 has 10 assertFalse(scoreCounter.endOfGameReached()) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) //Now user1 has 20 in bullet. assertTrue(scoreCounter.endOfGameReached()) assertEquals(20, scoreCounter.bullet[user1]) assertEquals(2, scoreCounter.bullet[user2]) assertEquals(10, scoreCounter.bullet[user3]) assertEquals(0, scoreCounter.heap[user1]) assertEquals(0, scoreCounter.heap[user2]) assertEquals(0, scoreCounter.heap[user3]) val res = scoreCounter.getFinalScores() assertEquals(186, res[user1]) assertEquals(-173, res[user2]) assertEquals(-13, res[user3]) } /** * Simulate game flow: * -user1 wants to play 10, takes 6 * -user2 wants to play 6, takes 10 * -user3 wants to play 9, takes 6 * -user3 wants to play 9, takes 6 * -everyone passed (2, 2, 6) * -everyone passed (3, 3, 4) * -everyone passed (0, 7, 3) * -user1 successfully played 10 * -user1 successfully played 10 * -user1 successfully played 10 */ @Test fun checkAllCells() { val scoreCounter = PreferansScoreCounter(listOf(user1, user2, user3), maxBulletPerUser = 10) val handsTaken = mutableMapOf(user1 to 0, user2 to 0, user3 to 0) val whists = mutableMapOf(user1 to Whists.PASS, user2 to Whists.WHIST_BLIND, user3 to Whists.PASS) //first playerId failed to play 10, took only 6 handsTaken[user1] = 6 handsTaken[user2] = 2 handsTaken[user3] = 2 scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) //user 2 said, he plays 6, both whisted, took 10 handsTaken[user1] = 0 handsTaken[user2] = 10 handsTaken[user3] = 0 whists[user2] = Whists.PASS whists[user1] = Whists.WHIST_BLIND whists[user3] = Whists.WHIST_BLIND scoreCounter.updateScore(handsTaken, Bet.SIX_NO_TRUMP, whists, user2) //first playerId failed to play 9, took only 6 handsTaken[user1] = 2 handsTaken[user2] = 2 handsTaken[user3] = 6 whists[user1] = Whists.PASS whists[user2] = Whists.WHIST_BLIND whists[user3] = Whists.PASS scoreCounter.updateScore(handsTaken, Bet.NINE_NO_TRUMP, whists, user3) //Now user1 has 10 in bullet. user2 has 2, user3 has 10 assertFalse(scoreCounter.endOfGameReached()) //First playerId won 30 two times in a row, ending the game handsTaken[user1] = 2 handsTaken[user2] = 2 handsTaken[user3] = 6 whists[user1] = Whists.PASS whists[user2] = Whists.PASS whists[user3] = Whists.PASS scoreCounter.updateScore(handsTaken, Bet.PASS, null, null) handsTaken[user1] = 3 handsTaken[user2] = 3 handsTaken[user3] = 4 scoreCounter.updateScore(handsTaken, Bet.PASS, null, null) handsTaken[user1] = 0 handsTaken[user2] = 7 handsTaken[user3] = 3 scoreCounter.updateScore(handsTaken, Bet.PASS, null, null) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) scoreCounter.updateScore(handsTaken, Bet.TEN_NO_TRUMP, whists, user1) //Now user1 has 20 in bullet. assertTrue(scoreCounter.endOfGameReached()) assertEquals(30, scoreCounter.bullet[user1]) assertEquals(2, scoreCounter.bullet[user2]) assertEquals(0, scoreCounter.bullet[user3]) assertEquals(100, scoreCounter.heap[user1]) assertEquals(58, scoreCounter.heap[user2]) assertEquals(98, scoreCounter.heap[user3]) assertEquals(80, scoreCounter.whists[user1 to user3]) assertEquals(80, scoreCounter.whists[user2 to user3]) assertEquals(120, scoreCounter.whists[user2 to user1]) assertEquals(120, scoreCounter.whists[user3 to user1]) val res = scoreCounter.getFinalScores() assertEquals(80, res[user1]) assertEquals(300, res[user2]) assertEquals(-380, res[user3]) } }
2
null
4
9
319cab30277110edaa698b237b3c77e5380377bf
6,682
p2p-games
Apache License 2.0
src/main/kotlin/mcx/pass/frontend/elaborate/Elaborate.kt
mcenv
558,700,207
false
null
package mcx.pass.frontend.elaborate import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.plus import kotlinx.collections.immutable.toPersistentList import mcx.ast.* import mcx.ast.Annotation import mcx.lsp.Instruction import mcx.lsp.contains import mcx.lsp.diagnostic import mcx.pass.* import mcx.pass.frontend.Resolve import mcx.util.collections.mapWith import org.eclipse.lsp4j.* import org.eclipse.lsp4j.jsonrpc.messages.Either.forLeft import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract import mcx.ast.Core as C import mcx.ast.Resolved as R @Suppress("NAME_SHADOWING", "NOTHING_TO_INLINE") class Elaborate private constructor( dependencies: List<C.Module>, private val input: Resolve.Result, private val instruction: Instruction?, ) { private val meta: Meta = Meta() private val definitions: MutableMap<DefinitionLocation, C.Definition> = dependencies.flatMap { dependency -> dependency.definitions.map { it.name to it } }.toMap().toMutableMap() private lateinit var location: DefinitionLocation private val diagnostics: MutableMap<DefinitionLocation, MutableList<Diagnostic>> = hashMapOf() private var hover: (() -> Hover)? = null private var inlayHints: MutableList<InlayHint> = mutableListOf() private fun elaborate(): Result { val module = elaborateModule(input.module) val diagnostics = (input.diagnostics.keys + diagnostics.keys).associateWith { location -> (input.diagnostics[location] ?: emptyList()) + (diagnostics[location] ?: emptyList()) } return Result( module, diagnostics, hover, inlayHints, ) } private fun elaborateModule( module: R.Module, ): C.Module { module.imports.forEach { import -> when (val definition = definitions[import.value]) { is C.Definition.Def -> hoverDef(import.range, definition) else -> {} } } val definitions = module.definitions.values.mapNotNull { elaborateDefinition(it) } return C.Module(module.name, definitions) } private fun elaborateDefinition( definition: R.Definition, ): C.Definition? { if (definition is R.Definition.Hole) { return null } val doc = definition.doc val annotations = definition.annotations.map { it.value } val modifiers = definition.modifiers.map { it.value } val name = definition.name.value location = name return when (definition) { is R.Definition.Def -> { val modifiers = if (definition.body.let { it is R.Term.FuncOf && !it.open }) modifiers + Modifier.DIRECT else modifiers val ctx = emptyCtx() val phase = getPhase(modifiers) val type = ctx.checkTerm(definition.type, phase, meta.freshType(definition.type.range)) if (Modifier.REC in modifiers) { definitions[name] = C.Definition.Def(doc, annotations, modifiers, name, type, null) } val body = definition.body?.let { ctx.checkTerm(it, phase, ctx.env.evalTerm(type)) } val (zonkedType, zonkedBody) = meta.checkSolved(diagnostics.computeIfAbsent(location) { mutableListOf() }, type, body) C.Definition.Def(doc, annotations, modifiers, name, zonkedType!!, zonkedBody).also { hoverDef(definition.name.range, it) } } is R.Definition.Hole -> error("Unreachable") }.also { definitions[name] = it } } private inline fun Ctx.synthTerm( term: R.Term, phase: Phase, ): Pair<C.Term, Value> { return elaborateTerm(term, phase, null) } private inline fun Ctx.checkTerm( term: R.Term, phase: Phase, type: Value, ): C.Term { return elaborateTerm(term, phase, type).first } private fun Ctx.elaborateTerm( term: R.Term, phase: Phase, type: Value?, ): Pair<C.Term, Value> { val type = type?.let { meta.forceValue(type) } return when { term is R.Term.Tag && phase == Phase.CONST && synth(type) -> { C.Term.Tag to Value.Type.END } term is R.Term.TagOf && phase == Phase.CONST && synth(type) -> { C.Term.TagOf(term.repr) to Value.Tag } term is R.Term.Type && synth(type) -> { val tag = checkTerm(term.element, Phase.CONST, Value.Tag) C.Term.Type(tag) to Value.Type.BYTE } term is R.Term.Bool && synth(type) -> { C.Term.Bool to Value.Type.BYTE } term is R.Term.BoolOf && synth(type) -> { C.Term.BoolOf(term.value) to Value.Bool } term is R.Term.If && match<Value>(type) -> { val condition = checkTerm(term.condition, phase, Value.Bool) val (thenBranch, thenBranchType) = /* TODO: avoid duplication? */ duplicate().elaborateTerm(term.thenBranch, phase, type) val (elseBranch, elseBranchType) = elaborateTerm(term.elseBranch, phase, type) val type = type ?: Value.Union(listOf(lazyOf(thenBranchType), lazyOf(elseBranchType)), thenBranchType.type /* TODO: validate */) typed(type) { C.Term.If(condition, thenBranch, elseBranch, it) } } term is R.Term.I8 && synth(type) -> { C.Term.I8 to Value.Type.BYTE } term is R.Term.NumOf && term.value is Byte && synth(type) -> { C.Term.I8Of(term.value) to Value.I8 } term is R.Term.NumOf && term.inferred && term.value is Long && check<Value.I8>(type) -> { C.Term.I8Of(term.value.toByte() /* TODO: check range */) to Value.I8 } term is R.Term.I16 && synth(type) -> { C.Term.I16 to Value.Type.SHORT } term is R.Term.NumOf && term.value is Short && synth(type) -> { C.Term.I16Of(term.value) to Value.I16 } term is R.Term.NumOf && term.inferred && term.value is Long && check<Value.I16>(type) -> { C.Term.I16Of(term.value.toShort() /* TODO: check range */) to Value.I16 } term is R.Term.I32 && synth(type) -> { C.Term.I32 to Value.Type.INT } term is R.Term.NumOf && term.value is Int && synth(type) -> { C.Term.I32Of(term.value) to Value.I32 } term is R.Term.NumOf && term.inferred && term.value is Long && synth(type) -> { C.Term.I32Of(term.value.toInt() /* TODO: check range */) to Value.I32 } term is R.Term.I64 && synth(type) -> { C.Term.I64 to Value.Type.LONG } term is R.Term.NumOf && term.value is Long && synth(type) -> { C.Term.I64Of(term.value) to Value.I64 } term is R.Term.NumOf && term.inferred && term.value is Long && check<Value.I64>(type) -> { C.Term.I64Of(term.value) to Value.I64 } term is R.Term.F32 && synth(type) -> { C.Term.F32 to Value.Type.FLOAT } term is R.Term.NumOf && term.value is Float && synth(type) -> { C.Term.F32Of(term.value) to Value.F32 } term is R.Term.NumOf && term.inferred && term.value is Double && check<Value.F32>(type) -> { C.Term.F32Of(term.value.toFloat() /* TODO: check range */) to Value.F32 } term is R.Term.F64 && synth(type) -> { C.Term.F64 to Value.Type.DOUBLE } term is R.Term.NumOf && term.value is Double && synth(type) -> { C.Term.F64Of(term.value) to Value.F64 } term is R.Term.Str && synth(type) -> { C.Term.Str to Value.Type.STRING } term is R.Term.StrOf && synth(type) -> { C.Term.StrOf(term.value) to Value.Str } term is R.Term.I8Array && synth(type) -> { C.Term.I8Array to Value.Type.BYTE_ARRAY } term is R.Term.I8ArrayOf && synth(type) -> { val elements = term.elements.map { checkTerm(it, phase, Value.I8) } C.Term.I8ArrayOf(elements) to Value.I8Array } term is R.Term.I32Array && synth(type) -> { C.Term.I32Array to Value.Type.INT_ARRAY } term is R.Term.I32ArrayOf && synth(type) -> { val elements = term.elements.map { checkTerm(it, phase, Value.I32) } C.Term.I32ArrayOf(elements) to Value.I32Array } term is R.Term.I64Array && synth(type) -> { C.Term.I64Array to Value.Type.LONG_ARRAY } term is R.Term.I64ArrayOf && synth(type) -> { val elements = term.elements.map { checkTerm(it, phase, Value.I64) } C.Term.I64ArrayOf(elements) to Value.I64Array } term is R.Term.Vec && synth(type) -> { val element = checkTerm(term.element, phase, meta.freshType(term.element.range)) C.Term.Vec(element) to Value.Type.LIST } term is R.Term.VecOf && match<Value.Vec>(type) -> { val elementType = type?.element?.value val (elements, elementsTypes) = term.elements.map { elaborateTerm(it, phase, elementType) }.unzip() val type = type ?: Value.Vec(lazyOf(Value.Union(elementsTypes.map { lazyOf(it) }, elementsTypes.firstOrNull()?.type ?: Value.Type.END_LAZY))) typed(type) { C.Term.VecOf(elements, it) } } term is R.Term.Struct && synth(type) -> { val elements = term.elements.associateTo(linkedMapOf()) { (key, element) -> val element = checkTerm(element, phase, meta.freshType(element.range)) key.value to element } C.Term.Struct(elements) to Value.Type.COMPOUND } term is R.Term.StructOf && synth(type) -> { val elements = linkedMapOf<String, C.Term>() val elementsTypes = linkedMapOf<String, Lazy<Value>>() term.elements.forEach { (key, element) -> val (element, elementType) = synthTerm(element, phase) elements[key.value] = element elementsTypes[key.value] = lazyOf(elementType) } val type = Value.Struct(elementsTypes) typed(type) { C.Term.StructOf(elements, it) } } term is R.Term.StructOf && check<Value.Struct>(type) -> { val elements = term.elements.associateTo(linkedMapOf()) { (name, element) -> val (element, elementType) = elaborateTerm(element, phase, type.elements[name.value]?.value) name.value to element } typed(type) { C.Term.StructOf(elements, it) } } term is R.Term.Ref && synth(type) -> { val element = checkTerm(term.element, phase, meta.freshType(term.element.range)) C.Term.Ref(element) to Value.Type.INT } term is R.Term.RefOf && match<Value.Ref>(type) -> { val (element, elementType) = elaborateTerm(term.element, phase, type?.element?.value) val type = type ?: Value.Ref(lazyOf(elementType)) typed(type) { C.Term.RefOf(element, it) } } term is R.Term.Point && synth(type) -> { // TODO: unify tags val (element, elementType) = synthTerm(term.element, phase) val type = elementType.type.value typed(type) { C.Term.Point(element, it) } } term is R.Term.Union && match<Value.Type>(type) -> { val type = type ?: meta.freshType(term.range) val elements = term.elements.map { checkTerm(it, phase, type) } typed(type) { C.Term.Union(elements, it) } } term is R.Term.Func && synth(type) -> { val (ctx, params) = term.params.mapWith(this) { transform, (pattern, term) -> val term = checkTerm(term, phase, meta.freshType(term.range)) val vTerm = env.evalTerm(term) elaboratePattern(pattern, phase, vTerm, lazyOf(Value.Var("#${next()}", next(), lazyOf(vTerm)))) { (pattern, patternType) -> transform(this) pattern to term } } val result = ctx.checkTerm(term.result, phase, meta.freshType(term.result.range)) val type = if (term.open) Value.Type.COMPOUND else Value.Type.INT C.Term.Func(term.open, params, result) to type } term is R.Term.FuncOf && synth(type) -> { val (ctx, params) = term.params.mapWith(this) { transform, param -> val paramType = meta.freshValue(param.range) elaboratePattern(param, phase, paramType, lazyOf(Value.Var("#${next()}", next(), lazyOf(paramType)))) { (pattern, patternType) -> transform(this) pattern to lazyOf(patternType) } } val (result, resultType) = ctx.synthTerm(term.result, phase) val type = Value.Func(term.open, params, Closure(env, next().quoteValue(resultType))) typed(type) { C.Term.FuncOf(term.open, params.map { param -> param.first }, result, it) } } term is R.Term.FuncOf && check<Value.Func>(type) && term.open == type.open -> { if (type.params.size == term.params.size) { val (ctx, params) = (term.params zip type.params).mapWith(this) { transform, (pattern, term) -> val paramType = term.second.value elaboratePattern(pattern, phase, paramType, lazyOf(Value.Var("#${next()}", next(), lazyOf(paramType)))) { transform(this) it } } val result = ctx.checkTerm(term.result, phase, type.result.open(next(), params.map { lazyOf(it.second) })) typed(type) { C.Term.FuncOf(term.open, params.map { param -> param.first }, result, it) } } else { invalidTerm(arityMismatch(type.params.size, term.params.size, term.range)) } } term is R.Term.Apply && synth(type) -> { val (func, maybeFuncType) = synthTerm(term.func, phase) val funcType = when (val funcType = meta.forceValue(maybeFuncType)) { is Value.Func -> funcType else -> return invalidTerm(cannotSynthesize(term.func.range)) // TODO: unify? } if (funcType.params.size != term.args.size) { return invalidTerm(arityMismatch(funcType.params.size, term.args.size, term.range)) } val (_, args) = (term.args zip funcType.params).mapWith(env) { transform, (arg, param) -> val paramType = evalTerm(next().quoteValue(param.second.value)) // TODO: use telescopic closure val arg = checkTerm(arg, phase, paramType) transform(this + lazy { evalTerm(arg) }) arg } val (_, vArgs) = args.mapWith(env) { transform, arg -> val vArg = lazy { env.evalTerm(arg) } transform(env + vArg) vArg } val type = funcType.result(vArgs) typed(type) { C.Term.Apply(funcType.open, func, args, it) } } term is R.Term.Code && phase == Phase.CONST && synth(type) -> { val element = checkTerm(term.element, phase, meta.freshType(term.element.range)) C.Term.Code(element) to Value.Type.END } term is R.Term.CodeOf && phase == Phase.CONST && match<Value.Code>(type) -> { val (element, elementType) = elaborateTerm(term.element, phase, type?.element?.value) val type = type ?: Value.Code(lazyOf(elementType)) typed(type) { C.Term.CodeOf(element, it) } } term is R.Term.Splice && match<Value>(type) -> { val type = type ?: meta.freshValue(term.range) val element = checkTerm(term.element, Phase.CONST, Value.Code(lazyOf(type))) typed(type) { C.Term.Splice(element, it) } } term is R.Term.Command && match<Value>(type) -> { val type = type ?: meta.freshValue(term.range) val element = checkTerm(term.element, Phase.CONST, Value.Str) typed(type) { C.Term.Command(element, it) } } term is R.Term.Let && match<Value>(type) -> { val (init, initType) = synthTerm(term.init, phase) elaboratePattern(term.binder, phase, initType, lazy { env.evalTerm(init) }) { (binder, binderType) -> if (next().sub(initType, binderType)) { val (body, bodyType) = elaborateTerm(term.body, phase, type) val type = type ?: bodyType [email protected](type) { C.Term.Let(binder, init, body, it) } } else { invalidTerm(next().typeMismatch(initType, binderType, term.init.range)) } } } term is R.Term.Match && match<Value>(type) -> { val (scrutinee, scrutineeType) = synthTerm(term.scrutinee, phase) val vScrutinee = lazy { env.evalTerm(scrutinee) } // TODO: duplicate context // TODO: check exhaustiveness val (branches, branchesTypes) = term.branches.map { (pattern, body) -> elaboratePattern(pattern, phase, scrutineeType, vScrutinee) { (pattern, _) -> val (body, bodyType) = elaborateTerm(body, phase, type) (pattern to body) to bodyType } }.unzip() val type = type ?: Value.Union(branchesTypes.map { lazyOf(it) }, branchesTypes.firstOrNull()?.let { lazyOf(it) } ?: Value.Type.END_LAZY /* TODO: validate */) typed(type) { C.Term.Match(scrutinee, branches, it) } } term is R.Term.Var && synth(type) -> { val entry = entries[term.idx.toLvl(Lvl(entries.size)).value] if (entry.used) { invalidTerm(alreadyUsed(term.range)) } else { val type = meta.forceValue(entry.value.type.value) if (type is Value.Ref) { entry.used = true } when { entry.phase == phase -> { next().quoteValue(entry.value) to type } entry.phase < phase -> { inlayHint(term.range.start, "`") typed(Value.Code(lazyOf(type))) { C.Term.CodeOf(next().quoteValue(entry.value), it) } } entry.phase > phase && type is Value.Code -> { inlayHint(term.range.start, "$") typed(type.element.value) { C.Term.Splice(next().quoteValue(entry.value), it) } } else -> { invalidTerm(phaseMismatch(phase, entry.phase, term.range)) } } } } term is R.Term.Def && synth(type) -> { when (val definition = definitions[term.name]) { is C.Definition.Def -> { hoverDef(term.range, definition) if (Annotation.Deprecated in definition.annotations) { diagnose(deprecated(term.range)) } if (Annotation.Unstable in definition.annotations) { diagnose(unstable(term.range)) } if (Annotation.Delicate in definition.annotations) { diagnose(delicate(term.range)) } val actualPhase = getPhase(definition.modifiers) if (actualPhase <= phase) { val def = C.Term.Def(definition, definition.type) val type = env.evalTerm(definition.type) def to type } else { invalidTerm(phaseMismatch(phase, actualPhase, term.range)) } } else -> { invalidTerm(expectedDef(term.range)) } } } term is R.Term.Meta && match<Value>(type) -> { val type = type ?: meta.freshValue(term.range) next().quoteValue(meta.freshValue(term.range)) to type } term is R.Term.As && synth(type) -> { val type = env.evalTerm(checkTerm(term.type, phase, meta.freshType(term.type.range))) checkTerm(term.element, phase, type) to type } term is R.Term.Hole && match<Value>(type) -> { C.Term.Hole to Value.Hole } synth(type) && phase == Phase.WORLD -> { invalidTerm(phaseMismatch(Phase.CONST, phase, term.range)) } synth(type) -> { invalidTerm(cannotSynthesize(term.range)) } check<Value>(type) -> { val (synth, synthType) = synthTerm(term, phase) lateinit var diagnostic: Lazy<Diagnostic> fun sub(value1: Value, value2: Value): Boolean { return if (next().sub(value1, value2)) { true } else if (value2 is Value.Point) { val element1 = env.evalTerm(synth) val element2 = value2.element.value with(meta) { next().unifyValue(element1, element2) }.also { if (!it) { diagnostic = lazy { next().typeMismatch(element1, element2, term.range) } } } } else { diagnostic = lazy { next().typeMismatch(value1, value2, term.range) } false } } if (sub(synthType, type)) { return synth to type } else if (type is Value.Code && sub(synthType, type.element.value)) { inlayHint(term.range.start, "`") return typed(type) { C.Term.CodeOf(synth, it) } } else if (synthType is Value.Code && sub(synthType.element.value, type)) { inlayHint(term.range.start, "$") return typed(type) { C.Term.Splice(synth, it) } } invalidTerm(diagnostic.value) } else -> { error("Unreachable") } }.also { (_, type) -> hoverType(term.range, type) } } private inline fun <T> Ctx.elaboratePattern( pattern: R.Pattern, phase: Phase, type: Value, value: Lazy<Value>, block: Ctx.(Pair<C.Pattern, Value>) -> T, ): T { val entries = mutableListOf<Ctx.Entry>() val result = bindPattern(entries, pattern, phase, type) { it } val ctx = Ctx(this.entries + entries, env + value) return ctx.block(result) } private fun Ctx.bindPattern( entries: MutableList<Ctx.Entry>, pattern: R.Pattern, phase: Phase, type: Value?, make: (Value) -> Value, ): Pair<C.Pattern, Value> { val type = type?.let { meta.forceValue(type) } return when { pattern is R.Pattern.I32Of && synth(type) -> { C.Pattern.I32Of(pattern.value) to Value.I32 } pattern is R.Pattern.StructOf && match<Value.Struct>(type) -> { val results = pattern.elements.associateTo(linkedMapOf()) { (name, element) -> val type = type?.elements?.get(name.value)?.value ?: invalidTerm(unknownKey(name.value, name.range)).second val (element, elementType) = bindPattern(entries, element, phase, type) { Value.Proj(make(it), Projection.StructOf(name.value), lazyOf(type)) } name.value to (element to elementType) } val elements = results.mapValuesTo(linkedMapOf()) { it.value.first } val type = type ?: Value.Struct(results.mapValuesTo(linkedMapOf()) { lazyOf(it.value.second) }) C.Pattern.StructOf(elements) to type } pattern is R.Pattern.Var && match<Value>(type) -> { val type = type ?: meta.freshValue(pattern.range) entries += Ctx.Entry(pattern.name, phase, make(Value.Var(pattern.name, next(), lazyOf(type))), false) C.Pattern.Var(pattern.name) to type } pattern is R.Pattern.Drop && match<Value>(type) -> { val type = type ?: meta.freshValue(pattern.range) C.Pattern.Drop to type } pattern is R.Pattern.As && synth(type) -> { val type = env.evalTerm(checkTerm(pattern.type, phase, meta.freshType(pattern.type.range))) bindPattern(entries, pattern.element, phase, type, make) } pattern is R.Pattern.Hole && match<Value>(type) -> { C.Pattern.Hole to Value.Hole } synth(type) -> { invalidPattern(cannotSynthesize(pattern.range)) } check<Value>(type) -> { val synth = bindPattern(entries, pattern, phase, null, make) if (next().sub(synth.second, type)) { synth } else { invalidPattern(next().typeMismatch(type, synth.second, pattern.range)) } } else -> { error("Unreachable") } }.also { (_, type) -> hoverType(pattern.range, type) } } private fun Lvl.sub( value1: Value, value2: Value, ): Boolean { val value1 = meta.forceValue(value1) val value2 = meta.forceValue(value2) return when { value1 is Value.Vec && value2 is Value.Vec -> { sub(value1.element.value, value2.element.value) } value1 is Value.Struct && value2 is Value.Struct -> { value1.elements.size == value2.elements.size && value1.elements.all { (key1, element1) -> value2.elements[key1]?.let { element2 -> sub(element1.value, element2.value) } ?: false } } value1 is Value.Ref && value2 is Value.Ref -> { sub(value1.element.value, value2.element.value) } value1 is Value.Point && value2 !is Value.Point -> { sub(value1.element.value.type.value, value2) } value1 is Value.Union -> { value1.elements.all { sub(it.value, value2) } } value2 is Value.Union -> { // TODO: implement subtyping with unification that has lower bound and upper bound if (value1 is Value.Meta && value2.elements.isEmpty()) { with(meta) { unifyValue(value1, value2) } } else { value2.elements.any { sub(value1, it.value) } } } value1 is Value.Func && value2 is Value.Func -> { value1.open == value2.open && value1.params.size == value2.params.size && (value1.params zip value2.params).all { (param1, param2) -> sub(param2.second.value, param1.second.value) } && sub( value1.result.open(this, value1.params.map { (_, type) -> type }), value2.result.open(this, value2.params.map { (_, type) -> type }), ) } value1 is Value.Code && value2 is Value.Code -> { sub(value1.element.value, value2.element.value) } else -> { with(meta) { unifyValue(value1, value2) } } } } private fun getPhase(modifiers: Collection<Modifier>): Phase { return if (Modifier.CONST in modifiers) Phase.CONST else Phase.WORLD } @OptIn(ExperimentalContracts::class) private inline fun synth(type: Value?): Boolean { contract { returns(false) implies (type != null) returns(true) implies (type == null) } return type == null } @OptIn(ExperimentalContracts::class) private inline fun <reified V : Value> check(type: Value?): Boolean { contract { returns(false) implies (type !is V) returns(true) implies (type is V) } return type is V } @OptIn(ExperimentalContracts::class) private inline fun <reified V : Value> match(type: Value?): Boolean { contract { returns(false) implies (type !is V?) returns(true) implies (type is V?) } return type is V? } private fun Ctx.hoverType( range: Range, type: Value, ) { hover(range) { val type = next().prettyValue(type) Hover(MarkupContent(MarkupKind.MARKDOWN, "```mcx\n$type\n```")) } } private fun hoverDef( range: Range, definition: C.Definition.Def, ) { hover(range) { val modifiers = definition.modifiers.joinToString(" ", "", " ").ifBlank { "" } val name = definition.name.name val type = prettyTerm(definition.type) val doc = definition.doc Hover(MarkupContent(MarkupKind.MARKDOWN, "```mcx\n${modifiers}def $name : $type\n```\n---\n$doc")) } } private fun hover( range: Range, message: () -> Hover, ) { if (hover == null && instruction is Instruction.Hover && instruction.position in range) { hover = message } } private fun inlayHint( position: Position, label: String, ) { if (instruction is Instruction.InlayHint && position in instruction.range) { inlayHints += InlayHint(position, forLeft(label)) } } private fun Lvl.typeMismatch( expected: Value, actual: Value, range: Range, ): Diagnostic { val expected = prettyValue(expected) val actual = prettyValue(actual) return diagnostic( range, """type mismatch: | expected: $expected | actual : $actual """.trimMargin(), DiagnosticSeverity.Error, ) } private fun Lvl.prettyValue( value: Value, ): String { return prettyTerm(with(meta) { zonkTerm(quoteValue(value)) }) } private fun invalidTerm( diagnostic: Diagnostic, ): Pair<C.Term, Value> { diagnose(diagnostic) return C.Term.Hole to Value.Hole } private fun invalidPattern( diagnostic: Diagnostic, ): Pair<C.Pattern, Value> { diagnose(diagnostic) return C.Pattern.Hole to Value.Hole } private fun diagnose(diagnostic: Diagnostic) { diagnostics.computeIfAbsent(location) { mutableListOf() } += diagnostic } private inline fun Ctx.typed( type: Value, build: (C.Term) -> C.Term, ): Pair<C.Term, Value> { return build(next().quoteValue(type)) to type } private data class Ctx( val entries: PersistentList<Entry>, val env: Env, ) { data class Entry( val name: String, val phase: Phase, val value: Value, var used: Boolean, ) } private fun emptyCtx(): Ctx { return Ctx(persistentListOf(), emptyEnv()) } private fun Ctx.next(): Lvl { return Lvl(env.size) } private fun Ctx.duplicate(): Ctx { return copy(entries = entries.map { it.copy() }.toPersistentList(), env = env) } data class Result( val module: C.Module, val diagnostics: Map<DefinitionLocation?, List<Diagnostic>>, val hover: (() -> Hover)?, val inlayHints: List<InlayHint>, ) companion object { private fun unknownKey( name: String, range: Range, ): Diagnostic { return diagnostic( range, "unknown key: $name", DiagnosticSeverity.Error, ) } private fun arityMismatch( expected: Int, actual: Int, range: Range, ): Diagnostic { return diagnostic( range, """arity mismatch: | expected: $expected | actual : $actual """.trimMargin(), DiagnosticSeverity.Error, ) } private fun phaseMismatch( expected: Phase, actual: Phase, range: Range, ): Diagnostic { return diagnostic( range, """phase mismatch: | expected: $expected | actual : $actual """.trimMargin(), DiagnosticSeverity.Error, ) } private fun alreadyUsed( range: Range, ): Diagnostic { return diagnostic( range, "already used", DiagnosticSeverity.Error, ) } private fun expectedDef( range: Range, ): Diagnostic { return diagnostic( range, "expected definition: def", DiagnosticSeverity.Error, ) } private fun cannotSynthesize( range: Range, ): Diagnostic { return diagnostic( range, "cannot synthesize", DiagnosticSeverity.Error, ) } private fun deprecated( range: Range, ): Diagnostic { return diagnostic( range, "deprecated", DiagnosticSeverity.Warning, ) } private fun unstable( range: Range, ): Diagnostic { return diagnostic( range, "unstable", DiagnosticSeverity.Warning, ) } private fun delicate( range: Range, ): Diagnostic { return diagnostic( range, "delicate", DiagnosticSeverity.Warning, ) } operator fun invoke( context: Context, dependencies: List<C.Module>, input: Resolve.Result, instruction: Instruction?, ): Result { try { return Elaborate(dependencies, input, instruction).elaborate() } catch (e: Exception) { println(input.module.name) throw e } } } }
127
Kotlin
0
8
f3a04a95b02ed14ef629c2391bb32b09e599baca
34,924
mcx
MIT License