path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/nilhcem/blenamebadge/core/android/ext/ViewExt.kt | Nilhcem | 113,239,619 | false | null | package org.fossasia.badgemagic.core.android.ext
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
fun View.showKeyboard() {
postDelayed({
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}, 150L)
}
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
} | 1 | Kotlin | 6 | 28 | c05f4dd7eb8d702ef89e0e9594eb0599c39fab10 | 545 | ble-led-name-badge-android | Apache License 2.0 |
api/src/main/kotlin/edu/wgu/osmt/elasticsearch/ElasticsearchClientManager.kt | JohnKallies | 457,873,790 | true | {"TypeScript": 580384, "Kotlin": 430178, "HTML": 128324, "Shell": 27042, "Java": 8284, "JavaScript": 3402, "Dockerfile": 771, "CSS": 80} | package edu.wgu.osmt.elasticsearch
import org.apache.http.HttpHost
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.RestHighLevelClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.convert.converter.Converter
import org.springframework.data.convert.ReadingConverter
import org.springframework.data.convert.WritingConverter
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate
import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
@Configuration
@EnableElasticsearchRepositories(*["edu.wgu.osmt.elasticsearch"])
class ElasticsearchClientManager {
@Autowired
lateinit var esConfig: EsConfig
@Override
@Bean
fun elasticSearchClient(): RestHighLevelClient {
return RestHighLevelClient(RestClient.builder(HttpHost.create(esConfig.uri)))
}
@Bean
fun elasticsearchTemplate(): ElasticsearchRestTemplate {
return ElasticsearchRestTemplate(elasticSearchClient())
}
@Bean
@Override
fun elasticSearchCustomConversions(): ElasticsearchCustomConversions{
return ElasticsearchCustomConversions(
listOf(LocalDateTimeToString(), StringToLocalDatetime(),
UuidToString(), StringToUuid()
)
)
}
@WritingConverter
internal class LocalDateTimeToString : Converter<LocalDateTime, String> {
override fun convert(source: LocalDateTime): String {
return source.format(DateTimeFormatter.ISO_DATE_TIME)
}
}
@ReadingConverter
internal class StringToLocalDatetime: Converter<String, LocalDateTime>{
override fun convert(source: String): LocalDateTime {
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
}
}
@WritingConverter
internal class UuidToString : Converter<UUID, String> {
override fun convert(source: UUID): String {
return source.toString()
}
}
@ReadingConverter
internal class StringToUuid: Converter<String, UUID>{
override fun convert(source: String): UUID {
return UUID.fromString(source)
}
}
}
| 1 | TypeScript | 0 | 0 | 8cde0a104a3a05a6a60978636325b8ffc5a719a2 | 2,530 | osmt | Apache License 2.0 |
src/main/kotlin/operators/ArithmeticConversion.kt | softbluecursoscode | 603,710,984 | false | {"Kotlin": 53437} | package operators
fun main() {
val a = 10.0
val b = 3
println(a / b)
val c = 30L
val d = 20
println(c * d)
println(10 / (3).toDouble())
}
| 0 | Kotlin | 2 | 5 | d9d3b179af5fcf851947fe59fe4e13a825532417 | 171 | kotlin | MIT License |
core/src/main/java/com/kylix/core/ui/UserAdapter.kt | KylixEza | 338,973,481 | false | null | package com.ferdian.core.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.ferdian.core.databinding.ItemUserListBinding
import com.ferdian.core.domain.model.User
class UserAdapter(private val user: ArrayList<User>, private val clickListener: (String, View) -> Unit):
RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
fun setData(items: List<User>?) {
user.apply {
clear()
items?.let { addAll(it) }
}
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder =
UserViewHolder(ItemUserListBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: UserViewHolder, position: Int) = holder.bind(user[position], clickListener)
override fun getItemCount(): Int = user.size
inner class UserViewHolder(private val binding: ItemUserListBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(user: User, click: (String, View) -> Unit) {
binding.data = user
binding.root.transitionName = user.login
binding.root.setOnClickListener { user.login?.let { it1 -> click(it1, binding.root) } }
}
}
} | 0 | Kotlin | 1 | 6 | 90f9ae1d297d57e240ea49af58abb1a2ee8f99c6 | 1,335 | Submission-MADE2-Dicoding | Apache License 2.0 |
app/src/main/java/com/gdgnairobi/devfest18/utils/DateUtils.kt | etonotieno | 149,093,023 | false | {"Kotlin": 16213} | /*
* Copyright (C) 2018 <NAME>
*
* 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.gdgnairobi.devfest18.utils
import org.joda.time.DateTimeZone
import org.joda.time.format.ISODateTimeFormat
import java.util.*
object DateUtils {
/**
* This method gets the time difference between the date passed as its parameter and the
* current date from the device.
*
* @param dateString The date as a String which we want to get the time difference.
* @return the time difference as a long variable.
*/
@JvmStatic
private fun getTimeDifferenceInSeconds(dateString: String): Long {
// Gets the current date from the device
val androidTime = Calendar.getInstance().time
// Find the difference between the two long values and then convert the value to hours
val dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(dateString)
dateTime.withZone(DateTimeZone.forTimeZone(TimeZone.getDefault()))
val seconds1 = dateTime.millis / 1000
val seconds2 = androidTime.time / 1000
return seconds2 - seconds1
}
/**
* This method creates a String variable according to the time in seconds passed as a parameter.
* For example, if 1 was used then the method would return "1 second ago" . If 2 was used, it
* would return "2 seconds ago".
*
* @param time The time in seconds which you want to get the appropriate string for.
* @return The prettified time string
*/
@JvmStatic
fun getPrettifiedTimeString(dateString: String): String {
val time = getTimeDifferenceInSeconds(dateString)
val timeStrings = arrayOf("minute", "hour", "day", "week")
val timePassed = arrayOf(60, 3600, 86400, 604800)
var prettifiedTime = if (time <= 1) time.toString() + " second ago" else time.toString() + " seconds ago"
for (i in timePassed.indices) {
val calc = time / timePassed[i]
if (time >= timePassed[i]) {
prettifiedTime = if (calc > 1) calc.toString() + " " + timeStrings[i] + "s ago" else calc.toString() + " " + timeStrings[i] + " ago"
}
}
return prettifiedTime
}
}
| 1 | Kotlin | 1 | 2 | e25c228f247bb1f65a06c8f4c7cfc4bb8891dd93 | 2,746 | DevFest18 | Apache License 2.0 |
src/main/kotlin/com/example/Application.kt | iproduct | 591,738,048 | false | null | package com.abmo
import io.ktor.server.application.*
import com.abmo.plugins.*
fun main(args: Array<String>): Unit =
io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
configureSerialization()
configureMonitoring()
configureRouting()
}
| 40 | null | 340 | 4 | 89884f8c29fffe6c6f0384a49ae8768c8e7ab509 | 408 | course-kotlin | Apache License 2.0 |
src/main/kotlin/com/example/Application.kt | iproduct | 591,738,048 | false | null | package com.abmo
import io.ktor.server.application.*
import com.abmo.plugins.*
fun main(args: Array<String>): Unit =
io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
configureSerialization()
configureMonitoring()
configureRouting()
}
| 40 | null | 340 | 4 | 89884f8c29fffe6c6f0384a49ae8768c8e7ab509 | 408 | course-kotlin | Apache License 2.0 |
src/main/kotlin/xyz/gnarbot/gnar/commands/executors/music/ShuffleCommand.kt | Brramble | 98,334,315 | true | {"Kotlin": 208790, "Java": 152227} | package xyz.gnarbot.gnar.commands.executors.music
import xyz.gnarbot.gnar.Bot
import xyz.gnarbot.gnar.commands.Category
import xyz.gnarbot.gnar.commands.Command
import xyz.gnarbot.gnar.commands.CommandExecutor
import xyz.gnarbot.gnar.commands.Scope
import xyz.gnarbot.gnar.utils.Context
@Command(
id = 72,
aliases = arrayOf("shuffle"),
description = "Shuffle the music queue.",
category = Category.MUSIC,
scope = Scope.VOICE
)
class ShuffleCommand : CommandExecutor() {
override fun execute(context: Context, label: String, args: Array<String>) {
val manager = Bot.getPlayers().getExisting(context.guild)
if (manager == null) {
context.send().error("There's no music player in this guild.\n$PLAY_MESSAGE").queue()
return
}
val botChannel = context.guild.selfMember.voiceState.channel
if (botChannel == null) {
context.send().error("The bot is not currently in a channel.\n$PLAY_MESSAGE").queue()
return
}
if (context.member.voiceState.channel != botChannel) {
context.send().error("You're not in the same channel as the bot.").queue()
return
}
if (manager.scheduler.queue.isEmpty()) {
context.send().error("The queue is empty.\n$PLAY_MESSAGE").queue()
return
}
manager.scheduler.shuffle()
context.send().embed("Shuffle Queue") {
desc { "Player has been shuffled" }
}.action().queue()
}
}
| 0 | Kotlin | 1 | 0 | f1c9ac2648d0a78d58cd6da62273fdbebc099b81 | 1,555 | Gnar-bot | MIT License |
app/src/main/java/com/vaibhav/taskify/util/ActivityExtensions.kt | Vaibhav2002 | 375,697,442 | false | null | package dev.vaibhav.quizzify.util
import android.app.Activity
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
fun Activity.makeStatusBarTransparent() {
window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
statusBarColor = Color.TRANSPARENT
}
}
fun View.setMarginTop(marginTop: Int) {
val menuLayoutParams = this.layoutParams as ViewGroup.MarginLayoutParams
menuLayoutParams.setMargins(0, marginTop.dp, 0, 0)
this.layoutParams = menuLayoutParams
}
| 2 | Kotlin | 29 | 89 | 664a4cd4600a6bfc12082f9f083897fb8b4001c7 | 790 | Taskify | MIT License |
app/src/main/java/org/blitzortung/android/map/overlay/color/ColorHandler.kt | likix | 57,131,986 | true | {"Kotlin": 283459, "Java": 62} | /*
Copyright 2015 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.map.overlay.color
import android.content.SharedPreferences
import android.graphics.Color
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.get
import org.blitzortung.android.data.TimeIntervalWithOffset
abstract class ColorHandler(private val preferences: SharedPreferences) {
var colorScheme: ColorScheme = ColorScheme.BLITZORTUNG
private set
private lateinit var target: ColorTarget
init {
updateTarget()
}
fun updateTarget() {
target = ColorTarget.valueOf(preferences.get(PreferenceKey.MAP_TYPE, "SATELLITE"))
colorScheme = ColorScheme.valueOf(preferences.get(PreferenceKey.COLOR_SCHEME, ColorScheme.BLITZORTUNG.toString()))
}
val colors: IntArray
get() = getColors(target)
protected abstract fun getColors(target: ColorTarget): IntArray
fun getColorSection(now: Long, eventTime: Long, timeIntervalWithOffset: TimeIntervalWithOffset): Int {
return getColorSection(now, eventTime, timeIntervalWithOffset.intervalDuration, timeIntervalWithOffset.intervalOffset)
}
private fun getColorSection(now: Long, eventTime: Long, intervalDuration: Int, intervalOffset: Int): Int {
val minutesPerColor = intervalDuration / colors.size
var section = (now + intervalOffset * 60 * 1000 - eventTime).toInt() / 1000 / 60 / minutesPerColor
return limitToValidRange(section)
}
fun getColor(now: Long, eventTime: Long, intervalDuration: Int): Int {
return getColor(getColorSection(now, eventTime, intervalDuration, 0))
}
fun getColor(index: Int): Int {
return colors[limitToValidRange(index)]
}
private fun limitToValidRange(index: Int): Int {
return Math.max(Math.min(index, colors.size - 1), 0)
}
val textColor: Int
get() = getTextColor(target)
open fun getTextColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0xffffffff.toInt()
ColorTarget.STREETMAP -> 0xff000000.toInt()
}
}
val lineColor: Int
get() = getLineColor(target)
open fun getLineColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0xffffffff.toInt()
ColorTarget.STREETMAP -> 0xff000000.toInt()
}
}
val backgroundColor: Int
get() = getBackgroundColor(target)
open fun getBackgroundColor(target: ColorTarget): Int {
return when (target) {
ColorTarget.SATELLITE -> 0x00000000.toInt()
ColorTarget.STREETMAP -> 0x00ffffff.toInt()
}
}
val numberOfColors: Int
get() = colors.size
fun modifyBrightness(colors: IntArray, factor: Float): IntArray {
val HSVValues = FloatArray(3)
return colors.map {
Color.colorToHSV(it, HSVValues)
HSVValues[2] *= factor
Color.HSVToColor(HSVValues)
}.toIntArray()
}
} | 0 | Kotlin | 0 | 0 | b337a556b3aad0f002f876ecbfb4e365b2c5b64a | 3,612 | bo-android | Apache License 2.0 |
kales-cli/src/main/kotlin/kales/cli/task/NewApplicationTask.kt | felipecsl | 170,625,125 | false | null | package kales.cli.task
import com.github.ajalt.clikt.core.UsageError
import kales.cli.copyToWithLogging
import kales.cli.relativePathFor
import kales.cli.task.KalesVersionTask.Companion.kalesVersion
import kales.cli.writeTextWithLogging
import java.io.File
import java.nio.file.Files
import java.nio.file.Files.exists
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermissions
/** "kales new" command: Creates a new Kales application */
class NewApplicationTask(
currentDir: File,
private val appName: String
) : KalesTask {
private val appRootDir = File(currentDir, appName)
override fun run() {
checkTargetDirectory()
File(appRootDir, "build.gradle").writeTextWithLogging(buildFileContents())
val srcDirRelativePath = (setOf("src", "main", "kotlin") + appName.split("."))
.joinToString(File.separator)
val sourcesDir = File(appRootDir, srcDirRelativePath)
val appDir = File(sourcesDir, "app")
appDir.mkdirs()
File(sourcesDir, "Main.kt").writeTextWithLogging(mainAppFileContents())
setOf("controllers", "views", "models").forEach {
File(appDir, it).mkdirs()
}
val layoutsDir = File(appDir, relativePathFor("views", "layouts"))
layoutsDir.mkdirs()
File(layoutsDir, "AppLayout.kt").writeTextWithLogging(appLayoutFileContents())
File(sourcesDir, relativePathFor("db", "migrate")).mkdirs()
val resourcesDir = File(appRootDir, relativePathFor("src", "main", "resources"))
resourcesDir.mkdirs()
File(resourcesDir, "database.yml").writeTextWithLogging("""
development:
adapter: sqlite
host: localhost
database: ${appName}_development
""".trimIndent())
val gradleWrapperDir = relativePathFor("gradle", "wrapper")
File(appRootDir, gradleWrapperDir).mkdirs()
File(File(appRootDir, gradleWrapperDir), "gradle-wrapper.properties")
.writeTextWithLogging(GRADLE_WRAPPER_FILE_CONTENTS)
copyResource("gradle-wrapper.bin", File(File(appRootDir, gradleWrapperDir), "gradle-wrapper.jar"))
File(appRootDir, "gradlew").also { gradlewFile ->
gradlewFile.toPath().makeExecutable()
copyResource("gradlew", gradlewFile)
}
println("""
New Kales project successfully initialized at '${appRootDir.absoluteFile.absolutePath}'.
Happy coding!
""".trimIndent())
}
private fun checkTargetDirectory() {
if (!appRootDir.exists() && !appRootDir.mkdirs()) {
throw UsageError("Failed to create directory ${appRootDir.absolutePath}")
}
}
private fun copyResource(resourceName: String, destination: File) {
val inputStream = javaClass.classLoader.getResourceAsStream(resourceName)
// If the file is zero bytes we'll just consider it non-existing
inputStream.copyToWithLogging(destination)
}
private fun Path.makeExecutable() {
if (!exists(this)) {
val ownerWritable = PosixFilePermissions.fromString("rwxr--r--")
val permissions = PosixFilePermissions.asFileAttribute(ownerWritable)
Files.createFile(this, permissions)
}
}
private fun appLayoutFileContents() = """
package $appName.app.views.layouts
import io.ktor.html.insert
import kales.actionview.ApplicationLayout
import kotlinx.html.*
class AppLayout : ApplicationLayout() {
override fun HTML.apply() {
head {
title { +"Hello world" }
}
body {
h1 { +"Hello World" }
insert(body)
}
}
}
""".trimIndent()
private fun buildFileContents() = """
buildscript {
repositories {
jcenter()
}
}
plugins {
id 'application'
id "org.jetbrains.kotlin.jvm" version "1.3.21"
}
repositories {
jcenter()
maven { url "http://oss.sonatype.org/content/repositories/snapshots" }
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
mainClassName = '$appName.MainKt'
dependencies {
implementation "com.felipecsl.kales:kales:${kalesVersion()}"
implementation "io.ktor:ktor-server-netty:1.1.2"
}
""".trimIndent()
private fun mainAppFileContents() = """
package $appName
import io.ktor.application.Application
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import kales.kalesApp
import $appName.app.views.layouts.AppLayout
fun Application.module() {
kalesApp(AppLayout::class) {
}
}
fun main() {
embeddedServer(
Netty, 8080,
watchPaths = listOf("."),
module = Application::module
).start()
}
""".trimIndent()
private val GRADLE_WRAPPER_FILE_CONTENTS = """
#Wed Feb 13 09:15:40 PST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-all.zip
""".trimIndent()
}
| 19 | null | 7 | 80 | 4a6bdd8918b5d2a12119ac6704a05451f7da05ad | 5,211 | kales | Apache License 2.0 |
idea/testData/intentions/loopToCallChain/smartCasts/smartCastNotBroken.kt | JakeWharton | 99,388,807 | true | null | // WITH_STDLIB
// INTENTION_TEXT: "Replace with '...filter{}.map{}.firstOrNull()'"
// INTENTION_TEXT_2: "Replace with 'asSequence()...filter{}.map{}.firstOrNull()'"
fun foo(list: List<String>, o: Any): Int? {
if (o is Int) {
<caret>for (s in list) {
val length = s.length + o
if (length > 0) {
val x = length * o.hashCode()
return x
}
}
return null
}
return 0
} | 1 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 465 | kotlin | Apache License 2.0 |
sudoemail/src/main/java/com/sudoplatform/sudoemail/NotificationConfigurationExtensions.kt | sudoplatform | 303,299,846 | false | {"Kotlin": 1511736} | /*
* Copyright © 2024 <NAME>, Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sudoplatform.sudoemail
import com.sudoplatform.sudoemail.notifications.MessageReceivedNotification
import com.sudoplatform.sudoemail.util.Constants
import com.sudoplatform.sudonotification.types.NotificationConfiguration
import com.sudoplatform.sudonotification.types.NotificationFilterItem
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
// By default, disable all notifications we do not know how to handle
internal val DEFAULT_FIRST_RULE_STRING = JsonObject(
mapOf(
Pair(
"!=",
JsonArray(
listOf(
JsonObject(
mapOf(
Pair("var", JsonPrimitive("meta.type")),
),
),
JsonPrimitive(MessageReceivedNotification.TYPE),
),
),
),
),
).toString()
// Disable notification types other than those we know how to handle
internal val DEFAULT_FIRST_RULE = NotificationFilterItem(
name = Constants.SERVICE_NAME,
status = NotificationConfiguration.DISABLE_STR,
rules = DEFAULT_FIRST_RULE_STRING,
)
internal const val DEFAULT_LAST_RULE_STRING = NotificationConfiguration.DEFAULT_RULE_STRING
// Enable all otherwise unfiltered out notifications
internal val DEFAULT_LAST_RULE = NotificationFilterItem(
name = Constants.SERVICE_NAME,
status = NotificationConfiguration.ENABLE_STR,
rules = DEFAULT_LAST_RULE_STRING,
)
internal fun isRuleMatchingEmailAddressId(rule: String?, emailAddressId: String): Boolean {
return isRuleMatchingSingleMeta(rule, "emailAddressId", emailAddressId)
}
internal fun isRuleMatchingSudoId(rule: String?, sudoId: String): Boolean {
return isRuleMatchingSingleMeta(rule, "sudoId", sudoId)
}
internal fun isRuleMatchingSingleMeta(rule: String?, metaName: String, metaValue: String): Boolean {
if (rule == null) {
return false
}
val jsonRules = Json.decodeFromString<JsonObject>(rule)
val equality = jsonRules["=="]
if (equality is JsonArray && equality.size == 2) {
val lhs = equality[0]
val rhs = equality[1]
// "var meta.emailAddressId == emailAddressId
if (lhs is JsonObject && rhs is JsonPrimitive && rhs.isString) {
val v = lhs["var"]
if (v is JsonPrimitive && v.isString && v.content == "meta.$metaName" && rhs.content == metaValue) {
return true
}
}
// "emailAddressId == var meta.emailAddressId
else if (rhs is JsonObject && lhs is JsonPrimitive && lhs.isString) {
val v = rhs["var"]
if (v is JsonPrimitive && v.isString && v.content == "meta.$metaName" && lhs.content == metaValue) {
return true
}
}
}
return false
}
/**
* Extension function to ensure a [NotificationConfiguration] is initialized for
* receipt of email service notifications.
*
* @return New NotificationConfiguration with updated rules
*/
fun NotificationConfiguration.initEmailNotifications(): NotificationConfiguration {
val newConfigs = this.configs
.filter { it.name != Constants.SERVICE_NAME }
.toMutableList()
val emServiceConfigs = this.configs
.filter { it.name == Constants.SERVICE_NAME }
// Filter out any current or historic default rules.
// We'll add current default rules back in
.filter { it.rules != DEFAULT_FIRST_RULE_STRING && it.rules != DEFAULT_LAST_RULE_STRING }
.toMutableList()
newConfigs.add(DEFAULT_FIRST_RULE)
newConfigs.addAll(emServiceConfigs)
newConfigs.add(DEFAULT_LAST_RULE)
return NotificationConfiguration(
configs = newConfigs.toList(),
)
}
internal fun NotificationConfiguration.setEmailNotificationsForSingleMeta(
metaName: String,
metaValue: String,
enabled: Boolean,
): NotificationConfiguration {
// Start with any rules for other services
val newRules = this.configs
.filter { it.name != Constants.SERVICE_NAME }.toMutableList()
// Then find all the email service rules except our defaults and
// any existing rule matching this meta.
val newEmServiceRules = this.configs
.filter { it.name == Constants.SERVICE_NAME }
// Filter out any current or historic default rules.
// We'll add current default rules back in
.filter { it.rules != DEFAULT_FIRST_RULE_STRING && it.rules != DEFAULT_LAST_RULE_STRING }
// Filter out any rule specific to our meta name and value
.filter { !isRuleMatchingSingleMeta(it.rules, metaName, metaValue) }
// Re-add DEFAULT_FIRST_RULE
newRules.add(DEFAULT_FIRST_RULE)
// Re-add other email service rules
newRules.addAll(newEmServiceRules)
// If we're disabling notifications for this meta value then
// add an explicit rule for that
if (!enabled) {
val newJsonRule = JsonObject(
mapOf(
Pair(
"==",
JsonArray(
listOf(
JsonObject(
mapOf(
Pair("var", JsonPrimitive("meta.$metaName")),
),
),
JsonPrimitive(metaValue),
),
),
),
),
)
newRules.add(
NotificationFilterItem(
name = Constants.SERVICE_NAME,
status = NotificationConfiguration.DISABLE_STR,
rules = newJsonRule.toString(),
),
)
}
// Re-add the default catch all enabling rule
newRules.add(DEFAULT_LAST_RULE)
return NotificationConfiguration(
configs = newRules.toList(),
)
}
/**
* Extension function to add rules to a [NotificationConfiguration] for enabling
* or disabling email service notifications for a particular email address ID.
*
* Once all notification configurations across all Sudo platform SDKs have
* been performed, call the
* [com.sudoplatform.sudonotification.SudoNotificationClient.setNotificationConfiguration]
* to set the full notification configuration for your application.
*
* @param emailAddressId
* ID of email address to set email service notification enablement for
*
* @param enabled
* Whether or not email service notifications are to be enabled or disabled for the
* email address with the specified ID.
*
* @return New NotificationConfiguration with updated rules
*/
fun NotificationConfiguration.setEmailNotificationsForAddressId(emailAddressId: String, enabled: Boolean): NotificationConfiguration {
return setEmailNotificationsForSingleMeta("emailAddressId", emailAddressId, enabled)
}
/**
* Extension function to add rules to a [NotificationConfiguration] for enabling
* or disabling email service notifications for a particular sudo ID.
*
* Once all notification configurations across all Sudo platform SDKs have
* been performed, call the
* [com.sudoplatform.sudonotification.SudoNotificationClient.setNotificationConfiguration]
* to set the full notification configuration for your application.
*
* @param sudoId
* ID of Sudo to set email service notification enablement for
*
* @param enabled
* Whether or not email service notifications are to be enabled or disabled for the
* Sudo with the specified ID.
*
* @return New NotificationConfiguration with updated rules
*/
fun NotificationConfiguration.setEmailNotificationsForSudoId(sudoId: String, enabled: Boolean): NotificationConfiguration {
return setEmailNotificationsForSingleMeta("sudoId", sudoId, enabled)
}
/**
* Test whether or not email service notifications are enabled for a particular email address
*
* @param emailAddressId ID of email address to test
*
* @return Whether or not email service notifications are enabled for the email address with the specified ID
*/
fun NotificationConfiguration.isEmailNotificationForAddressIdEnabled(emailAddressId: String): Boolean {
val emailAddressRule = this.configs
.filter { it.name == Constants.SERVICE_NAME }
// Filter out any current or historic default rules.
// We'll add current default rules back in
.filter { it.rules != DEFAULT_FIRST_RULE_STRING && it.rules != DEFAULT_LAST_RULE_STRING }
// Filter out any rule specific to our emailAddressId
.find { isRuleMatchingEmailAddressId(it.rules, emailAddressId) }
// Notifications are enabled for this email address if either there
// is no matching rule (because the default enables it) or if the
// matching rule explicitly enables them.
return emailAddressRule == null ||
emailAddressRule.status == NotificationConfiguration.ENABLE_STR
}
/**
* Test whether or not email service notifications are enabled for a particular Sudo
*
* @param sudoId ID of Sudo to test
*
* @return Whether or not email service notifications are enabled for the Sudo with the specified ID
*/
fun NotificationConfiguration.isEmailNotificationForSudoIdEnabled(sudoId: String): Boolean {
val sudoRule = this.configs
.filter { it.name == Constants.SERVICE_NAME }
// Filter out any current or historic default rules.
// We'll add current default rules back in
.filter { it.rules != DEFAULT_FIRST_RULE_STRING && it.rules != DEFAULT_LAST_RULE_STRING }
// Filter out any rule specific to our sudoId
.find { isRuleMatchingSudoId(it.rules, sudoId) }
// Notifications are enabled for this Sudo if either there
// is no matching rule (because the default enables it) or if the
// matching rule explicitly enables them.
return sudoRule == null ||
sudoRule.status == NotificationConfiguration.ENABLE_STR
}
| 0 | Kotlin | 0 | 1 | 10d097649e0e25fa04371a0cf473e896025d2fbc | 10,139 | sudo-email-android | Apache License 2.0 |
plugin/src/main/kotlin/com/lightningkite/khrysalis/web/convertToTypescript.kt | lightningkite | 161,243,441 | false | null | package com.lightningkite.khrysalis.web
import com.lightningkite.khrysalis.generic.CompilerPluginUseInfo
import com.lightningkite.khrysalis.generic.runCompiler
import com.lightningkite.khrysalis.utils.copyFolderOutFromRes
import org.gradle.api.Project
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.classpathAsList
import org.jetbrains.kotlin.incremental.destinationAsFile
import java.io.File
fun typescriptPluginUse(project: Project, webBase: File, projectName: String?, libraryMode: Boolean = false): CompilerPluginUseInfo {
return CompilerPluginUseInfo(
project = project,
configName = "khrysalisTypescript",
options = listOfNotNull(
"plugin:com.lightningkite.khrysalis.typescript:outputDirectory=\"${webBase.resolve("src")}\"",
projectName?.let { "plugin:com.lightningkite.khrysalis.typescript:projName=\"${it}\"" },
"plugin:com.lightningkite.khrysalis.typescript:equivalents=\"${webBase}\"",
"plugin:com.lightningkite.khrysalis.typescript:libraryMode=\"${libraryMode}\""
)
)
}
| 13 | Kotlin | 0 | 9 | b620e939c7461799ae1dae91e9b4b426fa3acfc1 | 1,518 | khrysalis | MIT License |
examples/image_generation/android/app/src/main/java/com/google/mediapipe/examples/imagegeneration/MainActivity.kt | googlesamples | 555,519,447 | false | {"Jupyter Notebook": 940565, "JavaScript": 116392, "Kotlin": 46206, "HTML": 6974, "Python": 1494, "CSS": 1381} | package com.google.mediapipe.examples.imagegeneration
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.mediapipe.examples.imagegeneration.databinding.ActivityMainBinding
import com.google.mediapipe.examples.imagegeneration.diffusion.DiffusionActivity
import com.google.mediapipe.examples.imagegeneration.loraweights.LoRAWeightActivity
import com.google.mediapipe.examples.imagegeneration.plugins.PluginActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnDiffusion.setOnClickListener {
startActivity(Intent(this, DiffusionActivity::class.java))
}
binding.btnPlugins.setOnClickListener {
startActivity(Intent(this, PluginActivity::class.java))
}
binding.btnLoRA.setOnClickListener {
startActivity(Intent(this, LoRAWeightActivity::class.java))
}
}
} | 48 | Jupyter Notebook | 257 | 988 | 0fc6e2b809b13b7cb1de1792288409624f5f6007 | 1,178 | mediapipe | Apache License 2.0 |
platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/StyleTest.kt | tianj-zh | 174,555,805 | false | {"Git Config": 1, "Markdown": 52, "YAML": 9, "JSON": 297, "CMake": 52, "Python": 5, "Ignore List": 6, "Makefile": 3, "XML": 266, "C++": 1287, "Objective-C++": 99, "OpenStep Property List": 15, "JavaScript": 34, "Protocol Buffer": 5, "Text": 16, "Shell": 48, "Objective-C": 270, "C": 70, "Swift": 8, "EJS": 27, "SVG": 19, "Ruby": 6, "Rich Text Format": 1, "Gradle": 16, "Batchfile": 1, "INI": 1, "Java Properties": 2, "Proguard": 2, "Java": 410, "Kotlin": 36, "HTML": 1, "SQL": 2, "CODEOWNERS": 1, "Starlark": 1, "PowerShell": 1} | package com.mapbox.mapboxsdk.maps
import android.graphics.Bitmap
import android.graphics.drawable.ShapeDrawable
import com.mapbox.mapboxsdk.constants.MapboxConstants
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.style.layers.TransitionOptions
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class StyleTest {
private lateinit var mapboxMap: MapboxMap
private lateinit var nativeMapView: NativeMapView
@Before
fun setup() {
nativeMapView = mockk()
mapboxMap = MapboxMap(nativeMapView, null, null, null, null, null)
every { nativeMapView.styleUrl = any() } answers {}
every { nativeMapView.styleJson = any() } answers {}
every { nativeMapView.addLayerBelow(any(), any()) } answers {}
every { nativeMapView.addLayerAbove(any(), any()) } answers {}
every { nativeMapView.addLayerAt(any(), any()) } answers {}
every { nativeMapView.addSource(any()) } answers {}
every { nativeMapView.addImages(any()) } answers {}
every { nativeMapView.transitionOptions = any() } answers {}
every { nativeMapView.isDestroyed } returns false
mapboxMap.injectLocationComponent(spyk())
}
@Test
fun testFromUrl() {
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
}
@Test
fun testFromJson() {
val builder = Style.Builder().fromJson("{}")
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
}
@Test
fun testEmptyBuilder() {
val builder = Style.Builder()
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
}
@Test
fun testWithLayer() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayer(layer)
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, MapboxConstants.LAYER_ID_ANNOTATIONS) }
}
@Test
fun testWithLayerAbove() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerAbove(layer, "id")
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerAbove(layer, "id") }
}
@Test
fun testWithLayerBelow() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerBelow(layer, "id")
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "id") }
}
@Test
fun testWithLayerAt() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().withLayerAt(layer, 1)
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addLayerAt(layer, 1) }
}
@Test
fun testWithSource() {
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
}
@Test
fun testWithTransitionOptions() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().withTransition(transitionOptions)
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.transitionOptions = transitionOptions }
}
@Test
fun testWithFromLoadingSource() {
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withSource(source)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addSource(source) }
}
@Test
fun testWithFromLoadingLayer() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withLayer(layer)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, MapboxConstants.LAYER_ID_ANNOTATIONS) }
}
@Test
fun testWithFromLoadingLayerAt() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withLayerAt(layer, 1)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerAt(layer, 1) }
}
@Test
fun testWithFromLoadingLayerBelow() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withLayerBelow(layer, "below")
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "below") }
}
@Test
fun testWithFromLoadingLayerAbove() {
val layer = mockk<SymbolLayer>()
every { layer.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withLayerBelow(layer, "below")
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addLayerBelow(layer, "below") }
}
@Test
fun testWithFromLoadingTransitionOptions() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withTransition(transitionOptions)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.transitionOptions = transitionOptions }
}
@Test
fun testFromCallback() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS)
mapboxMap.setStyle(builder, callback)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testWithCallback() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
mapboxMap.setStyle(builder, callback)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncWith() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
mapboxMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().withSource(source)
mapboxMap.setStyle(builder)
mapboxMap.onFinishLoadingStyle()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncFrom() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
mapboxMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromJson("{}")
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetAsyncWithFrom() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
mapboxMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withSource(source)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.MAPBOX_STREETS }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addSource(source) }
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test
fun testGetNullStyle() {
Assert.assertNull(mapboxMap.style)
}
@Test
fun testGetNullWhileLoading() {
val transitionOptions = TransitionOptions(100, 200)
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS).withTransition(transitionOptions)
mapboxMap.setStyle(builder)
Assert.assertNull(mapboxMap.style)
mapboxMap.notifyStyleLoaded()
Assert.assertNotNull(mapboxMap.style)
}
@Test
fun testNotReinvokeSameListener() {
val callback = mockk<Style.OnStyleLoaded>()
every { callback.onStyleLoaded(any()) } answers {}
mapboxMap.getStyle(callback)
val source = mockk<GeoJsonSource>()
every { source.id } returns "1"
val builder = Style.Builder().fromJson("{}")
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleJson = "{}" }
mapboxMap.notifyStyleLoaded()
mapboxMap.setStyle(Style.MAPBOX_STREETS)
verify(exactly = 1) { callback.onStyleLoaded(any()) }
}
@Test(expected = IllegalStateException::class)
fun testIllegalStateExceptionWithStyleReload() {
val builder = Style.Builder().fromUrl(Style.MAPBOX_STREETS)
mapboxMap.setStyle(builder)
mapboxMap.notifyStyleLoaded()
val style = mapboxMap.style
mapboxMap.setStyle(Style.Builder().fromUrl(Style.DARK))
style!!.addLayer(mockk<SymbolLayer>())
}
@Test
fun testAddImage() {
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
val builder = Style.Builder().fromUrl(Style.SATELLITE).withImage("id", bitmap)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.SATELLITE }
verify(exactly = 0) { nativeMapView.addImages(any()) }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addImages(any()) }
}
@Test
fun testAddDrawable() {
val drawable = ShapeDrawable()
drawable.intrinsicHeight = 10
drawable.intrinsicWidth = 10
val builder = Style.Builder().fromUrl(Style.SATELLITE).withImage("id", drawable)
mapboxMap.setStyle(builder)
verify(exactly = 1) { nativeMapView.styleUrl = Style.SATELLITE }
verify(exactly = 0) { nativeMapView.addImages(any()) }
mapboxMap.notifyStyleLoaded()
verify(exactly = 1) { nativeMapView.addImages(any()) }
}
}
| 1 | null | 1 | 1 | d5659aa6647f1fc77159567bd22029a2dc9cd7a3 | 12,042 | qtlocation-mapboxgl | Boost Software License 1.0 |
DnDTable/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.* // ktlint-disable no-wildcard-imports
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.dnd.DnDConstants
import java.awt.dnd.DragGestureEvent
import java.awt.dnd.DragGestureListener
import java.awt.dnd.DragSource
import java.awt.dnd.DragSourceDragEvent
import java.awt.dnd.DragSourceDropEvent
import java.awt.dnd.DragSourceEvent
import java.awt.dnd.DragSourceListener
import java.awt.dnd.DropTarget
import java.awt.dnd.DropTargetDragEvent
import java.awt.dnd.DropTargetDropEvent
import java.awt.dnd.DropTargetEvent
import java.awt.dnd.DropTargetListener
import javax.swing.* // ktlint-disable no-wildcard-imports
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableModel
fun makeUI(): Component {
val columnNames = arrayOf("String", "Integer", "Boolean")
val data = arrayOf(
arrayOf("aaa", 12, true),
arrayOf("bbb", 5, false),
arrayOf("CCC", 92, true),
arrayOf("DDD", 0, false),
arrayOf("eee", 1, true),
arrayOf("GGG", 3, false),
arrayOf("hhh", 72, true),
arrayOf("fff", 4, false)
)
val model = object : DefaultTableModel(data, columnNames) {
override fun getColumnClass(column: Int) = getValueAt(0, column).javaClass
}
val table = DnDTable(model)
table.fillsViewportHeight = true
table.componentPopupMenu = TablePopupMenu()
table.columnModel.getColumn(0).also {
it.minWidth = 60
it.maxWidth = 60
it.resizable = false
}
return JPanel(BorderLayout()).also {
it.add(JScrollPane(table))
it.preferredSize = Dimension(320, 240)
}
}
private class TablePopupMenu : JPopupMenu() {
private val delete: JMenuItem
init {
add("add").addActionListener {
val table = invoker as? JTable
val model = table?.model
if (model is DefaultTableModel) {
model.addRow(arrayOf("New row", model.rowCount, false))
val r = table.getCellRect(model.rowCount - 1, 0, true)
table.scrollRectToVisible(r)
}
}
addSeparator()
delete = add("delete")
delete.addActionListener {
val table = invoker as? JTable
val model = table?.model
if (model is DefaultTableModel) {
val selection = table.selectedRows
for (i in selection.indices.reversed()) {
model.removeRow(table.convertRowIndexToModel(selection[i]))
}
}
}
}
override fun show(c: Component?, x: Int, y: Int) {
if (c is JTable) {
delete.isEnabled = c.selectedRowCount > 0
super.show(c, x, y)
}
}
}
private class DnDTable(model: TableModel?) : JTable(model), DragGestureListener, Transferable {
private val targetLine = Rectangle()
private var draggedIndex = -1
private var targetIndex = -1
private val dsl = TableDragSourceListener()
init {
DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, CDropTargetListener(), true)
val ds = DragSource.getDefaultDragSource()
ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this)
}
override fun prepareRenderer(tcr: TableCellRenderer, row: Int, column: Int): Component =
super.prepareRenderer(tcr, row, column).also {
if (isRowSelected(row)) {
it.foreground = getSelectionForeground()
it.background = getSelectionBackground()
} else {
it.foreground = foreground
it.background = if (row % 2 == 0) EVEN_BACKGROUND else background
}
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (targetIndex >= 0) {
val g2 = g.create() as? Graphics2D ?: return
g2.paint = LINE_COLOR
g2.fill(targetLine)
g2.dispose()
}
}
private fun initTargetLine(p: Point) {
val rect = Rectangle()
val cellHeight = getRowHeight()
val lineWidth = width
val lineHeight = 2
rect.setSize(lineWidth, cellHeight)
targetLine.setSize(lineWidth, lineHeight)
targetIndex = -1
val rowCount = rowCount
for (i in 0 until rowCount) {
rect.setLocation(0, cellHeight * i - cellHeight / 2)
if (rect.contains(p)) {
targetIndex = i
targetLine.setLocation(0, i * cellHeight)
break
}
}
if (targetIndex < 0) {
targetIndex = rowCount
targetLine.setLocation(0, targetIndex * cellHeight - lineHeight)
}
}
// Interface: DragGestureListener
override fun dragGestureRecognized(e: DragGestureEvent) {
val oneOrMore = selectedRowCount > 1
draggedIndex = rowAtPoint(e.dragOrigin)
if (oneOrMore || draggedIndex < 0) {
return
}
runCatching {
e.startDrag(DragSource.DefaultMoveDrop, this, dsl)
}
}
// Interface: Transferable
override fun getTransferData(flavor: DataFlavor) = this
override fun getTransferDataFlavors() = arrayOf(FLAVOR)
override fun isDataFlavorSupported(flavor: DataFlavor) = flavor.humanPresentableName == NAME
private inner class CDropTargetListener : DropTargetListener {
override fun dragExit(e: DropTargetEvent) {
targetIndex = -1
repaint()
}
override fun dragEnter(e: DropTargetDragEvent) {
if (isDragAcceptable(e)) {
e.acceptDrag(e.dropAction)
} else {
e.rejectDrag()
}
}
override fun dragOver(e: DropTargetDragEvent) {
if (isDragAcceptable(e)) {
e.acceptDrag(e.dropAction)
cursor = DragSource.DefaultMoveDrop
} else {
e.rejectDrag()
cursor = DragSource.DefaultMoveNoDrop
return
}
initTargetLine(e.location)
repaint()
}
override fun dropActionChanged(e: DropTargetDragEvent) {
// if (isDragAcceptable(e)) {
// e.acceptDrag(e.getDropAction())
// } else {
// e.rejectDrag()
// }
}
override fun drop(e: DropTargetDropEvent) {
val model = model as? DefaultTableModel ?: return
if (isDropAcceptable(e)) {
if (targetIndex == draggedIndex) {
setRowSelectionInterval(targetIndex, targetIndex)
} else {
val tg = if (targetIndex < draggedIndex) targetIndex else targetIndex - 1
model.moveRow(draggedIndex, draggedIndex, tg)
setRowSelectionInterval(tg, tg)
}
e.dropComplete(true)
} else {
e.dropComplete(false)
}
e.dropComplete(false)
cursor = Cursor.getDefaultCursor()
targetIndex = -1
repaint()
}
private fun isDragAcceptable(e: DropTargetDragEvent) =
isDataFlavorSupported(e.currentDataFlavors[0])
private fun isDropAcceptable(e: DropTargetDropEvent) =
isDataFlavorSupported(e.transferable.transferDataFlavors[0])
}
companion object {
private val LINE_COLOR = Color(0xFF_64_64)
private const val NAME = "test"
private val FLAVOR = DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME)
private val EVEN_BACKGROUND = Color(0xF0_F0_F0)
}
}
private class TableDragSourceListener : DragSourceListener {
override fun dragEnter(e: DragSourceDragEvent) {
e.dragSourceContext.cursor = DragSource.DefaultMoveDrop
}
override fun dragExit(e: DragSourceEvent) {
e.dragSourceContext.cursor = DragSource.DefaultMoveNoDrop
}
override fun dragOver(e: DragSourceDragEvent) {
// not needed
}
override fun dropActionChanged(e: DragSourceDragEvent) {
// not needed
}
override fun dragDropEnd(e: DragSourceDropEvent) {
// e.getDragSourceContext().setCursor(Cursor.getDefaultCursor())
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 6 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 7,941 | kotlin-swing-tips | MIT License |
app/src/main/java/com/example/project_flow_android/ui/sign/LoginActivity.kt | DSM-JAVA-PROJECT | 392,317,851 | false | null | package com.example.project_flow_android.ui.sign
import android.content.Intent
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isInvisible
import androidx.lifecycle.ViewModelProvider
import com.example.project_flow_android.R
import com.example.project_flow_android.base.BaseActivity
import com.example.project_flow_android.databinding.ActivityLoginBinding
import com.example.project_flow_android.ui.main.MainActivity
import com.example.project_flow_android.viewmodel.login.LoginViewModel
import com.example.project_flow_android.viewmodel.login.LoginViewModelFactory
import kotlinx.android.synthetic.main.activity_login.*
import org.koin.android.ext.android.inject
class LoginActivity : BaseActivity<ActivityLoginBinding>(R.layout.activity_login) {
private val vmFactory by inject<LoginViewModelFactory>()
override val vm: LoginViewModel by lazy {
ViewModelProvider(this, vmFactory).get(LoginViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
successfulLogin()
}
private fun successfulLogin() {
vm.run {
successLogin.observe(this@LoginActivity, {
if (it) {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
binding.comment2Tv.text = vm.changeComment.value
}
binding.oauthBtn.setOnClickListener{
val intent = Intent(this@LoginActivity,LoginOauthActivity::class.java)
startActivity(intent)
}
binding.comment2Tv.text = vm.changeComment.value
})
}
}
} | 0 | Kotlin | 0 | 12 | c7b7dea550ffb7025cb1ffd8abc65e8f701ab0e1 | 1,795 | Project-Flow_Android | MIT License |
stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/call/ringing/outgoingcall/OutgoingCallContent.kt | GetStream | 505,572,267 | false | null | /*
* Copyright (c) 2014-2024 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.video.android.compose.ui.components.call.ringing.outgoingcall
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import io.getstream.video.android.compose.theme.VideoTheme
import io.getstream.video.android.compose.ui.components.background.CallBackground
import io.getstream.video.android.core.Call
import io.getstream.video.android.core.MemberState
import io.getstream.video.android.core.call.state.CallAction
import io.getstream.video.android.mock.StreamPreviewDataUtils
import io.getstream.video.android.mock.previewCall
import io.getstream.video.android.mock.previewMemberListState
/**
* Represents the Outgoing Call state and UI, when the user is calling other people.
*
* @param call The call contains states and will be rendered with participants.
* @param isVideoType Represent the call type is a video or an audio.
* @param modifier Modifier for styling.
* @param isShowingHeader Weather or not the app bar will be shown.
* @param headerContent Content shown for the call header.
* @param detailsContent Content shown for call details, such as call participant information.
* @param controlsContent Content shown for controlling call, such as accepting a call or declining a call.
* @param onBackPressed Handler when the user taps on the back button.
* @param onCallAction Handler used when the user interacts with Call UI.
*/
@Composable
public fun OutgoingCallContent(
modifier: Modifier = Modifier,
call: Call,
isVideoType: Boolean,
isShowingHeader: Boolean = true,
headerContent: (@Composable ColumnScope.() -> Unit)? = null,
detailsContent: (
@Composable ColumnScope.(
participants: List<MemberState>,
topPadding: Dp,
) -> Unit
)? = null,
controlsContent: (@Composable BoxScope.() -> Unit)? = null,
onBackPressed: () -> Unit = {},
onCallAction: (CallAction) -> Unit = {},
) {
val participants: List<MemberState> by call.state.members.collectAsStateWithLifecycle()
OutgoingCallContent(
call = call,
isVideoType = isVideoType,
participants = participants,
modifier = modifier,
isShowingHeader = isShowingHeader,
headerContent = headerContent,
detailsContent = detailsContent,
controlsContent = controlsContent,
onBackPressed = onBackPressed,
onCallAction = onCallAction,
)
}
/**
* Represents the Outgoing Call state and UI, when the user is calling other people.
*
* @param call The call contains states and will be rendered with participants.
* @param isVideoType Represent the call type is a video or an audio.
* @param modifier Modifier for styling.
* @param participants A list of participants.
* @param isShowingHeader Weather or not the app bar will be shown.
* @param headerContent Content shown for the call header.
* @param detailsContent Content shown for call details, such as call participant information.
* @param controlsContent Content shown for controlling call, such as accepting a call or declining a call.
* @param onBackPressed Handler when the user taps on the back button.
* @param onCallAction Handler used when the user interacts with Call UI.
*/
@Composable
public fun OutgoingCallContent(
modifier: Modifier = Modifier,
call: Call,
isVideoType: Boolean = true,
participants: List<MemberState>,
isShowingHeader: Boolean = true,
headerContent: (@Composable ColumnScope.() -> Unit)? = null,
detailsContent: (
@Composable ColumnScope.(
participants: List<MemberState>,
topPadding: Dp,
) -> Unit
)? = null,
controlsContent: (@Composable BoxScope.() -> Unit)? = null,
onBackPressed: () -> Unit = {},
onCallAction: (CallAction) -> Unit = {},
) {
val isCameraEnabled by if (LocalInspectionMode.current) {
remember { mutableStateOf(true) }
} else {
call.camera.isEnabled.collectAsStateWithLifecycle()
}
val isMicrophoneEnabled by if (LocalInspectionMode.current) {
remember { mutableStateOf(true) }
} else {
call.microphone.isEnabled.collectAsStateWithLifecycle()
}
CallBackground(
modifier = modifier,
) {
Column {
if (isShowingHeader) {
headerContent?.invoke(this)
}
val topPadding = if (participants.size == 1 || isVideoType) {
VideoTheme.dimens.spacingL
} else {
VideoTheme.dimens.spacingM
}
detailsContent?.invoke(this, participants, topPadding) ?: OutgoingCallDetails(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = topPadding),
participants = participants,
isVideoType = isVideoType,
)
}
controlsContent?.invoke(this) ?: OutgoingCallControls(
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = VideoTheme.dimens.componentHeightM),
isVideoCall = isVideoType,
isCameraEnabled = isCameraEnabled,
isMicrophoneEnabled = isMicrophoneEnabled,
onCallAction = onCallAction,
)
}
}
@Preview
@Composable
private fun OutgoingCallVideoPreview() {
StreamPreviewDataUtils.initializeStreamVideo(LocalContext.current)
VideoTheme {
OutgoingCallContent(
call = previewCall,
isVideoType = true,
participants = previewMemberListState,
onBackPressed = {},
) {}
}
}
@Preview
@Composable
private fun OutgoingCallAudioPreview() {
StreamPreviewDataUtils.initializeStreamVideo(LocalContext.current)
VideoTheme {
OutgoingCallContent(
call = previewCall,
isVideoType = false,
participants = previewMemberListState,
onBackPressed = {},
) {}
}
}
| 3 | null | 35 | 350 | 24b30afb18a7d55ae86d0b4e4237cb9c4d40125f | 7,251 | stream-video-android | FSF All Permissive License |
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/AbstractKotlinGroupUsagesBySimilarityTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.findUsages
import com.intellij.openapi.application.ReadAction
import com.intellij.psi.PsiElement
import com.intellij.testFramework.assertEqualsToFile
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageInfoToUsageConverter
import com.intellij.usages.similarity.clustering.ClusteringSearchSession
import com.intellij.util.concurrency.AppExecutorUtil
import java.io.File
import java.util.concurrent.Callable
abstract class AbstractKotlinGroupUsagesBySimilarityTest: AbstractFindUsagesTest() {
override fun <T : PsiElement> doTest(path: String) {
myFixture.configureByFile(getTestName(true) + ".kt")
val findUsages = findUsages(myFixture.elementAtCaret, null, false, myFixture.project)
val session = ClusteringSearchSession()
ReadAction.nonBlocking(Callable {
findUsages.forEach { usage ->
val u = UsageInfoToUsageConverter.convertToSimilarUsage(arrayOf(myFixture.elementAtCaret), usage, session)
(u as UsageInfo2UsageAdapter).updateCachedPresentation()
}
}
).submit(AppExecutorUtil.getAppExecutorService()).get()
val file = File(testDataDirectory, getTestName(true) + ".results.txt")
assertEqualsToFile("", file, session.clusters.toString())
}
} | 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,454 | intellij-community | Apache License 2.0 |
07_AndroidVersions/GeoQuiz/app/src/main/java/com/bignerdranch/android/geoquiz/CheatActivity.kt | sby5388 | 373,231,323 | false | null | package com.example.geoquiz
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
private const val EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true"
const val EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown"
class CheatActivity : AppCompatActivity() {
private var answerIsTrue = false;
private lateinit var answerTextView: TextView
private lateinit var showAnswerButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cheat)
answerTextView = findViewById(R.id.answer_text_view)
showAnswerButton = findViewById(R.id.show_answer_button)
showAnswerButton.setOnClickListener {
val answerText = when {
answerIsTrue -> R.string.true_button
else -> R.string.false_button
}
answerTextView.setText(answerText)
setAnswerShownResult(true)
}
answerIsTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false)
}
companion object {
fun newIntent(packageContext: Context, answerIsTrue: Boolean): Intent {
return Intent(packageContext, CheatActivity::class.java).apply {
putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue)
}
}
}
private fun setAnswerShownResult(isAnswerShown: Boolean) {
val data = Intent().apply {
putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown)
}
setResult(Activity.RESULT_OK, data)
}
} | 0 | Kotlin | 4 | 8 | b0fc2c08e17e5333a50e4d57e1d47634e4db562c | 1,747 | AndroidBianChengQuanWeiZhiNanV4-kotlin | Apache License 2.0 |
x-pref/src/androidTest/java/com/bilibili/xpref/SharedPreferencesWrapperTest.kt | bilibili | 115,354,349 | false | null | /*
* Copyright (c) 2017. bilibili, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bilibili.xpref
import android.content.SharedPreferences
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
import kotlin.test.assertTrue
/**
* @author yrom
*/
@RunWith(AndroidJUnit4::class)
class SharedPreferencesWrapperTest {
@Test
fun testWrapper() {
val mock = MockSharedPreferences()
val wrapper = XprefProvider.SharedPreferencesWrapper(mock,
SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> })
wrapper.all
wrapper.getString("", "")
wrapper.getInt("", 0)
wrapper.getLong("", 0)
wrapper.getFloat("", 0f)
wrapper.getStringSet("", null)
wrapper.contains("")
wrapper.edit().putString("", "").apply()
wrapper.edit().putString("1", "").commit()
assertTrue(
mock.testedMethods.containsAll(arrayListOf("getAll", "getString",
"getInt", "getLong", "getFloat", "getStringSet",
"contains", "edit", "apply", "commit",
"registerOnSharedPreferenceChangeListener"))
)
}
internal class MockSharedPreferences : SharedPreferences {
var testedMethods: MutableList<String> = ArrayList()
override fun getAll(): Map<String, *> {
testedMethods.add("getAll")
return emptyMap<String, Any>()
}
override fun getString(key: String, defValue: String?): String? {
testedMethods.add("getString")
return defValue
}
override fun getStringSet(key: String, defValues: Set<String>?): Set<String>? {
testedMethods.add("getStringSet")
return defValues
}
override fun getInt(key: String, defValue: Int): Int {
testedMethods.add("getInt")
return defValue
}
override fun getLong(key: String, defValue: Long): Long {
testedMethods.add("getLong")
return defValue
}
override fun getFloat(key: String, defValue: Float): Float {
testedMethods.add("getFloat")
return defValue
}
override fun getBoolean(key: String, defValue: Boolean): Boolean {
testedMethods.add("getBoolean")
return defValue
}
override fun contains(key: String): Boolean {
testedMethods.add("contains")
return false
}
override fun edit(): SharedPreferences.Editor {
testedMethods.add("edit")
return object : SharedPreferences.Editor {
override fun putString(key: String, value: String?): SharedPreferences.Editor {
return this
}
override fun putStringSet(key: String, values: Set<String>?): SharedPreferences.Editor {
return this
}
override fun putInt(key: String, value: Int): SharedPreferences.Editor {
return this
}
override fun putLong(key: String, value: Long): SharedPreferences.Editor {
return this
}
override fun putFloat(key: String, value: Float): SharedPreferences.Editor {
return this
}
override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor {
return this
}
override fun remove(key: String): SharedPreferences.Editor {
return this
}
override fun clear(): SharedPreferences.Editor {
return this
}
override fun commit(): Boolean {
testedMethods.add("commit")
return false
}
override fun apply() {
testedMethods.add("apply")
}
}
}
override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
testedMethods.add("registerOnSharedPreferenceChangeListener")
}
override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
testedMethods.add("unregisterOnSharedPreferenceChangeListener")
}
}
} | 0 | null | 12 | 84 | ccdc4d00ffcd4a2604becccca3ff308a6562517d | 5,094 | xpref | Apache License 2.0 |
src/main/kotlin/io/vexelabs/bitbuilder/llvm/ir/Instruction.kt | ardlank | 302,768,929 | true | {"Kotlin": 408575} | package io.vexelabs.bitbuilder.llvm.ir
import io.vexelabs.bitbuilder.llvm.internal.contracts.PointerIterator
import io.vexelabs.bitbuilder.llvm.internal.contracts.Validatable
import io.vexelabs.bitbuilder.llvm.internal.util.fromLLVMBool
import io.vexelabs.bitbuilder.llvm.ir.values.traits.DebugLocationValue
import org.bytedeco.javacpp.SizeTPointer
import org.bytedeco.llvm.LLVM.LLVMValueRef
import org.bytedeco.llvm.global.LLVM
/**
* Interface to llvm::Instruction
*
* An instruction is an operation which is performed on a set of [Value]s in
* the LLVM IR.
*
* Common instructions are add, sub, mul and div.
*
* See https://llvm.org/docs/LangRef.html#instruction-reference
*/
public open class Instruction internal constructor() : Value(),
DebugLocationValue, Validatable, Cloneable {
public override var valid: Boolean = true
public constructor(llvmRef: LLVMValueRef) : this() {
ref = llvmRef
}
/**
* Determine if this instruction has metadata
*
* @see LLVM.LLVMHasMetadata
*/
public fun hasMetadata(): Boolean {
return LLVM.LLVMHasMetadata(ref).fromLLVMBool()
}
/**
* Get the metadata for this instruction
*
* If the instruction does not have metadata, an exception will be thrown
*
* @see LLVM.LLVMGetMetadata
*/
public fun getMetadata(kind: Int): Value? {
val value = LLVM.LLVMGetMetadata(ref, kind)
return value?.let { Value(it) }
}
/**
* Get the metadata for this instruction
*
* This function converts the [kind] to the integer kind. This requires a
* context. You can pass a custom context via the [context] argument. By
* default, the context the instruction was created in will be used.
*
* @see LLVM.LLVMGetMetadata
*/
public fun getMetadata(
kind: String,
context: Context = getContext()
): Value? {
val kindId = context.getMetadataKindId(kind)
return getMetadata(kindId)
}
/**
* Set the metadata for this instruction
*
* This function uses numeric metadata ids. If you prefer to use string
* ids, use the overload for [String]
**
* @see LLVM.LLVMSetMetadata
*/
public fun setMetadata(kind: Int, metadata: Value) {
LLVM.LLVMSetMetadata(ref, kind, metadata.ref)
}
/**
* Set the metadata for this instruction
*
* This function converts the [kind] to the integer kind. This requires a
* context. You can pass a custom context via the [context] argument. By
* default, the context the instruction was created in will be used.
*
* @see LLVM.LLVMGetMDKindIDInContext
* @see LLVM.LLVMSetMetadata
*/
public fun setMetadata(
kind: String,
metadata: Value,
context: Context = getContext()
) {
val kindId = context.getMetadataKindId(kind)
setMetadata(kindId, metadata)
}
/**
* Get all the metadata for the instruction apart from debug location
* metadata
*
* @see LLVM.LLVMInstructionGetAllMetadataOtherThanDebugLoc
*/
public fun getAllMetadataExceptDebugLocations(): MetadataEntries {
val size = SizeTPointer(0)
val entries = LLVM.LLVMInstructionGetAllMetadataOtherThanDebugLoc(
ref,
size
)
return MetadataEntries(entries, size)
}
/**
* Get the [BasicBlock] this instruction lives inside
*
* @see LLVM.LLVMGetInstructionParent
*/
public fun getInstructionBlock(): BasicBlock? {
val bb = LLVM.LLVMGetInstructionParent(ref)
return bb?.let { BasicBlock(it) }
}
/**
* Removes the instruction from the basic block it resides in
*
* @see LLVM.LLVMInstructionRemoveFromParent
*/
public fun remove() {
require(getInstructionBlock() != null) { "This block has no parent" }
LLVM.LLVMInstructionRemoveFromParent(ref)
}
/**
* Removes the instruction from the basic block it resides in and deletes
* the reference
*
* @see LLVM.LLVMInstructionEraseFromParent
*/
public fun delete() {
require(getInstructionBlock() != null) { "This block has no parent" }
require(valid) { "This instruction has already been deleted" }
valid = false
LLVM.LLVMInstructionEraseFromParent(ref)
}
/**
* Get the opcode for this instruction
*
* @see LLVM.LLVMGetInstructionOpcode
*/
public fun getOpcode(): Opcode {
val opcode = LLVM.LLVMGetInstructionOpcode(ref)
return Opcode[opcode]
}
/**
* Clone the opcode
*
* The clone does not have a basic block attached and it does not have a
* name either
*
* @see LLVM.LLVMInstructionClone
*/
public override fun clone(): Instruction {
val clone = LLVM.LLVMInstructionClone(ref)
return Instruction(clone)
}
/**
* Determine if this instruction is a terminator instruction
*
* @see LLVM.LLVMIsATerminatorInst
*/
public fun isTerminator(): Boolean {
val inst = LLVM.LLVMIsATerminatorInst(ref)
return inst != null
}
/**
* Class to perform iteration over instructions
*
* @see [PointerIterator]
*/
public class Iterator(ref: LLVMValueRef) :
PointerIterator<Instruction, LLVMValueRef>(
start = ref,
yieldNext = { LLVM.LLVMGetNextInstruction(it) },
apply = { Instruction(it) }
)
}
| 0 | null | 0 | 0 | 633b9dcbb886446c62d90add3257d8f2f39a670c | 5,583 | bitbuilder | Apache License 2.0 |
shared/src/commonMain/kotlin/com/example/coffeeshop/data/model/DataCart.kt | larkes-cyber | 716,249,551 | false | {"Kotlin": 243966, "Swift": 80413} | package com.example.coffeeshop.data.model
data class DataCart(
val products:String
) | 0 | Kotlin | 0 | 1 | 679a5c6d59adc23da1078a18afecd2cdc8f41c5a | 89 | CoffeeShop | Apache License 2.0 |
idea/testData/codeInsight/moveUpDown/parametersAndArguments/callArgs2.kt | JakeWharton | 99,388,807 | false | null | // MOVE: down
val x = foo(
<caret>a,
b,
c
)
| 0 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 68 | kotlin | Apache License 2.0 |
data_source/src/main/java/com/titou/data_source/local/device_location/DeviceLocationManager.kt | Titoura | 307,479,201 | false | null | package com.titou.data_source.local.device_location
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.fungeo.data.entity.LocationWithName
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.OnCompleteListener
import com.titou.data_source.R
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableEmitter
import org.koin.core.KoinComponent
import java.io.IOException
class DeviceLocationManager() : KoinComponent {
lateinit var fusedLocationClient: FusedLocationProviderClient
lateinit var context: Context
fun requestLocationPermission(appCompatActivity: AppCompatActivity) {
ActivityCompat.requestPermissions(
appCompatActivity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
appCompatActivity.resources.getInteger(R.integer.location_permission_request_code)
)
}
fun build(appCompatActivity: AppCompatActivity) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(appCompatActivity)
if (appCompatActivity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestLocationPermission(appCompatActivity)
}
requestLocation()
context = appCompatActivity
}
// TODO: Make a stronger request to location so that he location is fetched even f not accessed by another app
@SuppressLint("MissingPermission")
fun getCurrentLocationObservable(): Observable<Location> {
return Observable.create { emitter ->
val completeListener = getOnCompleteListener(emitter)
try {
fusedLocationClient.lastLocation.addOnSuccessListener {
if (!emitter.isDisposed && it != null) emitter.onNext(it)
}
fusedLocationClient.lastLocation.addOnCompleteListener(completeListener)
} catch (e: Exception) {
emitter.tryOnError(e)
}
}
}
@SuppressLint("MissingPermission")
fun requestLocation(): Location? {
return try {
fusedLocationClient.lastLocation.result
} catch (e: java.lang.Exception) {
null
}
}
private fun getOnCompleteListener(emitter: ObservableEmitter<Location>): OnCompleteListener<Location> {
return OnCompleteListener { task ->
if (!task.isSuccessful) {
emitter.tryOnError(
task.exception
?: IllegalStateException("Can't get location from FusedLocationProviderClient")
)
}
}
}
}
data class Optional<T>(val value: T?)
fun <T> T?.carry() = Optional(this)
| 0 | Kotlin | 0 | 0 | 2cd5d4d0ac9fb771daf188329dc9f868dfacda5a | 3,128 | Fungeo | MIT License |
StayCation/app/src/main/java/com/withfauzan/staycation/data/ProvideData.kt | fauzanajipray | 405,716,907 | false | {"Kotlin": 42326} | package com.withfauzan.staycation.data
import androidx.compose.ui.res.painterResource
import com.withfauzan.staycation.R
object ProvideData {
val listType = listOf(
Type(R.drawable.ic_apartment,"Apartement"),
Type(R.drawable.ic_house,"House"),
Type(R.drawable.ic_studio,"Studio")
)
val listStay = listOf(
Places("Jojo's Resort", "Bali, Indonesia",80,6, R.drawable.image_category_1),
Places("Futurest", "Bandung, Indonesia",22,2, R.drawable.image_category_2),
Places("Jojo's Resort", "Jogja, Indonesia",80,6, R.drawable.image_category_3),
Places("Jojo's Resort", "Bali, Indonesia",80,6, R.drawable.image_category_1),
Places("Futurest", "Bandung, Indonesia",22,2, R.drawable.image_category_2),
Places("Jojo's Resort", "Jogja, Indonesia",80,6, R.drawable.image_category_3)
)
val listCity = listOf(
City("Bali",19542, R.drawable.city_1),
City("Jogja",9542, R.drawable.city_2),
City("Malang",5032, R.drawable.city_3)
)
val listNav = listOf(
Type(R.drawable.ic_home,"Home"),
Type(R.drawable.ic_save,"Save"),
Type(R.drawable.ic_search,"Search"),
Type(R.drawable.ic_user,"Profile")
)
} | 0 | Kotlin | 0 | 0 | 9024edec3b80858262b8fb621f62e91e9097910f | 1,240 | compose-layouting | Apache License 2.0 |
kotlin-typescript/src/main/generated/typescript/PrefixUnaryExpression.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
package typescript
sealed external interface PrefixUnaryExpression : UpdateExpression, Union.PrefixUnaryExpression_ {
override val kind: SyntaxKind.PrefixUnaryExpression
val operator: PrefixUnaryOperator
val operand: UnaryExpression
}
| 12 | Kotlin | 145 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 293 | kotlin-wrappers | Apache License 2.0 |
colormath/src/commonMain/kotlin/com/github/ajalt/colormath/internal/InternalMath.kt | ajalt | 139,778,270 | false | null | package com.github.ajalt.colormath.internal
import kotlin.math.*
internal fun Float.degToRad(): Float = toDouble().degToRad().toFloat()
internal fun Float.radToDeg(): Float = toDouble().radToDeg().toFloat()
internal fun Float.gradToDeg(): Float = this * .9f
internal fun Float.turnToDeg(): Float = this * 360f
internal fun Float.degToGrad(): Float = this * 200f / 180f
internal fun Float.degToTurns(): Float = this / 360f
internal fun Double.radToDeg(): Double = (this * 180.0 / PI)
internal fun Double.degToRad(): Double = (this * PI / 180.0)
internal fun cosDeg(deg: Double) = cos(deg.degToRad())
internal fun sinDeg(deg: Double) = sin(deg.degToRad())
// formula from https://www.w3.org/TR/css-color-4/#hue-interpolation
/** Return this value shifted to lie in [0, 360] */
internal fun Float.normalizeDeg(): Float = ((this % 360f) + 360f) % 360f
internal fun Double.normalizeDeg(): Double = ((this % 360.0) + 360.0) % 360.0
internal fun Float.nanToOne(): Float = if (isNaN()) 1f else this
// Used for LAB <-> LCHab, LUV <-> LCHuv, Oklab <-> Oklch, JAB <-> JCH
// https://www.w3.org/TR/css-color-4/#lab-to-lch
// https://bottosson.github.io/posts/oklab/#the-oklab-color-space
// https://en.wikipedia.org/wiki/CIELUV#Cylindrical_representation_.28CIELCH.29
internal inline fun <T> toPolarModel(a: Float, b: Float, block: (c: Float, h: Float) -> T): T {
val c = sqrt(a * a + b * b)
val h = if (c > -1e-7 && c < 1e-7) Float.NaN else atan2(b, a).radToDeg()
return block(c, h.normalizeDeg())
}
internal inline fun <T> fromPolarModel(c: Float, h: Float, block: (a: Float, b: Float) -> T): T {
val hDegrees = if (h.isNaN()) 0f else h.degToRad()
val a = c * cos(hDegrees)
val b = c * sin(hDegrees)
return block(a, b)
}
/**
* return `sign(a) * |a|^p`, which avoids NaN when `this` is negative
*/
internal fun Double.spow(p: Double): Double = absoluteValue.pow(p).withSign(this)
internal fun Float.spow(p: Double): Double = toDouble().spow(p)
internal fun sqrtSumSq(a: Float, b: Float, c: Float): Float = sqrt(a.pow(2) + b.pow(2) + c.pow(2))
internal fun sqrtSumSq(a: Double, b: Double): Double = sqrt(a.pow(2) + b.pow(2))
internal fun sqrtSumSq(a: Double, b: Double, c: Double): Double = sqrt(a.pow(2) + b.pow(2) + c.pow(2))
internal fun scaleRange(l1: Float, r1: Float, l2: Float, r2: Float, t: Float): Float {
return if (r1 == l1) t else (r2 - l2) * (t - l1) / (r1 - l1) + l2
}
| 1 | null | 6 | 293 | 903b87cce2574cce96994cd69a9806586ee03ce2 | 2,418 | colormath | MIT License |
app/src/main/java/com/example/screen/data/database/entity/DailyEntity.kt | eneskkoc | 417,625,276 | false | null | package com.example.mvmm.data.database.entity
import android.annotation.SuppressLint
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.text.SimpleDateFormat
import java.util.*
@Entity(tableName = "daily")
data class DailyEntity (
@ColumnInfo(name = "dt") var dt: Long?,
@ColumnInfo(name = "temp") var temp: TempEntity?,//TempEntity
@ColumnInfo(name = "weather") var weather: List<WeatherXentity>?,//List<Weather>
@ColumnInfo(name = "humidity") var humidity: Int?,
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id") var id: Int=0
)
{
@SuppressLint("SimpleDateFormat")
fun date(): String { // timestamp convert date
var day=dt
val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy", Locale.forLanguageTag("tr"))
var dy=simpleDateFormat.format(day!! * 1000L)
return dy.toString()
}
}
| 0 | Kotlin | 0 | 0 | 37de38f8725ad0b78cd49b6d1c11172421f03080 | 921 | forecast-weather-app-v2 | MIT License |
fxgl/src/main/kotlin/com/almasb/fxgl/extra/ai/goap/FSMState.kt | valdirluiz | 152,665,398 | true | {"YAML": 2, "Maven POM": 4, "Markdown": 6, "Text": 11, "Ignore List": 1, "Kotlin": 228, "Java": 657, "kvlang": 2, "Java Properties": 3, "XML": 15, "CSS": 7, "JavaScript": 6, "Ragel": 1, "JSON": 6} | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.extra.ai.goap
import com.almasb.fxgl.entity.Entity
/**
* Adapted from https://github.com/sploreg/goap
* Original source: C#, author: <NAME>.
*
* @author <NAME> (<EMAIL>)
*/
interface FSMState {
fun update(fsm: FSM, entity: Entity)
} | 0 | Java | 0 | 0 | cad7ced19da4693e87828a4a07919a5bb30b45cd | 393 | FXGL | MIT License |
state/src/main/java/me/rei_m/hyakuninisshu/state/material/model/Material.kt | rei-m | 68,487,243 | false | null | /*
* Copyright (c) 2020. <NAME>
*
* 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 me.rei_m.hyakuninisshu.state.material.model
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.DrawableRes
/**
* 歌の資料表示用.
*
* @param no 番号
* @param noTxt 番号の表示用テキスト
* @param kimariji 決まり字
* @param kimarijiTxt 決まり字の表示用テキスト
* @param creator 作者
* @param shokuKanji 初句の漢字
* @param shokuKana 初句のかな
* @param nikuKanji 二句の漢字
* @param nikuKana 二句のかな
* @param sankuKanji 三句の漢字
* @param sankuKana 三句のかな
* @param shikuKanji 四句の漢字
* @param shikuKana 四句のかな
* @param gokuKanji 結句の漢字
* @param gokuKana 結句のかな
* @param translation 訳
* @param imageResId 画像のリソースID
*/
data class Material(
val no: Int,
val noTxt: String,
val kimariji: Int,
val kimarijiTxt: String,
val creator: String,
val shokuKanji: String,
val shokuKana: String,
val nikuKanji: String,
val nikuKana: String,
val sankuKanji: String,
val sankuKana: String,
val shikuKanji: String,
val shikuKana: String,
val gokuKanji: String,
val gokuKana: String,
val translation: String,
@DrawableRes val imageResId: Int
) : Parcelable {
val kamiNoKuKanji: String = "$shokuKanji $nikuKanji $sankuKanji"
val kamiNoKuKana: String = "$shokuKana $nikuKana $sankuKana"
val shimoNoKuKanji: String = "$shikuKanji $gokuKanji"
val shimoNoKuKana: String = "$shikuKana $gokuKana"
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString()!!,
parcel.readInt(),
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readInt()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(no)
parcel.writeString(noTxt)
parcel.writeInt(kimariji)
parcel.writeString(kimarijiTxt)
parcel.writeString(creator)
parcel.writeString(shokuKanji)
parcel.writeString(shokuKana)
parcel.writeString(nikuKanji)
parcel.writeString(nikuKana)
parcel.writeString(sankuKanji)
parcel.writeString(sankuKana)
parcel.writeString(shikuKanji)
parcel.writeString(shikuKana)
parcel.writeString(gokuKanji)
parcel.writeString(gokuKana)
parcel.writeString(translation)
parcel.writeInt(imageResId)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Material> {
override fun createFromParcel(parcel: Parcel): Material {
return Material(parcel)
}
override fun newArray(size: Int): Array<Material?> {
return arrayOfNulls(size)
}
}
}
| 0 | null | 1 | 11 | c43afed6779430cd08f85a208260896e4e295c35 | 3,555 | android_hyakuninisshu | Apache License 2.0 |
photos_ui/src/main/java/com/nowjordanhappy/photos_ui/search/components/CardLoadingPresenter.kt | nowjordanhappy | 631,133,237 | false | {"Kotlin": 98399} | package com.nowjordanhappy.photos_ui.search.components
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.core.view.updateLayoutParams
import androidx.leanback.widget.Presenter
/**
* A CardPresenter is used to generate Views and bind Objects to them on demand.
* It contains an ImageCardView.
*/
class CardLoadingPresenter(
private val width: Int = 313,
private val height: Int = 176
) : Presenter() {
override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder {
val cardView = LayoutInflater.from(parent.context)
.inflate(com.nowjordanhappy.photos_ui.R.layout.card_loading_layout, parent, false);
cardView.isFocusable = false
cardView.isFocusableInTouchMode = false
return Presenter.ViewHolder(cardView)
}
override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) {
val item = item as? Int
val cardView = viewHolder.view as RelativeLayout
cardView.updateLayoutParams {
height = [email protected]
width = [email protected]
}
/*val shimmer = cardView.findViewById<ShimmerFrameLayout>(R.id.shimmer_view_container)
if(!shimmer.isShimmerVisible)shimmer.startShimmer()*/
Log.d(TAG, "onBindViewHolder")
}
override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) {
Log.d(TAG, "onUnbindViewHolder")
val cardView = viewHolder.view as RelativeLayout
/*val shimmer = cardView.findViewById<ShimmerFrameLayout>(R.id.shimmer_view_container)
if(shimmer.isShimmerVisible)shimmer.stopShimmer()*/
}
companion object {
private val TAG = "CardLoadingPresenter"
}
} | 0 | Kotlin | 0 | 1 | 8c8d7d412d8464ba49b238988a085c41020a5a19 | 1,819 | AndroidTvDemoPlus | The Unlicense |
test-app/ios-shared/src/commonMain/kotlin/com/example/redwood/testapp/ios/TestAppLauncher.kt | cashapp | 305,409,146 | false | {"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129} | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.redwood.emojisearch.ios
import app.cash.redwood.leaks.LeakDetector
import app.cash.redwood.treehouse.EventListener
import app.cash.redwood.treehouse.TreehouseApp
import app.cash.redwood.treehouse.TreehouseAppFactory
import app.cash.zipline.Zipline
import app.cash.zipline.ZiplineManifest
import app.cash.zipline.loader.ManifestVerifier
import app.cash.zipline.loader.asZiplineHttpClient
import app.cash.zipline.loader.withDevelopmentServerPush
import com.example.redwood.emojisearch.launcher.EmojiSearchAppSpec
import com.example.redwood.emojisearch.treehouse.EmojiSearchPresenter
import com.example.redwood.emojisearch.treehouse.HostApi
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.flowOf
import platform.Foundation.NSLog
import platform.Foundation.NSOperationQueue
import platform.Foundation.NSURLSession
class EmojiSearchLauncher(
private val nsurlSession: NSURLSession,
private val hostApi: HostApi,
) {
private val coroutineScope: CoroutineScope = MainScope()
private val manifestUrl = "http://localhost:8080/manifest.zipline.json"
@Suppress("unused") // Invoked in Swift.
fun createTreehouseApp(listener: EmojiSearchEventListener): TreehouseApp<EmojiSearchPresenter> {
val ziplineHttpClient = nsurlSession.asZiplineHttpClient()
val eventListener = object : EventListener() {
override fun codeLoadFailed(exception: Exception, startValue: Any?) {
NSLog("Treehouse: codeLoadFailed: $exception")
NSOperationQueue.mainQueue.addOperationWithBlock {
listener.codeLoadFailed()
}
}
override fun codeLoadSuccess(manifest: ZiplineManifest, zipline: Zipline, startValue: Any?) {
NSLog("Treehouse: codeLoadSuccess")
NSOperationQueue.mainQueue.addOperationWithBlock {
listener.codeLoadSuccess()
}
}
}
val treehouseAppFactory = TreehouseAppFactory(
httpClient = ziplineHttpClient,
manifestVerifier = ManifestVerifier.Companion.NO_SIGNATURE_CHECKS,
leakDetector = LeakDetector.timeBasedIn(
scope = coroutineScope,
timeSource = TimeSource.Monotonic,
leakThreshold = 10.seconds,
callback = { reference, note ->
NSLog("Leak detected! $reference $note")
},
),
)
val manifestUrlFlow = flowOf(manifestUrl)
.withDevelopmentServerPush(ziplineHttpClient)
val treehouseApp = treehouseAppFactory.create(
appScope = coroutineScope,
spec = EmojiSearchAppSpec(
manifestUrl = manifestUrlFlow,
hostApi = hostApi,
),
eventListenerFactory = object : EventListener.Factory {
override fun create(app: TreehouseApp<*>, manifestUrl: String?) = eventListener
override fun close() {
}
},
)
treehouseApp.start()
return treehouseApp
}
}
interface EmojiSearchEventListener {
fun codeLoadFailed()
fun codeLoadSuccess()
}
| 85 | Kotlin | 73 | 1,648 | 3f14e622c2900ec7e0dfaff5bd850c95a7f29937 | 3,654 | redwood | Apache License 2.0 |
mbnetworkkit/src/main/java/com/daimler/mbnetworkkit/socket/message/Notifyable.kt | Daimler | 199,815,262 | false | null | package com.daimler.mbnetworkkit.socket.message
interface Notifyable {
fun <T> notifyChange(clazz: Class<T>, data: T)
}
| 1 | null | 8 | 15 | 3721af583408721b9cd5cf89dd7b99256e9d7dda | 126 | MBSDK-Mobile-Android | MIT License |
compiler/testData/codegen/box/reflection/methodsFromAny/adaptedCallableReferencesNotEqualToCallablesFromAPI.kt | JetBrains | 3,432,266 | false | null | // Bug happens on JVM , JVM -Xuse-ir
// WITH_REFLECT
// IGNORE_BACKEND_FIR: JVM_IR
// TARGET_BACKEND: JVM
// FILE: tmp0.kt
import kotlin.reflect.*
import kotlin.test.assertNotEquals
class A {
fun foo(s: String = "", vararg xs: Long): String = "foo"
}
fun checkNotEqual(x: Any, y: Any) {
assertNotEquals(x, y)
assertNotEquals(y, x)
}
fun coercionToUnit(f: (A, String, LongArray) -> Unit): Any = f
fun varargToElement(f: (A, String, Long, Long) -> String): Any = f
fun defaultAndVararg(f: (A) -> String): Any = f
fun allOfTheAbove(f: (A) -> Unit): Any = f
fun box(): String {
val foo = A::class.members.single { it.name == "foo" }
checkNotEqual(coercionToUnit(A::foo), foo)
checkNotEqual(varargToElement(A::foo), foo)
checkNotEqual(defaultAndVararg(A::foo), foo)
checkNotEqual(allOfTheAbove(A::foo), foo)
return "OK"
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 860 | kotlin | Apache License 2.0 |
PrticaViewModellistaRolvel/app/src/main/java/com/example/prtica_viewmodel_listarolvel/data/DataSource.kt | Jhonnathan-Jhonny | 752,604,468 | false | {"Kotlin": 305111} | package com.example.prtica_viewmodel_listarolvel.data
import com.example.prtica_viewmodel_listarolvel.R
import com.example.prtica_viewmodel_listarolvel.model.UserModel
class DataSource {
companion object {
fun loadUsers(): List<UserModel> {
return listOf(
UserModel(R.string.user1_number, R.string.user1_first_name, R.string.user1_last_name, R.drawable.avatar_1),
UserModel(R.string.user2_number, R.string.user2_first_name, R.string.user2_last_name, R.drawable.avatar_1),
UserModel(R.string.user3_number, R.string.user3_first_name, R.string.user3_last_name, R.drawable.avatar_1),
UserModel(R.string.user4_number, R.string.user4_first_name, R.string.user4_last_name, R.drawable.avatar_1),
UserModel(R.string.user5_number, R.string.user5_first_name, R.string.user5_last_name, R.drawable.avatar_1),
UserModel(R.string.user6_number, R.string.user6_first_name, R.string.user6_last_name, R.drawable.avatar_1),
UserModel(R.string.user7_number, R.string.user7_first_name, R.string.user7_last_name, R.drawable.avatar_1),
UserModel(R.string.user8_number, R.string.user8_first_name, R.string.user8_last_name, R.drawable.avatar_1),
UserModel(R.string.user9_number, R.string.user9_first_name, R.string.user9_last_name, R.drawable.avatar_1),
UserModel(R.string.user10_number, R.string.user10_first_name, R.string.user10_last_name, R.drawable.avatar_1)
)
}
}
} | 0 | Kotlin | 0 | 0 | 5b7526aedd35869f86d115e6c32c4d14f2a425f6 | 1,555 | Kotlin-AndroidStudio | MIT License |
capy/src/main/java/com/jocmp/capy/accounts/AddFeedResult.kt | jocmp | 610,083,236 | false | {"Kotlin": 674590, "Ruby": 1236, "Makefile": 1211} | package com.jocmp.capy.accounts
import com.jocmp.capy.Feed
sealed class AddFeedResult {
enum class ErrorType {
FEED_NOT_FOUND,
NETWORK_ERROR,
SAVE_FAILURE,
}
sealed class AddFeedError: Exception() {
class FeedNotFound: AddFeedError()
class NetworkError: AddFeedError()
class SaveFailure: AddFeedError()
}
data class Success(val feed: Feed): AddFeedResult()
data class MultipleChoices(val choices: List<FeedOption>): AddFeedResult()
data class Failure(val error: AddFeedError): AddFeedResult()
}
data class FeedOption(
val feedURL: String,
val title: String
)
| 15 | Kotlin | 3 | 91 | f8ac7e8c4a6fccfe8f26f1b492261a4f5ce7dafa | 651 | capyreader | MIT License |
packages/hmssdk_flutter/android/src/main/kotlin/live/hms/hmssdk_flutter/hls_player/HMSHLSPlayerAction.kt | 100mslive | 381,963,509 | false | null | package live.hms.hmssdk_flutter.hls_player
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel.Result
import live.hms.hmssdk_flutter.HMSErrorLogger
import java.lang.ref.WeakReference
/**
* This class is used to send actions from flutter plugin to HLS Player
* We use broadcast receiver to forward the request to HMSHLSPlayer
*/
class HMSHLSPlayerAction {
companion object {
private var hlsActions: WeakReference<IHLSPlayerActionInterface>? = null
fun hlsPlayerAction(
call: MethodCall,
result: Result,
) {
when (call.method) {
"start_hls_player" -> start(call, result)
"stop_hls_player" -> stop(result)
"pause_hls_player" -> pause(result)
"resume_hls_player" -> resume(result)
"seek_to_live_position" -> seekToLivePosition(result)
"seek_forward" -> seekForward(call, result)
"seek_backward" -> seekBackward(call, result)
"set_hls_player_volume" -> setVolume(call, result)
"add_hls_stats_listener" -> addHLSStatsListener(result)
"remove_hls_stats_listener" -> removeHLSStatsListener(result)
"are_closed_captions_supported" -> areClosedCaptionsSupported(result)
"enable_closed_captions" -> enableClosedCaptions(result)
"disable_closed_captions" -> disableClosedCaptions(result)
"get_stream_properties" -> getStreamProperties(result)
"get_hls_layers" -> getHLSLayers(result)
"set_hls_layer" -> setHLSLayer(call, result)
"get_current_hls_layer" -> getCurrentHLSLayer(result)
else -> {
result.notImplemented()
}
}
}
fun assignInterfaceObject(actionObject: WeakReference<IHLSPlayerActionInterface>) {
hlsActions = actionObject
}
/**
* Starts the HLS player by sending a broadcast intent with the specified method call and HLS URL.
*
* @param call The method call object containing the HLS URL as an argument.
* @param result The result object to be returned after starting the player.
*/
private fun start(
call: MethodCall,
result: Result,
) {
val hlsUrl = call.argument<String?>("hls_url")
hlsActions?.let {
it.get()?.start(hlsUrl, result)
} ?: run {
HMSErrorLogger.logError("start", "hlsActions is NULL", "NULL Error")
}
}
/**
* Stops the HLS player by sending a broadcast intent with the specified method call.
*
* @param result The result object to be returned after stopping the player.
*/
private fun stop(result: Result) {
hlsActions?.let {
it.get()?.stop(result)
} ?: run {
HMSErrorLogger.logError("stop", "hlsActions is NULL", "NULL Error")
}
}
/**
* Pauses the HLS player by sending a broadcast intent with the specified method call.
*
* @param result The result object to be returned after pausing the player.
*/
private fun pause(result: Result) {
hlsActions?.let {
it.get()?.pause(result)
} ?: run {
HMSErrorLogger.logError("pause", "hlsActions is NULL", "NULL Error")
}
}
/**
* Resumes the HLS player by sending a broadcast intent with the specified method call.
*
* @param result The result object to be returned after resuming the player.
*/
private fun resume(result: Result) {
hlsActions?.let {
it.get()?.resume(result)
} ?: run {
HMSErrorLogger.logError("resume", "hlsActions is NULL", "NULL Error")
}
}
/**
* Seeks to the live position in the HLS player by sending a broadcast intent with the specified method call.
*
* @param result The result object to be returned after seeking to the live position.
*/
private fun seekToLivePosition(result: Result) {
hlsActions?.let {
it.get()?.seekToLivePosition(result)
} ?: run {
HMSErrorLogger.logError("seekToLivePosition", "hlsActions is NULL", "NULL Error")
}
}
/**
* Seeks forward in the HLS player by the specified number of seconds, sending a broadcast intent with the seek duration.
*
* @param call The method call object containing the number of seconds to seek forward as an argument.
* @param result The result object to be returned after seeking forward.
*/
private fun seekForward(
call: MethodCall,
result: Result,
) {
val seconds: Int? =
call.argument<Int?>("seconds") ?: run {
HMSErrorLogger.returnArgumentsError("seconds parameter is null in seekForward method")
null
}
seconds?.let {
hlsActions?.let { _hlsActions ->
_hlsActions.get()?.seekForward(it, result)
} ?: run {
HMSErrorLogger.logError("seekForward", "hlsActions is NULL", "NULL Error")
}
}
}
/**
* Seeks backward in the HLS player by the specified number of seconds, sending a broadcast intent with the seek duration.
*
* @param call The method call object containing the number of seconds to seek backward as an argument.
* @param result The result object to be returned after seeking backward.
*/
private fun seekBackward(
call: MethodCall,
result: Result,
) {
val seconds: Int? =
call.argument<Int?>("seconds") ?: run {
HMSErrorLogger.returnArgumentsError("seconds parameter is null in seekBackward method")
null
}
seconds?.let {
hlsActions?.let { _hlsActions ->
_hlsActions.get()?.seekBackward(it, result)
} ?: run {
HMSErrorLogger.logError("seekBackward", "hlsActions is NULL", "NULL Error")
}
}
}
/**
* Sets the volume level of the HLS player by sending a broadcast intent with the specified volume value.
*
* @param call The method call object containing the volume level as an argument.
* @param result The result object to be returned after setting the volume.
*/
private fun setVolume(
call: MethodCall,
result: Result,
) {
val volume: Int? =
call.argument<Int?>("volume") ?: run {
HMSErrorLogger.returnArgumentsError("Volume parameter is null in setVolume method")
null
}
volume?.let {
hlsActions?.let { _hlsActions ->
_hlsActions.get()?.setVolume(it, result)
} ?: run {
HMSErrorLogger.logError("setVolume", "hlsActions is NULL", "NULL Error")
}
}
}
/**
* Adds a listener to receive HLS player statistics by sending a broadcast intent with the corresponding method call.
*
* @param result The result object to be returned after adding the HLS stats listener.
*/
private fun addHLSStatsListener(result: Result) {
hlsActions?.let {
it.get()?.addHLSStatsListener(result)
} ?: run {
HMSErrorLogger.logError("addHLSStatsListener", "hlsActions is NULL", "NULL Error")
}
}
/**
* Removes the listener for HLS player statistics by sending a broadcast intent with the corresponding method call.
*
* @param result The result object to be returned after removing the HLS stats listener.
*/
private fun removeHLSStatsListener(result: Result) {
hlsActions?.let {
it.get()?.removeHLSStatsListener(result)
} ?: run {
HMSErrorLogger.logError("removeHLSStatsListener", "hlsActions is NULL", "NULL Error")
}
}
/**
* Checks whether closed captions are supported or not
* This can be enabled/disabled from 100ms dashboard
*
* @param result The result object used to send response regarding closed captions
*/
private fun areClosedCaptionsSupported(result: Result) {
hlsActions?.let {
it.get()?.areClosedCaptionsSupported(result)
} ?: run {
HMSErrorLogger.logError("areClosedCaptionsSupported", "hlsActions is NULL", "NULL Error")
}
}
/**
* Enable closed captions in the player
*
* @param result is the object to be returned after enabling closed captions
*/
private fun enableClosedCaptions(result: Result) {
hlsActions?.let {
it.get()?.enableClosedCaptions(result)
} ?: run {
HMSErrorLogger.logError("enableClosedCaptions", "hlsActions is NULL", "NULL Error")
}
}
/**
* Disable closed captions in the player
*
* @param result is the object to be returned after disabling closed captions
*/
private fun disableClosedCaptions(result: Result) {
hlsActions?.let {
it.get()?.disableClosedCaptions(result)
} ?: run {
HMSErrorLogger.logError("disableClosedCaptions", "hlsActions is NULL", "NULL Error")
}
}
private fun getStreamProperties(result: Result) {
hlsActions?.let {
it.get()?.getStreamProperties(result)
} ?: run {
HMSErrorLogger.logError("getStreamProperties", "hlsActions is NULL", "NULL Error")
}
}
private fun getHLSLayers(result: Result) {
hlsActions?.let {
it.get()?.getHLSLayers(result)
} ?: run {
HMSErrorLogger.logError("getHLSLayers", "hlsActions is NULL", "NULL Error")
}
}
private fun setHLSLayer(
call: MethodCall,
result: Result,
) {
val layerMap = call.argument<HashMap<Any, Any?>?>("layer")
layerMap?.let {
if (layerMap["resolution"] != null && layerMap["bitrate"] != null) {
hlsActions?.let {
it.get()?.setHLSLayer(layerMap, result)
} ?: run {
HMSErrorLogger.logError("getCurrentHLSLayer", "hlsActions is NULL", "NULL Error")
}
}
} ?: run {
HMSErrorLogger.returnArgumentsError("hmsHLSLayer is null in setHLSLayer")
}
}
private fun getCurrentHLSLayer(result: Result) {
hlsActions?.let {
it.get()?.getCurrentHLSLayer(result)
} ?: run {
HMSErrorLogger.logError("getCurrentHLSLayer", "hlsActions is NULL", "NULL Error")
}
}
}
}
| 2 | null | 64 | 137 | 85a1d95b9c36f118146b309196111d59ea8570ab | 11,710 | 100ms-flutter | MIT License |
src/main/kotlin/com/autonomousapps/model/intermediates/producers.kt | autonomousapps | 217,134,508 | false | null | package com.autonomousapps.model.intermediates
import com.autonomousapps.internal.utils.ifNotEmpty
import com.autonomousapps.internal.utils.toCoordinates
import com.autonomousapps.model.*
import com.squareup.moshi.JsonClass
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import java.io.File
internal interface DependencyView<T> : Comparable<T> where T : DependencyView<T> {
val coordinates: Coordinates
fun toCapabilities(): List<Capability>
override fun compareTo(other: T): Int = coordinates.compareTo(other.coordinates)
}
/**
* A dependency that includes a lint jar. (Which is maybe always named lint.jar?)
*
* Example registry: `nl.littlerobots.rxlint.RxIssueRegistry`.
*
* nb: Deliberately does not implement [DependencyView]. For various reasons, this information gets embedded in
* [ExplodedJar], which is the preferred access point for deeper analysis.
*/
@JsonClass(generateAdapter = false)
internal data class AndroidLinterDependency(
val coordinates: Coordinates,
val lintRegistry: String,
) : Comparable<AndroidLinterDependency> {
override fun compareTo(other: AndroidLinterDependency): Int = coordinates.compareTo(other.coordinates)
}
/** Metadata from an Android manifest. */
@JsonClass(generateAdapter = false)
internal data class AndroidManifestDependency(
override val coordinates: Coordinates,
/** A map of component type to components. */
val componentMap: Map<AndroidManifestCapability.Component, Set<String>>,
) : DependencyView<AndroidManifestDependency> {
constructor(
componentMap: Map<AndroidManifestCapability.Component, Set<String>>,
artifact: ResolvedArtifactResult,
) : this(
componentMap = componentMap,
coordinates = artifact.toCoordinates()
)
override fun toCapabilities(): List<Capability> = listOf(AndroidManifestCapability(componentMap))
}
/** A dependency that includes Android assets (e.g., src/main/assets). A runtime dependency. */
@JsonClass(generateAdapter = false)
internal data class AndroidAssetDependency(
override val coordinates: Coordinates,
val assets: List<String>,
) : DependencyView<AndroidAssetDependency> {
override fun toCapabilities(): List<Capability> = listOf(AndroidAssetCapability(assets))
}
@JsonClass(generateAdapter = false)
internal data class AndroidResDependency(
override val coordinates: Coordinates,
/** An import that indicates a possible use of an Android resource from this dependency. */
val import: String,
val lines: List<AndroidResCapability.Line>,
) : DependencyView<AndroidResDependency> {
override fun toCapabilities(): List<Capability> = listOf(AndroidResCapability(import, lines))
}
@JsonClass(generateAdapter = false)
internal data class AnnotationProcessorDependency(
override val coordinates: Coordinates,
val processor: String,
val supportedAnnotationTypes: Set<String>,
) : DependencyView<AnnotationProcessorDependency> {
constructor(
processor: String,
supportedAnnotationTypes: Set<String>,
artifact: ResolvedArtifactResult,
) : this(
processor = processor,
supportedAnnotationTypes = supportedAnnotationTypes,
coordinates = artifact.toCoordinates()
)
override fun toCapabilities(): List<Capability> = listOf(
AnnotationProcessorCapability(processor, supportedAnnotationTypes)
)
}
@JsonClass(generateAdapter = false)
internal data class InlineMemberDependency(
override val coordinates: Coordinates,
val inlineMembers: Set<InlineMemberCapability.InlineMember>,
) : DependencyView<InlineMemberDependency> {
override fun toCapabilities(): List<Capability> = listOf(InlineMemberCapability(inlineMembers))
}
@JsonClass(generateAdapter = false)
internal data class TypealiasDependency(
override val coordinates: Coordinates,
val typealiases: Set<TypealiasCapability.Typealias>,
) : DependencyView<TypealiasDependency> {
override fun toCapabilities(): List<Capability> = listOf(TypealiasCapability(typealiases))
}
@JsonClass(generateAdapter = false)
internal data class NativeLibDependency(
override val coordinates: Coordinates,
val fileNames: Set<String>,
) : DependencyView<NativeLibDependency> {
override fun toCapabilities(): List<Capability> = listOf(NativeLibCapability(fileNames))
}
@JsonClass(generateAdapter = false)
internal data class ServiceLoaderDependency(
override val coordinates: Coordinates,
val providerFile: String,
val providerClasses: Set<String>,
) : DependencyView<ServiceLoaderDependency> {
constructor(
providerFile: String,
providerClasses: Set<String>,
artifact: ResolvedArtifactResult,
) : this(
providerFile = providerFile,
providerClasses = providerClasses,
coordinates = artifact.toCoordinates()
)
override fun toCapabilities(): List<Capability> = listOf(ServiceLoaderCapability(providerFile, providerClasses))
}
/**
* A library or project, along with the set of classes declared by, and other information contained within, this
* exploded jar. This is the serialized form of [ExplodingJar].
*/
@JsonClass(generateAdapter = false)
internal data class ExplodedJar(
override val coordinates: Coordinates,
val jarFile: File,
/**
* True if this dependency contains only annotation that are only needed at compile-time (`CLASS`
* and `SOURCE` level retention policies). False otherwise.
*/
val isCompileOnlyAnnotations: Boolean = false,
/**
* The set of classes that are service providers (they extend [java.security.Provider]). May be
* empty.
*/
val securityProviders: Set<String> = emptySet(),
/**
* Android Lint registry, if there is one. May be null.
*/
val androidLintRegistry: String? = null,
/**
* True if this component contains _only_ an Android Lint jar/registry. If this is true,
* [androidLintRegistry] must be non-null.
*/
val isLintJar: Boolean = false,
/**
* The classes declared by this library.
*/
val classes: Set<String>,
/**
* A map of each class declared by this library to the set of constants it defines. The latter may
* be empty for any given declared class.
*/
val constantFields: Map<String, Set<String>>,
/**
* All of the "Kt" files within this component.
*/
val ktFiles: Set<KtFile>,
) : DependencyView<ExplodedJar> {
internal constructor(
artifact: PhysicalArtifact,
exploding: ExplodingJar,
) : this(
coordinates = artifact.coordinates,
jarFile = artifact.file,
isCompileOnlyAnnotations = exploding.isCompileOnlyCandidate,
securityProviders = exploding.securityProviders,
androidLintRegistry = exploding.androidLintRegistry,
isLintJar = exploding.isLintJar,
classes = exploding.classNames,
constantFields = exploding.constants,
ktFiles = exploding.ktFiles
)
override fun compareTo(other: ExplodedJar): Int {
return coordinates.compareTo(other.coordinates).let {
if (it == 0) jarFile.compareTo(other.jarFile) else it
}
}
init {
if (isLintJar && androidLintRegistry == null) {
throw IllegalStateException("Android lint jar for $coordinates must contain a lint registry")
}
}
override fun toCapabilities(): List<Capability> {
val capabilities = mutableListOf<Capability>()
capabilities += InferredCapability(isCompileOnlyAnnotations = isCompileOnlyAnnotations)
classes.ifNotEmpty { capabilities += ClassCapability(it) }
constantFields.ifNotEmpty { capabilities += ConstantCapability(it, ktFiles) }
securityProviders.ifNotEmpty { capabilities += SecurityProviderCapability(it) }
androidLintRegistry?.let { capabilities += AndroidLinterCapability(it, isLintJar) }
return capabilities
}
}
| 85 | null | 55 | 910 | da02a56a0b7a00a26876cdaa29321f8376bf7099 | 7,642 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
app/src/main/java/kz/oqu/android/model/repositories/user/UserRepository.kt | abikko | 362,209,725 | false | null | package kz.oqu.android.model.repositories.user
interface UserRepository {
fun getUser(callbacks: UserDownloadCallbacks)
fun updateUserAsStudent(grade: String, name: String, callbacks: UserUpdateCallbacks)
fun exitUserFromAccount(callbacks: UserExitFromAccountCallbacks)
} | 0 | Kotlin | 0 | 2 | 5b9b8dd259634831a3057b50d4dc6425c421c216 | 286 | oqutushy.kz | MIT License |
Section 5/Paging/app/src/main/java/com/paging/packt/paging/GitRepoDataSource.kt | PacktPublishing | 165,982,326 | false | null | package com.paging.packt.paging
import androidx.paging.PageKeyedDataSource
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GitRepoDataSource : PageKeyedDataSource<Int, GitRepo>() {
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, GitRepo>) {
val service = GitRepoServiceBuilder.buildService(GitRepoService::class.java)
val call = service.getRepositories(FIRST_PAGE, PAGE_SIZE, TOPIC)
call.enqueue(object : Callback<GitRepoResponse> {
// If you receive a HTTP Response, then this method is executed
override fun onResponse(call: Call<GitRepoResponse>, response: Response<GitRepoResponse>) {
if (response.isSuccessful) {
val apiResponse = response.body()!!
val responseItems = apiResponse.items
responseItems?.let {
callback.onResult(responseItems, null, FIRST_PAGE + 1)
}
}
}
// Invoked in case of Network Error or Establishing connection with Server
// or Error Creating Http Request or Error Processing Http Response
override fun onFailure(call: Call<GitRepoResponse>, t: Throwable) {
}
})
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, GitRepo>) {
val service = GitRepoServiceBuilder.buildService(GitRepoService::class.java)
val call = service.getRepositories(params.key, PAGE_SIZE, TOPIC)
call.enqueue(object : Callback<GitRepoResponse> {
override fun onResponse(call: Call<GitRepoResponse>, response: Response<GitRepoResponse>) {
if (response.isSuccessful) {
val apiResponse = response.body()!!
val responseItems = apiResponse.items
val key = if (apiResponse.totalCount > params.key) params.key + 1 else apiResponse.totalCount
responseItems?.let {
callback.onResult(responseItems, key)
}
}
}
override fun onFailure(call: Call<GitRepoResponse>, t: Throwable) {
}
})
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, GitRepo>) {
val service = GitRepoServiceBuilder.buildService(GitRepoService::class.java)
val call = service.getRepositories(params.key, PAGE_SIZE, TOPIC)
call.enqueue(object : Callback<GitRepoResponse> {
override fun onResponse(call: Call<GitRepoResponse>, response: Response<GitRepoResponse>) {
if (response.isSuccessful) {
val apiResponse = response.body()!!
val responseItems = apiResponse.items
val key = if (params.key > 1) params.key - 1 else 0
responseItems?.let {
callback.onResult(responseItems, key)
}
}
}
override fun onFailure(call: Call<GitRepoResponse>, t: Throwable) {
}
})
}
companion object {
const val PAGE_SIZE = 10
const val FIRST_PAGE = 1
const val TOPIC = "android"
}
} | 1 | Kotlin | 9 | 24 | dd4170eed18631f03932f001f965ae0f72139623 | 3,355 | Android-Jetpack-Architecture-Components | MIT License |
core/src/commonMain/kotlin/de/haukesomm/sokoban/core/moving/MoveServiceImpl.kt | haukesomm | 245,519,631 | false | {"Kotlin": 236642, "Java": 15311, "JavaScript": 3207, "HTML": 820, "CSS": 58} | package de.haukesomm.sokoban.core.moving
import de.haukesomm.sokoban.core.*
/**
* Implementation of [MoveService] which uses a set of [MoveRule]s to determine whether a move is possible.
*
* These rules are checked in order and the first rule which returns [MoveRuleResult.Status.Impossible] stops the
* process and the method returns `null`. If the first rule returns [MoveRuleResult.Status.BoxAheadNeedsToMove], the
* service tries to move the box ahead recursively. If this recursive call returns `null`, the method returns `null` as
* well. Otherwise, the method returns a new [GameState] with the entity moved and the box moved as well.
*/
class MoveServiceImpl(private vararg val moveRules: MoveRule) : MoveService {
private data class Result(
val success: Boolean,
val moveActions: MutableList<MoveAction>
)
override fun moveEntityIfPossible(state: GameState, position: Position, direction: Direction): GameState? {
val result = determineMovesRecursively(state, position, direction)
return if (result.success) {
result.moveActions
.fold(state) { acc, action -> action.performMove(acc) }
.transform { previous = state }
} else null
}
private fun determineMovesRecursively(state: GameState, position: Position, direction: Direction): Result {
val results = moveRules
.toSet()
.checkAll(state, position, direction)
val statuses = results
.map(MoveRuleResult::status)
.toMutableSet()
if (MoveRuleResult.Status.Impossible in statuses) {
return Result(
success = false,
moveActions = mutableListOf()
)
} else if (MoveRuleResult.Status.BoxAheadNeedsToMove in statuses) {
val nextPosition = position.nextInDirection(direction)
if (state.tileAt(nextPosition)?.entity == null)
throw IllegalStateException("Box ahead needs to move but there is no entity!")
return determineMovesRecursively(state, nextPosition, direction).apply {
if (success) {
moveActions += SimpleMoveAction(position, direction).incrementPushes()
}
}
} else {
return Result(
success = true,
moveActions = mutableListOf(
SimpleMoveAction(position, direction).incrementMoves()
)
)
}
}
} | 0 | Kotlin | 0 | 3 | 66e550f1f46720fa3c11d37626a20e4c73b45acc | 2,535 | Sokoban | MIT License |
src/day03/Day03.kt | PoisonedYouth | 571,927,632 | false | null | package day03
import readInput
fun main() {
fun Char.calculatePriority(): Int {
return if (this.isUpperCase()) (this - 'A' + 27) else (this - 'a' + 1)
}
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val (part1, part2) = line.chunked(line.length / 2).map { it.toSet() }
part1.intersect(part2).first().calculatePriority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
val (elv1, elv2, elv3) = group.map { it.toSet() }
elv1.intersect(elv2).intersect(elv3).first().calculatePriority()
}
}
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 1 | 0 | dbcb627e693339170ba344847b610f32429f93d1 | 756 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNodeTextureParameter.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.TypeManager
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.memory.TransferContext
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
/**
* Performs a uniform texture lookup within the visual shader graph.
*
* Performs a lookup operation on the texture provided as a uniform for the shader.
*/
@GodotBaseType
public open class VisualShaderNodeTextureParameter internal constructor() :
VisualShaderNodeParameter() {
/**
* Defines the type of data provided by the source texture. See [enum TextureType] for options.
*/
public var textureType: TextureType
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTextureTypePtr, LONG)
return VisualShaderNodeTextureParameter.TextureType.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, MethodBindings.setTextureTypePtr, NIL)
}
/**
* Sets the default color if no texture is assigned to the uniform.
*/
public var colorDefault: ColorDefault
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getColorDefaultPtr, LONG)
return VisualShaderNodeTextureParameter.ColorDefault.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, MethodBindings.setColorDefaultPtr, NIL)
}
/**
* Sets the texture filtering mode. See [enum TextureFilter] for options.
*/
public var textureFilter: TextureFilter
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTextureFilterPtr, LONG)
return VisualShaderNodeTextureParameter.TextureFilter.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, MethodBindings.setTextureFilterPtr, NIL)
}
/**
* Sets the texture repeating mode. See [enum TextureRepeat] for options.
*/
public var textureRepeat: TextureRepeat
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTextureRepeatPtr, LONG)
return VisualShaderNodeTextureParameter.TextureRepeat.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, MethodBindings.setTextureRepeatPtr, NIL)
}
/**
* Sets the texture source mode. Used for reading from the screen, depth, or normal_roughness texture. See [enum TextureSource] for options.
*/
public var textureSource: TextureSource
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTextureSourcePtr, LONG)
return VisualShaderNodeTextureParameter.TextureSource.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, MethodBindings.setTextureSourcePtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_VISUALSHADERNODETEXTUREPARAMETER, scriptIndex)
return true
}
public enum class TextureType(
id: Long,
) {
/**
* No hints are added to the uniform declaration.
*/
TYPE_DATA(0),
/**
* Adds `source_color` as hint to the uniform declaration for proper sRGB to linear conversion.
*/
TYPE_COLOR(1),
/**
* Adds `hint_normal` as hint to the uniform declaration, which internally converts the texture for proper usage as normal map.
*/
TYPE_NORMAL_MAP(2),
/**
* Adds `hint_anisotropy` as hint to the uniform declaration to use for a flowmap.
*/
TYPE_ANISOTROPY(3),
/**
* Represents the size of the [enum TextureType] enum.
*/
TYPE_MAX(4),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class ColorDefault(
id: Long,
) {
/**
* Defaults to fully opaque white color.
*/
COLOR_DEFAULT_WHITE(0),
/**
* Defaults to fully opaque black color.
*/
COLOR_DEFAULT_BLACK(1),
/**
* Defaults to fully transparent black color.
*/
COLOR_DEFAULT_TRANSPARENT(2),
/**
* Represents the size of the [enum ColorDefault] enum.
*/
COLOR_DEFAULT_MAX(3),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class TextureFilter(
id: Long,
) {
/**
* Sample the texture using the filter determined by the node this shader is attached to.
*/
FILTER_DEFAULT(0),
/**
* The texture filter reads from the nearest pixel only. The simplest and fastest method of filtering, but the texture will look pixelized.
*/
FILTER_NEAREST(1),
/**
* The texture filter blends between the nearest four pixels. Use this for most cases where you want to avoid a pixelated style.
*/
FILTER_LINEAR(2),
/**
* The texture filter reads from the nearest pixel in the nearest mipmap. This is the fastest way to read from textures with mipmaps.
*/
FILTER_NEAREST_MIPMAP(3),
/**
* The texture filter blends between the nearest 4 pixels and between the nearest 2 mipmaps. Use this for non-pixel art textures that may be viewed at a low scale (e.g. due to [godot.Camera2D] zoom), as mipmaps are important to smooth out pixels that are smaller than on-screen pixels.
*/
FILTER_LINEAR_MIPMAP(4),
/**
* The texture filter reads from the nearest pixel, but selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. The anisotropic filtering level can be changed by adjusting [godot.ProjectSettings.rendering/textures/defaultFilters/anisotropicFilteringLevel].
*
* **Note:** This texture filter is rarely useful in 2D projects. [FILTER_LINEAR_MIPMAP] is usually more appropriate.
*/
FILTER_NEAREST_MIPMAP_ANISOTROPIC(5),
/**
* The texture filter blends between the nearest 4 pixels and selects a mipmap based on the angle between the surface and the camera view. This reduces artifacts on surfaces that are almost in line with the camera. This is the slowest of the filtering options, but results in the highest quality texturing. The anisotropic filtering level can be changed by adjusting [godot.ProjectSettings.rendering/textures/defaultFilters/anisotropicFilteringLevel].
*
* **Note:** This texture filter is rarely useful in 2D projects. [FILTER_LINEAR_MIPMAP] is usually more appropriate.
*/
FILTER_LINEAR_MIPMAP_ANISOTROPIC(6),
/**
* Represents the size of the [enum TextureFilter] enum.
*/
FILTER_MAX(7),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class TextureRepeat(
id: Long,
) {
/**
* Sample the texture using the repeat mode determined by the node this shader is attached to.
*/
REPEAT_DEFAULT(0),
/**
* Texture will repeat normally.
*/
REPEAT_ENABLED(1),
/**
* Texture will not repeat.
*/
REPEAT_DISABLED(2),
/**
* Represents the size of the [enum TextureRepeat] enum.
*/
REPEAT_MAX(3),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class TextureSource(
id: Long,
) {
/**
* The texture source is not specified in the shader.
*/
SOURCE_NONE(0),
/**
* The texture source is the screen texture which captures all opaque objects drawn this frame.
*/
SOURCE_SCREEN(1),
/**
* The texture source is the depth texture from the depth prepass.
*/
SOURCE_DEPTH(2),
/**
* The texture source is the normal-roughness buffer from the depth prepass.
*/
SOURCE_NORMAL_ROUGHNESS(3),
/**
* Represents the size of the [enum TextureSource] enum.
*/
SOURCE_MAX(4),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public companion object
internal object MethodBindings {
public val setTextureTypePtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "set_texture_type")
public val getTextureTypePtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "get_texture_type")
public val setColorDefaultPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "set_color_default")
public val getColorDefaultPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "get_color_default")
public val setTextureFilterPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "set_texture_filter")
public val getTextureFilterPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "get_texture_filter")
public val setTextureRepeatPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "set_texture_repeat")
public val getTextureRepeatPtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "get_texture_repeat")
public val setTextureSourcePtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "set_texture_source")
public val getTextureSourcePtr: VoidPtr =
TypeManager.getMethodBindPtr("VisualShaderNodeTextureParameter", "get_texture_source")
}
}
| 63 | null | 39 | 571 | 39dc30230a30d2a6ab4ec3277eb3bc270995ab23 | 10,840 | godot-kotlin-jvm | MIT License |
dialects/sqlite/src/main/kotlin/factory/mikrate/dialects/sqlite/SqliteTypeSqlGen.kt | factory-org | 336,666,335 | false | null | package factory.mikrate.dialects.sqlite
import factory.mikrate.dialects.api.TypeSqlGen
import factory.mikrate.dialects.api.models.DialectDbType
public object SqliteTypeSqlGen : TypeSqlGen {
override fun supportsType(dbType: DialectDbType): Boolean = when (dbType) {
is DialectDbType.IntegerType -> supportedIntegerSizes.contains(dbType.size)
DialectDbType.BooleanType,
DialectDbType.ByteType,
DialectDbType.TextType,
DialectDbType.UuidType,
is DialectDbType.VarcharType -> true
is DialectDbType.EnumType,
is DialectDbType.Other -> false
}
internal fun mapType(dbType: DialectDbType): String = when (dbType) {
DialectDbType.BooleanType -> "NUMERIC"
DialectDbType.ByteType,
is DialectDbType.IntegerType -> "INTEGER"
DialectDbType.TextType,
is DialectDbType.VarcharType -> "Text"
DialectDbType.UuidType -> "BLOB"
is DialectDbType.EnumType,
is DialectDbType.Other -> throw IllegalArgumentException("Other type is not supported")
}
private val supportedIntegerSizes = setOf<Short>(1, 2, 3, 4, 6, 8)
}
| 0 | Kotlin | 0 | 0 | 31095027750ef1e074e5b64e1662d4acbf7c36f7 | 1,148 | mikrate | Apache License 2.0 |
VCL/src/main/java/io/velocitycareerlabs/impl/domain/repositories/ResolveKidRepository.kt | velocitycareerlabs | 525,006,413 | false | null | /**
* Created by <NAME> on 4/20/21.
*
* Copyright 2022 Velocity Career Labs inc.
* SPDX-License-Identifier: Apache-2.0
*/
package io.velocitycareerlabs.impl.domain.repositories
import io.velocitycareerlabs.api.entities.VCLPublicJwk
import io.velocitycareerlabs.api.entities.VCLResult
internal interface ResolveKidRepository {
fun getPublicKey(kid: String, completionBlock: (VCLResult<VCLPublicJwk>) -> Unit)
} | 0 | null | 0 | 2 | 160e938b2a3a676800e65aabec95c7badffbb4a6 | 421 | WalletAndroid | Apache License 2.0 |
first_flutter_app/android/app/src/main/kotlin/com/example/first_flutter_app/MainActivity.kt | cndoit18 | 368,693,669 | false | {"Java": 55107, "Dart": 11609, "Swift": 1212, "Kotlin": 397, "Objective-C": 114} | package com.example.first_flutter_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | null | 1 | 1 | 840d454a11a395bee4f983f3430f528c90ca37fb | 134 | learning-flutter | MIT License |
threejs-wrapper/src/main/kotlin/info/laht/threekt/materials/Material.kt | markaren | 111,575,995 | false | null | /*
* The MIT License
*
* Copyright 2017-2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
@file:JsModule("three")
@file:JsNonModule
package three.materials
@JsName("Material")
open external class Material {
/**
* Unique number for this material instance.
*/
val id: Int
var uuid: String
/**
* Optional name of the object (doesn't need to be unique). Default is an empty string.
*/
var name: String
var type: String
/**
* Whether the material is affected by fog. Default is true.
*/
var fog: Boolean
var lights: Boolean
var blending: Int
var side: Int
var flatShading: Boolean
var vertexColors: Int
/**
* Double in the range of 0.0 - 1.0 indicating how transparent the material is. A value of 0.0 indicates fully transparent, 1.0 is fully opaque.
If the material's # .transparent property is not set to true, the material will remain fully opaque and this value will only affect its color.
Default is 1.0.
*/
var opacity: Double
var transparent: Boolean
var blendSrc: Int
/**
* Blending destination. Default is OneMinusSrcAlphaFactor. See the destination factors constants for all possible values.
The material's # .blending must be set to CustomBlending for this to have any effect.
*/
var blendDst: Int
/**
* Blending equation to use when applying blending. Default is AddEquation. See the blending equation constants for all possible values.
The material's # .blending must be set to CustomBlending for this to have any effect.
*/
var blendEquation: Int
var blendSrcAlpha: Int
/**
* The tranparency of the .blendDst. Default is null.
*/
var blendDstAlpha: Int?
var blendEquationAlpha: Int
var depthFunc: Int
var depthTest: Boolean
var depthWrite: Boolean
var colorWrite: Boolean
var precision: String?
/**
* Sets the polygon offset factor. Default is 0.
*/
var polygonOffset: Boolean
var polygonOffsetFactor: Number
/**
* Sets the polygon offset units. Default is 0.
*/
var polygonOffsetUnits: Number
var dithering: Boolean
/**
* Sets the alpha value to be used when running an alpha test.
* The material will not be renderered if the opacity is lower than this value. Default is 0.
*/
var alphaTest: Double
var premultipliedAlpha: Boolean
var overdraw: Double
var visible: Boolean
var userData: dynamic
/**
* Specifies that the material needs to be updated at the WebGL level. Set it to true if you made changes that need to be reflected in WebGL.
This property is automatically set to true when instancing a new material.
*/
var needsUpdate: Boolean
fun toJSON(meta: String = definedExternally): String
open fun clone(): Material
fun copy(material: Material): Material
fun dispose()
} | 15 | Kotlin | 6 | 53 | c13a96add591a7e0e52911c4d8f59dddfc6165ef | 3,985 | three-kt-wrapper | MIT License |
app/src/main/java/com/adg/superherobucket/data/db/model/DBMappers.kt | varo610 | 183,915,778 | false | null | package com.adg.superherobucket.data.db.model
import com.adg.superherobucket.data.db.model.DBSuperHero
import com.adg.superherobucket.data.network.model.mapToDomain
import com.adg.superherobucket.domain.model.DomainAppearance
import com.adg.superherobucket.domain.model.DomainBiography
import com.adg.superherobucket.domain.model.DomainImage
import com.adg.superherobucket.domain.model.DomainSuperHero
import com.adg.superherobucket.presentation.model.Image
fun DBSuperHero.mapToDomain(): DomainSuperHero {
return DomainSuperHero(
image = DomainImage(url = this.url),
appearance = DomainAppearance(
eyeColor = this.eyeColor,
gender = this.gender,
race = this.race,
weight = this.weight,
height = this.height,
hairColor = this.hairColor
),
biography = DomainBiography(
placeOfBirth = this.placeOfBirth,
firstAppearance = this.firstAppearance,
publisher = this.publisher,
alignment = this.alignment,
fullName = this.fullName,
alterEgos = this.alterEgos
),
id = this.id,
name = this.name
)
} | 0 | Kotlin | 0 | 1 | 0f70354de21968de38517dce498049577ed5ddfc | 1,200 | SuperHeroBucket | Apache License 2.0 |
src/main/kotlin/me/devoxin/flight/api/events/ParsingErrorEvent.kt | mixtape-oss | 331,475,215 | true | {"Kotlin": 120308} | package me.devoxin.flight.api.events
import me.devoxin.flight.api.command.Context
import me.devoxin.flight.internal.entities.ICommand
/**
* Emitted when the argument parser encounters an error.
*/
data class ParsingErrorEvent(
val ctx: Context,
val command: ICommand,
val error: Throwable
) : Event
| 0 | Kotlin | 0 | 3 | 70c2ba879fe1d67959d9c125479cced9dea38ed2 | 315 | flight | Apache License 2.0 |
app/src/main/java/aiu/myapplication/ProductDetails.kt | AzamatIbraimov | 305,125,284 | false | null | package aiu.myapplication
import aiu.myapplication.model.Basket
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_basket.*
import java.lang.reflect.Type
class ProductDetails : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_product_details)
val i = intent
val name = i.getStringExtra("name")
val image = i.getIntExtra("image", R.drawable.b1)
val price = i.getStringExtra("price")
val desc = i.getStringExtra("desc")
val quantity = i.getStringExtra("quantity")
val unit = i.getStringExtra("unit")
val proName = findViewById<TextView>(R.id.productName)
val proDesc = findViewById<TextView>(R.id.prodDesc)
val proPrice = findViewById<TextView>(R.id.prodPrice)
val img = findViewById<ImageView>(R.id.big_image)
val back = findViewById<ImageView>(R.id.back2)
val addToBasket = findViewById<ImageView>(R.id.imageView7)
val cart = findViewById<ImageView>(R.id.cart)
val proQuantity = findViewById<TextView>(R.id.qty)
val proUnit = findViewById<TextView>(R.id.unit)
val button = findViewById<TextView>(R.id.button)
proName.text = name
proPrice.text = price
proDesc.text = desc
proQuantity.text = quantity
proUnit.text = unit
img.setImageResource(image)
back.setOnClickListener {
val i = Intent(this@ProductDetails, MainActivity::class.java)
startActivity(i)
finish()
}
cart.setOnClickListener{
val i = Intent(this@ProductDetails, BasketActivity::class.java)
startActivity(i)
}
addToBasket.setOnClickListener {
val basket = price?.let { it1 -> Basket(0, name.toString(), it1) }
var listb : ArrayList<Basket> = ArrayList<Basket>()
basket?.let { it1 -> listb.add(it1) }
saveLessons(listb)
Toast.makeText(this, "Продукт добавлен в корзину", Toast.LENGTH_SHORT).show()
}
button.setOnClickListener {
Toast.makeText(this, "Заказ успешно отправлен", Toast.LENGTH_SHORT).show()
}
}
private fun saveLessons(list: ArrayList<Basket>){
val gson = Gson()
val myPrefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).edit()
myPrefs.putString("basketObj", gson.toJson(list))
myPrefs.apply()
}
} | 0 | Kotlin | 0 | 1 | 7d6f065e9d2d81d7c61be26878ef28d3357af679 | 2,849 | BimarApp | MIT License |
feature-staking-impl/src/main/java/com/edgeverse/wallet/feature_staking_impl/domain/validations/reedeem/RedeemValidationPayload.kt | finn-exchange | 512,140,809 | false | {"Kotlin": 2956205, "Java": 14536, "JavaScript": 399} | package com.edgeverse.wallet.feature_staking_impl.domain.validations.reedeem
import com.edgeverse.wallet.feature_wallet_api.domain.model.Asset
import java.math.BigDecimal
class RedeemValidationPayload(
val fee: BigDecimal,
val asset: Asset
)
| 0 | Kotlin | 1 | 0 | 03229c4188cb56b0fb0340e60d60184c7afa2c75 | 252 | edgeverse-wallet | Apache License 2.0 |
src/test/kotlin/shirates/spec/uitest/android/SpecReport_platformBranch_Test.kt | ldi-github | 538,873,481 | false | {"Kotlin": 3671492, "JavaScript": 12703, "CSS": 5036} | package shirates.spec.uitest
import org.apache.poi.xssf.usermodel.XSSFCell
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import shirates.core.configuration.Testrun
import shirates.core.driver.branchextension.*
import shirates.core.driver.commandextension.describe
import shirates.core.driver.commandextension.launchApp
import shirates.core.driver.commandextension.screenIs
import shirates.core.logging.TestLog
import shirates.core.testcode.NoLoadRun
import shirates.core.testcode.SheetName
import shirates.core.testcode.UITest
import shirates.core.utility.format
import shirates.spec.utilily.ExcelUtility
import shirates.spec.utilily.cells
import shirates.spec.utilily.text
import shirates.spec.utilily.worksheets
import java.nio.file.Files
import java.util.*
@SheetName("SheetName1")
@Testrun("unitTestConfig/android/androidSettings/testrun.properties")
class SpecReport_platformBranch_Test : UITest() {
@NoLoadRun
@Test
@Order(10)
@DisplayName("s10@NoLoadRun")
fun s10() {
scenarioCore()
}
@Test
@Order(11)
@DisplayName("s11")
fun s11() {
scenarioCore()
}
private fun scenarioCore() {
scenario {
case(1) {
condition {
it.launchApp("Settings")
.screenIs("[Android Settings Top Screen]")
branches()
}.action {
branches()
}.expectation {
branches()
}
}
}
}
private fun branches() {
android {
describe("in android")
emulator {
describe("in emulator")
}
}
ios {
describe("in ios")
simulator {
describe("in simulator")
}
}
virtualDevice {
describe("in virtualDevice")
arm64 {
describe("in arm64")
}
intel {
describe("in intel")
}
}
realDevice {
describe("in realDevice")
osaifuKeitai {
describe("in osaifuKeitai")
}.osaifuKeitaiNot {
describe("in osaifuKeitaiNot")
}
}
stub {
describe("in stub")
}.stubNot {
describe("in stubNot")
}
}
override fun finally() {
var filePath =
TestLog.directoryForLog.resolve("SpecReport_platformBranch_Test/SpecReport_platformBranch_Test.xlsx")
if (Files.exists(filePath).not()) {
filePath =
TestLog.directoryForLog.resolve("SpecReport_platformBranch_Test/[email protected]")
}
val ws = ExcelUtility.getWorkbook(filePath = filePath).worksheets("SheetName1")
fun XSSFCell.textIs(expected: String) {
assertThat(this.text).isEqualTo(expected)
}
/**
* Header
*/
val deviceModel = if (ws.cells("D4").text.isNotBlank()) "sdk_gphone64_arm64" else ""
val platformVersion = if (deviceModel.isNotBlank()) "12" else ""
ws.assertHeader(
testConfigName = "Settings",
sheetName = "SheetName1",
testClassName = "SpecReport_platformBranch_Test",
profileName = "Pixel 3a API 31(Android 12)",
deviceModel = deviceModel,
platformVersion = platformVersion,
notImpl = 1,
total = 1
)
/**
* Row Header
*/
ws.assertRowHeader()
/**
* Rows
*/
assertRowsOnNoLoadRunningMode(ws)
assertRowsOnLoadRunningMode(ws)
}
private fun assertRowsOnNoLoadRunningMode(ws: XSSFSheet) {
with(ws) {
assertRow(
rowNum = 10,
id = 1,
step = "s10",
condition = "s10@NoLoadRun",
)
assertRow(
rowNum = 11,
id = 2,
step = "1",
condition = """
- Launch app <Settings>
- [Android Settings Top Screen] is displayed
android {
- in android
emulator {
- in emulator
}
}
ios {
- in ios
simulator {
- in simulator
}
}
virtualDevice {
- in virtualDevice
arm64 {
- in arm64
}
intel {
- in intel
}
}
realDevice {
- in realDevice
osaifuKeitai {
- in osaifuKeitai
}
osaifuKeitaiNot {
- in osaifuKeitaiNot
}
}
stub {
- in stub
}
stubNot {
- in stubNot
}
""".trimIndent(),
action = """
android {
- in android
emulator {
- in emulator
}
}
ios {
- in ios
simulator {
- in simulator
}
}
virtualDevice {
- in virtualDevice
arm64 {
- in arm64
}
intel {
- in intel
}
}
realDevice {
- in realDevice
osaifuKeitai {
- in osaifuKeitai
}
osaifuKeitaiNot {
- in osaifuKeitaiNot
}
}
stub {
- in stub
}
stubNot {
- in stubNot
}
""".trimIndent(),
expectation = "- in android",
os = "Android",
)
assertRow(
rowNum = 12,
id = 3,
expectation = "- in emulator",
os = "Android",
special = "emulator"
)
assertRow(
rowNum = 13,
id = 4,
expectation = "- in ios",
os = "iOS",
)
assertRow(
rowNum = 14,
id = 5,
expectation = "- in simulator",
os = "iOS",
special = "simulator"
)
assertRow(
rowNum = 15,
id = 6,
expectation = "- in virtualDevice",
special = "virtualDevice"
)
assertRow(
rowNum = 16,
id = 7,
expectation = "- in arm64",
special = "virtualDevice/arm64"
)
assertRow(
rowNum = 17,
id = 8,
expectation = "- in intel",
special = "virtualDevice/intel"
)
assertRow(
rowNum = 18,
id = 9,
expectation = "- in realDevice",
special = "realDevice"
)
assertRow(
rowNum = 19,
id = 10,
expectation = "- in osaifuKeitai",
special = "realDevice/osaifuKeitai"
)
assertRow(
rowNum = 20,
id = 11,
expectation = "- in osaifuKeitaiNot",
special = "realDevice/osaifuKeitaiNot"
)
assertRow(
rowNum = 21,
id = 12,
expectation = "- in stub",
special = "stub"
)
assertRow(
rowNum = 22,
id = 13,
expectation = "- in stubNot",
special = "stubNot"
)
}
}
private fun assertRowsOnLoadRunningMode(ws: XSSFSheet) {
with(ws) {
assertRow(
rowNum = 23,
id = 14,
step = "s11",
condition = "s11",
)
assertRow(
rowNum = 24,
id = 15,
step = "1",
condition = """
- Launch app <Settings>
- [Android Settings Top Screen] is displayed
android {
- in android
emulator {
- in emulator
}
}
virtualDevice {
- in virtualDevice
arm64 {
- in arm64
}
}
stubNot {
- in stubNot
}
""".trimIndent(),
action = """
android {
- in android
emulator {
- in emulator
}
}
virtualDevice {
- in virtualDevice
arm64 {
- in arm64
}
}
stubNot {
- in stubNot
}
""".trimIndent(),
expectation = "- in android",
os = "Android",
)
assertRow(
rowNum = 25,
id = 16,
expectation = "- in emulator",
os = "Android",
special = "emulator"
)
assertRow(
rowNum = 26,
id = 17,
expectation = "- in virtualDevice",
special = "virtualDevice"
)
assertRow(
rowNum = 27,
id = 18,
expectation = "- in arm64",
special = "virtualDevice/arm64"
)
val date = Date().format("yyyy/MM/dd")
assertRow(
rowNum = 28,
id = 19,
expectation = "- in stubNot",
special = "stubNot",
auto = "A",
result = "NOTIMPL",
testDate = date,
tester = "auto"
)
}
}
} | 0 | Kotlin | 0 | 8 | f5ff94f3a36495b71e15e78eafec46ce10623bf0 | 9,219 | shirates-core | Apache License 2.0 |
chatkit-core/src/main/kotlin/com/pusher/chatkit/util/FutureValue.kt | pusher | 106,020,436 | false | null | package com.pusher.chatkit.util
import com.pusher.platform.network.Futures
import com.pusher.platform.network.Wait
import com.pusher.platform.network.wait
import java.util.concurrent.BlockingQueue
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.TimeUnit
import kotlin.reflect.KProperty
class FutureValue<A>(private val wait: Wait = Wait.For(10, TimeUnit.SECONDS)) {
private val queue: BlockingQueue<Value<A>> = SynchronousQueue(true)
private val future = Futures.schedule { queue.take().value }
operator fun getValue(thisRef: Nothing?, property: KProperty<*>): A = get()
operator fun setValue(thisRef: Nothing?, property: KProperty<*>, value: A) = set(value)
fun get(): A = future.wait(wait)
fun set(value: A) = queue.put(Value(value))
}
/**
* [SynchronousQueue] doesn't take nullable objects so have to wrap it on this.
*/
private data class Value<A>(val value: A)
| 12 | null | 14 | 54 | 4bc7d96059a8d6ec66032c84819f77149b6c3296 | 921 | chatkit-android | MIT License |
adapters/admob/src/main/java/io/bidon/mediation/adapter/admob/AdMobNetworkAdUnit.kt | bidon-io | 603,002,504 | false | null | package io.bidon.mediation.adapter.admob
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import io.bidon.mediation.sdk.network.NetworkAdUnit
class AdMobNetworkAdUnit : NetworkAdUnit {
companion object {
const val PARAM_LINE_ITEMS: String = "line_items"
const val PARAM_AD_REQUEST: String = "ad_request"
const val PARAM_AD_SIZE: String = "ad_size"
val DEFAULT_AD_SIZE: AdSize = AdSize.BANNER
}
constructor(lineItems: Collection<AdMobLineItem>) : this() {
params[PARAM_LINE_ITEMS] = lineItems
}
constructor(params: MutableMap<String, Any> = mutableMapOf()) : super(AdMobNetworkAdapter.KEY, params)
fun setAdRequest(adRequest: AdRequest): AdMobNetworkAdUnit {
params[PARAM_AD_REQUEST] = adRequest
return this
}
fun setAdSize(adSize: AdSize): AdMobNetworkAdUnit {
params[PARAM_AD_SIZE] = adSize
return this
}
internal fun getLineItems(): Collection<AdMobLineItem>? {
return if (params.containsKey(PARAM_LINE_ITEMS)) {
(params[PARAM_LINE_ITEMS] as? Collection<*>)?.filterIsInstance(AdMobLineItem::class.java)
} else {
null
}
}
internal fun obtainAdRequest(): AdRequest = params[PARAM_AD_REQUEST] as? AdRequest ?: AdRequest.Builder().build()
internal fun obtainAdSize(): AdSize = params[PARAM_AD_SIZE] as? AdSize ?: DEFAULT_AD_SIZE
} | 0 | Kotlin | 0 | 0 | ab4412d5ad7cc80758ae22f69fc602d4a6db739c | 1,448 | postbid-demo-android | Apache License 2.0 |
preview-designer/testSrc/com/android/tools/idea/preview/actions/IssueNotificationActionFakes.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.preview.actions
import com.android.tools.adtui.compose.InformationPopup
import com.android.tools.adtui.compose.IssueNotificationAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.ProjectRule
import com.intellij.util.Alarm
import java.awt.event.InputEvent
import java.awt.event.MouseEvent
import javax.swing.JComponent
fun ProjectRule.createFakeActionEvent(issueNotificationAction: IssueNotificationAction): AnActionEvent {
val dataContext = object : DataContext {
var files: Array<VirtualFile> = arrayOf()
override fun getData(dataId: String): Any {
return project
}
override fun <T> getData(key: DataKey<T>): T? {
@Suppress("UNCHECKED_CAST")
return when (key) {
CommonDataKeys.PROJECT -> project as T
else -> null
}
}
}
val mouseEvent = createFakeMouseEvent()
AnActionEvent.createFromInputEvent(
mouseEvent,
ActionPlaces.EDITOR_POPUP,
PresentationFactory().getPresentation(issueNotificationAction),
ActionToolbar.getDataContextFor(mouseEvent.component),
false, true
)
return AnActionEvent.createFromInputEvent(mouseEvent, "", Presentation(), dataContext)
}
fun createFakeMouseEvent(): MouseEvent = MouseEvent(
object : JComponent() {},
0,
0,
0,
0,
0,
1,
true,
MouseEvent.BUTTON1
)
fun createFakeAlarm(
onAddRequest: (Int) -> Unit = { },
onCancelAllRequest: () -> Unit = { }
) = object : Alarm() {
override fun cancelAllRequests(): Int {
onCancelAllRequest()
return super.cancelAllRequests()
}
override fun addRequest(request: Runnable, delayMillis: Int) {
request.run()
onAddRequest(delayMillis)
}
}
fun createFakePopup(
onHidePopup: () -> Unit = {},
onShowPopup: () -> Unit = {},
onMouseEnterCallback: () -> Unit = {},
isPopupVisible: Boolean = false
): InformationPopup = object : InformationPopup {
override val popupComponent: JComponent = object : JComponent() {}
override var onMouseEnteredCallback: () -> Unit = onMouseEnterCallback
override fun hidePopup() = onHidePopup()
override fun showPopup(disposableParent: Disposable, event: InputEvent) = onShowPopup()
override fun isVisible(): Boolean = isPopupVisible
}
| 5 | Kotlin | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 3,354 | android | Apache License 2.0 |
app/src/main/java/com/mollie/checkout/data/model/SelectCheckoutLayoutStyle.kt | mollie | 431,494,734 | false | {"Kotlin": 74081} | package com.mollie.checkout.data.model
enum class SelectCheckoutLayoutStyle(
val index: Int,
) {
LIST(0),
GRID(1);
companion object {
fun from(index: Int?): SelectCheckoutLayoutStyle? {
return values().firstOrNull { it.index == index }
}
}
} | 1 | Kotlin | 2 | 2 | fa2ea1801b6ffc11246fa55fc779bc44427b2bba | 291 | demo-checkout-android | MIT License |
src/year2023/day05/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 136821} | package year2023.day05
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.intersect
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 5, transform = ::parse)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(35),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(46),
algorithm = ::part2,
),
)
}
private fun parse(input: List<String>) = Input(
seeds = input.first()
.drop(7)
.split(' ')
.map { it.toLong() },
mappings = input.drop(2).fold(mutableListOf(mutableListOf<Pair<LongRange, Long>>())) { accumulator, line ->
if (line.isEmpty()) accumulator.add(mutableListOf())
else if (!line.first().isLetter()) line.splitToSequence(' ')
.map { it.toLong() }
.toList()
.let { (end, start, length) ->
accumulator.last().add(
Pair(
(start until (start + length)),
end - start,
)
)
}
accumulator
}
)
private fun part1(input: Input): Long {
return input.seeds.asSequence()
.map { seed ->
input.mappings.fold(seed) { location, mapping ->
val offset = mapping.firstOrNull { location in it.first }?.second ?: 0L
location + offset
}
}
.min()
}
private fun part2(input: Input): Long {
val seeds = input.seeds.chunked(2) { (start, length) -> start until (start + length) }
return input.mappings
.fold(seeds) { seedsPositions, mapping ->
seedsPositions.flatMap { seedRange ->
val newSeedRanges = mapping.mapNotNull { (range, offset) ->
(range intersect seedRange)?.to(offset)
}
val unmovedSeeds = newSeedRanges.fold(listOf(seedRange)) { unusedRanges, (usedRange) ->
unusedRanges.flatMap { unusedRange ->
val intersect = unusedRange intersect usedRange
if (intersect == null) listOf(unusedRange) else {
val startRange = unusedRange.first until usedRange.first
val endRange = (usedRange.last + 1)..unusedRange.last
listOfNotNull(startRange.takeUnless { it.isEmpty() }, endRange.takeUnless { it.isEmpty() })
}
}
}
newSeedRanges.mapTo(unmovedSeeds.toMutableList()) {
(it.first.first + it.second)..(it.first.last + it.second)
}
}
}
.minOf { it.first }
}
private data class Input(
val seeds: List<Long>,
val mappings: List<List<Pair<LongRange, Long>>>,
)
| 0 | Kotlin | 0 | 0 | 042213bdfa37dc730f9c1b37b5b8a370f20657ff | 3,046 | Advent-of-Code | Apache License 2.0 |
app/src/main/java/com/example/andriiginting/news/view/BaseActivity.kt | andriiginting | 142,031,035 | false | null | package com.example.andriiginting.news.view
import android.annotation.SuppressLint
import android.support.design.widget.BaseTransientBottomBar
import android.support.design.widget.BottomSheetDialog
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Toast
import com.example.andriiginting.news.R
import com.example.andriiginting.news.utils.ConnectivityCheck.Companion.connectivityCheck
import com.example.andriiginting.news.utils.ConnectivityListener
@SuppressLint("Registered")
open class BaseActivity : AppCompatActivity(),
ConnectivityListener,
BaseView {
override fun onNetworkChanged(isConnected: Boolean) {
if (isConnected) {
Log.d("koneksi", isConnected.toString())
showToast(resources.getString(R.string.check_your_internet_connection))
} else {
}
}
@SuppressLint("WrongConstant")
override fun showToast(message: String) {
Toast.makeText(applicationContext,message,Toast.LENGTH_LONG).show()
}
override fun onResume() {
super.onResume()
connectivityCheck = this
}
} | 0 | Kotlin | 0 | 0 | 90e3606b5ee80c39de7207e53d4984170c77206f | 1,183 | news-app | Apache License 2.0 |
core/src/ru/serdjuk/zxsna/app/utils/RectInt.kt | vito-Z80 | 302,118,445 | false | {"Gradle": 4, "INI": 2, "Shell": 1, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "JAR Manifest": 1, "Java": 2, "Kotlin": 70, "Assembly": 1, "XML": 1} | package ru.serdjuk.zxsna.app.utils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
class RectInt(var x: Int = 0, var y: Int = 0, var width: Int = 0, var height: Int = 0) {
fun overlaps(r: Rectangle): Boolean {
return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y
}
fun contains(x: Float, y: Float): Boolean {
return this.x <= x && this.x + width >= x && this.y <= y && this.y + height >= y
}
operator fun contains(point: Vector2): Boolean {
return contains(point.x, point.y)
}
fun set(x: Int, y: Int, width: Int, height: Int) {
this.x = x
this.y = y
this.width = width
this.height = height
}
fun set(rect: RectInt) {
this.x = rect.x
this.y = rect.y
this.width = rect.width
this.height = rect.height
}
/** Creates rectangles of the specified size from the user's selection area.
* Нарезка квадратов размером 8 или 16
* @param selection user selection area
* @param size the size of the cut rectangles, may be only 16 or 8
* @return возвращает нарезанные ректанглы
*/
suspend fun slicingRectangles(size: Int): Array<RectInt> {
val width = this.width / size
val height = this.height / size
val rectangles = Array<RectInt>(width * height) { RectInt() }
// создание ректанглов слеваСверху
var count = 0
while (this.height > 0) {
this.height -= size
var x = 0
while (x < this.width) {
rectangles[count++].set(this.x + x, this.y + this.height, size, size)
x += size
}
}
return rectangles
// FIXME другой вариант:
// FIXME выделение должно быть кратно 8/16 либо отмена действия
// FIXME причем если выделение кратно 8 то работать можно только с тайлами
// FIXME если выделение кратно 16 то работать можно как со спрайтами так и с тайлами
// FIXME то есть меню ПКМ должно подстроиться под кратность выделения, при не кратности оповестить пользователя
}
override fun toString(): String {
return "[$x,$y,$width,$height]"
}
} | 1 | null | 1 | 1 | 8e19849cb1d6f71fc6a155940a2c3180db98e89d | 2,266 | ZXSNAv2 | Apache License 2.0 |
project-system-gradle/src/com/android/tools/idea/gradle/project/sync/hyperlink/DoNotShowJdkHomeWarningAgainHyperlink.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.project.sync.hyperlink
import com.android.tools.idea.gradle.project.sync.GradleSyncState.Companion.JDK_LOCATION_WARNING_NOTIFICATION_GROUP
import com.android.tools.idea.gradle.project.sync.issues.SyncIssueNotificationHyperlink
import com.android.tools.idea.project.hyperlink.NotificationHyperlink
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsConfiguration
import com.intellij.openapi.project.Project
/**
* A [NotificationHyperlink] that stops showing a warning when the JDK used by Studio is not the same as Java Home.
*/
class DoNotShowJdkHomeWarningAgainHyperlink : SyncIssueNotificationHyperlink(
"doNotShowJdkHomeWarning", "Do not show this warning again", null) {
public override fun execute(project: Project) {
val msg = "Warnings about JDK location not being JAVA_HOME were disabled.\n" +
"They can be enabled again in the Settings dialog."
JDK_LOCATION_WARNING_NOTIFICATION_GROUP.createNotification(msg, NotificationType.INFORMATION).notify(project)
NotificationsConfiguration.getNotificationsConfiguration().changeSettings(JDK_LOCATION_WARNING_NOTIFICATION_GROUP.displayId,
JDK_LOCATION_WARNING_NOTIFICATION_GROUP.displayType,
false /* do not log */, false /* not read aloud */)
}
}
| 5 | null | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 2,094 | android | Apache License 2.0 |
feature/dashboard/src/main/kotlin/com/stonecap/wardrobe/feature/dashboard/navigation/DashboardNavigation.kt | Stonecap | 591,597,268 | false | null | package com.stonecap.wardrobe.feature.dashboard.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import com.stonecap.wardrobe.feature.dashboard.DashboardRoute
import com.stonecap.wardrobe.feature.dashboard.DashboardScreen
const val dashboardNavigationRoute = "dashboard_route"
fun NavController.navigateToDashboard(navOptions: NavOptions? = null) {
this.navigate(dashboardNavigationRoute, navOptions)
}
fun NavGraphBuilder.dashboardScreen() {
composable(route = dashboardNavigationRoute) {
DashboardRoute()
}
}
| 0 | Kotlin | 0 | 0 | 8c8a527502ec14ddb359eaf06c0225a6bcd1274e | 666 | wardrobe-app | MIT License |
foryouandme/src/main/java/com/foryouandme/ui/dailysurveytime/DailySurveyTimeFragment.kt | 4YouandMeData | 610,425,317 | false | null | package com.foryouandme.ui.dailysurveytime
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.viewModels
import com.foryouandme.core.arch.android.BaseFragment
import com.foryouandme.databinding.DailySurveyTimeBinding
import com.foryouandme.ui.dailysurveytime.compose.DailySurveyTimePage
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class DailySurveyTimeFragment : BaseFragment() {
private val viewModel: DailySurveyTimeViewModel by viewModels()
private val binding: DailySurveyTimeBinding?
get() = view?.let { DailySurveyTimeBinding.bind(it) }
@ExperimentalAnimationApi
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View =
ComposeView(requireContext()).apply {
setContent {
DailySurveyTimePage(
viewModel = viewModel,
onBack = { navigator.back(rootNavController()) }
)
}
}
/*override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.stateUpdate
.unwrapEvent(name)
.onEach {
when (it) {
DailySurveyTimeStateUpdate.GetUserSettings ->
applyTime()
DailySurveyTimeStateUpdate.SaveUserSettings ->
navigator.back(rootNavController())
}
}
.observeIn(this)
viewModel.loading
.unwrapEvent(name)
.onEach {
when (it.task) {
DailySurveyTimeLoading.GetUserSettings ->
binding?.loading?.setVisibility(it.active, false)
DailySurveyTimeLoading.SaveUserSettings ->
binding?.loading?.setVisibility(it.active)
}
}
.observeIn(this)
viewModel.error
.unwrapEvent(name)
.onEach {
when (it.cause) {
DailySurveyTimeError.GetUserSettings ->
binding?.error?.setError(it.error, configuration) {
viewModel.execute(DailySurveyTimeStateEvent.GetUserSettings)
}
DailySurveyTimeError.SaveUserSettings ->
binding?.error?.setError(it.error, configuration)
}
}
.observeIn(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
applyConfiguration()
if (viewModel.state.userSettings == null)
viewModel.execute(DailySurveyTimeStateEvent.GetUserSettings)
else
applyTime()
}
override fun onConfigurationChange() {
super.onConfigurationChange()
applyConfiguration()
}
private fun applyConfiguration() {
val viewBinding = binding
val config = configuration
if (viewBinding != null && config != null) {
setStatusBar(config.theme.primaryColorStart.color())
viewBinding.root.setBackgroundColor(config.theme.secondaryColor.color())
viewBinding.toolbar.setBackgroundColor(config.theme.primaryColorStart.color())
viewBinding.toolbar.showBackButton(imageConfiguration) {
navigator.back(rootNavController())
}
viewBinding.title.setTextColor(config.theme.secondaryColor.color())
viewBinding.title.text = config.text.profile.fifthItem
viewBinding.description.setTextColor(config.theme.primaryTextColor.color())
viewBinding.description.text = config.text.profile.dailySurveyTimeDescription
viewBinding.timePicker.setIs24HourView(false)
// TODO: move to configuration
viewBinding.saveButton.text = "Save"
viewBinding.saveButton.setTextColor(config.theme.secondaryTextColor.color())
viewBinding.saveButton.background = button(config.theme.primaryColorStart.color())
viewBinding.saveButton.setOnClickListener {
val timePicker = binding?.timePicker
if (timePicker != null) {
val localTime = LocalTime.of(timePicker.hour, timePicker.minute)
viewModel.execute(DailySurveyTimeStateEvent.SaveUserSettings(localTime))
}
}
}
}
private fun applyTime() {
val time = viewModel.state.userSettings?.dailySurveyTime
val viewBinding = binding
if (viewBinding != null && time != null) {
viewBinding.timePicker.hour = time.hour
viewBinding.timePicker.minute = time.minute
}
}*/
} | 0 | Kotlin | 0 | 0 | bc82972689db5052344365ac07c8f6711f5ad7fa | 5,076 | 4YouandMeAndroid | MIT License |
android_app/src/main/java/com/aglushkov/wordteacher/android_app/helper/VKAuthControllerImpl.kt | soniccat | 302,971,014 | false | {"Kotlin": 1114266, "Go": 170819, "Swift": 38695, "TypeScript": 29600, "Dockerfile": 5502, "JavaScript": 3131, "Makefile": 3016, "Shell": 2338, "Ruby": 1740, "HTML": 897, "Java": 872, "SCSS": 544, "C": 59} | package com.aglushkov.wordteacher.android_app.helper
import androidx.activity.ComponentActivity
import com.aglushkov.wordteacher.shared.general.auth.VKAuthController
import com.aglushkov.wordteacher.shared.general.auth.VKAuthData
import com.aglushkov.wordteacher.shared.general.auth.NetworkAuthData
import com.aglushkov.wordteacher.shared.general.resource.Resource
import com.aglushkov.wordteacher.shared.general.resource.isLoadedOrError
import com.aglushkov.wordteacher.shared.general.resource.isLoading
import com.vk.id.AccessToken
import com.vk.id.VKID
import com.vk.id.VKIDAuthFail
import com.vk.id.auth.VKIDAuthCallback
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.update
import java.lang.RuntimeException
class VKAuthControllerImpl : VKAuthController {
private var vkid: VKID? = null
private var vkAuthDataState: MutableStateFlow<Resource<NetworkAuthData>> =
MutableStateFlow(Resource.Uninitialized())
override var authDataFlow: StateFlow<Resource<NetworkAuthData>> = vkAuthDataState
private val vkAuthCallback = object : VKIDAuthCallback {
override fun onAuth(accessToken: AccessToken) {
vkAuthDataState.update {
Resource.Loaded(
VKAuthData(
token = accessToken.token,
userID = accessToken.userID,
expireTime = accessToken.expireTime,
firstName = accessToken.userData.firstName,
lastName = accessToken.userData.lastName,
)
)
}
}
override fun onFail(fail: VKIDAuthFail) {
when (fail) {
is VKIDAuthFail.Canceled -> {
vkAuthDataState.update { Resource.Uninitialized() }
}
else -> {
vkAuthDataState.update { Resource.Error(RuntimeException(fail.description)) }
}
}
}
}
fun bind(activity: ComponentActivity) {
vkid = VKID.instance
}
override suspend fun signIn(): Resource<NetworkAuthData> {
launchSignIn()
vkAuthDataState.takeWhile { !it.isLoadedOrError() }.collect()
return vkAuthDataState.value
}
private suspend fun launchSignIn() {
if (vkAuthDataState.value.isLoading()) {
return
}
vkAuthDataState.value = Resource.Loading()
vkid!!.authorize(callback = vkAuthCallback)
}
override fun launchSignOut() {
vkAuthDataState.update { Resource.Uninitialized() }
}
}
| 0 | Kotlin | 1 | 11 | b17c340bd7bfa2fc7c9f025bbea5f5fa1e79a142 | 2,748 | WordTeacher | MIT License |
app/src/main/java/com/pr0gramm/app/ui/fragments/FavedCommentFragment.kt | chrosey | 95,877,863 | false | {"Gradle": 5, "Shell": 6, "Java Properties": 2, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 3, "Proguard": 2, "Kotlin": 266, "XML": 132, "JSON": 42, "Java": 12, "SVG": 11, "Python": 1} | package com.pr0gramm.app.ui.fragments
import android.content.Intent
import android.net.Uri
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.github.salomonbrys.kodein.instance
import com.pr0gramm.app.R
import com.pr0gramm.app.Settings
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.services.FavedCommentService
import com.pr0gramm.app.ui.MessageAdapter
import com.pr0gramm.app.ui.MessageView
import com.pr0gramm.app.ui.showDialog
/**
*/
class FavedCommentFragment : MessageInboxFragment("FavedCommentFragment") {
private val settings = Settings.get()
private val favedCommentService: FavedCommentService by instance()
init {
setHasOptionsMenu(true)
}
override fun newLoaderHelper(): LoaderHelper<List<Api.Message>> {
return LoaderHelper.of {
favedCommentService
.list(settings.contentType)
.map { comments -> comments.map { FavedCommentService.commentToMessage(it) } }
}
}
override fun newMessageAdapter(messages: List<Api.Message>): MessageAdapter {
val adapter = super.newMessageAdapter(messages)
adapter.pointsVisibility = MessageView.PointsVisibility.NEVER
return adapter
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_kfav, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_info) {
showKFavInfoPopup()
return true
}
return super.onOptionsItemSelected(item)
}
private fun showKFavInfoPopup() {
showDialog(context) {
content(R.string.info_kfav_userscript)
negative(R.string.okay)
positive(R.string.open_website) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://goo.gl/py7xNW"))
context.startActivity(intent)
}
}
}
}
| 1 | null | 1 | 1 | b6a7b846bcae573545da824cb716a07a334adedb | 2,072 | Pr0 | MIT License |
client/android/div/src/main/java/com/yandex/div/core/view2/divs/widgets/ReleaseViewVisitor.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.core.view2.divs.widgets
import android.view.View
import androidx.annotation.VisibleForTesting
import com.yandex.div.core.DivCustomContainerViewAdapter
import com.yandex.div.core.DivCustomViewAdapter
import com.yandex.div.core.annotations.Mockable
import com.yandex.div.core.dagger.DivViewScope
import com.yandex.div.core.extension.DivExtensionController
import com.yandex.div.core.util.releasableList
import com.yandex.div.core.view2.Div2View
import com.yandex.div.core.view2.Releasable
import com.yandex.div.json.expressions.ExpressionResolver
import com.yandex.div2.DivBase
import javax.inject.Inject
@DivViewScope
@Mockable
internal class ReleaseViewVisitor @Inject constructor(
private val divView: Div2View,
private val divCustomViewAdapter: DivCustomViewAdapter,
private val divCustomContainerViewAdapter: DivCustomContainerViewAdapter,
private val divExtensionController: DivExtensionController,
) : DivViewVisitor() {
override fun defaultVisit(view: DivHolderView<*>) =
releaseInternal(view as View, view.div, view.bindingContext?.expressionResolver)
override fun visit(view: DivPagerView) {
super.visit(view)
view.viewPager.adapter = null
}
override fun visit(view: DivRecyclerView) {
super.visit(view)
view.adapter = null
}
override fun visit(view: DivCustomWrapper) {
val divCustom = view.div ?: return
val resolver = view.bindingContext?.expressionResolver ?: return
release(view)
view.customView?.let {
divExtensionController.unbindView(divView, resolver, it, divCustom)
divCustomViewAdapter.release(it, divCustom)
divCustomContainerViewAdapter?.release(it, divCustom)
}
}
override fun visit(view: View) = release(view)
private fun releaseInternal(view: View, div: DivBase?, resolver: ExpressionResolver?) {
if (div != null && resolver != null) {
divExtensionController.unbindView(divView, resolver, view, div)
}
release(view)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun release(view: View) {
if (view is Releasable) {
view.release()
}
view.releasableList?.forEach { releasable ->
releasable.release()
}
}
}
| 7 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 2,359 | divkit | Apache License 2.0 |
app/src/main/java/com/dmbaryshev/bd/model/repository/BaseRepo.kt | DmBard | 57,616,046 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 3, "XML": 58, "Kotlin": 106} | package com.dmbaryshev.bd.model.repository
import com.dmbaryshev.bd.model.dto.common.CommonResponse
import com.dmbaryshev.bd.model.dto.common.VkError
import com.dmbaryshev.bd.model.mapper.BaseMapper
import com.dmbaryshev.bd.model.view_model.IViewModel
import com.dmbaryshev.bd.network.ResponseAnswer
import com.dmbaryshev.bd.network.errors.ErrorUtils
import retrofit2.Response
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
abstract class BaseRepo<V, VM : IViewModel> {
protected fun load(networkConcreteObservable: Observable<Response<CommonResponse<V>>>): Observable<ResponseAnswer<VM>> {
return networkConcreteObservable.map({ initNetworkResponseAnswer(it) }).observeOn( AndroidSchedulers.mainThread()).cache()
}
private fun initNetworkResponseAnswer(response: Response<CommonResponse<V>>?): ResponseAnswer<VM> {
var answer: List<V>? = null
var vkError: VkError? = null
var responseAnswer = ResponseAnswer(0, answer, vkError)
if (response == null) {
return initMapper().execute(responseAnswer)
}
val commonResponse = response.body() ?: return initMapper().execute(responseAnswer)
val vkResponse = commonResponse.mVkResponse
if (vkResponse == null) {
val commonError = ErrorUtils.parseError(response)
responseAnswer.vkError = commonError.mVkError
} else {
if(isSaved) save(vkResponse.items)
responseAnswer.count = vkResponse.count
responseAnswer.answer = vkResponse.items
}
return initMapper().execute(responseAnswer)
}
protected abstract fun save(items: List<V>?)
protected abstract fun initMapper(): BaseMapper<V, VM>
protected open var isSaved:Boolean = false
} | 0 | Kotlin | 0 | 7 | 7c554d784a45097001a2af7505e00bddc594fecb | 1,790 | bd | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/modules/deeplink/ui/DeeplinkHandler.kt | perawallet | 364,359,642 | false | null | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.deeplink.ui
import com.algorand.android.models.AssetAction
import com.algorand.android.models.AssetInformation
import com.algorand.android.models.AssetTransaction
import com.algorand.android.models.User
import com.algorand.android.modules.deeplink.DeepLinkParser
import com.algorand.android.modules.deeplink.domain.model.BaseDeepLink
import com.algorand.android.modules.deeplink.domain.model.BaseDeepLink.WalletConnectConnectionDeepLink
import com.algorand.android.modules.deeplink.domain.model.NotificationGroupType
import com.algorand.android.modules.webimport.common.data.model.WebImportQrCode
import com.algorand.android.usecase.AccountDetailUseCase
import com.algorand.android.utils.toShortenedAddress
import javax.inject.Inject
class DeeplinkHandler @Inject constructor(
private val accountDetailUseCase: AccountDetailUseCase,
private val deepLinkParser: DeepLinkParser
) {
private var listener: Listener? = null
fun setListener(listener: Listener?) {
this.listener = listener
}
fun handleDeepLink(uri: String) {
val rawDeepLink = deepLinkParser.parseDeepLink(uri)
val parsedDeepLink = BaseDeepLink.create(rawDeepLink)
handleDeeplink(parsedDeepLink)
}
private fun handleDeeplink(baseDeeplink: BaseDeepLink) {
val isDeeplinkHandled: Boolean = when (baseDeeplink) {
is BaseDeepLink.AccountAddressDeepLink -> handleAccountAddressDeepLink(baseDeeplink)
is BaseDeepLink.AssetTransferDeepLink -> handleAssetTransferDeepLink(baseDeeplink)
is BaseDeepLink.AssetOptInDeepLink -> handleAssetOptInDeepLink(baseDeeplink.assetId)
is BaseDeepLink.MnemonicDeepLink -> handleMnemonicDeepLink(baseDeeplink)
is WalletConnectConnectionDeepLink -> handleWalletConnectConnectionDeepLink(baseDeeplink)
is BaseDeepLink.UndefinedDeepLink -> handleUndefinedDeepLink(baseDeeplink)
is BaseDeepLink.WebImportQrCodeDeepLink -> handleWebImportQrCodeDeepLink(baseDeeplink)
is BaseDeepLink.NotificationDeepLink -> handleNotificationDeepLink(baseDeeplink)
}
if (!isDeeplinkHandled) listener?.onDeepLinkNotHandled(baseDeeplink)
}
private fun handleAccountAddressDeepLink(deepLink: BaseDeepLink.AccountAddressDeepLink): Boolean {
return triggerListener { it.onAccountAddressDeeplink(deepLink.accountAddress, deepLink.label) }
}
private fun handleAssetOptInDeepLink(assetId: Long): Boolean {
val assetAction = AssetAction(assetId = assetId)
return triggerListener { it.onAssetOptInDeepLink(assetAction) }
}
private fun handleMnemonicDeepLink(mnemonicDeeplink: BaseDeepLink.MnemonicDeepLink): Boolean {
return triggerListener { it.onImportAccountDeepLink(mnemonicDeeplink.mnemonic) }
}
private fun handleWalletConnectConnectionDeepLink(wcConnectionDeeplink: WalletConnectConnectionDeepLink): Boolean {
return triggerListener {
it.onWalletConnectConnectionDeeplink(wcUrl = wcConnectionDeeplink.url)
}
}
private fun handleUndefinedDeepLink(undefinedDeeplink: BaseDeepLink.UndefinedDeepLink): Boolean {
return triggerListener { it.onUndefinedDeepLink(undefinedDeeplink); true }
}
private fun handleWebImportQrCodeDeepLink(webImportQrCodeDeepLink: BaseDeepLink.WebImportQrCodeDeepLink): Boolean {
return triggerListener {
it.onWebImportQrCodeDeepLink(
webImportQrCode = webImportQrCodeDeepLink.webImportQrCode
)
}
}
private fun handleAssetTransferDeepLink(assetTransferDeeplink: BaseDeepLink.AssetTransferDeepLink): Boolean {
val assetId = assetTransferDeeplink.assetId
val isAssetOwnedByAnyAccount = if (assetId == AssetInformation.ALGO_ID) {
true
} else {
accountDetailUseCase.isAssetOwnedByAnyAccount(assetTransferDeeplink.assetId)
}
return if (isAssetOwnedByAnyAccount) {
with(assetTransferDeeplink) {
val assetTransaction = AssetTransaction(
assetId = assetId,
note = note, // normal note
xnote = xnote, // locked note
amount = amount,
receiverUser = User(
publicKey = receiverAccountAddress,
name = label ?: receiverAccountAddress.toShortenedAddress(),
imageUriAsString = null
)
)
triggerListener { it.onAssetTransferDeepLink(assetTransaction) }
}
} else {
triggerListener { it.onAssetTransferWithNotOptInDeepLink(assetId) }
}
}
private fun handleNotificationDeepLink(notificationDeepLink: BaseDeepLink.NotificationDeepLink): Boolean {
return triggerListener {
it.onNotificationDeepLink(
accountAddress = notificationDeepLink.address,
assetId = notificationDeepLink.assetId,
notificationGroupType = notificationDeepLink.notificationGroupType
)
}
}
private fun triggerListener(action: (Listener) -> Boolean): Boolean {
return listener?.run(action) ?: false
}
interface Listener {
fun onAssetTransferDeepLink(assetTransaction: AssetTransaction): Boolean = false
fun onAssetOptInDeepLink(assetAction: AssetAction): Boolean = false
fun onImportAccountDeepLink(mnemonic: String): Boolean = false
fun onAccountAddressDeeplink(accountAddress: String, label: String?): Boolean = false
fun onWalletConnectConnectionDeeplink(wcUrl: String): Boolean = false
fun onAssetTransferWithNotOptInDeepLink(assetId: Long): Boolean = false
fun onWebImportQrCodeDeepLink(webImportQrCode: WebImportQrCode): Boolean = false
fun onNotificationDeepLink(
accountAddress: String,
assetId: Long,
notificationGroupType: NotificationGroupType
): Boolean = false
fun onUndefinedDeepLink(undefinedDeeplink: BaseDeepLink.UndefinedDeepLink)
fun onDeepLinkNotHandled(deepLink: BaseDeepLink)
}
}
| 22 | null | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 6,836 | pera-wallet | Apache License 2.0 |
src/main/java/at/petrak/hexcasting/common/casting/operators/spells/OpColorize.kt | Noobulus | 479,910,974 | false | {"Java Properties": 1, "Groovy": 1, "Text": 3, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Gradle": 1, "Ignore List": 1, "Kotlin": 118, "Java": 108, "JSON": 435, "TOML": 1, "INI": 1} | package at.petrak.hexcasting.common.casting.operators.spells
import at.petrak.hexcasting.api.spell.ParticleSpray
import at.petrak.hexcasting.api.spell.RenderedSpell
import at.petrak.hexcasting.api.spell.SpellDatum
import at.petrak.hexcasting.api.spell.SpellOperator
import at.petrak.hexcasting.common.casting.CastingContext
import at.petrak.hexcasting.common.casting.colors.FrozenColorizer
import at.petrak.hexcasting.common.lib.HexCapabilities
import at.petrak.hexcasting.common.network.HexMessages
import at.petrak.hexcasting.common.network.MsgColorizerUpdateAck
import net.minecraftforge.network.PacketDistributor
object OpColorize : SpellOperator {
override val argc = 0
override fun execute(
args: List<SpellDatum<*>>,
ctx: CastingContext
): Triple<RenderedSpell, Int, List<ParticleSpray>> {
return Triple(
Spell,
10_000,
listOf()
)
}
private object Spell : RenderedSpell {
override fun cast(ctx: CastingContext) {
val maybeCap = ctx.caster.getCapability(HexCapabilities.PREFERRED_COLORIZER).resolve()
if (!maybeCap.isPresent)
return
val cap = maybeCap.get()
val otherHandItem = ctx.caster.getItemInHand(ctx.otherHand)
if (FrozenColorizer.isColorizer(otherHandItem.item)) {
val item = otherHandItem.item
if (ctx.withdrawItem(otherHandItem.item, 1, true)) {
cap.colorizer = FrozenColorizer(item, ctx.caster.uuid)
HexMessages.getNetwork()
.send(PacketDistributor.PLAYER.with { ctx.caster }, MsgColorizerUpdateAck(cap))
}
}
}
}
} | 1 | null | 1 | 1 | fd206287f685261aa257957f6a4eb634db46630f | 1,744 | HexMod | MIT License |
app/src/main/java/tipz/viola/webviewui/BaseActivity.kt | TipzRickyCheung | 287,279,448 | false | null | /*
* Copyright (c) 2022-2024 Tipz Team
*
* 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 tipz.viola.webviewui
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import tipz.viola.Application
import tipz.viola.settings.SettingsKeys
import tipz.viola.settings.SettingsSharedPreference
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsPreference = (applicationContext as Application).settingsPreference
windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
}
public override fun onStart() {
super.onStart()
doSettingsCheck()
}
/*
* Settings config checker
*
* This function is called every time a user returns to the app, where
* onStart() is executed. It checks all configuration items and performs
* actions to perform the actions required. Activities that implement us
* will need to call this function.
*/
@CallSuper
open fun doSettingsCheck() {
// Dark Mode
darkModeCheck(this)
}
companion object {
var settingsPreference: SettingsSharedPreference? = null
var windowInsetsController: WindowInsetsControllerCompat? = null
fun darkModeCheck(context: Context) {
// Dark mode
if (settingsPreference!!.getInt(SettingsKeys.themeId) == 0) AppCompatDelegate.setDefaultNightMode(
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY else AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
else AppCompatDelegate.setDefaultNightMode(
if (settingsPreference!!.getInt(SettingsKeys.themeId) == 2) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO
)
windowInsetsController!!.isAppearanceLightStatusBars = !getDarkMode(context)
windowInsetsController!!.isAppearanceLightNavigationBars = !getDarkMode(context)
}
fun getDarkMode(context: Context): Boolean {
return context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
Configuration.UI_MODE_NIGHT_YES
}
}
} | 0 | null | 3 | 14 | c1c2f55a23b2cfac67efa6b39f362b163f228cc8 | 3,092 | viola | Apache License 2.0 |
tiltak/src/main/kotlin/no/nav/amt/tiltak/nav_enhet/NavEnhetServiceImpl.kt | navikt | 393,356,849 | false | null | package no.nav.amt.tiltak.nav_enhet
import no.nav.amt.tiltak.clients.amt_person.AmtPersonClient
import no.nav.amt.tiltak.clients.veilarbarena.VeilarbarenaClient
import no.nav.amt.tiltak.core.domain.tiltak.NavEnhet
import no.nav.amt.tiltak.core.port.NavEnhetService
import no.nav.amt.tiltak.log.SecureLog.secureLog
import org.springframework.stereotype.Service
import java.util.UUID
@Service
open class NavEnhetServiceImpl(
private val navEnhetRepository: NavEnhetRepository,
private val veilarbarenaClient: VeilarbarenaClient,
private val amtPersonClient: AmtPersonClient,
) : NavEnhetService {
override fun getNavEnhetForBruker(personIdent: String): NavEnhet? {
val oppfolgingsenhetId = veilarbarenaClient.hentBrukerOppfolgingsenhetId(personIdent)
?: return null
return getNavEnhet(oppfolgingsenhetId)
.also {
if (it == null) {
secureLog.warn("Bruker med fnr=$personIdent har enhetId=$oppfolgingsenhetId som ikke finnes i amt-person")
}
}
}
override fun getNavEnhet(enhetId: String) =
navEnhetRepository.hentEnhet(enhetId)?.toNavEnhet()
?: opprettEnhet(enhetId)
override fun getNavEnhet(id: UUID) = navEnhetRepository.get(id).toNavEnhet()
private fun opprettEnhet(enhetId: String): NavEnhet? {
val navEnhet = amtPersonClient.hentNavEnhet(enhetId)
.recover {
if (it is NoSuchElementException) return null
else throw it
}.getOrThrow()
val insertInput = NavEnhetInsertInput(
id = navEnhet.id,
enhetId = navEnhet.enhetId,
navn = navEnhet.navn
)
navEnhetRepository.insert(insertInput)
return navEnhet
}
}
| 2 | Kotlin | 3 | 4 | 7f3df04447dc622e87538f454e4fcc69bfd713e9 | 1,585 | amt-tiltak | MIT License |
app/src/main/java/com/example/binanceticker/data/local/TickerDao.kt | AsenMarkov | 842,203,668 | false | {"Kotlin": 30756} | package com.example.binanceticker.data.local
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
@Dao
interface TickerDao {
@Upsert
fun upsertAll(tickerList: List<TickerEntity>)
@Query("SELECT * FROM ticker_entity")
fun pagingSource(): PagingSource<Int, TickerEntity>
@Query("SELECT * FROM ticker_entity WHERE id = :id LIMIT 1")
fun getSingleItem(id: Int): TickerEntity
}
| 0 | Kotlin | 0 | 0 | 9c60cf2e2e92eb0de8af53f3f7daaa5863a204a4 | 465 | BinanceTicker | Apache License 2.0 |
engine/game/src/main/kotlin/org/rsmod/game/stat/PlayerSkillXPTable.kt | rsmod | 293,875,986 | false | {"Kotlin": 1817705} | package org.rsmod.game.stat
import kotlin.math.pow
public object PlayerSkillXPTable {
public val XP_TABLE: IntArray =
IntArray(126).apply {
var accumulatedXp = 0
for (level in 1 until size) {
accumulatedXp += (level + 300 * 2.0.pow(level / 7.0)).toInt()
this[level] = accumulatedXp / 4
}
}
public fun getXPFromLevel(level: Int): Int {
require(level - 1 in XP_TABLE.indices)
return XP_TABLE[level - 1]
}
public fun getLevelFromXP(xp: Int): Int {
val searchResultIndex = XP_TABLE.binarySearch(xp)
if (searchResultIndex >= 0) {
return searchResultIndex + 1
}
val nearestLowerLevel = -(searchResultIndex + 1)
return nearestLowerLevel
}
public fun getFineXPFromLevel(level: Int): Int {
val xp = getXPFromLevel(level)
return PlayerStatMap.toFineXP(xp.toDouble()).toInt()
}
public fun getLevelFromFineXP(fineXp: Int): Int {
val xp = PlayerStatMap.normalizeFineXP(fineXp)
return getLevelFromXP(xp)
}
}
| 0 | Kotlin | 64 | 95 | 3ba446ed70bcde0870ef431e1a8527efc6837d6c | 1,120 | rsmod | ISC License |
kotlin/src/main/kotlin/between_two_sets/between-two-sets.kt | francisakpan | 299,567,682 | false | {"Kotlin": 16639, "Dart": 2622, "Java": 2384} | package between_two_sets
fun main() {
val a = arrayOf(2,6)
val b = arrayOf(24, 36)
println(getTotalX(a, b))
}
fun getTotalX(a: Array<Int>, b: Array<Int>): Int {
// Write your code here
var count = 0
for (i in 1..100) {
if (a.all { i % it == 0 }){
if (b.all { it % i == 0 }){
count++
}
}
}
return count
} | 0 | Kotlin | 0 | 0 | efb8fa9ee0249c01a4822485c40f86bec8a8e4cc | 394 | random-exercises | MIT License |
presentation/src/main/java/com/mygomii/presentation/screens/Main.kt | mygomii | 793,599,316 | false | {"Kotlin": 39154} | package com.mygomii.presentation.screens
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.mygomii.data.models.CachedFileState
import com.mygomii.data.models.DownloadError
import com.mygomii.data.models.FileManagerScreenState
import com.mygomii.presentation.R
import com.mygomii.presentation.main.MainViewModel
import com.orhanobut.logger.Logger
@Composable
fun Main() {
FileManagerScreen(modifier = Modifier.fillMaxSize())
}
@Composable
fun FileManagerScreen(modifier: Modifier = Modifier, viewModel: MainViewModel = hiltViewModel()) {
val screenState = viewModel.screenStateStream.collectAsState().value
val actions = remember(viewModel) {
object : FileActions {
override fun download(cachedFileState: CachedFileState) {
viewModel.download(cachedFileState)
}
override fun delete(cachedFileState: CachedFileState) {
viewModel.delete(cachedFileState)
}
}
}
Scaffold(modifier = modifier) {
Box(
modifier = Modifier
.padding(it)
.fillMaxSize()
) {
when (screenState) {
is FileManagerScreenState.Error -> Text(text = "An error occurred. Please try again.")
is FileManagerScreenState.Loaded -> Loaded(screenState = screenState, actions)
is FileManagerScreenState.Loading -> CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
}
}
@Composable
private fun Loaded(screenState: FileManagerScreenState.Loaded, actions: FileActions, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier.fillMaxSize()) {
items(screenState.cachedFileState.size) { index ->
FileCacheStateItem(screenState.cachedFileState[index], actions)
}
}
}
@Composable
private fun FileCacheStateItem(cachedFileState: CachedFileState, actions: FileActions) {
Column(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Row {
Text(
modifier = Modifier
.weight(1f)
.align(Alignment.CenterVertically),
text = cachedFileState.metadata.name
)
CachedFileState(cachedFileState, actions = actions, modifier = Modifier.align(Alignment.CenterVertically))
}
if (cachedFileState is CachedFileState.Error) {
ErrorMessage(cachedFileState.reason)
}
AnimatedVisibility(visible = cachedFileState is CachedFileState.Cached) {
if (cachedFileState is CachedFileState.Cached) {
AsyncImage(
modifier = Modifier.fillMaxWidth(),
model = cachedFileState.downloadedFile.file.toUri(),
contentDescription = cachedFileState.metadata.name
)
}
}
}
}
@Composable
private fun ErrorMessage(reason: DownloadError) {
val res = when (reason) {
is DownloadError.CannotResume -> R.string.download_error_cannot_resume
is DownloadError.FileAlreadyExists -> R.string.download_error_file_already_exists
is DownloadError.InsufficientSpace -> R.string.download_error_insufficient_space
is DownloadError.FileDownloadError,
is DownloadError.DeviceNotFound,
is DownloadError.Http,
is DownloadError.HttpData,
is DownloadError.TooManyRedirects,
is DownloadError.UnhandledHttpCode,
is DownloadError.Unknown -> {
Logger.i("Download error: $reason")
R.string.download_error_general
}
}
val text = stringResource(res)
val formattedMessage = stringResource(R.string.download_error_message, text)
Text(text = formattedMessage, color = MaterialTheme.colorScheme.error)
}
@Composable
private fun CachedFileState(cachedFileState: CachedFileState, actions: FileActions, modifier: Modifier = Modifier) {
val text = when (cachedFileState) {
is CachedFileState.Cached -> stringResource(R.string.cached_file_state_button_delete)
is CachedFileState.Error -> stringResource(R.string.cached_file_state_button_retry)
is CachedFileState.Downloading -> stringResource(R.string.cached_file_state_button_downloading)
is CachedFileState.NotCached -> stringResource(R.string.cached_file_state_button_download)
}
val buttonColor = when (cachedFileState) {
is CachedFileState.Cached -> MaterialTheme.colorScheme.secondary
is CachedFileState.Downloading -> MaterialTheme.colorScheme.tertiary
is CachedFileState.Error -> MaterialTheme.colorScheme.error
is CachedFileState.NotCached -> MaterialTheme.colorScheme.primary
}
Button(
modifier = modifier,
colors = ButtonDefaults.buttonColors(containerColor = buttonColor),
onClick = {
when (cachedFileState) {
is CachedFileState.NotCached -> actions.download(cachedFileState)
is CachedFileState.Cached -> actions.delete(cachedFileState)
is CachedFileState.Downloading -> actions.delete(cachedFileState)
is CachedFileState.Error -> actions.download(cachedFileState)
}
},
) {
AnimatedVisibility(visible = cachedFileState is CachedFileState.Downloading) {
CircularProgressIndicator(
modifier = Modifier
.padding(end = 12.dp)
.size(24.dp),
color = MaterialTheme.colorScheme.onPrimary
)
}
Text(text = text)
}
}
interface FileActions {
fun download(cachedFileState: CachedFileState)
fun delete(cachedFileState: CachedFileState)
} | 0 | Kotlin | 0 | 0 | d6e8fb4d68320a40222429a3c9d0d0761f3a84c0 | 6,887 | download-manager-android | Apache License 2.0 |
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientSessionJvm.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.tls
import io.ktor.network.sockets.*
import io.ktor.network.util.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import java.nio.*
import kotlin.coroutines.*
internal actual suspend fun openTLSSession(
socket: Socket,
input: ByteReadChannel, output: ByteWriteChannel,
config: TLSConfig,
context: CoroutineContext
): Socket {
val handshake = TLSClientHandshake(input, output, config, context)
try {
handshake.negotiate()
} catch (cause: ClosedSendChannelException) {
throw TLSException("Negotiation failed due to EOS", cause)
}
return TLSSocket(handshake.input, handshake.output, socket, context)
}
private class TLSSocket(
private val input: ReceiveChannel<TLSRecord>,
private val output: SendChannel<TLSRecord>,
socket: Socket,
override val coroutineContext: CoroutineContext
) : CoroutineScope, Socket by socket {
override fun attachForReading(channel: ByteChannel): WriterJob =
writer(coroutineContext + CoroutineName("cio-tls-input-loop"), channel) {
appDataInputLoop(this.channel)
}
override fun attachForWriting(channel: ByteChannel): ReaderJob =
reader(coroutineContext + CoroutineName("cio-tls-output-loop"), channel) {
appDataOutputLoop(this.channel)
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun appDataInputLoop(pipe: ByteWriteChannel) {
try {
input.consumeEach { record ->
val packet = record.packet
val length = packet.remaining
when (record.type) {
TLSRecordType.ApplicationData -> {
pipe.writePacket(record.packet)
pipe.flush()
}
else -> throw TLSException("Unexpected record ${record.type} ($length bytes)")
}
}
} catch (cause: Throwable) {
} finally {
pipe.close()
}
}
private suspend fun appDataOutputLoop(
pipe: ByteReadChannel
): Unit = DefaultByteBufferPool.useInstance { buffer: ByteBuffer ->
try {
while (true) {
buffer.clear()
val rc = pipe.readAvailable(buffer)
if (rc == -1) break
buffer.flip()
output.send(TLSRecord(TLSRecordType.ApplicationData, packet = buildPacket { writeFully(buffer) }))
}
} finally {
output.close()
}
}
}
| 269 | null | 962 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 2,783 | ktor | Apache License 2.0 |
cathode/src/main/java/net/simonvt/cathode/ui/lists/CreateListFragment.kt | SimonVT | 9,478,484 | false | null | /*
* Copyright (C) 2016 <NAME>
*
* 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 net.simonvt.cathode.ui.lists
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.DialogFragment
import net.simonvt.cathode.R
import net.simonvt.cathode.api.enumeration.Privacy
import net.simonvt.cathode.api.enumeration.SortBy
import net.simonvt.cathode.api.enumeration.SortOrientation
import net.simonvt.cathode.databinding.DialogListCreateBinding
import net.simonvt.cathode.settings.TraktLinkSettings
import net.simonvt.cathode.sync.scheduler.ListsTaskScheduler
import javax.inject.Inject
class CreateListFragment @Inject constructor(
private val listsTaskScheduler: ListsTaskScheduler
) : DialogFragment() {
private var _binding: DialogListCreateBinding? = null
private val binding get() = _binding!!
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
if (showsDialog) {
setStyle(DialogFragment.STYLE_NO_TITLE, 0)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
inState: Bundle?
): View? {
_binding = DialogListCreateBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
binding.toolbarInclude.toolbar.setTitle(R.string.action_list_create)
binding.toolbarInclude.toolbar.inflateMenu(R.menu.fragment_list_create)
binding.toolbarInclude.toolbar.setOnMenuItemClickListener(Toolbar.OnMenuItemClickListener { item ->
when (item.itemId) {
R.id.menu_create -> {
val privacyValue = when (binding.privacy.selectedItemPosition) {
1 -> Privacy.FRIENDS
2 -> Privacy.PUBLIC
else -> Privacy.PRIVATE
}
val sortByValue = when (binding.sortBy.selectedItemPosition) {
2 -> SortBy.ADDED
3 -> SortBy.TITLE
4 -> SortBy.RELEASED
5 -> SortBy.RUNTIME
6 -> SortBy.POPULARITY
7 -> SortBy.PERCENTAGE
8 -> SortBy.VOTES
9 -> SortBy.MY_RATING
10 -> SortBy.RANDOM
else -> SortBy.RANK
}
val sortOrientationValue = when (binding.sortOrientation.selectedItemPosition) {
1 -> SortOrientation.DESC
else -> SortOrientation.ASC
}
listsTaskScheduler.createList(
binding.name.text.toString(),
binding.description.text.toString(),
privacyValue,
binding.displayNumbers.isChecked,
binding.allowComments.isChecked,
sortByValue,
sortOrientationValue
)
dismiss()
return@OnMenuItemClickListener true
}
}
false
})
if (TraktLinkSettings.isLinked(requireContext())) {
val privacyAdapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.list_privacy,
android.R.layout.simple_spinner_item
)
privacyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.privacy.adapter = privacyAdapter
} else {
binding.privacy.visibility = View.GONE
binding.allowComments.visibility = View.GONE
}
val sortByAdapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.list_sort_by,
android.R.layout.simple_spinner_item
)
sortByAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.sortBy.adapter = sortByAdapter
val sortOrientationAdapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.list_sort_orientation,
android.R.layout.simple_spinner_item
)
sortOrientationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.sortOrientation.adapter = sortOrientationAdapter
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
}
| 11 | Kotlin | 9 | 99 | 29d916efcd1dbb8ddac1fc2600b2bfbe6ee84c27 | 4,671 | cathode | Apache License 2.0 |
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/Context.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.intellij.build.images.ImageExtension
import java.io.File
import java.nio.file.Files
import java.util.function.Consumer
import kotlin.concurrent.thread
internal class Context(private val errorHandler: Consumer<String> = Consumer { error(it) },
private val devIconsVerifier: Consumer<Collection<File>>? = null) {
companion object {
const val iconsCommitHashesToSyncArg = "sync.icons.commits"
private const val iconsRepoArg = "icons.repo"
}
var devRepoDir: File
var iconsRepoDir: File
val iconsRepoName: String
val devRepoName: String
val skipDirsPattern: String?
val doSyncIconsRepo: Boolean
val doSyncDevRepo: Boolean
val doSyncRemovedIconsInDev: Boolean
private val failIfSyncDevIconsRequired: Boolean
val notifySlack: Boolean
val byDev = Changes()
val byCommit = mutableMapOf<String, Changes>()
val consistent: MutableCollection<String> = mutableListOf()
var icons: Map<String, GitObject> = emptyMap()
var devIcons: Map<String, GitObject> = emptyMap()
var devCommitsToSync: Map<File, Collection<CommitInfo>> = emptyMap()
var iconsCommitsToSync: Map<File, Collection<CommitInfo>> = emptyMap()
val iconsCommitHashesToSync: MutableSet<String>
val devIconsCommitHashesToSync: MutableSet<String>
val devIconsSyncAll: Boolean
init {
val devRepoArg = "dev.repo"
val iconsRepoNameArg = "icons.repo.name"
val iconsRepoPathArg = "icons.repo.path"
val devRepoNameArg = "dev.repo.name"
val patternArg = "skip.dirs.pattern"
val syncIconsArg = "sync.icons"
val syncDevIconsArg = "sync.dev.icons"
val syncRemovedIconsInDevArg = "sync.dev.icons.removed"
val failIfSyncDevIconsRequiredArg = "fail.if.sync.dev.icons.required"
val assignInvestigationArg = "assign.investigation"
val notifySlackArg = "notify.slack"
val devIconsSyncAllArg = "sync.dev.icons.all"
@Suppress("unused")
fun usage() = println("""
|Usage: -D$devRepoArg=<devRepoDir> -D$iconsRepoArg=<iconsRepoDir> [-Doption=...]
|Options:
|* `$iconsRepoArg` - designers' repo
|* `$devRepoArg` - developers' repo
|* `$iconsRepoPathArg` - path in designers' repo
|* `$iconsRepoNameArg` - designers' repo name (for report)
|* `$devRepoNameArg` - developers' repo name (for report)
|* `$patternArg` - regular expression for names of directories to skip
|* `$syncDevIconsArg` - sync icons in developers' repo. Switch off to run check only
|* `$syncIconsArg` - sync icons in designers' repo. Switch off to run check only
|* `$syncRemovedIconsInDevArg` - remove icons in developers' repo removed by designers
|* `$failIfSyncDevIconsRequiredArg` - do fail if icons sync in developers' repo is required
|* `$assignInvestigationArg` - assign investigation if required
|* `$notifySlackArg` - notify slack channel if required
|* `$iconsCommitHashesToSyncArg` - commit hashes in designers' repo to sync icons from, implies $syncDevIconsArg
|* `$devIconsSyncAllArg` - sync all changes from developers' repo to designers' repo, implies $syncIconsArg
""".trimMargin())
fun bool(arg: String) = System.getProperty(arg)?.toBoolean() ?: false
fun commits(arg: String) = System.getProperty(arg)
?.takeIf { it.trim() != "*" }
?.split(",", ";", " ")
?.filter { it.isNotBlank() }
?.mapTo(mutableSetOf(), String::trim) ?: mutableSetOf<String>()
devRepoDir = findDirectoryIgnoringCase(System.getProperty(devRepoArg)) ?: {
log("WARNING: $devRepoArg not found")
File(System.getProperty("user.dir"))
}()
val iconsRepoRelativePath = System.getProperty(iconsRepoPathArg) ?: ""
val iconsRepoRootDir = findDirectoryIgnoringCase(System.getProperty(iconsRepoArg)) ?: cloneIconsRepoToTempDir()
iconsRepoDir = iconsRepoRootDir.resolve(iconsRepoRelativePath)
if (!iconsRepoDir.exists() && !iconsRepoDir.mkdirs() || !iconsRepoDir.isDirectory) {
doFail("Cannot access $iconsRepoDir")
}
iconsRepoName = System.getProperty(iconsRepoNameArg) ?: "icons repo"
devRepoName = System.getProperty(devRepoNameArg) ?: "dev repo"
skipDirsPattern = System.getProperty(patternArg)
doSyncDevRepo = bool(syncDevIconsArg)
doSyncIconsRepo = bool(syncIconsArg)
failIfSyncDevIconsRequired = bool(failIfSyncDevIconsRequiredArg)
notifySlack = bool(notifySlackArg)
iconsCommitHashesToSync = commits(iconsCommitHashesToSyncArg)
doSyncRemovedIconsInDev = bool(syncRemovedIconsInDevArg) || iconsCommitHashesToSync.isNotEmpty()
// scheduled build is always full check
devIconsSyncAll = bool(devIconsSyncAllArg) || isScheduled()
// read TeamCity provided changes
devIconsCommitHashesToSync = System.getProperty("teamcity.build.changedFiles.file")
// if icons sync is required
?.takeIf { doSyncIconsRepo }
// or full check is not required
?.takeIf { !devIconsSyncAll }
?.let(::File)
?.takeIf(File::exists)
?.let(FileUtil::loadFile)
?.takeIf { !it.contains("<personal>") }
?.let(StringUtil::splitByLines)
?.mapNotNull {
val split = it.split(':')
if (split.size != 3) {
log("WARNING: malformed line in 'teamcity.build.changedFiles.file' : $it")
return@mapNotNull null
}
val (file, _, commit) = split
if (ImageExtension.fromName(file) != null) commit else null
}?.toMutableSet() ?: mutableSetOf()
}
val iconsRepo: File by lazy {
findGitRepoRoot(iconsRepoDir)
}
val devRepoRoot: File by lazy {
findGitRepoRoot(devRepoDir)
}
private fun cloneIconsRepoToTempDir(): File {
log("WARNING: $iconsRepoArg not found")
val tmp = Files.createTempDirectory("icons-sync").toFile()
Runtime.getRuntime().addShutdownHook(thread(start = false) {
tmp.deleteRecursively()
})
val uri = "ssh://[email protected]/JetBrains/IntelliJIcons.git"
return callWithTimer("Cloning $uri into $tmp") { gitClone(uri, tmp) }
}
val byDesigners = Changes(includeRemoved = doSyncRemovedIconsInDev)
val devIconsFilter: (File) -> Boolean by lazy {
val skipDirsRegex = skipDirsPattern?.toRegex()
val testRoots = searchTestRoots(devRepoRoot.absolutePath)
log("Found ${testRoots.size} test roots")
return@lazy { file: File ->
filterDevIcon(file, testRoots, skipDirsRegex, this)
}
}
var iconsFilter: (File) -> Boolean = { Icon(it).isValid }
fun devChanges() = byDev.all()
fun iconsChanges() = byDesigners.all()
fun iconsSyncRequired() = devChanges().isNotEmpty()
fun devSyncRequired() = iconsChanges().isNotEmpty()
fun verifyDevIcons(repos: Collection<File>) = devIconsVerifier?.accept(repos)
fun doFail(report: String) {
log(report)
errorHandler.accept(report)
}
fun isFail() = notifySlack && failIfSyncDevIconsRequired && devSyncRequired()
private fun findDirectoryIgnoringCase(path: String?): File? {
if (path == null) return null
val file = File(path)
if (file.isDirectory) return file
return file.parentFile?.listFiles()?.firstOrNull {
it.absolutePath.equals(FileUtil.toSystemDependentName(path), ignoreCase = true)
}
}
} | 191 | null | 4372 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 7,606 | intellij-community | Apache License 2.0 |
json-builder/kotlin/src/generated/kotlin/divkit/dsl/ActionVideo.kt | divkit | 523,491,444 | false | null | @file:Suppress(
"unused",
"UNUSED_PARAMETER",
)
package divkit.dsl
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonValue
import divkit.dsl.annotation.*
import divkit.dsl.core.*
import divkit.dsl.scope.*
import kotlin.Any
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.collections.Map
/**
* Manages video playback.
*
* Can be created using the method [actionVideo].
*
* Required parameters: `type, id, action`.
*/
@Generated
data class ActionVideo internal constructor(
@JsonIgnore
val properties: Properties,
) : ActionTyped {
@JsonAnyGetter
internal fun getJsonProperties(): Map<String, Any> = properties.mergeWith(
mapOf("type" to "video")
)
operator fun plus(additive: Properties): ActionVideo = ActionVideo(
Properties(
action = additive.action ?: properties.action,
id = additive.id ?: properties.id,
)
)
data class Properties internal constructor(
/**
* Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
*/
val action: Property<Action>?,
/**
* Video ID.
*/
val id: Property<String>?,
) {
internal fun mergeWith(properties: Map<String, Any>): Map<String, Any> {
val result = mutableMapOf<String, Any>()
result.putAll(properties)
result.tryPutProperty("action", action)
result.tryPutProperty("id", id)
return result
}
}
/**
* Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
*
* Possible values: [start], [pause].
*/
@Generated
sealed interface Action
}
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun DivScope.actionVideo(
`use named arguments`: Guard = Guard.instance,
action: ActionVideo.Action? = null,
id: String? = null,
): ActionVideo = ActionVideo(
ActionVideo.Properties(
action = valueOrNull(action),
id = valueOrNull(id),
)
)
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun DivScope.actionVideoProps(
`use named arguments`: Guard = Guard.instance,
action: ActionVideo.Action? = null,
id: String? = null,
) = ActionVideo.Properties(
action = valueOrNull(action),
id = valueOrNull(id),
)
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun TemplateScope.actionVideoRefs(
`use named arguments`: Guard = Guard.instance,
action: ReferenceProperty<ActionVideo.Action>? = null,
id: ReferenceProperty<String>? = null,
) = ActionVideo.Properties(
action = action,
id = id,
)
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun ActionVideo.override(
`use named arguments`: Guard = Guard.instance,
action: ActionVideo.Action? = null,
id: String? = null,
): ActionVideo = ActionVideo(
ActionVideo.Properties(
action = valueOrNull(action) ?: properties.action,
id = valueOrNull(id) ?: properties.id,
)
)
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun ActionVideo.defer(
`use named arguments`: Guard = Guard.instance,
action: ReferenceProperty<ActionVideo.Action>? = null,
id: ReferenceProperty<String>? = null,
): ActionVideo = ActionVideo(
ActionVideo.Properties(
action = action ?: properties.action,
id = id ?: properties.id,
)
)
/**
* @param action Defines the action for the video: <li>`start` — starts playing the video if the video is ready to be played, or schedules playback</li><li>`pause' — stops the video playback</li>
* @param id Video ID.
*/
@Generated
fun ActionVideo.evaluate(
`use named arguments`: Guard = Guard.instance,
action: ExpressionProperty<ActionVideo.Action>? = null,
id: ExpressionProperty<String>? = null,
): ActionVideo = ActionVideo(
ActionVideo.Properties(
action = action ?: properties.action,
id = id ?: properties.id,
)
)
@Generated
fun ActionVideo.asList() = listOf(this)
@Generated
fun ActionVideo.Action.asList() = listOf(this)
| 5 | null | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 5,317 | divkit | Apache License 2.0 |
src/main/java/com/hongwei/model/v2/jpa/au/StateDataV2.kt | hongwei-bai | 398,241,961 | false | {"HTML": 105668, "Java": 63260, "Kotlin": 54971} | package com.hongwei.model.v2.jpa.au
data class StateDataV2(
val state: String = "",
val totalCases: Long = 0,
val overseasCases: Long = 0,
val newCases: Long = 0,
val isObsoletedData: Boolean = false,
var lastValidDataVersion: Long = 0
) | 0 | HTML | 0 | 4 | 8067cf4e5d82a34e59b1b806aff0906611331b7f | 292 | covid-application-service | Apache License 2.0 |
app/src/test/java/com/ignitetech/compose/ui/home/HomeViewModelTest.kt | gnumilanix | 602,430,902 | false | null | package com.ignitetech.compose.ui.home
import app.cash.turbine.test
import com.ignitetech.compose.data.preference.PreferenceRepository
import com.ignitetech.compose.rules.TestDispatcherRule
import com.ignitetech.compose.ui.Screens
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.junit4.MockKRule
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {
@get:Rule
val mockkRule = MockKRule(this)
@get:Rule
val dispatcherRule = TestDispatcherRule()
@MockK
lateinit var preferenceRepository: PreferenceRepository
lateinit var viewModel: HomeViewModel
private val defaultTabs = listOf(
Screens.HomeScreens.Chats,
Screens.HomeScreens.Groups,
Screens.HomeScreens.Calls
)
@Test
fun `onboardComplete sets preferenceRepository_onboardComplete true`() = runTest {
every { preferenceRepository.onboardCompleteFlow } returns flowOf()
coEvery { preferenceRepository.userId(any()) } returns Unit
coEvery { preferenceRepository.onboardComplete(any()) } returns Unit
viewModel = HomeViewModel(preferenceRepository)
viewModel.onboardComplete()
coVerify {
preferenceRepository.userId(0)
preferenceRepository.onboardComplete(true)
}
}
@Test
fun `state returns default HomeUiState initially`() = runTest {
every { preferenceRepository.onboardCompleteFlow } returns flowOf()
viewModel = HomeViewModel(preferenceRepository)
val state = viewModel.state.value
assertNull(state.onboardComplete)
assertEquals(defaultTabs, state.tabs)
verify { preferenceRepository.onboardCompleteFlow }
}
@Test
fun `state returns updated HomeUiState when onboardCompleteFlow updates`() = runTest {
every { preferenceRepository.onboardCompleteFlow } returns flow {
delay(100)
emit(true)
}
viewModel = HomeViewModel(preferenceRepository)
viewModel.state.test {
assertState(null, defaultTabs, awaitItem())
advanceTimeBy(200)
assertState(true, defaultTabs, awaitItem())
}
}
private fun assertState(
expectedOnboardComplete: Boolean?,
expectedTabs: List<Screens.HomeScreens>,
updatedState: HomeUiState
) {
assertEquals(expectedOnboardComplete, updatedState.onboardComplete)
assertEquals(expectedTabs, updatedState.tabs)
}
}
| 3 | Kotlin | 1 | 0 | 7a7fc31e7013e91ae78947af6bca1d97fb1140ed | 2,937 | explore-compose | Apache License 2.0 |
runtime/src/main/java/io/novafoundation/nova/runtime/ethereum/Web3Api.kt | novasamatech | 496,649,319 | false | {"Kotlin": 5949531, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.runtime.ethereum
import io.novafoundation.nova.core.ethereum.Web3Api
import io.novafoundation.nova.core.ethereum.log.Topic
import jp.co.soramitsu.fearless_utils.wsrpc.SocketService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.asFlow
import org.web3j.protocol.Web3j
import org.web3j.protocol.Web3jService
import org.web3j.protocol.core.Request
import org.web3j.protocol.core.methods.response.EthSubscribe
import org.web3j.protocol.websocket.events.LogNotification
fun Web3Api(web3jService: Web3jService): Web3Api = RealWeb3Api(web3jService)
fun Web3Api(socketService: SocketService): Web3Api = RealWeb3Api(WebSocketWeb3jService(socketService))
internal class RealWeb3Api(
private val web3jService: Web3jService,
private val delegate: Web3j = Web3j.build(web3jService)
) : Web3Api, Web3j by delegate {
override fun logsNotifications(addresses: List<String>, topics: List<Topic>): Flow<LogNotification> {
val logParams = createLogParams(addresses, topics)
val requestParams = listOf("logs", logParams)
val request = Request("eth_subscribe", requestParams, web3jService, EthSubscribe::class.java)
return web3jService.subscribe(request, "eth_unsubscribe", LogNotification::class.java)
.asFlow()
}
private fun createLogParams(addresses: List<String>, topics: List<Topic>): Map<String, Any> {
return buildMap {
if (addresses.isNotEmpty()) {
put("address", addresses)
}
if (topics.isNotEmpty()) {
put("topics", topics.unifyTopics())
}
}
}
private fun List<Topic>.unifyTopics(): List<Any?> {
return map { topic ->
when (topic) {
Topic.Any -> null
is Topic.AnyOf -> topic.values
is Topic.Single -> topic.value
}
}
}
}
| 5 | Kotlin | 9 | 28 | fcd118ab5cbedded709ec062ae5d4bc890aaf96d | 1,934 | nova-android-app | Apache License 2.0 |
app/src/main/java/com/devmanishpatole/latestmovies/ui/navigation/Screen.kt | devmanishpatole | 508,834,053 | false | {"Kotlin": 69845} | package com.devmanishpatole.latestmovies.ui.navigation
/**
* Screen keys for navigation graph
*
* @author Manish Patole, [email protected]
* @since 02/07/22
*/
sealed class Screen(val route: String){
object Movies : Screen("movies")
object Detail : Screen("detail")
object Search : Screen("search")
}
| 1 | Kotlin | 0 | 1 | aeb07c88301919dd7aade3abfcaf4df4f281c64e | 329 | LatestMovies | The Unlicense |
svc-hl7-replay/src/main/kotlin/gov/cdc/dex/replay/service/Application.kt | CDCgov | 510,836,864 | false | {"Kotlin": 694547, "Scala": 208820, "Python": 44391, "Java": 17996, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979} | package gov.cdc.dex.replay.service
import io.micronaut.runtime.Micronaut
import io.swagger.v3.oas.annotations.OpenAPIDefinition
import io.swagger.v3.oas.annotations.info.Info
@OpenAPIDefinition(
info = Info(
title = "HL7v2 Replay API",
version = "1.0",
description = "An API for replaying validated and error queued HL7v2 messages back to the HL7V2 Pipeline")
)
object Application {
@JvmStatic
fun main(args: Array<String>) {
// Micronaut.run(Application.javaClass)
Micronaut.build()
.mainClass(Application.javaClass)
.environmentPropertySource(true)
.start()
}
}
| 121 | Kotlin | 14 | 9 | c88287d49963f07d0a1525c555f3b499196ecb7c | 659 | data-exchange-hl7 | Apache License 2.0 |
RichTextEditorAndroid/src/main/kotlin/net/dankito/richtexteditor/android/util/KeyboardState.kt | TrendingTechnology | 145,268,255 | true | {"Kotlin": 243673, "JavaScript": 15285, "Java": 6364, "CSS": 1750, "HTML": 552} | package net.dankito.richtexteditor.android.util
import android.app.Activity
class KeyboardState {
companion object {
var isKeyboardVisible: Boolean = false
private set
private val keyboardToggleListener = KeyboardUtils.SoftKeyboardToggleListener { isVisible ->
isKeyboardVisible = isVisible
}
fun init(activity: Activity) {
KeyboardUtils.addKeyboardToggleListener(activity, keyboardToggleListener)
}
/**
* It's very important to call cleanUp() when done to avoid memory leaks!
*/
fun cleanUp() {
KeyboardUtils.removeKeyboardToggleListener(keyboardToggleListener)
}
}
} | 0 | Kotlin | 0 | 0 | 022fef76f5071bc0b6590f70f7443ef5404401da | 717 | RichTextEditor | Apache License 2.0 |
android/app/src/main/kotlin/com/sleepylee/survey/survey/MainActivity.kt | sleepylee | 350,631,619 | false | {"Dart": 167444, "Ruby": 1354, "Swift": 404, "Kotlin": 132, "Objective-C": 38} | package com.sleepylee.survey.survey
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 3 | Dart | 0 | 1 | 71bd9577f16f31f8030311946141164556eb5356 | 132 | flutter-survey | MIT License |
src/main/kotlin/dsl/DSLRootComponentExtension.kt | isyscore | 336,950,526 | false | {"Kotlin": 220307, "Java": 5620, "HTML": 643} | @file:Suppress("DuplicatedCode", "unused")
package com.isyscore.kotlin.swing.dsl
import com.isyscore.kotlin.swing.component.*
import com.isyscore.kotlin.swing.inline.newClassInstance
import org.apache.batik.anim.dom.SAXSVGDocumentFactory
import org.apache.batik.swing.JSVGCanvas
import org.apache.batik.util.XMLResourceDescriptor
import java.awt.Component
import java.awt.Image
import java.io.File
import java.io.InputStream
import java.net.URI
import java.net.URL
import java.util.*
import javax.swing.*
import javax.swing.table.TableColumnModel
import javax.swing.table.TableModel
import javax.swing.tree.TreeModel
import javax.swing.tree.TreeNode
fun rootLabel(title: String? = null, icon: Icon? = null, horizontalAlignment: Int = JLabel.LEFT, block: JLabel.() -> Unit): JLabel = JLabel(title, icon, horizontalAlignment).apply(block)
fun rootInput(text: String? = null, column: Int = 0, block: KTextField.() -> Unit): KTextField = KTextField(text, column).apply(block)
fun <T> rootCombobox(model: ComboBoxModel<T>? = null, array: Array<T>? = null, vector: Vector<T>? = null, block: JComboBox<T>.() -> Unit): JComboBox<T> = when {
model != null -> JComboBox(model)
array != null -> JComboBox(array)
vector != null -> JComboBox(vector)
else -> JComboBox()
}.apply(block)
fun rootButton(title: String? = null, icon: Icon? = null, block: JButton.() -> Unit): JButton = JButton(title, icon).apply(block)
fun rootCheckbox(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JCheckBox.() -> Unit): JCheckBox = JCheckBox(title, icon, selected).apply(block)
fun rootRadio(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JRadioButton.() -> Unit): JRadioButton = JRadioButton(title, icon, selected).apply(block)
fun rootToggle(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JToggleButton.() -> Unit): JToggleButton = JToggleButton(title, icon, selected).apply(block)
fun rootTextArea(text: String? = null, rows: Int = 0, columns: Int = 0, block: KTextArea.() -> Unit): KTextArea = KTextArea(text, rows, columns).apply(block)
fun rootInputPassword(text: String? = null, column: Int = 0, block: KPasswordField.() -> Unit): KPasswordField = KPasswordField(text, column).apply(block)
fun rootTextPane(block: KTextPane.() -> Unit): KTextPane = KTextPane().apply(block)
fun rootEditorPane(contentType: String? = null, text: String? = null, url: URL? = null, block: KEditorPane.() -> Unit): KEditorPane = when {
url != null -> KEditorPane(url)
contentType != null -> KEditorPane(contentType, text)
else -> KEditorPane()
}.apply(block)
fun rootSpinner(model: SpinnerModel? = null, block: JSpinner.() -> Unit): JSpinner = (if (model == null) JSpinner() else JSpinner(model)).apply(block)
fun <T> rootList(model: ListModel<T>? = null, array: Array<T>? = null, vector: Vector<T>? = null, block: JList<T>.() -> Unit): JList<T> = when {
model != null -> JList(model)
array != null -> JList(array)
vector != null -> JList(vector)
else -> JList()
}.apply(block)
fun rootTable(
model: TableModel? = null,
columnModel: TableColumnModel? = null,
selectionModel: ListSelectionModel? = null,
rows: Int = -1,
cols: Int = -1,
vecRowData: Vector<out Vector<*>>? = null,
vecColumnNames: Vector<*>? = null,
arrayRowData: Array<Array<*>>? = null,
arrayColumnNames: Array<*>? = null,
block: JTable.() -> Unit
): JTable = when {
model != null -> JTable(model, columnModel, selectionModel)
rows != -1 && cols != -1 -> JTable(rows, cols)
vecRowData != null && vecColumnNames != null -> JTable(vecRowData, vecColumnNames)
arrayRowData != null && arrayColumnNames != null -> JTable(arrayRowData, arrayColumnNames)
else -> JTable()
}.apply(block)
fun rootTree(
model: TreeModel? = null, node: TreeNode? = null, array: Array<*>? = null, vector: Vector<*>? = null, hashtable: Hashtable<*, *>? = null, block: JTree.() -> Unit
): JTree = when {
model != null -> JTree(model)
node != null -> JTree(node)
array != null -> JTree(array)
vector != null -> JTree(vector)
hashtable != null -> JTree(hashtable)
else -> JTree()
}.apply(block)
fun rootProgress(orient: Int = JProgressBar.HORIZONTAL, min: Int = 0, max: Int = 100, block: JProgressBar.() -> Unit): JProgressBar = JProgressBar(orient, min, max).apply(block)
fun rootScrollbar(orientation: Int = JScrollBar.VERTICAL, value: Int = 0, extent: Int = 10, min: Int = 0, max: Int = 100, block: JScrollBar.() -> Unit): JScrollBar = JScrollBar(orientation, value, extent, min, max).apply(block)
fun rootSeparator(orientation: Int = JSeparator.HORIZONTAL, block: JSeparator.() -> Unit): JSeparator = JSeparator(orientation).apply(block)
fun rootSlider(orientation: Int = JSlider.HORIZONTAL, min: Int = 0, max: Int = 100, value: Int = 0, block: JSlider.() -> Unit): JSlider = JSlider(orientation, min, max, value).apply(block)
fun rootBox(axis: Int = 0, block: Box.() -> Unit): Box = Box(axis).apply(block)
fun rootImage(data: ByteArray? = null, img: Image? = null, filename: String? = null, location: URL? = null, block: StretchIcon.() -> Unit): StretchIcon = when {
data != null -> StretchIcon(imageData = data)
img != null -> StretchIcon(image = img)
filename != null -> StretchIcon(filename = filename)
location != null -> StretchIcon(location = location)
else -> throw IllegalArgumentException("All image sources are empty.")
}.apply(block)
fun rootSvg(uri: URI? = null, file: File? = null, inputStream: InputStream? = null, block: JSVGCanvas.() -> Unit): JSVGCanvas {
val canvas = JSVGCanvas()
when{
file != null -> canvas.uri = file.toURI().toString()
else -> {
val parser = XMLResourceDescriptor.getXMLParserClassName()
val factory = SAXSVGDocumentFactory(parser)
canvas.svgDocument = when{
uri != null -> factory.createSVGDocument(uri.toString())
inputStream != null -> factory.createSVGDocument("", inputStream)
else -> throw IllegalArgumentException("All image sources are empty.")
}
}
}
canvas.apply(block)
return canvas
}
inline fun <reified T : Component> rootCustom(vararg params: Any, block: T.() -> Unit): T = newClassInstance<T>(*params).apply(block)
fun <T : Component> rootComp(comp: T, block: T.() -> Unit): T = comp.apply(block)
| 0 | Kotlin | 0 | 2 | 3f5ea19ea036e3c0a5cddb54dc172d7dab9da04c | 6,454 | common-swing | MIT License |
app/src/main/java/io/sinzak/android/remote/dataclass/response/chat/ChatRoomCheckResponse.kt | SINZAK | 567,559,091 | false | {"Kotlin": 482864} | package io.sinzak.android.remote.dataclass.response.chat
import com.google.gson.annotations.SerializedName
import io.sinzak.android.remote.dataclass.CResponse
data class ChatRoomCheckResponse(
@SerializedName("data") val data : RoomCheck? = null
) :CResponse() {
data class RoomCheck(
@SerializedName("roomUuid") val uuid : String? = null,
@SerializedName("exist") val exist : Boolean
)
}
| 0 | Kotlin | 0 | 3 | 3467e8ee8afeb6b91b51f3a454f7010bc717c436 | 419 | sinzak-android | MIT License |
common-ui/src/main/java/com/yuriy/openradio/shared/view/dialog/BaseAddEditStationDialog.kt | ChernyshovYuriy | 679,720,363 | false | {"Kotlin": 877885, "Java": 3552} | /*
* Copyright 2017-2022 The "Open Radio" Project. Author: <NAME>
*
* 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.yuriy.openradio.shared.view.dialog
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.Spinner
import com.yuriy.openradio.shared.R
import com.yuriy.openradio.shared.dependencies.DependencyRegistryCommonUi
import com.yuriy.openradio.shared.permission.PermissionChecker
import com.yuriy.openradio.shared.service.LocationService
import com.yuriy.openradio.shared.utils.AppLogger
import com.yuriy.openradio.shared.utils.AppUtils
import com.yuriy.openradio.shared.utils.ImageFilePath
import com.yuriy.openradio.shared.utils.IntentUtils
import com.yuriy.openradio.shared.utils.findButton
import com.yuriy.openradio.shared.utils.findCheckBox
import com.yuriy.openradio.shared.utils.findEditText
import com.yuriy.openradio.shared.utils.findLinearLayout
import com.yuriy.openradio.shared.utils.findTextView
import com.yuriy.openradio.shared.utils.findView
import com.yuriy.openradio.shared.utils.invisible
import com.yuriy.openradio.shared.utils.visible
import com.yuriy.openradio.shared.view.BaseDialogFragment
import com.yuriy.openradio.shared.view.SafeToast
import com.yuriy.openradio.shared.vo.RadioStationToAdd
/**
* Created by <NAME>
* At Android Studio
* On 12/20/14
* E-Mail: <EMAIL>
*
*
* Base dialog to use by Edit and Add dialogs.
*/
abstract class BaseAddEditStationDialog : BaseDialogFragment() {
protected lateinit var mPresenter: AddEditStationDialogPresenter
protected lateinit var mNameEdit: EditText
protected lateinit var mUrlEdit: EditText
protected lateinit var mCountriesSpinner: Spinner
protected lateinit var mGenresSpinner: Spinner
protected lateinit var mAddToFavCheckView: CheckBox
/**
* Text view for Image Url.
*/
private lateinit var mImageLocalUrlEdit: EditText
private lateinit var mProgressView: ProgressBar
private lateinit var mGenresAdapter: ArrayAdapter<CharSequence>
private lateinit var mCountriesAdapter: ArrayAdapter<String>
fun configureWith(presenter: AddEditStationDialogPresenter) {
mPresenter = presenter
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DependencyRegistryCommonUi.inject(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.dialog_add_edit_station, container, false)
val layoutParams = FrameLayout.LayoutParams(
(AppUtils.getShortestScreenSize(requireActivity()) * 0.8).toInt(),
ViewGroup.LayoutParams.WRAP_CONTENT
)
val root = view.findLinearLayout(R.id.add_edit_station_dialog_root)
root.layoutParams = layoutParams
val homePageEdit = view.findEditText(R.id.add_edit_station_home_page_edit)
mNameEdit = view.findEditText(R.id.add_edit_station_name_edit)
mUrlEdit = view.findEditText(R.id.add_edit_station_stream_url_edit)
mImageLocalUrlEdit = view.findEditText(R.id.add_edit_station_image_url_edit)
val imageWebUrlEdit = view.findEditText(R.id.add_edit_station_web_image_url_edit)
mProgressView = view.findViewById(R.id.add_edit_station_dialog_progress_bar_view)
val countries = ArrayList(LocationService.COUNTRY_CODE_TO_NAME.values)
countries.sort()
mCountriesSpinner = view.findViewById(R.id.add_edit_station_country_spin)
// Create an ArrayAdapter using the string array and a default spinner layout
mCountriesAdapter = ArrayAdapter(
requireActivity(),
android.R.layout.simple_spinner_item,
countries
)
// Specify the layout to use when the list of choices appears
mCountriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the mCountriesAdapter to the spinner
mCountriesSpinner.adapter = mCountriesAdapter
mGenresSpinner = view.findViewById(R.id.add_station_genre_spin)
// Create an ArrayAdapter using the string array and a default spinner layout
mGenresAdapter = ArrayAdapter(
requireActivity(),
android.R.layout.simple_spinner_item,
ArrayList<CharSequence>(AppUtils.predefinedCategories())
)
// Specify the layout to use when the list of choices appears
mGenresAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the mCountriesAdapter to the spinner
mGenresSpinner.adapter = mGenresAdapter
val launcher = IntentUtils.registerForActivityResultIntrl(
this, ::onActivityResultCallback
)
val imageUrlBtn = view.findButton(R.id.add_edit_station_image_browse_btn)
imageUrlBtn.setOnClickListener {
val galleryIntent = Intent()
galleryIntent.type = "image/*"
galleryIntent.action = Intent.ACTION_GET_CONTENT
// Chooser of filesystem options.
val chooserIntent = Intent.createChooser(galleryIntent, "Select Image")
launcher.launch(chooserIntent)
}
mAddToFavCheckView = view.findViewById(R.id.add_to_fav_check_view)
val addToSrvrCheckView = view.findCheckBox(R.id.add_to_srvr_check_view)
addToSrvrCheckView.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
toggleWebImageView(view, isChecked)
}
val addOrEditBtn = view.findButton(R.id.add_edit_station_dialog_add_btn_view)
addOrEditBtn.setOnClickListener {
mProgressView.visible()
processInputInternal(
mNameEdit.text.toString(),
mUrlEdit.text.toString(),
mImageLocalUrlEdit.text.toString(),
imageWebUrlEdit.text.toString(),
homePageEdit.text.toString(),
mGenresSpinner.selectedItem.toString(),
mCountriesSpinner.selectedItem.toString(),
mAddToFavCheckView.isChecked,
addToSrvrCheckView.isChecked
)
}
val cancelBtn = view.findButton(R.id.add_edit_station_dialog_cancel_btn_view)
cancelBtn.setOnClickListener { dialog?.dismiss() }
mProgressView.invisible()
return view
}
override fun onResume() {
super.onResume()
val context: Activity? = activity
if (!PermissionChecker.isExternalStorageGranted(context!!)) {
PermissionChecker.requestExternalStoragePermission(
context, requireView().findView(R.id.dialog_add_edit_root_layout)
)
}
}
override fun onDestroyView() {
super.onDestroyView()
mProgressView.invisible()
}
protected fun onSuccess(message: String) {
mProgressView.invisible()
SafeToast.showAnyThread(context, message)
dialog?.dismiss()
}
protected fun onFailure(reason: String) {
mProgressView.invisible()
SafeToast.showAnyThread(context, reason)
}
private fun onActivityResultCallback(data: Intent?) {
val selectedImageUri = data?.data
if (selectedImageUri == null) {
AppLogger.e("Can not process image path, image uri is null")
return
}
val ctx = context
if (ctx == null) {
AppLogger.e("Can not process image path, context is null")
return
}
// MEDIA GALLERY
val selectedImagePath = ImageFilePath.getPath(ctx, selectedImageUri)
AppLogger.d("Image Path:$selectedImagePath")
if (selectedImagePath != AppUtils.EMPTY_STRING) {
mImageLocalUrlEdit.setText(selectedImagePath)
} else {
SafeToast.showAnyThread(ctx, ctx.getString(R.string.can_not_open_file))
}
}
/**
* Abstraction to handle action once input is processed.
*
* @param radioStationToAdd Data to add as radio station.
*/
protected abstract fun processInput(radioStationToAdd: RadioStationToAdd)
/**
* Return position of country in drop down list.
*
* @param country Country of the Radio Station.
* @return Position of country.
*/
fun getCountryPosition(country: String?): Int {
return mCountriesAdapter.getPosition(country)
}
/**
* Return position of genre in drop down list.
*
* @param genre Genre of the Radio Station.
* @return Position of Genre.
*/
fun getGenrePosition(genre: String?): Int {
return mGenresAdapter.getPosition(genre)
}
/**
* Processing provided input to perform appropriate actions on the data: add or edit Radio Station.
*
* @param name Name of the Radio Station.
* @param url Url of the Stream associated with Radio Station.
* @param imageLocalUrl Local Url of the Image associated with Radio Station.
* @param imageWebUrl Web Url of the Image associated with Radio Station.
* @param homePage Web Url of Radio Station's home page.
* @param genre Genre of the Radio Station.
* @param country Country of the Radio Station.
* @param addToFav Whether or not add radio station to favorites.
* @param addToServer Whether or not add radio station to the server.
*/
private fun processInputInternal(
name: String, url: String, imageLocalUrl: String,
imageWebUrl: String, homePage: String, genre: String,
country: String, addToFav: Boolean, addToServer: Boolean
) {
val rsToAdd = RadioStationToAdd(
name, url, imageLocalUrl, imageWebUrl, homePage, genre, country, addToFav, addToServer
)
processInput(rsToAdd)
}
private fun toggleWebImageView(view: View?, enabled: Boolean) {
if (view == null) {
return
}
val label = view.findTextView(R.id.add_edit_station_web_image_url_label)
val edit = view.findTextView(R.id.add_edit_station_web_image_url_edit)
label.isEnabled = enabled
edit.isEnabled = enabled
}
}
| 13 | Kotlin | 1 | 8 | 7cfe3b7e55228f14df5f85b8d993db32df771d42 | 11,102 | OpenRadio | Apache License 2.0 |
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/style/Palette.kt | Neckar-IT | 599,079,962 | false | null | /**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.style
import com.meistercharts.algorithms.painter.Color
import com.meistercharts.algorithms.painter.RgbaColor
import it.neckar.open.kotlin.lang.getModulo
/**
* Contains default colors that can be used if no colors are provided
*/
object Palette {
/**
* A "nice" gray that is used as default at a lot of places
*/
val defaultGray: Color = Color.rgb(115, 127, 133)
val primaryColors: List<RgbaColor> = listOf(
Color.rgb(0, 161, 229), //first
Color.rgb(0, 46, 70), //second
Color.rgb(159, 213, 216) //third
)
/**
* Returns the primary color for the given index (modulo)
*/
fun getPrimaryColor(index: Int): Color = primaryColors.getModulo(index)
val chartColors: List<RgbaColor> = listOf(
Color.rgb(0, 161, 229),
Color.rgb(0, 46, 70),
Color.rgb(159, 213, 216),
Color.rgb(0, 104, 150),
Color.rgb(118, 199, 238),
Color.rgb(59, 145, 129)
)
/**
* Returns a chart color for the given index (modulo)
*/
fun getChartColor(index: Int): Color = chartColors.getModulo(index)
/** 'green'; could also be used for an OK-state */
val stateSuperior: RgbaColor = Color.rgb(146, 194, 89)
/** 'blue' */
val stateNormal: RgbaColor = Color.rgb(0, 161, 229)
/** 'yellow' */
val stateWarning: RgbaColor = Color.rgb(243, 197, 0)
/** 'orange' */
val stateCritical: RgbaColor = Color.rgb(241, 132, 34)
/** 'red' */
val stateError: RgbaColor = Color.rgb(230, 44, 86)
/** 'dark blue'; could also be used for an unknown-state */
val stateOffline: RgbaColor = Color.rgb(0, 46, 70)
/**
* Contains all state colors
*/
val stateColors: List<RgbaColor> = listOf(stateSuperior, stateNormal, stateWarning, stateCritical, stateError, stateOffline)
/**
* Contains all palettes
*/
val all: List<List<RgbaColor>> = listOf(primaryColors, chartColors, stateColors)
}
| 3 | null | 3 | 5 | ed849503e845b9d603598e8d379f6525a7a92ee2 | 2,500 | meistercharts | Apache License 2.0 |
analysis/analysis-api/testData/components/resolver/singleByPsi/kDoc/qualified/callables/notImported/privateFunctionFromClass.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // FILE: Foo.kt
package foo
class Foo {
private fun foo() {}
}
// FILE: main.kt
package test
/**
* [foo.Foo.<caret>foo]
*/
fun usage() {}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 147 | kotlin | Apache License 2.0 |
common/src/main/kotlin/dev/ricky12awesome/resourcenodes/block/ExtractorBlock.kt | Ricky12Awesome | 629,865,482 | false | null | @file:Suppress("OVERRIDE_DEPRECATION")
package dev.ricky12awesome.resourcenodes.block
import dev.ricky12awesome.resourcenodes.ResourceNodes
import dev.ricky12awesome.resourcenodes.block.entity.BlockEntities
import dev.ricky12awesome.resourcenodes.block.entity.ExtractorBlockEntity
import dev.ricky12awesome.resourcenodes.tag.Tags
import net.minecraft.ChatFormatting
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.nbt.TagParser
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResult
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
import net.minecraft.world.level.LevelAccessor
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.EntityBlock
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.material.Material
import net.minecraft.world.level.storage.loot.LootContext
import net.minecraft.world.phys.BlockHitResult
import net.minecraft.world.level.block.Blocks as MCBlocks
class ExtractorBlock : Block(Properties.of(Material.METAL)), EntityBlock {
override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): ExtractorBlockEntity {
return ExtractorBlockEntity(blockPos, blockState)
}
override fun <T : BlockEntity?> getTicker(
level: Level,
blockState: BlockState,
blockEntityType: BlockEntityType<T>
): BlockEntityTicker<T>? {
if (blockEntityType != BlockEntities.EXTRACTOR_BLOCK_ENTITY.get()) {
return null
}
return BlockEntityTicker { level, pos, state, entity ->
(entity as ExtractorBlockEntity).tick(level, pos, state)
}
}
override fun use(
blockState: BlockState,
level: Level,
blockPos: BlockPos,
player: Player,
interactionHand: InteractionHand,
blockHitResult: BlockHitResult
): InteractionResult {
if (level.isClientSide) return InteractionResult.SUCCESS
val entity = level.getBlockEntity(blockPos) as ExtractorBlockEntity
player.displayClientMessage(
Component
.empty()
.append(Component.literal("T/R: ").withStyle(ChatFormatting.LIGHT_PURPLE))
.append(Component.literal("${entity.ticksPerResource}").withStyle(ChatFormatting.RED))
.append(Component.literal(" RF/T: ").withStyle(ChatFormatting.LIGHT_PURPLE))
.append(Component.literal("${entity.rfPerTick}").withStyle(ChatFormatting.RED))
.append(Component.literal(" Res: ").withStyle(ChatFormatting.LIGHT_PURPLE))
.append(Component.translatable(entity.resource.descriptionId).withStyle(ChatFormatting.AQUA))
.append(Component.literal(" Cnt: ").withStyle(ChatFormatting.LIGHT_PURPLE))
.append(Component.literal("${entity.items[0].count}").withStyle(ChatFormatting.RED)), true
)
return InteractionResult.SUCCESS
}
override fun onPlace(
blockState: BlockState,
level: Level,
blockPos: BlockPos,
blockState2: BlockState,
bl: Boolean
) {
val entity = level.getBlockEntity(blockPos) as? ExtractorBlockEntity ?: return
val node = blockPos
.adjacent()
.map(level::getBlockState)
.firstOrNull { it.isInTag(Tags.VALID_NODES) }
?: return
val block = node.block.registryName()?.toString() ?: return
val config = ResourceNodes.config.getExtractorBlockConfig(block) ?: return
val resourceId = ResourceLocation(config.resource.id)
val resourceItem = BuiltInRegistries.ITEM.get(resourceId)
val resource = ItemStack(resourceItem, 1)
resource.tag = try {
config.resource.nbt?.let(TagParser::parseTag)
} catch (e: Exception) {
null
}
entity.node = node.block.registryName()
entity.resource = resource
entity.capacity = config.rfCapacity
entity.rfPerTick = config.rfPerTick
entity.ticksPerResource = config.ticksPerResource
}
override fun getDrops(blockState: BlockState, builder: LootContext.Builder): MutableList<ItemStack> {
return mutableListOf(
ItemStack(Blocks.EXTRACTOR_BLOCK_ITEM.get(), 1)
)
}
override fun updateShape(
blockState: BlockState,
direction: Direction,
blockState2: BlockState,
levelAccessor: LevelAccessor,
blockPos: BlockPos,
blockPos2: BlockPos
): BlockState {
val entity = levelAccessor.getBlockEntity(blockPos) as? ExtractorBlockEntity
val node = entity?.node
val result = blockPos
.adjacent()
.map(levelAccessor::getBlockState)
.map { it.block.registryName() }
.any { it == node }
if (!result) {
return MCBlocks.AIR.defaultBlockState()
}
return super.updateShape(blockState, direction, blockState2, levelAccessor, blockPos, blockPos2)
}
} | 0 | Kotlin | 0 | 0 | f110c3fac9caee3ffd9953f58af66babd0793ec1 | 5,103 | ResourceNodes | MIT License |
src/test/kotlin/com/muhron/kotlinq/ReverseTest.kt | RyotaMurohoshi | 53,187,022 | false | null | package com.muhron.kotlinq
import org.junit.Assert
import org.junit.Test
import java.util.*
class ReverseTest {
@Test
fun test0() {
val result = sequenceOf(0, 1, 2).reverse().toList()
Assert.assertEquals(result, listOf(2, 1, 0))
}
@Test
fun test1() {
val result = emptySequence<Int>().reverse().toList()
Assert.assertEquals(result, emptyList<Int>())
}
@Test
fun testNoThrownException() {
exceptionSequence<Int>().reverse()
}
} | 1 | Kotlin | 0 | 5 | 1bb201d7032cdcc302f342bc771ab356f1d96db2 | 506 | KotLinq | MIT License |
tests/src/commonMain/kotlin/app/thelema/test/MainTest.kt | zeganstyl | 275,550,896 | false | null | /*
* Copyright 2020-2021 Anton Trushkov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.thelema.test
import app.thelema.app.APP
import app.thelema.ecs.Entity
import app.thelema.ecs.mainLoop
import app.thelema.g3d.mesh.BoxMesh
import app.thelema.g3d.mesh.boxMesh
import app.thelema.g3d.scene
import app.thelema.g3d.transformNode
import app.thelema.math.MATH
import app.thelema.shader.SimpleShader3D
import app.thelema.test.audio.SoundOggTest
import app.thelema.test.g3d.BoxMeshTest
import app.thelema.test.g3d.MeshCubeTest
import app.thelema.test.g3d.gltf.GLTFDamagedHelmetTest
import app.thelema.test.g3d.gltf.GLTFLoadMultithreaded
import app.thelema.test.g3d.gltf.GLTFRiggedFigureTest
import app.thelema.test.g3d.mesh.DebugMeshTest
import app.thelema.test.gl.MeshTest
import app.thelema.test.gl.ScreenQuadTest
import app.thelema.test.gl.TriangleBaseTest
import app.thelema.test.img.FrameBufferTest
import app.thelema.test.img.SkyboxBaseTest
import app.thelema.test.img.Texture2DTest
import app.thelema.test.phys.BoxShapeTest
import app.thelema.test.phys.TrimeshShapeTest
import app.thelema.test.shader.LogarithmicDepthBufferTest
import app.thelema.test.shader.node.*
import app.thelema.test.ui.UITest
class MainTest {
init {
SSAOTest().testMain()
}
}
| 6 | Kotlin | 4 | 32 | e7699bb0201856ed034738798078c5aac7e2bd9b | 1,798 | thelema-engine | Apache License 2.0 |
app/src/main/java/digital/lamp/dagger_test/data/Dummy.kt | amaljofy | 248,206,587 | false | null | package digital.lamp.dagger_test.data
/**
* Created by Amal Jofy Dept. on 18,March,2020
*/
data class Dummy(val name:String) | 0 | Kotlin | 0 | 1 | e606b55696e428c62cc960128b41483c184b9867 | 127 | NewsList-Part-1 | MIT License |
src/main/kotlin/com/katanox/tabour/integration/sqs/config/SqsConfiguration.kt | katanox | 375,699,718 | false | null | package com.katanox.tabour.integration.sqs.config
import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.sqs.AmazonSQSAsync
import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cloud.aws.messaging.config.annotation.EnableSqs
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
@Configuration(proxyBeanMethods = false)
@EnableSqs
class SqsConfiguration(@Autowired val sqsProperties: SqsProperties) {
@Bean
@Primary
fun amazonSQSAsync(): AmazonSQSAsync {
return AmazonSQSAsyncClientBuilder.standard()
.withCredentials(credentialsProvider())
.withRegion(sqsProperties.region)
.build()
}
@Bean
fun credentialsProvider(): AWSCredentialsProvider {
return AWSStaticCredentialsProvider(
BasicAWSCredentials(sqsProperties.accessKey, sqsProperties.secretKey)
)
}
@Bean
fun queueMessagingTemplate(): QueueMessagingTemplate {
return QueueMessagingTemplate(amazonSQSAsync())
}
}
| 16 | Kotlin | 0 | 6 | b2d96b8e9fa055fd9a403005363b6344914310be | 1,402 | tabour | Apache License 2.0 |
app/src/main/java/xyz/tberghuis/floatingtimer/viewmodels/StopwatchScreenVm.kt | tberghuis | 500,632,576 | false | {"Kotlin": 126369} | package xyz.tberghuis.floatingtimer.viewmodels
import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import xyz.tberghuis.floatingtimer.DEFAULT_HALO_COLOR
import xyz.tberghuis.floatingtimer.MainApplication
import xyz.tberghuis.floatingtimer.data.SavedStopwatch
import xyz.tberghuis.floatingtimer.provideDatabase
import xyz.tberghuis.floatingtimer.providePreferencesRepository
class StopwatchScreenVm(
private val application: Application,
) : AndroidViewModel(application) {
private val savedStopwatchDao = application.provideDatabase().savedStopwatchDao()
var showDeleteDialog by mutableStateOf<SavedStopwatch?>(null)
private val preferencesRepository = application.providePreferencesRepository()
val premiumVmc = PremiumVmc(application, viewModelScope)
private val boundFloatingService = (application as MainApplication).boundFloatingService
var haloColor by mutableStateOf(DEFAULT_HALO_COLOR)
init {
viewModelScope.launch {
preferencesRepository.haloColourFlow.collect {
haloColor = it
}
}
}
fun savedStopwatchFlow(): Flow<List<SavedStopwatch>> {
return savedStopwatchDao.getAll()
}
fun savedStopwatchClick(timer: SavedStopwatch) {
addStopwatch(Color(timer.timerColor))
}
private fun addStopwatch(haloColor: Color) {
viewModelScope.launch {
if (shouldShowPremiumDialogMultipleTimers(application)) {
premiumVmc.showPurchaseDialog = true
return@launch
}
boundFloatingService.provideFloatingService().overlayController.addStopwatch(
haloColor
)
}
}
fun stopwatchButtonClick() {
addStopwatch(haloColor)
}
fun deleteSavedStopwatch(timer: SavedStopwatch) {
viewModelScope.launch(IO) {
savedStopwatchDao.delete(timer)
}
}
fun addToSaved() {
val timer = SavedStopwatch(
timerShape = "circle",
timerColor = haloColor.toArgb(),
)
viewModelScope.launch(IO) {
savedStopwatchDao.insertAll(timer)
}
}
} | 16 | Kotlin | 5 | 60 | 713c1bb2bd89085aaa21943854581dbd718a27d2 | 2,373 | FloatingCountdownTimer | MIT License |
data/src/main/java/com/example/data/remote/model/ConversationGroupRemote.kt | mourchidimfoumby | 726,650,487 | false | {"Kotlin": 108126} | package com.example.data.remote.model
import com.example.data.model.Message
import com.example.data.model.User
data class ConversationGroupRemote(
var id: String = "",
val listInterlocutors: MutableList<User>,
var messages: List<Message>? = null,
var title: String = "",
)
| 9 | Kotlin | 0 | 0 | 7ba59f9a3806a76a57eb0dbb0b2262c177e891c4 | 291 | studentchat | Apache License 2.0 |
app/src/main/java/com/capstone/gometry/ui/auth/AuthActivity.kt | herdianurdin | 580,187,239 | false | null | package com.capstone.gometry.ui.auth
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.capstone.gometry.R
import com.capstone.gometry.databinding.ActivityAuthBinding
import com.capstone.gometry.ui.main.MainActivity
import com.capstone.gometry.utils.MessageUtility.showToast
import com.capstone.gometry.utils.viewBinding
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.material.button.MaterialButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class AuthActivity : AppCompatActivity() {
private val binding by viewBinding(ActivityAuthBinding::inflate)
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var btnSignInWithGoogle: MaterialButton
private var resultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
try {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
val account = task.getResult(ApiException::class.java)!!
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) { showErrorOccurred() }
} else {
btnSignInWithGoogle.isEnabled = true
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
supportActionBar?.hide()
val googleSignOptions = GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, googleSignOptions)
firebaseAuth = Firebase.auth
btnSignInWithGoogle = binding.btnSignInWithGoogle
btnSignInWithGoogle.setOnClickListener { signInWithGoogle() }
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
lifecycleScope.launchWhenResumed {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this@AuthActivity) { task ->
val currentUser = firebaseAuth.currentUser
if (task.isSuccessful && currentUser != null) {
showToast(this@AuthActivity, getString(R.string.success_sign_in))
Intent(this@AuthActivity, MainActivity::class.java).also {
startActivity(it)
finish()
}
} else showErrorOccurred()
}
}
}
private fun signInWithGoogle() {
btnSignInWithGoogle.isEnabled = false
val signInIntent = googleSignInClient.signInIntent
resultLauncher.launch(signInIntent)
}
private fun showErrorOccurred() {
showToast(this@AuthActivity, getString(R.string.error_sign_in))
btnSignInWithGoogle.isEnabled = true
}
} | 0 | Kotlin | 0 | 0 | 541957635bff1bab59136bc88bc6b6dfa34b03b7 | 3,658 | gometry | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.