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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shared/src/commonTest/kotlin/in_/droidcon/india/TestAnnotations.kt
|
iamBedant
| 519,594,485 | false |
{"Kotlin": 43045, "Swift": 7213, "Ruby": 1706}
|
package in_.droidcon.india
import kotlin.reflect.KClass
@OptIn(ExperimentalMultiplatform::class)
@OptionalExpectation
expect annotation class RunWith(val value: KClass<out Runner>)
expect abstract class Runner
expect class AndroidJUnit4 : Runner
| 0 |
Kotlin
|
0
| 0 |
df480ec915c6c10902e257477944021496661a0f
| 248 |
DroidconIN
|
MIT License
|
app/src/main/java/com/sunnyweather/android/logic/network/SunnyWeatherNetwork.kt
|
GERECOC
| 464,824,767 | false | null |
/*
* 本文件定义一个统一的网络数据源访问入口,对所有网络请求的api进行封装
* */
package com.sunnyweather.android.logic.network
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.await
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object SunnyWeatherNetwork {
//使用ServiceCreator创建了一个PlaceService的动态动态代理对象
private val placeService = ServiceCreator.create<PlaceService>()
//将searchPlaces函数声明成挂起函数,使用协程通过await()函数实现简化Retrofit回调
suspend fun searchPlaces(query:String) = placeService.searchPlaces(query).await()
//借助suspendCoroutine函数将传统的回调机制写法大幅简化
/*
* suspendCoroutine函数必须在协程作用域或挂起函数中才能调用,它接收一个Lambda表达式,主要作用是将当前协程立即挂起,然后在一个普通线程中执行Lambda表达式代码
* Lambda表达式传入一个Continuation参数,调用它的resume()方法或者resumeWithException()可以让协程恢复执行
* await()函数是一个挂起函数,这里给它声明了一个泛型T,并将await()函数定义成Call<T>的扩展函数,这样所有返回值是Call类型的retrofit网络请求都可以直接调用await()函数
* */
private suspend fun <T> Call<T>.await() : T{
return suspendCoroutine {
continuation -> enqueue(object : Callback<T>{
override fun onResponse(call: Call<T>, response: Response<T>) {
val body = response.body()
if (body != null) continuation.resume(body)
else continuation.resumeWithException(RuntimeException("response body is null"))
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
}
| 0 |
Kotlin
|
0
| 0 |
602840fa9978d25925116dccc4ddf45533508e0e
| 1,545 |
SunnyWeather
|
Apache License 2.0
|
data/local/images/src/main/java/com/alexnechet/local/images/RemoteKeysLocalDataSource.kt
|
alex-nechet
| 634,167,292 | false | null |
package com.alexnechet.local.images
import com.alexnechet.local.images.db.RemoteKeysDao
import com.alexnechet.local.images.model.RemoteKeys
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
interface RemoteKeysLocalDataSource {
suspend fun insertAll(remoteKey: List<RemoteKeys>)
suspend fun remoteKeysImageId(imageId: Long): RemoteKeys?
suspend fun clearRemoteKeys()
}
class RemoteKeysLocalDataSourceImpl(
private val dao: RemoteKeysDao,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : RemoteKeysLocalDataSource {
override suspend fun insertAll(remoteKey: List<RemoteKeys>) = withContext(dispatcher) {
dao.insertAll(remoteKey)
}
override suspend fun remoteKeysImageId(imageId: Long): RemoteKeys? = withContext(dispatcher) {
dao.remoteKeysRepoId(imageId)
}
override suspend fun clearRemoteKeys() = withContext(dispatcher) {
dao.clearRemoteKeys()
}
}
| 0 |
Kotlin
|
0
| 0 |
6adf90e68f20d413a4a20a960339ae5c26840fb6
| 1,010 |
PixabayApp
|
MIT License
|
quote/src/main/java/com/pyamsoft/tickertape/quote/base/SearchBar.kt
|
pyamsoft
| 371,196,339 | false | null |
/*
* Copyright 2024 pyamsoft
*
* 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.pyamsoft.tickertape.quote.base
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Surface
import androidx.compose.material.Tab
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.tickertape.stocks.api.EquityType
import com.pyamsoft.tickertape.ui.debouncedOnTextChange
@Composable
internal fun SearchBar(
modifier: Modifier = Modifier,
search: String,
currentTab: EquityType,
onSearchChanged: (String) -> Unit,
onTabUpdated: (EquityType) -> Unit,
) {
val contentColor = LocalContentColor.current
val allTypes = remember { EquityType.entries.toMutableStateList() }
val selectedTabIndex = currentTab.ordinal
Column(
modifier = modifier.fillMaxWidth(),
) {
SearchInput(
modifier = Modifier.fillMaxWidth(),
search = search,
onSearchChanged = onSearchChanged,
)
ScrollableTabRow(
selectedTabIndex = selectedTabIndex,
backgroundColor = Color.Transparent,
contentColor = contentColor,
indicator = { tabPositions ->
val tabPosition = tabPositions[selectedTabIndex]
TabRowDefaults.Indicator(
modifier = Modifier.tabIndicatorOffset(tabPosition),
color = MaterialTheme.colors.secondary,
)
},
) {
allTypes.forEach { tab ->
TickerTab(
current = currentTab,
tab = tab,
onTabUpdated = onTabUpdated,
)
}
}
}
}
@Composable
private fun TickerTab(
tab: EquityType,
current: EquityType,
onTabUpdated: (EquityType) -> Unit,
) {
val contentColor = LocalContentColor.current
Tab(
selected = tab == current,
selectedContentColor = MaterialTheme.colors.secondary.copy(alpha = ContentAlpha.medium),
unselectedContentColor = contentColor.copy(alpha = ContentAlpha.medium),
onClick = { onTabUpdated(tab) },
) {
Text(
modifier = Modifier.padding(vertical = MaterialTheme.keylines.typography),
text = tab.display,
)
}
}
@Composable
@OptIn(ExperimentalAnimationApi::class)
private fun SearchInput(
modifier: Modifier = Modifier,
search: String,
onSearchChanged: (String) -> Unit,
) {
val (query, onChange) = debouncedOnTextChange(search, onSearchChanged)
val (isSearchFocused, setSearchFocused) = remember { mutableStateOf(false) }
val hasSearchQuery = remember(query) { query.isNotBlank() }
val handleClearSearch by rememberUpdatedState { onChange("") }
// If search bar is populated and focused, back gesture clears
if (isSearchFocused && hasSearchQuery) {
BackHandler(
onBack = { handleClearSearch() },
)
}
OutlinedTextField(
modifier =
modifier
.padding(horizontal = MaterialTheme.keylines.content)
.padding(bottom = MaterialTheme.keylines.baseline)
.onFocusChanged { setSearchFocused(it.isFocused) },
value = query,
onValueChange = onChange,
singleLine = true,
shape = RoundedCornerShape(percent = 50),
label = {
Text(
modifier = Modifier.padding(horizontal = MaterialTheme.keylines.baseline),
text = "Search for something...",
)
},
trailingIcon = {
AnimatedVisibility(
visible = hasSearchQuery,
enter = scaleIn(),
exit = scaleOut(),
) {
IconButton(
onClick = { handleClearSearch() },
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Clear Search",
)
}
}
},
)
}
@Preview
@Composable
private fun PreviewSearchBar() {
Surface {
SearchBar(
search = "",
onSearchChanged = {},
currentTab = EquityType.STOCK,
onTabUpdated = {},
)
}
}
| 0 | null |
0
| 7 |
1a0e3f076d7c10804a8db33d4dd107531a4a9f05
| 5,922 |
tickertape
|
Apache License 2.0
|
src/commonMain/kotlin/maryk/rocksdb/ReadTier.kt
|
marykdb
| 192,168,972 | false | null |
package maryk.rocksdb
expect enum class ReadTier {
READ_ALL_TIER,
BLOCK_CACHE_TIER,
PERSISTED_TIER,
MEMTABLE_TIER;
/**
* Returns the byte value of the enumerations value
* @return byte representation
*/
fun getValue(): Byte
}
| 0 |
Kotlin
|
2
| 7 |
7e2c471854195b7635db7b75ca23d26305700ba7
| 267 |
rocksdb-multiplatform
|
Apache License 2.0
|
android/app/src/main/java/ai/kun/socialdistancealarm/ui/launch/LaunchFragment.kt
|
goOICT
| 250,982,109 | false |
{"Kotlin": 224674, "Swift": 81144, "Ruby": 615, "Objective-C": 553}
|
package ai.kun.socialdistancealarm.ui.launch
import ai.kun.socialdistancealarm.R
import ai.kun.socialdistancealarm.util.Constants
import ai.kun.opentracesdk_fat.BLETrace
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
/**
* This doesn't really do much of anything. When we started the project we thought there might be
* some kind of login for corp. accounts, so if that's what you're building, you want to put that
* stuff here. Originally the plan was to use firebase for that. Right now all it really does
* is decide if you should see the home fragment next or the onboarding fragment.
*
*/
class LaunchFragment : Fragment() {
private val TAG = "LaunchFragment"
/**
* hide the options menu since this is a splash screen
*
* @param savedInstanceState
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(false)
}
/**
* Inflate and return
*
* @param inflater the layout inflater
* @param container the container
* @param savedInstanceState not used
* @return the view
*/
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_launch, container, false)
return root
}
/**
* We used to wait for the firebase login here, but we don't anymore.
*
* @param view the view
* @param savedInstanceState not used
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val model: LaunchViewModel by viewModels()
val authStateObserver = Observer<Boolean> {isLoggedIn ->
when (isLoggedIn) {
true -> moveToHome()
false -> waitForSignIn()
}
}
model.isLoggedIn.observe(viewLifecycleOwner, authStateObserver)
}
/**
* This is where we decide if we are actually going to launch the home fragment or if we
* are going to launch the onboard fragment.
*
*/
private fun moveToHome() {
val sharedPrefs = context?.applicationContext?.getSharedPreferences(
Constants.PREF_FILE_NAME, Context.MODE_PRIVATE
)
if (sharedPrefs == null || !sharedPrefs.getBoolean(Constants.PREF_IS_ONBOARDED, false)) {
BLETrace.uuidString = BLETrace.getNewUniqueId()
BLETrace.init(requireContext().applicationContext)
findNavController().navigate(R.id.action_launchFragment_to_onBoardFragment_1)
} else {
findNavController().navigate(R.id.action_launchFragment_to_navigation_home)
}
}
/**
* Firebase login is disabled. We just call move to home.
*
*/
private fun waitForSignIn() {
/* val auth = FirebaseAuth.getInstance()
val task = auth.signInAnonymously()
task.addOnCompleteListener() {
if(it.isSuccessful) {
Log.d(TAG, "signInAnonymously:success")
}
else {
Log.w(TAG, "signInAnonymously:failure", task.exception)
Toast.makeText(context, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}*/
moveToHome()
}
}
| 19 |
Kotlin
|
14
| 23 |
67a32553eb7c7087a1f7ca7fa08402034ec89bc7
| 3,667 |
SocialDistance
|
MIT License
|
sample/src/main/java/com/javavirys/circularprogressbar/sample/MainActivityViewModel.kt
|
LiteSoftware
| 436,669,162 | false | null |
/*
* Copyright 2021 Vitaliy Sychov. 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.
*/
package com.javavirys.circularprogressbar.sample
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random
class MainActivityViewModel : ViewModel() {
val speedLiveData = MutableLiveData<Int>()
var launchFlag = false
fun start() {
if (launchFlag) return
launchFlag = true
viewModelScope.launch(Dispatchers.IO) {
while (launchFlag) {
speedLiveData.postValue(Random.nextInt(0, 100))
delay(800)
}
}
}
fun stop() {
launchFlag = false
}
}
| 0 |
Kotlin
|
0
| 2 |
7b0db4d0b27e7bcee1400d1a077862e6000f4404
| 1,387 |
CircularProgressBar
|
Apache License 2.0
|
klog/src/main/kotlin/com/coditory/klog/text/json/JsonEscapedAppendable.kt
|
coditory
| 736,731,539 | false |
{"Kotlin": 149010}
|
package com.coditory.klog.text.json
internal class JsonEscapedAppendable(
private val appendable: Appendable,
) : Appendable {
override fun append(csq: CharSequence?): Appendable {
if (csq != null) {
JsonEncoder.encode(csq, appendable)
}
return this
}
override fun append(
csq: CharSequence?,
start: Int,
end: Int,
): Appendable {
if (csq != null) {
JsonEncoder.encode(csq, appendable, start = start, end = end)
}
return this
}
override fun append(ch: Char): Appendable {
JsonEncoder.encode(ch, appendable)
return this
}
}
| 0 |
Kotlin
|
0
| 0 |
dc34894d4a929f486280ec689be81a71e904cae2
| 670 |
klog
|
Apache License 2.0
|
feature/note/src/main/java/com/teamwiney/notedetail/component/NoteDetailBottomSheet.kt
|
AdultOfNineteen
| 639,481,288 | false |
{"Kotlin": 628771}
|
package com.teamwiney.notedetail.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.teamwiney.ui.theme.WineyTheme
@Composable
fun NoteDetailBottomSheet(
deleteNote: () -> Unit,
patchNote: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(
color = WineyTheme.colors.gray_950,
shape = RoundedCornerShape(
topStart = 6.dp,
topEnd = 6.dp
)
)
.padding(
start = 24.dp,
end = 24.dp,
top = 10.dp,
bottom = 20.dp
),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "삭제하기",
color = WineyTheme.colors.gray_50,
style = WineyTheme.typography.bodyB1,
modifier = Modifier
.fillMaxWidth()
.clickable { deleteNote() }
.padding(20.dp)
)
Text(
text = "수정하기",
color = WineyTheme.colors.gray_50,
style = WineyTheme.typography.bodyB1,
modifier = Modifier
.fillMaxWidth()
.clickable {
patchNote()
}
.padding(20.dp)
)
}
}
| 7 |
Kotlin
|
1
| 5 |
a2bedf166e92ab38fcbcb6fe1ee35d3d2f5de5bf
| 1,814 |
WINEY-Android
|
MIT License
|
cinescout/details/presentation/src/main/kotlin/cinescout/details/presentation/model/ScreenplayDetailsUiModel.kt
|
fardavide
| 280,630,732 | false |
{"Kotlin": 2374797, "Shell": 11599}
|
package cinescout.details.presentation.model
import androidx.compose.runtime.Composable
import cinescout.details.presentation.state.DetailsSeasonsState
import cinescout.resources.TextRes
import cinescout.resources.string
import cinescout.screenplay.domain.model.id.ScreenplayIds
import kotlinx.collections.immutable.ImmutableList
data class ScreenplayDetailsUiModel(
val creditsMembers: ImmutableList<CreditsMember>,
val genres: ImmutableList<String>,
val backdrops: ImmutableList<String?>,
val ids: ScreenplayIds,
val overview: String,
val personalRating: Int?,
val posterUrl: String?,
val premiere: Premiere,
val ratingAverage: String,
val ratingCount: TextRes,
val runtime: TextRes?,
val seasonsState: DetailsSeasonsState,
val tagline: String?,
val title: String,
val videos: ImmutableList<Video>
) {
data class CreditsMember(
val name: String,
val profileImageUrl: String?,
val role: String?
)
data class Premiere(
val releaseDate: String?,
val status: TextRes?
) {
@Composable
fun string(): String {
val statusString = status?.let { string(textRes = it) }
return listOfNotNull(releaseDate, statusString).joinToString(separator = " • ")
}
}
data class Video(
val previewUrl: String,
val title: String,
val url: String
)
}
| 11 |
Kotlin
|
2
| 6 |
67ae15424264bb80befcae68590243e970e9d040
| 1,432 |
CineScout
|
Apache License 2.0
|
app/src/main/java/br/com/wilson/mielke/baseapplication/ui/EventListFragment.kt
|
mielke44
| 409,394,990 | false |
{"Kotlin": 38749}
|
package br.com.wilson.mielke.baseapplication.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import br.com.wilson.mielke.baseapplication.config.models.EventModel
import br.com.wilson.mielke.baseapplication.databinding.EventListFragmentBinding
import br.com.wilson.mielke.baseapplication.ui.adapter.EventListAdapter
import br.com.wilson.mielke.baseapplication.utils.RecyclerItemSpacingDecoration
import br.com.wilson.mielke.baseapplication.viewModel.SecondArchitectureViewModel
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
class EventListFragment: Fragment() {
private var eventList : List<EventModel>? = null
private var binding : EventListFragmentBinding? = null
private val baseViewModel: SecondArchitectureViewModel by sharedViewModel()
private val eventsAdapter by lazy {
eventList?.let{
EventListAdapter(it){eventItem ->
startEventDetailView(eventItem)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = EventListFragmentBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
baseViewModel.eventList.observe(viewLifecycleOwner, { events ->
eventList = events
buildRecyclerView()
(activity as? MainActivity)?.stopLoader()
})
}
private fun buildRecyclerView(){
binding?.apply{
eventRecycler.layoutManager = LinearLayoutManager(context)
eventRecycler.adapter = eventsAdapter
eventRecycler.addItemDecoration(RecyclerItemSpacingDecoration((60)))
}
}
private fun startEventDetailView(model: EventModel){
(activity as? MainActivity)?.startEventDetailFragment(model.id.toInt())
}
companion object{
fun newInstance(): EventListFragment = EventListFragment()
}
}
| 0 |
Kotlin
|
0
| 0 |
17bd2029a9ce18d7b9e50d5f9032d82a17f9b08b
| 2,214 |
baseApplication
|
MIT License
|
contracts/src/main/kotlin/com/tradeix/contractcomposition/contracts/common/FulfillableAsRefInput.kt
|
tradeix
| 290,489,883 | false | null |
package com.tradeix.contractcomposition.contracts.common
/**
* Marker interface so that contracts can know whether the reference inputs in a fulfill command are in fact allowed
* to be fulfilled as a ref input
*
* We might need to change this so that it's the Contracts rather than the States which implement this.
*/
interface FulfillableAsRefInput
| 1 |
Kotlin
|
0
| 0 |
9f3ef4fbec2ddd2c2c55348686496868e3176aa9
| 356 |
contracts
|
Apache License 2.0
|
app/src/main/kotlin/com/litekite/compose/customlayout/CustomLayoutActivity.kt
|
svignesh93
| 394,283,528 | false | null |
/*
* Copyright 2021 LiteKite Startup. 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.
*/
package com.litekite.compose.customlayout
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.litekite.compose.theme.ComposeTheme
/**
* A Custom Layout Modifier that includes padding from the text baseline
*
* @author Vignesh S
* @see [Jetpack Compose basics]
* @see [https://developer.android.com/courses/pathways/compose]
*/
class CustomLayoutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTheme {
Text("Hi there!", Modifier.firstBaselineToTop(32.dp))
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
242e74163bb4750c4f6d497107241325785c2458
| 1,443 |
Experiment-Compose
|
Apache License 2.0
|
framework666/src/main/java/studio/attect/framework666/model/MutablePair.kt
|
Attect
| 192,833,321 | false | null |
package studio.attect.framework666.model
/**
* Represents a generic pair of two values.
*
* There is no meaning attached to values in this class, it can be used for any purpose.
* Pair exhibits value semantics, i.e. two pairs are equal if both components are equal.
*
*
* @param A type of the first value.
* @param B type of the second value.
* @property first First value.
* @property second Second value.
* @constructor Creates a new instance of Pair.
*/
data class MutablePair<A, B>(var first: A, var second: B) {
}
| 0 |
Kotlin
|
1
| 6 |
22285ee7026abf6fd00150af6a96d12287154336
| 531 |
Android-Framework666
|
Apache License 2.0
|
framework666/src/main/java/studio/attect/framework666/model/MutablePair.kt
|
Attect
| 192,833,321 | false | null |
package studio.attect.framework666.model
/**
* Represents a generic pair of two values.
*
* There is no meaning attached to values in this class, it can be used for any purpose.
* Pair exhibits value semantics, i.e. two pairs are equal if both components are equal.
*
*
* @param A type of the first value.
* @param B type of the second value.
* @property first First value.
* @property second Second value.
* @constructor Creates a new instance of Pair.
*/
data class MutablePair<A, B>(var first: A, var second: B) {
}
| 0 |
Kotlin
|
1
| 6 |
22285ee7026abf6fd00150af6a96d12287154336
| 531 |
Android-Framework666
|
Apache License 2.0
|
androidx-viewmodel/src/main/kotlin/org/rewedigital/katana/androidx/viewmodel/ViewModel.kt
|
rewe-digital-incubator
| 155,181,363 | false | null |
@file:Suppress("unused")
package org.rewedigital.katana.androidx.viewmodel
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import org.rewedigital.katana.Component
import org.rewedigital.katana.KatanaTrait
import org.rewedigital.katana.ModuleBindingContext
import org.rewedigital.katana.androidx.viewmodel.internal.viewModelName
import org.rewedigital.katana.dsl.ProviderDsl
import org.rewedigital.katana.dsl.factory
//<editor-fold desc="Internal utility functions and classes">
@Suppress("UNCHECKED_CAST")
@PublishedApi
internal class KatanaViewModelProviderFactory(private val viewModelProvider: () -> ViewModel) :
ViewModelProvider.Factory {
override fun <VM : ViewModel> create(modelClass: Class<VM>) =
viewModelProvider() as VM
}
@PublishedApi
internal inline fun <reified VM : ViewModel> ViewModelProvider.get(key: String?) =
when (key) {
null -> get(VM::class.java)
else -> get(key, VM::class.java)
}
@PublishedApi
internal object InternalViewModelProvider {
inline fun <reified VM : ViewModel> of(
owner: ViewModelStoreOwner,
key: String?,
noinline viewModelProvider: () -> ViewModel
) =
ViewModelProvider(
owner,
KatanaViewModelProviderFactory(viewModelProvider)
).get<VM>(key)
}
//</editor-fold>
//<editor-fold desc="Module DSL">
/**
* Declares a [ViewModel] dependency binding.
*
* Body of provider syntax facilitates arbitrary dependency injection into the ViewModel when first instantiated.
* **Important:** The ViewModel instance is handled by AndroidX's [ViewModelProvider] and not by Katana itself.
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ProviderDsl.viewModel
* @see ProviderDsl.activityViewModel
*/
inline fun <reified VM : ViewModel> ModuleBindingContext.viewModel(
key: String? = null,
noinline body: ProviderDsl.() -> VM
) =
factory(name = viewModelName(modelClass = VM::class.java, key = key), body = body)
/**
* Provides [ViewModel] instance of given [ViewModelStoreOwner] declared in current injection context.
*/
inline fun <reified VM : ViewModel> ProviderDsl.viewModel(owner: ViewModelStoreOwner, key: String? = null) =
InternalViewModelProvider.of<VM>(owner, key) {
context.injectNow(name = viewModelName(VM::class.java, key))
}
/**
* Provides [Fragment] [ViewModel] instance scoped to its [FragmentActivity] declared in current injection context.
*/
inline fun <reified VM : ViewModel> ProviderDsl.activityViewModel(fragment: Fragment, key: String? = null) =
viewModel<VM>(owner = fragment.requireActivity(), key = key)
//</editor-fold>
//<editor-fold desc="Injection extension functions">
/**
* Immediately injects [ViewModel] of specified [ViewModelStoreOwner].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel> Component.viewModelNow(owner: ViewModelStoreOwner, key: String? = null) =
InternalViewModelProvider.of<VM>(owner, key) {
injectNow(name = viewModelName(VM::class.java, key))
}
@PublishedApi
internal inline fun <reified VM : ViewModel> Component.internalViewModel(
noinline ownerProvider: () -> ViewModelStoreOwner,
key: String? = null
) =
lazy { viewModelNow<VM>(ownerProvider(), key) }
/**
* Injects [ViewModel] of specified [ViewModelStoreOwner].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel> Component.viewModel(owner: ViewModelStoreOwner, key: String? = null) =
internalViewModel<VM>(ownerProvider = { owner }, key = key)
/**
* Immediately injects [ViewModel] of current [ViewModelStoreOwner] implementing [KatanaTrait] interface.
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel, T> T.viewModelNow(key: String? = null) where T : KatanaTrait, T : ViewModelStoreOwner =
component.viewModelNow<VM>(this, key)
/**
* Injects [ViewModel] of current [ViewModelStoreOwner] implementing [KatanaTrait] interface.
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel, T> T.viewModel(key: String? = null) where T : KatanaTrait, T : ViewModelStoreOwner =
component.viewModel<VM>(this, key)
/**
* Immediately injects [ViewModel] of specified [Fragment] scoped to its [FragmentActivity].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel> Component.activityViewModelNow(fragment: Fragment, key: String? = null) =
viewModelNow<VM>(owner = fragment.requireActivity(), key = key)
/**
* Injects [ViewModel] of specified [Fragment] scoped to its [FragmentActivity].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel> Component.activityViewModel(fragment: Fragment, key: String? = null) =
internalViewModel<VM>(ownerProvider = { fragment.requireActivity() }, key = key)
/**
* Immediately injects [ViewModel] of current [Fragment] implementing [KatanaTrait] scoped to its [FragmentActivity].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel, T> T.activityViewModelNow(key: String? = null) where T : KatanaTrait, T : Fragment =
component.viewModelNow<VM>(owner = requireActivity(), key = key)
/**
* Injects [ViewModel] of current [Fragment] implementing [KatanaTrait] scoped to its [FragmentActivity].
*
* @param key Optional key as required for `ViewModelProvider.get(String, Class)`
*
* @see ModuleBindingContext.viewModel
*/
inline fun <reified VM : ViewModel, T> T.activityViewModel(key: String? = null) where T : KatanaTrait, T : Fragment =
component.internalViewModel<VM>(ownerProvider = { requireActivity() }, key = key)
//</editor-fold>
| 1 |
Kotlin
|
9
| 183 |
4c55f29f793a35f77dff96ede2204fde12fc1cb4
| 6,446 |
katana
|
MIT License
|
must_have_android-main/10_TodoList/app/src/main/java/com/example/todolist/db/ToDoEntity.kt
|
cbw6088
| 795,353,310 | false |
{"Kotlin": 148227}
|
package com.example.todolist.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity // 어떤 구성요소인지를 알려주려면 꼭 어노테이션을 써주어야 합니다.
data class ToDoEntity ( // ❶ 중괄호 아닌 소괄호입니다.
@PrimaryKey(autoGenerate = true) var id : Int? = null, // ❷
@ColumnInfo(name="title") val title : String,
@ColumnInfo(name="importance") val importance : Int
)
| 0 |
Kotlin
|
0
| 0 |
aa0dc57432dac4b89d02ba86eaa0465ceaccbd55
| 389 |
KotlinTraining
|
MIT License
|
app/src/main/java/com/mospolytech/mospolyhelper/domain/account/deadlines/repository/DeadlinesRepository.kt
|
tonykolomeytsev
| 341,524,793 | true |
{"Kotlin": 646693}
|
package com.mospolytech.mospolyhelper.domain.account.deadlines.repository
import com.mospolytech.mospolyhelper.domain.account.deadlines.model.Deadline
import com.mospolytech.mospolyhelper.utils.Result
import kotlinx.coroutines.flow.Flow
interface DeadlinesRepository {
suspend fun getDeadlines(): Flow<Result<List<Deadline>>>
suspend fun getLocalInfo(): Flow<Result<List<Deadline>>>
suspend fun setDeadlines(deadlines: List<Deadline>): Flow<Result<List<Deadline>>>
}
| 0 | null |
0
| 0 |
379c9bb22913da1854f536bf33e348a459db48b9
| 481 |
mospolyhelper-android
|
MIT License
|
src/main/kotlin/phonon/puppet/math/Vector3f.kt
|
phonon
| 278,514,975 | false | null |
/**
* Vector3 Float32
*/
package phonon.puppet.math
import org.bukkit.Location
public data class Vector3f(
var x: Float,
var y: Float,
var z: Float
) {
companion object {
// re-usable constant vectors
// (must not be mutated by any client)
public val ZERO: Vector3f = Vector3f(0f, 0f, 0f)
public val ONE: Vector3f = Vector3f(1f, 1f, 1f)
// return new zero vector
public fun zero(): Vector3f {
return Vector3f(0.0f, 0.0f, 0.0f)
}
// return new one vector
public fun one(): Vector3f {
return Vector3f(1.0f, 1.0f, 1.0f)
}
// return new x-axis unit vector
public fun x(): Vector3f {
return Vector3f(1.0f, 0.0f, 0.0f)
}
// return new y-axis unit vector
public fun y(): Vector3f {
return Vector3f(0.0f, 1.0f, 0.0f)
}
// return new z-axis unit vector
public fun z(): Vector3f {
return Vector3f(0.0f, 0.0f, 1.0f)
}
// from bukkit location
public fun fromLocation(loc: Location): Vector3f {
return Vector3f(loc.x.toFloat(), loc.y.toFloat(), loc.z.toFloat())
}
}
// implement array index: vec3[index]
operator fun get(i: Int): Float {
when ( i ) {
0 -> return this.x
1 -> return this.y
2 -> return this.z
else -> throw ArrayIndexOutOfBoundsException(i)
}
}
operator fun set(i: Int, v: Float) {
when ( i ) {
0 -> this.x = v
1 -> this.y = v
2 -> this.z = v
else -> throw ArrayIndexOutOfBoundsException(i)
}
}
public fun clone(): Vector3f {
return Vector3f(this.x, this.y, this.z)
}
public fun copy(other: Vector3f): Vector3f {
this.x = other.x
this.y = other.y
this.z = other.z
return this
}
public fun set(x: Double, y: Double, z: Double): Vector3f {
this.x = x.toFloat()
this.y = y.toFloat()
this.z = z.toFloat()
return this
}
public fun set(x: Float, y: Float, z: Float): Vector3f {
this.x = x
this.y = y
this.z = z
return this
}
public fun setScalar(scalar: Double): Vector3f {
this.x = scalar.toFloat()
this.y = scalar.toFloat()
this.z = scalar.toFloat()
return this
}
public fun setX(x: Double): Vector3f {
this.x = x.toFloat()
return this
}
public fun setY(y: Double): Vector3f {
this.y = y.toFloat()
return this
}
public fun setZ(z: Double): Vector3f {
this.z = z.toFloat()
return this
}
public fun add(v: Vector3f): Vector3f {
this.x += v.x
this.y += v.y
this.z += v.z
return this
}
public fun addScalar(d: Double): Vector3f {
val f = d.toFloat()
this.x += f
this.y += f
this.z += f
return this
}
public fun addVectors(a: Vector3f, b: Vector3f): Vector3f {
this.x = a.x + b.x
this.y = a.y + b.y
this.z = a.z + b.z
return this
}
public fun addScaledVector(v: Vector3f, d: Double): Vector3f {
val f = d.toFloat()
this.x += (v.x * f)
this.y += (v.y * f)
this.z += (v.z * f)
return this
}
public fun sub(v: Vector3f): Vector3f {
this.x -= v.x
this.y -= v.y
this.z -= v.z
return this
}
public fun subScalar(d: Double): Vector3f {
val f = d.toFloat()
this.x -= f
this.y -= f
this.z -= f
return this
}
public fun subVectors(a: Vector3f, b: Vector3f): Vector3f {
this.x = a.x - b.x
this.y = a.y - b.y
this.z = a.z - b.z
return this
}
public fun multiply(v: Vector3f): Vector3f {
this.x *= v.x
this.y *= v.y
this.z *= v.z
return this
}
public fun multiplyScalar(d: Double): Vector3f {
val f = d.toFloat()
this.x *= f
this.y *= f
this.z *= f
return this
}
public fun multiplyVectors(a: Vector3f, b: Vector3f): Vector3f {
this.x = a.x * b.x
this.y = a.y * b.y
this.z = a.z * b.z
return this
}
public fun divide(v: Vector3f): Vector3f {
this.x /= v.x
this.y /= v.y
this.z /= v.z
return this
}
public fun divideScalar(d: Double): Vector3f {
val f = 1f / d.toFloat()
this.x *= f
this.y *= f
this.z *= f
return this
}
public fun divideVectors(a: Vector3f, b: Vector3f): Vector3f {
this.x = a.x / b.x
this.y = a.y / b.y
this.z = a.z / b.z
return this
}
public fun dot(v: Vector3f): Double {
return (this.x * v.x + this.y * v.y + this.z * v.z).toDouble()
}
public fun cross(v: Vector3f): Vector3f {
return this.crossVectors(this, v)
}
public fun crossVectors(a: Vector3f, b: Vector3f): Vector3f {
this.x = a.y * b.z - a.z * b.y
this.y = a.z * b.x - a.x * b.z
this.z = a.x * b.y - a.y * b.x
return this
}
public fun lengthSquared(): Double {
return (this.x * this.x + this.y * this.y + this.z * this.z).toDouble()
}
public fun length(): Double {
return Math.sqrt( (this.x * this.x + this.y * this.y + this.z * this.z).toDouble() )
}
public fun manhattanLength(): Double {
return Math.abs(this.x.toDouble()) + Math.abs(this.y.toDouble()) + Math.abs(this.z.toDouble())
}
public fun distanceToSquared(v: Vector3f ): Double {
val dx = this.x - v.x
val dy = this.y - v.y
val dz = this.z - v.z
return (dx * dx + dy * dy + dz * dz).toDouble()
}
public fun distanceTo(v: Vector3f): Double {
return Math.sqrt( this.distanceToSquared(v) )
}
public fun manhattanDistanceTo(v: Vector3f): Double {
return Math.abs( (this.x - v.x).toDouble() ) + Math.abs( (this.y - v.y).toDouble() ) + Math.abs( (this.z - v.z).toDouble() )
}
public fun normalize(): Vector3f {
return this.divideScalar(this.length())
}
public fun setLength(length: Double): Vector3f {
return this.normalize().multiplyScalar(length)
}
public fun min(v: Vector3f): Vector3f {
this.x = Math.min( this.x, v.x )
this.y = Math.min( this.y, v.y )
this.z = Math.min( this.z, v.z )
return this
}
public fun max(v: Vector3f): Vector3f {
this.x = Math.max( this.x, v.x )
this.y = Math.max( this.y, v.y )
this.z = Math.max( this.z, v.z )
return this
}
// component-wise clamp
// assumes min < max
public fun clamp(min: Vector3f, max: Vector3f): Vector3f {
this.x = Math.max( min.x.toDouble(), Math.min( max.x.toDouble(), this.x.toDouble() ) ).toFloat()
this.y = Math.max( min.y.toDouble(), Math.min( max.y.toDouble(), this.y.toDouble() ) ).toFloat()
this.z = Math.max( min.z.toDouble(), Math.min( max.z.toDouble(), this.z.toDouble() ) ).toFloat()
return this
}
public fun clampScalar(min: Double, max: Double): Vector3f {
this.x = Math.max( min, Math.min( max, this.x.toDouble() ) ).toFloat()
this.y = Math.max( min, Math.min( max, this.y.toDouble() ) ).toFloat()
this.z = Math.max( min, Math.min( max, this.z.toDouble() ) ).toFloat()
return this
}
public fun clampLength(min: Double, max: Double): Vector3f {
val length = this.length()
return this.divideScalar(length).multiplyScalar( Math.max( min, Math.min( max, length ) ) )
}
public fun floor(): Vector3f {
this.x = Math.floor( this.x.toDouble() ).toFloat()
this.y = Math.floor( this.y.toDouble() ).toFloat()
this.z = Math.floor( this.z.toDouble() ).toFloat()
return this
}
public fun ceil(): Vector3f {
this.x = Math.ceil( this.x.toDouble() ).toFloat()
this.y = Math.ceil( this.y.toDouble() ).toFloat()
this.z = Math.ceil( this.z.toDouble() ).toFloat()
return this
}
public fun round(): Vector3f {
this.x = Math.round( this.x.toDouble() ).toFloat()
this.y = Math.round( this.y.toDouble() ).toFloat()
this.z = Math.round( this.z.toDouble() ).toFloat()
return this
}
public fun roundToZero(): Vector3f {
this.x = if ( this.x < 0f ) Math.ceil( this.x.toDouble() ).toFloat() else Math.floor( this.x.toDouble() ).toFloat()
this.y = if ( this.y < 0f ) Math.ceil( this.y.toDouble() ).toFloat() else Math.floor( this.y.toDouble() ).toFloat()
this.z = if ( this.z < 0f ) Math.ceil( this.z.toDouble() ).toFloat() else Math.floor( this.z.toDouble() ).toFloat()
return this
}
public fun negate(): Vector3f {
this.x = -this.x
this.y = -this.y
this.z = -this.z
return this
}
public fun applyEuler(euler: Euler): Vector3f {
return this.applyQuaternion( Quaternion.fromEuler(euler) )
}
public fun applyAxisAngle(axis: Vector3f, angle: Double): Vector3f {
return this.applyQuaternion( Quaternion.fromAxisAngle(axis, angle) )
}
// multiply by matrix4: matrix x vector = [4x4] x [4x1]
// vector3 -> implicit [x y z 1]
public fun applyMatrix4(mat4: Matrix4f): Vector3f {
val x = this.x
val y = this.y
val z = this.z
val e = mat4.elements
val w = 1f / ( e[m30] * x + e[m31] * y + e[m32] * z + e[m33] )
this.x = ( e[m00] * x + e[m01] * y + e[m02] * z + e[m03] ) * w
this.y = ( e[m10] * x + e[m11] * y + e[m12] * z + e[m13] ) * w
this.z = ( e[m20] * x + e[m21] * y + e[m22] * z + e[m23] ) * w
return this
}
// multiply by rotation component contained within a 4x4 matrix
// assumes the upper-left 3x3 portion of the matrix is a pure rotation
// (i.e. no scale)
public fun applyRotationMatrix4(mat4: Matrix4f): Vector3f {
val x = this.x
val y = this.y
val z = this.z
val e = mat4.elements
this.x = e[m00] * x + e[m01] * y + e[m02] * z
this.y = e[m10] * x + e[m11] * y + e[m12] * z
this.z = e[m20] * x + e[m21] * y + e[m22] * z
return this
}
public fun applyQuaternion(q: Quaternion): Vector3f {
val x = this.x
val y = this.y
val z = this.z
val qx = q.x
val qy = q.y
val qz = q.z
val qw = q.w
// calculate quat * vector
val ix = qw * x + qy * z - qz * y
val iy = qw * y + qz * x - qx * z
val iz = qw * z + qx * y - qy * x
val iw = -qx * x - qy * y - qz * z
// calculate result * inverse quat
this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy
this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz
this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx
return this
}
// input: affine matrix
// vector interpreted as a direction
public fun transformDirection(mat4: Matrix4f): Vector3f {
val x = this.x
val y = this.y
val z = this.z
val e = mat4.elements
this.x = e[m00] * x + e[m01] * y + e[m02] * z
this.y = e[m10] * x + e[m11] * y + e[m12] * z
this.z = e[m20] * x + e[m21] * y + e[m22] * z
return this.normalize()
}
// linear interpolation with another vector
public fun lerp(v: Vector3f, alpha: Double): Vector3f {
val af = alpha.toFloat()
this.x += ( v.x - this.x ) * af
this.y += ( v.y - this.y ) * af
this.z += ( v.z - this.z ) * af
return this
}
// linear interpolation between two vectors
public fun lerpVectors(v1: Vector3f, v2: Vector3f, alpha: Double): Vector3f {
val af = alpha.toFloat()
this.x = v1.x * (1f - af) + v2.x * af
this.y = v1.y * (1f - af) + v2.y * af
this.z = v1.z * (1f - af) + v2.z * af
return this
}
public fun projectOnVector(v: Vector3f): Vector3f {
val mag = v.lengthSquared()
if ( mag == 0.0 ) {
return this.set(0.0, 0.0, 0.0)
}
val scalar = (v.dot(this) / mag).toFloat()
this.x = v.x * scalar
this.y = v.y * scalar
this.z = v.z * scalar
return this
}
public fun projectOnPlane(planeNormal: Vector3f): Vector3f {
val v = this.clone().projectOnVector(planeNormal)
return this.sub(v)
}
// reflect returns incident vector off plane orthogonal to normal
// normal assumed to have unit length
public fun reflect(normal: Vector3f): Vector3f {
return this.sub(normal).multiplyScalar(2.0 * this.dot(normal))
}
public fun angleTo(v: Vector3f): Double {
val denominator = Math.sqrt( this.lengthSquared() * v.lengthSquared() );
if ( denominator == 0.0 ) {
return Math.PI / 2.0
}
var theta = this.dot(v) / denominator
// clamp, to handle numerical problems
theta = Math.max(-1.0, Math.min(1.0, theta))
return Math.acos(theta)
}
public fun setFromMatrixPosition(m: Matrix4f): Vector3f {
val e = m.elements
this.x = e[m03]
this.y = e[m13]
this.z = e[m23]
return this
}
public fun setFromMatrixScale(m: Matrix4f): Vector3f {
val sx = this.setFromMatrixColumn(m, 0).length()
val sy = this.setFromMatrixColumn(m, 1).length()
val sz = this.setFromMatrixColumn(m, 2).length()
this.x = sx.toFloat()
this.y = sy.toFloat()
this.z = sz.toFloat()
return this
}
public fun fromFloatArray(array: FloatArray, offset: Int): Vector3f {
this.x = array[offset]
this.y = array[offset + 1]
this.z = array[offset + 2]
return this
}
public fun toFloatArray(): FloatArray {
val array: FloatArray = FloatArray(3)
array[0] = this.x
array[1] = this.y
array[2] = this.z
return array
}
public fun toFloatArray(array: FloatArray, offset: Int): FloatArray {
array[offset] = this.x
array[offset + 1] = this.y
array[offset + 2] = this.z
return array
}
// get matrix column, matrices in column-major format
// index column is [0, 1, 2, 3]
public fun setFromMatrixColumn(m: Matrix4f, index: Int): Vector3f {
when ( index ) {
0 -> {
this.x = m.elements[m00]
this.y = m.elements[m10]
this.z = m.elements[m20]
}
1 -> {
this.x = m.elements[m01]
this.y = m.elements[m11]
this.z = m.elements[m21]
}
2 -> {
this.x = m.elements[m02]
this.y = m.elements[m12]
this.z = m.elements[m22]
}
3 -> {
this.x = m.elements[m03]
this.y = m.elements[m13]
this.z = m.elements[m23]
}
else -> throw ArrayIndexOutOfBoundsException(index)
}
return this
}
}
| 0 |
Kotlin
|
0
| 9 |
55b6d7055fd6bed9377bebfa39b7084dd24d9341
| 15,447 |
minecraft-puppet
|
MIT License
|
app/src/main/java/au/sgallitz/pokedex/MainActivity.kt
|
Sarah-Gallitz
| 154,786,336 | false |
{"Kotlin": 2841}
|
package au.sgallitz.pokedex
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
class MainActivity : ComponentActivity() {
private val lightScheme = lightColorScheme()
private val darkScheme = darkColorScheme()
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MaterialTheme(
colorScheme = if (isSystemInDarkTheme()) darkScheme else lightScheme
) {
Scaffold(
topBar = { TopAppBar(title = { Text("Pokedex") }) }
) { defaultPadding ->
Column(
Modifier
.padding(defaultPadding)
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp)
) {
Card() {
Column(
Modifier
.fillMaxWidth()
.padding(
vertical = 24.dp,
horizontal = 16.dp
),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text("Hello World!", style = MaterialTheme.typography.titleLarge)
Text("This is a little demonstration app")
}
}
}
}
}
}
}
}
| 0 |
Kotlin
|
0
| 4 |
09ba294d5a4687d4819dd432f6aafd3aea9611f2
| 2,742 |
Sample-Tested-App
|
The Unlicense
|
Ejercicio02/app/src/main/java/com/example/ejercicio02/MainActivity.kt
|
romeramatias
| 346,540,395 | false | null |
package com.example.ejercicio02
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import com.example.ejercicio02.domain.User
class MainActivity : AppCompatActivity() {
// Cosas del Nav
private lateinit var navHostFragment: NavHostFragment
private lateinit var navController: NavController
// User
var user : User = User("matias","123")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
this.navController = navHostFragment.navController
NavigationUI.setupActionBarWithNavController(this, this.navController)
}
override fun onSupportNavigateUp(): Boolean {
return this.navController.navigateUp()
}
}
| 0 |
Kotlin
|
0
| 0 |
0f3d7fd5a42033b6377dbdde1f8fdd860186125d
| 1,169 |
ort-2-2-tp3
|
MIT License
|
app/src/main/java/com/antonioleiva/weatherapp/ui/adapters/ForecastListAdapter.kt
|
ppamorim
| 42,244,005 | true |
{"Kotlin": 17067, "Java": 358}
|
package com.antonioleiva.weatherapp.ui.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.antonioleiva.weatherapp.R
import com.antonioleiva.weatherapp.domain.model.Forecast
import com.antonioleiva.weatherapp.domain.model.ForecastList
import com.antonioleiva.weatherapp.extensions.ctx
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.item_forecast.view.*
import org.jetbrains.anko.layoutInflater
import org.jetbrains.anko.onClick
import org.jetbrains.anko.text
import java.text.DateFormat
import java.util.Locale
class ForecastListAdapter(val weekForecast: ForecastList, val itemClick: (Forecast) -> Unit) :
RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? {
val view = parent.ctx.layoutInflater.inflate(R.layout.item_forecast, parent, false)
return ViewHolder(view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindForecast(weekForecast[position])
}
override fun getItemCount() = weekForecast.size()
class ViewHolder(view: View, val itemClick: (Forecast) -> Unit) : RecyclerView.ViewHolder(view) {
fun bindForecast(forecast: Forecast) {
with(forecast) {
Picasso.with(itemView.ctx).load(iconUrl).into(itemView.icon)
itemView.date.text = convertDate(date)
itemView.description.text = description
itemView.maxTemperature.text = "${high.toString()}º"
itemView.minTemperature.text = "${low.toString()}º"
itemView.onClick { itemClick(forecast) }
}
}
private fun convertDate(date: Long): String {
val df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
return df.format(date)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
d0755afc949b86cda8470facd6857d4d52b208ee
| 1,957 |
Kotlin-for-Android-Developers
|
Apache License 2.0
|
src/main/kotlin/io/ashdavies/preferences/CoroutineSharedPreferences.kt
|
ashdavies
| 253,285,517 | false | null |
package io.ashdavies.preferences
import android.app.Application
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
internal class CoroutineSharedPreferences(
private val application: Application,
private val name: String
) : CoroutineValue<SharedPreferences> {
override suspend fun get(): SharedPreferences =
suspendCancellableCoroutine {
it.resume(application.getSharedPreferences(name, MODE_PRIVATE))
}
}
| 3 |
Kotlin
|
0
| 1 |
d51938f47a8ca5b37507400848b2b639be2a270e
| 570 |
preferences-store
|
Apache License 2.0
|
src/main/kotlin/math/Quaternion.kt
|
MJARuijs
| 238,959,670 | false | null |
package com.blazeit.game.math
import com.blazeit.game.math.matrices.Matrix4
import com.blazeit.game.math.vectors.Vector2
import com.blazeit.game.math.vectors.Vector3
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
data class Quaternion(var w: Float = 1.0f, var x: Float = 0.0f, var y: Float = 0.0f, var z: Float = 0.0f) {
constructor(quaternion: Quaternion): this(quaternion.w, quaternion.x, quaternion.y, quaternion.z)
constructor(angles: Vector2): this(Quaternion(Axis.X, angles.x) * Quaternion(Axis.Y, angles.y))
constructor(angles: Vector3): this(Quaternion(Axis.X, angles.x) * Quaternion(Axis.Y, angles.y) * Quaternion(Axis.Z, angles.z))
constructor(normal: Vector3, angle: Float): this(
cos(angle / 2.0f),
normal.x * sin(angle / 2.0f),
normal.y * sin(angle / 2.0f),
normal.z * sin(angle / 2.0f)
)
constructor(axis: Axis, angle: Float): this(axis.normal, angle)
fun toMatrix(): Matrix4 {
val normal = normal()
val x = normal.x
val y = normal.y
val z = normal.z
val w = normal.w
return Matrix4(floatArrayOf(
1.0f - 2.0f * y * y - 2.0f * z * z, 2.0f * x * y - 2.0f * z * w, 2.0f * x * z + 2.0f * y * w, 0.0f,
2.0f * x * y + 2.0f * z * w, 1.0f - 2.0f * x * x - 2.0f * z * z, 2.0f * y * z - 2.0f * x * w, 0.0f,
2.0f * x * z - 2.0f * y * w, 2.0f * y * z + 2.0f * x* w, 1.0f - 2.0f * x * x - 2.0f * y * y, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
))
}
operator fun unaryMinus() = Quaternion(-w, -x, -y, -z)
operator fun plus(other: Quaternion) = Quaternion(w + other.w, x + other.x, y + other.y, z + other.z)
operator fun minus(other: Quaternion) = Quaternion(w - other.w, x - other.x, y - other.y, z - other.z)
operator fun times(other: Quaternion) = Quaternion(
((w * other.w) - (x * other.x) - (y * other.y) - (z * other.z)),
((w * other.x) + (x * other.w) + (y * other.z) - (z * other.y)),
((w * other.y) - (x * other.z) + (y * other.w) + (z * other.x)),
((w * other.z) + (x * other.y) - (y * other.x) + (z * other.w))
)
operator fun times(vector: Vector3): Vector3 {
val point = Quaternion(0.0f, vector.x, vector.y, vector.z)
val unit = unit()
val result = (unit * point) * unit.conjugate()
return Vector3(result.x, result.y, result.z)
}
operator fun times(factor: Float) = Quaternion(w * factor, x * factor, y * factor, z * factor)
operator fun div(factor: Float) = Quaternion(w / factor, x / factor, y * factor, z / factor)
fun dot(other: Quaternion) = (w * other.w) + (x * other.x) + (y * other.y) + (z * other.z)
fun conjugate() = Quaternion(w, -x, -y, -z)
fun transposition() = conjugate()
fun norm() = sqrt(dot(this))
fun length() = norm()
fun size() = norm()
fun magnitude() = norm()
fun absolute() = norm()
fun modulus() = norm()
fun versor() = div(norm())
fun normal() = versor()
fun unit() = versor()
fun normalize() {
val length = length()
w /= length
x /= length
y /= length
z /= length
}
fun reciprocal() = conjugate() / norm()
fun inverse() = reciprocal()
/**
* @return the string representation of the quaternion.
*/
override fun toString() = "<$w, $x, $y, $z>"
}
| 0 |
Kotlin
|
0
| 0 |
ba34391da0b523907d84d71e47b70f4ad3c12173
| 3,465 |
Morgan
|
MIT License
|
src/main/kotlin/org/incava/mesa/IntColumn.kt
|
jpace
| 483,382,354 | false |
{"Kotlin": 259801, "Ruby": 674}
|
package org.incava.mesa
open class IntColumn(header: String, width: Int) : Column(header, width) {
override fun cellFormat(): String {
return "%${width}d"
}
}
| 0 |
Kotlin
|
0
| 0 |
b359710848fa9e5126eadd20bb66e1f1d900ac24
| 175 |
mmonkeys
|
MIT License
|
calf-ui/src/iosMain/kotlin/com/mohamedrejeb/calf/ui/timepicker/AdaptiveTimePicker.ios.kt
|
MohamedRejeb
| 674,932,206 | false | null |
package com.mohamedrejeb.calf.ui.timepicker
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.interop.UIKitView
import androidx.compose.ui.unit.dp
import com.mohamedrejeb.calf.core.InternalCalfApi
import kotlinx.cinterop.ExperimentalForeignApi
import platform.UIKit.UIDatePicker
@OptIn(ExperimentalMaterial3Api::class, ExperimentalForeignApi::class, InternalCalfApi::class)
@Composable
actual fun AdaptiveTimePicker(
state: AdaptiveTimePickerState,
modifier: Modifier,
colors: TimePickerColors,
layoutType: TimePickerLayoutType,
) {
val datePicker = remember {
UIDatePicker()
}
val datePickerManager = remember {
TimePickerManager(
datePicker = datePicker,
initialMinute = state.minute,
initialHour = state.hour,
is24Hour = state.is24hour,
onHourChanged = { hour ->
state.hourState = hour
},
onMinuteChanged = { minute ->
state.minuteState = minute
}
)
}
UIKitView(
factory = {
datePicker
},
modifier = modifier
.then(
if (datePickerManager.datePickerWidth.value > 0f)
Modifier.width(datePickerManager.datePickerWidth.value.dp)
else
Modifier
)
.then(
if (datePickerManager.datePickerHeight.value > 0f)
Modifier.height(datePickerManager.datePickerHeight.value.dp)
else
Modifier
)
)
}
| 28 | null |
41
| 905 |
acb2a7388a776a6f22fcf7f351868359c3113695
| 1,835 |
Calf
|
Apache License 2.0
|
kotlin-typescript/src/jsMain/generated/typescript/ImmediatelyInvokedArrowFunctionExpression.kt
|
JetBrains
| 93,250,841 | false |
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Automatically generated - do not modify!
package typescript
sealed external interface ImmediatelyInvokedArrowFunctionExpression : ParenthesizedExpression {
override val expression: ArrowFunction
}
| 38 |
Kotlin
|
162
| 1,347 |
997ed3902482883db4a9657585426f6ca167d556
| 206 |
kotlin-wrappers
|
Apache License 2.0
|
EnableDisableButton/app/src/main/java/algokelvin/app/csenabledbtn/EdtTxtViewModel.kt
|
algokelvin-373
| 342,448,208 | false |
{"Kotlin": 31878, "Java": 18969}
|
package algokelvin.app.csenabledbtn
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class EdtTxtViewModel: ViewModel() {
fun rqsStatus(pin: String): LiveData<Boolean> {
val status = MutableLiveData<Boolean>()
if (pin == "123456") {
status.postValue(true)
} else {
status.postValue(false)
}
return status
}
}
| 0 |
Kotlin
|
3
| 6 |
1c39012041c15a3be30f7355ebb02a2539d8205d
| 447 |
ProjectAppAndroid
|
Apache License 2.0
|
EnableDisableButton/app/src/main/java/algokelvin/app/csenabledbtn/EdtTxtViewModel.kt
|
algokelvin-373
| 342,448,208 | false |
{"Kotlin": 31878, "Java": 18969}
|
package algokelvin.app.csenabledbtn
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class EdtTxtViewModel: ViewModel() {
fun rqsStatus(pin: String): LiveData<Boolean> {
val status = MutableLiveData<Boolean>()
if (pin == "123456") {
status.postValue(true)
} else {
status.postValue(false)
}
return status
}
}
| 0 |
Kotlin
|
3
| 6 |
1c39012041c15a3be30f7355ebb02a2539d8205d
| 447 |
ProjectAppAndroid
|
Apache License 2.0
|
app/src/main/java/com/sudhirkhanger/genius/ui/list/MainViewModelFactory.kt
|
ChandrakantOmn
| 154,100,839 | true |
{"Kotlin": 46352}
|
/*
* 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.sudhirkhanger.genius.ui.list
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.sudhirkhanger.genius.data.MovieRepository
import com.sudhirkhanger.genius.di.scopes.ActivityScope
import javax.inject.Inject
@ActivityScope
class MainViewModelFactory @Inject constructor(private val movieRepository: MovieRepository) :
ViewModelProvider.NewInstanceFactory() {
// https://stackoverflow.com/a/45517555/3034693
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
modelClass.getConstructor(MovieRepository::class.java).newInstance(movieRepository)
}
| 0 |
Kotlin
|
0
| 0 |
f77ef1cb1aac31b23433cc91fbbda3e959483fbe
| 1,235 |
Genius
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/RemoveVideoStream.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
/**
*````
*
* Name: RemoveVideoStream
*
* Full name: System`RemoveVideoStream
*
* RemoveVideoStream[] deletes all VideoStream objects.
* RemoveVideoStream[stream] deletes the VideoStream object stream.
* Usage: RemoveAudioStream[video] deletes all the VideoStream objects stemming from video.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/RemoveVideoStream
* Documentation: web: http://reference.wolfram.com/language/ref/RemoveVideoStream.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun removeVideoStream(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("RemoveVideoStream", arguments.toMutableList(), options)
}
| 2 |
Kotlin
|
0
| 3 |
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,201 |
mathemagika
|
Apache License 2.0
|
sample/src/main/java/com/liarstudio/recycler_drag/base/DragModel.kt
|
midery
| 208,662,886 | false | null |
package com.liarstudio.recycler_drag.base
class DragModel(
var sourceItemId: String = EMPTY_DRAG_ID,
var targetItemId: String = EMPTY_DRAG_ID,
var isPlacedUp: Boolean = false
) {
/**
* Проверка на одинаковый id у целевого и перетаскиваемого элементов
*/
val hasSameId get() = sourceItemId == targetItemId
/**
* Проверка на то, было ли начато перетаскивание
*/
val isInitialized get() = sourceItemId != EMPTY_DRAG_ID && targetItemId != EMPTY_DRAG_ID
/**
* Очистка модели
*/
fun clear() {
sourceItemId = EMPTY_DRAG_ID
targetItemId = EMPTY_DRAG_ID
isPlacedUp = false
}
companion object {
private const val EMPTY_DRAG_ID = "EMPTY_DRAG_ID"
}
}
| 0 |
Kotlin
|
0
| 1 |
cac98a99e5395abecdaf79f3c3a30dccdabf85d2
| 752 |
RecyclerDragHelper
|
Apache License 2.0
|
database/src/main/java/com/cerminnovations/database/entities/tv/trendingweek/TrendingWeekRemoteKey.kt
|
mbobiosio
| 324,425,383 | false | null |
package com.cerminnovations.database.entities.tv.trendingweek
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* @Author <NAME>
* https://linktr.ee/mbobiosio
*/
@Entity(tableName = "trending_week_tv_remote_keys")
data class TrendingWeekRemoteKey(
@PrimaryKey
val tvId: Long,
val prevKey: Int?,
val nextKey: Int?
)
| 0 |
Kotlin
|
3
| 7 |
07270aa17f45edabfb6792fd529c212e1c585ce4
| 350 |
MoviesBoard
|
MIT License
|
app/src/main/java/com/sample/tmdb/data/response/DetailDto.kt
|
alirezaeiii
| 544,156,630 | false | null |
package com.sample.tmdb.data.response
import com.sample.tmdb.domain.model.Genre
import com.sample.tmdb.domain.model.MovieDetails
import com.sample.tmdb.domain.model.SpokenLanguage
import com.sample.tmdb.domain.model.TvDetails
import com.sample.tmdb.utils.Constants.BASE_WIDTH_342_PATH
import com.sample.tmdb.utils.Constants.BASE_WIDTH_780_PATH
import com.squareup.moshi.Json
interface TMDbItemDetailsResponse {
val backdropPath: String?
val genres: List<GenreResponse>
val homepage: String?
val id: Int
val originalLanguage: String
val originalTitle: String
val overview: String
val popularity: Double
val posterPath: String?
val releaseDate: String?
val spokenLanguages: List<SpokenLanguageResponse>
val status: String
val tagline: String
val title: String
val voteAverage: Double
val voteCount: Int
}
data class MovieDetailResponse(
@Json(name = "backdrop_path") override val backdropPath: String?,
@Json(name = "genres") override val genres: List<GenreResponse>,
@Json(name = "homepage") override val homepage: String?,
@Json(name = "id") override val id: Int,
@Json(name = "original_language") override val originalLanguage: String,
@Json(name = "original_title") override val originalTitle: String,
@Json(name = "overview") override val overview: String,
@Json(name = "popularity") override val popularity: Double,
@Json(name = "poster_path") override val posterPath: String?,
@Json(name = "release_date") override val releaseDate: String?,
@Json(name = "spoken_languages") override val spokenLanguages: List<SpokenLanguageResponse>,
@Json(name = "status") override val status: String,
@Json(name = "tagline") override val tagline: String,
@Json(name = "title") override val title: String,
@Json(name = "vote_average") override val voteAverage: Double,
@Json(name = "vote_count") override val voteCount: Int
) : TMDbItemDetailsResponse
data class TvDetailResponse(
@Json(name = "backdrop_path") override val backdropPath: String?,
@Json(name = "genres") override val genres: List<GenreResponse>,
@Json(name = "homepage") override val homepage: String?,
@Json(name = "id") override val id: Int,
@Json(name = "original_language") override val originalLanguage: String,
@Json(name = "original_name") override val originalTitle: String,
@Json(name = "overview") override val overview: String,
@Json(name = "popularity") override val popularity: Double,
@Json(name = "poster_path") override val posterPath: String?,
@Json(name = "first_air_date") override val releaseDate: String?,
@Json(name = "spoken_languages") override val spokenLanguages: List<SpokenLanguageResponse>,
@Json(name = "status") override val status: String,
@Json(name = "tagline") override val tagline: String,
@Json(name = "name") override val title: String,
@Json(name = "vote_average") override val voteAverage: Double,
@Json(name = "vote_count") override val voteCount: Int,
) : TMDbItemDetailsResponse
data class GenreResponse(
@Json(name = "id") val id: Int,
@Json(name = "name") val name: String?
)
data class SpokenLanguageResponse(
@Json(name = "iso_639_1") val iso6391: String,
@Json(name = "name") val name: String
)
fun MovieDetailResponse.asDomainModel(): MovieDetails = MovieDetails(
backdropPath?.let {
String.format(
BASE_WIDTH_780_PATH,
it
)
}, genres.asGenreDomainModel(),
homepage, id, originalLanguage, originalTitle, overview, popularity, posterPath?.let {
String.format(
BASE_WIDTH_342_PATH,
it
)
}, releaseDate,
spokenLanguages.asLanguageDomainModel(), status, tagline, title, voteAverage, voteCount
)
fun TvDetailResponse.asDomainModel(): TvDetails = TvDetails(
backdropPath?.let {
String.format(
BASE_WIDTH_780_PATH,
it
)
},
genres.asGenreDomainModel(),
homepage,
id,
originalLanguage,
originalTitle,
overview,
popularity,
posterPath?.let {
String.format(
BASE_WIDTH_342_PATH,
it
)
},
releaseDate,
spokenLanguages.asLanguageDomainModel(),
status,
tagline,
title,
voteAverage,
voteCount
)
private fun List<GenreResponse>.asGenreDomainModel(): List<Genre> = map {
Genre(it.id, it.name)
}
private fun List<SpokenLanguageResponse>.asLanguageDomainModel(): List<SpokenLanguage> = map {
SpokenLanguage(it.iso6391, it.name)
}
| 0 |
Kotlin
|
0
| 1 |
dc398a09f4dacda2201a1362a7711bc508d77978
| 4,596 |
TMDb-Compose-Playground
|
The Unlicense
|
core/src/main/java/vn/thailam/core/ResultState.kt
|
ngthailam
| 710,795,027 | false |
{"Kotlin": 40074}
|
package vn.thailam.core
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@OptIn(ExperimentalContracts::class)
sealed class ResultState {
object Loading : ResultState()
data class Success<T>(val data: T) : ResultState()
data class Failure(val throwable: Throwable) : ResultState()
fun isLoading(): Boolean {
contract {
returns(true) implies (this@ResultState is Loading)
}
return this is Loading
}
fun isSuccess(): Boolean {
contract {
returns(true) implies (this@ResultState is Success<*>)
}
return this is Success<*>
}
fun isFailure(): Boolean {
contract {
returns(true) implies (this@ResultState is Failure)
}
return this is Failure
}
}
| 4 |
Kotlin
|
0
| 0 |
f694fba45c30b16556971c7f73cf312ad1466e64
| 818 |
android-base
|
MIT License
|
src/test/kotlin/org/jetbrains/kotlinx/dataframe/api/implode.kt
|
Kotlin
| 259,256,617 | false | null |
package org.jetbrains.kotlinx.dataframe.api
import io.kotest.matchers.shouldBe
import org.junit.Test
class ImplodeTests {
@Test
fun `implode into`() {
val df = dataFrameOf("a" to listOf(1, 1), "b" to listOf(2, 3))
val imploded = df.implode { "b" into "c" }
val expected = dataFrameOf("a" to listOf(1), "c" to listOf(listOf(2, 3)))
imploded shouldBe expected
}
@Test
fun `implode all`() {
val df = dataFrameOf("a" to listOf(1, 1), "b" to listOf(2, 3))
df.implode() shouldBe df.implode { all() }[0]
}
}
| 10 |
Kotlin
|
4
| 94 |
41a099b4d9b563d0518e1550e764211f43e34702
| 577 |
dataframe
|
Apache License 2.0
|
app/src/main/java/ac/id/unikom/codelabs/navigasee/data/model/list_transportation_available/Duration.kt
|
DewaTriWijaya
| 708,758,940 | false |
{"Kotlin": 300215, "Java": 197611}
|
package ac.id.unikom.codelabs.navigasee.data.model.list_transportation_available
import com.google.gson.annotations.SerializedName
data class Duration(
@field:SerializedName("text")
val text: String? = null,
@field:SerializedName("value")
val value: Int? = null
)
| 0 |
Kotlin
|
0
| 0 |
d6e6693760962842ed798fa66ad75be2044ee232
| 299 |
Voiye
|
Apache License 2.0
|
app/src/main/java/com/batdemir/github/ui/detail/DetailViewModel.kt
|
batdemir
| 316,447,806 | false | null |
package com.batdemir.github.ui.detail
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.batdemir.github.data.entities.RepositoryModel
import com.batdemir.github.data.repository.GithubRepository
import kotlinx.coroutines.launch
import javax.inject.Inject
class DetailViewModel @Inject constructor(
private val githubRepository: GithubRepository
) : ViewModel() {
private val _item = MutableLiveData<RepositoryModel>()
val item: LiveData<RepositoryModel> = _item
fun start(repositoryModel: RepositoryModel) {
_item.value = repositoryModel
}
fun updateModel(): Boolean {
val status = !_item.value!!.isFavorite
_item.value!!.isFavorite = status
viewModelScope.launch {
githubRepository.updateRepository(_item.value!!)
}
return status
}
}
| 0 |
Kotlin
|
0
| 0 |
5ab4fc9ad687cadb0fa816523414691417257dc5
| 941 |
github.kotlin
|
Apache License 2.0
|
src/main/kotlin/compat/Tools.kt
|
guame
| 108,177,271 | true |
{"Kotlin": 70488, "CSS": 9213, "HTML": 3083, "JavaScript": 1120, "Batchfile": 1089, "Shell": 455}
|
package compat
import android.content.res.AssetManager
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
/**
* Utility class that should be reworked in Android project to use standard
* Android classes (Base64, classloader) instead of JDK or Apache Commons ones.
*/
class Tools {
companion object {
val PAUSE_BETWEEN_MAG_DL = 30L
val VERSION_URL = "https://raw.githubusercontent.com/jonathanlermitage/tikione-c2e/master/uc/latest_version.txt"
val VERSION = resourceAsStr("version.txt", AssetManager())
var debug = false
private val log: Logger = LoggerFactory.getLogger(Tools::class.java.javaClass)
@Suppress("UNUSED_PARAMETER")
@Throws(IOException::class)
@JvmStatic
fun resourceAsBase64(path: String, asset: AssetManager): String {
return Base64.encodeBase64String(IOUtils.toByteArray(Tools::class.java.classLoader.getResourceAsStream(path)))
}
@Suppress("UNUSED_PARAMETER")
@Throws(IOException::class)
@JvmStatic
fun resourceAsStr(path: String, asset: AssetManager): String {
return IOUtils.toString(Tools::class.java.classLoader.getResourceAsStream(path), StandardCharsets.UTF_8)
}
/**
* Resize a picture.
* Based on ImageMagick (must be in path) and validated with ImageMagick-7.0.6-10-Q16-x64 on Windows-8.1-x64.
*
* todo: why not using Java directly for this operation ?
* see https://stackoverflow.com/questions/244164/how-can-i-resize-an-image-using-java
*
* @param src original picture.
* @param dest new picture.
* @param resize new size ratio (percents), eg. '50'.
* @return convert (ImageMagick) exit value.
*/
@JvmStatic
fun resizePicture(src: String, dest: String, resize: String): Int {
val cmd = "magick convert -resize $resize% $src $dest"
val p = Runtime.getRuntime().exec(cmd)
p.waitFor(30, TimeUnit.SECONDS)
val ev = p.exitValue()
if (ev != 0) {
log.warn("la commande ImageMagick [$cmd] s'est teminee ave le code [$ev]")
}
return ev
}
@JvmStatic
fun setProxy(host: String, port: String) {
log.info("utilisation du proxy HTTP(S) {}:{}", host, port)
System.setProperty("http.proxyHost", host)
System.setProperty("http.proxyPort", port)
System.setProperty("https.proxyHost", host)
System.setProperty("https.proxyPort", port)
}
@JvmStatic
fun setSysProxy() {
log.info("utilisation du proxy systeme")
System.setProperty("java.net.useSystemProxies", "true")
}
}
}
| 0 |
Kotlin
|
0
| 1 |
9c75eaa11a325943df0ef1da486ed7c3d0b25789
| 3,001 |
tikione-c2e
|
MIT License
|
app/src/main/java/com/montfel/pokfinder/di/DataSourcesModule.kt
|
Montfel
| 489,497,209 | false | null |
package com.montfel.pokfinder.di
import com.apollographql.apollo3.ApolloClient
import com.montfel.pokfinder.data.home.service.HomeService
import com.montfel.pokfinder.data.profile.service.ProfileService
import com.montfel.pokfinder.domain.home.usecase.HomeUseCases
import com.montfel.pokfinder.domain.home.usecase.SortPokemonsUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal object DataSourcesModule {
@Singleton
@Provides
fun providesProfileService(retrofit: Retrofit): ProfileService =
retrofit.create(ProfileService::class.java)
@Singleton
@Provides
fun providesHomeService(apolloClient: ApolloClient) = HomeService(apolloClient)
@Provides
@Singleton
fun providesHomeUseCases() = HomeUseCases(sortPokemonsUseCase = SortPokemonsUseCase())
}
| 24 |
Kotlin
|
2
| 8 |
9231d27521814ba3db15e43b324e2af4d36475de
| 984 |
pokfinder
|
MIT License
|
src/main/kotlin/com/saintdan/framework/repo/OauthRefreshTokenRepository.kt
|
danielliao11
| 114,665,498 | false | null |
package com.saintdan.framework.repo
import com.saintdan.framework.po.OauthRefreshToken
import org.springframework.data.jpa.repository.JpaRepository
import java.util.*
/**
* @author <a href="http://github.com/saintdan"><NAME></a>
* @date 19/12/2017
* @since JDK1.8
*/
interface OauthRefreshTokenRepository : JpaRepository<OauthRefreshToken, String> {
fun findByTokenId(tokenId: String): Optional<OauthRefreshToken>
}
| 0 |
Kotlin
|
0
| 1 |
2d8a85b1f542e54f957371943e4395cd99cc2e4a
| 424 |
kotlin-spring-microservices-biolerplate
|
MIT License
|
PercentagesWithAnimationCompose/src/main/java/com/nicos/percentageswithanimationcompose/CirclePercentage.kt
|
NicosNicolaou16
| 825,364,273 | false |
{"Kotlin": 34204}
|
package com.nicos.percentageswithanimationcompose
import androidx.annotation.FloatRange
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp.Companion.Infinity
import androidx.compose.ui.unit.dp
/**
* @param currentPercentage - The current value of the progress indicator (current value must be less than or equal to maximum value currentValue >= 0 && currentValue <= maximumValue)
* @param maxPercentage - The maximum value of the progress indicator (maximum value must be greater than or equal to 0)
* @param circleSize - The size of the circle, default value is 100
* @param percentageAnimationDuration - The duration of the animation (percentage animation duration must be greater than or equal to 0)
* @param circlePercentageBackgroundColor - The background color of the circle, default value is LightGray
* @param circlePercentageColor - The color of the circle, default value is Black
* @param circleStrokeBackgroundWidth - The width of the circle stroke, default value is 10
* @param centerTextStyle - The text style of the center text
* */
@Composable
fun CirclePercentage(
@FloatRange(
from = 0.0,
to = Float.MAX_VALUE.toDouble()
)
currentPercentage: Float,
@FloatRange(
from = 0.0,
to = Float.MAX_VALUE.toDouble()
)
maxPercentage: Float,
circleSize: Int = 100,
percentageAnimationDuration: Int = 1_500,
circlePercentageBackgroundColor: Color = Color.LightGray,
circlePercentageColor: Color = Color.Black,
circleStrokeBackgroundWidth: Float = 10F,
centerTextStyle: TextStyle,
) {
assert(currentPercentage >= 0) { "Current value must be greater than or equal to 0" }
assert(currentPercentage <= maxPercentage) { "Current value must be less than or equal to maximum value" }
assert(percentageAnimationDuration >= 0) { "Percentage animation duration must be greater than or equal to 0" }
assert(circleSize >= 0) { "Circular size must be greater than or equal to 0" }
assert(circleStrokeBackgroundWidth > 0) { "Circle stroke background width must be greater than 0" }
var percentage by remember { mutableFloatStateOf(0F) }
var actualPercentage by remember { mutableFloatStateOf(0F) }
val progressAnimation by animateFloatAsState(
targetValue = if (percentage != Infinity.value) percentage else 0F,
animationSpec = tween(
durationMillis = percentageAnimationDuration,
easing = FastOutSlowInEasing
),
label = "",
)
Box(contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.size(circleSize.dp)) {
actualPercentage = (progressAnimation / 360) * maxPercentage
drawCircle(
color = circlePercentageBackgroundColor,
style = Stroke(width = circleStrokeBackgroundWidth),
radius = size.minDimension / 2,
center = Offset(size.width / 2, size.height / 2)
)
drawArc(
color = circlePercentageColor,
startAngle = -90f,
sweepAngle = progressAnimation,
useCenter = true,
size = Size(size.width, size.height),
topLeft = Offset(0f, 0f)
)
}
Text(
text = actualPercentage.toInt().toString(),
style = centerTextStyle,
)
}
LaunchedEffect(Unit) {
percentage = (currentPercentage * 360) / maxPercentage
}
}
@Preview
@Composable
private fun CirclePercentagePreview() {
CirclePercentage(
currentPercentage = 50F,
maxPercentage = 100F,
centerTextStyle = TextStyle(
color = Color.Black,
textAlign = TextAlign.Center
)
)
}
| 0 |
Kotlin
|
0
| 6 |
c9df8df5ad512067296627dd39ef3275bd98f331
| 4,737 |
PercentagesWithAnimationCompose
|
Apache License 2.0
|
src/main/kotlin/ch10/1.6_4_MakingCodeMoreReusableByReducingDuplicationWithLambdas3.kt
|
draganglumac
| 843,717,905 | false |
{"Kotlin": 114145, "Java": 878}
|
package ch10.ex6_4_MakingCodeMoreReusableByReducingDuplicationWithLambdas3
data class SiteVisit(
val path: String,
val duration: Double,
val os: OS,
)
enum class OS { WINDOWS, LINUX, MAC, IOS, ANDROID }
val log = listOf(
SiteVisit("/", 34.0, OS.WINDOWS),
SiteVisit("/", 22.0, OS.MAC),
SiteVisit("/login", 12.0, OS.WINDOWS),
SiteVisit("/signup", 8.0, OS.IOS),
SiteVisit("/", 16.3, OS.ANDROID)
)
fun List<SiteVisit>.averageDurationFor(predicate: (SiteVisit) -> Boolean) =
filter(predicate).map(SiteVisit::duration).average()
fun main() {
println(
log.averageDurationFor {
it.os in setOf(OS.ANDROID, OS.IOS)
}
)
// 12.15
println(
log.averageDurationFor {
it.os == OS.IOS && it.path == "/signup"
}
)
// 8.0
}
| 0 |
Kotlin
|
0
| 0 |
ba8291a209fb7c6bae4997c1c9da2e7910788aed
| 826 |
kotlin-in-action-2e-main
|
MIT License
|
Fragment/Lazy/src/main/java/fragment/develop/android/lazy/LazyMainActivity.kt
|
WenChaoLuo
| 187,828,306 | true |
{"Markdown": 85, "HTML": 101, "Java Properties": 41, "Shell": 24, "Batchfile": 24, "Proguard": 43, "Java": 645, "Kotlin": 194, "CSS": 1, "INI": 8, "JavaScript": 7, "CMake": 1, "C++": 1, "Objective-C": 4}
|
package fragment.develop.android.lazy
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.lazy_activity_main.*
import java.util.*
class LazyMainActivity : AppCompatActivity() {
private lateinit var mData: MutableList<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.lazy_activity_main)
mData = ArrayList()
mData.add("一")
mData.add("二")
mData.add("三")
mData.add("四")
mData.add("五")
mData.add("六")
mData.add("七")
val tabNameAdapter = TabNameAdapter(supportFragmentManager)
viewPager.adapter = tabNameAdapter
viewPager.offscreenPageLimit = mData.size
tabLayout.setupWithViewPager(viewPager)
}
inner class TabNameAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment = TestLazyFragment.newInstance(position)
override fun getPageTitle(position: Int): CharSequence? = mData[position]
override fun getCount(): Int = mData.size
}
}
| 0 |
Java
|
0
| 0 |
3aa2a1973279f9d836b3ebb97cc82f0593fa0023
| 1,301 |
AndroidDevelop
|
Apache License 2.0
|
sample/app/src/main/java/com/google/android/jacquard/sample/haptics/HapticsViewModel.kt
|
gildardoperez
| 624,963,235 | true |
{"Text": 2, "Markdown": 16, "Gradle": 8, "Ignore List": 5, "Java Properties": 2, "XML": 138, "Shell": 2, "Proguard": 2, "Java": 251, "JSON": 4, "YAML": 1, "SVG": 2, "SCSS": 1, "JavaScript": 1, "INI": 1, "Kotlin": 100}
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.jacquard.sample.haptics
import android.content.res.Resources
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.google.android.jacquard.sample.ConnectivityManager
import com.google.android.jacquard.sample.ConnectivityManager.Events
import com.google.android.jacquard.sample.Preferences
import com.google.android.jacquard.sample.R
import com.google.android.jacquard.sdk.command.HapticCommand
import com.google.android.jacquard.sdk.connection.ConnectionState
import com.google.android.jacquard.sdk.model.Component
import com.google.android.jacquard.sdk.model.GearState
import com.google.android.jacquard.sdk.rx.Fn
import com.google.android.jacquard.sdk.rx.Signal
import com.google.android.jacquard.sdk.tag.ConnectedJacquardTag
/** View model class for the [HapticsFragment]. */
class HapticsViewModel(
private val connectivityManager: ConnectivityManager,
private val navController: NavController,
private val resources: Resources,
private val preferences: Preferences
) : ViewModel() {
private lateinit var connectionStateSignal: Signal<ConnectionState>
private lateinit var connectedJacquardTag: Signal<ConnectedJacquardTag>
/**
* Initialize view model, It should be called from onViewCreated.
*/
fun init() {
preferences.currentTag?.let {
connectionStateSignal = connectivityManager
.getConnectionStateSignal(it.address())
connectedJacquardTag = connectivityManager
.getConnectedJacquardTag(it.address())
}
}
fun sendHapticRequest(type: HapticPatternType): Signal<Boolean> {
return getAttachedComponent().first().flatMap { attachedComponent: Component ->
getConnectedJacquardTag().first()
.switchMap { connectedJacquardTag: ConnectedJacquardTag ->
connectedJacquardTag
.enqueue(HapticCommand(type.getFrame(), attachedComponent))
}
}
}
private fun getAttachedComponent(): Signal<Component> {
return getConnectionStateSignal().first().flatMap { connectionState: ConnectionState ->
check(connectionState.isType(ConnectionState.Type.CONNECTED)) { resources.getString(R.string.tag_not_connected) }
getGearNotification().first()
}.map { gearState: GearState ->
check(gearState.type == GearState.Type.ATTACHED) { resources.getString(R.string.gear_detached) }
gearState.attached()
}
}
/**
* Handles back arrow in toolbar.
*/
fun backArrowClick() {
navController.popBackStack()
}
/**
* Emits connectivity events [Events].
*/
fun getConnectivityEvents(): Signal<Events> {
return preferences.currentTag?.let {
connectivityManager.getEventsSignal(it.address())
.distinctUntilChanged()
} ?: Signal.empty()
}
private fun getGearNotification(): Signal<GearState> {
return connectedJacquardTag
.distinctUntilChanged()
.switchMap(
Fn { obj: ConnectedJacquardTag -> obj.connectedGearSignal } as Fn<ConnectedJacquardTag, Signal<GearState>>)
}
private fun getConnectionStateSignal(): Signal<ConnectionState> {
return connectionStateSignal.distinctUntilChanged()
}
private fun getConnectedJacquardTag(): Signal<ConnectedJacquardTag> {
return connectedJacquardTag.distinctUntilChanged()
}
}
| 0 | null |
0
| 0 |
f88ec2dea9813203a4ed5d70646915c4d5651d6e
| 4,134 |
JacquardSDKAndroid
|
Apache License 2.0
|
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/CatalogsUpdatableHotelAttributes.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.JsonProperty
import org.openapitools.model.CatalogsHotelAddress
import org.openapitools.model.CatalogsHotelGuestRatings
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
/**
*
* @param name The hotel's name.
* @param link Link to the product page
* @param description Brief description of the hotel.
* @param brand The brand to which this hotel belongs to.
* @param latitude Latitude of the hotel.
* @param longitude Longitude of the hotel.
* @param neighborhood A list of neighborhoods where the hotel is located
* @param address
* @param customLabel0 Custom grouping of hotels
* @param customLabel1 Custom grouping of hotels
* @param customLabel2 Custom grouping of hotels
* @param customLabel3 Custom grouping of hotels
* @param customLabel4 Custom grouping of hotels
* @param category The type of property. The category can be any type of internal description desired.
* @param basePrice Base price of the hotel room per night followed by the ISO currency code
* @param salePrice Sale price of a hotel room per night. Used to advertise discounts off the regular price of the hotel.
* @param guestRatings
*/
data class CatalogsUpdatableHotelAttributes(
@Schema(example = "null", description = "The hotel's name.")
@get:JsonProperty("name") val name: kotlin.String? = null,
@Schema(example = "null", description = "Link to the product page")
@get:JsonProperty("link") val link: kotlin.String? = null,
@Schema(example = "null", description = "Brief description of the hotel.")
@get:JsonProperty("description") val description: kotlin.String? = null,
@Schema(example = "null", description = "The brand to which this hotel belongs to.")
@get:JsonProperty("brand") val brand: kotlin.String? = null,
@Schema(example = "null", description = "Latitude of the hotel.")
@get:JsonProperty("latitude") val latitude: java.math.BigDecimal? = null,
@Schema(example = "null", description = "Longitude of the hotel.")
@get:JsonProperty("longitude") val longitude: java.math.BigDecimal? = null,
@Schema(example = "null", description = "A list of neighborhoods where the hotel is located")
@get:JsonProperty("neighborhood") val neighborhood: kotlin.collections.List<kotlin.String>? = null,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("address") val address: CatalogsHotelAddress? = null,
@Schema(example = "null", description = "Custom grouping of hotels")
@get:JsonProperty("custom_label_0") val customLabel0: kotlin.String? = null,
@Schema(example = "null", description = "Custom grouping of hotels")
@get:JsonProperty("custom_label_1") val customLabel1: kotlin.String? = null,
@Schema(example = "null", description = "Custom grouping of hotels")
@get:JsonProperty("custom_label_2") val customLabel2: kotlin.String? = null,
@Schema(example = "null", description = "Custom grouping of hotels")
@get:JsonProperty("custom_label_3") val customLabel3: kotlin.String? = null,
@Schema(example = "null", description = "Custom grouping of hotels")
@get:JsonProperty("custom_label_4") val customLabel4: kotlin.String? = null,
@Schema(example = "null", description = "The type of property. The category can be any type of internal description desired.")
@get:JsonProperty("category") val category: kotlin.String? = null,
@Schema(example = "100 USD", description = "Base price of the hotel room per night followed by the ISO currency code")
@get:JsonProperty("base_price") val basePrice: kotlin.String? = null,
@Schema(example = "90 USD", description = "Sale price of a hotel room per night. Used to advertise discounts off the regular price of the hotel.")
@get:JsonProperty("sale_price") val salePrice: kotlin.String? = null,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("guest_ratings") val guestRatings: CatalogsHotelGuestRatings? = null
) {
}
| 0 |
Java
|
0
| 2 |
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
| 4,441 |
pinterest-sdk
|
MIT License
|
rapidosqlite/src/main/java/com/izeni/rapidosqlite/table/ParentDataTable.kt
|
RyanAndroidTaylor
| 69,109,027 | false |
{"Java": 1582154, "Kotlin": 186386}
|
package com.izeni.rapidosqlite.table
/**
* Created by ryantaylor on 9/23/16.
*/
interface ParentDataTable : DataTable {
fun getChildren(): List<DataTable>
}
| 1 | null |
1
| 1 |
3d52aedfb0747bb575bb49b82147dea2eb1b06b3
| 163 |
Rapido
|
MIT License
|
rapidosqlite/src/main/java/com/izeni/rapidosqlite/table/ParentDataTable.kt
|
RyanAndroidTaylor
| 69,109,027 | false |
{"Java": 1582154, "Kotlin": 186386}
|
package com.izeni.rapidosqlite.table
/**
* Created by ryantaylor on 9/23/16.
*/
interface ParentDataTable : DataTable {
fun getChildren(): List<DataTable>
}
| 1 | null |
1
| 1 |
3d52aedfb0747bb575bb49b82147dea2eb1b06b3
| 163 |
Rapido
|
MIT License
|
feature-account-impl/src/main/java/com/edgeverse/wallet/feature_account_impl/presentation/account/model/AccountModel.kt
|
finn-exchange
| 512,140,809 | false |
{"Kotlin": 2956205, "Java": 14536, "JavaScript": 399}
|
package com.edgeverse.wallet.feature_account_impl.presentation.account.model
import android.graphics.drawable.PictureDrawable
import com.edgeverse.wallet.core.model.Network
import com.edgeverse.wallet.feature_account_impl.presentation.view.advanced.encryption.model.CryptoTypeModel
data class AccountModel(
val address: String,
val name: String?,
val image: PictureDrawable,
val accountIdHex: String,
val position: Int,
val cryptoTypeModel: CryptoTypeModel,
val network: Network
)
| 0 |
Kotlin
|
1
| 0 |
03229c4188cb56b0fb0340e60d60184c7afa2c75
| 511 |
edgeverse-wallet
|
Apache License 2.0
|
gabimoreno/src/test/java/soy/gabimoreno/data/tracker/DefaultTrackerTest.kt
|
soygabimoreno
| 477,796,937 | false |
{"Kotlin": 364408, "Swift": 648, "Shell": 441}
|
package soy.gabimoreno.data.tracker
import com.google.firebase.analytics.FirebaseAnalytics
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import soy.gabimoreno.core.testing.relaxedMockk
import soy.gabimoreno.core.testing.verifyOnce
import soy.gabimoreno.domain.usecase.GetTrackingEventNameUseCase
@RunWith(RobolectricTestRunner::class)
class DefaultTrackerTest {
private val firebaseAnalytics: FirebaseAnalytics = relaxedMockk()
private val getTrackingEventNameUseCase: GetTrackingEventNameUseCase = relaxedMockk()
private lateinit var defaultTracker: DefaultTracker
@Before
fun setUp() {
defaultTracker = DefaultTracker(
firebaseAnalytics,
getTrackingEventNameUseCase
)
}
@Test
fun `WHEN trackEvent THEN do the corresponding calls`() {
val trackerEvent: TrackerEvent = relaxedMockk()
defaultTracker.trackEvent(trackerEvent)
verifyOnce {
getTrackingEventNameUseCase(trackerEvent)
firebaseAnalytics.logEvent(any(), any())
}
}
}
| 6 |
Kotlin
|
10
| 13 |
5d5ff8117cda10f7567ac0caf152501c1d439baa
| 1,142 |
Base
|
Apache License 2.0
|
src/main/kotlin/pers/neige/banker/loot/impl/All.kt
|
Neige7
| 624,015,130 | false | null |
package pers.neige.banker.loot.impl
import org.bukkit.Bukkit
import org.bukkit.configuration.ConfigurationSection
import pers.neige.banker.loot.LootGenerator
import pers.neige.banker.manager.LootManager
import pers.neige.neigeitems.manager.ActionManager
import pers.neige.neigeitems.utils.ConfigUtils.clone
import java.util.concurrent.ConcurrentHashMap
class All(data: ConfigurationSection) : LootGenerator(data) {
// 获取战利品动作
private val lootAction = let {
var lootAction = data.get("LootAction")
if (lootAction !is List<*>) {
lootAction = arrayListOf(lootAction)
}
lootAction as List<*>
}
override fun run(
damageData: Map<String, Double>,
sortedDamageData: List<Map.Entry<String, Double>>,
totalDamage: Double,
params: MutableMap<String, String>?
) {
// 遍历玩家ID
damageData.forEach { (name, damage) ->
// 获取在线玩家
val player = Bukkit.getPlayer(name)
// 玩家不在线则停止执行
if (player != null) {
(params?.toMutableMap<String, Any?>() ?: mutableMapOf()).also { map ->
map["damage"] = "%.2f".format(damage)
map["totalDamage"] = "%.2f".format(totalDamage)
// 执行动作
ActionManager.runAction(
player,
lootAction,
map,
map
)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
cb5b49e37708b057d6135d83519a8cb78f0e0601
| 1,529 |
Banker
|
MIT License
|
app/src/main/java/io/github/drumber/kitsune/util/DataUtil.kt
|
Drumber
| 406,471,554 | false |
{"Kotlin": 993796, "Ruby": 2109}
|
package io.github.drumber.kitsune.util
import android.content.Context
import io.github.drumber.kitsune.R
import io.github.drumber.kitsune.data.common.Titles
import io.github.drumber.kitsune.data.common.en
import io.github.drumber.kitsune.data.common.enJp
import io.github.drumber.kitsune.data.common.jaJp
import io.github.drumber.kitsune.data.source.local.user.model.LocalTitleLanguagePreference
import io.github.drumber.kitsune.preference.KitsunePref
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
object DataUtil {
@JvmStatic
fun formatDate(dateString: String?) = dateString?.parseDate()?.formatDate(SimpleDateFormat.LONG)
@JvmStatic
fun getGenderString(gender: String?, context: Context): String {
return when (gender) {
"male" -> context.getString(R.string.profile_gender_male)
"female" -> context.getString(R.string.profile_gender_female)
"secret", null -> context.getString(R.string.profile_data_private)
else -> gender
}
}
@JvmStatic
fun formatUserJoinDate(joinDate: String?, context: Context): String? {
return joinDate?.parseDate()?.let { dateJoined ->
val diffMillis = Calendar.getInstance().timeInMillis - dateJoined.time
val differenceString = TimeUtil.roundTime(diffMillis / 1000, context)
"${dateJoined.formatDate(SimpleDateFormat.LONG)} " +
"(${context.getString(R.string.profile_data_join_date_ago, differenceString)})"
}
}
@JvmStatic
fun getTitle(title: Titles?, canonical: String?): String? {
return when (KitsunePref.titles) {
LocalTitleLanguagePreference.Canonical -> canonical.nb()
?: title?.enJp.nb() ?: title?.en.nb() ?: title?.jaJp
LocalTitleLanguagePreference.Romanized -> title?.enJp.nb()
?: canonical.nb() ?: title?.en.nb() ?: title?.jaJp
LocalTitleLanguagePreference.English -> title?.en.nb()
?: canonical.nb() ?: title?.enJp.nb() ?: title?.jaJp
}
}
@JvmStatic
fun <T> Map<String, T>.mapLanguageCodesToDisplayName(includeCountry: Boolean = true): Map<String, T> {
return mapKeys {
val locale = Locale.forLanguageTag(it.key.replace('_', '-'))
if (includeCountry && it.key.lowercase().split('_').toSet().size > 1)
locale.displayName
else
locale.displayLanguage
}
}
/**
* Maps blank strings to null.
*/
private fun String?.nb() = if (this.isNullOrBlank()) null else this
}
| 6 |
Kotlin
|
4
| 92 |
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
| 2,637 |
Kitsune
|
Apache License 2.0
|
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/ExecutableCommon.kt
|
Pitel
| 382,259,274 | true |
{"Kotlin": 1351692, "ANTLR": 8207, "Java": 3282, "Shell": 832}
|
package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.api.Adapter
import com.apollographql.apollo3.api.CompiledSelection
import com.apollographql.apollo3.api.CustomScalarAdapters
import com.apollographql.apollo3.api.json.JsonWriter
import com.apollographql.apollo3.compiler.codegen.Identifier.customScalarAdapters
import com.apollographql.apollo3.compiler.codegen.Identifier.selections
import com.apollographql.apollo3.compiler.codegen.Identifier.serializeVariables
import com.apollographql.apollo3.compiler.codegen.Identifier.toJson
import com.apollographql.apollo3.compiler.codegen.Identifier.writer
import com.apollographql.apollo3.compiler.codegen.kotlin.adapter.obj
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.patchKotlinNativeOptionalArrayProperties
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
fun serializeVariablesFunSpec(
adapterClassName: TypeName?,
emptyMessage: String
): FunSpec {
val body = if (adapterClassName == null) {
CodeBlock.of("""
// $emptyMessage
""".trimIndent())
} else {
CodeBlock.of(
"%L.$toJson($writer, $customScalarAdapters, this)",
CodeBlock.of("%T", adapterClassName)
)
}
return FunSpec.builder(serializeVariables)
.addModifiers(KModifier.OVERRIDE)
.addParameter(writer, JsonWriter::class)
.addParameter(customScalarAdapters, CustomScalarAdapters::class.asTypeName())
.addCode(body)
.build()
}
fun adapterFunSpec(
adapterTypeName: TypeName,
adaptedTypeName: TypeName
): FunSpec {
return FunSpec.builder("adapter")
.addModifiers(KModifier.OVERRIDE)
.returns(Adapter::class.asClassName().parameterizedBy(adaptedTypeName))
.addCode(CodeBlock.of("return·%T", adapterTypeName).obj(false))
.build()
}
fun selectionsFunSpec(context: KotlinContext, className: ClassName): FunSpec {
return FunSpec.builder(selections)
.addModifiers(KModifier.OVERRIDE)
.returns(List::class.parameterizedBy(CompiledSelection::class))
.addCode("return %T.%L\n", className, context.layout.rootSelectionsPropertyName())
.build()
}
fun TypeSpec.maybeAddFilterNotNull(generateFilterNotNull: Boolean): TypeSpec {
if (!generateFilterNotNull) {
return this
}
return patchKotlinNativeOptionalArrayProperties()
}
| 0 |
Kotlin
|
0
| 0 |
d6e74e0ca4c9029552c9b08b8898684734b994a6
| 2,768 |
apollo-android
|
MIT License
|
app/src/main/java/com/example/movplayv3/utils/ShapeUtils.kt
|
Aldikitta
| 514,876,509 | false |
{"Kotlin": 850016}
|
package com.example.movplayv3.utils
import androidx.annotation.FloatRange
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
class BottomRoundedArcShape(
@FloatRange(from = 0.0, to = 1.0)
private val ratio: Float = 0f,
@FloatRange(from = 0.0, to = 1.0)
private val edgeHeightRatio: Float = 0.9f,
) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
return Outline.Generic(
path = drawArcPath(
size = size,
ratio = ratio,
edgeHeightRatio = edgeHeightRatio
)
)
}
}
fun drawArcPath(size: Size, ratio: Float, edgeHeightRatio: Float): Path {
val deltaHeight = 1f - edgeHeightRatio
val edgePointsHeight = (edgeHeightRatio + deltaHeight * ratio) * size.height
return Path().apply {
reset()
lineTo(size.width, 0f)
lineTo(size.width, edgePointsHeight)
cubicTo(
x1 = size.width,
y1 = edgePointsHeight,
x2 = size.width / 2,
y2 = size.height,
x3 = 0f,
y3 = edgePointsHeight
)
lineTo(0f, 0f)
close()
}
}
| 1 |
Kotlin
|
12
| 77 |
8344e2a5cf62289c2b56494bf4ecd5227e26de31
| 1,449 |
MovplayV3
|
Apache License 2.0
|
src/main/kotlin/com/vinarnt/jikan4j/service/BaseService.kt
|
KyuBlade
| 127,173,430 | false | null |
package com.vinarnt.jikan4j.service
import com.vinarnt.jikan4j.Constants
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
open class BaseService(private val path: String) {
companion object {
val client = OkHttpClient()
}
protected fun getUrl(vararg pathSegments: Any) = HttpUrl.Builder()
.scheme(Constants.API_SCHEME)
.host(Constants.API_HOST)
.addPathSegment(path)
.apply { pathSegments.forEach { addPathSegment(it.toString()) } }
.build()
}
| 2 |
Kotlin
|
0
| 0 |
54589856cbc40dba6b987f0ae4d8e25ec28985c1
| 531 |
Jikan4J
|
MIT License
|
src/main/kotlin/ch/obermuhlner/chat/tools/PublicTransportSwitzerland.kt
|
eobermuhlner
| 828,796,106 | false |
{"Kotlin": 104902}
|
package ch.obermuhlner.chat.tools
import dev.langchain4j.agent.tool.Tool
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import org.slf4j.LoggerFactory
class PublicTransportSwitzerland {
companion object {
private val logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
}
val client = OkHttpClient()
@Tool("Get locations of public transport")
fun getLocations(query: String? = null, x: Double? = null, y: Double? = null, type: String? = null): String {
logger.info("Getting locations with query: $query, coordinates: ($x, $y), type: $type")
val urlBuilder = HttpUrl.Builder()
.scheme("https")
.host("transport.opendata.ch")
.addPathSegment("v1")
.addPathSegment("locations")
query?.let { urlBuilder.addQueryParameter("query", it) }
x?.let { urlBuilder.addQueryParameter("x", it.toString()) }
y?.let { urlBuilder.addQueryParameter("y", it.toString()) }
type?.let { urlBuilder.addQueryParameter("type", it) }
val url = urlBuilder.build()
return simpleGetRequest(client, url)
}
@Tool("Get public transport connections between two stations")
fun getConnections(from: String, to: String, via: List<String>? = null, date: String? = null, time: String? = null, isArrivalTime: Int? = null, transportations: List<String>? = null, limit: Int? = null, page: Int? = null): String {
logger.info("Getting connections from: $from, to: $to, via: $via, date: $date, time: $time, isArrivalTime: $isArrivalTime, transportations: $transportations, limit: $limit, page: $page")
val urlBuilder = HttpUrl.Builder()
.scheme("https")
.host("transport.opendata.ch")
.addPathSegment("v1")
.addPathSegment("connections")
.addQueryParameter("from", from)
.addQueryParameter("to", to)
via?.forEach { urlBuilder.addQueryParameter("via[]", it) }
date?.let { urlBuilder.addQueryParameter("date", it) }
time?.let { urlBuilder.addQueryParameter("time", it) }
isArrivalTime?.let { urlBuilder.addQueryParameter("isArrivalTime", it.toString()) }
transportations?.forEach { urlBuilder.addQueryParameter("transportations[]", it) }
limit?.let { urlBuilder.addQueryParameter("limit", it.toString()) }
page?.let { urlBuilder.addQueryParameter("page", it.toString()) }
val url = urlBuilder.build()
return simpleGetRequest(client, url)
}
@Tool("Get public transport leaving a specific station")
fun getStationBoard(station: String, id: String? = null, limit: Int? = null, transportations: List<String>? = null, datetime: String? = null, type: String? = null): String {
logger.info("Getting stationboard for station: $station, id: $id, limit: $limit, transportations: $transportations, datetime: $datetime, type: $type")
val urlBuilder = HttpUrl.Builder()
.scheme("https")
.host("transport.opendata.ch")
.addPathSegment("v1")
.addPathSegment("stationboard")
.addQueryParameter("station", station)
id?.let { urlBuilder.addQueryParameter("id", it) }
limit?.let { urlBuilder.addQueryParameter("limit", it.toString()) }
transportations?.forEach { urlBuilder.addQueryParameter("transportations[]", it) }
datetime?.let { urlBuilder.addQueryParameter("datetime", it) }
type?.let { urlBuilder.addQueryParameter("type", it) }
val url = urlBuilder.build()
return simpleGetRequest(client, url)
}
private fun simpleGetRequest(client: OkHttpClient, url: HttpUrl): String {
val request = okhttp3.Request.Builder().url(url).build()
client.newCall(request).execute().use { response ->
return if (response.isSuccessful) {
response.body?.string() ?: "No response body"
} else {
"Request failed with code ${response.code}"
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
44a28a0905e443b234f30575f7493ed132755116
| 4,062 |
chat-with-memory
|
MIT License
|
1547.Minimum Cost to Cut a Stick.kt
|
sarvex
| 842,260,390 | false |
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
fun minCost(n: Int, cuts: IntArray): Int {
val nums: List<Int> = ArrayList()
for (x in cuts) {
nums.add(x)
}
nums.add(0)
nums.add(n)
Collections.sort(nums)
val m: Int = nums.size()
val f = Array(m) { IntArray(m) }
for (l in 2 until m) {
var i = 0
while (i + l < m) {
val j: Int = i + l
f[i][j] = 1 shl 30
for (k in i + 1 until j) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums[j] - nums[i])
}
++i
}
}
return f[0][m - 1]
}
}
| 0 |
Kotlin
|
0
| 0 |
17a80985d970c8316fb694e4952692e598d700af
| 580 |
kotlin-leetcode
|
MIT License
|
yorkie/src/main/kotlin/dev/yorkie/core/Attachment.kt
|
yorkie-team
| 518,739,505 | false | null |
package dev.yorkie.core
import dev.yorkie.document.Document
internal data class Attachment(
val document: Document,
val documentID: String,
val isRealTimeSync: Boolean,
val peerPresences: Peers = UninitializedPresences,
val remoteChangeEventReceived: Boolean = false,
) {
companion object {
val UninitializedPresences = Peers()
}
}
| 3 |
Kotlin
|
2
| 8 |
f7dc8a19b6f22a351e0e5c20dbc88ee477e8e789
| 371 |
yorkie-android-sdk
|
Apache License 2.0
|
entities/src/commonMain/kotlin/gcu/product/entities/other/IconsSize.kt
|
Ilyandr
| 612,297,078 | false | null |
package gcu.product.entities.other
import dev.icerock.moko.parcelize.Parcelable
import dev.icerock.moko.parcelize.Parcelize
enum class IconsSize {
SmallFirst, SmallSecond, Medium, Large
}
@Parcelize
data class PairIconSize(
val vertical: IconsSize = IconsSize.Medium,
val horizontal: IconsSize = IconsSize.Medium
) : Parcelable
| 0 |
Kotlin
|
0
| 1 |
856e9f54c57a49dce86d58ac9c72437452b50775
| 342 |
Friendly
|
Apache License 2.0
|
data/model/src/main/java/com/gyorgyzoltan/sprayApp/model/Configuration.kt
|
pandulapeter
| 279,548,090 | false | null |
package com.gyorgyzoltan.sprayApp.model
import com.gyorgyzoltan.sprayApp.model.nozzle.Nozzle
interface Configuration {
val nozzle: Nozzle?
val wheelRadius: Float?
val screwCount: Int?
val nozzleCount: Int?
val nozzleDistance: Float?
val isValid get() = nozzle != null && wheelRadius != null && screwCount != null && nozzleCount != null && nozzleDistance != null
}
| 0 |
Kotlin
|
0
| 2 |
9a5238105eafc74373f496d26f97cf095daa4696
| 390 |
spray-app
|
Apache License 2.0
|
common/core/src/main/java/com/him/sama/spotifycompose/common/core/di/NetworkModule.kt
|
arohim
| 762,735,266 | false |
{"Kotlin": 117808}
|
package com.him.sama.spotifycompose.common.core.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton
fun provideOkHttp(): OkHttpClient {
return OkHttpClient.Builder().build()
}
@Provides
@Singleton
fun provideRetrofit(
okHttpClient: OkHttpClient,
): Retrofit {
return Retrofit.Builder()
.baseUrl("https://mock.mock")
.client(okHttpClient)
.build()
}
}
| 0 |
Kotlin
|
0
| 0 |
c09afe9faf2a756fe1597ac6061f062b204d6ac8
| 697 |
SpotifyJetpackCompose
|
Apache License 2.0
|
app/src/main/java/dev/eakin/blob/ui/main/Blob.kt
|
GregEakin
| 230,686,423 | false |
{"Gradle": 4, "Java Properties": 2, "Prolog": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 23, "Java": 2, "XML": 23}
|
/*
* Copyright 2019 Greg Eakin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.eakin.blob.ui.main
import android.graphics.*
import kotlin.math.acos
import kotlin.random.Random
interface Blob {
val points: List<PointMass>
val numPoints: Int
var radius: Float
val middle: PointMass
var selected: Touch?
val x: Float
val y: Float
fun linkBlob(blob: Blob)
fun unlinkBlob(blob: Blob)
fun scale(scaleFactor: Float)
fun move(dt: Float)
fun sc(env: Environment)
fun setForce(value: Vector)
fun addForce(force: Vector)
fun moveTo(destX: Float, destY: Float)
fun draw(canvas: Canvas)
}
class BlobImpl(
private val startX: Float,
private val startY: Float,
override var radius: Float,
override val numPoints: Int
) : Blob {
init {
if (radius <= 0.0f)
throw Exception("Can't have a negative radius.")
if (numPoints < 3)
throw Exception("Need at least three points to draw a blob.")
}
constructor(mother: Blob) : this(mother.x, mother.y, mother.radius, mother.numPoints)
enum class Eye {
OPEN, CLOSED, YIHAA
}
enum class Face {
SMILE, OPEN, OOH
}
override val middle: PointMass = PointMass(startX, startY, 1.0f)
override val points: List<PointMass> = pointsInit()
private fun pointsInit(): List<PointMass> {
val list = mutableListOf<PointMass>()
for (i in 0 until numPoints) {
val theta = i * 2.0 * Math.PI / numPoints
val cx = Math.cos(theta) * radius + startX
val cy = Math.sin(theta) * radius + startY
val mass = if (i < 2) 4.0f else 1.0f
val pt = PointMass(cx.toFloat(), cy.toFloat(), mass)
list.add(pt)
}
return list
}
val skins: List<Skin> = skinInit()
private fun skinInit(): List<Skin> {
val list = mutableListOf<Skin>()
for (i in 0 until numPoints) {
val pointMassA = points[i]
val index = pointMassIndex(i + 1)
val pointMassB = points[index]
val skin = Skin(pointMassA, pointMassB)
list.add(skin)
}
return list
}
val bones: List<Bone> = bonesInit()
private fun bonesInit(): List<Bone> {
val list = mutableListOf<Bone>()
for (i in 0 until numPoints) {
val crossShort = 0.95f
val crossLong = 1.05f
val middleShort = crossLong * 0.9f
val middleLong = crossShort * 1.1f
val pointMassA = points[i]
val index = pointMassIndex(i + numPoints / 2 + 1)
val pointMassB = points[index]
val bone1 = Bone(pointMassA, pointMassB, crossShort, crossLong)
list.add(bone1)
val bone2 = Bone(pointMassA, middle, middleShort, middleLong)
list.add(bone2)
}
return list
}
override var selected: Touch? = null
override val x: Float
get() = middle.xPos
override val y: Float
get() = middle.yPos
val mass: Float
get() = middle.mass
fun pointMassIndex(x: Int): Int {
val m = numPoints
return (x % m + m) % m
}
val neighbors: MutableList<Neighbor> = mutableListOf()
override fun linkBlob(blob: Blob) {
val distance = radius + blob.radius
val neighbor = Neighbor(middle, blob.middle, distance * 0.95f)
neighbors.add(neighbor)
}
override fun unlinkBlob(blob: Blob) {
for (neighbor in neighbors) {
if (neighbor.pointMassB != blob.middle)
continue
neighbors.remove(neighbor)
break
}
}
override fun scale(scaleFactor: Float) {
for (skin in skins)
skin.scale(scaleFactor)
for (bone in bones)
bone.scale(scaleFactor)
for (neighbor in neighbors)
neighbor.scale(scaleFactor)
radius *= scaleFactor
}
override fun move(dt: Float) {
val touch = selected
if (touch?.blob == this) {
moveTo(touch.x, touch.y)
} else {
for (point in points)
point.move(dt)
middle.move(dt)
}
}
override fun sc(env: Environment) {
for (j in 0 until 4) {
for (point in points) {
val collision = env.collision(point.pos, point.prev)
point.friction = if (collision) 0.75f else 0.01f
}
for (skin in skins)
skin.sc()
for (bone in bones)
bone.sc()
for (neighbor in neighbors)
neighbor.sc()
}
}
override fun setForce(value: Vector) {
middle.force = value
for (point in points)
point.force = value
}
override fun addForce(force: Vector) {
middle.addForce(force)
for (point in points)
point.addForce(force)
// put a spin on the blob
val pointMass = points[0]
pointMass.addForce(force)
pointMass.addForce(force)
pointMass.addForce(force)
pointMass.addForce(force)
}
override fun moveTo(destX: Float, destY: Float) {
val deltaX = destX - middle.pos.x
val deltaY = destY - middle.pos.y
for (point in points) {
point.prev.x = point.pos.x
point.prev.y = point.pos.y
point.pos.add(deltaX, deltaY)
}
middle.prev.x = middle.pos.x
middle.prev.y = middle.pos.y
middle.pos.add(deltaX, deltaY)
}
// val view: BlobView by lazy { BlobView() }
// inner class BlobView {
private val paint = Paint()
private var eyes: Eye = Eye.OPEN
private var face: Face = Face.OPEN
init {
paint.textSize = 20.0f
}
// fun drawEars(canvas: Canvas, scaleFactor: Float) {}
fun drawEyesOpen(canvas: Canvas) {
paint.strokeWidth = 1.0f
val r1 = 0.12f * radius
val left = 0.35f * radius
val right = 0.65f * radius
val y1 = 0.30f * radius
paint.color = Color.WHITE
paint.style = Paint.Style.FILL
canvas.drawCircle(left, y1, r1, paint)
canvas.drawCircle(right, y1, r1, paint)
paint.color = Color.BLACK
paint.style = Paint.Style.STROKE
canvas.drawCircle(left, y1, r1, paint)
canvas.drawCircle(right, y1, r1, paint)
val r2 = 0.06f * radius
val y2 = 0.33f * radius
paint.style = Paint.Style.FILL
canvas.drawCircle(left, y2, r2, paint)
canvas.drawCircle(right, y2, r2, paint)
}
fun drawEyesClosed(canvas: Canvas) {
paint.color = Color.BLACK
paint.style = Paint.Style.STROKE
paint.strokeWidth = 1.0f
val r = 0.12f * radius
val left = 0.35f * radius
val right = 0.65f * radius
val y = 0.30f * radius
canvas.drawCircle(left, y, r, paint)
canvas.drawLine(left - r, y, left + r, y, paint)
canvas.drawCircle(right, y, r, paint)
canvas.drawLine(right - r, y, right + r, y, paint)
}
fun drawSmile(canvas: Canvas, paint: Paint) {
val left = 0.25f * radius
val top = 0.40f * radius
val right = 0.50f * radius + left
val bottom = 0.50f * radius + top
val oval = RectF(left, top, right, bottom)
canvas.drawArc(oval, 0f, 180f, false, paint)
}
fun drawOohFace(canvas: Canvas) {
paint.style = Paint.Style.FILL
paint.strokeWidth = 2.0f
drawSmile(canvas, paint)
val x1 = 0.25f * radius
val x2 = 0.45f * radius
val x3 = 0.75f * radius
val x4 = 0.55f * radius
val y1 = 0.20f * radius
val y2 = 0.30f * radius
val y3 = 0.40f * radius
canvas.drawLine(x1, y1, x2, y2, paint)
canvas.drawLine(x2, y2, x1, y3, paint)
canvas.drawLine(x3, y1, x4, y2, paint)
canvas.drawLine(x4, y2, x3, y3, paint)
}
fun updateFace() {
if (face == Face.SMILE && Random.nextDouble() < 0.025)
face = Face.OPEN
else if (face == Face.OPEN && Random.nextDouble() < 0.05)
face = Face.SMILE
if (eyes == Eye.OPEN && Random.nextDouble() < 0.010)
eyes = Eye.CLOSED
else if (eyes == Eye.CLOSED && Random.nextDouble() < 0.150)
eyes = Eye.OPEN
}
fun drawFace(canvas: Canvas) {
if (middle.velocity > 200.0f)
drawOohFace(canvas)
else {
paint.style = if (face == Face.SMILE) Paint.Style.STROKE else Paint.Style.FILL
paint.strokeWidth = 2.0f
drawSmile(canvas, paint)
if (eyes == Eye.OPEN) {
drawEyesOpen(canvas)
} else {
drawEyesClosed(canvas)
}
}
}
fun drawBody(canvas: Canvas) {
paint.style = Paint.Style.STROKE
paint.strokeWidth = 3.0f
val path = Path()
val startX = points[0].xPos
val startY = points[0].yPos
path.moveTo(startX, startY)
for (i in points.indices) {
val prevPointMass = points[pointMassIndex(i - 1)]
val currentPointMass = points[pointMassIndex(i)]
val nextPointMass = points[pointMassIndex(i + 1)]
val nextNextPointMass = points[pointMassIndex(i + 2)]
val cx = currentPointMass.xPos
val cy = currentPointMass.yPos
val tx = nextPointMass.xPos
val ty = nextPointMass.yPos
val nx = cx - prevPointMass.xPos + tx - nextNextPointMass.xPos
val ny = cy - prevPointMass.yPos + ty - nextNextPointMass.yPos
val px = cx * 0.5f + tx * 0.5f + nx * 0.16f
val py = cy * 0.5f + ty * 0.5f + ny * 0.16f
path.cubicTo(px, py, tx, ty, tx, ty)
}
canvas.drawPath(path, paint)
// for (i in points.indices) {
// val point = points[i]
// val r2 = 0.06f * radius * point.mass
// paint.style = Paint.Style.STROKE
// canvas.drawCircle(point.xPos, point.yPos, r2, paint)
//
// val force = point.force
// val x = point.xPos + 1e5f * force.x * point.mass
// val y = point.yPos + 1e5f * force.y * point.mass
// canvas.drawLine(point.xPos, point.yPos, x, y, paint)
// }
}
val up = Vector(0.0f, -1.0f)
override fun draw(canvas: Canvas) {
updateFace()
canvas.save()
drawBody(canvas)
val ori = points[0].pos - middle.pos
val ang = acos(ori * up / ori.length.toDouble())
val radians = if (ori.x < 0.0f) -ang else ang
val theta = (180.0 / Math.PI) * radians
canvas.rotate(theta.toFloat(), middle.xPos, middle.yPos)
val tx = middle.xPos - radius / 2f
val ty = (middle.yPos - 0.35f * radius) - radius / 2f
canvas.translate(tx, ty)
drawFace(canvas)
canvas.restore()
// if (selected?.blob !== this) return
//
// var r = radius * radius
// canvas.drawText("${selected?.number}", x, y, paint)
}
}
| 0 |
Kotlin
|
0
| 0 |
c669f4be594fe885d7094f7e8182da97eb17f7dc
| 11,747 |
BlobSallad.Android
|
Apache License 2.0
|
plugins/api/src/main/kotlin/org/rsmod/plugins/api/protocol/packet/client/MovePacket.kt
|
Rune-Server
| 328,442,238 | true |
{"Kotlin": 289952}
|
package org.rsmod.plugins.api.protocol.packet.client
import com.google.inject.Inject
import org.rsmod.game.action.ActionBus
import org.rsmod.game.message.ClientPacket
import org.rsmod.game.message.ClientPacketHandler
import org.rsmod.game.model.client.Client
import org.rsmod.game.model.map.Coordinates
import org.rsmod.game.model.mob.Player
import org.rsmod.plugins.api.protocol.packet.MapMove
data class MoveGameClick(
val x: Int,
val y: Int,
val type: Int
) : ClientPacket
class GameClickHandler @Inject constructor(
private val actions: ActionBus
) : ClientPacketHandler<MoveGameClick> {
override fun handle(client: Client, player: Player, packet: MoveGameClick) {
val destination = Coordinates(packet.x, packet.y)
val action = MapMove(player, destination, player.speed)
actions.publish(action)
}
}
| 0 | null |
0
| 0 |
533909dbcf2153b472714beb52b3eb3238850a48
| 855 |
rsmod-new
|
ISC License
|
app/src/main/java/com/stevenpopovich/talktothat/taskmanager/tasks/DontTouchTask.kt
|
stevepopovich
| 291,135,072 | false |
{"G-code": 32972125}
|
package com.stevenpopovich.talktothat.taskmanager.tasks
import com.stevenpopovich.talktothat.MainDependencyModule
import com.stevenpopovich.talktothat.usbinterfacing.ArduinoInterface
import com.stevenpopovich.talktothat.usbinterfacing.SerialPortInterface
class DontTouchTask(
private val arduinoInterface: ArduinoInterface = MainDependencyModule.arduinoInterface,
private val serialPortInterface: SerialPortInterface? = MainDependencyModule.serialPortInterface,
) : Task {
override fun start() {
serialPortInterface?.let {
arduinoInterface.writeStringToSerialPort(it, "donttouch")
}
}
override fun finish() {
super.finish()
serialPortInterface?.let {
arduinoInterface.writeStringToSerialPort(it, "stop")
}
}
}
| 5 |
G-code
|
0
| 4 |
180327cbd933262087ac5e7537bca8053de79db4
| 801 |
sam
|
MIT License
|
features/schedule/src/main/java/dev/ryzhoov/napomnix/schedule/ui/list/items/GroupItem.kt
|
v1aditech
| 581,266,106 | false |
{"Kotlin": 161157}
|
package dev.ryzhoov.napomnix.schedule.ui.list.items
internal data class GroupItem(
override val id: Long,
val name: String,
val description: String
) : Item
| 0 |
Kotlin
|
0
| 0 |
5b0fc12bf74f19f765d99d5671b0f599bebd17a9
| 169 |
napomnix
|
Apache License 2.0
|
app/src/main/java/de/graphql/movies/ui/movies/MoviesAdapter.kt
|
sorinirimies
| 170,533,758 | false | null |
package de.graphql.movies.ui.movies
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import de.graphql.movies.R
import de.graphql.movies.injection.TMDB_BASE_IMAGE_URL
import de.graphql.movies.model.MovieItem
import de.graphql.movies.model.TmdbImgSize
import kotlinx.android.synthetic.main.listitem_movie.view.*
private typealias MovieSelected = (movieListItem: MovieItem) -> Unit
class MoviesAdapter(private val movieSelected: MovieSelected) : RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder>() {
private val movieListItems: ArrayList<MovieItem> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoviesViewHolder =
MoviesViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.listitem_movie,
parent,
false
)
)
override fun onBindViewHolder(holder: MoviesViewHolder, position: Int) =
holder.bind(movieListItems[position], movieSelected)
fun addItem(item: MovieItem) {
if (movieListItems.map { it.title }.contains(item.title)) return
movieListItems.add(item)
notifyItemInserted(movieListItems.indexOf(item))
}
fun addItems(items: List<MovieItem>) {
movieListItems.clear()
movieListItems.addAll(items)
notifyDataSetChanged()
}
fun clearItems() {
movieListItems.clear()
notifyDataSetChanged()
}
fun removeItem(item: MovieItem) {
val position = movieListItems.indexOf(item)
movieListItems.removeAt(position)
notifyItemRemoved(position)
}
override fun getItemCount() = movieListItems.size
inner class MoviesViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val contMovieItem = view.contMovieItem
private val imgMovieTitle = view.imgItemMoviePoster
private val tvMovieTitle = view.tvItemMovieTitle
private val tvItemMovieVoteCount = view.tvItemMovieVoteCount
private val tvMovieVoteAverage = view.tvItemMovieVoteAverage
private val tvMovieActorName = view.tvCastName
private val tvMovieYear = view.tvItemMovieYear
private val tvMoviePopularity = view.tvItemMoviePopularity
private val imgMovieMainActor = view.imgMovieCast
fun bind(movieListItem: MovieItem, movieSelected: MovieSelected) {
Picasso.get()
.load("$TMDB_BASE_IMAGE_URL${TmdbImgSize.IMG_342.size}${movieListItem.poster_path}")
.placeholder(R.drawable.ic_movies)
.into(imgMovieTitle)
imgMovieMainActor.visibility = View.GONE
movieListItem.profile_path?.let {
imgMovieMainActor.visibility = View.VISIBLE
Picasso.get()
.load("$TMDB_BASE_IMAGE_URL${TmdbImgSize.IMG_ORIGINAL.size}$it")
.into(imgMovieMainActor)
}
tvMovieActorName.text = movieListItem.name
tvMovieTitle.text = movieListItem.title
tvItemMovieVoteCount.text = "${movieListItem.vote_count}"
tvMovieYear.text = movieListItem.release_date
tvMoviePopularity.text = "${movieListItem.popularity}"
tvMovieVoteAverage.text = "${movieListItem.vote_average}"
contMovieItem.setOnClickListener { movieSelected.invoke(movieListItem) }
}
}
}
| 0 |
Kotlin
|
0
| 0 |
7c4903307bac046758b94ea07f6dee237bf79630
| 3,524 |
movierank-android
|
Apache License 2.0
|
app/src/main/java/com/zyl/beheapp/mvp/model/GankModel.kt
|
zylfly
| 115,254,025 | false | null |
package com.tt.lvruheng.eyepetizer.mvp.model
import com.hazz.kotlinmvp.rx.scheduler.SchedulerUtils
import com.zyl.beheapp.http.RetrofitClientKt
import com.zyl.beheapp.mvp.model.bean.GankBean
import io.reactivex.Observable
class GankModel {
fun loadGank(page: Int): Observable<GankBean> {
return RetrofitClientKt.instances().service
.getGankLists(page).compose(SchedulerUtils.ioToMain())
}
}
| 0 | null |
2
| 2 |
d689c9f2b0dbe0618f307763cc526790b644e9e6
| 425 |
BhApp
|
Apache License 2.0
|
datasource/src/main/java/io/github/afalalabarce/mvvmproject/datasource/mapper/IMapperEntity.kt
|
afalabarce
| 565,204,782 | false |
{"Kotlin": 56649}
|
package io.github.afalalabarce.mvvmproject.datasource.mapper
interface IMapperEntity
| 0 |
Kotlin
|
4
| 67 |
f4cbc62c9da8ff558f82578e1263606140d5fe2f
| 85 |
MVVMProject
|
MIT License
|
tmp/arrays/youTrackTests/9226.kt
|
DaniilStepanov
| 228,623,440 | false | null |
// Original bug: KT-7495
enum class E {
a, b, c ;
val text : String = "name = ${name} ordinal = ${ordinal} toString() = ${toString()}"
}
fun main(args: Array<String>) {
E.values().forEach {
println(it.name + ": " + it.text)
}
}
| 1 | null |
8
| 1 |
602285ec60b01eee473dcb0b08ce497b1c254983
| 254 |
bbfgradle
|
Apache License 2.0
|
plugins/kotlin-serialization/kotlin-serialization-compiler/test/org/jetbrains/kotlinx/serialization/RuntimeSearch.kt
|
prasenjitghose36
| 273,158,317 | true |
{"Kotlin": 51024013, "Java": 7691261, "JavaScript": 185101, "HTML": 77858, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "CSS": 9270, "Swift": 8450, "Shell": 7220, "Batchfile": 5727, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
|
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization
import junit.framework.TestCase
import org.jetbrains.kotlin.utils.PathUtil
import org.junit.Test
import java.io.File
class RuntimeLibraryInClasspathTest {
private val runtimeLibraryPath = getSerializationLibraryRuntimeJar()
@Test
fun testRuntimeLibraryExists() {
TestCase.assertNotNull(
"kotlinx-serialization runtime library is not found. Make sure it is present in test classpath",
runtimeLibraryPath
)
}
}
internal fun getSerializationLibraryRuntimeJar(): File? = try {
PathUtil.getResourcePathForClass(Class.forName("kotlinx.serialization.KSerializer"))
} catch (e: ClassNotFoundException) {
null
}
| 0 | null |
0
| 2 |
acced52384c00df5616231fa5ff7e78834871e64
| 925 |
kotlin
|
Apache License 2.0
|
src/test/java/org/tokend/sdk/test/RemoteFileTest.kt
|
tokend
| 153,458,393 | false | null |
package org.tokend.sdk.test
import org.junit.Assert
import org.junit.Test
import org.tokend.sdk.api.base.model.RemoteFile
import org.tokend.sdk.api.base.model.isReallyNullOrNullAccordingToTheJavascript
import org.tokend.sdk.factory.JsonApiTools
class RemoteFileTest {
@Test
fun parseAndCompare() {
val json = """
{
"key": "dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
"name": "sample.pdf",
"mime_type": "application/pdf"
}
""".trimIndent()
val remoteFileJson = JsonApiTools.objectMapper.readValue(json, RemoteFile::class.java)
Assert.assertEquals(
"dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
remoteFileJson.key
)
Assert.assertEquals(
"sample.pdf",
remoteFileJson.name
)
Assert.assertEquals(
"application/pdf",
remoteFileJson.mimeType
)
}
@Test
fun serialize() {
val file = RemoteFile(
key = "dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
name = "file.pdf",
mimeType = "application/pdf"
)
Assert.assertEquals(
"{\"key\":\"dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2\",\"name\":\"file.pdf\",\"mime_type\":\"application/pdf\"}",
JsonApiTools.objectMapper.writeValueAsString(file)
)
}
@Test
fun parseWithAliasesAndCompare() {
// MIME type alias.
val json = """
{
"key": "dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
"name": "sample.pdf",
"mimeType": "application/pdf"
}
""".trimIndent()
val remoteFileJson = JsonApiTools.objectMapper.readValue(json, RemoteFile::class.java)
Assert.assertEquals(
"dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
remoteFileJson.key
)
Assert.assertEquals(
"sample.pdf",
remoteFileJson.name
)
Assert.assertEquals(
"application/pdf",
remoteFileJson.mimeType
)
}
@Test
fun getUrl() {
val file = RemoteFile(
key = "dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
name = "file.pdf",
mimeType = "application/pdf"
)
Assert.assertEquals(
"Trailing slash must be added if required",
"https://tokend.io/storage/dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
file.getUrl("https://tokend.io/storage")
)
Assert.assertEquals(
"https://tokend.io/storage/dpurex4inf5nahjrsqkkimns6ascqpnddoe2roficpj7xtqorlvw4jd3lsglzzh4a4ctkaxuigqyht6i3t2usyu2",
file.getUrl("https://tokend.io/storage/")
)
}
@Test
fun isImage() {
val imageFiles = listOf(
RemoteFile(
key = "k", name = "n", mimeType = "image/jpeg"
),
RemoteFile(
key = "k", name = "n", mimeType = "image/png"
)
)
val notImage = RemoteFile(
key = "k", name = "n", mimeType = "application/pdf"
)
imageFiles.forEach {
Assert.assertTrue(it.isImage)
}
Assert.assertFalse(notImage.isImage)
}
@Test
fun javascript() {
val fakeNullJsFile = RemoteFile(
key = "", name = "", mimeType = ""
)
val nullFile: RemoteFile? = null
Assert.assertTrue(fakeNullJsFile.isReallyNullOrNullAccordingToTheJavascript)
Assert.assertTrue(nullFile.isReallyNullOrNullAccordingToTheJavascript)
}
}
| 0 |
Kotlin
|
1
| 14 |
84927c92bc5f8b41346106d8241e2ad66cb042fa
| 4,145 |
kotlin-sdk
|
Apache License 2.0
|
src/main/kotlin/bgolc/jsonplaceholder/model/Comment.kt
|
Pazdr0
| 247,317,805 | false | null |
package bgolc.jsonplaceholder.model
data class Comment(
val postId: Int,
override val id: Int,
val name: String,
val email: String,
val body: String
) : DownloadableContent
| 0 |
Kotlin
|
0
| 0 |
4dea653b406bc6d2721190513468d24eb64af60e
| 193 |
JSONPlaceholder
|
Apache License 2.0
|
tempAlgEval/src/main/kotlin/json/parsers/TemporalQueryParser.kt
|
vGsteiger
| 375,249,755 | false | null |
package json.parsers
import json.Model
import json.TemporalQuery
import java.io.File
class TemporalQueryParser : Parser() {
override fun fromJsonToModel(s: String): Model {
return gson.fromJson(s, TemporalQuery::class.java)
}
override fun fromFileToModel(file: String): Model {
val f = File(file).readText()
return gson.fromJson(f, TemporalQuery::class.java)
}
}
| 0 |
Kotlin
|
3
| 0 |
656175458227de2026a507e4fb93318de3c04d00
| 407 |
BachelorsThesisContribution
|
MIT License
|
app/src/main/java/com/wpf/app/quick/demo/fragment/MainTestFragment.kt
|
walgr
| 487,438,913 | false |
{"Kotlin": 549952, "Shell": 488}
|
package com.wpf.app.quick.demo.fragment
import com.wpf.app.quick.activity.QuickBindingFragment
import com.wpf.app.quick.demo.R
import com.wpf.app.quick.demo.databinding.FragmentMainTestBinding
import com.wpf.app.quickutil.helper.dp
import com.wpf.app.quickutil.helper.postDelayed
import com.wpf.app.quickutil.view.onProgressChanged
class MainTestFragment : QuickBindingFragment<FragmentMainTestBinding>(
R.layout.fragment_main_test,
titleName = "测试场"
) {
override fun initView(view: FragmentMainTestBinding?) {
super.initView(view)
view?.llRoot?.postDelayed(2000) {
view.llRoot.setNewItemSpaceWithAnim(20.dp())
view.ll1.setNewItemSpaceWithAnim(20.dp())
view.ll2.setNewItemSpaceWithAnim(20.dp())
}
view?.seekbar?.onProgressChanged { _, progress, _ ->
view.llRoot.setNewItemSpace(progress)
view.ll1.setNewItemSpace(progress)
view.ll2.setNewItemSpace(progress)
}
}
}
| 0 |
Kotlin
|
1
| 16 |
bbecd81eb8f795531b05d5f470cca787c6aa4a34
| 993 |
Quick
|
MIT License
|
api/src/main/java/com/getcode/solana/keys/Types.kt
|
code-payments
| 723,049,264 | false | null |
package com.getcode.solana.keys
typealias Seed16 = Key16
typealias Seed32 = Key32
typealias Hash = Key32
typealias PrivateKey = Key64
class Signature(bytes: List<Byte>): Key64(bytes) {
companion object {
val zero = Signature(ByteArray(LENGTH_64).toList())
}
}
| 6 | null |
11
| 9 |
491cbd54ead3fbe1ed8af1b0e6a0f3b4a1ed2623
| 289 |
code-android-app
|
MIT License
|
components/bottombar/impl/src/main/java/com/flipperdevices/bottombar/impl/navigate/ScreenTabProviderImpl.kt
|
flipperdevices
| 288,258,832 | false | null |
package com.flipperdevices.bottombar.impl.navigate
import com.flipperdevices.archive.api.ArchiveApi
import com.flipperdevices.bottombar.impl.main.TestFragment
import com.flipperdevices.bottombar.impl.model.FlipperBottomTab
import com.flipperdevices.core.di.AppGraph
import com.flipperdevices.info.api.screen.InfoScreenProvider
import com.github.terrakok.cicerone.Screen
import com.github.terrakok.cicerone.androidx.FragmentScreen
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
@ContributesBinding(AppGraph::class)
class ScreenTabProviderImpl @Inject constructor(
private val infoScreenProvider: InfoScreenProvider,
private val archiveApi: ArchiveApi
) : ScreenTabProvider {
override fun getScreen(tab: FlipperBottomTab): Screen {
return when (tab) {
FlipperBottomTab.DEVICE -> infoScreenProvider.deviceInformationScreen()
FlipperBottomTab.STORAGE -> archiveApi.getArchiveScreen()
else -> FragmentScreen { TestFragment() }
}
}
}
| 1 | null |
29
| 267 |
6b116430ac0b16c9fe0a00d119507de6fff5474a
| 1,035 |
Flipper-Android-App
|
MIT License
|
app/src/main/java/com/ruhul/letschatdemo/fragments/login/SignInEmailFragment.kt
|
RUHULRUHUL
| 601,777,294 | false | null |
package com.ruhul.letschatdemo.fragments.login
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.ruhul.letschatdemo.R
import com.ruhul.letschatdemo.databinding.FragmentSignInEmailBinding
import com.ruhul.letschatdemo.utils.MPreference
import com.ruhul.letschatdemo.utils.isValidDestination
class SignInEmailFragment : Fragment() {
private lateinit var binding: FragmentSignInEmailBinding
private lateinit var auth: FirebaseAuth
private val viewModel by activityViewModels<LogInViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSignInEmailBinding.inflate(inflater)
auth = Firebase.auth
binding.signUpButton.setOnClickListener {
signUp()
}
binding.logInButton.setOnClickListener {
signIn()
}
return binding.root
}
private fun signUp() {
if (binding.emailEditText.text.isNotEmpty() && binding.passwordEdiText.text.isNotEmpty()) {
auth.createUserWithEmailAndPassword(
binding.emailEditText.text.toString().trim(),
binding.passwordEdiText.text.toString().trim()
)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
Toast.makeText(
requireContext(), "success",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
requireContext(), "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}
} else {
Toast.makeText(requireContext(), "check this field", Toast.LENGTH_SHORT).show()
}
}
private fun signIn() {
if (binding.emailEditText.text.isNotEmpty() && binding.passwordEdiText.text.isNotEmpty()) {
auth.signInWithEmailAndPassword(
binding.emailEditText.text.toString().trim(),
binding.passwordEdiText.text.toString().trim()
).addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
Toast.makeText(
requireContext(), "log in Success",
Toast.LENGTH_SHORT
).show()
getFetchUserProfile()
} else {
Toast.makeText(
requireContext(), "log in Failed",
Toast.LENGTH_SHORT
).show()
}
}
} else {
Toast.makeText(requireContext(), "check this field", Toast.LENGTH_SHORT).show()
}
}
private fun getFetchUserProfile() {
viewModel.fetchUser(auth)
val preference = MPreference(requireContext())
Log.d("getFetchUserProfile", preference.getUid().toString())
Log.d("getFetchUserProfile", "auth Id" + auth.uid.toString())
/* if (findNavController().isValidDestination(R.id.FLogIn)){
findNavController().navigate(R.id.action_FLogIn_to_FProfile)
}*/
}
}
| 0 |
Kotlin
|
0
| 0 |
c2f0e8c11029080433d95f250f2fe125bbafa658
| 3,731 |
LetsChatProject
|
MIT License
|
data/position/src/commonMain/kotlin/tech/antibytes/keather/data/position/model/store/SaveablePosition.kt
|
bitPogo
| 762,226,385 | false |
{"Kotlin": 372822, "MDX": 11276, "TypeScript": 8443, "JavaScript": 8164, "Swift": 6863, "CSS": 2415, "XS": 819, "C": 194, "HTML": 184, "SCSS": 91}
|
/*
* Copyright (c) 2024 <NAME> (bitPogo) / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package tech.antibytes.keather.data.position.model.store
import tech.antibytes.keather.entity.Latitude
import tech.antibytes.keather.entity.Longitude
data class SaveablePosition(
val longitude: Longitude,
val latitude: Latitude,
)
| 0 |
Kotlin
|
0
| 0 |
45cc973d016f5b8c08906121f321a19353b74a75
| 368 |
keather
|
Apache License 2.0
|
core/src/com/fabiantarrach/breakinout/util/engine/Timespan.kt
|
ftarrach
| 158,593,064 | false | null |
package com.fabiantarrach.breakinout.util.engine
import com.fabiantarrach.breakinout.util.math.Factor
class Timespan(millis: Float) : Factor(millis)
| 0 |
Kotlin
|
0
| 0 |
8ebe8338ad5702f6f12e1cf7ce46b25addf5ebda
| 150 |
BreakinOut
|
MIT License
|
app/src/main/java/net/jspiner/viewer/ui/library/LibraryActivity.kt
|
JSpiner
| 148,756,051 | false | null |
package net.jspiner.viewer.ui.library
import android.Manifest
import android.database.Cursor
import android.os.Bundle
import android.provider.MediaStore
import android.support.v7.widget.GridLayoutManager
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.TedPermission
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import net.jspiner.viewer.R
import net.jspiner.viewer.databinding.ActivityLibraryBinding
import net.jspiner.viewer.ui.base.BaseActivity
import java.io.File
class LibraryActivity : BaseActivity<ActivityLibraryBinding, LibraryViewModel>() {
private val adapter = LibraryAdapter()
override fun getLayoutId(): Int {
return R.layout.activity_library
}
override fun createViewModel(): LibraryViewModel {
return LibraryViewModel()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
init()
}
override fun loadState(bundle: Bundle) {
// no-op
}
override fun saveState(bundle: Bundle) {
// no-op
}
private fun init() {
binding.recyclerView.apply {
layoutManager = GridLayoutManager(context, 2)
adapter = [email protected]
}
requestPermission()
}
private fun requestPermission() {
TedPermission.with(this)
.setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE)
.setPermissionListener(object : PermissionListener {
override fun onPermissionGranted() {
loadEpub()
}
override fun onPermissionDenied(list: MutableList<String>?) {
requestPermission()
}
}).check()
}
private fun loadEpub() {
getEpubFilePathList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(bindLifecycle())
.subscribe { it -> adapter.setDataList(it) }
}
private fun getEpubFilePathList(): Single<ArrayList<String>> {
val cursor: Cursor = contentResolver.query(
MediaStore.Files.getContentUri("external"),
null,
null,
null,
null
) ?: return Single.just(ArrayList())
return Single.create { emitter ->
val epubFileList = ArrayList<String>()
if (cursor.moveToFirst()) {
do {
val file = File(cursor.getString(1))
if (file.extension == "epub") {
epubFileList.add(file.path)
}
} while (cursor.moveToNext())
}
cursor.close()
emitter.onSuccess(epubFileList)
}
}
}
| 5 |
Kotlin
|
4
| 34 |
c39e8b770633a5cec9b76417c824de4a4bbe02aa
| 2,886 |
epub-viewer
|
MIT License
|
app/src/main/java/chat/rocket/android/chatroom/uimodel/BaseFileAttachmentUiModel.kt
|
donald0109
| 149,884,462 | true |
{"Kotlin": 961442, "Shell": 2914, "Java": 1197}
|
package chat.rocket.android.chatroom.uimodel
interface BaseFileAttachmentUiModel<out T> : BaseAttachmentUiModel<T> {
val attachmentTitle: CharSequence
val id: Long
}
| 0 |
Kotlin
|
0
| 2 |
cb57e76e58a247d1cf3cca81713918ae4f09aa76
| 174 |
Rocket.Chat.Android
|
MIT License
|
app/src/main/java/com/berkaykurtoglu/worktracker/domain/usecases/GetCurrentUsersUnmarkedTasksUseCase.kt
|
BerkayyKurtoglu
| 678,305,681 | false | null |
package com.berkaykurtoglu.worktracker.domain.usecases
import com.berkaykurtoglu.worktracker.data.YourTaskRepository
import javax.inject.Singleton
@Singleton
class GetCurrentUsersUnmarkedTasksUseCase (
private val yourTaskRepository: YourTaskRepository
){
operator fun invoke(
email : String
) = yourTaskRepository.getUsersUnmarkedTasks(email)
}
| 0 |
Kotlin
|
0
| 0 |
ce3d72c037b3301115ada78e3f7bb1add818ee68
| 371 |
TaskManager
|
Apache License 2.0
|
js/js.translator/testData/reservedWords/cases/toplevelValKotlin.kt
|
staltz
| 73,301,428 | true |
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
|
package foo
// NOTE THIS FILE IS AUTO-GENERATED by the generateTestDataForReservedWords.kt. DO NOT EDIT!
val Kotlin: Int = 0
fun box(): String {
testNotRenamed("Kotlin", { Kotlin })
return "OK"
}
| 0 |
Java
|
0
| 1 |
80074c71fa925a1c7173e3fffeea4cdc5872460f
| 207 |
kotlin
|
Apache License 2.0
|
intellij-plugin-verifier/verifier-core/src/main/java/com/jetbrains/pluginverifier/results/problems/InstanceAccessOfStaticFieldProblem.kt
|
JetBrains
| 3,686,654 | false |
{"Kotlin": 2524497, "Java": 253600, "CSS": 1454, "JavaScript": 692}
|
/*
* Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.pluginverifier.results.problems
import com.jetbrains.plugin.structure.base.utils.formatMessage
import com.jetbrains.pluginverifier.results.instruction.Instruction
import com.jetbrains.pluginverifier.results.location.FieldLocation
import com.jetbrains.pluginverifier.results.location.MethodLocation
import com.jetbrains.pluginverifier.results.reference.FieldReference
import java.util.*
class InstanceAccessOfStaticFieldProblem(
val fieldReference: FieldReference,
val field: FieldLocation,
val accessor: MethodLocation,
val instruction: Instruction
) : CompatibilityProblem() {
override val problemType
get() = "Instance field changed to static field"
override val shortDescription
get() = "Attempt to execute instance access instruction *{0}* on static field {1}".formatMessage(instruction, field)
override val fullDescription
get() = ("Method {0} has instance field access instruction *{1}* referencing static field {2}, " +
"what might have been caused by incompatible change of the field to static. " +
"This can lead to **IncompatibleClassChangeError** exception at runtime."
).formatMessage(accessor, instruction, field)
override fun equals(other: Any?) = other is InstanceAccessOfStaticFieldProblem
&& fieldReference == other.fieldReference
&& field == other.field
&& accessor == other.accessor
override fun hashCode() = Objects.hash(fieldReference, field, accessor)
}
| 6 |
Kotlin
|
38
| 178 |
4deec2e4e08c9ee4ce087697ef80b8b327703548
| 1,639 |
intellij-plugin-verifier
|
Apache License 2.0
|
src/main/kotlin/view/graph/VertexView.kt
|
spbu-coding-2023
| 800,988,857 | false |
{"Kotlin": 104827}
|
package view.graph
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import viewmodel.graph.VertexViewModel
@Composable
fun <D> VertexView(
viewModel: VertexViewModel<D>,
modifier: Modifier = Modifier,
) {
fun isColorDark(color: Color): Boolean {
val red = color.red
val green = color.green
val blue = color.blue
val brightness = (red * 299 + green * 587 + blue * 114) / 1000
return brightness < 0.5
}
Box(modifier = modifier
.size(viewModel.radius * 2, viewModel.radius * 2)
.offset(viewModel.x, viewModel.y)
.background(
color = viewModel.color,
shape = CircleShape
)
.pointerInput(viewModel) {
detectDragGestures { change, dragAmount ->
change.consume()
viewModel.onDrag(dragAmount)
}
}
) {
if (viewModel.labelVisible) {
Text(
modifier = Modifier
.align(Alignment.Center),
text = viewModel.label,
color = if (isColorDark(viewModel.color)) Color.White else Color.Black
)
}
}
}
| 1 |
Kotlin
|
1
| 0 |
856a9cfd55acbcd37182b5c360a8e4f424264abc
| 1,476 |
graphs-graphs-13
|
MIT License
|
src/main/kotlin/pingsetting_boxes/PingSettingBoxesB.kt
|
olracnai
| 720,999,284 | false |
{"Kotlin": 115621}
|
package pingsetting_boxes
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import custom_resources.ErgoGray
import custom_resources.settingSpacerH
import engine_logic.*
import engine_logic.SLFObjectA.loadFontSizeA
////////////////////////////// Second column of boxes located in Ip settings
@Composable
@Preview
fun pingSettingBoxesB() {
var ipAddressB0 by remember { mutableStateOf(readIpFile4()) }
var ipAddressB1 by remember { mutableStateOf(readIpFile5()) }
var ipAddressB2 by remember { mutableStateOf(readIpFile6()) }
var ipAddressB3 by remember { mutableStateOf(readIpFile7()) }
var ipTitleB0 by remember { mutableStateOf(readTiFile4()) }
var ipTitleB1 by remember { mutableStateOf(readTiFile5()) }
var ipTitleB2 by remember { mutableStateOf(readTiFile6()) }
var ipTitleB3 by remember { mutableStateOf(readTiFile7()) }
// Font size ram
val fontSizedSA by remember { mutableStateOf(loadFontSizeA().sp) }
Column( modifier = Modifier.padding(top = 10.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
////////////////////////////// Edit box B0 - ReWr4
Box( modifier = Modifier
.background(color = Color.Black, shape = AbsoluteRoundedCornerShape(8.dp))
.padding(4.dp)
.weight(1f)
.background((ErgoGray), shape = AbsoluteRoundedCornerShape(5.dp)), // color based on ping result
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
/////////////// Title input B0
TextField(
value = ipTitleB0,
onValueChange = { newValue ->
ipTitleB0 = newValue
writeTiToFile4(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = placeHolderTitle, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center)
}
}
)
/////////////// Divider line B0
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color.Black,
thickness = 1.5.dp
)
/////////////// Ip input B0
TextField(
value = ipAddressB0,
onValueChange = { newValue ->
ipAddressB0 = newValue
writeIpToFile4(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = { Box( modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center ) {
Text( text = placeHolderIP, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center ) }
}
)
}
}
////////////////////////////// Edit box B1 - ReWr5
settingSpacerH()
Box(
modifier = Modifier
.background(color = Color.Black, shape = AbsoluteRoundedCornerShape(8.dp))
.padding(4.dp)
.weight(1f)
.background((ErgoGray), shape = AbsoluteRoundedCornerShape(5.dp)), // color based on ping result
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
/////////////// Title input B1
TextField(
value = ipTitleB1,
onValueChange = { newValue ->
ipTitleB1 = newValue
writeTiToFile5(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = placeHolderTitle, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center)
}
}
)
/////////////// Divider line B1
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color.Black,
thickness = 1.5.dp
)
/////////////// Ip input B1
TextField(
value = ipAddressB1,
onValueChange = { newValue ->
ipAddressB1 = newValue
writeIpToFile5(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = { Box( modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center ) {
Text( text = placeHolderIP, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center ) }
}
)
}
}
////////////////////////////// Edit box B2 - ReWr6
settingSpacerH()
Box(
modifier = Modifier
.background(color = Color.Black, shape = AbsoluteRoundedCornerShape(8.dp))
.padding(4.dp)
.weight(1f)
.background((ErgoGray), shape = AbsoluteRoundedCornerShape(5.dp)), // color based on ping result
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
/////////////// Title input B2
TextField(
value = ipTitleB2,
onValueChange = { newValue ->
ipTitleB2 = newValue
writeTiToFile6(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = placeHolderTitle, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center)
}
}
)
/////////////// Divider line B2
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color.Black,
thickness = 1.5.dp
)
/////////////// Ip input B2
TextField(
value = ipAddressB2,
onValueChange = { newValue ->
ipAddressB2 = newValue
writeIpToFile6(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = { Box( modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center ) {
Text( text = placeHolderIP, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center ) }
}
)
}
}
////////////////////////////// Edit box B3 - ReWr7
settingSpacerH()
Box(
modifier = Modifier
.background(color = Color.Black, shape = AbsoluteRoundedCornerShape(8.dp))
.padding(4.dp)
.weight(1f)
.background((ErgoGray), shape = AbsoluteRoundedCornerShape(5.dp)), // color based on ping result
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
/////////////// Title input B3
TextField(
value = ipTitleB3,
onValueChange = { newValue ->
ipTitleB3 = newValue
writeTiToFile7(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = placeHolderTitle, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center)
}
}
)
/////////////// Divider line B3
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color.Black,
thickness = 1.5.dp
)
/////////////// Ip input B3
TextField(
value = ipAddressB3,
onValueChange = { newValue ->
ipAddressB3 = newValue
writeIpToFile7(newValue)
},
modifier = Modifier.fillMaxSize().weight(1f),
textStyle = TextStyle(
fontSize = fontSizedSA,
color = Color.White,
textAlign = TextAlign.Center
),
placeholder = { Box( modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center ) {
Text( text = placeHolderIP, fontSize = fontSizedSA,
color = Color.White, textAlign = TextAlign.Center ) }
}
)
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
4d3f74d97c42250e747983bd696bea7676d09dc1
| 12,547 |
MonithorClient
|
MIT License
|
src/main/kotlin/xyz/tcreopargh/versioner/compat/crafttweaker/SponsorsCT.kt
|
TCreopargh
| 344,445,685 | false | null |
package xyz.tcreopargh.versioner.compat.crafttweaker
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.data.IData
import crafttweaker.api.minecraft.CraftTweakerMC
import crafttweaker.api.player.IPlayer
import crafttweaker.api.text.ITextComponent
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
import xyz.tcreopargh.versioner.data.SponsorData
import xyz.tcreopargh.versioner.util.CT_NAMESPACE
import xyz.tcreopargh.versioner.util.getDataFromJsonElement
import java.util.stream.Collectors
/**
* Note: Don't try to add ZenGetters or ZenSetters, they are bugged when used with ZenMethods
* @author TCreopargh
*/
@ZenClass(CT_NAMESPACE + "Sponsors")
@ZenRegister
class SponsorsCT(val internal: SponsorData) {
@ZenMethod
fun isPlayerInCategory(player: IPlayer, category: String): Boolean {
val mcPlayer = CraftTweakerMC.getPlayer(player)
if (mcPlayer != null) {
return internal.isPlayerInCategory(mcPlayer, category)
}
return false
}
@ZenMethod
fun isSponsor(player: IPlayer): Boolean {
val mcPlayer = CraftTweakerMC.getPlayer(player)
if (mcPlayer != null) {
return internal.isSponsor(mcPlayer)
}
return false
}
@ZenMethod
fun getPlayerCategory(player: IPlayer): String? {
val mcPlayer = CraftTweakerMC.getPlayer(player)
if (mcPlayer != null) {
return internal.checkPlayer(mcPlayer)?.name as String
}
return null
}
@ZenMethod
fun getCategories(): List<String> = internal.categoryList.stream().map { v ->
v.name
}.collect(Collectors.toList())
@ZenMethod
fun getCategoryDisplayName(category: String): String? = internal[category]?.displayName
@ZenMethod
fun getFormattedCategory(category: String): ITextComponent? {
val text = internal[category]?.getFormattedName()
return if (text != null) CraftTweakerMC.getITextComponent(text) else null
}
@ZenMethod
fun getFormattedCategorySponsors(category: String): List<ITextComponent?>? {
return internal[category]?.getFormattedText()?.stream()?.map { v ->
if (v != null) CraftTweakerMC.getITextComponent(v) else null
}?.collect(Collectors.toList())
}
@ZenMethod
fun getAsData(): IData = getDataFromJsonElement(internal.jsonArray)
}
| 1 |
Kotlin
|
0
| 7 |
fba434f37dd13295728cec3c40561ea57f42fc48
| 2,421 |
Versioner
|
MIT License
|
app/src/main/java/com/example/buncisapp/views/history/HistoryActivity.kt
|
pertamina-kontinental
| 680,141,012 | false | null |
package com.example.buncisapp.views.history
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.buncisapp.R
class HistoryActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
}
}
| 0 |
Kotlin
|
0
| 0 |
a17ba97a87e3f6d77a15b03699267e007dde44ba
| 353 |
BuncisMobileApp
|
MIT License
|
core/persistence/src/desktopMain/kotlin/org/michaelbel/movies/persistence/database/MoviePersistence.kt
|
michaelbel
| 115,437,864 | false |
{"Kotlin": 774529, "Java": 10013, "Swift": 342, "Shell": 235}
|
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package org.michaelbel.movies.persistence.database
import androidx.paging.PagingSource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import org.michaelbel.movies.persistence.database.entity.MoviePojo
import org.michaelbel.movies.persistence.database.entity.mini.MovieDbMini
actual class MoviePersistence internal constructor() {
actual fun pagingSource(movieList: String): PagingSource<Int, MoviePojo> {
TODO("Not Implemented")
}
actual fun moviesFlow(movieList: String, limit: Int): Flow<List<MoviePojo>> {
return emptyFlow()
}
actual suspend fun movies(movieList: String, limit: Int): List<MoviePojo> {
return emptyList()
}
actual suspend fun moviesMini(movieList: String, limit: Int): List<MovieDbMini> {
return emptyList()
}
actual suspend fun insertMovies(movies: List<MoviePojo>) {}
actual suspend fun insertMovie(movie: MoviePojo) {}
actual suspend fun removeMovies(movieList: String) {}
actual suspend fun removeMovie(movieList: String, movieId: Int) {}
actual suspend fun movieById(pagingKey: String, movieId: Int): MoviePojo? {
return null
}
actual suspend fun maxPosition(movieList: String): Int? {
return null
}
actual suspend fun isEmpty(movieList: String): Boolean {
return true
}
actual suspend fun updateMovieColors(movieId: Int, containerColor: Int, onContainerColor: Int) {}
}
| 5 |
Kotlin
|
31
| 210 |
4d27e5e343e6d68953fa39330203b7b6a4927ff0
| 1,536 |
movies
|
Apache License 2.0
|
app/src/main/java/me/cyber/nukleos/dagger/PredictModule.kt
|
cyber-punk-me
| 141,065,829 | false | null |
package me.cyber.nukleos.dagger
import dagger.Module
import dagger.Provides
import me.cyber.nukleos.ui.predict.PredictInterface
import me.cyber.nukleos.ui.predict.PredictPresenter
@Module
class PredictModule {
@Provides
fun providePredictPresenter(chartsView: PredictInterface.View, peripheryManager: PeripheryManager)
= PredictPresenter(chartsView, peripheryManager)
}
| 1 |
Kotlin
|
9
| 17 |
03fad246834e6c569e301b005037849bdfccb664
| 393 |
nukleos
|
Apache License 2.0
|
jetbrains-core/tst/software/aws/toolkits/jetbrains/core/credentials/MockCredentialsManager.kt
|
ranyoo2367
| 278,680,393 | true |
{"Kotlin": 2018365, "Java": 192426, "C#": 117040}
|
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.core.credentials
import com.intellij.openapi.components.ServiceManager
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials
import software.amazon.awssdk.auth.credentials.AwsCredentials
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider
import software.amazon.awssdk.http.SdkHttpClient
import software.aws.toolkits.core.credentials.CredentialProviderFactory
import software.aws.toolkits.core.credentials.CredentialsChangeListener
import software.aws.toolkits.core.credentials.ToolkitCredentialsIdentifier
import software.aws.toolkits.core.credentials.ToolkitCredentialsProvider
import software.aws.toolkits.core.region.AwsRegion
class MockCredentialsManager : CredentialManager() {
init {
reset()
}
fun reset() {
getCredentialIdentifiers().filterNot { it.id == DUMMY_PROVIDER_IDENTIFIER.id }.forEach { removeProvider(it) }
addProvider(DUMMY_PROVIDER_IDENTIFIER)
}
fun addCredentials(
id: String,
credentials: AwsCredentials = AwsBasicCredentials.create("Access", "Secret")
): ToolkitCredentialsIdentifier {
val credentialIdentifier = MockCredentialIdentifier(id, StaticCredentialsProvider.create(credentials))
addProvider(credentialIdentifier)
return credentialIdentifier
}
fun removeCredentials(credentialIdentifier: ToolkitCredentialsIdentifier) {
removeProvider(credentialIdentifier)
}
override fun factoryMapping(): Map<String, CredentialProviderFactory> = mapOf(MockCredentialProviderFactory.id to MockCredentialProviderFactory)
companion object {
fun getInstance(): MockCredentialsManager = ServiceManager.getService(CredentialManager::class.java) as MockCredentialsManager
val DUMMY_PROVIDER_IDENTIFIER: ToolkitCredentialsIdentifier = MockCredentialIdentifier(
"DUMMY_CREDENTIALS",
StaticCredentialsProvider.create(AwsBasicCredentials.create("DummyAccess", "DummySecret"))
)
}
private class MockCredentialIdentifier(override val displayName: String, val credentials: AwsCredentialsProvider) :
ToolkitCredentialsIdentifier() {
override val id: String = displayName
override val factoryId: String = "mockCredentialProviderFactory"
}
private object MockCredentialProviderFactory :
CredentialProviderFactory {
override val id: String = "mockCredentialProviderFactory"
override fun setUp(credentialLoadCallback: CredentialsChangeListener) {}
override fun createAwsCredentialProvider(
providerId: ToolkitCredentialsIdentifier,
region: AwsRegion,
sdkHttpClientSupplier: () -> SdkHttpClient
): ToolkitCredentialsProvider = ToolkitCredentialsProvider(providerId, (providerId as MockCredentialIdentifier).credentials)
}
}
| 0 |
Kotlin
|
0
| 0 |
aaa2a7e33e46966f036c6da37e9fc574369ae38e
| 3,079 |
aws-toolkit-jetbrains
|
Apache License 2.0
|
common/src/main/kotlin/org/valkyrienskies/tournament/TournamentDebugHelper.kt
|
ConstantDust
| 598,304,637 | false | null |
package org.valkyrienskies.tournament
import org.valkyrienskies.tournament.api.debug.DebugObject
import org.valkyrienskies.tournament.api.debug.DebugObjectID
class TournamentDebugHelper {
companion object {
private var objects = HashMap<Long, DebugObject?>()
fun addObject(obj : DebugObject) : Long {
val id = objects.size
objects.put(id.toLong(), obj)
return (id).toLong()
}
fun updateObject(id : DebugObjectID, obj : DebugObject) : DebugObjectID {
if (id.toInt() == -1) {
return addObject(obj)
} else {
objects[id.toInt().toLong()] = obj
}
return id
}
fun removeObject(id : DebugObjectID) {
objects.remove(id)
}
fun list() : HashMap<Long, DebugObject?> {
return objects
}
fun exists(id : Long) : Boolean {
return objects.containsKey(id)
}
}
}
| 0 | null |
0
| 3 |
c80088257a7d7cb1b90291db9f0d0924ebe5a236
| 1,002 |
VS2_tournament
|
Apache License 2.0
|
KotlinTut/app/src/test/java/com/goldenthumb/android/kotlintut/KotlinDataClass.kt
|
zhijunsheng
| 374,335,076 | false | null |
package com.goldenthumb.android.kotlintut
import org.junit.Test
class KotlinDataClass {
private class ChessPieceNormalClass(val row: Int, val col: Int, val chessman: String)
private data class ChessPieceDataClass(val row: Int, val col: Int, val chessman: String)
@Test
fun testChessPiece() {
val normalPiece1 = ChessPieceNormalClass(0, 0, "King")
val normalPiece2 = ChessPieceNormalClass(0, 0, "King")
print("with normal class: ${normalPiece1 == normalPiece2}\n")
val dataPiece1 = ChessPieceDataClass(0, 0, "King")
val dataPiece2 = ChessPieceDataClass(0, 0, "King")
print("with data class: ${dataPiece1 == dataPiece2}\n")
print("$normalPiece1\n$dataPiece1") // toString()
}
}
| 0 |
Kotlin
|
0
| 0 |
9f415f79ac89f1f9df25ab1eb85a1aef4d4ec3f3
| 757 |
kotlin-tut-andr
|
MIT License
|
shared/src/commonMain/kotlin/uk/co/sentinelweb/cuer/app/util/recent/RecentLocalPlaylists.kt
|
sentinelweb
| 220,796,368 | false | null |
package uk.co.sentinelweb.cuer.app.util.recent
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract.Identifier
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract.Source.LOCAL
import uk.co.sentinelweb.cuer.app.orchestrator.toIdentifier
import uk.co.sentinelweb.cuer.app.util.prefs.multiplatfom_settings.MultiPlatformPreferencesWrapper
import uk.co.sentinelweb.cuer.core.wrapper.LogWrapper
import uk.co.sentinelweb.cuer.domain.PlaylistDomain
class RecentLocalPlaylists constructor(
private val prefs: MultiPlatformPreferencesWrapper,
private val log: LogWrapper,
// private val localSearch: LocalSearchPlayistInteractor,
) {
init {
log.tag(this)
}
fun getRecent(): List<Long> = prefs.recentIds
?.split(",")
?.map { it.toLong() }
?.toMutableList()
?: mutableListOf()
fun addRecent(pl: PlaylistDomain) {
val id = pl.id
addPlaylistId(id)
}
fun addRecentId(id: Long) {
addPlaylistId(id)
}
private fun addPlaylistId(id: Long?) {
val current = getRecent().toMutableList()
if (id != null) {
current.remove(id)
current.add(id)
while (current.size > MAX_RECENT) current.removeAt(0)
prefs.recentIds = current.toTypedArray().joinToString(",")
}
}
fun buildRecentSelectionList(): List<Identifier<Long>> {
val recent = mutableListOf<Identifier<Long>>()
// prefs.lastAddedPlaylistId
// ?.toIdentifier(LOCAL)
// ?.also { recent.add(it) }
prefs.pinnedPlaylistId
?.toIdentifier(LOCAL)
?.also { recent.add(0, it) }
// localSearch.search()
// ?.playlists
// ?.forEach { playlist ->
// playlist.id?.toIdentifier(LOCAL)?.also { recent.add(it) }
// }
getRecent().reversed().forEach { id ->
id.toIdentifier(LOCAL).also { recent.add(it) }
}
return recent.distinct()
}
companion object {
private const val MAX_RECENT = 15
}
}
| 82 |
Kotlin
|
0
| 2 |
cd5b28c720c08c9b718f904421b0580e6b716ec0
| 2,110 |
cuer
|
Apache License 2.0
|
tegral-featureful/src/main/kotlin/guru/zoroark/tegral/featureful/SimpleFeature.kt
|
utybo
| 491,247,680 | false |
{"Kotlin": 1066259, "Nix": 2449, "Shell": 8}
|
/*
* 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 guru.zoroark.tegral.featureful
import guru.zoroark.tegral.di.extensions.ExtensibleContextBuilderDsl
/**
* A simplified interface for [Feature] that cannot be configured.
*
* In reality, the type of the configuration is [Unit]. If you need to use [SimpleFeature] in combination with
* [ConfigurableFeature] or other specializations of [Feature], use `Unit` as the type parameter.
*/
interface SimpleFeature : Feature<Unit> {
override fun createConfigObject() = Unit
/**
* Identical to [Feature.install], but without a configuration object.
*/
fun ExtensibleContextBuilderDsl.install()
override fun ExtensibleContextBuilderDsl.install(configuration: Unit) {
install()
}
}
| 26 |
Kotlin
|
4
| 37 |
fa4284047f2ce7ba9ee78e92d8c67954716e9dcc
| 1,288 |
Tegral
|
Apache License 2.0
|
android/apps/AutoTesterAndroid/app/src/main/java/com/mousebirdconsulting/autotester/TestCases/FindHeightTestCase.kt
|
coderDeven
| 388,133,305 | true |
{"C++": 10436489, "HTML": 5020617, "Objective-C": 2171996, "Objective-C++": 2145418, "C": 1336540, "Java": 1244975, "Kotlin": 286491, "Swift": 198197, "Python": 91496, "Scheme": 64772, "Metal": 49677, "CMake": 29274, "Ruby": 14918, "Roff": 12277, "Shell": 9920, "SWIG": 6571, "Rich Text Format": 3451, "CSS": 1130, "Batchfile": 746, "Makefile": 83}
|
package com.mousebirdconsulting.autotester.TestCases
import android.app.Activity
import android.os.Handler
import com.mousebird.maply.*
import com.mousebirdconsulting.autotester.Framework.MaplyTestCase
/**
* Find Height just tests the findHeight logic for the globe and map.
*/
class FindHeightTestCase(activity: Activity) : MaplyTestCase(activity, "Find Height") {
// Run a findHeight
fun runDelayedFind(vc: BaseController) {
Handler().postDelayed(Runnable {
val bbox = Mbr(Point2d.FromDegrees(7.05090689853, 47.7675500593),
Point2d.FromDegrees(8.06813647023, 49.0562323851))
val center = Point2d.FromDegrees((7.05090689853+8.06813647023)/2, (47.7675500593+49.0562323851)/2)
if (vc is GlobeController) {
val height = vc.findHeightToViewBounds(bbox, center)
vc.animatePositionGeo(center.x,center.y,height,1.0)
} else if (vc is MapController) {
val height = vc.findHeightToViewBounds(bbox, center)
vc.animatePositionGeo(center.x,center.y,height,1.0)
}
}, 1000)
}
var baseCase : MaplyTestCase? = null
override fun setUpWithMap(mapVC: MapController?): Boolean {
baseCase = CartoLightTestCase(getActivity())
baseCase?.setUpWithMap(mapVC)
val loc = Point2d.FromDegrees(-98.58, 39.83)
mapVC?.setPositionGeo(loc.x,loc.y,1.0)
runDelayedFind(mapVC!!)
return true
}
override fun setUpWithGlobe(globeVC: GlobeController?): Boolean {
baseCase = CartoLightTestCase(getActivity())
baseCase?.setUpWithGlobe(globeVC)
val loc = Point2d.FromDegrees(-98.58, 39.83)
globeVC?.setPositionGeo(loc.x,loc.y,1.5)
runDelayedFind(globeVC!!)
return true
}
}
| 0 | null |
0
| 0 |
6ab04c480b4314ca8a1cc95eccc880bf1320a95a
| 1,834 |
WhirlyGlobe
|
Apache License 2.0
|
components-core/src/main/java/com/adyen/checkout/components/core/internal/analytics/data/remote/AnalyticsTrackRequestProvider.kt
|
Adyen
| 91,104,663 | false |
{"Kotlin": 4786289, "Shell": 4700}
|
/*
* Copyright (c) 2024 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by ararat on 4/3/2024.
*/
package com.adyen.checkout.components.core.internal.analytics.data.remote
import com.adyen.checkout.components.core.internal.analytics.AnalyticsEvent
import com.adyen.checkout.components.core.internal.analytics.AnalyticsPlatformParams
import com.adyen.checkout.components.core.internal.data.model.AnalyticsTrackInfo
import com.adyen.checkout.components.core.internal.data.model.AnalyticsTrackLog
import com.adyen.checkout.components.core.internal.data.model.AnalyticsTrackRequest
internal class AnalyticsTrackRequestProvider {
operator fun invoke(
infoList: List<AnalyticsEvent.Info>,
logList: List<AnalyticsEvent.Log>,
): AnalyticsTrackRequest {
return AnalyticsTrackRequest(
channel = AnalyticsPlatformParams.channel,
platform = AnalyticsPlatformParams.platform,
info = infoList.map { event -> event.mapToTrackEvent() },
logs = logList.map { event -> event.mapToTrackEvent() },
)
}
private fun AnalyticsEvent.Info.mapToTrackEvent() = AnalyticsTrackInfo(
id = id,
timestamp = timestamp,
component = component,
type = type?.value,
target = target,
isStoredPaymentMethod = isStoredPaymentMethod,
brand = brand,
issuer = issuer,
validationErrorCode = validationErrorCode,
validationErrorMessage = validationErrorMessage,
)
private fun AnalyticsEvent.Log.mapToTrackEvent() = AnalyticsTrackLog(
id = id,
timestamp = timestamp,
component = component,
type = type?.value,
subType = subType,
target = target,
message = message,
result = result,
)
}
| 23 |
Kotlin
|
66
| 126 |
5b728181dbf41af37c5f9d436b4c65cb30a23e41
| 1,878 |
adyen-android
|
MIT License
|
web/src/main/kotlin/top/bettercode/summer/web/serializer/ArraySerializer.kt
|
top-bettercode
| 387,652,015 | false |
{"Kotlin": 2860676, "Java": 23654, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
|
package top.bettercode.summer.web.serializer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.BeanProperty
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl
import com.fasterxml.jackson.databind.jsontype.TypeSerializer
import com.fasterxml.jackson.databind.ser.ContextualSerializer
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer
import top.bettercode.summer.web.serializer.annotation.JsonArray
/**
* JSON序列化url自动补全
*
* @author <NAME>
*/
@JacksonStdImpl
class ArraySerializer @JvmOverloads constructor(
private val useExtensionField: Boolean = true,
private val separator: String = ",") : StdScalarSerializer<String>(String::class.java, false), ContextualSerializer {
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
if (useExtensionField) {
gen.writeString(value)
val outputContext = gen.outputContext
val fieldName = outputContext.currentName
gen.writeObjectField(fieldName + "Array",
if (value.isNotBlank()) value.split(separator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() else arrayOf(0))
} else {
gen.writeObject(
if (value.isNotBlank()) value.split(separator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() else arrayOf(0))
}
}
override fun serializeWithType(value: String, gen: JsonGenerator, provider: SerializerProvider,
typeSer: TypeSerializer) {
serialize(value, gen, provider)
}
override fun createContextual(prov: SerializerProvider, property: BeanProperty?): JsonSerializer<*> {
if (property != null) {
val annotation = property.getAnnotation(JsonArray::class.java)
?: throw RuntimeException("未注解@" + JsonArray::class.java.name)
return ArraySerializer(annotation.extended, annotation.value)
}
return this
}
}
| 0 |
Kotlin
|
0
| 1 |
da096b3c592335e25869d9ff2cdb91c2551c794c
| 2,150 |
summer
|
Apache License 2.0
|
lang/src/main/kotlin/com/uchuhimo/datamodel/DataModel.kt
|
uchuhimo
| 90,075,694 | false | null |
package com.uchuhimo.datamodel
import java.util.Arrays
import kotlin.reflect.KClass
interface InputStream {
fun readInt(): Int
fun readIntArray(): IntArray
fun <T : Any> read(type: KClass<T>): T
}
interface OutputStream {
fun writeInt(value: Int)
fun writeIntArray(value: IntArray)
fun <T : Any> write(value: T, type: KClass<out T>)
}
class InputStreamImpl : InputStream {
override fun readInt(): Int {
return 1
}
override fun readIntArray(): IntArray {
return intArrayOf(0)
}
override fun <T : Any> read(type: KClass<T>): T {
@Suppress("UNCHECKED_CAST")
return ID(2, 3) as T
}
}
class OutputStreamImpl : OutputStream {
override fun writeInt(value: Int) {
println("int: $value")
}
override fun writeIntArray(value: IntArray) {
println("int array: ${Arrays.toString(value)}")
}
override fun <T : Any> write(value: T, type: KClass<out T>) {
println("object: $value")
}
}
interface Serializer<T> {
fun serialize(value: T, outputStream: OutputStream)
}
interface Deserializer<T> {
fun deserialize(inputStream: InputStream): T
}
interface Serde<T> : Serializer<T>, Deserializer<T>
class IntSerde : Serde<Int> {
override fun serialize(value: Int, outputStream: OutputStream) {
outputStream.writeInt(value)
}
override fun deserialize(inputStream: InputStream): Int {
return inputStream.readInt()
}
}
class IntArraySerde : Serde<IntArray> {
override fun serialize(value: IntArray, outputStream: OutputStream) {
outputStream.writeIntArray(value)
}
override fun deserialize(inputStream: InputStream): IntArray {
return inputStream.readIntArray()
}
}
abstract class ObjectSerde<T>(
private val serializeActions: List<(T, OutputStream) -> Unit>) : Serde<T> {
override fun serialize(value: T, outputStream: OutputStream) {
serializeActions.forEach { action -> action(value, outputStream) }
}
}
class ImmutableSerde<T>(
serializeActions: List<(T, OutputStream) -> Unit>,
private val deserializeActions: List<(InputStream) -> Any>,
private val create: (List<Any>) -> T) : ObjectSerde<T>(serializeActions) {
override fun deserialize(inputStream: InputStream): T {
return create(deserializeActions.map { action -> action(inputStream) })
}
}
class MutableSerde<T>(
serializeActions: List<(T, OutputStream) -> Unit>,
private val deserializeActions: List<(T, InputStream) -> Unit>,
private val create: () -> T) : ObjectSerde<T>(serializeActions) {
override fun deserialize(inputStream: InputStream): T {
val value = create()
deserializeActions.forEach { action -> action(value, inputStream) }
return value
}
}
data class ID(val group: Int, val value: Int)
data class WrappedArray(val array: IntArray, val length: Int, val id: ID)
fun serialize(wrappedArray: WrappedArray, outputStream: OutputStream) {
outputStream.writeIntArray(wrappedArray.array)
outputStream.writeInt(wrappedArray.length)
outputStream.write(wrappedArray.id, ID::class)
}
fun deserialize(inputStream: InputStream): WrappedArray {
val array = inputStream.readIntArray()
val length = inputStream.readInt()
val id = inputStream.read(ID::class)
return WrappedArray(array, length, id)
}
sealed class FieldModel<T>
sealed class ImmutableModel<T> : FieldModel<T>()
sealed class MutableModel<T> : FieldModel<T>()
data class ImmutableIntModel<T>(val getter: (T) -> Int) : ImmutableModel<T>()
data class MutableIntModel<T>(val getter: (T) -> Int, val setter: (T, Int) -> Unit) : MutableModel<T>()
data class ImmutableIntArrayModel<T>(val getter: (T) -> IntArray) : ImmutableModel<T>()
data class MutableIntArrayModel<T>(val getter: (T) -> IntArray, val setter: (T, IntArray) -> Unit) : MutableModel<T>()
data class ImmutableObjectModel<T, ObjectType : Any>(val type: KClass<ObjectType>, val getter: (T) -> ObjectType) : ImmutableModel<T>()
data class MutableObjectModel<T, ObjectType : Any>(val type: KClass<ObjectType>, val getter: (T) -> ObjectType, val setter: (T, ObjectType) -> Unit) : MutableModel<T>()
sealed class ParentModel<T>
data class ImmutableParentModel<T>(val create: (List<Any>) -> T, val fields: List<ImmutableModel<T>>) : ParentModel<T>()
data class MutableParentModel<T>(val create: () -> T, val fields: List<MutableModel<T>>) : ParentModel<T>()
fun <T> modelToSerde(model: ParentModel<T>): Serde<T> = when (model) {
is ImmutableParentModel<T> -> {
ImmutableSerde(
serializeActions = model.fields.map { field ->
when (field) {
is ImmutableIntModel<T> ->
{ instance: T, outputStream: OutputStream ->
outputStream.writeInt(field.getter(instance))
}
is ImmutableIntArrayModel<T> ->
{ instance, outputStream ->
outputStream.writeIntArray(field.getter(instance))
}
is ImmutableObjectModel<T, *> ->
{ instance, outputStream ->
val value = field.getter(instance)
outputStream.write(value, value::class)
}
}
},
deserializeActions = model.fields.map { field ->
when (field) {
is ImmutableIntModel<T> ->
{ inputStream: InputStream -> inputStream.readInt() }
is ImmutableIntArrayModel<T> ->
{ inputStream -> inputStream.readIntArray() }
is ImmutableObjectModel<T, *> ->
{ inputStream -> inputStream.read(field.type) }
}
},
create = model.create
)
}
else -> TODO()
}
class ImmutableContext<T> {
private lateinit var create: (List<Any>) -> T
private val fields: MutableList<ImmutableModel<T>> = mutableListOf()
fun create(func: (List<Any>) -> T) {
create = func
}
fun withInt(getter: (T) -> Int) {
fields += ImmutableIntModel(getter)
}
fun withIntArray(getter: (T) -> IntArray) {
fields += ImmutableIntArrayModel(getter)
}
fun <ObjectType : Any> withObject(type: KClass<ObjectType>, getter: (T) -> ObjectType) {
fields += ImmutableObjectModel(type, getter)
}
fun toModel(): ImmutableParentModel<T> = ImmutableParentModel(create, fields)
}
fun <T> immutable(init: ImmutableContext<T>.() -> Unit): ImmutableParentModel<T> = ImmutableContext<T>().apply(init).toModel()
fun main(args: Array<String>) {
val wrappedArray = WrappedArray(intArrayOf(0), 1, ID(2, 3))
val outputStream = OutputStreamImpl()
val inputStream = InputStreamImpl()
serialize(wrappedArray, outputStream)
serialize(deserialize(inputStream), outputStream)
val serde = ImmutableSerde(
serializeActions = arrayListOf(
{ wrappedArray, outputStream -> outputStream.writeIntArray(wrappedArray.array) },
{ wrappedArray, outputStream -> outputStream.writeInt(wrappedArray.length) },
{ wrappedArray, outputStream -> outputStream.write(wrappedArray.id, wrappedArray.id::class) }
),
deserializeActions = arrayListOf(
{ inputStream -> inputStream.readIntArray() },
{ inputStream -> inputStream.readInt() },
{ inputStream -> inputStream.read(ID::class) }
),
create = { args -> WrappedArray(args[0] as IntArray, args[1] as Int, args[2] as ID) }
)
serde.serialize(serde.deserialize(inputStream), outputStream)
val wrapperArrayModel1 = ImmutableParentModel(
create = { args -> WrappedArray(args[0] as IntArray, args[1] as Int, args[2] as ID) },
fields = arrayListOf(
ImmutableIntArrayModel(WrappedArray::array),
ImmutableIntModel(WrappedArray::length),
ImmutableObjectModel(ID::class, WrappedArray::id)
)
)
val serde1 = modelToSerde(wrapperArrayModel1)
serde1.serialize(serde1.deserialize(inputStream), outputStream)
val wrapperArrayModel2 = immutable<WrappedArray> {
withIntArray(WrappedArray::array)
withInt(WrappedArray::length)
withObject(ID::class, WrappedArray::id)
create { WrappedArray(it[0] as IntArray, it[1] as Int, it[2] as ID) }
}
val serde2 = modelToSerde(wrapperArrayModel2)
serde2.serialize(serde2.deserialize(inputStream), outputStream)
}
| 0 |
Kotlin
|
0
| 1 |
cbd4b6fbdc6c9af595369a4d7389044792cd20c0
| 8,907 |
kotlin-playground
|
Apache License 2.0
|
core/src/main/java/com/alphacoder/core/util/ImageLoader.kt
|
amircoder
| 247,449,623 | false | null |
package com.alphacoder.core.util
import android.view.View
import android.widget.ImageView
interface ImageLoader {
fun loadImage(view: ImageView,
placeHolderId: Int,
errorPlaceHolderId: Int,
imageUrl: String)
}
| 0 |
Kotlin
|
0
| 0 |
bbfe9f7da4ff64cbef0379ef42e6a7931b6832a9
| 270 |
ProjectX
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.