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/ro/alexmamo/firemag/presentation/main/MainScreen.kt
|
alexmamo
| 569,800,514
| false
| null |
package ro.alexmamo.firemag.presentation.main
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.launch
import ro.alexmamo.firemag.components.DrawerTopBar
import ro.alexmamo.firemag.core.Utils.Companion.items
import ro.alexmamo.firemag.presentation.main.components.SignOut
import ro.alexmamo.firemag.presentation.main.components.drawer.DrawerContent
import ro.alexmamo.firemag.presentation.main.components.drawer.items.ItemFavorites
import ro.alexmamo.firemag.presentation.main.components.drawer.items.ItemHome
import ro.alexmamo.firemag.presentation.main.components.drawer.items.ItemOrders
import ro.alexmamo.firemag.presentation.main.components.drawer.items.ItemProfile
@Composable
@ExperimentalMaterial3Api
@ExperimentalFoundationApi
fun MainScreen(
viewModel: MainViewModel = hiltViewModel(),
navigateToProductSearchScreen: () -> Unit,
navigateToShoppingCartScreen: () -> Unit,
navigateToProductDetailsScreen: (productId: String) -> Unit,
navigateToBrandProductsScreen: (productBrand: String) -> Unit,
navigateToProductsOrderScreen: (orderId: String) -> Unit,
navigateToAuthScreen: () -> Unit
) {
val drawerState = rememberDrawerState(DrawerValue.Closed)
val coroutineScope = rememberCoroutineScope()
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DrawerContent(
user = viewModel.user,
drawerState = drawerState,
coroutineScope = coroutineScope
)
},
content = {
Scaffold(
topBar = {
DrawerTopBar(
openNavigationDrawer = {
coroutineScope.launch {
drawerState.open()
}
},
onSearchIconClick = navigateToProductSearchScreen,
onShoppingCartIconClick = navigateToShoppingCartScreen
)
},
content = { padding ->
Box(
modifier = Modifier.fillMaxSize().padding(padding)
) {
when (viewModel.selectedItem) {
items[0] -> ItemHome(
navigateToProductDetailsScreen = navigateToProductDetailsScreen,
navigateToBrandProductsScreen = navigateToBrandProductsScreen
)
items[1] -> ItemOrders(
navigateToProductsOrderScreen = navigateToProductsOrderScreen
)
items[2] -> ItemFavorites(
navigateToProductDetailsScreen = navigateToProductDetailsScreen
)
items[3] -> ItemProfile()
items[4] -> viewModel.signOut()
}
}
}
)
}
)
SignOut { signedOut ->
if (signedOut) {
navigateToAuthScreen()
}
}
}
| 0
|
Kotlin
|
1
| 9
|
d648c129c9d9f0841b898b6c178170e404f35024
| 3,593
|
FireMag
|
Apache License 2.0
|
app/src/main/java/ru/ltst/u2020mvp/base/mvp/Registry.kt
|
LiveTyping
| 69,892,571
| false
| null |
package ru.ltst.u2020mvp.base.mvp
import android.app.Activity
import android.os.Bundle
import android.support.annotation.IdRes
import ru.ltst.u2020mvp.util.Strings
import timber.log.Timber
import java.util.*
object Registry {
private val registers = HashMap<String, Entry<BaseView>>()
val SERVER: ActivityHierarchyServer.Empty = object : ActivityHierarchyServer.Empty() {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
val key = getKey(activity)
val entry = registers[key]
Timber.d("%s onActivityCreated", key)
if (entry != null && entry.presenter != null && savedInstanceState != null) {
entry.presenter.onRestore(savedInstanceState)
}
}
@SuppressWarnings("unchecked")
override fun onActivityStarted(activity: Activity) {
val key = getKey(activity)
val entry = registers[key]
Timber.d("%s onActivityStarted", key)
if (entry != null && entry.presenter != null) {
val view = activity.findViewById(entry.viewId) as BaseView
entry.presenter.takeView(view)
}
}
@SuppressWarnings("unchecked")
override fun onActivityStopped(activity: Activity) {
val key = getKey(activity)
val entry = registers[key]
Timber.d("%s onActivityStopped", key)
if (entry != null && entry.presenter != null) {
val view = activity.findViewById(entry.viewId) as BaseView
entry.presenter.dropView(view)
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
val key = getKey(activity)
val entry = registers[key]
Timber.d("%s onActivitySaveInstanceState", key)
if (entry != null && entry.presenter != null) {
entry.presenter.onSave(outState)
}
}
override fun onActivityDestroyed(activity: Activity) {
val key = getKey(activity)
Timber.d("%s onActivityDestroyed", key)
registers.remove(key)
}
}
fun <V : BaseView> add(activity: Activity, @IdRes viewId: Int, presenter: BasePresenter<V>) {
registers.put(getKey(activity), Entry(viewId, presenter) as Entry<BaseView>)
}
private fun getKey(activity: Activity): String {
val builder = StringBuilder()
builder.append(activity.javaClass.name)
if (activity is BaseActivity) {
val uniqueKey = activity.uniqueKey()
if (!uniqueKey.isEmpty()) {
builder.append(Strings.DOT).append(uniqueKey)
}
} else {
val action = activity.intent.action
if (action != null) {
builder.append(Strings.DOT).append(action)
}
val data = activity.intent.data
if (data != null) {
builder.append(Strings.DOT).append(data.toString())
}
val extras = activity.intent.extras
if (extras != null) {
for (key in extras.keySet()) {
val value = extras.get(key) ?: continue
val valueString: String
if (value.javaClass.isArray) {
valueString = Arrays.toString(value as Array<Any>)
} else {
valueString = value.toString()
}
builder.append(Strings.DOT)
builder.append(key).append(Strings.COLON)
builder.append(valueString)
}
}
}
return builder.toString()
}
private class Entry<V : BaseView>(@IdRes
val viewId: Int, val presenter: BasePresenter<V>?)
}
| 0
|
Kotlin
|
4
| 5
|
a704da798d7f11ceb4a59cbdbac5c5d4f34e3500
| 3,920
|
u2020-mvp-kotlin
|
Apache License 2.0
|
app/src/main/java/com/dawinder/customshapes_jc/ui/shapes/DiamondShape.kt
|
DawinderGill
| 670,214,470
| false
| null |
package com.dawinder.customshapes_jc.ui.shapes
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
/**
* Custom [Shape] implementation representing the shape of a diamond.
*
* The diamond shape is created using a [Path] by connecting its points with straight lines
* based on the provided [size] of the diamond.
*/
class DiamondShape : Shape {
/**
* Creates the [Outline] for the diamond shape.
*
* @param size The [Size] of the diamond.
* @param layoutDirection The [LayoutDirection] of the diamond.
* @param density The [Density] of the diamond.
* @return The [Outline] representing the diamond shape.
*/
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
return Outline.Generic(
path = drawDiamondPath(size)
)
}
}
/**
* Draws the path for the diamond shape.
*
* @param size The [Size] of the diamond.
* @return The [Path] representing the diamond shape.
*/
private fun drawDiamondPath(size: Size): Path {
return Path().apply {
val centerX = size.width / 2f
val diamondCurve = 60f
val width = size.width
val height = size.height
moveTo(x = 0f + diamondCurve, y = 0f)
lineTo(x = width - diamondCurve, y = 0f)
lineTo(x = width, y = diamondCurve)
lineTo(x = centerX, y = height)
lineTo(x = 0f, y = diamondCurve)
close()
}
}
| 0
|
Kotlin
|
0
| 1
|
3dac4209ccbaa15a5d423a2c99e08b18decfb660
| 1,686
|
CustomShapes-JetpackCompose
|
Apache License 2.0
|
src/main/kotlin/g2301_2400/s2322_minimum_score_after_removals_on_a_tree/Solution.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2301_2400.s2322_minimum_score_after_removals_on_a_tree
// #Hard #Array #Depth_First_Search #Tree #Bit_Manipulation
// #2023_06_30_Time_412_ms_(100.00%)_Space_49.1_MB_(100.00%)
class Solution {
private var ans = Int.MAX_VALUE
// function to travel 2nd time on the tree and find the second edge to be removed
private fun helper(
src: Int,
graph: Array<ArrayList<Int>?>,
arr: IntArray,
par: Int,
block: Int,
xor1: Int,
tot: Int
): Int {
// Setting the value for the current subtree's XOR value
var myXOR = arr[src]
for (nbr in graph[src]!!) {
// If the current nbr is niether the parent of this node nor the blocked node , then
// only we'll proceed
if (nbr != par && nbr != block) {
val nbrXOR = helper(nbr, graph, arr, src, block, xor1, tot)
// 'src <----> nbr' is the second edge to be removed
// Getting the XOR value of the current neighbor
// The XOR of the remaining component
val xor3 = tot xor xor1 xor nbrXOR
// Getting the minimum of the three values
val max = xor1.coerceAtLeast(nbrXOR.coerceAtLeast(xor3))
// Getting the maximum of the three value
val min = xor1.coerceAtMost(nbrXOR.coerceAtMost(xor3))
ans = ans.coerceAtMost(max - min)
// Including the neighbour subtree's XOR value in the XOR value of the subtree
// rooted at src node
myXOR = myXOR xor nbrXOR
}
}
// Returing the XOR value of the current subtree rooted at the src node
return myXOR
}
// function to travel 1st time on the tree and find the first edge to be removed and
// then block the node at which the edge ends to avoid selecting the same node again
private fun dfs(src: Int, graph: Array<ArrayList<Int>?>, arr: IntArray, par: Int, tot: Int): Int {
// Setting the value for the current subtree's XOR value
var myXOR = arr[src]
for (nbr in graph[src]!!) {
// If the current nbr is not the parent of this node, then only we'll proceed
if (nbr != par) {
// After selecting 'src <----> nbr' as the first edge, we block 'nbr' node and then
// make a call to try all the second edges
val nbrXOR = dfs(nbr, graph, arr, src, tot)
// Calling the helper to find the try all the second edges after blocking the
// current node
helper(0, graph, arr, -1, nbr, nbrXOR, tot)
// Including the neighbour subtree's XOR value in the XOR value of the subtree
// rooted at src node
myXOR = myXOR xor nbrXOR
}
}
// Returing the XOR value of the current subtree rooted at the src node
return myXOR
}
fun minimumScore(arr: IntArray, edges: Array<IntArray>): Int {
val n = arr.size
val graph: Array<ArrayList<Int>?> = arrayOfNulls(n)
var tot = 0
for (i in 0 until n) {
// Initializing the graph and finding the total XOR
graph[i] = ArrayList()
tot = tot xor arr[i]
}
for (edge in edges) {
// adding the edges
val u = edge[0]
val v = edge[1]
graph[u]!!.add(v)
graph[v]!!.add(u)
}
ans = Int.MAX_VALUE
dfs(0, graph, arr, -1, tot)
return ans
}
}
| 0
|
Kotlin
|
20
| 43
|
e8b08d4a512f037e40e358b078c0a091e691d88f
| 3,624
|
LeetCode-in-Kotlin
|
MIT License
|
app/src/main/java/com/softcross/onepiece/core/data/modal/Location.kt
|
ErenMlg
| 731,047,216
| false
|
{"Kotlin": 160094}
|
package com.softcross.onepiece.core.data.modal
data class Location(
val id:String,
val locationName:String,
val locationPictureURL:String
)
| 0
|
Kotlin
|
0
| 0
|
718dead7aa72a0798a23b441b969893ecba0e204
| 152
|
OnePieceAndroid
|
Apache License 2.0
|
code/app/src/main/java/com/tanfra/shopmob/smob/data/net/api/SmobShopApi.kt
|
fwornle
| 440,434,944
| false
| null |
package com.tanfra.shopmob.smob.data.net.api
import com.tanfra.shopmob.Constants
import com.tanfra.shopmob.smob.data.net.nto.SmobShopNTO
import retrofit2.Response
import retrofit2.http.*
/**
* Service interface (exposed by retrofit library) for "SmobShops".
*/
interface SmobShopApi {
// HTTP GET (fetch a specific shop)
@GET("${Constants.SMOB_API_URL}/shops/{id}")
suspend fun getSmobItemById(
@Path(value = "id", encoded = true) id: String
// @Query("q") searchText: String,
): Response<SmobShopNTO>
// HTTP GET (fetch all shops)
@GET("${Constants.SMOB_API_URL}/shops")
suspend fun getSmobItems(
// --> @Query annotation can be used to provide additional query parameters
// @Query("q") searchText: String,
): Response<ArrayList<SmobShopNTO>>
// HTTP POST (insert a new shop)
@Headers("Content-Type: application/json")
@POST("${Constants.SMOB_API_URL}/shops")
suspend fun saveSmobItem(
@Body newItem: SmobShopNTO?
): Response<Void>
// HTTP PUT (update a specific shop)
@Headers("Content-Type: application/json")
@PUT("${Constants.SMOB_API_URL}/shops/{id}")
suspend fun updateSmobItemById(
@Path(value = "id", encoded = true) id: String,
@Body newItem: SmobShopNTO?
): Response<Void>
// HTTP DELETE (delete a specific shop)
@Headers("Content-Type: application/json")
@DELETE("${Constants.SMOB_API_URL}/shops/{id}")
suspend fun deleteSmobItemById(
@Path(value = "id", encoded = true) id: String,
): Response<Void>
}
| 0
|
Kotlin
|
0
| 0
|
3dd02cae7a45ab2febb9c492c41d96b9db52fdee
| 1,738
|
ShopMob
|
MIT License
|
src/main/kotlin/com/intellij/ideolog/largeFile/LargeLogFileRegexSearchNotificationProvider.kt
|
JetBrains
| 93,527,718
| false
|
{"Kotlin": 199682, "HTML": 1378}
|
package com.intellij.ideolog.largeFile
import com.intellij.largeFilesEditor.editor.LargeFileRegexSearchNotificationProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationProvider
class LargeLogFileRegexSearchNotificationProvider(
private val delegate: LargeFileRegexSearchNotificationProvider = LargeFileRegexSearchNotificationProvider()
) : EditorNotificationProvider {
override fun collectNotificationData(
project: Project, file: VirtualFile
) = delegate.collectNotificationData(project, file)
}
| 76
|
Kotlin
|
53
| 251
|
d43133fcf1a5608a7c97622ef86111208bd02c49
| 594
|
ideolog
|
MIT License
|
src/main/kotlin/com/zhangke/activitypub/api/PagingLinkInfo.kt
|
0xZhangKe
| 594,285,909
| false
|
{"Kotlin": 87574}
|
package com.zhangke.activitypub.api
data class PagingLinkInfo(
val preUrl: String?,
val preSinceId: String?,
val nextUrl: String?,
val nextMaxId: String?,
){
companion object{
val EMPTY = PagingLinkInfo(null, null, null, null)
}
}
data class PagingResult<T>(
val pagingInfo: PagingLinkInfo,
val data: T,
)
| 0
|
Kotlin
|
0
| 3
|
20df23caa5dca3594abdff8f9cdf388296a78090
| 350
|
ActivityPub-Kotlin
|
Apache License 2.0
|
app/src/main/java/com/ae/apps/messagecounter/data/business/MessagesTableConstants.kt
|
midhunhk
| 9,828,089
| false
|
{"Kotlin": 148066, "Shell": 1219}
|
/*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ae.apps.messagecounter.data.business
import android.annotation.SuppressLint
import android.database.Cursor
import com.ae.apps.messagecounter.data.models.Message
import com.ae.apps.messagecounter.data.repositories.getMessageCount
const val COLUMN_NAME_PROTOCOL = "protocol"
const val COLUMN_NAME_ID = "_id"
const val COLUMN_NAME_DATE = "date"
const val COLUMN_NAME_PERSON = "person"
const val COLUMN_NAME_BODY = "body"
const val COLUMN_NAME_ADDRESS = "address"
val SMS_TABLE_PROJECTION = arrayOf(COLUMN_NAME_ID,
COLUMN_NAME_DATE,
COLUMN_NAME_PERSON,
COLUMN_NAME_BODY,
COLUMN_NAME_PROTOCOL,
COLUMN_NAME_ADDRESS)
val SMS_TABLE_MINIMAL_PROJECTION = arrayOf(COLUMN_NAME_ID,
COLUMN_NAME_ADDRESS,
COLUMN_NAME_PERSON)
val SMS_TABLE_ALL_PROJECTION = arrayOf(
COLUMN_NAME_ID,
COLUMN_NAME_DATE,
COLUMN_NAME_PERSON,
COLUMN_NAME_BODY,
COLUMN_NAME_PROTOCOL,
COLUMN_NAME_ADDRESS)
const val SELECT_SENT_MESSAGES_AFTER_DATE = "person is null and protocol is null and $COLUMN_NAME_DATE > ? "
const val SELECT_SENT_MESSAGES_AFTER_LAST = "and _id > ?"
const val SORT_BY_DATE = "$COLUMN_NAME_DATE ASC"
const val DEFAULT_MESSAGE_COUNT = 1
const val DEFAULT_INDEX_TIME_STAMP = "0"
@SuppressLint("Range")
fun getMessageFromCursor(cursor: Cursor): Message {
val messageId = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ID))
val protocol = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_PROTOCOL))
val sentTime = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE))
val body = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_BODY))
val address = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ADDRESS))
// Calculate the messages count for multipart messages
val messagesCount = try {
getMessageCount(body)
} catch (e: Exception) {
// Skip any exceptions and use default value
DEFAULT_MESSAGE_COUNT
}
return Message(messageId, messagesCount, body, sentTime, protocol, address)
}
@SuppressLint("Range")
fun getMessageForBackupFromCursor(cursor: Cursor): Message {
val messageId = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ID))
val address = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ADDRESS))
// person is null when they are not in the address book, eg: OTPs, Financial institutions etc
val person = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_PERSON))?: ""
val protocol = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_PROTOCOL))
val sentTime = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE))
val body = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_BODY))
return Message(messageId, 0, body, sentTime, protocol, address, person)
}
| 0
|
Kotlin
|
10
| 21
|
9319d166daa609813688f2ee891fd4558f377494
| 3,378
|
message-counter
|
Apache License 2.0
|
app/src/main/java/com/one/kumaran/restpokemon/injection/RestModule.kt
|
bellank
| 145,264,830
| false
| null |
package com.one.kumaran.restpokemon.injection
import android.content.Context
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.one.kumaran.restpokemon.repository.network.ApiInterface
import dagger.Module
import dagger.Provides
import io.reactivex.schedulers.Schedulers
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
class RestModule(val baseUrl: String, val context: Context) {
@Provides
@Singleton
fun providesGson(): Gson {
return GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
}
@Provides
@Singleton
fun providesCache(): Cache {
return Cache(context.cacheDir, 10 * 1024 * 1024L)
}
@Provides
@Singleton
fun providesOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
}
@Provides
@Singleton
fun providesRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.baseUrl(baseUrl)
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun providesApiInterface(retrofit: Retrofit): ApiInterface {
return retrofit.create(ApiInterface::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
37254090da661e4cd897e5cb0c4de77295e46e0e
| 1,875
|
restpokemon
|
Apache License 2.0
|
src/main/kotlin/com/devstromo/behavioral/cor/handler/CorHandlerMain.kt
|
devstromo
| 726,667,072
| false
|
{"Kotlin": 39963}
|
package com.devstromo.behavioral.cor.handler
fun main() {
val handlerA = ConcreteHandlerA()
val handlerB = ConcreteHandlerB()
handlerA.setNext(handlerB)
arrayOf("A", "B", "C").forEach { request ->
handlerA.handle(request)
}
}
| 0
|
Kotlin
|
0
| 0
|
d8aedda55940a22cca26ce71c008b13b2a2d9fa7
| 256
|
design-patterns-kotlin
|
MIT License
|
samples/packages/asset-export-basic/src/main/kotlin/AssetExportBasicCfg.kt
|
Aryamanz29
| 734,240,005
| false
|
{"Markdown": 2, "Batchfile": 1, "Shell": 1, "Gradle Kotlin DSL": 30, "Java Properties": 1, "Dockerfile": 2, "Java": 1046, "Kotlin": 217, "INI": 1}
|
/* SPDX-License-Identifier: Apache-2.0
Copyright 2023 Atlan Pte. Ltd. */
import com.atlan.pkg.CustomConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonProperty
import javax.annotation.processing.Generated
/**
* Expected configuration for the Asset Export (Basic) custom package.
*/
@Generated("com.atlan.pkg.CustomPackage")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
data class AssetExportBasicCfg(
@JsonProperty("export_scope") val exportScope: String? = null,
@JsonProperty("qn_prefix") val qnPrefix: String? = null,
@JsonProperty("include_description") val includeDescription: Boolean? = null,
@JsonProperty("include_glossaries") val includeGlossaries: Boolean? = null,
@JsonProperty("asset_types_to_include") val assetTypesToInclude: String? = null,
@JsonProperty("attributes_to_include") val attributesToInclude: String? = null,
@JsonProperty("email_addresses") val emailAddresses: String? = null,
) : CustomConfig()
| 1
| null |
1
| 1
|
0234b6506266c3c946040e5d89431063633edf49
| 1,033
|
atlan-java
|
Creative Commons Attribution 4.0 International
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/evmfee/legacy/LegacyFeeSettingsViewModel.kt
|
horizontalsystems
| 142,825,178
| false
| null |
package io.horizontalsystems.bankwallet.modules.evmfee.legacy
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.Warning
import io.horizontalsystems.bankwallet.core.ethereum.CautionViewItem
import io.horizontalsystems.bankwallet.core.ethereum.CautionViewItemFactory
import io.horizontalsystems.bankwallet.core.ethereum.EvmCoinService
import io.horizontalsystems.bankwallet.core.feePriceScale
import io.horizontalsystems.bankwallet.core.providers.Translator
import io.horizontalsystems.bankwallet.core.subscribeIO
import io.horizontalsystems.bankwallet.entities.DataState
import io.horizontalsystems.bankwallet.entities.ViewState
import io.horizontalsystems.bankwallet.modules.evmfee.*
import io.reactivex.disposables.CompositeDisposable
class LegacyFeeSettingsViewModel(
private val gasPriceService: LegacyGasPriceService,
private val feeService: IEvmFeeService,
private val coinService: EvmCoinService,
private val cautionViewItemFactory: CautionViewItemFactory
) : ViewModel() {
private val disposable = CompositeDisposable()
val sliderViewItemLiveData = MutableLiveData<SliderViewItem>()
val feeViewItemLiveData = MutableLiveData<FeeViewItem>()
val feeViewItemStateLiveData = MutableLiveData<ViewState>()
val feeViewItemLoadingLiveData = MutableLiveData<Boolean>()
val cautionsLiveData = MutableLiveData<List<CautionViewItem>>()
val isRecommendedGasPriceSelected by gasPriceService::isRecommendedGasPriceSelected
init {
sync(gasPriceService.state)
gasPriceService.stateObservable
.subscribeIO {
sync(it)
}.let {
disposable.add(it)
}
syncTransactionStatus(feeService.transactionStatus)
feeService.transactionStatusObservable
.subscribe { transactionStatus ->
syncTransactionStatus(transactionStatus)
}
.let {
disposable.add(it)
}
}
fun onSelectGasPrice(gasPrice: Long) {
gasPriceService.setGasPrice(gasPrice)
}
fun onClickReset() {
gasPriceService.setRecommended()
}
private fun syncTransactionStatus(transactionStatus: DataState<Transaction>) {
syncFeeViewItems(transactionStatus)
syncCautions(transactionStatus)
}
private fun syncFeeViewItems(transactionStatus: DataState<Transaction>) {
when (transactionStatus) {
DataState.Loading -> {
feeViewItemLoadingLiveData.postValue(true)
}
is DataState.Error -> {
feeViewItemLoadingLiveData.postValue(false)
feeViewItemStateLiveData.postValue(ViewState.Error(transactionStatus.error))
val notAvailable = Translator.getString(R.string.NotAvailable)
feeViewItemLiveData.postValue(FeeViewItem(notAvailable, notAvailable))
}
is DataState.Success -> {
val transaction = transactionStatus.data
feeViewItemLoadingLiveData.postValue(false)
val viewState = transaction.errors.firstOrNull()?.let { ViewState.Error(it) } ?: ViewState.Success
feeViewItemStateLiveData.postValue(viewState)
val fee = coinService.amountData(transactionStatus.data.gasData.fee).getFormatted()
val gasLimit = App.numberFormatter.format(transactionStatus.data.gasData.gasLimit.toBigDecimal(), 0, 0)
feeViewItemLiveData.postValue(FeeViewItem(fee, gasLimit))
}
}
}
private fun syncCautions(transactionStatus: DataState<Transaction>) {
val warnings = mutableListOf<Warning>()
val errors = mutableListOf<Throwable>()
if (transactionStatus is DataState.Error) {
errors.add(transactionStatus.error)
} else if (transactionStatus is DataState.Success) {
warnings.addAll(transactionStatus.data.warnings)
errors.addAll(transactionStatus.data.errors)
}
cautionsLiveData.postValue(cautionViewItemFactory.cautionViewItems(warnings, errors))
}
private fun sync(state: DataState<GasPriceInfo>) {
if (state is DataState.Success) {
sliderViewItemLiveData.postValue(
SliderViewItem(
initialWeiValue = state.data.gasPrice.max,
weiRange = gasPriceService.gasPriceRange
?: gasPriceService.defaultGasPriceRange,
stepSize = EvmFeeModule.stepSize(
gasPriceService.recommendedGasPrice
?: gasPriceService.defaultGasPriceRange.first
),
scale = coinService.token.blockchainType.feePriceScale
)
)
}
}
}
| 131
| null |
288
| 551
|
c48fdb4463a1245418edd0ace4d1e7d029bc4d70
| 4,990
|
unstoppable-wallet-android
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/leaguebot/hardware/LeagueFoundationGrabber.kt
|
CookedPelvis
| 278,513,219
| false
|
{"Gradle": 8, "Shell": 1, "Markdown": 8, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "HTML": 386, "JavaScript": 1, "CSS": 1, "Text": 5, "XML": 22, "AIDL": 1, "Java": 189, "INI": 1, "Kotlin": 66}
|
package org.firstinspires.ftc.teamcode.leaguebot.hardware
import com.acmerobotics.dashboard.config.Config
import com.qualcomm.robotcore.util.ElapsedTime
import org.firstinspires.ftc.teamcode.bulkLib.RevHubServo
import org.firstinspires.ftc.teamcode.opmodeLib.Globals
@Config
class LeagueFoundationGrabber {
private val leftServo = RevHubServo("rightFoundation")
private val rightServo = RevHubServo("leftFoundation")
private val upTimer = ElapsedTime()
private val actingTimer = ElapsedTime()
val clearsClaw get() = upTimer.seconds() > 0.8
private val clawCleared get() = actingTimer.seconds() > 0.25
enum class State(val leftPos: () -> Double, val rightPos: () -> Double) {
up({ lUp }, { rUp }),
down({ lDown }, { rDown }),
prep({ lPrep }, { rPrep })
}
var state = State.up
fun grab() {
state = State.down
}
fun release() {
state = State.up
}
fun prepForGrab() {
state = State.prep
}
fun update() {
if (state == State.up)
actingTimer.reset()
else
upTimer.reset()
val state = if (clawCleared) state else State.up
val l = state.leftPos()
val r = state.rightPos()
if (Globals.mode.movementAllowed) {
leftServo.position = l
rightServo.position = r
}
}
companion object {
@JvmField
var lDown = 0.1
@JvmField
var rDown = 0.77
@JvmField
var lUp = 1.0
@JvmField
var rUp = 0.0
@JvmField
var lPrep = 0.18
@JvmField
var rPrep = 0.68
}
}
| 1
| null |
1
| 1
|
5d018bdf2803511eeff947b2118956ec4bfd8f4a
| 1,664
|
SkystoneApp
|
MIT License
|
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/MediaUploadStatus.kt
|
oapicf
| 489,369,143
| false
|
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
|
package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
* Media upload status
* Values: registered,processing,succeeded,failed
*/
enum class MediaUploadStatus(val value: kotlin.String) {
@JsonProperty("registered") registered("registered"),
@JsonProperty("processing") processing("processing"),
@JsonProperty("succeeded") succeeded("succeeded"),
@JsonProperty("failed") failed("failed")
}
| 0
|
Java
|
0
| 2
|
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
| 941
|
pinterest-sdk
|
MIT License
|
surveys/src/main/kotlin/com/krake/surveys/model/Answer.kt
|
LaserSrl
| 165,023,586
| false
|
{"Gradle": 23, "Text": 3, "INI": 20, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "XML": 512, "JSON": 4, "Java": 163, "Kotlin": 393, "Proguard": 2, "Groovy": 2}
|
package com.krake.surveys.model
import com.krake.core.media.MediaPartURLWrapper
import com.krake.core.model.MediaPart
import com.krake.core.model.RecordWithIdentifier
/**
* Created by joel on 08/03/17.
*/
interface Answer : RecordWithIdentifier, AllFileImage {
val answer: String?
val correctResponse: Boolean
val position: Long?
val published: Boolean
}
interface AllFileImage {
val allFiles: String? get() = null
val image: MediaPart? get() {
if (allFiles.isNullOrEmpty())
return null
else
return MediaPartURLWrapper(allFiles!!)
}
}
| 1
| null |
1
| 1
|
51b97524ff72273227d029faf06acbef0f2699f8
| 612
|
KrakeAndroid
|
Apache License 2.0
|
xmlschema/src/commonMain/kotlin/io/github/pdvrieze/formats/xmlschema/datatypes/serialization/ParseQName.kt
|
pdvrieze
| 143,553,364
| false
|
{"Kotlin": 3481762}
|
/*
* Copyright (c) 2023.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.formats.xmlschema.datatypes.serialization
import kotlinx.serialization.SerializationException
import nl.adaptivity.xmlutil.QName
import nl.adaptivity.xmlutil.serialization.XML
internal fun parseQName(d: XML.XmlInput?, str: String): QName {
val cIdx = str.lastIndexOf(':')
if (d==null) {
if (cIdx<0) return QName(str)
val localName = if(cIdx<0) str else str.substring(cIdx+1)
if (str[0]!='{') throw SerializationException("Missing { before namespace")
val clIdx = str.indexOf('}', 1)
if (clIdx<1) throw SerializationException("Missing } after namespace")
val namespace = str.substring(1, clIdx)
val prefix = str.substring(clIdx+1, cIdx)
return QName(namespace, localName, prefix)
} else {
val localName: String
val prefix: String
if(cIdx<0) {
localName = str
prefix = ""
} else {
localName = str.substring(cIdx+1)
prefix = str.substring(0, cIdx)
}
val namespace = d.getNamespaceURI(prefix) ?: ""
return QName(namespace, localName, prefix)
}
}
| 35
|
Kotlin
|
31
| 378
|
c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79
| 1,899
|
xmlutil
|
Apache License 2.0
|
app/src/main/java/cz/muni/moviewishlist/database/DbHandler.kt
|
tomas-jezek
| 183,380,438
| false
| null |
package cz.muni.moviewishlist.database
import android.content.ContentValues
import android.content.Context
import android.database.DatabaseUtils
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import cz.muni.moviewishlist.R
import cz.muni.moviewishlist.categories.Category
import cz.muni.moviewishlist.movies.MovieItem
class DbHandler(private val context: Context) : SQLiteOpenHelper(
context,
DATABASE_NAME, null,
DB_VERSION
) {
override fun onCreate(db: SQLiteDatabase) {
val createToDoTable = "CREATE TABLE $TABLE_CATEGORY (" +
"$COL_ID integer PRIMARY KEY AUTOINCREMENT," +
"$COL_CATEGORY_CREATED_AT datetime DEFAULT CURRENT_TIMESTAMP," +
"$COL_CATEGORY_NAME varchar);"
val createToDoItemTable = "CREATE TABLE $TABLE_MOVIE_ITEM (" +
"$COL_ID integer PRIMARY KEY AUTOINCREMENT," +
"$COL_MOVIE_ITEM_CATEGORY_ID integer," +
"$COL_MOVIE_ITEM_CREATED_AT datetime DEFAULT CURRENT_TIMESTAMP," +
"$COL_MOVIE_ITEM_NAME varchar," +
"$COL_MOVIE_ITEM_WATCHED boolean," +
"$COL_MOVIE_ITEM_ORDER integer);"
db.execSQL(createToDoTable)
db.execSQL(createToDoItemTable)
// Add two default categories
val movieCategory = ContentValues()
movieCategory.put(COL_CATEGORY_NAME, context.getString(R.string.category_movies))
val seriesCategory = ContentValues()
seriesCategory.put(COL_CATEGORY_NAME, context.getString(R.string.category_series))
db.insert(TABLE_CATEGORY, null, movieCategory)
db.insert(TABLE_CATEGORY, null, seriesCategory)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
// TODO: Migrations
}
/**
* Adds a [Category] entry to the database or updates an existing one.
*/
fun addOrUpdateCategory(category: Category) {
val db = writableDatabase
val cv = ContentValues()
cv.put(COL_CATEGORY_NAME, category.name)
if (category.id != -1L) cv.put(COL_ID, category.id)
val id = db.insertWithOnConflict(TABLE_CATEGORY, null, cv, SQLiteDatabase.CONFLICT_IGNORE)
if (id == -1L) {
db.update(TABLE_CATEGORY, cv, "$COL_ID = ?", arrayOf(category.id.toString()))
}
}
/**
* Adds a [MovieItem] entry to the database.
*/
fun addOrUpdateMovieItem(movie: MovieItem) {
val db = writableDatabase
val cv = ContentValues()
cv.put(COL_MOVIE_ITEM_NAME, movie.itemName)
cv.put(COL_MOVIE_ITEM_CATEGORY_ID, movie.categoryId)
cv.put(COL_MOVIE_ITEM_WATCHED, movie.watched)
if (movie.id != -1L) {
// Update
cv.put(COL_ID, movie.id)
cv.put(COL_MOVIE_ITEM_ORDER, movie.order)
} else {
// Add
val totalCountInCategory = DatabaseUtils.queryNumEntries(db, TABLE_MOVIE_ITEM,
"$COL_MOVIE_ITEM_CATEGORY_ID = ?", arrayOf(movie.categoryId.toString()))
cv.put(COL_MOVIE_ITEM_ORDER, totalCountInCategory + 1)
}
val id = db.insertWithOnConflict(TABLE_MOVIE_ITEM, null, cv, SQLiteDatabase.CONFLICT_IGNORE)
if (id == -1L) {
db.update(TABLE_MOVIE_ITEM, cv, "$COL_ID = ?", arrayOf(movie.id.toString()))
}
}
/**
* Retrieves a collection of [Category] from the database
*/
fun getCategories(): MutableList<Category> {
val db = readableDatabase
return db.use { database ->
val result: MutableList<Category> = ArrayList()
val queryResult = database.rawQuery("SELECT * FROM $TABLE_CATEGORY", null)
if (queryResult.moveToFirst()) {
queryResult.use {
do {
val id = queryResult.getLong(queryResult.getColumnIndex(COL_ID))
val name = queryResult.getString(queryResult.getColumnIndex(COL_CATEGORY_NAME))
val category = Category(name)
category.id = id
result.add(category)
} while (queryResult.moveToNext())
}
}
return@use result
}
}
fun getMovieItems(categoryId: Long): MutableList<MovieItem> {
val db = readableDatabase
return db.use { database ->
val result: MutableList<MovieItem> = ArrayList()
val queryResult = database.rawQuery(
"SELECT * FROM $TABLE_MOVIE_ITEM WHERE $COL_MOVIE_ITEM_CATEGORY_ID = ?",
arrayOf(categoryId.toString())
)
if (queryResult.moveToFirst()) {
queryResult.use {
do {
val id = queryResult.getLong(queryResult.getColumnIndex(COL_ID))
val name = queryResult.getString(queryResult.getColumnIndex(COL_MOVIE_ITEM_NAME))
val watched = queryResult.getInt(queryResult.getColumnIndex(COL_MOVIE_ITEM_WATCHED)) == 1 // boolean
val order = queryResult.getLong(queryResult.getColumnIndex(COL_MOVIE_ITEM_ORDER))
val movie = MovieItem(categoryId, name, watched)
movie.id = id
movie.order = order
result.add(movie)
} while (queryResult.moveToNext())
}
}
result.sortBy { it.order }
return@use result
}
}
fun deleteCategory(categoryId: Long) {
val db = writableDatabase
// Delete with all its children
db.delete(TABLE_MOVIE_ITEM, "$COL_MOVIE_ITEM_CATEGORY_ID = ?", arrayOf(categoryId.toString()))
db.delete(TABLE_CATEGORY, "$COL_ID = ?", arrayOf(categoryId.toString()))
}
fun deleteMovieItem(itemId: Long) {
val db = writableDatabase
db.delete(TABLE_MOVIE_ITEM, "$COL_ID = ?", arrayOf(itemId.toString()))
}
fun watchMovieItem(categoryId: Long, watched: Boolean) {
val db = writableDatabase
val queryResult = db.rawQuery(
"SELECT * FROM $TABLE_MOVIE_ITEM WHERE $COL_MOVIE_ITEM_CATEGORY_ID = ?",
arrayOf(categoryId.toString())
)
if (queryResult.moveToFirst()) {
queryResult.use {
do {
val id = queryResult.getLong(queryResult.getColumnIndex(COL_ID))
val name = queryResult.getString(queryResult.getColumnIndex(COL_MOVIE_ITEM_NAME))
val movie = MovieItem(categoryId, name, watched)
movie.id = id
addOrUpdateMovieItem(movie)
} while (queryResult.moveToNext())
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
29b380ef347b581e5cc5becda4e5e2dce4851cd1
| 6,887
|
MovieWishlist
|
The Unlicense
|
app/src/main/java/com/sanjay/constraintlayoutanimation/LoginRegisterActivity.kt
|
sanjay4one
| 222,292,761
| false
| null |
package com.sanjay.constraintlayoutanimation
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.transition.TransitionManager
import android.view.View
import androidx.constraintlayout.widget.ConstraintSet
import kotlinx.android.synthetic.main.activity_register.*
class LoginRegisterActivity : AppCompatActivity(), View.OnClickListener {
private var loginConstraintSet = ConstraintSet()
private var fadeConstraintSet = ConstraintSet()
private var registerConstraintSet = ConstraintSet()
private var isLoginView = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
changeConstraintsForLogin()
}
private fun changeConstraintsForLogin() {
loginConstraintSet.clone(parentConstraintLayout)
registerConstraintSet.clone(parentConstraintLayout)
loginConstraintSet.setVisibility(R.id.editTextName, ConstraintSet.GONE)
loginConstraintSet.setVisibility(R.id.editTextCompany, ConstraintSet.GONE)
loginConstraintSet.setVisibility(R.id.editTextMobile, ConstraintSet.GONE)
button.text = getString(R.string.login)
textViewLogin.text = getString(R.string.register)
loginConstraintSet.applyTo(parentConstraintLayout)
fadeConstraintSet.clone(loginConstraintSet)
fadeConstraintSet.setVisibility(R.id.editTextEmail, ConstraintSet.GONE)
fadeConstraintSet.setVisibility(R.id.editTextPassword, ConstraintSet.GONE)
fadeConstraintSet.setVisibility(R.id.button, ConstraintSet.GONE)
fadeConstraintSet.setVisibility(R.id.textViewLogin, ConstraintSet.GONE)
fadeConstraintSet.setVisibility(R.id.textViewHelp, ConstraintSet.GONE)
fadeConstraintSet.applyTo(parentConstraintLayout)
Handler().postDelayed({
TransitionManager.beginDelayedTransition(parentConstraintLayout)
loginConstraintSet.applyTo(parentConstraintLayout)
}, 500)
textViewLogin.setOnClickListener(this)
button.setOnClickListener(this)
}
override fun onClick(v: View?) {
if (v == textViewLogin) {
isLoginView = !isLoginView
TransitionManager.beginDelayedTransition(parentConstraintLayout)
if (isLoginView) {
button.text = getString(R.string.login)
textViewLogin.text = getString(R.string.register)
loginConstraintSet.applyTo(parentConstraintLayout)
} else {
button.text = getString(R.string.register)
textViewLogin.text = getString(R.string.login)
editTextPassword.setText("")
registerConstraintSet.applyTo(parentConstraintLayout)
}
} else {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
b2e05a8bd00c233564aca6af70c385d137e975ca
| 3,001
|
ConstraintLayoutAnimation
|
Apache License 2.0
|
ethereum-scan/src/main/kotlin/com/uuhnaut69/ethereumscan/repository/LastBlockRepository.kt
|
uuhnaut69
| 686,534,020
| false
| null |
package com.uuhnaut69.ethereumscan.repository
import com.uuhnaut69.ethereumscan.model.entity.LastBlockEntity
import org.springframework.data.r2dbc.repository.R2dbcRepository
import org.springframework.stereotype.Repository
import reactor.core.publisher.Mono
import java.util.UUID
/**
* cloud-native-microservices
*
* @author uuhnaut69
*
*/
@Repository
interface LastBlockRepository : R2dbcRepository<LastBlockEntity, UUID> {
fun findByChainId(chainId: Long): Mono<LastBlockEntity>
}
| 0
|
Kotlin
|
0
| 0
|
98fdf5621adbcfc80332105ac009d042ace65e58
| 496
|
cloud-native-microservices
|
MIT License
|
app/src/main/java/com/example/composeapplication/data/ProductList.kt
|
Lilytreasure
| 609,425,104
| false
| null |
package com.example.composeapplication.data
data class ProductList(
val id: Long,
val title: String,
val price: Double,
val description: String,
//val category: Category,
val image: String,
val rating: Rating
)
| 0
|
Kotlin
|
0
| 0
|
3830be02f8c74185c287a46f0f4a018153c13519
| 241
|
Compose-Application
|
Apache License 2.0
|
src/main/kotlin/io/github/tcrawford/versioning/internal/errors/InvalidOverrideVersionError.kt
|
tcrawford-figure
| 707,752,444
| false
|
{"Kotlin": 106204, "Shell": 4438}
|
package io.github.tcrawford.versioning.internal.errors
class InvalidOverrideVersionError(
invalidVersion: String,
) : Exception(
"Invalid override version provided: $invalidVersion",
)
| 0
|
Kotlin
|
0
| 0
|
9548b14e51884d2b319a2b31b528c2ab3c8f5d1c
| 202
|
git-aware-versioning-plugin
|
MIT License
|
ion-schema/src/main/kotlin/com/amazon/ionschema/writer/internal/constraints/PrecisionWriter.kt
|
amazon-ion
| 148,685,964
| false
|
{"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631}
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.ionschema.writer.internal.constraints
import com.amazon.ion.IonWriter
import com.amazon.ionschema.model.Constraint
import com.amazon.ionschema.model.ExperimentalIonSchemaModel
import com.amazon.ionschema.writer.internal.writeRange
@ExperimentalIonSchemaModel
internal object PrecisionWriter : ConstraintWriter {
override val supportedClasses = setOf(Constraint.Precision::class)
override fun IonWriter.write(c: Constraint) {
check(c is Constraint.Precision)
setFieldName("precision")
writeRange(c.range)
}
}
| 40
|
Kotlin
|
14
| 27
|
7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b
| 676
|
ion-schema-kotlin
|
Apache License 2.0
|
src/main/kotlin/me/bardy/gsonkt/gson.kt
|
BomBardyGamer
| 372,222,995
| false
| null |
/*
* This file is part of GsonKt, licensed under the MIT license.
*
* Copyright (C) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:JvmMultifileClass
@file:JvmName("GsonKt")
package me.bardy.gsonkt
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import java.io.Reader
/**
* Create a [TypeToken] object for the given reified type [T], which can be used to get generic type parameter
* information at runtime.
*
* @param T the type
* @return a [TypeToken] for the given type [T]
* @since 1.0
*/
public inline fun <reified T> typeOf(): TypeToken<T> = object : TypeToken<T>() {}
/**
* Get the corresponding registered [TypeAdapter] for the given type [T], throwing an
* [IllegalArgumentException] if there is no adapter registered for [T].
*
* @param T the type
* @return the registered [TypeAdapter] for the given type [T]
* @throws IllegalArgumentException if there is no adapter registered for the given type [T]
* @since 1.0
*/
public inline fun <reified T> Gson.getAdapter(): TypeAdapter<T> = getAdapter(typeOf<T>())
/**
* Get an alternate type adapter for the given type [T]. That is, one that is overridden by a [TypeAdapterFactory].
*
* See [Gson.getDelegateAdapter] for more information on how this actually works.
*
* @param T the type
* @param skipPast the factory that needs to be skipped while searching for a matching type
* @return the registered delegate [TypeAdapter] for the given type [T]
* @since 1.0
* @see Gson.getDelegateAdapter
*/
public inline fun <reified T> Gson.getDelegateAdapter(skipPast: TypeAdapterFactory): TypeAdapter<T> = getDelegateAdapter(skipPast, typeOf<T>())
/**
* Convert the given [src] object to a tree of [JsonElement]s.
*
* @param T the type
* @param src the instance of the given type [T] to convert to a [JsonElement] tree
* @return the converted [JsonElement] tree
* @since 1.0
* @see Gson.toJsonTree
*/
public inline fun <reified T> Gson.toJsonTree(src: Any): JsonElement = toJsonTree(src, typeOf<T>().type)
/**
* Convert the given [src] object to a JSON [String].
*
* @param T the type
* @param src the instance of the given type [T] to convert to a JSON [String]
* @return a JSON string
* @since 1.0
* @see Gson.toJson
*/
public inline fun <reified T> Gson.toJson(src: Any): String = toJson(src, typeOf<T>().type)
/**
* Write the given [src] object to the given [writer].
*
* @param T the type
* @param src the instance of the given type [T]
* @param writer the writer to write the JSON to
* @since 1.0
* @see Gson.toJson
*/
public inline fun <reified T> Gson.toJson(src: Any, writer: Appendable): Unit = toJson(src, typeOf<T>().type, writer)
/**
* Write the given [src] object to the given [writer].
*
* @param T the type
* @param src the instance of the given type [T]
* @param writer the writer to write the JSON to
* @since 1.0
* @see Gson.toJson
*/
public inline fun <reified T> Gson.toJson(src: Any, writer: JsonWriter): Unit = toJson(src, typeOf<T>().type, writer)
/**
* Convert the given [json] string to an object of the given type [T].
*
* @param T the type
* @param json the JSON string
* @return the JSON object of type [T]
* @since 1.0
* @see Gson.fromJson
*/
public inline fun <reified T> Gson.fromJson(json: String): T = fromJson(json, typeOf<T>().type)
/**
* Deserialize JSON from the given [json] reader.
*
* @param T the type
* @param json the reader to read from
* @return the JSON object of type [T]
* @since 1.0
* @see Gson.fromJson
*/
public inline fun <reified T> Gson.fromJson(json: Reader): T = fromJson(json, typeOf<T>().type)
/**
* Deserialize JSON from the given [reader].
*
* @param T the type
* @param reader the reader to read from
* @return the JSON object of type [T]
* @since 1.0
* @see Gson.fromJson
*/
public inline fun <reified T> Gson.fromJson(reader: JsonReader): T = fromJson(reader, typeOf<T>().type)
| 0
|
Kotlin
|
0
| 0
|
cb444bc98ccb3fffde054ed9e676202e8d971137
| 5,148
|
gson-kt
|
MIT License
|
protocol/kotlin/src/solarxr_protocol/rpc/SerialDevicePort.kt
|
SlimeVR
| 456,320,520
| false
|
{"Rust": 790111, "Java": 650829, "TypeScript": 507384, "C++": 434772, "Kotlin": 356034, "PowerShell": 959, "Shell": 910, "Nix": 587}
|
// automatically generated by the FlatBuffers compiler, do not modify
package solarxr_protocol.rpc
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
class SerialDevicePort : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : SerialDevicePort {
__init(_i, _bb)
return this
}
val port : String?
get() {
val o = __offset(4)
return if (o != 0) __string(o + bb_pos) else null
}
val portAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
fun portInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
companion object {
@JvmStatic
fun validateVersion() = Constants.FLATBUFFERS_22_10_26()
@JvmStatic
fun getRootAsSerialDevicePort(_bb: ByteBuffer): SerialDevicePort = getRootAsSerialDevicePort(_bb, SerialDevicePort())
@JvmStatic
fun getRootAsSerialDevicePort(_bb: ByteBuffer, obj: SerialDevicePort): SerialDevicePort {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
@JvmStatic
fun createSerialDevicePort(builder: FlatBufferBuilder, portOffset: Int) : Int {
builder.startTable(1)
addPort(builder, portOffset)
return endSerialDevicePort(builder)
}
@JvmStatic
fun startSerialDevicePort(builder: FlatBufferBuilder) = builder.startTable(1)
@JvmStatic
fun addPort(builder: FlatBufferBuilder, port: Int) = builder.addOffset(0, port, 0)
@JvmStatic
fun endSerialDevicePort(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 11
|
Rust
|
20
| 19
|
60f3146f914e2a9e35d759a8146be213e715d6d2
| 1,860
|
SolarXR-Protocol
|
Apache License 2.0
|
src/main/kotlin/no/nav/helseidnavtest/edi20/BusinessDokument.kt
|
navikt
| 754,033,318
| false
|
{"Kotlin": 174830, "HTML": 1340}
|
package no.nav.helseidnavtest.edi20
import com.fasterxml.jackson.annotation.JsonValue
import no.nav.helseidnavtest.dialogmelding.HerId
import no.nav.helseidnavtest.edi20.ApprecStatus.OK
import no.nav.helseidnavtest.edi20.PostMessageRequest.SystemInfo
import org.springframework.http.MediaType.APPLICATION_XML_VALUE
import java.time.LocalDateTime
import java.util.*
private const val APP_NAVN = "HelseIdNavTest"
private const val VERSJON = "1.0.0"
data class PostMessageRequest(
val businessDocument: String,
val contentTransferEncoding: String = "base64",
val contentType: String = APPLICATION_XML_VALUE,
val systemInfo: SystemInfo = SystemInfo(),
val ebxmlOverrides: EbxmlOverrides? = null) {
data class SystemInfo(
val applicationName: String = APP_NAVN,
val applicationVersion: String = VERSJON,
val middlewareName: String? = APP_NAVN,
val middlewareVersion: String? = VERSJON)
data class EbxmlOverrides(
val cpaId: String? = null,
val conversationId: String? = null,
val service: String? = null,
val serviceType: String? = null,
val action: String? = null,
val senderHerId: Int? = null,
val senderRole: String? = null,
val receiverHerId: Int? = null,
val receiverRole: String? = null)
override fun toString() =
"PostMessageRequest(businessDocument='${businessDocument.length}', contentTransferEncoding='$contentTransferEncoding', contentType='$contentType', systemInfo=$systemInfo, ebxmlOverrides=$ebxmlOverrides)"
}
data class Melding(val id: UUID,
val receiverHerId: List<HerId>,
val senderHerId: HerId?,
val businessDocumentId: UUID?,
val businessDocumentGenDate: LocalDateTime?,
val isAppRec: Boolean)
data class ApprecErrorDetail(val description: String, val errorCode: String? = null, val details: String? = null)
enum class ApprecStatus(@JsonValue val result: Int) {
OK(1),
ERROR(2),
DELFEIL(3)
}
data class ApprecRequest(
val appRecStatus: ApprecStatus = OK,
val appRecErrorList: List<ApprecErrorDetail> = emptyList(),
val systemInfo: SystemInfo = SystemInfo())
data class Status(
val herId: HerId,
val acknowledged: Boolean,
val appRecReceived: Boolean,
val appRecResult: ApprecStatus?,
val appRecErrorList: List<ApprecErrorDetail> = emptyList())
data class DeftStatus(val receiverDownloadStatus: Map<String, Boolean>)
| 1
|
Kotlin
|
0
| 0
|
efc0f80b59352555ab2bb5431e780f1bc7056f7f
| 2,527
|
helseid-nav-test
|
MIT License
|
src/main/kotlin/Day07.kt
|
nmx
| 572,850,616
| false
|
{"Kotlin": 18806}
|
fun main(args: Array<String>) {
val TOTAL_DISK_SPACE = 70000000
val UNUSED_SPACE_NEEDED = 30000000
abstract class Node(val name: String, var size: Int) {
abstract fun calcSize(): Int
abstract fun sumMatchingSizes(): Int
}
class File(name: String, size: Int): Node(name, size) {
override fun calcSize(): Int {
return size
}
override fun sumMatchingSizes(): Int {
return 0
}
}
class Dir(name: String, val parent: Dir?): Node(name, 0) {
val children = mutableMapOf<String, Node>()
override fun calcSize(): Int {
size = children.values.sumOf { it.calcSize() }
return size
}
override fun sumMatchingSizes(): Int {
return (if (size <= 100000) size else 0) + children.values.sumOf { it.sumMatchingSizes() }
}
fun findSmallestDirWithMinSize(minSize: Int): Dir? {
val me = if (size >= minSize) this else null
val descendantCandidates = children.values.mapNotNull {
if (it !is Dir) null else it.findSmallestDirWithMinSize(minSize)
}
return (listOfNotNull(me) + descendantCandidates).minWithOrNull(compareBy { it.size })
}
}
fun executeLine(cwd: Dir, lines: List<String>, startLineNum: Int): Pair<Dir, Int> {
var lineNum = startLineNum
val tokens = lines[lineNum++].split(" ")
if (tokens[0] != "$") {
throw Exception("Expected prompt, got ${tokens[0]}")
}
when (tokens[1]) {
"cd" -> {
val targetDir = tokens[2]
when (targetDir) {
"/" -> {
if (cwd.parent != null) {
throw Exception("unexpected cd to root after start")
}
// else ignore
}
".." -> {
return Pair(cwd.parent!!, lineNum)
}
else -> {
// assume "cd X" never precedes the ls output for its parent
return Pair(cwd.children.getValue(targetDir) as Dir, lineNum)
}
}
}
"ls" -> {
if (cwd.children.isNotEmpty()) {
throw Exception("already listed ${cwd.name}")
} else {
while (lineNum < lines.size
&& lines[lineNum].isNotEmpty()
&& !lines[lineNum].startsWith("$")
) {
val (dirOrSize, name) = lines[lineNum++].split(" ")
val child = if (dirOrSize == "dir") {
Dir(name, cwd)
} else {
File(name, dirOrSize.toInt())
}
if (cwd.children.containsKey(name))
throw Exception("$name already exists")
cwd.children[name] = child
}
}
return Pair(cwd, lineNum)
}
else -> {
throw Exception("bad token ${tokens[1]}")
}
}
return Pair(cwd, lineNum)
}
fun loadFileSystem(input: String): Dir {
val lines = input.split("\n")
val root = Dir("/", null)
var cwd = root
var lineNum = 0
while (lineNum < lines.size && lines[lineNum].isNotEmpty()) {
val res = executeLine(cwd, lines, lineNum)
cwd = res.first
lineNum = res.second
}
root.calcSize()
return root
}
fun part1(root: Dir) {
println("Part 1 sum of matching sizes: " + root.sumMatchingSizes())
}
fun part2(root: Dir) {
val freeSpace = TOTAL_DISK_SPACE - root.size
val spaceNeeded = UNUSED_SPACE_NEEDED - freeSpace
if (spaceNeeded <= 0) {
throw Exception("There's already enough free space")
}
println("Needed space: $spaceNeeded")
val toDelete = root.findSmallestDirWithMinSize(spaceNeeded)
println("Dir to delete: ${toDelete!!.name} ${toDelete!!.size}")
}
val input = object {}.javaClass.getResource("Day07.txt").readText()
val root = loadFileSystem(input)
part1(root)
part2(root)
}
| 0
|
Kotlin
|
0
| 0
|
33da2136649d08c32728fa7583ecb82cb1a39049
| 4,470
|
aoc2022
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsbookavideolinkapi/security/VideoBookingAccessKtTest.kt
|
ministryofjustice
| 789,053,149
| false
|
{"Kotlin": 1204892, "Shell": 11651, "Dockerfile": 1492}
|
package uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.security
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.UNKNOWN_COURT_CODE
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.UNKNOWN_PROBATION_TEAM_CODE
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.PRISON_USER_BIRMINGHAM
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.SERVICE_USER
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.court
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.courtBooking
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.courtUser
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.probationBooking
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.probationTeam
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.probationUser
class VideoBookingAccessKtTest {
@Test
fun `should fail booking check for court user accessing a probation booking`() {
assertThrows<VideoBookingAccessException> { checkVideoBookingAccess(courtUser(), probationBooking()) }
}
@Test
fun `should fail booking check for probation user accessing a court booking`() {
assertThrows<VideoBookingAccessException> { checkVideoBookingAccess(probationUser(), courtBooking()) }
}
@Test
fun `should fail booking check for court user accessing an unknown court booking`() {
assertThrows<VideoBookingAccessException> { checkVideoBookingAccess(courtUser(), courtBooking(court = court(code = UNKNOWN_COURT_CODE))) }
}
@Test
fun `should fail booking check for probation user accessing an unknown probation booking`() {
assertThrows<VideoBookingAccessException> { checkVideoBookingAccess(probationUser(), probationBooking(probationTeam = probationTeam(code = UNKNOWN_PROBATION_TEAM_CODE))) }
}
@Test
fun `should succeed booking check for court user accessing a court booking`() {
assertDoesNotThrow { checkVideoBookingAccess(courtUser(), courtBooking()) }
}
@Test
fun `should succeed booking check for probation user accessing a probation booking`() {
assertDoesNotThrow { checkVideoBookingAccess(probationUser(), probationBooking()) }
}
@Test
fun `should succeed booking check when user is not an external user`() {
assertDoesNotThrow { checkVideoBookingAccess(PRISON_USER_BIRMINGHAM, courtBooking()) }
assertDoesNotThrow { checkVideoBookingAccess(SERVICE_USER, courtBooking()) }
assertDoesNotThrow { checkVideoBookingAccess(PRISON_USER_BIRMINGHAM, probationBooking()) }
assertDoesNotThrow { checkVideoBookingAccess(SERVICE_USER, probationBooking()) }
}
}
| 2
|
Kotlin
|
0
| 0
|
32258306b78a8e0c974ea34c057b33569e9d4c1d
| 2,787
|
hmpps-book-a-video-link-api
|
MIT License
|
GoTrue/src/wasmJsMain/kotlin/io/github/jan/supabase/gotrue/RedirectUrl.kt
|
supabase-community
| 495,084,592
| false
|
{"Kotlin": 883057}
|
package io.github.jan.supabase.gotrue
import io.github.jan.supabase.annotations.SupabaseInternal
import kotlinx.browser.window
@SupabaseInternal
actual fun Auth.defaultPlatformRedirectUrl(): String? = window.location.origin
| 12
|
Kotlin
|
37
| 369
|
020ec03eef1efc94a80d97337e515df9338f3df0
| 225
|
supabase-kt
|
MIT License
|
main-course-project/src/main/kotlin/br/com/leuras/core/business/pipeline/impl/IncreaseSharesPipelineStep.kt
|
leuras
| 672,251,747
| false
| null |
package br.com.leuras.core.business.pipeline.impl
import br.com.leuras.core.business.pipeline.PipelineStep
import br.com.leuras.core.port.CustomerSharesDetailRepository
class IncreaseSharesPipelineStep(
private val walletRepository: CustomerSharesDetailRepository): PipelineStep {
override fun execute(input: Any): Any {
// val customerOrder = input as CustomerOrder
//
// return this.walletRepository.find(customerOrder.customer.customerId)
// ?.let { walletDetails ->
//
// val newStockShares = walletDetails.shares.firstOrNull { it.tickerSymbol == customerOrder.tickerSymbol }
// ?.let { stockShares -> stockShares + customerOrder }
// ?: CustomerSharesDetail(
// tickerSymbol = customerOrder.tickerSymbol,
// shares = customerOrder.quantity,
// averagePrice = customerOrder.unitPrice, // TODO: deduction of brokerage fee
// customerId = customerOrder.customerId,
// createdAt = LocalDateTime.now(),
// updatedAt = LocalDateTime.now()
// )
//
// this.walletRepository.update(newStockShares)
// customerOrder.copy(status = OrderStatus.REGISTERED)
//
// } ?: customerOrder.copy(status = OrderStatus.REJECTED)
TODO()
}
}
| 0
|
Kotlin
|
0
| 0
|
a781207b157a87e22b4ddfa58b87fba060ea5a87
| 1,453
|
kotlin-unit-testing-course
|
MIT License
|
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/SlideSearch.kt
|
Konyaco
| 574,321,009
| false
| null |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.SlideSearch: ImageVector
get() {
if (_slideSearch != null) {
return _slideSearch!!
}
_slideSearch = fluentIcon(name = "Filled.SlideSearch") {
fluentPath {
moveTo(2.0f, 6.75f)
arcTo(2.75f, 2.75f, 0.0f, false, true, 4.75f, 4.0f)
horizontalLineToRelative(14.5f)
arcTo(2.75f, 2.75f, 0.0f, false, true, 22.0f, 6.75f)
verticalLineToRelative(10.5f)
arcTo(2.75f, 2.75f, 0.0f, false, true, 19.25f, 20.0f)
horizontalLineToRelative(-6.78f)
lineToRelative(-2.04f, -2.05f)
curveToRelative(0.36f, -0.74f, 0.57f, -1.57f, 0.57f, -2.45f)
horizontalLineToRelative(4.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f)
horizontalLineToRelative(-4.46f)
arcToRelative(5.47f, 5.47f, 0.0f, false, false, -0.68f, -1.5f)
horizontalLineToRelative(7.14f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f)
lineTo(8.66f, 11.0f)
arcToRelative(5.48f, 5.48f, 0.0f, false, false, -6.66f, 0.26f)
lineTo(2.0f, 6.75f)
close()
moveTo(6.75f, 8.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f)
horizontalLineToRelative(6.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f)
horizontalLineToRelative(-6.5f)
close()
moveTo(5.5f, 20.0f)
curveToRelative(0.97f, 0.0f, 1.87f, -0.3f, 2.6f, -0.83f)
lineToRelative(2.62f, 2.61f)
arcToRelative(0.75f, 0.75f, 0.0f, true, false, 1.06f, -1.06f)
lineToRelative(-2.61f, -2.61f)
arcTo(4.5f, 4.5f, 0.0f, true, false, 5.5f, 20.0f)
close()
moveTo(5.5f, 18.5f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, 0.0f, -6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 0.0f, 6.0f)
close()
}
}
return _slideSearch!!
}
private var _slideSearch: ImageVector? = null
| 1
|
Kotlin
|
3
| 83
|
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 2,508
|
compose-fluent-ui
|
Apache License 2.0
|
common/src/main/java/com/topview/purejoy/common/mvvm/binding/CommonBindingAdapters.kt
|
giagor
| 421,858,760
| false
|
{"Kotlin": 800571, "AIDL": 3111}
|
package com.topview.purejoy.common.mvvm.binding
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
@BindingAdapter("commonLoadImg")
fun loadImg(iv: ImageView, url: String?) {
url?.let {
Glide.with(iv.context)
.load(it)
.apply(RequestOptions().override(iv.width, iv.height))
.into(iv)
}
}
| 1
|
Kotlin
|
1
| 5
|
f58ca9570486871066d99fc5e0827af66d6f0c3b
| 446
|
PureJoy
|
MIT License
|
app/src/main/java/ukponahiunsijeffery/example/asteroidraderapp/database/AsteroidDatabaseEntity.kt
|
deba-jeff
| 521,185,939
| false
| null |
package ukponahiunsijeffery.example.asteroidraderapp.database
import androidx.room.Entity
import androidx.room.PrimaryKey
import ukponahiunsijeffery.example.asteroidraderapp.domain.AsteroidDomain
@Entity(tableName = "asteroid_table")
data class AsteroidDatabaseEntity(
@PrimaryKey
var id: String,
var name: String,
var absoluteMagnitude: Double,
var estimatedDiameter: Double,
var isPotentiallyHazardous: Boolean,
var closeApproachDate: String,
var relativeVelocity: String,
var distanceFromEarth: String)
/**
* Converts an ArrayList of AsteroidDatabaseEntity to a List of AsteroidDomain
*/
fun List<AsteroidDatabaseEntity>.asDomainModel(): List<AsteroidDomain>{
return map {
AsteroidDomain(
id = it.id,
name = it.name,
absoluteMagnitude = it.absoluteMagnitude,
estimatedDiameter = it.estimatedDiameter,
isPotentiallyHazardous = it.isPotentiallyHazardous,
closeApproachDate = it.closeApproachDate,
relativeVelocity = it.relativeVelocity,
distanceFromEarth = it.distanceFromEarth
)
}
}
| 0
|
Kotlin
|
0
| 0
|
31ea67ea5c07028f6bd14863ae3da4b7a3a0aa4e
| 1,160
|
Asteroid-Rader-App
|
MIT License
|
app/src/main/java/com/github/jan222ik/gamification/ui/screens/RoundEvaluation.kt
|
jan222ik
| 453,740,147
| false
| null |
package com.github.jan222ik.gamification.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import com.github.jan222ik.gamification.ui.components.SingeRoundEval
import com.github.jan222ik.gamification.ui.logic.Game
import com.google.accompanist.pager.ExperimentalPagerApi
@OptIn(ExperimentalPagerApi::class)
@Composable
fun ColumnScope.RoundEvaluation(game: Game) {
Row(
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = { game.endGame() }
) {
Text(text = "Historie und Spielende")
}
}
game.historyPerRound[game.round]?.let {
SingeRoundEval(roundHistory = it, nextRound = { game.nextRound() })
}
}
| 0
|
Kotlin
|
0
| 0
|
073f387a9f23af97acda3b7a299081aa0187968d
| 945
|
MSc-S3-FAS-KON-Gamification
|
MIT License
|
app/src/main/java/com/example/quizapp/MainActivity.kt
|
budifauzan
| 535,572,654
| false
| null |
package com.example.quizapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private var edtName: EditText? = null
private var btnStart: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeView()
setOnClick()
}
private fun initializeView() {
edtName = findViewById(R.id.edt_activity_main_name)
btnStart = findViewById(R.id.btn_activity_main_start)
}
private fun setOnClick() {
btnStart?.setOnClickListener {
if (edtName?.text.toString().isEmpty()) {
Toast.makeText(this, "Please enter your name!", Toast.LENGTH_SHORT).show()
} else {
val intent = Intent(this, QuizQuestionsActivity::class.java)
intent.putExtra(Constants.USER_NAME, edtName?.text.toString())
startActivity(intent)
finish()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d51f7dd6384f3fbb65933b6dbacbaca2f00bac8e
| 1,198
|
QuizApp
|
MIT License
|
GcbApplication/module_store/src/main/java/com/gocashback/module_store/adapter/CashBackCateAdapter.kt
|
ybx945ybx
| 247,870,704
| false
| null |
package com.gocashback.module_store.adapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gocashback.lib_common.network.model.store.StoreDetailSpecialItemModel
import com.gocashback.module_store.R
/**
* @Author 55HAITAO
* @Date 2019-06-18 14:33
*/
class CashBackCateAdapter(list: List<StoreDetailSpecialItemModel>) : BaseQuickAdapter<StoreDetailSpecialItemModel, BaseViewHolder>(R.layout.item_cash_back_categories, list) {
override fun convert(helper: BaseViewHolder, item: StoreDetailSpecialItemModel) {
with(item) {
helper.setText(R.id.tv_cate, cate_name)
.setText(R.id.tv_cate_value, cate_rebate)
.setVisible(R.id.iv_line, helper.layoutPosition != data.size - 1)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0da5ca3b1dddcb8907d5bcc062722b4ad3ac3546
| 823
|
gcb
|
Apache License 2.0
|
android/src/oldarch/OverscrollViewManagerSpec.kt
|
Hao-yiwen
| 876,671,086
| false
|
{"Kotlin": 6040, "TypeScript": 2437, "JavaScript": 1743, "Ruby": 295, "C": 103, "Swift": 62}
|
package com.overscroll
import android.view.ViewGroup
import com.facebook.react.uimanager.ViewGroupManager
abstract class OverscrollViewManagerSpec<T : ViewGroup> : ViewGroupManager<T>() {
abstract fun setBounce(view: T?, value: Boolean)
}
| 0
|
Kotlin
|
0
| 1
|
1682d20ff8f59f5e9625ddb423319e6ae826f684
| 243
|
react-native-overscroll2
|
MIT License
|
src/main/java/ir/firoozehcorp/gameservice/core/gslive/GSLiveChat.kt
|
AR-Ghodrati
| 246,913,293
| false
| null |
/*
* <copyright file="GSLiveChat.kt" company="Firoozeh Technology LTD">
* Copyright (C) 2020. Firoozeh Technology LTD. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
* </copyright>
*/
package ir.firoozehcorp.gameservice.core.gslive
import ir.firoozehcorp.gameservice.core.GameService
import ir.firoozehcorp.gameservice.handlers.command.request.chat.*
import ir.firoozehcorp.gameservice.models.GameServiceException
import ir.firoozehcorp.gameservice.models.annotations.NotNull
import ir.firoozehcorp.gameservice.models.gsLive.command.RoomDetail
/**
* Represents Game Service Chat System
* @author Alireza Ghodrati
*/
object GSLiveChat {
/**
* Subscribe In Channel With channelName.
* @param channelName Name of Channel You want To Subscribe
*/
@Throws(GameServiceException::class)
fun subscribeChannel(@NotNull channelName: String) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (channelName.isEmpty()) throw GameServiceException("channelName Cant Be EmptyOrNull")
GSLive.handler.commandHandler.request(SubscribeChannelHandler.signature, channelName)
}
/**
* UnSubscribeChannel With channelName.
* @param channelName Name of Channel You want To UnSubscribe
*/
@Throws(GameServiceException::class)
fun unSubscribeChannel(@NotNull channelName: String) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (channelName.isEmpty()) throw GameServiceException("channelName Cant Be EmptyOrNull")
GSLive.handler.commandHandler.request(UnSubscribeChannelHandler.signature, channelName)
}
/**
* Send Message In SubscribedChannel.
* @param channelName Name of Channel You want To Send Message
* @param message Message Data
*/
@Throws(GameServiceException::class)
fun sendChannelMessage(@NotNull channelName: String, @NotNull message: String) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (channelName.isEmpty() && message.isEmpty()) throw GameServiceException("channelName Or message Cant Be EmptyOrNull")
GSLive.handler.commandHandler.request(SendChannelMessageHandler.signature, Pair(channelName, message))
}
/**
* Send Message In SubscribedChannel.
* @param memberId ID of Member You want To Send Message
* @param message Message Data
*/
@Throws(GameServiceException::class)
fun sendPrivateMessage(@NotNull memberId: String, @NotNull message: String) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (memberId.isEmpty() && message.isEmpty()) throw GameServiceException("memberId Or message Cant Be EmptyOrNull")
GSLive.handler.commandHandler.request(SendPrivateMessageHandler.signature, Pair(memberId, message))
}
/**
* Get Channels Subscribe List
*/
@Throws(GameServiceException::class)
fun getChannelsSubscribed() {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
GSLive.handler.commandHandler.request(GetChannelsSubscribedHandler.signature)
}
/**
* Get Channel last 30 Messages.
* @param channelName Name of Channel You want To Get last 30 Messages
*/
@Throws(GameServiceException::class)
fun getChannelRecentMessages(@NotNull channelName: String) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (channelName.isEmpty()) throw GameServiceException("channelName Cant Be EmptyOrNull")
GSLive.handler.commandHandler.request(GetChannelRecentMessagesRequestHandler.signature, RoomDetail().apply { id = channelName })
}
/**
* Get Channel Members
* @param channelName Name of Channel You want To Get Members
* @param skip The skip value
* @param limit (Max = 15) The Limit value
*/
@Throws(GameServiceException::class)
fun getChannelMembers(@NotNull channelName: String, skip: Int, limit: Int) {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
if (channelName.isEmpty()) throw GameServiceException("channelName Cant Be EmptyOrNull")
if (limit <= 0 || limit > 15) throw GameServiceException("invalid Limit Value")
if (skip < 0) throw GameServiceException("invalid Skip Value")
GSLive.handler.commandHandler.request(GetChannelsMembersRequestHandler.signature, RoomDetail()
.apply {
id = channelName
min = skip
max = limit
}
)
}
/**
* Get Your Pending Messages
*/
@Throws(GameServiceException::class)
fun getPendingMessages() {
if (GameService.IsGuest) throw GameServiceException("This Function Not Working In Guest Mode")
GSLive.handler.commandHandler.request(GetPendingMessagesRequestHandler.signature)
}
}
| 0
|
Kotlin
|
0
| 0
|
2977427a328b7accb7972a03e4bd401a09693b72
| 5,662
|
GameService-Kotlin-SDK
|
Apache License 2.0
|
network/src/main/kotlin/org/openapitools/client/models/Image.kt
|
manish218
| 597,589,035
| false
| null |
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import com.squareup.moshi.Json
/**
*
*
* @param id Unique resource id
* @param title Title of a content item
* @param description Description of the content
* @param url Relative URL to this resource. Ex /channel/itv1 or /taxonomy/football
* @param height Height in pixels
* @param width Width in pixels
* @param kind type of image to determine where to use
*/
data class Image (
/* Unique resource id */
@Json(name = "id")
val id: java.util.UUID? = null,
/* Title of a content item */
@Json(name = "title")
val title: kotlin.String? = null,
/* Description of the content */
@Json(name = "description")
val description: kotlin.String? = null,
/* Relative URL to this resource. Ex /channel/itv1 or /taxonomy/football */
@Json(name = "url")
val url: kotlin.String? = null,
/* Height in pixels */
@Json(name = "height")
val height: kotlin.Int? = null,
/* Width in pixels */
@Json(name = "width")
val width: kotlin.Int? = null,
/* type of image to determine where to use */
@Json(name = "kind")
val kind: Image.Kind? = null
) {
/**
* type of image to determine where to use
*
* Values: thumbnail,logo,logoMinusGrey,heroMinusBackgroundMinusPort,heroMinusBackgroundMinusLand
*/
enum class Kind(val value: kotlin.String) {
@Json(name = "thumbnail") thumbnail("thumbnail"),
@Json(name = "logo") logo("logo"),
@Json(name = "logo-grey") logoMinusGrey("logo-grey"),
@Json(name = "hero-background-port") heroMinusBackgroundMinusPort("hero-background-port"),
@Json(name = "hero-background-land") heroMinusBackgroundMinusLand("hero-background-land");
}
}
| 1
|
Kotlin
|
0
| 0
|
7b4e97161b530dc7106d28780a08048b7b11754a
| 2,034
|
fast-player
|
MIT License
|
src/main/kotlin/kr/ac/jbnu/ampm/ampmsiteapi/Service/MemberActivityService.kt
|
ampm-jbnu
| 599,133,979
| false
| null |
package kr.ac.jbnu.ampm.ampmsiteapi.Service
import kr.ac.jbnu.ampm.ampmsiteapi.DTO.MemberActivityDTO
import kr.ac.jbnu.ampm.ampmsiteapi.DTO.toEntity
import kr.ac.jbnu.ampm.ampmsiteapi.Entity.toDTO
import kr.ac.jbnu.ampm.ampmsiteapi.Repo.MemberActivityRepo
class MemberActivityService(private val memberActivityRepository : MemberActivityRepo) {
fun getAllMembers():List<MemberActivityDTO>{
return memberActivityRepository.findAll().map{it.toDTO()}
}
fun getMemberById(id: Long) : MemberActivityDTO {
val Member = memberActivityRepository.findById(id).orElseThrow{MemberNotFoundException()}
return Member.toDTO()
}
fun createMember(memberDTO: MemberActivityDTO): MemberActivityDTO {
val memberEntity = memberDTO.toEntity()
val savedMemberEntity = memberActivityRepository.save(memberEntity)
return savedMemberEntity.toDTO()
}
fun updateMemberByID(id:Long, memberDTO: MemberActivityDTO): MemberActivityDTO {
val Member = memberActivityRepository.findById(id).orElseThrow{MemberNotFoundException()}
Member.name = memberDTO.name
Member.email = memberDTO.email
Member.studentNum = memberDTO.studentNum
Member.bio = memberDTO.bio
Member.interest = memberDTO.interest
Member.status = memberDTO.status
Member.applyStatus = memberDTO.applyStatus
val updatedEntity = memberActivityRepository.save(Member)
return updatedEntity.toDTO()
}
}
class MemberNotFoundException : RuntimeException("Member not found")
| 1
|
Kotlin
|
2
| 2
|
8d21ee326383f97d8113c7fa84798bd29a8956e6
| 1,559
|
ampm-site-api
|
MIT License
|
app/src/main/java/com/example/if570_lab_uts_agustinus_00000053639/HomeActivity.kt
|
agustinusss
| 720,303,153
| false
|
{"Kotlin": 23017}
|
package com.example.if570_lab_uts_agustinus_00000053639
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.widget.Toolbar
import androidx.viewpager2.widget.ViewPager2
import com.example.if570_lab_uts_agustinus_00000053639.adapter.HomePagerAdapter
import com.example.if570_lab_uts_agustinus_00000053639.adapter.MyFragmentController
import com.example.if570_lab_uts_agustinus_00000053639.fragments.DetailFragment
import com.example.if570_lab_uts_agustinus_00000053639.fragments.ListFragment
import com.example.if570_lab_uts_agustinus_00000053639.fragments.ProfileFragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
class HomeActivity : AppCompatActivity() {
private val fragmentController = MyFragmentController(this, R.id.fragment_detail_xml)
private lateinit var userName: String
private lateinit var viewPager: ViewPager2
private lateinit var listFragment: ListFragment
private lateinit var profileFragment: ProfileFragment
private lateinit var detailFragmentContainer: FrameLayout // Tambahkan ini
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
userName = intent.getStringExtra("user_name") ?: "User"
val toolbar = findViewById<Toolbar>(R.id.toolbar)
detailFragmentContainer = findViewById(R.id.fragment_detail_xml) // Inisialisasi detailFragmentContainer
setSupportActionBar(toolbar)
supportActionBar?.title = null
viewPager = findViewById(R.id.viewPager2)
val adapter = HomePagerAdapter(this)
viewPager.adapter = adapter
// Tabs berfungsi dan menggunakan Fragment
val tabLayout = findViewById<TabLayout>(R.id.TabLayout)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
when (position) {
0 -> tab.text = getString(R.string.CE_title)
1 -> tab.text = getString(R.string.Profile_title)
}
}.attach()
// Nama diambil dari Landing Page (bukan hardcode)
profileFragment = ProfileFragment()
val bundle = Bundle()
bundle.putString("user_name", userName)
profileFragment.arguments = bundle
adapter.addFragment(profileFragment)
val fragment = DetailFragment() // fragment yang ingin di tampilkan
fragmentController.replaceFragment(fragment)
// listener tab
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
val selectedTabPosition = tab?.position
if (selectedTabPosition == 1) { // Tab Profile
detailFragmentContainer.visibility = View.GONE
}
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
// Tidak perlu melakukan apa pun saat tab tidak terpilih
}
override fun onTabReselected(tab: TabLayout.Tab?) {
// Tidak perlu melakukan apa pun saat tab terpilih kembali
}
})
}
// Options Menu berfungsi
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_home, menu)
// Kirim data nama pengguna ke option menu
// Nama pada Option Menu diambil dari Landing Page (bukan hardcode)
val userProfileMenuItem = menu.findItem(R.id.action_user_profile)
userProfileMenuItem.title = "Hi, $userName"
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_user_profile -> {
return true
}
R.id.action_logout -> {
// Tombol Logout ditekan, pindah ke LandingActivity
val intent = Intent(this, LandingActivity::class.java)
startActivity(intent)
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// Halaman tidak berpindah ke Landing Page ketika tombol Back HP ditekan
}
}
| 0
|
Kotlin
|
0
| 0
|
626b4dfc8efbf3676daae481ac639e2b7ad37c09
| 4,437
|
SimpleMobile_Pokedex
|
MIT License
|
app/src/main/java/com/franzliszt/magicmusic/bean/video/MlogContentBean.kt
|
FranzLiszt-1847
| 753,088,527
| false
|
{"Kotlin": 879960, "Java": 1923}
|
package com.franzliszt.magicmusic.bean.video
data class MlogContentBean(
val accompanyInfo: Any,
val actList: List<Any>,
val albumExt: Any,
val audio: Any,
val coverColor: Int,
val coverExt: Any,
val creation: Any,
val creationProtocolInfos: List<Any>,
val creationTagType: Int,
val creationUrl: Any,
val image: List<Any>,
val imageCreationUrl: Any,
val interveneText: String,
val randomSong: Any,
val realateSongs: List<Any>,
val relateSongs: List<Any>,
val song: Any,
val songs: List<Any>,
val templateId: Any,
val text: String,
val title: String,
val topics: Any,
val video: MlogVideoBean
)
| 0
|
Kotlin
|
1
| 1
|
dcbc4c0cb9c0478e617423812712659df52a3b7d
| 686
|
MagicPlayer
|
Apache License 2.0
|
app/src/main/java/com/example/fragment/project/ui/register/RegisterScreen.kt
|
miaowmiaow
| 364,865,870
| false
| null |
package com.example.fragment.project.ui.register
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.fragment.project.R
import com.example.fragment.project.components.BoxLayout
import com.example.fragment.project.components.WhiteTextField
import kotlinx.coroutines.launch
@Composable
fun RegisterScreen(
registerViewModel: RegisterViewModel = viewModel(),
onPopBackStackToMain: () -> Unit = {},
) {
val context = LocalContext.current
val uiState by registerViewModel.uiState.collectAsStateWithLifecycle()
val coroutineScope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
val scrollState = rememberScrollState()
if (uiState.errorCode == "0") {
onPopBackStackToMain()
}
SideEffect {
if (uiState.errorMsg.isNotBlank()) {
coroutineScope.launch {
scaffoldState.snackbarHostState.showSnackbar(uiState.errorMsg)
}
}
}
var usernameText by rememberSaveable { mutableStateOf("") }
var passwordText by rememberSaveable { mutableStateOf("") }
var againPasswordText by rememberSaveable { mutableStateOf("") }
Scaffold(
scaffoldState = scaffoldState,
snackbarHost = { SnackbarHost(it) { data -> Snackbar(snackbarData = data) } },
content = { innerPadding ->
BoxLayout(uiState.isLoading, innerPadding) {
Column(
modifier = Modifier
.fillMaxSize()
.paint(
painter = painterResource(id = R.drawable.bg),
contentScale = ContentScale.FillBounds
)
.padding(start = 40.dp, top = 15.dp, end = 40.dp, bottom = 15.dp)
.verticalScroll(scrollState)
.systemBarsPadding()
.navigationBarsPadding()
) {
Image(
painter = painterResource(R.drawable.ic_back),
contentDescription = null,
modifier = Modifier
.size(15.dp)
.clickable {
if (context is AppCompatActivity) {
context.onBackPressedDispatcher.onBackPressed()
}
}
)
Spacer(Modifier.height(30.dp))
Text(
text = "Create",
style = MaterialTheme.typography.h4,
color = colorResource(R.color.white),
)
Spacer(Modifier.height(20.dp))
Text(
text = "Account",
style = MaterialTheme.typography.h5,
color = colorResource(R.color.white),
)
Spacer(Modifier.weight(1f))
WhiteTextField(
value = usernameText,
onValueChange = { usernameText = it },
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
placeholder = { Text("请输入用户名") },
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Next),
)
Spacer(Modifier.height(15.dp))
WhiteTextField(
value = passwordText,
onValueChange = { passwordText = it },
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
placeholder = { Text("请输入用户密码") },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Next
),
)
Spacer(Modifier.height(15.dp))
WhiteTextField(
value = againPasswordText,
onValueChange = { againPasswordText = it },
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
placeholder = { Text("请再次输入密码") },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Go
),
keyboardActions = KeyboardActions(onGo = {
registerViewModel.register(
usernameText,
passwordText,
againPasswordText
)
}),
)
Spacer(Modifier.height(30.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = "注册",
fontSize = 20.sp,
color = colorResource(R.color.white),
)
Spacer(Modifier.weight(1f))
Button(
onClick = {
registerViewModel.register(
usernameText,
passwordText,
againPasswordText
)
},
elevation = ButtonDefaults.elevation(0.dp, 0.dp, 0.dp),
shape = RoundedCornerShape(50),
colors = ButtonDefaults.buttonColors(
backgroundColor = colorResource(R.color.theme_orange),
contentColor = colorResource(R.color.white)
),
contentPadding = PaddingValues(15.dp),
modifier = Modifier.size(55.dp)
) {
Icon(
painter = painterResource(R.drawable.ic_right_arrow),
contentDescription = null
)
}
}
Spacer(Modifier.height(30.dp))
Text(
text = "去登录",
textDecoration = TextDecoration.Underline,
fontSize = 12.sp,
color = colorResource(R.color.white),
modifier = Modifier
.clickable {
if (context is AppCompatActivity) {
context.onBackPressedDispatcher.onBackPressed()
}
}
)
Spacer(Modifier.height(30.dp))
}
}
}
)
}
| 0
|
Kotlin
|
187
| 951
|
0e4c3f31e34e0d808765a8e2a6e40b086fbed30b
| 8,741
|
fragmject
|
Apache License 2.0
|
app/src/main/java/com/example/baseapp/MyApplication.kt
|
TReturn
| 399,864,608
| false
| null |
package com.example.baseapp
import com.example.lib_base.BaseApplication
/**
* @CreateDate : 2020/12/30
* @Author : 青柠
* @Description :
*/
class MyApplication : BaseApplication() {
override fun onCreate() {
super.onCreate()
}
}
| 0
|
Kotlin
|
1
| 1
|
ac75e3c6c3bceae4b4f94a918b58bbd627c17dd2
| 248
|
BaseApp
|
Apache License 2.0
|
android/Rental/app/src/main/java/com/project/pradyotprakash/rental/app/pages/wishlist/view/WishlistScreen.kt
|
pradyotprksh
| 385,586,594
| false
| null |
package com.project.pradyotprakash.rental.app.pages.wishlist.view
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.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.project.pradyotprakash.rental.app.composables.ConfirmationDialog
import com.project.pradyotprakash.rental.app.composables.PageStateComposable
import com.project.pradyotprakash.rental.app.composables.PropertyDetailsComposable
import com.project.pradyotprakash.rental.app.localization.TR
import com.project.pradyotprakash.rental.app.pages.wishlist.viewmodel.WishlistViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WishlistScreen(
wishlistViewModel: WishlistViewModel = hiltViewModel(),
) {
LaunchedEffect(key1 = wishlistViewModel) {
wishlistViewModel.getAllWishlist()
}
val loading = wishlistViewModel.loading.observeAsState(false)
val error = wishlistViewModel.error.observeAsState("")
val wishlists = wishlistViewModel.wishlists.observeAsState()
val confirmationDialog = wishlistViewModel.confirmationDialog.observeAsState(
ConfirmationDialog()
)
PageStateComposable(
isLoading = loading.value,
errorMessage = error.value,
dismissErrorAlert = wishlistViewModel::updateErrorState,
confirmationDialog = confirmationDialog.value,
) {
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(),
title = { Text(text = TR.yourWatchlist) },
navigationIcon = {
IconButton(onClick = wishlistViewModel::navigateBack) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = Icons.Default.ArrowBack.name,
)
}
},
)
},
) { paddingValues ->
wishlists.value?.let { allWishlist ->
LazyColumn(
contentPadding = PaddingValues(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding(),
)
) {
items(allWishlist) { wishlist ->
val propertyDetails = wishlist.property_details
Column {
propertyDetails?.let {
PropertyDetailsComposable(
property = propertyDetails
) { wishlistViewModel.navigateToPropertyDetails(it) }
}
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(
horizontal = 10.dp,
)
) {
Text(
text = String.format(TR.added, wishlist.wishlistCreateOnTimeAgo)
)
IconButton(
onClick = {
propertyDetails?.let {
wishlistViewModel.confirmDeleteWishList(
propertyId = propertyDetails.property_id,
propertyName = propertyDetails.property_name,
)
}
}
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = Icons.Default.Delete.name
)
}
}
}
}
item {
Spacer(modifier = Modifier.height(10.dp))
}
}
}
}
}
}
| 0
|
Kotlin
|
7
| 9
|
e10e007fab12c3d056920741c06ff599a64cca21
| 5,587
|
development_learning
|
MIT License
|
app/src/main/java/com/zenika/story/adventure/domain/GetCasablancaPaperStateUseCase.kt
|
Zenika
| 628,692,757
| false
|
{"Kotlin": 394194, "Shell": 305}
|
package com.zenika.story.adventure.domain
import com.zenika.story.adventure.data.AdventureGameStateManager
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class GetCasablancaPaperStateUseCase @Inject constructor(
private val gameStateManager: AdventureGameStateManager
) {
operator fun invoke() = gameStateManager.state.map { it.isCasablancaPaperCollected }
}
| 1
|
Kotlin
|
0
| 2
|
3e81f9e98c283fb243bb5c06e620c637ac61a6ef
| 384
|
ZEscape-Android
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/GetEnvironment.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/** \! " in the operating system environment.
*```` * StyleBox["var", "TI"] * GetEnvironment[{var , var , …}] gives a list of rules, corresponding to specified environment variables.
* * 1 2
* Name: GetEnvironment * Usage: GetEnvironment[] gives information about all existing settings in the operating system environment.
* *
* Full name: System`GetEnvironment * Options: None
* *
* GetEnvironment["var"] gives the setting corresponding to the variable " * Attributes: Protected
*
* local: paclet:ref/GetEnvironment
* Documentation: web: http://reference.wolfram.com/language/ref/GetEnvironment.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun getEnvironment(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("GetEnvironment", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 4,630
|
mathemagika
|
Apache License 2.0
|
feature/movies/src/main/java/vn/toanpv/sample/movies/ui/movie/adapter/search/MovieHintAdapter.kt
|
toanpv
| 620,264,148
| false
| null |
package vn.toanpv.sample.movies.ui.movie.adapter.search
import android.view.LayoutInflater
import android.view.ViewGroup
import vn.toanpv.sample.movies.ui.movie.model.MovieItem
import vn.toanpv.sample.arena.core.ui.widget.recyclerview.BaseRecyclerViewAdapter
import vn.toanpv.sample.movies.databinding.ItemMovieSearchHintBinding
class MovieHintAdapter(private val onItemClick: (MovieItem) -> Unit) :
BaseRecyclerViewAdapter<MovieItem, MovieSearchHintViewHolder>() {
override fun areItemsSame(oldItem: MovieItem, newItem: MovieItem): Boolean {
return oldItem.imdbID == newItem.imdbID
}
override fun areContentsSame(oldItem: MovieItem, newItem: MovieItem): Boolean {
return oldItem.title == newItem.title
}
override fun createHolder(parent: ViewGroup, viewType: Int): MovieSearchHintViewHolder {
return MovieSearchHintViewHolder(
ItemMovieSearchHintBinding.inflate(
LayoutInflater.from(parent.context), parent, false
), onItemClick
)
}
}
| 0
|
Kotlin
|
0
| 0
|
2815a33ac1e597a6e053da7d1e27454522f36bfb
| 1,039
|
InspiusArena
|
Apache License 2.0
|
app/src/main/java/br/com/movieapp/movie_favorite_feature/domain/usecase/GetMoviesFavoriteUseCase.kt
|
LeoDiasDev
| 874,309,011
| false
|
{"Kotlin": 181905}
|
package br.com.movieapp.movie_favorite_feature.domain.usecase
import br.com.movieapp.core.domain.model.Movie
import br.com.movieapp.movie_favorite_feature.domain.repository.MovieFavoriteRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import javax.inject.Inject
interface GetMoviesMovieFavoriteUseCase{
suspend operator fun invoke(): Flow<List<Movie>>
}
class GetMoviesMovieFavoriteUseCaseImpl @Inject constructor(
private val movieFavoriteRepository: MovieFavoriteRepository
): GetMoviesMovieFavoriteUseCase{
override suspend fun invoke(): Flow<List<Movie>> {
return try {
movieFavoriteRepository.getMovies()
}catch (e: Exception){
emptyFlow()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a7492d47da1f12144015c8ffcbfb91fc5c4331a1
| 757
|
movie-app
|
MIT License
|
src/jsMain/kotlin/App.kt
|
Odaym
| 654,765,122
| false
| null |
import csstype.TextDecoration
import emotion.react.css
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import react.*
import react.dom.html.ReactHTML.h1
import react.dom.html.ReactHTML.li
import react.dom.html.ReactHTML.ul
private val scope = MainScope()
val App = FC<Props> {
var (shoppingList, setShoppingList) = useState(emptyList<ShoppingListItem>())
val (deleted, setDeleted) = useState(mutableListOf<ShoppingListItem>())
useEffectOnce {
scope.launch {
setShoppingList(getShoppingList())
}
}
h1 {
+"Full-Stack Shopping List"
}
ul {
shoppingList.sortedByDescending(ShoppingListItem::priority).forEach { item ->
li {
if (item in deleted) {
css {
textDecoration = TextDecoration.lineThrough
}
}
key = item.toString()
onClick = {
scope.launch {
val newList = deleted.apply { remove(item) }
setDeleted(newList)
// setShoppingList(getShoppingList())
}
}
+"[${item.priority}] ${item.desc}"
}
}
}
InputComponent {
onSubmit = { input ->
val cartItem = ShoppingListItem(
input.replace("!", ""),
input.count { it == '!' }
)
scope.launch {
addShoppingListItem(cartItem)
shoppingList = getShoppingList()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f9eca4ea015284a72302aa294759e487e2a9ee9d
| 1,648
|
fullstack-shopping-list-kmm
|
Apache License 2.0
|
app/src/main/kotlin/com/absinthe/kage/media/MediaDirectory.kt
|
zhaobozhen
| 223,542,983
| false
| null |
package com.absinthe.kage.media
import android.os.Parcel
import android.os.Parcelable
import java.util.*
class MediaDirectory : Parcelable {
private var mediaList: MutableList<LocalMedia>? = null
var name: String? = null
var id: Long = 0
var type = 0
internal constructor()
constructor(parcel: Parcel) {
id = parcel.readLong()
mediaList = parcel.createTypedArrayList(LocalMedia.CREATOR)
name = parcel.readString()
type = parcel.readInt()
}
val itemCount: Int
get() {
val list: List<LocalMedia>? = mediaList
return list?.size ?: 0
}
fun addMedia(media: LocalMedia) {
if (mediaList == null) {
mediaList = ArrayList()
}
mediaList!!.add(media)
}
fun getMediaList(): List<LocalMedia>? {
return mediaList
}
val firstMediaPath: String?
get() {
val list: List<LocalMedia>? = mediaList
return if (list == null) {
null
} else {
mediaList!![0].filePath
}
}
override fun equals(other: Any?): Boolean {
if (other !is MediaDirectory) {
return false
}
if (this === other) {
return true
}
return other.id == id && other.name == name
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id)
dest.writeTypedList(mediaList)
dest.writeString(name)
dest.writeInt(type)
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (mediaList?.hashCode() ?: 0)
result = 31 * result + (name?.hashCode() ?: 0)
result = 31 * result + type
return result
}
companion object CREATOR : Parcelable.Creator<MediaDirectory> {
override fun createFromParcel(parcel: Parcel): MediaDirectory {
return MediaDirectory(parcel)
}
override fun newArray(size: Int): Array<MediaDirectory?> {
return arrayOfNulls(size)
}
}
}
| 1
|
Kotlin
|
5
| 25
|
71dc5f8ee51b3b566723455fbc4b019845c2a347
| 2,189
|
Kage
|
Apache License 2.0
|
app/src/main/kotlin/io/github/importre/eddystone/EddyStone.kt
|
hojinchu99
| 46,778,834
| false
|
{"Kotlin": 79978, "Java": 674}
|
package io.github.importre.eddystone
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.os.ParcelUuid
import java.util.*
public class EddyStone(val activity: Activity, val cb: EddyStoneCallback, val requestCodeForBT: Int) {
companion object {
public val UUID: ParcelUuid = ParcelUuid.fromString("0000FEAA-0000-1000-8000-00805F9B34FB")
}
private val scanFilterList: ArrayList<ScanFilter> = arrayListOf()
private var scanner: BluetoothLeScanner? = null
private val scanHandler: ScanHandler
private val settings: ScanSettings
init {
scanHandler = ScanHandler(cb)
settings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0)
.build()
init()
}
public fun init() {
stop()
val systemService = activity.getSystemService(Context.BLUETOOTH_SERVICE)
val blManager = systemService as BluetoothManager
blManager.adapter?.let {
initScanner(activity, it, requestCodeForBT)
initScanFilter()
}
}
private fun initScanner(activity: Activity, btAdapter: BluetoothAdapter, requestCode: Int) {
if (!btAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
activity.startActivityForResult(enableBtIntent, requestCode)
} else {
scanner = btAdapter.bluetoothLeScanner
}
}
private fun initScanFilter() {
ScanFilter.Builder().setServiceUuid(UUID)?.build()?.let {
scanFilterList.add(it)
}
}
public fun start() {
try {
scanner?.let {
it.startScan(scanFilterList, settings, scanHandler)
scanHandler.start()
}
} catch (e: Exception) {
}
}
public fun stop() {
try {
scanner?.let {
it.stopScan(scanHandler)
scanHandler.stop()
}
} catch (e: Exception) {
}
}
}
| 0
|
Kotlin
|
0
| 0
|
50ff11b443d953f4212268326095c65fd4be5be8
| 2,339
|
yeobara-android
|
MIT License
|
src/main/kotlin/by/mrpetchenka/flanscore/common/blocks/BlockGunWorkbench.kt
|
PeTcHeNkA
| 506,586,519
| false
| null |
package by.mrpetchenka.flanscore.common.blocks
import by.mrpetchenka.flanscore.client.core.helper.IconHelper
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.block.material.Material
import net.minecraft.client.renderer.texture.IIconRegister
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.IIcon
import net.minecraft.world.World
import java.time.Duration
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class BlockGunWorkbench : BlockMod(Material.iron) {
private lateinit var iSide: IIcon
private lateinit var iTop: IIcon
private lateinit var iBottom: IIcon
private val executor: ScheduledExecutorService = Executors.newScheduledThreadPool(1)
private val time = LocalTime.of(23, 0, 0)
private var inited = false;
init {
setBlockUnbreakable()
setBlockName("workbench")
if(!inited) {
inited = true
val task = Runnable { println("Running task...") }
executor.scheduleEverydayAt(time, task)
}
}
override fun getIcon(side: Int, meta: Int): IIcon {
return when (side) {
1 -> iTop
0 -> iBottom
else -> iSide
}
}
@SideOnly(Side.CLIENT)
override fun registerBlockIcons(icon: IIconRegister) {
iTop = IconHelper.forBlock(icon, this, "Top")
iBottom = IconHelper.forBlock(icon, this, "Bottom")
iSide = IconHelper.forBlock(icon, this, "Side")
}
override fun onBlockActivated(
world: World,
x: Int,
y: Int,
z: Int,
player: EntityPlayer,
side: Int,
xOffset: Float,
yOffset: Float,
zOffset: Float
): Boolean {
if (!world.isRemote) {
println("Time left until next run: ${getTimeRemaining()}")
}
return true
}
private fun getTimeRemaining(): String {
val duration = getTimeDuration()
val hours = duration.toHours()
val minutes = duration.toMinutes() % 60
val seconds = duration.seconds % 60
return "$hours hours $minutes minutes $seconds seconds"
}
private fun getTimeDuration(): Duration {
val now = LocalDateTime.now()
var nextRun = now.with(time)
if (now.isAfter(nextRun)) {
nextRun = nextRun.plusDays(1)
}
return Duration.between(now, nextRun)
}
private fun ScheduledExecutorService.scheduleEverydayAt(time: LocalTime, task: Runnable) {
scheduleAtFixedRate(task, getTimeDuration().seconds, TimeUnit.DAYS.toSeconds(1), TimeUnit.SECONDS)
}
}
| 0
|
Kotlin
|
0
| 0
|
f4f5eef2db6631e3ba6adbaa4e6d5a36391798e2
| 2,789
|
FlansCore
|
MIT License
|
NetworkUtils/src/main/java/com/abiots/networkutils/core/AddressResolutionProtocol.kt
|
AbiotsLabs
| 415,655,663
| false
|
{"Kotlin": 17353}
|
package com.abiots.networkutils.core
import com.abiots.networkutils.BuildConfig
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.io.FileReader
/**
* @author <NAME>
* - ARP stands for Address Resolution Protocol
*/
object AddressResolutionProtocol {
init {
if (Timber.treeCount() == 0 && BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else Unit
}
private const val GET_IP_NEIGHBOURS_COMMAND = "ip neigh show"
private const val ARP_CACHE_PATH = "/proc/net/arp"
private const val INVALID_MAC_ADDRESS = "00:00:00:00:00:00"
private val MAC_ID_REGEX = "..:..:..:..:..:..".toRegex()
/**
* This method is used to get the Ip address-Mac address map from the ARP cache and IPS sleigh.
*/
suspend fun getAllIPAndMACAddressesInARPCache() = withContext(IO) {
Timber.d("getting ip and mac data from ARP cache")
getAllIpAndMACAddressesFromIPSleigh().apply ipMacMap@{
runCatching {
if (File(ARP_CACHE_PATH).canRead()) {
FileReader(ARP_CACHE_PATH).buffered().readLines().forEach { arpData ->
arpData.split(" +").let {
if (it.size >= 4 && it[3].matches(MAC_ID_REGEX) && it[3] != INVALID_MAC_ADDRESS && !this@ipMacMap.containsKey(it[0])) {
this@ipMacMap.put(it[0], it[3])
} else Unit
}
}
} else Unit
}.onFailure {
Timber.e("Error opening the ARP data cache %s", it.localizedMessage)
}.onSuccess {
Timber.d("ARP data from the ARP cache are :${this@ipMacMap} ")
}
}
}
private suspend fun getAllIpAndMACAddressesFromIPSleigh() = withContext(IO) {
Timber.d("Getting IP and MAC from ARP IP sleigh")
HashMap<String, String>().apply macIpHashMap@{
runCatching {
Timber.d("getting the IP and mac from the IP sleigh")
val ipNeighboursProcess = Runtime.getRuntime().exec(GET_IP_NEIGHBOURS_COMMAND)
ipNeighboursProcess.waitFor()
ipNeighboursProcess.inputStream.bufferedReader().readLines()
}.onFailure {
Timber.e("error getting the IP and mac address from the ARP IP sleigh ${it.localizedMessage}")
}.onSuccess {
Timber.d("ARP data from Ip sleigh $it")
it.forEach { line ->
line.split(" ").let { details ->
if (details.size > 4) {
this@macIpHashMap.put(details[0], details[4])
} else Unit
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
70025555b2f953829b5a1d84dd97eaa568fce845
| 2,885
|
NetworkTools
|
Apache License 2.0
|
cinescout/screenplay/data/remote/trakt/src/commonMain/kotlin/screenplay/data/remote/trakt/model/TraktTvShowExtended.kt
|
fardavide
| 280,630,732
| false
| null |
package screenplay.data.remote.trakt.model
import cinescout.screenplay.domain.model.ids.TmdbTvShowId
import cinescout.screenplay.domain.model.ids.TraktTvShowId
import korlibs.time.Date
import korlibs.time.DateTime
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.time.Duration
typealias TraktTvShowsExtendedResponse = List<TraktTvShowExtendedBody>
@Serializable
@SerialName(TraktContentType.TvShow)
data class TraktTvShowExtendedBody(
@SerialName(AiredEpisodes)
val airedEpisodes: Int,
@Contextual
@SerialName(FirstAired)
val firstAirDate: Date = DateTime.EPOCH.date,
@SerialName(TraktContent.Ids)
override val ids: TraktTvShowIds,
@SerialName(TraktContent.Overview)
override val overview: String = "",
@Contextual
@SerialName(TraktContent.Runtime)
override val runtime: Duration? = null,
@SerialName(TraktContent.Title)
val title: String,
@SerialName(TraktContent.Rating)
override val voteAverage: Double,
@SerialName(TraktContent.Votes)
override val voteCount: Int
) : TraktScreenplayExtendedBody {
override val tmdbId: TmdbTvShowId
get() = ids.tmdb
override val traktId: TraktTvShowId
get() = ids.trakt
companion object {
const val AiredEpisodes = "aired_episodes"
const val FirstAired = "first_aired"
}
}
| 14
|
Kotlin
|
2
| 6
|
f04a22b832397f22065a85af038dd15d90225cde
| 1,423
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/hypertrack/android/adapters/ItemsAdapter.kt
|
amrfaisal
| 252,781,704
| true
|
{"Kotlin": 91717}
|
package com.hypertrack.android.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.hypertrack.android.response.Items
import com.hypertrack.logistics.android.github.R
// Job lists item adapters
class ItemsAdapter(context: Context, onclick: OnScanListItemClick) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var onItemClick: OnScanListItemClick? = null
private var layoutInflater: LayoutInflater? = null
private var itemsList: ArrayList<Items>
init {
this.itemsList = arrayListOf()
this.onItemClick = onclick
layoutInflater = LayoutInflater.from(context)
}
fun updateList(list: ArrayList<Items>) {
itemsList = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.inflate_scan_item, parent, false)
return ItemViewHolder(itemView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ItemViewHolder) {
holder.tvItemId?.text = "#".plus(itemsList[holder.adapterPosition].item_id)
}
}
override fun getItemCount(): Int {
return itemsList.size
}
inner class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var tvItemId: TextView? = null
init {
tvItemId = view.findViewById(R.id.tvItemId)
}
}
interface OnScanListItemClick {
fun onScanClick(position: Int, type: String = "")
}
}
| 0
| null |
1
| 1
|
217a2fdbc652bb45f65fa3907228a64e99fc518b
| 1,799
|
logistics-android
|
MIT License
|
android/PostsComments/app/src/main/java/com/pradyotprakash/postscomments/app/pages/posts/viewmodel/PostsViewModel.kt
|
pradyotprksh
| 385,586,594
| false
|
{"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
|
package com.pradyotprakash.postscomments.app.pages.posts.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pradyotprakash.postscomments.app.composables.ConfirmationDialog
import com.pradyotprakash.postscomments.app.localization.TR
import com.pradyotprakash.postscomments.core.auth.AuthState
import com.pradyotprakash.postscomments.core.auth.AuthStateListener
import com.pradyotprakash.postscomments.core.navigator.Navigator
import com.pradyotprakash.postscomments.core.navigator.Routes
import com.pradyotprakash.postscomments.core.response.PostsCommentsResponse
import com.pradyotprakash.postscomments.core.toast.ToastListener
import com.pradyotprakash.postscomments.core.utils.PostCommentFormArguments
import com.pradyotprakash.postscomments.domain.models.PostCompleteDetails
import com.pradyotprakash.postscomments.domain.usecases.AuthenticationUseCase
import com.pradyotprakash.postscomments.domain.usecases.CommentUseCase
import com.pradyotprakash.postscomments.domain.usecases.PostUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PostsViewModel @Inject constructor(
private val authenticationUseCase: AuthenticationUseCase,
private val authStateListener: AuthStateListener,
private val navigator: Navigator,
private val postUseCase: PostUseCase,
private val commentUseCase: CommentUseCase,
private val toastListener: ToastListener
) : ViewModel() {
private val _loading = MutableLiveData(false)
val loading: LiveData<Boolean>
get() = _loading
private val _errorText = MutableLiveData("")
val error: LiveData<String>
get() = _errorText
private val _confirmationDialog = MutableLiveData(ConfirmationDialog())
val confirmationDialog: LiveData<ConfirmationDialog>
get() = _confirmationDialog
private val _posts = MutableLiveData<List<PostCompleteDetails>>(emptyList())
val posts: LiveData<List<PostCompleteDetails>>
get() = _posts
fun updateErrorState(message: String? = "") {
_loading.value = false
_errorText.value = message
}
fun confirmLogOutUser() {
_confirmationDialog.value = ConfirmationDialog(
text = TR.confirmLogout,
onConfirm = {
_confirmationDialog.value = ConfirmationDialog()
logoutUser()
},
onDismiss = {
_confirmationDialog.value = ConfirmationDialog()
},
)
}
fun confirmDeletePosts(postId: String) {
_confirmationDialog.value = ConfirmationDialog(
text = TR.surePostDelete,
onConfirm = {
_confirmationDialog.value = ConfirmationDialog()
deletePost(postId)
},
onDismiss = {
_confirmationDialog.value = ConfirmationDialog()
},
)
}
private fun deletePost(postId: String) {
viewModelScope.launch {
postUseCase.deletePost(postId = postId).collect {
when (it) {
is PostsCommentsResponse.Error -> updateErrorState(it.exception.message)
is PostsCommentsResponse.Success -> {
toastListener.showToast(TR.postDeleted)
deleteComments(postId)
}
else -> {}
}
}
}
}
private suspend fun deleteComments(postId: String) {
commentUseCase.getComments(postId = postId).collect {
when (it) {
is PostsCommentsResponse.Success -> {
it.data.forEach { comment ->
commentUseCase.deleteComment(commentId = comment.commentId)
}
}
else -> {}
}
}
}
private fun logoutUser() {
authenticationUseCase.logoutUser()
authStateListener.stateChange(AuthState.Unauthenticated)
}
fun openCreatePostScreen() {
navigator.navigate {
it.navigate(
Routes.PostForm.route + PostCommentFormArguments.postForm + "/${PostCommentFormArguments.create}" + "/${PostCommentFormArguments.na}" + "/${PostCommentFormArguments.na}"
)
}
}
fun getPosts() {
viewModelScope.launch {
postUseCase.getPosts().collect {
when (it) {
is PostsCommentsResponse.Error -> updateErrorState(it.exception.message)
is PostsCommentsResponse.Success -> {
_posts.value = emptyList()
_posts.value = it.data ?: emptyList()
}
else -> {}
}
}
}
}
fun isFromCurrentUser(createdBy: String): Boolean =
authenticationUseCase.getCurrentUserId() == createdBy
fun editPost(postId: String) {
navigator.navigate {
it.navigate(
Routes.PostForm.route + PostCommentFormArguments.postForm + "/${PostCommentFormArguments.edit}" + "/$postId" + "/${PostCommentFormArguments.na}"
)
}
}
fun goToPostDetails(postId: String) {
navigator.navigate {
it.navigate(
"${Routes.Post.route}$postId"
)
}
}
}
| 0
|
Kotlin
|
11
| 24
|
a31e612a63e1dc42ed4cf2f50db90b8613fb5177
| 5,560
|
development_learning
|
MIT License
|
app/src/main/java/jp/funmake/example/store/ManageSpaceActivity.kt
|
nosix
| 571,445,795
| false
| null |
package jp.funmake.example.store
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
// TODO research this
class ManageSpaceActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manage_space)
}
}
| 0
|
Kotlin
|
0
| 0
|
2cb1b98ebdbfd3fd1152ce7230c28882dff6ade8
| 342
|
android-store-example
|
Apache License 2.0
|
source/model/src/main/kotlin/de/webis/webisstud/thesis/reimer/model/Document.kt
|
webis-de
| 261,803,727
| false
|
{"Kotlin": 235840, "Jupyter Notebook": 43040, "Java": 7525}
|
package de.webis.webisstud.thesis.reimer.model
interface Document : Comparable<Document> {
val topic: Topic<*>
val id: String
override fun compareTo(other: Document) = id.compareTo(other.id)
fun asMetadata(): Metadata {
return object : Metadata {
override val documentId = id
override val topicId = topic.id
}
}
interface Metadata {
val documentId: String
val topicId: String
}
}
| 0
|
Kotlin
|
2
| 2
|
34cbd80dad107b6a7cd57b6a740d35f76013984a
| 468
|
sigir20-sampling-bias-due-to-near-duplicates-in-learning-to-rank
|
MIT License
|
src/model/Character.kt
|
mikhalchenko-alexander
| 125,385,896
| false
| null |
package model
interface Character {
val id: Int
val name: String
val status: String
val species: String
val type: String
val gender: String
val origin: LocationShort
val location: LocationShort
val image: String
val episode: Array<String>
val url: String
val created: String
}
| 0
|
Kotlin
|
0
| 0
|
8ee8633a53d74f86e8733ca61e1e4999218d1b97
| 326
|
rick-and-morty-api-ui
|
Apache License 2.0
|
intellij-idea/src/main/kotlin/com/itangcent/intellij/config/resource/FileResource.kt
|
Earth-1610
| 178,314,657
| false
|
{"Kotlin": 1216447, "Java": 35079, "Shell": 3153}
|
package com.itangcent.intellij.config.resource
import com.itangcent.common.logger.Log
import com.itangcent.common.utils.SystemUtils
import com.itangcent.intellij.config.ConfigReader
import com.itangcent.intellij.context.ActionContext
import java.io.File
import java.io.InputStream
import java.net.URL
import java.util.regex.Pattern
class FileResource(val path: String) : Resource() {
companion object : Log()
private val currPath: String? =
ActionContext.getContext()
?.instance(ConfigReader::class)
?.first("_curr_path")
private var resolveFile: File? = null
override val reachable: Boolean
get() = asFile()?.takeIf { it.exists() && it.isFile } != null
fun asFile(): File? {
if (resolveFile != null) {
return resolveFile
}
resolveFile = SysFileResolve.adaptive().resolveFile(path, currPath)
LOG.debug("$path resolved as ${resolveFile?.path}")
return resolveFile?.takeIf { it.exists() }
}
override val url: URL
get() {
return File(path).toURI().toURL()
}
override val inputStream: InputStream?
get() {
return asFile()?.inputStream()
}
}
private enum class SysFileResolve {
OS_SYS_FILE_RESOLVE {
override fun separator(): String {
return "/"
}
override fun isAbsolute(path: String): Boolean {
return path.startsWith("/")
}
override fun asFile(path: String): File {
return super.asFile(path).takeIf { it.exists() }
?: super.asFile(path.replace('\\', '/'))
}
},
WIN_SYS_FILE_RESOLVE {
override fun separator(): String {
return "\\"
}
override fun isAbsolute(path: String): Boolean {
return Pattern.matches("[a-zA-Z]+:.*?", path)
}
override fun asFile(path: String): File {
return super.asFile(path).takeIf { it.exists() }
?: super.asFile(path.replace('/', '\\'))
}
};
abstract fun isAbsolute(path: String): Boolean
open fun separator(): String {
return File.separator
}
fun resolveFile(path: String, currPath: String?): File? {
if (isAbsolute(path)) {
return asFile(path)
}
if (path.startsWith('~')) {
val home = SystemUtils.userHome
return asFile(home.removeSuffix(separator()) + separator() + path.substring(1))
}
var p = path
var cp = currPath ?: ""
while (true) {
if (p.startsWith("../")) {//goto parent directory
cp = cp.substringBeforeLast(separator())
p = p.substring("../".length)
} else if (p.startsWith("./")) {//current directory
if (cp.isBlank()) return File(p).takeIf { it.exists() }
p = p.substring("./".length)
}
break
}
return asFile(cp.removeSuffix(separator()) + separator() + p.removePrefix(separator()))
}
open fun asFile(path: String): File {
return File(path)
}
companion object : Log() {
private var adaptiveSysFileResolve: SysFileResolve? = null
fun adaptive(): SysFileResolve {
if (adaptiveSysFileResolve == null) {
val separator = File.separator
adaptiveSysFileResolve = values().firstOrNull { it.separator() == separator } ?: OS_SYS_FILE_RESOLVE
}
return adaptiveSysFileResolve!!
}
}
}
| 0
|
Kotlin
|
5
| 8
|
af802e7ea26b233610c9d35af89365c93f48158b
| 3,597
|
intellij-kotlin
|
Apache License 2.0
|
intellij-idea/src/main/kotlin/com/itangcent/intellij/config/resource/FileResource.kt
|
Earth-1610
| 178,314,657
| false
|
{"Kotlin": 1216447, "Java": 35079, "Shell": 3153}
|
package com.itangcent.intellij.config.resource
import com.itangcent.common.logger.Log
import com.itangcent.common.utils.SystemUtils
import com.itangcent.intellij.config.ConfigReader
import com.itangcent.intellij.context.ActionContext
import java.io.File
import java.io.InputStream
import java.net.URL
import java.util.regex.Pattern
class FileResource(val path: String) : Resource() {
companion object : Log()
private val currPath: String? =
ActionContext.getContext()
?.instance(ConfigReader::class)
?.first("_curr_path")
private var resolveFile: File? = null
override val reachable: Boolean
get() = asFile()?.takeIf { it.exists() && it.isFile } != null
fun asFile(): File? {
if (resolveFile != null) {
return resolveFile
}
resolveFile = SysFileResolve.adaptive().resolveFile(path, currPath)
LOG.debug("$path resolved as ${resolveFile?.path}")
return resolveFile?.takeIf { it.exists() }
}
override val url: URL
get() {
return File(path).toURI().toURL()
}
override val inputStream: InputStream?
get() {
return asFile()?.inputStream()
}
}
private enum class SysFileResolve {
OS_SYS_FILE_RESOLVE {
override fun separator(): String {
return "/"
}
override fun isAbsolute(path: String): Boolean {
return path.startsWith("/")
}
override fun asFile(path: String): File {
return super.asFile(path).takeIf { it.exists() }
?: super.asFile(path.replace('\\', '/'))
}
},
WIN_SYS_FILE_RESOLVE {
override fun separator(): String {
return "\\"
}
override fun isAbsolute(path: String): Boolean {
return Pattern.matches("[a-zA-Z]+:.*?", path)
}
override fun asFile(path: String): File {
return super.asFile(path).takeIf { it.exists() }
?: super.asFile(path.replace('/', '\\'))
}
};
abstract fun isAbsolute(path: String): Boolean
open fun separator(): String {
return File.separator
}
fun resolveFile(path: String, currPath: String?): File? {
if (isAbsolute(path)) {
return asFile(path)
}
if (path.startsWith('~')) {
val home = SystemUtils.userHome
return asFile(home.removeSuffix(separator()) + separator() + path.substring(1))
}
var p = path
var cp = currPath ?: ""
while (true) {
if (p.startsWith("../")) {//goto parent directory
cp = cp.substringBeforeLast(separator())
p = p.substring("../".length)
} else if (p.startsWith("./")) {//current directory
if (cp.isBlank()) return File(p).takeIf { it.exists() }
p = p.substring("./".length)
}
break
}
return asFile(cp.removeSuffix(separator()) + separator() + p.removePrefix(separator()))
}
open fun asFile(path: String): File {
return File(path)
}
companion object : Log() {
private var adaptiveSysFileResolve: SysFileResolve? = null
fun adaptive(): SysFileResolve {
if (adaptiveSysFileResolve == null) {
val separator = File.separator
adaptiveSysFileResolve = values().firstOrNull { it.separator() == separator } ?: OS_SYS_FILE_RESOLVE
}
return adaptiveSysFileResolve!!
}
}
}
| 0
|
Kotlin
|
5
| 8
|
af802e7ea26b233610c9d35af89365c93f48158b
| 3,597
|
intellij-kotlin
|
Apache License 2.0
|
game/src/main/kotlin/io/posidon/rpg/client/world/Composition.kt
|
zaguragit
| 365,525,969
| false
|
{"Kotlin": 139728, "GLSL": 19421}
|
package io.posidon.rpg.client.world
/**
* Percentages of elements (1f = 1%)
*/
data class Composition(
val redMatter: Float, // energy conduction
val greenMatter: Float, // energy production, silicone
val blueMatter: Float, // energy production
val stringMatter: Float, // building
) {
init {
val sum = (greenMatter * 10f + redMatter * 10f + stringMatter * 10f + blueMatter * 10f) / 10f
if (sum != 100f)
throw IllegalStateException("All the elements in a composition must add up to 100, but the sum is $sum, (r: $redMatter, g: $greenMatter, b: $blueMatter, s: $stringMatter)")
}
}
| 0
|
Kotlin
|
0
| 0
|
4ef6bffe2f857e8ade0cdc34d4c8a59778bafb28
| 636
|
rpg-engine
|
Apache License 2.0
|
randomizer/src/main/java/com/chrisjanusa/randomizer/filter_boolean/updaters/OpenNowUpdater.kt
|
chrisjanusa
| 209,855,968
| false
| null |
package com.chrisjanusa.randomizer.filter_boolean.updaters
import com.chrisjanusa.base.interfaces.BaseUpdater
import com.chrisjanusa.base.models.RandomizerState
import java.util.HashSet
class OpenNowUpdater(private val openNow: Boolean) : BaseUpdater {
override fun performUpdate(prevState: RandomizerState): RandomizerState {
return prevState.copy(openNowSelected = openNow, restaurantCacheValid = false, restaurantsSeenRecently = HashSet())
}
}
| 1
|
Kotlin
|
0
| 0
|
4c675b740ccf2cf29630bf82c50c04ed5113249c
| 464
|
RandomRestaurantKotlin
|
MIT License
|
kotlin-remix-run-router/src/jsMain/generated/remix/run/router/BaseNavigateOptions.kt
|
JetBrains
| 93,250,841
| false
| null |
package remix.run.router
sealed external interface BaseNavigateOptions : BaseNavigateOrFetchOptions {
var replace: Boolean?
var state: Any?
var fromRouteId: String?
}
| 29
| null |
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 181
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/amp/bemobile/data/features/transactions/repository/TransactionRepositoryImpl.kt
|
alvaromarco
| 414,525,714
| false
| null |
package com.amp.bemobile.data.features.transactions.repository
import com.amp.bemobile.data.features.transactions.service.TransactionService
import com.amp.bemobile.domain.core.functional.Either
import com.amp.bemobile.domain.core.functional.Failure
import com.amp.bemobile.domain.core.functional.map
import com.amp.bemobile.domain.features.transactions.TransactionRepository
import com.amp.bemobile.domain.features.transactions.models.RateView
import com.amp.bemobile.domain.features.transactions.models.TransactionView
class TransactionRepositoryImpl(private val service: TransactionService) : TransactionRepository {
override suspend fun getRates(): Either<Failure, List<RateView>> =
service.getRates().map { list -> list.map { it.toView() } }
override suspend fun getTransactions(): Either<Failure, List<TransactionView>> =
service.getTransactions().map { list -> list.map { it.toView() } }
}
| 0
| null |
0
| 0
|
7a29c67b76bf12fdea7ad869c03e77708bb61ac0
| 924
|
BeMobile
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/manageusersapi/resource/prison/UserCaseloadsControllerIntTest.kt
|
ministryofjustice
| 406,273,579
| false
|
{"Kotlin": 604654, "Shell": 7014, "Dockerfile": 1110}
|
package uk.gov.justice.digital.hmpps.manageusersapi.resource.prison
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor
import com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.web.reactive.function.BodyInserters.fromValue
import uk.gov.justice.digital.hmpps.manageusersapi.integration.IntegrationTestBase
class UserCaseloadsControllerIntTest : IntegrationTestBase() {
@Nested
inner class GetCaseloads {
@Test
fun `access forbidden when no authority`() {
webTestClient.get().uri("/prisonusers/bob/caseloads")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `access forbidden when no role`() {
webTestClient.get().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf()))
.exchange()
.expectStatus().isForbidden
}
@Test
fun `access forbidden when wrong role`() {
webTestClient.get().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG_ROLE")))
.exchange()
.expectStatus().isForbidden
}
@Test
fun ` get user caseloads`() {
nomisApiMockServer.stubGetUserCaseloads("bob")
webTestClient.get().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf("ROLE_MAINTAIN_ACCESS_ROLES_ADMIN")))
.exchange()
.expectStatus().isOk
.expectBody()
.jsonPath("$.username").isEqualTo("bob")
.jsonPath("$.caseloads[0].name").isEqualTo("WANDSWORTH (HMP)")
nomisApiMockServer.verify(
getRequestedFor(urlEqualTo("/users/bob/caseloads")),
)
}
}
@Nested
inner class AddCaseloads {
@Test
fun `access forbidden when no authority`() {
webTestClient.post().uri("/prisonusers/bob/caseloads")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `access forbidden when no role`() {
webTestClient.post().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf()))
.body(fromValue(listOf("CASELOAD1", "CASELOAD2")))
.exchange()
.expectStatus().isForbidden
}
@Test
fun `access forbidden when wrong role`() {
webTestClient.post().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG_ROLE")))
.body(fromValue(listOf("CASELOAD1", "CASELOAD2")))
.exchange()
.expectStatus().isForbidden
}
@Test
fun `post user caseloads calls nomis api`() {
nomisApiMockServer.stubPostUserCaseloads("bob", "[\"CASELOAD1\",\"CASELOAD2\"]")
webTestClient.post().uri("/prisonusers/bob/caseloads")
.headers(setAuthorisation(roles = listOf("ROLE_MAINTAIN_ACCESS_ROLES_ADMIN")))
.body(fromValue(listOf("CASELOAD1", "CASELOAD2")))
.exchange()
.expectStatus().isCreated
nomisApiMockServer.verify(
postRequestedFor(urlEqualTo("/users/bob/caseloads"))
.withRequestBody(WireMock.equalToJson("[\"CASELOAD1\",\"CASELOAD2\"]")),
)
}
}
@Nested
inner class RemoveCaseload {
@Test
fun `access forbidden when no authority`() {
webTestClient.delete().uri("/prisonusers/bob/caseloads/LEI")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `access forbidden when no role`() {
webTestClient.delete().uri("/prisonusers/bob/caseloads/LEI")
.headers(setAuthorisation(roles = listOf()))
.exchange()
.expectStatus().isForbidden
}
@Test
fun `access forbidden when wrong role`() {
webTestClient.delete().uri("/prisonusers/bob/caseloads/LEI")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG_ROLE")))
.exchange()
.expectStatus().isForbidden
}
@Test
fun `remove user caseload calls nomis api`() {
nomisApiMockServer.stubDeleteUserCaseloads("bob", "LEI")
webTestClient.delete().uri("/prisonusers/bob/caseloads/LEI")
.headers(setAuthorisation(roles = listOf("ROLE_MAINTAIN_ACCESS_ROLES_ADMIN")))
.exchange()
.expectStatus().isOk
nomisApiMockServer.verify(WireMock.deleteRequestedFor(urlEqualTo("/users/bob/caseloads/LEI")))
}
}
}
| 4
|
Kotlin
|
0
| 0
|
1d02d86d2d7da5f6de16056c9f32546fd83f9dbb
| 4,478
|
hmpps-manage-users-api
|
MIT License
|
domain/src/main/kotlin/com/ilgiz/kitsu/domain/useCases/FetchSingleAnimeUseCase.kt
|
ilgiz05
| 493,248,856
| false
| null |
package com.ilgiz.kitsu.domain.useCases
import com.ilgiz.kitsu.domain.repositories.AnimeRepository
import javax.inject.Inject
class FetchSingleAnimeUseCase @Inject constructor(
private val animeRepository: AnimeRepository
) {
operator fun invoke(id: String) = animeRepository.fetchAnimeDetails(id)
}
| 0
|
Kotlin
|
0
| 0
|
f9d4b4b9899bc2faa3fc992233c3187774d3d8d8
| 309
|
kitsuApi
|
MIT License
|
EcoSwapAndroid/src/main/java/com/darrenthiores/ecoswap/android/presentation/home/components/CategorySection.kt
|
darrenthiores
| 688,372,873
| false
|
{"Kotlin": 770054, "Swift": 362583}
|
package com.darrenthiores.ecoswap.android.presentation.home.components
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
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 com.darrenthiores.ecoswap.android.R
import com.darrenthiores.ecoswap.android.presentation.components.header.SectionHeader
import com.darrenthiores.ecoswap.android.presentation.components.indicator.PageIndicator
import com.darrenthiores.ecoswap.android.presentation.utils.getIcon
import com.darrenthiores.ecoswap.android.theme.Caption1R
import com.darrenthiores.ecoswap.android.theme.EcoSwapTheme
import com.darrenthiores.ecoswap.domain.core.utils.Constant
import com.darrenthiores.ecoswap.domain.item.model.ItemCategory
import kotlin.math.ceil
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
@Composable
fun CategorySection(
modifier: Modifier = Modifier,
pagerState: PagerState,
viewAll: Boolean = true,
onItemClick: (ItemCategory) -> Unit,
onToggleViewAll: () -> Unit
) {
val pageCount = ceil(Constant.categories.size.toDouble().div(4)).toInt()
Column(
modifier = modifier
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
SectionHeader(
modifier = Modifier
.padding(horizontal = 24.dp),
title = stringResource(id = R.string.item_category),
endAction = if (viewAll) stringResource(id = R.string.view_less) else stringResource(id = R.string.view_all),
onActionClick = onToggleViewAll
)
if (!viewAll) {
HorizontalPager(
modifier = Modifier
.fillMaxWidth(),
state = pagerState,
pageCount = pageCount,
contentPadding = PaddingValues(
horizontal = 24.dp
),
pageSpacing = 24.dp
) { page ->
val index = page + 1
val lastIndex = (index * 4) - 1
val firstIndexCount = (lastIndex + 1 - 4)
val firstIndex = if (firstIndexCount < 0) 0 else firstIndexCount
val categories = if (Constant.categories.size - 1 < lastIndex) {
Constant.categories.slice(
firstIndex until Constant.categories.size
)
} else {
Constant.categories.slice(
firstIndex..lastIndex
)
}
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
categories.forEach { category ->
CategoryItem(
modifier = Modifier
.clickable { onItemClick(category) },
category = category
)
}
}
}
PageIndicator(
pagerState = pagerState,
pageCount = pageCount
)
} else {
FlowRow(
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 24.dp
),
maxItemsInEachRow = 4,
horizontalArrangement = Arrangement.SpaceBetween
) {
Constant.categories.forEach { category ->
CategoryItem(
modifier = Modifier
.padding(bottom = 16.dp)
.clickable { onItemClick(category) },
category = category
)
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
private fun CategorySectionPreview() {
EcoSwapTheme {
val pagerState = rememberPagerState()
CategorySection(
pagerState = pagerState,
onItemClick = { }
) {
}
}
}
@Composable
private fun CategoryItem(
modifier: Modifier = Modifier,
category: ItemCategory
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(4.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.size(70.dp)
.background(
color = MaterialTheme.colors.primary.copy(
alpha = 0.3f
),
shape = CircleShape
),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier
.width(36.dp),
painter = painterResource(id = category.getIcon()),
contentDescription = category.display,
contentScale = ContentScale.FillWidth
)
}
Text(
text = category.display,
style = Caption1R,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
@Preview(
showBackground = true
)
@Composable
private fun CategoryItemPreview() {
EcoSwapTheme {
CategoryItem(
category = Constant.categories[0]
)
}
}
| 0
|
Kotlin
|
0
| 0
|
6da03175466a0458ba4a28392f7371f8a429d4cf
| 6,857
|
EcoSwap
|
MIT License
|
orchestrator/src/main/kotlin/io/github/akmal2409/ets/orchestrator/onboarding/service/RawMediaService.kt
|
akmal2409
| 708,369,158
| false
|
{"Kotlin": 64660, "Java": 37521, "Shell": 530}
|
package io.github.akmal2409.ets.orchestrator.onboarding.service
import io.github.akmal2409.ets.orchestrator.commons.db.OptimisticLockingException
import io.github.akmal2409.ets.orchestrator.config.MessagingProperties
import io.github.akmal2409.ets.orchestrator.onboarding.controller.dto.unboxing.UnboxingCompletedEvent
import io.github.akmal2409.ets.orchestrator.onboarding.domain.*
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.amqp.AmqpException
import org.springframework.amqp.AmqpIOException
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.dao.DataAccessException
import org.springframework.dao.NonTransientDataAccessException
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Clock
import java.util.*
private val logger = KotlinLogging.logger {}
@Service
data class RawMediaService(
val rawMediaRepository: RawMediaRepository,
val rabbitTemplate: RabbitTemplate,
val messagingProperties: MessagingProperties,
val unboxingJobRepository: UnboxingJobRepository,
val clock: Clock
) {
/**
* When raw file is uploaded to a special bucket in S3 with a key
* we need to persist it in the database and automatically trigger unboxing
* job.
*/
@Transactional
fun onboardRawFile(rawFileRequest: RawFileCreateRequest): RawMedia {
val rawMedia = try {
saveNewRawFile(rawFileRequest)
} catch (nonRecoverableDataEx: NonTransientDataAccessException) {
throw InvalidRawFileException(
rawFileRequest.mediaKey,
"Invalid parameters",
nonRecoverableDataEx
)
} catch (recoverableDataEx: DataAccessException) {
throw RawFileOnboardingException(
rawFileRequest.mediaKey,
"Exception when saving",
recoverableDataEx
)
}
beginUnboxingJob(rawMedia)
return rawMedia
}
@Transactional
fun onUnboxingComplete(completedEvent: UnboxingCompletedEvent) {
val media = rawMediaRepository.findByJobId(completedEvent.jobId)
?: throw UnboxingJobNotFoundException("${completedEvent.jobId} was not found")
val (unboxedMedia, job) = media.completeUnboxing(clock, completedEvent.toDomainUnboxedFiles())
rawMediaRepository.update(unboxedMedia)
unboxingJobRepository.update(job)
}
private fun beginUnboxingJob(rawMedia: RawMedia): UnboxingJob {
val (unboxingJob, beginUnboxingEvent) = try {
rawMedia.beginUnboxingJob(clock = clock)
} catch (stateEx: IllegalStateException) {
throw AlreadyUnboxedRawFileException(rawMedia.key)
}
try {
unboxingJobRepository.insert(unboxingJob)
} catch (nonRecoverableDataEx: NonTransientDataAccessException) {
throw InvalidRawFileException(
rawMedia.key,
"Invalid parameters for unboxing job",
nonRecoverableDataEx
)
} catch (recoverableDataEx: DataAccessException) {
throw RawFileOnboardingException(
rawMedia.key,
"Exception when saving unboxing job",
recoverableDataEx
)
}
// TODO: Add retries with resilience4j a circuit breaker
// TODO: whatever fails, needs to go to a retry queue (add header with Retry-Attempt: n and drop if exceeds retries)
try {
rabbitTemplate.convertAndSend(
messagingProperties.rabbitQueues.mediaUnboxingQueue,
beginUnboxingEvent
)
} catch (ioEx: AmqpIOException) {
throw UnboxingJobFailedStartException(
rawMedia.key,
"Could not publish event due to IO exception",
ioEx
)
} catch (amqpEx: AmqpException) {
throw NonRecoverableJobStartException(rawMedia.key, "Cannot start due to misconfiguration", amqpEx)
}
logger.debug { "message=Triggered unboxing job;service=media-unboxer;jobId=${unboxingJob.id};key=${rawMedia.key}" }
return unboxingJob
}
private fun saveNewRawFile(rawFileRequest: RawFileCreateRequest): RawMedia {
val media = RawMedia(rawFileRequest.mediaKey, false, 0)
rawMediaRepository.insert(media)
logger.debug { "message=Saved new raw media ${rawFileRequest.mediaKey};service=postgres;key=${rawFileRequest.mediaKey}" }
return media
}
fun findAll(page: Int, size: Int): Page<RawMedia> = rawMediaRepository.findAll(PageRequest.of(page, size))
fun findById(id: UUID): RawMedia? = rawMediaRepository.findById(id)
}
| 0
|
Kotlin
|
0
| 0
|
c7db2b58ed01bf4b8c574a0049a3bc562aab4961
| 4,918
|
elastic-transcoding-service
|
Apache License 2.0
|
internal-plugins/android-plugin/src/main/kotlin/com/bselzer/gradle/internal/android/library/plugin/AndroidLibraryExtension.kt
|
Woody230
| 638,902,833
| false
| null |
package com.bselzer.gradle.internal.android.library.plugin
import com.bselzer.gradle.internal.android.plugin.AndroidExtension
interface AndroidLibraryExtension : AndroidExtension
| 0
|
Kotlin
|
0
| 0
|
e469fd53064f21d6e374f0f6faa27b757a86b064
| 180
|
GradleExtensions
|
Apache License 2.0
|
src/main/kotlin/com/daimond113/miraculous_miracles/core/AbstractMiraculous.kt
|
daimond113
| 683,141,761
| false
|
{"Kotlin": 194915}
|
package com.daimond113.miraculous_miracles.core
import com.daimond113.miraculous_miracles.MiraculousMiracles
import com.daimond113.miraculous_miracles.state.PlayerState
import com.daimond113.miraculous_miracles.state.ServerState
import net.minecraft.enchantment.Enchantments
import net.minecraft.entity.Entity
import net.minecraft.entity.EquipmentSlot
import net.minecraft.entity.ItemEntity
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.ItemUsageContext
import net.minecraft.nbt.NbtCompound
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.server.world.ServerWorld
import net.minecraft.text.Text
import net.minecraft.util.ActionResult
import net.minecraft.util.Hand
import net.minecraft.util.ItemScatterer
import net.minecraft.util.Rarity
import java.util.*
abstract class AbstractMiraculous(val miraculousType: MiraculousType, slot: ((ItemStack) -> EquipmentSlot)? = null) :
Item(
itemSettingsOf(
rarity = Rarity.EPIC,
fireproof = true,
equipmentSlot = slot,
group = MiraculousMiracles.ITEM_GROUP,
maxDamage = 128
)
) {
companion object {
protected fun getNBT(stack: ItemStack): NbtCompound {
return stack.orCreateNbt.apply {
if (!contains("isHungry")) {
putBoolean("isHungry", false)
}
}
}
fun getCharged(stack: ItemStack): Boolean {
return !getNBT(stack).contains("kwamiUuid")
}
fun setNBT(stack: ItemStack, kwamiUuid: Optional<UUID>? = null, kwamiHungry: Boolean? = null) {
stack.nbt = getNBT(stack).apply {
if (kwamiUuid != null) {
if (kwamiUuid.isPresent) {
putUuid("kwamiUuid", kwamiUuid.get())
} else {
remove("kwamiUuid")
}
}
if (kwamiHungry != null) {
putBoolean("isHungry", kwamiHungry)
}
}
}
fun getOptionalKwamiUuid(stack: ItemStack): UUID? {
return getNBT(stack).let {
if (it.contains("kwamiUuid"))
it.getUuid("kwamiUuid")
else
null
}
}
fun renounceKwami(
stack: ItemStack,
world: ServerWorld
) {
val kwami = getOptionalKwamiUuid(stack)?.let { world.getEntity(it) }
if (kwami !is AbstractKwami) return
renounceKwami(stack, kwami)
}
fun renounceKwami(
stack: ItemStack,
kwami: AbstractKwami
) {
kwami.remove(Entity.RemovalReason.DISCARDED)
setNBT(stack, Optional.empty())
}
}
override fun onItemEntityDestroyed(entity: ItemEntity) {
renounceKwami(entity.stack, entity.world as ServerWorld)
}
override fun useOnBlock(context: ItemUsageContext): ActionResult {
val player = context.player
val itemStack = player?.getStackInHand(context.hand)
val hitPos = context.hitPos
if (itemStack == null || player.world?.server == null) return ActionResult.PASS
var kwamiUuid = getOptionalKwamiUuid(itemStack)
fun spawnKwami() {
val newKwami = MiraculousMiracles.KWAMIS[miraculousType]!!.create(player.world)?.let {
it.updatePosition(hitPos.x, hitPos.y, hitPos.z)
kwamiUuid = it.uuid
it.isHungry = getNBT(itemStack).getBoolean("isHungry")
it.setOwner(player)
it
}
player.world.spawnEntity(newKwami)
}
val playerState = ServerState.getPlayerState(player)
if (kwamiUuid == null) {
spawnKwami()
} else if (
(player.world as ServerWorld).getEntity(kwamiUuid) == null &&
!playerState.activeMiraculous.contains(miraculousType)
) {
spawnKwami()
}
if (kwamiUuid == null) return ActionResult.PASS
setNBT(itemStack, Optional.of(kwamiUuid!!))
return ActionResult.CONSUME
}
override fun postHit(stack: ItemStack, kwami: LivingEntity, attacker: LivingEntity): Boolean {
if (kwami is AbstractKwami &&
kwami.miraculousType == miraculousType &&
kwami.uuid == getOptionalKwamiUuid(stack) &&
attacker.world.server != null &&
attacker is ServerPlayerEntity
) {
PlayerState.sendMessageFrom(
Text.translatable(
"text.miraculous_miracles.renunciation",
Text.translatable("entity.miraculous_miracles.${miraculousType.toString().lowercase()}_kwami")
),
attacker
)
renounceKwami(stack, kwami)
return true
}
return false
}
override fun useOnEntity(stack: ItemStack, user: PlayerEntity, kwami: LivingEntity, hand: Hand): ActionResult {
if (kwami is AbstractKwami &&
kwami.miraculousType == miraculousType &&
user.world.server != null &&
kwami.uuid == getOptionalKwamiUuid(stack) &&
!kwami.isHungry &&
!user.hasStatusEffect(
MiraculousMiracles.TRANSFORMATION_TIME_LEFT_EFFECT
) &&
user is ServerPlayerEntity
) {
if (stack.damage >= stack.maxDamage) {
user.sendMessage(Text.translatable("text.miraculous_miracles.miraculous_too_damaged"), true)
return ActionResult.PASS
}
val playerState = ServerState.getPlayerState(user)
// TODO: Unifications
if (playerState.activeMiraculous.isEmpty()) {
playerState.activeMiraculous[miraculousType] = stack.nbt ?: NbtCompound()
playerState.updateActiveMiraculous(user)
val inventory = user.inventory
val newArmor = MiraculousMiracles.ARMORS[miraculousType]!!.map { armorItem ->
val armorStack = ItemStack(armorItem, 1)
armorStack.addEnchantment(Enchantments.BINDING_CURSE, 1)
armorStack.addEnchantment(Enchantments.VANISHING_CURSE, 1)
armorStack
}
for (i in 0..3) {
val oldArmor = inventory.armor[i]
if (!oldArmor.isEmpty) {
if (!inventory.insertStack(oldArmor)) {
ItemScatterer.spawn(user.world, user.x, user.y, user.z, oldArmor)
}
}
inventory.armor[i] = newArmor[i]
}
PlayerState.sendMessageFrom(
Text.translatable(
"text.miraculous_miracles.${
miraculousType.toString().lowercase()
}.transformation"
),
user
)
kwami.remove(Entity.RemovalReason.DISCARDED)
val weaponStack = ItemStack(MiraculousMiracles.MIRACULOUS_WEAPONS[miraculousType]!!)
weaponStack.addEnchantment(Enchantments.VANISHING_CURSE, 1)
// in spite of returning CONSUME which should stop bubbling, the item's `use` is still called, so we add a small cooldown
user.itemCooldownManager[weaponStack.item] = 15
PlayerState.replaceItemStack(stack, weaponStack, user)
return ActionResult.CONSUME
}
}
return ActionResult.PASS
}
override fun isDamageable(): Boolean {
return false
}
}
| 1
|
Kotlin
|
1
| 0
|
a3f4aeca52df52cf0c65c9e111637d05a26e121d
| 7,987
|
miraculous-miracles
|
MIT License
|
src/main/kotlin/leight/storage/DuplicateEntityException.kt
|
marek-hanzal
| 259,577,282
| false
| null |
package leight.storage
class DuplicateEntityException(message: String, cause: Throwable? = null) : StorageException(message, cause)
| 112
|
Kotlin
|
0
| 1
|
7a485228438c5fb9a61b1862e8164f5e87361e4a
| 133
|
DeRivean
|
Apache License 2.0
|
features/src/main/kotlin/ru/mobileup/features/launchers/ui/upcoming/UpcomingLaunchersComponent.kt
|
MobileUpLLC
| 495,342,634
| false
|
{"Kotlin": 206427}
|
package ru.mobileup.features.launchers.ui.upcoming
import me.aartikov.replica.single.Loadable
import ru.mobileup.features.launchers.ui.LauncherViewData
interface UpcomingLaunchersComponent {
val upcomingLaunchersViewState: Loadable<List<LauncherViewData>>
fun onRetryClick()
}
| 0
|
Kotlin
|
1
| 1
|
717fec2a43e5e9314b7ffe0d3aaa94047b6ca229
| 288
|
Education-Space-Android
|
MIT License
|
app/src/main/java/com/breezebioqempharma/features/meetinglist/api/MeetingRepo.kt
|
DebashisINT
| 836,199,992
| false
|
{"Kotlin": 15543658, "Java": 1026757}
|
package com.breezebioqempharma.features.meetinglist.api
import com.breezebioqempharma.app.Pref
import com.breezebioqempharma.features.meetinglist.model.MeetingListResponseModel
import io.reactivex.Observable
/**
* Created by Saikat on 21-01-2020.
*/
class MeetingRepo(val apiService: MeetingApi) {
fun meetingList(): Observable<MeetingListResponseModel> {
return apiService.getMeetingList(Pref.session_token!!, Pref.user_id!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
4c8d2f61bffcf049b911626940a7d6e7d83eadfd
| 450
|
BioqemPharma
|
Apache License 2.0
|
library/src/main/java/com/github/markowanga/timberloggingtofile/LogManager.kt
|
Murtowski
| 461,476,680
| true
|
{"Kotlin": 20453}
|
package com.github.markowanga.timberloggingtofile
import android.content.Context
import androidx.core.content.ContextCompat
import java.io.File
import java.time.Instant
import java.time.temporal.ChronoUnit
object LogManager {
private const val DEFAULT_LOG_DIRECTORY = "app-logs"
private fun getPrimaryExternalStorage(context: Context): File {
val externalStorageVolumes: Array<out File> =
ContextCompat.getExternalFilesDirs(context, null)
return externalStorageVolumes[0]
}
fun getExternalLogsDirectory(
context: Context,
logDirectory: String = DEFAULT_LOG_DIRECTORY
): File =
File(getPrimaryExternalStorage(context), logDirectory).prepare()
fun getInternalLogsDirectory(
context: Context,
logDirectory: String = DEFAULT_LOG_DIRECTORY
): File =
File(context.filesDir, logDirectory).prepare()
private fun File.prepare() = apply {
if (!this.exists()) {
this.mkdirs()
}
}
fun removeFilesOlderThanDays(daysCount: Long, rootFile: File) {
val minimumBefore = Instant.now().minus(daysCount, ChronoUnit.DAYS)
(rootFile.listFiles()?.toList() ?: listOf())
.filter { it.isFile }
.filter { Instant.ofEpochMilli(it.lastModified()).isBefore(minimumBefore) }
.forEach { it.delete() }
}
}
| 0
| null |
0
| 0
|
2dd5069db156c4f9f9dd992994c6580a3324f1a0
| 1,382
|
timber-logging-to-file
|
Apache License 2.0
|
app/src/test/java/com/example/macropay/core/Flow.kt
|
salvadormaurilio
| 805,100,814
| false
|
{"Kotlin": 84128}
|
package com.example.macropay.core
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
suspend fun <T> Flow<T>.collectAndCancel(delay: Long = DELAY_FLOW) {
coroutineScope {
val job = launch {
this@collectAndCancel.collect()
}
delay(delay)
job.cancel()
}
}
private const val DELAY_FLOW = 250L
| 0
|
Kotlin
|
0
| 1
|
985f4e38d6cd50187458cc0ec2230558d7a68565
| 474
|
MacroPay-Challenge
|
Apache License 2.0
|
app/src/main/kotlin/org/jw/warehousecontrol/presentation/viewmodel/MenuViewModel.kt
|
anandacamara
| 739,857,108
| false
|
{"Kotlin": 89174}
|
package org.jw.warehousecontrol.presentation.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.database.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.jw.warehousecontrol.domain.model.ItemEntity
import org.jw.warehousecontrol.domain.repository.SavedItemsRepository
import org.jw.warehousecontrol.presentation.model.state.MenuState
/**
* @author <NAME>
*/
internal class MenuViewModel(
private val repository: SavedItemsRepository
) : ViewModel() {
private val databaseRef: DatabaseReference =
FirebaseDatabase.getInstance().reference.child(ITEMS_DATABASE_REFERENCE)
private val _stateFlow =
MutableStateFlow<MenuState>(MenuState.None)
val stateFlow: StateFlow<MenuState>
get() = _stateFlow
fun refreshItems() = viewModelScope.launch {
repository.cleanSavedItemsDatabase()
databaseRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {
val entity = it.getValue(ItemEntity::class.java)
entity?.let { item -> saveItem(item) }
}
_stateFlow.value = MenuState.Success
}
override fun onCancelled(databaseError: DatabaseError) {
_stateFlow.value = MenuState.Failure
}
})
}
private fun saveItem(item: ItemEntity) = viewModelScope.launch {
repository.saveItems(item)
}
companion object {
private const val ITEMS_DATABASE_REFERENCE = "items"
}
}
| 0
|
Kotlin
|
0
| 0
|
5f8afefddc77fd5cd083da067816479ca5b84dcc
| 1,743
|
warehouse_control
|
MIT License
|
composeApp/src/commonMain/kotlin/data/mapper/PhotoCreatorMapper.kt
|
dalafiarisamuel
| 820,153,053
| false
| null |
package data.mapper
import data.model.remote.UnsplashUser
import data.model.ui.PhotoCreator
class PhotoCreatorMapper : UIModelMapper<UnsplashUser, PhotoCreator>() {
override fun mapToUI(entity: UnsplashUser): PhotoCreator {
return with(entity) {
PhotoCreator(name, username, attributionUrl)
}
}
override fun mapFromUI(model: PhotoCreator): UnsplashUser {
throw Exception("Doesn't work that way")
}
}
| 0
| null |
2
| 7
|
f51a1c1c7490d07f742591f76db5bfa0312c6e47
| 454
|
Unsplash-KMP
|
MIT License
|
app/src/main/java/com/example/gymlog/ui/auth/authclient/UserCredentials.kt
|
LucasMelll0
| 635,043,401
| false
|
{"Kotlin": 350707}
|
package com.example.gymlog.ui.auth.authclient
data class UserCredentials(
val email: String,
val password: String,
val userName: String? = null
)
| 0
|
Kotlin
|
0
| 1
|
7ab200245fbd83e1401c338ee81216e07d8e206f
| 158
|
GymLog
|
Apache License 2.0
|
src/main/kotlin/model/Version.kt
|
steep-wms
| 237,438,539
| false
|
{"Kotlin": 1539171, "JavaScript": 233382, "SCSS": 38483, "Shell": 1830, "Dockerfile": 1598, "PLpgSQL": 1198}
|
package model
import java.util.Calendar
/**
* Steep version info
* @param version Steep's version number
* @param build the build ID from the CI server
* @param commit the Git commit this build was based on
* @param timestamp the timestamp when the build was executed
* @author <NAME>
*/
data class Version(
val version: String,
val build: String,
val commit: String,
val timestamp: Calendar
)
| 37
|
Kotlin
|
5
| 38
|
8270b146664463b962e0c7387cf4f80d44b95e7b
| 419
|
steep
|
Apache License 2.0
|
src/main/kotlin/ru/quipy/dto/Dtos.kt
|
DimonTurbina
| 708,906,169
| false
|
{"Kotlin": 35461, "Dockerfile": 354}
|
package ru.quipy.dto
import java.util.UUID
data class ProjectDto(
val id: UUID,
val title: String,
val createdAt: String,
val creatorId: UUID,
val tasks: List<TaskDto>,
val tags: List<TagDto>
)
data class ProjectsDto(
val id: UUID,
val title: String,
val createdAt: String,
val creatorId: UUID
)
data class TaskDto(
val id: UUID,
val name: String,
val description: String,
val tagId: UUID,
val createdAt: String
)
data class TagDto(
val id: UUID,
val name: String,
val createdAt: String
)
| 0
|
Kotlin
|
0
| 0
|
02f38589df28ee90d18e32b19a9bfa3a6a4973be
| 564
|
is-ppo
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/bold/arrowsaction/Scale.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.bold.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.bold.ArrowsActionGroup
val ArrowsActionGroup.Scale: ImageVector
get() {
if (_scale != null) {
return _scale!!
}
_scale = Builder(
name = "Scale", 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(15.9062f, 2.0f)
curveTo(15.9062f, 2.4142f, 16.242f, 2.75f, 16.6562f, 2.75f)
horizontalLineTo(20.1893f)
lineTo(12.75f, 10.1893f)
verticalLineTo(8.0f)
curveTo(12.75f, 7.5858f, 12.4142f, 7.25f, 12.0f, 7.25f)
curveTo(11.5858f, 7.25f, 11.25f, 7.5858f, 11.25f, 8.0f)
verticalLineTo(12.0f)
curveTo(11.25f, 12.4142f, 11.5858f, 12.75f, 12.0f, 12.75f)
horizontalLineTo(16.0f)
curveTo(16.4142f, 12.75f, 16.75f, 12.4142f, 16.75f, 12.0f)
curveTo(16.75f, 11.5858f, 16.4142f, 11.25f, 16.0f, 11.25f)
horizontalLineTo(13.8107f)
lineTo(21.25f, 3.8107f)
verticalLineTo(7.3438f)
curveTo(21.25f, 7.758f, 21.5858f, 8.0938f, 22.0f, 8.0938f)
curveTo(22.4142f, 8.0938f, 22.75f, 7.758f, 22.75f, 7.3438f)
verticalLineTo(2.0f)
curveTo(22.75f, 1.5858f, 22.4142f, 1.25f, 22.0f, 1.25f)
horizontalLineTo(16.6562f)
curveTo(16.242f, 1.25f, 15.9062f, 1.5858f, 15.9062f, 2.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(19.7516f, 7.4303f)
curveTo(19.797f, 8.6297f, 20.7812f, 9.5887f, 21.9904f, 9.5937f)
curveTo(22.0f, 10.3198f, 22.0f, 11.1187f, 22.0f, 12.0f)
curveTo(22.0f, 16.714f, 22.0f, 19.0711f, 20.5355f, 20.5355f)
curveTo(19.0711f, 22.0f, 16.714f, 22.0f, 12.0f, 22.0f)
curveTo(7.286f, 22.0f, 4.9289f, 22.0f, 3.4645f, 20.5355f)
curveTo(2.0f, 19.0711f, 2.0f, 16.714f, 2.0f, 12.0f)
curveTo(2.0f, 7.286f, 2.0f, 4.9289f, 3.4645f, 3.4645f)
curveTo(4.9289f, 2.0f, 7.286f, 2.0f, 12.0f, 2.0f)
curveTo(12.8813f, 2.0f, 13.6802f, 2.0f, 14.4063f, 2.0096f)
curveTo(14.4113f, 3.2188f, 15.3703f, 4.203f, 16.5697f, 4.2484f)
lineTo(13.9468f, 6.8712f)
curveTo(13.5572f, 6.2008f, 12.8313f, 5.75f, 12.0f, 5.75f)
curveTo(10.7574f, 5.75f, 9.75f, 6.7574f, 9.75f, 8.0f)
verticalLineTo(12.0f)
curveTo(9.75f, 13.2426f, 10.7574f, 14.25f, 12.0f, 14.25f)
horizontalLineTo(16.0f)
curveTo(17.2426f, 14.25f, 18.25f, 13.2426f, 18.25f, 12.0f)
curveTo(18.25f, 11.1687f, 17.7992f, 10.4428f, 17.1288f, 10.0532f)
lineTo(19.7516f, 7.4303f)
close()
}
}
.build()
return _scale!!
}
private var _scale: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 4,062
|
SolarIconSetAndroid
|
MIT License
|
app/src/main/java/com/robowatch/util/OnBoardingPage.kt
|
Saeb0x
| 661,292,932
| false
| null |
package com.robowatch.util
import androidx.annotation.DrawableRes
import com.robowatch.R
sealed class OnBoardingPage(
@DrawableRes
val image: Int,
val title: String,
val description: String
) {
object First : OnBoardingPage(
image = R.drawable.first,
title = "Live Feed Stream",
description = "With RoboWatch, you can remotely see what's happening in your home, office, or any other place you want to monitor!"
)
object Second : OnBoardingPage(
image = R.drawable.second,
title = "Manual Control",
description = "With the Manual Control feature, you can take full control of your robot's movement and explore your environment in real-time!"
)
object Third : OnBoardingPage(
image = R.drawable.third,
title = "Alerts and Notifications",
description = "With the Alerts and Notifications feature, you can receive real-time updates about what's happening in your environment!"
)
}
| 0
|
Kotlin
|
0
| 0
|
d7cc3c8fd0330d3a42b6164c562f31bf4659cbca
| 993
|
RoboWatch
|
Apache License 2.0
|
base/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/base/http/EntityType.kt
|
Wavesonics
| 499,367,913
| false
|
{"Kotlin": 1290354, "Swift": 32452, "CSS": 2064, "Ruby": 1579, "Shell": 361}
|
package com.darkrockstudios.apps.hammer.base.http
enum class EntityType {
Scene, Note, TimelineEvent, EncyclopediaEntry, SceneDraft
}
| 14
|
Kotlin
|
7
| 99
|
2feba4da350977e6eac5fdf07b3be644ee255b7a
| 135
|
hammer-editor
|
MIT License
|
core/data/local/src/main/java/com/fappslab/rickandmortygraphql/core/data/local/prefs/DataPrefs.kt
|
F4bioo
| 585,168,438
| false
| null |
package com.fappslab.rickandmortygraphql.core.data.local.prefs
import android.content.Context
import android.content.SharedPreferences
class DataPrefs(
private val context: Context,
private val prefsName: String
) {
private val prefs by lazy {
context.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
}
fun create(): SharedPreferences = prefs
}
| 0
|
Kotlin
|
0
| 0
|
b2a46bb919d7159c8417832a731798fdb9d159e9
| 382
|
RickAndMorty-GraphQL
|
MIT License
|
gaia-sdk-java/gaia-sdk-core/src/test/kotlin/gaia/sdk/core/jwt/JWTSkillTest.kt
|
leftshiftone
| 218,051,248
| false
|
{"Python": 597076, "TypeScript": 553203, "Kotlin": 517386, "JavaScript": 6976, "ANTLR": 2281}
|
package gaia.sdk.core.jwt
import gaia.sdk.GaiaCredentials
import gaia.sdk.core.AuthorizationTestHelper
import gaia.sdk.core.SkillTest
import org.junit.jupiter.api.Disabled
class JWTSkillTest : SkillTest(){
override fun retrieveCredentials() : GaiaCredentials {
return AuthorizationTestHelper.getValidJWTCredentials()
}
}
| 8
|
Python
|
2
| 1
|
10190c1de4b2b5f1d4a5f014602c4ccc5c11bee4
| 340
|
gaia-sdk
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/adjustments/api/error/ApiValidationException.kt
|
ministryofjustice
| 607,762,818
| false
|
{"Kotlin": 388997, "Shell": 1421, "Dockerfile": 1397}
|
package uk.gov.justice.digital.hmpps.adjustments.api.error
class ApiValidationException(
override var message: String,
) : Exception(message)
| 2
|
Kotlin
|
0
| 0
|
12b74b0560bfc6e4557b2f1d48794725dc530ffb
| 145
|
hmpps-adjustments-api
|
MIT License
|
app/src/main/java/com/dluvian/nozzle/ui/app/views/profileList/ProfileListRoute.kt
|
dluvian
| 645,936,540
| false
|
{"Kotlin": 600976}
|
package com.dluvian.nozzle.ui.app.views.profileList
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import com.dluvian.nozzle.data.profileFollower.IProfileFollower
import com.dluvian.nozzle.ui.app.navigation.PostCardLambdas
@Composable
fun ProfileListRoute(
profileListViewModel: ProfileListViewModel,
profileFollower: IProfileFollower,
postCardLambdas: PostCardLambdas,
onGoBack: () -> Unit,
) {
val isRefreshing by profileListViewModel.isRefreshing.collectAsState()
val profilesFlow by profileListViewModel.profiles.collectAsState()
val profiles by profilesFlow.collectAsState()
val forceFollowed by profileFollower.getForceFollowedState()
val type by profileListViewModel.type
val pubkey by profileListViewModel.pubkey
val adjustedProfiles = remember(forceFollowed, profiles) {
profiles.map { it.copy(isFollowedByMe = forceFollowed[it.pubkey] ?: it.isFollowedByMe) }
}
ProfileListScreen(
profiles = adjustedProfiles,
pubkey = pubkey,
isRefreshing = isRefreshing,
type = type,
onFollow = postCardLambdas.onFollow,
onUnfollow = postCardLambdas.onUnfollow,
onLoadMore = profileListViewModel.onLoadMore,
onSubscribeToUnknowns = profileListViewModel.onSubscribeToUnknowns,
onNavigateToProfile = postCardLambdas.navLambdas.onNavigateToProfile,
onGoBack = onGoBack
)
}
| 5
|
Kotlin
|
3
| 28
|
a1f9bebd460de48dfa69f75433b9ddbc9447537e
| 1,536
|
Nozzle
|
MIT License
|
app/src/main/java/com/app/uiuxsamples/materialactionbar/MaterialActionBarSampleActivity.kt
|
rastogitech
| 134,158,496
| false
|
{"Kotlin": 30378}
|
package com.app.uiuxsamples.materialactionbar
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.app.uiuxsamples.BaseActivity
import com.app.uiuxsamples.R
import kotlinx.android.synthetic.main.activity_material_action_bar_sample.*
/**
* Copyright 2018 Rahul Rastogi. All Rights Reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
class MaterialActionBarSampleActivity : BaseActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_material_action_bar_sample)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
/**
* In CollapsingToolbarLayout:
*
* 1. app:layout_scrollFlags="scroll|enterAlways": To collapse action bar fully on scroll up
* and expand immediately on scroll down.
*
* 2. app:layout_scrollFlags="scroll|enterAlwaysCollapsed": To collapse action bar fully on scroll up
* and doesn't expand until the whole scrollable content is visible.
*
* 3. app:layout_scrollFlags="scroll|exitUntilCollapsed": If CollapsingToolbarLayout height
* is larger than height of Toolbar then action bar collapses on scrolling up to the height of
* Toolbar only and doesn't expand on scrolling down until whole scrollable content is visible.
*
* 4. app:layout_scrollFlags="scroll|snap": If CollapsingToolbarLayout height
* is larger than height of Toolbar then action bar collapses fully on scrolling up
* and doesn't expands on scrolling down until whole scrollable content is visible.
*/
scrolling_action_bar_with_header_tabs.setOnClickListener(this)
scrolling_action_bar_at_last_scroll.setOnClickListener(this)
big_scrolling_action_bar_at_last_scroll.setOnClickListener(this)
big_scrolling_action_bar_until_collapsed.setOnClickListener(this)
parallax_action_bar.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.scrolling_action_bar_with_header_tabs ->
startActivity(Intent(this, ScrollingActionBarImmediateScrollWithHeaderTabActivity::class.java))
R.id.scrolling_action_bar_at_last_scroll ->
startActivity(Intent(this, ScrollingActionBarAtLastScrollActivity::class.java))
R.id.big_scrolling_action_bar_at_last_scroll ->
startActivity(Intent(this, BigScrollingActionBarAtLastScrollActivity::class.java))
R.id.big_scrolling_action_bar_until_collapsed ->
startActivity(Intent(this, BigScrollingActionBarUntilCollapsedActivity::class.java))
R.id.parallax_action_bar ->
startActivity(Intent(this, ParallaxScrollingBarActivity::class.java))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
ce85e02f6fe6b89848c8a58ef034b6230c4fec31
| 3,431
|
UI-UX-Android-Samples
|
Apache License 2.0
|
websocket/websocket-core/src/main/kotlin/co/nilin/opex/websocket/core/inout/QueryOrderRequest.kt
|
opexdev
| 370,411,517
| false
|
{"Kotlin": 1443488, "HTML": 43145, "Java": 19673, "PLpgSQL": 17262, "Shell": 7915, "Dockerfile": 5680, "HCL": 823}
|
package co.nilin.opex.websocket.core.inout
data class QueryOrderRequest(
val symbol: String,
val orderId: Long?,
val origClientOrderId: String?
)
| 23
|
Kotlin
|
13
| 23
|
9c58721f0df3e8ae21f8c60adba830e5091901d0
| 158
|
core
|
MIT License
|
src/main/kotlin/com/w3bshark/newsfeed/web/PostController.kt
|
TylerMcCraw
| 114,279,637
| false
| null |
package com.w3bshark.newsfeed.web
import com.w3bshark.newsfeed.data.User
import com.w3bshark.newsfeed.data.source.IFriendRelationshipRepository
import com.w3bshark.newsfeed.data.source.IPostRepository
import com.w3bshark.newsfeed.data.source.IUserRepository
import org.joda.time.DateTime
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
/**
* Rest Controller for Post-specific API endpoints
*/
@RestController
class PostController @Autowired constructor(
val postRepo: IPostRepository,
val userRepo: IUserRepository,
val friendsRepo: IFriendRelationshipRepository
) {
/**
* Our main NewsFeed API
*
* Normally, this wouldn't have User ID built within the URL path,
* but we're using this to quickly prototype and test our different users
*
* @param count - maximum limit of # of items to return
* @param sinceId - ID of post to be used as an ending point in a chronological search
* (in other words - get me the posts that have been created since this particular Post ID)
* @param maxId - ID of post to be used as a starting point in a chronological search
* (in other words - get me the next several posts that have occurred after this particular Post ID)
*/
@GetMapping("/{userId}/feed")
fun userFeed(@PathVariable(value = "userId") userId: String,
@RequestParam(value = "count", defaultValue = "20", required = false) count: Int,
@RequestParam(value = "since_id", required = false) sinceId: Int?,
@RequestParam(value = "max_id", required = false) maxId: Int?): Iterable<NewsFeedPost>? {
val userIdInt: Int = try {
userId.toInt()
} catch (e: NumberFormatException) {
// TODO throw fatal error
0
}
val user = userRepo.find(userIdInt) ?: return listOf() //TODO throw fatal error
// Get the user's friends
val friendIds = friendsRepo.findFriendsForUser(userIdInt)
val userIds = mutableListOf<Int>()
userIds.addAll(friendIds)
// Include current user in posts list
userIds.add(user.id!!)
// Get user map - ID -> User object
val friendsMap = userRepo.findUsersForIds(userIds)
when {
sinceId != null -> {
// Get newer posts ending at post with ID == sinceId
val mostRecentSyncedPost = postRepo.find(sinceId)
mostRecentSyncedPost?.let {
return postRepo.findPostsForUserIds(userIds, count, endAt = DateTime(it.createdAt))
.map {
NewsFeedPost(it.id!!, it.createdAt, it.createdByUserId, it.text, it.imageUrl, it.link,
friendsMap[it.createdByUserId] ?: User())
}
} ?: return listOf()
}
maxId != null -> {
// Get older posts starting at post with ID == maxId
val oldestSyncedPost = postRepo.find(maxId)
oldestSyncedPost?.let {
return postRepo.findPostsForUserIds(userIds, count, startAt = DateTime(it.createdAt))
.map {
NewsFeedPost(it.id!!, it.createdAt, it.createdByUserId, it.text, it.imageUrl, it.link,
friendsMap[it.createdByUserId] ?: User())
}
} ?: return listOf()
}
else ->
// Get all posts from friends
return postRepo.findPostsForUserIds(userIds, count)
.map {
NewsFeedPost(it.id!!, it.createdAt, it.createdByUserId, it.text, it.imageUrl, it.link,
friendsMap[it.createdByUserId] ?: User())
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2f078ff41087076d8ce6116b99f8c9fcb934b38c
| 4,175
|
spring-newsfeed-api
|
Apache License 2.0
|
app/src/main/java/com/dedeandres/movieapp/presenter/movie/movielist/adapter/MovieListAdapter.kt
|
dedeandress
| 373,596,520
| false
| null |
package com.dedeandres.movieapp.presenter.movie.movielist.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.dedeandres.movieapp.databinding.ItemMoviePosterBinding
import com.dedeandres.movieapp.presenter.movie.movielist.entity.MovieResult
import timber.log.Timber
class MovieListAdapter : RecyclerView.Adapter<MovieListAdapter.ViewHolder>() {
private val items: ArrayList<MovieResult> = ArrayList()
private var onItemClickListener: OnItemClickListener? = null
init {
Timber.d("MovieListAdapter init")
}
fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
this.onItemClickListener = onItemClickListener
}
fun bind(items: List<MovieResult>) {
this.items.clear()
if (this.items.isEmpty()) {
this.items.addAll(items)
Timber.d("MovieListAdapter bind: ${this.items}")
}
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemBinding =
ItemMoviePosterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.bindMovie(item)
}
override fun getItemCount(): Int = items.size
interface OnItemClickListener {
fun onMovieItemClick(movieItem: MovieResult)
}
inner class ViewHolder(private val itemBinding: ItemMoviePosterBinding) :
RecyclerView.ViewHolder(itemBinding.root) {
fun bindMovie(movieItem: MovieResult) {
itemBinding.tvMovieTitle.text = movieItem.originalTitle
itemBinding.tvRating.text = movieItem.voteAverage
Glide.with(itemBinding.root)
.load("https://image.tmdb.org/t/p/original" + movieItem.posterPath)
.into(itemBinding.ivPoster)
itemView.setOnClickListener {
onItemClickListener?.onMovieItemClick(movieItem)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
28cbe0a80321fa7fd5abb0d9c3d0724d69d1e6e0
| 2,195
|
movie_app_android
|
MIT License
|
module/parser/src/commonMain/kotlin/org/cru/godtools/shared/tool/parser/model/Tabs.kt
|
CruGlobal
| 310,338,913
| false
| null |
package org.cru.godtools.shared.tool.parser.model
import org.ccci.gto.support.androidx.annotation.RestrictTo
import org.ccci.gto.support.androidx.annotation.RestrictToScope
import org.cru.godtools.shared.tool.parser.model.AnalyticsEvent.Companion.parseAnalyticsEvents
import org.cru.godtools.shared.tool.parser.model.AnalyticsEvent.Trigger
import org.cru.godtools.shared.tool.parser.xml.XmlPullParser
import org.cru.godtools.shared.tool.parser.xml.parseChildren
private const val XML_TAB = "tab"
private const val XML_LABEL = "label"
class Tabs : Content {
internal companion object {
internal const val XML_TABS = "tabs"
}
val tabs: List<Tab>
override val tips get() = tabs.flatMap { it.contentTips }
internal constructor(parent: Base, parser: XmlPullParser) : super(parent, parser) {
parser.require(XmlPullParser.START_TAG, XMLNS_CONTENT, XML_TABS)
tabs = buildList {
parser.parseChildren {
when (parser.namespace) {
XMLNS_CONTENT -> when (parser.name) {
XML_TAB -> add(Tab(this@Tabs, parser))
}
}
}
}
}
@RestrictTo(RestrictToScope.TESTS)
internal constructor(parent: Base = Manifest()) : super(parent) {
tabs = emptyList()
}
class Tab : BaseModel, Parent, HasAnalyticsEvents {
private val tabs: Tabs
val position get() = tabs.tabs.indexOf(this)
val analyticsEvents: List<AnalyticsEvent>
val listeners: Set<EventId>
val label: Text?
override val content: List<Content>
internal constructor(parent: Tabs, parser: XmlPullParser) : super(parent) {
tabs = parent
parser.require(XmlPullParser.START_TAG, XMLNS_CONTENT, XML_TAB)
listeners = parser.getAttributeValue(XML_LISTENERS)?.toEventIds()?.toSet().orEmpty()
analyticsEvents = mutableListOf()
var label: Text? = null
content = parseContent(parser) {
when (parser.namespace) {
XMLNS_ANALYTICS -> when (parser.name) {
AnalyticsEvent.XML_EVENTS -> analyticsEvents += parser.parseAnalyticsEvents(this)
}
XMLNS_CONTENT -> when (parser.name) {
XML_LABEL -> label = parser.parseTextChild(this, XMLNS_CONTENT, XML_LABEL)
}
}
}
this.label = label
}
@RestrictTo(RestrictToScope.TESTS)
internal constructor(
parent: Tabs = Tabs(),
analyticsEvents: List<AnalyticsEvent> = emptyList()
) : super(parent) {
tabs = parent
this.analyticsEvents = analyticsEvents
listeners = emptySet()
label = null
content = emptyList()
}
override fun getAnalyticsEvents(type: Trigger) = when (type) {
Trigger.CLICKED -> analyticsEvents.filter { it.isTriggerType(Trigger.CLICKED, Trigger.DEFAULT) }
else -> error("The $type trigger type is currently unsupported on Tabs")
}
}
}
| 5
|
Kotlin
|
1
| 0
|
6f53069d28ac91a2de18a9f4e01a9e52b9dd9c32
| 3,190
|
kotlin-mpp-godtools-tool-parser
|
MIT License
|
src/main/java/geode/Geode.kt
|
jaimeaz
| 568,111,941
| false
|
{"Java": 74228, "Kotlin": 25582}
|
package geode
import solver.Vec2
import solver.Vec3
import solver.Vec3Dir
import kotlin.math.PI
import kotlin.math.pow
import kotlin.math.roundToInt
enum class StickyBlockType {
SLIME,
SLIME_OFFSET,
HONEY,
HONEY_OFFSET;
companion object {
@JvmStatic
fun isHoney(block: StickyBlockType): Boolean {
return block == HONEY || block == HONEY_OFFSET
}
fun isOffset(block: StickyBlockType): Boolean {
return block == SLIME_OFFSET || block == HONEY_OFFSET
}
}
}
class Geode(val buds: List<Vec3>) {
companion object {
const val BUD_DENSITY = 0.083
fun random(radius: Int, density: Double = BUD_DENSITY): Geode {
return random(radius.toDouble(), density)
}
fun random(radius: Double, density: Double = BUD_DENSITY, crack: Boolean = true): Geode {
val surfaceArea = 4.0 / 3.0 * PI * radius.pow(3)
val numBuds = (surfaceArea * density).roundToInt()
var buds = (0 until numBuds).map { Vec3.randomOnSphere(radius) }
if (crack) {
val crackPoint = Vec3.randomOnSphere(radius)
val crackDist = (2 * PI * radius) / 8
buds = buds.filter { it.dist(crackPoint) > crackDist }
}
return Geode(buds)
}
}
fun toProjection(dir: Vec3Dir): GeodeProjection {
val cells: MutableMap<Vec2, BlockType> = mutableMapOf()
for (budPosition in buds) {
val budXY = budPosition.without(dir)
cells[budXY] = BlockType.BUD
cells[budXY.left()] = BlockType.CRYSTAL.max(cells[budXY.left()] ?: BlockType.AIR)
cells[budXY.right()] = BlockType.CRYSTAL.max(cells[budXY.right()] ?: BlockType.AIR)
cells[budXY.up()] = BlockType.CRYSTAL.max(cells[budXY.up()] ?: BlockType.AIR)
cells[budXY.down()] = BlockType.CRYSTAL.max(cells[budXY.down()] ?: BlockType.AIR)
}
// Remove completely surrounded crystals
for ((loc, type) in cells) {
if (type == BlockType.CRYSTAL && cells[loc.up()] == BlockType.BUD && cells[loc.down()] == BlockType.BUD && cells[loc.left()] == BlockType.BUD && cells[loc.right()] == BlockType.BUD) {
cells[loc] = BlockType.BUD
}
}
return GeodeProjection(cells)
}
}
| 1
| null |
1
| 1
|
116d49af6c2cc27946860202de907bc59b4d3d0f
| 2,385
|
Geodesy-fabric-auto
|
MIT License
|
packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/NotifGutsViewManager.kt
|
liu-wanshun
| 595,904,109
| true
| null |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.notification.collection.render
/** A type which provides open and close guts events to a single listener */
interface NotifGutsViewManager {
/**
* @param listener the object that will listen to open and close guts events
*/
fun setGutsListener(listener: NotifGutsViewListener?)
}
| 0
|
Java
|
1
| 2
|
e99201cd9b6a123b16c30cce427a2dc31bb2f501
| 958
|
platform_frameworks_base
|
Apache License 2.0
|
BBChat/src/main/java/id/bluebird/chat/methods/logout.kt
|
bluebird-id
| 715,886,189
| false
|
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Git Attributes": 1, "Markdown": 3, "INI": 1, "Proguard": 3, "Kotlin": 37, "XML": 154, "Java": 137, "Protocol Buffer": 1, "JSON": 2}
|
package id.bluebird.chat.methods
import id.bluebird.chat.sdk.Cache
import id.bluebird.chat.sdk.CallManager
fun logout(): Boolean {
CallManager.unregisterCallingAccount()
Cache.invalidate()
return false
}
| 0
|
Java
|
0
| 0
|
292935626a93cdba391ebe4d69862532debc8e4e
| 219
|
bb-chat-android
|
Apache License 2.0
|
magick-kt-native-q8/src/commonMain/kotlin/imagemagick/magicknative/types/NativePrimaryInfo.kt
|
Gounlaf
| 692,782,810
| false
|
{"Kotlin": 954080, "C": 942148, "C++": 3285}
|
@file:Suppress("KDocMissingDocumentation")
package imagemagick.magicknative.types
import imagemagick.bridge.dispose
import imagemagick.bridge.x
import imagemagick.bridge.y
import imagemagick.bridge.z
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import libMagickNative.PrimaryInfo
import libMagickNative.PrimaryInfo_Create
@ExperimentalStdlibApi
@ExperimentalForeignApi
public class NativePrimaryInfo(public val ptr: CPointer<PrimaryInfo>) : AutoCloseable {
public constructor() : this(create())
public var x: Double
get() = ptr.x()
set(value) = ptr.x(value)
public var y: Double
get() = ptr.y()
set(value) = ptr.y(value)
public var z: Double
get() = ptr.z()
set(value) = ptr.z(value)
override fun close() {
ptr.dispose()
}
public companion object {
@Throws(IllegalStateException::class)
public inline fun create(): CPointer<PrimaryInfo> =
PrimaryInfo_Create() ?: error("Failed to instantiate native PrimaryInfo")
}
}
| 0
|
Kotlin
|
0
| 0
|
a075a88d293b5c77668d8079c73b463c2d601fc8
| 1,076
|
Magick.KT
|
MIT License
|
SharedCode/src/iosTest/kotlin/dev/polek/episodetracker/common/resources/Resources.kt
|
y-polek
| 234,707,032
| false
| null |
package dev.polek.episodetracker.common.resources
actual object Resource {
actual fun read(path: String): String? {
TODO("not implemented")
}
}
| 0
|
Kotlin
|
1
| 3
|
3ecbee176b5d1a74e293b94af74229aa17cff2dd
| 161
|
EpisodeTracker
|
Apache License 2.0
|
app/src/main/java/de/drtobiasprinz/summitbook/fragments/SummationFragment.kt
|
prinztob
| 370,702,913
| false
| null |
package de.drtobiasprinz.summitbook.fragments
import de.drtobiasprinz.summitbook.db.entities.Summit
interface SummationFragment {
fun update(filteredSummitEntries: List<Summit>?)
}
| 0
|
Kotlin
|
0
| 0
|
b7bbb8f6a6edc5c42fc7e98dacc50032f52957ad
| 186
|
summitbook
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.