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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
airsync-api/src/main/java/ffc/airsync/api/dao/Es.kt | porntipa | 125,967,174 | true | {"Kotlin": 89876, "Java": 34607} | /*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.airsync.api.dao
import org.elasticsearch.action.delete.DeleteResponse
import org.elasticsearch.action.get.GetResponse
import org.elasticsearch.action.index.IndexResponse
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.xcontent.XContentType
fun TransportClient.insert(index: String, type: String, id: String, json: String): IndexResponse {
return this
.prepareIndex(index, type, id)
.setSource(json, XContentType.JSON)
.get()
}
fun TransportClient.get(index: String, type: String, id: String): GetResponse {
return this
.prepareGet(index, type, id)
.get()
}
fun TransportClient.delete(index: String, type: String, id: String): DeleteResponse {
return this
.prepareDelete(index, type, id)
.get()
}
fun TransportClient.search(index: String, type: String): SearchResponse {
return this
.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).get()
}
| 0 | Kotlin | 0 | 0 | 638796977b3d9f8253c8e237f9b91cfddabe1751 | 1,776 | airsync | Apache License 2.0 |
skulpt/src/main/java/org/skulpt/render/RenderPreviewPlaceholder.kt | timbrueggenthies | 461,235,201 | false | {"Kotlin": 29054} | package org.skulpt.render
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@Composable
fun RenderPreviewPlaceholder() {
Box(modifier = Modifier.fillMaxSize().background(Color.Blue)) {
Text(text = "Scene cannot be rendered in Preview", modifier = Modifier.align(Alignment.Center))
}
}
| 0 | Kotlin | 0 | 0 | 6e83bddfddcb98e3fc9e58730f6ec3afb639259d | 595 | skulpt | Apache License 2.0 |
resource-context/src/main/kotlin/com/mmolosay/resource/state/Failure.kt | mmolosay | 499,459,876 | false | {"Kotlin": 45539} | package com.mmolosay.resource.state
import com.mmolosay.resource.context.ResourceContext
/*
* Copyright 2022 <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.
*/
/**
* Represents failure, occurred while obtaining data.
*
* @param cause [Exception] caught.
*/
public class Failure(
public val cause: Exception,
) : AbstractResourceState<Nothing>(Element) {
public companion object Element : ResourceContext.Element
/**
* Produces instances of [Failure] state.
*/
public interface Producer {
/**
* Creates new [Failure] out of [cause] exception.
*/
public fun <V> failure(cause: Exception): ResourceState<V> =
Failure(cause)
/**
* Creates new [Failure] out of [cause] string.
* [Failure.cause] will be an [Exception] with [cause] for its message.
*/
public fun <V> failure(cause: String): ResourceState<V> =
Failure(Exception(cause))
}
} | 0 | Kotlin | 0 | 7 | 6ef31468c741e4a0adacd51aceb12d452aefd7ac | 1,498 | Resource | Apache License 2.0 |
cogboard-app/src/main/kotlin/com/cognifide/cogboard/widget/type/zabbix/ZabbixWidget.kt | wttech | 199,830,591 | false | {"JavaScript": 338125, "Kotlin": 178733, "HTML": 2154, "Shell": 951, "Dockerfile": 433} | package com.cognifide.cogboard.widget.type.zabbix
import com.cognifide.cogboard.config.service.BoardsConfigService
import com.cognifide.cogboard.http.auth.AuthenticationType
import com.cognifide.cogboard.widget.AsyncWidget
import com.cognifide.cogboard.widget.Widget
import io.vertx.core.Vertx
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.Logger
import io.vertx.core.logging.LoggerFactory
import kotlin.math.roundToLong
import com.cognifide.cogboard.CogboardConstants.Props
class ZabbixWidget(
vertx: Vertx,
config: JsonObject,
serv: BoardsConfigService
) : AsyncWidget(vertx, config, serv) {
private val selectedMetric: String = config.getString(METRIC, "")
private val host: String = config.getString(HOST, "")
private val maxValue: Int = config.getInteger(MAX_VALUE, 0)
private val range: JsonArray = config.getJsonArray(RANGE, JsonArray())
override fun authenticationTypes(): Set<AuthenticationType> {
return setOf(AuthenticationType.NONE)
}
override fun updateState() {
when {
publicUrl.isBlank() -> sendConfigurationError("Endpoint URL is blank.")
authorizationToken.containsKey(publicUrl) -> fetchItemData()
else -> fetchAuthorizationToken()
}
}
private fun fetchAuthorizationToken() {
val body = attachCredentialsToBody()
httpPost(publicUrl, body)
}
private fun attachCredentialsToBody(): JsonObject {
val credentials = JsonObject()
.put(Props.USER, user)
.put(Props.PASSWORD, <PASSWORD>)
return prepareRequestBody(USER_LOGIN, credentials)
}
override fun handleResponse(responseBody: JsonObject) {
val result = extractResult(responseBody)
when {
hasResponseData(result) -> sendUpdate(result)
isAuthorized(result) -> fetchItemData()
hasError(responseBody) -> sendAuthorizationError(responseBody)
else -> {
saveToken(result.toString())
fetchItemData()
}
}
}
private fun extractResult(responseBody: JsonObject): Any {
val body = responseBody.getString(BODY) ?: "{}"
val value = JsonObject(body)
return value.getValue(RESULT, "")
}
private fun hasResponseData(result: Any) = result.toString().contains("key_")
private fun sendUpdate(result: Any) {
val responseParams = result as JsonArray
val lastValue = responseParams.extractValue(LAST_VALUE)
val state = JsonObject()
.put(LAST_VALUE, lastValue)
.put(IS_EXPANDED_CONTENT, hasExpandedContent(responseParams.extractValue(NAME)))
.put(NAME, responseParams.extractValue(NAME))
.put(HISTORY, modifyHistory(responseParams))
.put(Props.WIDGET_STATUS, getStatusResponse(lastValue))
send(state)
}
private fun hasExpandedContent(name: String): Boolean {
return name != "System uptime"
}
private fun modifyHistory(responseParams: JsonArray): JsonObject {
val history = fetchHistoryFromContent()
val lastUpdate = responseParams.extractValue(LAST_CLOCK).toLong()
val filteredHistory = history.filter { it.key.toLong() > lastUpdate.minus(HOUR_IN_MILLS) }
val lastValue = responseParams.extractValue(LAST_VALUE)
return JsonObject(filteredHistory).mergeIn(JsonObject().put(lastUpdate.toString(), lastValue), true)
}
private fun fetchHistoryFromContent(): Map<String, Any> {
val widgetId = config.getString(Props.ID)
val content = boardService.getContent(widgetId)
return content.getJsonObject(HISTORY, JsonObject()).map
}
private fun getStatusResponse(lastValue: String): Widget.Status {
val convertedValue = lastValue.toFloat().roundToLong()
return when {
metricHasMaxValue() -> status(convertedValue.convertToPercentage(maxValue), range)
metricHasProgress() -> status(convertedValue, range)
else -> Widget.Status.NONE
}
}
private fun metricHasMaxValue() = metricHasProgress() &&
METRICS_WITH_MAX_VALUE.contains(selectedMetric)
private fun metricHasProgress() = METRICS_WITH_PROGRESS.contains(selectedMetric)
private fun isAuthorized(result: Any) =
authorizationToken.containsKey(publicUrl) && !result.toString().contains(selectedMetric)
private fun hasError(responseBody: JsonObject) =
JsonObject(responseBody.getString(BODY)).containsKey(ERROR)
private fun sendAuthorizationError(responseBody: JsonObject) {
val body = JsonObject(responseBody.getString(BODY))
val error = JsonObject(body.getValue(ERROR).toString())
val errorMessage = error.getString("message")
val errorCause = error.getString("data")
LOGGER.error("Error message: $errorMessage; Cause: $errorCause")
send(JsonObject()
.put(Props.ERROR_MESSAGE, errorMessage)
.put(Props.ERROR_CAUSE, errorCause))
}
private fun saveToken(token: String) {
authorizationToken[publicUrl] = token
}
private fun fetchItemData() {
val bodyToSend = prepareRequestBody(ITEM_GET, prepareParams(), authorizationToken[publicUrl])
httpPost(publicUrl, bodyToSend)
}
private fun JsonArray.extractValue(param: String): String =
(this.list[0] as LinkedHashMap<*, *>)[param] as String
private fun prepareRequestBody(method: String, params: JsonObject, auth: String? = null): JsonObject {
val authVal = if (auth == null) {
null
} else {
"\"$auth\""
}
return JsonObject(
"""
{
"jsonrpc": "2.0",
"method": "$method",
"params": $params,
"id": 1,
"auth": $authVal
}
"""
)
}
private fun prepareParams(): JsonObject {
return JsonObject(
"""
{
"filter": {
"host": [
"$host"
]
},
"search": {
"key_": "$selectedMetric"
},
"sortfield": "name"
}
"""
)
}
companion object {
private const val METRIC = "selectedZabbixMetric"
private const val HOST = "host"
private const val MAX_VALUE = "maxValue"
private const val RANGE = "range"
private const val USER_LOGIN = "user.login"
private const val ITEM_GET = "item.get"
private const val ERROR = "error"
private const val RESULT = "result"
private const val LAST_VALUE = "lastvalue"
private const val IS_EXPANDED_CONTENT = "isExpandedContent"
private const val LAST_CLOCK = "lastclock"
private const val NAME = "name"
private const val BODY = "body"
private const val HISTORY = "history"
private const val HOUR_IN_MILLS = 3600000L
val authorizationToken = hashMapOf<String, String>()
val METRICS_WITH_PROGRESS = setOf(
"system.cpu.util[,idle]",
"system.swap.size[,used]",
"vm.memory.size[available]",
"vfs.fs.size[/,used]",
"jmx[\\\"java.lang:type=Memory\\\",\\\"HeapMemoryUsage.used\\\"]")
val METRICS_WITH_MAX_VALUE = setOf(
"system.swap.size[,used]",
"vm.memory.size[available]",
"vfs.fs.size[/,used]",
"jmx[\\\"java.lang:type=Memory\\\",\\\"HeapMemoryUsage.used\\\"]")
val LOGGER: Logger = LoggerFactory.getLogger(ZabbixWidget::class.java)
}
}
| 56 | JavaScript | 9 | 15 | fc2e392bc072ea5738b6172a5b1f01609b4e6f13 | 7,985 | cogboard | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/util/view/BottomSheetExtensions.kt | nekomangaorg | 182,704,531 | false | {"Kotlin": 3442643} | package eu.kanade.tachiyomi.util.view
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_SETTLING
fun BottomSheetBehavior<*>.hide() {
state = STATE_HIDDEN
}
fun BottomSheetBehavior<*>.collapse() {
state = STATE_COLLAPSED
}
fun BottomSheetBehavior<*>.expand() {
state = STATE_EXPANDED
}
fun BottomSheetBehavior<*>?.isExpanded() = this?.state == STATE_EXPANDED
fun BottomSheetBehavior<*>?.isSettling() = this?.state == STATE_SETTLING
fun BottomSheetBehavior<*>?.isCollapsed() = this?.state == STATE_COLLAPSED
fun BottomSheetBehavior<*>?.isHidden() = this?.state == STATE_HIDDEN
| 83 | Kotlin | 119 | 2,261 | 3e0f16dd125e6d173e29defa7fcb62410358239d | 930 | Neko | Apache License 2.0 |
core/src/test/java/com/ebnrdwan/core/data/error/manager/ErrorManagerTest.kt | ebnrdwan | 236,335,124 | false | null | package com.ebnrdwan.core.data.error.manager
import com.ebnrdwan.core.data.error.Error
import com.ebnrdwan.core.data.error.mapper.ErrorMapper
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class ErrorManagerTest {
lateinit var mapper: ErrorMapper
lateinit var manager: ErrorManager
@Before
fun setUp() {
mapper = ErrorMapper()
manager = ErrorManager(mapper)
}
@Test
fun getError() {
assertEquals(manager.getError(TypeCastException()).message, Error().message)
}
} | 0 | Kotlin | 1 | 1 | 9090b4b9a1f6d6ee7541b86bc9610e97bad403fa | 556 | NY-Times | Apache License 2.0 |
src/main/kotlin/com/alongo/discordbot/domain/messagehandlers/qr/QrDecodeMessageHandler.kt | alongotv | 521,663,361 | false | {"Kotlin": 47457, "Dockerfile": 315} | package com.alongo.discordbot.domain.messagehandlers.qr
import com.alongo.discordbot.domain.messagehandlers.BaseMessageHandler
import com.alongo.discordbot.domain.usecase.ResolveQrCodeUseCase
import com.alongo.discordbot.utils.FileUtils
import com.google.zxing.NotFoundException
import dev.kord.core.behavior.reply
import dev.kord.core.entity.Attachment
import dev.kord.core.event.message.MessageCreateEvent
class QrDecodeMessageHandler(
private val resolveQrCodeUseCase: ResolveQrCodeUseCase
) : BaseMessageHandler() {
override suspend fun handle(command: String, event: MessageCreateEvent) {
val senderUsername = event.message.author?.mention ?: "User"
val messageAttachments = event.message.attachments
if (messageAttachments.size != 1 || !messageAttachments.first().isImage) {
event.message.reply {
content = "$senderUsername, please attach exactly one image file."
}
return
}
val fileToResolve: Attachment = messageAttachments.first()
val inputStream = FileUtils.downloadFile(fileToResolve.url)
try {
val resolvedQrCodeText = resolveQrCodeUseCase(inputStream)
event.message.reply {
content =
"$senderUsername, the bot has found \"$resolvedQrCodeText\" encoded in your picture."
}
} catch (e: NotFoundException) {
println(e.message)
event.message.reply {
content = "$senderUsername, the bot was unable to find any QR codes in the provided picture"
}
}
}
}
| 0 | Kotlin | 1 | 3 | fb65c32e8c8fefc582b314dc3622bff6de4ad267 | 1,626 | Stroggs-Discord-Bot | MIT License |
src/main/kotlin/com/refinedmods/refinedstorage/container/transfer/InsertionResultType.kt | thinkslynk | 290,596,653 | true | {"Kotlin": 695976, "Shell": 456} | package com.refinedmods.refinedstorage.container.transfer
internal enum class InsertionResultType {
CONTINUE_IF_POSSIBLE, STOP
} | 1 | Kotlin | 0 | 2 | c92afa51af0e5e08caded00882f91171652a89e3 | 133 | refinedstorage | MIT License |
core/src/io/github/tozydev/patek/nbt/ReadWriteNBTs.kt | tozydev | 773,615,401 | false | {"Kotlin": 128971, "Java": 2674} | package io.github.tozydev.patek.nbt
import io.github.tozydev.patek.nbt.iface.ReadWriteNBT
import org.bukkit.inventory.ItemStack
import java.util.*
/**
* Sets the [value] associated with a given [key] in the NBT compound.
*
* @throws IllegalArgumentException if the value is of unsupported NBT type
* @see ReadWriteNBT
*/
operator fun ReadWriteNBT.set(
key: String,
value: Any?,
) = when (value) {
is String -> setString(key, value)
is Int -> setInteger(key, value)
is Double -> setDouble(key, value)
is Byte -> setByte(key, value)
is Short -> setShort(key, value)
is Long -> setLong(key, value)
is Float -> setFloat(key, value)
is ByteArray -> setByteArray(key, value)
is IntArray -> setIntArray(key, value)
is LongArray -> setLongArray(key, value)
is Boolean -> setBoolean(key, value)
is ItemStack -> setItemStack(key, value)
is UUID -> setUUID(key, value)
else -> throw IllegalArgumentException("Unsupported NBT type: ${value?.javaClass?.simpleName}")
}
/**
* Removes a [key] from the NBT compound.
*
* @see ReadWriteNBT.removeKey
*/
operator fun ReadWriteNBT.minusAssign(key: String) = removeKey(key)
| 0 | Kotlin | 0 | 1 | f5b0fd5ba40c51dd53934d3bb5b41052675fb205 | 1,180 | patek | MIT License |
app/src/main/java/com/dreamit/androidquiz/quizsolving/presenter/QuizSolvingPresenter.kt | mkAndroDev | 142,674,492 | false | null | package com.dreamit.androidquiz.quizsolving.presenter
import com.dreamit.androidquiz.data.quizSolve.QuizSolveRepository
import com.dreamit.androidquiz.quizsolving.QuizSolvingContract
import com.dreamit.androidquiz.quizsolving.model.QuizSolve
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class QuizSolvingPresenter(
private val quizSolveRepository: QuizSolveRepository,
private val view: QuizSolvingContract.View
) : QuizSolvingContract.Presenter {
override fun getQuizSolve(quizId: Long) {
quizSolveRepository.getQuizSolve(quizId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ quizSolve ->
view.showQuizSolving(quizSolve)
}, { error ->
view.showError(error.message.orEmpty())
})
}
override fun saveQuizSolve(quizSolve: QuizSolve) {
quizSolveRepository.saveQuizSolve(quizSolve)
}
override fun clearQuizSolve(quizSolve: QuizSolve) {
saveQuizSolve(quizSolve.apply {
userAnswers.clear()
})
}
} | 0 | Kotlin | 0 | 0 | eabf29df22080fcb6c4656b638ef1f6c5cc004f4 | 1,191 | AndroidQuiz | MIT License |
android/src/main/kotlin/dev/tabhishekpaul/notification_listener/NotificationUtils.kt | tabhishekpaul | 874,947,728 | false | {"Kotlin": 22122, "Dart": 5591} | package dev.tabhishekpaul.notification_listener
import android.app.Notification
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.RemoteInput
import dev.tabhishekpaul.notification_listener.models.Action
object NotificationUtils {
private val REPLY_KEYWORDS = arrayOf("reply", "android.intent.extra.text")
private const val INPUT_KEYWORD = "input"
fun getBitmapFromDrawable(drawable: Drawable): Bitmap {
val bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun getQuickReplyAction(notification: Notification, packageName: String): Action? {
val action = getNotificationAction(notification)
?: getWearReplyAction(notification)
return action?.let { Action(it, packageName, true) }
}
private fun getNotificationAction(notification: Notification): NotificationCompat.Action? {
for (i in 0 until NotificationCompat.getActionCount(notification)) {
val action = NotificationCompat.getAction(notification, i)
action?.remoteInputs?.forEach { input ->
if (isKnownReplyKey(input.resultKey)) return action
}
}
return null
}
private fun getWearReplyAction(notification: Notification): NotificationCompat.Action? {
val wearableExtender = NotificationCompat.WearableExtender(notification)
wearableExtender.actions.forEach { action ->
action.remoteInputs?.forEach { input ->
if (isKnownReplyKey(input.resultKey) || input.resultKey.contains(INPUT_KEYWORD, true)) {
return action
}
}
}
return null
}
private fun isKnownReplyKey(resultKey: String?): Boolean {
if (resultKey.isNullOrEmpty()) return false
return REPLY_KEYWORDS.any { resultKey.contains(it, ignoreCase = true) }
}
}
| 0 | Kotlin | 0 | 0 | 8188f2c7260bef77504cbd7ab443b7d6c1e5d803 | 2,338 | notification_listener | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/factory/CaseAccessFactory.kt | ministryofjustice | 515,276,548 | false | {"Kotlin": 8262155, "Shell": 15359, "Dockerfile": 1667, "Mustache": 383} | package uk.gov.justice.digital.hmpps.approvedpremisesapi.factory
import io.github.bluegroundltd.kfactory.Factory
import io.github.bluegroundltd.kfactory.Yielded
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.CaseAccess
import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomStringUpperCase
class CaseAccessFactory : Factory<CaseAccess> {
var crn: Yielded<String> = { randomStringUpperCase(10) }
var userExcluded: Yielded<Boolean> = { false }
var userRestricted: Yielded<Boolean> = { false }
var exclusionMessage: Yielded<String?> = { null }
var restrictionMessage: Yielded<String?> = { null }
fun withCrn(crn: String) = apply {
this.crn = { crn }
}
fun withUserExcluded(userExcluded: Boolean) = apply {
this.userExcluded = { userExcluded }
}
fun withUserRestricted(userRestricted: Boolean) = apply {
this.userRestricted = { userRestricted }
}
fun withExclusionMessage(exclusionMessage: String?) = apply {
this.exclusionMessage = { exclusionMessage }
}
fun withRestrictionMessage(restrictionMessage: String?) = apply {
this.restrictionMessage = { restrictionMessage }
}
override fun produce(): CaseAccess = CaseAccess(
crn = this.crn(),
userExcluded = this.userExcluded(),
userRestricted = this.userRestricted(),
exclusionMessage = this.exclusionMessage(),
restrictionMessage = this.restrictionMessage(),
)
}
| 26 | Kotlin | 1 | 5 | 51e95acef683f6c9a2c1b654b8a31e095b21e38f | 1,427 | hmpps-approved-premises-api | MIT License |
src/en/mangarockteam/src/eu/kanade/tachiyomi/extension/en/mangarockteam/MangaRockTeam.kt | komikku-app | 720,497,299 | false | {"Kotlin": 6775539, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.en.mangarockteam
import eu.kanade.tachiyomi.multisrc.madara.Madara
class MangaRockTeam : Madara("Manga Rock Team", "https://mangarockteam.com", "en")
| 22 | Kotlin | 8 | 97 | 7fc1d11ee314376fe0daa87755a7590a03bc11c0 | 190 | komikku-extensions | Apache License 2.0 |
EZRecipes/app/src/main/java/com/abhiek/ezrecipes/data/terms/MockTermsService.kt | Abhiek187 | 502,751,240 | false | {"Kotlin": 215379, "Ruby": 11396} | package com.abhiek.ezrecipes.data.terms
import com.abhiek.ezrecipes.data.models.RecipeError
import com.abhiek.ezrecipes.data.models.Term
import com.abhiek.ezrecipes.utils.Constants
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Response
// Send hardcoded recipe responses for tests
// Using an object to create a singleton to pass to the repository
object MockTermsService: TermsService {
var isSuccess = true // controls whether the mock API calls succeed or fail
private const val recipeErrorString =
"{\"error\":\"You are not authorized. Please read https://spoonacular.com/food-api/docs#Authentication\"}"
val recipeError =
RecipeError(error = "You are not authorized. Please read https://spoonacular.com/food-api/docs#Authentication")
override suspend fun getTerms(): Response<List<Term>> {
return if (isSuccess) {
Response.success(Constants.Mocks.TERMS)
} else {
Response.error(401, recipeErrorString.toResponseBody())
}
}
}
| 1 | Kotlin | 0 | 0 | 3eeaf0f07c8f349b70fe0375d2a17225dd018541 | 1,042 | ez-recipes-android | MIT License |
desktopApp/src/jvmMain/kotlin/eu/heha/ncfilerenamer/ui/MainViewModel.kt | sihamark | 737,350,096 | false | {"Kotlin": 30129} | package eu.heha.ncfilerenamer.ui
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.heha.ncfilerenamer.ViewModel
import eu.heha.ncfilerenamer.model.FileController
import io.github.aakira.napier.Napier
import kotlinx.coroutines.launch
import java.net.URI
class MainViewModel : ViewModel() {
private val fileController = FileController()
var fileState: FileState? by mutableStateOf(null)
private set
fun loadRoot() {
load()
}
fun load(resource: FileController.Resource) {
if (!resource.isDirectory) {
Napier.e("clicked, resource ${resource.ref}, which is not a directory")
return
}
load(resource.ref)
}
private fun load(ref: String? = null) {
Napier.e("Loading $ref")
viewModelScope.launch {
var actualRef = ref ?: "unknown"
try {
actualRef = ref ?: fileController.rootRef()
fileState = FileState.Loading(actualRef)
fileState = FileState.Files(actualRef, fileController.loadFileContent(actualRef))
} catch (e: Exception) {
Napier.e("Error loading $ref", e)
fileState = FileState.Error(actualRef, e.message ?: "Unknown error")
}
}
}
fun reload() {
val ref = fileState?.ref ?: return
load(ref)
}
fun navigateUp() {
val ref = fileState?.ref ?: return
val parent = URI(ref).resolve("..").toString()
load(parent)
}
sealed interface FileState {
val ref: String
data class Loading(override val ref: String) : FileState
data class Error(
override val ref: String,
val message: String
) : FileState
data class Files(
override val ref: String,
val content: FileController.ResourceContent
) : FileState
}
} | 0 | Kotlin | 0 | 0 | 266204b1b2ac578b34dbd8b010d228b84a0d4f82 | 2,001 | NextCloudPhotoRenamer | Apache License 2.0 |
core/src/main/kotlin/com/samples/verifier/internal/utils/ParseHelper.kt | vmishenev | 353,425,739 | true | {"Kotlin": 34423, "HTML": 1691} | package com.samples.verifier.internal.utils
import com.samples.verifier.Code
import com.samples.verifier.FileType
import com.samples.verifier.model.Attribute
import com.samples.verifier.model.ParseConfiguration
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.ast.Node
import com.vladsch.flexmark.util.data.MutableDataSet
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.io.File
import java.util.*
private val parseOptions = MutableDataSet()
private val htmlRenderer = HtmlRenderer.builder(parseOptions).build()
private val htmlParser = Parser.builder(parseOptions).build()
internal fun processHTMLFile(file: File, parseConfiguration: ParseConfiguration): List<Code> {
return processHTMLText(file.readText(), parseConfiguration, FileType.HTML)
}
internal fun processMarkdownFile(file: File, parseConfiguration: ParseConfiguration): List<Code> {
val node: Node = htmlParser.parse(file.readText())
val htmlText = htmlRenderer.render(node)
return processHTMLText(htmlText, parseConfiguration, FileType.MD)
}
private fun processHTMLText(text: String, parseConfiguration: ParseConfiguration, fileType: FileType): List<Code> {
val document = Jsoup.parse(text)
val snippets = mutableListOf<Code>()
val queue = LinkedList<Element>()
val codeFlags = if (fileType == FileType.MD) {
parseConfiguration.snippetFlags.map { "language-$it" }
} else parseConfiguration.snippetFlags
queue.addFirst(document.body())
with(parseConfiguration) {
while (queue.isNotEmpty()) {
val elem = queue.remove()
val attrs = elem.attributes().map { Attribute(it.key, it.value) }.toHashSet()
if (ignoreAttributes != null && attrs.intersect(ignoreAttributes!!).isNotEmpty())
continue
queue.addAll(elem.children())
if ((parseTags != null && (elem.tagName() !in parseTags!!)) ||
(parseTags == null && (elem.tagName() != "code") && fileType == FileType.MD)
) {
continue
}
if (elem.tagName() == "code") {
if (elem.classNames().intersect(codeFlags).isNotEmpty()) {
val code = elem.wholeText().trimIndent()
snippets.add(code)
}
} else {
if (elem.classNames().intersect(snippetFlags).isNotEmpty()) {
val code = elem.wholeText().trimIndent()
snippets.add(code)
}
}
}
}
return snippets
} | 0 | Kotlin | 0 | 0 | 2afcb374f091e67f502b22723f7ddc41cdb4eb3b | 2,434 | kotlin-samples-verifier | Apache License 2.0 |
shared/src/iosMain/kotlin/likco/likfit/services/stepscounter/StepsCounterServiceMock.kt | LikDan | 653,590,458 | false | null | package likco.likfit.services.stepscounter
import likco.likfit.services.StepsCounterService
import platform.posix.sleep
import kotlin.native.concurrent.TransferMode
import kotlin.native.concurrent.Worker
import kotlin.random.Random
actual object StepsCounterServiceNative {
private var stopped = true
actual fun start() {
if (!stopped) return
this.stopped = false
val worker = Worker.start()
worker.execute(TransferMode.SAFE, { this to worker }) {
while (!it.first.stopped) {
update(Random.nextInt(25))
sleep(5)
}
}
}
actual fun stop() {
this.stopped = true
}
actual fun update(steps: Int) = StepsCounterService.update(steps)
} | 0 | Kotlin | 0 | 0 | ab39c86e6380b8e7a5ad6975b986ef7f25660efd | 761 | LikFit | Apache License 2.0 |
feature/qr/src/main/java/com/prography/qr/LessonCertificationQrUiMachine.kt | prography-team8 | 799,143,036 | false | {"Kotlin": 459261} | package com.prography.qr
import NavigationEvent
import com.prography.qr.domain.GenerateGwasuwonQrUseCase
import com.prography.qr.domain.GenerateLessonCertificationQrUseCase
import com.prography.qr.domain.GenerateQrUseCase
import com.prography.usm.holder.UiStateMachine
import com.prography.usm.result.Result
import com.prography.usm.result.asResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.transform
/**
* Created by MyeongKi.
*/
class LessonCertificationQrUiMachine(
coroutineScope: CoroutineScope,
lessonId: Long,
navigateFlow: MutableSharedFlow<NavigationEvent>
) : UiStateMachine<
OnlyQrUiState,
OnlyQrMachineState,
LessonCertificationQrActionEvent,
LessonCertificationQrIntent>(coroutineScope) {
private val generateLessonCertificationQrUseCase = GenerateLessonCertificationQrUseCase(
generateGwasuwonQrUseCase = GenerateGwasuwonQrUseCase(
generateQrUseCase = GenerateQrUseCase()
)
)
override var machineInternalState: OnlyQrMachineState = OnlyQrMachineState()
private val popBackFlow = actionFlow
.filterIsInstance<LessonCertificationQrActionEvent.PopBack>()
.onEach {
navigateFlow.emit(NavigationEvent.PopBack)
}
private val generateQrFlow = actionFlow
.filterIsInstance<LessonCertificationQrActionEvent.GenerateQr>()
.transform { emitAll(generateLessonCertificationQrUseCase(lessonId).asResult()) }
.map {
when (it) {
is Result.Error -> {
machineInternalState
}
is Result.Loading -> {
machineInternalState
}
is Result.Success -> {
machineInternalState.copy(qr = it.data)
}
}
}
override val outerNotifyScenarioActionFlow = merge(
popBackFlow
)
init {
initMachine()
}
override fun mergeStateChangeScenarioActionsFlow(): Flow<OnlyQrMachineState> {
return generateQrFlow
}
}
| 0 | Kotlin | 0 | 0 | 964f14a6f1688b7c8e6f10a0f1ac45e831110d37 | 2,389 | gwasuwon-aos | Apache License 2.0 |
defitrack-common/src/main/java/io/defitrack/token/FungibleTokenWithAmount.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack.token
import java.math.BigDecimal
class FungibleTokenWithAmount(
val amount: BigDecimal?,
address: String,
name: String,
decimals: Int,
symbol: String,
logo: String?,
type: TokenType
) : FungibleToken(address, name, decimals, symbol, logo, type)
| 16 | Kotlin | 6 | 5 | e4640223e69c30f986b8b4238e026202b08a5548 | 297 | defi-hub | MIT License |
src/main/kotlin/com/github/malayP/decorations/block/machine/machine/BlastFurnace.kt | MalayPrime | 379,254,123 | false | null | package com.github.malayP.decorations.block.machine.machine
import com.github.malayP.decorations.modResourcesLocation
import com.github.malayP.decorations.register.AllTileEntity.blastFurnaceType
import com.github.zomb_676.fantasySoup.block.HorizonBlockWithTileEntity
import com.mojang.blaze3d.matrix.MatrixStack
import com.mojang.blaze3d.vertex.IVertexBuilder
import net.minecraft.block.BlockState
import net.minecraft.block.material.Material
import net.minecraft.client.renderer.IRenderTypeBuffer
import net.minecraft.client.renderer.RenderType
import net.minecraft.client.renderer.entity.model.EntityModel
import net.minecraft.client.renderer.model.Model
import net.minecraft.client.renderer.model.ModelRenderer
import net.minecraft.client.renderer.tileentity.TileEntityRenderer
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher
import net.minecraft.state.properties.BlockStateProperties
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.shapes.ISelectionContext
import net.minecraft.util.math.shapes.VoxelShape
import net.minecraft.util.math.vector.Vector3f
import net.minecraft.world.IBlockReader
class BlastFurnace : HorizonBlockWithTileEntity(Properties.create(Material.IRON)) {
companion object{
private val shape: VoxelShape = makeCuboidShape(0.0,0.0,0.0,16.0,16.0,16.0)
}
override fun createTileEntity(state: BlockState?, world: IBlockReader?): TileEntity = BlastFurnaceTileEntity()
override fun getCollisionShape(state: BlockState, reader: IBlockReader, pos: BlockPos): VoxelShape = shape
override fun getCollisionShape(
state: BlockState,
worldIn: IBlockReader,
pos: BlockPos,
context: ISelectionContext
): VoxelShape = shape
override fun getShape(
state: BlockState?,
worldIn: IBlockReader?,
pos: BlockPos?,
context: ISelectionContext?
): VoxelShape = shape
}
class BlastFurnaceTileEntity : TileEntity(blastFurnaceType.get()) {}
class BlastFurnaceTileEntityRender(dispatcher: TileEntityRendererDispatcher) :
TileEntityRenderer<BlastFurnaceTileEntity>(dispatcher) {
companion object {
val model = BlastFurnaceModel()
val texture: ResourceLocation= modResourcesLocation("textures/tile_entity/production/blast_furnace/blast_furnace.png")
}
override fun render(
tileEntityIn: BlastFurnaceTileEntity,
partialTicks: Float,
matrixStackIn: MatrixStack,
bufferIn: IRenderTypeBuffer,
combinedLightIn: Int,
combinedOverlayIn: Int,
) {
matrixStackIn.push()
val renderType = RenderType.getEntityTranslucent(texture)
val buffer = bufferIn.getBuffer(renderType)
matrixStackIn.scale(1f, -1f, -1f)
matrixStackIn.translate(0.5, -1.5, -0.5)
val f: Float =
if (tileEntityIn.world != null) tileEntityIn.blockState.get(BlockStateProperties.HORIZONTAL_FACING).horizontalAngle else 90f
matrixStackIn.rotate(Vector3f.YP.rotationDegrees(f))
model.render(matrixStackIn, buffer, combinedLightIn, combinedOverlayIn, 1f, 1f, 1f, 1f)
matrixStackIn.pop()
}
}
class BlastFurnaceModel : Model(RenderType::getEntitySolid) {
private val shell: ModelRenderer
private val fixed: ModelRenderer
private val base: ModelRenderer
private val bone2: ModelRenderer
private val bone3: ModelRenderer
private val bone4: ModelRenderer
private val bone5: ModelRenderer
private val bone: ModelRenderer
private val pipe: ModelRenderer
private val bone14: ModelRenderer
private val `in`: ModelRenderer
private val bone6: ModelRenderer
private val bone7: ModelRenderer
private val bone8: ModelRenderer
private val bone9: ModelRenderer
private val bone10: ModelRenderer
private val bone11: ModelRenderer
private val bone12: ModelRenderer
private val bone13: ModelRenderer
private val rotatable: ModelRenderer
private val draw: ModelRenderer
override fun render(
matrixStack: MatrixStack,
buffer: IVertexBuilder,
packedLight: Int,
packedOverlay: Int,
red: Float,
green: Float,
blue: Float,
alpha: Float
) {
shell.render(matrixStack, buffer, packedLight, packedOverlay)
}
fun setRotationAngle(modelRenderer: ModelRenderer, x: Float, y: Float, z: Float) {
modelRenderer.rotateAngleX = x
modelRenderer.rotateAngleY = y
modelRenderer.rotateAngleZ = z
}
init {
textureWidth = 128
textureHeight = 128
shell = ModelRenderer(this)
shell.setRotationPoint(0.0f, 16.0f, 0.0f)
fixed = ModelRenderer(this)
fixed.setRotationPoint(0.0f, 0.0f, 0.0f)
shell.addChild(fixed)
fixed.setTextureOffset(7, 25).addBox(-5.0f, -1.5f, -7.5f, 2.0f, 1.0f, 1.0f, 0.0f, false)
fixed.setTextureOffset(7, 19).addBox(3.0f, -1.5f, -7.5f, 2.0f, 1.0f, 1.0f, 0.0f, false)
fixed.setTextureOffset(69, 47).addBox(-7.0f, -8.0f, 6.0f, 14.0f, 7.0f, 2.0f, 0.0f, false)
base = ModelRenderer(this)
base.setRotationPoint(0.0f, 0.0f, 0.0f)
fixed.addChild(base)
base.setTextureOffset(0, 0).addBox(-8.0f, 6.0f, -8.0f, 16.0f, 2.0f, 16.0f, 0.0f, false)
base.setTextureOffset(0, 36).addBox(-6.0f, 5.0f, -7.0f, 12.0f, 1.0f, 12.0f, 0.0f, false)
base.setTextureOffset(0, 50).addBox(-8.0f, 0.0f, -7.0f, 2.0f, 6.0f, 15.0f, 0.0f, false)
base.setTextureOffset(77, 0).addBox(-6.0f, 0.0f, 8.0f, 12.0f, 6.0f, 0.0f, 0.0f, false)
base.setTextureOffset(74, 16).addBox(-6.0f, -0.1213f, 4.4645f, 12.0f, 4.0f, 1.0f, 0.0f, false)
base.setTextureOffset(34, 36).addBox(6.0f, 0.0f, -7.0f, 2.0f, 6.0f, 15.0f, 0.0f, false)
base.setTextureOffset(0, 19).addBox(-8.0f, -1.0f, -7.0f, 16.0f, 1.0f, 15.0f, 0.0f, false)
base.setTextureOffset(84, 7).addBox(-2.0f, -0.5f, -2.0f, 4.0f, 2.0f, 4.0f, 0.0f, false)
base.setTextureOffset(81, 66).addBox(-5.0f, -15.0f, 6.3284f, 10.0f, 14.0f, 1.0f, 0.0f, false)
base.setTextureOffset(0, 72).addBox(-5.0f, -15.0f, -5.5f, 10.0f, 14.0f, 1.0f, 0.0f, false)
base.setTextureOffset(58, 58).addBox(-6.4142f, -15.0f, -4.0858f, 1.0f, 14.0f, 10.0f, 0.0f, false)
base.setTextureOffset(35, 58).addBox(5.4142f, -15.0f, -4.0858f, 1.0f, 14.0f, 10.0f, 0.0f, false)
base.setTextureOffset(49, 0).addBox(-0.5858f, -14.75f, -4.62f, 6.0f, 1.0f, 11.0f, 0.0f, false)
base.setTextureOffset(54, 34).addBox(-5.4108f, -14.75f, -4.62f, 6.0f, 1.0f, 11.0f, 0.0f, false)
bone2 = ModelRenderer(this)
bone2.setRotationPoint(0.0f, 0.0f, 0.0f)
base.addChild(bone2)
setRotationAngle(bone2, 0.0f, -0.7854f, 0.0f)
bone2.setTextureOffset(44, 95).addBox(-0.3536f, -14.9f, -7.4246f, 2.0f, 14.0f, 1.0f, 0.0f, false)
bone3 = ModelRenderer(this)
bone3.setRotationPoint(0.0f, 0.0f, 0.0f)
base.addChild(bone3)
setRotationAngle(bone3, 0.0f, -2.3562f, 0.0f)
bone3.setTextureOffset(37, 95).addBox(-0.3536f, -14.9f, -8.7175f, 2.0f, 14.0f, 1.0f, 0.0f, false)
bone4 = ModelRenderer(this)
bone4.setRotationPoint(0.0f, 0.0f, 0.0f)
base.addChild(bone4)
setRotationAngle(bone4, 0.0f, 2.3562f, 0.0f)
bone4.setTextureOffset(7, 0).addBox(-1.6464f, -14.9f, -8.7175f, 2.0f, 14.0f, 1.0f, 0.0f, false)
bone5 = ModelRenderer(this)
bone5.setRotationPoint(0.0f, 0.0f, 0.0f)
base.addChild(bone5)
setRotationAngle(bone5, 0.0f, 0.7854f, 0.0f)
bone5.setTextureOffset(0, 0).addBox(-1.6464f, -14.9f, -7.4246f, 2.0f, 14.0f, 1.0f, 0.0f, false)
bone = ModelRenderer(this)
bone.setRotationPoint(0.0f, 0.0f, 0.0f)
base.addChild(bone)
setRotationAngle(bone, 0.7854f, 0.0f, 0.0f)
bone.setTextureOffset(74, 22).addBox(-6.0f, 5.8995f, 0.4142f, 12.0f, 4.0f, 1.0f, 0.0f, false)
pipe = ModelRenderer(this)
pipe.setRotationPoint(0.0f, 0.0f, 0.5f)
base.addChild(pipe)
pipe.setTextureOffset(5, 36).addBox(-5.0f, -18.0f, -7.5f, 1.0f, 9.0f, 1.0f, 0.0f, false)
pipe.setTextureOffset(0, 36).addBox(4.0f, -18.0f, -7.5f, 1.0f, 9.0f, 1.0f, 0.0f, false)
pipe.setTextureOffset(0, 25).addBox(-5.0f, -18.0f, -6.5f, 1.0f, 1.0f, 4.0f, 0.0f, false)
pipe.setTextureOffset(0, 19).addBox(4.0f, -18.0f, -6.5f, 1.0f, 1.0f, 4.0f, 0.0f, false)
pipe.setTextureOffset(0, 31).addBox(-5.0f, -9.0f, -6.5f, 1.0f, 1.0f, 1.0f, 0.0f, false)
pipe.setTextureOffset(10, 30).addBox(4.0f, -9.0f, -6.5f, 1.0f, 1.0f, 1.0f, 0.0f, false)
pipe.setTextureOffset(49, 13).addBox(-8.0f, -9.0f, -7.5f, 16.0f, 1.0f, 1.0f, 0.0f, false)
pipe.setTextureOffset(78, 28).addBox(7.0f, -3.0f, -1.5f, 1.0f, 1.0f, 8.0f, 0.0f, false)
pipe.setTextureOffset(48, 58).addBox(-8.0f, -3.0f, -1.5f, 1.0f, 1.0f, 8.0f, 0.0f, false)
bone14 = ModelRenderer(this)
bone14.setRotationPoint(0.0f, 0.0f, 0.0f)
pipe.addChild(bone14)
setRotationAngle(bone14, -0.7854f, 0.0f, 0.0f)
bone14.setTextureOffset(20, 50).addBox(-7.9f, -1.7678f, -10.9602f, 1.0f, 1.0f, 9.0f, 0.0f, false)
bone14.setTextureOffset(23, 74).addBox(6.9f, -1.7678f, -10.9602f, 1.0f, 1.0f, 9.0f, 0.0f, false)
`in` = ModelRenderer(this)
`in`.setRotationPoint(0.0f, 0.1f, 0.0f)
fixed.addChild(`in`)
`in`.setTextureOffset(48, 19).addBox(-4.0f, -21.0f, -3.5f, 8.0f, 1.0f, 9.0f, 0.0f, false)
bone6 = ModelRenderer(this)
bone6.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone6)
bone6.setTextureOffset(72, 94).addBox(-3.0f, -22.75f, -5.1f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone7 = ModelRenderer(this)
bone7.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone7)
setRotationAngle(bone7, 0.0f, -0.7854f, 0.0f)
bone7.setTextureOffset(94, 35).addBox(-2.192f, -22.85f, -5.0205f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone8 = ModelRenderer(this)
bone8.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone8)
setRotationAngle(bone8, 0.0f, -1.5708f, 0.0f)
bone8.setTextureOffset(92, 91).addBox(-1.5645f, -22.75f, -5.5355f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone9 = ModelRenderer(this)
bone9.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone9)
setRotationAngle(bone9, 0.0f, -2.3562f, 0.0f)
bone9.setTextureOffset(0, 88).addBox(-1.4849f, -22.85f, -6.3435f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone10 = ModelRenderer(this)
bone10.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone10)
setRotationAngle(bone10, 0.0f, 3.1416f, 0.0f)
bone10.setTextureOffset(20, 85).addBox(-2.0f, -22.75f, -6.9711f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone11 = ModelRenderer(this)
bone11.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone11)
setRotationAngle(bone11, 0.0f, 2.3562f, 0.0f)
bone11.setTextureOffset(58, 83).addBox(-2.808f, -22.85f, -7.0506f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone12 = ModelRenderer(this)
bone12.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone12)
setRotationAngle(bone12, 0.0f, 1.5708f, 0.0f)
bone12.setTextureOffset(41, 83).addBox(-3.4355f, -22.75f, -6.5355f, 5.0f, 8.0f, 3.0f, 0.0f, false)
bone13 = ModelRenderer(this)
bone13.setRotationPoint(0.5f, 0.0f, 0.0f)
`in`.addChild(bone13)
setRotationAngle(bone13, 0.0f, 0.7854f, 0.0f)
bone13.setTextureOffset(78, 82).addBox(-3.5151f, -22.85f, -5.7276f, 5.0f, 8.0f, 3.0f, 0.0f, false)
rotatable = ModelRenderer(this)
rotatable.setRotationPoint(0.0f, 0.0f, 0.0f)
shell.addChild(rotatable)
draw = ModelRenderer(this)
draw.setRotationPoint(0.0f, -1.0f, -7.0f)
rotatable.addChild(draw)
draw.setTextureOffset(71, 57).addBox(-7.5f, 0.0f, -1.0f, 15.0f, 7.0f, 1.0f, 0.0f, false)
}
} | 0 | Kotlin | 1 | 1 | 111cf27428c1580b91602a384bb46cd0988415cd | 12,111 | rotarism-decorations | MIT License |
common/src/desktopMain/kotlin/com/numq/common/collector/Collector.kt | numq | 622,627,887 | false | {"Kotlin": 52598, "Java": 37229} | package com.numq.common.collector
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.produceState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlin.coroutines.EmptyCoroutineContext
actual object Collector {
@Composable
actual fun <T> collectLatest(flow: Flow<T>): T? = produceState<T?>(
null,
this,
EmptyCoroutineContext
) {
flow.collectLatest { value = it }
}.value
@Composable
actual fun <T> collect(flow: StateFlow<T>): T = flow.collectAsState().value
@Composable
actual fun <T> collect(flow: Flow<T>, initialValue: T?): T? = flow.collectAsState(initialValue).value
} | 0 | Kotlin | 0 | 0 | 1e85bb7bd4ffeb65693153b7012216d7f80e6c22 | 795 | gifq | MIT License |
server/src/main/kotlin/dev/robocode/tankroyale/server/score/ScoreAndDamage.kt | robocode-dev | 457,523,927 | false | {"Kotlin": 494724, "Java": 418337, "C#": 406673, "SCSS": 1367, "TypeScript": 1071, "Shell": 83} | package dev.robocode.tankroyale.server.score
import dev.robocode.tankroyale.server.dev.robocode.tankroyale.server.model.TeamOrBotId
import dev.robocode.tankroyale.server.rules.RAM_DAMAGE
/** Bot record that tracks damage and survival of a bot, and can calculate score. */
class ScoreAndDamage {
private val bulletDamage = mutableMapOf<TeamOrBotId, Double>()
private val ramDamage = mutableMapOf<TeamOrBotId, Double>()
private val bulletKillEnemyIds = mutableSetOf<TeamOrBotId>()
private val ramKillEnemyIds = mutableSetOf<TeamOrBotId>()
/** The survival count, which is the number of rounds where the bot has survived. */
var survivalCount = 0
private set
/** The last survivor count, which is the number of bots that was killed, before this bot became the last survivor. */
var lastSurvivorCount = 0
private set
/** The total bullet damage dealt by this bot to other bots. */
fun getTotalBulletDamage() = bulletDamage.keys.sumOf { getBulletDamage(it) }
/** The total ram damage dealt by this bot to other bots. */
fun getTotalRamDamage() = bulletDamage.keys.sumOf { getRamDamage(it) }
/** Returns the bullet kill enemy ids. */
fun getBulletKillEnemyIds(): Set<TeamOrBotId> = bulletKillEnemyIds
/**
* Returns the bullet damage dealt by this bot to specific bot.
* @param enemyId is the enemy bot to retrieve the damage for.
* @return the bullet damage dealt to a specific bot.
*/
fun getBulletDamage(enemyId: TeamOrBotId): Double = bulletDamage[enemyId] ?: 0.0
/**
* Returns the ram damage dealt by this bot to specific bot.
* @param enemyId is the enemy bot to retrieve the damage for.
* @return the ram damage dealt to a specific bot.
*/
fun getRamDamage(enemyId: TeamOrBotId): Double = ramDamage[enemyId] ?: 0.0
/**
* Adds bullet damage to a specific enemy bot.
* @param enemyId is the identifier of the enemy bot
* @param damage is the amount of damage that the enemy bot has received
*/
fun addBulletDamage(enemyId: TeamOrBotId, damage: Double) {
bulletDamage[enemyId] = getBulletDamage(enemyId) + damage
}
/**
* Adds ram damage to a specific enemy bot.
* @param enemyId is the identifier of the enemy bot
*/
fun addRamDamage(enemyId: TeamOrBotId) {
ramDamage[enemyId] = getRamDamage(enemyId) + RAM_DAMAGE
}
/** Increment the survival count, meaning that this bot has survived an additional round. */
fun incrementSurvivalCount() {
survivalCount++
}
/**
* Add number of dead enemies to the last survivor count, which only counts, if this bot becomes the last survivor.
* @param numberOfDeadEnemies is the number of dead bots that must be added to the last survivor count.
*/
fun addLastSurvivorCount(numberOfDeadEnemies: Int) {
lastSurvivorCount += numberOfDeadEnemies
}
/**
* Adds the identifier of an enemy bot to the set over bots killed by a bullet from this bot.
* @param enemyId is the identifier of the enemy bot that was killed by this bot
*/
fun addBulletKillEnemyId(enemyId: TeamOrBotId) {
bulletKillEnemyIds += enemyId
}
/**
* Adds the identifier of an enemy bot to the set over bots killed by ramming by this bot.
* @param enemyId is the identifier of the enemy bot that was killed by this bot
*/
fun addRamKillEnemyId(enemyId: TeamOrBotId) {
ramKillEnemyIds += enemyId
}
} | 3 | Kotlin | 13 | 80 | aa33bf2de5e392bd7bdc5c1feaac02e1d035b8ee | 3,534 | tank-royale | Apache License 2.0 |
Week3/MassAndWeight.kt | InfiniteExalt | 528,918,884 | false | {"Kotlin": 18434, "Roff": 397} | fun main(){
//User will imput the mass in newtons
println("Enter mass in newtons: ")
val mass = Integer.valueOf(readLine())
if (mass>1000) {
println("mass is too heavy.")
}else{
if (mass<10)
println("mass is too light")
}
//the weight equation for mass
var weight=(mass * 9.8)
println("The weight is: $weight")
//Will output the conversion
}
| 0 | Kotlin | 0 | 2 | 673cd3f2dae1c7e7c18815e6b81dfab8552924d4 | 410 | KotlinFall22 | MIT License |
samples/src/main/java/com/google/ai/client/generative/samples/controlled_generation.kt | google-gemini | 727,310,537 | false | {"Kotlin": 297005, "Shell": 1948} | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ai.client.generative.samples
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.FunctionType
import com.google.ai.client.generativeai.type.Schema
import com.google.ai.client.generativeai.type.generationConfig
// Set up your API Key
// ====================
//
// To use the Gemini API, you'll need an API key. To learn more, see
// the "Set up your API Key section" in the [Gemini API
// quickstart](https://ai.google.dev/gemini-api/docs/quickstart?lang=android#set-up-api-key).
suspend fun json_controlled_generation() {
// [START json_controlled_generation]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey,
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = Schema(
name = "recipes",
description = "List of recipes",
type = FunctionType.ARRAY,
items = Schema(
name = "recipe",
description = "A recipe",
type = FunctionType.OBJECT,
properties = mapOf(
"recipeName" to Schema(
name = "recipeName",
description = "Name of the recipe",
type = FunctionType.STRING,
nullable = false
),
),
required = listOf("recipeName")
),
)
})
val prompt = "List a few popular cookie recipes."
val response = generativeModel.generateContent(prompt)
print(response.text)
// [END json_controlled_generation]
}
suspend fun json_no_schema() {
// [START json_no_schema]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey,
generationConfig = generationConfig {
responseMimeType = "application/json"
})
val prompt = """
List a few popular cookie recipes using this JSON schema:
Recipe = {'recipeName': string}
Return: Array<Recipe>
""".trimIndent()
val response = generativeModel.generateContent(prompt)
print(response.text)
// [END json_no_schema]
}
| 26 | Kotlin | 153 | 708 | b5d2e5610d19522ad10e6dc7e98236689aaa3587 | 3,466 | generative-ai-android | Apache License 2.0 |
app/src/main/java/com/example/lockunlockdetection/MainActivity.kt | alihaider78222 | 693,083,673 | false | {"Kotlin": 4797} | package com.example.lockunlockdetection
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val REQUEST_CODE_ENABLE_ADMIN = 1
private var devicePolicyManager: DevicePolicyManager? = null
private var componentName: ComponentName? = null
var enableAdmin: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//
enableAdmin = findViewById<View>(R.id.enableAdminButton) as Button
// Initialize DevicePolicyManager and ComponentName
devicePolicyManager = getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
componentName = ComponentName(this, MyDeviceAdminReceiver::class.java)
val enableAdminButton = findViewById<Button>(R.id.enableAdminButton)
enableAdminButton.setOnClickListener {
// Check if the app is already a device administrator
if (!devicePolicyManager!!.isAdminActive(componentName!!)) {
// If not, request device administrator privileges
val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName)
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Your explanation here")
startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN)
} else {
// App is already a device administrator
// You can handle this case as needed
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_ENABLE_ADMIN) {
if (resultCode == RESULT_OK) {
// Device admin privileges granted
// You can handle this case as needed
} else {
// Device admin privileges not granted
// You can handle this case as needed
}
}
}
} | 0 | Kotlin | 0 | 1 | cb5cec61c47dda264fc6c7169b9722845a356b9f | 2,335 | Lock-Unlock-Detection-POC | MIT License |
src/test/we/rashchenko/networks/controllers/ComplexControllerTest.kt | dimitree54 | 395,058,303 | false | null | package we.rashchenko.networks.controllers
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import we.rashchenko.base.Feedback
import we.rashchenko.neurons.ControlledNeuron
import we.rashchenko.neurons.SlowNeuron
import we.rashchenko.neurons.zoo.RandomNeuron
internal class ComplexControllerTest {
@Test
fun getControllerFeedbacks() {
val neurons = listOf(
ControlledNeuron(RandomNeuron(0.0f)).apply { control = true },
ControlledNeuron(SlowNeuron(0.0f)).apply { control = true },
ControlledNeuron(RandomNeuron(0.6f)).apply { control = true },
ControlledNeuron(SlowNeuron(0.6f)).apply { control = true },
ControlledNeuron(RandomNeuron(0.8f)).apply { control = true },
ControlledNeuron(SlowNeuron(0.8f)).apply { control = true },
)
repeat(500) { timeStep ->
neurons.forEach {
it.touch(timeStep, timeStep.toLong())
it.update(Feedback.NEUTRAL, timeStep.toLong())
it.getFeedback(timeStep)
it.forgetSource(timeStep)
it.active
}
}
val controllerFeedbacks =
ComplexController(listOf(ActivityController(), TimeController())).getControllerFeedbacks(neurons)
assertEquals(
controllerFeedbacks.indices.sortedBy { controllerFeedbacks[it] },
listOf(1, 5, 3, 0, 4, 2)
)
}
@Test
fun testInvalidArguments() {
assertThrows<IllegalArgumentException> {
ComplexController(listOf(ActivityController(), TimeController()), listOf(1.0))
}
assertThrows<IllegalArgumentException> {
ComplexController(listOf(ActivityController()), listOf(1.0, 0.0))
}
assertThrows<IllegalArgumentException> {
ComplexController(listOf(), listOf())
}
}
@Test
fun testWeights() {
val neurons = listOf(
ControlledNeuron(RandomNeuron(0.0f)).apply { control = true },
ControlledNeuron(RandomNeuron(0.6f)).apply { control = true },
ControlledNeuron(RandomNeuron(0.8f)).apply { control = true }
)
repeat(1000) { timeStep ->
neurons.forEach {
it.touch(timeStep, timeStep.toLong())
it.update(Feedback.NEUTRAL, timeStep.toLong())
}
}
assertEquals(
ComplexController(listOf(TimeController(), ActivityController()), listOf(0.0, 1.0)).getControllerFeedbacks(
neurons
),
ActivityController().getControllerFeedbacks(neurons)
)
assertEquals(
Feedback.VERY_POSITIVE,
ComplexController(listOf(ActivityController()), listOf(1000.0)).getControllerFeedbacks(neurons)[1],
)
}
}
| 5 | Kotlin | 0 | 1 | 04c9f6eab98722e971194cd235bd84d35afd92b7 | 2,922 | ChNN-Library | MIT License |
src/main/java/site/hirecruit/hr/domain/auth/aop/UserSessionInfoUpdateAspect.kt | themoment-team | 473,691,285 | false | {"Kotlin": 205045, "Dockerfile": 1004, "Shell": 97} | package site.hirecruit.hr.domain.auth.aop
import mu.KotlinLogging
import org.aspectj.lang.annotation.AfterReturning
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.springframework.stereotype.Component
import site.hirecruit.hr.domain.auth.dto.AuthUserInfo
import site.hirecruit.hr.global.data.SessionAttribute
import javax.servlet.http.HttpSession
private val log = KotlinLogging.logger {}
/**
* session에 저장된 AuthUserInfo 저장 Aspect
*
* @author 정시원
* @since 1.0
*/
@Component
@Aspect
class UserSessionInfoUpdateAspect (
private val httpSession: HttpSession
) {
@Pointcut("execution(* site.hirecruit.hr.domain.auth.service.UserAuthService+.authentication(..))")
private fun userAuthService_AuthenticationMethodPointCut(){}
@Pointcut("execution(* site.hirecruit.hr.domain.user.service.UserRegistrationRollbackService+.rollback(..))")
private fun userRegistrationRollbackService_rollback(){}
@Pointcut("execution(* site.hirecruit.hr.domain.user.service.UserUpdateService+.update(..))")
private fun userUpdateService_update(){}
/**
* [site.hirecruit.hr.domain.auth.service.UserAuthService.authentication]에서의 유저 인증 수행 후 세션을 발급하는 AOP method
*/
@AfterReturning(
"userAuthService_AuthenticationMethodPointCut() || userRegistrationRollbackService_rollback() || userUpdateService_update()",
returning = "authUserInfo"
)
private fun setSessionByAuthUserInfo(authUserInfo: AuthUserInfo): Any{
log.debug("UserAuthAspect.setSessionByAuthUserInfo active")
httpSession.setAttribute(SessionAttribute.AUTH_USER_INFO.attributeName, authUserInfo)
log.debug("session id='${httpSession.id}', authUserInfo='${httpSession.getAttribute(SessionAttribute.AUTH_USER_INFO.attributeName)}'")
return authUserInfo
}
} | 2 | Kotlin | 0 | 16 | 6dbf1779257a5ecde9f51c9878bc0cb8871f5336 | 1,851 | HiRecruit-server | MIT License |
app/src/main/java/com/andrii_a/muze/MuzeApplication.kt | andrew-andrushchenko | 655,902,633 | false | null | package com.andrii_a.muze
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MuzeApplication : Application() | 0 | Kotlin | 0 | 2 | a3c327faa2c1aa5f30b6400187d7d3745508f99d | 154 | Muze | The Unlicense |
app/src/main/java/com/andrii_a/muze/MuzeApplication.kt | andrew-andrushchenko | 655,902,633 | false | null | package com.andrii_a.muze
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MuzeApplication : Application() | 0 | Kotlin | 0 | 2 | a3c327faa2c1aa5f30b6400187d7d3745508f99d | 154 | Muze | The Unlicense |
share/src/main/java/com/kyawhut/atsycast/share/base/BaseBrowseSupportFragment.kt | kyawhtut-cu | 406,324,527 | false | null | package com.kyawhut.atsycast.share.base
import android.annotation.SuppressLint
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.TextView
import androidx.fragment.app.Fragment
import androidx.leanback.app.BrowseSupportFragment
import androidx.leanback.widget.*
import com.kyawhut.atsycast.share.R
import com.kyawhut.atsycast.share.components.IOSLoading
import com.kyawhut.atsycast.share.network.utils.NetworkError
import com.kyawhut.atsycast.share.network.utils.NetworkError.Companion.printStackTrace
import com.kyawhut.atsycast.share.ui.error.ErrorFragment
import com.kyawhut.atsycast.share.utils.binding.TextViewBinding.applyMMFont
import com.kyawhut.atsycast.share.utils.extension.Extension.getColorValue
import com.kyawhut.atsycast.share.utils.extension.FragmentExtension.addFragment
/**
* @author kyawhtut
* @date 9/3/21
*/
abstract class BaseBrowseSupportFragment : BrowseSupportFragment() {
private val rowsAdapter by lazy { ArrayObjectAdapter(ListRowPresenter()) }
private val rowDiffCallback by lazy { RowDiffCallback() }
open val onSearchClicked: (() -> Unit)? = null
abstract fun onClickRetry()
private val errorFragment by lazy {
ErrorFragment.newInstance().apply {
setTargetFragment(this@BaseBrowseSupportFragment, 1)
}
}
abstract fun onCreateRowFragment(header: HeaderItem): Fragment
private val loadingView by lazy {
LayoutInflater.from(context).inflate(R.layout.view_loading, null)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupUIElements()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBarManager.apply {
enableProgressBar()
setProgressBarView(
loadingView.also {
(view.parent as ViewGroup).addView(it)
})
initialDelay = 0
}
view.findViewById<TitleView>(R.id.browse_title_group)
.findViewById<TextView>(R.id.title_text).apply {
textSize = resources.getDimensionPixelSize(R.dimen.text_regular_2x).toFloat()
applyMMFont()
}
adapter = rowsAdapter
}
fun clearRows() {
rowsAdapter.clear()
}
fun setRowItem(rows: List<Row>) {
rowsAdapter.setItems(rows, rowDiffCallback)
startEntranceTransition()
}
fun addRowItem(rows: Row) {
rowsAdapter.add(rows)
}
fun addRowItem(index: Int, rows: Row) {
rowsAdapter.add(index, rows)
}
fun removeRow(rows: Row) {
rowsAdapter.remove(rows)
}
fun removeRow(index: Int, count: Int = 1) {
rowsAdapter.removeItems(index, count)
}
fun getRow(index: Int): Row {
return rowsAdapter[index] as Row
}
private fun setupUIElements() {
headersState = HEADERS_ENABLED
isHeadersTransitionOnBackEnabled = true
if (onSearchClicked != null) setOnSearchClickedListener {
onSearchClicked?.invoke()
}
brandColor = getColorValue(R.color.brandColor)
searchAffordanceColor = getColorValue(R.color.searchAffordanceColor)
mainFragmentRegistry.registerFragment(PageRow::class.java, PageRowFragmentFactory())
}
fun showLoading() {
loadingView.findViewById<IOSLoading>(R.id.ios_loading).toggleAnimation(true)
progressBarManager.show()
}
fun hideLoading() {
loadingView.findViewById<IOSLoading>(R.id.ios_loading).toggleAnimation(false)
progressBarManager.hide()
}
fun showError(error: NetworkError?, isBackEnable: Boolean = false) {
errorFragment.isBackEnabled = isBackEnable
error.printStackTrace()
hideLoading()
parentFragmentManager.addFragment(R.id.scale_frame, errorFragment, ErrorFragment.TAG)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
1 -> {
parentFragmentManager.popBackStack(
ErrorFragment.TAG,
androidx.fragment.app.FragmentManager.POP_BACK_STACK_INCLUSIVE
)
if (resultCode == Activity.RESULT_OK) {
onClickRetry()
}
}
}
}
private inner class PageRowFragmentFactory : BrowseSupportFragment.FragmentFactory<Fragment>() {
override fun createFragment(row: Any?): Fragment {
val headerItem = (row as Row).headerItem
title = headerItem.name
return onCreateRowFragment(headerItem)
}
}
class RowDiffCallback : DiffCallback<Row>() {
override fun areItemsTheSame(oldItem: Row, newItem: Row) =
oldItem.hashCode() == newItem.hashCode()
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: Row, newItem: Row) =
oldItem == newItem
}
} | 0 | Kotlin | 4 | 3 | 72d56fa28f5be7526f0a9848491ddd87cca3804d | 5,191 | atsy-cast | Apache License 2.0 |
app/src/main/java/me/zhaoweihao/hnuplus/Utils/HttpUtil.kt | zhaoweih | 128,950,368 | false | null | package me.zhaoweihao.hnuplus.Utils
import okhttp3.OkHttpClient
import okhttp3.Request
/**
* Created by Zhaoweihao on 2018/1/6.
*/
object HttpUtil {
fun sendOkHttpRequest(address: String, callback: okhttp3.Callback) {
val client = OkHttpClient()
val request = Request.Builder()
.url(address)
.build()
client.newCall(request).enqueue(callback)
}
}
| 0 | Kotlin | 0 | 13 | 73f2e2b5467c0010f2cb8852c306b0fe0ef95617 | 416 | Nice-Trader | MIT License |
alarmscheduler/src/main/java/com/carterchen247/alarmscheduler/model/AlarmInfo.kt | CarterChen247 | 245,651,581 | false | null | package com.carterchen247.alarmscheduler.model
import com.carterchen247.alarmscheduler.AlarmIdProvider
data class AlarmInfo(
val alarmType: Int,
val triggerTime: Long,
var alarmId: Int = AlarmIdProvider.AUTO_GENERATE,
var dataPayload: DataPayload? = null
) | 1 | Kotlin | 1 | 8 | 8726177fb3ed121d396384d05489a8a6d5da347b | 274 | AlarmScheduler | The Unlicense |
app/src/main/kotlin/aoc2021/day05/Point.kt | dbubenheim | 435,284,482 | false | null | package aoc2021.day05
data class Point(val x: Int, val y: Int) {
operator fun rangeTo(point: Point): List<Point> {
val minY = minOf(y, point.y)
val maxY = maxOf(y, point.y)
val minX = minOf(x, point.x)
val maxX = maxOf(x, point.x)
return when {
// vertical line
x == point.x -> (minY..maxY).map { curY -> Point(x, curY) }//.also { println(it) }
// horizontal line
y == point.y -> (minX..maxX).map { curX -> Point(curX, y) }//.also { println(it) }
// diagonal line
else -> {
when {
x <= point.x && y <= point.y -> (x..point.x).mapIndexed { index, curX ->
Point(
curX,
y + index
)
}//.also { println(it) }
x > point.x && y <= point.y -> (y..point.y).mapIndexed { index, curY ->
Point(
x - index,
curY
)
}//.also { println(it) }
x <= point.x && y > point.y -> (x..point.x).mapIndexed { index, curX ->
Point(
curX,
y - index
)
}//.also { println(it) }
else -> (point.x..x).mapIndexed { index, _ -> Point(x - index, y - index) }//.also { println(it) }
}
// // 8,0 -> 0,8 /
// // 0,0 -> 8,8 \
// if (y < point.y) {
// (minX..maxX).mapIndexed { index, curX -> Point(curX, minY + index) }.also { println(it) }
// }
// else {
// (minX..maxX).mapIndexed { index, curX -> Point(curX, maxY - index) }.also { println(it) }
// }
// // (minX..maxX).mapIndexed { index, curX -> Point(curX, minY + index) }
}
}
}
} | 6 | Kotlin | 0 | 0 | aa6d15c339965d226670cc6b882f34153c7d52ee | 2,068 | advent-of-code-2021 | MIT License |
data/RF01998/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01998"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 2
42 to 43
}
value = "#eaefb1"
}
color {
location {
7 to 11
29 to 33
}
value = "#f8cafc"
}
color {
location {
12 to 13
25 to 26
}
value = "#674bf0"
}
color {
location {
62 to 64
69 to 71
}
value = "#89a10c"
}
color {
location {
72 to 74
173 to 175
}
value = "#0f674f"
}
color {
location {
84 to 85
164 to 165
}
value = "#9a36a4"
}
color {
location {
106 to 107
154 to 155
}
value = "#3eaa09"
}
color {
location {
3 to 6
34 to 41
}
value = "#b63176"
}
color {
location {
12 to 11
27 to 28
}
value = "#06f9af"
}
color {
location {
14 to 24
}
value = "#892a83"
}
color {
location {
65 to 68
}
value = "#cf5cd2"
}
color {
location {
75 to 83
166 to 172
}
value = "#a7345d"
}
color {
location {
86 to 105
156 to 163
}
value = "#4829db"
}
color {
location {
108 to 153
}
value = "#05c64e"
}
color {
location {
44 to 61
}
value = "#3bce20"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 2,364 | Rfam-for-RNArtist | MIT License |
net/src/main/java/com/tans/tfiletransporter/netty/extensions/IPackageDataConverter.kt | Tans5 | 329,625,887 | false | {"Kotlin": 513053} | package com.tans.tfiletransporter.netty.extensions
import com.tans.tfiletransporter.netty.PackageData
interface IPackageDataConverter {
fun couldHandle(type: Int, dataClass: Class<*>): Boolean
fun <T> convert(type: Int, messageId: Long, data: T, dataClass: Class<T>): PackageData?
} | 0 | Kotlin | 20 | 96 | 061bf75ba02b48693e61fbc15af670dc24a4c2cf | 294 | tFileTransporter | Apache License 2.0 |
src/main/kotlin/icfp2019/model/Orientation.kt | bspradling | 193,332,580 | true | {"JavaScript": 797310, "Kotlin": 85937, "CSS": 9434, "HTML": 5859} | package icfp2019.model
enum class Orientation {
Up, Down, Left, Right
}
| 0 | JavaScript | 0 | 0 | 9f7e48cce858cd6a517d4fb69b9a0ec2d2a69dc5 | 77 | icfp-2019 | The Unlicense |
acl-demo/server/src/main/kotlin/net/corda/samples/acl/server/Main.kt | anniyanvr | 174,407,442 | true | {"Kotlin": 575108, "Java": 153918, "HTML": 55513, "JavaScript": 40046, "CSS": 2042} | package net.corda.samples.acl.server
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import net.corda.core.identity.CordaX500Name
import java.io.File
import java.net.InetSocketAddress
const val DEFAULT_ACL_FILE_NAME = "acl.txt"
class AccessControlList(private val file: File) {
val list: Set<CordaX500Name> get() = readListFromFile()
private fun readListFromFile() = file.readLines().map { CordaX500Name.parse(it) }.toSet()
}
fun parseArgs(args: Array<String>) = when (args.size) {
0 -> DEFAULT_ACL_FILE_NAME
1 -> args[1]
else -> throw IllegalStateException("Only one optional argument is required.")
}
fun main(args: Array<String>) {
val file = File(parseArgs(args))
println("This program serves an access control list of CordaX500Names on localhost:8000.")
println("WARNING: \"$file\" must contain correctly formatted CordaX500Names.")
val acl = AccessControlList(file)
val handler = AclHandler(acl)
createHttpServer(handler)
println("Press Ctrl+C to quit.")
}
fun createHttpServer(handler: HttpHandler) {
val server = HttpServer.create(InetSocketAddress(8000), 0)
server.createContext("/acl", handler)
server.executor = null
server.start()
}
class AclHandler(val acl: AccessControlList) : HttpHandler {
override fun handle(request: HttpExchange) {
val (list, error) = try {
Pair(acl.list.joinToString("\n"), false)
} catch (e: Throwable) {
Pair("The access control list contains malformed CordaX500Names", true)
}
if (error) {
request.sendResponseHeaders(500, 0)
val response = request.responseBody
response.close()
} else {
request.sendResponseHeaders(200, list.length.toLong())
val response = request.responseBody
response.write(list.toByteArray())
response.close()
}
}
}
| 0 | Kotlin | 0 | 0 | bc5495a35f3b9647afa0d2be11ee4edcebb26a9d | 1,992 | samples | Apache License 2.0 |
feature/settings/src/main/java/com/kanyideveloper/settings/presentation/settings/SettingsViewModel.kt | joelkanyi | 554,742,212 | false | {"Kotlin": 566635, "Shell": 761, "Java": 595} | /*
* Copyright 2022 <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.kanyideveloper.settings.presentation.settings
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.joelkanyi.analytics.domain.usecase.TrackUserEventUseCase
import com.joelkanyi.common.state.TextFieldState
import com.joelkanyi.common.util.UiEvents
import com.kanyideveloper.settings.domain.usecase.SetCurrentThemeUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val trackUserEventUseCase: TrackUserEventUseCase,
private val setCurrentThemeUseCase: SetCurrentThemeUseCase,
) : ViewModel() {
fun trackUserEvent(eventName: String) {
trackUserEventUseCase.invoke(eventName)
}
private val _eventsFlow = MutableSharedFlow<UiEvents>()
val eventsFlow = _eventsFlow
private val _shouldShowThemesDialog = mutableStateOf(false)
val shouldShowThemesDialog: State<Boolean> = _shouldShowThemesDialog
fun setShowThemesDialogState(value: Boolean) {
_shouldShowThemesDialog.value = value
}
private val _shouldShowSubscriptionDialog = mutableStateOf(false)
val shouldShowSubscriptionDialog: State<Boolean> = _shouldShowSubscriptionDialog
fun setShowSubscriptionDialogState(value: Boolean) {
_shouldShowSubscriptionDialog.value = value
}
private val _shouldShowFeedbackDialog = mutableStateOf(false)
val shouldShowFeedbackDialog: State<Boolean> = _shouldShowFeedbackDialog
fun setShowFeedbackDialogState(value: Boolean) {
_shouldShowFeedbackDialog.value = value
}
private val _feedback = mutableStateOf(TextFieldState())
val feedback: State<TextFieldState> = _feedback
fun setFeedbackState(value: String) {
_feedback.value = feedback.value.copy(
text = value,
error = null
)
}
fun updateTheme(themeValue: Int) {
viewModelScope.launch {
setCurrentThemeUseCase(themeValue)
setShowThemesDialogState(false)
}
}
fun validateFeedbackTextfield(message: String) {
if (message.isEmpty()) {
_feedback.value = feedback.value.copy(
error = "Feedback cannot be empty"
)
}
}
private val _logoutState = mutableStateOf(LogoutState())
val logoutState: State<LogoutState> = _logoutState
fun logoutUser() {
viewModelScope.launch {
_logoutState.value = LogoutState(isLoading = true)
Firebase.auth.signOut()
val user = Firebase.auth.currentUser
if (user == null) {
_logoutState.value = LogoutState(isLoading = false)
_eventsFlow.emit(UiEvents.NavigationEvent(""))
}
}
}
}
data class LogoutState(
val isLoading: Boolean = false
)
| 2 | Kotlin | 9 | 70 | c07bf99afa8aa278ffa6cdde4572ba49f3798d42 | 3,691 | mealtime | Apache License 2.0 |
app/src/main/java/io/nosyntax/foundation/presentation/settings/SettingsScreen.kt | aelrahmanashraf | 683,553,348 | false | {"Kotlin": 192249, "Groovy": 3590, "HTML": 1491, "Batchfile": 1149, "Shell": 744} | package io.nosyntax.foundation.presentation.settings
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import io.nosyntax.foundation.R
import io.nosyntax.foundation.core.utility.Intents.openEmail
import io.nosyntax.foundation.core.utility.Intents.openPlayStore
import io.nosyntax.foundation.core.utility.Intents.openUrl
import io.nosyntax.foundation.core.utility.Utilities.findActivity
import io.nosyntax.foundation.presentation.main.MainActivity
import io.nosyntax.foundation.ui.theme.DynamicTheme
@Composable
fun SettingsScreen(
navController: NavController
) {
val context = LocalContext.current
Box(modifier = Modifier
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.background)
.verticalScroll(rememberScrollState())
) {
Column(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { context.openPlayStore(context.packageName) }
.padding(horizontal = 20.dp, vertical = 15.dp)
) {
Text(
text = stringResource(id = R.string.rate_us),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground
)
}
Divider(
thickness = 1.dp,
color = MaterialTheme.colorScheme.surface
)
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { context.openEmail(email = "<EMAIL>") }
.padding(horizontal = 20.dp, vertical = 15.dp)
) {
Text(
text = stringResource(id = R.string.send_feedback),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground
)
}
Divider(
thickness = 1.dp,
color = MaterialTheme.colorScheme.surface
)
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { context.openUrl("https://example.com") }
.padding(horizontal = 20.dp, vertical = 15.dp)
) {
Text(
text = stringResource(id = R.string.privacy_policy),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground
)
}
Divider(
thickness = 1.dp,
color = MaterialTheme.colorScheme.surface
)
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { context.openUrl("https://example.com") }
.padding(horizontal = 20.dp, vertical = 15.dp)
) {
Text(
text = "About Us",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground
)
}
}
}
BackHandler(enabled = true) {
(context.findActivity() as MainActivity).showInterstitial(onAdDismissed = {
navController.popBackStack()
})
}
}
@Preview
@Composable
fun SettingsScreenPreview() {
DynamicTheme(darkTheme = false) {
val navController = rememberNavController()
SettingsScreen(navController = navController)
}
} | 0 | Kotlin | 0 | 0 | 3314a7e3f8a3faed2b120868ffc81339dd04ddbe | 4,537 | nosyntax-foundation-android | MIT License |
funcify-feature-eng-tools/src/test/kotlin/funcify/feature/tools/extensions/PersistentListExtensionsTest.kt | anticipasean | 458,910,592 | false | null | package funcify.feature.tools.extensions
import funcify.feature.tools.extensions.PersistentListExtensions.reduceToPersistentList
import java.util.stream.Stream
import kotlinx.collections.immutable.PersistentList
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
internal class PersistentListExtensionsTest {
@Test
fun parallelOrderPreservationTest() {
val outputList: PersistentList<Int> =
(1..200)
.toList()
.stream()
.parallel()
.filter { i -> i % 3 != 0 }
.flatMap { i ->
if (i and 1 == 0) {
Stream.of(i)
} else {
Stream.empty()
}
}
.reduceToPersistentList()
Assertions.assertEquals(2, outputList.first())
Assertions.assertEquals(100, outputList[outputList.size shr 1])
Assertions.assertEquals(200, outputList.last())
}
@Test
fun sequentialOrderPreservationTest() {
val outputList: PersistentList<Int> =
(1..200)
.toList()
.stream()
.filter { i -> i % 3 != 0 }
.flatMap { i ->
if (i and 1 == 0) {
Stream.of(i)
} else {
Stream.empty()
}
}
.reduceToPersistentList()
Assertions.assertEquals(2, outputList.first())
Assertions.assertEquals(100, outputList[outputList.size shr 1])
Assertions.assertEquals(200, outputList.last())
}
}
| 0 | Kotlin | 0 | 0 | 202a13324edc1d477c82b3de54a55a4cb72669ad | 1,694 | funcify-feature-eng | Apache License 2.0 |
telegram-bot/src/main/kotlin/com/theapache64/cs/utils/FeedbackParser.kt | shyamsunder0072 | 249,824,626 | true | {"Jupyter Notebook": 197971, "Python": 105096, "JavaScript": 42047, "Kotlin": 25543, "CSS": 16364, "HTML": 857, "Dockerfile": 408, "Java": 299} | package com.theapache64.cs.utils
import com.theapache64.cs.models.Feedback
object FeedbackParser {
private val feedbackRegEx = "(?<feedback>\\w)(?<documentId>\\d+)(?<question>.+)".toRegex()
fun parse(data: String): Feedback {
val match = feedbackRegEx.find(data)
val groups = match!!.groups
return Feedback(
groups["feedback"]!!.value[0],
groups["question"]!!.value,
groups["documentId"]!!.value.toLong()
)
}
} | 0 | null | 0 | 0 | a8474955911db70438fb1ec0396ef5ce2e8ad213 | 492 | COVID-QA | Apache License 2.0 |
ui/galleries/android/impl/src/main/kotlin/com/adjectivemonk2/pixels/ui/galleries/android/impl/GalleriesInfoViewFactoryImpl.kt | Sripadmanabans | 300,346,280 | false | null | package com.adjectivemonk2.pixels.ui.galleries.android.impl
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.adjectivemonk2.pixels.scope.ActivityScope
import com.adjectivemonk2.pixels.ui.galleries.android.GalleriesInfoViewFactory
import com.adjectivemonk2.pixels.ui.galleries.common.GalleriesScreen.Info
import com.adjectivemonk2.pixels.ui.galleries.common.GalleryListItem
import com.adjectivemonk2.pixels.ui.galleries.common.MediaItem
import com.squareup.anvil.annotations.ContributesBinding
import com.squareup.workflow1.ui.ViewEnvironment
import com.squareup.workflow1.ui.compose.tooling.Preview
import javax.inject.Inject
@ContributesBinding(scope = ActivityScope::class)
public class GalleriesInfoViewFactoryImpl @Inject constructor() : GalleriesInfoViewFactory() {
@Composable override fun Content(rendering: Info, viewEnvironment: ViewEnvironment) {
Surface {
Box(
modifier = Modifier
.fillMaxSize()
.animateContentSize(),
) {
LazyColumn {
items(items = rendering.galleryListItems) { item ->
GalleryItem(galleryListItem = item)
}
}
}
}
}
@Composable internal fun GalleryItem(galleryListItem: GalleryListItem) {
val painter = if (LocalInspectionMode.current) {
painterResource(id = R.drawable.error)
} else {
rememberImagePainter(data = galleryListItem.accountImageUrl)
}
Image(
painter = painter,
contentDescription = stringResource(id = R.string.profile_image),
modifier = Modifier.size(48.dp)
)
}
}
@Preview(showBackground = true)
@Composable private fun GalleriesSuccessViewFactoryPreview() {
val factory = GalleriesInfoViewFactoryImpl()
factory.Preview(Info(emptyList()))
}
@Preview(showBackground = true)
@Composable private fun GalleryItemPreview() {
val factory = GalleriesInfoViewFactoryImpl()
val galleryItem1 = GalleryListItem(
galleryId = "123",
userId = "asv",
accountImageUrl = "https://www.w3schools.com/howto/img_avatar2.png",
mediaItem = MediaItem.Image(id = "sample", "https://www.w3schools.com/howto/img_avatar.png"),
title = "Sample one",
showDownArrow = false,
diff = "20000",
commentCount = "1234",
views = "23456",
showItemCount = false,
itemCount = "10",
)
val galleryItem2 = GalleryListItem(
galleryId = "123",
userId = "asv",
accountImageUrl = "https://www.w3schools.com/howto/img_avatar2.png",
mediaItem = MediaItem.Image(id = "sample", "https://www.w3schools.com/howto/img_avatar.png"),
title = "Sample one",
showDownArrow = false,
diff = "20000",
commentCount = "1234",
views = "23456",
showItemCount = false,
itemCount = "10",
)
factory.Preview(Info(listOf(galleryItem1, galleryItem2)))
}
| 1 | Kotlin | 0 | 1 | b4e217a9da7b833989d806644348fa5caeb7e065 | 3,491 | Pixels | Apache License 2.0 |
dial-phone-api/src/commonMain/kotlin/de/mtorials/dialphone/api/model/mevents/todevice/MRoomKeyRequest.kt | mtorials | 272,526,016 | false | null | package de.mtorials.dialphone.api.model.mevents.todevice
import de.mtorials.dialphone.api.ids.UserId
import de.mtorials.dialphone.api.model.RequestedKeyInfo
import de.mtorials.dialphone.api.model.enums.KeyRequestAction
import de.mtorials.dialphone.api.model.mevents.EventContent
import de.mtorials.dialphone.api.model.mevents.MatrixEvent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName(MRoomKeyRequest.EVENT_TYPE)
data class MRoomKeyRequest(
override val content: MRoomKeyRequestContent,
) : MatrixEvent {
override val sender: UserId? = null
@Serializable
data class MRoomKeyRequestContent(
val action: KeyRequestAction,
val body: RequestedKeyInfo? = null,
@SerialName("request_id")
val requestId: String,
@SerialName("requesting_device_id")
val requestingDeviceId: String,
) : EventContent
override fun getTypeName(): String = EVENT_TYPE
companion object {
const val EVENT_TYPE = "m.room_key_request"
}
} | 1 | Kotlin | 0 | 6 | 1f78fed1af1287069fa8c6c585f868cd75e372f9 | 1,057 | dial-phone | Apache License 2.0 |
src/main/kotlin/kvmInternals/systemCalls/calls/readFile.kt | ChippyPlus | 850,474,357 | false | {"Kotlin": 74636} | package org.example.kvmInternals.systemCalls.calls
import org.example.data.registers.enumIdenifiers.SuperRegisterType
import org.example.fileDescriptors
import org.example.helpers.fullRegisterRead
import org.example.helpers.fullRegisterWrite
import org.example.helpers.writeRegisterString
import org.example.kvmInternals.systemCalls.SystemCall
fun SystemCall.readFile(fd: SuperRegisterType, buffer: SuperRegisterType) {
val f = fileDescriptors.getFileDescriptor(fullRegisterRead(fd))!!
fullRegisterWrite(SuperRegisterType.R2, writeRegisterString(buffer, f.file.readText()))
} | 0 | Kotlin | 0 | 1 | 86733d9aa14f896af295c1cc9b941d85a04d71a5 | 587 | MVM | MIT License |
src/main/kotlin/kvmInternals/systemCalls/calls/readFile.kt | ChippyPlus | 850,474,357 | false | {"Kotlin": 74636} | package org.example.kvmInternals.systemCalls.calls
import org.example.data.registers.enumIdenifiers.SuperRegisterType
import org.example.fileDescriptors
import org.example.helpers.fullRegisterRead
import org.example.helpers.fullRegisterWrite
import org.example.helpers.writeRegisterString
import org.example.kvmInternals.systemCalls.SystemCall
fun SystemCall.readFile(fd: SuperRegisterType, buffer: SuperRegisterType) {
val f = fileDescriptors.getFileDescriptor(fullRegisterRead(fd))!!
fullRegisterWrite(SuperRegisterType.R2, writeRegisterString(buffer, f.file.readText()))
} | 0 | Kotlin | 0 | 1 | 86733d9aa14f896af295c1cc9b941d85a04d71a5 | 587 | MVM | MIT License |
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryDirElemConstructor.kt | rhdunn | 62,201,764 | false | null | /*
* Copyright (C) 2016-2021 <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 uk.co.reecedunn.intellij.plugin.xquery.ast.xquery
import com.intellij.psi.HintedReferenceHost
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
/**
* An XQuery 1.0 `DirElemConstructor` node in the XQuery AST.
*/
interface XQueryDirElemConstructor : HintedReferenceHost, XQueryDirectConstructor, XdmElementNode {
val closingTag: XsQNameValue?
val dirAttributeListStartElement: PsiElement
val dirElemContentStartElement: PsiElement
val dirElemContentEndElement: PsiElement
}
| 47 | Kotlin | 4 | 25 | d363dad28df1eb17c815a821c87b4f15d2b30343 | 1,210 | xquery-intellij-plugin | Apache License 2.0 |
src/test/kotlin/g2601_2700/s2679_sum_in_a_matrix/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2601_2700.s2679_sum_in_a_matrix
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun matrixSum() {
assertThat(
Solution().matrixSum(
arrayOf(
intArrayOf(7, 2, 1), intArrayOf(6, 4, 2),
intArrayOf(6, 5, 3), intArrayOf(3, 2, 1)
)
),
equalTo(15)
)
}
@Test
fun matrixSum2() {
assertThat(
Solution().matrixSum(arrayOf(intArrayOf(1))),
equalTo(1)
)
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 653 | LeetCode-in-Kotlin | MIT License |
app/src/main/java/fr/gilles/riceattend/ui/widget/components/LineChartView.kt | Gilles-kpn | 498,005,092 | false | {"Kotlin": 442751} | package fr.gilles.riceattend.ui.widget.components
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.himanshoe.charty.bar.BarChart
import com.himanshoe.charty.bar.config.BarConfig
import com.himanshoe.charty.bar.model.BarData
import com.himanshoe.charty.common.axis.AxisConfig
import com.himanshoe.charty.common.dimens.ChartDimens
import fr.gilles.riceattend.models.ActivitiesData
import fr.gilles.riceattend.models.ActivityStatus
import me.bytebeats.views.charts.pie.PieChart
import me.bytebeats.views.charts.pie.PieChartData
import me.bytebeats.views.charts.pie.render.SimpleSliceDrawer
import me.bytebeats.views.charts.simpleChartAnimation
@Composable
fun LineChartView(activitiesData: ActivitiesData) {
Card(
elevation = 10.dp,
modifier = Modifier.padding(26.dp)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
if(activitiesData.activitiesByCreatedDate.isEmpty()){
EmptyCard()
}else{
BarChart(
barData = activitiesData.activitiesByCreatedDate.map { e ->
BarData(e.key, e.value.toFloat())
},
onBarClick = {},
color = MaterialTheme.colors.primary,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 40.dp, vertical = 60.dp)
.height(250.dp),
chartDimens = ChartDimens(
20.dp
),
axisConfig = AxisConfig(
showXLabels = true,
showAxis = true,
showUnitLabels = true,
isAxisDashed = true,
xAxisColor = MaterialTheme.colors.secondary,
yAxisColor = MaterialTheme.colors.background,
textColor = MaterialTheme.colors.primary
),
barConfig = BarConfig(
hasRoundedCorner = false
)
)
Text("Répartition des activités par mois", modifier = Modifier.padding(vertical = 10.dp))
}
}
}
}
@Composable
fun ActivityByStatus(activitiesData: ActivitiesData) {
Card(
elevation = 10.dp,
modifier = Modifier.padding(16.dp)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
if(activitiesData.activitiesByStatus.isEmpty()){
EmptyCard()
}else{
PieChart(
pieChartData = PieChartData(
slices = activitiesData.activitiesByStatus.map { e -> PieChartData.Slice(
e.value.toFloat(),
when(e.key){
ActivityStatus.INIT -> Color.LightGray
ActivityStatus.CANCELLED, ActivityStatus.UNDONE -> MaterialTheme.colors.error
ActivityStatus.IN_PROGRESS -> Color(0xFFFF5722)
ActivityStatus.DONE -> MaterialTheme.colors.primary
}
) }
),
// Optional properties.
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.padding(vertical = 10.dp),
animation = simpleChartAnimation(),
sliceDrawer = SimpleSliceDrawer( 100F)
)
Row(
Modifier
.fillMaxWidth()
.padding(vertical = 10.dp)
.horizontalScroll(rememberScrollState())) {
Row(Modifier.padding(horizontal = 10.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.size(width = 30.dp, height = 10.dp)
.background(Color.LightGray)
.clip(CircleShape))
Text(text = ActivityStatus.INIT.label+
"(${activitiesData.activitiesByStatus[ActivityStatus.INIT] ?: 0})")
}
Row(Modifier.padding(horizontal = 10.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.size(width = 30.dp, height = 10.dp)
.background(MaterialTheme.colors.error)
.clip(CircleShape))
Text(text = ActivityStatus.UNDONE.label + "(${activitiesData.activitiesByStatus[ActivityStatus.UNDONE] ?: 0})")
}
Row(Modifier.padding(horizontal = 10.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.size(width = 30.dp, height = 10.dp)
.background(Color(0xFFFF5722))
.clip(CircleShape))
Text(text = ActivityStatus.IN_PROGRESS.label + "(${activitiesData.activitiesByStatus[ActivityStatus.IN_PROGRESS] ?: 0})")
}
Row(Modifier.padding(horizontal = 10.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.size(width = 30.dp, height = 10.dp)
.background(MaterialTheme.colors.primary)
.clip(CircleShape))
Text(text = ActivityStatus.DONE.label + "(${activitiesData.activitiesByStatus[ActivityStatus.DONE] ?: 0})")
}
}
Text("Répartition des activités par status", modifier = Modifier.padding(vertical = 10.dp))
}
}
}
} | 0 | Kotlin | 0 | 1 | b75abaf8d21014bdfe79a2ab8db82bcb1f561bf8 | 6,665 | RiceAttend-Mobile | MIT License |
src/main/kotlin/mathfoundation/automaticdifferentiation/automatic_diff_multivar.kt | widi-nugroho | 397,121,501 | false | null | package mathfoundation.automaticdifferentiation
import ai.djl.engine.Engine
import ai.djl.ndarray.NDManager
fun main(){
var manager=NDManager.newBaseManager()
var x=manager.arange(4f)
var y=manager.arange(4f)
x.setRequiresGradient(true)
y.setRequiresGradient(true)
var gc=Engine.getInstance().newGradientCollector()
var z=x.pow(3).add(y.pow(2))
println("z:"+ z.toString())
gc.backward(z)
gc.close()
var xgradient=x.gradient
var ygradient=y.getGradient()
println("X Gradient:$xgradient")
println("Y Gradient:$ygradient")
} | 0 | Kotlin | 0 | 0 | 542c1084f327c930c19a73d6b9b2c904d725e4c6 | 582 | diveintodeeplearning | Apache License 2.0 |
src/main/kotlin/com/dataxow/helper/ImageHelper.kt | paulocoutinhox | 763,882,755 | false | {"Kotlin": 94338, "Vue": 12412, "JavaScript": 1759, "HTML": 1023, "SCSS": 154} | package com.dataxow.helper
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asComposeImageBitmap
import com.google.zxing.BarcodeFormat
import com.google.zxing.qrcode.QRCodeWriter
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.Rect
class ImageHelper {
companion object {
fun generateQRCode(data: String): ImageBitmap {
val writer = QRCodeWriter()
val bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, 512, 512)
val width = bitMatrix.width
val height = bitMatrix.height
val bitmap = Bitmap()
bitmap.allocN32Pixels(width, height)
val canvas = org.jetbrains.skia.Canvas(bitmap)
val paint = org.jetbrains.skia.Paint().apply {
color = org.jetbrains.skia.Color.BLACK
isAntiAlias = false
}
canvas.clear(org.jetbrains.skia.Color.WHITE)
for (y in 0 until height) {
for (x in 0 until width) {
if (bitMatrix[x, y]) {
canvas.drawRect(Rect.makeXYWH(x.toFloat(), y.toFloat(), 1f, 1f), paint)
}
}
}
return bitmap.asComposeImageBitmap()
}
}
}
| 0 | Kotlin | 0 | 1 | 0c5d679e45680e37fb477d585e719a0aa516aec7 | 1,292 | dataxow | MIT License |
src/main/kotlin/io/kloudformation/specification/SpecificationGenerator.kt | hexlabsio | 137,217,471 | false | null | package io.kloudformation.specification
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.module.kotlin.readValue
import io.kloudformation.specification.SpecificationMerger.merge
import java.net.URL
import java.util.zip.GZIPInputStream
private val jacksonObjectMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
private val specificationListUrl = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html"
fun main() {
SpecificationPoet.generate(SpecificationScraper
.scrapeLinks(specificationListUrl)
.mapNotNull { (specificationName, specificationUrl) ->
try {
URL(specificationUrl).openStream().use { stream ->
System.out.println("Downloading $specificationName from $specificationUrl")
specificationName to if (specificationUrl.contains("gzip")) {
GZIPInputStream(stream).bufferedReader().readText()
} else {
stream.bufferedReader().readText()
}
}.asSpecification()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
.merge()
)
}
private fun Pair<String, String>.asSpecification() =
try {
println("Reading $first")
jacksonObjectMapper.readValue<Specification>(second)
} catch (ex: Exception) {
System.err.println("Failed to parse $first specification")
ex.printStackTrace()
Specification(emptyMap(), emptyMap(), "")
}
| 3 | Kotlin | 1 | 33 | 19b703f6f57f1f4b24ddc835c6d96d02d007b1cd | 1,847 | kloudformation | Apache License 2.0 |
src/test/kotlin/org/kalasim/examples/atm/Atm.kt | cybernetics | 328,781,400 | true | {"Jupyter Notebook": 476274, "Kotlin": 211305, "R": 3312} | //Atm.kt
import org.apache.commons.math3.distribution.ExponentialDistribution
import org.kalasim.*
import org.kalasim.misc.display
//https://youtrack.jetbrains.com/issue/KT-44062
fun main() {
createSimulation(false) {
val lambda = 1.5
val mu = 1.0
val rho = lambda / mu
println(
"rho is ${rho}. With rho>1 the system would be unstable, " +
"because there are more arrivals then the atm can serve."
)
val atm = Resource("atm", 1)
class Customer : Component() {
val ed = ExponentialDistribution(rg, mu)
override fun process() = sequence {
request(atm)
hold(ed.sample())
release(atm)
}
}
ComponentGenerator(iat = exponential(lambda)) {
Customer()
}
run(2000)
atm.occupancyMonitor.display()
atm.requesters.queueLengthMonitor.display()
atm.requesters.lengthOfStayMonitor.display()
println(atm.requesters.lengthOfStayMonitor.statistics())
}
} | 0 | null | 0 | 0 | 5d395ad27ae66eb4a06041325e29fa014990a012 | 1,106 | kalasim | MIT License |
core/src/test/kotlin/simulation/resources/StoreTest.kt | aarangop | 618,418,716 | false | null | /*
* Copyright (c) 2023. Andrés Arango Pérez <[email protected]>
*
* You may use, distribute and modify this code under the terms of the MIT license.
*/
package simulation.resources
import event.EventValueStatus
import event.StoreGetEvent
import event.StorePutEvent
import exceptions.StoreAlreadyInitializedException
import org.junit.jupiter.api.Test
import process.SimProcess
import resources.Store
import simulation.KDESimTestBase
import kotlin.test.*
class StoreTest : KDESimTestBase() {
private var storeCapacity = 10
private var store: Store<Unit> = Store(this.env, storeCapacity)
fun getFullStore(): Store<Unit> {
val newStore = Store<Unit>(env, storeCapacity)
newStore.initialize(List(storeCapacity) { })
return newStore
}
fun getEmptyStore(): Store<Unit> {
return Store<Unit>(env, storeCapacity)
}
@BeforeTest
fun initializeStore() {
store = Store(env, storeCapacity)
store.initialize(List(store.storeCapacity) { })
}
@Test
fun `uninitialized store has no available items`() {
val emptyStore = Store<Unit>(env, 10)
assertEquals(0, emptyStore.numberOfAvailableItems)
}
@Test
fun `initialized store has available items`() {
val store = Store<Unit>(env, 10)
store.initialize(List(10) {})
assertEquals(10, store.numberOfAvailableItems)
}
@Test
fun `trying to initialize a store again throws exception`() {
assertFailsWith<StoreAlreadyInitializedException> {
store.initialize(List(store.storeCapacity) { })
}
}
@Test
fun `get one item from the store`() {
var requestedItem: Unit? = null
val p1 = SimProcess(env, sequence {
// Request a product from the store
val request = store.requestOne()
yield(request)
requestedItem = request.value()
})
env.process(p1)
env.run()
assert(requestedItem != null)
}
@Test
fun `put item into the store`() {
val store = Store<Unit>(env, 10)
env.process(sequence {
val request = store.putOne(Unit)
yield(request)
})
env.run()
assertEquals(1, store.numberOfAvailableItems)
}
@Test
fun `item is not added to the store if the store is full`() {
var request: StorePutEvent<Unit>? = null
env.process(sequence {
request = store.putOne(Unit)
yield(request!!)
})
env.run()
assertNull(request?.value())
}
@Test
fun `get request is fulfilled after item has been put into the store`() {
val store = getEmptyStore()
var getRequest: StoreGetEvent<Unit>? = null
env.process(sequence {
getRequest = store.requestOne()
yield(getRequest!!)
})
env.process(sequence {
yield(env.timeout(10.0))
store.putOne(Unit)
})
env.run()
assertNotNull(getRequest!!.value())
}
@Test
fun `put request is fulfilled after an item has been taken from the store`() {
val store = getFullStore()
var putRequest: StorePutEvent<Unit>? = null
env.process(sequence {
putRequest = store.putOne(Unit)
yield(putRequest!!)
})
env.process(sequence {
yield(env.timeout(50.0))
store.requestOne()
})
env.run()
assertEquals(EventValueStatus.AVAILABLE, putRequest!!.valueStatus)
}
} | 5 | Kotlin | 0 | 0 | 0424d803419e52da6abd6df957c4134f37c78e03 | 3,592 | k-DESim | MIT License |
app/src/main/java/com/ghstudios/android/ClickListeners/HelpExpandableClickListener.kt | theMaelstro | 513,896,693 | false | {"Kotlin": 747422, "Java": 406804} | package com.ghstudios.android.ClickListeners
import android.view.View
/**
* Simple ClickListener class to hide and show elements.
* Takes view element to be toggled as parameter.
* Universal, can be used outside of Help page.
*/
class HelpExpandableClickListener(private val element: View) :
View.OnClickListener {
override fun onClick(v: View) {
if (element.visibility == View.GONE) {
element.visibility = View.VISIBLE
}
else {
element.visibility = View.GONE
}
}
}
| 0 | Kotlin | 2 | 12 | 0e71fe8d60c937c22dc5111eceb3722be03575a2 | 542 | MHFZZDatabase | MIT License |
features/properties/presentation/src/main/java/com/danielwaiguru/tripitacaandroid/properties/presentation/propertieslisting/PropertiesUIState.kt | daniel-waiguru | 742,252,528 | false | {"Kotlin": 164708} | package com.danielwaiguru.tripitacaandroid.properties.presentation.propertieslisting
import androidx.compose.runtime.Stable
import com.danielwaiguru.tripitacaandroid.shared.models.Property
@Stable
data class PropertiesUIState(
val properties: List<Property> = emptyList(),
val filteredProperties: List<Property> = emptyList(),
val isLoading: Boolean = false,
val errorMessage: String? = null,
val username: String = "Anonymous",
val userProfileUri: String? = null,
val selectedAmenityFilter: String? = null,
val amenities: List<String> = listOf(
"TV",
"Internet",
"Wireless Internet",
"Air conditioning",
"Wheelchair accessible",
"Kitchen",
"Free parking on premises",
"Pets allowed",
"Elevator in building",
"Buzzer/wireless intercom",
"Heating",
"Family/kid friendly",
"Suitable for events",
"Washer",
"Dryer",
"Smoke detector",
"Carbon monoxide detector",
"First aid kit",
"Fire extinguisher",
"Essentials",
"Shampoo",
"24-hour check-in",
"Hangers",
"Hair dryer",
"Iron",
"Laptop friendly workspace"
)
)
| 1 | Kotlin | 2 | 4 | 83f39b24b3a1c999052e1c24c6796f309ba89347 | 1,252 | QuickStay | MIT License |
src/main/java/com/github/shur/mariaquest/quest/QuestId.kt | SigureRuri | 374,370,450 | false | null | package com.github.shur.mariaquest.quest
class QuestId private constructor(private val id: String) {
init {
if (!id.matches(PATTERN))
throw IllegalArgumentException("id must match [a-z_0-9]+")
}
override fun toString(): String = id
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as QuestId
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
companion object {
private val PATTERN = "[a-z_0-9]+".toRegex()
@JvmStatic
fun of(id: String) = QuestId(id)
}
}
| 0 | Kotlin | 0 | 0 | a4443319f30758603d9044a0236894653dcb9c4e | 728 | MariaQuest | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/lambda/DestinationConfigDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.lambda
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.lambda.DestinationConfig
@Generated
public fun buildDestinationConfig(initializer: @AwsCdkDsl DestinationConfig.Builder.() -> Unit):
DestinationConfig = DestinationConfig.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | b22e397ff37c5fce365a5430790e5d83f0dd5a64 | 401 | aws-cdk-kt | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/FloppyDiskCircleArrowRight.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.FloppyDiskCircleArrowRight: ImageVector
get() {
if (_floppyDiskCircleArrowRight != null) {
return _floppyDiskCircleArrowRight!!
}
_floppyDiskCircleArrowRight = Builder(name = "FloppyDiskCircleArrowRight", defaultWidth =
512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight =
24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0f, 12.0f)
curveToRelative(-3.31f, 0.0f, -6.0f, 2.69f, -6.0f, 6.0f)
reflectiveCurveToRelative(2.69f, 6.0f, 6.0f, 6.0f)
reflectiveCurveToRelative(6.0f, -2.69f, 6.0f, -6.0f)
reflectiveCurveToRelative(-2.69f, -6.0f, -6.0f, -6.0f)
close()
moveTo(20.41f, 19.41f)
lineToRelative(-2.17f, 2.17f)
lineToRelative(-1.41f, -1.41f)
lineToRelative(1.17f, -1.17f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(3.0f)
lineToRelative(-1.09f, -1.09f)
lineToRelative(1.41f, -1.41f)
lineToRelative(2.09f, 2.09f)
curveToRelative(0.78f, 0.78f, 0.78f, 2.05f, 0.0f, 2.83f)
close()
moveTo(14.0f, 5.0f)
lineTo(7.0f, 5.0f)
lineTo(7.0f, 0.0f)
horizontalLineToRelative(7.0f)
lineTo(14.0f, 5.0f)
close()
moveTo(10.59f, 21.0f)
lineTo(0.0f, 21.0f)
lineTo(0.0f, 3.0f)
curveTo(0.0f, 1.35f, 1.35f, 0.0f, 3.0f, 0.0f)
horizontalLineToRelative(2.0f)
lineTo(5.0f, 7.0f)
horizontalLineToRelative(11.0f)
lineTo(16.0f, 0.0f)
horizontalLineToRelative(0.01f)
lineToRelative(4.99f, 4.99f)
verticalLineToRelative(5.6f)
curveToRelative(-0.93f, -0.38f, -1.94f, -0.59f, -3.0f, -0.59f)
curveToRelative(-1.73f, 0.0f, -3.33f, 0.56f, -4.64f, 1.49f)
curveToRelative(-0.63f, -0.9f, -1.68f, -1.49f, -2.86f, -1.49f)
curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f)
curveToRelative(0.0f, 1.78f, 1.35f, 3.24f, 3.08f, 3.46f)
curveToRelative(-0.04f, 0.34f, -0.08f, 0.69f, -0.08f, 1.04f)
curveToRelative(0.0f, 1.06f, 0.21f, 2.07f, 0.59f, 3.0f)
close()
moveTo(11.86f, 12.88f)
curveToRelative(-0.53f, 0.63f, -0.96f, 1.34f, -1.27f, 2.12f)
curveToRelative(-0.03f, 0.0f, -0.06f, 0.0f, -0.09f, 0.0f)
curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f)
curveToRelative(0.6f, 0.0f, 1.12f, 0.36f, 1.36f, 0.88f)
close()
}
}
.build()
return _floppyDiskCircleArrowRight!!
}
private var _floppyDiskCircleArrowRight: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,918 | icons | MIT License |
app/src/main/java/xyz/pokkst/pokket/lite/util/PaymentContent.kt | pokkst | 356,665,068 | false | null | package xyz.pokkst.pokket.lite.util
import org.bitcoinj.core.Coin
class PaymentContent(val addressOrPayload: String?, val amount: Coin?, val paymentType: PaymentType)
enum class PaymentType {
ADDRESS,
BIP70
} | 0 | Kotlin | 0 | 2 | 9a196e59d80ad03bc4718e97b0d411d418c5bbf6 | 219 | pokket.lite | MIT License |
app/src/main/java/com/brookes6/cloudmusic/ui/page/MyPage.kt | brokes6 | 428,601,432 | false | null | package com.brookes6.cloudmusic.ui.page
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.brookes6.cloudmusic.MainActivity
import com.brookes6.cloudmusic.R
import com.brookes6.cloudmusic.action.MyAction
import com.brookes6.cloudmusic.ui.sub.MyFunctionSub
import com.brookes6.cloudmusic.ui.sub.MyLikeSongSub
import com.brookes6.cloudmusic.ui.sub.MyTopUserSub
import com.brookes6.cloudmusic.vm.MyViewModel
/**
* Author: fuxinbo
* Date: 2023/3/3
* Description:
*/
@Composable
fun MyPage(
viewModel: MyViewModel,
onNavController: (String) -> Unit = {}
) {
val state = rememberScrollState()
Box() {
// 背景
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.crossfade(true)
.data(viewModel.user.value?.profile?.backgroundUrl)
.build(),
contentDescription = stringResource(id = R.string.description),
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
.clip(RoundedCornerShape(bottomEnd = 150.dp, bottomStart = 150.dp)),
contentScale = ContentScale.Crop
)
// 整体布局
Column(
modifier = Modifier.verticalScroll(state)
) {
// 头像部分
MyTopUserSub(viewModel, onNavController)
// 功能区部分
MyFunctionSub(viewModel, onNavController)
// 我喜欢的歌单部分
MyLikeSongSub(viewModel, onNavController)
}
}
LaunchedEffect(key1 = Unit, block = {
viewModel.dispatch(MyAction.GetUserInfo)
viewModel.dispatch(MyAction.GetUserPlayList)
})
BackHandler(enabled = true) {
MainActivity.content.finish()
}
} | 0 | Kotlin | 3 | 15 | af5805f903107d61467eebbd9ddfb00a595f7319 | 2,500 | CloudMusic | Apache License 2.0 |
native/android/app/src/main/java/tuerantuer/app/integreat/fetcher/FetchResult.kt | digitalfabrik | 298,817,213 | false | {"TypeScript": 1686582, "JavaScript": 23047, "Ruby": 20883, "Kotlin": 12817, "CSS": 7280, "Swift": 7195, "EJS": 7183, "Shell": 5863, "Objective-C++": 3607, "Objective-C": 953} | package tuerantuer.app.integreat.fetcher
import java.util.Date
class FetchResult(
@JvmField val url: String,
@JvmField val lastUpdate: Date,
private val alreadyExisted: Boolean,
private val errorMessage: String?
) {
fun alreadyExisted(): Boolean {
return alreadyExisted
}
fun getErrorMessage(): String? {
return errorMessage
}
}
| 110 | TypeScript | 14 | 47 | b39c0e6c881e3ae53a7a2d13d93640d93649a338 | 380 | integreat-app | MIT License |
app/src/main/java/com/gchristensen/petfindingapp/AlertService.kt | grchristensen | 269,789,719 | false | null | package com.gchristensen.petfindingapp
import android.app.PendingIntent
import android.content.Intent
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
/**
* Handles the receiving of alerts
* */
class AlertService: FirebaseMessagingService() {
/**
* Called every time a message is received. How relevant the message is has been determined
* by the server.
*
* @param remoteMessage Object representing the message received from FCM.
* */
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Log the sender of the message.
Log.d(MSG_TAG, "From: " + remoteMessage.from)
// Get a user friendly notification body.
val userNotification = generateUserNotification(remoteMessage)
// Send notification to device.
sendNotification(userNotification)
}
/**
* Called whenever the InstanceID token is updated, and also when it is initially generated.
* This will send the token to the server so that it may update the user's info.
*
* @param token A String representing the new token.
* */
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d(TOKEN_TAG, "Refreshed token: $token")
sendRegistrationToServer(token)
}
/**
* Parses the remote message and generates a user friendly notification to display.
*
* @param remoteMessage The RemoteMessage received.
* */
private fun generateUserNotification(remoteMessage: RemoteMessage): String {
// TODO("Need to determine structure of remote message data")
return "Hi"
}
/**
* Sends a user friendly notification to the user's device.
*
* @param message The body of the notification. Intended for the user's view.
* */
private fun sendNotification(message: String?) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
}
/**
* Sends the token to the server so that the user's profile will be updated and they can
* still receive notifications.
*
* @param token The new token of the user.
* */
private fun sendRegistrationToServer(token: String) {
// TODO("Need to research server-side")
}
companion object {
private const val TOKEN_TAG = "FirebaseTOKEN"
private const val MSG_TAG = "FirebaseMSG"
}
} | 0 | Kotlin | 0 | 0 | b7b2872b3d9a3de3960f971e005b98addb3320bb | 2,633 | StrayAlertHTNE | MIT License |
src/Main.kt | alfadur | 76,307,132 | false | null | import kotlin.browser.document
import kotlin.browser.window
enum class GameFlowState
{
DaySelection,
Ingame,
Feedback,
Pause
}
class Game
{
val screenWidth = 620
val screenHeight = 440
val renderer = PIXI.CanvasRenderer(screenWidth, screenHeight)
val scene = PIXI.Container()
var controller: Controller = MenuKeyboardController(window)
var gameStage: GameStage
var flow = GameFlowState.DaySelection
val background = PIXI.BaseTexture.fromImage("images/background.png", false)
val windowTexture = PIXI.BaseTexture.fromImage("images/window.png", false)
val gameSize = Point(screenWidth, screenHeight)
init
{
document.getElementById("game")?.appendChild(renderer.view)
window.requestAnimationFrame { update() }
val b = PIXI.Sprite(
PIXI.Texture(background, PIXI.Rectangle(0, 0, screenWidth, screenHeight)))
scene.addChild(b)
gameStage = MainMenuStage(gameSize, windowTexture)
scene.addChild(gameStage.root)
}
fun switchStage(newStage: GameStage)
{
scene.removeChild(gameStage.root)
scene.addChild(newStage.root)
gameStage = newStage
}
fun update()
{
gameStage.handleController(controller)
gameStage.update()
val stage = gameStage
when (flow)
{
GameFlowState.DaySelection ->
{
if (stage is MainMenuStage && stage.isReady)
{
val items = stage.selectedOption + 1
switchStage(IngameStage(gameSize, items, windowTexture))
flow = GameFlowState.Ingame
controller = KeyboardController(window)
}
}
GameFlowState.Ingame ->
{
val done = (gameStage as? IngameStage)?.done
if (stage is IngameStage)
{
if (done != null)
{
switchStage(FeedbackStage(gameSize, windowTexture,
stage.itemsPerCharacter, done))
flow = GameFlowState.Feedback
controller = MenuKeyboardController(window)
}
else if (stage.needsPause)
{
switchStage(PauseStage(gameSize, windowTexture, stage.level))
flow = GameFlowState.Pause
controller = MenuKeyboardController(window)
}
}
}
GameFlowState.Pause ->
{
if (stage is PauseStage && stage.isReady)
{
if (stage.selectedOption == 0)
{
switchStage(IngameStage(gameSize, stage.pausedLevel.itemsPerCharacter,
windowTexture, stage.pausedLevel))
flow = GameFlowState.Ingame
controller = KeyboardController(window)
}
else
{
switchStage(MainMenuStage(gameSize, windowTexture))
flow = GameFlowState.DaySelection
}
}
}
GameFlowState.Feedback ->
{
if (stage is FeedbackStage && stage.isReady)
{
if (stage.selectedOption == 0)
{
val items = stage.day
switchStage(IngameStage(gameSize, items, windowTexture))
flow = GameFlowState.Ingame
controller = KeyboardController(window)
}
else
{
switchStage(MainMenuStage(gameSize, windowTexture))
flow = GameFlowState.DaySelection
}
}
}
}
renderer.render(scene)
window.requestAnimationFrame { update() }
}
}
fun main(args: Array<String>)
{
window.onload =
{
Game()
}
} | 0 | Kotlin | 0 | 0 | cde79237592b4a7b5481e77c9684f97aa9e5915b | 4,268 | roomservice | MIT License |
core/domain/src/main/kotlin/org/sollecitom/chassis/core/domain/quantity/NonZeroCount.kt | sollecitom | 669,483,842 | false | {"Kotlin": 837953, "Java": 30834} | package org.sollecitom.chassis.core.domain.quantity
@JvmInline
value class NonZeroCount(val value: Int) : Comparable<NonZeroCount> {
init {
require(value > 0) { "value cannot be negative" }
}
override fun compareTo(other: NonZeroCount) = value.compareTo(other.value)
companion object
} | 0 | Kotlin | 0 | 2 | b1a566393c2b7735682c7956ce4808cd74c4e68b | 313 | chassis | MIT License |
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/QuoteOpening.kt | alexzhirkevich | 636,411,288 | false | {"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868} | /*
* Copyright (c) 2023-2024. Compose Cupertino project and open source contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.alexzhirkevich.cupertino.icons.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Outlined.QuoteOpening: ImageVector
get() {
if (_quoteOpening != null) {
return _quoteOpening!!
}
_quoteOpening = Builder(name = "QuoteOpening", defaultWidth = 25.793.dp, defaultHeight =
16.2539.dp, viewportWidth = 25.793f, viewportHeight = 16.2539f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.7188f, 10.6172f)
curveTo(11.7188f, 7.5f, 9.4102f, 5.0156f, 6.4336f, 5.0156f)
curveTo(5.0391f, 5.0156f, 3.7148f, 5.5664f, 2.7422f, 6.6445f)
lineTo(2.4258f, 6.6445f)
curveTo(3.1055f, 4.4297f, 5.168f, 2.5781f, 7.7344f, 1.8164f)
curveTo(8.0977f, 1.6992f, 8.3672f, 1.5938f, 8.5313f, 1.4531f)
curveTo(8.7188f, 1.3008f, 8.8242f, 1.1133f, 8.8242f, 0.8438f)
curveTo(8.8242f, 0.3516f, 8.4492f, 0.0117f, 7.8984f, 0.0117f)
curveTo(7.5352f, 0.0117f, 7.2539f, 0.082f, 6.75f, 0.2461f)
curveTo(5.1328f, 0.7734f, 3.6797f, 1.6992f, 2.5547f, 2.8828f)
curveTo(0.9727f, 4.5234f, 0.0f, 6.7148f, 0.0f, 9.3164f)
curveTo(0.0f, 13.7109f, 2.7891f, 16.2539f, 6.0586f, 16.2539f)
curveTo(9.2813f, 16.2539f, 11.7188f, 13.793f, 11.7188f, 10.6172f)
close()
moveTo(25.793f, 10.6172f)
curveTo(25.793f, 7.5f, 23.4727f, 5.0156f, 20.5078f, 5.0156f)
curveTo(19.1133f, 5.0156f, 17.7773f, 5.5664f, 16.8164f, 6.6445f)
lineTo(16.5f, 6.6445f)
curveTo(17.1797f, 4.4297f, 19.2422f, 2.5781f, 21.7969f, 1.8164f)
curveTo(22.1602f, 1.6992f, 22.4414f, 1.5938f, 22.6055f, 1.4531f)
curveTo(22.793f, 1.3008f, 22.8867f, 1.1133f, 22.8867f, 0.8438f)
curveTo(22.8867f, 0.3516f, 22.5234f, 0.0117f, 21.9727f, 0.0117f)
curveTo(21.5977f, 0.0117f, 21.3281f, 0.082f, 20.8125f, 0.2461f)
curveTo(19.207f, 0.7734f, 17.7422f, 1.6992f, 16.6172f, 2.8828f)
curveTo(15.0469f, 4.5234f, 14.0742f, 6.7148f, 14.0742f, 9.3164f)
curveTo(14.0742f, 13.7109f, 16.8633f, 16.2539f, 20.1328f, 16.2539f)
curveTo(23.3555f, 16.2539f, 25.793f, 13.793f, 25.793f, 10.6172f)
close()
}
}
.build()
return _quoteOpening!!
}
private var _quoteOpening: ImageVector? = null
| 18 | Kotlin | 31 | 848 | 54bfbb58f6b36248c5947de343567903298ee308 | 3,912 | compose-cupertino | Apache License 2.0 |
src/main/kotlin/io/emeraldpay/dshackle/quorum/ValueAwareQuorum.kt | bitindi | 692,819,625 | false | {"Kotlin": 974369, "Groovy": 712181, "Java": 21948, "JavaScript": 5522, "Shell": 646} | /**
* Copyright (c) 2020 EmeraldPay, Inc
* Copyright (c) 2019 ETCDEV GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.emeraldpay.dshackle.quorum
import io.emeraldpay.dshackle.Global
import io.emeraldpay.dshackle.upstream.Upstream
import io.emeraldpay.dshackle.upstream.rpcclient.JsonRpcError
import io.emeraldpay.dshackle.upstream.rpcclient.JsonRpcException
import io.emeraldpay.dshackle.upstream.signature.ResponseSigner
import io.emeraldpay.etherjar.rpc.RpcException
import org.slf4j.LoggerFactory
abstract class ValueAwareQuorum<T>(
val clazz: Class<T>
) : CallQuorum {
private val log = LoggerFactory.getLogger(ValueAwareQuorum::class.java)
private var rpcError: JsonRpcError? = null
protected val resolvers = ArrayList<Upstream>()
fun extractValue(response: ByteArray, clazz: Class<T>): T? {
return Global.objectMapper.readValue(response.inputStream(), clazz)
}
override fun record(
response: ByteArray,
signature: ResponseSigner.Signature?,
upstream: Upstream
): Boolean {
try {
val value = extractValue(response, clazz)
recordValue(response, value, signature, upstream)
resolvers.add(upstream)
} catch (e: RpcException) {
recordError(response, e.rpcMessage, signature, upstream)
} catch (e: Exception) {
recordError(response, e.message, signature, upstream)
}
return isResolved()
}
override fun record(
error: JsonRpcException,
signature: ResponseSigner.Signature?,
upstream: Upstream
) {
this.rpcError = error.error
recordError(null, error.error.message, signature, upstream)
}
abstract fun recordValue(
response: ByteArray,
responseValue: T?,
signature: ResponseSigner.Signature?,
upstream: Upstream
)
abstract fun recordError(
response: ByteArray?,
errorMessage: String?,
signature: ResponseSigner.Signature?,
upstream: Upstream
)
override fun getError(): JsonRpcError? {
return rpcError
}
override fun getResolvedBy(): Collection<Upstream> = resolvers
}
| 0 | Kotlin | 0 | 0 | 3dafa23728acfdfd046580dc0d1fcb9ba61718d4 | 2,729 | dshackle | Apache License 2.0 |
geeksmediapicker/src/main/java/com/geeksmediapicker/utils/ViewExtensions.kt | im-manisharma | 271,395,161 | false | null | package com.geeksmediapicker.utils
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.geeksmediapicker.R
internal fun View.visible() {
visibility = View.VISIBLE
}
internal fun View.gone() {
visibility = View.GONE
}
internal fun View.invisible() {
visibility = View.INVISIBLE
}
internal fun View.isVisible(): Boolean = visibility == View.VISIBLE
internal fun Context.showToast(message: String) {
val myInflater = LayoutInflater.from(this)
val view = myInflater.inflate(R.layout.my_custom_toast, null)
val myToast = Toast(this)
myToast.duration = Toast.LENGTH_SHORT
myToast.view = view
view.findViewById<TextView>(R.id.tvMsg).text = message
myToast.show()
}
| 1 | Kotlin | 3 | 13 | e8eefc69dfc78574817bd6408f459755074529e0 | 816 | GeeksMediaPicker | MIT License |
src/main/kotlin/BMI.kt | Talnz007 | 728,051,979 | false | {"Kotlin": 7941, "JavaScript": 5597, "HTML": 1669, "CSS": 930} | open class BMI {
var WeightKg: Double = 0.0
var HeightM: Double = 0.0
open var HeightFeet: Double = 0.0
open var HeightInches: Double = 0.0
var HeightTotal: Double = 0.0
open var WeightLb: Double = 0.0
}
| 0 | Kotlin | 0 | 0 | ec3ca3d046a7dc32616962b7df1dc64e1bd77380 | 228 | BMI-CALCULATOR | Apache License 2.0 |
src/main/kotlin/com/projectcitybuild/features/warps/usecases/CreateWarpUseCase.kt | projectcitybuild | 42,997,941 | false | null | package com.projectcitybuild.features.warps.usecases
import com.projectcitybuild.core.utilities.Failure
import com.projectcitybuild.core.utilities.Result
import com.projectcitybuild.core.utilities.Success
import com.projectcitybuild.entities.CrossServerLocation
import com.projectcitybuild.entities.Warp
import com.projectcitybuild.features.warps.events.WarpCreateEvent
import com.projectcitybuild.features.warps.repositories.WarpRepository
import com.projectcitybuild.modules.datetime.time.Time
import com.projectcitybuild.modules.eventbroadcast.LocalEventBroadcaster
import javax.inject.Inject
class CreateWarpUseCase @Inject constructor(
private val warpRepository: WarpRepository,
private val localEventBroadcaster: LocalEventBroadcaster,
private val time: Time,
) {
enum class FailureReason {
WARP_ALREADY_EXISTS,
}
fun createWarp(name: String, location: CrossServerLocation): Result<Unit, FailureReason> {
if (warpRepository.exists(name)) {
return Failure(FailureReason.WARP_ALREADY_EXISTS)
}
val warp = Warp(
name,
location,
time.now()
)
warpRepository.add(warp)
localEventBroadcaster.emit(WarpCreateEvent())
return Success(Unit)
}
} | 23 | Kotlin | 0 | 2 | 24c6a86aee15535c3122ba6fb57cc7ca351e32bb | 1,285 | PCBridge | MIT License |
src/main/kotlin/kz/btsd/messenger/bot/api/model/update/FormUpdate.kt | btsdigital | 195,374,563 | false | null | package kz.btsd.messenger.bot.api.model.update
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import io.swagger.annotations.ApiModel
import kz.btsd.messenger.bot.api.model.peer.Peer
@ApiModel(discriminator = "type", subTypes = [
FormClosed::class,
FormMessageSent::class,
FormSubmitted::class
])
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true)
@JsonSubTypes(value = [
JsonSubTypes.Type(value = FormClosed::class, name = "FormClosed"),
JsonSubTypes.Type(value = FormSubmitted::class, name = "FormSubmitted"),
JsonSubTypes.Type(value = FormMessageSent::class, name = "FormMessageSent")
])
abstract class FormUpdate(
override val updateId: String,
open val formId: String,
open val dialog: Peer,
open val sender: Peer,
override val type: String
) : Update(updateId, type)
| 0 | Kotlin | 1 | 15 | 6279fd30b15e4896a6810d9ebda3436a90dd6781 | 948 | bot-api-contract | Apache License 2.0 |
core/src/commonMain/kotlin/org/kobjects/greenspun/core/func/ImportedFunc.kt | kobjects | 340,712,554 | false | {"Kotlin": 92759, "Ruby": 1673} | package org.kobjects.greenspun.core.func
import org.kobjects.greenspun.core.tree.CodeWriter
import org.kobjects.greenspun.core.type.FuncType
class ImportedFunc(
override val index: Int,
val module: String,
val name: String,
override val type: FuncType
) : FuncInterface {
override val localContextSize: Int
get() = type.parameterTypes.size
override fun call(context: LocalRuntimeContext) =
context.instance.imports[index](context.instance, context.variables)
override fun toString(writer: CodeWriter) {
writer.newLine()
writer.newLine()
writer.write("val func$index = ")
writer.write("ImportFunc(")
writer.writeQuoted(module)
writer.write(", ")
writer.writeQuoted(name)
writer.write(", ")
writer.write(type.returnType)
for (param in type.parameterTypes) {
writer.write(", ")
writer.write(param)
}
writer.write(")")
}
override fun toString() = "import$index"
} | 0 | Kotlin | 0 | 0 | 1f55591687303d28af1acdc4d567f491281378c7 | 1,039 | greenspun | Apache License 2.0 |
showkase/src/main/java/com/airbnb/android/showkase/exceptions/ShowkaseException.kt | airbnb | 257,758,318 | false | {"Kotlin": 715619} | package com.airbnb.android.showkase.exceptions
import java.lang.Exception
/**
* Used to throw an exception for Showkase specific errors.
*/
internal class ShowkaseException(message: String): Exception(message)
| 50 | Kotlin | 106 | 2,073 | 9c3d6fc313d63b8f555fc65232ac15f798aede9a | 215 | Showkase | Apache License 2.0 |
Lemonade/app/src/main/java/com/example/lemonade/MainActivity.kt | correabuscar | 774,353,112 | false | {"Kotlin": 828886, "Shell": 2341} | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.BottomCenter
import androidx.compose.ui.Alignment.Companion.Top
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.modifier.modifierLocalConsumer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.lemonade.ui.theme.LemonadeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LemonadeTheme {
LemonApp()
}
}
}
}
@Composable
fun LemonApp(initialStep:Int =1) {
// Current step the app is displaying (remember allows the state to be retained
// across recompositions).
var currentStep by rememberSaveable { mutableStateOf(initialStep) }
// Number of times the lemon needs to be squeezed to turn into a glass of lemonade
var squeezeCount by rememberSaveable { mutableStateOf(0) }
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
when (currentStep) {
1 -> {
// Display lemon tree image and ask user to pick a lemon from the tree
LemonTextAndImage(
textLabelResourceId = R.string.lemon_select,
drawableResourceId = R.drawable.lemon_tree,
contentDescriptionResourceId = R.string.lemon_tree_content_description,
onImageClick = {
// Update to next step
currentStep = 2
// Each time a lemon is picked from the tree, get a new random number
// between 2 and 4 (inclusive) for the number of times the lemon needs
// to be squeezed to turn into lemonade
squeezeCount = (4..8).random()
}
)
}
2 -> {
// Column(
// horizontalAlignment = Alignment.CenterHorizontally,
// verticalArrangement = Arrangement.Top,
// //modifier = Modifier.//wrapContentSize(unbounded = true)//Height(Top)//fillMaxSize()//.padding(10.dp)
// modifier = Modifier.fillMaxSize(1f).padding(0.dp)
// ) {
Box(
//modifier = Modifier.fillMaxSize(),
) {
// Display lemon image and ask user to squeeze the lemon
LemonTextAndImage(
textLabelResourceId = R.string.lemon_squeeze,
drawableResourceId = R.drawable.lemon_squeeze,
contentDescriptionResourceId = R.string.lemon_content_description,
onImageClick = {
// Decrease the squeeze count by 1 for each click the user performs
squeezeCount--
// When we're done squeezing the lemon, move to the next step
if (squeezeCount <= 0) {
currentStep = 3
}
},
//modifier=Modifier.wrapContentSize(Alignment.Center,unbounded = true)
//modifier=Modifier.fillMaxSize()
)
Text("Taps left: "+squeezeCount.toString(),
//modifier=Modifier.weight(1f)
textAlign = TextAlign.Center,//Arrangement.aligned(Alignment.CenterHorizontally)
modifier=Modifier.align(BottomCenter).padding(bottom=240.dp)//FIXME: hack!
)
}
}
3 -> {
// Display glass of lemonade image and ask user to drink the lemonade
LemonTextAndImage(
textLabelResourceId = R.string.lemon_drink,
drawableResourceId = R.drawable.lemon_drink,
contentDescriptionResourceId = R.string.lemonade_content_description,
onImageClick = {
// Update to next step
currentStep = 4
}
)
}
4 -> {
// Display empty glass image and ask user to start again
LemonTextAndImage(
textLabelResourceId = R.string.lemon_empty_glass,
drawableResourceId = R.drawable.lemon_restart,
contentDescriptionResourceId = R.string.empty_glass_content_description,
onImageClick = {
// Back to starting step
currentStep = 1
}
)
}
}
}
}
/**
* Composable that displays a text label above an image that is clickable.
*
* @param textLabelResourceId is the resource ID for the text string to display
* @param drawableResourceId is the resource ID for the image drawable to display below the text
* @param contentDescriptionResourceId is the resource ID for the string to use as the content
* description for the image
* @param onImageClick will be called when the user clicks the image
* @param modifier modifiers to set to this composable
*/
@Composable
fun LemonTextAndImage(
textLabelResourceId: Int,
drawableResourceId: Int,
contentDescriptionResourceId: Int,
onImageClick: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = modifier.fillMaxSize()//0.9f)
//modifier = modifier.fillMaxWidth()
) {
Text(
text = stringResource(textLabelResourceId),
fontSize = 18.sp
)
Spacer(modifier = Modifier.height(16.dp))
Image(
painter = painterResource(drawableResourceId),
contentDescription = stringResource(contentDescriptionResourceId),
modifier = Modifier
.wrapContentSize()
.clickable(
onClick = onImageClick
)
.border(
BorderStroke(2.dp, Color(105, 205, 216)),
shape = RoundedCornerShape(44.dp)
)
.padding(26.dp)
)
}
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true, showSystemUi = true)
@Composable
fun LemonPreview1() {
LemonadeTheme() {
LemonApp(1)
//LemonApp(2)
}
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview2() {
LemonadeTheme() {
LemonApp(2)
}
}@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview3() {
LemonadeTheme() {
LemonApp(3)
}
}@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview4() {
LemonadeTheme() {
LemonApp(4)
}
} | 0 | Kotlin | 0 | 0 | 059f1d543e4d07117698983e1f93c3106dd09a73 | 8,840 | android_projects_sandbox | Apache License 2.0 |
Lemonade/app/src/main/java/com/example/lemonade/MainActivity.kt | correabuscar | 774,353,112 | false | {"Kotlin": 828886, "Shell": 2341} | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.BottomCenter
import androidx.compose.ui.Alignment.Companion.Top
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.modifier.modifierLocalConsumer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.lemonade.ui.theme.LemonadeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LemonadeTheme {
LemonApp()
}
}
}
}
@Composable
fun LemonApp(initialStep:Int =1) {
// Current step the app is displaying (remember allows the state to be retained
// across recompositions).
var currentStep by rememberSaveable { mutableStateOf(initialStep) }
// Number of times the lemon needs to be squeezed to turn into a glass of lemonade
var squeezeCount by rememberSaveable { mutableStateOf(0) }
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
when (currentStep) {
1 -> {
// Display lemon tree image and ask user to pick a lemon from the tree
LemonTextAndImage(
textLabelResourceId = R.string.lemon_select,
drawableResourceId = R.drawable.lemon_tree,
contentDescriptionResourceId = R.string.lemon_tree_content_description,
onImageClick = {
// Update to next step
currentStep = 2
// Each time a lemon is picked from the tree, get a new random number
// between 2 and 4 (inclusive) for the number of times the lemon needs
// to be squeezed to turn into lemonade
squeezeCount = (4..8).random()
}
)
}
2 -> {
// Column(
// horizontalAlignment = Alignment.CenterHorizontally,
// verticalArrangement = Arrangement.Top,
// //modifier = Modifier.//wrapContentSize(unbounded = true)//Height(Top)//fillMaxSize()//.padding(10.dp)
// modifier = Modifier.fillMaxSize(1f).padding(0.dp)
// ) {
Box(
//modifier = Modifier.fillMaxSize(),
) {
// Display lemon image and ask user to squeeze the lemon
LemonTextAndImage(
textLabelResourceId = R.string.lemon_squeeze,
drawableResourceId = R.drawable.lemon_squeeze,
contentDescriptionResourceId = R.string.lemon_content_description,
onImageClick = {
// Decrease the squeeze count by 1 for each click the user performs
squeezeCount--
// When we're done squeezing the lemon, move to the next step
if (squeezeCount <= 0) {
currentStep = 3
}
},
//modifier=Modifier.wrapContentSize(Alignment.Center,unbounded = true)
//modifier=Modifier.fillMaxSize()
)
Text("Taps left: "+squeezeCount.toString(),
//modifier=Modifier.weight(1f)
textAlign = TextAlign.Center,//Arrangement.aligned(Alignment.CenterHorizontally)
modifier=Modifier.align(BottomCenter).padding(bottom=240.dp)//FIXME: hack!
)
}
}
3 -> {
// Display glass of lemonade image and ask user to drink the lemonade
LemonTextAndImage(
textLabelResourceId = R.string.lemon_drink,
drawableResourceId = R.drawable.lemon_drink,
contentDescriptionResourceId = R.string.lemonade_content_description,
onImageClick = {
// Update to next step
currentStep = 4
}
)
}
4 -> {
// Display empty glass image and ask user to start again
LemonTextAndImage(
textLabelResourceId = R.string.lemon_empty_glass,
drawableResourceId = R.drawable.lemon_restart,
contentDescriptionResourceId = R.string.empty_glass_content_description,
onImageClick = {
// Back to starting step
currentStep = 1
}
)
}
}
}
}
/**
* Composable that displays a text label above an image that is clickable.
*
* @param textLabelResourceId is the resource ID for the text string to display
* @param drawableResourceId is the resource ID for the image drawable to display below the text
* @param contentDescriptionResourceId is the resource ID for the string to use as the content
* description for the image
* @param onImageClick will be called when the user clicks the image
* @param modifier modifiers to set to this composable
*/
@Composable
fun LemonTextAndImage(
textLabelResourceId: Int,
drawableResourceId: Int,
contentDescriptionResourceId: Int,
onImageClick: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = modifier.fillMaxSize()//0.9f)
//modifier = modifier.fillMaxWidth()
) {
Text(
text = stringResource(textLabelResourceId),
fontSize = 18.sp
)
Spacer(modifier = Modifier.height(16.dp))
Image(
painter = painterResource(drawableResourceId),
contentDescription = stringResource(contentDescriptionResourceId),
modifier = Modifier
.wrapContentSize()
.clickable(
onClick = onImageClick
)
.border(
BorderStroke(2.dp, Color(105, 205, 216)),
shape = RoundedCornerShape(44.dp)
)
.padding(26.dp)
)
}
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true, showSystemUi = true)
@Composable
fun LemonPreview1() {
LemonadeTheme() {
LemonApp(1)
//LemonApp(2)
}
}
@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview2() {
LemonadeTheme() {
LemonApp(2)
}
}@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview3() {
LemonadeTheme() {
LemonApp(3)
}
}@Preview(uiMode = UI_MODE_NIGHT_YES, showBackground = true)
@Composable
fun LemonPreview4() {
LemonadeTheme() {
LemonApp(4)
}
} | 0 | Kotlin | 0 | 0 | 059f1d543e4d07117698983e1f93c3106dd09a73 | 8,840 | android_projects_sandbox | Apache License 2.0 |
circuitkt/src/main/kotlin/com/github/cybercodernaj/components/gates/Xnor.kt | cybercoder-naj | 567,041,894 | false | {"Kotlin": 6211} | package com.github.cybercodernaj.components.gates
/**
* Xnor gate's output is the inverted form of the Xor gate.
*
* @see Xor
*/
class Xnor : Gate() {
override fun simulate() {
if (inputs.size <= 1)
throw IllegalStateException()
val ones = inputs.count { it.current }
outputs.onEach {
it.current = ones !in 1 until inputs.size
}
}
} | 1 | Kotlin | 0 | 0 | 3ccb6f375081b1ffcf6bf535818c8b83c9a55ca6 | 402 | CircuitKt | MIT License |
app/src/main/java/net/pfiers/osmfocus/view/support/ViewFunctions.kt | ubipo | 310,888,250 | false | {"Kotlin": 276359, "Ruby": 583} | package net.pfiers.osmfocus.view.support
import android.content.res.Resources
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.view.Gravity
import androidx.annotation.ColorInt
import net.pfiers.osmfocus.service.jts.toDecimalDegrees
import net.pfiers.osmfocus.service.tagboxlocation.TbLoc
import org.locationtech.jts.geom.Coordinate
import org.ocpsoft.prettytime.PrettyTime
import java.time.Instant
@ExperimentalStdlibApi
class ViewFunctions {
companion object {
private val prettyTime = PrettyTime()
@JvmStatic
fun gravityFromTbLoc(tbLoc: TbLoc): Int {
val gravityRow = when (tbLoc.y) {
TbLoc.Y.TOP -> Gravity.TOP
TbLoc.Y.MIDDLE -> Gravity.CENTER_VERTICAL
TbLoc.Y.BOTTOM -> Gravity.BOTTOM
}
val gravityColumn = when (tbLoc.x) {
TbLoc.X.LEFT -> Gravity.START
TbLoc.X.MIDDLE -> Gravity.CENTER_HORIZONTAL
TbLoc.X.RIGHT -> Gravity.END
}
return gravityRow or gravityColumn
}
@JvmStatic
fun createStrokeFrameBg(
strokeWidthDp: Float,
@ColorInt strokeColor: Int,
@ColorInt bgColor: Int
) =
GradientDrawable().apply {
setStroke(dpToPx(strokeWidthDp), strokeColor)
setColor(bgColor)
}
private val pxToDpCache = HashMap<Float, Int>()
@JvmStatic
fun dpToPx(dp: Float): Int = pxToDpCache.getOrPut(dp) {
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
Resources.getSystem().displayMetrics
).toInt()
}
@JvmStatic
fun prettyTime(instant: Instant): String = prettyTime.format(instant)
@JvmStatic
fun decimalDegrees(coordinate: Coordinate) = coordinate.toDecimalDegrees()
}
}
| 7 | Kotlin | 5 | 43 | 53cfdeff366aa23627ea2b6d824c949bc052f25c | 1,974 | osmfocus | Apache License 2.0 |
app/src/test/java/org/simple/clinic/reassignpatient/ReassignPatientUpdateTest.kt | resolvetosavelives | 132,515,649 | false | {"Gradle Kotlin DSL": 10, "Shell": 11, "Markdown": 37, "Java Properties": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "YAML": 11, "Git Attributes": 1, "EditorConfig": 1, "JSON5": 1, "Kotlin": 2464, "XML": 365, "INI": 5, "Proguard": 4, "TOML": 1, "Python": 3, "JSON": 117, "HTML": 1} | package org.simple.clinic.reassignpatient
import com.spotify.mobius.test.NextMatchers.hasEffects
import com.spotify.mobius.test.NextMatchers.hasModel
import com.spotify.mobius.test.NextMatchers.hasNoEffects
import com.spotify.mobius.test.NextMatchers.hasNoModel
import com.spotify.mobius.test.UpdateSpec
import com.spotify.mobius.test.UpdateSpec.assertThatNext
import org.junit.Test
import org.simple.sharedTestCode.TestData
import java.util.Optional
import java.util.UUID
class ReassignPatientUpdateTest {
private val patientUuid = UUID.fromString("b66a9d8e-fdf1-494f-b9d7-6e7cc5679cbe")
private val updateSpec = UpdateSpec(ReassignPatientUpdate())
private val model = ReassignPatientModel.create(patientUuid)
@Test
fun `when assigned facility is loaded, then update the model`() {
val facility = TestData.facility(
uuid = UUID.fromString("06f5e0af-9464-4636-807a-dbb9984061fd"),
name = "UHC Doha"
)
updateSpec
.given(model)
.whenEvent(AssignedFacilityLoaded(Optional.of(facility)))
.then(assertThatNext(
hasModel(model.assignedFacilityUpdated(facility)),
hasNoEffects()
))
}
@Test
fun `when reassign patient not now is clicked, then close sheet`() {
updateSpec
.given(model)
.whenEvent(NotNowClicked)
.then(assertThatNext(
hasNoModel(),
hasEffects(CloseSheet(ReassignPatientSheetClosedFrom.NOT_NOW))
))
}
@Test
fun `when reassign patient change is clicked, then open select facility sheet`() {
updateSpec
.given(model)
.whenEvent(ChangeClicked)
.then(assertThatNext(
hasNoModel(),
hasEffects(OpenSelectFacilitySheet)
))
}
@Test
fun `when new assign facility is selected, then change the assigned facility`() {
val assignedFacility = TestData.facility(
uuid = UUID.fromString("06f5e0af-9464-4636-807a-dbb9984061fd"),
name = "<NAME>"
)
updateSpec
.given(model)
.whenEvent(NewAssignedFacilitySelected(assignedFacility))
.then(assertThatNext(
hasNoModel(),
hasEffects(ChangeAssignedFacility(model.patientUuid, assignedFacility.uuid))
))
}
@Test
fun `when assigned facility is changed, then close the sheet`() {
updateSpec
.given(model)
.whenEvent(AssignedFacilityChanged)
.then(assertThatNext(
hasNoModel(),
hasEffects(CloseSheet(ReassignPatientSheetClosedFrom.CHANGE))
))
}
}
| 1 | null | 1 | 1 | 73e215679850d3ecdbd4c7d7f1d46477941bd5d0 | 2,569 | redapp | MIT License |
src/main/kotlin/ui/HomeTab.kt | XiLaiTL | 813,186,648 | false | {"Kotlin": 90879, "ANTLR": 2191} | package ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import cafe.adriel.voyager.navigator.tab.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
sealed class HomeTabs{
object Code : Tab, HomeTabs() {
override val options: TabOptions
@Composable
get() {
val title = "代码片段解释器"
val icon = rememberVectorPainter(Icons.Default.Build)
return remember { TabOptions(index = 0u, title = title, icon = icon) }
}
@Composable
override fun Content() {
CodeCalculatorPage()
}
}
object Single : Tab,HomeTabs() {
override val options: TabOptions
@Composable
get() {
val title = "Lambda表达式演算"
val icon = rememberVectorPainter(Icons.Default.Edit)
return remember { TabOptions(index = 1u, title = title, icon = icon) }
}
@Composable
override fun Content() {
SingleCalculatorPage()
}
}
companion object{
var scaffoldState:ScaffoldState? = null
var scope:CoroutineScope? = null
fun showInfo(info:String){
scope?.launch {
scaffoldState?.snackbarHostState?.showSnackbar(info)
}
}
}
}
@Composable
fun HomeTabBar(){
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()
HomeTabs.scope=scope
HomeTabs.scaffoldState=scaffoldState
TabNavigator(HomeTabs.Single) {
Scaffold(
content = {
CurrentTab()
},
scaffoldState = scaffoldState,
snackbarHost = {
SnackbarHost(it, snackbar = { st ->
Snackbar(
st, backgroundColor = SnackbarDefaults.backgroundColor,
contentColor = MaterialTheme.colors.onBackground,
actionColor = SnackbarDefaults.primaryActionColor,
)
})
},
topBar = {
TopAppBar {
TabNavigationItem(HomeTabs.Single)
TabNavigationItem(HomeTabs.Code)
}
}
)
}
}
@Composable
private fun RowScope.TabNavigationItem(tab: Tab) {
val tabNavigator = LocalTabNavigator.current
BottomNavigationItem(
selected = tabNavigator.current == tab,
onClick = { tabNavigator.current = tab },
icon = { Icon(painter = tab.options.icon!!, contentDescription = tab.options.title) },
label = { Text(tab.options.title) },
modifier = Modifier.background(MaterialTheme.colors.surface)
)
} | 0 | Kotlin | 0 | 0 | 42d6310fc931510561970ae2c0e379b462ba9ec0 | 3,075 | lambda-calculator | MIT License |
src/main/kotlin/me/nepnep/nepbot/message/command/commands/fun/Lmddgtfy.kt | NepNep21 | 332,348,863 | false | null | package me.nepnep.nepbot.message.command.commands.`fun`
import me.nepnep.nepbot.message.command.Category
import me.nepnep.nepbot.message.command.AbstractCommand
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.entities.GuildMessageChannel
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
class Lmddgtfy : AbstractCommand(
"lmddgtfy",
Category.FUN,
"Searches something for you on duck duck go: ;lmddgtfy <String query>"
) {
override fun execute(args: List<String>, event: MessageReceivedEvent, channel: GuildMessageChannel) {
val query = args.subList(0, args.size).joinToString(" ")
val safe = query.replace(" ", "%20")
val embed = EmbedBuilder().setDescription("[Result](https://lmddgtfy.net/?q=$safe)").build()
channel.sendMessageEmbeds(embed).queue()
}
} | 0 | Kotlin | 1 | 1 | e46f9f06de4d31abc41e9795dff40ae421d42f51 | 843 | nepbot | MIT License |
investor/src/main/java/com/mityushov/investor/database/StockDatabase.kt | NikitaMityushov | 391,630,324 | false | null | package com.mityushov.investor.database
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.mityushov.investor.models.StockPurchase
@Database(entities = [StockPurchase::class], version = 1)
@TypeConverters(StockTypeConverter::class)
abstract class StockDatabase: RoomDatabase() {
abstract fun stockDao(): StockDao
} | 0 | Kotlin | 0 | 0 | 81c1ecacf09a8140d7bb325954cfea65f2f1c0e6 | 380 | AndroidClasses | MIT License |
crp-util-desktop/src/main/kotlin/com/x256n/desktop/crputil/component/ResultPanelScreen.kt | liosha2007 | 471,299,880 | false | null | package com.x256n.desktop.crputil.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.x256n.desktop.crputil.ActivePanel
import com.x256n.desktop.crputil.DisplayResultItem
import com.x256n.desktop.crputil.LogMessage
import com.x256n.desktop.crputil.MainViewModel
@Composable
fun ResultPanelScreen(modifier: Modifier = Modifier, viewModel: MainViewModel) {
val state = viewModel.state.value
val multiplier = if (state.activePanel == ActivePanel.RESULT) 1.6f else 1f
Column(
modifier = modifier.background(Color.Black).fillMaxHeight()
) {
Column(
modifier = Modifier
.padding(10.dp)
.fillMaxHeight()
) {
if (state.result.isNotEmpty()) {
MessageItemScreen(multiplier, LogMessage.InfoMessage("Результати"))
ResultHeaserScreen(multiplier, viewModel)
LazyColumn(
modifier = Modifier.weight(1f),
) {
items(state.result) { item ->
when (item) {
is DisplayResultItem.Message -> {
MessageItemScreen(multiplier, item.message)
}
is DisplayResultItem.Delimiter -> {
Spacer(
modifier = Modifier
.fillMaxWidth().height(1.dp)
.padding(horizontal = 15.dp)
.background(Color.Green)
)
}
is DisplayResultItem.AnswerUp -> {
val time = if (item.time % 1000 == 0) {
"${item.time / 1000}sec"
} else {
"${item.time}ms"
}
ItemScreen(
multiplier = multiplier,
ip = item.ip,
port = item.port,
time = time,
host = item.host,
viewModel = viewModel
) {
LogMessage.SuccessMessage(it)
}
}
is DisplayResultItem.AnswerDown -> {
val timeout = if (item.timeout % 1000 == 0) {
"${item.timeout / 1000}sec"
} else {
"${item.timeout}ms"
}
ItemScreen(
multiplier = multiplier,
ip = item.ip,
port = item.port,
time = "n/a (>$timeout)",
host = item.host,
viewModel = viewModel
) {
LogMessage.WarningMessage(it)
}
}
}
}
}
}
}
}
}
@Composable
private fun ResultHeaserScreen(multiplier: Float, viewModel: MainViewModel) {
Row {
Row(
modifier = Modifier.width(95.dp * multiplier),
verticalAlignment = Alignment.CenterVertically
) {
val menu = remember { mutableStateOf(false) }
Icon(
modifier = Modifier
.background(Color.White)
.size(10.dp)
.clickable { menu.value = !menu.value },
imageVector = Icons.Default.Menu,
contentDescription = "Menu"
)
ContextMenuScreen(menu, viewModel)
Text(
modifier = Modifier
.padding(start = 5.dp),
text = "IP",
style = TextStyle(
fontSize = 10.sp * multiplier,
color = Color.White,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.W600
)
)
}
Text(
modifier = Modifier.width(45.dp * multiplier),
text = "port",
style = TextStyle(
fontSize = 10.sp * multiplier,
color = Color.White,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.W600
)
)
Text(
modifier = Modifier.width(85.dp * multiplier),
text = "time",
style = TextStyle(
fontSize = 10.sp * multiplier,
color = Color.White,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.W600
)
)
Text(
modifier = Modifier.weight(1f),
text = "host",
style = TextStyle(
fontSize = 10.sp * multiplier,
color = Color.White,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.W600
)
)
}
}
@Composable
fun ItemScreen(
multiplier: Float,
ip: String,
port: Int,
time: String,
host: String,
viewModel: MainViewModel,
LogMessageBuilder: (value: String) -> LogMessage
) {
Row(
modifier = Modifier.fillMaxWidth()
) {
Text(
modifier = Modifier.width(95.dp * multiplier)
.clickable {
viewModel.onCopyToClipboard(ip)
},
text = buildAnnotatedString {
AnnotatedLogMessageScreen(LogMessageBuilder(ip))
}, style = MaterialTheme.typography.body1.copy(
fontSize = 10.sp * multiplier,
)
)
Text(
modifier = Modifier.width(45.dp * multiplier)
.clickable {
viewModel.onCopyToClipboard("$ip:$port")
},
text = buildAnnotatedString {
AnnotatedLogMessageScreen(LogMessageBuilder(":$port"))
}, style = MaterialTheme.typography.body1.copy(
fontSize = 10.sp * multiplier,
)
)
Text(
modifier = Modifier.width(85.dp * multiplier), text = buildAnnotatedString {
AnnotatedLogMessageScreen(LogMessageBuilder(time))
}, style = MaterialTheme.typography.body1.copy(
fontSize = 10.sp * multiplier,
)
)
if (host.isEmpty()) {
Text(
modifier = Modifier.weight(1f)
.clickable {
viewModel.onResolveHost(ip)
},
text = "?",
style = TextStyle(
fontSize = 10.sp * multiplier,
color = Color.Blue,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.W600
)
)
} else {
Text(
modifier = Modifier
.weight(1f)
.clickable {
if (host != "-") {
viewModel.onCopyToClipboard(host)
}
},
text = buildAnnotatedString {
AnnotatedLogMessageScreen(LogMessageBuilder(host))
}, style = MaterialTheme.typography.body1.copy(
fontSize = 10.sp * multiplier,
)
)
}
}
}
@Composable
fun MessageItemScreen(multiplier: Float, log: LogMessage) {
Text(
modifier = Modifier.fillMaxWidth().padding(4.dp),
text = buildAnnotatedString {
AnnotatedLogMessageScreen(log)
},
style = MaterialTheme.typography.body1.copy(
fontSize = 10.sp * multiplier,
)
)
} | 0 | Kotlin | 0 | 0 | 23ec8032fbe3719a6e9a6b5d80cfb88fa2a31a90 | 9,294 | crp-util | MIT License |
src/main/kotlin/com/ravishrajput/restapi/controller/UserController.kt | ravishrajput | 402,513,929 | false | {"Kotlin": 19744, "CSS": 16568, "FreeMarker": 6208, "Procfile": 68} | package com.ravishrajput.restapi.controller
import com.ravishrajput.restapi.database.DaoRepository
import com.ravishrajput.restapi.model.Response
import com.ravishrajput.restapi.model.User
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
fun Route.routeUser(dao: DaoRepository) {
get("/user") {
val userList = mapOf("users" to dao.getAllUsers())
call.respond(userList)
}
get("/user/{id}") {
val id = call.parameters["id"]
id?.let {
val user = dao.getUser(it.toInt())
call.respond(user ?: Response(404, "Record not found!"))
} ?: call.respond(Response(400, "Invalid id!"))
}
delete("/user/{id}") {
val id = call.parameters["id"]
id?.let {
dao.deleteUser(it.toInt())
call.respond(Response(200, "Record deleted!"))
} ?: call.respond(Response(400, "Invalid id!"))
}
post("/user") {
val user = call.receiveParameters().run {
User(
id = null,
this["name"].toString(),
this["username"].toString(),
this["email"].toString(),
this["imageUrl"].toString()
)
}
dao.createUser(user)
call.respond(Response(200, "User Added Successfully!"))
}
} | 0 | Kotlin | 0 | 2 | 21500be0420b8e41de7e9efc9e905975ed1360f2 | 1,371 | ktor-rest-api-example | Apache License 2.0 |
data/src/main/java/com/foobarust/data/models/seller/SellerRatingCountDto.kt | foobar-UST | 285,792,732 | false | null | package com.foobarust.data.models.seller
import com.foobarust.data.constants.Constants.SELLER_RATING_COUNT_EXCELLENT_FIELD
import com.foobarust.data.constants.Constants.SELLER_RATING_COUNT_FAIR_FIELD
import com.foobarust.data.constants.Constants.SELLER_RATING_COUNT_GOOD_FIELD
import com.foobarust.data.constants.Constants.SELLER_RATING_COUNT_POOR_FIELD
import com.foobarust.data.constants.Constants.SELLER_RATING_COUNT_VERY_GOOD_FIELD
import com.google.firebase.firestore.PropertyName
/**
* Created by kevin on 3/3/21
*/
data class SellerRatingCountDto(
@JvmField
@PropertyName(SELLER_RATING_COUNT_EXCELLENT_FIELD)
val excellent: Int? = null,
@JvmField
@PropertyName(SELLER_RATING_COUNT_VERY_GOOD_FIELD)
val veryGood: Int? = null,
@JvmField
@PropertyName(SELLER_RATING_COUNT_GOOD_FIELD)
val good: Int? = null,
@JvmField
@PropertyName(SELLER_RATING_COUNT_FAIR_FIELD)
val fair: Int? = null,
@JvmField
@PropertyName(SELLER_RATING_COUNT_POOR_FIELD)
val poor: Int? = null
) | 0 | Kotlin | 2 | 2 | b4358ef0323a0b7a95483223496164e616a01da5 | 1,038 | foobar-android | MIT License |
app/src/main/java/com/breezebengaldetergentproducts/app/domain/ContactActivityEntity.kt | DebashisINT | 863,405,964 | false | {"Kotlin": 15991783, "Java": 1032672} | package com.breezebengaldetergentproducts.app.domain
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.breezebengaldetergentproducts.app.AppConstant
@Entity(tableName = AppConstant.CONTACT_ACTIVITY)
data class ContactActivityEntity (
@PrimaryKey(autoGenerate = true) var sl_no: Int = 0,
@ColumnInfo var shop_id:String = "",
@ColumnInfo var activity_date:String = "",
@ColumnInfo var create_date_time:String = "",
@ColumnInfo var isActivityDone:Boolean = false
) | 0 | Kotlin | 0 | 0 | 0cd8b29158b494893e3d7be77b87a725e3d49abf | 536 | BengalDetergentProducts | Apache License 2.0 |
libs/lib_threading/src/main/java/com/bael/executor/demo/lib/threading/executor/concurrent/contract/ConcurrentExecutor.kt | ErickSumargo | 291,285,538 | false | null | package com.bael.executor.demo.lib.threading.executor.concurrent.contract
/**
* Created by ErickSumargo on 01/09/20.
*/
interface ConcurrentExecutor {
suspend fun <T> run(block: suspend () -> T): T
}
| 0 | Kotlin | 3 | 12 | a1314a7e8278fba319029dfd7f758edc42c14e13 | 209 | Executor-Demo | MIT License |
app/src/main/kotlin/com/delicious/mvvm/di/component/AppComponent.kt | pzverkov | 181,941,661 | false | null | package com.delicious.mvvm.di.component
import com.delicious.mvvm.App
import dagger.Component
import dagger.android.AndroidInjectionModule
import com.delicious.mvvm.di.module.AppModule
import com.delicious.mvvm.di.module.BuildersModule
import com.delicious.mvvm.di.module.NetModule
import javax.inject.Singleton
@Singleton
@Component(
modules = [(AndroidInjectionModule::class), (BuildersModule::class), (AppModule::class), (NetModule::class)]
)
interface AppComponent {
fun inject(app: App)
}
| 0 | Kotlin | 0 | 0 | 57191562cb2c940aa11e62d74d434f85359377f5 | 502 | FoodApp-Kotlin | MIT License |
lock/src/main/java/com/hzy/lock/util/PatternLockUtil.kt | huangziye | 176,403,059 | false | null | package com.hzy.lock.util
import com.hzy.lock.PatternLockView
import java.io.UnsupportedEncodingException
import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
/**
*
* @author: ziye_huang
* @date: 2019/3/18
*/
object PatternLockUtil {
private val UTF8 = "UTF-8"
private val SHA1 = "SHA-1"
private val MD5 = "MD5"
/**
* Serializes a given pattern to its equivalent string representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The pattern in its string form
*/
fun patternToString(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>?): String {
if (pattern == null) return ""
val patternSize = pattern.size
val stringBuilder = StringBuilder()
for (i in 0 until patternSize) {
val dot = pattern[i]
stringBuilder.append(dot.row * patternLockView.getDotCount() + dot.column)
}
return stringBuilder.toString()
}
/**
* De-serializes a given string to its equivalent pattern representation
*
* @param string The pattern serialized with [.patternToString]
* @return The actual pattern
*/
fun stringToPattern(patternLockView: PatternLockView, string: String): List<PatternLockView.Dot> {
val result = arrayListOf<PatternLockView.Dot>()
for (i in 0 until string.length) {
val number = Character.getNumericValue(string[i])
result.add(
PatternLockView.Dot.of(
number / patternLockView.getDotCount(),
number % patternLockView.getDotCount()
)
)
}
return result
}
/**
* Serializes a given pattern to its equivalent SHA-1 representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The SHA-1 string of the pattern
*/
fun patternToSha1(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>): String? {
return try {
val messageDigest = MessageDigest.getInstance(SHA1)
messageDigest.update(patternToString(patternLockView, pattern).toByteArray(charset(UTF8)))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
String.format(Locale.SIMPLIFIED_CHINESE, "%0" + digest.size * 2 + "x", bigInteger).toLowerCase()
} catch (e: NoSuchAlgorithmException) {
null
} catch (e: UnsupportedEncodingException) {
null
}
}
/**
* Serializes a given pattern to its equivalent MD5 representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The MD5 string of the pattern
*/
fun patternToMD5(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>): String? {
return try {
val messageDigest = MessageDigest.getInstance(MD5)
messageDigest.update(patternToString(patternLockView, pattern).toByteArray(charset(UTF8)))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
String.format(Locale.SIMPLIFIED_CHINESE, "%0" + digest.size * 2 + "x", bigInteger).toLowerCase()
} catch (e: NoSuchAlgorithmException) {
null
} catch (e: UnsupportedEncodingException) {
null
}
}
/**
* Generates a random "CAPTCHA" pattern. The generated pattern is easy for the user to re-draw.
*
*
* NOTE: This method is **not** optimized and **not** benchmarked yet for large mSize
* of the pattern's matrix. Currently it works fine with a matrix of `3x3` cells.
* Be careful when the mSize increases.
*/
@Throws(IndexOutOfBoundsException::class)
fun generateRandomPattern(patternLockView: PatternLockView?, size: Int): ArrayList<PatternLockView.Dot> {
if (patternLockView == null) {
throw IllegalArgumentException("PatternLockView can not be null.")
}
if (size <= 0 || size > patternLockView.getDotCount()) {
throw IndexOutOfBoundsException("Size must be in range [1, " + patternLockView.getDotCount() + "]")
}
val usedIds = arrayListOf<Int>()
var lastId = RandomUtil.randInt(patternLockView.getDotCount())
usedIds.add(lastId)
while (usedIds.size < size) {
// We start from an empty matrix, so there's always a break point to
// exit this loop
val lastRow = lastId / patternLockView.getDotCount()
val lastCol = lastId % patternLockView.getDotCount()
// This is the max available rows/ columns that we can reach from
// the cell of `lastId` to the border of the matrix.
val maxDistance = Math.max(
Math.max(lastRow, patternLockView.getDotCount() - lastRow),
Math.max(lastCol, patternLockView.getDotCount() - lastCol)
)
lastId = -1
// Starting from `distance` = 1, find the closest-available
// neighbour value of the cell [lastRow, lastCol].
for (distance in 1..maxDistance) {
// Now we have a square surrounding the current cell. We call it
// ABCD, in which A is top-left, and C is bottom-right.
val rowA = lastRow - distance
val colA = lastCol - distance
val rowC = lastRow + distance
val colC = lastCol + distance
var randomValues: IntArray
// Process randomly AB, BC, CD, and DA. Break the loop as soon
// as we find one value.
val lines = RandomUtil.randIntArray(4)
for (line in lines) {
when (line) {
0 -> {
if (rowA >= 0) {
randomValues = RandomUtil.randIntArray(
Math.max(0, colA),
Math.min(patternLockView.getDotCount(), colC + 1)
)
for (c in randomValues) {
lastId = rowA * patternLockView.getDotCount() + c
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
1 -> {
if (colC < patternLockView.getDotCount()) {
randomValues = RandomUtil.randIntArray(
Math.max(0, rowA + 1),
Math.min(patternLockView.getDotCount(), rowC + 1)
)
for (r in randomValues) {
lastId = r * patternLockView.getDotCount() + colC
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
2 -> {
if (rowC < patternLockView.getDotCount()) {
randomValues = RandomUtil.randIntArray(
Math.max(0, colA),
Math.min(patternLockView.getDotCount(), colC)
)
for (c in randomValues) {
lastId = rowC * patternLockView.getDotCount() + c
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
3 -> {
if (colA >= 0) {
randomValues = RandomUtil.randIntArray(
Math.max(0, rowA + 1),
Math.min(patternLockView.getDotCount(), rowC)
)
for (r in randomValues) {
lastId = r * patternLockView.getDotCount() + colA
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
}
if (lastId >= 0)
break
}
if (lastId >= 0)
break
}
usedIds.add(lastId)
}
val result = arrayListOf<PatternLockView.Dot>()
for (id in usedIds) {
result.add(PatternLockView.Dot.of(id))
}
return result
}
} | 0 | Kotlin | 0 | 0 | bb1de9c05317f8432f7a9e82587af3865618c1b4 | 9,665 | PatternLock | Apache License 2.0 |
lock/src/main/java/com/hzy/lock/util/PatternLockUtil.kt | huangziye | 176,403,059 | false | null | package com.hzy.lock.util
import com.hzy.lock.PatternLockView
import java.io.UnsupportedEncodingException
import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
/**
*
* @author: ziye_huang
* @date: 2019/3/18
*/
object PatternLockUtil {
private val UTF8 = "UTF-8"
private val SHA1 = "SHA-1"
private val MD5 = "MD5"
/**
* Serializes a given pattern to its equivalent string representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The pattern in its string form
*/
fun patternToString(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>?): String {
if (pattern == null) return ""
val patternSize = pattern.size
val stringBuilder = StringBuilder()
for (i in 0 until patternSize) {
val dot = pattern[i]
stringBuilder.append(dot.row * patternLockView.getDotCount() + dot.column)
}
return stringBuilder.toString()
}
/**
* De-serializes a given string to its equivalent pattern representation
*
* @param string The pattern serialized with [.patternToString]
* @return The actual pattern
*/
fun stringToPattern(patternLockView: PatternLockView, string: String): List<PatternLockView.Dot> {
val result = arrayListOf<PatternLockView.Dot>()
for (i in 0 until string.length) {
val number = Character.getNumericValue(string[i])
result.add(
PatternLockView.Dot.of(
number / patternLockView.getDotCount(),
number % patternLockView.getDotCount()
)
)
}
return result
}
/**
* Serializes a given pattern to its equivalent SHA-1 representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The SHA-1 string of the pattern
*/
fun patternToSha1(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>): String? {
return try {
val messageDigest = MessageDigest.getInstance(SHA1)
messageDigest.update(patternToString(patternLockView, pattern).toByteArray(charset(UTF8)))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
String.format(Locale.SIMPLIFIED_CHINESE, "%0" + digest.size * 2 + "x", bigInteger).toLowerCase()
} catch (e: NoSuchAlgorithmException) {
null
} catch (e: UnsupportedEncodingException) {
null
}
}
/**
* Serializes a given pattern to its equivalent MD5 representation. You can store this string
* in any persistence storage or send it to the server for verification
*
* @param pattern The actual pattern
* @return The MD5 string of the pattern
*/
fun patternToMD5(patternLockView: PatternLockView, pattern: List<PatternLockView.Dot>): String? {
return try {
val messageDigest = MessageDigest.getInstance(MD5)
messageDigest.update(patternToString(patternLockView, pattern).toByteArray(charset(UTF8)))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
String.format(Locale.SIMPLIFIED_CHINESE, "%0" + digest.size * 2 + "x", bigInteger).toLowerCase()
} catch (e: NoSuchAlgorithmException) {
null
} catch (e: UnsupportedEncodingException) {
null
}
}
/**
* Generates a random "CAPTCHA" pattern. The generated pattern is easy for the user to re-draw.
*
*
* NOTE: This method is **not** optimized and **not** benchmarked yet for large mSize
* of the pattern's matrix. Currently it works fine with a matrix of `3x3` cells.
* Be careful when the mSize increases.
*/
@Throws(IndexOutOfBoundsException::class)
fun generateRandomPattern(patternLockView: PatternLockView?, size: Int): ArrayList<PatternLockView.Dot> {
if (patternLockView == null) {
throw IllegalArgumentException("PatternLockView can not be null.")
}
if (size <= 0 || size > patternLockView.getDotCount()) {
throw IndexOutOfBoundsException("Size must be in range [1, " + patternLockView.getDotCount() + "]")
}
val usedIds = arrayListOf<Int>()
var lastId = RandomUtil.randInt(patternLockView.getDotCount())
usedIds.add(lastId)
while (usedIds.size < size) {
// We start from an empty matrix, so there's always a break point to
// exit this loop
val lastRow = lastId / patternLockView.getDotCount()
val lastCol = lastId % patternLockView.getDotCount()
// This is the max available rows/ columns that we can reach from
// the cell of `lastId` to the border of the matrix.
val maxDistance = Math.max(
Math.max(lastRow, patternLockView.getDotCount() - lastRow),
Math.max(lastCol, patternLockView.getDotCount() - lastCol)
)
lastId = -1
// Starting from `distance` = 1, find the closest-available
// neighbour value of the cell [lastRow, lastCol].
for (distance in 1..maxDistance) {
// Now we have a square surrounding the current cell. We call it
// ABCD, in which A is top-left, and C is bottom-right.
val rowA = lastRow - distance
val colA = lastCol - distance
val rowC = lastRow + distance
val colC = lastCol + distance
var randomValues: IntArray
// Process randomly AB, BC, CD, and DA. Break the loop as soon
// as we find one value.
val lines = RandomUtil.randIntArray(4)
for (line in lines) {
when (line) {
0 -> {
if (rowA >= 0) {
randomValues = RandomUtil.randIntArray(
Math.max(0, colA),
Math.min(patternLockView.getDotCount(), colC + 1)
)
for (c in randomValues) {
lastId = rowA * patternLockView.getDotCount() + c
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
1 -> {
if (colC < patternLockView.getDotCount()) {
randomValues = RandomUtil.randIntArray(
Math.max(0, rowA + 1),
Math.min(patternLockView.getDotCount(), rowC + 1)
)
for (r in randomValues) {
lastId = r * patternLockView.getDotCount() + colC
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
2 -> {
if (rowC < patternLockView.getDotCount()) {
randomValues = RandomUtil.randIntArray(
Math.max(0, colA),
Math.min(patternLockView.getDotCount(), colC)
)
for (c in randomValues) {
lastId = rowC * patternLockView.getDotCount() + c
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
3 -> {
if (colA >= 0) {
randomValues = RandomUtil.randIntArray(
Math.max(0, rowA + 1),
Math.min(patternLockView.getDotCount(), rowC)
)
for (r in randomValues) {
lastId = r * patternLockView.getDotCount() + colA
if (usedIds.contains(lastId))
lastId = -1
else
break
}
}
}
}
if (lastId >= 0)
break
}
if (lastId >= 0)
break
}
usedIds.add(lastId)
}
val result = arrayListOf<PatternLockView.Dot>()
for (id in usedIds) {
result.add(PatternLockView.Dot.of(id))
}
return result
}
} | 0 | Kotlin | 0 | 0 | bb1de9c05317f8432f7a9e82587af3865618c1b4 | 9,665 | PatternLock | Apache License 2.0 |
common-ui/src/main/java/com/netease/yunxin/kit/common/ui/adapter/BaseFragmentAdapter.kt | netease-kit | 41,782,426 | false | {"Java": 3118605, "Kotlin": 75524} | /*
* Copyright (c) 2022 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
package com.netease.yunxin.kit.common.ui.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
/**
* Fragment Adapter
* used in MainActivity
*/
class BaseFragmentAdapter : FragmentStateAdapter {
private var fragmentList: List<Fragment>? = null
constructor(fragmentActivity: FragmentActivity) : super(fragmentActivity) {}
constructor(fragment: Fragment) : super(fragment) {}
constructor(fragmentManager: FragmentManager, lifecycle: Lifecycle) : super(
fragmentManager,
lifecycle
) {
}
fun setFragmentList(fragmentList: List<Fragment>?) {
this.fragmentList = fragmentList
}
override fun createFragment(position: Int): Fragment {
return if (fragmentList == null || fragmentList!!.size <= position) {
Fragment()
} else {
fragmentList!![position]
}
}
override fun getItemCount(): Int {
return if (fragmentList == null) 0 else fragmentList!!.size
}
companion object {
private const val TAG = "BaseFragmentAdapter"
}
}
| 0 | Java | 134 | 689 | 5ad0e61f2ba98eebb804c43f661bfa4b8c51697c | 1,403 | nim-uikit-android | MIT License |
main/java/com/app/chenyang/ussettings/utils/LogUtils.kt | yaoyang4346 | 133,810,257 | false | null | package com.app.chenyang.ussettings.utils
import android.util.Log
/**
* Created by chenyang on 2017/8/9.
*/
class LogUtils {
companion object {
val TAG = "UsSettings"
fun d(str:String){
Log.d(TAG,str)
}
}
} | 0 | Kotlin | 0 | 0 | fc0cb17df7ccceb66b3dc9b8124992cca57e89b8 | 254 | Kotlin-Settings | Apache License 2.0 |
app/src/main/java/com/wonium/helium/adapter/SlidingButtonAdapter.kt | wonium-ethan | 230,730,312 | false | null | /*
* Copyright (c) 2020. Ethan
*
* 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.wonium.helium.adapter
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.helium.android.SlidingButtonView
import com.helium.android.SlidingButtonView.SlidingButtonListener
import com.wonium.helium.R
import com.wonium.helium.adapter.SlidingButtonAdapter.MyViewHolder
import com.wonium.helium.helper.screenWidth
import java.util.*
/**
* @Description:
* @Author: Ethan
* @E-mail: <EMAIL>
* @Blog: https://blog.wonium.com
* @CreateDate: 2020/2/26 23:03
* @UpdateUser: Ethan
* @UpdateDate: 2020/2/26 23:03
* @UpdateDescription: 更新说明
* @Version: 1.0.0
*/
class SlidingButtonAdapter(private val mContext: Context) : RecyclerView.Adapter<MyViewHolder>(), SlidingButtonListener {
private val mIDeleteBtnClickListener: SlidingViewClickListener
private val mDatas: MutableList<String> = ArrayList()
private var mMenu: SlidingButtonView? = null
override fun getItemCount(): Int {
return mDatas.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = mDatas[position]
holder.layout_content.layoutParams.width =holder.itemView.context.screenWidth()
holder.textView.setOnClickListener { v ->
if (menuIsOpen()) {
closeMenu()
} else {
val n = holder.layoutPosition
mIDeleteBtnClickListener.onItemClick(v, n)
}
}
holder.btn_Delete.setOnClickListener { v: View? ->
val n = holder.layoutPosition
mIDeleteBtnClickListener.onDeleteBtnClick(v, n)
}
}
override fun onCreateViewHolder(arg0: ViewGroup, arg1: Int): MyViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.layout_sliding_item, arg0, false)
return MyViewHolder(view)
}
inner class MyViewHolder(itemView: View) : ViewHolder(itemView) {
var btn_Delete: TextView
var textView: TextView
var layout_content: ViewGroup
init {
btn_Delete = itemView.findViewById<View>(R.id.labelDelete) as TextView
textView = itemView.findViewById<View>(R.id.text) as TextView
layout_content = itemView.findViewById<View>(R.id.layout_content) as ViewGroup
(itemView as SlidingButtonView).setSlidingButtonListener(this@SlidingButtonAdapter)
}
}
fun addData(position: Int) {
mDatas.add(position, position.toString())
notifyItemInserted(position)
}
fun removeData(position: Int) {
mDatas.removeAt(position)
notifyItemRemoved(position)
}
override fun onMenuIsOpen(view: View?) {
mMenu = view as SlidingButtonView?
}
override fun onDownOrMove(slidingButtonView: SlidingButtonView?) {
if (menuIsOpen()) {
if (mMenu != slidingButtonView) {
closeMenu()
}
}
}
fun closeMenu() {
mMenu!!.closeMenu()
mMenu = null
}
fun menuIsOpen(): Boolean {
if (mMenu != null) {
return true
}
Log.i("asd", "mMenuΪnull")
return false
}
interface SlidingViewClickListener {
fun onItemClick(view: View?, position: Int)
fun onDeleteBtnClick(view: View?, position: Int)
}
init {
mIDeleteBtnClickListener = mContext as SlidingViewClickListener
for (i in 0..9) {
mDatas.add(i.toString() + "")
}
}
}
| 0 | Kotlin | 0 | 0 | c1e16007fa0b6a9b2e0161525d8a9e1dc1d1e288 | 4,313 | Helium | Apache License 2.0 |
api/src/main/kotlin/com/google/prefab/api/PlatformInterface.kt | DanAlbert | 219,671,482 | true | {"Kotlin": 108330} | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.prefab.api
import java.nio.file.Path
/**
* Defines the platform-specific information that is used to determine
* compatibility between user requirements and prebuilt libraries.
*/
interface PlatformDataInterface {
/**
* Determines if the given [requirement] can be used with this platform.
*
* This [PlatformDataInterface] object defines the platform requirements
* specified by the user. The given [requirement] object defines the
* requirements of a prebuilt library found in the module. This function
* returns true if the library can be used given the user's requirements.
*
* @param[requirement] The [platform requirements][PlatformDataInterface]
* for a library to be checked for compatibility.
* @return true if the given [requirement] is compatible with this
* [PlatformDataInterface] platform.
*/
fun canUse(requirement: PlatformDataInterface): Boolean
/**
* Returns the library file found in the given directory.
*
* @param[directory] The path to the library directory.
* @param[module] The module the library belongs to.
* @throws[RuntimeException] No unique library could be found in the
* directory.
* @return A [Path] referring to the prebuilt library for the given
* directory and module name.
*/
fun libraryFileFromDirectory(directory: Path, module: Module): Path
}
| 0 | null | 0 | 1 | a0bc1ba22f8bfde0251a3098ac2d12fdafd5b14e | 2,024 | prefab | Apache License 2.0 |
src/main/kotlin/com/skhu/mypack/member/dao/MemberRepository.kt | My-Pack | 611,048,216 | false | null | package com.skhu.mypack.member.dao
import com.skhu.mypack.member.domain.Member
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Slice
import org.springframework.data.jpa.repository.JpaRepository
interface MemberRepository : JpaRepository<Member, Long> {
fun findByEmail(email: String): Member?
fun findByName(name: String): Member?
fun findAllByNameLike(query: String, pageable: Pageable): Slice<Member>
fun existsByName(name: String): Boolean
} | 2 | Kotlin | 0 | 0 | 4e80d44cd23570fcf61fd2854dc85866d6da103f | 501 | MyPack-Server | MIT License |
cordapp-contracts-states/src/test/kotlin/com/hmlr/contracts/LandTitleIssuanceTests.kt | LandRegistry | 158,533,826 | false | null | package com.hmlr.contracts
import com.hmlr.AbstractContractsStatesTestUtils
import com.hmlr.model.*
import com.hmlr.states.LandTitleState
import net.corda.finance.POUNDS
import net.corda.testing.node.MockServices
import net.corda.testing.node.ledger
import org.junit.Test
class LandTitleIssuanceTests : AbstractContractsStatesTestUtils() {
private var ledgerServices = MockServices(listOf("com.hmlr.contracts"))
@Test
fun `must Include Issue Land Title Command`() {
val outputIssuanceRequestState = requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED)
ledgerServices.ledger {
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceApproveTests.DummyCommand())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `must Include Exactly One Input State `() {
val outputIssuanceRequestState = requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED)
ledgerServices.ledger {
// Remove an input state
transaction {
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
// Add an input state
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `must Include Exactly Two Output States`() {
val outputIssuanceRequestState = requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED)
ledgerServices.ledger {
// Add an output state
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
// Remove an output state
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `status Of Issue Transaction Should Be Set To Issued`() {
ledgerServices.ledger{
transaction {
val location = Address("A1-S2","GreenBank Road","Devon","Plymouth", "UK", "PL6 5ZD")
val prop = LandTitleProperties(location, BOB.party, LENDER1.party ,CustomParty("Alex", "Gomes", "125464", location, UserType.INDIVIDUAL, "<EMAIL>","+447700900354",true, null, sellerPublicKey))
val landTitleState = LandTitleState(titleID = "12345", landTitleProperties = prop, titleIssuer = ALICE.party, titleType = TitleType.WHOLE, lastSoldValue = null, status = LandTitleStatus.TRANSFERRED, charges = setOf(charge), restrictions = setOf(chargeRestriction), proposedChargeOrRestrictionLinearId = proposedChargeOrRestrictionState.linearId.toString(),revenueAndCustom = HMRC.party)
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `issued Land Asset Should Not Have Offer Price`() {
ledgerServices.ledger {
transaction {
val location = Address("A1-S2","GreenBank Road","Devon","Plymouth", "UK", "PL6 5ZD")
val prop = LandTitleProperties(location, BOB.party, LENDER1.party ,CustomParty("Alex", "Smith", "125464", location, UserType.INDIVIDUAL, "<EMAIL>","+447700900354",true, null, sellerPublicKey))
val landTitleState = LandTitleState(titleID = "12345", landTitleProperties = prop, titleIssuer = ALICE.party, titleType = TitleType.WHOLE, lastSoldValue = 100.POUNDS, status = LandTitleStatus.ISSUED, charges = setOf(charge), restrictions = setOf(chargeRestriction), proposedChargeOrRestrictionLinearId = proposedChargeOrRestrictionState.linearId.toString(), revenueAndCustom = HMRC.party)
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(landTitleState.titleIssuer.owningKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this .fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `issuer Must Sign Issue Land Title Issuance Transaction`() {
val outputIssuanceRequestState = requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED)
ledgerServices.ledger {
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(BOB.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, outputIssuanceRequestState)
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `seller Identity Must Be Verified`() {
ledgerServices.ledger {
transaction {
val location = Address("A1-S2","GreenBank Road","Devon","Plymouth", "UK", "PL6 5ZD")
val prop = LandTitleProperties(location, BOB.party, LENDER1.party, CustomParty("Alex", "Smith", "125464", location, UserType.INDIVIDUAL, "<EMAIL>","+447700900354",false, null, sellerPublicKey))
val landTitleState = LandTitleState(titleID = "12345", landTitleProperties = prop, titleIssuer = ALICE.party, titleType = TitleType.WHOLE, lastSoldValue = null, status = LandTitleStatus.ISSUED, charges = setOf(charge), restrictions = setOf(chargeRestriction), proposedChargeOrRestrictionLinearId = proposedChargeOrRestrictionState.linearId.toString(), revenueAndCustom = HMRC.party)
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
@Test
fun `issued Land Title Number Should Match With Requested Title Number`() {
ledgerServices.ledger {
transaction {
val location = Address("A1-S2","GreenBank Road","Devon","Plymouth", "UK", "PL6 5ZD")
val prop = LandTitleProperties(location, BOB.party, LENDER1.party, CustomParty("Alex", "Smith", "125464", location, UserType.INDIVIDUAL, "<EMAIL>","+447700900354",true, null, sellerPublicKey))
val landTitleState = LandTitleState(titleID = "212123131", landTitleProperties = prop, titleIssuer = ALICE.party, titleType = TitleType.WHOLE, lastSoldValue = null, status = LandTitleStatus.ISSUED, charges = setOf(charge), restrictions = setOf(chargeRestriction), proposedChargeOrRestrictionLinearId = proposedChargeOrRestrictionState.linearId.toString(), revenueAndCustom = HMRC.party)
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.fails()
}
transaction {
input(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState)
output(RequestIssuanceContract.REQUEST_ISSUANCE_CONTRACT_ID, requestIssuanceState.copy(status = RequestIssuanceStatus.APPROVED))
output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState)
output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState)
command(listOf(ALICE.publicKey), RequestIssuanceContract.Commands.ApproveRequest())
command(listOf(ALICE.publicKey), LandTitleContract.Commands.IssueLandTitle())
command(listOf(ALICE.publicKey), ProposedChargeAndRestrictionContract.Commands.IssueProposedChargeAndRestriction())
this.verifies()
}
}
}
} | 0 | Kotlin | 6 | 7 | 3c3b8f0c3bbd5927766d9df3113ecd951afd91b1 | 19,832 | digital-street-cordapp | MIT License |
ktfx-coroutines/src/ktfx/coroutines/scene/control/TreeTableView.kt | alilosoft | 182,138,993 | true | {"Kotlin": 364065, "HTML": 1385, "Java": 682} | @file:Suppress("PackageDirectoryMismatch")
package ktfx.coroutines
import javafx.scene.control.ScrollToEvent
import javafx.scene.control.SortEvent
import javafx.scene.control.TreeTableColumn
import javafx.scene.control.TreeTableView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.javafx.JavaFx
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
/** Called when there's a request to scroll an index into view using [TreeTableView.scrollTo]. */
fun TreeTableView<*>.onScrollTo(
context: CoroutineContext = Dispatchers.JavaFx,
action: suspend CoroutineScope.(ScrollToEvent<Int>) -> Unit
): Unit = setOnScrollTo { event -> GlobalScope.launch(context) { action(event) } }
/**
* Called when there's a request to scroll a column into view using [TreeTableView.scrollToColumn] or
* [TreeTableView.scrollToColumnIndex].
*/
fun <T> TreeTableView<T>.onScrollToColumn(
context: CoroutineContext = Dispatchers.JavaFx,
action: suspend CoroutineScope.(ScrollToEvent<TreeTableColumn<T, *>>) -> Unit
): Unit = setOnScrollToColumn { event -> GlobalScope.launch(context) { action(event) } }
/** Called when there's a request to sort the control. */
fun <T> TreeTableView<T>.onSort(
context: CoroutineContext = Dispatchers.JavaFx,
action: suspend CoroutineScope.(SortEvent<TreeTableView<T>>) -> Unit
): Unit = setOnSort { event -> GlobalScope.launch(context) { action(event) } } | 0 | Kotlin | 0 | 0 | f499c9d7abddb270f1946c0e9ffb9072e45cd625 | 1,510 | ktfx | Apache License 2.0 |
app/src/main/java/com/example/hellocowcow/app/di/viewModels/ViewModelUtils.kt | Elyt622 | 665,358,514 | false | {"Kotlin": 274991} | package com.example.hellocowcow.app.di.viewModels
import com.example.hellocowcow.ui.viewmodels.util.MySchedulers
import com.example.hellocowcow.ui.viewmodels.util.MySchedulersImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class UtilsPresenterModule {
@Binds
abstract fun bindNetworkSchedulers(
networkSchedulers: MySchedulersImpl
): MySchedulers
} | 0 | Kotlin | 0 | 0 | 72900bfe02b1527edb40d9abf40d553ac9b64e59 | 503 | Hello-Cowcow | Apache License 2.0 |
shared/src/commonMain/kotlin/com/ericktijerou/anticucho_detector/di/AnticuchoDetectorDatabaseWrapper.kt | ericktijerou | 382,207,681 | false | null | package com.ericktijerou.anticucho_detector.di
import com.ericktijerou.anticucho_detector.db.AnticuchoDetectorDatabase
class AnticuchoDetectorDatabaseWrapper(val instance: AnticuchoDetectorDatabase?) | 0 | Kotlin | 0 | 0 | 6e31f2c080ef267a49408dce7440d42372e48d43 | 201 | anticucho-detector-mobile | Apache License 2.0 |
model/src/main/java/org/ligi/kithub/model/GithubIssue.kt | MaTriXy | 106,587,325 | true | {"Kotlin": 8064} | package org.ligi.kithub.model
data class GithubIssue(val title: String,
val body: String,
val user: GithubUser,
val milestone: String?,
val pull_request: GithubPullRequest?,
val labels:List<String>,
val assignees: List<String>
) | 0 | Kotlin | 0 | 0 | fa85001f96602baa8f4912e31c0f37c46a61f03b | 367 | Kithub | MIT License |
model/src/main/java/org/ligi/kithub/model/GithubIssue.kt | MaTriXy | 106,587,325 | true | {"Kotlin": 8064} | package org.ligi.kithub.model
data class GithubIssue(val title: String,
val body: String,
val user: GithubUser,
val milestone: String?,
val pull_request: GithubPullRequest?,
val labels:List<String>,
val assignees: List<String>
) | 0 | Kotlin | 0 | 0 | fa85001f96602baa8f4912e31c0f37c46a61f03b | 367 | Kithub | MIT License |
example/src/main/kotlin/com/github/andrewoma/kwery/example/film/model/FilmModel.kt | aPureBase | 170,159,654 | true | {"Kotlin": 452423, "HTML": 7111, "Scala": 2252} | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.example.film.model
import java.time.Duration
data class Name(val first: String = "", val last: String = "")
data class Actor(
val id: Int = 0,
val name: Name = Name(),
override val version: Int = 0,
val films: Set<Film> = setOf()
) : AttributeSetByVersion
data class Film(
val id: Int = 0,
val title: String = "",
val description: String = "",
val releaseYear: Int = 0,
val language: Language = Language(0),
val originalLanguage: Language? = null,
val duration: Duration? = null, // minutes
val rating: FilmRating? = null,
val specialFeatures: List<String> = listOf(),
val actors: Set<Actor> = setOf(),
override val version: Int = 0
) : AttributeSetByVersion
enum class FilmRating {
G, PG, PG_13, R, NC_17
}
data class FilmActor(val id: FilmActor.Id = FilmActor.Id()) {
data class Id(val filmId: Int = 0, val actorId: Int = 0)
}
data class Language(
val id: Int = 0,
val name: String = "",
override val version: Int = 0
) : AttributeSetByVersion
interface Version {
val version: Int
}
// TODO ... move AttributeSet logic to be external to the model itself into the Jackson filter definition
enum class AttributeSet { Id, All }
interface HasAttributeSet {
fun attributeSet(): AttributeSet
}
interface AttributeSetByVersion : HasAttributeSet, Version {
override fun attributeSet() = if (this.version == 0) AttributeSet.Id else AttributeSet.All
}
| 12 | Kotlin | 0 | 4 | 8f0116eb96b655088dc2c06acb96507189bd73ed | 2,676 | kwery | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.