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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ocpp-1-5-core/src/main/kotlin/com/izivia/ocpp/core15/model/clearcache/ClearCacheReq.kt
|
IZIVIA
| 501,708,979
| false
|
{"Kotlin": 1934096}
|
package com.izivia.ocpp.core15.model.clearcache
class ClearCacheReq
| 6
|
Kotlin
|
10
| 32
|
bd8e7334ae05ea75d02d96a508269acbe076bcd8
| 68
|
ocpp-toolkit
|
MIT License
|
apps/intellij/src/main/kotlin/dev/nx/console/generate/ui/NxGeneratorListCellRenderer.kt
|
nrwl
| 137,811,219
| false
|
{"TypeScript": 760376, "Kotlin": 491881, "JavaScript": 8118, "HTML": 304, "CSS": 298}
|
package dev.nx.console.generate.ui
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBScalableIcon
import com.intellij.util.ui.UIUtil
import dev.nx.console.models.NxGenerator
import javax.swing.Icon
import javax.swing.JList
class NxGeneratorListCellRenderer(
private val myIcon: Icon = JBUIScale.scaleIcon(EmptyIcon.create(5) as JBScalableIcon),
private val alternatingRowColors: Boolean = true,
) : ColoredListCellRenderer<NxGenerator>() {
override fun customizeCellRenderer(
list: JList<out NxGenerator>,
value: NxGenerator,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
if (alternatingRowColors) {
if (!selected && index % 2 == 0) {
background = UIUtil.getDecoratedRowColor()
}
}
icon = myIcon
append(
"${value.data.collection} - ${value.data.name}",
SimpleTextAttributes.REGULAR_ATTRIBUTES,
true
)
append(
" " +
StringUtil.shortenTextWithEllipsis(
value.data.description,
80 - value.name.length,
0
),
SimpleTextAttributes.GRAY_ATTRIBUTES,
false
)
}
}
| 44
|
TypeScript
|
212
| 1,307
|
990e2dfb2cdc928d4041654d40d8e8c4c5cb45a6
| 1,480
|
nx-console
|
MIT License
|
app/src/main/java/com/example/countries/network/CountriesApiService.kt
|
neerajb18
| 743,459,554
| false
|
{"Kotlin": 33214}
|
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.countries.network
import com.example.countries.model.Country
import retrofit2.http.GET
/**
* A public interface that exposes the [getAllCountries] method
*/
interface CountriesApiService {
@GET("all")
suspend fun getAllCountries(): List<Country>
}
| 0
|
Kotlin
|
0
| 0
|
3de052d09bcf9e993fc861f1fdc1ee133ddd3542
| 901
|
countries-app
|
Apache License 2.0
|
sample/src/main/kotlin/com/github/stephenvinouze/kontinuousspeechrecognizer/activities/MainActivity.kt
|
StephenVinouze
| 91,692,096
| false
| null |
package com.github.stephenvinouze.kontinuousspeechrecognizer.activities
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.speech.SpeechRecognizer
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.github.stephenvinouze.core.interfaces.RecognitionCallback
import com.github.stephenvinouze.core.managers.KontinuousRecognitionManager
import com.github.stephenvinouze.core.models.RecognitionStatus
import com.github.stephenvinouze.kontinuousspeechrecognizer.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), RecognitionCallback {
companion object {
/**
* Put any keyword that will trigger the speech recognition
*/
private const val ACTIVATION_KEYWORD = "OK test"
private const val RECORD_AUDIO_REQUEST_CODE = 101
}
private val recognitionManager: KontinuousRecognitionManager by lazy {
KontinuousRecognitionManager(this, activationKeyword = ACTIVATION_KEYWORD, callback = this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressBar.visibility = View.INVISIBLE
progressBar.max = 10
recognitionManager.createRecognizer()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE)
}
}
override fun onDestroy() {
recognitionManager.destroyRecognizer()
super.onDestroy()
}
override fun onResume() {
super.onResume()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
startRecognition()
}
}
override fun onPause() {
stopRecognition()
super.onPause()
}
private fun startRecognition() {
progressBar.isIndeterminate = false
progressBar.visibility = View.VISIBLE
recognitionManager.startRecognition()
}
private fun stopRecognition() {
progressBar.isIndeterminate = true
progressBar.visibility = View.INVISIBLE
recognitionManager.stopRecognition()
}
private fun getErrorText(errorCode: Int): String = when (errorCode) {
SpeechRecognizer.ERROR_AUDIO -> "Audio recording error"
SpeechRecognizer.ERROR_CLIENT -> "Client side error"
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Insufficient permissions"
SpeechRecognizer.ERROR_NETWORK -> "Network error"
SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Network timeout"
SpeechRecognizer.ERROR_NO_MATCH -> "No match"
SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "RecognitionService busy"
SpeechRecognizer.ERROR_SERVER -> "Error from server"
SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "No speech input"
else -> "Didn't understand, please try again."
}
override fun onBeginningOfSpeech() {
Log.i("Recognition","onBeginningOfSpeech")
}
override fun onBufferReceived(buffer: ByteArray) {
Log.i("Recognition", "onBufferReceived: $buffer")
}
override fun onEndOfSpeech() {
Log.i("Recognition","onEndOfSpeech")
}
override fun onError(errorCode: Int) {
val errorMessage = getErrorText(errorCode)
Log.i("Recognition","onError: $errorMessage")
textView.text = errorMessage
}
override fun onEvent(eventType: Int, params: Bundle) {
Log.i("Recognition","onEvent")
}
override fun onReadyForSpeech(params: Bundle) {
Log.i("Recognition","onReadyForSpeech")
}
override fun onRmsChanged(rmsdB: Float) {
progressBar.progress = rmsdB.toInt()
}
override fun onPrepared(status: RecognitionStatus) {
when (status) {
RecognitionStatus.SUCCESS -> {
Log.i("Recognition","onPrepared: Success")
textView.text = "Recognition ready"
}
RecognitionStatus.UNAVAILABLE -> {
Log.i("Recognition", "onPrepared: Failure or unavailable")
AlertDialog.Builder(this)
.setTitle("Speech Recognizer unavailable")
.setMessage("Your device does not support Speech Recognition. Sorry!")
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
}
override fun onKeywordDetected() {
Log.i("Recognition","keyword detected !!!")
textView.text = "Keyword detected"
}
override fun onPartialResults(results: List<String>) {}
override fun onResults(results: List<String>, scores: FloatArray?) {
val text = results.joinToString(separator = "\n")
Log.i("Recognition","onResults : $text")
textView.text = text
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
RECORD_AUDIO_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecognition()
}
}
}
}
}
| 6
|
Kotlin
|
41
| 132
|
06305c404161f200f6a0cf87b44c4c01b903a0ff
| 5,690
|
KontinuousSpeechRecognizer
|
Apache License 2.0
|
firebase/src/main/java/com/safechat/firebase/RegisterServiceImpl.kt
|
kingcosta
| 60,254,872
| true
|
{"Kotlin": 20111, "Java": 6817}
|
package com.safechat.firebase
import com.safechat.encryption.toBase64String
import com.safechat.register.RegisterService
import rx.Observable
import java.security.PublicKey
class RegisterServiceImpl : RegisterService {
override fun registerNewKey(publicKey: PublicKey): Observable<Unit> {
val publicKeyString = publicKey.toBase64String()
val email = publicKeyString + "@safechat.com"
val password = publicKeyString + "<PASSWORD>"
return createUser(email, password)
.flatMap { loginUser(email, password) }
.flatMap { putUser(it.user.uid, publicKeyString) }
}
}
| 0
|
Kotlin
|
0
| 0
|
8e0a36cd4f208fabd3fbc6125451cf1e6150a169
| 635
|
secure-messenger-android
|
Apache License 2.0
|
telegram-bot-core/src/main/kotlin/io/github/dehuckakpyt/telegrambot/api/TelegramBotApiHandling.kt
|
DEHuckaKpyT
| 670,859,055
| false
| null |
package io.github.dehuckakpyt.telegrambot.api
import io.github.dehuckakpyt.telegrambot.TelegramBot
import io.github.dehuckakpyt.telegrambot.container.Container
import io.github.dehuckakpyt.telegrambot.model.telegram.BotCommand
import io.github.dehuckakpyt.telegrambot.model.telegram.BotCommandScope
import io.github.dehuckakpyt.telegrambot.model.telegram.BotDescription
import io.github.dehuckakpyt.telegrambot.model.telegram.BotName
import io.github.dehuckakpyt.telegrambot.model.telegram.BotShortDescription
import io.github.dehuckakpyt.telegrambot.model.telegram.BusinessConnection
import io.github.dehuckakpyt.telegrambot.model.telegram.ChatAdministratorRights
import io.github.dehuckakpyt.telegrambot.model.telegram.ChatFullInfo
import io.github.dehuckakpyt.telegrambot.model.telegram.ChatInviteLink
import io.github.dehuckakpyt.telegrambot.model.telegram.ChatMember
import io.github.dehuckakpyt.telegrambot.model.telegram.ChatPermissions
import io.github.dehuckakpyt.telegrambot.model.telegram.File
import io.github.dehuckakpyt.telegrambot.model.telegram.ForumTopic
import io.github.dehuckakpyt.telegrambot.model.telegram.GameHighScore
import io.github.dehuckakpyt.telegrambot.model.telegram.InlineKeyboardMarkup
import io.github.dehuckakpyt.telegrambot.model.telegram.InlineQueryResult
import io.github.dehuckakpyt.telegrambot.model.telegram.InlineQueryResultsButton
import io.github.dehuckakpyt.telegrambot.model.telegram.InputMedia
import io.github.dehuckakpyt.telegrambot.model.telegram.InputPaidMedia
import io.github.dehuckakpyt.telegrambot.model.telegram.InputPollOption
import io.github.dehuckakpyt.telegrambot.model.telegram.InputSticker
import io.github.dehuckakpyt.telegrambot.model.telegram.LabeledPrice
import io.github.dehuckakpyt.telegrambot.model.telegram.LinkPreviewOptions
import io.github.dehuckakpyt.telegrambot.model.telegram.MaskPosition
import io.github.dehuckakpyt.telegrambot.model.telegram.MenuButton
import io.github.dehuckakpyt.telegrambot.model.telegram.Message
import io.github.dehuckakpyt.telegrambot.model.telegram.MessageEntity
import io.github.dehuckakpyt.telegrambot.model.telegram.MessageId
import io.github.dehuckakpyt.telegrambot.model.telegram.PassportElementError
import io.github.dehuckakpyt.telegrambot.model.telegram.Poll
import io.github.dehuckakpyt.telegrambot.model.telegram.ReactionType
import io.github.dehuckakpyt.telegrambot.model.telegram.ReplyMarkup
import io.github.dehuckakpyt.telegrambot.model.telegram.ReplyParameters
import io.github.dehuckakpyt.telegrambot.model.telegram.SentWebAppMessage
import io.github.dehuckakpyt.telegrambot.model.telegram.ShippingOption
import io.github.dehuckakpyt.telegrambot.model.telegram.StarTransactions
import io.github.dehuckakpyt.telegrambot.model.telegram.Sticker
import io.github.dehuckakpyt.telegrambot.model.telegram.StickerSet
import io.github.dehuckakpyt.telegrambot.model.telegram.Update
import io.github.dehuckakpyt.telegrambot.model.telegram.User
import io.github.dehuckakpyt.telegrambot.model.telegram.UserChatBoosts
import io.github.dehuckakpyt.telegrambot.model.telegram.UserProfilePhotos
import io.github.dehuckakpyt.telegrambot.model.telegram.WebhookInfo
import io.github.dehuckakpyt.telegrambot.model.telegram.input.ContentInput
import io.github.dehuckakpyt.telegrambot.model.telegram.input.Input
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.collections.Iterable
import kotlin.collections.List
/**
* @author KScript
*/
public abstract class TelegramBotApiHandling {
protected abstract val bot: TelegramBot
/**
* Use this method to receive incoming updates using long polling
* ([wiki](https://en.wikipedia.org/wiki/Push_technology#Long_polling)). Returns an Array of
* [Update](https://core.telegram.org/bots/api/#update) objects.
*
* @param offset Identifier of the first update to be returned. Must be greater by one than the
* highest among the identifiers of previously received updates. By default, updates starting with
* the earliest unconfirmed update are returned. An update is considered confirmed as soon as
* [getUpdates](https://core.telegram.org/bots/api/#getupdates) is called with an *offset* higher
* than its *update_id*. The negative offset can be specified to retrieve updates starting from
* *-offset* update from the end of the updates queue. All previous updates will be forgotten.
* @param limit Limits the number of updates to be retrieved. Values between 1-100 are accepted.
* Defaults to 100.
* @param timeout Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling.
* Should be positive, short polling should be used for testing purposes only.
* @param allowedUpdates A JSON-serialized list of the update types you want your bot to
* receive. For example, specify `["message", "edited_channel_post", "callback_query"]` to only
* receive updates of these types. See [Update](https://core.telegram.org/bots/api/#update) for a
* complete list of available update types. Specify an empty list to receive all update types
* except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not
* specified, the previous setting will be used.
*
* Please note that this parameter doesn't affect updates created before the call to the
* getUpdates, so unwanted updates may be received for a short period of time.
*/
public suspend fun Container.getUpdates(
offset: Long? = null,
limit: Int? = null,
timeout: Int? = null,
allowedUpdates: Iterable<String>? = null,
): List<Update> = bot.getUpdates(
offset = offset,
limit = limit,
timeout = timeout,
allowedUpdates = allowedUpdates,
)
/**
* Use this method to specify a URL and receive incoming updates via an outgoing webhook.
* Whenever there is an update for the bot, we will send an HTTPS POST request to the specified
* URL, containing a JSON-serialized [Update](https://core.telegram.org/bots/api/#update). In case
* of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns
* *True* on success.
*
* If you'd like to make sure that the webhook was set by you, you can specify secret data in
* the parameter *secret_token*. If specified, the request will contain a header
* “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.
*
* @param url HTTPS URL to send updates to. Use an empty string to remove webhook integration
* @param certificate Upload your public key certificate so that the root certificate in use can
* be checked. See our [self-signed guide](https://core.telegram.org/bots/self-signed) for details.
* @param ipAddress The fixed IP address which will be used to send webhook requests instead of
* the IP address resolved through DNS
* @param maxConnections The maximum allowed number of simultaneous HTTPS connections to the
* webhook for update delivery, 1-100. Defaults to *40*. Use lower values to limit the load on your
* bot's server, and higher values to increase your bot's throughput.
* @param allowedUpdates A JSON-serialized list of the update types you want your bot to
* receive. For example, specify `["message", "edited_channel_post", "callback_query"]` to only
* receive updates of these types. See [Update](https://core.telegram.org/bots/api/#update) for a
* complete list of available update types. Specify an empty list to receive all update types
* except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not
* specified, the previous setting will be used.
* Please note that this parameter doesn't affect updates created before the call to the
* setWebhook, so unwanted updates may be received for a short period of time.
* @param dropPendingUpdates Pass *True* to drop all pending updates
* @param secretToken A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in
* every webhook request, 1-256 characters. Only characters `A-Z`, `a-z`, `0-9`, `_` and `-` are
* allowed. The header is useful to ensure that the request comes from a webhook set by you.
*/
public suspend fun Container.setWebhook(
url: String,
certificate: ContentInput? = null,
ipAddress: String? = null,
maxConnections: Int? = null,
allowedUpdates: Iterable<String>? = null,
dropPendingUpdates: Boolean? = null,
secretToken: String? = null,
): Boolean = bot.setWebhook(
url = url,
certificate = certificate,
ipAddress = ipAddress,
maxConnections = maxConnections,
allowedUpdates = allowedUpdates,
dropPendingUpdates = dropPendingUpdates,
secretToken = secretToken,
)
/**
* Use this method to remove webhook integration if you decide to switch back to
* [getUpdates](https://core.telegram.org/bots/api/#getupdates). Returns *True* on success.
*
* @param dropPendingUpdates Pass *True* to drop all pending updates
*/
public suspend fun Container.deleteWebhook(dropPendingUpdates: Boolean? = null): Boolean =
bot.deleteWebhook(
dropPendingUpdates = dropPendingUpdates,
)
/**
* Use this method to get current webhook status. Requires no parameters. On success, returns a
* [WebhookInfo](https://core.telegram.org/bots/api/#webhookinfo) object. If the bot is using
* [getUpdates](https://core.telegram.org/bots/api/#getupdates), will return an object with the
* *url* field empty.
*/
public suspend fun Container.getWebhookInfo(): WebhookInfo = bot.getWebhookInfo(
)
/**
* A simple method for testing your bot's authentication token. Requires no parameters. Returns
* basic information about the bot in form of a [User](https://core.telegram.org/bots/api/#user)
* object.
*/
public suspend fun Container.getMe(): User = bot.getMe(
)
/**
* Use this method to log out from the cloud Bot API server before launching the bot locally.
* You **must** log out the bot before running it locally, otherwise there is no guarantee that the
* bot will receive updates. After a successful call, you can immediately log in on a local server,
* but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns *True*
* on success. Requires no parameters.
*/
public suspend fun Container.logOut(): Boolean = bot.logOut(
)
/**
* Use this method to close the bot instance before moving it from one local server to another.
* You need to delete the webhook before calling this method to ensure that the bot isn't launched
* again after server restart. The method will return error 429 in the first 10 minutes after the
* bot is launched. Returns *True* on success. Requires no parameters.
*/
public suspend fun Container.close(): Boolean = bot.close(
)
/**
* Use this method to send text messages. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param text Text of the message to be sent, 1-4096 characters after entities parsing
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param parseMode Mode for parsing entities in the message text. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param entities A JSON-serialized list of special entities that appear in message text, which
* can be specified instead of *parse_mode*
* @param linkPreviewOptions Link preview generation options for the message
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendMessage(
text: String,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
parseMode: String? = null,
entities: Iterable<MessageEntity>? = null,
linkPreviewOptions: LinkPreviewOptions? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendMessage(
chatId = chat.id,
text = text,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
parseMode = parseMode,
entities = entities,
linkPreviewOptions = linkPreviewOptions,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to forward messages of any kind. Service messages and messages with protected
* content can't be forwarded. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param fromChatId Unique identifier for the chat where the original message was sent (or
* channel username in the format `@channelusername`)
* @param messageId Message identifier in the chat specified in *from_chat_id*
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the forwarded message from forwarding and
* saving
*/
public suspend fun Container.forwardMessage(
fromChatId: String,
messageId: Long,
messageThreadId: Long? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
): Message = bot.forwardMessage(
chatId = chat.id,
fromChatId = fromChatId,
messageId = messageId,
messageThreadId = messageThreadId,
disableNotification = disableNotification,
protectContent = protectContent,
)
/**
* Use this method to forward multiple messages of any kind. If some of the specified messages
* can't be found or forwarded, they are skipped. Service messages and messages with protected
* content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array
* of [MessageId](https://core.telegram.org/bots/api/#messageid) of the sent messages is returned.
*
* @param fromChatId Unique identifier for the chat where the original messages were sent (or
* channel username in the format `@channelusername`)
* @param messageIds A JSON-serialized list of 1-100 identifiers of messages in the chat
* *from_chat_id* to forward. The identifiers must be specified in a strictly increasing order.
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param disableNotification Sends the messages
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the forwarded messages from forwarding and
* saving
*/
public suspend fun Container.forwardMessages(
fromChatId: String,
messageIds: Iterable<Long>,
messageThreadId: Long? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
): List<MessageId> = bot.forwardMessages(
chatId = chat.id,
fromChatId = fromChatId,
messageIds = messageIds,
messageThreadId = messageThreadId,
disableNotification = disableNotification,
protectContent = protectContent,
)
/**
* Use this method to copy messages of any kind. Service messages, paid media messages, giveaway
* messages, giveaway winners messages, and invoice messages can't be copied. A quiz
* [poll](https://core.telegram.org/bots/api/#poll) can be copied only if the value of the field
* *correct_option_id* is known to the bot. The method is analogous to the method
* [forwardMessage](https://core.telegram.org/bots/api/#forwardmessage), but the copied message
* doesn't have a link to the original message. Returns the
* [MessageId](https://core.telegram.org/bots/api/#messageid) of the sent message on success.
*
* @param fromChatId Unique identifier for the chat where the original message was sent (or
* channel username in the format `@channelusername`)
* @param messageId Message identifier in the chat specified in *from_chat_id*
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param caption New caption for media, 0-1024 characters after entities parsing. If not
* specified, the original caption is kept
* @param parseMode Mode for parsing entities in the new caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the new
* caption, which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media. Ignored if a new caption isn't specified.
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.copyMessage(
fromChatId: String,
messageId: Long,
messageThreadId: Long? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): MessageId = bot.copyMessage(
chatId = chat.id,
fromChatId = fromChatId,
messageId = messageId,
messageThreadId = messageThreadId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
disableNotification = disableNotification,
protectContent = protectContent,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to copy messages of any kind. If some of the specified messages can't be
* found or copied, they are skipped. Service messages, paid media messages, giveaway messages,
* giveaway winners messages, and invoice messages can't be copied. A quiz
* [poll](https://core.telegram.org/bots/api/#poll) can be copied only if the value of the field
* *correct_option_id* is known to the bot. The method is analogous to the method
* [forwardMessages](https://core.telegram.org/bots/api/#forwardmessages), but the copied messages
* don't have a link to the original message. Album grouping is kept for copied messages. On
* success, an array of [MessageId](https://core.telegram.org/bots/api/#messageid) of the sent
* messages is returned.
*
* @param fromChatId Unique identifier for the chat where the original messages were sent (or
* channel username in the format `@channelusername`)
* @param messageIds A JSON-serialized list of 1-100 identifiers of messages in the chat
* *from_chat_id* to copy. The identifiers must be specified in a strictly increasing order.
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param disableNotification Sends the messages
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent messages from forwarding and saving
* @param removeCaption Pass *True* to copy the messages without their captions
*/
public suspend fun Container.copyMessages(
fromChatId: String,
messageIds: Iterable<Long>,
messageThreadId: Long? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
removeCaption: Boolean? = null,
): List<MessageId> = bot.copyMessages(
chatId = chat.id,
fromChatId = fromChatId,
messageIds = messageIds,
messageThreadId = messageThreadId,
disableNotification = disableNotification,
protectContent = protectContent,
removeCaption = removeCaption,
)
/**
* Use this method to send photos. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param photo Photo to send. Pass a file_id as String to send a photo that exists on the
* Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from
* the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB
* in size. The photo's width and height must not exceed 10000 in total. Width and height ratio
* must be at most 20. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param caption Photo caption (may also be used when resending photos by *file_id*), 0-1024
* characters after entities parsing
* @param parseMode Mode for parsing entities in the photo caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media
* @param hasSpoiler Pass *True* if the photo needs to be covered with a spoiler animation
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendPhoto(
photo: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
hasSpoiler: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendPhoto(
chatId = chat.id,
photo = photo,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
hasSpoiler = hasSpoiler,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send audio files, if you want Telegram clients to display them in the
* music player. Your audio must be in the .MP3 or .M4A format. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned. Bots can currently send
* audio files of up to 50 MB in size, this limit may be changed in the future.
*
* For sending voice messages, use the
* [sendVoice](https://core.telegram.org/bots/api/#sendvoice) method instead.
*
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists
* on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio
* file from the Internet, or upload a new one using multipart/form-data. [More information on
* Sending Files ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param caption Audio caption, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the audio caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param duration Duration of the audio in seconds
* @param performer Performer
* @param title Track name
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the
* file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in
* size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded
* using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so
* you can pass “attach://\<file_attach_name\>” if the thumbnail was uploaded using
* multipart/form-data under \<file_attach_name\>. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendAudio(
audio: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
duration: Int? = null,
performer: String? = null,
title: String? = null,
thumbnail: ContentInput? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendAudio(
chatId = chat.id,
audio = audio,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
duration = duration,
performer = performer,
title = title,
thumbnail = thumbnail,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send general files. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned. Bots can currently send
* files of any type of up to 50 MB in size, this limit may be changed in the future.
*
* @param document File to send. Pass a file_id as String to send a file that exists on the
* Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the
* Internet, or upload a new one using multipart/form-data. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the
* file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in
* size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded
* using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so
* you can pass “attach://\<file_attach_name\>” if the thumbnail was uploaded using
* multipart/form-data under \<file_attach_name\>. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param caption Document caption (may also be used when resending documents by *file_id*),
* 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the document caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param disableContentTypeDetection Disables automatic server-side content type detection for
* files uploaded using multipart/form-data
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendDocument(
document: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
thumbnail: ContentInput? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
disableContentTypeDetection: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendDocument(
chatId = chat.id,
document = document,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
thumbnail = thumbnail,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
disableContentTypeDetection = disableContentTypeDetection,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send video files, Telegram clients support MPEG4 videos (other formats may
* be sent as [Document](https://core.telegram.org/bots/api/#document)). On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned. Bots can currently send
* video files of up to 50 MB in size, this limit may be changed in the future.
*
* @param video Video to send. Pass a file_id as String to send a video that exists on the
* Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from
* the Internet, or upload a new video using multipart/form-data. [More information on Sending
* Files ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param duration Duration of sent video in seconds
* @param width Video width
* @param height Video height
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the
* file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in
* size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded
* using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so
* you can pass “attach://\<file_attach_name\>” if the thumbnail was uploaded using
* multipart/form-data under \<file_attach_name\>. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param caption Video caption (may also be used when resending videos by *file_id*), 0-1024
* characters after entities parsing
* @param parseMode Mode for parsing entities in the video caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media
* @param hasSpoiler Pass *True* if the video needs to be covered with a spoiler animation
* @param supportsStreaming Pass *True* if the uploaded video is suitable for streaming
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendVideo(
video: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
duration: Int? = null,
width: Int? = null,
height: Int? = null,
thumbnail: ContentInput? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
hasSpoiler: Boolean? = null,
supportsStreaming: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendVideo(
chatId = chat.id,
video = video,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
duration = duration,
width = width,
height = height,
thumbnail = thumbnail,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
hasSpoiler = hasSpoiler,
supportsStreaming = supportsStreaming,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On
* success, the sent [Message](https://core.telegram.org/bots/api/#message) is returned. Bots can
* currently send animation files of up to 50 MB in size, this limit may be changed in the future.
*
* @param animation Animation to send. Pass a file_id as String to send an animation that exists
* on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an
* animation from the Internet, or upload a new animation using multipart/form-data. [More
* information on Sending Files ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param duration Duration of sent animation in seconds
* @param width Animation width
* @param height Animation height
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the
* file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in
* size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded
* using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so
* you can pass “attach://\<file_attach_name\>” if the thumbnail was uploaded using
* multipart/form-data under \<file_attach_name\>. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param caption Animation caption (may also be used when resending animation by *file_id*),
* 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the animation caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media
* @param hasSpoiler Pass *True* if the animation needs to be covered with a spoiler animation
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendAnimation(
animation: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
duration: Int? = null,
width: Int? = null,
height: Int? = null,
thumbnail: ContentInput? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
hasSpoiler: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendAnimation(
chatId = chat.id,
animation = animation,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
duration = duration,
width = width,
height = height,
thumbnail = thumbnail,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
hasSpoiler = hasSpoiler,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a
* playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS,
* or in .MP3 format, or in .M4A format (other formats may be sent as
* [Audio](https://core.telegram.org/bots/api/#audio) or
* [Document](https://core.telegram.org/bots/api/#document)). On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned. Bots can currently send
* voice messages of up to 50 MB in size, this limit may be changed in the future.
*
* @param voice Audio file to send. Pass a file_id as String to send a file that exists on the
* Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the
* Internet, or upload a new one using multipart/form-data. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param caption Voice message caption, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the voice message caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param duration Duration of the voice message in seconds
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendVoice(
voice: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
duration: Int? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendVoice(
chatId = chat.id,
voice = voice,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
duration = duration,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* As of [v.4.0](https://telegram.org/blog/video-messages-and-telescope), Telegram clients
* support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video
* messages. On success, the sent [Message](https://core.telegram.org/bots/api/#message) is
* returned.
*
* @param videoNote Video note to send. Pass a file_id as String to send a video note that
* exists on the Telegram servers (recommended) or upload a new video using multipart/form-data.
* [More information on Sending Files ](https://core.telegram.org/bots/api/#sending-files). Sending
* video notes by a URL is currently unsupported
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param duration Duration of sent video in seconds
* @param length Video width and height, i.e. diameter of the video message
* @param thumbnail Thumbnail of the file sent; can be ignored if thumbnail generation for the
* file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in
* size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded
* using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so
* you can pass “attach://\<file_attach_name\>” if the thumbnail was uploaded using
* multipart/form-data under \<file_attach_name\>. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendVideoNote(
videoNote: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
duration: Int? = null,
length: Int? = null,
thumbnail: ContentInput? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendVideoNote(
chatId = chat.id,
videoNote = videoNote,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
duration = duration,
length = length,
thumbnail = thumbnail,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send paid media to channel chats. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param starCount The number of Telegram Stars that must be paid to buy access to the media
* @param media A JSON-serialized array describing the media to be sent; up to 10 items
* @param caption Media caption, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the media caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendPaidMedia(
starCount: Int,
media: Iterable<InputPaidMedia>,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendPaidMedia(
chatId = chat.id,
starCount = starCount,
media = media,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
disableNotification = disableNotification,
protectContent = protectContent,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send a group of photos, videos, documents or audios as an album. Documents
* and audio files can be only grouped in an album with messages of the same type. On success, an
* array of [Messages](https://core.telegram.org/bots/api/#message) that were sent is returned.
*
* @param media A JSON-serialized array describing messages to be sent, must include 2-10 items
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param disableNotification Sends messages
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent messages from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
*/
public suspend fun Container.sendMediaGroup(
media: Iterable<InputMedia>,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
): List<Message> = bot.sendMediaGroup(
chatId = chat.id,
media = media,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
)
/**
* Use this method to send point on the map. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param latitude Latitude of the location
* @param longitude Longitude of the location
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param horizontalAccuracy The radius of uncertainty for the location, measured in meters;
* 0-1500
* @param livePeriod Period in seconds during which the location will be updated (see [Live
* Locations](https://telegram.org/blog/live-locations), should be between 60 and 86400, or
* 0x7FFFFFFF for live locations that can be edited indefinitely.
* @param heading For live locations, a direction in which the user is moving, in degrees. Must
* be between 1 and 360 if specified.
* @param proximityAlertRadius For live locations, a maximum distance for proximity alerts about
* approaching another chat member, in meters. Must be between 1 and 100000 if specified.
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendLocation(
latitude: Double,
longitude: Double,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
horizontalAccuracy: Double? = null,
livePeriod: Int? = null,
heading: Int? = null,
proximityAlertRadius: Int? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendLocation(
chatId = chat.id,
latitude = latitude,
longitude = longitude,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
horizontalAccuracy = horizontalAccuracy,
livePeriod = livePeriod,
heading = heading,
proximityAlertRadius = proximityAlertRadius,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send information about a venue. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param latitude Latitude of the venue
* @param longitude Longitude of the venue
* @param title Name of the venue
* @param address Address of the venue
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param foursquareId Foursquare identifier of the venue
* @param foursquareType Foursquare type of the venue, if known. (For example,
* “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
* @param googlePlaceId Google Places identifier of the venue
* @param googlePlaceType Google Places type of the venue. (See [supported
* types](https://developers.google.com/places/web-service/supported_types).)
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendVenue(
latitude: Double,
longitude: Double,
title: String,
address: String,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
foursquareId: String? = null,
foursquareType: String? = null,
googlePlaceId: String? = null,
googlePlaceType: String? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendVenue(
chatId = chat.id,
latitude = latitude,
longitude = longitude,
title = title,
address = address,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
foursquareId = foursquareId,
foursquareType = foursquareType,
googlePlaceId = googlePlaceId,
googlePlaceType = googlePlaceType,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send phone contacts. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param phoneNumber Contact's phone number
* @param firstName Contact's first name
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param lastName Contact's last name
* @param vcard Additional data about the contact in the form of a
* [vCard](https://en.wikipedia.org/wiki/VCard), 0-2048 bytes
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendContact(
phoneNumber: String,
firstName: String,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
lastName: String? = null,
vcard: String? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendContact(
chatId = chat.id,
phoneNumber = phoneNumber,
firstName = firstName,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
lastName = lastName,
vcard = vcard,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send a native poll. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param question Poll question, 1-300 characters
* @param options A JSON-serialized list of 2-10 answer options
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param questionParseMode Mode for parsing entities in the question. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details. Currently,
* only custom emoji entities are allowed
* @param questionEntities A JSON-serialized list of special entities that appear in the poll
* question. It can be specified instead of *question_parse_mode*
* @param isAnonymous *True*, if the poll needs to be anonymous, defaults to *True*
* @param type Poll type, “quiz” or “regular”, defaults to “regular”
* @param allowsMultipleAnswers *True*, if the poll allows multiple answers, ignored for polls
* in quiz mode, defaults to *False*
* @param correctOptionId 0-based identifier of the correct answer option, required for polls in
* quiz mode
* @param explanation Text that is shown when a user chooses an incorrect answer or taps on the
* lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities
* parsing
* @param explanationParseMode Mode for parsing entities in the explanation. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param explanationEntities A JSON-serialized list of special entities that appear in the poll
* explanation. It can be specified instead of *explanation_parse_mode*
* @param openPeriod Amount of time in seconds the poll will be active after creation, 5-600.
* Can't be used together with *close_date*.
* @param closeDate Point in time (Unix timestamp) when the poll will be automatically closed.
* Must be at least 5 and no more than 600 seconds in the future. Can't be used together with
* *open_period*.
* @param isClosed Pass *True* if the poll needs to be immediately closed. This can be useful
* for poll preview.
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendPoll(
question: String,
options: Iterable<InputPollOption>,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
questionParseMode: String? = null,
questionEntities: Iterable<MessageEntity>? = null,
isAnonymous: Boolean? = null,
type: String? = null,
allowsMultipleAnswers: Boolean? = null,
correctOptionId: Long? = null,
explanation: String? = null,
explanationParseMode: String? = null,
explanationEntities: Iterable<MessageEntity>? = null,
openPeriod: Int? = null,
closeDate: Long? = null,
isClosed: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendPoll(
chatId = chat.id,
question = question,
options = options,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
questionParseMode = questionParseMode,
questionEntities = questionEntities,
isAnonymous = isAnonymous,
type = type,
allowsMultipleAnswers = allowsMultipleAnswers,
correctOptionId = correctOptionId,
explanation = explanation,
explanationParseMode = explanationParseMode,
explanationEntities = explanationEntities,
openPeriod = openPeriod,
closeDate = closeDate,
isClosed = isClosed,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to send an animated emoji that will display a random value. On success, the
* sent [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param emoji Emoji on which the dice throw animation is based. Currently, must be one of
* “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values
* 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendDice(
businessConnectionId: String? = null,
messageThreadId: Long? = null,
emoji: String? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendDice(
chatId = chat.id,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
emoji = emoji,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients
* clear its typing status). Returns *True* on success.
*
* Example: The [ImageBot](https://t.me/imagebot) needs some time to process a request and
* upload the image. Instead of sending a text message along the lines of “Retrieving image, please
* wait…”, the bot may use [sendChatAction](https://core.telegram.org/bots/api/#sendchataction)
* with *action* = *upload_photo*. The user will see a “sending photo” status for the bot.
*
* We only recommend using this method when a response from the bot will take a **noticeable**
* amount of time to arrive.
*
* @param action Type of action to broadcast. Choose one, depending on what the user is about to
* receive: *typing* for [text messages](https://core.telegram.org/bots/api/#sendmessage),
* *upload_photo* for [photos](https://core.telegram.org/bots/api/#sendphoto), *record_video* or
* *upload_video* for [videos](https://core.telegram.org/bots/api/#sendvideo), *record_voice* or
* *upload_voice* for [voice notes](https://core.telegram.org/bots/api/#sendvoice),
* *upload_document* for [general files](https://core.telegram.org/bots/api/#senddocument),
* *choose_sticker* for [stickers](https://core.telegram.org/bots/api/#sendsticker),
* *find_location* for [location data](https://core.telegram.org/bots/api/#sendlocation),
* *record_video_note* or *upload_video_note* for [video
* notes](https://core.telegram.org/bots/api/#sendvideonote).
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the action will be sent
* @param messageThreadId Unique identifier for the target message thread; for supergroups only
*/
public suspend fun Container.sendChatAction(
action: String,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
): Boolean = bot.sendChatAction(
chatId = chat.id,
action = action,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
)
/**
* Use this method to change the chosen reactions on a message. Service messages can't be
* reacted to. Automatically forwarded messages from a channel to its discussion group have the
* same available reactions as messages in the channel. Returns *True* on success.
*
* @param messageId Identifier of the target message. If the message belongs to a media group,
* the reaction is set to the first non-deleted message in the group instead.
* @param reaction A JSON-serialized list of reaction types to set on the message. Currently, as
* non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be
* used if it is either already present on the message or explicitly allowed by chat
* administrators.
* @param isBig Pass *True* to set the reaction with a big animation
*/
public suspend fun Container.setMessageReaction(
messageId: Long,
reaction: Iterable<ReactionType>? = null,
isBig: Boolean? = null,
): Boolean = bot.setMessageReaction(
chatId = chat.id,
messageId = messageId,
reaction = reaction,
isBig = isBig,
)
/**
* Use this method to get a list of profile pictures for a user. Returns a
* [UserProfilePhotos](https://core.telegram.org/bots/api/#userprofilephotos) object.
*
* @param userId Unique identifier of the target user
* @param offset Sequential number of the first photo to be returned. By default, all photos are
* returned.
* @param limit Limits the number of photos to be retrieved. Values between 1-100 are accepted.
* Defaults to 100.
*/
public suspend fun Container.getUserProfilePhotos(
userId: Long,
offset: Int? = null,
limit: Int? = null,
): UserProfilePhotos = bot.getUserProfilePhotos(
userId = userId,
offset = offset,
limit = limit,
)
/**
* Use this method to get basic information about a file and prepare it for downloading. For the
* moment, bots can download files of up to 20MB in size. On success, a
* [File](https://core.telegram.org/bots/api/#file) object is returned. The file can then be
* downloaded via the link `https://api.telegram.org/file/bot<token>/<file_path>`, where
* `<file_path>` is taken from the response. It is guaranteed that the link will be valid for at
* least 1 hour. When the link expires, a new one can be requested by calling
* [getFile](https://core.telegram.org/bots/api/#getfile) again.
*
* @param fileId File identifier to get information about
*/
public suspend fun Container.getFile(fileId: String): File = bot.getFile(
fileId = fileId,
)
/**
* Use this method to ban a user in a group, a supergroup or a channel. In the case of
* supergroups and channels, the user will not be able to return to the chat on their own using
* invite links, etc., unless [unbanned](https://core.telegram.org/bots/api/#unbanchatmember)
* first. The bot must be an administrator in the chat for this to work and must have the
* appropriate administrator rights. Returns *True* on success.
*
* @param userId Unique identifier of the target user
* @param untilDate Date when the user will be unbanned; Unix time. If user is banned for more
* than 366 days or less than 30 seconds from the current time they are considered to be banned
* forever. Applied for supergroups and channels only.
* @param revokeMessages Pass *True* to delete all messages from the chat for the user that is
* being removed. If *False*, the user will be able to see messages in the group that were sent
* before the user was removed. Always *True* for supergroups and channels.
*/
public suspend fun Container.banChatMember(
userId: Long,
untilDate: Long? = null,
revokeMessages: Boolean? = null,
): Boolean = bot.banChatMember(
chatId = chat.id,
userId = userId,
untilDate = untilDate,
revokeMessages = revokeMessages,
)
/**
* Use this method to unban a previously banned user in a supergroup or channel. The user will
* **not** return to the group or channel automatically, but will be able to join via link, etc.
* The bot must be an administrator for this to work. By default, this method guarantees that after
* the call the user is not a member of the chat, but will be able to join it. So if the user is a
* member of the chat they will also be **removed** from the chat. If you don't want this, use the
* parameter *only_if_banned*. Returns *True* on success.
*
* @param userId Unique identifier of the target user
* @param onlyIfBanned Do nothing if the user is not banned
*/
public suspend fun Container.unbanChatMember(userId: Long, onlyIfBanned: Boolean? = null):
Boolean = bot.unbanChatMember(
chatId = chat.id,
userId = userId,
onlyIfBanned = onlyIfBanned,
)
/**
* Use this method to restrict a user in a supergroup. The bot must be an administrator in the
* supergroup for this to work and must have the appropriate administrator rights. Pass *True* for
* all permissions to lift restrictions from a user. Returns *True* on success.
*
* @param userId Unique identifier of the target user
* @param permissions A JSON-serialized object for new user permissions
* @param useIndependentChatPermissions Pass *True* if chat permissions are set independently.
* Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply
* the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*,
* *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the
* *can_send_polls* permission will imply the *can_send_messages* permission.
* @param untilDate Date when restrictions will be lifted for the user; Unix time. If user is
* restricted for more than 366 days or less than 30 seconds from the current time, they are
* considered to be restricted forever
*/
public suspend fun Container.restrictChatMember(
userId: Long,
permissions: ChatPermissions,
useIndependentChatPermissions: Boolean? = null,
untilDate: Long? = null,
): Boolean = bot.restrictChatMember(
chatId = chat.id,
userId = userId,
permissions = permissions,
useIndependentChatPermissions = useIndependentChatPermissions,
untilDate = untilDate,
)
/**
* Use this method to promote or demote a user in a supergroup or a channel. The bot must be an
* administrator in the chat for this to work and must have the appropriate administrator rights.
* Pass *False* for all boolean parameters to demote a user. Returns *True* on success.
*
* @param userId Unique identifier of the target user
* @param isAnonymous Pass *True* if the administrator's presence in the chat is hidden
* @param canManageChat Pass *True* if the administrator can access the chat event log, get
* boost list, see hidden supergroup and channel members, report spam messages and ignore slow
* mode. Implied by any other administrator privilege.
* @param canDeleteMessages Pass *True* if the administrator can delete messages of other users
* @param canManageVideoChats Pass *True* if the administrator can manage video chats
* @param canRestrictMembers Pass *True* if the administrator can restrict, ban or unban chat
* members, or access supergroup statistics
* @param canPromoteMembers Pass *True* if the administrator can add new administrators with a
* subset of their own privileges or demote administrators that they have promoted, directly or
* indirectly (promoted by administrators that were appointed by him)
* @param canChangeInfo Pass *True* if the administrator can change chat title, photo and other
* settings
* @param canInviteUsers Pass *True* if the administrator can invite new users to the chat
* @param canPostStories Pass *True* if the administrator can post stories to the chat
* @param canEditStories Pass *True* if the administrator can edit stories posted by other
* users, post stories to the chat page, pin chat stories, and access the chat's story archive
* @param canDeleteStories Pass *True* if the administrator can delete stories posted by other
* users
* @param canPostMessages Pass *True* if the administrator can post messages in the channel, or
* access channel statistics; for channels only
* @param canEditMessages Pass *True* if the administrator can edit messages of other users and
* can pin messages; for channels only
* @param canPinMessages Pass *True* if the administrator can pin messages; for supergroups only
* @param canManageTopics Pass *True* if the user is allowed to create, rename, close, and
* reopen forum topics; for supergroups only
*/
public suspend fun Container.promoteChatMember(
userId: Long,
isAnonymous: Boolean? = null,
canManageChat: Boolean? = null,
canDeleteMessages: Boolean? = null,
canManageVideoChats: Boolean? = null,
canRestrictMembers: Boolean? = null,
canPromoteMembers: Boolean? = null,
canChangeInfo: Boolean? = null,
canInviteUsers: Boolean? = null,
canPostStories: Boolean? = null,
canEditStories: Boolean? = null,
canDeleteStories: Boolean? = null,
canPostMessages: Boolean? = null,
canEditMessages: Boolean? = null,
canPinMessages: Boolean? = null,
canManageTopics: Boolean? = null,
): Boolean = bot.promoteChatMember(
chatId = chat.id,
userId = userId,
isAnonymous = isAnonymous,
canManageChat = canManageChat,
canDeleteMessages = canDeleteMessages,
canManageVideoChats = canManageVideoChats,
canRestrictMembers = canRestrictMembers,
canPromoteMembers = canPromoteMembers,
canChangeInfo = canChangeInfo,
canInviteUsers = canInviteUsers,
canPostStories = canPostStories,
canEditStories = canEditStories,
canDeleteStories = canDeleteStories,
canPostMessages = canPostMessages,
canEditMessages = canEditMessages,
canPinMessages = canPinMessages,
canManageTopics = canManageTopics,
)
/**
* Use this method to set a custom title for an administrator in a supergroup promoted by the
* bot. Returns *True* on success.
*
* @param userId Unique identifier of the target user
* @param customTitle New custom title for the administrator; 0-16 characters, emoji are not
* allowed
*/
public suspend fun Container.setChatAdministratorCustomTitle(userId: Long, customTitle: String):
Boolean = bot.setChatAdministratorCustomTitle(
chatId = chat.id,
userId = userId,
customTitle = customTitle,
)
/**
* Use this method to ban a channel chat in a supergroup or a channel. Until the chat is
* [unbanned](https://core.telegram.org/bots/api/#unbanchatsenderchat), the owner of the banned
* chat won't be able to send messages on behalf of **any of their channels**. The bot must be an
* administrator in the supergroup or channel for this to work and must have the appropriate
* administrator rights. Returns *True* on success.
*
* @param senderChatId Unique identifier of the target sender chat
*/
public suspend fun Container.banChatSenderChat(senderChatId: Long): Boolean =
bot.banChatSenderChat(
chatId = chat.id,
senderChatId = senderChatId,
)
/**
* Use this method to unban a previously banned channel chat in a supergroup or channel. The bot
* must be an administrator for this to work and must have the appropriate administrator rights.
* Returns *True* on success.
*
* @param senderChatId Unique identifier of the target sender chat
*/
public suspend fun Container.unbanChatSenderChat(senderChatId: Long): Boolean =
bot.unbanChatSenderChat(
chatId = chat.id,
senderChatId = senderChatId,
)
/**
* Use this method to set default chat permissions for all members. The bot must be an
* administrator in the group or a supergroup for this to work and must have the
* *can_restrict_members* administrator rights. Returns *True* on success.
*
* @param permissions A JSON-serialized object for new default chat permissions
* @param useIndependentChatPermissions Pass *True* if chat permissions are set independently.
* Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply
* the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*,
* *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the
* *can_send_polls* permission will imply the *can_send_messages* permission.
*/
public suspend fun Container.setChatPermissions(permissions: ChatPermissions,
useIndependentChatPermissions: Boolean? = null): Boolean = bot.setChatPermissions(
chatId = chat.id,
permissions = permissions,
useIndependentChatPermissions = useIndependentChatPermissions,
)
/**
* Use this method to generate a new primary invite link for a chat; any previously generated
* primary link is revoked. The bot must be an administrator in the chat for this to work and must
* have the appropriate administrator rights. Returns the new invite link as *String* on success.
*/
public suspend fun Container.exportChatInviteLink(): String = bot.exportChatInviteLink(
chatId = chat.id,
)
/**
* Use this method to create an additional invite link for a chat. The bot must be an
* administrator in the chat for this to work and must have the appropriate administrator rights.
* The link can be revoked using the method
* [revokeChatInviteLink](https://core.telegram.org/bots/api/#revokechatinvitelink). Returns the
* new invite link as [ChatInviteLink](https://core.telegram.org/bots/api/#chatinvitelink) object.
*
* @param name Invite link name; 0-32 characters
* @param expireDate Point in time (Unix timestamp) when the link will expire
* @param memberLimit The maximum number of users that can be members of the chat simultaneously
* after joining the chat via this invite link; 1-99999
* @param createsJoinRequest *True*, if users joining the chat via the link need to be approved
* by chat administrators. If *True*, *member_limit* can't be specified
*/
public suspend fun Container.createChatInviteLink(
name: String? = null,
expireDate: Long? = null,
memberLimit: Int? = null,
createsJoinRequest: Boolean? = null,
): ChatInviteLink = bot.createChatInviteLink(
chatId = chat.id,
name = name,
expireDate = expireDate,
memberLimit = memberLimit,
createsJoinRequest = createsJoinRequest,
)
/**
* Use this method to edit a non-primary invite link created by the bot. The bot must be an
* administrator in the chat for this to work and must have the appropriate administrator rights.
* Returns the edited invite link as a
* [ChatInviteLink](https://core.telegram.org/bots/api/#chatinvitelink) object.
*
* @param inviteLink The invite link to edit
* @param name Invite link name; 0-32 characters
* @param expireDate Point in time (Unix timestamp) when the link will expire
* @param memberLimit The maximum number of users that can be members of the chat simultaneously
* after joining the chat via this invite link; 1-99999
* @param createsJoinRequest *True*, if users joining the chat via the link need to be approved
* by chat administrators. If *True*, *member_limit* can't be specified
*/
public suspend fun Container.editChatInviteLink(
inviteLink: String,
name: String? = null,
expireDate: Long? = null,
memberLimit: Int? = null,
createsJoinRequest: Boolean? = null,
): ChatInviteLink = bot.editChatInviteLink(
chatId = chat.id,
inviteLink = inviteLink,
name = name,
expireDate = expireDate,
memberLimit = memberLimit,
createsJoinRequest = createsJoinRequest,
)
/**
* Use this method to revoke an invite link created by the bot. If the primary link is revoked,
* a new link is automatically generated. The bot must be an administrator in the chat for this to
* work and must have the appropriate administrator rights. Returns the revoked invite link as
* [ChatInviteLink](https://core.telegram.org/bots/api/#chatinvitelink) object.
*
* @param inviteLink The invite link to revoke
*/
public suspend fun Container.revokeChatInviteLink(inviteLink: String): ChatInviteLink =
bot.revokeChatInviteLink(
chatId = chat.id,
inviteLink = inviteLink,
)
/**
* Use this method to approve a chat join request. The bot must be an administrator in the chat
* for this to work and must have the *can_invite_users* administrator right. Returns *True* on
* success.
*
* @param userId Unique identifier of the target user
*/
public suspend fun Container.approveChatJoinRequest(userId: Long): Boolean =
bot.approveChatJoinRequest(
chatId = chat.id,
userId = userId,
)
/**
* Use this method to decline a chat join request. The bot must be an administrator in the chat
* for this to work and must have the *can_invite_users* administrator right. Returns *True* on
* success.
*
* @param userId Unique identifier of the target user
*/
public suspend fun Container.declineChatJoinRequest(userId: Long): Boolean =
bot.declineChatJoinRequest(
chatId = chat.id,
userId = userId,
)
/**
* Use this method to set a new profile photo for the chat. Photos can't be changed for private
* chats. The bot must be an administrator in the chat for this to work and must have the
* appropriate administrator rights. Returns *True* on success.
*
* @param photo New chat photo, uploaded using multipart/form-data
*/
public suspend fun Container.setChatPhoto(photo: Input): Boolean = bot.setChatPhoto(
chatId = chat.id,
photo = photo,
)
/**
* Use this method to delete a chat photo. Photos can't be changed for private chats. The bot
* must be an administrator in the chat for this to work and must have the appropriate
* administrator rights. Returns *True* on success.
*/
public suspend fun Container.deleteChatPhoto(): Boolean = bot.deleteChatPhoto(
chatId = chat.id,
)
/**
* Use this method to change the title of a chat. Titles can't be changed for private chats. The
* bot must be an administrator in the chat for this to work and must have the appropriate
* administrator rights. Returns *True* on success.
*
* @param title New chat title, 1-128 characters
*/
public suspend fun Container.setChatTitle(title: String): Boolean = bot.setChatTitle(
chatId = chat.id,
title = title,
)
/**
* Use this method to change the description of a group, a supergroup or a channel. The bot must
* be an administrator in the chat for this to work and must have the appropriate administrator
* rights. Returns *True* on success.
*
* @param description New chat description, 0-255 characters
*/
public suspend fun Container.setChatDescription(description: String? = null): Boolean =
bot.setChatDescription(
chatId = chat.id,
description = description,
)
/**
* Use this method to add a message to the list of pinned messages in a chat. If the chat is not
* a private chat, the bot must be an administrator in the chat for this to work and must have the
* 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator
* right in a channel. Returns *True* on success.
*
* @param messageId Identifier of a message to pin
* @param disableNotification Pass *True* if it is not necessary to send a notification to all
* chat members about the new pinned message. Notifications are always disabled in channels and
* private chats.
*/
public suspend fun Container.pinChatMessage(messageId: Long, disableNotification: Boolean? =
null): Boolean = bot.pinChatMessage(
chatId = chat.id,
messageId = messageId,
disableNotification = disableNotification,
)
/**
* Use this method to remove a message from the list of pinned messages in a chat. If the chat
* is not a private chat, the bot must be an administrator in the chat for this to work and must
* have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages'
* administrator right in a channel. Returns *True* on success.
*
* @param messageId Identifier of a message to unpin. If not specified, the most recent pinned
* message (by sending date) will be unpinned.
*/
public suspend fun Container.unpinChatMessage(messageId: Long? = null): Boolean =
bot.unpinChatMessage(
chatId = chat.id,
messageId = messageId,
)
/**
* Use this method to clear the list of pinned messages in a chat. If the chat is not a private
* chat, the bot must be an administrator in the chat for this to work and must have the
* 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator
* right in a channel. Returns *True* on success.
*/
public suspend fun Container.unpinAllChatMessages(): Boolean = bot.unpinAllChatMessages(
chatId = chat.id,
)
/**
* Use this method for your bot to leave a group, supergroup or channel. Returns *True* on
* success.
*/
public suspend fun Container.leaveChat(): Boolean = bot.leaveChat(
chatId = chat.id,
)
/**
* Use this method to get up-to-date information about the chat. Returns a
* [ChatFullInfo](https://core.telegram.org/bots/api/#chatfullinfo) object on success.
*/
public suspend fun Container.getChat(): ChatFullInfo = bot.getChat(
chatId = chat.id,
)
/**
* Use this method to get a list of administrators in a chat, which aren't bots. Returns an
* Array of [ChatMember](https://core.telegram.org/bots/api/#chatmember) objects.
*/
public suspend fun Container.getChatAdministrators(): List<ChatMember> =
bot.getChatAdministrators(
chatId = chat.id,
)
/**
* Use this method to get the number of members in a chat. Returns *Int* on success.
*/
public suspend fun Container.getChatMemberCount(): Int = bot.getChatMemberCount(
chatId = chat.id,
)
/**
* Use this method to get information about a member of a chat. The method is only guaranteed to
* work for other users if the bot is an administrator in the chat. Returns a
* [ChatMember](https://core.telegram.org/bots/api/#chatmember) object on success.
*
* @param userId Unique identifier of the target user
*/
public suspend fun Container.getChatMember(userId: Long): ChatMember = bot.getChatMember(
chatId = chat.id,
userId = userId,
)
/**
* Use this method to set a new group sticker set for a supergroup. The bot must be an
* administrator in the chat for this to work and must have the appropriate administrator rights.
* Use the field *can_set_sticker_set* optionally returned in
* [getChat](https://core.telegram.org/bots/api/#getchat) requests to check if the bot can use this
* method. Returns *True* on success.
*
* @param stickerSetName Name of the sticker set to be set as the group sticker set
*/
public suspend fun Container.setChatStickerSet(stickerSetName: String): Boolean =
bot.setChatStickerSet(
chatId = chat.id,
stickerSetName = stickerSetName,
)
/**
* Use this method to delete a group sticker set from a supergroup. The bot must be an
* administrator in the chat for this to work and must have the appropriate administrator rights.
* Use the field *can_set_sticker_set* optionally returned in
* [getChat](https://core.telegram.org/bots/api/#getchat) requests to check if the bot can use this
* method. Returns *True* on success.
*/
public suspend fun Container.deleteChatStickerSet(): Boolean = bot.deleteChatStickerSet(
chatId = chat.id,
)
/**
* Use this method to get custom emoji stickers, which can be used as a forum topic icon by any
* user. Requires no parameters. Returns an Array of
* [Sticker](https://core.telegram.org/bots/api/#sticker) objects.
*/
public suspend fun Container.getForumTopicIconStickers(): List<Sticker> =
bot.getForumTopicIconStickers(
)
/**
* Use this method to create a topic in a forum supergroup chat. The bot must be an
* administrator in the chat for this to work and must have the *can_manage_topics* administrator
* rights. Returns information about the created topic as a
* [ForumTopic](https://core.telegram.org/bots/api/#forumtopic) object.
*
* @param name Topic name, 1-128 characters
* @param iconColor Color of the topic icon in RGB format. Currently, must be one of 7322096
* (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2),
* or 16478047 (0xFB6F5F)
* @param iconCustomEmojiId Unique identifier of the custom emoji shown as the topic icon. Use
* [getForumTopicIconStickers](https://core.telegram.org/bots/api/#getforumtopiciconstickers) to
* get all allowed custom emoji identifiers.
*/
public suspend fun Container.createForumTopic(
name: String,
iconColor: Int? = null,
iconCustomEmojiId: String? = null,
): ForumTopic = bot.createForumTopic(
chatId = chat.id,
name = name,
iconColor = iconColor,
iconCustomEmojiId = iconCustomEmojiId,
)
/**
* Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be
* an administrator in the chat for this to work and must have *can_manage_topics* administrator
* rights, unless it is the creator of the topic. Returns *True* on success.
*
* @param messageThreadId Unique identifier for the target message thread of the forum topic
* @param name New topic name, 0-128 characters. If not specified or empty, the current name of
* the topic will be kept
* @param iconCustomEmojiId New unique identifier of the custom emoji shown as the topic icon.
* Use [getForumTopicIconStickers](https://core.telegram.org/bots/api/#getforumtopiciconstickers)
* to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not
* specified, the current icon will be kept
*/
public suspend fun Container.editForumTopic(
messageThreadId: Long,
name: String? = null,
iconCustomEmojiId: String? = null,
): Boolean = bot.editForumTopic(
chatId = chat.id,
messageThreadId = messageThreadId,
name = name,
iconCustomEmojiId = iconCustomEmojiId,
)
/**
* Use this method to close an open topic in a forum supergroup chat. The bot must be an
* administrator in the chat for this to work and must have the *can_manage_topics* administrator
* rights, unless it is the creator of the topic. Returns *True* on success.
*
* @param messageThreadId Unique identifier for the target message thread of the forum topic
*/
public suspend fun Container.closeForumTopic(messageThreadId: Long): Boolean =
bot.closeForumTopic(
chatId = chat.id,
messageThreadId = messageThreadId,
)
/**
* Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an
* administrator in the chat for this to work and must have the *can_manage_topics* administrator
* rights, unless it is the creator of the topic. Returns *True* on success.
*
* @param messageThreadId Unique identifier for the target message thread of the forum topic
*/
public suspend fun Container.reopenForumTopic(messageThreadId: Long): Boolean =
bot.reopenForumTopic(
chatId = chat.id,
messageThreadId = messageThreadId,
)
/**
* Use this method to delete a forum topic along with all its messages in a forum supergroup
* chat. The bot must be an administrator in the chat for this to work and must have the
* *can_delete_messages* administrator rights. Returns *True* on success.
*
* @param messageThreadId Unique identifier for the target message thread of the forum topic
*/
public suspend fun Container.deleteForumTopic(messageThreadId: Long): Boolean =
bot.deleteForumTopic(
chatId = chat.id,
messageThreadId = messageThreadId,
)
/**
* Use this method to clear the list of pinned messages in a forum topic. The bot must be an
* administrator in the chat for this to work and must have the *can_pin_messages* administrator
* right in the supergroup. Returns *True* on success.
*
* @param messageThreadId Unique identifier for the target message thread of the forum topic
*/
public suspend fun Container.unpinAllForumTopicMessages(messageThreadId: Long): Boolean =
bot.unpinAllForumTopicMessages(
chatId = chat.id,
messageThreadId = messageThreadId,
)
/**
* Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot
* must be an administrator in the chat for this to work and must have *can_manage_topics*
* administrator rights. Returns *True* on success.
*
* @param name New topic name, 1-128 characters
*/
public suspend fun Container.editGeneralForumTopic(name: String): Boolean =
bot.editGeneralForumTopic(
chatId = chat.id,
name = name,
)
/**
* Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be
* an administrator in the chat for this to work and must have the *can_manage_topics*
* administrator rights. Returns *True* on success.
*/
public suspend fun Container.closeGeneralForumTopic(): Boolean = bot.closeGeneralForumTopic(
chatId = chat.id,
)
/**
* Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must
* be an administrator in the chat for this to work and must have the *can_manage_topics*
* administrator rights. The topic will be automatically unhidden if it was hidden. Returns *True*
* on success.
*/
public suspend fun Container.reopenGeneralForumTopic(): Boolean = bot.reopenGeneralForumTopic(
chatId = chat.id,
)
/**
* Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an
* administrator in the chat for this to work and must have the *can_manage_topics* administrator
* rights. The topic will be automatically closed if it was open. Returns *True* on success.
*/
public suspend fun Container.hideGeneralForumTopic(): Boolean = bot.hideGeneralForumTopic(
chatId = chat.id,
)
/**
* Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an
* administrator in the chat for this to work and must have the *can_manage_topics* administrator
* rights. Returns *True* on success.
*/
public suspend fun Container.unhideGeneralForumTopic(): Boolean = bot.unhideGeneralForumTopic(
chatId = chat.id,
)
/**
* Use this method to clear the list of pinned messages in a General forum topic. The bot must
* be an administrator in the chat for this to work and must have the *can_pin_messages*
* administrator right in the supergroup. Returns *True* on success.
*/
public suspend fun Container.unpinAllGeneralForumTopicMessages(): Boolean =
bot.unpinAllGeneralForumTopicMessages(
chatId = chat.id,
)
/**
* Use this method to send answers to callback queries sent from [inline
* keyboards](https://core.telegram.org/bots/features#inline-keyboards). The answer will be
* displayed to the user as a notification at the top of the chat screen or as an alert. On
* success, *True* is returned.
*
* Alternatively, the user can be redirected to the specified Game URL. For this option to work,
* you must first create a game for your bot via [@BotFather](https://t.me/botfather) and accept
* the terms. Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with
* a parameter.
*
* @param callbackQueryId Unique identifier for the query to be answered
* @param text Text of the notification. If not specified, nothing will be shown to the user,
* 0-200 characters
* @param showAlert If *True*, an alert will be shown by the client instead of a notification at
* the top of the chat screen. Defaults to *false*.
* @param url URL that will be opened by the user's client. If you have created a
* [Game](https://core.telegram.org/bots/api/#game) and accepted the conditions via
* [@BotFather](https://t.me/botfather), specify the URL that opens your game - note that this will
* only work if the query comes from a
* [*callback_game*](https://core.telegram.org/bots/api/#inlinekeyboardbutton) button.
*
* Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a
* parameter.
* @param cacheTime The maximum amount of time in seconds that the result of the callback query
* may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults
* to 0.
*/
public suspend fun Container.answerCallbackQuery(
callbackQueryId: String,
text: String? = null,
showAlert: Boolean? = null,
url: String? = null,
cacheTime: Int? = null,
): Boolean = bot.answerCallbackQuery(
callbackQueryId = callbackQueryId,
text = text,
showAlert = showAlert,
url = url,
cacheTime = cacheTime,
)
/**
* Use this method to get the list of boosts added to a chat by a user. Requires administrator
* rights in the chat. Returns a
* [UserChatBoosts](https://core.telegram.org/bots/api/#userchatboosts) object.
*
* @param userId Unique identifier of the target user
*/
public suspend fun Container.getUserChatBoosts(userId: Long): UserChatBoosts =
bot.getUserChatBoosts(
chatId = chat.id,
userId = userId,
)
/**
* Use this method to get information about the connection of the bot with a business account.
* Returns a [BusinessConnection](https://core.telegram.org/bots/api/#businessconnection) object on
* success.
*
* @param businessConnectionId Unique identifier of the business connection
*/
public suspend fun Container.getBusinessConnection(businessConnectionId: String):
BusinessConnection = bot.getBusinessConnection(
businessConnectionId = businessConnectionId,
)
/**
* Use this method to change the list of the bot's commands. See [this
* manual](https://core.telegram.org/bots/features#commands) for more details about bot commands.
* Returns *True* on success.
*
* @param commands A JSON-serialized list of bot commands to be set as the list of the bot's
* commands. At most 100 commands can be specified.
* @param scope A JSON-serialized object, describing scope of users for which the commands are
* relevant. Defaults to
* [BotCommandScopeDefault](https://core.telegram.org/bots/api/#botcommandscopedefault).
* @param languageCode A two-letter ISO 639-1 language code. If empty, commands will be applied
* to all users from the given scope, for whose language there are no dedicated commands
*/
public suspend fun Container.setMyCommands(
commands: Iterable<BotCommand>,
scope: BotCommandScope? = null,
languageCode: String? = null,
): Boolean = bot.setMyCommands(
commands = commands,
scope = scope,
languageCode = languageCode,
)
/**
* Use this method to delete the list of the bot's commands for the given scope and user
* language. After deletion, [higher level
* commands](https://core.telegram.org/bots/api/#determining-list-of-commands) will be shown to
* affected users. Returns *True* on success.
*
* @param scope A JSON-serialized object, describing scope of users for which the commands are
* relevant. Defaults to
* [BotCommandScopeDefault](https://core.telegram.org/bots/api/#botcommandscopedefault).
* @param languageCode A two-letter ISO 639-1 language code. If empty, commands will be applied
* to all users from the given scope, for whose language there are no dedicated commands
*/
public suspend fun Container.deleteMyCommands(scope: BotCommandScope? = null,
languageCode: String? = null): Boolean = bot.deleteMyCommands(
scope = scope,
languageCode = languageCode,
)
/**
* Use this method to get the current list of the bot's commands for the given scope and user
* language. Returns an Array of [BotCommand](https://core.telegram.org/bots/api/#botcommand)
* objects. If commands aren't set, an empty list is returned.
*
* @param scope A JSON-serialized object, describing scope of users. Defaults to
* [BotCommandScopeDefault](https://core.telegram.org/bots/api/#botcommandscopedefault).
* @param languageCode A two-letter ISO 639-1 language code or an empty string
*/
public suspend fun Container.getMyCommands(scope: BotCommandScope? = null, languageCode: String?
= null): List<BotCommand> = bot.getMyCommands(
scope = scope,
languageCode = languageCode,
)
/**
* Use this method to change the bot's name. Returns *True* on success.
*
* @param name New bot name; 0-64 characters. Pass an empty string to remove the dedicated name
* for the given language.
* @param languageCode A two-letter ISO 639-1 language code. If empty, the name will be shown to
* all users for whose language there is no dedicated name.
*/
public suspend fun Container.setMyName(name: String? = null, languageCode: String? = null):
Boolean = bot.setMyName(
name = name,
languageCode = languageCode,
)
/**
* Use this method to get the current bot name for the given user language. Returns
* [BotName](https://core.telegram.org/bots/api/#botname) on success.
*
* @param languageCode A two-letter ISO 639-1 language code or an empty string
*/
public suspend fun Container.getMyName(languageCode: String? = null): BotName = bot.getMyName(
languageCode = languageCode,
)
/**
* Use this method to change the bot's description, which is shown in the chat with the bot if
* the chat is empty. Returns *True* on success.
*
* @param description New bot description; 0-512 characters. Pass an empty string to remove the
* dedicated description for the given language.
* @param languageCode A two-letter ISO 639-1 language code. If empty, the description will be
* applied to all users for whose language there is no dedicated description.
*/
public suspend fun Container.setMyDescription(description: String? = null, languageCode: String?
= null): Boolean = bot.setMyDescription(
description = description,
languageCode = languageCode,
)
/**
* Use this method to get the current bot description for the given user language. Returns
* [BotDescription](https://core.telegram.org/bots/api/#botdescription) on success.
*
* @param languageCode A two-letter ISO 639-1 language code or an empty string
*/
public suspend fun Container.getMyDescription(languageCode: String? = null): BotDescription =
bot.getMyDescription(
languageCode = languageCode,
)
/**
* Use this method to change the bot's short description, which is shown on the bot's profile
* page and is sent together with the link when users share the bot. Returns *True* on success.
*
* @param shortDescription New short description for the bot; 0-120 characters. Pass an empty
* string to remove the dedicated short description for the given language.
* @param languageCode A two-letter ISO 639-1 language code. If empty, the short description
* will be applied to all users for whose language there is no dedicated short description.
*/
public suspend fun Container.setMyShortDescription(shortDescription: String? = null,
languageCode: String? = null): Boolean = bot.setMyShortDescription(
shortDescription = shortDescription,
languageCode = languageCode,
)
/**
* Use this method to get the current bot short description for the given user language. Returns
* [BotShortDescription](https://core.telegram.org/bots/api/#botshortdescription) on success.
*
* @param languageCode A two-letter ISO 639-1 language code or an empty string
*/
public suspend fun Container.getMyShortDescription(languageCode: String? = null):
BotShortDescription = bot.getMyShortDescription(
languageCode = languageCode,
)
/**
* Use this method to change the bot's menu button in a private chat, or the default menu
* button. Returns *True* on success.
*
* @param menuButton A JSON-serialized object for the bot's new menu button. Defaults to
* [MenuButtonDefault](https://core.telegram.org/bots/api/#menubuttondefault)
*/
public suspend fun Container.setChatMenuButton(menuButton: MenuButton? = null): Boolean =
bot.setChatMenuButton(
chatId = chat.id,
menuButton = menuButton,
)
/**
* Use this method to get the current value of the bot's menu button in a private chat, or the
* default menu button. Returns [MenuButton](https://core.telegram.org/bots/api/#menubutton) on
* success.
*/
public suspend fun Container.getChatMenuButton(): MenuButton = bot.getChatMenuButton(
chatId = chat.id,
)
/**
* Use this method to change the default administrator rights requested by the bot when it's
* added as an administrator to groups or channels. These rights will be suggested to users, but
* they are free to modify the list before adding the bot. Returns *True* on success.
*
* @param rights A JSON-serialized object describing new default administrator rights. If not
* specified, the default administrator rights will be cleared.
* @param forChannels Pass *True* to change the default administrator rights of the bot in
* channels. Otherwise, the default administrator rights of the bot for groups and supergroups will
* be changed.
*/
public suspend fun Container.setMyDefaultAdministratorRights(rights: ChatAdministratorRights? =
null, forChannels: Boolean? = null): Boolean = bot.setMyDefaultAdministratorRights(
rights = rights,
forChannels = forChannels,
)
/**
* Use this method to get the current default administrator rights of the bot. Returns
* [ChatAdministratorRights](https://core.telegram.org/bots/api/#chatadministratorrights) on
* success.
*
* @param forChannels Pass *True* to get default administrator rights of the bot in channels.
* Otherwise, default administrator rights of the bot for groups and supergroups will be returned.
*/
public suspend fun Container.getMyDefaultAdministratorRights(forChannels: Boolean? = null):
ChatAdministratorRights = bot.getMyDefaultAdministratorRights(
forChannels = forChannels,
)
/**
* Use this method to edit text and [game](https://core.telegram.org/bots/api/#games) messages.
* On success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned. Note that business messages that were not sent by the bot and do not contain an inline
* keyboard can only be edited within **48 hours** from the time they were sent.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* to edit
* @param text New text of the message, 1-4096 characters after entities parsing
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param parseMode Mode for parsing entities in the message text. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param entities A JSON-serialized list of special entities that appear in message text, which
* can be specified instead of *parse_mode*
* @param linkPreviewOptions Link preview generation options for the message
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageText(
messageId: Long,
text: String,
businessConnectionId: String? = null,
parseMode: String? = null,
entities: Iterable<MessageEntity>? = null,
linkPreviewOptions: LinkPreviewOptions? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.editMessageText(
chatId = chat.id,
messageId = messageId,
text = text,
businessConnectionId = businessConnectionId,
parseMode = parseMode,
entities = entities,
linkPreviewOptions = linkPreviewOptions,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit captions of messages. On success, if the edited message is not an
* inline message, the edited [Message](https://core.telegram.org/bots/api/#message) is returned,
* otherwise *True* is returned. Note that business messages that were not sent by the bot and do
* not contain an inline keyboard can only be edited within **48 hours** from the time they were
* sent.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* to edit
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param caption New caption of the message, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the message caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media. Supported only for animation, photo and video messages.
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageCaption(
messageId: Long,
businessConnectionId: String? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.editMessageCaption(
chatId = chat.id,
messageId = messageId,
businessConnectionId = businessConnectionId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit animation, audio, document, photo, or video messages. If a message is
* part of a message album, then it can be edited only to an audio for audio albums, only to a
* document for document albums and to a photo or a video otherwise. When an inline message is
* edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify
* a URL. On success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned. Note that business messages that were not sent by the bot and do not contain an inline
* keyboard can only be edited within **48 hours** from the time they were sent.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* to edit
* @param media A JSON-serialized object for a new media content of the message
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageMedia(
messageId: Long,
media: InputMedia,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.editMessageMedia(
chatId = chat.id,
messageId = messageId,
media = media,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit live location messages. A location can be edited until its
* *live_period* expires or editing is explicitly disabled by a call to
* [stopMessageLiveLocation](https://core.telegram.org/bots/api/#stopmessagelivelocation). On
* success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* to edit
* @param latitude Latitude of new location
* @param longitude Longitude of new location
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param livePeriod New period in seconds during which the location can be updated, starting
* from the message send date. If 0x7FFFFFFF is specified, then the location can be updated
* forever. Otherwise, the new value must not exceed the current *live_period* by more than a day,
* and the live location expiration date must remain within the next 90 days. If not specified,
* then *live_period* remains unchanged
* @param horizontalAccuracy The radius of uncertainty for the location, measured in meters;
* 0-1500
* @param heading Direction in which the user is moving, in degrees. Must be between 1 and 360
* if specified.
* @param proximityAlertRadius The maximum distance for proximity alerts about approaching
* another chat member, in meters. Must be between 1 and 100000 if specified.
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageLiveLocation(
messageId: Long,
latitude: Double,
longitude: Double,
businessConnectionId: String? = null,
livePeriod: Int? = null,
horizontalAccuracy: Double? = null,
heading: Int? = null,
proximityAlertRadius: Int? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.editMessageLiveLocation(
chatId = chat.id,
messageId = messageId,
latitude = latitude,
longitude = longitude,
businessConnectionId = businessConnectionId,
livePeriod = livePeriod,
horizontalAccuracy = horizontalAccuracy,
heading = heading,
proximityAlertRadius = proximityAlertRadius,
replyMarkup = replyMarkup,
)
/**
* Use this method to stop updating a live location message before *live_period* expires. On
* success, if the message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* with live location to stop
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.stopMessageLiveLocation(
messageId: Long,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.stopMessageLiveLocation(
chatId = chat.id,
messageId = messageId,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit only the reply markup of messages. On success, if the edited message
* is not an inline message, the edited [Message](https://core.telegram.org/bots/api/#message) is
* returned, otherwise *True* is returned. Note that business messages that were not sent by the
* bot and do not contain an inline keyboard can only be edited within **48 hours** from the time
* they were sent.
*
* @param messageId Required if *inline_message_id* is not specified. Identifier of the message
* to edit
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageReplyMarkup(
messageId: Long,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.editMessageReplyMarkup(
chatId = chat.id,
messageId = messageId,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to stop a poll which was sent by the bot. On success, the stopped
* [Poll](https://core.telegram.org/bots/api/#poll) is returned.
*
* @param messageId Identifier of the original message with the poll
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for a new message [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.stopPoll(
messageId: Long,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Poll = bot.stopPoll(
chatId = chat.id,
messageId = messageId,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to delete a message, including service messages, with the following
* limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Service messages about a supergroup, channel, or forum topic creation can't be deleted.
* - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
*
* - Bots can delete outgoing messages in private chats, groups, and supergroups.
* - Bots can delete incoming messages in private chats.
* - Bots granted *can_post_messages* permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has *can_delete_messages* permission in a supergroup or a channel, it can delete
* any message there.
* Returns *True* on success.
*
* @param messageId Identifier of the message to delete
*/
public suspend fun Container.deleteMessage(messageId: Long): Boolean = bot.deleteMessage(
chatId = chat.id,
messageId = messageId,
)
/**
* Use this method to delete multiple messages simultaneously. If some of the specified messages
* can't be found, they are skipped. Returns *True* on success.
*
* @param messageIds A JSON-serialized list of 1-100 identifiers of messages to delete. See
* [deleteMessage](https://core.telegram.org/bots/api/#deletemessage) for limitations on which
* messages can be deleted
*/
public suspend fun Container.deleteMessages(messageIds: Iterable<Long>): Boolean =
bot.deleteMessages(
chatId = chat.id,
messageIds = messageIds,
)
/**
* Use this method to send static .WEBP, [animated](https://telegram.org/blog/animated-stickers)
* .TGS, or [video](https://telegram.org/blog/video-stickers-better-reactions) .WEBM stickers. On
* success, the sent [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the
* Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker
* from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data.
* [More information on Sending Files ](https://core.telegram.org/bots/api/#sending-files). Video
* and animated stickers can't be sent via an HTTP URL.
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param emoji Emoji associated with the sticker; only for just uploaded stickers
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup Additional interface options. A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards), [custom reply
* keyboard](https://core.telegram.org/bots/features#keyboards), instructions to remove a reply
* keyboard or to force a reply from the user
*/
public suspend fun Container.sendSticker(
sticker: Input,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
emoji: String? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: ReplyMarkup? = null,
): Message = bot.sendSticker(
chatId = chat.id,
sticker = sticker,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
emoji = emoji,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to get a sticker set. On success, a
* [StickerSet](https://core.telegram.org/bots/api/#stickerset) object is returned.
*
* @param name Name of the sticker set
*/
public suspend fun Container.getStickerSet(name: String): StickerSet = bot.getStickerSet(
name = name,
)
/**
* Use this method to get information about custom emoji stickers by their identifiers. Returns
* an Array of [Sticker](https://core.telegram.org/bots/api/#sticker) objects.
*
* @param customEmojiIds A JSON-serialized list of custom emoji identifiers. At most 200 custom
* emoji identifiers can be specified.
*/
public suspend fun Container.getCustomEmojiStickers(customEmojiIds: Iterable<String>):
List<Sticker> = bot.getCustomEmojiStickers(
customEmojiIds = customEmojiIds,
)
/**
* Use this method to upload a file with a sticker for later use in the
* [createNewStickerSet](https://core.telegram.org/bots/api/#createnewstickerset),
* [addStickerToSet](https://core.telegram.org/bots/api/#addstickertoset), or
* [replaceStickerInSet](https://core.telegram.org/bots/api/#replacestickerinset) methods (the file
* can be used multiple times). Returns the uploaded
* [File](https://core.telegram.org/bots/api/#file) on success.
*
* @param userId User identifier of sticker file owner
* @param sticker A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See
* [https://core.telegram.org/stickers](https://core.telegram.org/stickers) for technical
* requirements. [More information on Sending Files
* ](https://core.telegram.org/bots/api/#sending-files)
* @param stickerFormat Format of the sticker, must be one of “static”, “animated”, “video”
*/
public suspend fun Container.uploadStickerFile(
userId: Long,
sticker: Input,
stickerFormat: String,
): File = bot.uploadStickerFile(
userId = userId,
sticker = sticker,
stickerFormat = stickerFormat,
)
/**
* Use this method to create a new sticker set owned by a user. The bot will be able to edit the
* sticker set thus created. Returns *True* on success.
*
* @param userId User identifier of created sticker set owner
* @param name Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g.,
* *animals*). Can contain only English letters, digits and underscores. Must begin with a letter,
* can't contain consecutive underscores and must end in `"_by_<bot_username>"`. `<bot_username>`
* is case insensitive. 1-64 characters.
* @param title Sticker set title, 1-64 characters
* @param stickers A JSON-serialized list of 1-50 initial stickers to be added to the sticker
* set
* @param stickerType Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By
* default, a regular sticker set is created.
* @param needsRepainting Pass *True* if stickers in the sticker set must be repainted to the
* color of text when used in messages, the accent color if used as emoji status, white on chat
* photos, or another appropriate color based on context; for custom emoji sticker sets only
*/
public suspend fun Container.createNewStickerSet(
userId: Long,
name: String,
title: String,
stickers: Iterable<InputSticker>,
stickerType: String? = null,
needsRepainting: Boolean? = null,
): Boolean = bot.createNewStickerSet(
userId = userId,
name = name,
title = title,
stickers = stickers,
stickerType = stickerType,
needsRepainting = needsRepainting,
)
/**
* Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have
* up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns *True* on success.
*
* @param userId User identifier of sticker set owner
* @param name Sticker set name
* @param sticker A JSON-serialized object with information about the added sticker. If exactly
* the same sticker had already been added to the set, then the set isn't changed.
*/
public suspend fun Container.addStickerToSet(
userId: Long,
name: String,
sticker: InputSticker,
): Boolean = bot.addStickerToSet(
userId = userId,
name = name,
sticker = sticker,
)
/**
* Use this method to move a sticker in a set created by the bot to a specific position. Returns
* *True* on success.
*
* @param sticker File identifier of the sticker
* @param position New sticker position in the set, zero-based
*/
public suspend fun Container.setStickerPositionInSet(sticker: String, position: Int): Boolean =
bot.setStickerPositionInSet(
sticker = sticker,
position = position,
)
/**
* Use this method to delete a sticker from a set created by the bot. Returns *True* on success.
*
* @param sticker File identifier of the sticker
*/
public suspend fun Container.deleteStickerFromSet(sticker: String): Boolean =
bot.deleteStickerFromSet(
sticker = sticker,
)
/**
* Use this method to replace an existing sticker in a sticker set with a new one. The method is
* equivalent to calling
* [deleteStickerFromSet](https://core.telegram.org/bots/api/#deletestickerfromset), then
* [addStickerToSet](https://core.telegram.org/bots/api/#addstickertoset), then
* [setStickerPositionInSet](https://core.telegram.org/bots/api/#setstickerpositioninset). Returns
* *True* on success.
*
* @param userId User identifier of the sticker set owner
* @param name Sticker set name
* @param oldSticker File identifier of the replaced sticker
* @param sticker A JSON-serialized object with information about the added sticker. If exactly
* the same sticker had already been added to the set, then the set remains unchanged.
*/
public suspend fun Container.replaceStickerInSet(
userId: Long,
name: String,
oldSticker: String,
sticker: InputSticker,
): Boolean = bot.replaceStickerInSet(
userId = userId,
name = name,
oldSticker = oldSticker,
sticker = sticker,
)
/**
* Use this method to change the list of emoji assigned to a regular or custom emoji sticker.
* The sticker must belong to a sticker set created by the bot. Returns *True* on success.
*
* @param sticker File identifier of the sticker
* @param emojiList A JSON-serialized list of 1-20 emoji associated with the sticker
*/
public suspend fun Container.setStickerEmojiList(sticker: String, emojiList: Iterable<String>):
Boolean = bot.setStickerEmojiList(
sticker = sticker,
emojiList = emojiList,
)
/**
* Use this method to change search keywords assigned to a regular or custom emoji sticker. The
* sticker must belong to a sticker set created by the bot. Returns *True* on success.
*
* @param sticker File identifier of the sticker
* @param keywords A JSON-serialized list of 0-20 search keywords for the sticker with total
* length of up to 64 characters
*/
public suspend fun Container.setStickerKeywords(sticker: String, keywords: Iterable<String>? =
null): Boolean = bot.setStickerKeywords(
sticker = sticker,
keywords = keywords,
)
/**
* Use this method to change the [mask
* position](https://core.telegram.org/bots/api/#maskposition) of a mask sticker. The sticker must
* belong to a sticker set that was created by the bot. Returns *True* on success.
*
* @param sticker File identifier of the sticker
* @param maskPosition A JSON-serialized object with the position where the mask should be
* placed on faces. Omit the parameter to remove the mask position.
*/
public suspend fun Container.setStickerMaskPosition(sticker: String, maskPosition: MaskPosition?
= null): Boolean = bot.setStickerMaskPosition(
sticker = sticker,
maskPosition = maskPosition,
)
/**
* Use this method to set the title of a created sticker set. Returns *True* on success.
*
* @param name Sticker set name
* @param title Sticker set title, 1-64 characters
*/
public suspend fun Container.setStickerSetTitle(name: String, title: String): Boolean =
bot.setStickerSetTitle(
name = name,
title = title,
)
/**
* Use this method to set the thumbnail of a regular or mask sticker set. The format of the
* thumbnail file must match the format of the stickers in the set. Returns *True* on success.
*
* @param name Sticker set name
* @param userId User identifier of the sticker set owner
* @param format Format of the thumbnail, must be one of “static” for a **.WEBP** or **.PNG**
* image, “animated” for a **.TGS** animation, or “video” for a **WEBM** video
* @param thumbnail A **.WEBP** or **.PNG** image with the thumbnail, must be up to 128
* kilobytes in size and have a width and height of exactly 100px, or a **.TGS** animation with a
* thumbnail up to 32 kilobytes in size (see
* [https://core.telegram.org/stickers#animated-sticker-requirements](https://core.telegram.org/stickers#animated-sticker-requirements)
* for animated sticker technical requirements), or a **WEBM** video with the thumbnail up to 32
* kilobytes in size; see
* [https://core.telegram.org/stickers#video-sticker-requirements](https://core.telegram.org/stickers#video-sticker-requirements)
* for video sticker technical requirements. Pass a *file_id* as a String to send a file that
* already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file
* from the Internet, or upload a new one using multipart/form-data. [More information on Sending
* Files ](https://core.telegram.org/bots/api/#sending-files). Animated and video sticker set
* thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the
* first sticker is used as the thumbnail.
*/
public suspend fun Container.setStickerSetThumbnail(
name: String,
userId: Long,
format: String,
thumbnail: Input? = null,
): Boolean = bot.setStickerSetThumbnail(
name = name,
userId = userId,
format = format,
thumbnail = thumbnail,
)
/**
* Use this method to set the thumbnail of a custom emoji sticker set. Returns *True* on
* success.
*
* @param name Sticker set name
* @param customEmojiId Custom emoji identifier of a sticker from the sticker set; pass an empty
* string to drop the thumbnail and use the first sticker as the thumbnail.
*/
public suspend fun Container.setCustomEmojiStickerSetThumbnail(name: String,
customEmojiId: String? = null): Boolean = bot.setCustomEmojiStickerSetThumbnail(
name = name,
customEmojiId = customEmojiId,
)
/**
* Use this method to delete a sticker set that was created by the bot. Returns *True* on
* success.
*
* @param name Sticker set name
*/
public suspend fun Container.deleteStickerSet(name: String): Boolean = bot.deleteStickerSet(
name = name,
)
/**
* Use this method to send answers to an inline query. On success, *True* is returned.
* No more than **50** results per query are allowed.
*
* @param inlineQueryId Unique identifier for the answered query
* @param results A JSON-serialized array of results for the inline query
* @param cacheTime The maximum amount of time in seconds that the result of the inline query
* may be cached on the server. Defaults to 300.
* @param isPersonal Pass *True* if results may be cached on the server side only for the user
* that sent the query. By default, results may be returned to any user who sends the same query.
* @param nextOffset Pass the offset that a client should send in the next query with the same
* text to receive more results. Pass an empty string if there are no more results or if you don't
* support pagination. Offset length can't exceed 64 bytes.
* @param button A JSON-serialized object describing a button to be shown above inline query
* results
*/
public suspend fun Container.answerInlineQuery(
inlineQueryId: String,
results: Iterable<InlineQueryResult>,
cacheTime: Int? = null,
isPersonal: Boolean? = null,
nextOffset: String? = null,
button: InlineQueryResultsButton? = null,
): Boolean = bot.answerInlineQuery(
inlineQueryId = inlineQueryId,
results = results,
cacheTime = cacheTime,
isPersonal = isPersonal,
nextOffset = nextOffset,
button = button,
)
/**
* Use this method to set the result of an interaction with a [Web
* App](https://core.telegram.org/bots/webapps) and send a corresponding message on behalf of the
* user to the chat from which the query originated. On success, a
* [SentWebAppMessage](https://core.telegram.org/bots/api/#sentwebappmessage) object is returned.
*
* @param webAppQueryId Unique identifier for the query to be answered
* @param result A JSON-serialized object describing the message to be sent
*/
public suspend fun Container.answerWebAppQuery(webAppQueryId: String,
result: InlineQueryResult): SentWebAppMessage = bot.answerWebAppQuery(
webAppQueryId = webAppQueryId,
result = result,
)
/**
* Use this method to send invoices. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param title Product name, 1-32 characters
* @param description Product description, 1-255 characters
* @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the
* user, use for your internal processes.
* @param currency Three-letter ISO 4217 currency code, see [more on
* currencies](https://core.telegram.org/bots/payments#supported-currencies). Pass “XTR” for
* payments in [Telegram Stars](https://t.me/BotNews/90).
* @param prices Price breakdown, a JSON-serialized list of components (e.g. product price, tax,
* discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments
* in [Telegram Stars](https://t.me/BotNews/90).
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param providerToken Payment provider token, obtained via
* [@BotFather](https://t.me/botfather). Pass an empty string for payments in [Telegram
* Stars](https://t.me/BotNews/90).
* @param maxTipAmount The maximum accepted amount for tips in the *smallest units* of the
* currency (integer, **not** float/double). For example, for a maximum tip of `US$ 1.45` pass
* `max_tip_amount = 145`. See the *exp* parameter in
* [currencies.json](https://core.telegram.org/bots/payments/currencies.json), it shows the number
* of digits past the decimal point for each currency (2 for the majority of currencies). Defaults
* to 0. Not supported for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param suggestedTipAmounts A JSON-serialized array of suggested amounts of tips in the
* *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip
* amounts can be specified. The suggested tip amounts must be positive, passed in a strictly
* increased order and must not exceed *max_tip_amount*.
* @param startParameter Unique deep-linking parameter. If left empty, **forwarded copies** of
* the sent message will have a *Pay* button, allowing multiple users to pay directly from the
* forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message
* will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value
* used as the start parameter
* @param providerData JSON-serialized data about the invoice, which will be shared with the
* payment provider. A detailed description of required fields should be provided by the payment
* provider.
* @param photoUrl URL of the product photo for the invoice. Can be a photo of the goods or a
* marketing image for a service. People like it better when they see what they are paying for.
* @param photoSize Photo size in bytes
* @param photoWidth Photo width
* @param photoHeight Photo height
* @param needName Pass *True* if you require the user's full name to complete the order.
* Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needPhoneNumber Pass *True* if you require the user's phone number to complete the
* order. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needEmail Pass *True* if you require the user's email address to complete the order.
* Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needShippingAddress Pass *True* if you require the user's shipping address to complete
* the order. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param sendPhoneNumberToProvider Pass *True* if the user's phone number should be sent to the
* provider. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param sendEmailToProvider Pass *True* if the user's email address should be sent to the
* provider. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param isFlexible Pass *True* if the final price depends on the shipping method. Ignored for
* payments in [Telegram Stars](https://t.me/BotNews/90).
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards). If empty, one 'Pay `total
* price`' button will be shown. If not empty, the first button must be a Pay button.
*/
public suspend fun Container.sendInvoice(
title: String,
description: String,
payload: String,
currency: String,
prices: Iterable<LabeledPrice>,
messageThreadId: Long? = null,
providerToken: String? = null,
maxTipAmount: Int? = null,
suggestedTipAmounts: Iterable<Int>? = null,
startParameter: String? = null,
providerData: String? = null,
photoUrl: String? = null,
photoSize: Int? = null,
photoWidth: Int? = null,
photoHeight: Int? = null,
needName: Boolean? = null,
needPhoneNumber: Boolean? = null,
needEmail: Boolean? = null,
needShippingAddress: Boolean? = null,
sendPhoneNumberToProvider: Boolean? = null,
sendEmailToProvider: Boolean? = null,
isFlexible: Boolean? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.sendInvoice(
chatId = chat.id,
title = title,
description = description,
payload = payload,
currency = currency,
prices = prices,
messageThreadId = messageThreadId,
providerToken = providerToken,
maxTipAmount = maxTipAmount,
suggestedTipAmounts = suggestedTipAmounts,
startParameter = startParameter,
providerData = providerData,
photoUrl = photoUrl,
photoSize = photoSize,
photoWidth = photoWidth,
photoHeight = photoHeight,
needName = needName,
needPhoneNumber = needPhoneNumber,
needEmail = needEmail,
needShippingAddress = needShippingAddress,
sendPhoneNumberToProvider = sendPhoneNumberToProvider,
sendEmailToProvider = sendEmailToProvider,
isFlexible = isFlexible,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to create a link for an invoice. Returns the created invoice link as *String*
* on success.
*
* @param title Product name, 1-32 characters
* @param description Product description, 1-255 characters
* @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the
* user, use for your internal processes.
* @param currency Three-letter ISO 4217 currency code, see [more on
* currencies](https://core.telegram.org/bots/payments#supported-currencies). Pass “XTR” for
* payments in [Telegram Stars](https://t.me/BotNews/90).
* @param prices Price breakdown, a JSON-serialized list of components (e.g. product price, tax,
* discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments
* in [Telegram Stars](https://t.me/BotNews/90).
* @param providerToken Payment provider token, obtained via
* [@BotFather](https://t.me/botfather). Pass an empty string for payments in [Telegram
* Stars](https://t.me/BotNews/90).
* @param maxTipAmount The maximum accepted amount for tips in the *smallest units* of the
* currency (integer, **not** float/double). For example, for a maximum tip of `US$ 1.45` pass
* `max_tip_amount = 145`. See the *exp* parameter in
* [currencies.json](https://core.telegram.org/bots/payments/currencies.json), it shows the number
* of digits past the decimal point for each currency (2 for the majority of currencies). Defaults
* to 0. Not supported for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param suggestedTipAmounts A JSON-serialized array of suggested amounts of tips in the
* *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip
* amounts can be specified. The suggested tip amounts must be positive, passed in a strictly
* increased order and must not exceed *max_tip_amount*.
* @param providerData JSON-serialized data about the invoice, which will be shared with the
* payment provider. A detailed description of required fields should be provided by the payment
* provider.
* @param photoUrl URL of the product photo for the invoice. Can be a photo of the goods or a
* marketing image for a service.
* @param photoSize Photo size in bytes
* @param photoWidth Photo width
* @param photoHeight Photo height
* @param needName Pass *True* if you require the user's full name to complete the order.
* Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needPhoneNumber Pass *True* if you require the user's phone number to complete the
* order. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needEmail Pass *True* if you require the user's email address to complete the order.
* Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param needShippingAddress Pass *True* if you require the user's shipping address to complete
* the order. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param sendPhoneNumberToProvider Pass *True* if the user's phone number should be sent to the
* provider. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param sendEmailToProvider Pass *True* if the user's email address should be sent to the
* provider. Ignored for payments in [Telegram Stars](https://t.me/BotNews/90).
* @param isFlexible Pass *True* if the final price depends on the shipping method. Ignored for
* payments in [Telegram Stars](https://t.me/BotNews/90).
*/
public suspend fun Container.createInvoiceLink(
title: String,
description: String,
payload: String,
currency: String,
prices: Iterable<LabeledPrice>,
providerToken: String? = null,
maxTipAmount: Int? = null,
suggestedTipAmounts: Iterable<Int>? = null,
providerData: String? = null,
photoUrl: String? = null,
photoSize: Int? = null,
photoWidth: Int? = null,
photoHeight: Int? = null,
needName: Boolean? = null,
needPhoneNumber: Boolean? = null,
needEmail: Boolean? = null,
needShippingAddress: Boolean? = null,
sendPhoneNumberToProvider: Boolean? = null,
sendEmailToProvider: Boolean? = null,
isFlexible: Boolean? = null,
): String = bot.createInvoiceLink(
title = title,
description = description,
payload = payload,
currency = currency,
prices = prices,
providerToken = providerToken,
maxTipAmount = maxTipAmount,
suggestedTipAmounts = suggestedTipAmounts,
providerData = providerData,
photoUrl = photoUrl,
photoSize = photoSize,
photoWidth = photoWidth,
photoHeight = photoHeight,
needName = needName,
needPhoneNumber = needPhoneNumber,
needEmail = needEmail,
needShippingAddress = needShippingAddress,
sendPhoneNumberToProvider = sendPhoneNumberToProvider,
sendEmailToProvider = sendEmailToProvider,
isFlexible = isFlexible,
)
/**
* If you sent an invoice requesting a shipping address and the parameter *is_flexible* was
* specified, the Bot API will send an [Update](https://core.telegram.org/bots/api/#update) with a
* *shipping_query* field to the bot. Use this method to reply to shipping queries. On success,
* *True* is returned.
*
* @param shippingQueryId Unique identifier for the query to be answered
* @param ok Pass *True* if delivery to the specified address is possible and *False* if there
* are any problems (for example, if delivery to the specified address is not possible)
* @param shippingOptions Required if *ok* is *True*. A JSON-serialized array of available
* shipping options.
* @param errorMessage Required if *ok* is *False*. Error message in human readable form that
* explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired
* address is unavailable'). Telegram will display this message to the user.
*/
public suspend fun Container.answerShippingQuery(
shippingQueryId: String,
ok: Boolean,
shippingOptions: Iterable<ShippingOption>? = null,
errorMessage: String? = null,
): Boolean = bot.answerShippingQuery(
shippingQueryId = shippingQueryId,
ok = ok,
shippingOptions = shippingOptions,
errorMessage = errorMessage,
)
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final
* confirmation in the form of an [Update](https://core.telegram.org/bots/api/#update) with the
* field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success,
* *True* is returned. **Note:** The Bot API must receive an answer within 10 seconds after the
* pre-checkout query was sent.
*
* @param preCheckoutQueryId Unique identifier for the query to be answered
* @param ok Specify *True* if everything is alright (goods are available, etc.) and the bot is
* ready to proceed with the order. Use *False* if there are any problems.
* @param errorMessage Required if *ok* is *False*. Error message in human readable form that
* explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought
* the last of our amazing black T-shirts while you were busy filling out your payment details.
* Please choose a different color or garment!"). Telegram will display this message to the user.
*/
public suspend fun Container.answerPreCheckoutQuery(
preCheckoutQueryId: String,
ok: Boolean,
errorMessage: String? = null,
): Boolean = bot.answerPreCheckoutQuery(
preCheckoutQueryId = preCheckoutQueryId,
ok = ok,
errorMessage = errorMessage,
)
/**
* Returns the bot's Telegram Star transactions in chronological order. On success, returns a
* [StarTransactions](https://core.telegram.org/bots/api/#startransactions) object.
*
* @param offset Number of transactions to skip in the response
* @param limit The maximum number of transactions to be retrieved. Values between 1-100 are
* accepted. Defaults to 100.
*/
public suspend fun Container.getStarTransactions(offset: Int? = null, limit: Int? = null):
StarTransactions = bot.getStarTransactions(
offset = offset,
limit = limit,
)
/**
* Refunds a successful payment in [Telegram Stars](https://t.me/BotNews/90). Returns *True* on
* success.
*
* @param userId Identifier of the user whose payment will be refunded
* @param telegramPaymentChargeId Telegram payment identifier
*/
public suspend fun Container.refundStarPayment(userId: Long, telegramPaymentChargeId: String):
Boolean = bot.refundStarPayment(
userId = userId,
telegramPaymentChargeId = telegramPaymentChargeId,
)
/**
* Informs a user that some of the Telegram Passport elements they provided contains errors. The
* user will not be able to re-submit their Passport to you until the errors are fixed (the
* contents of the field for which you returned the error must change). Returns *True* on success.
*
* Use this if the data submitted by the user doesn't satisfy the standards your service
* requires for any reason. For example, if a birthday date seems invalid, a submitted document is
* blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to
* make sure the user knows how to correct the issues.
*
* @param userId User identifier
* @param errors A JSON-serialized array describing the errors
*/
public suspend fun Container.setPassportDataErrors(userId: Long,
errors: Iterable<PassportElementError>): Boolean = bot.setPassportDataErrors(
userId = userId,
errors = errors,
)
/**
* Use this method to send a game. On success, the sent
* [Message](https://core.telegram.org/bots/api/#message) is returned.
*
* @param gameShortName Short name of the game, serves as the unique identifier for the game.
* Set up your games via [@BotFather](https://t.me/botfather).
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message will be sent
* @param messageThreadId Unique identifier for the target message thread (topic) of the forum;
* for forum supergroups only
* @param disableNotification Sends the message
* [silently](https://telegram.org/blog/channels-2-0#silent-messages). Users will receive a
* notification with no sound.
* @param protectContent Protects the contents of the sent message from forwarding and saving
* @param messageEffectId Unique identifier of the message effect to be added to the message;
* for private chats only
* @param replyParameters Description of the message to reply to
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards). If empty, one 'Play
* game_title' button will be shown. If not empty, the first button must launch the game.
*/
public suspend fun Container.sendGame(
gameShortName: String,
businessConnectionId: String? = null,
messageThreadId: Long? = null,
disableNotification: Boolean? = null,
protectContent: Boolean? = null,
messageEffectId: String? = null,
replyParameters: ReplyParameters? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Message = bot.sendGame(
chatId = chat.id,
gameShortName = gameShortName,
businessConnectionId = businessConnectionId,
messageThreadId = messageThreadId,
disableNotification = disableNotification,
protectContent = protectContent,
messageEffectId = messageEffectId,
replyParameters = replyParameters,
replyMarkup = replyMarkup,
)
/**
* Use this method to set the score of the specified user in a game message. On success, if the
* message is not an inline message, the [Message](https://core.telegram.org/bots/api/#message) is
* returned, otherwise *True* is returned. Returns an error, if the new score is not greater than
* the user's current score in the chat and *force* is *False*.
*
* @param userId User identifier
* @param score New score, must be non-negative
* @param messageId Required if *inline_message_id* is not specified. Identifier of the sent
* message
* @param force Pass *True* if the high score is allowed to decrease. This can be useful when
* fixing mistakes or banning cheaters
* @param disableEditMessage Pass *True* if the game message should not be automatically edited
* to include the current scoreboard
*/
public suspend fun Container.setGameScore(
userId: Long,
score: Int,
messageId: Long,
force: Boolean? = null,
disableEditMessage: Boolean? = null,
): Message = bot.setGameScore(
userId = userId,
score = score,
chatId = chat.id,
messageId = messageId,
force = force,
disableEditMessage = disableEditMessage,
)
/**
* Use this method to get data for high score tables. Will return the score of the specified
* user and several of their neighbors in a game. Returns an Array of
* [GameHighScore](https://core.telegram.org/bots/api/#gamehighscore) objects.
*
* This method will currently return scores for the target user, plus two of their closest
* neighbors on each side. Will also return the top three users if the user and their neighbors are
* not among them. Please note that this behavior is subject to change.
*
* @param userId Target user id
* @param messageId Required if *inline_message_id* is not specified. Identifier of the sent
* message
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
*/
public suspend fun Container.getGameHighScores(
userId: Long,
messageId: Long? = null,
inlineMessageId: String? = null,
): List<GameHighScore> = bot.getGameHighScores(
userId = userId,
chatId = chat.id,
messageId = messageId,
inlineMessageId = inlineMessageId,
)
/**
* Use this method to edit text and [game](https://core.telegram.org/bots/api/#games) messages.
* On success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned. Note that business messages that were not sent by the bot and do not contain an inline
* keyboard can only be edited within **48 hours** from the time they were sent.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param text New text of the message, 1-4096 characters after entities parsing
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param parseMode Mode for parsing entities in the message text. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param entities A JSON-serialized list of special entities that appear in message text, which
* can be specified instead of *parse_mode*
* @param linkPreviewOptions Link preview generation options for the message
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageText(
inlineMessageId: String,
text: String,
businessConnectionId: String? = null,
parseMode: String? = null,
entities: Iterable<MessageEntity>? = null,
linkPreviewOptions: LinkPreviewOptions? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.editMessageText(
inlineMessageId = inlineMessageId,
text = text,
businessConnectionId = businessConnectionId,
parseMode = parseMode,
entities = entities,
linkPreviewOptions = linkPreviewOptions,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit captions of messages. On success, if the edited message is not an
* inline message, the edited [Message](https://core.telegram.org/bots/api/#message) is returned,
* otherwise *True* is returned. Note that business messages that were not sent by the bot and do
* not contain an inline keyboard can only be edited within **48 hours** from the time they were
* sent.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param caption New caption of the message, 0-1024 characters after entities parsing
* @param parseMode Mode for parsing entities in the message caption. See [formatting
* options](https://core.telegram.org/bots/api/#formatting-options) for more details.
* @param captionEntities A JSON-serialized list of special entities that appear in the caption,
* which can be specified instead of *parse_mode*
* @param showCaptionAboveMedia Pass *True*, if the caption must be shown above the message
* media. Supported only for animation, photo and video messages.
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageCaption(
inlineMessageId: String,
businessConnectionId: String? = null,
caption: String? = null,
parseMode: String? = null,
captionEntities: Iterable<MessageEntity>? = null,
showCaptionAboveMedia: Boolean? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.editMessageCaption(
inlineMessageId = inlineMessageId,
businessConnectionId = businessConnectionId,
caption = caption,
parseMode = parseMode,
captionEntities = captionEntities,
showCaptionAboveMedia = showCaptionAboveMedia,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit animation, audio, document, photo, or video messages. If a message is
* part of a message album, then it can be edited only to an audio for audio albums, only to a
* document for document albums and to a photo or a video otherwise. When an inline message is
* edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify
* a URL. On success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned. Note that business messages that were not sent by the bot and do not contain an inline
* keyboard can only be edited within **48 hours** from the time they were sent.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param media A JSON-serialized object for a new media content of the message
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageMedia(
inlineMessageId: String,
media: InputMedia,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.editMessageMedia(
inlineMessageId = inlineMessageId,
media = media,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit live location messages. A location can be edited until its
* *live_period* expires or editing is explicitly disabled by a call to
* [stopMessageLiveLocation](https://core.telegram.org/bots/api/#stopmessagelivelocation). On
* success, if the edited message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param latitude Latitude of new location
* @param longitude Longitude of new location
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param livePeriod New period in seconds during which the location can be updated, starting
* from the message send date. If 0x7FFFFFFF is specified, then the location can be updated
* forever. Otherwise, the new value must not exceed the current *live_period* by more than a day,
* and the live location expiration date must remain within the next 90 days. If not specified,
* then *live_period* remains unchanged
* @param horizontalAccuracy The radius of uncertainty for the location, measured in meters;
* 0-1500
* @param heading Direction in which the user is moving, in degrees. Must be between 1 and 360
* if specified.
* @param proximityAlertRadius The maximum distance for proximity alerts about approaching
* another chat member, in meters. Must be between 1 and 100000 if specified.
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageLiveLocation(
inlineMessageId: String,
latitude: Double,
longitude: Double,
businessConnectionId: String? = null,
livePeriod: Int? = null,
horizontalAccuracy: Double? = null,
heading: Int? = null,
proximityAlertRadius: Int? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.editMessageLiveLocation(
inlineMessageId = inlineMessageId,
latitude = latitude,
longitude = longitude,
businessConnectionId = businessConnectionId,
livePeriod = livePeriod,
horizontalAccuracy = horizontalAccuracy,
heading = heading,
proximityAlertRadius = proximityAlertRadius,
replyMarkup = replyMarkup,
)
/**
* Use this method to stop updating a live location message before *live_period* expires. On
* success, if the message is not an inline message, the edited
* [Message](https://core.telegram.org/bots/api/#message) is returned, otherwise *True* is
* returned.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for a new [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.stopMessageLiveLocation(
inlineMessageId: String,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.stopMessageLiveLocation(
inlineMessageId = inlineMessageId,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to edit only the reply markup of messages. On success, if the edited message
* is not an inline message, the edited [Message](https://core.telegram.org/bots/api/#message) is
* returned, otherwise *True* is returned. Note that business messages that were not sent by the
* bot and do not contain an inline keyboard can only be edited within **48 hours** from the time
* they were sent.
*
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param businessConnectionId Unique identifier of the business connection on behalf of which
* the message to be edited was sent
* @param replyMarkup A JSON-serialized object for an [inline
* keyboard](https://core.telegram.org/bots/features#inline-keyboards).
*/
public suspend fun Container.editMessageReplyMarkup(
inlineMessageId: String,
businessConnectionId: String? = null,
replyMarkup: InlineKeyboardMarkup? = null,
): Boolean = bot.editMessageReplyMarkup(
inlineMessageId = inlineMessageId,
businessConnectionId = businessConnectionId,
replyMarkup = replyMarkup,
)
/**
* Use this method to set the score of the specified user in a game message. On success, if the
* message is not an inline message, the [Message](https://core.telegram.org/bots/api/#message) is
* returned, otherwise *True* is returned. Returns an error, if the new score is not greater than
* the user's current score in the chat and *force* is *False*.
*
* @param userId User identifier
* @param score New score, must be non-negative
* @param inlineMessageId Required if *chat_id* and *message_id* are not specified. Identifier
* of the inline message
* @param force Pass *True* if the high score is allowed to decrease. This can be useful when
* fixing mistakes or banning cheaters
* @param disableEditMessage Pass *True* if the game message should not be automatically edited
* to include the current scoreboard
*/
public suspend fun Container.setGameScore(
userId: Long,
score: Int,
inlineMessageId: String,
force: Boolean? = null,
disableEditMessage: Boolean? = null,
): Boolean = bot.setGameScore(
userId = userId,
score = score,
inlineMessageId = inlineMessageId,
force = force,
disableEditMessage = disableEditMessage,
)
}
| 1
| null |
3
| 24
|
5912e61857da3f63a7bb383490730f47f7f1f8c6
| 183,775
|
telegram-bot
|
Apache License 2.0
|
common/theme/theme-impl/src/main/java/dev/bwaim/loteria/theme/impl/ThemeRepositoryImpl.kt
|
Bwaim
| 410,120,178
| false
| null |
/*
* Copyright 2022 Dev Bwaim team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.bwaim.loteria.theme.impl
import androidx.annotation.VisibleForTesting
import androidx.datastore.core.DataStore
import dev.bwaim.loteria.theme.Theme
import dev.bwaim.loteria.theme.ThemeRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
@VisibleForTesting
public class ThemeRepositoryImpl @Inject constructor(
private val dataStore: DataStore<ThemePreferences>,
) : ThemeRepository {
override fun observeTheme(): Flow<Theme> {
return dataStore
.data
.distinctUntilChanged()
.map { prefs ->
ThemeHelper.fromPreferences(prefs.theme)
}
}
override suspend fun setTheme(theme: Theme) {
dataStore.updateData {
it.copy {
this@copy.theme = theme.value
}
}
}
}
| 19
|
Kotlin
|
1
| 3
|
83ea974b6e1b14a9a65a6a2f89f407e13e5fea31
| 1,524
|
Loteria-Mexicana
|
Apache License 2.0
|
app/src/main/java/com/unitewikiapp/unitewiki/utils/Response.kt
|
jhj0517
| 656,711,299
| false
|
{"Kotlin": 95340, "Java": 9115}
|
package com.unitewikiapp.unitewiki.utils
sealed class Response<out T> {
class Loading<out T> : Response<T>()
data class Success<out T>(val data: T) : Response<T>()
data class Failure<out T>(val throwable: Throwable) : Response<T>()
}
| 0
|
Kotlin
|
0
| 0
|
71d4eaba5de378f095b2f9fb7cb0b966a4efa9b8
| 246
|
UniteWiki
|
Apache License 2.0
|
app/src/main/java/org/listenbrainz/android/viewmodel/BPAlbumViewModel.kt
|
metabrainz
| 550,726,972
| false
|
{"Kotlin": 1481175, "Ruby": 423}
|
package org.listenbrainz.android.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.listenbrainz.android.model.Album
import org.listenbrainz.android.model.Song
import org.listenbrainz.android.repository.brainzplayer.BPAlbumRepository
import org.listenbrainz.android.repository.preferences.AppPreferences
import javax.inject.Inject
@HiltViewModel
class BPAlbumViewModel @Inject constructor(
val BPAlbumRepository: BPAlbumRepository,
val appPreferences: AppPreferences
) : ViewModel() {
val albums = BPAlbumRepository.getAlbums()
// Refreshing variables.
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing = _isRefreshing.asStateFlow()
init {
fetchAlbumsFromDevice()
}
fun fetchAlbumsFromDevice(userRequestedRefresh: Boolean = false) {
viewModelScope.launch(Dispatchers.IO) {
if (userRequestedRefresh){
_isRefreshing.update { true }
appPreferences.albumsOnDevice = BPAlbumRepository.addAlbums(userRequestedRefresh = true)
_isRefreshing.update { false }
} else {
albums.collectLatest {
if (it.isEmpty()) {
_isRefreshing.update { true }
appPreferences.albumsOnDevice = BPAlbumRepository.addAlbums()
_isRefreshing.update { false }
}
}
}
}
}
fun getAlbumFromID(albumID: Long): Flow<Album> {
return BPAlbumRepository.getAlbum(albumID)
}
fun getAllSongsOfAlbum(albumID: Long): Flow<List<Song>>{
return BPAlbumRepository.getAllSongsOfAlbum(albumID)
}
}
| 25
|
Kotlin
|
31
| 99
|
573ab0ec6c5b87ea963f013174159ddfcd123976
| 2,086
|
listenbrainz-android
|
Apache License 2.0
|
app/src/main/java/org/listenbrainz/android/viewmodel/BPAlbumViewModel.kt
|
metabrainz
| 550,726,972
| false
|
{"Kotlin": 1481175, "Ruby": 423}
|
package org.listenbrainz.android.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.listenbrainz.android.model.Album
import org.listenbrainz.android.model.Song
import org.listenbrainz.android.repository.brainzplayer.BPAlbumRepository
import org.listenbrainz.android.repository.preferences.AppPreferences
import javax.inject.Inject
@HiltViewModel
class BPAlbumViewModel @Inject constructor(
val BPAlbumRepository: BPAlbumRepository,
val appPreferences: AppPreferences
) : ViewModel() {
val albums = BPAlbumRepository.getAlbums()
// Refreshing variables.
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing = _isRefreshing.asStateFlow()
init {
fetchAlbumsFromDevice()
}
fun fetchAlbumsFromDevice(userRequestedRefresh: Boolean = false) {
viewModelScope.launch(Dispatchers.IO) {
if (userRequestedRefresh){
_isRefreshing.update { true }
appPreferences.albumsOnDevice = BPAlbumRepository.addAlbums(userRequestedRefresh = true)
_isRefreshing.update { false }
} else {
albums.collectLatest {
if (it.isEmpty()) {
_isRefreshing.update { true }
appPreferences.albumsOnDevice = BPAlbumRepository.addAlbums()
_isRefreshing.update { false }
}
}
}
}
}
fun getAlbumFromID(albumID: Long): Flow<Album> {
return BPAlbumRepository.getAlbum(albumID)
}
fun getAllSongsOfAlbum(albumID: Long): Flow<List<Song>>{
return BPAlbumRepository.getAllSongsOfAlbum(albumID)
}
}
| 25
|
Kotlin
|
31
| 99
|
573ab0ec6c5b87ea963f013174159ddfcd123976
| 2,086
|
listenbrainz-android
|
Apache License 2.0
|
kotlin-node/src/main/generated/node/crypto/getCurves.kt
|
stefanthaler
| 440,580,782
| true
|
{"Kotlin": 8815376, "JavaScript": 528}
|
// Automatically generated - do not modify!
@file:JsModule("node:crypto")
@file:JsNonModule
package node.crypto
import kotlinx.js.ReadonlyArray
/**
* ```js
* const {
* getCurves
* } = await import('crypto');
*
* console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
* ```
* @since v2.3.0
* @return An array with the names of the supported elliptic curves.
*/
external fun getCurves(): ReadonlyArray<String>
| 0
|
Kotlin
|
0
| 0
|
fc27a2b5d98423c8db24f8a28d1c3a95dc682b0a
| 438
|
kotlin-wrappers
|
Apache License 2.0
|
tests/src/commonMain/kotlin/app/thelema/test/phys/CylinderShapeTest.kt
|
zeganstyl
| 275,550,896
| false
| null |
/*
* Copyright 2020-2021 Anton Trushkov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.thelema.test.phys
import app.thelema.ecs.mainEntity
import app.thelema.g3d.cam.orbitCameraControl
import app.thelema.g3d.material
import app.thelema.g3d.mesh.cylinderMesh
import app.thelema.gl.mesh
import app.thelema.math.MATH
import app.thelema.math.Vec3
import app.thelema.phys.*
import app.thelema.shader.SimpleShader3D
import app.thelema.test.Test
/** @author zeganstyl */
class CylinderShapeTest: Test {
override fun testMain() = mainEntity {
orbitCameraControl {
targetDistance = 10f
}
val cylinder = cylinderMesh {
radius = 1f
length = 1f
divisions = 32
axis = Vec3(0f, 0f, 1f)
mesh.isVisible = false
}
// material will be set to box mesh automatically
material {
shader = SimpleShader3D()
}
entity("dynamic") {
mesh { inheritedMesh = cylinder.mesh }
cylinderShape {
radius = cylinder.radius
length = cylinder.length
}
rigidBody {
node.position.set(0f, 3f, 0f)
}
}
entity("static1") {
mesh { inheritedMesh = cylinder.mesh }
cylinderShape {
radius = cylinder.radius
length = cylinder.length
}
rigidBody {
node.position.set(1.25f, 0f, 0f)
node.rotateAroundAxis(1f, 0f, 0f, MATH.PI_HALF)
isStatic = true
}
}
entity("static2") {
mesh { inheritedMesh = cylinder.mesh }
cylinderShape {
radius = cylinder.radius
length = cylinder.length
}
rigidBody {
node.position.set(-2f, 0f, 0f)
node.rotateAroundAxis(1f, 0f, 0f, MATH.PI_HALF)
isStatic = true
}
}
rigidBodyPhysicsWorld {
startSimulation()
}
}
}
| 3
|
Kotlin
|
5
| 61
|
8e2943b6d2de3376ce338025b58ff31c14097caf
| 2,635
|
thelema-engine
|
Apache License 2.0
|
subprojects/delivery/cd/src/main/kotlin/com/avito/ci/BuildStepListExtension.kt
|
avito-tech
| 230,265,582
| false
| null |
package com.avito.ci
import com.avito.android.Problem
import com.avito.android.asRuntimeException
import com.avito.ci.steps.ArtifactsConfiguration
import com.avito.ci.steps.BuildStep
import com.avito.ci.steps.CompileUiTests
import com.avito.ci.steps.ConfigurationCheck
import com.avito.ci.steps.CustomTaskStep
import com.avito.ci.steps.DependencyAnalysisStep
import com.avito.ci.steps.DeployStep
import com.avito.ci.steps.FlakyReportStep
import com.avito.ci.steps.ImpactAnalysisAwareBuildStep
import com.avito.ci.steps.ImpactMetrics
import com.avito.ci.steps.LintCheck
import com.avito.ci.steps.MarkReportAsSourceForTMSStep
import com.avito.ci.steps.TestSummaryStep
import com.avito.ci.steps.UiTestCheck
import com.avito.ci.steps.UnitTestCheck
import com.avito.ci.steps.UploadBuildResult
import com.avito.ci.steps.UploadToArtifactory
import com.avito.ci.steps.UploadToProsector
import com.avito.ci.steps.UploadToQapps
import com.avito.ci.steps.VerifyArtifactsStep
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.Named
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.kotlin.dsl.property
@Suppress("UnstableApiUsage", "unused", "MemberVisibilityCanBePrivate")
public open class BuildStepListExtension(
internal val buildStepListName: String,
objects: ObjectFactory
) : Named {
private val artifactsConfig = ArtifactsConfiguration()
internal val steps = objects.polymorphicDomainObjectContainer(BuildStep::class.java).apply {
registerFactory(ConfigurationCheck::class.java) { name ->
ConfigurationCheck(buildStepListName, name)
}
registerFactory(UiTestCheck::class.java) { name ->
UiTestCheck(buildStepListName, name)
}
registerFactory(CompileUiTests::class.java) { name ->
CompileUiTests(buildStepListName, name)
}
registerFactory(ImpactMetrics::class.java) { name ->
ImpactMetrics(buildStepListName, name)
}
registerFactory(UnitTestCheck::class.java) { name ->
UnitTestCheck(buildStepListName, name)
}
registerFactory(LintCheck::class.java) { name ->
LintCheck(buildStepListName, name)
}
registerFactory(MarkReportAsSourceForTMSStep::class.java) { name ->
MarkReportAsSourceForTMSStep(buildStepListName, name)
}
registerFactory(TestSummaryStep::class.java) { name ->
TestSummaryStep(buildStepListName, name)
}
registerFactory(FlakyReportStep::class.java) { name ->
FlakyReportStep(buildStepListName, name)
}
registerFactory(DependencyAnalysisStep::class.java) { name ->
DependencyAnalysisStep(buildStepListName, name)
}
registerFactory(UploadToQapps::class.java) { name ->
UploadToQapps(buildStepListName, artifactsConfig, name)
}
registerFactory(UploadToArtifactory::class.java) { name ->
UploadToArtifactory(buildStepListName, artifactsConfig, name)
}
registerFactory(UploadToProsector::class.java) { name ->
UploadToProsector(buildStepListName, artifactsConfig, name)
}
registerFactory(UploadBuildResult::class.java) { name ->
UploadBuildResult(buildStepListName, name)
}
registerFactory(DeployStep::class.java) { name ->
DeployStep(buildStepListName, artifactsConfig, name)
}
registerFactory(VerifyArtifactsStep::class.java) { name ->
VerifyArtifactsStep(buildStepListName, artifactsConfig, name)
}
registerFactory(CustomTaskStep::class.java) { name ->
CustomTaskStep(buildStepListName, name)
}
}
// todo property
public var useImpactAnalysis: Boolean = true
public val taskDescription: Property<String> = objects.property()
override fun getName(): String = buildStepListName
public fun configuration(closure: Closure<ConfigurationCheck>) {
configureAndAdd("configuration", closure)
}
public fun configuration(action: Action<ConfigurationCheck>) {
configureAndAdd("configuration", action)
}
public fun uiTests(closure: Closure<UiTestCheck>) {
configureAndAdd("uiTests", closure)
}
public fun uiTests(action: Action<UiTestCheck>) {
configureAndAdd("uiTests", action)
}
public fun compileUiTests(closure: Closure<CompileUiTests>) {
configureAndAdd("compileUiTests", closure)
}
public fun compileUiTests(action: Action<CompileUiTests>) {
configureAndAdd("compileUiTests", action)
}
public fun impactMetrics(closure: Closure<ImpactMetrics>) {
configureAndAdd("impactMetrics", closure)
}
public fun impactMetrics(action: Action<ImpactMetrics>) {
configureAndAdd("impactMetrics", action)
}
public fun unitTests(closure: Closure<UnitTestCheck>) {
configureAndAdd("unitTests", closure)
}
public fun unitTests(action: Action<UnitTestCheck>) {
configureAndAdd("unitTests", action)
}
public fun dependencyAnalysis(closure: Closure<DependencyAnalysisStep>) {
configureAndAdd("dependencyAnalysis", closure)
}
public fun dependencyAnalysis(action: Action<DependencyAnalysisStep>) {
configureAndAdd("dependencyAnalysis", action)
}
public fun lint(closure: Closure<LintCheck>) {
configureAndAdd("lint", closure)
}
public fun lint(action: Action<LintCheck>) {
configureAndAdd("lint", action)
}
public fun markReportAsSourceForTMS(closure: Closure<MarkReportAsSourceForTMSStep>) {
configureAndAdd("markReportAsSourceForTMS", closure)
}
public fun markReportAsSourceForTMS(action: Action<MarkReportAsSourceForTMSStep>) {
configureAndAdd("markReportAsSourceForTMS", action)
}
public fun testSummary(closure: Closure<TestSummaryStep>) {
configureAndAdd("testSummary", closure)
}
public fun testSummary(action: Action<TestSummaryStep>) {
configureAndAdd("testSummary", action)
}
public fun flakyReport(closure: Closure<FlakyReportStep>) {
configureAndAdd("flakyReport", closure)
}
public fun flakyReport(action: Action<FlakyReportStep>) {
configureAndAdd("flakyReport", action)
}
public fun uploadToQapps(closure: Closure<UploadToQapps>) {
configureAndAdd("uploadToQapps", closure)
}
public fun uploadToQapps(action: Action<UploadToQapps>) {
configureAndAdd("uploadToQapps", action)
}
public fun uploadToArtifactory(closure: Closure<UploadToArtifactory>) {
configureAndAdd("uploadToArtifactory", closure)
}
public fun uploadToArtifactory(action: Action<UploadToArtifactory>) {
configureAndAdd("uploadToArtifactory", action)
}
public fun uploadToProsector(closure: Closure<UploadToProsector>) {
configureAndAdd("uploadToProsector", closure)
}
public fun uploadToProsector(action: Action<UploadToProsector>) {
configureAndAdd("uploadToProsector", action)
}
public fun uploadBuildResult(closure: Closure<UploadBuildResult>) {
configureAndAdd("uploadBuildResult", closure)
}
public fun uploadBuildResult(action: Action<UploadBuildResult>) {
configureAndAdd("uploadBuildResult", action)
}
public fun deploy(closure: Closure<DeployStep>) {
configureAndAdd("deploy", closure)
}
public fun deploy(action: Action<DeployStep>) {
configureAndAdd("deploy", action)
}
/**
* @name any unique name of a step
*/
public fun customTask(name: String, configuration: Action<CustomTaskStep>) {
configureAndAdd(name, configuration)
}
/**
* @name any unique name of a step
*/
public fun customTask(name: String, configuration: Closure<CustomTaskStep>) {
configureAndAdd(name, configuration)
}
public fun artifacts(closure: Closure<ArtifactsConfiguration>): Unit =
artifacts(
closure.toAction(delegate = artifactsConfig)
)
public fun artifacts(action: Action<ArtifactsConfiguration>) {
action.execute(artifactsConfig)
val step = steps.maybeCreate("artifacts", VerifyArtifactsStep::class.java)
step.useImpactAnalysis = this.useImpactAnalysis
}
public fun <T : BuildStep> overrideStep(type: Class<T>, configuration: Closure<T>): Unit =
overrideStep(type, configuration.toAction())
public inline fun <reified T : BuildStep> overrideStep(configuration: Action<T>): Unit =
overrideStep(T::class.java, configuration)
public fun <T : BuildStep> overrideStep(type: Class<T>, configuration: Action<T>) {
val steps = steps.withType(type).toList()
require(steps.isNotEmpty()) {
"Build step ${type.simpleName} is not registered in $buildStepListName"
}
require(steps.size == 1) {
"Found multiple steps ${type.simpleName} in $buildStepListName. Please, specify the name."
}
val step = steps.first()
configuration.execute(step)
}
public fun <T : BuildStep> overrideStep(name: String, type: Class<T>, configuration: Closure<T>): Unit =
overrideStep(name, type, configuration.toAction())
public fun <T : BuildStep> overrideStep(name: String, type: Class<T>, configuration: Action<T>) {
val step = requireNotNull(steps.findByName(name)) {
"Build step '$name' is not registered in $buildStepListName"
}
require(type.isAssignableFrom(step::class.java)) {
"Build step '$name' is ${step::class.java} but expected ${type.name}"
}
@Suppress("UNCHECKED_CAST")
configuration.execute(step as T)
}
private inline fun <reified T : BuildStep> configureAndAdd(
name: String,
configuration: Closure<T>
) = configureAndAdd(name, configuration.toAction())
private inline fun <reified T : BuildStep> configureAndAdd(
name: String,
configuration: Action<T>
) {
ensureNotRegistered(name)
val step = steps.create(name, T::class.java)
configuration.execute(step)
if (step is ImpactAnalysisAwareBuildStep) {
step.useImpactAnalysis = this.useImpactAnalysis
}
}
private fun ensureNotRegistered(name: String) {
val step = steps.findByName(name)
if (step != null) {
throw Problem.Builder(
shortDescription = "Overriding existing build step '$name' (${step::class.java.simpleName}) " +
"in '$buildStepListName' chain",
context = "Adding a build step '$name' to $buildStepListName"
)
.because("Forbid implicit overriding of build steps")
.addSolution("Configure the build step in one place")
.addSolution("Override the build step explicitly by overrideStep() method")
.build()
.asRuntimeException()
}
}
private fun <T> Closure<T>.toAction(
delegate: Any? = null
): Action<T> = Action<T> {
this.delegate = delegate ?: it
this.resolveStrategy = Closure.DELEGATE_FIRST
this.call()
}
}
| 6
| null |
36
| 327
|
b8d12a06a169ae60d89d24f66978a7dc23833282
| 11,385
|
avito-android
|
MIT License
|
Zhidian/app/src/main/java/com/zhidian/application/ui/search/SearchViewModel.kt
|
EricMoin
| 638,540,521
| false
| null |
package com.zhidian.application.ui.search
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.zhidian.application.logic.data.StockItem
import com.zhidian.application.logic.model.SearchRepository
import com.zhidian.application.logic.model.StockRepository
import com.zhidian.stockmanager.logic.GroupRepository
import com.zhidian.stockmanager.logic.data.ManageGroupItem
import com.zhidian.stockmanager.logic.data.ManageStockItem
class SearchViewModel : ViewModel() {
private val _historyLiveData = MutableLiveData< List<StockItem> >()
val historyLiveData get() = _historyLiveData
private val _rankLiveData = MutableLiveData< List<StockItem> >()
val rankLiveData get() = _rankLiveData
private val _searchLiveData = MutableLiveData< List<StockItem> >()
val searchLiveData get() = _searchLiveData
val historyList = ArrayList<StockItem>()
val searchList = ArrayList<StockItem>()
val rankList = ArrayList<StockItem>()
val groups = ArrayList<ManageGroupItem>()
fun getHistory(){
_historyLiveData.value = SearchRepository.getHistory()
}
fun loadHistory() = SearchRepository.loadHistory()
fun saveHistory(stock:StockItem) = SearchRepository.saveHistory(stock)
fun getRank(){
_rankLiveData.value = SearchRepository.getRanks()
}
fun getSearch(query:String,uri:String){
_searchLiveData.value = SearchRepository.getSearch(query,uri)
}
fun loadGroups() = GroupRepository.loadGroups()
fun loadGroups(path:String) = GroupRepository.loadGroups(path)
fun saveGroup(group: ManageGroupItem) = GroupRepository.saveGroup(group)
fun getGroupList() = GroupRepository.getGroupList()
fun moveStockTo(stock:ManageStockItem, groupName:String) = GroupRepository.moveStockTo(stock,groupName)
fun removeStockInAllGroups(stockName: String) = GroupRepository.removeStockInAllGroups(stockName)
fun newGroup(groupName:String) = groups.add(ManageGroupItem( groupName,ArrayList<ManageStockItem>() ) )
fun updateGroups(groups:List<ManageGroupItem>) = GroupRepository.updateGroups(groups)
fun getDefaultList() = GroupRepository.getDefaultList()
fun deleteGroup(position:Int) = groups.removeAt(position)
fun removeHistory(stock: StockItem){
historyList.remove(stock)
SearchRepository.removeHistory(stock)
}
fun queryHasFocused(item:StockItem):Boolean{
loadGroups()
val list = getGroupList()
for(group in list){
for(stock in group.stocks){
Log.d("ViewModel","query ${item.code} ?: ${stock.id}")
if(item.code == stock.id) return true
}
}
return false
}
}
| 0
|
Kotlin
|
0
| 0
|
54c55ece61c995c46de7160bf0e11b6b528c0b4b
| 2,737
|
ZhiDianREP
|
Apache License 2.0
|
app/src/main/java/tw/shounenwind/boringreader/UnitText.kt
|
michaeimm
| 201,517,838
| false
| null |
package tw.shounenwind.boringreader
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import android.view.ViewGroup
import org.jetbrains.anko.*
class UnitText(base: Context) : AnkoComponent<ViewGroup>, ContextWrapper(base) {
override fun createView(ui: AnkoContext<ViewGroup>): View = with(ui) {
textView {
id = R.id.text_unit
leftPadding = dip(16)
rightPadding = dip(16)
topPadding = dip(4)
bottomPadding = dip(4)
textSize = 16f
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d753fec31bb0fc793834ed0ea7086ec8a4a60397
| 578
|
BoringReader
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/ui/screens/characterlist/CharacterListViewModel.kt
|
gurkankesgin
| 834,752,770
| false
|
{"Kotlin": 18784, "Swift": 621}
|
package com.disney.ui.screens.characterlist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.disney.domain.model.Character
import com.disney.domain.usecase.GetCharacterUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
/**
* Created by gurkankesgin on 28.07.2024.
*/
class CharacterListViewModel(private var useCase: GetCharacterUseCase?) : ViewModel() {
private val _uiState = MutableStateFlow<CharacterListUIState>(CharacterListUIState.Loading)
val uiState: StateFlow<CharacterListUIState> = _uiState.asStateFlow()
init {
getResult()
}
private fun getResult() {
viewModelScope.launch {
useCase?.invoke()?.onEach { characterList ->
_uiState.value = CharacterListUIState.Success(characterList)
}?.launchIn(viewModelScope)
}
}
sealed class CharacterListUIState {
data object Loading : CharacterListUIState()
data class Success(
val data: List<Character>? = null,
) : CharacterListUIState()
}
}
| 0
|
Kotlin
|
0
| 0
|
fd8919c17983a10e105018573ba40ca9bd0c88d9
| 1,272
|
Disney-KMPOfflineFirstApp
|
The Unlicense
|
android/app/src/main/kotlin/top/z7workbench/focyapp/MainActivity.kt
|
z7workbench
| 355,858,261
| false
|
{"Dart": 11154, "Swift": 404, "Kotlin": 128, "Objective-C": 38}
|
package top.z7workbench.focyapp
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
c40b178e0f5fa82fdf880df6379f856bcd354702
| 128
|
focyapp
|
MIT License
|
dagger-track/src/test/kotlin/me/amanjeet/daggertrack/utils/DaggerAndroidMinimalProjectCreator.kt
|
amanjeetsingh150
| 372,235,899
| false
| null |
package me.amanjeet.daggertrack.utils
fun createMinimalDaggerAndroidProject(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addDependencies(
"implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.5.10'",
"implementation 'androidx.appcompat:appcompat:1.1.0'",
"implementation 'androidx.core:core-ktx:1.5.0'",
"implementation 'androidx.constraintlayout:constraintlayout:2.0.4'",
"implementation 'me.amanjeet.daggertrack:dagger-track-clocks:LOCAL_SNAPSHOT'",
"implementation 'com.google.dagger:dagger-android-support:2.35.1'",
"annotationProcessor 'com.google.dagger:dagger-android-processor:2.35.1'",
"annotationProcessor 'com.google.dagger:dagger-compiler:2.35.1'"
)
createApplicationClass(gradleTestRunner)
createApplicationComponent(gradleTestRunner)
createDaggerModules(gradleTestRunner)
createHomeScreenDeps(gradleTestRunner)
createHomeActivity(gradleTestRunner)
}
private fun createApplicationClass(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addSrc(
srcPath = "minimal/MyApp.java",
srcContent =
"""
package minimal;
import android.app.Application;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import minimal.DaggerApplicationComponent;
import dagger.android.HasAndroidInjector;
public class MyApp extends Application implements HasAndroidInjector {
@Inject
DispatchingAndroidInjector<Object> androidInjector;
@Override
public void onCreate() {
super.onCreate();
DaggerApplicationComponent
.builder()
.bindApplication(this)
.build()
.inject(this);
}
@Override
public AndroidInjector<Object> androidInjector() {
return androidInjector;
}
}
""".trimIndent()
)
gradleTestRunner.setAppClassName(".MyApp")
}
private fun createHomeScreenDeps(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addSrc(
srcPath = "minimal/HomeDependency.java",
srcContent = """
package minimal;
class HomeDependency {
public HomeDependency() {
// some home dependency
}
}
""".trimIndent()
)
}
private fun createHomeActivity(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addSrc(
srcPath = "minimal/HomeActivity.java",
srcContent =
"""
package minimal;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.AndroidInjection;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasAndroidInjector;
public class HomeActivity extends AppCompatActivity implements HasAndroidInjector {
@Inject
DispatchingAndroidInjector<Object> androidInjector;
@Inject
HomeDependency homeDependency;
@Override
public void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
}
@Override
public AndroidInjector<Object> androidInjector() {
return androidInjector;
}
}
""".trimIndent()
)
gradleTestRunner.addActivities(
"<activity android:name=\".HomeActivity\"/>"
)
}
private fun createApplicationComponent(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addSrc(
srcPath = "minimal/ApplicationComponent.java",
srcContent = """
package minimal;
import android.app.Application;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjectionModule;
import dagger.android.support.AndroidSupportInjectionModule;
import minimal.MyApp;
import javax.inject.Singleton;
@Singleton
@Component(
modules = {
AndroidInjectionModule.class,
AppModule.class,
AndroidSupportInjectionModule.class,
HomeActivityModule.class
}
)
interface ApplicationComponent {
void inject(MyApp myApplication);
@Component.Builder
interface Builder {
Builder bindApplication(@BindsInstance Application application);
ApplicationComponent build();
}
}
""".trimIndent()
)
}
private fun createDaggerModules(gradleTestRunner: GradleTestRunner) {
gradleTestRunner.addSrc(
srcPath = "minimal/HomeActivityModule.java",
srcContent = """
package minimal;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import minimal.HomeActivity;
@Module
abstract class HomeActivityModule {
@ContributesAndroidInjector(modules = { HomeModule.class })
abstract HomeActivity homeActivity();
}
""".trimIndent()
)
gradleTestRunner.addSrc(
srcPath = "minimal/AppModule.java",
srcContent = """
package minimal;
import android.app.Application;
import android.content.Context;
import dagger.Binds;
import dagger.Module;
import javax.inject.Singleton;
@Module
abstract class AppModule {
@Binds
@Singleton
abstract Context provideApplicationContext(Application application);
}
""".trimIndent()
)
gradleTestRunner.addSrc(
srcPath = "minimal/HomeModule.java",
srcContent = """
package minimal;
import dagger.Module;
import dagger.Provides;
import minimal.HomeDependency;
@Module
class HomeModule {
@Provides
HomeDependency providesHeavyDependencyOne() {
return new HomeDependency();
}
}
""".trimIndent()
)
}
| 4
|
Kotlin
|
3
| 63
|
38828b3e93ff81ff8e10a60e352462df73e12192
| 8,034
|
dagger-track
|
Apache License 2.0
|
bellatrix.web/src/main/java/solutions/bellatrix/web/components/contracts/ComponentLongDesc.kt
|
AutomateThePlanet
| 334,964,015
| false
| null |
/*
* Copyright 2021 Automate The Planet Ltd.
* Author: <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package solutions.bellatrix.web.components.contracts
import solutions.bellatrix.web.components.WebComponent
import solutions.bellatrix.web.validations.ComponentValidator
interface ComponentLongDesc : Component {
val longdesc: String
fun validateLongDescIs(value: String) {
defaultValidateAttributeIs(this as WebComponent, longdesc, value, "longdesc")
}
fun validateLongDescIsSet() {
defaultValidateAttributeIsSet(this as WebComponent, longdesc, "longdesc")
}
fun validateLongDescNotSet() {
defaultValidateAttributeNotSet(this as WebComponent, longdesc, "longdesc")
}
fun validateLongDescContains(value: String) {
defaultValidateAttributeContains(this as WebComponent, longdesc, value, "longdesc")
}
fun validateLongDescNotContains(value: String) {
defaultValidateAttributeNotContains(this as WebComponent, longdesc, value, "longdesc")
}
companion object : ComponentValidator()
}
| 1
|
Kotlin
|
1
| 1
|
5da5e705b47e12c66937d130b3031ac8703b8279
| 1,584
|
BELLATRIX-Kotlin
|
Apache License 2.0
|
app/src/main/java/com/smartsolutions/spotifyclone/MainActivity.kt
|
staglizd
| 680,700,900
| false
| null |
package com.smartsolutions.spotifyclone
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.bumptech.glide.RequestManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var glide: RequestManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 0
|
Kotlin
|
0
| 0
|
9d58d3a319726121ed6ac7f66f592844ff81922a
| 497
|
SpotifyMVVM
|
MIT License
|
app/src/main/java/com/hypertrack/android/ui/common/delegates/AddressDelegate.kt
|
hypertrack
| 241,723,736
| false
| null |
package com.hypertrack.android.ui.common.delegates
import android.location.Address
import com.google.android.gms.maps.model.LatLng
import com.google.android.libraries.places.api.model.Place
import com.hypertrack.android.api.GeofenceVisit
import com.hypertrack.android.api.asLocation
import com.hypertrack.android.models.local.LocalGeofence
import com.hypertrack.android.models.local.LocalGeofenceVisit
import com.hypertrack.android.models.local.LocalOrder
import com.hypertrack.android.ui.common.util.format
import com.hypertrack.android.ui.common.util.nullIfBlank
import com.hypertrack.android.ui.common.util.nullIfEmpty
import com.hypertrack.android.utils.OsUtilsProvider
import com.hypertrack.android.utils.datetimeFromString
import com.hypertrack.android.utils.formatters.DatetimeFormatter
import com.hypertrack.logistics.android.github.R
class OrderAddressDelegate(
val osUtilsProvider: OsUtilsProvider,
val datetimeFormatter: DatetimeFormatter
) {
//todo nominatim first two parts
//used as order name in list
fun shortAddress(order: LocalOrder): String {
return order.destinationAddress?.nullIfBlank()?.let {
if (it.length < SHORT_ADDRESS_LIMIT) {
it
} else null
} ?: osUtilsProvider.getPlaceFromCoordinates(
order.destinationLatLng.latitude,
order.destinationLatLng.longitude
)?.toAddressString(short = true, disableCoordinatesFallback = true)
?: order.scheduledAt?.let {
osUtilsProvider.stringFromResource(
R.string.order_scheduled_at,
datetimeFormatter.formatDatetime(it)
)
}
?: osUtilsProvider.stringFromResource(R.string.order_address_not_available)
}
fun fullAddress(order: LocalOrder): String {
return order.destinationAddress?.nullIfBlank()
?: osUtilsProvider.getPlaceFromCoordinates(
order.destinationLatLng.latitude,
order.destinationLatLng.longitude
)?.toAddressString(disableCoordinatesFallback = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
}
class GeofenceAddressDelegate(val osUtilsProvider: OsUtilsProvider) {
fun shortAddress(geofence: LocalGeofence): String {
return geofence.address?.nullIfBlank()?.let {
if (it.length < SHORT_ADDRESS_LIMIT) {
it
} else null
} ?: osUtilsProvider.getPlaceFromCoordinates(
geofence.latLng.latitude,
geofence.latLng.longitude
)?.toAddressString(short = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun fullAddress(geofence: LocalGeofence): String {
return geofence.address?.nullIfBlank()
?: osUtilsProvider.getPlaceFromCoordinates(
geofence.latLng.latitude,
geofence.latLng.longitude
)?.toAddressString()
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun shortAddress(visit: LocalGeofenceVisit): String {
return visit.address
?: visit.metadata?.address
?: visit.location.let {
osUtilsProvider.getPlaceFromCoordinates(
it.latitude,
it.longitude
)?.toAddressString(short = true)
}
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
}
class GooglePlaceAddressDelegate(
private val osUtilsProvider: OsUtilsProvider
) {
fun displayAddress(place: Place): String {
return place.getAddressString(strictMode = false)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun displayAddress(address: Address?): String {
return address?.toAddressString(disableCoordinatesFallback = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun strictAddress(address: Address): String? {
return address.toAddressString(strictMode = true)
}
fun strictAddress(place: Place): String? {
return place.getAddressString(strictMode = true)
}
}
fun String?.parseNominatimAddress(): String? {
return this?.let {
split(",").map { it.trim() }.take(2).joinToString(", ")
}
}
fun Address.toAddressString(
strictMode: Boolean = false,
short: Boolean = false,
disableCoordinatesFallback: Boolean = false,
): String? {
if (strictMode && thoroughfare == null) {
return null
}
val firstPart = if (short) null else locality ?: ""
val secondPart = if (!short) {
//long
if (thoroughfare != null) {
"$thoroughfare${subThoroughfare.wrapIfPresent(start = ", ")}"
} else {
if (!disableCoordinatesFallback) {
LatLng(latitude, longitude).format()
} else {
""
}
}
} else {
//short
if (thoroughfare != null) {
"$thoroughfare${subThoroughfare.wrapIfPresent(start = ", ")}"
} else {
if (!disableCoordinatesFallback) {
LatLng(latitude, longitude).format()
} else {
locality.wrapIfPresent()
}
}
}
return listOf(firstPart, secondPart)
.filter { !it.isNullOrBlank() }
.joinToString(", ")
.nullIfEmpty()
}
fun Place.getAddressString(
strictMode: Boolean = false
): String? {
val locality =
addressComponents?.asList()?.firstOrNull { "locality" in it.types }?.name
?: addressComponents?.asList()
?.firstOrNull { "administrative_area_level_1" in it.types }?.name
?: addressComponents?.asList()
?.firstOrNull { "administrative_area_level_2" in it.types }?.name
?: addressComponents?.asList()?.firstOrNull { "political" in it.types }?.name
val thoroughfare =
addressComponents?.asList()
?.firstOrNull { "route" in it.types }
?.name
var subThoroughfare =
addressComponents?.asList()?.firstOrNull { "street_number" in it.types }?.name
addressComponents?.asList()
?.firstOrNull { "subpremise" in it.types }
?.name.let {
subThoroughfare += " $it"
}
val parts = listOfNotNull(locality, thoroughfare, subThoroughfare)
return if (parts.isEmpty() || (strictMode && (thoroughfare == null || subThoroughfare == null))) {
null
} else {
parts.joinToString(", ")
}
}
fun String?.wrapIfPresent(start: String? = null, end: String? = null): String {
return this?.let { "${start.wrapIfPresent()}$it${end.wrapIfPresent()}" } ?: ""
}
const val SHORT_ADDRESS_LIMIT = 50
| 1
|
Kotlin
|
15
| 28
|
d418c449cbbbb19eca4f875a3e4f1099614213e4
| 6,847
|
logistics-android
|
MIT License
|
app/src/main/java/com/hypertrack/android/ui/common/delegates/AddressDelegate.kt
|
hypertrack
| 241,723,736
| false
| null |
package com.hypertrack.android.ui.common.delegates
import android.location.Address
import com.google.android.gms.maps.model.LatLng
import com.google.android.libraries.places.api.model.Place
import com.hypertrack.android.api.GeofenceVisit
import com.hypertrack.android.api.asLocation
import com.hypertrack.android.models.local.LocalGeofence
import com.hypertrack.android.models.local.LocalGeofenceVisit
import com.hypertrack.android.models.local.LocalOrder
import com.hypertrack.android.ui.common.util.format
import com.hypertrack.android.ui.common.util.nullIfBlank
import com.hypertrack.android.ui.common.util.nullIfEmpty
import com.hypertrack.android.utils.OsUtilsProvider
import com.hypertrack.android.utils.datetimeFromString
import com.hypertrack.android.utils.formatters.DatetimeFormatter
import com.hypertrack.logistics.android.github.R
class OrderAddressDelegate(
val osUtilsProvider: OsUtilsProvider,
val datetimeFormatter: DatetimeFormatter
) {
//todo nominatim first two parts
//used as order name in list
fun shortAddress(order: LocalOrder): String {
return order.destinationAddress?.nullIfBlank()?.let {
if (it.length < SHORT_ADDRESS_LIMIT) {
it
} else null
} ?: osUtilsProvider.getPlaceFromCoordinates(
order.destinationLatLng.latitude,
order.destinationLatLng.longitude
)?.toAddressString(short = true, disableCoordinatesFallback = true)
?: order.scheduledAt?.let {
osUtilsProvider.stringFromResource(
R.string.order_scheduled_at,
datetimeFormatter.formatDatetime(it)
)
}
?: osUtilsProvider.stringFromResource(R.string.order_address_not_available)
}
fun fullAddress(order: LocalOrder): String {
return order.destinationAddress?.nullIfBlank()
?: osUtilsProvider.getPlaceFromCoordinates(
order.destinationLatLng.latitude,
order.destinationLatLng.longitude
)?.toAddressString(disableCoordinatesFallback = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
}
class GeofenceAddressDelegate(val osUtilsProvider: OsUtilsProvider) {
fun shortAddress(geofence: LocalGeofence): String {
return geofence.address?.nullIfBlank()?.let {
if (it.length < SHORT_ADDRESS_LIMIT) {
it
} else null
} ?: osUtilsProvider.getPlaceFromCoordinates(
geofence.latLng.latitude,
geofence.latLng.longitude
)?.toAddressString(short = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun fullAddress(geofence: LocalGeofence): String {
return geofence.address?.nullIfBlank()
?: osUtilsProvider.getPlaceFromCoordinates(
geofence.latLng.latitude,
geofence.latLng.longitude
)?.toAddressString()
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun shortAddress(visit: LocalGeofenceVisit): String {
return visit.address
?: visit.metadata?.address
?: visit.location.let {
osUtilsProvider.getPlaceFromCoordinates(
it.latitude,
it.longitude
)?.toAddressString(short = true)
}
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
}
class GooglePlaceAddressDelegate(
private val osUtilsProvider: OsUtilsProvider
) {
fun displayAddress(place: Place): String {
return place.getAddressString(strictMode = false)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun displayAddress(address: Address?): String {
return address?.toAddressString(disableCoordinatesFallback = true)
?: osUtilsProvider.stringFromResource(R.string.address_not_available)
}
fun strictAddress(address: Address): String? {
return address.toAddressString(strictMode = true)
}
fun strictAddress(place: Place): String? {
return place.getAddressString(strictMode = true)
}
}
fun String?.parseNominatimAddress(): String? {
return this?.let {
split(",").map { it.trim() }.take(2).joinToString(", ")
}
}
fun Address.toAddressString(
strictMode: Boolean = false,
short: Boolean = false,
disableCoordinatesFallback: Boolean = false,
): String? {
if (strictMode && thoroughfare == null) {
return null
}
val firstPart = if (short) null else locality ?: ""
val secondPart = if (!short) {
//long
if (thoroughfare != null) {
"$thoroughfare${subThoroughfare.wrapIfPresent(start = ", ")}"
} else {
if (!disableCoordinatesFallback) {
LatLng(latitude, longitude).format()
} else {
""
}
}
} else {
//short
if (thoroughfare != null) {
"$thoroughfare${subThoroughfare.wrapIfPresent(start = ", ")}"
} else {
if (!disableCoordinatesFallback) {
LatLng(latitude, longitude).format()
} else {
locality.wrapIfPresent()
}
}
}
return listOf(firstPart, secondPart)
.filter { !it.isNullOrBlank() }
.joinToString(", ")
.nullIfEmpty()
}
fun Place.getAddressString(
strictMode: Boolean = false
): String? {
val locality =
addressComponents?.asList()?.firstOrNull { "locality" in it.types }?.name
?: addressComponents?.asList()
?.firstOrNull { "administrative_area_level_1" in it.types }?.name
?: addressComponents?.asList()
?.firstOrNull { "administrative_area_level_2" in it.types }?.name
?: addressComponents?.asList()?.firstOrNull { "political" in it.types }?.name
val thoroughfare =
addressComponents?.asList()
?.firstOrNull { "route" in it.types }
?.name
var subThoroughfare =
addressComponents?.asList()?.firstOrNull { "street_number" in it.types }?.name
addressComponents?.asList()
?.firstOrNull { "subpremise" in it.types }
?.name.let {
subThoroughfare += " $it"
}
val parts = listOfNotNull(locality, thoroughfare, subThoroughfare)
return if (parts.isEmpty() || (strictMode && (thoroughfare == null || subThoroughfare == null))) {
null
} else {
parts.joinToString(", ")
}
}
fun String?.wrapIfPresent(start: String? = null, end: String? = null): String {
return this?.let { "${start.wrapIfPresent()}$it${end.wrapIfPresent()}" } ?: ""
}
const val SHORT_ADDRESS_LIMIT = 50
| 1
|
Kotlin
|
15
| 28
|
d418c449cbbbb19eca4f875a3e4f1099614213e4
| 6,847
|
logistics-android
|
MIT License
|
project-system-gradle-psd/src/com/android/tools/idea/gradle/structure/configurables/ui/RenderedComboBox.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.structure.configurables.ui
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.StatusText
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Rectangle
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import javax.swing.DefaultComboBoxModel
import javax.swing.JList
import javax.swing.JTextField
import javax.swing.ListCellRenderer
import javax.swing.plaf.basic.BasicComboBoxEditor
/**
* An abstract surface to render a formatted text to.
*/
interface TextRenderer {
fun append(text: String, attributes: SimpleTextAttributes)
}
/**
* A base for drop-down editors providing a selection of pre-formatted text values.
*/
abstract class RenderedComboBox<T>(
private val itemsModel: DefaultComboBoxModel<T>
) : ComboBox<T>() {
interface Extension : ExtendableTextComponent.Extension
protected var lastValueSet: T? = null
private set
protected var beingLoaded = false
private set
/**
* Parses [text] and converts it to the value of type [T] if possible, otherwise returns null.
*/
abstract fun parseEditorText(text: String): T?
/**
* Converts [anObject] to the text format used by this editor for manual input.
*/
abstract fun toEditorText(anObject: T?): String
/**
* Renders [value] the desired rich presentation of the [value] to the receiver renderer.
*/
abstract fun TextRenderer.renderCell(value: T?)
// Make the methods callable from the constructor.
final override fun setRenderer(renderer: ListCellRenderer<in T>?) = super.setRenderer(renderer)
/**
* Sets the current value of the editor and makes the inactive editor renderer the presentation of [value].
*
* Note: It might be necessary to call setValue() in response to selectedItemChanged if the value returned by [parseEditorText] needs
* to be further enriched to render the proper presentation.
*/
fun setValue(value: T) {
beingLoaded = true
try {
lastValueSet = value
if (selectedItem != value) {
selectedItem = value
}
}
finally {
beingLoaded = false
}
}
private var currentStatusTriggerText: String? = null
override fun selectedItemChanged() {
super.selectedItemChanged()
updateWatermark()
}
internal fun updateWatermark() {
@Suppress("UNCHECKED_CAST")
val value = selectedItem as T?
currentStatusTriggerText = toEditorText(value)
val jbTextField = comboBoxEditor.editorComponent
val emptyText = jbTextField.emptyText
emptyText.clear()
emptyText.toRenderer().renderCell(value)
}
/**
* Populates the drop-down list of the combo-box.
*
* Note: The exact presentation of items is determined by [TextRenderer.renderCell].
*/
fun setKnownValues(knownValues: List<T>) {
beingLoaded = true
try {
val prevItemCount = itemsModel.size
val selectedItem = itemsModel.selectedItem
val existing = (0 until itemsModel.size).asSequence().map { itemsModel.getElementAt(it) }.toMutableSet()
knownValues.forEachIndexed { index, value ->
if (existing.contains(value)) {
while (itemsModel.size > index && itemsModel.getElementAt(index) != value) {
itemsModel.removeElementAt(index)
existing.remove(value)
}
}
if (itemsModel.size == index || itemsModel.getElementAt(index) != value) {
itemsModel.insertElementAt(value, index)
}
}
if (isPopupVisible && prevItemCount == 0) {
hidePopup()
showPopup()
}
if (itemsModel.selectedItem != selectedItem) {
itemsModel.selectedItem = selectedItem
}
updateWatermark()
}
finally {
beingLoaded = false
}
}
private val comboBoxEditor = object : BasicComboBoxEditor() {
override fun setItem(anObject: Any?) {
@Suppress("UNCHECKED_CAST")
editor.text = toEditorText(anObject as T?)
}
override fun getItem(): Any? = parseEditorText(editor.text.trim())
override fun createEditorComponent(): JTextField {
val field =
object : ExtendableTextField() {
init {
setExtensions(createEditorExtensions())
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (!currentStatusTriggerText.isNullOrEmpty() && !isFocusOwner) {
g.color = background
val rect = Rectangle(size)
val insets = insets
JBInsets.removeFrom(rect, insets)
JBInsets.removeFrom(rect, margin)
(g as Graphics2D).fill(rect)
g.setColor(foreground)
}
emptyText.component.font = font
setTextToTriggerEmptyTextStatus(currentStatusTriggerText)
emptyText.paint(this, g)
setTextToTriggerEmptyTextStatus("")
}
}
field.addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent) {
update(e)
}
override fun focusLost(e: FocusEvent) {
update(e)
}
private fun update(e: FocusEvent) {
val c = e.component.parent
if (c != null) {
c.revalidate()
c.repaint()
}
}
})
return field
}
override fun getEditorComponent(): JBTextField = super.getEditorComponent() as JBTextField
}
open fun createEditorExtensions(): List<Extension> = listOf()
private val comboBoxRenderer = object : ColoredListCellRenderer<T>() {
override fun customizeCellRenderer(list: JList<out T>,
value: T?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
toRenderer().renderCell(value)
}
}
init {
super.setModel(itemsModel)
setEditor(comboBoxEditor)
setRenderer(comboBoxRenderer)
}
}
internal fun StatusText.toRenderer() = object : TextRenderer {
override fun append(text: String, attributes: SimpleTextAttributes) {
this@toRenderer.appendText(text, attributes)
}
}
internal fun SimpleColoredComponent.toRenderer() = object : TextRenderer {
override fun append(text: String, attributes: SimpleTextAttributes) {
this@toRenderer.append(text, attributes)
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 7,400
|
android
|
Apache License 2.0
|
app/src/main/java/io/marlon/cleanarchitecture/data/converter/RepoRemoteConverter.kt
|
marloncarvalho
| 110,142,579
| false
| null |
package io.marlon.cleanarchitecture.data.converter
import io.marlon.cleanarchitecture.data.remote.api.services.repo.RepoResponse
import io.marlon.cleanarchitecture.domain.converter.Converter
import io.marlon.cleanarchitecture.domain.model.Repo
import javax.inject.Inject
class RepoRemoteConverter @Inject constructor(): Converter<RepoResponse, Repo> {
override fun convert(input: RepoResponse): Repo = Repo(input.id, input.name!!)
override fun convert(listInput: List<RepoResponse>): List<Repo> = listInput.map { convert(it) }
override fun revert(output: Repo): RepoResponse = RepoResponse(output.id, output.name)
override fun revert(listOutput: List<Repo>): List<RepoResponse> = listOutput.map { revert(it) }
}
| 0
|
Kotlin
|
0
| 0
|
613153498ffb28813652526a5a829ed64f71a1fa
| 729
|
android-clean-architecture
|
MIT License
|
src/main/kotlin/dev/emortal/lobby/commands/SpawnCommand.kt
|
EmortalMC
| 396,165,548
| false
| null |
package dev.emortal.lobby.commands
import dev.emortal.immortal.game.GameManager
import dev.emortal.immortal.game.GameManager.joinGameOrNew
import dev.emortal.lobby.LobbyExtension.Companion.SPAWN_POINT
import net.kyori.adventure.sound.Sound
import net.minestom.server.sound.SoundEvent
import world.cepi.kstom.command.kommand.Kommand
object SpawnCommand : Kommand({
onlyPlayers
default {
if (player.instance!!.getTag(GameManager.gameNameTag).contentEquals("lobby", true)) {
player.teleport(SPAWN_POINT)
} else {
player.joinGameOrNew("lobby")
}
player.playSound(Sound.sound(SoundEvent.ENTITY_ENDERMAN_TELEPORT, Sound.Source.MASTER, 1f, 1f), Sound.Emitter.self())
}
}, "spawn", "lobby", "hub", "l")
| 2
|
Kotlin
|
0
| 1
|
f1c50b4d916e25651b484169eee172f591ea210d
| 767
|
LobbyExtension
|
MIT License
|
app/src/main/java/com/example/iverify/devices/ui/theme/Dimens.kt
|
advaitsaravade
| 688,747,942
| false
|
{"Kotlin": 44547}
|
package com.example.iverify.devices.ui.theme
import androidx.compose.ui.unit.dp
val BoundsHalf = 8.dp
val Bounds1x = 16.dp
val Bounds2x = 32.dp
val RoundedCornerBound = 5.dp
| 0
|
Kotlin
|
0
| 0
|
16b2ba310c1b3d058e1f6cf8b28a2513f39c6895
| 176
|
Devices-Compose-Kotlin
|
Apache License 2.0
|
src/me/anno/engine/raycast/RaycastSkeletal.kt
|
AntonioNoack
| 456,513,348
| false
|
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
|
package me.anno.engine.raycast
import me.anno.ecs.components.mesh.Mesh
import me.anno.utils.Done
import me.anno.utils.types.Booleans.hasFlag
import me.anno.utils.types.Triangles
import org.joml.Matrix4x3d
import org.joml.Matrix4x3f
import org.joml.Vector3d
object RaycastSkeletal {
private class RaycastSkeletalHelper(query: RayQuery, mesh: Mesh, val matrices: List<Matrix4x3f>) {
val result = query.result
val tmpF = result.tmpVector3fs
val tmpD = result.tmpVector3ds
val positions = mesh.positions!!
val weights = mesh.boneWeights
val indices = mesh.boneIndices!!
fun transformByBones(i: Int, j: Int): Vector3d {
val tmp = tmpF[i]
val i4 = j * 4
if (weights == null) {
tmp.set(positions, j * 3)
// just use single index
val index = indices[i4].toInt().and(255)
if (index < matrices.size) {
val matrix = matrices[index]
matrix.transformPosition(tmp)
}
} else {
val tmp2 = tmpF[i + 1].set(positions, j * 3)
val tmp3 = tmpF[i + 2]
tmp.set(0f) // sum
var unitFactor = 1f
// interpolate using weights
for (k in 0 until 4) {
val index = indices[i4 + k].toInt().and(255)
val weight = weights[i4 + k]
if (weight != 0f && index < matrices.size) {
val matrix = matrices[index]
matrix.transformPosition(tmp2, tmp3) // tmp3 = matrix * tmp2
tmp3.mulAdd(weight, tmp, tmp) // tmp += tmp3 * weight
unitFactor -= weight
}
}
tmp2.mulAdd(unitFactor, tmp, tmp) // tmp += tmp2 * unitFactor
}
return tmpD[i + 2].set(tmp)
}
}
fun raycastGlobalBoneMeshClosestHit(
query: RayQuery, globalTransform: Matrix4x3d?, mesh: Mesh,
matrices: List<Matrix4x3f>
) {
val typeMask = query.typeMask
val acceptFront = typeMask.hasFlag(Raycast.TRIANGLE_FRONT)
val acceptBack = typeMask.hasFlag(Raycast.TRIANGLE_BACK)
if (!acceptFront && !acceptBack) return
mesh.positions ?: return
mesh.boneIndices ?: return
val helper = RaycastSkeletalHelper(query, mesh, matrices)
val result = query.result
val tmpD = result.tmpVector3ds
val tmpPos = tmpD[0]
val tmpNor = tmpD[1]
mesh.forEachTriangleIndex { ai, bi, ci ->
val distance = getDistance(ai, bi, ci, helper, globalTransform, query, result)
if (isHit(distance, query, result, acceptFront, acceptBack)) {
result.distance = distance
result.positionWS.set(tmpPos)
result.geometryNormalWS.set(tmpNor)
result.shadingNormalWS.set(tmpNor)
}
}
}
fun raycastGlobalBoneMeshAnyHit(
query: RayQuery,
globalTransform: Matrix4x3d?, mesh: Mesh,
matrices: List<Matrix4x3f>
): Boolean {
val typeMask = query.typeMask
val acceptFront = typeMask.hasFlag(Raycast.TRIANGLE_FRONT)
val acceptBack = typeMask.hasFlag(Raycast.TRIANGLE_BACK)
if (!acceptFront && !acceptBack) return false
mesh.positions ?: return false
mesh.boneIndices ?: return false
val result = query.result
val tmpD = result.tmpVector3ds
val helper = RaycastSkeletalHelper(query, mesh, matrices)
val tmpPos = tmpD[0]
val tmpNor = tmpD[1]
return try {
mesh.forEachTriangleIndex { ai, bi, ci ->
val distance = getDistance(ai, bi, ci, helper, globalTransform, query, result)
if (isHit(distance, query, result, acceptFront, acceptBack)) {
result.distance = distance
result.positionWS.set(tmpPos)
result.geometryNormalWS.set(tmpNor)
result.shadingNormalWS.set(tmpNor)
throw Done
}
}
false
} catch (ignored: Done) {
true
}
}
private fun isHit(
distance: Double, query: RayQuery, result: RayHit,
acceptFront: Boolean, acceptBack: Boolean
): Boolean {
val tmpD = result.tmpVector3ds
val tmpNor = tmpD[1]
return distance < result.distance && if (tmpNor.dot(query.direction) < 0f) acceptFront else acceptBack
}
private fun getDistance(
ai: Int, bi: Int, ci: Int,
helper: RaycastSkeletalHelper,
globalTransform: Matrix4x3d?,
query: RayQuery, result: RayHit,
): Double {
val a = helper.transformByBones(0, ai)
val b = helper.transformByBones(1, bi)
val c = helper.transformByBones(2, ci)
if (globalTransform != null) {
globalTransform.transformPosition(a)
globalTransform.transformPosition(b)
globalTransform.transformPosition(c)
}
val maxDistance = result.distance
val tmpD = result.tmpVector3ds
val tmpPos = tmpD[0]
val tmpNor = tmpD[1]
return Triangles.rayTriangleIntersection(
query.start, query.direction, a, b, c,
query.radiusAtOrigin, query.radiusPerUnit,
maxDistance, tmpPos, tmpNor
)
}
}
| 0
|
Kotlin
|
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 5,553
|
RemsEngine
|
Apache License 2.0
|
data/src/main/java/com/toadfrogson/forgetmenot/data/TaskDB.kt
|
wimpytoad
| 516,743,861
| false
| null |
package com.toadfrogson.forgetmenot.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.toadfrogson.forgetmenot.data.dao.TaskDao
import com.toadfrogson.forgetmenot.data.entity.SingleTaskEntity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.internal.synchronized
const val DATABASE_NAME = "tasks_db"
const val DATABASE_DATA_FILENAME = "tasks_db.json"
@Database(entities = [SingleTaskEntity::class], version = 2, exportSchema = true)
abstract class TaskDB : RoomDatabase() {
abstract fun taskDao() : TaskDao
companion object {
private var dbInstance: TaskDB? = null
@OptIn(InternalCoroutinesApi::class)
fun getDatabase(context: Context, scope: CoroutineScope): TaskDB {
return dbInstance ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
TaskDB::class.java,
DATABASE_NAME
).build()
dbInstance = instance
instance
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
49153ec730cb29e8a966e29d3d21bf3b9bf32720
| 1,208
|
Template
|
Apache License 2.0
|
jps-plugin/testData/general/KotlinJavaScriptProjectWithTestsAndTestAndSrcModuleDependency/tests/MainTests.kt
|
JakeWharton
| 99,388,807
| false
| null |
import src.*
import test.*
fun testMain() {
main()
srcAndTests()
testSrcAndTests()
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 98
|
kotlin
|
Apache License 2.0
|
plugins/completion-ml-ranking/src/com/intellij/completion/ml/features/MLRankingCompletionCollectorExtension.kt
|
JetBrains
| 2,489,216
| false
| null |
package com.intellij.completion.ml.features
import com.intellij.codeInsight.lookup.impl.LookupUsageTracker
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.FeatureUsageCollectorExtension
internal class MLRankingCompletionCollectorExtension : FeatureUsageCollectorExtension {
override fun getGroupId(): String {
return LookupUsageTracker.GROUP_ID
}
override fun getEventId(): String {
return LookupUsageTracker.FINISHED_EVENT_ID
}
override fun getExtensionFields(): List<EventField<*>> {
return listOf<EventField<*>>(totalMlTime, mlUsed, EventFields.Version)
}
companion object {
val totalMlTime = EventFields.Long("total_ml_time")
val mlUsed = EventFields.Boolean("ml_used")
}
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 868
|
intellij-community
|
Apache License 2.0
|
compose-lint-checks/src/test/java/slack/lint/compose/BaseSlackLintTest.kt
|
slackhq
| 593,729,034
| false
| null |
// Copyright (C) 2021 Slack Technologies, LLC
// SPDX-License-Identifier: Apache-2.0
package slack.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestLintClient
import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.checks.infrastructure.TestMode
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import com.android.utils.SdkUtils
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import java.net.MalformedURLException
import junit.framework.TestCase
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@Suppress("UnstableApiUsage")
@RunWith(JUnit4::class)
abstract class BaseSlackLintTest : LintDetectorTest() {
private val rootPath = "resources/test/com/slack/lint/data/"
private val stubsPath = "testStubs"
/** Optional override to customize the lint client name when running lint test tasks. */
open val lintClientName: String? = null
/**
* Lint periodically adds new "TestModes" to LintDetectorTest. These modes act as a sort of chaos
* testing mechanism, adding different common variations of code (extra spaces, extra parens, etc)
* to the test files to ensure that lints are robust against them. They also make it quite
* difficult to test against and need extra work sometimes to properly support, so we expose this
* property to allow tests to skip certain modes that need more work in subsequent PRs.
*/
open val skipTestModes: Array<TestMode>? = null
fun loadStub(stubName: String): TestFile {
return copy(stubsPath + File.separatorChar + stubName, "src/main/java/$stubName")
}
abstract override fun getDetector(): Detector
abstract override fun getIssues(): List<Issue>
override fun lint(): TestLintTask {
val sdkLocation = System.getProperty("android.sdk") ?: System.getenv("ANDROID_HOME")
val lintTask = super.lint()
lintClientName?.let { lintTask.clientFactory { TestLintClient(it) } }
sdkLocation?.let { lintTask.sdkHome(File(it)) }
lintTask.allowCompilationErrors(false)
skipTestModes?.let { testModesToSkip -> lintTask.skipTestModes(*testModesToSkip) }
return lintTask
}
/**
* The default finder for resources doesn't work with our file structure; this ensures it will.
*
* https://www.bignerdranch.com/blog/building-custom-lint-checks-in-android/
*/
override fun getTestResource(relativePath: String, expectExists: Boolean): InputStream {
val path = (rootPath + relativePath).replace('/', File.separatorChar)
val file = File(getTestDataRootDir(), path)
if (file.exists()) {
try {
return BufferedInputStream(FileInputStream(file))
} catch (e: FileNotFoundException) {
if (expectExists) {
TestCase.fail("Could not find file $relativePath")
}
}
}
return BufferedInputStream(ByteArrayInputStream("".toByteArray()))
}
private fun getTestDataRootDir(): File? {
val source = javaClass.protectionDomain.codeSource
if (source != null) {
val location = source.location
try {
val classesDir = SdkUtils.urlToFile(location)
return classesDir.parentFile!!.absoluteFile.parentFile!!.parentFile
} catch (e: MalformedURLException) {
fail(e.localizedMessage)
}
}
return null
}
}
| 20
| null |
8
| 311
|
97c7410b99ebac92a4af5199d60ed9396013115f
| 3,603
|
compose-lints
|
Apache License 2.0
|
protoc-gen-kotlin-ext/src/test/kotlin/dev/hsbrysk/protoc/gen/CompileOptionTest.kt
|
be-hase
| 802,058,732
| false
|
{"Kotlin": 46488}
|
package dev.hsbrysk.protoc.gen
import assertk.assertFailure
import assertk.assertThat
import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import com.google.protobuf.compiler.PluginProtos
import dev.hsbrysk.protoc.gen.CompileOption.FACTORY
import dev.hsbrysk.protoc.gen.CompileOption.MESSAGE_OR_NULL_GETTER
import dev.hsbrysk.protoc.gen.CompileOption.OR_NULL_GETTER
import org.junit.jupiter.api.Test
class CompileOptionTest {
@Test
fun parseOptions() {
// The default is `FACTORY, SCALAR_OR_NULL_GETTER`.
assertThat(
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("")
.build(),
),
).isEqualTo(setOf(FACTORY, OR_NULL_GETTER))
// It's okay to specify explicitly (though it's meaningless).
assertThat(
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("factory+, orNullGetter+")
.build(),
),
).isEqualTo(setOf(FACTORY, OR_NULL_GETTER))
// Enable all.
assertThat(
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("messageOrNullGetter+")
.build(),
),
).isEqualTo(setOf(FACTORY, OR_NULL_GETTER, MESSAGE_OR_NULL_GETTER))
// Disable all.
assertThat(
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("factory-, orNullGetter-")
.build(),
),
).isEqualTo(setOf())
}
@Test
fun `parseOptions error`() {
assertFailure {
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("invalid")
.build(),
)
}.isInstanceOf(IllegalArgumentException::class).hasMessage("option name must be followed by + or -")
assertFailure {
CompileOption.parseOptions(
PluginProtos.CodeGeneratorRequest.newBuilder()
.setParameter("invalid+")
.build(),
)
}.isInstanceOf(IllegalArgumentException::class).hasMessage("invalid option name")
}
}
| 4
|
Kotlin
|
1
| 8
|
91558c84b252e52a847c93d09d0ed191e1404115
| 2,492
|
protoc-gen-kotlin-ext
|
MIT License
|
app/src/main/java/de/msdevs/einschlafhilfe/AppIntroActivity.kt
|
DonMarv00
| 171,038,644
| false
| null |
package de.msdevs.einschlafhilfe
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.fragment.app.Fragment
import com.github.appintro.AppIntro
import com.github.appintro.AppIntroCustomLayoutFragment
import com.github.appintro.AppIntroFragment
import de.msdevs.einschlafhilfe.fragments.PrivacyFragment
import de.msdevs.einschlafhilfe.fragments.SettingsFragment
class AppIntroActivity : AppIntro() {
lateinit var sharedPreferences: SharedPreferences
lateinit var sharedPreferencesEditor: SharedPreferences.Editor
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
isSkipButtonEnabled = false
setIndicatorColor(
selectedIndicatorColor = getColor(R.color.white),
unselectedIndicatorColor = getColor(R.color.whiteSecondary)
)
addSlide(AppIntroFragment.createInstance(
title = resources.getString(R.string.welcome),
backgroundColorRes = R.color.black,
imageDrawable = R.drawable.ic_covers,
description = resources.getString(R.string.welcome_text)
))
addSlide(SettingsFragment.newInstance())
addSlide(PrivacyFragment())
}
override fun onSkipPressed(currentFragment: Fragment?) {
super.onSkipPressed(currentFragment)
// Decide what to do when the user clicks on "Skip"
finish()
}
override fun onDonePressed(currentFragment: Fragment?) {
super.onDonePressed(currentFragment)
sharedPreferences = getSharedPreferences(packageName,0)
sharedPreferencesEditor = sharedPreferences.edit()
sharedPreferencesEditor.putInt("first",1)
sharedPreferencesEditor.apply()
finish()
}
}
| 1
| null |
2
| 4
|
47e6f2766873d243150169b3fdc87e754281d552
| 1,845
|
DieDreiFragezeichenEinschlafhilfe
|
MIT License
|
android/app/src/main/java/ar/edu/utn/frba/foody/ui/navigation/AppScreens.kt
|
UTN-FRBA-Mobile
| 795,060,308
| false
|
{"Kotlin": 15095}
|
package ar.edu.utn.frba.foody.ui.navigation
sealed class AppScreens(val route: String) {
object Home_Screen: AppScreens("HomeScreen")
object Login_Screen: AppScreens("Login")
}
| 0
|
Kotlin
|
0
| 2
|
2991ef76f3e78d4bb242430505370e0394d7a662
| 185
|
Foody
|
MIT License
|
sdds-core/uikit/src/main/kotlin/com/sdds/uikit/RadioBox.kt
|
salute-developers
| 765,665,583
| false
|
{"Kotlin": 1286830}
|
package com.sdds.uikit
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.StyleRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatRadioButton
import com.sdds.uikit.internal.CheckableDelegate
import com.sdds.uikit.internal.RadioBoxDrawable
/**
* Компонент RadioBox
* @param context контекст
* @param attrs аттрибуты view
* @param defStyleAttr аттрибут стиля по умолчанию
* @author <NAME> on 03.06.2024
*/
open class RadioBox @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.radioButtonStyle,
) : AppCompatRadioButton(context, attrs, defStyleAttr) {
@Suppress("LeakingThis")
private val _checkableDelegate: CheckableDelegate = CheckableDelegate(this, attrs, defStyleAttr)
private var _buttonDrawable: RadioBoxDrawable? = null
private var _offsetY = 0f
init {
background = null
buttonDrawable = RadioBoxDrawable(context, attrs, defStyleAttr).apply {
isInEditMode = this@RadioBox.isInEditMode
}
obtainAttributes(attrs, defStyleAttr)
}
/**
* Текст-описание
*/
open var description: CharSequence?
get() = _checkableDelegate.description
set(value) { _checkableDelegate.description = value }
/**
* Устанавливает стиль дополнительного текста по идентификатору стиля в ресурсах
* @param textAppearanceId идентификатор стиля текста в ресурсах
*/
open fun setDescriptionTextAppearance(@StyleRes textAppearanceId: Int) {
_checkableDelegate.setDescriptionTextAppearance(textAppearanceId)
}
/**
* Устанавливает цвета дополнительного текста
* @param colors [ColorStateList] цвета дополнительного текста
*/
open fun setDescriptionTextColors(colors: ColorStateList?) {
_checkableDelegate.setDescriptionTextColors(colors)
}
/**
* Устанавливает цвет дополнительного текста
* @param color цвет дополнительного текста
*/
fun setDescriptionTextColor(@ColorInt color: Int) {
setDescriptionTextColors(ColorStateList.valueOf(color))
}
/**
* Устанавливает цвет дополнительного текста по идентификатору
* @param colorRes идентификатор цвета в ресурсах
*/
fun setDescriptionTextColorResource(@ColorRes colorRes: Int) {
setDescriptionTextColors(AppCompatResources.getColorStateList(context, colorRes))
}
/**
* Устанавливает цвета для [getButtonDrawable].
* @param borderColors цвета границы
* @param boxColors цвета заливки
* @param boxColors цвета маркера
*/
open fun setRadioBoxColors(
borderColors: ColorStateList?,
boxColors: ColorStateList?,
checkMarkColors: ColorStateList?,
): Unit = _buttonDrawable?.run {
setBorderTintList(borderColors)
setBoxTintList(boxColors)
setCheckMarkTintList(checkMarkColors)
this.invalidateSelf()
} ?: Unit
override fun toggle() {
isChecked = !isChecked
}
final override fun setButtonIcon(icon: Icon?) {
super.setButtonIcon(null)
// buttonDrawable может быть только RadioBoxDrawable или null
}
final override fun setButtonDrawable(buttonDrawable: Drawable?) {
super.setButtonDrawable(null)
// buttonDrawable может быть только RadioBoxDrawable или null
_buttonDrawable = buttonDrawable as? RadioBoxDrawable
setCompoundDrawablesRelativeWithIntrinsicBounds(buttonDrawable, null, null, null)
}
override fun getButtonDrawable(): Drawable? = _buttonDrawable
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val newWidth = _checkableDelegate.measureWidth(widthMeasureSpec)
val newHeight = _checkableDelegate.measureHeight(heightMeasureSpec)
if (newWidth != measuredWidth || newHeight != measuredHeight) {
_offsetY = (measuredHeight - newHeight) / 2f
setMeasuredDimension(newWidth, newHeight)
} else {
_offsetY = 0f
}
}
override fun onDraw(canvas: Canvas) {
with(canvas) {
save()
translate(0f, _offsetY)
super.onDraw(canvas)
restore()
}
_checkableDelegate.drawDescription(canvas)
}
private fun obtainAttributes(attrs: AttributeSet?, defStyleAttr: Int) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RadioBox, defStyleAttr, 0)
setRadioBoxColors(
borderColors = typedArray.getColorStateList(R.styleable.RadioBox_sd_buttonBorderColor),
boxColors = typedArray.getColorStateList(R.styleable.RadioBox_sd_buttonBoxColor),
checkMarkColors = typedArray.getColorStateList(R.styleable.RadioBox_sd_buttonMarkColor),
)
typedArray.recycle()
}
}
| 4
|
Kotlin
|
0
| 1
|
fe241f7fbaef5b6d65bdc20dc9eb857dbc31744c
| 5,210
|
plasma-android
|
MIT License
|
lib/src/main/kotlin/com/swmansion/starknet/data/types/Uint256.kt
|
software-mansion
| 503,730,882
| false
| null |
package com.swmansion.starknet.data.types
import com.swmansion.starknet.data.parseHex
import com.swmansion.starknet.data.types.conversions.ConvertibleToCalldata
import com.swmansion.starknet.extensions.toHex
import java.math.BigInteger
private const val SHIFT = 128
private val SHIFT_MOD: BigInteger = BigInteger.valueOf(2).pow(128)
data class Uint256(override val value: BigInteger) : NumAsHexBase(value), ConvertibleToCalldata {
constructor(value: Long) : this(BigInteger.valueOf(value))
constructor(value: Int) : this(BigInteger.valueOf(value.toLong()))
constructor(value: Felt) : this(value.value)
constructor(low: BigInteger, high: BigInteger) : this(low.add(high.shiftLeft(SHIFT)))
constructor(low: Felt, high: Felt) : this(low.value, high.value)
init {
if (value < BigInteger.ZERO) {
throw IllegalArgumentException("Default Uint256 constructor does not accept negative numbers, [$value] given.")
}
if (value > MAX) {
throw IllegalArgumentException("Default Uint256 constructor does not accept numbers higher than 2^256-1, [$value] given.")
}
}
/**
* Get low 128 bits of Uint256
*/
@Suppress("MemberVisibilityCanBePrivate")
val low: Felt
get() = Felt(value.mod(SHIFT_MOD))
/**
* Get high 128 bits of Uint256
*/
@Suppress("MemberVisibilityCanBePrivate")
val high: Felt
get() = Felt(value.shiftRight(SHIFT))
override fun toCalldata() = listOf(low, high)
override fun toString() = "Uint256($value)"
override fun hexString() = value.toHex()
override fun decString(): String = value.toString(10)
companion object {
@field:JvmField
val MAX = BigInteger.valueOf(2).pow(256).minus(BigInteger.ONE)
@field:JvmField
val ZERO = Uint256(BigInteger.ZERO)
@field:JvmField
val ONE = Uint256(BigInteger.ONE)
@JvmStatic
fun fromHex(value: String) = Uint256(parseHex(value))
}
}
| 7
| null |
16
| 64
|
4e97d5a9e1c524902208a04c0bc1f1be5a92f193
| 2,012
|
starknet-jvm
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/components/search/Search.kt
|
kwmt
| 346,881,422
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.components.search
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Search
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.ui.theme.DevChallengeScaffold
import com.example.androiddevchallenge.ui.theme.DevChallengeTheme
@Composable
fun Search(modifier: Modifier) {
SearchBar(modifier = modifier)
}
@Composable
fun SearchBar(modifier: Modifier = Modifier) {
SearchTextField(
modifier = modifier,
placeHolder = { SearchHint() }
)
}
@Composable
fun SearchHint() {
Row(
modifier = Modifier.fillMaxWidth()
) {
Icon(
modifier = Modifier.size(18.dp),
imageVector = Icons.Outlined.Search,
contentDescription = null,
tint = DevChallengeTheme.colors.textBody1,
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Search",
style = DevChallengeTheme.typography.body1,
color = DevChallengeTheme.colors.textBody1
)
}
}
@Composable
fun SearchTextField(
modifier: Modifier = Modifier,
placeHolder: @Composable () -> Unit
) {
OutlinedTextField(
modifier = modifier
.height(56.dp)
.fillMaxWidth(),
value = "", onValueChange = { /*TODO*/ },
placeholder = placeHolder,
colors = TextFieldDefaults.outlinedTextFieldColors(
cursorColor = DevChallengeTheme.colors.textBody1,
focusedBorderColor = DevChallengeTheme.colors.textBody1.copy(alpha = ContentAlpha.high),
unfocusedBorderColor = DevChallengeTheme.colors.textBody1,
),
singleLine = true,
)
}
@Composable
@Preview
fun PreviewSearch() {
DevChallengeScaffold {
Search(Modifier.padding(horizontal = 16.dp))
}
}
@Composable
@Preview
fun DarkPreviewSearch() {
DevChallengeScaffold(darkTheme = true) {
Search(Modifier.padding(horizontal = 16.dp))
}
}
| 1
|
Kotlin
|
0
| 0
|
6b9f9fbfc040654babe870481e27fde321e45042
| 3,341
|
android-dev-challenge-compose-week3
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnDataSetIngestionWaitPolicyPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.quicksight
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnDataSet
/**
* The wait policy to use when creating or updating a Dataset.
*
* The default is to wait for SPICE ingestion to finish with timeout of 36 hours.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* IngestionWaitPolicyProperty ingestionWaitPolicyProperty = IngestionWaitPolicyProperty.builder()
* .ingestionWaitTimeInHours(123)
* .waitForSpiceIngestion(false)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dataset-ingestionwaitpolicy.html)
*/
@CdkDslMarker
public class CfnDataSetIngestionWaitPolicyPropertyDsl {
private val cdkBuilder: CfnDataSet.IngestionWaitPolicyProperty.Builder =
CfnDataSet.IngestionWaitPolicyProperty.builder()
/**
* @param ingestionWaitTimeInHours The maximum time (in hours) to wait for Ingestion to
* complete. Default timeout is 36 hours. Applicable only when `DataSetImportMode` mode is set
* to SPICE and `WaitForSpiceIngestion` is set to true.
*/
public fun ingestionWaitTimeInHours(ingestionWaitTimeInHours: Number) {
cdkBuilder.ingestionWaitTimeInHours(ingestionWaitTimeInHours)
}
/**
* @param waitForSpiceIngestion Wait for SPICE ingestion to finish to mark dataset creation or
* update as successful. Default (true). Applicable only when `DataSetImportMode` mode is set
* to SPICE.
*/
public fun waitForSpiceIngestion(waitForSpiceIngestion: Boolean) {
cdkBuilder.waitForSpiceIngestion(waitForSpiceIngestion)
}
/**
* @param waitForSpiceIngestion Wait for SPICE ingestion to finish to mark dataset creation or
* update as successful. Default (true). Applicable only when `DataSetImportMode` mode is set
* to SPICE.
*/
public fun waitForSpiceIngestion(waitForSpiceIngestion: IResolvable) {
cdkBuilder.waitForSpiceIngestion(waitForSpiceIngestion)
}
public fun build(): CfnDataSet.IngestionWaitPolicyProperty = cdkBuilder.build()
}
| 3
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 2,634
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/top/niunaijun/blackboxa/WelcomeActivity.kt
|
NepMods
| 821,652,736
| false
|
{"C++": 2222377, "Java": 1496924, "C": 111417, "AIDL": 37520, "Kotlin": 8265, "Assembly": 7189, "CMake": 4330, "Makefile": 1571}
|
package top.niunaijun.blackboxa
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import com.android.support.Main
import top.niunaijun.blackbox.BlackBoxCore
class WelcomeActivity : Activity() {
var package_name = "com.mobirix.zombiefire";
var user_id = 0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && !android.provider.Settings.canDrawOverlays(this))
{
Toast.makeText(
this.getApplicationContext(),
"Overlay permission is required in order to show mod menu. Restart the game after you allow permission",
Toast.LENGTH_LONG
).show()
Toast.makeText(
this.getApplicationContext(),
"Overlay permission is required in order to show mod menu. Restart the game after you allow permission",
Toast.LENGTH_LONG
).show()
this.startActivity(
Intent(
"android.settings.action.MANAGE_OVERLAY_PERMISSION",
Uri.parse("package:" + this.getPackageName())
)
)
val handler = Handler()
handler.postDelayed({ System.exit(1) }, 5000)
return
}
jump()
}
private fun jump() {
var hasApp = BlackBoxCore.get().isInstalled(package_name, user_id);
if(!hasApp) {
BlackBoxCore.get().installPackageAsUser(package_name, user_id);
}
BlackBoxCore.get().launchApk(package_name, user_id);
Main.Start(this);
}
}
| 1
|
C++
|
15
| 41
|
6784f517d256de0c179964da08bcf526c4ef4bf8
| 1,798
|
InjectARM64
|
MIT License
|
app/src/androidTest/java/me/hufman/androidautoidrive/InstrumentedTestNotificationEmoji.kt
|
BimmerGestalt
| 164,273,785
| false
| null |
package me.hufman.androidautoidrive
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class TestNotificationEmoji {
@Before
fun setup() {
UnicodeCleaner._addPlaceholderEmoji("\uD83D\uDC08", listOf("cat2"), "cat")
UnicodeCleaner._addPlaceholderEmoji("\uD83D\uDE3B", listOf("heart_eyes_cat"), "heart_eyes_cat")
}
/** Verifies that foreign letters don't get emoji parsed */
@Test
fun testEmojiForeign() {
run {
// danish
val correct = "\u00C6\u00D8\u00C5"
val parsed = UnicodeCleaner.clean(correct)
assertEquals(correct, parsed)
}
run {
// kanji
val correct = "\u732B"
val parsed = UnicodeCleaner.clean(correct)
assertEquals(correct, parsed)
}
}
/** Verifies that emoji get parsed */
@Test
fun testEmojiParse() {
run {
val correct = "I :cat2:!"
val source = "I \ud83d\udc08!"
assertEquals(correct, UnicodeCleaner.clean(source))
}
run {
val correct = "I :heart_eyes_cat:!"
val source = "I \ud83d\ude3b!"
assertEquals(correct, UnicodeCleaner.clean(source))
}
}
}
| 49
| null |
90
| 546
|
ea49ba17a18c353a8ba55f5040e8e4321bf14bd7
| 1,057
|
AAIdrive
|
MIT License
|
controls-core/src/commonMain/kotlin/ru/mipt/npm/controls/api/Device.kt
|
mipt-npm
| 240,888,288
| false
| null |
package space.kscience.controls.api
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import space.kscience.controls.api.Device.Companion.DEVICE_TARGET
import space.kscience.dataforge.context.ContextAware
import space.kscience.dataforge.context.info
import space.kscience.dataforge.context.logger
import space.kscience.dataforge.meta.Meta
import space.kscience.dataforge.misc.DFExperimental
import space.kscience.dataforge.misc.Type
import space.kscience.dataforge.names.Name
/**
* A lifecycle state of a device
*/
public enum class DeviceLifecycleState{
INIT,
OPEN,
CLOSED
}
/**
* General interface describing a managed Device.
* [Device] is a supervisor scope encompassing all operations on a device.
* When canceled, cancels all running processes.
*/
@Type(DEVICE_TARGET)
public interface Device : AutoCloseable, ContextAware, CoroutineScope {
/**
* Initial configuration meta for the device
*/
public val meta: Meta get() = Meta.EMPTY
/**
* List of supported property descriptors
*/
public val propertyDescriptors: Collection<PropertyDescriptor>
/**
* List of supported action descriptors. Action is a request to the device that
* may or may not change the properties
*/
public val actionDescriptors: Collection<ActionDescriptor>
/**
* Read the physical state of property and update/push notifications if needed.
*/
public suspend fun readProperty(propertyName: String): Meta
/**
* Get the logical state of property or return null if it is invalid
*/
public fun getProperty(propertyName: String): Meta?
/**
* Invalidate property (set logical state to invalid)
*
* This message is suspended to provide lock-free local property changes (they require coroutine context).
*/
public suspend fun invalidate(propertyName: String)
/**
* Set property [value] for a property with name [propertyName].
* In rare cases could suspend if the [Device] supports command queue, and it is full at the moment.
*/
public suspend fun writeProperty(propertyName: String, value: Meta)
/**
* A subscription-based [Flow] of [DeviceMessage] provided by device. The flow is guaranteed to be readable
* multiple times.
*/
public val messageFlow: Flow<DeviceMessage>
/**
* Send an action request and suspend caller while request is being processed.
* Could return null if request does not return a meaningful answer.
*/
public suspend fun execute(actionName: String, argument: Meta? = null): Meta?
/**
* Initialize the device. This function suspends until the device is finished initialization
*/
public suspend fun open(): Unit = Unit
/**
* Close and terminate the device. This function does not wait for the device to be closed.
*/
override fun close() {
logger.info { "Device $this is closed" }
cancel("The device is closed")
}
@DFExperimental
public val lifecycleState: DeviceLifecycleState
public companion object {
public const val DEVICE_TARGET: String = "device"
}
}
/**
* Get the logical state of property or suspend to read the physical value.
*/
public suspend fun Device.getOrReadProperty(propertyName: String): Meta =
getProperty(propertyName) ?: readProperty(propertyName)
/**
* Get a snapshot of the device logical state
*
*/
public fun Device.getAllProperties(): Meta = Meta {
for (descriptor in propertyDescriptors) {
setMeta(Name.parse(descriptor.name), getProperty(descriptor.name))
}
}
/**
* Subscribe on property changes for the whole device
*/
public fun Device.onPropertyChange(callback: suspend PropertyChangedMessage.() -> Unit): Job =
messageFlow.filterIsInstance<PropertyChangedMessage>().onEach(callback).launchIn(this)
| 5
|
Kotlin
|
3
| 9
|
a20fb97c02f6394fe49436f97373991bed2f8f6f
| 4,082
|
controls.kt
|
Apache License 2.0
|
controls-core/src/commonMain/kotlin/ru/mipt/npm/controls/api/Device.kt
|
mipt-npm
| 240,888,288
| false
| null |
package space.kscience.controls.api
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import space.kscience.controls.api.Device.Companion.DEVICE_TARGET
import space.kscience.dataforge.context.ContextAware
import space.kscience.dataforge.context.info
import space.kscience.dataforge.context.logger
import space.kscience.dataforge.meta.Meta
import space.kscience.dataforge.misc.DFExperimental
import space.kscience.dataforge.misc.Type
import space.kscience.dataforge.names.Name
/**
* A lifecycle state of a device
*/
public enum class DeviceLifecycleState{
INIT,
OPEN,
CLOSED
}
/**
* General interface describing a managed Device.
* [Device] is a supervisor scope encompassing all operations on a device.
* When canceled, cancels all running processes.
*/
@Type(DEVICE_TARGET)
public interface Device : AutoCloseable, ContextAware, CoroutineScope {
/**
* Initial configuration meta for the device
*/
public val meta: Meta get() = Meta.EMPTY
/**
* List of supported property descriptors
*/
public val propertyDescriptors: Collection<PropertyDescriptor>
/**
* List of supported action descriptors. Action is a request to the device that
* may or may not change the properties
*/
public val actionDescriptors: Collection<ActionDescriptor>
/**
* Read the physical state of property and update/push notifications if needed.
*/
public suspend fun readProperty(propertyName: String): Meta
/**
* Get the logical state of property or return null if it is invalid
*/
public fun getProperty(propertyName: String): Meta?
/**
* Invalidate property (set logical state to invalid)
*
* This message is suspended to provide lock-free local property changes (they require coroutine context).
*/
public suspend fun invalidate(propertyName: String)
/**
* Set property [value] for a property with name [propertyName].
* In rare cases could suspend if the [Device] supports command queue, and it is full at the moment.
*/
public suspend fun writeProperty(propertyName: String, value: Meta)
/**
* A subscription-based [Flow] of [DeviceMessage] provided by device. The flow is guaranteed to be readable
* multiple times.
*/
public val messageFlow: Flow<DeviceMessage>
/**
* Send an action request and suspend caller while request is being processed.
* Could return null if request does not return a meaningful answer.
*/
public suspend fun execute(actionName: String, argument: Meta? = null): Meta?
/**
* Initialize the device. This function suspends until the device is finished initialization
*/
public suspend fun open(): Unit = Unit
/**
* Close and terminate the device. This function does not wait for the device to be closed.
*/
override fun close() {
logger.info { "Device $this is closed" }
cancel("The device is closed")
}
@DFExperimental
public val lifecycleState: DeviceLifecycleState
public companion object {
public const val DEVICE_TARGET: String = "device"
}
}
/**
* Get the logical state of property or suspend to read the physical value.
*/
public suspend fun Device.getOrReadProperty(propertyName: String): Meta =
getProperty(propertyName) ?: readProperty(propertyName)
/**
* Get a snapshot of the device logical state
*
*/
public fun Device.getAllProperties(): Meta = Meta {
for (descriptor in propertyDescriptors) {
setMeta(Name.parse(descriptor.name), getProperty(descriptor.name))
}
}
/**
* Subscribe on property changes for the whole device
*/
public fun Device.onPropertyChange(callback: suspend PropertyChangedMessage.() -> Unit): Job =
messageFlow.filterIsInstance<PropertyChangedMessage>().onEach(callback).launchIn(this)
| 5
|
Kotlin
|
3
| 9
|
a20fb97c02f6394fe49436f97373991bed2f8f6f
| 4,082
|
controls.kt
|
Apache License 2.0
|
sentry-kotlin-multiplatform/src/commonMain/kotlin/io/sentry/kotlin/multiplatform/SentryKMP.kt
|
getsentry
| 285,502,515
| false
| null |
package io.sentry.kotlin.multiplatform
import io.sentry.kotlin.multiplatform.protocol.SentryId
import io.sentry.kotlin.multiplatform.protocol.UserFeedback
typealias ScopeCallback = (Scope) -> Unit
typealias OptionsConfiguration = (SentryOptions) -> Unit
expect abstract class Context
/** Sentry Kotlin Multiplatform SDK API entry point */
object Sentry {
/**
* Sentry initialization with an option configuration handler.
*
* @param context: The context (used for retrieving Android Context)
* @param configuration Options configuration handler.
*/
fun init(context: Context, configuration: OptionsConfiguration) {
SentryBridge.init(context, configuration)
}
/**
* Sentry initialization with an option configuration handler.
* This is a convenience init for direct initialization on Apple platforms.
*
* @param configuration Options configuration handler.
*/
fun init(configuration: OptionsConfiguration) {
SentryBridge.init(configuration = configuration)
}
/**
* Captures the message.
*
* @param message The message to send.
*/
fun captureMessage(message: String): SentryId {
return SentryBridge.captureMessage(message)
}
/**
* Captures the exception.
*
* @param message The message to send.
* @param scopeCallback The local scope callback.
*/
fun captureMessage(message: String, scopeCallback: ScopeCallback): SentryId {
return SentryBridge.captureMessage(message, scopeCallback)
}
/**
* Captures the exception.
*
* @param throwable The exception.
*/
fun captureException(throwable: Throwable): SentryId {
return SentryBridge.captureException(throwable)
}
/**
* Captures the exception.
*
* @param throwable The exception.
* @param scopeCallback The local scope callback.
*/
fun captureException(throwable: Throwable, scopeCallback: ScopeCallback): SentryId {
return SentryBridge.captureException(throwable, scopeCallback)
}
/**
* Captures a manually created user feedback and sends it to Sentry.
*
* @param userFeedback The user feedback to send to Sentry.
*/
fun captureUserFeedback(userFeedback: UserFeedback) {
return SentryBridge.captureUserFeedback(userFeedback)
}
/**
* Configures the scope through the callback.
*
* @param scopeCallback The configure scope callback.
*/
fun configureScope(scopeCallback: ScopeCallback) {
SentryBridge.configureScope(scopeCallback)
}
/**
* Throws a RuntimeException, useful for testing.
*/
fun crash() {
throw RuntimeException("Uncaught Exception from Kotlin Multiplatform.")
}
/**
* Closes the SDK.
*/
fun close() {
SentryBridge.close()
}
}
| 7
|
Kotlin
|
9
| 32
|
2842bc3af8cb39b723601aef63a05e042ffcac25
| 2,896
|
sentry-kotlin-multiplatform
|
MIT License
|
app/src/main/java/com/kylecorry/trail_sense/tools/augmented_reality/domain/position/SphericalARPoint.kt
|
kylecorry31
| 215,154,276
| false
|
{"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553}
|
package com.kylecorry.trail_sense.tools.augmented_reality.domain.position
import com.kylecorry.trail_sense.shared.camera.AugmentedRealityUtils
import com.kylecorry.trail_sense.tools.augmented_reality.ui.AugmentedRealityView
/**
* A point in spherical coordinates
* @param bearing The bearing in degrees
* @param elevationAngle The elevation angle in degrees
* @param distance The distance in meters, defaults to MAX_VALUE
* @param angularDiameter The angular diameter in degrees, defaults to 1
* @param isTrueNorth True if the bearing is true north, false if it is magnetic north
*/
class SphericalARPoint(
bearing: Float,
elevationAngle: Float,
distance: Float = Float.MAX_VALUE,
private val angularDiameter: Float = 1f,
isTrueNorth: Boolean = true
) : ARPoint {
val coordinate = AugmentedRealityCoordinate(
AugmentedRealityUtils.toEastNorthUp(
bearing,
elevationAngle,
distance
), isTrueNorth
)
override fun getAngularDiameter(view: AugmentedRealityView): Float {
return angularDiameter
}
override fun getAugmentedRealityCoordinate(view: AugmentedRealityView): AugmentedRealityCoordinate {
return coordinate
}
}
| 456
|
Kotlin
|
66
| 989
|
41176d17b498b2dcecbbe808fbe2ac638e90d104
| 1,236
|
Trail-Sense
|
MIT License
|
app/src/main/java/com/flixclusive/data/config/ConfigurationProviderImpl.kt
|
rhenwinch
| 659,237,375
| false
|
{"Kotlin": 1156049}
|
package com.flixclusive.data.config
import com.flixclusive.common.LoggerUtils.errorLog
import com.flixclusive.data.api.GithubConfigService
import com.flixclusive.data.utils.catchInternetRelatedException
import com.flixclusive.domain.config.ConfigurationProvider
import com.flixclusive.domain.config.RemoteConfigStatus
import com.flixclusive.domain.model.config.AppConfig
import com.flixclusive.domain.model.config.HomeCategoriesConfig
import com.flixclusive.domain.model.config.ProviderStatus
import com.flixclusive.domain.model.config.SearchCategoriesConfig
import com.flixclusive.domain.preferences.AppSettingsManager
import com.flixclusive.domain.preferences.ProviderConfiguration
import com.flixclusive.domain.repository.ProvidersRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
private const val MAX_RETRIES = 5
class ConfigurationProviderImpl @Inject constructor(
private val githubConfigService: GithubConfigService,
private val providersRepository: ProvidersRepository,
private val appSettingsManager: AppSettingsManager,
private val ioScope: CoroutineScope
): ConfigurationProvider {
private val _remoteStatus = MutableStateFlow<RemoteConfigStatus>(RemoteConfigStatus.Loading)
override val remoteStatus: StateFlow<RemoteConfigStatus>
get() = _remoteStatus.asStateFlow()
override var homeCategoriesConfig: HomeCategoriesConfig? = null
override var searchCategoriesConfig: SearchCategoriesConfig? = null
override var appConfig: AppConfig? = null
override var providersStatus: List<ProviderStatus>? = null
override fun initialize() {
ioScope.launch {
for(i in 0..MAX_RETRIES) {
_remoteStatus.update { RemoteConfigStatus.Loading }
try {
appConfig = githubConfigService.getAppConfig()
providersStatus = githubConfigService.getProvidersStatus()
initializeProviders()
homeCategoriesConfig = githubConfigService.getHomeCategoriesConfig()
searchCategoriesConfig = githubConfigService.getSearchCategoriesConfig()
_remoteStatus.update { RemoteConfigStatus.Success }
break
} catch (e: Exception) {
errorLog(e.stackTraceToString())
val errorMessageId = e.catchInternetRelatedException().error!!
_remoteStatus.update { RemoteConfigStatus.Error(errorMessageId) }
}
}
}
}
private suspend fun initializeProviders() {
val appSettings = appSettingsManager.localAppSettings
val providersConfigurations = appSettings.providers.toMutableList()
val isConfigEmpty = providersConfigurations.isEmpty()
if(providersRepository.providers.size == providersStatus!!.size)
return
for (i in providersStatus!!.indices) {
val provider = if(!isConfigEmpty) {
providersStatus!!.find {
it.name.equals(
other = providersConfigurations[i].name,
ignoreCase = true
)
}
} else providersStatus!![i]
val isIgnored = if(isConfigEmpty)
false
else providersConfigurations[i].isIgnored
providersRepository.populate(
name = provider!!.name,
isMaintenance = provider.isMaintenance,
isIgnored = isIgnored
)
if(isConfigEmpty) {
providersConfigurations.add(
ProviderConfiguration(name = provider.name)
)
appSettingsManager.updateData(
appSettings.copy(
providers = providersConfigurations.toList()
)
)
}
}
}
}
| 21
|
Kotlin
|
7
| 96
|
a90215b8c40ac0675cd217b38b842d2d57c90acc
| 4,171
|
Flixclusive
|
MIT License
|
Android/App_YanZiJi/App/src/main/java/com/zktony/android/ui/Settings.kt
|
OriginalLight
| 556,213,614
| false
|
{"Kotlin": 6123849, "C#": 376657, "Vue": 164353, "Rust": 101266, "C++": 63250, "TypeScript": 62359, "Python": 28781, "CMake": 18271, "C": 16214, "Less": 2885, "Dockerfile": 1898, "HTML": 648, "JavaScript": 450}
|
package com.zktony.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForwardIos
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.zktony.android.BuildConfig
import com.zktony.android.R
import com.zktony.android.data.Role
import com.zktony.android.data.Sound
import com.zktony.android.ui.components.DateTimePicker
import com.zktony.android.ui.components.PasswordModifyDialog
import com.zktony.android.ui.components.SegmentedButtonTabRow
import com.zktony.android.ui.navigation.Route
import com.zktony.android.ui.utils.LocalNavigationActions
import com.zktony.android.ui.utils.RequirePermission
import com.zktony.android.ui.viewmodel.SettingsViewModel
import com.zktony.android.utils.AuthUtils
import com.zktony.android.utils.Constants
import com.zktony.android.utils.DateTimeUtils
import com.zktony.android.utils.HzmctUtils
import com.zktony.datastore.rememberDataSaverState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun SettingsView(viewModel: SettingsViewModel = hiltViewModel()) {
val navigationActions = LocalNavigationActions.current
BackHandler {
navigationActions.navigateUp()
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(
color = MaterialTheme.colorScheme.surface,
shape = MaterialTheme.shapes.medium
)
.padding(16.dp)
.clip(MaterialTheme.shapes.medium),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
item {
SystemSettingsView(viewModel = viewModel)
}
item {
UserSettingsView(viewModel = viewModel)
}
item {
RequirePermission(role = Role.CUSTOMER_SERVICE) {
FactorySettingsView()
}
}
}
}
// 用户设置
@Composable
fun UserSettingsView(
modifier: Modifier = Modifier,
viewModel: SettingsViewModel
) {
val navigationActions = LocalNavigationActions.current
var showPasswordModify by remember { mutableStateOf(false) }
if (showPasswordModify) {
PasswordModifyDialog(
onDismiss = { showPasswordModify = false },
onVerifyPassword = viewModel::verifyPassword,
onModifyPassword = viewModel::modifyPassword
)
}
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
modifier = Modifier.padding(top = 16.dp),
text = stringResource(id = R.string.app_user_settings),
style = MaterialTheme.typography.headlineMedium
)
// 当前用户
AuthUtils.getLoggedUser()?.let {
Row(
modifier = modifier
.fillMaxWidth()
.background(
MaterialTheme.colorScheme.surfaceVariant,
MaterialTheme.shapes.medium
)
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = it.name,
style = TextStyle(fontSize = 24.sp, fontWeight = FontWeight.Bold)
)
Column {
Text(
text = it.role,
style = TextStyle(fontSize = 12.sp)
)
Text(
text = DateTimeUtils.format(it.lastLoginTime, DateTimeUtils.F3),
style = TextStyle(fontSize = 12.sp)
)
}
}
Button(onClick = { showPasswordModify = true }) {
Text(text = "修改密码")
}
}
}
RequirePermission(role = Role.ADMIN) {
// 用户管理
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_USER_MANAGEMENT) },
title = stringResource(id = R.string.app_user_management)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
}
}
}
// 系统设置
@Composable
fun SystemSettingsView(
modifier: Modifier = Modifier,
viewModel: SettingsViewModel
) {
val scope = rememberCoroutineScope()
val navigationActions = LocalNavigationActions.current
// 语言
var language by rememberDataSaverState(
key = Constants.LANGUAGE,
default = Constants.DEFAULT_LANGUAGE
)
// 提示音
var sound by rememberDataSaverState(
key = Constants.SOUND,
default = Constants.DEFAULT_SOUND
)
// 导航栏
var navigationBar by rememberDataSaverState(
key = Constants.NAVIGATION_BAR,
default = Constants.DEFAULT_NAVIGATION_BAR
)
// 状态栏
var statusBar by rememberDataSaverState(
key = Constants.STATUS_BAR,
default = Constants.DEFAULT_STATUS_BAR
)
// 主屏幕
var homePackage by remember {
mutableStateOf(
HzmctUtils.getHomePackage()?.contains(BuildConfig.APPLICATION_ID) ?: false
)
}
// 系统时间
var systemTime by remember { mutableLongStateOf(System.currentTimeMillis()) }
var showDateTimePicker by remember { mutableStateOf(false) }
// 显示日期时间选择器
if (showDateTimePicker) {
DateTimePicker(
dateMillis = systemTime,
onDateChange = {
scope.launch {
systemTime = it
showDateTimePicker = false
if (!viewModel.setSystemTime(it)) {
delay(500L)
systemTime = System.currentTimeMillis()
}
}
}) {
showDateTimePicker = false
}
}
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = stringResource(id = R.string.app_system_settings),
style = MaterialTheme.typography.headlineMedium
)
// 语言
SettingsItem(title = stringResource(id = R.string.app_language)) {
SegmentedButtonTabRow(
modifier = Modifier.width(300.dp),
tabItems = listOf("简体中文", "English"),
selected = if (language == "zh") 0 else 1
) {
scope.launch {
language = if (it == 0) "zh" else "en"
viewModel.setLanguage(if (it == 0) "zh" else "en")
}
}
}
// 提示音
SettingsItem(title = stringResource(id = R.string.app_sound)) {
SegmentedButtonTabRow(
modifier = Modifier.width(300.dp),
tabItems = Sound.getResIdList().map { stringResource(id = it) },
selected = Sound.indexFromName(sound)
) {
scope.launch {
sound = Sound.getNameByIndex(it)
viewModel.setSound(Sound.getNameByIndex(it))
}
}
}
// 导航栏
SettingsItem(title = stringResource(id = R.string.app_navigation_bar)) {
Switch(
checked = navigationBar,
onCheckedChange = {
scope.launch {
navigationBar = it
if (!viewModel.setNavigationBar(it)) {
delay(500L)
navigationBar = !it
}
}
}
)
}
// 状态栏
SettingsItem(title = stringResource(id = R.string.app_status_bar)) {
Switch(
checked = statusBar,
onCheckedChange = {
scope.launch {
statusBar = it
if (!viewModel.setStatusBar(it)) {
delay(500L)
statusBar = !it
}
}
}
)
}
// 主屏幕
SettingsItem(title = stringResource(id = R.string.app_home_package)) {
Switch(checked = homePackage, onCheckedChange = {
scope.launch {
homePackage = it
if (!viewModel.setHomePackage(it)) {
delay(500L)
homePackage = !it
}
}
})
}
// 配件寿命
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { },
title = stringResource(id = R.string.app_accessory_life)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// 维护记录
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { },
title = stringResource(id = R.string.app_maintenance_record)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// 故障日志
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_ERROR_LOG) },
title = stringResource(id = R.string.app_error_log)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// 版本信息
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_VERSION_INFO) },
title = stringResource(id = R.string.app_version_info)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// 系统时间
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { showDateTimePicker = true },
title = stringResource(id = R.string.app_system_time)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = DateTimeUtils.format(systemTime, DateTimeUtils.F3),
style = MaterialTheme.typography.bodyLarge
)
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
}
}
}
// 工厂设置
@Composable
fun FactorySettingsView(modifier: Modifier = Modifier) {
val navigationActions = LocalNavigationActions.current
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
modifier = Modifier.padding(top = 16.dp),
text = stringResource(id = R.string.app_factory_settings),
style = MaterialTheme.typography.headlineMedium
)
// 参数
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_ARGUMENTS) },
title = stringResource(id = R.string.app_arguments)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// 调试
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_DEBUG) },
title = stringResource(id = R.string.app_debug)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
RequirePermission(role = Role.FACTORY) {
// Fqc
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_FQC) },
title = stringResource(id = R.string.app_fqc)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
// Aging
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_AGING) },
title = stringResource(id = R.string.app_aging)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
}
// 运行日志
SettingsItem(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { navigationActions.navigate(Route.SETTINGS_RUNTIME_LOG) },
title = stringResource(id = R.string.app_runtime_log)
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowForwardIos,
contentDescription = "ArrowForwardIos"
)
}
}
}
@Composable
fun SettingsItem(
modifier: Modifier = Modifier,
title: String,
content: @Composable () -> Unit
) {
Row(
modifier = modifier
.fillMaxWidth()
.height(64.dp)
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.medium)
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = title, style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Normal))
content()
}
}
| 0
|
Kotlin
|
0
| 1
|
bcf0671b9e4ad199e579764f29683c1c575369d2
| 16,603
|
ZkTony
|
Apache License 2.0
|
app/src/main/java/com/johnny/insytgroove/models/UserMDL.kt
|
stevandoh
| 161,178,663
| false
|
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 40, "XML": 36, "Java": 4}
|
package com.johnny.insytgroove.models
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class UserMDL: RealmObject() {
@PrimaryKey
@SerializedName("id")
@Expose
var id: Int = 0
@SerializedName("name")
@Expose
var name: String? = null
@SerializedName("username")
@Expose
var username: String? = null
@SerializedName("email")
@Expose
var email: String? = null
@SerializedName("phone")
@Expose
var phone: String? = null
@SerializedName("website")
@Expose
var website: String? = null
}
| 1
| null |
1
| 1
|
e36d24cf64927cc92a92bf9cc5e222a227212745
| 670
|
insyntGroove
|
MIT License
|
app/src/main/java/com/example/myapplication/ui/theme/Color.kt
|
AlessandraPastore
| 366,678,690
| false
| null |
package com.example.myapplication.ui.theme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.ui.graphics.Color
val Gray900 = Color(0xFF212121)
val Red500 = Color(0xFFD32F2F)
val Red700 = Color(0xFFB71C1C)
val DeepOrange100 = Color(0xFFFFECB3)
val Amber600 = Color(0xFFFFA000)
val LightColors = lightColors(
primary = Red500,
primaryVariant = Red700,
secondary = Amber600,
surface = DeepOrange100,
//il resto è di default
)
val DarkColors = darkColors(
primary = Amber600,
primaryVariant = Gray900,
secondary = Amber600,
onPrimary = Color.Black,
onSecondary = Color.Black,
surface = Color.Black
//il resto è di default
)
| 0
|
Kotlin
|
2
| 3
|
611b464414244f481713bc2cee0145d066b72a26
| 748
|
ComposeApplication
|
MIT License
|
app/src/test/java/com/example/desafio/data/repository/HitRepositoryDataTest.kt
|
awarewire
| 668,075,108
| false
| null |
@file:OptIn(ExperimentalCoroutinesApi::class)
package com.example.desafio.data.repository
import com.example.desafio.data.datasource.HitRemoteDataSource
import com.example.desafio.data.datasource.db.HitsDao
import com.example.desafio.data.datasource.db.toListEntity
import com.example.desafio.data.datasource.device.NetworkHandler
import com.example.desafio.data.datasource.remote.model.toListDomain
import com.example.desafio.domain.HitDomain
import com.example.desafio.domain.commons.errors.NetworkConnection
import com.example.desafio.utils.FakeData
import com.example.desafio.utils.FakeData.getFakeHitDomain
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class HitRepositoryDataTest {
@Mock
lateinit var mockHitRemoteDataSource: HitRemoteDataSource
@Mock
lateinit var mockHitsDao: HitsDao
@Mock
lateinit var mockNetworkHandler: NetworkHandler
@InjectMocks
lateinit var sutHitRepositoryData: HitRepositoryData
@Test
fun `given hits when getHits then success Result returned`() {
runTest {
val hits = FakeData.getFakeHitResponseModel().hits!!.toListDomain()
val response = Result.success(hits)
whenever(mockHitRemoteDataSource.getHits()).thenReturn(response)
val result = sutHitRepositoryData.getHits()
Assert.assertEquals(result.isSuccess, true)
}
}
@Test
fun `given hits when getHitsStream then dao data equals result domain data`() =
runTest {
val hitsDomain = listOf(getFakeHitDomain(), getFakeHitDomain())
whenever(mockHitsDao.getHitsStream()).thenReturn(
flow { emit(hitsDomain.toListEntity()) }
)
val domainStream = sutHitRepositoryData.getHitsStream().first()
assertEquals(Result.success(hitsDomain), domainStream)
}
@Test
fun `given hits EMPTY when getHitsStream then error Result returned`() =
runTest {
val hitsDomain = listOf<HitDomain>()
whenever(mockHitsDao.getHitsStream()).thenReturn(
flow { emit(hitsDomain.toListEntity()) }
)
whenever(mockNetworkHandler.isConnected()).thenReturn(false)
val domainStream = sutHitRepositoryData.getHitsStream().first()
assertEquals(Result.failure<List<HitDomain>>(NetworkConnection()), domainStream)
}
}
| 0
|
Kotlin
|
0
| 0
|
32d73bf22dd661eeeff05d02a51724c3825636a5
| 2,813
|
desafio-android-reign
|
MIT License
|
src/main/kotlin/challenge2/Challenge2-1.kts
|
MintInfusion
| 573,329,608
| false
|
{"Kotlin": 7119}
|
import java.io.File
/**
* A, X = ROCK (1 Point)
* B, Y = PAPER (2 Points)
* C, Z = Scissors (3 Points)
*/
val totalScore = File("./input.txt")
.readLines()
.map { roundString ->
val (opponent, me) = roundString.split(" ")
when (opponent) {
"A" ->
when(me) {
"X" -> 1 + 3
"Y" -> 2 + 6
"Z" -> 3 + 0
else -> throw Error("somethings wrong... opponent: $opponent, me: $me")
}
"B" -> when(me) {
"X" -> 1 + 0
"Y" -> 2 + 3
"Z" -> 3 + 6
else -> throw Error("somethings wrong... opponent: $opponent, me: $me")
}
"C" -> when(me) {
"X" -> 1 + 6
"Y" -> 2 + 0
"Z" -> 3 + 3
else -> throw Error("somethings wrong... opponent: $opponent, me: $me")
}
else -> throw Error("somethings wrong... opponent: $opponent, me: $me")
}
}.sum()
print(totalScore)
| 0
|
Kotlin
|
0
| 0
|
2e7ffe34c5a6f0724e12ae47b79dc929fac63504
| 1,126
|
Advent-of-Code-2022
|
Apache License 2.0
|
app/src/main/java/com/davion/github/customview/screen/progress/ProgressFragment.kt
|
dragonddavion
| 296,300,104
| false
| null |
package com.davion.github.customview.screen.progress
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import com.davion.github.customview.MainActivity
import com.davion.github.customview.R
import com.davion.github.customview.core.viewBinding
import com.davion.github.customview.databinding.FragmentProgressBinding
class ProgressFragment : Fragment(R.layout.fragment_progress) {
private val binding by viewBinding(FragmentProgressBinding::bind)
private lateinit var timer: CountDownTimer
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupActionBar()
initTimer()
initButton()
}
private fun setupActionBar() {
binding.toolbarLayout.toolbar.title = "Progress"
val navController = this.findNavController()
val appBarConfiguration = AppBarConfiguration(navController.graph)
binding.toolbarLayout.toolbar.setupWithNavController(navController, appBarConfiguration)
}
private fun initTimer() {
timer = object : CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {
binding.progressLayout.progressBar.progress += 5
binding.progressLayout.seekBar.progress += 5
binding.progressLayout.progressCircle.progress += 5
val progressText = binding.progressLayout.progressCircle.progress.toString() + "%"
binding.progressLayout.textView2.text = progressText
}
override fun onFinish() {
Log.d("Davion", "onFinish")
}
}
timer.start()
}
private fun initButton() {
binding.progressLayout.button.setOnClickListener {
binding.progressLayout.progressBar.progress += 10
}
binding.progressLayout.buttonReset.setOnClickListener {
binding.progressLayout.progressBar.progress = 0
binding.progressLayout.seekBar.progress = 0
binding.progressLayout.progressCircle.progress = 0
timer.cancel()
timer.start()
}
}
override fun onDestroyView() {
super.onDestroyView()
timer.cancel()
}
}
| 0
|
Kotlin
|
0
| 0
|
c0a9434d4b4c94bb25322ff520e14deba6a16b86
| 2,555
|
custom_view_android
|
Apache License 2.0
|
essential-tests/src/testFixtures/kotlin/org/stellar/anchor/platform/integrationtest/Sep10Tests.kt
|
stellar
| 452,893,461
| false
| null |
package org.stellar.anchor.platform.integrationtest
import kotlin.test.assertFailsWith
import org.junit.jupiter.api.Test
import org.stellar.anchor.api.exception.SepNotAuthorizedException
import org.stellar.anchor.api.sep.sep10.ValidationRequest
import org.stellar.anchor.client.Sep10Client
import org.stellar.anchor.platform.*
class Sep10Tests : AbstractIntegrationTests(TestConfig(testProfileName = "default")) {
lateinit var sep10Client: Sep10Client
lateinit var sep10ClientMultiSig: Sep10Client
init {
if (!::sep10Client.isInitialized) {
sep10Client =
Sep10Client(
toml.getString("WEB_AUTH_ENDPOINT"),
toml.getString("SIGNING_KEY"),
CLIENT_WALLET_ACCOUNT,
CLIENT_WALLET_SECRET
)
}
if (!::sep10ClientMultiSig.isInitialized) {
sep10ClientMultiSig =
Sep10Client(
toml.getString("WEB_AUTH_ENDPOINT"),
toml.getString("SIGNING_KEY"),
CLIENT_WALLET_ACCOUNT,
arrayOf(
CLIENT_WALLET_SECRET,
CLIENT_WALLET_EXTRA_SIGNER_1_SECRET,
CLIENT_WALLET_EXTRA_SIGNER_2_SECRET
)
)
}
}
@Test
fun testAuth() {
sep10Client.auth()
}
@Test
fun testMultiSig() {
sep10ClientMultiSig.auth()
}
@Test
fun testUnsignedChallenge() {
val challenge = sep10Client.challenge()
assertFailsWith(
exceptionClass = SepNotAuthorizedException::class,
block = { sep10Client.validate(ValidationRequest.of(challenge.transaction)) }
)
}
}
| 15
| null |
33
| 32
|
32de9627789218f657eb17c2cea0267b91111f0f
| 1,545
|
java-stellar-anchor-sdk
|
Apache License 2.0
|
kotlin-styled-next/src/main/kotlin/styled/CssBuilder.kt
|
JetBrains
| 93,250,841
| false
| null |
package styled
import kotlinx.css.CssBuilder
import kotlinx.css.properties.*
fun CssBuilder.animation(
duration: Time = 0.s,
timing: Timing = Timing.ease,
delay: Time = 0.s,
iterationCount: IterationCount = 1.times,
direction: AnimationDirection = AnimationDirection.normal,
fillMode: FillMode = FillMode.none,
playState: PlayState = PlayState.running,
builder: KeyframesBuilder.() -> Unit,
) {
val name = GlobalStyles.scheduleToInject(builder)
animation(name, duration, timing, delay, iterationCount, direction, fillMode, playState)
}
| 38
| null |
162
| 983
|
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 578
|
kotlin-wrappers
|
Apache License 2.0
|
lithic-java-core/src/test/kotlin/com/lithic/api/models/AccountHolderListParamsTest.kt
|
lithic-com
| 592,386,416
| false
|
{"Kotlin": 4133523, "Java": 5023, "Shell": 1056, "Dockerfile": 305}
|
// File generated from our OpenAPI spec by Stainless.
package com.lithic.api.models
import com.lithic.api.models.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class AccountHolderListParamsTest {
@Test
fun createAccountHolderListParams() {
AccountHolderListParams.builder()
.endingBefore("string")
.externalId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")
.limit(123L)
.startingAfter("string")
.build()
}
@Test
fun getQueryParams() {
val params =
AccountHolderListParams.builder()
.endingBefore("string")
.externalId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")
.limit(123L)
.startingAfter("string")
.build()
val expected = mutableMapOf<String, List<String>>()
expected.put("ending_before", listOf("string"))
expected.put("external_id", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e"))
expected.put("limit", listOf("123"))
expected.put("starting_after", listOf("string"))
assertThat(params.getQueryParams()).isEqualTo(expected)
}
@Test
fun getQueryParamsWithoutOptionalFields() {
val params = AccountHolderListParams.builder().build()
val expected = mutableMapOf<String, List<String>>()
assertThat(params.getQueryParams()).isEqualTo(expected)
}
}
| 0
|
Kotlin
|
0
| 15
|
c38a3009752f12f503cbdc99300c160e4450832d
| 1,456
|
lithic-java
|
Apache License 2.0
|
client_restaurant/shared/src/androidMain/kotlin/main.android.kt
|
TheChance101
| 671,967,732
| false
|
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
|
import androidx.compose.runtime.Composable
import presentation.app.App
@Composable fun MainView() = App()
| 4
|
Kotlin
|
55
| 572
|
1d2e72ba7def605529213ac771cd85cbab832241
| 107
|
beep-beep
|
Apache License 2.0
|
examples/randomGif/src/main/kotlin/com/brianegan/bansa/randomGif/store.kt
|
brianegan
| 47,591,925
| false
| null |
package com.brianegan.bansa.randomGif
| 4
|
Kotlin
|
29
| 442
|
ffb606ad2aefa58cac08e9daee26b6767b03186b
| 39
|
bansa
|
MIT License
|
app/src/main/java/com/plcoding/jetpackcomposepokedex/MainActivity.kt
|
wagarcdev
| 573,946,216
| false
| null |
package com.plcoding.jetpackcomposepokedex
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.rememberNavController
import com.plcoding.jetpackcomposepokedex.pokemondetail.PokemonDetailScreen
import com.plcoding.jetpackcomposepokedex.pokemonlist.PokemonListScreen
import com.plcoding.jetpackcomposepokedex.ui.theme.JetpackComposePokedexTheme
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposePokedexTheme {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "pokemon_list_screen"
) {
composable("pokemon_list_screen") {
PokemonListScreen(navController = navController)
}
composable(
"pokemon_detail_screen/{dominantColor}/{pokemonName}",
arguments = listOf(
navArgument("dominantColor") {
type = NavType.IntType
},
navArgument("pokemonName") {
type = NavType.StringType
}
)
) {
val dominantColor = remember {
val color = it.arguments?.getInt("dominantColor")
color?.let { Color(it) } ?: Color(0xFFFFFFFF)
}
val pokemonName = remember {
it.arguments?.getString("pokemonName")
}
PokemonDetailScreen(
dominantColor = dominantColor,
pokemonName = pokemonName?.toLowerCase(Locale.ROOT) ?: "",
navController = navController
)
// Detail Screen
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a81c4ec8fe7c4da54326fd959921b0705b79a175
| 2,840
|
myPokedex
|
MIT License
|
src/main/kotlin/sh/lumin/kioku/utils/LogEntryCodec.kt
|
lumin-sh
| 815,701,453
| false
|
{"Kotlin": 20893}
|
/*
* Copyright (C) 2024 LuminSh
*
* 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 sh.lumin.kioku.utils
import org.bson.BsonReader
import org.bson.BsonType
import org.bson.BsonWriter
import org.bson.codecs.Codec
import org.bson.codecs.DecoderContext
import org.bson.codecs.EncoderContext
import sh.lumin.kioku.db.LogEntry
class LogEntryCodec : Codec<LogEntry> {
override fun encode(writer: BsonWriter, value: LogEntry, encoderContext: EncoderContext) {
writer.writeStartDocument()
writer.writeName("timestamp")
writer.writeDateTime(value.timestamp)
writer.writeName("topic")
writer.writeString(value.topic)
writer.writeName("data")
when (value.data) {
is String -> writer.writeString(value.data)
is Number -> writer.writeDouble(value.data.toDouble())
is Boolean -> writer.writeBoolean(value.data)
else -> writer.writeString(value.data.toString()) // Fallback to string representation
}
writer.writeEndDocument()
}
override fun getEncoderClass(): Class<LogEntry> = LogEntry::class.java
override fun decode(reader: BsonReader, decoderContext: DecoderContext): LogEntry {
reader.readStartDocument()
var timestamp: Long? = null
var topic: String? = null
var data: Any? = null
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
val fieldName = reader.readName() // Read the field name
when (fieldName) {
"timestamp" -> timestamp = reader.readDateTime()
"topic" -> topic = reader.readString()
"data" -> {
data = when (reader.currentBsonType) {
BsonType.STRING -> reader.readString()
BsonType.INT32 -> reader.readInt32()
BsonType.INT64 -> reader.readInt64()
BsonType.DOUBLE -> reader.readDouble()
BsonType.BOOLEAN -> reader.readBoolean()
else -> {
reader.skipValue()
null
}
}
}
else -> {
reader.skipValue()
}
}
}
reader.readEndDocument()
return LogEntry(timestamp ?: 0L, topic ?: "", data ?: "Unknown")
}
}
| 0
|
Kotlin
|
0
| 0
|
004b7d15dfbfd86a0017df876eb892f63892fbb7
| 2,959
|
Kioku
|
Apache License 2.0
|
src/main/kotlin/xyz/magentaize/dynamicdata/list/ListFilterPolicy.kt
|
Magentaize
| 290,133,754
| false
| null |
package xyz.magentaize.dynamicdata.list
enum class ListFilterPolicy {
ClearAndReplace,
CalculateDiff
}
| 0
|
Kotlin
|
0
| 3
|
dda522f335a6ab3847cc90ff56e8429c15834800
| 112
|
dynamicdata-kotlin
|
MIT License
|
expandablehinttext/src/main/java/com/tomlonghurst/expandablehinttext/ExpandableEditText.kt
|
thomhurst
| 163,102,531
| false
| null |
package com.tomlonghurst.expandablehinttext
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.widget.EditText
/**
* Edit Text for Expandable Hint Text
*/
class ExpandableEditText : EditText {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private var onBackPressed: Runnable? = null
/**
* Custom event for clicking back when on this view is active
* @sample ExpandableEditText.setOnBackPressListener { Runnable { println("Back Pressed") } }
*/
fun setOnBackPressListener(onBackPressed: Runnable?) {
this.onBackPressed = onBackPressed
}
private var clickable: Boolean = true
override fun setClickable(clickable: Boolean) {
super.setClickable(clickable)
this.clickable = clickable
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
return if (clickable) {
super.onTouchEvent(event)
} else {
false
}
}
override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
if (event?.keyCode == KeyEvent.KEYCODE_BACK) {
this.clearFocus()
onBackPressed?.run()
}
return super.onKeyPreIme(keyCode, event)
}
}
| 5
| null |
20
| 179
|
5891297e568f1ffe028a119df5f46e85ab2b990a
| 1,487
|
ExpandableHintText
|
Apache License 2.0
|
src/test/kotlin/com/fwdekker/randomness/affix/AffixDecoratorTest.kt
|
FWDekker
| 96,791,256
| false
|
{"Kotlin": 577505, "HTML": 2713, "Java": 1024}
|
package com.fwdekker.randomness.affix
import com.fwdekker.randomness.stateDeepCopyTestFactory
import com.fwdekker.randomness.testhelpers.Tags
import com.fwdekker.randomness.testhelpers.shouldValidateAsBundle
import io.kotest.core.spec.style.FunSpec
import io.kotest.data.row
import io.kotest.datatest.withData
import io.kotest.matchers.shouldBe
/**
* Unit tests for [AffixDecorator].
*/
object AffixDecoratorTest : FunSpec({
tags(Tags.SCHEME)
context("generateStrings") {
withData(
mapOf(
"returns default input if disabled" to
row(AffixDecorator(enabled = false, descriptor = """<@>"""), """[i0]"""),
"appends and prepends if no '@'" to
row(AffixDecorator(enabled = true, descriptor = """*"""), "*[i0]*"),
"replaces 'at' with input" to
row(AffixDecorator(enabled = true, descriptor = "(@)"), "([i0])"),
"replaces multiple 'at' with input" to
row(AffixDecorator(enabled = true, descriptor = "(@|@)"), "([i0]|[i0])"),
"interprets escaped 'at' as literal" to
row(AffixDecorator(enabled = true, descriptor = """(\@)"""), """(@)[i0](@)"""),
"interprets escaped 'backslash' as literal" to
row(AffixDecorator(enabled = true, descriptor = """(\\@)"""), """(\[i0])"""),
)
) { (scheme, output) ->
scheme.generator = { count -> List(count) { "[i$it]" } }
scheme.generateStrings()[0] shouldBe output
}
}
context("doValidate") {
withData(
mapOf(
"succeeds for default state" to
row(AffixDecorator(), null),
"succeeds for empty descriptor" to
row(AffixDecorator(enabled = true, descriptor = ""), null),
"succeeds for complex descriptor" to
row(AffixDecorator(enabled = true, descriptor = """\\@\@@\@\\"""), null),
"fails descriptor has single trailing backslash" to
row(AffixDecorator(enabled = true, descriptor = """\"""), "affix.error.trailing_escape"),
"succeeds if descriptor has double trailing backslash" to
row(AffixDecorator(enabled = true, descriptor = """\\"""), null),
"fails if descriptors has triple trailing backslash" to
row(AffixDecorator(enabled = true, descriptor = """\\\"""), "affix.error.trailing_escape"),
"fails for invalid settings even if disabled" to
row(AffixDecorator(enabled = false, descriptor = """\"""), "affix.error.trailing_escape"),
)
) { (scheme, validation) ->
scheme.generator = { count -> List(count) { "[i$it]" } }
scheme shouldValidateAsBundle validation
}
}
include(stateDeepCopyTestFactory { AffixDecorator() })
})
| 7
|
Kotlin
|
7
| 45
|
7d323799d6e12fdc741b0984afef62bc363aa7c8
| 2,992
|
intellij-randomness
|
MIT License
|
app/src/main/java/com/example/foodpanda/data/DataOrException.kt
|
mannu1392004
| 764,179,113
| false
|
{"Kotlin": 103727}
|
package com.example.foodpanda.data
data class DataOrException<T, Boolean, E: Exception>(
var data: T? = null,
var loading: kotlin.Boolean = true,
var e: E? = null)
| 1
|
Kotlin
|
0
| 0
|
b4bae544a9cc9c65f251df0c81e30af1a3641a9b
| 176
|
Panda-Food
|
MIT License
|
app/src/main/java/com/task/searchbar/extensions/SearchViewExtentions.kt
|
EzzWaleed
| 205,580,621
| false
| null |
import android.app.SearchManager
import android.database.MatrixCursor
import androidx.appcompat.widget.SearchView
import androidx.cursoradapter.widget.CursorAdapter
import androidx.cursoradapter.widget.SimpleCursorAdapter
import com.task.searchbar.R
private fun SearchView.initSuggestionAdapterAdapter(){
val columnNames = arrayOf(SearchManager.SUGGEST_COLUMN_TEXT_1)
val viewIds = intArrayOf(R.id.tv)
suggestionsAdapter = SimpleCursorAdapter(
context,
R.layout.list_item_drop_down,
null,
columnNames,
viewIds,
CursorAdapter.IGNORE_ITEM_VIEW_TYPE)
setOnSuggestionListener(object : SearchView.OnSuggestionListener {
override fun onSuggestionSelect(position: Int): Boolean {
return false
}
override fun onSuggestionClick(position: Int): Boolean {
val cursor = suggestionsAdapter.cursor
cursor.moveToPosition(position)
val query = cursor.getString(1)
setQuery(query, true)
return true
}
})
}
fun SearchView.replaceSuggestions(suggestions: List<String>?){
suggestions?.let {
if (suggestionsAdapter == null)
initSuggestionAdapterAdapter()
else
suggestionsAdapter.cursor.close()
val menuCols = arrayOf(
"_id",
SearchManager.SUGGEST_COLUMN_TEXT_1
)
val cursor = MatrixCursor(menuCols)
for (i in it.indices) {
cursor.addRow(arrayOf(i, it[i]))
}
suggestionsAdapter.swapCursor(cursor)
}
}
| 0
|
Kotlin
|
0
| 3
|
b03afd9bfb6a2a674b005c86eb268e984268e6df
| 1,592
|
SearchBar
|
Apache License 2.0
|
src/main/kotlin/repository/holder/CreatorItem.kt
|
matsumo0922
| 551,886,267
| false
|
{"Kotlin": 30956}
|
package repository.holder
data class CreatorItem(
val id: String,
val title: String,
val publishedTime: String,
val updateTime: String,
val isLicked: Boolean,
val lickCount: Int,
val commentCount: Int,
)
| 0
|
Kotlin
|
0
| 0
|
a5b5f5315cf61e6ef758a1578c029422ff5876a1
| 232
|
FanboxDownloader
|
Apache License 2.0
|
plugins/kotlin/completion/tests/testData/basic/java/importAliases/TopLevelFun.kt
|
JetBrains
| 2,489,216
| false
| null |
import kotlin.collections.listOf as list
fun foo() {
lis<caret>
}
// EXIST: { lookupString: "list", itemText: "list", tailText: "() (kotlin.collections.listOf)", icon: "nodes/function.svg"}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 196
|
intellij-community
|
Apache License 2.0
|
subprojects/delivery/nupokati/src/main/kotlin/com/avito/android/agp/Accessors.kt
|
avito-tech
| 230,265,582
| false
|
{"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
|
package com.avito.android.agp
import com.android.build.api.variant.ApplicationVariant
import com.android.build.api.variant.VariantOutputConfiguration
import com.avito.android.Problem
import com.avito.android.asRuntimeException
internal fun ApplicationVariant.getVersionCode(): Int {
return outputs.firstOrNull {
// todo probably not a correct artifact, need to be more specific
it.outputType == VariantOutputConfiguration.OutputType.SINGLE && it.enabled.get()
}?.versionCode?.orNull ?: throw Problem(
shortDescription = "versionCode in not available",
context = "Configuring NupokatiPlugin",
because = "No obvious reason, versionCode should be set here"
).asRuntimeException()
}
| 10
|
Kotlin
|
50
| 414
|
4dc43d73134301c36793e49289305768e68e645b
| 733
|
avito-android
|
MIT License
|
app/src/main/java/com/uxstate/skycast/domain/repository/WeatherRepository.kt
|
Tonnie-Dev
| 698,802,033
| false
|
{"Kotlin": 169908}
|
package com.uxstate.skycast.domain.repository
import com.uxstate.skycast.domain.model.CurrentWeather
import com.uxstate.skycast.domain.model.ForecastWeather
import com.uxstate.skycast.domain.model.GeoPoint
import com.uxstate.skycast.utils.Resource
import kotlinx.coroutines.flow.Flow
interface WeatherRepository {
fun getCurrentWeather(geoPoint: GeoPoint): Flow<Resource<CurrentWeather>>
fun getForecastWeather(cityId:Int):Flow<Resource<List<ForecastWeather>>>
}
| 0
|
Kotlin
|
0
| 0
|
1bf6826fb3d0ec9c6decf54d6e1176211bf7f3e2
| 469
|
SkyCast
|
The Unlicense
|
partiql-cli/src/main/kotlin/org/partiql/cli/shell/Shell.kt
|
partiql
| 186,474,394
| false
| null |
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.partiql.cli.shell
import com.google.common.base.CharMatcher
import com.google.common.util.concurrent.Uninterruptibles
import org.fusesource.jansi.AnsiConsole
import org.jline.reader.EndOfFileException
import org.jline.reader.History
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import org.jline.reader.UserInterruptException
import org.jline.reader.impl.completer.AggregateCompleter
import org.jline.terminal.TerminalBuilder
import org.jline.utils.AttributedString
import org.jline.utils.AttributedStringBuilder
import org.jline.utils.AttributedStyle
import org.jline.utils.InfoCmp
import org.joda.time.Duration
import org.partiql.cli.format.ExplainFormatter
import org.partiql.cli.pipeline.AbstractPipeline
import org.partiql.lang.SqlException
import org.partiql.lang.eval.Bindings
import org.partiql.lang.eval.EvaluationSession
import org.partiql.lang.eval.ExprValue
import org.partiql.lang.eval.PartiQLResult
import org.partiql.lang.eval.delegate
import org.partiql.lang.syntax.PartiQLParserBuilder
import org.partiql.lang.util.ConfigurableExprValueFormatter
import org.partiql.lang.util.ExprValueFormatter
import java.io.Closeable
import java.io.OutputStream
import java.io.PrintStream
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Locale
import java.util.Properties
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import javax.annotation.concurrent.GuardedBy
private const val PROMPT_1 = "PartiQL> "
private const val PROMPT_2 = " | "
private const val BAR_1 = "===' "
private const val BAR_2 = "--- "
private const val WELCOME_MSG = "Welcome to the PartiQL shell!"
private const val HELP = """
!add_to_global_env Adds to the global environment key/value pairs of the supplied struct
!global_env Displays the current global environment
!list_commands Prints this message
!help Prints this message
!history Prints command history
!exit Exits the shell
!clear Clears the screen
"""
private val SUCCESS: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN)
private val ERROR: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)
private val INFO: AttributedStyle = AttributedStyle.DEFAULT
private val WARN: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW)
private val EXIT_DELAY: Duration = Duration(3000)
/**
* Initial work to replace the REPL with JLine3. I have attempted to keep this similar to Repl.kt, but have some
* opinions on ways to clean this up in later PRs.
*/
internal class Shell(
private val output: OutputStream,
private val compiler: AbstractPipeline,
private val initialGlobal: Bindings<ExprValue>,
private val config: ShellConfiguration = ShellConfiguration()
) {
private val homeDir: Path = Paths.get(System.getProperty("user.home"))
private val globals = ShellGlobalBinding().add(initialGlobal)
private var previousResult = ExprValue.nullValue
private val out = PrintStream(output)
fun start() {
val exiting = AtomicBoolean()
val interrupter = ThreadInterrupter()
val exited = CountDownLatch(1)
Runtime
.getRuntime()
.addShutdownHook(
Thread {
exiting.set(true)
interrupter.interrupt()
Uninterruptibles.awaitUninterruptibly(exited, EXIT_DELAY.millis, TimeUnit.MILLISECONDS)
}
)
try {
AnsiConsole.systemInstall()
run(exiting)
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
} finally {
exited.countDown()
interrupter.close()
AnsiConsole.systemUninstall()
}
}
private fun run(exiting: AtomicBoolean) = TerminalBuilder.builder().build().use { terminal ->
val highlighter = when {
this.config.isMonochrome -> null
else -> ShellHighlighter()
}
val completer = AggregateCompleter(CompleterDefault())
val reader = LineReaderBuilder.builder()
.terminal(terminal)
.parser(ShellParser)
.completer(completer)
.option(LineReader.Option.GROUP_PERSIST, true)
.option(LineReader.Option.AUTO_LIST, true)
.option(LineReader.Option.CASE_INSENSITIVE, true)
.variable(LineReader.LIST_MAX, 10)
.highlighter(highlighter)
.expander(ShellExpander)
.variable(LineReader.HISTORY_FILE, homeDir.resolve(".partiql/.history"))
.variable(LineReader.SECONDARY_PROMPT_PATTERN, PROMPT_2)
.build()
out.info(WELCOME_MSG)
out.info("Typing mode: ${compiler.options.typingMode.name}")
out.info("Using version: ${retrievePartiQLVersionAndHash()}")
while (!exiting.get()) {
val line: String = try {
reader.readLine(PROMPT_1)
} catch (ex: UserInterruptException) {
if (ex.partialLine.isNotEmpty()) {
reader.history.add(ex.partialLine)
}
continue
} catch (ex: EndOfFileException) {
out.info("^D")
return
}
// Pretty print AST
if (line.endsWith("\n!!")) {
printAST(line.removeSuffix("!!"))
continue
}
if (line.isBlank()) {
out.success("OK!")
continue
}
// Handle commands
val command = when (val end: Int = CharMatcher.`is`(';').or(CharMatcher.whitespace()).indexIn(line)) {
-1 -> ""
else -> line.substring(0, end)
}
when (command.toLowerCase(Locale.ENGLISH).trim()) {
"!exit" -> return
"!add_to_global_env" -> {
// Consider PicoCLI + Jline, but it doesn't easily place nice with commands + raw SQL
// https://github.com/partiql/partiql-lang-kotlin/issues/63
val arg = line.trim().removePrefix(command).trim()
if (arg.isEmpty() || arg.isBlank()) {
out.error("!add_to_global_env requires 1 parameter")
continue
}
executeAndPrint {
val locals = Bindings.buildLazyBindings<ExprValue> {
addBinding("_") {
previousResult
}
}.delegate(globals.bindings)
val result = compiler.compile(arg, EvaluationSession.build { globals(locals) }) as PartiQLResult.Value
globals.add(result.value.bindings)
result
}
continue
}
"!global_env" -> {
executeAndPrint { AbstractPipeline.convertExprValue(globals.asExprValue()) }
continue
}
"!clear" -> {
terminal.puts(InfoCmp.Capability.clear_screen)
terminal.flush()
continue
}
"!history" -> {
for (entry in reader.history) {
out.println(entry.pretty())
}
continue
}
"!list_commands", "!help" -> {
out.info(HELP)
continue
}
}
// Execute PartiQL
executeAndPrint {
val locals = Bindings.buildLazyBindings<ExprValue> {
addBinding("_") { previousResult }
}.delegate(globals.bindings)
compiler.compile(line, EvaluationSession.build { globals(locals) })
}
}
}
private fun executeAndPrint(func: () -> PartiQLResult) {
val result: PartiQLResult? = try {
func.invoke()
} catch (ex: SqlException) {
out.error(ex.generateMessage())
out.error(ex.message)
null // signals that there was an error
}
printPartiQLResult(result)
}
private fun printPartiQLResult(result: PartiQLResult?) {
when (result) {
null -> {
out.error("ERROR!")
}
is PartiQLResult.Value -> {
printExprValue(ConfigurableExprValueFormatter.pretty, result.value)
out.success("OK!")
}
is PartiQLResult.Explain.Domain -> {
val explain = ExplainFormatter.format(result)
out.println(explain)
out.success("OK!")
}
is PartiQLResult.Insert,
is PartiQLResult.Replace,
is PartiQLResult.Delete -> {
out.warn("Insert/Replace/Delete are not yet supported")
}
}
out.flush()
}
private fun printExprValue(formatter: ExprValueFormatter, result: ExprValue) {
out.info(BAR_1)
formatter.formatTo(result, out)
out.println()
out.info(BAR_2)
previousResult = result
}
private fun retrievePartiQLVersionAndHash(): String {
val properties = Properties()
properties.load(this.javaClass.getResourceAsStream("/partiql.properties"))
return "${properties.getProperty("version")}-${properties.getProperty("commit")}"
}
private fun printAST(query: String) {
if (query.isNotBlank()) {
val parser = PartiQLParserBuilder.standard().build()
val ast = try {
parser.parseAstStatement(query)
} catch (ex: SqlException) {
out.error(ex.generateMessage())
out.error(ex.message)
out.error("ERROR!")
out.flush()
return
}
val explain = PartiQLResult.Explain.Domain(value = ast, format = null)
val output = ExplainFormatter.format(explain)
out.println(output)
out.success("OK!")
out.flush()
}
}
/**
* A configuration class representing any configurations specified by the user
* @param isMonochrome specifies the removal of syntax highlighting
*/
class ShellConfiguration(val isMonochrome: Boolean = false)
}
/**
* Pretty print a History.Entry with a gutter for the entry index
*/
private fun History.Entry.pretty(): String {
val entry = StringBuilder()
for (line in this.line().lines()) {
entry.append('\t').append(line).append('\n')
}
return AttributedStringBuilder()
.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.CYAN))
.append(java.lang.String.format("%5d", this.index() + 1))
.style(AttributedStyle.DEFAULT)
.append(entry.trimEnd())
.toAnsi()
}
private fun ansi(string: String, style: AttributedStyle) = AttributedString(string, style).toAnsi()
private fun PrintStream.success(string: String) = this.println(ansi(string, SUCCESS))
private fun PrintStream.error(string: String) = this.println(ansi(string, ERROR))
private fun PrintStream.info(string: String) = this.println(ansi(string, INFO))
private fun PrintStream.warn(string: String) = this.println(ansi(string, WARN))
private class ThreadInterrupter : Closeable {
private val thread = Thread.currentThread()
@GuardedBy("this")
private var processing = true
@Synchronized
fun interrupt() {
if (processing) {
thread.interrupt()
}
}
@Synchronized
override fun close() {
processing = false
Thread.interrupted()
}
}
| 228
|
Kotlin
|
60
| 523
|
6e5d4a637871bccb90f49596d043549e22c15a51
| 12,591
|
partiql-lang-kotlin
|
Apache License 2.0
|
src/test/kotlin/recce/server/dataset/DatasetRecServiceIntegrationTest.kt
|
thoughtworks
| 407,469,297
| false
|
{"Kotlin": 152890}
|
package recce.server.dataset
import io.micronaut.context.ApplicationContext
import io.micronaut.inject.qualifiers.Qualifiers
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import io.r2dbc.spi.R2dbcBadGrammarException
import jakarta.inject.Inject
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import reactor.kotlin.core.util.function.component1
import reactor.kotlin.core.util.function.component2
import reactor.kotlin.test.test
import reactor.util.function.Tuples
import recce.server.BuildInfoConfiguration
import recce.server.R2dbcDatasource
import recce.server.RecConfiguration
import recce.server.dataset.datasource.FlywayMigrator
import recce.server.recrun.*
import java.nio.file.Path
@MicronautTest(
environments = ["test-integration"],
propertySources = ["classpath:config/application-test-dataset.yml"],
transactional = false
)
open class DatasetRecServiceIntegrationTest {
@TempDir lateinit var tempDir: Path
@Inject lateinit var migrator: FlywayMigrator
@Inject lateinit var ctx: ApplicationContext
@Inject lateinit var service: DatasetRecService
@Inject lateinit var runRepository: RecRunRepository
@Inject lateinit var recordRepository: RecRecordRepository
@BeforeEach
fun setup() {
migrator.cleanMigrateSource(tempDir)
migrator.cleanMigrateTarget(tempDir)
}
@BeforeEach
@AfterEach
fun wipeDb() {
runRepository.deleteAll().block()
}
@Test
fun `can run a simple reconciliation`() {
service.runFor("test-dataset")
.test()
.assertNext { run ->
checkCompleted(run)
checkSuccessful(run)
}
.verifyComplete()
runRepository.findAll()
.flatMap { run ->
recordRepository.findByRecRunId(run.id!!).map { Tuples.of(run, it) }
}
.test()
.assertNext { (run, record) ->
checkCompleted(run)
checkSuccessful(run)
assertThat(record.key.recRunId).isEqualTo(run.id)
assertThat(record.key.migrationKey).isEqualTo("Test0")
assertThat(record.sourceData).isEqualTo(record.targetData).`is`(hexSha256Hash)
}
.assertNext { (run, record) ->
assertThat(run.datasetId).isEqualTo("test-dataset")
assertThat(record.key.recRunId).isEqualTo(run.id)
assertThat(record.key.migrationKey).isEqualTo("Test1")
assertThat(record.sourceData).isEqualTo(record.targetData).`is`(hexSha256Hash)
}
.assertNext { (run, record) ->
assertThat(run.datasetId).isEqualTo("test-dataset")
assertThat(record.key.recRunId).isEqualTo(run.id)
assertThat(record.key.migrationKey).isEqualTo("Test2")
assertThat(record.sourceData).`is`(hexSha256Hash)
assertThat(record.targetData).isNull()
}
.assertNext { (run, record) ->
assertThat(run.datasetId).isEqualTo("test-dataset")
assertThat(record.key.recRunId).isEqualTo(run.id)
assertThat(record.key.migrationKey).isEqualTo("Test3")
assertThat(record.sourceData).isNull()
assertThat(record.targetData).`is`(hexSha256Hash)
}
.assertNext { (run, record) ->
assertThat(run.datasetId).isEqualTo("test-dataset")
assertThat(record.key.recRunId).isEqualTo(run.id)
assertThat(record.key.migrationKey).isEqualTo("Test4")
assertThat(record.sourceData).isNull()
assertThat(record.targetData).`is`(hexSha256Hash)
}
.verifyComplete()
}
private fun checkCompleted(run: RecRun) {
val datasetConfig = ctx.getBean(RecConfiguration::class.java).datasets["test-dataset"]
val buildConfig = ctx.getBean(BuildInfoConfiguration::class.java)
val sourceR2dbcConfig = ctx.getBean(R2dbcDatasource::class.java, Qualifiers.byName("source-h2"))
val targetR2dbcConfig = ctx.getBean(R2dbcDatasource::class.java, Qualifiers.byName("target-h2"))
val expectedMeta =
mapOf(
"sourceQuery" to datasetConfig?.source?.queryStatement,
"targetQuery" to datasetConfig?.target?.queryStatement,
"sourceUrl" to sourceR2dbcConfig.url,
"targetUrl" to targetR2dbcConfig.url,
"version" to buildConfig.version
)
SoftAssertions.assertSoftly { softly ->
softly.assertThat(run.id).isNotNull
softly.assertThat(run.datasetId).isEqualTo("test-dataset")
softly.assertThat(run.createdTime).isNotNull
softly.assertThat(run.updatedTime).isAfterOrEqualTo(run.createdTime)
softly.assertThat(run.completedTime).isAfterOrEqualTo(run.createdTime)
softly.assertThat(run.metadata).usingRecursiveComparison().isEqualTo(expectedMeta)
}
}
private fun checkSuccessful(run: RecRun) {
SoftAssertions.assertSoftly { softly ->
softly.assertThat(run.status).isEqualTo(RunStatus.Successful)
softly.assertThat(run.failureCause).isNull()
softly.assertThat(run.summary).isEqualTo(MatchStatus(1, 2, 2, 0))
val expectedMeta =
DatasetMeta(
listOf(
ColMeta("MIGRATIONKEY", "String"),
ColMeta("NAME", "String"),
ColMeta("VAL", "String")
)
)
softly.assertThat(run.sourceMeta).usingRecursiveComparison().isEqualTo(expectedMeta)
softly.assertThat(run.targetMeta).usingRecursiveComparison().isEqualTo(expectedMeta)
}
}
private fun checkFailed(run: RecRun) {
SoftAssertions.assertSoftly { softly ->
softly.assertThat(run.status).isEqualTo(RunStatus.Failed)
softly.assertThat(run.summary).satisfiesAnyOf(
{ st -> assertThat(st).isNull() },
{ st -> assertThat(st).isEqualTo(MatchStatus()) }
)
softly.assertThat(run.sourceMeta).isEqualTo(DatasetMeta())
softly.assertThat(run.targetMeta).isEqualTo(DatasetMeta())
}
}
@Test
fun `should fail run on bad source query`() {
// Wipe the source DB
migrator.cleanMigrateSource(tempDir, "SELECT 1")
service.runFor("test-dataset")
.test()
.assertNext { run ->
checkCompleted(run)
checkFailed(run)
assertThat(run.failureCause)
.isExactlyInstanceOf(DataLoadException::class.java)
.hasMessageContaining("Failed to load data from Source(ref=source-h2)")
.hasMessageContaining("\"TESTDATA\" not found")
.hasCauseExactlyInstanceOf(R2dbcBadGrammarException::class.java)
}
.verifyComplete()
// Check persisted representation
runRepository.findAll()
.test()
.assertNext { run ->
checkCompleted(run)
checkFailed(run)
}
.verifyComplete()
}
@Test
fun `should fail run on bad target query`() {
// Wipe the target DB
migrator.cleanMigrateTarget(tempDir, "SELECT 1")
service.runFor("test-dataset")
.test()
.assertNext { run ->
checkCompleted(run)
checkFailed(run)
assertThat(run.failureCause)
.isExactlyInstanceOf(DataLoadException::class.java)
.hasMessageContaining("Failed to load data from Target(ref=target-h2)")
.hasMessageContaining("\"TESTDATA\" not found")
.hasCauseExactlyInstanceOf(R2dbcBadGrammarException::class.java)
}
.verifyComplete()
// Check persisted representation
runRepository.findAll()
.test()
.assertNext { run ->
checkCompleted(run)
checkFailed(run)
}
.verifyComplete()
}
}
| 21
|
Kotlin
|
3
| 23
|
b2d2212a4a789e8585f59e416f2eade26ca66e1c
| 8,542
|
recce
|
Apache License 2.0
|
plugin/src/test/kotlin/dev/aga/gradle/versioncatalogs/mock/ResolutionStrategy.kt
|
austinarbor
| 679,523,691
| false
|
{"Kotlin": 83528}
|
package dev.aga.gradle.versioncatalogs.mock
import java.util.concurrent.TimeUnit
import org.gradle.api.Action
import org.gradle.api.artifacts.CapabilitiesResolution
import org.gradle.api.artifacts.ComponentSelectionRules
import org.gradle.api.artifacts.DependencyResolveDetails
import org.gradle.api.artifacts.DependencySubstitutions
import org.gradle.api.artifacts.ModuleVersionSelector
import org.gradle.api.internal.artifacts.ComponentSelectionRulesInternal
import org.gradle.api.internal.artifacts.DependencySubstitutionInternal
import org.gradle.api.internal.artifacts.configurations.ConflictResolution
import org.gradle.api.internal.artifacts.configurations.MutationValidator
import org.gradle.api.internal.artifacts.configurations.ResolutionStrategyInternal
import org.gradle.api.internal.artifacts.configurations.dynamicversion.CachePolicy
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyLockingProvider
import org.gradle.api.internal.artifacts.ivyservice.dependencysubstitution.DependencySubstitutionsInternal
import org.gradle.api.internal.artifacts.ivyservice.resolutionstrategy.CapabilitiesResolutionInternal
import org.gradle.api.provider.Property
import org.gradle.internal.ImmutableActionSet
internal class ResolutionStrategy : ResolutionStrategyInternal {
override fun failOnVersionConflict(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun failOnDynamicVersions(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun failOnChangingVersions(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun failOnNonReproducibleResolution(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun preferProjectModules() {
TODO("Not yet implemented")
}
override fun activateDependencyLocking(): org.gradle.api.artifacts.ResolutionStrategy {
return this
}
override fun deactivateDependencyLocking(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun disableDependencyVerification(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun enableDependencyVerification(): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun force(
vararg moduleVersionSelectorNotations: Any?
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun setForcedModules(
vararg moduleVersionSelectorNotations: Any?
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun getForcedModules(): MutableSet<ModuleVersionSelector> {
TODO("Not yet implemented")
}
override fun eachDependency(
rule: Action<in DependencyResolveDetails>
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun cacheDynamicVersionsFor(value: Int, units: String) {
TODO("Not yet implemented")
}
override fun cacheDynamicVersionsFor(value: Int, units: TimeUnit) {
TODO("Not yet implemented")
}
override fun cacheChangingModulesFor(value: Int, units: String) {
TODO("Not yet implemented")
}
override fun cacheChangingModulesFor(value: Int, units: TimeUnit) {
TODO("Not yet implemented")
}
override fun getComponentSelection(): ComponentSelectionRulesInternal {
TODO("Not yet implemented")
}
override fun componentSelection(
action: Action<in ComponentSelectionRules>
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun getDependencySubstitution(): DependencySubstitutionsInternal {
TODO("Not yet implemented")
}
override fun dependencySubstitution(
action: Action<in DependencySubstitutions>
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun getUseGlobalDependencySubstitutionRules(): Property<Boolean> {
TODO("Not yet implemented")
}
override fun sortArtifacts(sortOrder: org.gradle.api.artifacts.ResolutionStrategy.SortOrder) {
TODO("Not yet implemented")
}
override fun capabilitiesResolution(
action: Action<in CapabilitiesResolution>
): org.gradle.api.artifacts.ResolutionStrategy {
TODO("Not yet implemented")
}
override fun getCapabilitiesResolution(): CapabilitiesResolution {
TODO("Not yet implemented")
}
override fun discardStateRequiredForGraphResolution() {
TODO("Not yet implemented")
}
override fun getCachePolicy(): CachePolicy {
TODO("Not yet implemented")
}
override fun getConflictResolution(): ConflictResolution {
TODO("Not yet implemented")
}
override fun getDependencySubstitutionRule():
ImmutableActionSet<DependencySubstitutionInternal> {
TODO("Not yet implemented")
}
override fun assumeFluidDependencies() {
TODO("Not yet implemented")
}
override fun resolveGraphToDetermineTaskDependencies(): Boolean {
TODO("Not yet implemented")
}
override fun getSortOrder(): org.gradle.api.artifacts.ResolutionStrategy.SortOrder {
TODO("Not yet implemented")
}
override fun copy(): ResolutionStrategyInternal {
TODO("Not yet implemented")
}
override fun setMutationValidator(action: MutationValidator) {
TODO("Not yet implemented")
}
override fun getDependencyLockingProvider(): DependencyLockingProvider {
TODO("Not yet implemented")
}
override fun isDependencyLockingEnabled(): Boolean {
TODO("Not yet implemented")
}
override fun confirmUnlockedConfigurationResolved(configurationName: String) {
TODO("Not yet implemented")
}
override fun getCapabilitiesResolutionRules(): CapabilitiesResolutionInternal {
TODO("Not yet implemented")
}
override fun isFailingOnDynamicVersions(): Boolean {
TODO("Not yet implemented")
}
override fun isFailingOnChangingVersions(): Boolean {
TODO("Not yet implemented")
}
override fun isDependencyVerificationEnabled(): Boolean {
TODO("Not yet implemented")
}
override fun setReturnAllVariants(returnAllVariants: Boolean) {
TODO("Not yet implemented")
}
override fun getReturnAllVariants(): Boolean {
TODO("Not yet implemented")
}
}
| 3
|
Kotlin
|
0
| 8
|
2a1a03df12676ab4adaa4c4d793961d49be0dd32
| 6,713
|
version-catalog-generator
|
Apache License 2.0
|
livingdoc-fixture-converter/src/test/java/org/livingdoc/fixture/converter/common/IntegerConverterTest.kt
|
nicopaul
| 93,719,105
| true
|
{"Kotlin": 33638, "Java": 8950}
|
package org.livingdoc.fixture.converter.common
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.livingdoc.fixture.api.converter.ConversionException
import java.lang.Integer.MAX_VALUE
import java.lang.Integer.MIN_VALUE
import java.util.*
internal class IntegerConverterTest {
val cut = IntegerConverter()
@Test
fun `zero value can be converted`() {
val result = cut.convert("0")
assertThat(result).isEqualTo(0)
}
@Test
fun `smallest integer can be converted`() {
val value = MIN_VALUE.toString()
val result = cut.convert(value)
assertThat(result).isEqualTo(MIN_VALUE)
}
@Test
fun `small integer can be converted`() {
val value = "-10000000"
val result = cut.convert(value)
assertThat(result).isEqualTo(-10000000)
}
@Test
fun `largest integer can be converted`() {
val value = MAX_VALUE.toString()
val result = cut.convert(value)
assertThat(result).isEqualTo(MAX_VALUE)
}
@Test
fun `large integer can be converted`() {
val value = "10000000"
val result = cut.convert(value)
assertThat(result).isEqualTo(10000000)
}
@Test
fun `any integer can be converted`() {
Random().ints(1000)//
.forEach { value ->
val positiveValue = value.toString()
val negativeValue = (-value).toString()
assertThat(cut.convert(positiveValue)).isEqualTo(value)
assertThat(cut.convert(negativeValue)).isEqualTo(-value)
}
}
@Test
fun `leading whitespaces are removed`() {
assertThat(cut.convert(" 1")).isEqualTo(1)
assertThat(cut.convert("\t1")).isEqualTo(1)
assertThat(cut.convert("\n1")).isEqualTo(1)
}
@Test
fun `trailing whitespaces are removed`() {
assertThat(cut.convert("1 ")).isEqualTo(1)
assertThat(cut.convert("1\t")).isEqualTo(1)
assertThat(cut.convert("1\n")).isEqualTo(1)
}
@Test
fun `illegal format throws ConversionException`() {
assertThrows(ConversionException::class.java) { cut.convert("hello world") }
}
}
| 0
|
Kotlin
|
0
| 0
|
f796609092b479b517762362db5a48d02cd5704b
| 2,309
|
livingdoc2
|
Apache License 2.0
|
app/src/main/java/com/nicoapps/cooktime/model/Instruction.kt
|
andremn
| 758,641,451
| false
|
{"Kotlin": 185045}
|
package com.nicoapps.cooktime.model
import java.time.ZonedDateTime
data class Instruction(
val id: Long = 0,
val text: String,
val createdAt: ZonedDateTime = ZonedDateTime.now(),
val lastUpdatedAt: ZonedDateTime? = null
)
| 0
|
Kotlin
|
0
| 0
|
389af6b6dffccd88ddbf4a434a090fa7c1a65e6a
| 240
|
cooktime
|
MIT License
|
randomizer/src/main/java/com/chrisjanusa/randomizer/location_base/LocationUIManager.kt
|
chrisjanusa
| 209,855,968
| false
|
{"Kotlin": 223559}
|
package com.chrisjanusa.randomizer.location_base
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import com.chrisjanusa.base.CommunicationHelper.sendAction
import com.chrisjanusa.randomizer.R
import com.chrisjanusa.base.interfaces.FeatureUIManager
import com.chrisjanusa.base.interfaces.BaseFragmentDetails
import com.chrisjanusa.base.models.RandomizerState
import com.chrisjanusa.base.models.RandomizerViewModel
import com.chrisjanusa.randomizer.RandomizerFragmentDetails
import com.chrisjanusa.randomizer.RandomizerFragment
import com.chrisjanusa.randomizer.location_search.actions.SearchGainFocusAction
import com.google.android.libraries.maps.model.BitmapDescriptor
import com.google.android.libraries.maps.model.BitmapDescriptorFactory
object LocationUIManager : FeatureUIManager {
override fun init(randomizerViewModel: RandomizerViewModel, baseFragmentDetails: BaseFragmentDetails) {
if (baseFragmentDetails is RandomizerFragmentDetails) {
baseFragmentDetails.fragment.run {
baseFragmentDetails.binding.locationContainer.searchCard.currentLocation.setOnClickListener {
sendAction(
SearchGainFocusAction(randomizerViewModel.state.value?.addressSearchString ?: ""),
randomizerViewModel
)
}
}
}
}
override fun render(state: RandomizerState, baseFragmentDetails: BaseFragmentDetails) {
if (baseFragmentDetails is RandomizerFragmentDetails) {
baseFragmentDetails.binding.locationContainer.searchCard.currentText.text = state.locationText
}
}
fun getDefaultMarker(fragment: RandomizerFragment): BitmapDescriptor {
return vectorToBitmap(R.drawable.marker, fragment)
}
private fun vectorToBitmap(@DrawableRes id: Int, fragment: RandomizerFragment): BitmapDescriptor {
val vectorDrawable =
ResourcesCompat.getDrawable(fragment.resources, id, null) ?: return BitmapDescriptorFactory.defaultMarker()
val bitmap = Bitmap.createBitmap(
vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
vectorDrawable.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
}
| 1
|
Kotlin
|
0
| 0
|
cd1bfe507e320d2774869d926fd35bc721d2c218
| 2,517
|
RandomRestaurantKotlin
|
MIT License
|
manager/src/main/java/moe/shizuku/manager/apphider/ShizukuAppHider.kt
|
khang-atg-dev
| 839,114,891
| false
|
{"Kotlin": 347249, "Java": 297278, "C++": 44477, "C": 4332, "CMake": 3138, "AIDL": 2437, "Shell": 2054}
|
package moe.shizuku.manager.apphider
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.IBinder
import android.system.Os
import android.util.Log
import moe.shizuku.manager.R
import moe.shizuku.manager.ShizukuSettings
import rikka.shizuku.Shizuku
import rikka.shizuku.ShizukuBinderWrapper
import rikka.shizuku.ShizukuProvider
import rikka.shizuku.SystemServiceHelper
import java.lang.reflect.Method
class ShizukuAppHider(val context: Context) : BaseAppHider(context) {
private val shizukuRequestCode = 1001
init {
ShizukuProvider.enableMultiProcessSupport(false)
}
override fun hide(pkgNames: Set<String>) {
if (!Shizuku.pingBinder()) {
Log.d(getName(), "Binder not available")
return
}
setAppDisabled(disabled = true, pkgNames = pkgNames)
setAppHidden(hidden = true, pkgNames = pkgNames)
}
override fun show(pkgNames: Set<String>) {
if (!Shizuku.pingBinder()) {
Log.d(getName(), "Binder not available")
return
}
setAppDisabled(disabled = false, pkgNames = pkgNames)
setAppHidden(hidden = false, pkgNames = pkgNames)
}
override fun getName(): String {
return this.javaClass.name
}
override fun tryToActive(listener: ActivationCallbackListener) {
try {
//Check version
if (Shizuku.isPreV11()) {
Log.d(getName(), "checking version: The current version is pre v11!")
listener.onActivationSuccess(
appHider = this.javaClass,
success = false,
msg = context.getString(R.string.unsupported_shizuku_version)
)
return
}
//Check the Shizuku permission
if (Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED) {
if (Shizuku.pingBinder()) {
Log.d(getName(), "tryToActive: Shizuku is available.")
listener.onActivationSuccess(
appHider = this.javaClass,
success = true,
msg = ""
)
return
} else {
Log.d(getName(), "tryToActive: Binder not available.")
listener.onActivationSuccess(
appHider = this.javaClass,
success = false,
msg = context.getString(R.string.shizuku_not_running)
)
return
}
}
//The Shizuku permission is denied forever
if (Shizuku.shouldShowRequestPermissionRationale()) {
Log.d(getName(), "tryToActive: permission is denied.")
listener.onActivationSuccess(
appHider = this.javaClass,
success = false,
msg = context.getString(R.string.shizuku_perrmission_denied)
)
return
}
//Request Shizuku permission
val permissionListener = object : Shizuku.OnRequestPermissionResultListener {
override fun onRequestPermissionResult(requestCode: Int, grantResult: Int) {
when (grantResult) {
PackageManager.PERMISSION_GRANTED -> {
Log.d(getName(), "tryToActive: Permission granted.")
listener.onActivationSuccess(
appHider = this@ShizukuAppHider.javaClass,
success = true,
msg = ""
)
}
else -> {
Log.d(getName(), "tryToActive: Permission denied.")
listener.onActivationSuccess(
appHider = this@ShizukuAppHider.javaClass,
success = false,
msg = context.getString(R.string.shizuku_perrmission_denied)
)
}
}
Shizuku.removeRequestPermissionResultListener(this)
}
}
Shizuku.addRequestPermissionResultListener(permissionListener)
Shizuku.requestPermission(shizukuRequestCode)
ShizukuSettings.setIsOpenOtherActivity(true)
} catch (e: Exception) {
Log.e(getName(), "tryToActive error: ${e.message}")
listener.onActivationSuccess(
appHider = this.javaClass,
success = false,
msg = context.getString(R.string.shizuku_note)
)
}
}
@SuppressLint("PrivateApi")
private fun setAppDisabled(disabled: Boolean, pkgNames: Set<String>) {
val mSetApplicationEnabledSetting: Method?
val iPmInstance: Any?
try {
val iPmClass = Class.forName("android.content.pm.IPackageManager")
val iPmStub = Class.forName("android.content.pm.IPackageManager\$Stub")
val asInterface = iPmStub.getMethod("asInterface", IBinder::class.java)
iPmInstance = asInterface.invoke(
null,
ShizukuBinderWrapper(SystemServiceHelper.getSystemService("package"))
)
mSetApplicationEnabledSetting = iPmClass.getMethod(
"setApplicationEnabledSetting",
String::class.java,
Int::class.java,
Int::class.java,
Int::class.java,
String::class.java
)
} catch (e: Exception) {
Log.e(getName(), "get disabled method: $disabled ${e.message}")
return
}
if (mSetApplicationEnabledSetting != null && iPmInstance != null) {
try {
pkgNames.forEach {
mSetApplicationEnabledSetting.invoke(
iPmInstance,
it,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER.takeIf { disabled }
?: PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
0,
Os.getegid() / 100000,
context.packageName
)
Log.d(getName(), "disabled: $it")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@SuppressLint("PrivateApi")
private fun setAppHidden(hidden: Boolean, pkgNames: Set<String>) {
val mSetApplicationHiddenAppSettingAsUser: Method?
val iPmInstance: Any?
try {
val iPmClass = Class.forName("android.content.pm.IPackageManager")
val iPmStub = Class.forName("android.content.pm.IPackageManager\$Stub")
val asInterface = iPmStub.getMethod("asInterface", IBinder::class.java)
iPmInstance = asInterface.invoke(
null,
ShizukuBinderWrapper(SystemServiceHelper.getSystemService("package"))
)
mSetApplicationHiddenAppSettingAsUser = iPmClass.getMethod(
"setApplicationHiddenSettingAsUser",
String::class.java,
Boolean::class.java,
Int::class.java
)
} catch (e: Exception) {
Log.e(getName(), "get hidden method: $hidden ${e.message}")
return
}
if (mSetApplicationHiddenAppSettingAsUser != null && iPmInstance != null) {
try {
pkgNames.forEach {
mSetApplicationHiddenAppSettingAsUser.invoke(
iPmInstance,
it,
hidden,
Os.getegid() / 100000
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7928086d4c5f0657b2c6ee093c206cb1858c4b85
| 8,207
|
hidden-app-atg
|
Apache License 2.0
|
alcool_gasolina/android/app/src/main/kotlin/br/uninove/alcool_gasolina/MainActivity.kt
|
Leandrors91
| 413,806,223
| true
|
{"Dart": 17815, "HTML": 7712, "Swift": 808, "Kotlin": 256, "Objective-C": 76}
|
package br.uninove.alcool_gasolina
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
f6d41c4dff5376c1730b29cc62e6342b47e39f51
| 131
|
2021-2_terca_manha
|
MIT License
|
app/src/main/java/com/concordium/wallet/data/backend/repository/ProxyRepository.kt
|
Concordium
| 358,250,608
| false
| null |
package com.concordium.wallet.data.backend.repository
import com.concordium.wallet.App
import com.concordium.wallet.core.backend.BackendCallback
import com.concordium.wallet.core.backend.BackendRequest
import com.concordium.wallet.data.cryptolib.CreateTransferOutput
import com.concordium.wallet.data.model.AccountBalance
import com.concordium.wallet.data.model.AccountKeyData
import com.concordium.wallet.data.model.AccountNonce
import com.concordium.wallet.data.model.AccountSubmissionStatus
import com.concordium.wallet.data.model.AccountTransactions
import com.concordium.wallet.data.model.AppSettings
import com.concordium.wallet.data.model.BakerPoolStatus
import com.concordium.wallet.data.model.CIS2Tokens
import com.concordium.wallet.data.model.CIS2TokensBalances
import com.concordium.wallet.data.model.CIS2TokensMetadata
import com.concordium.wallet.data.model.ChainParameters
import com.concordium.wallet.data.model.CredentialWrapper
import com.concordium.wallet.data.model.GlobalParamsWrapper
import com.concordium.wallet.data.model.SubmissionData
import com.concordium.wallet.data.model.TransferCost
import com.concordium.wallet.data.model.TransferSubmissionStatus
import java.math.BigInteger
class ProxyRepository {
private val backend = App.appCore.getProxyBackend()
companion object {
const val SIMPLE_TRANSFER = "simpleTransfer"
const val ENCRYPTED_TRANSFER = "encryptedTransfer"
const val TRANSFER_TO_SECRET = "transferToSecret"
const val TRANSFER_TO_PUBLIC = "transferToPublic"
const val REGISTER_DELEGATION = "registerDelegation"
const val UPDATE_DELEGATION = "updateDelegation"
const val REMOVE_DELEGATION = "removeDelegation"
const val REGISTER_BAKER = "registerBaker"
const val UPDATE_BAKER_STAKE = "updateBakerStake"
const val UPDATE_BAKER_POOL = "updateBakerPool"
const val UPDATE_BAKER_KEYS = "updateBakerKeys"
const val REMOVE_BAKER = "removeBaker"
const val CONFIGURE_BAKER = "configureBaker"
const val UPDATE = "update"
const val CIS_2_TOKEN_BALANCE_MAX_TOKEN_IDS = 20
const val CIS_2_TOKEN_METADATA_MAX_TOKEN_IDS = 20
}
fun submitCredential(
credentialWrapper: CredentialWrapper,
success: (SubmissionData) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<SubmissionData> {
val call = backend.submitCredential(credentialWrapper)
call.enqueue(object : BackendCallback<SubmissionData>() {
override fun onResponseData(response: SubmissionData) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
suspend fun getAccountSubmissionStatusSuspended(submissionId: String) =
backend.accountSubmissionStatusSuspended(submissionId)
fun getAppSettings(
version: Int,
success: (AppSettings) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<AppSettings> {
val call = backend.appSettings("android", version)
call.enqueue(object : BackendCallback<AppSettings>() {
override fun onResponseData(response: AppSettings) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getBakerPool(
bakerId: String,
success: (BakerPoolStatus) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<BakerPoolStatus> {
val call = backend.bakerPool(bakerId)
call.enqueue(object : BackendCallback<BakerPoolStatus>() {
override fun onResponseData(response: BakerPoolStatus) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getAccountSubmissionStatus(
submissionId: String,
success: (AccountSubmissionStatus) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<AccountSubmissionStatus> {
val call = backend.accountSubmissionStatus(submissionId)
call.enqueue(object : BackendCallback<AccountSubmissionStatus>() {
override fun onResponseData(response: AccountSubmissionStatus) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getAccountNonce(
accountAddress: String,
success: (AccountNonce) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<AccountNonce> {
val call = backend.accountNonce(accountAddress)
call.enqueue(object : BackendCallback<AccountNonce>() {
override fun onResponseData(response: AccountNonce) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun submitTransfer(
transfer: CreateTransferOutput,
success: (SubmissionData) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<SubmissionData> {
val call = backend.submitTransfer(transfer)
call.enqueue(object : BackendCallback<SubmissionData>() {
override fun onResponseData(response: SubmissionData) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
suspend fun getTransferSubmissionStatusSuspended(submissionId: String) =
backend.transferSubmissionStatusSuspended(submissionId)
fun getTransferSubmissionStatus(
submissionId: String,
success: (TransferSubmissionStatus) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<TransferSubmissionStatus> {
val call = backend.transferSubmissionStatus(submissionId)
call.enqueue(object : BackendCallback<TransferSubmissionStatus>() {
override fun onResponseData(response: TransferSubmissionStatus) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getTransferCost(
type: String,
memoSize: Int? = null,
amount: BigInteger? = null,
restake: Boolean? = null,
lPool: Boolean? = null,
targetChange: Boolean? = null,
metadataSize: Int? = null,
openStatus: String? = null,
sender: String? = null,
contractIndex: Int? = null,
contractSubindex: Int? = null,
receiveName: String? = null,
parameter: String? = null,
executionNRGBuffer: Int? = null,
success: (TransferCost) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<TransferCost> {
val lPoolArg = if (lPool == true) "lPool" else null
val targetArg = if (targetChange == true) "target" else null
val call = backend.transferCost(
type,
memoSize,
amount?.toString(),
restake,
lPoolArg,
targetArg,
metadataSize,
openStatus,
sender,
contractIndex,
contractSubindex,
receiveName,
parameter,
executionNRGBuffer
)
call.enqueue(object : BackendCallback<TransferCost>() {
override fun onResponseData(response: TransferCost) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getChainParameters(
success: (ChainParameters) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<ChainParameters> {
val call = backend.chainParameters()
call.enqueue(object : BackendCallback<ChainParameters>() {
override fun onResponseData(response: ChainParameters) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
suspend fun getChainParametersSuspended() = backend.chainParametersSuspended()
suspend fun getPassiveDelegationSuspended() = backend.passiveDelegationSuspended()
suspend fun getBakerPoolSuspended(poolId: String) = backend.bakerPoolSuspended(poolId)
suspend fun getAccountBalanceSuspended(accountAddress: String) =
backend.accountBalanceSuspended(accountAddress)
fun getAccountBalance(
accountAddress: String,
success: (AccountBalance) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<AccountBalance> {
val call = backend.accountBalance(accountAddress)
call.enqueue(object : BackendCallback<AccountBalance>() {
override fun onResponseData(response: AccountBalance) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getAccountTransactions(
accountAddress: String,
success: (AccountTransactions) -> Unit,
failure: ((Throwable) -> Unit)?,
order: String? = "desc",
from: Int? = null,
limit: Int? = null,
includeRewards: String? = "all"
): BackendRequest<AccountTransactions> {
val call = backend.accountTransactions(accountAddress, order, from, limit, includeRewards)
call.enqueue(object : BackendCallback<AccountTransactions>() {
override fun onResponseData(response: AccountTransactions) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun requestGTUDrop(
accountAddress: String,
success: (SubmissionData) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<SubmissionData> {
val call = backend.requestGTUDrop(accountAddress)
call.enqueue(object : BackendCallback<SubmissionData>() {
override fun onResponseData(response: SubmissionData) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getIGlobalInfo(
success: (GlobalParamsWrapper) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<GlobalParamsWrapper> {
val call = App.appCore.getProxyBackend().getGlobalInfo()
call.enqueue(object : BackendCallback<GlobalParamsWrapper>() {
override fun onResponseData(response: GlobalParamsWrapper) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
fun getAccountEncryptedKey(
accountAddress: String,
success: (AccountKeyData) -> Unit,
failure: ((Throwable) -> Unit)?
): BackendRequest<AccountKeyData> {
val call = App.appCore.getProxyBackend().getAccountEncryptedKey(accountAddress)
call.enqueue(object : BackendCallback<AccountKeyData>() {
override fun onResponseData(response: AccountKeyData) {
success(response)
}
override fun onFailure(t: Throwable) {
failure?.invoke(t)
}
})
return BackendRequest(
call = call,
success = success,
failure = failure
)
}
suspend fun getCIS2Tokens(
index: String,
subIndex: String,
from: String? = null,
limit: Int? = null,
): CIS2Tokens = backend.cis2Tokens(index, subIndex, from, limit)
/**
* @param tokenIds comma-separated token IDs, but no more than [CIS_2_TOKEN_METADATA_MAX_TOKEN_IDS]
*
* @return metadata items for tokens having it
*/
suspend fun getCIS2TokenMetadataV1(
index: String,
subIndex: String,
tokenIds: String,
): CIS2TokensMetadata = backend.cis2TokenMetadataV1(index, subIndex, tokenIds)
/**
* @param tokenIds comma-separated token IDs, but no more than [CIS_2_TOKEN_BALANCE_MAX_TOKEN_IDS]
* @return balance items for tokens having it
*/
suspend fun getCIS2TokenBalanceV1(
index: String,
subIndex: String,
accountAddress: String,
tokenIds: String,
): CIS2TokensBalances = backend.cis2TokenBalanceV1(index, subIndex, accountAddress, tokenIds)
}
| 17
| null |
3
| 12
|
41f9755247c94f17254b3ddcd0a18696ba0a07dc
| 14,376
|
concordium-reference-wallet-android
|
Apache License 2.0
|
src/test/kotlin/org/opensearch/indexmanagement/indexstatemanagement/transport/action/indexpolicy/IndexPolicyResponseTests.kt
|
mch2
| 400,646,884
| true
|
{"Kotlin": 1908596, "Python": 1396}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.transport.action.indexpolicy
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.Policy
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.State
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.action.IndexPriorityActionConfig
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomErrorNotification
import org.opensearch.common.io.stream.BytesStreamOutput
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.rest.RestStatus
import org.opensearch.test.OpenSearchTestCase
import java.time.Instant
import java.time.temporal.ChronoUnit
class IndexPolicyResponseTests : OpenSearchTestCase() {
fun `test index policy response index priority action`() {
val id = "id"
val version: Long = 1
val primaryTerm: Long = 123
val seqNo: Long = 456
val policyID = "policyID"
val actionConfig = IndexPriorityActionConfig(50, 0)
val states = listOf(State(name = "SetPriorityState", actions = listOf(actionConfig), transitions = listOf()))
val policy = Policy(
id = policyID,
description = "description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
val status = RestStatus.CREATED
val res = IndexPolicyResponse(id, version, primaryTerm, seqNo, policy, status)
val out = BytesStreamOutput()
res.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newRes = IndexPolicyResponse(sin)
assertEquals(id, newRes.id)
assertEquals(version, newRes.version)
assertEquals(primaryTerm, newRes.primaryTerm)
assertEquals(seqNo, newRes.seqNo)
assertEquals(policy, newRes.policy)
assertEquals(status, newRes.status)
}
}
| 0
| null |
0
| 0
|
5c41b04fb21ec7ed026b7a186ba3a5a3248b2403
| 3,044
|
opensearch-project-index-management
|
Apache License 2.0
|
app/src/main/java/com/example/simplecleanarchitecture/users/usecase/user/UserGetAttachmentUseCase.kt
|
tom2048
| 350,885,111
| false
| null |
package com.example.simplecleanarchitecture.users.usecase.user
import com.example.simplecleanarchitecture.core.repository.AssetsRepository
import io.reactivex.rxjava3.core.Single
interface UserGetAttachmentUseCase : (String) -> Single<ByteArray>
class UserGetAttachmentUseCaseDefault(
private val assetsRepository: AssetsRepository
) : UserGetAttachmentUseCase {
override fun invoke(key: String): Single<ByteArray> =
assetsRepository.getImage(key)
}
| 0
|
Kotlin
|
0
| 1
|
bf273b8f7a4418505e5a382cfa5940cc98cceea9
| 470
|
simple-clean-architecture-android-example
|
MIT License
|
shoring/desk/src/main/kotlin/com/panopset/marin/apps/fw/FxFunctionLoader.kt
|
panopset
| 752,122,553
| false
|
{"Kotlin": 597894, "Java": 26106, "Shell": 9716, "CSS": 4623, "JavaScript": 4084, "Batchfile": 2807, "HTML": 1317}
|
package com.panopset.marin.apps.fw
import com.panopset.flywheel.Flywheel.Companion.defineAllowedScriptCalls
import com.panopset.flywheel.FlywheelFunction
import com.panopset.flywheel.ReflectionInvoker.Companion.all
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.scene.control.ComboBox
import javafx.scene.control.TextArea
import java.util.*
class FxFunctionLoader {
fun loadUpFunctions(cbFunctions: ComboBox<FlywheelFunction>, fwTemplate: TextArea) {
populateDropdown(cbFunctions)
wireUpEvents(cbFunctions, fwTemplate)
}
private fun wireUpEvents(cbFunctions: ComboBox<FlywheelFunction>, fwTemplate: TextArea) {
cbFunctions.onAction = EventHandler { event: ActionEvent? -> fwTemplate.appendText(cbFunctions.value.example) }
}
private fun populateDropdown(cbFunctions: ComboBox<FlywheelFunction>) {
defineAllowedScriptCalls()
cbFunctions.items.add(FlywheelFunction())
val allBut_dt: MutableCollection<FlywheelFunction> = Collections.synchronizedSortedSet(TreeSet())
for (ff in all) {
if (!"dt".equals(ff.key, ignoreCase = true)) {
allBut_dt.add(ff)
}
}
cbFunctions.items.addAll(allBut_dt)
}
}
| 0
|
Kotlin
|
0
| 0
|
94b3d3bfa9fb74e551b178932125f51b44c30b9a
| 1,264
|
pan
|
MIT License
|
kotlin-csstype/src/main/generated/csstype/WillChange.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
// language=JavaScript
@JsName("""(/*union*/{contents: 'contents', scrollPosition: 'scroll-position'}/*union*/)""")
sealed external interface WillChange {
companion object {
val contents: WillChange
val scrollPosition: WillChange
}
}
| 12
|
Kotlin
|
6
| 983
|
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 418
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/tangwy/apidemokt/framework/notification/NotificationAPI.kt
|
troytang
| 144,459,140
| false
| null |
package com.tangwy.apidemokt.framework.notification
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import android.support.v4.app.TaskStackBuilder
import android.widget.RemoteViews
import com.tangwy.apidemokt.R
import com.tangwy.apidemokt.ui.notification.NotificationActivity
import com.tangwy.apidemokt.ui.notification.NotificationSpecialActivity
import com.tangwy.apidemokt.util.Device
import java.util.*
class NotificationAPI {
companion object {
@SuppressLint("NewApi")
fun notify(context: Context, title: String, content: String) {
val id = Random().nextInt(1000)
val channelId = "channelId$id"
val channelName = "channelName"
var builder: NotificationCompat.Builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
// 创建一个目标页面的 Intent
var resultIntent = Intent(context, NotificationActivity::class.java)
var stackBuilder: TaskStackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(NotificationActivity::class.java)
stackBuilder.addNextIntent(resultIntent)
// 包裹 Intent
var pendingIntent: PendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)!!
builder.setContentIntent(pendingIntent)
var notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, builder.build())
}
@SuppressLint("NewApi")
fun notifyWithStyle(context: Context, title: String, content: String) {
val id = Random().nextInt(1000)
val channelId = "channel$id"
val channelName = "channelName"
var builder: NotificationCompat.Builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
// 扩展布局
var inboxStyle = NotificationCompat.InboxStyle()
var events = arrayListOf<String>()
events.add("First")
events.add("Second")
events.add("Third")
inboxStyle.setBigContentTitle("Big content title")
for (event in events) {
inboxStyle.addLine(event)
}
builder.setStyle(inboxStyle)
// 创建跳转页面的 Intent
val resultIntent = Intent(context, NotificationActivity::class.java)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(NotificationActivity::class.java)
stackBuilder.addNextIntent(resultIntent)
// 包裹 Intent
val pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent)
var notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, builder.build())
}
@SuppressLint("NewApi")
fun notifyUpdate(context: Context, title: String, content: String, id: Int) {
val channelId = "channel$id"
val channelName = "channelName"
val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, channelId)
.setAutoCancel(false)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content)
// 创建一个跳转页面的 Intent
val intent = Intent(context, NotificationActivity::class.java)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(NotificationActivity::class.java)
stackBuilder.addNextIntent(intent)
// 包裹 Intent
val pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, builder.build())
}
@SuppressLint("NewApi")
fun notifySpecial(context: Context, title: String, content: String) {
val id = Random().nextInt(1000)
val chanelId = "channel$id"
val channelName = "channelName"
val builder = NotificationCompat.Builder(context, chanelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(false)
.setContentTitle(title)
.setContentText(content)
val intent = Intent(context, NotificationSpecialActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(chanelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, builder.build())
}
@SuppressLint("NewApi")
fun notifyProgress(context: Context, title: String, content: String) {
val id = Random().nextInt(1000)
val channelId = "channel$id"
val channelName = "channelName"
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(false)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
// 起线程模拟异步
Thread(Runnable {
// 开始进度
for (i in 0..100) {
builder.setProgress(100, i, false)
notificationManager.notify(id, builder.build())
Thread.sleep(1000)
}
// 结束,隐藏进度条
builder.setProgress(0, 0, false)
builder.setContentText("Completed!")
notificationManager.notify(id, builder.build())
}).start()
}
@SuppressLint("NewApi")
fun notifyActivityIndicator(context: Context, title: String, content: String) {
val id = Random().nextInt(1000)
val channelId = "channel$id"
val channelName = "channelName"
val buidler = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(false)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, buidler.build())
// 创建一个线程模拟
Thread(Runnable {
for (i in 0..100) {
buidler.setProgress(0, 0, true)
notificationManager.notify(id, buidler.build())
Thread.sleep(1000)
}
// 结束
buidler.setProgress(0, 0, false)
buidler.setContentText("Completed!")
notificationManager.notify(id, buidler.build())
}).start()
}
@SuppressLint("NewApi")
fun notifyCustom(context: Context, packageName: String, resId: Int) {
val customView = RemoteViews(packageName, resId)
val id = Random().nextInt(1000)
val channelId = "channel$id"
val channelName = "channelName"
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContent(customView)
.setAutoCancel(false)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Device.afterO()) {
val nc = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(nc)
}
notificationManager.notify(id, builder.build())
}
}
}
| 0
|
Kotlin
|
0
| 2
|
b58c94cb57f0d9f0c05fccefd81f6e96557b43f6
| 10,485
|
ApiDemoKt
|
Apache License 2.0
|
buildSrc/src/main/kotlin/Config.kt
|
SRGSSR
| 469,671,723
| false
|
{"Kotlin": 139247, "Java": 10619, "Shell": 555}
|
object Config {
const val compileSdk = 33
const val targetSdk = 33
const val minSdk = 21
const val major = 0
const val minor = 6
const val patch = 1
const val versionName = "$major.$minor.$patch"
const val maven_group = "ch.srg.data.provider"
}
| 4
|
Kotlin
|
0
| 0
|
f28db63b568478a81b75163605d8482456d1831e
| 279
|
srgdataprovider-android
|
MIT License
|
app/src/main/kotlin/batect/cli/CommandLineOptions.kt
|
HYDPublic
| 119,497,078
| true
|
{"Kotlin": 988909, "Python": 3315, "Shell": 2655, "HTML": 400, "Java": 256}
|
/*
Copyright 2017-2018 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.cli
import batect.cli.options.LevelOfParallelismDefaultValueProvider
import batect.logging.FileLogSink
import batect.logging.LogSink
import batect.logging.NullLogSink
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.singleton
import java.nio.file.FileSystem
data class CommandLineOptions(
val showHelp: Boolean = false,
val showVersionInfo: Boolean = false,
val listTasks: Boolean = false,
val configurationFileName: String = "batect.yml",
val logFileName: String? = null,
val forceSimpleOutputMode: Boolean = false,
val forceQuietOutputMode: Boolean = false,
val disableColorOutput: Boolean = false,
val disableUpdateNotification: Boolean = false,
val levelOfParallelism: Int = LevelOfParallelismDefaultValueProvider.value,
val disableCleanupAfterFailure: Boolean = false,
val dontPropagateProxyEnvironmentVariables: Boolean = false,
val taskName: String? = null,
val additionalTaskCommandArguments: Iterable<String> = emptyList()
) {
fun extend(originalKodein: Kodein): Kodein = Kodein {
extend(originalKodein)
bind<CommandLineOptions>() with instance(this@CommandLineOptions)
bind<LogSink>() with singleton {
if (logFileName == null) {
NullLogSink()
} else {
val fileSystem = instance<FileSystem>()
FileLogSink(fileSystem.getPath(logFileName), instance(), instance())
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
bebfc745e814168ea6ffce49ffe5e8b221fb96bd
| 2,188
|
batect
|
Apache License 2.0
|
common/iteration/src/test/kotlin/com/curtislb/adventofcode/common/iteration/PermutationsTest.kt
|
curtislb
| 226,797,689
| false
|
{"Kotlin": 2230363}
|
package com.curtislb.adventofcode.common.iteration
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
/**
* Tests the [permutations] extension function.
*/
class PermutationsTest {
@Test
fun permutations_emptyList() {
val list = emptyList<Any>()
assertThat(list.permutations().toList()).isEmpty()
}
@Test
fun permutations_singletonList() {
val list = listOf("foo")
assertThat(list.permutations().toList()).containsExactly(listOf("foo"))
}
@Test
fun permutations_twoElementList_noDuplicates() {
val list = listOf("foo", "bar")
assertThat(list.permutations().toList())
.containsExactlyInAnyOrder(listOf("foo", "bar"), listOf("bar", "foo"))
}
@Test
fun permutations_twoElementList_withDuplicates() {
val list = listOf("foo", "foo")
assertThat(list.permutations().toList())
.containsExactlyInAnyOrder(listOf("foo", "foo"), listOf("foo", "foo"))
}
@Test
fun permutations_threeElementList_noDuplicates() {
val list = listOf("foo", "bar", "baz")
assertThat(list.permutations().toList()).containsExactlyInAnyOrder(
listOf("foo", "bar", "baz"),
listOf("foo", "baz", "bar"),
listOf("bar", "foo", "baz"),
listOf("bar", "baz", "foo"),
listOf("baz", "foo", "bar"),
listOf("baz", "bar", "foo")
)
}
@Test
fun permutations_threeElementList_withDuplicates() {
val list = listOf("foo", "bar", "foo")
assertThat(list.permutations().toList()).containsExactlyInAnyOrder(
listOf("foo", "bar", "foo"),
listOf("foo", "foo", "bar"),
listOf("bar", "foo", "foo"),
listOf("bar", "foo", "foo"),
listOf("foo", "foo", "bar"),
listOf("foo", "bar", "foo")
)
}
@Test
fun permutations_fourElementList_noDuplicates() {
val list = listOf("foo", "bar", "baz", "qux")
assertThat(list.permutations().toList()).containsExactlyInAnyOrder(
listOf("foo", "bar", "baz", "qux"),
listOf("foo", "bar", "qux", "baz"),
listOf("foo", "qux", "bar", "baz"),
listOf("qux", "foo", "bar", "baz"),
listOf("foo", "baz", "bar", "qux"),
listOf("foo", "baz", "qux", "bar"),
listOf("foo", "qux", "baz", "bar"),
listOf("qux", "foo", "baz", "bar"),
listOf("bar", "foo", "baz", "qux"),
listOf("bar", "foo", "qux", "baz"),
listOf("bar", "qux", "foo", "baz"),
listOf("qux", "bar", "foo", "baz"),
listOf("bar", "baz", "foo", "qux"),
listOf("bar", "baz", "qux", "foo"),
listOf("bar", "qux", "baz", "foo"),
listOf("qux", "bar", "baz", "foo"),
listOf("baz", "foo", "bar", "qux"),
listOf("baz", "foo", "qux", "bar"),
listOf("baz", "qux", "foo", "bar"),
listOf("qux", "baz", "foo", "bar"),
listOf("baz", "bar", "foo", "qux"),
listOf("baz", "bar", "qux", "foo"),
listOf("baz", "qux", "bar", "foo"),
listOf("qux", "baz", "bar", "foo"),
)
}
@Test
fun permutations_fourElementList_withDuplicates() {
val list = listOf("foo", "foo", "bar", "bar")
assertThat(list.permutations().toList()).containsExactlyInAnyOrder(
listOf("foo", "foo", "bar", "bar"),
listOf("foo", "foo", "bar", "bar"),
listOf("foo", "bar", "foo", "bar"),
listOf("bar", "foo", "foo", "bar"),
listOf("foo", "bar", "foo", "bar"),
listOf("foo", "bar", "bar", "foo"),
listOf("foo", "bar", "bar", "foo"),
listOf("bar", "foo", "bar", "foo"),
listOf("foo", "foo", "bar", "bar"),
listOf("foo", "foo", "bar", "bar"),
listOf("foo", "bar", "foo", "bar"),
listOf("bar", "foo", "foo", "bar"),
listOf("foo", "bar", "foo", "bar"),
listOf("foo", "bar", "bar", "foo"),
listOf("foo", "bar", "bar", "foo"),
listOf("bar", "foo", "bar", "foo"),
listOf("bar", "foo", "foo", "bar"),
listOf("bar", "foo", "bar", "foo"),
listOf("bar", "bar", "foo", "foo"),
listOf("bar", "bar", "foo", "foo"),
listOf("bar", "foo", "foo", "bar"),
listOf("bar", "foo", "bar", "foo"),
listOf("bar", "bar", "foo", "foo"),
listOf("bar", "bar", "foo", "foo"),
)
}
}
| 0
|
Kotlin
|
1
| 1
|
06ddf047ea59b1383afd4596e2bf2607d750a324
| 4,651
|
AdventOfCode
|
MIT License
|
app/src/main/java/au/edu/utas/zhe4/babytracker/presentation/record/TimePickerFragment.kt
|
ShanQincheng
| 622,925,577
| false
| null |
package au.edu.utas.zhe4.babytracker.presentation.record
import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.text.format.DateFormat
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment
import java.util.Calendar
class TimePickerFragment(setTime: (hour: Int, minute: Int) -> Unit) : DialogFragment(), TimePickerDialog.OnTimeSetListener {
private val setTime = setTime
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the current time as the default values for the picker
val c = Calendar.getInstance()
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
}
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
setTime(hourOfDay, minute)
}
}
| 0
|
Kotlin
|
0
| 0
|
44ce04d21b6a65f89d4f61910f1bf1fe17f6a21f
| 1,010
|
BabyTracker
|
Apache License 2.0
|
app/src/androidTest/java/com/praveen/astro/utils/AstroFakeRepository.kt
|
praveenrajput
| 371,303,894
| false
|
{"Kotlin": 60155}
|
package com.praveen.astro.utils
import com.praveen.astro.data.repository.AstrosRepositoryInterface
import com.praveen.astro.models.IssNow
import com.praveen.astro.models.IssPosition
import com.praveen.astro.models.People
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
class AstroFakeRepository : AstrosRepositoryInterface {
val astros = listOf(
People("Test Craft", "Test Name"),
People("Test Craft1", "Test Name1")
)
val issPosition = IssNow(
issPosition = IssPosition("15.15", "30.30")
)
override fun getIssNow(): Flow<IssNow> {
return flowOf(issPosition)
}
override fun getPeopleWithName(astroName: String): Flow<People> {
return flowOf(astros.find { it.name == astroName } ?: People())
}
override fun getPeople(): Flow<List<People>> {
return flowOf(astros)
}
override suspend fun refreshPeople() {
// no implementation needed
}
override suspend fun refreshIss() {
// no implementation needed
}
}
| 0
|
Kotlin
|
0
| 2
|
aa4d668c9ea8fb3c906b263792902a910f07ede7
| 1,055
|
Astro
|
Apache License 2.0
|
src/main/kotlin/io/pivotal/trilogy/parsing/GenericStringTestCaseParser.kt
|
louishust
| 122,236,143
| true
|
{"Kotlin": 210685, "PLSQL": 9831, "Shell": 6958, "PLpgSQL": 371}
|
package io.pivotal.trilogy.parsing
import io.pivotal.trilogy.i18n.MessageCreator
import io.pivotal.trilogy.parsing.exceptions.test.BaseParseException
import io.pivotal.trilogy.parsing.exceptions.testcase.InvalidFormat
import io.pivotal.trilogy.testcase.GenericTrilogyTest
import io.pivotal.trilogy.testcase.GenericTrilogyTestCase
import io.pivotal.trilogy.testcase.MalformedTrilogyTest
import io.pivotal.trilogy.testcase.TestCaseFixtures
class GenericStringTestCaseParser(testCaseBody: String) : BaseStringTestCaseParser(testCaseBody) {
init {
validate()
}
override fun getTestCase(): GenericTrilogyTestCase {
return GenericTrilogyTestCase(parseDescription(), parseTests(), parseTestHooks(), malformedTests())
}
private fun malformedTests(): List<MalformedTrilogyTest> {
return testStrings.map {
try {
GenericStringTestParser(it).getTest()
null
} catch (e: BaseParseException) {
MalformedTrilogyTest(e.testName, e.localizedMessage)
}
}.filterNotNull()
}
private fun parseTestHooks(): TestCaseFixtures {
return TestCaseFixtures(
beforeEachTest = parseHookSection("BEFORE EACH TEST"),
afterEachTest = parseHookSection("AFTER EACH TEST"),
beforeAll = parseHookSection("BEFORE ALL"),
afterAll = parseHookSection("AFTER ALL")
)
}
override fun validate() {
if (testCaseBody.hasInvalidHeader()) throw InvalidFormat(MessageCreator.getI18nMessage("testCaseParser.errors.malformedHeader"))
}
private fun String.hasValidHeader(): Boolean = this.contains(Regex("^# TEST CASE\\s*$", RegexOption.MULTILINE))
private fun String.hasInvalidHeader() = !this.hasValidHeader()
private fun parseTests(): List<GenericTrilogyTest> {
return testStrings.map {
try {
GenericStringTestParser(it).getTest()
} catch (e: BaseParseException) {
null
}
}.filterNotNull()
}
}
| 0
|
Kotlin
|
0
| 0
|
d578f76bc096649406a00751c2c7536182daa0a5
| 2,093
|
trilogy
|
MIT License
|
plugins/kotlin/compiler-reference-index/tests/testData/compilerIndex/properties/fromObject/nestedObject/staticExtensionVariable/Write.kt
|
ingokegel
| 72,937,917
| true
| null |
package one.two
fun write() {
with(KotlinObject.Nested) {
42.staticExtensionVariable = 3
}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 109
|
intellij-community
|
Apache License 2.0
|
zoomimage-view/src/main/java/com/github/panpf/zoomimage/view/internal/ViewPlatformUtils.kt
|
panpf
| 647,222,866
| false
| null |
package com.github.panpf.zoomimage.view.internal
import android.graphics.Rect
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView.ScaleType
import androidx.core.view.ViewCompat
import com.github.panpf.zoomimage.core.IntRectCompat
import com.github.panpf.zoomimage.core.IntSizeCompat
import com.github.panpf.zoomimage.core.ScaleFactorCompat
import com.github.panpf.zoomimage.core.times
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
internal fun requiredMainThread() {
check(Looper.myLooper() == Looper.getMainLooper()) {
"This method must be executed in the UI thread"
}
}
internal fun requiredWorkThread() {
check(Looper.myLooper() != Looper.getMainLooper()) {
"This method must be executed in the work thread"
}
}
internal val View.isAttachedToWindowCompat: Boolean
get() = ViewCompat.isAttachedToWindow(this)
internal fun getPointerIndex(action: Int): Int {
return action and MotionEvent.ACTION_POINTER_INDEX_MASK shr MotionEvent.ACTION_POINTER_INDEX_SHIFT
}
val ZeroRect = Rect(0, 0, 0, 0)
internal fun IntSizeCompat.times(scale: Float): IntSizeCompat =
IntSizeCompat(
(this.width * scale).roundToInt(),
(this.height * scale).roundToInt()
)
internal fun Rect.scale(scale: Float): Rect {
return Rect(
left = (left * scale).roundToInt(),
top = (top * scale).roundToInt(),
right = (right * scale).roundToInt(),
bottom = (bottom * scale).roundToInt()
)
}
fun Rect(left: Int, top: Int, right: Int, bottom: Int): Rect {
return Rect(left, top, right, bottom)
}
internal fun Rect.toIntRectCompat(): IntRectCompat {
return IntRectCompat(left, top, right, bottom)
}
internal fun ScaleType.computeScaleFactor(
srcSize: IntSizeCompat,
dstSize: IntSizeCompat
): ScaleFactorCompat {
val widthScale = dstSize.width / srcSize.width.toFloat()
val heightScale = dstSize.height / srcSize.height.toFloat()
val fillMaxDimension = max(widthScale, heightScale)
val fillMinDimension = min(widthScale, heightScale)
return when (this) {
ScaleType.CENTER -> ScaleFactorCompat(scaleX = 1.0f, scaleY = 1.0f)
ScaleType.CENTER_CROP -> {
ScaleFactorCompat(scaleX = fillMaxDimension, scaleY = fillMaxDimension)
}
ScaleType.CENTER_INSIDE -> {
if (srcSize.width <= dstSize.width && srcSize.height <= dstSize.height) {
ScaleFactorCompat(scaleX = 1.0f, scaleY = 1.0f)
} else {
ScaleFactorCompat(scaleX = fillMinDimension, scaleY = fillMinDimension)
}
}
ScaleType.FIT_START,
ScaleType.FIT_CENTER,
ScaleType.FIT_END -> {
ScaleFactorCompat(scaleX = fillMinDimension, scaleY = fillMinDimension)
}
ScaleType.FIT_XY -> {
ScaleFactorCompat(scaleX = widthScale, scaleY = heightScale)
}
ScaleType.MATRIX -> ScaleFactorCompat(1.0f, 1.0f)
else -> ScaleFactorCompat(scaleX = 1.0f, scaleY = 1.0f)
}
}
internal fun ScaleType.isStart(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.MATRIX
|| this == ScaleType.FIT_XY
|| (this == ScaleType.FIT_START && scaledSrcSize.width < dstSize.width)
}
internal fun ScaleType.isHorizontalCenter(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.CENTER
|| this == ScaleType.CENTER_CROP
|| this == ScaleType.CENTER_INSIDE
|| this == ScaleType.FIT_CENTER
|| (this == ScaleType.FIT_START && scaledSrcSize.width >= dstSize.width)
|| (this == ScaleType.FIT_END && scaledSrcSize.width >= dstSize.width)
}
internal fun ScaleType.isCenter(
@Suppress("UNUSED_PARAMETER") srcSize: IntSizeCompat,
@Suppress("UNUSED_PARAMETER") dstSize: IntSizeCompat
): Boolean =
this == ScaleType.CENTER
|| this == ScaleType.CENTER_CROP
|| this == ScaleType.CENTER_INSIDE
|| this == ScaleType.FIT_CENTER
internal fun ScaleType.isEnd(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.FIT_END && scaledSrcSize.width < dstSize.width
}
internal fun ScaleType.isTop(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.MATRIX
|| this == ScaleType.FIT_XY
|| (this == ScaleType.FIT_START && scaledSrcSize.height < dstSize.height)
}
internal fun ScaleType.isVerticalCenter(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.CENTER
|| this == ScaleType.CENTER_CROP
|| this == ScaleType.CENTER_INSIDE
|| this == ScaleType.FIT_CENTER
|| (this == ScaleType.FIT_START && scaledSrcSize.height >= dstSize.height)
|| (this == ScaleType.FIT_END && scaledSrcSize.height >= dstSize.height)
}
internal fun ScaleType.isBottom(srcSize: IntSizeCompat, dstSize: IntSizeCompat): Boolean {
val scaledSrcSize = srcSize.times(computeScaleFactor(srcSize = srcSize, dstSize = dstSize))
return this == ScaleType.FIT_END && scaledSrcSize.height < dstSize.height
}
| 0
|
Kotlin
|
0
| 3
|
a6814e1fc8a84946d8bad0cf41406519197784eb
| 5,753
|
zoomimage
|
Apache License 2.0
|
server/src/main/kotlin/net/azisaba/api/server/resources/Store.kt
|
AzisabaNetwork
| 510,787,122
| false
|
{"Kotlin": 208961}
|
package net.azisaba.api.server.resources
import com.stripe.model.Event
import com.stripe.model.checkout.Session
import com.stripe.net.ApiResource
import io.ktor.http.HttpStatusCode
import io.ktor.resources.Resource
import io.ktor.server.application.ApplicationCall
import io.ktor.server.application.call
import io.ktor.server.request.header
import io.ktor.server.request.receiveText
import io.ktor.util.pipeline.PipelineContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import net.azisaba.api.data.IProduct
import net.azisaba.api.data.Product
import net.azisaba.api.data.PurchaseData
import net.azisaba.api.data.SaraProduct
import net.azisaba.api.server.DatabaseManager
import net.azisaba.api.server.RedisManager
import net.azisaba.api.server.ServerConfig
import net.azisaba.api.server.schemas.AzisabaAPI
import net.azisaba.api.server.schemas.LuckPerms
import net.azisaba.api.server.schemas.SpicyAzisaBan
import net.azisaba.api.server.storage.PersistentDataStore
import net.azisaba.api.server.util.StripeUtil
import net.azisaba.api.server.util.Util
import net.azisaba.api.util.JSON
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
import kotlin.collections.set
@Serializable
@Resource("/store")
class Store {
companion object {
private val ranks = listOf("100000000", "100000", "50000", "10000", "5000", "2000", "1000", "500", "100")
fun getAllProducts() = transaction(DatabaseManager.azisabaApi) {
AzisabaAPI.Product.all().filter { !it.hidden }.map {
mapOf(
"id" to it.id.value,
"name" to it.name,
"description" to it.description,
"price" to it.price,
"image_url" to it.imageUrl,
"tags" to it.tags,
"hidden" to it.hidden,
"price_id" to it.priceId,
)
} to
AzisabaAPI.SaraProduct.all().filter { !it.hidden }.map {
mapOf(
"id" to it.id.value,
"name" to it.name,
"description" to it.description,
"price" to it.price,
"image_url" to it.imageUrl,
"hidden" to it.hidden,
"product_id" to it.productId,
)
}
}
fun getHighestSara(name: String): Int? {
val uuid = SpicyAzisaBan.Players.getIdByUsername(name) ?: UUID(0, 0)
return transaction(DatabaseManager.luckPerms) {
val groups = LuckPerms.UserPermissions.getGroupsForPlayer(uuid).map {
it.permission.substringAfter("group.").substringAfter("hide").substringBefore("yen")
}
if (groups.isEmpty()) return@transaction null
groups.firstOrNull { it in ranks }?.toInt() ?: return@transaction 0
}
}
fun hasGamingSara(name: String): Boolean {
val uuid = SpicyAzisaBan.Players.getIdByUsername(name) ?: UUID(0, 0)
return transaction(DatabaseManager.luckPerms) {
val groups = LuckPerms.UserPermissions.getGroupsForPlayer(uuid).map {
it.permission.substringAfter("group.").substringAfter("hide")
}
if (groups.isEmpty()) return@transaction false
return@transaction groups.any { it == "gamingsara" || it == "changegamingsara" }
}
}
}
@Serializable
@Resource("products")
data class Products(
@Suppress("unused")
val parent: Store,
): RequestHandler() {
override suspend fun PipelineContext<Unit, ApplicationCall>.handleRequest() {
val (products, saraProducts) = getAllProducts()
call.respondJson(
mapOf(
"products" to products,
"sara_products" to saraProducts,
)
)
}
}
@Serializable
@Resource("pay")
data class Pay(
@Suppress("unused")
val parent: Store,
): RequestHandler() {
override suspend fun PipelineContext<Unit, ApplicationCall>.handleRequest() {
val referer = call.request.header("Referer")
if (referer == null || (!referer.startsWith("https://newstore.azisaba.net") && !referer.startsWith("http://localhost:"))) {
return call.respondJson(mapOf("error" to "invalid_referer"), status = HttpStatusCode.BadRequest)
}
val body = JSON.parseToJsonElement(call.receiveText()).jsonObject
val name = body["name"]!!.jsonPrimitive.content
val uuid = SpicyAzisaBan.Players.getIdByUsername(name)
if (uuid == null) {
return call.respondJson(mapOf("error" to "name_not_found"), status = HttpStatusCode.BadRequest)
}
val highestSara = getHighestSara(name) ?: return call.respondJson(mapOf("error" to "name_not_found"), status = HttpStatusCode.BadRequest)
val (products, saraProducts) = getAllProducts()
val receivedProductIds = body["products"]!!.jsonArray.map { it.jsonPrimitive.long }
if (receivedProductIds.contains(ServerConfig.instance.stripe.gamingSaraId) && hasGamingSara(name)) {
return call.respondJson(mapOf("error" to "already_has_gaming_sara"), status = HttpStatusCode.BadRequest)
}
val receivedSaraProductIds = body["sara_products"]!!.jsonArray.map { it.jsonPrimitive.long }
val productsToBuy = products.filter { it["id"] in receivedProductIds }
val saraProductsToBuy = saraProducts.filter { it["id"] in receivedSaraProductIds }
val validSaraProducts = saraProductsToBuy.filter { (it["price"] as Int) > highestSara }
if (receivedSaraProductIds.size != validSaraProducts.size) {
return call.respondJson(mapOf("error" to "invalid_sara"), status = HttpStatusCode.BadRequest)
}
if (validSaraProducts.size > 1) {
return call.respondJson(mapOf("error" to "too_many_sara"), status = HttpStatusCode.BadRequest)
}
// flatten products (merge multiple product A's into one)
val productMap = productsToBuy.groupBy { it["price_id"] as String }.mapValues { it.value.size.toLong() }
val saraPrice = validSaraProducts.firstOrNull()?.get("price") as Int?
val session = StripeUtil.createCheckoutSession(referer, productMap, validSaraProducts.firstOrNull()?.get("product_id") as String?, saraPrice, highestSara)
val persistentData = mutableListOf<IProduct>()
persistentData += productsToBuy.map { Product(uuid, it["id"] as Long) }
if (saraPrice != null) {
persistentData += SaraProduct(uuid, saraPrice)
}
PersistentDataStore.getListContainer<IProduct>().data["session_${session.id}"] = persistentData
call.respondJson(mapOf("url" to session.url))
}
}
@Serializable
@Resource("webhook")
data class Webhook(
@Suppress("unused")
val parent: Store,
): RequestHandler() {
override suspend fun PipelineContext<Unit, ApplicationCall>.handleRequest() {
val payload = call.receiveText()
var event = ApiResource.GSON.fromJson(payload, Event::class.java)
if (ServerConfig.instance.stripe.webhookSecret.isNotBlank()) {
if (call.request.header("Stripe-Signature") != null) {
val signature = call.request.header("Stripe-Signature")!!
event = com.stripe.net.Webhook.constructEvent(payload, signature, ServerConfig.instance.stripe.webhookSecret)
} else {
call.respondJson(mapOf("error" to "missing signature"), status = HttpStatusCode.BadRequest)
return
}
}
val stripeObject = if (event.dataObjectDeserializer.`object`?.isPresent == true) {
event.dataObjectDeserializer.`object`.get()
} else {
call.respondJson(mapOf("error" to "could not deserialize object"), status = HttpStatusCode.BadRequest)
return
}
if (event.type == "checkout.session.completed") {
stripeObject as Session
Util.sendDiscordWebhookAsync(ServerConfig.instance.stripe.discordNotifyUrl, null, """
`${stripeObject.customerDetails.email}` が ${stripeObject.amountTotal} ${stripeObject.currency.uppercase()} の支払いが完了しました。
Checkout Session ID: `${stripeObject.id}`
Payment Intent ID: [`${stripeObject.paymentIntent}`](https://dashboard.stripe.com/payments/${stripeObject.paymentIntent})
""".trimIndent())
RedisManager.pool.resource.use { jedis ->
var uuid: UUID? = null
PersistentDataStore.getListContainer<IProduct>().data["session_${stripeObject.id}"]?.forEach { prod ->
uuid = prod.uuid
if (!ServerConfig.instance.stripe.testMode) {
jedis.publish(
"azisaba-api:store:purchase-item",
JSON.encodeToString(IProduct.serializer(), prod)
)
}
}
if (uuid != null) {
Util.sendDiscordWebhookAsync(ServerConfig.instance.stripe.discordNotifyUrl, null, "プレイヤーUUID: $uuid")
jedis.publish(
"azisaba-api:store:purchase",
JSON.encodeToString(PurchaseData(uuid, stripeObject.amountTotal))
)
}
}
}
call.respondJson(mapOf("info" to "processed"))
}
}
@Serializable
@Resource("players/{name}/highest_sara")
data class HighestSara(
@Suppress("unused")
val parent: Store,
val name: String,
): RequestHandler() {
override suspend fun PipelineContext<Unit, ApplicationCall>.handleRequest() {
call.respondJson(mapOf("highest_sara" to getHighestSara(name), "gaming_sara" to hasGamingSara(name)))
}
}
}
| 7
|
Kotlin
|
0
| 5
|
00a410bbe61d34601ffcc7a2e33152a7ca671540
| 10,762
|
api
|
MIT License
|
features/searchproducts/src/main/java/co/com/mercadolibre_test/searchproducts/presentation/productresults/ProductResultsFragment.kt
|
CarlosQuezadaP
| 672,701,916
| false
| null |
package co.com.mercadolibre_test.searchproducts.presentation.productresults
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import co.com.mercadolibre_test.core.base.BaseFragment
import co.com.mercadolibre_test.core.utils.viewBinding
import co.com.mercadolibre_test.searchproducts.R
import co.com.mercadolibre_test.searchproducts.databinding.FragmentProductResultsBinding
import co.com.mercadolibre_test.searchproducts.domain.exceptions.ProductResultsException
import co.com.mercadolibre_test.searchproducts.domain.models.productresults.Product
import co.com.mercadolibre_test.searchproducts.presentation.productresults.adapter.OnProductClickListener
import co.com.mercadolibre_test.searchproducts.presentation.productresults.adapter.ProductsAdapter
import co.com.mercadolibre_test.searchproducts.utils.hide
import co.com.mercadolibre_test.searchproducts.utils.show
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
class ProductResultsFragment : BaseFragment<FragmentProductResultsBinding>(R.layout.fragment_product_results), OnProductClickListener {
@Inject
lateinit var viewModelAssistedFactory: ProductResultsViewModelAssistedFactory // Se utiliza assistedInjection para proveer parametros desde la vista antes de que el viewmodel sea creado
override val binding by viewBinding(FragmentProductResultsBinding::bind) // viewBinding es una extension para obtener el binding de esta pantalla y evitar el codigo boilerplate
private val args: ProductResultsFragmentArgs by navArgs() // Se trabajó con los safe args de Navigation Component para pasar parámetros entra las vistas
private val viewModel: ProductResultsViewModel by viewModels {
viewModelAssistedFactory.create(this, args.query) // Se usa la inyección asistida y se pasa como parámetro el query al ViewModel en cuestion
}
private val myAdapter = ProductsAdapter(this@ProductResultsFragment)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.setupViews()
subscribeToProductsResults()
}
// Se configuran las vistas de la pantalla
private fun FragmentProductResultsBinding.setupViews() {
ivBack.setOnClickListener { onBackPressed() }
etSearchProductsPlaceHolder.run {
setText(args.query)
setOnClickListener {
findNavController().navigate(ProductResultsFragmentDirections.navigateToSearchProducts(args.query))
}
}
rvProductResults.run {
layoutManager = LinearLayoutManager(context)
ContextCompat.getDrawable(context, R.drawable.recycler_divider)?.let { divider ->
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { setDrawable(divider) })
}
adapter = myAdapter
}
lifecycleScope.launchWhenResumed {
myAdapter.loadStateFlow.collectLatest {
if (it.source.refresh is LoadState.NotLoading && it.source.prepend.endOfPaginationReached) { // Esto permite observar el estado del adaptador y saber si ya pagin ha terminado de actualizar los datos
if (myAdapter.itemCount == 0) { // Si los datos de pagin son vacios significa que no se encontraron resultados para mostrar
showEmptyWidget()
}
binding.productsShimmer.hide()
}
if (it.refresh is LoadState.Error) {
viewModel.pagingException((it.refresh as LoadState.Error).error)
}
}
}
}
private fun subscribeToProductsResults() {
lifecycleScope.launchWhenCreated {
viewModel.state.onEach(::handleProductsResponse).launchIn(this)
}
}
private fun handleProductsResponse(screenState: ProductResultsScreenState) { // El estado de a vista se representa con un sealed class y acá reaccionamos a esos estados dependiendo de cuál estado se produce en el viewModel
when (screenState) {
ProductResultsScreenState.Loading -> {
binding.productsShimmer.show()
hideEmptyWidget()
}
is ProductResultsScreenState.Success -> {
hideEmptyWidget()
loadPagingData(screenState.products)
}
is ProductResultsScreenState.Failure -> {
binding.productsShimmer.hide()
hideEmptyWidget()
handleException(screenState.error)
}
}
}
// Asignamos el PadingData el adaptador
private fun loadPagingData(products: Flow<PagingData<Product>>) {
lifecycleScope.launch {
products.collect { myAdapter.submitData(it) }
}
}
private fun handleException(exception: ProductResultsException) {
when (exception) {
is ProductResultsException.ProductsNotAvailable -> showToastMessage(exception.errorMessage)
is ProductResultsException.UnknownError -> handleUnknownError(exception.error) // Si es un error desconocido dentro del flujo se pide a la clase padre que lo maneje
}
}
private fun showEmptyWidget() {
binding.vsProductEmpty.run {
if (layoutResource == VIEW_STUB_NO_LAYOUT_RESULT) {
layoutResource = R.layout.products_empty_layout
inflate()
}
visibility = View.VISIBLE
}
}
private fun hideEmptyWidget() {
binding.vsProductEmpty.visibility = View.GONE
}
override fun onProductClick(product: Product) {
findNavController().navigate(ProductResultsFragmentDirections.navigateToProductDetails(product))
}
}
private const val VIEW_STUB_NO_LAYOUT_RESULT = 0
| 1
|
Kotlin
|
0
| 0
|
82b89bbe0a55ad3d8901350e71eb03715da87af4
| 6,372
|
meliTest
|
Apache License 2.0
|
application/core/theme/android-util/src/main/java/com/stepango/blockme/core/theme/android/util/di/ThemeComponent.kt
|
formatools
| 289,781,857
| false
|
{"Kotlin": 279989, "C++": 2058, "C": 545, "CMake": 190}
|
package com.stepango.blockme.core.theme.android.util.di
import com.stepango.blockme.core.theme.android.util.ThemeUtils
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [
ThemeModule::class
])
interface ThemeComponent {
fun themeUtils(): ThemeUtils
@Component.Factory
interface Factory {
fun create(): ThemeComponent
}
}
interface ThemeComponentProvider {
fun getThemeComponent(): ThemeComponent
}
| 24
|
Kotlin
|
8
| 176
|
b6d3a1378c1bdc0c8e66d0240622975729070808
| 473
|
forma
|
Apache License 2.0
|
src/main/kotlin/no/nav/bidrag/stønad/bo/OppdatertPeriode.kt
|
navikt
| 360,850,317
| false
|
{"Kotlin": 230915, "Dockerfile": 158}
|
package no.nav.bidrag.stønad.bo
data class OppdatertPeriode(val periodeListe: List<PeriodeBo>, val oppdaterPerioder: Boolean = false, val settPeriodeSomUgyldig: Boolean = false)
| 8
|
Kotlin
|
0
| 0
|
868eff6cbd22efecba5fdf48d6d29eae5189c6fc
| 179
|
bidrag-stonad
|
MIT License
|
lawnchair/src/app/lawnchair/ui/preferences/DockPreferences.kt
|
Ruppi64
| 453,016,249
| false
|
{"Java Properties": 2, "YAML": 3, "Text": 9, "XML": 736, "INI": 5, "Makefile": 4, "Gradle": 6, "Shell": 1, "Python": 3, "Markdown": 3, "Batchfile": 1, "Soong": 4, "Ignore List": 5, "Git Config": 1, "AIDL": 12, "Java": 858, "Kotlin": 184, "JSON": 3, "Protocol Buffer": 5, "Proguard": 3}
|
/*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences
import androidx.compose.animation.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavGraphBuilder
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.ui.preferences.components.*
import com.android.launcher3.R
@ExperimentalAnimationApi
fun NavGraphBuilder.dockGraph(route: String) {
preferenceGraph(route, { DockPreferences() })
}
@ExperimentalAnimationApi
@Composable
fun DockPreferences() {
val prefs = preferenceManager()
PreferenceLayout(label = stringResource(id = R.string.dock_label)) {
PreferenceGroup(
isFirstChild = true,
heading = stringResource(id = R.string.search_bar_label)
) {
val enableHotseatQsbAdapter = prefs.enableHotseatQsb.getAdapter()
SwitchPreference(
adapter = enableHotseatQsbAdapter,
label = stringResource(id = R.string.hotseat_qsb_label),
)
AnimatedVisibility(
visible = enableHotseatQsbAdapter.state.value,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
DividerColumn {
SwitchPreference(
label = stringResource(id = R.string.apply_accent_color_label),
adapter = prefs.themedHotseatQsb.getAdapter(),
)
SliderPreference(
label = stringResource(id = R.string.corner_radius_label),
adapter = prefs.hotseatQsbCornerRadius.getAdapter(),
step = 0.1F,
valueRange = 0F..1F,
showAsPercentage = true
)
}
}
}
PreferenceGroup(heading = stringResource(id = R.string.grid)) {
SliderPreference(
label = stringResource(id = R.string.dock_icons),
adapter = prefs.hotseatColumns.getAdapter(),
step = 1,
valueRange = 3..10,
)
}
}
}
| 1
| null |
1
| 1
|
c51b2a221838aefb610b7146fc4ef7cb34e5e495
| 2,845
|
lawnchair
|
Apache License 2.0
|
app/src/main/java/com/lateinit/rightweight/di/DatabaseModule.kt
|
boostcampwm-2022
| 563,132,819
| false
|
{"Kotlin": 320392}
|
package com.lateinit.rightweight.di
import android.content.Context
import androidx.room.Room
import com.lateinit.rightweight.data.database.AppDatabase
import com.lateinit.rightweight.data.dataStore.AppPreferencesDataStore
import com.lateinit.rightweight.data.database.dao.HistoryDao
import com.lateinit.rightweight.data.database.dao.RoutineDao
import com.lateinit.rightweight.data.database.dao.SharedRoutineDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class DatabaseModule {
@Provides
@Singleton
fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, DB_NAME).build()
}
@Provides
@Singleton
fun provideRoutineDao(appDatabase: AppDatabase): RoutineDao {
return appDatabase.routineDao()
}
@Provides
@Singleton
fun provideHistoryDao(appDatabase: AppDatabase): HistoryDao {
return appDatabase.historyDao()
}
@Provides
@Singleton
fun provideSharedRoutineDao(appDatabase: AppDatabase): SharedRoutineDao {
return appDatabase.sharedRoutineDao()
}
@Provides
@Singleton
fun provideAppPreferencesDataStore(@ApplicationContext context: Context): AppPreferencesDataStore {
return AppPreferencesDataStore(context)
}
companion object {
private const val DB_NAME = "right_weight.db"
}
}
| 6
|
Kotlin
|
0
| 27
|
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
| 1,612
|
android09-RightWeight
|
MIT License
|
template/app/src/main/kotlin/app/datasource/storage/keyvalue/AppKeyValueSource.kt
|
kotlitecture
| 738,057,168
| false
|
{"Kotlin": 264246, "HTML": 891}
|
package app.datasource.storage.keyvalue
import android.app.Application
import core.data.datasource.storage.keyvalue.BasicKeyValueSource
/**
* Decorator class for working with key-value storage on the app level.
*
* Can provide extra methods without impacting facade implementations.
*/
class AppKeyValueSource(app: Application) : BasicKeyValueSource(app)
| 0
|
Kotlin
|
0
| 0
|
7200f3ed86a9c1bbc2c348c9bdc1f0889b99a531
| 360
|
template-android-compose
|
MIT License
|
layout-inspector/src/com/android/tools/idea/layoutinspector/pipeline/appinspection/AppInspectionInspectorClient.kt
|
phpc0de
| 470,555,455
| false
|
{"Java": 39631279, "Kotlin": 28526369, "HTML": 1206758, "Starlark": 482060, "C": 66005, "Python": 59985, "NSIS": 58515, "Lex": 46798, "CMake": 24483, "JavaScript": 18437, "C++": 11882, "Shell": 7470, "RenderScript": 4411, "AIDL": 3251, "Makefile": 2298, "IDL": 269, "QMake": 18}
|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.layoutinspector.pipeline.appinspection
import com.android.ddmlib.AndroidDebugBridge
import com.android.tools.idea.appinspection.api.AppInspectionApiServices
import com.android.tools.idea.appinspection.ide.AppInspectionDiscoveryService
import com.android.tools.idea.appinspection.inspector.api.process.ProcessDescriptor
import com.android.tools.idea.concurrency.coroutineScope
import com.android.tools.idea.concurrency.createChildScope
import com.android.tools.idea.flags.StudioFlags
import com.android.tools.idea.layoutinspector.metrics.LayoutInspectorMetrics
import com.android.tools.idea.layoutinspector.metrics.statistics.SessionStatistics
import com.android.tools.idea.layoutinspector.model.AndroidWindow
import com.android.tools.idea.layoutinspector.model.InspectorModel
import com.android.tools.idea.layoutinspector.pipeline.AbstractInspectorClient
import com.android.tools.idea.layoutinspector.pipeline.InspectorClient
import com.android.tools.idea.layoutinspector.pipeline.InspectorClient.Capability
import com.android.tools.idea.layoutinspector.pipeline.InspectorClientSettings
import com.android.tools.idea.layoutinspector.pipeline.TreeLoader
import com.android.tools.idea.layoutinspector.pipeline.appinspection.compose.ComposeLayoutInspectorClient
import com.android.tools.idea.layoutinspector.pipeline.appinspection.view.ViewLayoutInspectorClient
import com.android.tools.idea.layoutinspector.properties.PropertiesProvider
import com.android.tools.idea.layoutinspector.skia.SkiaParserImpl
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.SettableFuture
import com.google.wireless.android.sdk.stats.DynamicLayoutInspectorEvent.DynamicLayoutInspectorEventType
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import layoutinspector.view.inspection.LayoutInspectorViewProtocol
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.util.EnumSet
/**
* An [InspectorClient] that talks to an app-inspection based inspector running on a target device.
*
* @param apiServices App inspection services used for initializing and shutting down app
* inspection-based inspectors.
* @param scope App inspection APIs use coroutines, while this class's interface does not, so this
* coroutine scope is used to handle the bridge between the two approaches.
*/
class AppInspectionInspectorClient(
adb: AndroidDebugBridge,
process: ProcessDescriptor,
private val model: InspectorModel,
stats: SessionStatistics,
@TestOnly private val apiServices: AppInspectionApiServices = AppInspectionDiscoveryService.instance.apiServices,
@TestOnly private val scope: CoroutineScope = model.project.coroutineScope.createChildScope(true),
) : AbstractInspectorClient(process) {
private lateinit var viewInspector: ViewLayoutInspectorClient
private lateinit var propertiesProvider: AppInspectionPropertiesProvider
/** Compose inspector, may be null if user's app isn't using the compose library. */
@VisibleForTesting
var composeInspector: ComposeLayoutInspectorClient? = null
private set
private val exceptionHandler = CoroutineExceptionHandler { _, t ->
fireError(t.message!!)
}
private val debugViewAttributes = DebugViewAttributes(adb, model.project, process)
private val metrics = LayoutInspectorMetrics.create(model.project, process, stats)
override val capabilities =
EnumSet.of(Capability.SUPPORTS_CONTINUOUS_MODE,
Capability.SUPPORTS_FILTERING_SYSTEM_NODES,
Capability.SUPPORTS_SYSTEM_NODES,
Capability.SUPPORTS_SKP)!!
private val skiaParser = SkiaParserImpl(
{
viewInspector.updateScreenshotType(LayoutInspectorViewProtocol.Screenshot.Type.BITMAP)
capabilities.remove(Capability.SUPPORTS_SKP)
})
override val treeLoader: TreeLoader = AppInspectionTreeLoader(
model.project,
logEvent = metrics::logEvent,
skiaParser
)
override val provider: PropertiesProvider
get() = propertiesProvider
override val isCapturing: Boolean
get() = InspectorClientSettings.isCapturingModeOn
override fun doConnect(): ListenableFuture<Nothing> {
val future = SettableFuture.create<Nothing>()
val connectFailureHandler = CoroutineExceptionHandler { _, t -> future.setException(t) }
scope.launch(connectFailureHandler) {
metrics.logEvent(DynamicLayoutInspectorEventType.ATTACH_REQUEST)
if (StudioFlags.DYNAMIC_LAYOUT_INSPECTOR_ENABLE_COMPOSE_SUPPORT.get()) {
composeInspector = ComposeLayoutInspectorClient.launch(apiServices, process, model)
}
viewInspector = ViewLayoutInspectorClient.launch(apiServices, process, model, scope, composeInspector, ::fireError, ::fireTreeEvent)
propertiesProvider = AppInspectionPropertiesProvider(viewInspector, composeInspector, model)
metrics.logEvent(DynamicLayoutInspectorEventType.ATTACH_SUCCESS)
debugViewAttributes.set()
if (isCapturing) {
startFetching()
}
else {
refresh()
}
future.set(null)
}
return future
}
override fun doDisconnect(): ListenableFuture<Nothing> {
val future = SettableFuture.create<Nothing>()
scope.launch(exceptionHandler) {
debugViewAttributes.clear()
viewInspector.disconnect()
composeInspector?.disconnect()
skiaParser.shutdown()
metrics.logEvent(DynamicLayoutInspectorEventType.SESSION_DATA)
future.set(null)
}
return future
}
override fun startFetching() {
scope.launch(exceptionHandler) {
viewInspector.startFetching(continuous = true)
}
}
override fun stopFetching() {
scope.launch(exceptionHandler) {
// Reset the scale to 1 to support zooming while paused, and get an SKP if possible.
if (capabilities.contains(Capability.SUPPORTS_SKP)) {
updateScreenshotType(AndroidWindow.ImageType.SKP, 1.0f)
}
else {
viewInspector.updateScreenshotType(null, 1.0f)
}
viewInspector.stopFetching()
}
}
override fun refresh() {
scope.launch(exceptionHandler) {
viewInspector.startFetching(continuous = false)
}
}
override fun updateScreenshotType(type: AndroidWindow.ImageType?, scale: Float) {
if (model.pictureType != type || scale >= 0f) {
viewInspector.updateScreenshotType(type?.protoType, scale)
}
}
override fun addDynamicCapabilities(dynamicCapabilities: Set<Capability>) {
capabilities.addAll(dynamicCapabilities)
}
}
| 0
|
Java
|
1
| 1
|
79e20f027ca1d047b91aa7acd92fb71fa2968a09
| 7,256
|
idea-android
|
Apache License 2.0
|
compiler/testData/writeFlags/function/deprecatedFlag/setter.kt
|
JakeWharton
| 99,388,807
| false
| null |
class MyClass() {
var test = 1
@deprecated("") set(i: Int) { test = i }
}
// TESTED_OBJECT_KIND: function
// TESTED_OBJECTS: MyClass, setTest
// FLAGS: ACC_DEPRECATED, ACC_PUBLIC, ACC_FINAL
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 204
|
kotlin
|
Apache License 2.0
|
app/shared/bitkey-primitives/fake/src/commonMain/kotlin/build/wallet/bitkey/f8e/F8eSpendingKeysetMock.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.bitkey.f8e
import build.wallet.bitcoin.keys.DescriptorPublicKeyMock
val F8eSpendingKeysetMock =
F8eSpendingKeyset(
keysetId = "f8e-spending-keyset-id",
spendingPublicKey =
F8eSpendingPublicKey(
key = DescriptorPublicKeyMock("f8e-spending-keyset-dpub")
)
)
| 0
|
C
|
10
| 98
|
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
| 311
|
bitkey
|
MIT License
|
app/src/main/java/com/sukacolab/app/ui/component/StatelessTopBar.kt
|
cahyadiantoni
| 757,308,387
| false
|
{"Kotlin": 211492}
|
package com.sukacolab.app.ui.component
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SmallTopAppBar
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
@Composable
fun StatelessTopBar(
navigationIcon: (@Composable () -> Unit)?=null,
title: String,
actionIcon: @Composable RowScope.() -> Unit
) {
CenterAlignedTopAppBar(
navigationIcon = { navigationIcon?.invoke() },
title = { Text(text = title, color = Color.White) },
colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = MaterialTheme.colorScheme.primary),
actions = actionIcon,
)
}
| 0
|
Kotlin
|
0
| 0
|
ee38c667fcad913b2ec372d2ca609e64cf860102
| 868
|
sukacolab
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.