path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/dev/shorthouse/coinwatch/domain/GetFavouritesPreferencesUseCase.kt | shorthouse | 655,260,745 | false | {"Kotlin": 665878} | package dev.shorthouse.coinwatch.domain
import dev.shorthouse.coinwatch.data.preferences.favourites.FavouritesPreferences
import dev.shorthouse.coinwatch.data.preferences.favourites.FavouritesPreferencesRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetFavouritesPreferencesUseCase @Inject constructor(
private val favouritesPreferencesRepository: FavouritesPreferencesRepository
) {
operator fun invoke(): Flow<FavouritesPreferences> {
return getFavouritesPreferences()
}
private fun getFavouritesPreferences(): Flow<FavouritesPreferences> {
return favouritesPreferencesRepository.favouritesPreferencesFlow
}
}
| 5 | Kotlin | 3 | 58 | c83054306d9885d81f759105d080b3f1c4c1ed30 | 684 | CoinWatch | Apache License 2.0 |
src/main/kotlin/com/nikichxp/tgbot/service/actions/LikedMessageService.kt | NikichXP | 395,716,371 | false | null | package com.nikichxp.tgbot.service.actions
import com.nikichxp.tgbot.core.CurrentUpdateProvider
import com.nikichxp.tgbot.dto.User
import com.nikichxp.tgbot.entity.MessageInteractionResult
import com.nikichxp.tgbot.service.TgOperations
import com.nikichxp.tgbot.service.UserInfo
import com.nikichxp.tgbot.service.UserService
import com.nikichxp.tgbot.util.UserFormatter.getUserPrintName
import org.springframework.stereotype.Service
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.concurrent.atomic.AtomicReference
@Service
class LikedMessageService(
private val userService: UserService,
private val currentUpdateProvider: CurrentUpdateProvider,
private val tgOperations: TgOperations,
private val likedHistoryService: LikedHistoryService
) {
// TODO save history of karma givers
fun changeRating(interaction: MessageInteractionResult) {
val actor = interaction.getActor()
val actorInfo = userService.getUserInfo(actor)
val target = interaction.getTarget() ?: throw IllegalStateException(impossibleStateOfNoTarget)
val diff = calculateKarmaDiff(actorInfo, target, interaction)
val result = AtomicReference(0.0)
userService.modifyUser(target) {
val resultRating = it.rating + diff
it.rating = BigDecimal.valueOf(resultRating).setScale(1, RoundingMode.HALF_UP).toDouble()
result.set(it.rating)
}
val text = "${getUserPrintName(actor)} changed karma of ${getUserPrintName(target)} (${result.get()})"
tgOperations.sendMessage(currentUpdateProvider.update?.message?.chat?.id?.toString()!!, text)
}
private fun calculateKarmaDiff(actor: UserInfo, target: User, interaction: MessageInteractionResult): Double {
val messageId = currentUpdateProvider.update?.message?.messageId ?: throw IllegalStateException()
likedHistoryService.report(actor.id, target.id, messageId)
return (1 + (actor.rating / 10)) * interaction.power
}
// TODO this should be a part of some properties file with errors
companion object {
const val impossibleStateOfNoTarget =
"[INT0001: no interaction target found when it is supposed to be a target]"
}
} | 0 | Kotlin | 0 | 0 | 3682bc1283de47c90dae290d1f20c210f8e1bb83 | 2,252 | tg-bot | Apache License 2.0 |
app/src/main/java/com/revolgenx/anilib/common/ui/view/KaomojiLoader.kt | AniLibApp | 244,410,204 | false | {"Kotlin": 1593083, "Shell": 52} | package com.revolgenx.anilib.common.ui.view
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.setPadding
import com.pranavpandey.android.dynamic.support.widget.DynamicTextView
import com.pranavpandey.android.dynamic.theme.Theme
import com.revolgenx.anilib.R
import com.revolgenx.anilib.ui.view.makeToast
import com.revolgenx.anilib.util.dp
import timber.log.Timber
class KaomojiLoader : FrameLayout {
private lateinit var kaomojiTextView: DynamicTextView
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet) {
initLoader()
}
constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
context,
attributeSet,
defStyle
) {
initLoader()
}
private fun initLoader() {
kaomojiTextView = DynamicTextView(context).also {
it.layoutParams =
LayoutParams(LayoutParams.WRAP_CONTENT, dp(100f)).also {
it.gravity = Gravity.CENTER
}
it.text = loadingKoeMoji.random()
it.textSize = 18f
it.gravity = Gravity.CENTER
it.includeFontPadding = false
}
kaomojiTextView.colorType = Theme.ColorType.ACCENT
kaomojiTextView.typeface = ResourcesCompat.getFont(context, R.font.rubik_bold)
kaomojiTextView.rotate()
addView(kaomojiTextView)
}
private fun TextView.rotate() {
val rotateAnimation = RotateAnimation(
0f, 359f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
rotateAnimation.repeatCount = Animation.INFINITE
rotateAnimation.duration = 1600
rotateAnimation.interpolator = LinearInterpolator()
startAnimation(rotateAnimation)
}
} | 36 | Kotlin | 3 | 76 | b3caec5c00779c878e4cf22fb7d2034aefbeee54 | 2,218 | AniLib | Apache License 2.0 |
orbit/src/main/kotlin/com/zyron/orbit/scrollview/ScrollViewManager.kt | Zyron-Official | 865,917,955 | false | {"Kotlin": 86837} | package com.zyron.orbit.scrollview
class ScrollViewManager {
} | 0 | Kotlin | 0 | 1 | 2e25eef073b5a83e4a0b1ed70ca492d60f5c2b68 | 63 | Orbit-VFMS | Apache License 2.0 |
app/src/main/java/com/android/aman/newsapp/Networking/ApiClient.kt | Aman817 | 268,236,395 | false | null | package com.example.newsapp.Networking
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiClient {
var retrofit: Retrofit? = null
private const val BASE_URL = "https://newsapi.org/v2/"
val getApiClient: Retrofit?
get() {
if (retrofit == null) {
retrofit = retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
| 0 | Kotlin | 1 | 2 | a910d90ef9f77bb5540075a99d0667644e0cc582 | 573 | NEWS-APP | Apache License 2.0 |
src/main/kotlin/com/kneelawk/transpositioners/module/ItemMoverMk3Module.kt | Kneelawk | 332,850,862 | false | null | package com.kneelawk.transpositioners.module
import alexiil.mc.lib.attributes.SearchOptions
import alexiil.mc.lib.attributes.Simulation
import alexiil.mc.lib.attributes.item.FixedItemInv
import alexiil.mc.lib.attributes.item.ItemAttributes
import alexiil.mc.lib.attributes.item.ItemExtractable
import alexiil.mc.lib.attributes.item.ItemInsertable
import alexiil.mc.lib.attributes.item.filter.ConstantItemFilter
import alexiil.mc.lib.attributes.item.filter.ItemFilter
import alexiil.mc.lib.attributes.item.impl.EmptyFixedItemInv
import com.kneelawk.transpositioners.TPConstants
import com.kneelawk.transpositioners.item.TPItems
import com.kneelawk.transpositioners.net.ModuleDataPacketHandler
import com.kneelawk.transpositioners.screen.ItemMoverMk3ScreenHandler
import com.kneelawk.transpositioners.util.ExactStackContainer
import com.kneelawk.transpositioners.util.MovementDirection
import com.kneelawk.transpositioners.util.TooltipUtils
import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory
import net.minecraft.client.item.TooltipContext
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.inventory.Inventory
import net.minecraft.inventory.InventoryChangedListener
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtCompound
import net.minecraft.network.PacketByteBuf
import net.minecraft.screen.ScreenHandler
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.World
class ItemMoverMk3Module(
context: ModuleContext, path: ModulePath, initialDirection: MovementDirection, initialInsertionSide: Direction,
initialExtractionSide: Direction, initialStackSize: Int, initialTicksPerMove: Int,
val gates: ModuleInventory<ItemGateModule>, private var lastMove: Long
) : AbstractModule(Type, context, path), MoverModule, ExtendedScreenHandlerFactory, InventoryChangedListener {
companion object {
const val MIN_STACK_SIZE = 1
const val MAX_STACK_SIZE = 256
const val DEFAULT_STACK_SIZE = 8
const val DEFAULT_TICKS_PER_MOVE = 40
private val NET_PARENT = Module.NET_ID.subType(
ItemMoverMk3Module::class.java,
TPConstants.str("item_mover_mk3_module")
)
private val DIRECTION_CHANGE = ModuleDataPacketHandler(NET_PARENT.idData("DIRECTION_CHANGE"),
ItemMoverMk3ScreenHandler::class, { it.writeByte(direction.id) },
{ direction = MovementDirection.byId(it.readByte().toInt()) },
{ it.s2cReceiveDirectionChange(direction) })
private val INSERTION_SIDE_CHANGE = ModuleDataPacketHandler(NET_PARENT.idData("INSERTION_SIDE_CHANGE"),
ItemMoverMk3ScreenHandler::class, { it.writeByte(insertionSide.id) },
{ insertionSide = Direction.byId(it.readByte().toInt()) },
{ it.s2cReceiveInsertionSideChange(insertionSide) })
private val EXTRACTION_SIDE_CHANGE = ModuleDataPacketHandler(NET_PARENT.idData("EXTRACTION_SIDE_CHANGE"),
ItemMoverMk3ScreenHandler::class, { it.writeByte(extractionSide.id) },
{ extractionSide = Direction.byId(it.readByte().toInt()) },
{ it.s2cReceiveExtractionSideChange(extractionSide) })
private val STACK_SIZE_CHANGE = ModuleDataPacketHandler(NET_PARENT.idData("STACK_SIZE_CHANGE"),
ItemMoverMk3ScreenHandler::class, { it.writeVarUnsignedInt(stackSize) },
{ stackSize = it.readVarUnsignedInt() },
{ it.s2cReceiveStackSizeChange(stackSize) }
)
private val MOVES_PER_SECOND_CHANGE = ModuleDataPacketHandler(NET_PARENT.idData("MOVES_PER_SECOND_CHANGE"),
ItemMoverMk3ScreenHandler::class, { it.writeVarUnsignedInt(ticksPerMove) },
{ ticksPerMove = it.readVarUnsignedInt() },
{ it.s2cReceiveMovesPerSecondChange(ticksPerMove) }
)
}
var direction = initialDirection
private set
var insertionSide = initialInsertionSide
private set
var extractionSide = initialExtractionSide
private set
var stackSize = initialStackSize.coerceIn(MIN_STACK_SIZE, MAX_STACK_SIZE)
private set
var ticksPerMove = initialTicksPerMove
private set
private val ignoreStacks = mutableSetOf<ExactStackContainer>()
init {
gates.addListener(this)
}
fun updateDirection(newDirection: MovementDirection) {
direction = newDirection
DIRECTION_CHANGE.sendToClients(this)
markDirty()
}
fun updateInsertionSide(newInsertionSide: Direction) {
insertionSide = newInsertionSide
INSERTION_SIDE_CHANGE.sendToClients(this)
markDirty()
}
fun updateExtractionSide(newExtractionSide: Direction) {
extractionSide = newExtractionSide
EXTRACTION_SIDE_CHANGE.sendToClients(this)
markDirty()
}
fun updateStackSize(newStackSize: Int) {
stackSize = newStackSize.coerceIn(MIN_STACK_SIZE, MAX_STACK_SIZE)
STACK_SIZE_CHANGE.sendToClients(this)
markDirty()
}
fun updateTicksPerMove(newTicksPerMove: Int) {
ticksPerMove = newTicksPerMove.coerceAtLeast(1)
MOVES_PER_SECOND_CHANGE.sendToClients(this)
markDirty()
}
fun getInsertionPos() = when (direction) {
MovementDirection.FORWARD -> frontPos
MovementDirection.BACKWARD -> backPos
}
fun getExtractionPos() = when (direction) {
MovementDirection.FORWARD -> backPos
MovementDirection.BACKWARD -> frontPos
}
override fun move() {
val time = world.time
if (time - lastMove >= ticksPerMove) {
lastMove = time
markDirty()
ignoreStacks.clear()
val insert = getItemInsertable(getInsertionPos(), insertionSide.opposite)
val extractInv = getFixedItemInv(getExtractionPos(), extractionSide.opposite)
val itemFilter = gates.getModule(0)?.getItemFilter() ?: ConstantItemFilter.ANYTHING
if (extractInv != EmptyFixedItemInv.INSTANCE) {
var remaining = stackSize
for (slot in 0 until extractInv.slotCount) {
val extract = extractInv.getSlot(slot)
remaining = attemptTransfer(remaining, extract, insert, ignoreStacks, itemFilter)
if (remaining == 0) break
}
} else {
val extract = getItemExtractable(getExtractionPos(), extractionSide.opposite)
attemptTransfer(stackSize, extract, insert, ignoreStacks, itemFilter)
}
}
}
private fun attemptTransfer(
remaining: Int,
extract: ItemExtractable,
insert: ItemInsertable,
ignore: MutableSet<ExactStackContainer>,
filter: ItemFilter
): Int {
val extractedSim = extract.attemptExtraction(filter, remaining, Simulation.SIMULATE)
if (!extractedSim.isEmpty && !ignore.contains(ExactStackContainer.of(extractedSim))) {
val leftOverSim = insert.attemptInsertion(extractedSim, Simulation.SIMULATE)
val amount = extractedSim.count - leftOverSim.count
if (amount != 0) {
val leftOver =
insert.attemptInsertion(
extract.attemptExtraction(filter, amount, Simulation.ACTION),
Simulation.ACTION
)
assert(leftOver.isEmpty) { "leftOver: $leftOver" }
} else {
// If an inventory won't accept a kind of item, don't try and insert it a second time
ignore.add(ExactStackContainer.of(extractedSim))
}
return remaining - amount
}
return remaining
}
private fun getItemInsertable(pos: BlockPos, direction: Direction): ItemInsertable {
return ItemAttributes.INSERTABLE.get(world, pos, SearchOptions.inDirection(direction))
}
private fun getFixedItemInv(pos: BlockPos, direction: Direction): FixedItemInv {
return ItemAttributes.FIXED_INV.get(world, pos, SearchOptions.inDirection(direction))
}
private fun getItemExtractable(pos: BlockPos, direction: Direction): ItemExtractable {
return ItemAttributes.EXTRACTABLE.get(world, pos, SearchOptions.inDirection(direction))
}
override fun createMenu(syncId: Int, inv: PlayerInventory, player: PlayerEntity): ScreenHandler {
return ItemMoverMk3ScreenHandler(syncId, inv, this)
}
override fun getDisplayName(): Text {
return TPConstants.tt(TPItems.ITEM_MOVER_MODULE_MK3.translationKey)
}
override fun writeScreenOpeningData(player: ServerPlayerEntity, buf: PacketByteBuf) {
Module.writeModulePath(this, buf)
}
override fun onInventoryChanged(sender: Inventory) {
markDirty()
}
override fun writeToTag(tag: NbtCompound) {
tag.putByte("direction", direction.ordinal.toByte())
tag.putByte("insertionSide", insertionSide.id.toByte())
tag.putByte("extractionSide", extractionSide.id.toByte())
tag.putInt("stackSize", stackSize)
tag.putInt("ticksPerMove", ticksPerMove)
tag.put("gates", gates.toNbtList())
tag.putLong("lastMove", lastMove)
}
override fun getModule(index: Int): Module? {
return gates.getModule(index)
}
object Type : ModuleType<ItemMoverMk3Module> {
override fun readFromTag(
context: ModuleContext,
path: ModulePath,
stack: ItemStack,
tag: NbtCompound
): ItemMoverMk3Module {
val direction = if (tag.contains("direction")) MovementDirection.values()[tag.getByte("direction").toInt()
.coerceIn(0, 1)] else MovementDirection.FORWARD
val insertionSide = if (tag.contains("insertionSide")) {
Direction.byId(tag.getByte("insertionSide").toInt())
} else {
when (context) {
is ModuleContext.Configurator -> Direction.UP
is ModuleContext.Entity -> context.facing.opposite
}
}
val extractionSide = if (tag.contains("extractionSide")) {
Direction.byId(tag.getByte("extractionSide").toInt())
} else {
when (context) {
is ModuleContext.Configurator -> Direction.DOWN
is ModuleContext.Entity -> context.facing
}
}
val stackSize = if (tag.contains("stackSize")) tag.getInt("stackSize") else DEFAULT_STACK_SIZE
val ticksPerMove = if (tag.contains("ticksPerMove")) tag.getInt("ticksPerMove") else DEFAULT_TICKS_PER_MOVE
val gates = ModuleInventory(1, context, path, TPModules.ITEM_GATES)
if (tag.contains("gates")) {
gates.readNbtList(tag.getList("gates", 10))
}
val lastMove = if (tag.contains("lastMove")) tag.getLong("lastMove") else 0L
return ItemMoverMk3Module(
context, path, direction, insertionSide, extractionSide, stackSize, ticksPerMove, gates, lastMove
)
}
override fun newInstance(
context: ModuleContext,
path: ModulePath,
stack: ItemStack
): ItemMoverMk3Module {
return ItemMoverMk3Module(
context, path, MovementDirection.FORWARD, when (context) {
is ModuleContext.Configurator -> Direction.UP
is ModuleContext.Entity -> context.facing.opposite
}, when (context) {
is ModuleContext.Configurator -> Direction.DOWN
is ModuleContext.Entity -> context.facing
}, DEFAULT_STACK_SIZE, DEFAULT_TICKS_PER_MOVE, ModuleInventory(1, context, path, TPModules.ITEM_GATES), 0L
)
}
override fun appendTooltip(
stack: ItemStack,
world: World?,
tooltip: MutableList<Text>,
tooltipContext: TooltipContext,
moduleData: NbtCompound
) {
if (moduleData.contains("direction")) {
val direction = MovementDirection.values()[moduleData.getByte("direction").toInt().coerceIn(0, 1)]
tooltip += TooltipUtils.movementDirection(direction)
}
if (moduleData.contains("insertionSide")) {
val insertionSide = Direction.byId(moduleData.getByte("insertionSide").toInt())
tooltip += TooltipUtils.insertionSide(insertionSide)
}
if (moduleData.contains("extractionSide")) {
val extractionSide = Direction.byId(moduleData.getByte("extractionSide").toInt())
tooltip += TooltipUtils.extractionSide(extractionSide)
}
if (moduleData.contains("stackSize")) {
val stackSize = moduleData.getInt("stackSize")
tooltip += TooltipUtils.stackSize(stackSize)
}
if (moduleData.contains("ticksPerMove")) {
val ticksPerMove = moduleData.getInt("ticksPerMove")
tooltip += TooltipUtils.ticksPerMove(ticksPerMove)
}
if (moduleData.contains("gates")) {
val gates = moduleData.getList("gates", 10)
if (!gates.isEmpty()) {
tooltip += TPConstants.tooltip("gates", gates.size)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | b6be4a4a2484376e6e63dd30bf8819f3b7dcd2c7 | 13,714 | Transpositioners | MIT License |
app/src/main/java/ca/andries/portknocker/data/StoredDataManager.kt | DJAndries | 284,227,491 | false | null | package ca.andries.portknocker.data
import android.content.Context
import android.content.SharedPreferences
import ca.andries.portknocker.models.HistoryItem
import ca.andries.portknocker.models.Profile
import ca.andries.portknocker.R
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.*
import kotlin.collections.ArrayList
class StoredDataManager {
companion object {
private fun getSharedPrefs(context: Context): SharedPreferences {
return context.getSharedPreferences(
context?.getString(R.string.main_prefs),
Context.MODE_PRIVATE
)
?: throw RuntimeException("No context set!")
}
private fun <T> listObjects(context: Context, keyId: Int, typeToken: TypeToken<ArrayList<T>>) : ArrayList<T> {
val sharedPrefs =
getSharedPrefs(
context
)
val strVal = sharedPrefs.getString(context.getString(keyId), "[]")
return Gson().fromJson(strVal, typeToken.type)
}
private inline fun <reified T> saveObjects(context: Context, keyId: Int, list: List<T>) {
val sharedPrefs =
getSharedPrefs(
context
)
val serialized = Gson().toJson(list)
sharedPrefs.edit().putString(context.getString(keyId), serialized).commit()
}
fun listProfiles(context: Context): ArrayList<Profile> {
return listObjects(
context,
R.string.profiles_key,
object :
TypeToken<ArrayList<Profile>>() {})
}
fun listHistory(context: Context): ArrayList<HistoryItem> {
return listObjects(
context,
R.string.history_key,
object :
TypeToken<ArrayList<HistoryItem>>() {})
}
fun addHistory(context: Context, newItem: HistoryItem) {
var history =
listHistory(
context
)
history.add(0, newItem)
if (history.size > 100) {
history.removeAt(100)
}
saveObjects(
context,
R.string.history_key,
history
)
}
fun saveProfile(context: Context, profile : Profile) {
val profiles =
listProfiles(
context
)
if (profile.id == null) {
profile.id = UUID.randomUUID().toString()
}
val existingProfileIndex = profiles.indexOfFirst { v -> v.id.equals(profile.id, true) }
if (existingProfileIndex != -1) {
profiles.removeAt(existingProfileIndex)
profiles.add(existingProfileIndex, profile)
} else {
profiles.add(profile)
}
saveObjects(
context,
R.string.profiles_key,
profiles
)
}
fun deleteProfile(context: Context, index: Int) {
val profiles =
listProfiles(
context
)
profiles.removeAt(index)
saveObjects(
context,
R.string.profiles_key,
profiles
)
}
fun clearHistory(context: Context) {
saveObjects(
context,
R.string.history_key,
listOf<HistoryItem>()
)
}
}
} | 1 | Kotlin | 1 | 0 | 24f84203504884f881ebb7082b66b57778b03f30 | 3,681 | portknocker-android | MIT License |
apps/teacher/src/androidTest/java/com/instructure/teacher/ui/pages/InboxPage.kt | instructure | 179,290,947 | false | {"Kotlin": 15108419, "Dart": 4442579, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112} | package com.instructure.teacher.ui.pages
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.hasSibling
import androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast
import androidx.test.platform.app.InstrumentationRegistry
import com.instructure.canvas.espresso.scrollRecyclerView
import com.instructure.canvas.espresso.waitForMatcherWithRefreshes
import com.instructure.canvas.espresso.withCustomConstraints
import com.instructure.canvasapi2.models.Conversation
import com.instructure.dataseeding.model.ConversationApiModel
import com.instructure.espresso.OnViewWithId
import com.instructure.espresso.RecyclerViewItemCountAssertion
import com.instructure.espresso.RecyclerViewItemCountGreaterThanAssertion
import com.instructure.espresso.WaitForViewWithId
import com.instructure.espresso.assertDisplayed
import com.instructure.espresso.assertVisibility
import com.instructure.espresso.click
import com.instructure.espresso.longClick
import com.instructure.espresso.page.BasePage
import com.instructure.espresso.page.onView
import com.instructure.espresso.page.plus
import com.instructure.espresso.page.waitForView
import com.instructure.espresso.page.waitForViewWithId
import com.instructure.espresso.page.waitForViewWithText
import com.instructure.espresso.page.withAncestor
import com.instructure.espresso.page.withId
import com.instructure.espresso.page.withText
import com.instructure.espresso.scrollTo
import com.instructure.espresso.swipeLeft
import com.instructure.espresso.swipeRight
import com.instructure.teacher.R
import com.instructure.teacher.ui.utils.WaitForToolbarTitle
import org.hamcrest.Matchers
/**
* Represents the Inbox Page.
*
* This page extends the BasePage class and provides functionality for interacting with the inbox.
* It contains various view elements such as toolbar, inbox recycler view, add message FAB,
* empty inbox view, scope filter text, and edit toolbar.
*/
class InboxPage: BasePage() {
private val toolbarTitle by WaitForToolbarTitle(R.string.tab_inbox)
private val inboxRecyclerView by WaitForViewWithId(R.id.inboxRecyclerView)
private val addMessageFAB by WaitForViewWithId(R.id.addMessage)
//Only displayed when inbox is empty
private val emptyPandaView by WaitForViewWithId(R.id.emptyInboxView)
private val scopeFilterText by OnViewWithId(R.id.scopeFilterText)
private val editToolbar by OnViewWithId(R.id.editToolbar)
override fun assertPageObjects(duration: Long) {
toolbarTitle.assertDisplayed()
}
/**
* Asserts that the inbox has at least one conversation.
*/
fun assertHasConversation() {
assertConversationCountIsGreaterThan(0)
}
/**
* Asserts that the count of conversations is greater than the specified count.
*
* @param count The count to compare against.
*/
fun assertConversationCountIsGreaterThan(count: Int) {
inboxRecyclerView.check(RecyclerViewItemCountGreaterThanAssertion(count))
}
/**
* Asserts that the count of conversations matches the specified count.
*
* @param count The expected count of conversations.
*/
fun assertConversationCount(count: Int) {
inboxRecyclerView.check(RecyclerViewItemCountAssertion(count))
}
/**
* Clicks on the conversation with the specified subject.
*
* @param conversationSubject The subject of the conversation to click.
*/
fun clickConversation(conversationSubject: String) {
waitForViewWithText(conversationSubject).click()
}
/**
* Clicks on the conversation with the specified subject.
*
* @param conversation The subject of the conversation to click.
*/
fun clickConversation(conversation: ConversationApiModel) {
clickConversation(conversation.subject)
}
/**
* Clicks on the conversation with the specified subject.
*
* @param conversation The subject of the conversation to click.
*/
fun clickConversation(conversation: Conversation) {
clickConversation(conversation.subject!!)
}
/**
* Clicks on the add message FAB.
*/
fun clickAddMessageFAB() {
addMessageFAB.click()
}
/**
* Asserts that the inbox is empty.
*/
fun assertInboxEmpty() {
onView(withId(R.id.emptyInboxView)).assertDisplayed()
}
/**
* Refreshes the inbox view.
*/
fun refresh() {
onView(withId(R.id.swipeRefreshLayout))
.perform(withCustomConstraints(ViewActions.swipeDown(), isDisplayingAtLeast(50)))
}
/**
* Filters the messages by the specified filter.
*
* @param filterFor The filter to apply.
*/
fun filterMessageScope(filterFor: String) {
waitForView(withId(R.id.scopeFilterText))
onView(withId(R.id.scopeFilter)).click()
waitForViewWithText(filterFor).click()
}
/**
* Filters the messages by the specified course scope.
*
* @param courseName The name of the course to filter for.
*/
fun filterCourseScope(courseName: String) {
waitForView(withId(R.id.courseFilter)).click()
waitForViewWithText(courseName).click()
}
/**
* Clears the course filter.
*/
fun clearCourseFilter() {
waitForView(withId(R.id.courseFilter)).click()
onView(withId(R.id.clear) + withText(R.string.inboxClearFilter)).click()
}
/**
* Asserts whether there is an unread message based on the specified flag.
*
* @param unread Flag indicating whether there is an unread message.
*/
fun assertThereIsAnUnreadMessage(unread: Boolean) {
if(unread) onView(withId(R.id.unreadMark)).assertDisplayed()
else onView(withId(R.id.unreadMark) + ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE))
}
/**
* Asserts that the conversation with the specified subject is starred.
*
* @param subject The subject of the conversation.
*/
fun assertConversationStarred(subject: String) {
val matcher = Matchers.allOf(
withId(R.id.star),
ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
hasSibling(withId(R.id.userName)),
hasSibling(withId(R.id.date)),
hasSibling(Matchers.allOf(withId(R.id.subjectView), withText(subject)))
)
waitForMatcherWithRefreshes(matcher) // May need to refresh before the star shows up
onView(matcher).assertDisplayed()
}
/**
* Asserts that the conversation with the specified subject is not starred.
*
* @param subject The subject of the conversation.
*/
fun assertConversationNotStarred(subject: String) {
val matcher = Matchers.allOf(
withId(R.id.star),
ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
hasSibling(withId(R.id.userName)),
hasSibling(withId(R.id.date)),
hasSibling(Matchers.allOf(withId(R.id.subjectView), withText(subject)))
)
waitForMatcherWithRefreshes(matcher) // May need to refresh before the star shows up
onView(matcher).check(ViewAssertions.doesNotExist())
}
/**
* Asserts that the conversation with the specified subject is displayed.
*
* @param subject The subject of the conversation.
*/
fun assertConversationDisplayed(subject: String) {
val matcher = withText(subject)
waitForView(matcher).scrollTo().assertDisplayed()
}
/**
* Asserts that the conversation with the specified subject is not displayed.
*
* @param subject The subject of the conversation.
*/
fun assertConversationNotDisplayed(subject: String) {
val matcher = withText(subject)
onView(matcher).check(ViewAssertions.doesNotExist())
}
/**
* Asserts the visibility of the unread marker for the conversation with the specified subject.
*
* @param subject The subject of the conversation.
* @param visibility The expected visibility of the unread marker.
*/
fun assertUnreadMarkerVisibility(subject: String, visibility: ViewMatchers.Visibility) {
val matcher = Matchers.allOf(
withId(R.id.unreadMark),
ViewMatchers.withEffectiveVisibility(visibility),
hasSibling(Matchers.allOf(withId(R.id.avatar))),
hasSibling(Matchers.allOf(withId(R.id.subjectView), withText(subject)))
)
if(visibility == ViewMatchers.Visibility.VISIBLE) {
waitForMatcherWithRefreshes(matcher) // May need to refresh before the unread mark shows up
scrollRecyclerView(R.id.inboxRecyclerView, matcher)
onView(matcher).assertDisplayed()
}
else if(visibility == ViewMatchers.Visibility.GONE) {
onView(matcher).check(ViewAssertions.matches(Matchers.not(ViewMatchers.isDisplayed())))
}
}
/**
* Selects the conversation with the specified subject.
*
* @param conversationSubject The subject of the conversation to select.
*/
fun selectConversation(conversationSubject: String) {
waitForView(withId(R.id.inboxRecyclerView))
val matcher = withText(conversationSubject)
onView(matcher).scrollTo().longClick()
}
/**
* Selects the conversation with the specified subject.
*
* @param conversation The conversation to select.
*/
fun selectConversation(conversation: Conversation) {
selectConversation(conversation.subject!!)
}
/**
* Selects the conversation with the specified subject.
*
* @param conversation The conversation to select.
*/
fun selectConversation(conversation: ConversationApiModel) {
selectConversation(conversation.subject!!)
}
/**
* Clicks the archive option in the action mode.
*/
fun clickArchive() {
waitForViewWithId(R.id.inboxArchiveSelected).click()
}
/**
* Clicks the unarchive option in the action mode.
*/
fun clickUnArchive() {
waitForViewWithId(R.id.inboxUnarchiveSelected).click()
}
/**
* Clicks the star option in the action mode.
*/
fun clickStar() {
waitForViewWithId(R.id.inboxStarSelected).click()
}
/**
* Clicks the unstar option in the action mode.
*/
fun clickUnstar() {
waitForViewWithId(R.id.inboxUnstarSelected).click()
}
/**
* Clicks the mark as read option in the action mode.
*/
fun clickMarkAsRead() {
waitForViewWithId(R.id.inboxMarkAsReadSelected).click()
}
/**
* Clicks the mark as unread option in the action mode.
*/
fun clickMarkAsUnread() {
waitForViewWithId(R.id.inboxMarkAsUnreadSelected).click()
}
/**
* Clicks the delete option in the action mode.
*/
fun clickDelete() {
Espresso.openActionBarOverflowOrOptionsMenu(
InstrumentationRegistry.getInstrumentation().getTargetContext()
)
onView(ViewMatchers.withText("Delete"))
.perform(ViewActions.click());
}
/**
* Confirms the delete action.
*/
fun confirmDelete() {
waitForView(withText("DELETE") + withAncestor(R.id.buttonPanel)).click()
}
/**
* Swipes the conversation with the specified subject to the right.
*
* @param conversationSubject The subject of the conversation to swipe.
*/
fun swipeConversationRight(conversationSubject: String) {
waitForView(withId(R.id.inboxRecyclerView))
val matcher = withText(conversationSubject)
onView(matcher).scrollTo().swipeRight()
}
/**
* Swipes the conversation to the right.
*
* @param conversation The conversation to swipe.
*/
fun swipeConversationRight(conversation: ConversationApiModel) {
swipeConversationRight(conversation.subject!!)
}
/**
* Swipes the conversation to the right.
*
* @param conversation The conversation to swipe.
*/
fun swipeConversationRight(conversation: Conversation) {
swipeConversationRight(conversation.subject!!)
}
/**
* Swipes the conversation with the specified subject to the left.
*
* @param conversationSubject The subject of the conversation to swipe.
*/
fun swipeConversationLeft(conversationSubject: String) {
waitForView(withId(R.id.inboxRecyclerView))
val matcher = withText(conversationSubject)
onView(matcher).scrollTo()
onView(matcher).swipeLeft()
}
/**
* Swipes the conversation to the left.
*
* @param conversation The conversation to swipe.
*/
fun swipeConversationLeft(conversation: Conversation) {
swipeConversationLeft(conversation.subject!!)
}
/**
* Swipes the conversation to the left.
*
* @param conversation The conversation to swipe.
*/
fun swipeConversationLeft(conversation: ConversationApiModel) {
swipeConversationLeft(conversation.subject!!)
}
/**
* Selects multiple conversations.
*
* @param conversations The list of conversation subjects to select.
*/
fun selectConversations(conversations: List<String>) {
for(conversation in conversations) {
selectConversation(conversation)
}
}
/**
* Asserts the selected conversation number in the edit toolbar.
*
* @param selectedConversationNumber The expected selected conversation number.
*/
fun assertSelectedConversationNumber(selectedConversationNumber: String) {
onView(withText(selectedConversationNumber) + withAncestor(R.id.editToolbar))
}
/**
* Asserts the visibility of the edit toolbar.
*
* @param visibility The expected visibility of the edit toolbar.
*/
fun assertEditToolbarIs(visibility: ViewMatchers.Visibility) {
editToolbar.assertVisibility(visibility)
}
/**
* Asserts that the star icon is displayed.
*/
fun assertStarDisplayed() {
waitForViewWithId(R.id.inboxStarSelected).assertDisplayed()
}
/**
* Asserts that the unstar icon is displayed.
*/
fun assertUnStarDisplayed() {
waitForViewWithId(R.id.inboxUnstarSelected).assertDisplayed()
}
}
| 2 | Kotlin | 98 | 119 | 909acab97f879b6fa60a3f53e1e9e3869e707e6d | 14,617 | canvas-android | Apache License 2.0 |
app/src/main/java/com/greenart7c3/nostrsigner/ui/actions/RelaySelectionDialog.kt | greenart7c3 | 671,206,453 | false | null | package com.greenart7c3.nostrsigner.ui.actions
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.greenart7c3.nostrsigner.service.relays.Relay
import kotlinx.coroutines.launch
data class RelayList(
val relay: Relay,
val isSelected: Boolean
)
val ButtonBorder = RoundedCornerShape(20.dp)
val Size20Modifier = Modifier.size(20.dp)
@Composable
fun CloseButton(onCancel: () -> Unit) {
Button(
onClick = {
onCancel()
},
shape = ButtonBorder,
colors = ButtonDefaults
.buttonColors(
backgroundColor = Color.Gray
)
) {
CloseIcon()
}
}
@Composable
fun PostButton(modifier: Modifier = Modifier, onPost: () -> Unit = {}, isActive: Boolean) {
Button(
modifier = modifier,
onClick = {
if (isActive) {
onPost()
}
},
shape = ButtonBorder,
colors = ButtonDefaults
.buttonColors(
backgroundColor = if (isActive) MaterialTheme.colors.primary else Color.Gray
),
contentPadding = PaddingValues(0.dp)
) {
Text(text = "Post", color = Color.White)
}
}
@Composable
fun CloseIcon() {
Icon(
Icons.Default.Cancel,
contentDescription = "Cancel",
modifier = Size20Modifier,
tint = Color.White
)
}
@Composable
fun RelaySelectionDialog(
list: List<Relay>,
selectRelays: List<Relay>,
onClose: () -> Unit,
onPost: (list: List<Relay>) -> Unit
) {
val scope = rememberCoroutineScope()
val context = LocalContext.current
var relays by remember {
mutableStateOf(
list.map {
RelayList(
it,
if (selectRelays.isNotEmpty()) selectRelays.any { relay -> it.url == relay.url } else true
)
}
)
}
var selected by remember {
mutableStateOf(true)
}
Dialog(
onDismissRequest = { onClose() },
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnClickOutside = false,
decorFitsSystemWindows = false
)
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(start = 10.dp, end = 10.dp, top = 10.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
CloseButton(
onCancel = {
onClose()
}
)
PostButton(
onPost = {
val selectedRelays = relays.filter { it.isSelected }
if (selectedRelays.isEmpty()) {
scope.launch {
Toast.makeText(context, "Select a relay to continue", Toast.LENGTH_SHORT).show()
}
return@PostButton
}
onPost(selectedRelays.map { it.relay })
onClose()
},
isActive = true
)
}
RelaySwitch(
text = "Select/Deselect all",
checked = selected,
onClick = {
selected = !selected
relays = relays.mapIndexed { _, item ->
item.copy(isSelected = selected)
}
}
)
LazyColumn(
contentPadding = PaddingValues(
top = 10.dp,
bottom = 10.dp
)
) {
itemsIndexed(
relays,
key = { _, item -> item.relay.url }
) { index, item ->
RelaySwitch(
text = item.relay.url
.removePrefix("ws://")
.removePrefix("wss://")
.removeSuffix("/"),
checked = item.isSelected,
onClick = {
relays = relays.mapIndexed { j, item ->
if (index == j) {
item.copy(isSelected = !item.isSelected)
} else {
item
}
}
}
)
}
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun RelaySwitch(text: String, checked: Boolean, onClick: () -> Unit, onLongPress: () -> Unit = { }) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.combinedClickable(
onClick = onClick,
onLongClick = onLongPress
)
) {
Text(
modifier = Modifier.weight(1f),
text = text
)
Switch(
checked = checked,
onCheckedChange = {
onClick()
}
)
}
}
| 0 | Kotlin | 0 | 11 | 26f483ecad8ef5f93823395420cc8dcc498ddc88 | 7,533 | Amber | MIT License |
app/src/main/java/com/c22_pc383/wacayang/ProfileFragment.kt | Wacayang-Bangkit-2022 | 493,616,059 | false | {"Kotlin": 91881} | package com.c22_pc383.wacayang
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.c22_pc383.wacayang.databinding.FragmentProfileBinding
import com.c22_pc383.wacayang.helper.IGeneralSetup
import com.c22_pc383.wacayang.helper.Utils
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class ProfileFragment : Fragment(), IGeneralSetup {
private lateinit var binding: FragmentProfileBinding
private lateinit var auth: FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentProfileBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
childFragmentManager.beginTransaction().replace(R.id.child_fragment, SettingFragment()).commit()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
setup()
}
override fun setup() {
auth = Firebase.auth
if (!Utils.isCurrentUserAnonymous()) {
binding.apply {
auth.currentUser?.let {
itemTitle.text = it.displayName
itemSubtitle.text = it.email
Glide.with(requireContext())
.load(it.photoUrl)
.placeholder(Utils.getCircularProgressDrawable(requireContext()))
.circleCrop()
.into(itemImage)
}
}
}
}
} | 0 | Kotlin | 0 | 1 | c1043c6395e85c7c52d854aea6b1c54460d8793f | 1,806 | Wacayang-MobileDev | Microsoft Public License |
app/src/main/java/com/elementary/tasks/reminder/build/reminder/compose/ReminderCleaner.kt | naz013 | 165,067,747 | false | {"Kotlin": 2971145, "HTML": 20925} | package com.elementary.tasks.reminder.build.reminder.compose
import com.elementary.tasks.core.data.models.Reminder
import com.elementary.tasks.core.data.ui.reminder.UiReminderType
import timber.log.Timber
class ReminderCleaner {
operator fun invoke(reminder: Reminder) {
val type = UiReminderType(reminder.type)
when {
type.isByDate() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_DATE")
reminder.weekdays = listOf()
reminder.dayOfMonth = 0
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.recurDataObject = null
}
type.isTimer() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_TIME")
reminder.weekdays = listOf()
reminder.delay = 0
reminder.eventCount = 0
reminder.recurDataObject = null
}
type.isByWeekday() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_WEEK")
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.repeatInterval = 0
reminder.recurDataObject = null
}
type.isMonthly() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_MONTH")
reminder.weekdays = listOf()
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.recurDataObject = null
}
type.isYearly() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_DAY_OF_YEAR")
reminder.weekdays = listOf()
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.repeatInterval = 0
reminder.recurDataObject = null
}
type.isGpsType() -> {
Timber.d("invoke: clean up for ${reminder.type} as BY_GPS")
reminder.exportToCalendar = false
reminder.exportToTasks = false
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.repeatInterval = 0
reminder.recurDataObject = null
}
type.isRecur() -> {
Timber.d("invoke: clean up for ${reminder.type} as ICAL")
reminder.weekdays = listOf()
reminder.after = 0L
reminder.delay = 0
reminder.eventCount = 0
reminder.repeatInterval = 0
}
type.isSubTasks() -> {
Timber.d("invoke: clean up for ${reminder.type} as SUB_TASKS")
reminder.target = ""
}
else -> {
Timber.d("invoke: nothing to clean up for ${reminder.type}")
}
}
}
}
| 0 | Kotlin | 3 | 6 | a6eecfda739be05a4b84e7d47284cd9e2bc782d6 | 2,580 | reminder-kotlin | Apache License 2.0 |
core/actions/src/main/java/com/choidev/core/actions/SystemActions.kt | victory316 | 660,866,016 | false | null | package com.choidev.core.actions
sealed interface SystemAction : Action {
data class ShowToast(val message: String) : SystemAction
}
| 9 | Kotlin | 0 | 0 | 90efd575940a06b31b3e84bdebc4f9a1ce5d6737 | 138 | LatestEffort | Apache License 2.0 |
app/src/main/java/com/github/zsoltk/chesso/model/board/File.kt | zsoltk | 369,016,520 | false | null | package com.deveshmittal.chess.model.board
enum class File {
a, b, c, d, e, f, g, h
}
operator fun File.get(rank: Int): Position =
Position.values()[this.ordinal * 8 + (rank - 1)]
operator fun File.get(rank: Rank): Position =
Position.values()[this.ordinal * 8 + rank.ordinal]
| 2 | Kotlin | 6 | 87 | e31f0913a6af64f7769112f49a909e8ee52d8d09 | 293 | chesso | Apache License 2.0 |
src/main/kotlin/org/kamiblue/client/module/modules/render/Chams.kt | NotMonika | 509,486,355 | false | {"Kotlin": 1389924, "Java": 110277, "Shell": 15180, "GLSL": 3626} | package org.kamiblue.client.module.modules.render
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.entity.Entity
import net.minecraft.entity.item.EntityEnderCrystal
import net.minecraft.entity.item.EntityItem
import net.minecraft.entity.item.EntityXPOrb
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.projectile.EntityArrow
import net.minecraft.entity.projectile.EntityThrowable
import net.minecraftforge.fml.common.gameevent.TickEvent
import org.kamiblue.client.event.Phase
import org.kamiblue.client.event.events.RenderEntityEvent
import org.kamiblue.client.module.Category
import org.kamiblue.client.module.Module
import org.kamiblue.client.util.EntityUtils
import org.kamiblue.client.util.EntityUtils.mobTypeSettings
import org.kamiblue.client.util.color.HueCycler
import org.kamiblue.client.util.graphics.GlStateUtils
import org.kamiblue.client.util.threads.safeListener
import org.kamiblue.event.listener.listener
import org.lwjgl.opengl.GL11.*
internal object Chams : Module(
name = "Chams",
category = Category.RENDER,
description = "Modify entity rendering"
) {
private val page by setting("Page", Page.ENTITY_TYPE)
/* Entity type settings */
private val self by setting("Self", false, { page == Page.ENTITY_TYPE })
private val all by setting("All Entities", false, { page == Page.ENTITY_TYPE })
private val experience by setting("Experience", false, { page == Page.ENTITY_TYPE && !all })
private val arrows by setting("Arrows", false, { page == Page.ENTITY_TYPE && !all })
private val throwable by setting("Throwable", false, { page == Page.ENTITY_TYPE && !all })
private val items by setting("Items", false, { page == Page.ENTITY_TYPE && !all })
private val crystals by setting("Crystals", false, { page == Page.ENTITY_TYPE && !all })
private val players by setting("Players", true, { page == Page.ENTITY_TYPE && !all })
private val friends by setting("Friends", false, { page == Page.ENTITY_TYPE && !all && players })
private val sleeping by setting("Sleeping", false, { page == Page.ENTITY_TYPE && !all && players })
private val mobs by setting("Mobs", true, { page == Page.ENTITY_TYPE && !all })
private val passive by setting("Passive Mobs", false, { page == Page.ENTITY_TYPE && !all && mobs })
private val neutral by setting("Neutral Mobs", true, { page == Page.ENTITY_TYPE && !all && mobs })
private val hostile by setting("Hostile Mobs", true, { page == Page.ENTITY_TYPE && !all && mobs })
/* Rendering settings */
private val throughWall by setting("Through Wall", true, { page == Page.RENDERING })
private val texture by setting("Texture", false, { page == Page.RENDERING })
private val lightning by setting("Lightning", false, { page == Page.RENDERING })
private val customColor by setting("Custom Color", false, { page == Page.RENDERING })
private val rainbow by setting("Rainbow", false, { page == Page.RENDERING && customColor })
private val r by setting("Red", 255, 0..255, 1, { page == Page.RENDERING && customColor && !rainbow })
private val g by setting("Green", 255, 0..255, 1, { page == Page.RENDERING && customColor && !rainbow })
private val b by setting("Blue", 255, 0..255, 1, { page == Page.RENDERING && customColor && !rainbow })
private val a by setting("Alpha", 160, 0..255, 1, { page == Page.RENDERING && customColor })
private enum class Page {
ENTITY_TYPE, RENDERING
}
private var cycler = HueCycler(600)
init {
listener<RenderEntityEvent.All>(2000) {
if (!checkEntityType(it.entity)) return@listener
when (it.phase) {
Phase.PRE -> {
if (throughWall) glDepthRange(0.0, 0.01)
}
Phase.PERI -> {
if (throughWall) glDepthRange(0.0, 1.0)
}
else -> {
// Doesn't need to do anything on post phase
}
}
}
listener<RenderEntityEvent.Model> {
if (!checkEntityType(it.entity)) return@listener
when (it.phase) {
Phase.PRE -> {
if (!texture) glDisable(GL_TEXTURE_2D)
if (!lightning) glDisable(GL_LIGHTING)
if (customColor) {
if (rainbow) cycler.currentRgba(a).setGLColor()
else glColor4f(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f)
GlStateUtils.blend(true)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO)
}
}
Phase.POST -> {
if (!texture) glEnable(GL_TEXTURE_2D)
if (!lightning) glEnable(GL_LIGHTING)
if (customColor) {
GlStateUtils.blend(false)
glColor4f(1f, 1f, 1f, 1f)
}
}
else -> {
// RenderEntityEvent.Model doesn't have peri phase
}
}
}
safeListener<TickEvent.ClientTickEvent> {
if (it.phase == TickEvent.Phase.START) cycler++
}
}
private fun checkEntityType(entity: Entity) =
(self || entity != mc.player) && (
all
|| experience && entity is EntityXPOrb
|| arrows && entity is EntityArrow
|| throwable && entity is EntityThrowable
|| items && entity is EntityItem
|| crystals && entity is EntityEnderCrystal
|| players && entity is EntityPlayer && EntityUtils.playerTypeCheck(entity, friends, sleeping)
|| mobTypeSettings(entity, mobs, passive, neutral, hostile)
)
}
| 0 | Kotlin | 0 | 0 | 88dc5a7e96ba358898b03681bfdf760e93f94812 | 5,914 | __AntiZhangZongZe__ | Do What The F*ck You Want To Public License |
acme-domain/acme-domain-scheduling/src/test/kotlin/com/acme/scheduling/PractitionerTest.kt | mattupstate | 496,835,485 | false | {"Kotlin": 268687, "HCL": 28862, "HTML": 15841, "Smarty": 9320, "Shell": 2578, "Dockerfile": 460, "PLpgSQL": 179} | package com.acme.scheduling
import io.kotest.core.annotation.Ignored
import io.kotest.core.spec.style.ShouldSpec
@Ignored
class PractitionerTest : ShouldSpec({
val fixture = Practitioner(
id = Practitioner.Id("Practitioner123"),
user = UserId("User123"),
names = setOf(
HumanName(
family = Name.Family("World"),
given = Name.Given("Hello"),
prefix = Name.Prefix(""),
suffix = Name.Suffix(""),
period = Period.Unknown
)
),
gender = Gender.UNKNOWN,
contactPoints = emptySet()
)
})
| 0 | Kotlin | 0 | 6 | 302f7fb4e96e291bda6ac71f212f6d4d84adc2b3 | 562 | acme | MIT License |
src/main/kotlin/dev/throwouterror/util/data/JsonUtils.kt | throw-out-error | 275,984,155 | false | null | package dev.throwouterror.util.data
import com.google.gson.Gson
import com.google.gson.GsonBuilder
object JsonUtils {
val builder: Gson = GsonBuilder().setPrettyPrinting().create()
}
| 3 | Kotlin | 0 | 0 | bda30b0f1dbb7851b74ff47f5204b7b1aa138816 | 190 | toe-utils | MIT License |
domain/src/main/kotlin/ru/cinema/domain/movie/model/ContentForm.kt | alexBlack01 | 541,182,433 | false | {"Kotlin": 279406, "Procfile": 34} | package ru.cinema.domain.movie.model
data class ContentForm(
val fileBytes: ByteArray,
val fileType: String
)
| 0 | Kotlin | 0 | 0 | 97e1909d029b245c9e1d95a70746a7483073107b | 119 | cinema-backend | Apache License 1.1 |
src/main/kotlin/sspeiser/gMockGen/OutputConsole.kt | sfspeiser | 842,119,377 | false | {"Kotlin": 11898} | package sspeiser.gMockGen
import com.intellij.execution.filters.TextConsoleBuilderFactory
import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.content.Content
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
enum class ConsoleLogLevel {
INFO, ERROR
}
@Service(Service.Level.PROJECT)
class OutputConsole(project: Project) {
private val myProject: Project = project
@get:Synchronized
private var consoleView: ConsoleView? = null
get() {
if (field == null) {
field = createConsoleView(myProject)
}
return field
}
private fun createConsoleView(project: Project): ConsoleView {
val newConsoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).console
val toolWindow: ToolWindow? = ToolWindowManager.getInstance(project)
.getToolWindow("gMockGen")
ApplicationManager.getApplication().invokeLater {
if (toolWindow != null) {
toolWindow.show {
val content: Content = toolWindow.getContentManager()
.getFactory()
.createContent(newConsoleView.component, "gMock Generator", true)
toolWindow.getContentManager().addContent(content)
}
}
}
return newConsoleView
}
fun log(msg: String?, logLevel: ConsoleLogLevel) {
val consoleViewContentType = if (logLevel == ConsoleLogLevel.INFO) {
ConsoleViewContentType.NORMAL_OUTPUT
} else if (logLevel == ConsoleLogLevel.ERROR) {
ConsoleViewContentType.ERROR_OUTPUT
} else {
throw IllegalArgumentException(String.format("Unknown log level %s", logLevel))
}
consoleView?.print(
java.lang.String.format("%s %s > %s\n", logLevel, nowFormatted, msg),
consoleViewContentType
)
}
fun info(msg: String?) {
log(msg, ConsoleLogLevel.INFO)
}
fun error(msg: String?) {
log(msg, ConsoleLogLevel.ERROR)
}
private val nowFormatted: String
get() = DateTimeFormat.forPattern("HH:mm:ss.SSS").print(DateTime.now())
fun clear() {
consoleView!!.clear()
}
companion object {
fun get(project: Project): OutputConsole {
return project.getService(OutputConsole::class.java)
}
}
} | 0 | Kotlin | 0 | 0 | 9b756a9069fc92a206868464608e3817b8bdd0b2 | 2,747 | gMockGen | MIT License |
compiler/testData/diagnostics/tests/extensions/contextReceivers/deprecated.fir.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // LANGUAGE: +ContextReceivers
class A
class B
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
fun topLevelFun() {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A, B)
fun topLevelFunTwoReceivers() {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
var varProp: Int
get() = 42
set(newVal) {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
val valProp: Int get() = 42
<!CONTEXT_RECEIVERS_DEPRECATED, CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
class Clazz {
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
fun memberFun() {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
fun B.memberExtFun() {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
var varProp: Int
get() = 42
set(newVal) {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
val valProp: Int get() = 42
}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
class Clazz2 {
<!CONTEXT_RECEIVERS_DEPRECATED!>constructor()<!>
}
fun typeRef(body: <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A) () -> Unit): <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A) () -> Unit {
val x: <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A) () -> Unit = body
val y = body
val z: suspend <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A) B.() -> Unit = {}
val w: (<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(Int) () -> Unit, <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(Int) () -> Unit) -> (<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(Int) () -> Unit) = { a, b -> { } }
return {}
}
typealias typealiasDecl = <!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A) B.() -> Unit
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
fun Clazz.ext() {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
val Clazz.extVal: Int get() = 904
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
var Clazz.extVar: Int
get() = 904
set(newVal) {}
<!CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
interface I {}
<!CONTEXT_RECEIVERS_DEPRECATED, CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A, B)
class ClazzTwoReceivers {}
<!CONTEXT_RECEIVERS_DEPRECATED, CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
enum class E
<!CONTEXT_RECEIVERS_DEPRECATED, CONTEXT_RECEIVERS_DEPRECATED!>context<!>(A)
object O
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 2,155 | kotlin | Apache License 2.0 |
src/main/kotlin/frc/chargers/utils/math/MapBetweenRanges.kt | frc-5160-the-chargers | 497,722,545 | false | {"Kotlin": 438322, "Java": 56704} | package frc.chargers.utils.math
import com.batterystaple.kmeasure.dimensions.AnyDimension
import com.batterystaple.kmeasure.quantities.Quantity
public fun Double.mapBetweenRanges(from: ClosedRange<Double>, to: ClosedRange<Double>): Double {
require(this in from) { "An error has occured: your value($this) is not within the starting range($from)." }
val proportionIntoRange: Double = (this - from.start) / (from.endInclusive - from.start)
val distanceIntoToRange: Double = proportionIntoRange * (to.endInclusive - to.start)
return to.start + distanceIntoToRange
}
public fun <D: AnyDimension> Quantity<D>.mapBetweenRanges(
from: ClosedRange<Quantity<D>>,
to: ClosedRange<Quantity<D>>
): Quantity<D> = Quantity(
this.siValue.mapBetweenRanges(
from.start.siValue..from.endInclusive.siValue,
to.start.siValue..to.endInclusive.siValue
)
) | 3 | Kotlin | 0 | 2 | ef0bca03f00901ffcc5508981089edced59f91aa | 887 | ChargerLib | MIT License |
src/main/kotlin/frc/chargers/utils/math/MapBetweenRanges.kt | frc-5160-the-chargers | 497,722,545 | false | {"Kotlin": 438322, "Java": 56704} | package frc.chargers.utils.math
import com.batterystaple.kmeasure.dimensions.AnyDimension
import com.batterystaple.kmeasure.quantities.Quantity
public fun Double.mapBetweenRanges(from: ClosedRange<Double>, to: ClosedRange<Double>): Double {
require(this in from) { "An error has occured: your value($this) is not within the starting range($from)." }
val proportionIntoRange: Double = (this - from.start) / (from.endInclusive - from.start)
val distanceIntoToRange: Double = proportionIntoRange * (to.endInclusive - to.start)
return to.start + distanceIntoToRange
}
public fun <D: AnyDimension> Quantity<D>.mapBetweenRanges(
from: ClosedRange<Quantity<D>>,
to: ClosedRange<Quantity<D>>
): Quantity<D> = Quantity(
this.siValue.mapBetweenRanges(
from.start.siValue..from.endInclusive.siValue,
to.start.siValue..to.endInclusive.siValue
)
) | 3 | Kotlin | 0 | 2 | ef0bca03f00901ffcc5508981089edced59f91aa | 887 | ChargerLib | MIT License |
src/main/kotlin/no/nav/klage/pdfgen/config/ProblemHandlingControllerAdvice.kt | navikt | 409,564,766 | false | null | package no.nav.klage.pdfgen.config
import no.nav.klage.pdfgen.exception.ValidationException
import no.nav.klage.pdfgen.util.getSecureLogger
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
@RestControllerAdvice
class ProblemHandlingControllerAdvice : ResponseEntityExceptionHandler() {
companion object {
private val secureLogger = getSecureLogger()
}
@ExceptionHandler
fun handleValidationException(
ex: ValidationException,
request: NativeWebRequest
): ProblemDetail =
create(HttpStatus.BAD_REQUEST, ex)
private fun create(httpStatus: HttpStatus, ex: Exception): ProblemDetail {
val errorMessage = ex.message ?: "No error message available"
logError(
httpStatus = httpStatus,
errorMessage = errorMessage,
exception = ex
)
return ProblemDetail.forStatusAndDetail(httpStatus, errorMessage).apply {
title = errorMessage
}
}
private fun logError(httpStatus: HttpStatus, errorMessage: String, exception: Exception) {
when {
httpStatus.is5xxServerError -> {
secureLogger.error("Exception thrown to client: ${httpStatus.reasonPhrase}, $errorMessage", exception)
}
else -> {
secureLogger.warn("Exception thrown to client: ${httpStatus.reasonPhrase}, $errorMessage", exception)
}
}
}
}
| 2 | Kotlin | 0 | 0 | 4f7cbb13b5fe027a52edd95c7d43086c10750fa3 | 1,768 | kabal-json-to-pdf | MIT License |
app/src/main/java/com/f2h/f2h_buyer/utils/WalletBindingUtils.kt | Farm2Home | 245,578,294 | false | {"Kotlin": 264478} | package com.f2h.f2h_buyer.utils
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import com.f2h.f2h_buyer.R
import com.f2h.f2h_buyer.network.models.Wallet
import com.f2h.f2h_buyer.screens.group.group_wallet.GroupWalletViewModel
import com.f2h.f2h_buyer.screens.group.group_wallet.WalletItemsModel
import java.text.DateFormat
import java.text.SimpleDateFormat
@BindingAdapter("walletBalanceFormatted")
fun TextView.setWalletBalanceFormatted(data: Wallet?) {
text = String.format("Balance : %s%.0f", data?.currency, data?.balance)
}
@BindingAdapter("transactionAmountFormatted")
fun TextView.setPriceFormatted(data: WalletItemsModel?){
data?.let {
val colouredText = SpannableString(String.format("%s %.0f", data.currency, data.amount))
if (data.amount > 0){
colouredText.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.green_status)),0, colouredText.length,0)
}
if (data.amount < 0){
colouredText.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.red_status)),0, colouredText.length,0)
}
text = colouredText
}
}
@BindingAdapter("transactionDateFormatted")
fun TextView.settransactionDateFormatted(data: WalletItemsModel?) {
data?.let {
val df: DateFormat = SimpleDateFormat("yyyy-MM-dd")
val df_out: DateFormat = SimpleDateFormat("dd-MMM-EEEE")
if (data.transactionDate.isNullOrBlank()) {
text = ""
return
}
var formattedDate: String = df_out.format(df.parse(data.transactionDate))
text = String.format("%s", formattedDate)
}
}
| 0 | Kotlin | 0 | 0 | 16c8f32d7927f6d5739de21d1e427cd8f4701875 | 1,792 | f2h_buyer | MIT License |
browser-kotlin/src/jsMain/kotlin/web/prompts/prompt.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6372546} | // Automatically generated - do not modify!
package web.prompts
external fun prompt(
message: String,
default: String = definedExternally,
): String?
| 0 | Kotlin | 6 | 27 | 27e59504d558202951d0f4fffec55edd78878ac4 | 160 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/example/gamy/models/BoardSize.kt | soundarya-code | 574,328,212 | false | {"Kotlin": 31622} | package com.example.gamy.models
enum class BoardSize(val numCards:Int) {
EASY(8),MEDIUM(18),HARD(24);
companion object{
fun getByValue(value:Int)= values().first{
it.numCards==value
}
}
fun getWidth():Int{
return when(this){
EASY->2
MEDIUM->3
HARD->4
}
}
fun getHeight():Int{
return numCards/getWidth()
}
fun getNumPairs():Int{
return numCards/2
}
} | 0 | Kotlin | 0 | 0 | f9ce094f6bdb04fcc91603d4912176b080b8ee6b | 482 | Android-Memory-Game | Apache License 2.0 |
src/main/kotlin/com/cyan/cyanadmin/Repositories.kt | cthanhnguyendn | 253,547,272 | false | {"JavaScript": 15706, "Kotlin": 14641, "CSS": 5609, "HTML": 1747} | package com.cyan.cyanadmin
import org.springframework.data.repository.CrudRepository
import org.springframework.data.rest.core.annotation.RepositoryRestResource
@RepositoryRestResource(collectionResourceRel = "merchant", path = "merchant")
interface MerchantRepository :CrudRepository<Merchant,Long>
@RepositoryRestResource(collectionResourceRel = "user", path = "user")
interface UserRepository :CrudRepository<User,Long> | 23 | JavaScript | 0 | 0 | 6acc9712965dc589cb123bc36b2ccc6eb3e70e8a | 425 | cyan-boot-admin | Apache License 2.0 |
app/src/main/java/com/nielaclag/openweather/domain/model/LocalUser.kt | knightniel | 878,358,271 | false | {"Kotlin": 421417} | package com.nielaclag.openweather.domain.model
import com.nielaclag.openweather.domain.model.type.AuthenticationType
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Created by Niel on 10/21/2024.
*/
@JsonClass(generateAdapter = true)
data class LocalUser(
@Json(name = "id")
val id: Long,
@Json(name = "name")
val name: String?,
@Json(name = "email")
val email: String?,
@Json(name = "image")
val image: String?,
@Json(name = "authenticationType")
val authenticationType: AuthenticationType
) | 0 | Kotlin | 0 | 0 | 9dea4075f20a42b97e58e77d273e2ff8191700fd | 561 | OpenWeather | MIT License |
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/omsorgsopptjening/OmsorgsOpptjening.kt | navikt | 593,529,397 | false | null | package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsarbeid.OmsorgsArbeidSakDataObject
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.paragraf.vilkar.VilkarsResultat
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.person.Person
class OmsorgsOpptjening(
val omsorgsAr: Int,
val person: Person,
val grunnlag: OmsorgsArbeidSakDataObject,
val omsorgsopptjeningResultater: VilkarsResultat<*>,
val invilget: Boolean
) | 0 | Kotlin | 0 | 0 | 9c2dfe2f6e657e6a22ce51cc1492759237fc8f31 | 619 | omsorgsopptjening-bestem-pensjonsopptjening | MIT License |
simple-adapter-viewbinding/src/main/java/tech/thdev/simpleadapter/holder/SimpleViewBindingViewHolder.kt | taehwandev | 254,646,753 | false | null | package tech.thdev.simpleadapter.holder
import androidx.viewbinding.ViewBinding
import tech.thdev.simpleadapter.data.SimpleViewBindingViewHolderItem
class SimpleViewBindingViewHolder<BINDING : ViewBinding, in ITEM : Any>(
private val viewBinding: BINDING,
viewType: Int = -1,
private val bindViewHolder: SimpleViewBindingViewHolderItem<BINDING, ITEM>.() -> Unit
) : SimpleBaseViewHolder(
viewBinding.root,
viewType
) {
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(item: Any) {
try {
SimpleViewBindingViewHolderItem(viewBinding, item as ITEM)
.bindViewHolder()
} catch (e: Exception) {
// ...
}
}
}
| 0 | Kotlin | 1 | 13 | 7853b7ef7f30f7d137f99ce7a8f7ff199ebd920b | 711 | SimpleAdapter | Apache License 2.0 |
pgkotlin/src/commonMain/kotlin/com/bnorm/pgkotlin/Portal.kt | bnorm | 124,423,306 | false | null | package com.bnorm.pgkotlin
interface Portal {
suspend fun close()
}
| 2 | Kotlin | 0 | 8 | 84c1bd4a4d2a7c6c33a732aa2d5ce6ceb8f67253 | 71 | PgKotlin | Apache License 2.0 |
server/src/main/kotlin/net/horizonsend/ion/server/features/ai/spawning/spawner/LegacyFactionSpawner.kt | HorizonsEndMC | 461,042,096 | false | {"Kotlin": 3506791, "Java": 15809, "Shell": 1410, "JavaScript": 78} | package net.horizonsend.ion.server.features.ai.spawning.spawner
import net.horizonsend.ion.server.features.ai.configuration.WorldSettings
import net.horizonsend.ion.server.features.ai.spawning.formatLocationSupplier
import net.horizonsend.ion.server.features.ai.spawning.isSystemOccupied
import net.horizonsend.ion.server.features.ai.spawning.spawner.mechanics.SingleSpawn
import net.horizonsend.ion.server.features.ai.spawning.spawner.mechanics.WeightedShipSupplier
import net.horizonsend.ion.server.features.ai.spawning.spawner.scheduler.SpawnerScheduler
import net.horizonsend.ion.server.features.ai.util.SpawnMessage
import net.horizonsend.ion.server.miscellaneous.utils.weightedRandomOrNull
import net.kyori.adventure.text.Component
import java.util.function.Supplier
/**
* A standard AI spawner, spawns ships one at a time
**/
class LegacyFactionSpawner(
identifier: String,
override val scheduler: SpawnerScheduler,
spawnMessage: Component,
val worlds: List<WorldSettings>,
) : AISpawner(
identifier,
SingleSpawn(
WeightedShipSupplier(*worlds.flatMap { it.templates }.toTypedArray()),
Supplier {
val occupiedWorlds = worlds.filter { isSystemOccupied(it.getWorld()) }
val worldConfig = occupiedWorlds.weightedRandomOrNull { it.probability } ?: return@Supplier null
val bukkitWorld = worldConfig.getWorld()
return@Supplier formatLocationSupplier(bukkitWorld, worldConfig.minDistanceFromPlayer, worldConfig.maxDistanceFromPlayer).get()
},
SpawnMessage.WorldMessage(spawnMessage)
)
) {
init {
scheduler.setSpawner(this)
}
}
| 25 | Kotlin | 36 | 10 | 168d00ac77fcb3a968c1b3436e40e38422faebce | 1,563 | Ion | MIT License |
app-base/src/main/java/com/lhwdev/selfTestMacro/ui/composeColors.kt | lhwdev | 289,257,684 | false | null | package com.lhwdev.selfTestMacro.ui
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.lerp
val Colors.primaryActive: Color
@Composable get() = primaryActive(1f)
@Composable // friction + -> more primary
fun Colors.primaryActive(friction: Float): Color = when(val contentColor = LocalContentColor.current) {
onSurface, onBackground -> lerp(contentColor, primary, friction)
else -> lerp(primary, contentColor, friction * 0.5f + 0.5f) // to ensure legibility
}
val DefaultContentColor: Color
@Composable get() = LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
val MediumContentColor: Color
@Composable get() = LocalContentColor.current.copy(alpha = ContentAlpha.medium)
@Suppress("ComposableNaming")
@Composable
fun Color(onLight: Color, onDark: Color): Color =
if(MaterialTheme.colors.isLight) onLight else onDark
| 0 | Kotlin | 4 | 20 | e76877e60ffec8682f24709d5b66987b99bc3c7b | 951 | covid-selftest-macro | Apache License 2.0 |
app/src/main/java/dorin_roman/app/kongfujava/ui/components/IconLevel.kt | roma321m | 555,795,950 | false | {"Kotlin": 480911} | package dorin_roman.app.kongfujava.ui.components
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarOutline
import androidx.compose.material.icons.outlined.Lock
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import dorin_roman.app.kongfujava.ui.theme.star
@Composable
fun IconLevel(imageVector: ImageVector, tint: Color, modifier: Modifier) {
Icon(
imageVector = imageVector,
contentDescription = "icon",
tint = tint,
modifier = modifier
)
}
@Composable
fun LockLevel(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Outlined.Lock,
tint = Color.White,
modifier = Modifier
.alpha(0f)
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Outlined.Lock,
tint = Color.White,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Outlined.Lock,
tint = Color.White,
modifier = Modifier
.size(size)
.alpha(0f)
.padding(5.dp)
)
}
@Composable
fun ZeroLevelWhite(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = Color.White,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = Color.White,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = Color.White,
modifier = Modifier
.size(size)
.padding(5.dp)
)
}
@Composable
fun ZeroLevelYellow(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
}
@Composable
fun OneLevel(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
}
@Composable
fun TwoLevel(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.StarOutline,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
}
@Composable
fun ThreeLevel(type: String) {
val size = if (type == "World") 70.dp else 30.dp
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
IconLevel(
imageVector = Icons.Filled.Star,
tint = MaterialTheme.colors.star,
modifier = Modifier
.size(size)
.padding(5.dp)
)
} | 0 | Kotlin | 1 | 2 | 3c4f89aae10ca3f86e2cb6c1b0ecef3cb47729cd | 4,889 | Kong-Fu-Java | Apache License 2.0 |
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/requests/edit/text/EditInlineMessageText.kt | Djaler | 311,091,197 | true | {"Kotlin": 816932, "Shell": 373} | package dev.inmo.tgbotapi.requests.edit.text
import dev.inmo.tgbotapi.CommonAbstracts.*
import dev.inmo.tgbotapi.requests.edit.abstracts.*
import dev.inmo.tgbotapi.requests.edit.media.editMessageMediaMethod
import dev.inmo.tgbotapi.types.*
import dev.inmo.tgbotapi.types.MessageEntity.*
import dev.inmo.tgbotapi.types.ParseMode.ParseMode
import dev.inmo.tgbotapi.types.ParseMode.parseModeField
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup
import kotlinx.serialization.*
fun EditInlineMessageText(
inlineMessageId: InlineMessageIdentifier,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
replyMarkup: InlineKeyboardMarkup? = null
) = EditInlineMessageText(
inlineMessageId,
text,
parseMode,
null,
disableWebPagePreview,
replyMarkup
)
fun EditInlineMessageText(
inlineMessageId: InlineMessageIdentifier,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
replyMarkup: InlineKeyboardMarkup? = null
) = EditInlineMessageText(
inlineMessageId,
entities.makeString(),
null,
entities.toRawMessageEntities(),
disableWebPagePreview,
replyMarkup
)
@Serializable
data class EditInlineMessageText internal constructor(
@SerialName(inlineMessageIdField)
override val inlineMessageId: InlineMessageIdentifier,
@SerialName(textField)
override val text: String,
@SerialName(parseModeField)
override val parseMode: ParseMode? = null,
@SerialName(entitiesField)
private val rawEntities: List<RawMessageEntity>? = null,
@SerialName(disableWebPagePreviewField)
override val disableWebPagePreview: Boolean? = null,
@SerialName(replyMarkupField)
override val replyMarkup: InlineKeyboardMarkup? = null
) : EditInlineMessage, EditTextChatMessage, EditReplyMessage, EditDisableWebPagePreviewMessage {
override val entities: List<TextSource>? by lazy {
rawEntities ?.asTextParts(text ?: return@lazy null) ?.justTextSources()
}
override fun method(): String = editMessageMediaMethod
override val requestSerializer: SerializationStrategy<*>
get() = serializer()
}
| 0 | null | 0 | 0 | 83edda2dfe370fbc35f2e73283cd71e79f101e3c | 2,173 | TelegramBotAPI | Apache License 2.0 |
app/src/main/java/it/uniparthenope/parthenopeddit/android/adapters/PostAdapter.kt | GruppoProgettoTMM201920-Parthenopeddit | 264,177,213 | false | null | package it.uniparthenope.parthenopeddit.android.adapters
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import it.uniparthenope.parthenopeddit.R
import it.uniparthenope.parthenopeddit.model.Board
import it.uniparthenope.parthenopeddit.model.Post
import it.uniparthenope.parthenopeddit.util.DateParser
import kotlinx.android.synthetic.main.cardview_post.view.*
import kotlin.collections.ArrayList
class PostAdapter() : RecyclerView.Adapter<PostAdapter.PostViewHolder>() {
private val postList: ArrayList<Post> = ArrayList()
private var listener:PostItemClickListeners? = null
fun setItemClickListener( listener:PostItemClickListeners? ) {
this.listener = listener
}
fun aggiungiPost(postItemList: List<Post>) {
val initialSize = postList.size
this.postList.addAll(postItemList)
val updatedSize = postList.size
notifyItemRangeInserted(initialSize, updatedSize)
}
fun setPostList(postItemList: List<Post>) {
this.postList.clear()
this.postList.addAll(postItemList)
notifyDataSetChanged()
}
interface PostItemClickListeners {
fun onClickLike(id_post:Int, upvote_textview: TextView, downvote_textview: TextView)
fun onClickDislike(id_post:Int, upvote_textview: TextView, downvote_textview: TextView)
fun onClickComments(id_post:Int, post:Post)
fun onBoardClick(board_id: Int?, board: Board?)
fun onPostClick(id_post: Int, post:Post)
fun onUserClick(id_user: String)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.cardview_post,
parent, false)
return PostViewHolder(itemView)
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
val currentItem = postList[position]
holder.imageView.setImageResource(R.drawable.default_user_image)
holder.username_textview.text = currentItem.author?.display_name?:currentItem.author_id
holder.title_textview.text = currentItem.title
holder.board_textview.text = currentItem.posted_to_board?.name?:"Generale"
holder.timestamp_textview.text = DateParser.prettyParse(currentItem.timestamp)
holder.posttext_textview.text = currentItem.body
holder.upvote_textview.text = currentItem.likes_num.toString()
holder.downvote_textview.text = currentItem.dislikes_num.toString()
holder.comments_textview.text = currentItem.comments_num.toString()
if( currentItem.posted_to_board_id == 0 || currentItem.posted_to_board_id == null ) {
holder.board_textview.setBackgroundResource(R.drawable.general_textview_bubble)
holder.board_textview.setTextColor(Color.BLACK)
} else {
when (currentItem.posted_to_board!!.type) {
"course" -> {
holder.board_textview.setBackgroundResource(R.drawable.fab_textview_bubble)
holder.board_textview.setTextColor(Color.WHITE)
}
"group" -> {
holder.board_textview.setBackgroundResource(R.drawable.group_textview_bubble)
holder.board_textview.setTextColor(Color.WHITE)
}
else -> holder.board_textview.visibility = View.GONE
}
}
holder.upvote_btn.setOnClickListener {
listener?.onClickLike(currentItem.id, holder.upvote_textview, holder.downvote_textview)
}
holder.downvote_btn.setOnClickListener {
listener?.onClickDislike(currentItem.id, holder.upvote_textview, holder.downvote_textview)
}
holder.comment_btn.setOnClickListener {
listener?.onClickComments(currentItem.id, currentItem)
}
holder.board_textview.setOnClickListener {
listener?.onBoardClick(currentItem.posted_to_board_id, currentItem.posted_to_board)
}
holder.username_textview.setOnClickListener {
listener?.onUserClick(currentItem.author_id)
}
holder.relativeLayout.setOnClickListener {
listener?.onPostClick(currentItem.id, currentItem)
}
}
override fun getItemCount() = postList.size
class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { //SINGOLO ELEMENTO DELLA LISTA
val imageView: ImageView = itemView.image_view
val username_textview: TextView = itemView.username_textview
val title_textview: TextView = itemView.title_textview
val board_textview: TextView = itemView.group_textview
val timestamp_textview: TextView = itemView.timestamp_textview
val posttext_textview: TextView = itemView.posttext_textview
val upvote_btn: ImageButton = itemView.upvote_btn
val downvote_btn: ImageButton = itemView.downvote_btn
val upvote_textview: TextView = itemView.upvote_textview
val downvote_textview: TextView = itemView.downvote_textview
val comment_btn: ImageButton = itemView.comments_btn
val relativeLayout: RelativeLayout = itemView.post_relativelayout
val comments_textview: TextView = itemView.comments_textview
}
} | 0 | Kotlin | 0 | 0 | efd306b99cf3f0c6b42a033a161aee6a0fbcc933 | 5,435 | AndroidAPP | Apache License 2.0 |
app/src/main/java/ru/kartsev/dmitry/cryptorates/mvvm/model/network/api/CryptoApi.kt | Jaguarhl | 195,080,249 | false | null | package ru.kartsev.dmitry.cryptorates.mvvm.model.network.api
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Query
import ru.kartsev.dmitry.cryptorates.mvvm.model.entity.CoinListEntity
import ru.kartsev.dmitry.cryptorates.mvvm.model.entity.CoinsTopEntity
interface CryptoApi {
@GET("/data/top/totalvolfull")
fun getCoinsTopList(
@Query("limit") limit: Int? = null,
@Query("page") page: Int? = null,
@Query("tsym") currency: String
): Observable<CoinsTopEntity>
@GET("/data/all/coinlist")
fun getCoinList(): Observable<CoinListEntity>
} | 0 | Kotlin | 0 | 0 | ebbe7411b68edc53b0451e6bceb7cae7ad9ef3ff | 613 | crypto-currencies-rates | Apache License 2.0 |
app/src/main/kotlin/de/fabmax/calc/ui/Panel.kt | fabmax | 55,450,424 | false | null | package de.fabmax.calc.ui
import android.content.Context
import de.fabmax.lightgl.util.Color
import de.fabmax.lightgl.util.Painter
/**
* A panel with a single color background.
*/
open class Panel<T: PanelConfig>(config: T, context: Context) : UiElement<T>(config, context) {
/**
* Draws a rectangular shape with the current size and color of this panel
*/
override fun paint(painter: Painter) {
val color = layoutConfig.color
painter.setColor(color)
painter.fillRect(0.0f, 0.0f, width, height)
}
}
/**
* Panel specific LayoutConfiguration extended with a orientation dependent color.
*/
open class PanelConfig : LayoutConfig() {
private val props = Array(Orientation.ALL, { i -> PanelProperties() })
val color = FloatArray(4)
/**
* Interpolates panel size and color.
*/
override fun mixConfigs(portLandMix: Float) {
super.mixConfigs(portLandMix)
val colorP = props[Orientation.PORTRAIT].color
val colorL = props[Orientation.LANDSCAPE].color
color[0] = colorP.r * portLandMix + colorL.r * (1f - portLandMix)
color[1] = colorP.g * portLandMix + colorL.g * (1f - portLandMix)
color[2] = colorP.b * portLandMix + colorL.b * (1f - portLandMix)
color[3] = colorP.a * portLandMix + colorL.a * (1f - portLandMix)
}
fun getPanelProperties(orientation: Int): PanelProperties {
return props[orientation]
}
/**
* Sets the color for the given orientation. If orientation is Orientation.ALL, color is set
* for all orientations.
*/
fun setColor(orientation: Int, color: Color) {
if (orientation >= 0 && orientation < props.size) {
props[orientation].color = color
} else {
props.forEach { p -> p.color = color }
}
}
}
class PanelProperties {
var color = Color.LIGHT_GRAY
}
/**
* Base builder for panels, offers the color property.
*/
abstract class AbstractPanelBuilder<T: Panel<*>>(context: Context) : UiElementBuilder<T>(context) {
/**
* Panel color for the current orientation.
*/
var color: Color
get() = element.layoutConfig.getPanelProperties(orientation).color
set(value) {
element.layoutConfig.setColor(orientation, value)
}
}
class PanelBuilder(context: Context) : AbstractPanelBuilder<Panel<PanelConfig>>(context) {
override fun create(): Panel<PanelConfig> {
return Panel(PanelConfig(), context)
}
}
| 0 | Kotlin | 4 | 13 | 9673b8a3d99f7426c35e266bb633a278c86ec1d4 | 2,512 | calculator | Apache License 2.0 |
part-02/src/main/kotlin/eu/luminis/workshop/smallsteps/LegoRentingKtorModule.kt | nkrijnen | 557,352,579 | false | {"Kotlin": 49450} | package eu.luminis.workshop.smallsteps
import eu.luminis.workshop.smallsteps.api.configureErrorHandling
import eu.luminis.workshop.smallsteps.api.legoRentingRoutes
import eu.luminis.workshop.smallsteps.api.legoStockReportRoutes
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.routing.*
// Understands how to configure a ktor http server for this app
internal fun Application.legoRentingKtorModule(context: LegoRentingContext = LegoRentingContext()) {
this.configureSerialization()
this.configureErrorHandling()
this.configureRouting(context)
}
private fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
private fun Application.configureRouting(context: LegoRentingContext) {
routing {
legoRentingRoutes(context.legoStockMutationService)
legoStockReportRoutes(context.legoStockQueryService)
}
} | 0 | Kotlin | 1 | 0 | 2d168640126c39d2a13d5dc85d05cd6ab534b6d1 | 987 | workshop-ddd-nl-2022-11 | MIT License |
base/src/main/kotlin/browser/input/ime/InputContext.kt | DATL4G | 372,873,797 | false | null | @file:JsModule("webextension-polyfill")
@file:JsQualifier("input.ime")
package browser.input.ime
/**
* Describes an input Context
*/
public external interface InputContext {
/**
* This is used to specify targets of text field operations. This ID becomes invalid as soon as
* onBlur is called.
*/
public var contextID: Int
/**
* Type of value this text field edits, (Text, Number, URL, etc)
*/
public var type: InputContextType
/**
* Whether the text field wants auto-correct.
*/
public var autoCorrect: Boolean
/**
* Whether the text field wants auto-complete.
*/
public var autoComplete: Boolean
/**
* The auto-capitalize type of the text field.
*/
public var autoCapitalize: AutoCapitalizeType
/**
* Whether the text field wants spell-check.
*/
public var spellCheck: Boolean
/**
* Whether text entered into the text field should be used to improve typing suggestions for the
* user.
*/
public var shouldDoLearning: Boolean
}
| 0 | Kotlin | 1 | 37 | ab2a825dd8dd8eb704278f52c603dbdd898d1875 | 1,015 | Kromex | Apache License 2.0 |
packages/graalvm/src/main/kotlin/elide/runtime/intrinsics/js/node/EventsAPI.kt | elide-dev | 506,113,888 | false | {"Kotlin": 4156801, "Rust": 130170, "Java": 51233, "Python": 7851, "JavaScript": 6037, "Ruby": 2474, "C": 1926, "RenderScript": 578, "Shell": 160, "Pkl": 102, "TypeScript": 78, "Swift": 23} | /*
* Copyright (c) 2024 Elide Technologies, Inc.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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.
*/
@file:Suppress("StructuralWrap")
package elide.runtime.intrinsics.js.node
import org.graalvm.polyglot.Value
import org.graalvm.polyglot.proxy.ProxyObject
import elide.annotations.API
import elide.runtime.intrinsics.js.Disposable
import elide.runtime.intrinsics.js.JsPromise
import elide.runtime.intrinsics.js.node.events.*
import elide.vm.annotations.Polyglot
// Members from the Events API.
private val EVENTS_API_PROPS_AND_METHODS = arrayOf(
"defaultMaxListeners",
"errorMonitor",
"captureRejections",
"getEventListeners",
"getMaxListeners",
"setMaxListeners",
"once",
"listenerCount",
"on",
"addAbortListener",
)
/**
* # Node API: Events
*
* Describes the surface of the `events` built-in module provided as part of the Node API; the `events` API provides
* types like [EventEmitter], [EventTarget], [Event], and [EventListener] to work with events in Node.js.
*
* Events in Node behave similarly to DOM (browser) events, with a few caveats.
*
* For information about how the Node API behaves and how it differs from browsers, see the
* [Node.js Events documentation](https://nodejs.org/dist/latest-v16.x/docs/api/events.html).
*
* ## Node Events
*
* Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain
* kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.
*
* For instance: a `net.Server` object emits an event each time a peer connects to it; a `fs.ReadStream` emits an event
* when the file is opened; a stream emits an event whenever data is available to be read.
*
* All objects that emit events are instances of the [EventEmitter] class. These objects expose an [EventEmitter.on]
* function that allows one or more functions to be attached to named events emitted by the object. Typically, event
* names are camel-cased strings but any valid JavaScript property key can be used.
*
* When the [EventEmitter] object emits an event, all functions attached to that specific event are called
* synchronously. Any values returned by the called listeners are ignored and discarded.
*
* The following example shows a simple [EventEmitter] instance with a single listener. The [EventEmitter.on] method
* is used to register listeners, while the [EventEmitter.emit] method is used to trigger the event:
*
* ```javascript
* import { EventEmitter } from 'node:events';
*
* class MyEmitter extends EventEmitter {}
*
* const myEmitter = new MyEmitter();
* myEmitter.on('event', () => {
* console.log('an event occurred!');
* });
* myEmitter.emit('event');
* ```
*
*
*
* ### Passing arguments and `this` to listeners
*
* The [EventEmitter.emit] method allows an arbitrary set of arguments to be passed to the listener functions. Keep in
* mind that when an ordinary listener function is called, the standard `this` keyword is intentionally set to reference
* the [EventEmitter] instance to which the listener is attached.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* myEmitter.on('event', function(a, b) {
* console.log(a, b, this, this === myEmitter);
* // Prints:
* // a b MyEmitter {
* // _events: [Object: null prototype] { event: [Function (anonymous)] },
* // _eventsCount: 1,
* // _maxListeners: undefined,
* // [Symbol(shapeMode)]: false,
* // [Symbol(kCapture)]: false
* // } true
* });
* myEmitter.emit('event', 'a', 'b');
* ```
*
* It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the `this` keyword will no longer
* reference the EventEmitter instance:
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* myEmitter.on('event', (a, b) => {
* console.log(a, b, this);
* // Prints: a b {}
* });
* myEmitter.emit('event', 'a', 'b');
* ```
*
*
*
* ### Asynchronous vs. synchronous
*
* The [EventEmitter] calls all listeners synchronously in the order in which they were registered. This ensures the
* proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions
* can switch to an asynchronous mode of operation using the `setImmediate()` or `process.nextTick()` methods:
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* myEmitter.on('event', (a, b) => {
* setImmediate(() => {
* console.log('this happens asynchronously');
* });
* });
* myEmitter.emit('event', 'a', 'b');
* ```
*
*
*
* ### Handling events only once
*
* When a listener is registered using the [EventEmitter.on] method, that listener is invoked every time the named event
* is emitted.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* let m = 0;
* myEmitter.on('event', () => {
* console.log(++m);
* });
* myEmitter.emit('event');
* // Prints: 1
* myEmitter.emit('event');
* // Prints: 2
* ```
*
* Using the [EventEmitter.once] method, it is possible to register a listener which is called at most once for a
* particular event. Once the event is emitted, the listener is unregistered and then called.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* let m = 0;
* myEmitter.once('event', () => {
* console.log(++m);
* });
* myEmitter.emit('event');
* // Prints: 1
* myEmitter.emit('event');
* // Ignored
* ```
*
*
*
* ### Error events
*
* When an error occurs within an [EventEmitter] instance, the typical action is for an `'error'` event to be emitted.
* These are treated as special cases within Node.js.
*
* If an [EventEmitter] does not have at least one listener registered for the `'error'` event, and an `'error'` event
* is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* myEmitter.emit('error', new Error('whoops!'));
* // Throws and crashes Node.js
* ```
*
* To guard against crashing the Node.js process the `domain` module can be used. (Note, however, that the `node:domain`
* module is deprecated.)
*
* As a best practice, listeners should always be added for the `'error'` events.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
* myEmitter.on('error', (err) => {
* console.error('whoops! there was an error');
* });
* myEmitter.emit('error', new Error('whoops!'));
* // Prints: whoops! there was an error
* ```
*
* It is possible to monitor `'error'` events without consuming the emitted error by installing a listener using the
* symbol `events.errorMonitor`.
*
* ```javascript
* import { EventEmitter, errorMonitor } from 'node:events';
*
* const myEmitter = new EventEmitter();
* myEmitter.on(errorMonitor, (err) => {
* MyMonitoringTool.log(err);
* });
* myEmitter.emit('error', new Error('whoops!'));
* // Still throws and crashes Node.js
* ```
*
*
*
* ### Capture rejections of promises
*
* Using `async` functions with event handlers is problematic, because it can lead to an unhandled rejection in case of
* a thrown exception:
*
* ```javascript
* import { EventEmitter } from 'node:events';
* const ee = new EventEmitter();
* ee.on('something', async (value) => {
* throw new Error('kaboom');
* });
* ```
*
* The `captureRejections` option in the [EventEmitter] constructor or the global setting change this behavior,
* installing a `.then(undefined, handler)` handler on the Promise. This handler routes the exception asynchronously to
* the `Symbol.for('nodejs.rejection')` method if there is one, or to `'error'` event handler if there is none.
*
* ```javascript
* import { EventEmitter } from 'node:events';
* const ee1 = new EventEmitter({ captureRejections: true });
* ee1.on('something', async (value) => {
* throw new Error('kaboom');
* });
*
* ee1.on('error', console.log);
*
* const ee2 = new EventEmitter({ captureRejections: true });
* ee2.on('something', async (value) => {
* throw new Error('kaboom');
* });
*
* ee2[Symbol.for('nodejs.rejection')] = console.log;
* ```
*
* Setting `events.captureRejections = true` will change the default for all new instances of [EventEmitter].
*
* ```javascript
* import { EventEmitter } from 'node:events';
*
* EventEmitter.captureRejections = true;
* const ee1 = new EventEmitter();
* ee1.on('something', async (value) => {
* throw new Error('kaboom');
* });
*
* ee1.on('error', console.log);
* ```
*
* The `'error'` events that are generated by the `captureRejections` behavior do not have a catch handler to avoid
* infinite error loops: the recommendation is to not use async functions as `'error'` event handlers.
*
* @see Event for the base class for all events
* @see CustomEvent for the extension point used to create custom event types
* @see EventTarget for the interface supported for targets, or subjects, of events
* @see EventEmitter for the interface supported for objects that emit events
*/
@API public interface EventsAPI : NodeAPI, ProxyObject {
/**
* By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for
* individual EventEmitter instances using the `emitter.setMaxListeners(n) `method. To change the default for all
* EventEmitter instances, the events.defaultMaxListeners property can be used. If this value is not a positive
* number, a RangeError is thrown.
*
* Take caution when setting the events.defaultMaxListeners because the change affects all EventEmitter instances,
* including those created before the change is made. However, calling `emitter.setMaxListeners(n)` still has
* precedence over `events.defaultMaxListeners`.
*
* This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace
* warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any single
* EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to temporarily
* avoid this warning:
*
* ```js
* const EventEmitter = require('node:events');
* const emitter = new EventEmitter();
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
* emitter.once('event', () => {
* // do stuff
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
* });
* ```
*
* The `--trace-warnings` command-line flag can be used to display the stack trace for such warnings.
*
* The emitted warning can be inspected with `process.on('warning')` and will have the additional `emitter`, `type`,
* and `count` properties, referring to the event emitter instance, the event's name and the number of attached
* listeners, respectively.
*
* Its name property is set to 'MaxListenersExceededWarning'.
*/
@get:Polyglot @set:Polyglot public var defaultMaxListeners: Int
/**
* This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using
* this symbol are called before the regular `'error'` listeners are called.
*
* Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore,
* the process will still crash if no regular `'error'` listener is installed.
*/
@get:Polyglot @set:Polyglot public var errorMonitor: Any?
/**
* If set to `true`, the `'rejectionHandled'` event is emitted whenever a Promise is rejected, but there are no
* listeners to handle the rejection. This event is emitted with the following arguments:
*
* - `Promise` the Promise that was rejected.
*
* This event is useful for detecting and keeping track of promises that were rejected and not handled.
*/
@get:Polyglot public val captureRejections: Boolean
/**
* Returns an array listing the events for which the emitter has registered listeners. The values in the array are
* strings or Symbols.
*
* @param emitterOrTarget The EventEmitter or target object to query.
* @param event The name of the event to query.
* @return An array listing the events for which the emitter has registered listeners.
*/
@Polyglot public fun getEventListeners(emitterOrTarget: EmitterOrTarget, event: String): List<EventListener>
/**
* Returns the current max listener value for the given emitter or target.
*
* @param emitterOrTarget The EventEmitter or target object to query.
* @return The current max listener value for the given emitter or target.
*/
@Polyglot public fun getMaxListeners(emitterOrTarget: EmitterOrTarget): Int
/**
* Sets the maximum number of listeners for the given emitter or target.
*
* @param count The maximum number of listeners.
* @param emittersOrTargets The EventEmitter or target objects to set the maximum number of listeners for.
*/
@Polyglot public fun setMaxListeners(count: Int, vararg emittersOrTargets: EmitterOrTarget)
/**
* Adds a one-time listener function for the event named `name` to the `emitter`. The next time `name` is triggered,
* this listener is removed and then invoked.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
*/
@Polyglot public fun once(emitter: EventEmitter, name: String): JsPromise<Unit>
/**
* Adds a one-time listener function for the event named `name` to the `emitter`. The next time `name` is triggered,
* this listener is removed and then invoked.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
* @param options The options to use when adding the listener.
*/
@Polyglot public fun once(emitter: EventEmitter, name: String, options: Value): JsPromise<Unit>
/**
* Adds a one-time listener function for the event named `name` to the `emitter`. The next time `name` is triggered,
* this listener is removed and then invoked.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
* @param options The options to use when adding the listener.
*/
@Polyglot public fun once(emitter: EventEmitter, name: String, options: EventsOnceOptions): JsPromise<Unit>
/**
* Returns the number of listeners listening to the event named `event`.
*
* @param emitter The EventEmitter to query.
* @param event The name of the event to query.
* @return The number of listeners listening to the event named `event`.
*/
@Polyglot public fun listenerCount(emitter: Value, event: String): Int
/**
* Returns the number of listeners listening to the event named [eventName].
*
* @param emitter The [EventEmitter] or [EventTarget] to query.
* @param eventName The name of the event to query.
* @return The number of listeners listening to the event named [eventName].
*/
@Polyglot public fun listenerCount(emitter: EventEmitterOrTarget, eventName: String): Int
/**
* Adds the listener function to the end of the listeners array for the event named `name` to the `emitter`.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
*/
@Polyglot public fun on(emitter: EventEmitter, name: String)
/**
* Adds the listener function to the end of the listeners array for the event named `name` to the `emitter`.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
* @param options The options to use when adding the listener.
*/
@Polyglot public fun on(emitter: EventEmitter, name: String, options: Value)
/**
* Adds the listener function to the end of the listeners array for the event named `name` to the `emitter`.
*
* @param emitter The EventEmitter to add the listener to.
* @param name The name of the event to listen for.
* @param options The options to use when adding the listener.
*/
@Polyglot public fun on(emitter: EventEmitter, name: String, options: EventsOnceOptions)
/**
* Listens once to the `abort` event on the provided `signal`.
*
* Listening to the `abort` event on abort signals is unsafe and may lead to resource leaks since another third party
* with the signal can call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change this since it would
* violate the web standard.
*
* Additionally, the original API makes it easy to forget to remove listeners.
*
* This API allows safely using `AbortSignals` in Node.js APIs by solving these two issues by listening to the event
* such that `stopImmediatePropagation` does not prevent the listener from running.
*
* Returns a disposable so that it may be unsubscribed from more easily.
*/
@Polyglot public fun addAbortListener(signal: AbortSignal, listener: EventListener): Disposable
override fun getMemberKeys(): Array<String> = EVENTS_API_PROPS_AND_METHODS
override fun hasMember(key: String): Boolean = key in EVENTS_API_PROPS_AND_METHODS
override fun putMember(key: String?, value: Value?) {
throw UnsupportedOperationException("Cannot mutate member on Events API")
}
override fun removeMember(key: String?): Boolean {
throw UnsupportedOperationException("Cannot mutate member on Events API")
}
}
| 39 | Kotlin | 16 | 97 | 652036fb4e8394e8ad1aced2f4bbfaa9e00a5181 | 18,577 | elide | MIT License |
modules/domain/domain_notes/src/main/kotlin/kekmech/ru/domain_notes/NotesFeatureLauncher.kt | tonykolomeytsev | 203,239,594 | false | null | package kekmech.ru.domain_notes
import kekmech.ru.domain_notes.dto.Note
import kekmech.ru.domain_schedule.dto.Classes
import java.time.LocalDate
interface NotesFeatureLauncher {
fun launchNoteList(selectedClasses: Classes, selectedDate: LocalDate, resultKey: String)
fun launchNoteEdit(note: Note, resultKey: String)
fun launchAllNotes(selectedNote: Note? = null)
}
| 9 | Kotlin | 4 | 21 | 4ad7b2fe62efb956dc7f8255d35436695643d229 | 383 | mpeiapp | MIT License |
packages/canvas/src-native/canvas-android/canvas/src/main/java/org/nativescript/canvas/TNSDOMMatrix.kt | NativeScript | 293,639,798 | false | null | package com.github.triniwiz.canvas
/**
* Created by triniwiz on 3/27/20
*/
class TNSDOMMatrix(internal var matrix: Long) {
constructor() : this(nativeInit())
var a: Float
set(value) {
nativeSetA(matrix, value)
}
get() {
return nativeA(matrix)
}
var b: Float
set(value) {
nativeSetB(matrix, value)
}
get() {
return nativeB(matrix)
}
var c: Float
set(value) {
nativeSetC(matrix, value)
}
get() {
return nativeC(matrix)
}
var d: Float
set(value) {
nativeSetD(matrix, value)
}
get() {
return nativeD(matrix)
}
var e: Float
set(value) {
nativeSetE(matrix, value)
}
get() {
return nativeE(matrix)
}
var f: Float
set(value) {
nativeSetF(matrix, value)
}
get() {
return nativeF(matrix)
}
var m11: Float
set(value) {
nativeSetM11(matrix, value)
}
get() {
return nativeM11(matrix)
}
var m12: Float
set(value) {
nativeSetM12(matrix, value)
}
get() {
return nativeM12(matrix)
}
var m13: Float
set(value) {
nativeSetM13(matrix, value)
}
get() {
return nativeM13(matrix)
}
var m14: Float
set(value) {
nativeSetM14(matrix, value)
}
get() {
return nativeM14(matrix)
}
var m21: Float
set(value) {
nativeSetM21(matrix, value)
}
get() {
return nativeM21(matrix)
}
var m22: Float
set(value) {
nativeSetM22(matrix, value)
}
get() {
return nativeM22(matrix)
}
var m23: Float
set(value) {
nativeSetM23(matrix, value)
}
get() {
return nativeM23(matrix)
}
var m24: Float
set(value) {
nativeSetM24(matrix, value)
}
get() {
return nativeM24(matrix)
}
var m31: Float
set(value) {
nativeSetM31(matrix, value)
}
get() {
return nativeM31(matrix)
}
var m32: Float
set(value) {
nativeSetM32(matrix, value)
}
get() {
return nativeM32(matrix)
}
var m33: Float
set(value) {
nativeSetM33(matrix, value)
}
get() {
return nativeM33(matrix)
}
var m34: Float
set(value) {
nativeSetM34(matrix, value)
}
get() {
return nativeM34(matrix)
}
var m41: Float
set(value) {
nativeSetM41(matrix, value)
}
get() {
return nativeM41(matrix)
}
var m42: Float
set(value) {
nativeSetM42(matrix, value)
}
get() {
return nativeM42(matrix)
}
var m43: Float
set(value) {
nativeSetM43(matrix, value)
}
get() {
return nativeM43(matrix)
}
var m44: Float
set(value) {
nativeSetM44(matrix, value)
}
get() {
return nativeM44(matrix)
}
@Synchronized
@Throws(Throwable::class)
protected fun finalize() {
nativeDestroy(matrix)
}
companion object {
@JvmStatic
private external fun nativeInit(): Long
@JvmStatic
private external fun nativeDestroy(matrix: Long)
@JvmStatic
private external fun nativeUpdate(matrix: Long, data: FloatArray)
@JvmStatic
private external fun nativeA(matrix: Long): Float
@JvmStatic
private external fun nativeSetA(matrix: Long, a: Float)
@JvmStatic
private external fun nativeB(matrix: Long): Float
@JvmStatic
private external fun nativeSetB(matrix: Long, b: Float)
@JvmStatic
private external fun nativeC(matrix: Long): Float
@JvmStatic
private external fun nativeSetC(matrix: Long, c: Float)
@JvmStatic
private external fun nativeD(matrix: Long): Float
@JvmStatic
private external fun nativeSetD(matrix: Long, d: Float)
@JvmStatic
private external fun nativeE(matrix: Long): Float
@JvmStatic
private external fun nativeSetE(matrix: Long, e: Float)
@JvmStatic
private external fun nativeF(matrix: Long): Float
@JvmStatic
private external fun nativeSetF(matrix: Long, F: Float)
@JvmStatic
private external fun nativeM11(matrix: Long): Float
@JvmStatic
private external fun nativeSetM11(matrix: Long, a: Float)
@JvmStatic
private external fun nativeM12(matrix: Long): Float
@JvmStatic
private external fun nativeSetM12(matrix: Long, b: Float)
@JvmStatic
private external fun nativeM13(matrix: Long): Float
@JvmStatic
private external fun nativeSetM13(matrix: Long, c: Float)
@JvmStatic
private external fun nativeM14(matrix: Long): Float
@JvmStatic
private external fun nativeSetM14(matrix: Long, d: Float)
@JvmStatic
private external fun nativeM21(matrix: Long): Float
@JvmStatic
private external fun nativeSetM21(matrix: Long, a: Float)
@JvmStatic
private external fun nativeM22(matrix: Long): Float
@JvmStatic
private external fun nativeSetM22(matrix: Long, b: Float)
@JvmStatic
private external fun nativeM23(matrix: Long): Float
@JvmStatic
private external fun nativeSetM23(matrix: Long, c: Float)
@JvmStatic
private external fun nativeM24(matrix: Long): Float
@JvmStatic
private external fun nativeSetM24(matrix: Long, d: Float)
@JvmStatic
private external fun nativeM31(matrix: Long): Float
@JvmStatic
private external fun nativeSetM31(matrix: Long, a: Float)
@JvmStatic
private external fun nativeM32(matrix: Long): Float
@JvmStatic
private external fun nativeSetM32(matrix: Long, b: Float)
@JvmStatic
private external fun nativeM33(matrix: Long): Float
@JvmStatic
private external fun nativeSetM33(matrix: Long, c: Float)
@JvmStatic
private external fun nativeM34(matrix: Long): Float
@JvmStatic
private external fun nativeSetM34(matrix: Long, d: Float)
@JvmStatic
private external fun nativeM41(matrix: Long): Float
@JvmStatic
private external fun nativeSetM41(matrix: Long, a: Float)
@JvmStatic
private external fun nativeM42(matrix: Long): Float
@JvmStatic
private external fun nativeSetM42(matrix: Long, b: Float)
@JvmStatic
private external fun nativeM43(matrix: Long): Float
@JvmStatic
private external fun nativeSetM43(matrix: Long, c: Float)
@JvmStatic
private external fun nativeM44(matrix: Long): Float
@JvmStatic
private external fun nativeSetM44(matrix: Long, d: Float)
}
}
| 22 | null | 16 | 76 | cc723b4504a6878d8e25ec6b1fea22f5ca949f30 | 5,954 | canvas | Apache License 2.0 |
app/src/main/java/com/currencyexchange/app/di/module/NetworkApiModule.kt | AliAzaz | 569,301,571 | false | {"Kotlin": 53599} | package com.currencyexchange.app.di.module
import com.currencyexchange.app.BuildConfig
import com.currencyexchange.app.network.BackendApi
import com.currencyexchange.app.network.DefaultErrorFactory
import com.currencyexchange.app.network.IErrorFactory
import com.currencyexchange.app.utils.CONSTANTS
import com.currencyexchange.app.utils.StringResourceManager
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
/**
* @author AliAzazAlam on 11/20/2022.
*/
@Module
@InstallIn(SingletonComponent::class)
object NetworkApiModule {
@Provides
@Singleton
fun providesGson(): Gson = Gson()
@Singleton
@Provides
fun buildBackendApi(retrofit: Retrofit): BackendApi {
return retrofit.create(BackendApi::class.java)
}
@Singleton
@Provides
fun buildRetrofitClient(
okHttpClient: OkHttpClient,
gsonConverterFactory: GsonConverterFactory
): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(gsonConverterFactory)
.build()
}
@Singleton
@Provides
fun buildOkHttpClient(chainKeyInterceptor: Interceptor): OkHttpClient {
return OkHttpClient().newBuilder().also { item ->
val log = HttpLoggingInterceptor()
log.level = HttpLoggingInterceptor.Level.BODY
item.addInterceptor(log)
item.retryOnConnectionFailure(true)
}
.addNetworkInterceptor(chainKeyInterceptor)
.build()
}
@Provides
@Singleton
fun getGsonConverterFactory(): GsonConverterFactory {
return GsonConverterFactory.create()
}
@Provides
@Singleton
fun getChainKeyInterceptor(): Interceptor {
return Interceptor { chain ->
chain.request().let {
val urlBuilder = it.url.newBuilder()
.addQueryParameter(CONSTANTS.KEY, BuildConfig.API_KEY)
.build()
chain.proceed(it.newBuilder().url(urlBuilder).build())
}
}
}
@Provides
@Singleton
fun providesErrorFactory(stringResourceManager: StringResourceManager): IErrorFactory {
return DefaultErrorFactory(stringResourceManager)
}
} | 0 | Kotlin | 0 | 1 | 6a4284894e6bf1e92e3f291fb48df0eb1154c8b9 | 2,598 | CurrencyExchangeApp | MIT License |
src/main/kotlin/org/maru/memoryform/model/Hobby.kt | gonggit | 354,901,450 | false | null | package org.maru.memoryform.model
import javax.persistence.*
@Entity
@Table(name = "hobbies")
data class Hobby(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long,
@Column(name = "`user_name`")
val userName: String,
@Column(name = "`secret_hobby`")
val secretHobby: String?
) | 0 | Kotlin | 0 | 0 | bfe1ddea94c12fb4c765912140202beb453acd7b | 322 | memo-over-memory | MIT License |
view-service/src/main/java/dev/hirogakatageri/viewservice/viewmodel/ServiceViewModel.kt | HirogaKatageri | 396,198,096 | false | null | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hirogakatageri.viewservice.viewmodel
import android.util.Log
import androidx.annotation.CallSuper
import androidx.annotation.Keep
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import java.util.concurrent.CancellationException
import kotlin.coroutines.CoroutineContext
@Keep
abstract class ServiceViewModel : CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext = Dispatchers.Main + job
/**
* Callback method to notify the ViewModel the associated View has been detached from the
* WindowManager. By default this method is called during the onDetach of AbstractServiceView.
* This will cancel all Coroutine Jobs with CancellationException("View is detached").
* */
@CallSuper
open fun onDetach() {
Log.d(
this@ServiceViewModel::class.simpleName,
"Detached"
)
job.cancelChildren(CancellationException("View is detached"))
}
}
| 0 | Kotlin | 0 | 0 | 65cd6abc374eef3ccf64dd6cd93556c3f5fc6a43 | 1,713 | view-service | Apache License 2.0 |
domain/measurements/src/main/kotlin/ru/vt/domain/measurement/entity/HeadacheEntity.kt | magic-goop | 522,567,133 | false | {"Kotlin": 484480, "Shell": 117} | package ru.vt.domain.measurement.entity
import ru.vt.domain.common.Measurement
import ru.vt.domain.common.MeasurementParams
data class HeadacheEntity(
override val profileId: Long,
override val timestamp: Long,
val intensity: Int,
val headacheArea: HeadacheArea = HeadacheArea.UNDEFINED,
val description: String?
) : MeasurementEntity(profileId, Measurement.HEADACHE, timestamp) {
companion object {
private const val serialVersionUID: Long = 1L
}
}
enum class HeadacheArea(val key: String) {
UNDEFINED(""),
ALL(MeasurementParams.HEADACHE_ALL.key),
LEFT(MeasurementParams.HEADACHE_LEFT.key),
RIGHT(MeasurementParams.HEADACHE_RIGHT.key),
FOREHEAD(MeasurementParams.HEADACHE_FOREHEAD.key),
BACK_HEAD(MeasurementParams.HEADACHE_BACK_HEAD.key);
companion object {
fun valueFromKey(key: String?): HeadacheArea =
values().firstOrNull { it.key.lowercase() == key?.lowercase() } ?: UNDEFINED
}
}
| 0 | Kotlin | 0 | 2 | b7ff60f72cc67f43755a75b05ef4ba6a06d02315 | 980 | vitals-tracker | Apache License 2.0 |
solar/src/main/java/com/chiksmedina/solar/outline/arrowsaction/Export.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.outline.arrowsaction
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.ArrowsActionGroup
val ArrowsActionGroup.Export: ImageVector
get() {
if (_export != null) {
return _export!!
}
_export = Builder(
name = "Export", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(14.4697f, 7.5303f)
curveTo(14.7626f, 7.8232f, 15.2374f, 7.8232f, 15.5303f, 7.5303f)
curveTo(15.8232f, 7.2374f, 15.8232f, 6.7626f, 15.5303f, 6.4697f)
lineTo(12.5303f, 3.4697f)
curveTo(12.2374f, 3.1768f, 11.7626f, 3.1768f, 11.4697f, 3.4697f)
lineTo(8.4697f, 6.4697f)
curveTo(8.1768f, 6.7626f, 8.1768f, 7.2374f, 8.4697f, 7.5303f)
curveTo(8.7626f, 7.8232f, 9.2374f, 7.8232f, 9.5303f, 7.5303f)
lineTo(11.25f, 5.8107f)
verticalLineTo(14.0f)
curveTo(11.25f, 14.4142f, 11.5858f, 14.75f, 12.0f, 14.75f)
curveTo(12.4142f, 14.75f, 12.75f, 14.4142f, 12.75f, 14.0f)
verticalLineTo(5.8107f)
lineTo(14.4697f, 7.5303f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(20.75f, 12.0f)
curveTo(20.75f, 11.5858f, 20.4142f, 11.25f, 20.0f, 11.25f)
curveTo(19.5858f, 11.25f, 19.25f, 11.5858f, 19.25f, 12.0f)
curveTo(19.25f, 16.0041f, 16.0041f, 19.25f, 12.0f, 19.25f)
curveTo(7.9959f, 19.25f, 4.75f, 16.0041f, 4.75f, 12.0f)
curveTo(4.75f, 11.5858f, 4.4142f, 11.25f, 4.0f, 11.25f)
curveTo(3.5858f, 11.25f, 3.25f, 11.5858f, 3.25f, 12.0f)
curveTo(3.25f, 16.8325f, 7.1675f, 20.75f, 12.0f, 20.75f)
curveTo(16.8325f, 20.75f, 20.75f, 16.8325f, 20.75f, 12.0f)
close()
}
}
.build()
return _export!!
}
private var _export: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 3,039 | SolarIconSetAndroid | MIT License |
showkase-processor-testing/src/test/resources/ShowkaseProcessorTest/top_level_composable_and_class_with_@ScreenshotTest_generates_screenshot_test_for_composable/input/testComposables.kt | airbnb | 257,758,318 | false | {"Kotlin": 715619} | package com.airbnb.android.showkase_processor_testing
import androidx.compose.runtime.Composable
import com.airbnb.android.showkase.annotation.ShowkaseComposable
@ShowkaseComposable(name= "name1", group = "group1")
@Composable
public fun TestComposable1() {
}
@ShowkaseComposable(name= "name2", group = "group2")
@Composable
public fun TestComposable2() {
} | 50 | Kotlin | 106 | 2,073 | 9c3d6fc313d63b8f555fc65232ac15f798aede9a | 370 | Showkase | Apache License 2.0 |
server/src/main/kotlin/com/template/server/controllers/FlowController.kt | gatsinski | 156,692,279 | true | {"Kotlin": 97647, "HTML": 16282, "JavaScript": 1202} | package com.template.server.controllers
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.template.*
import com.template.server.NodeRPCConnection
import net.corda.core.contracts.Amount
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.identity.CordaX500Name
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
/**
* Define CorDapp-specific endpoints in a controller such as this.
*/
@RestController
@RequestMapping("/flows") // The paths for GET and POST requests are relative to this base path.
class FlowController(rpc: NodeRPCConnection) {
companion object {
private val logger = LoggerFactory.getLogger(RestController::class.java)
}
private val proxy = rpc.proxy
private val gson = Gson()
@PostMapping(value = "/agreejob")
private fun agreeJob(@RequestBody() jsonBody :String): ResponseEntity<*> {
var fromJson = gson.fromJson<Map<String, Any>>(jsonBody, object : TypeToken<Map<String, Any>>() {}.type)
val contractorName = fromJson["contractor"].toString()
val notaryName = fromJson["notary"].toString()
val contractAmount = fromJson["contractAmount"].toString().toDoubleOrNull()
val retentionPercentage = fromJson["retentionPercentage"].toString().toDoubleOrNull()
val allowPaymentOnAccount = fromJson["allowPaymentOnAccount"].toString().toBoolean()
var milestoneJson : List<Map<String,String>> = fromJson["milestones"] as List<Map<String,String>>
val milestones = milestoneJson.map { milestone ->
val reference = milestone["reference"].toString()
val quantity = milestone["amount"].toString()
val description = milestone["description"].toString()
val expectedEndDateString = milestone["expectedEndDate"]
val expectedEndDate = LocalDate.parse(expectedEndDateString, DateTimeFormatter.ISO_DATE)
val amount = Amount(quantity.toLong(), Currency.getInstance(milestone["currency"]))
val remarks = milestone["remarks"].toString()
Milestone(reference=reference, description=description, amount=amount, expectedEndDate=expectedEndDate, remarks=remarks)
}
val contractor = proxy.wellKnownPartyFromX500Name(CordaX500Name.parse(contractorName))
?: return ResponseEntity<Any>("Contractor $contractorName not found on network.", HttpStatus.INTERNAL_SERVER_ERROR)
val notary = proxy.wellKnownPartyFromX500Name(CordaX500Name.parse(notaryName))
?: return ResponseEntity<Any>("Notary $notaryName not found on network.", HttpStatus.INTERNAL_SERVER_ERROR)
val linearId = proxy.startFlowDynamic(AgreeJobFlow::class.java,
contractor,
contractAmount,
retentionPercentage,
allowPaymentOnAccount,
milestones,
notary).returnValue.get()
return ResponseEntity<Any>("New job created with ID ${linearId.id}.", HttpStatus.CREATED)
}
@PostMapping(value = "/startmilestone")
private fun startmilestone(
@RequestParam("linear-id") linearId: String,
@RequestParam("milestone-index") milestoneIndex: Int
): ResponseEntity<*> {
proxy.startFlowDynamic(StartMilestoneFlow::class.java, UniqueIdentifier.fromString(linearId), milestoneIndex).returnValue.get()
return ResponseEntity<Any>("Milestone # $milestoneIndex started for Job ID $linearId.", HttpStatus.OK)
}
@PostMapping(value = "/finishmilestone")
private fun finishmilestone(
@RequestParam("linear-id") linearId: String,
@RequestParam("milestone-index") milestoneIndex: Int
): ResponseEntity<*> {
proxy.startFlowDynamic(CompleteMilestoneFlow::class.java, UniqueIdentifier.fromString(linearId), milestoneIndex).returnValue.get()
return ResponseEntity<Any>("Milestone # $milestoneIndex finished for Job ID $linearId.", HttpStatus.OK)
}
@PostMapping(value = "/acceptmilestone")
private fun acceptmilestone(
@RequestParam("linear-id") linearId: String,
@RequestParam("milestone-index") milestoneIndex: Int
): ResponseEntity<*> {
val id = UniqueIdentifier.fromString(linearId)
proxy.startFlowDynamic(AcceptOrRejectFlow::class.java, id, true, milestoneIndex).returnValue.get()
return ResponseEntity<Any>("Job milestone with id $milestoneIndex was successfully accepted!",
HttpStatus.OK)
}
@PostMapping(value = "/rejectmilestone")
private fun rejectmilestone(
@RequestParam("linear-id") linearId: String,
@RequestParam("milestone-index") milestoneIndex: Int
): ResponseEntity<*> {
val id = UniqueIdentifier.fromString(linearId)
proxy.startFlowDynamic(AcceptOrRejectFlow::class.java, id, false, milestoneIndex).returnValue.get()
return ResponseEntity<Any>("Job milestone with id $milestoneIndex was successfully rejected!",
HttpStatus.OK)
}
@PostMapping(value = "/paymilestone")
private fun paymilestone(
@RequestParam("id") idString: String,
@RequestParam("milestone-index") milestoneIndex: Int
): ResponseEntity<*> {
val id = UniqueIdentifier.fromString(idString)
val linearId = proxy.startFlowDynamic(PayFlow::class.java, id, milestoneIndex).returnValue.get()
return ResponseEntity<Any>("Milestone $milestoneIndex of job ${linearId.id} paid.", HttpStatus.CREATED)
}
@PostMapping(value = "/issuecash")
private fun issuecash(
@RequestParam("quantity") quantity: String,
@RequestParam("currency") currency: String,
@RequestParam("notary") notaryName: String
): ResponseEntity<*> {
val amount = Amount(quantity.toLong(), Currency.getInstance(currency))
val notary = proxy.wellKnownPartyFromX500Name(CordaX500Name.parse(notaryName))
?: return ResponseEntity<Any>("Notary $notaryName not found on network.", HttpStatus.INTERNAL_SERVER_ERROR)
proxy.startFlowDynamic(IssueCashFlow::class.java, amount, notary).returnValue.get()
return ResponseEntity<Any>("$quantity of $currency issued.", HttpStatus.CREATED)
}
}
| 0 | Kotlin | 0 | 1 | ae6a46a4286c61f0f33db3e65b581f98a7b4c67a | 6,507 | CBC-Hackathon-1 | Apache License 2.0 |
walletlibrary/src/main/java/com/microsoft/walletlibrary/mappings/presentation/PresentationResponseMapping.kt | microsoft | 567,422,889 | false | {"Kotlin": 1390688} | package com.microsoft.walletlibrary.mappings.presentation
import com.microsoft.walletlibrary.did.sdk.credential.service.PresentationResponse
import com.microsoft.walletlibrary.requests.requirements.GroupRequirement
import com.microsoft.walletlibrary.requests.requirements.Requirement
import com.microsoft.walletlibrary.requests.requirements.VerifiedIdRequirement
import com.microsoft.walletlibrary.util.IdInVerifiedIdRequirementDoesNotMatchRequestException
import com.microsoft.walletlibrary.util.RequirementNotMetException
import com.microsoft.walletlibrary.util.UnSupportedRequirementException
import com.microsoft.walletlibrary.util.VerifiedIdExceptions
import com.microsoft.walletlibrary.util.VerifiedIdRequirementIdConflictException
import com.microsoft.walletlibrary.util.VerifiedIdRequirementMissingIdException
import com.microsoft.walletlibrary.verifiedid.VerifiableCredential
/**
* Fills the requested verifiable credentials in PresentationResponse object with Requirements object in library.
*/
internal fun PresentationResponse.addRequirements(requirement: Requirement) {
when (requirement) {
is GroupRequirement -> addGroupRequirement(requirement)
is VerifiedIdRequirement -> addVerifiedIdRequirement(requirement)
else -> throw UnSupportedRequirementException("Requirement type ${requirement::class.simpleName} is not unsupported.")
}
}
private fun PresentationResponse.addVerifiedIdRequirement(verifiedIdRequirement: VerifiedIdRequirement) {
if (verifiedIdRequirement.id == null)
throw VerifiedIdRequirementMissingIdException("Id is missing in the VerifiedId Requirement.")
if (verifiedIdRequirement.verifiedId == null)
throw RequirementNotMetException(
"Verified ID has not been set.",
VerifiedIdExceptions.REQUIREMENT_NOT_MET_EXCEPTION.value
)
val matchingInputDescriptors =
request.getPresentationDefinitions().filter {
presentationDefinition ->
// Limit to only this response' presentationDefinition
presentationDefinition.id == this.requestedVcPresentationDefinitionId
}.map {
presentationDefinition ->
// Filter to only matching inputDescriptor(s)
presentationDefinition.credentialPresentationInputDescriptors
.filter {
inputDescriptor ->
inputDescriptor.id == verifiedIdRequirement.id
}
}.reduce {
allInputDescriptors, inputDescriptor ->
// Flatten the inputDescriptors into a single array
allInputDescriptors + inputDescriptor
}
if (matchingInputDescriptors.isEmpty())
throw IdInVerifiedIdRequirementDoesNotMatchRequestException("Id in VerifiedId Requirement does not match the id in request.")
if (matchingInputDescriptors.size > 1)
throw VerifiedIdRequirementIdConflictException("Multiple VerifiedId Requirements have the same Ids.")
verifiedIdRequirement.validate().getOrThrow()
requestedVcPresentationSubmissionMap[matchingInputDescriptors.first()] =
(verifiedIdRequirement.verifiedId as VerifiableCredential).raw
}
private fun PresentationResponse.addGroupRequirement(groupRequirement: GroupRequirement) {
groupRequirement.validate().getOrThrow()
val requirements = groupRequirement.requirements
for (requirement in requirements) {
addRequirements(requirement)
}
} | 12 | Kotlin | 8 | 20 | 35cf5f995ff46cbb909cf582583e2c05600bf148 | 3,464 | entra-verifiedid-wallet-library-android | MIT License |
lib-moshi/src/main/java/net/codefeet/lemmyandroidclient/gen/types/ModFeaturePostView.kt | Flex4Reddit | 648,927,752 | false | null | package net.codefeet.lemmyandroidclient.gen.types
import android.os.Parcelable
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonClass(generateAdapter = true)
public data class ModFeaturePostView(
@Json(name = "mod_feature_post")
public val modFeaturePost: ModFeaturePost,
public val moderator: Person?,
public val post: Post,
public val community: Community,
) : Parcelable
| 0 | Kotlin | 0 | 0 | 8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac | 455 | lemmy-android-client | MIT License |
app/src/main/java/dlp/android/ma7moud3ly/screens/home/dialogs/DownloadDialog.kt | Ma7moud3ly | 783,520,987 | false | null | package dlp.android.ma7moud3ly.screens.home.dialogs
import ButtonSmall
import android.util.Log
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import dlp.android.ma7moud3ly.R
import dlp.android.ma7moud3ly.data.DownloadProgress
import dlp.android.ma7moud3ly.data.MediaFormat
import dlp.android.ma7moud3ly.data.MediaInfo
import dlp.android.ma7moud3ly.ui.appTheme.AppTheme
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private const val TAG = "DownloadProgressDialog"
@Preview
@Composable
private fun DownloadProgressDialogPreview() {
val format = MediaFormat(
resolution = "256x144",
ext = "MP4",
fileSize = "8388608"
)
val mediaInfo = MediaInfo(title = "My Test Video")
var progress by remember { mutableStateOf(DownloadProgress()) }
LaunchedEffect(Unit) {
for (i in 1..100) {
delay(1000)
val downloaded = 1.0 * i
val size = 30.0
val percent = "%.2f".format(downloaded / size * 100).toFloatOrNull() ?: 0f
progress = DownloadProgress(
downloaded = downloaded,
size = size,
percent = percent
)
}
}
AppTheme {
Surface(color = Color.White) {
DownloadDialog(
mediaFormat = { format },
mediaInfo = { mediaInfo },
downloadProgress = { progress },
onStopDownload = {}
)
}
}
}
@Composable
fun DownloadDialog(
mediaFormat: () -> MediaFormat?,
mediaInfo: () -> MediaInfo?,
downloadProgress: () -> DownloadProgress,
onStopDownload: () -> Unit
) {
val format = mediaFormat() ?: return
Dialog(
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
)
) {
val coroutineScope = rememberCoroutineScope()
val progress = downloadProgress()
val info = mediaInfo()
var progressJob by remember { mutableStateOf<Job?>(null) }
var progressPercent by remember {
mutableFloatStateOf(progress.percent / 100)
}
Surface(color = Color.White) {
Column {
LinearProgressIndicator(
progress = { progressPercent },
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.tertiary,
trackColor = MaterialTheme.colorScheme.primary,
)
Column(
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(16.dp)
) {
val percent1 = if (progress.percent == 0f) ""
else "${progress.percent.toInt()}% "
Text(
text = "$percent1${info?.title.orEmpty()}",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.secondary,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
val size = if (progress.size > 0) progress.size
else format.size() ?: 0.0
if (size > 0.0) FormatDetails(
title = R.string.download_progress_size,
value = "$size MB"
)
val percent2 = if (progress.percent == 0f) ""
else "(${progress.percent}%)"
if (progress.downloaded > 0.0) FormatDetails(
title = R.string.download_progress,
value = "${progress.downloaded} MB $percent2"
)
FormatDetails(
title = R.string.download_progress_format,
value = format.ext +
if (format.formatNote.isNotEmpty())
" - " + format.formatNote
else ""
)
if (format.resolution.isNotBlank()) FormatDetails(
title = R.string.download_progress_resolution,
value = format.resolution
)
Spacer(modifier = Modifier.height(8.dp))
ButtonSmall(
text = stringResource(id = R.string.download_cancel),
background = MaterialTheme.colorScheme.primary,
onClick = onStopDownload,
fillMaxWidth = true
)
}
}
}
LaunchedEffect(progress.size) {
Log.i(TAG, "progress size: ${progress.size}")
if (progress.size == 0.0 && progressJob == null) {
progressJob = coroutineScope.launch {
while (true) {
for (i in 0..10) {
progressPercent = i / 10f
delay(100)
//Log.v(TAG, "progress percent: $progressPercent")
}
delay(200)
}
}
} else {
progressJob?.cancel()
progressJob = null
}
}
LaunchedEffect(progress.percent) {
if (progressJob == null && progress.percent > 0.0) {
//Log.i(TAG, "progress percent: $progressPercent")
progressPercent = progress.percent / 100
}
}
}
}
@Composable
private fun FormatDetails(@StringRes title: Int, value: Any) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(id = title),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier.weight(0.4f)
)
Text(
text = value.toString(),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier.weight(0.6f),
maxLines = 1
)
}
}
| 0 | null | 0 | 3 | 4387d8b6c053da743ba59f1485b6c4148334d4bc | 7,756 | dlp-android | MIT License |
CMPE451/Android/app/src/main/java/com/example/carousel/vendor/VendorProductsAdapter.kt | oztasoi | 446,209,037 | false | {"Jupyter Notebook": 6340924, "JavaScript": 731585, "CSS": 625767, "Python": 401797, "Kotlin": 270488, "Java": 175718, "C++": 94490, "TeX": 88758, "HTML": 50873, "Prolog": 31901, "MATLAB": 12390, "Assembly": 8243, "Racket": 6521, "Shell": 1935, "QMake": 1422, "CMake": 1123, "Dockerfile": 638, "Makefile": 253} | package com.example.carousel.vendor
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.carousel.R
import com.example.carousel.map.ApiCaller
import com.example.carousel.map.ApiClient
import com.example.carousel.pojo.RequestProductAmountUpdate
import com.example.carousel.pojo.ResponseMainProduct
import com.example.carousel.pojo.ResponseProduct
import com.tapadoo.alerter.Alerter
import kotlinx.android.synthetic.main.fragment_vendor_home.*
class VendorProductsAdapter(
private var productList: ArrayList<VendorProduct>,
private val activity: Activity
) :
RecyclerView.Adapter<VendorProductsAdapter.ViewHolder>() {
var onItemClick: ((VendorProduct) -> Unit)? = null
override fun getItemCount(): Int {
return productList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val image: ImageView = itemView.findViewById(R.id.icon)
val title: TextView = itemView.findViewById(R.id.title)
val price: TextView = itemView.findViewById(R.id.price)
val amountLeft: TextView = itemView.findViewById(R.id.amountLeft)
val updateAmount: EditText = itemView.findViewById(R.id.updateAmount)
val updateButton: Button = itemView.findViewById(R.id.updateAmountButton)
init {
itemView.setOnClickListener {
onItemClick?.invoke(productList[adapterPosition])
}
updateButton.setOnClickListener {
val request = RequestProductAmountUpdate(
productList[adapterPosition].vendorId,
productList[adapterPosition].price,
updateAmount.text.toString().toInt(),
productList[adapterPosition].shipmentPrice,
productList[adapterPosition].cargoCompany
)
val apiCallerSetAmount: ApiCaller<ResponseProduct> = ApiCaller(activity)
apiCallerSetAmount.Caller =
ApiClient.getClient.productAmountUpdate(
productList[adapterPosition]._id,
productList[adapterPosition].vendorId,
request
)
apiCallerSetAmount.Success = { it ->
updateAmount.setText("")
Alerter.create(activity)
.setTitle("Success")
.setText("Stock update request is sent.")
.setBackgroundColorRes(R.color.successGreen)
.show()
}
apiCallerSetAmount.Failure = { Log.d("SECONDRESPONSE", "FAILED") }
apiCallerSetAmount.run()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.vendor_product_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val imgUri =
if (productList[position].photos.isNullOrEmpty()) R.mipmap.ic_no_image else productList[position].photos[0]
Glide.with(holder.image)
.load(imgUri)
.into(holder.image)
holder.title.text = productList[position].title
holder.price.text = "\$${productList[position].price}"
holder.amountLeft.text = productList[position].amountLeft.toString()
}
fun replaceProducts(newProducts: ArrayList<VendorProduct>) {
this.productList = newProducts
}
}
| 0 | Jupyter Notebook | 0 | 0 | a3e3a39efc9fed09db7290227848552f9604befa | 3,936 | bachelor-projects | MIT License |
app/src/main/java/io/github/drumber/kitsune/domain/manager/library/LibraryEntryServiceClient.kt | Drumber | 406,471,554 | false | {"Kotlin": 797542, "Ruby": 2045} | package io.github.drumber.kitsune.domain.manager.library
import com.github.jasminb.jsonapi.JSONAPIDocument
import io.github.drumber.kitsune.domain.mapper.toLibraryEntry
import io.github.drumber.kitsune.domain.model.common.library.LibraryStatus
import io.github.drumber.kitsune.domain.model.database.LocalLibraryEntryModification
import io.github.drumber.kitsune.domain.model.infrastructure.library.LibraryEntry
import io.github.drumber.kitsune.domain.model.infrastructure.media.Anime
import io.github.drumber.kitsune.domain.model.infrastructure.media.BaseMedia
import io.github.drumber.kitsune.domain.model.infrastructure.media.Manga
import io.github.drumber.kitsune.domain.model.infrastructure.user.User
import io.github.drumber.kitsune.domain.service.Filter
import io.github.drumber.kitsune.domain.service.library.LibraryEntriesService
import io.github.drumber.kitsune.exception.NotFoundException
import io.github.drumber.kitsune.util.logE
import kotlinx.coroutines.CancellationException
import retrofit2.HttpException
class LibraryEntryServiceClient(
private val libraryEntriesService: LibraryEntriesService
) {
private val filterForFullLibraryEntry
get() = Filter().include("anime", "manga")
suspend fun postNewLibraryEntry(
userId: String,
media: BaseMedia,
status: LibraryStatus
): LibraryEntry? {
val libraryEntry = LibraryEntry.withNulls().copy(
user = User(id = userId),
status = status,
anime = if (media is Anime) media else null,
manga = if (media is Manga) media else null
)
return try {
libraryEntriesService.postLibraryEntry(
JSONAPIDocument(libraryEntry),
filterForFullLibraryEntry.options
).get()
} catch (e: Exception) {
logE("Failed to create new library entry.", e)
null
}
}
suspend fun updateLibraryEntryWithModification(
libraryEntryModification: LocalLibraryEntryModification,
shouldFetchWithMedia: Boolean
): LibraryEntry? {
val libraryEntry = libraryEntryModification.toLocalLibraryEntry().toLibraryEntry()
val filter = if (shouldFetchWithMedia) filterForFullLibraryEntry.options else emptyMap()
return try {
libraryEntriesService.updateLibraryEntry(
libraryEntryModification.id,
JSONAPIDocument(libraryEntry),
filter
).get()
} catch (e: HttpException) {
if (e.code() == 404)
throw NotFoundException(
"Library entry with ID '${libraryEntryModification.id}' does not exist.",
e
)
val errorResponseBody = e.response()?.errorBody()?.string()
logE(
"Received HTTP exception while updating library entry with ID '${libraryEntryModification.id}'. Response body is: $errorResponseBody",
e
)
null
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logE("Failed to update library entry with ID '${libraryEntryModification.id}'.", e)
null
}
}
suspend fun deleteLibraryEntry(libraryEntryId: String): Boolean {
return try {
libraryEntriesService.deleteLibraryEntry(libraryEntryId).isSuccessful
} catch (e: Exception) {
logE("Failed to delete library entry with ID '$libraryEntryId'.", e)
false
}
}
suspend fun getFullLibraryEntry(libraryEntryId: String): LibraryEntry? {
return try {
libraryEntriesService.getLibraryEntry(
libraryEntryId,
filterForFullLibraryEntry.options
).get()
} catch (e: Exception) {
logE("Failed to get library entry with ID '$libraryEntryId'.", e)
null
}
}
suspend fun doesLibraryEntryExist(libraryEntryId: String): Boolean {
return try {
libraryEntriesService.getLibraryEntry(
libraryEntryId,
Filter().fields("libraryEntries", "id").options
).get() != null
} catch (e: HttpException) {
return e.code() == 404
} catch (e: Exception) {
logE("Failed to check for library entry with ID '${libraryEntryId}'.", e)
return false
}
}
} | 5 | Kotlin | 4 | 61 | 6ab88cfacd8ee4daad23edbe4a134ab1f2b1f62c | 4,482 | Kitsune | Apache License 2.0 |
app/src/main/java/com/a10miaomiao/bilimiao/comm/delegate/player/QualityPopupMenu.kt | 10miaomiao | 142,169,120 | false | null | package com.a10miaomiao.bilimiao.comm.delegate.player
import android.app.Activity
import android.view.Menu
import android.view.View
import androidx.appcompat.widget.PopupMenu
class QualityPopupMenu(
private val activity: Activity,
private val anchor: View,
private val list: List<String>,
private val value: String,
) {
private val popupMenu = PopupMenu(activity, anchor)
init {
popupMenu.menu.apply {
initMenu()
}
}
private fun Menu.initMenu() {
list.forEachIndexed { index, item ->
add(Menu.FIRST, index, 0, item).apply {
isChecked = value == item
}
}
setGroupCheckable(Menu.FIRST, true, true)
}
fun setOnMenuItemClickListener(listener: PopupMenu.OnMenuItemClickListener) {
popupMenu.setOnMenuItemClickListener(listener)
}
fun show() {
popupMenu.show()
}
} | 5 | Kotlin | 10 | 184 | 7bcce94cf56a140f492e52dd9ac6798aa0d67117 | 924 | bilimiao2 | Apache License 2.0 |
z2-service-runtime/src/commonMain/kotlin/hu/simplexion/z2/service/runtime/registry/BasicServiceImplFactory.kt | spxbhuhb | 667,868,480 | false | null | package hu.simplexion.z2.service.runtime.registry
import hu.simplexion.z2.service.runtime.ServiceContext
import hu.simplexion.z2.service.runtime.ServiceImpl
class BasicServiceImplFactory : ServiceImplFactory {
val templates = mutableMapOf<String, ServiceImpl>()
override fun plusAssign(template: ServiceImpl) {
templates[template.serviceName] = template
}
override fun get(serviceName: String, context: ServiceContext?): ServiceImpl? =
templates[serviceName]?.newInstance(context)
} | 0 | Kotlin | 1 | 11 | 339489cdddb9ebc72d92fa3de20c044a73e59da2 | 520 | z2-service | Apache License 2.0 |
offers/src/main/java/com/bed/offers/domain/usecases/GetAllOffersUsecase.kt | bed72 | 734,532,408 | false | {"Kotlin": 46083} | package com.bed.offers.domain.usecases
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.flowOn
import com.bed.shared.external.coroutines.Coroutines
import com.bed.offers.domain.alias.OffersType
import com.bed.offers.data.repositories.OffersRepository
import com.bed.offers.external.network.responses.toEntity
import com.bed.shared.external.network.responses.toEntity
interface GetAllOffersUsecase {
suspend operator fun invoke(): OffersType
}
class GetAllOffersUsecaseImpl(
private val coroutines: Coroutines,
private val repository: OffersRepository,
) : GetAllOffersUsecase {
override suspend fun invoke(): OffersType =
repository
.getAll("")
.take(1)
.flowOn(coroutines.io())
.map { response ->
response
.mapLeft { message -> message.toEntity() }
.map { offers -> offers.items.map { it.toEntity() } }
}
}
| 0 | Kotlin | 0 | 0 | 49ce992afe79ce3e0424d5c56e52a4e8e1b5d478 | 1,007 | OhhFerta | MIT License |
app/src/main/java/pl/elpassion/eltc/util/Logging.kt | thalezirnho | 98,657,076 | true | {"Kotlin": 65241} | package pl.elpassion.eltc.util
import android.util.Log
fun Any.log(message: Any?) = Log.w(javaClass.simpleName, message.toString()) | 0 | Kotlin | 0 | 0 | 928d06773b09d9bd1527dd338df20eced861c78b | 133 | teamcity-android-client | Apache License 2.0 |
app/src/main/java/com/groot/quotify/navigation/Route.kt | Kukki967 | 751,958,813 | false | {"Kotlin": 15893} | package com.groot.quotify.navigation
object Route {
val splashScreen = "splashScreen"
val signUpScreen = "signUpScreen"
val loginScreen = "loginScreen"
val homeScreen = "homeScreen"
} | 0 | Kotlin | 0 | 0 | ca9e3121863293a48fe01c7f1d2940e65b9b45f6 | 201 | Quotify | Apache License 2.0 |
app/src/main/java/com/example/sunnyweather/android/ui/star_place/StarPlaceFragment.kt | xv994 | 434,421,136 | false | {"Kotlin": 37106} | package com.example.sunnyweather.android.ui.star_place
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.sunnyweather.R
import com.example.sunnyweather.android.logic.Repository
import com.example.sunnyweather.android.ui.weather.WeatherViewModel
import kotlinx.android.synthetic.main.fragment_star_place.*
class StarPlaceFragment : Fragment() {
val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }
private lateinit var adapter: StarPlaceAdapter
// val starPlaceSizeInFragment = MutableLiveData(viewModel.starPlaceList.size)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_star_place, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val layoutManager = LinearLayoutManager(activity)
recyclerViewFromStarPlace.layoutManager = layoutManager
adapter = StarPlaceAdapter(this, viewModel.starPlaceList)
recyclerViewFromStarPlace.adapter = adapter
}
override fun onResume() {
super.onResume()
adapter = StarPlaceAdapter(this, Repository.getStarPlaceList())
recyclerViewFromStarPlace.adapter = adapter
Log.d("fragment", "resume")
}
override fun onPause() {
super.onPause()
Log.d("fragment", "pause")
}
} | 0 | Kotlin | 0 | 0 | ec00837cec6638d246bf649a2234ab4a5381437b | 1,882 | SunnyWeather | Apache License 2.0 |
middle/block/src/main/java/com/timecat/middle/block/mvvm/EditRecordViewModelFactory.kt | LinXueyuanStdio | 325,427,986 | false | {"Java": 471304, "Kotlin": 335967} | package com.timecat.middle.block.mvvm
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.timecat.data.room.record.RecordDao
/**
* @author 林学渊
* @email <EMAIL>
* @date 2019-11-26
* @description null
* @usage null
*/
class EditRecordViewModelFactory(
private val dataRepository: RecordDao
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return EditRecordViewModel(dataRepository) as T
}
companion object {
fun forRecord(dataRepository: RecordDao): ViewModelProvider.Factory {
return EditRecordViewModelFactory(dataRepository)
}
}
} | 1 | null | 1 | 1 | e8c126d51f1583b470523d5fa51c60971f8a6144 | 719 | TimeCatMiddle | Apache License 2.0 |
LABA5kt/src/exceptionsPack/IncorrectInputException.kt | deadxraver | 778,738,033 | false | {"Text": 3, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java Properties": 3, "Java": 221, "INI": 3, "XML": 27, "Ignore List": 4, "JAR Manifest": 1, "Kotlin": 48, "CSS": 4, "HTML": 85, "JavaScript": 9, "Markdown": 2} | package exceptionsPack
class IncorrectInputException : Exception() {
override val message: String
get() = "Incorrect input"
} | 0 | Java | 0 | 0 | 3f262f3175c7142487f8d225e4aac85f8f197d77 | 138 | Programming | MIT License |
src/main/java/org/mtransit/android/commons/provider/gbfs/data/api/v3/common/GBFSLocalizedURLApiModel.kt | mtransitapps | 24,689,836 | false | {"Shell": 6, "Ant Build System": 1, "Gradle": 1, "Proguard": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "XML": 58, "Kotlin": 85, "Java": 245, "JSON": 1, "Protocol Buffer": 1, "SVG": 21} | package org.mtransit.android.commons.provider.gbfs.data.api.v3.common
import com.google.gson.annotations.SerializedName
data class GBFSLocalizedURLApiModel(
@SerializedName("text")
val text: GBFSURLApiType,
@SerializedName("language")
val language: GBFSLanguageApiType,
) | 0 | Java | 3 | 4 | 3f7785acb499676fb40afbdc2a262161a955bcc2 | 289 | commons-android | Apache License 2.0 |
plugins/gradle/src/org/jetbrains/plugins/gradle/service/syncAction/GradleSyncContributor.kt | koxudaxi | 196,571,905 | false | {"Text": 9778, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 634, "Markdown": 752, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 261, "XML": 7881, "SVG": 4447, "Kotlin": 59448, "Java": 84016, "HTML": 3792, "Java Properties": 217, "Gradle": 460, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1424, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 742, "Groovy": 3109, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17066, "C": 109, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.syncAction
import com.intellij.gradle.toolingExtension.modelAction.GradleModelFetchPhase
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.ExtensionPointName.Companion.create
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
interface GradleSyncContributor {
val name: String
get() = javaClass.simpleName
/**
* Called when Gradle model building phase is completed.
* Guaranteed that all phases will be handled for the successful execution in the strict order.
*
* @param resolverContext contain all information about the current state of the Gradle sync.
* Use this context to access to the fetched Gradle models.
* @param phase current phase of the model fetching action.
*
* @see GradleModelFetchPhase
*/
suspend fun onModelFetchPhaseCompleted(
resolverContext: ProjectResolverContext,
phase: GradleModelFetchPhase
) = Unit
/**
* Called once Gradle has finished executing everything, including any tasks that might need to be run.
* The models are obtained separately and in some cases before this method is called.
*
* @param resolverContext contain all information about the current state of the Gradle sync.
* Use this context to access to the fetched Gradle models.
*/
suspend fun onModelFetchCompleted(
resolverContext: ProjectResolverContext
) = Unit
/**
* Called once Gradle has failed to execute everything.
* The models are obtained separately and in some cases before this method is called.
*
* @param resolverContext contain all information about the current state of the Gradle sync.
* Use this context to access to the fetched Gradle models.
* @param exception the exception thrown by Gradle, if everything completes successfully, then this will be null.
*/
suspend fun onModelFetchFailed(
resolverContext: ProjectResolverContext,
exception: Throwable
) = Unit
/**
* Called once Gradle has loaded projects but before any task execution.
* These models do not contain those models that are created when the build finished.
*
* @param resolverContext contain all information about the current state of the Gradle sync.
* Use this context to access to the fetched Gradle models.
*
* @see org.gradle.tooling.BuildActionExecuter.Builder.projectsLoaded
* @see org.gradle.tooling.IntermediateResultHandler
*/
@ApiStatus.Internal
suspend fun onProjectLoadedActionCompleted(
resolverContext: ProjectResolverContext
) = Unit
companion object {
@JvmField
val EP_NAME: ExtensionPointName<GradleSyncContributor> = create("org.jetbrains.plugins.gradle.syncContributor")
}
}
| 1 | null | 1 | 1 | 641c9567cc039e31dd60adbe4011f1b80a168b59 | 2,925 | intellij-community | Apache License 2.0 |
RickandMorty/episodes/src/main/java/com/renatoramos/rickandmorty/episodes/presentation/ui/episodeslist/adapter/datasource/EpisodesDataSourceFactory.kt | renatoramos7 | 208,802,459 | false | null | package com.renatoramos.rickandmorty.episodes.presentation.ui.episodeslist.adapter.datasource
import androidx.lifecycle.MutableLiveData
import androidx.paging.DataSource
import com.renatoramos.rickandmorty.domain.usecases.episodes.EpisodesUseCase
import com.renatoramos.rickandmorty.domain.viewobject.episodes.EpisodeViewObject
import io.reactivex.disposables.CompositeDisposable
class EpisodesDataSourceFactory (
private val compositeDisposable: CompositeDisposable,
private val episodesUseCase: EpisodesUseCase
) : DataSource.Factory<Int, EpisodeViewObject>() {
var listRepositoriesDataSourceLiveData = MutableLiveData<EpisodesDataSource>()
override fun create(): DataSource<Int, EpisodeViewObject> {
val listRepositoriesDataSource = EpisodesDataSource(compositeDisposable, episodesUseCase)
listRepositoriesDataSourceLiveData.postValue(listRepositoriesDataSource)
return listRepositoriesDataSource
}
}
| 0 | Kotlin | 1 | 1 | d953085a36b1daae251107cd4c18ac5b50eebb44 | 952 | Rick-And-Morty-Android | MIT License |
LavalinkServer/src/main/java/lavalink/server/util/loading.kt | lavalink-devs | 97,382,188 | false | {"Kotlin": 221913, "Java": 7277, "Dockerfile": 791} | package lavalink.server.util
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager
import com.sedmelluq.discord.lavaplayer.tools.ExceptionTools
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.track.AudioItem
/**
* Loads an audio item from the specified [identifier].
*
* This method wraps any exceptions thrown by the [AudioPlayerManager.loadItem] method in a [FriendlyException].
* This is meant to maintain the behavior from callback-style item loading.
*/
fun loadAudioItem(manager: AudioPlayerManager, identifier: String): AudioItem? = try {
manager.loadItemSync(identifier)
} catch (ex: Throwable) {
// re-throw any errors that are not exceptions
ExceptionTools.rethrowErrors(ex)
throw FriendlyException(
"Something went wrong while looking up the track.",
FriendlyException.Severity.FAULT,
ex
)
}
| 19 | Kotlin | 667 | 1,572 | 0d7decb7cc5fda0f3d7b2a6185c1d7be17e66300 | 924 | Lavalink | MIT License |
home/src/main/java/dev/muskelmekka/cannons/home/HomeScreen.kt | muskelmekka | 421,588,891 | false | null | package dev.muskelmekka.cannons.home
import android.content.res.Configuration
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.LocalWindowInsets
import com.google.accompanist.insets.rememberInsetsPaddingValues
import dev.muskelmekka.cannons.core.ui.insetsui.Card
import dev.muskelmekka.cannons.core.ui.insetsui.Divider
import dev.muskelmekka.cannons.core.ui.insetsui.SmallTopAppBar
import dev.muskelmekka.cannons.dna.AppTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen() {
Scaffold(
topBar = {
SmallTopAppBar(
contentPadding = rememberInsetsPaddingValues(LocalWindowInsets.current.statusBars),
title = { Text(stringResource(R.string.home_screen_title)) },
)
},
) { contentPadding ->
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = contentPadding,
verticalArrangement = Arrangement.spacedBy(0.dp),
) {
item { SectionHeader(title = stringResource(R.string.home_section_header_next_up)) }
item { NextWorkoutCard(modifier = Modifier.fillParentMaxWidth()) }
item { SectionHeader(title = stringResource(R.string.home_section_header_recent_workouts)) }
item { Spacer(Modifier.height(8.dp)) }
items(3) { RecentWorkoutItem() }
}
}
}
@Composable
private fun SectionHeader(modifier: Modifier = Modifier, title: String) {
Text(
text = title.uppercase(),
modifier = modifier.padding(start = 16.dp, top = 32.dp, end = 16.dp),
style = MaterialTheme.typography.titleSmall,
)
}
@Composable
private fun NextWorkoutCard(modifier: Modifier = Modifier) {
Card(modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp)) {
Column(Modifier.padding(16.dp)) {
Text("Arm Day", style = MaterialTheme.typography.titleMedium)
Text(
text = "Every day is arm day, and this one is no different. Lorem ipsum dolor sit amet.",
modifier = Modifier.padding(top = 8.dp),
style = MaterialTheme.typography.bodySmall,
)
Divider(Modifier.padding(top = 16.dp))
Row(Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
TextButton(onClick = {}) {
Text(stringResource(R.string.home_next_up_card_start_now_button))
}
TextButton(onClick = {}) {
Text(stringResource(R.string.home_next_up_card_show_details_button))
}
}
}
}
}
@Composable
private fun RecentWorkoutItem() {
Row(
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.clickable(onClick = {})
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Arm Day")
Text("Yesterday", style = MaterialTheme.typography.bodySmall)
}
Icon(Icons.Default.KeyboardArrowRight, contentDescription = null)
}
}
@Preview("Light Mode", uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview("Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun Preview() {
AppTheme {
HomeScreen()
}
}
| 5 | Kotlin | 0 | 0 | 9f15ac59fe1c090153196e67486673a0104bb3a2 | 4,165 | cannons-android | MIT License |
app/src/main/java/com/example/android_study/ui_custom/demo/flipbord/flipViewGroup/FlipListener.kt | RhythmCoderZZF | 281,057,053 | false | null | package com.example.android_study.ui_custom.demo.flipbord.flipViewGroup
import android.graphics.Camera
/**
* Author:create by RhythmCoder
* Date:2021/9/7
* Description:
*/
interface FlipListener {
fun onFlip(rotateL:Float,rotateR:Float)
fun onFlipEnd(isTop:Boolean)
} | 0 | Kotlin | 0 | 0 | 8de07e3a5613128ce05a9a0de2305bd02122da3a | 282 | AndroidStudy | Apache License 2.0 |
packages/proto/proto-flatbuffers/src/main/kotlin/elide/page/Context_/DynamicETag.kt | elide-dev | 506,113,888 | false | {"Kotlin": 5146702, "JavaScript": 1203447, "Java": 321269, "Protocol Buffer": 276092, "Shell": 87079, "Dockerfile": 50776, "Cap'n Proto": 35188, "Makefile": 30138, "CSS": 14730, "Python": 6626, "C": 4100, "Batchfile": 3016, "Ruby": 2474, "Handlebars": 1954, "HTML": 1010, "Rust": 525, "Swift": 23} | /*
* Copyright (c) 2023 Elide Ventures, LLC.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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.
*/
// automatically generated by the FlatBuffers compiler, do not modify
package elide.page.Context_
import com.google.flatbuffers.Constants
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.Table
import java.nio.ByteBuffer
import java.nio.ByteOrder
@Suppress("unused")
class DynamicETag : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : DynamicETag {
__init(_i, _bb)
return this
}
val enabled : Boolean
get() {
val o = __offset(4)
return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else false
}
val strong : Boolean
get() {
val o = __offset(6)
return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else false
}
val preimage : elide.data.DataFingerprint? get() = preimage(elide.data.DataFingerprint())
fun preimage(obj: elide.data.DataFingerprint) : elide.data.DataFingerprint? {
val o = __offset(8)
return if (o != 0) {
obj.__assign(__indirect(o + bb_pos), bb)
} else {
null
}
}
val response : elide.data.DataFingerprint? get() = response(elide.data.DataFingerprint())
fun response(obj: elide.data.DataFingerprint) : elide.data.DataFingerprint? {
val o = __offset(10)
return if (o != 0) {
obj.__assign(__indirect(o + bb_pos), bb)
} else {
null
}
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_22_12_06()
fun getRootAsDynamicETag(_bb: ByteBuffer): DynamicETag = getRootAsDynamicETag(_bb, DynamicETag())
fun getRootAsDynamicETag(_bb: ByteBuffer, obj: DynamicETag): DynamicETag {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createDynamicETag(builder: FlatBufferBuilder, enabled: Boolean, strong: Boolean, preimageOffset: Int, responseOffset: Int) : Int {
builder.startTable(4)
addResponse(builder, responseOffset)
addPreimage(builder, preimageOffset)
addStrong(builder, strong)
addEnabled(builder, enabled)
return endDynamicETag(builder)
}
fun startDynamicETag(builder: FlatBufferBuilder) = builder.startTable(4)
fun addEnabled(builder: FlatBufferBuilder, enabled: Boolean) = builder.addBoolean(0, enabled, false)
fun addStrong(builder: FlatBufferBuilder, strong: Boolean) = builder.addBoolean(1, strong, false)
fun addPreimage(builder: FlatBufferBuilder, preimage: Int) = builder.addOffset(2, preimage, 0)
fun addResponse(builder: FlatBufferBuilder, response: Int) = builder.addOffset(3, response, 0)
fun endDynamicETag(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 75 | Kotlin | 15 | 88 | 5cd3312b5ee32726db34f5673f0d4f557ec91cca | 3,545 | elide | MIT License |
src/main/kotlin/sciJava/sci.kt | elect86 | 333,834,311 | false | null | package sciJava
import org.gradle.api.Action
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.kotlin.dsl.DependencyHandlerScope
import sciJava.dsl.implementation
import sciJava.dsl.runtimeOnly
import sciJava.dsl.testImplementation
import sciJava.dsl.testRuntimeOnly
/**
* com.github.scenerygraphics:vector:958f2e6
* net.java.dev.jna:jna
* net.java.dev.jna:jna-platform:${jna}
*/
var debug = false
fun DependencyHandlerScope.sciJava(deps: List<String>) {
for (dep in deps)
sciJava(dep)
}
fun DependencyHandlerScope.sciJava(dep: String, native: String? = null, test: Boolean = false,
config: Action<ExternalModuleDependency>? = null) {
var dep = dep
val deps = dep.split(':')
var vers: String = deps.last()
when (deps.size) {
3 -> {
vers = deps[2]
// org.scijava:ui-behaviour:2.0.2
// net.java.dev.jna:jna-platform:\$jna
if (vers.startsWith('$')) { // we need to prepare for later extraction
vers = vers.substring(1)
dep = dep.substringBeforeLast(':') // remove tail
} else { // complete, eg: com.github.scenerygraphics:vector:958f2e6
if (test) {
if (debug) println("testImplementation(\"$dep\")")
when (config) {
null -> testImplementation(dep)
else -> testImplementation(dep, config)
}
} else {
if (debug) println("implementation(\"$dep\")")
when (config) {
null -> implementation(dep)
else -> implementation(dep, config)
}
}
if (native != null)
if (test) {
if (debug) println("testRuntimeOnly(${deps[0]}, ${deps[1]}, ${deps[2]}, classifier = $native)")
testRuntimeOnly(deps[0], deps[1], deps[2], classifier = native, dependencyConfiguration = config)
} else {
if (debug) println("runtimeOnly(${deps[0]}, ${deps[1]}, ${deps[2]}, classifier = $native)")
runtimeOnly(deps[0], deps[1], deps[2], classifier = native, dependencyConfiguration = config)
}
return
}
}
2 -> vers = deps[1]
1 -> {
// net.imagej
vers = dep.substringAfterLast('.')
dep = "$dep:$vers"
}
}
// we need to extract the version
val version = versions[vers] ?: versions[vers.substringBefore('-')]
// println("vers=$vers, version=$version")
if (test) {
if (debug) println("testImplementation(\"$dep:$version\")")
when (config) {
null -> testImplementation("$dep:$version")
else -> testImplementation("$dep:$version", config)
}
} else {
if (debug) println("implementation(\"$dep:$version\")")
when (config) {
null -> implementation("$dep:$version")
else -> implementation("$dep:$version", config)
}
}
if (native != null)
sciJavaRuntimeOnly(dep, native, test, config)
}
fun DependencyHandlerScope.sciJavaRuntimeOnly(dep: String, classifier: String? = null, test: Boolean = false,
config: Action<ExternalModuleDependency>? = null) {
val group = dep.substringBefore(':')
val name = dep.substringAfter(':')
if (test) {
if (debug) println("testRuntimeOnly($group, $name, classifier = $classifier)")
testRuntimeOnly(group, name, classifier = classifier, dependencyConfiguration = config)
} else {
if (debug) println("runtimeOnly($group, $name, classifier = $classifier)")
runtimeOnly(group, name, classifier = classifier, dependencyConfiguration = config)
}
}
fun DependencyHandlerScope.testSciJava(dep: String, native: String? = null, config: Action<ExternalModuleDependency>? = null) =
sciJava(dep, native, test = true, config = config) | 0 | Kotlin | 0 | 0 | 60af14dac81c8cc4dee16655e3f122cdd8935958 | 4,171 | sciJava | MIT License |
src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/lang/validation/requires/XpmRequiresSpecificationVersion.kt | rhdunn | 62,201,764 | false | null | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion
import uk.co.reecedunn.intellij.plugin.xpm.lang.configuration.XpmLanguageConfiguration
import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmBundle
@Suppress("unused")
class XpmRequiresSpecificationVersion(private val requires: XpmSpecificationVersion) : XpmRequiresConformanceTo {
override fun conformanceTo(configuration: XpmLanguageConfiguration): Boolean {
val implements = configuration.implements[requires.specification.id] ?: return false
return implements.specification === requires.specification && implements >= requires
}
override fun message(
configuration: XpmLanguageConfiguration,
conformanceName: String?
): String = when (conformanceName) {
null -> XpmBundle.message("diagnostic.unsupported-syntax", configuration.product, this)
else -> XpmBundle.message("diagnostic.unsupported-syntax-name", configuration.product, this, conformanceName)
}
override fun or(requires: XpmRequiresConformanceTo): XpmRequiresConformanceTo {
throw UnsupportedOperationException()
}
override fun toString(): String = requires.toString()
}
| 47 | Kotlin | 4 | 25 | d363dad28df1eb17c815a821c87b4f15d2b30343 | 1,867 | xquery-intellij-plugin | Apache License 2.0 |
src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/lang/validation/requires/XpmRequiresSpecificationVersion.kt | rhdunn | 62,201,764 | false | null | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion
import uk.co.reecedunn.intellij.plugin.xpm.lang.configuration.XpmLanguageConfiguration
import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmBundle
@Suppress("unused")
class XpmRequiresSpecificationVersion(private val requires: XpmSpecificationVersion) : XpmRequiresConformanceTo {
override fun conformanceTo(configuration: XpmLanguageConfiguration): Boolean {
val implements = configuration.implements[requires.specification.id] ?: return false
return implements.specification === requires.specification && implements >= requires
}
override fun message(
configuration: XpmLanguageConfiguration,
conformanceName: String?
): String = when (conformanceName) {
null -> XpmBundle.message("diagnostic.unsupported-syntax", configuration.product, this)
else -> XpmBundle.message("diagnostic.unsupported-syntax-name", configuration.product, this, conformanceName)
}
override fun or(requires: XpmRequiresConformanceTo): XpmRequiresConformanceTo {
throw UnsupportedOperationException()
}
override fun toString(): String = requires.toString()
}
| 47 | Kotlin | 4 | 25 | d363dad28df1eb17c815a821c87b4f15d2b30343 | 1,867 | xquery-intellij-plugin | Apache License 2.0 |
app/src/main/java/tech/ascendio/mvvm/ui/fragments/SubredditImagesFragment.kt | MarianVasilca | 134,165,874 | false | null | package tech.ascendio.mvvm.ui.fragments
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.widget.SearchView
import android.view.Menu
import android.view.MenuInflater
import kotlinx.android.synthetic.main.subreddit_images_fragment.*
import tech.ascendio.mvvm.R
import tech.ascendio.mvvm.databinding.SubredditImagesFragmentBinding
import tech.ascendio.mvvm.di.Injectable
import tech.ascendio.mvvm.testing.OpenForTesting
import tech.ascendio.mvvm.ui.adapters.ImageAdapter
import tech.ascendio.mvvm.util.AppExecutors
import tech.ascendio.mvvm.util.Constants.DEFAULT_SUBREDDIT
import tech.ascendio.mvvm.util.onSearch
import tech.ascendio.mvvm.viewmodel.ImageViewModel
import javax.inject.Inject
@OpenForTesting
class SubredditImagesFragment : BaseFragment<SubredditImagesFragmentBinding>(), Injectable {
override val layoutResource: Int
get() = R.layout.subreddit_images_fragment
override val tag: String
get() = "SubredditImagesFragment"
@Inject
lateinit var appExecutors: AppExecutors
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
lateinit var imagesViewModel: ImageViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
imagesViewModel = ViewModelProviders.of(this, viewModelFactory)
.get(ImageViewModel::class.java)
val adapter = ImageAdapter(dataBindingComponent, appExecutors) {}
imagesViewModel.subredditImages.observe(this, Observer { imagesResource ->
viewDataBinding.imagesResource = imagesResource
// we don't need any null checks here for the adapter since LiveData guarantees that
// it won't call us if fragment is stopped or not started.
if (imagesResource?.data != null) {
adapter.submitList(imagesResource.data)
} else {
adapter.submitList(emptyList())
}
})
viewDataBinding.rvImages.adapter = adapter
imagesViewModel.setSubreddit(DEFAULT_SUBREDDIT)
getMainActivity().setSupportActionBar(tbMain)
getMainActivity().supportActionBar?.title = DEFAULT_SUBREDDIT
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu, menu)
val searchItem = menu?.findItem(R.id.action_search)
val searchView = searchItem?.actionView as SearchView
// Configure the search info and add any event listeners...
searchView.queryHint = getString(R.string.search_hint)
searchView.onSearch {
imagesViewModel.setSubreddit(it?.trim())
getMainActivity().supportActionBar?.title = it
hideKeyboard(activity!!)
searchItem.collapseActionView()
}
return super.onCreateOptionsMenu(menu, inflater)
}
override fun onBoundViews() {
setHasOptionsMenu(true)
}
} | 0 | Kotlin | 0 | 0 | 6c811396291caab2e198fe7ee0452e644101bb25 | 3,089 | android-mvvm-imgur-browser | Apache License 2.0 |
Application/app/src/main/java/com/wrmh/allmyfood/views/HomeActivity.kt | MiguelPortillo18 | 259,108,086 | false | {"Kotlin": 94364} | package com.wrmh.allmyfood.views
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import com.wrmh.allmyfood.R
import com.wrmh.allmyfood.databinding.ActivityHomeBinding
class HomeActivity : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding =
DataBindingUtil.setContentView<ActivityHomeBinding>(
this,
R.layout.activity_home
)
drawerLayout = binding.drawerLayout
val navController = this.findNavController(R.id.myNavHostFragment)
NavigationUI.setupWithNavController(binding.navView, navController)
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
}
override fun onBackPressed() {
if (
supportFragmentManager.findFragmentById(R.id.myNavHostFragment)
?.childFragmentManager?.fragments?.first()
?.javaClass === WelcomeFragment::class.java
) {
Toast.makeText(applicationContext, "¡Vuelve pronto!", Toast.LENGTH_LONG).show()
finishAffinity()
}
else{
super.onBackPressed()
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.myNavHostFragment)
return NavigationUI.navigateUp(navController, drawerLayout)
}
} | 0 | Kotlin | 0 | 1 | 375977d261788687bfae093d1d09c8b58d7b6593 | 1,705 | Food-app | MIT License |
core/kotlinx-coroutines-io/test/ByteChannelJoinNoAutoFlushLinearizabilityTest.kt | DarkLab | 142,666,798 | true | {"Kotlin": 1920618, "CSS": 8215, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 356} | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.experimental.io
import com.devexperts.dxlab.lincheck.*
import com.devexperts.dxlab.lincheck.annotations.*
import com.devexperts.dxlab.lincheck.stress.*
import kotlinx.coroutines.experimental.*
import org.junit.*
@OpGroupConfigs(
OpGroupConfig(name = "write", nonParallel = true),
OpGroupConfig(name = "read1", nonParallel = true),
OpGroupConfig(name = "read2", nonParallel = true)
)
class ByteChannelJoinNoAutoFlushLinearizabilityTest : TestBase() {
private lateinit var from: ByteChannel
private lateinit var to: ByteChannel
private val lr = LinTesting()
@Reset
fun resetChannel() {
from = ByteChannel(false)
to = ByteChannel(false)
}
@Operation(runOnce = true, group = "read1")
fun read() = lr.run("read") {
to.readLong()
}
@Operation(runOnce = true, group = "write")
fun write() = lr.run("write") {
from.writeLong(0x1122334455667788L)
from.flush()
}
@Operation(runOnce = true, group = "read2")
fun joinTo() = lr.run("join") {
from.joinTo(to, true)
}
@Test
fun test() {
val options = StressOptions()
.iterations(100)
.invocationsPerIteration(1000 * stressTestMultiplier)
.addThread(1, 2)
.addThread(1, 1)
.addThread(1, 1)
.verifier(LinVerifier::class.java)
LinChecker.check(ByteChannelJoinNoAutoFlushLinearizabilityTest::class.java, options)
}
}
| 0 | Kotlin | 0 | 0 | 9964b3d97377963e353f10d7dcca7e18770997a3 | 1,626 | kotlinx.coroutines | Apache License 2.0 |
app/src/main/java/com/example/afisha/data/remote/AfishaRemoteRepository.kt | sshiae | 719,299,632 | false | {"Kotlin": 74790} | package com.example.afisha.data.remote
import androidx.paging.PagingData
import com.example.afisha.domain.model.Movie
import kotlinx.coroutines.flow.Flow
/**
* Удаленный репозиторий для работы с сетью
*/
interface AfishaRemoteRepository {
/**
* Используется для получения списка фильмов [Movie] сортированных по рейтингу
*
* @param country - страна
*/
suspend fun getMoviesSortedByRating(country: String): Flow<PagingData<Movie>>
/**
* Используется для получения фильма по [id]
*
* @param id - ID фильма
*/
suspend fun getMovieById(id: Int): Movie
} | 0 | Kotlin | 0 | 0 | b88fd0aa909e8684a461049fee06302269556b26 | 611 | MoviePoster | Apache License 2.0 |
app/src/test/java/com/example/goalapp/DateTimeUtilTest.kt | soikkea | 511,094,118 | false | {"Kotlin": 92568} | package com.example.goalapp
import com.example.goalapp.utilities.localDateTimeToLong
import com.example.goalapp.utilities.longToLocalDateTime
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
class DateTimeUtilTest {
@Test
fun test_localDateTimeToLong() {
val localDate = LocalDate.of(2022, 7, 10)
val dateTime = localDate.atStartOfDay()
val dtLong = localDateTimeToLong(dateTime)
val dateTime2 = longToLocalDateTime(dtLong)
assertEquals(dateTime, dateTime2)
}
@Test
fun test_localDateTimeToLongUTC() {
val localDate = LocalDate.of(2022, 7, 10)
val dateTime = localDate.atStartOfDay()
val dtLong = localDateTimeToLong(dateTime, true)
val dateTime2 = longToLocalDateTime(dtLong, true)
assertEquals(dateTime, dateTime2)
}
@Test
fun test_localDateTimeTimeZoneConversion() {
val localDateTime = LocalDateTime.of(2022, 7, 11, 12, 15)
val hoursOffset = 3
val offset = ZoneOffset.ofHours(hoursOffset)
val utcLong = localDateTime.atOffset(offset).toInstant().toEpochMilli()
val utcLocalDateTime = localDateTime.minusHours(hoursOffset.toLong())
assertEquals(utcLocalDateTime, longToLocalDateTime(utcLong, true))
assertEquals(utcLong, localDateTimeToLong(utcLocalDateTime, true))
val localDateTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(utcLong), offset)
assertEquals(localDateTime, localDateTime2)
}
} | 0 | Kotlin | 0 | 0 | 6608af04e56b6ee5e24152f76d8fdfef66fb9ef3 | 1,613 | goalapp | MIT License |
app/src/main/java/com/fallllllll/lipperwithkotlin/core/fragment/BaseListFragment.kt | haoxikang | 92,583,742 | false | null | package com.fallllllll.lipperwithkotlin.core.fragment
import android.annotation.SuppressLint
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DefaultItemAnimator
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ProgressBar
import com.fall.generalrecyclerviewfragment.GeneralRecyclerViewFragment
import com.fallllllll.lipperwithkotlin.R
import com.fallllllll.lipperwithkotlin.core.BaseViewUtils
import com.fallllllll.lipperwithkotlin.core.expandFunction.dpToPx
import com.fallllllll.lipperwithkotlin.core.expandFunction.showSnackBar
import com.fallllllll.lipperwithkotlin.core.presenter.Contract
import com.fallllllll.lipperwithkotlin.core.presenter.PresenterLifecycleHelper
import kotlinx.android.synthetic.main.view_list_error.view.*
import org.jetbrains.anko.doAsync
import kotlin.concurrent.fixedRateTimer
/**
* Created by fall on 2017/5/27/027.
* GitHub : https://github.com/348476129/LipperWithKotlin
*/
abstract class BaseListFragment : GeneralRecyclerViewFragment(), Contract.BaseView {
protected lateinit var errorView: View
protected lateinit var presenterLifecycleHelper: PresenterLifecycleHelper
protected lateinit var baseViewUtils: BaseViewUtils
private var progressBar: ProgressBar? = null
private lateinit var rootView: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenterLifecycleHelper = PresenterLifecycleHelper()
baseViewUtils = BaseViewUtils(context)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = super.onCreateView(inflater, container, savedInstanceState) as FrameLayout
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
swipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.accent)
recyclerView.itemAnimator = DefaultItemAnimator()
}
override fun onDestroy() {
super.onDestroy()
presenterLifecycleHelper.destroyPresenter()
}
override fun loadError(s: String?) {
loadError(getString(R.string.retry_hint), R.drawable.ic_retry_black_48dp)
}
override fun loadError(res: Int) {
loadError(getString(res))
}
override fun loadError(s: String?, res: Int) {
loadErrorView()
errorLayout.setOnClickListener {
presenter.checkAndRefreshData()
errorLayout.visibility = View.GONE
}
errorView.errorImage.setImageResource(res)
errorView.errorText.text = s
}
override fun loadError() {
loadError(getString(R.string.retry_hint))
}
override fun loadNextPageError() {
loadNextPageError(getString(R.string.failed_to_load))
}
override fun loadNextPageError(s: String?) {
loadNextPageError(s, -1)
}
override fun loadNextPageError(res: Int) {
loadNextPageError(getString(res))
}
override fun loadNextPageError(s: String?, res: Int) {
showSnackBar(s ?: getString(R.string.failed_to_load), swipeRefreshLayout)
}
override fun noDataLoad() {
noDataLoad(getString(R.string.no_data))
}
override fun noDataLoad(s: String?) {
noDataLoad((s), R.drawable.ic_no_data_black_48dp)
}
override fun noDataLoad(res: Int) {
noDataLoad(getString(res))
}
override fun noDataLoad(s: String?, res: Int) {
swipeRefreshLayout.isEnabled = false
loadErrorView()
errorLayout.setOnClickListener { }
errorView.errorImage.setImageResource(res)
errorView.errorText.text = s
}
private fun loadErrorView() {
errorLayout.visibility = View.VISIBLE
if (errorLayout.childCount == 0) {
errorView = LayoutInflater.from(context).inflate(R.layout.view_list_error, null)
errorLayout.addView(errorView)
}
}
override fun showToast(s: String) {
baseViewUtils.showToast(s)
}
override fun showTopDialog(s: String) {
baseViewUtils.showTopDialog(s)
}
override fun hideAllTopDialog() {
baseViewUtils.hideAllTopDialog()
}
override fun showErrorDialog(s: String) {
baseViewUtils.showErrorDialog(s)
}
override fun showLoadAnimation() {
if (recyclerView.adapter == null || recyclerView.adapter.itemCount == 0) {
if (progressBar == null) {
progressBar = ProgressBar(context)
val fp = FrameLayout.LayoutParams(activity!!.dpToPx(52).toInt(), activity!!.dpToPx(52).toInt())
fp.gravity = Gravity.CENTER
rootView.addView(progressBar, fp)
} else {
progressBar?.visibility = View.VISIBLE
}
} else {
super.showLoadAnimation()
}
}
override fun closeLoadAnimation() {
if (progressBar?.visibility == View.VISIBLE) {
progressBar?.visibility = View.GONE
} else {
super.closeLoadAnimation()
}
}
} | 0 | Kotlin | 3 | 10 | fa550792aefc532dd17ee6484fa007fef1651b2b | 5,367 | Lipper | MIT License |
sdk/src/main/java/com/spacer/sdk/data/api/ILoggerAPI.kt | spacer-dev | 404,248,319 | false | {"Kotlin": 103624} | package com.spacer.sdk.data.api
import com.spacer.sdk.data.api.reqData.logger.LoggerReqData
import com.spacer.sdk.data.api.resData.IResData
import retrofit2.Call
import retrofit2.http.POST
import retrofit2.http.Body
import retrofit2.http.HeaderMap
interface ILoggerAPI {
@POST("logger/warn")
fun sendWarn(@HeaderMap headers: Map<String, String>, @Body params: LoggerReqData): Call<IResData>
} | 0 | Kotlin | 0 | 0 | d5a72898ecad6ba3f6aee3c8f076478f63931fe3 | 402 | spacer-sdk-android | MIT License |
src/main/kotlin/no/nav/syfo/aktivitetskrav/api/AktivitetskravResponseDTO.kt | navikt | 554,767,872 | false | {"Kotlin": 411218, "Dockerfile": 226} | package no.nav.syfo.aktivitetskrav.api
import no.nav.syfo.aktivitetskrav.domain.Aktivitetskrav
import no.nav.syfo.aktivitetskrav.domain.AktivitetskravStatus
import no.nav.syfo.aktivitetskrav.domain.VurderingArsak
import no.nav.syfo.aktivitetskrav.domain.isInFinalState
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
data class AktivitetskravResponseDTO(
val uuid: UUID,
val createdAt: LocalDateTime,
val status: AktivitetskravStatus,
val inFinalState: Boolean,
val stoppunktAt: LocalDate,
val vurderinger: List<AktivitetskravVurderingResponseDTO>,
) {
companion object {
fun from(aktivitetskrav: Aktivitetskrav, vurderinger: List<AktivitetskravVurderingResponseDTO> = emptyList()) =
AktivitetskravResponseDTO(
uuid = aktivitetskrav.uuid,
createdAt = aktivitetskrav.createdAt.toLocalDateTime(),
status = aktivitetskrav.status,
inFinalState = aktivitetskrav.isInFinalState(),
stoppunktAt = aktivitetskrav.stoppunktAt,
vurderinger = vurderinger
)
}
}
data class AktivitetskravVurderingResponseDTO(
val uuid: String,
val createdAt: LocalDateTime,
val createdBy: String,
val status: AktivitetskravStatus,
val beskrivelse: String?,
val arsaker: List<VurderingArsak>,
val frist: LocalDate?,
val varsel: VarselResponseDTO?
)
data class VarselResponseDTO(
val uuid: String,
val createdAt: LocalDateTime,
val svarfrist: LocalDate,
val document: List<DocumentComponentDTO>,
)
| 1 | Kotlin | 1 | 0 | 2b15972fda3ae09c4116b818695c6d3fc8c9a784 | 1,607 | isaktivitetskrav | MIT License |
myandroidutil/src/main/java/com/starsoft/myandroidutil/timeutils/Timer.kt | DmitryStarkin | 315,625,438 | false | {"Kotlin": 326122, "Java": 29960} | /*
* Copyright (c) 2020. <NAME> Contacts: <EMAIL>
*
* 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
* //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.starsoft.myandroidutil.timeutils
import android.os.Handler
import android.os.Looper
import android.os.Message
// This File Created at 25.11.2020 13:35.
@Deprecated(
message = "Use ScheduledJobTimer instead",
replaceWith = ReplaceWith("ScheduledJobTimer()", "com.starsoft.myandroidutil.timeutils.ScheduledJobTimer")
)
object Timer : Handler(Looper.getMainLooper()){
private const val WENT_OFF = 1
@Suppress("UNCHECKED_CAST")
override fun handleMessage(msg: Message) {
when (msg.what) {
WENT_OFF -> (msg.obj as () -> Unit).invoke()
}
}
fun start(time: Long, listener: () -> Unit){
removeMessages(WENT_OFF)
val message: Message = obtainMessage(WENT_OFF, listener)
sendMessageDelayed(message, time)
}
fun stop(){
removeMessages(WENT_OFF)
}
} | 0 | Kotlin | 0 | 3 | e0f442ee764f2fe7ab972422d82ef69c75f92281 | 1,471 | my_android_utils | Apache License 2.0 |
auth/ForgetPasswordFragment.kt | MostafaaAbdelaziz | 734,837,104 | false | {"Kotlin": 209642} | package com.kotlinkhaos.ui.auth
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.kotlinkhaos.classes.errors.FirebaseAuthError
import com.kotlinkhaos.classes.user.User
import com.kotlinkhaos.databinding.FragmentForgetPasswordBinding
import kotlinx.coroutines.launch
class ForgetPasswordFragment : Fragment() {
private var _binding: FragmentForgetPasswordBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentForgetPasswordBinding.inflate(inflater, container, false)
val root: View = binding.root
//This is to handle the "ForgetPassword" button whenever it is clicked it goes into the
//function handleForgetPassword().
binding.forgetPasswordButton.setOnClickListener {
handleForgetPassword()
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
/**
* This function is to handle the "ForgetPassword" button whenever it is clicked it goes into the
* function handleForgetPassword(). This function handles the reset password of the user by asking the
* users email. Then by using the sendForgotPasswordEmail found in the User class we are able
* to reset the password of the user and if the user is reseted successfully with no issues or errors then
* the user is taken to the login page where they are presented with the login page. The email as I
* have tested multiple times can take a few minutes to be sent to the user, I recieved it in my
* spam/junk folder.
*/
private fun handleForgetPassword() {
lifecycleScope.launch {
try {
//This is to get the email from the user.
val email = binding.inputEmailAddress.text.toString().trim()
//This is to reset the password of the user. This is to send the email.
User.sendForgotPasswordEmail(email)
//This is to show a toast message whenever ti has been resetted successfully and
//tells the user to check their email.
Toast.makeText(
requireContext(),
"Password has been reseted successfully! Please check your email.",
Toast.LENGTH_LONG
).show()
//After that it will take the user if everything is successful to the login page.
handleGoToLogin()
} catch (err: Exception) {
if (err is FirebaseAuthError) {
//This is to show the error message if there is an error.
binding.errorMessage.text = err.message
return@launch
}
//if theres anythign else that goes wrong it will throw an error.
throw err
}
}
}
//This is to take the user back to the login page.
private fun handleGoToLogin() {
val action = ForgetPasswordFragmentDirections.actionGoToLogin()
findNavController().navigate(action)
}
} | 0 | Kotlin | 0 | 0 | 765e545baafacb3a1e581ba7f7fc65bbb7d7e202 | 3,503 | Kotlin-Khaos-AI-Powered-Learning-Application- | MIT License |
app/src/main/java/scimone/diafit/features/home/presentation/components/ComponentRotatingArrowIcon.kt | scimone | 821,835,868 | false | {"Kotlin": 48107} | package scimone.diafit.features.home.presentation.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.unit.dp
@Composable
fun ComponentRotatingArrowIcon(inputValue: Float?) {
if (inputValue != null) {
val rotationAngle = (-inputValue * 180f) // Scale inputValue to [0, 180] range
Canvas(
modifier = Modifier
.size(50.dp)
.rotate(rotationAngle)
) {
drawArrow(color = Color.White)
}
}
}
fun DrawScope.drawArrow(color: Color) {
val center = size.minDimension / 2f
val radius = center - 10.dp.toPx()
val arrowStrokeWidth = 2.5.dp.toPx()
// Draw outlined circle
drawCircle(
color = color,
radius = radius,
center = Offset(center, center),
style = Stroke(width = arrowStrokeWidth)
)
// Draw arrow line
val arrowLength = radius * 1.1f
val arrowStartX = center
val arrowEndX = center
val arrowStartY = center + arrowLength / 2
val arrowEndY = center - arrowLength / 2
drawLine(
color = color,
start = Offset(arrowStartX, arrowStartY - radius * 0.25f),
end = Offset(arrowEndX, arrowEndY),
strokeWidth = arrowStrokeWidth
)
// Draw arrowhead (triangle)
drawArrowhead(Offset(arrowStartX, arrowStartY), color, radius)
}
fun DrawScope.drawArrowhead(position: Offset, color: Color, radius: Float) {
val triangleHeight = radius * 0.35f
val triangleBaseHalf = radius * 0.5f
val path = Path().apply {
moveTo(position.x, position.y) // Tip of the arrowhead
lineTo(
position.x + triangleHeight,
position.y - triangleBaseHalf
) // Bottom right of the arrowhead
lineTo(
position.x - triangleHeight,
position.y - triangleBaseHalf
) // Bottom left of the arrowhead
close()
}
drawIntoCanvas { canvas ->
canvas.drawOutline(
outline = Outline.Generic(path),
paint = Paint().apply {
this.color = color
pathEffect = PathEffect.cornerPathEffect(radius * 0.1f) // Use a fraction of the radius for corner rounding
}
)
}
}
| 0 | Kotlin | 0 | 0 | aa00b35f79a1b3127cb45be88a77133e4c805a5c | 2,906 | diafit-android | MIT License |
src/test/java/tech/sirwellington/alchemy/http/restful/ReqResponseAPITest.kt | SirWellington | 43,511,958 | false | {"Kotlin": 237290, "Java": 9346} | /*
* Copyright © 2019. <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 tech.sirwellington.alchemy.http.restful
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory
import tech.sirwellington.alchemy.annotations.testing.IntegrationTest
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.smallPositiveIntegers
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.generator.one
import tech.sirwellington.alchemy.http.AlchemyHttpBuilder
import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException
import tech.sirwellington.alchemy.kotlin.extensions.isEmptyOrNull
import tech.sirwellington.alchemy.test.hamcrest.notNull
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.GeneratePojo
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.fail
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner::class)
@IntegrationTest
@Repeat(50)
class ReqResponseAPITest
{
companion object
{
private const val ENDPOINT = "https://reqres.in"
private val http = AlchemyHttpBuilder.newInstance().build()
private val LOG = LoggerFactory.getLogger(this::class.java)
}
data class CreateUserRequest(val name: String, val job: String)
data class CreateUserResponse(val name: String?,
val job: String?,
val id: String?,
val createdAt: String?)
data class UpdateUserResponse(val name: String?,
val job: String?,
val updatedAt: String?)
@GeneratePojo
private lateinit var request: CreateUserRequest
@Test
fun testCreateUser()
{
val url = "$ENDPOINT/api/users"
val response = http.go()
.post()
.body(request)
.expecting(CreateUserResponse::class.java)
.at(url)
LOG.info("POST @ [$url] produced | [$response]")
assertThat(response, notNull)
assertThat(response.name, equalTo(request.name))
assertThat(response.job, equalTo(request.job))
assertFalse { response.id.isEmptyOrNull }
assertFalse { response.createdAt.isEmptyOrNull }
}
@Test
fun testUpdateUser()
{
val userId = 3
val url = "$ENDPOINT/api/users/$userId"
val response = http.go()
.put()
.body(request)
.expecting(UpdateUserResponse::class.java)
.at(url)
LOG.info("PUT request @ [$url] produced response [$response]")
assertThat(response, notNull)
assertThat(response.name, equalTo(request.name))
assertThat(response.job, equalTo(request.job))
assertFalse { response.updatedAt.isEmptyOrNull }
}
@Test
fun testDeleteUser()
{
val userId = one(smallPositiveIntegers())
val url = "$ENDPOINT/api/users/$userId"
val response = http.go()
.delete()
.noBody()
.at(url)
LOG.info("DELETE request @[$url] produced | [$response]")
assertThat(response, notNull)
assertTrue { response.isOk }
assertThat(response.statusCode(), equalTo(204))
}
@Test
fun testWithInvalidBody()
{
val url = "$ENDPOINT/api/users"
val body = one(alphabeticStrings())
try
{
val response = http.go()
.post()
.body(body)
.at(url)
}
catch (ex: AlchemyHttpException)
{
assertThat(ex.request, notNull)
assertThat(ex.response, notNull)
LOG.info("Received response: [${ex.response}]")
return
}
catch (ex: Exception)
{
throw ex
}
fail("Expected exception here")
}
} | 4 | Kotlin | 1 | 6 | f2d312f336f7d8fec642a6a8158e7e56ada44b94 | 4,767 | alchemy-http | Apache License 2.0 |
compiler/src/main/kotlin/io/github/aplcornell/viaduct/analysis/HostTrustConfiguration.kt | apl-cornell | 169,159,978 | false | {"Kotlin": 1117382, "Java": 43793, "C++": 13898, "Lex": 12293, "Python": 11983, "Dockerfile": 1951, "Makefile": 1762, "SWIG": 1212, "Shell": 950} | package io.github.aplcornell.viaduct.analysis
import io.github.aplcornell.viaduct.algebra.FreeDistributiveLattice
import io.github.aplcornell.viaduct.algebra.FreeDistributiveLatticeCongruence
import io.github.aplcornell.viaduct.passes.PrincipalComponent
import io.github.aplcornell.viaduct.security.Component
import io.github.aplcornell.viaduct.security.ConfidentialityComponent
import io.github.aplcornell.viaduct.security.HostPrincipal
import io.github.aplcornell.viaduct.security.IntegrityComponent
import io.github.aplcornell.viaduct.security.Label
import io.github.aplcornell.viaduct.security.Principal
import io.github.aplcornell.viaduct.security.actsFor
import io.github.aplcornell.viaduct.syntax.intermediate.AuthorityDelegationDeclarationNode
import io.github.aplcornell.viaduct.syntax.intermediate.HostDeclarationNode
import io.github.aplcornell.viaduct.syntax.intermediate.ProgramNode
/** A map that associates each host with its authority label. */
class HostTrustConfiguration internal constructor(val program: ProgramNode) : Analysis<ProgramNode> {
val congruence: FreeDistributiveLatticeCongruence<Component<Principal>> =
FreeDistributiveLatticeCongruence(
program.filterIsInstance<AuthorityDelegationDeclarationNode>()
.flatMap { it.congruences() } +
program.filterIsInstance<HostDeclarationNode>().map {
FreeDistributiveLattice.LessThanOrEqualTo(
FreeDistributiveLattice(IntegrityComponent(HostPrincipal(it.name.value) as Principal) as PrincipalComponent),
FreeDistributiveLattice(ConfidentialityComponent(HostPrincipal(it.name.value) as Principal) as PrincipalComponent),
)
},
)
fun actsFor(from: Label, to: Label) = actsFor(from, to, congruence)
fun equals(from: Label, to: Label) = actsFor(from, to) && actsFor(to, from)
}
| 31 | Kotlin | 4 | 20 | 567491fdcfd313bf287b8cdd374e80f1e005ac62 | 1,923 | viaduct | MIT License |
src/commonMain/kotlin/net/kyori/adventure/webui/BuildInfo.kt | KyoriPowered | 390,772,083 | false | {"Kotlin": 91655, "HTML": 21526, "CSS": 6432} | package net.kyori.adventure.webui
import kotlinx.serialization.Serializable
@Serializable
public data class BuildInfo(
public val startedAt: String,
public val version: String,
public val commit: String,
public val bytebinInstance: String
)
| 41 | Kotlin | 16 | 28 | e8016f1f487d738a56ca52f79c431c7e2b7bb23f | 259 | adventure-webui | MIT License |
app/src/main/java/com/sunnyweather/android/logic/model/DailyResponse.kt | hhrhapsody | 264,823,805 | false | null | package com.sunnyweather.android.logic.model
import com.google.gson.annotations.SerializedName
import java.util.*
data class DailyResponse(val status:String,val result:Result) {
data class Result(val daily:Daily)
data class Daily(val temperature:List<Temperature>,val skycon:List<Skycon>,@SerializedName("life_index")val lifeIndex:LifeIndex)
data class Temperature(val max:Float,val min:Float)
data class Skycon(val value:String,val date: Date)
data class LifeIndex(val coldRisk: List<LifeDescription>,
val carWashing: List<LifeDescription>, val ultraviolet: List<LifeDescription>,
val dressing: List<LifeDescription>)
data class LifeDescription(val desc: String)
} | 0 | Kotlin | 0 | 0 | c4ea8970a7db485caade6a6a876dbc7a14e39419 | 742 | SunnyWeather | Apache License 2.0 |
app/src/main/java/com/connectycube/messenger/helpers/RTCSessionManager.kt | ConnectyCube | 198,286,170 | false | {"Kotlin": 391742, "Java": 23765} | package com.connectycube.messenger.helpers
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import com.connectycube.chat.ConnectycubeChatService
import com.connectycube.chat.WebRTCSignaling
import com.connectycube.core.helper.StringifyArrayList
import com.connectycube.messenger.CallActivity
import com.connectycube.messenger.EXTRA_IS_INCOMING_CALL
import com.connectycube.messenger.R
import com.connectycube.messenger.api.ConnectycubePushSender
import com.connectycube.pushnotifications.model.ConnectycubeEnvironment
import com.connectycube.pushnotifications.model.ConnectycubeEvent
import com.connectycube.pushnotifications.model.ConnectycubeNotificationType
import com.connectycube.videochat.RTCClient
import com.connectycube.videochat.RTCConfig
import com.connectycube.videochat.RTCMediaConfig
import com.connectycube.videochat.RTCSession
import com.connectycube.videochat.callbacks.RTCClientSessionCallbacks
import com.connectycube.videochat.callbacks.RTCClientSessionCallbacksImpl
import org.json.JSONObject
import timber.log.Timber
const val MAX_OPPONENTS = 4
class RTCSessionManager {
companion object {
// For Singleton instantiation
@Volatile
private var instance: RTCSessionManager? = null
fun getInstance() =
instance ?: synchronized(this) {
instance ?: RTCSessionManager().also { instance = it }
}
}
private var applicationContext: Context? = null
private var sessionCallbackListener: RTCClientSessionCallbacks? = null
var currentCall: RTCSession? = null
fun init(applicationContext: Context) {
this.applicationContext = applicationContext
this.sessionCallbackListener = RTCSessionCallbackListenerSimple()
RTCConfig.setMaxOpponentsCount(MAX_OPPONENTS)
RTCConfig.setDebugEnabled(true)
ConnectycubeChatService.getInstance()
.videoChatWebRTCSignalingManager?.addSignalingManagerListener { signaling, createdLocally ->
if (!createdLocally) {
RTCClient.getInstance(applicationContext).addSignaling(signaling as WebRTCSignaling)
}
}
RTCClient.getInstance(applicationContext).addSessionCallbacksListener(
sessionCallbackListener
)
RTCClient.getInstance(applicationContext).prepareToProcessCalls()
}
fun startCall(rtcSession: RTCSession) {
checkNotNull(applicationContext) { "RTCSessionManager should be initialized before start call" }
currentCall = rtcSession
initRTCMediaConfig()
startCallActivity(false)
sendCallPushNotification(rtcSession.opponents, rtcSession.sessionID, RTCConfig.getAnswerTimeInterval())
}
private fun initRTCMediaConfig() {
currentCall?.let {
if (it.opponents.size < 2) {
RTCMediaConfig.setVideoWidth(RTCMediaConfig.VideoQuality.HD_VIDEO.width)
RTCMediaConfig.setVideoHeight(RTCMediaConfig.VideoQuality.HD_VIDEO.height)
} else {
RTCMediaConfig.setVideoWidth(RTCMediaConfig.VideoQuality.QVGA_VIDEO.width)
RTCMediaConfig.setVideoHeight(RTCMediaConfig.VideoQuality.QVGA_VIDEO.height)
}
}
}
private fun sendCallPushNotification(
opponents: List<Int>,
sessionId: String,
answerTimeInterval: Long
) {
val event = ConnectycubeEvent()
event.userIds = StringifyArrayList(opponents)
event.environment = ConnectycubeEnvironment.DEVELOPMENT
event.notificationType = ConnectycubeNotificationType.PUSH
val json = JSONObject()
try {
json.put(
PARAM_MESSAGE,
applicationContext?.getString(R.string.you_have_got_new_incoming_call_open_app_to_manage_it)
)
// custom parameters
json.put(PARAM_NOTIFICATION_TYPE, NOTIFICATION_TYPE_CALL)
json.put(PARAM_CALL_ID, sessionId)
json.put(PARAM_ANSWER_TIMEOUT, answerTimeInterval)
} catch (e: Exception) {
e.printStackTrace()
}
event.message = json.toString()
ConnectycubePushSender().sendCallPushEvent(event)
}
fun receiveCall(rtcSession: RTCSession) {
if (currentCall != null) {
if (currentCall!!.sessionID != rtcSession.sessionID) {
rtcSession.rejectCall(hashMapOf())
}
return
}
currentCall = rtcSession
initRTCMediaConfig()
startCallActivity(true)
}
fun endCall() {
currentCall = null
}
private fun startCallActivity(isIncoming: Boolean) {
Timber.w("start call incoming - $isIncoming")
val intent = Intent(applicationContext, CallActivity::class.java)
intent.flags = FLAG_ACTIVITY_NEW_TASK
intent.putExtra(EXTRA_IS_INCOMING_CALL, isIncoming)
applicationContext?.startActivity(intent)
}
fun destroy() {
RTCClient.getInstance(applicationContext)
.removeSessionsCallbacksListener(sessionCallbackListener)
RTCClient.getInstance(applicationContext).destroy()
applicationContext = null
sessionCallbackListener = null
}
private inner class RTCSessionCallbackListenerSimple : RTCClientSessionCallbacksImpl() {
override fun onReceiveNewSession(session: RTCSession?) {
super.onReceiveNewSession(session)
session?.let { receiveCall(session) }
}
override fun onSessionClosed(session: RTCSession?) {
super.onSessionClosed(session)
if (session == null || currentCall == null) return
if (currentCall!!.sessionID == session.sessionID) {
endCall()
}
}
}
} | 9 | Kotlin | 21 | 50 | ebb33febac1c5addfa79378bb88ac4b148f1d7e4 | 5,875 | android-messenger-app | Apache License 2.0 |
android/src/main/kotlin/com/techprd/httpd/flutter_httpd/Response.kt | techprd | 225,112,114 | false | null | package com.techprd.httpd.flutter_httpd
import com.techprd.httpd.flutter_httpd.Statics.HTTP_OK
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.util.*
/**
* HTTP response.
* Return one of these from serve().
*/
class Response {
/**
* HTTP status code after processing, e.g. "200 OK", HTTP_OK
*/
var status: String
/**
* MIME type of content, e.g. "text/html"
*/
var mimeType: String
/**
* Data of the response, may be null.
*/
lateinit var data: InputStream
/**
* Headers for the HTTP response. Use addHeader()
* to add lines.
*/
var header = Properties()
/**
* Default constructor: response = HTTP_OK, data = mime = 'null'
*/
init {
this.status = HTTP_OK
}
/**
* Basic constructor.
*/
constructor(status: String, mimeType: String, data: InputStream) {
this.status = status
this.mimeType = mimeType
this.data = data
}
/**
* Convenience method that makes an InputStream out of
* given text.
*/
constructor(status: String, mimeType: String, txt: String) {
this.status = status
this.mimeType = mimeType
try {
this.data = ByteArrayInputStream(txt.toByteArray(charset("UTF-8")))
} catch (uee: UnsupportedEncodingException) {
uee.printStackTrace()
}
}
/**
* Adds given line to the header.
*/
fun addHeader(name: String, value: String) {
header[name] = value
}
} | 0 | Kotlin | 0 | 1 | fe82686385894d6f085dc553db2cb8cf1867b590 | 1,614 | flutter_httpd | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/apigatewayv2/HttpStagePropsDsl.kt | F43nd1r | 643,016,506 | false | {"Kotlin": 5253787} | package com.faendir.awscdkkt.generated.services.apigatewayv2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.apigatewayv2.HttpStageProps
@Generated
public fun buildHttpStageProps(initializer: @AwsCdkDsl HttpStageProps.Builder.() -> Unit = {}):
HttpStageProps = HttpStageProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 4 | 497558034ccaddec5ac20cbab34fd730c8cc4fd9 | 403 | aws-cdk-kt | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/presentation/ui/components/home/bottomsheet/MinBottomSheetContent.kt | timlam9 | 348,776,523 | 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.presentation.ui.components.home.bottomsheet
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraintsScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
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.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowRight
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.data.response.Hourly
import com.example.androiddevchallenge.presentation.ui.components.home.components.WeatherColumnCard
@Composable
fun BoxWithConstraintsScope.MinBottomSheetContent(data: List<Hourly>, action: () -> Unit) {
val dividerWidth = maxWidth / 6
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(2.dp))
Divider(
modifier = Modifier
.height(3.dp)
.width(dividerWidth)
.background(color = MaterialTheme.colors.secondary)
)
Spacer(modifier = Modifier.height(10.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.height(30.dp)
.padding(start = 30.dp, end = 20.dp)
) {
Text(
text = "Today",
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.surface
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
Text(
text = "Next 7 days",
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.surface
)
IconButton(
onClick = action,
modifier = Modifier.aspectRatio(1f)
) {
Icon(
imageVector = Icons.Default.ArrowRight,
contentDescription = "",
tint = MaterialTheme.colors.surface
)
}
}
}
LazyRow(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 10.dp, bottom = 10.dp, top = 5.dp)
) {
items(data) { weather ->
with(weather) {
WeatherColumnCard(type, time, temperature)
Spacer(modifier = Modifier.padding(end = 10.dp))
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 6ba21d49459b88ded2be8d032dc3355242563fac | 4,376 | ComposeWeatherApp | Apache License 2.0 |
src/main/kotlin/io/github/kr8gz/playerstatistics/database/Database.kt | kr8gz | 780,166,652 | false | {"Kotlin": 45309, "Java": 2522} | package io.github.kr8gz.playerstatistics.database
import io.github.kr8gz.playerstatistics.PlayerStatistics
import io.github.kr8gz.playerstatistics.extensions.ServerStatHandler.uuid
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.*
import net.minecraft.server.MinecraftServer
import net.minecraft.stat.ServerStatHandler
import net.minecraft.util.WorldSavePath
import java.nio.file.Files
import java.sql.*
import kotlin.streams.asSequence
import kotlin.time.Duration.Companion.seconds
object Database {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private lateinit var URL: String
private val connection by object {
var connection: Connection? = null
operator fun getValue(thisRef: Any?, property: Any?): Connection {
return connection?.takeUnless { it.isClosed } ?: DriverManager.getConnection(URL).apply {
autoCommit = false
connection = this
}
}
}
fun transaction(block: suspend Database.() -> Unit): Job {
return coroutineScope.launch { Database.block() }.apply {
invokeOnCompletion { connection.commit() }
}
}
// don't expose the connection object
fun prepareStatement(sql: String): PreparedStatement = connection.prepareStatement(sql)
class Initializer<T : Any>(block: suspend Statement.() -> T) {
private lateinit var value: T
operator fun getValue(thisRef: Any?, property: Any?) = value
init {
listeners += { value = block() }
}
companion object {
private var job: Job? = null
val isCompleted get() = job?.isCompleted == true
private val listeners = mutableListOf<suspend Statement.() -> Unit>()
fun run(server: MinecraftServer) {
URL = server.getSavePath(WorldSavePath.ROOT)
.resolve("${PlayerStatistics.MOD_NAME}.db").toFile()
.let { "jdbc:sqlite:$it?foreign_keys=on" }
job = transaction {
connection.createStatement().use { statement ->
listeners.forEach { it(statement) }
val hasExistingEntries = statement.executeQuery("SELECT 1 FROM $Statistics LIMIT 1").next()
if (!hasExistingEntries) populateTables(server)
}
}.apply {
invokeOnCompletion {
PlayerStatistics.LOGGER.info("Finished database initialization")
}
}
}
private suspend fun populateTables(server: MinecraftServer) {
fun streamStatsFiles() = Files.list(server.getSavePath(WorldSavePath.STATS))
val fileCount = streamStatsFiles().count().also { if (it == 0L) return }
val completedFiles = atomic(0)
coroutineScope.launch {
while (!isCompleted) {
PlayerStatistics.LOGGER.info("Populating tables ($completedFiles/$fileCount players)")
delay(5.seconds)
}
}
streamStatsFiles().asSequence().forEach { path ->
val statHandler = ServerStatHandler(server, path.toFile())
// the user cache can only store up to 1000 players by default, but at least it's better than nothing
server.userCache?.getByUuid(statHandler.uuid)?.let { if (it.isPresent) Players.updateProfile(it.get()) }
Statistics.updateStats(statHandler, changedOnly = false)
completedFiles.incrementAndGet()
}
}
}
}
sealed class Object(private val name: String) {
final override fun toString() = name
protected abstract fun createSQL(): String
init {
Initializer { executeUpdate(createSQL()) }
}
}
abstract class Table(name: String) : Object(name) {
protected abstract val schema: List<String>
override fun createSQL() = "CREATE TABLE IF NOT EXISTS $this (${schema.joinToString()})"
}
abstract class View(name: String) : Object(name) {
protected abstract val definition: String
override fun createSQL() = "CREATE VIEW IF NOT EXISTS $this AS $definition"
}
}
| 2 | Kotlin | 0 | 3 | 7ec35d74be4cdcd6d91b09193c2faf39e2cd96a2 | 4,399 | PlayerStatistics | MIT License |
src/commonMain/kotlin/de/tfr/game/libgx/emu/Viewport.kt | TobseF | 171,953,042 | true | {"Kotlin": 34114, "Shell": 1210} | package de.tfr.game.libgx.emu
import com.soywiz.korma.geom.Point
object Viewport {
fun unproject(point: Point) = point
fun update(width: Int, height: Int, b: Boolean) {
}
} | 0 | Kotlin | 0 | 0 | ad87c2a3ee21cdc8fe65e616bf118afb755d4b53 | 189 | korge-hitklack-port | MIT License |
src/main/java/me/shadowalzazel/mcodyssey/enchantments/ranged/SingularityShot.kt | ShadowAlzazel | 511,383,377 | false | null | package me.shadowalzazel.mcodyssey.enchantments.ranged
import me.shadowalzazel.mcodyssey.enchantments.OdysseyEnchantments
import me.shadowalzazel.mcodyssey.enchantments.base.OdysseyEnchantment
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemStack
object SingularityShot : OdysseyEnchantment("singularity_shot", "Singularity Shot", 3) {
override fun conflictsWith(other: Enchantment): Boolean {
return when (other) {
OdysseyEnchantments.RICOCHET, OdysseyEnchantments.PERPETUAL_PROJECTILE, OdysseyEnchantments.STELLAR_SHOWER -> {
true
}
else -> {
false
}
}
}
override fun canEnchantItem(item: ItemStack): Boolean {
return when (item.type) {
Material.ENCHANTED_BOOK, Material.CROSSBOW, Material.BOW -> {
true
}
else -> {
false
}
}
}
//
fun todo() {
TODO("Shoots singularity, replace arrow")
}
} | 0 | Kotlin | 0 | 3 | 19f50df1a672bc1a34a16ef7e89872a5db1c8f7f | 1,078 | MinecraftOdyssey | MIT License |
src/main/java/me/shadowalzazel/mcodyssey/enchantments/ranged/SingularityShot.kt | ShadowAlzazel | 511,383,377 | false | null | package me.shadowalzazel.mcodyssey.enchantments.ranged
import me.shadowalzazel.mcodyssey.enchantments.OdysseyEnchantments
import me.shadowalzazel.mcodyssey.enchantments.base.OdysseyEnchantment
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemStack
object SingularityShot : OdysseyEnchantment("singularity_shot", "Singularity Shot", 3) {
override fun conflictsWith(other: Enchantment): Boolean {
return when (other) {
OdysseyEnchantments.RICOCHET, OdysseyEnchantments.PERPETUAL_PROJECTILE, OdysseyEnchantments.STELLAR_SHOWER -> {
true
}
else -> {
false
}
}
}
override fun canEnchantItem(item: ItemStack): Boolean {
return when (item.type) {
Material.ENCHANTED_BOOK, Material.CROSSBOW, Material.BOW -> {
true
}
else -> {
false
}
}
}
//
fun todo() {
TODO("Shoots singularity, replace arrow")
}
} | 0 | Kotlin | 0 | 3 | 19f50df1a672bc1a34a16ef7e89872a5db1c8f7f | 1,078 | MinecraftOdyssey | MIT License |
src/main/kotlin/com/trackforever/main.kt | cse403trackforever | 133,859,678 | false | null | package com.trackforever
import com.trackforever.Application.Companion.arguments
import com.trackforever.repositories.ProjectRepository
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
@SpringBootApplication
class Application {
@Bean
fun init(projectRepository: ProjectRepository) = CommandLineRunner {
if (arguments.contains("clearAll")) {
logger.debug("CLEARING ALL DATA")
projectRepository.deleteAll()
}
}
companion object {
val logger = LoggerFactory.getLogger(Application::class.java)
lateinit var arguments: Array<String>
}
}
fun main(args: Array<String>) {
arguments = args
SpringApplication.run(Application::class.java, *args)
} | 3 | Kotlin | 0 | 3 | 52d4134a6aa93e361983b02ef7f32c4d304dd944 | 925 | server2 | MIT License |
src/main/kotlin/InstructionLoadToMemory.kt | hoodlm | 592,554,474 | false | null | import kotlin.reflect.KMutableProperty
interface InstructionLoadFromRegisterToMemory: Instruction {
override val size: UShort
get() = 1u
fun destinationAddress(registers: Registers, data: List<UByte>): UShort
fun valueRegister(registers: Registers): KMutableProperty<UByte>
fun postInvoke(registers: Registers) {
// Optional post-invoke code hook, e.g. for decrement/increment register instructions like LD (HL-) A
}
override fun invoke(registers: Registers, memory: Memory, immediateData: List<UByte>) {
assert(immediateData.size == 4)
val destinationAddress = destinationAddress(registers, immediateData)
val destinationValue = valueRegister(registers).getter.call()
memory.putByte(destinationAddress, destinationValue)
postInvoke(registers)
}
}
interface InstructionLoadFromRegisterToHL: InstructionLoadFromRegisterToMemory {
override fun destinationAddress(registers: Registers, data: List<UByte>) = registers.HL()
}
class InstructionLoadFromAToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
}
class InstructionLoadFromBToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::B
}
class InstructionLoadFromCToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::C
}
class InstructionLoadFromDToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::D
}
class InstructionLoadFromEToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::E
}
class InstructionLoadFromHToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::H
}
class InstructionLoadFromLToHL: InstructionLoadFromRegisterToHL {
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::L
}
class InstructionLoadFromAToHLDecrement: InstructionLoadFromRegisterToMemory {
override fun destinationAddress(registers: Registers, data: List<UByte>) = registers.HL()
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
override fun postInvoke(registers: Registers) {
registers.setHL(registers.HL().dec())
}
}
class InstructionLoadFromAToHLIncrement: InstructionLoadFromRegisterToMemory {
override fun destinationAddress(registers: Registers, data: List<UByte>) = registers.HL()
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
override fun postInvoke(registers: Registers) {
registers.setHL(registers.HL().inc())
}
}
class InstructionLoadAFromC: InstructionLoadFromRegisterToMemory {
override fun destinationAddress(registers: Registers, data: List<UByte>): UShort {
return (0xFF00u + registers.C).toUShort()
}
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
}
class InstructionLoadAFrom8BitLiteral: InstructionLoadFromRegisterToMemory {
override val size: UShort
get() = 2u
override fun destinationAddress(registers: Registers, data: List<UByte>): UShort {
return (0xFF00u + data[1]).toUShort()
}
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
}
class InstructionLoadAFrom16BitLiteral: InstructionLoadFromRegisterToMemory {
override val size: UShort
get() = 3u
override fun destinationAddress(registers: Registers, data: List<UByte>): UShort {
return Pair(data[2], data[1]).toUShort()
}
override fun valueRegister(registers: Registers): KMutableProperty<UByte> = registers::A
} | 0 | Kotlin | 0 | 0 | 3f8e64c10b0d13a9011064a194095da7bc5a64f0 | 3,928 | hoodboy | MIT License |
src/test/kotlin/com/vladsch/kotlin/jdbc/ModelJsonTest.kt | vsch | 133,859,578 | false | null | package com.vladsch.kotlin.jdbc
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import kotlin.test.assertEquals
// TODO: add json conversion tests
class ModelJsonTest {
@Rule
@JvmField
var thrown = ExpectedException.none()
}
| 6 | Kotlin | 10 | 50 | f0f1db26374a06757a3ba4638615ec9e8fb15386 | 277 | kotlin-jdbc | MIT License |
models/src/main/kotlin/io/provenance/api/models/p8e/tx/permissions/fees/get/GetFeeGrantAllowanceRequest.kt | provenance-io | 480,452,118 | false | {"Kotlin": 209962, "Shell": 13707} | package io.provenance.api.models.p8e.tx.permissions.fees.get
data class GetFeeGrantAllowanceRequest(
val nodeEndpoint: String,
val chainId: String,
val granter: String,
val grantee: String
)
| 5 | Kotlin | 6 | 1 | c3f61932f55945cc226780578496fde19dc1b000 | 208 | p8e-cee-api | Apache License 2.0 |
klaster-test/src/androidTest/java/com/github/rongi/klaster/TestKlasterBuilderWithViewHolder.kt | rongi | 132,181,599 | false | null | package com.github.rongi.klaster
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.github.rongi.klaster.test.test.R
import com.nhaarman.mockitokotlin2.*
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
@RunWith(AndroidJUnit4::class)
class TestKlasterBuilderWithViewHolder {
private val appContext = InstrumentationRegistry.getTargetContext()
private val parent = FrameLayout(appContext)
private val layoutInflater = LayoutInflater.from(appContext)
private val recyclerViewMock: RecyclerView = mock()
private val adapterDataObserverMock: RecyclerView.AdapterDataObserver = mock()
@Test
fun createsViewHolder() {
val items = listOf(Article("article title"))
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount { items.size }
.viewHolder { _, parent ->
val view = layoutInflater.inflate(R.layout.list_item, parent, false)
MyViewHolder(view)
}
.bind { position ->
articleTitle.text = items[position].title
}
.build()
val viewHolder = adapter.createViewHolder(parent, 0)
viewHolder assertIs MyViewHolder::class.java
}
@Test
fun createsViewHolderWithViewType() {
val items = listOf(Article("article title"))
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount { items.size }
.viewHolder { viewType: Int, parent: ViewGroup ->
when (viewType) {
TYPE1 -> MyViewHolder(TextView(appContext).apply {
text = "type 1"
id = R.id.item_text
})
TYPE2 -> MyViewHolder(TextView(appContext).apply {
text = "type 2"
id = R.id.item_text
})
else -> throw IllegalStateException("Unknown view type $viewType")
}
}
.bind { _ -> }
.build()
val viewHolder1 = adapter.createViewHolder(parent, TYPE1)
val viewHolder2 = adapter.createViewHolder(parent, TYPE2)
viewHolder1.itemView.cast<TextView>().text assertEquals "type 1"
viewHolder2.itemView.cast<TextView>().text assertEquals "type 2"
}
@Test
fun bindsViewHolder() {
val viewHolder = createViewHolder()
val items = listOf(Article("article title"))
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount { items.size }
.defaultViewHolder(layoutInflater)
.bind { position ->
articleTitle.text = "${items[position].title}, position: $position"
}
.build()
adapter.bindViewHolder(viewHolder, 0)
viewHolder.cast<MyViewHolder>().articleTitle.text assertEquals "article title, position: 0"
}
@Test
fun itemCountWorks() {
val items = listOf(Article("article1 title"), Article("article2 title"))
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount { items.size }
.defaultViewHolder(layoutInflater)
.bind { position ->
articleTitle.text = items[position].title
}
.build()
adapter.itemCount assertEquals 2
}
@Test
fun itemCountFromNumberWorks() {
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(42)
.defaultViewHolder(layoutInflater)
.bind { position ->
articleTitle.text = "position${position + 1}"
}
.build()
adapter.itemCount assertEquals 42
}
@Test
fun getItemIdWorks() {
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(42)
.defaultViewHolder(layoutInflater)
.defaultBind()
.getItemId { position -> position * 2L }
.build()
adapter.getItemId(10) assertEquals 20L
}
@Test
fun bindWithPayloadsWorks() {
val viewHolder = createViewHolder()
val mockFunction = mock<((binder: MyViewHolder, position: Int, payloads: MutableList<Any>) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.bind { position, payloads ->
mockFunction(this, position, payloads)
}
.build()
adapter.onBindViewHolder(viewHolder, 42, listOf("a"))
verify(mockFunction).invoke(any(), eq(42), eq(mutableListOf<Any>("a")))
}
@Test
fun getItemViewTypeWorks() {
val mockFunction = mock<((Int) -> Int)>().apply {
whenever(this.invoke(ArgumentMatchers.anyInt())).thenReturn(11)
}
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.getItemViewType { position ->
mockFunction(position)
}
.build()
adapter.getItemViewType(42)
verify(mockFunction).invoke(42)
}
@Test
fun setHasStableIdsWorks() {
val mockFunction = mock<(() -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.setHasStableIds {
mockFunction()
}
.build()
adapter.setHasStableIds(true)
verify(mockFunction).invoke()
}
@Test
fun onAttachedToRecyclerViewWorks() {
val mockFunction = mock<((recyclerView: RecyclerView) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onAttachedToRecyclerView { recyclerView ->
mockFunction(recyclerView)
}
.build()
adapter.onAttachedToRecyclerView(recyclerViewMock)
verify(mockFunction).invoke(recyclerViewMock)
}
@Test
fun onDetachedFromRecyclerViewWorks() {
val mockFunction = mock<((recyclerView: RecyclerView) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onDetachedFromRecyclerView { recyclerView ->
mockFunction(recyclerView)
}
.build()
adapter.onDetachedFromRecyclerView(recyclerViewMock)
verify(mockFunction).invoke(recyclerViewMock)
}
@Test
fun onViewAttachedToWindowWorks() {
val viewHolder = createViewHolder()
val mockFunction = mock<((holder: MyViewHolder) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onViewAttachedToWindow { holder ->
mockFunction(holder)
}
.build()
adapter.onViewAttachedToWindow(viewHolder)
verify(mockFunction).invoke(viewHolder)
}
@Test
fun onViewDetachedFromWindowWorks() {
val viewHolder = createViewHolder()
val mockFunction = mock<((holder: MyViewHolder) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onViewDetachedFromWindow { holder ->
mockFunction(holder)
}
.build()
adapter.onViewDetachedFromWindow(viewHolder)
verify(mockFunction).invoke(viewHolder)
}
@Test
fun onFailedToRecycleViewWorks() {
val viewHolder = createViewHolder()
val mockFunction = mock<((holder: MyViewHolder) -> Boolean)>().apply {
whenever(this.invoke(anyOrNull())).thenReturn(true)
}
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onFailedToRecycleView { holder ->
mockFunction(holder)
}
.build()
adapter.onFailedToRecycleView(viewHolder)
verify(mockFunction).invoke(viewHolder)
}
@Test
fun onViewRecycledWorks() {
val viewHolder = createViewHolder()
val mockFunction = mock<((holder: MyViewHolder) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.onViewRecycled { holder ->
mockFunction(holder)
}
.build()
adapter.onViewRecycled(viewHolder)
verify(mockFunction).invoke(viewHolder)
}
@Test
fun registerAdapterDataObserverWorks() {
val mockFunction = mock<((observer: RecyclerView.AdapterDataObserver) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.registerAdapterDataObserver { observer ->
mockFunction(observer)
}
.build()
adapter.registerAdapterDataObserver(adapterDataObserverMock)
verify(mockFunction).invoke(adapterDataObserverMock)
}
@Test
fun unregisterAdapterDataObserverWorks() {
val mockFunction = mock<((observer: RecyclerView.AdapterDataObserver) -> Unit)>()
val adapter = Klaster.withViewHolder<MyViewHolder>()
.itemCount(100)
.defaultViewHolder(layoutInflater)
.defaultBind()
.unregisterAdapterDataObserver { observer ->
mockFunction(observer)
}
.build()
adapter.unregisterAdapterDataObserver(adapterDataObserverMock)
verify(mockFunction).invoke(adapterDataObserverMock)
}
private fun createViewHolder(): MyViewHolder {
val viewMock: View = layoutInflater.inflate(R.layout.list_item, null)
return MyViewHolder(viewMock)
}
}
private fun KlasterBuilderWithViewHolder<MyViewHolder>.defaultViewHolder(layoutInflater: LayoutInflater): KlasterBuilderWithViewHolder<MyViewHolder> {
return this.viewHolder { _, parent ->
val view = layoutInflater.inflate(R.layout.list_item, parent, false)
MyViewHolder(view)
}
}
private fun KlasterBuilderWithViewHolder<MyViewHolder>.defaultBind(): KlasterBuilderWithViewHolder<MyViewHolder> {
return bind { position ->
articleTitle.text = "position${position + 1}"
}
}
| 4 | null | 10 | 371 | db40a14e47ea28def401b1f44c88f88cd70b33f5 | 9,925 | klaster | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.