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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/ryderbelserion/api/storage/FileManager.kt | ryderbelserion | 670,341,905 | false | null | package com.ryderbelserion.api.storage
import java.io.File
interface FileManager {
fun addFile(fileExtension: FileExtension?)
fun saveFile(fileExtension: FileExtension?)
fun removeFile(fileExtension: FileExtension?)
fun getFile(fileExtension: FileExtension?): File?
} | 0 | Kotlin | 0 | 0 | 0ffa4642dd8341ba42944007aebc20102c7b7f34 | 287 | Krul | MIT License |
app/src/main/java/com/capstone/backgroundlocaton1/MainActivity.kt | NarendranathReddyMaddikeri2007 | 727,041,125 | false | {"Kotlin": 12637} | package com.capstone.backgroundlocaton1
import android.Manifest
import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.capstone.backgroundlocaton1.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
companion object{
const val ACTION_START_LOCATION_SERVICE : String = "startLocationService"
const val ACTION_STOP_LOCATION_SERVICE : String = "stopLocationService"
}
private val REQUEST_CODE_LOCATION_PREMISSION = 1
private lateinit var _binding : ActivityMainBinding
private val locationReceiver = object : BroadcastReceiver(){
override fun onReceive(p0: Context?, intent: Intent?) {
if (intent!=null && intent.action=="location_update"){
val latitude = intent.getDoubleExtra("latitude",0.0)
val longitude = intent.getDoubleExtra("longitude",0.0)
_binding.latitudeActivityMain.text = "${latitude}"
_binding.longitudeActivityMain.text = "${longitude}"
}
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private val permissions = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.FOREGROUND_SERVICE
)
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(_binding.root)
val filter = IntentFilter("location_update")
registerReceiver(locationReceiver,filter, null, null)
buttonClicks()
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun buttonClicks() {
_binding.startActivityMain.setOnClickListener {
if (checkPermissions() && isLocationEnabled(this@MainActivity)){
startLocationService()
}
else{
requestPermission()
}
}
_binding.stopActivityMain.setOnClickListener {
stopLocationService()
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun requestPermission() {
ActivityCompat.requestPermissions(this@MainActivity,permissions, REQUEST_CODE_LOCATION_PREMISSION)
}
private fun isLocationEnabled(context: Context?): Boolean {
val locManager = context?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CODE_LOCATION_PREMISSION) {
var allPermissionsGranted = true
for (result in grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allPermissionsGranted = false
break
}
}
if (allPermissionsGranted) {
startLocationService()
}
else{
Snackbar.make(_binding.root,"Permissions Denied",Snackbar.LENGTH_SHORT)
.show()
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun checkPermissions() : Boolean{
for(permission in permissions){
if (ContextCompat.checkSelfPermission(
this@MainActivity,
permission
)!=PackageManager.PERMISSION_GRANTED
){
return false
}
}
return true
}
private fun isLocationServiceRunning() : Boolean{
val activityManager : ActivityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.getRunningServices(Integer.MAX_VALUE).forEach { service ->
if(LocationService::class.java.name.equals(service.service.className)){
if(service.foreground) return true
}
}
return false
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun startLocationService(){
if (!isLocationServiceRunning() && checkPermissions()) {
val intent = Intent(this, LocationService::class.java)
intent.action = ACTION_START_LOCATION_SERVICE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
Snackbar.make(_binding.root,"Location Service Started",Snackbar.LENGTH_SHORT)
.show()
}
}
private fun stopLocationService(){
if(isLocationServiceRunning()){
val intent = Intent(this@MainActivity,LocationService::class.java)
intent.action = ACTION_STOP_LOCATION_SERVICE
startService(intent)
Snackbar.make(_binding.root,"Location Service Stopped",Snackbar.LENGTH_SHORT)
.show()
}
}
} | 0 | Kotlin | 0 | 1 | 1e0ea540233bd17efd4ee9c21900b4da2a683391 | 5,864 | Background-Location-Tracker | MIT License |
sdk/src/main/java/live/talkshop/sdk/core/show/ShowProvider.kt | TalkShopLive | 756,521,933 | false | {"Kotlin": 134235} | package live.talkshop.sdk.core.show
import live.talkshop.sdk.core.show.models.ProductModel
import live.talkshop.sdk.core.show.models.ShowModel
import live.talkshop.sdk.core.show.models.ShowStatusModel
import live.talkshop.sdk.resources.APIClientError
import live.talkshop.sdk.resources.Constants
import live.talkshop.sdk.utils.Collector
import live.talkshop.sdk.utils.networking.APICalls.getCurrentEvent
import live.talkshop.sdk.utils.networking.APICalls.getShowDetails
import live.talkshop.sdk.utils.networking.APICalls.getShowProducts
import live.talkshop.sdk.utils.networking.APICalls.incrementView
/**
* This class is responsible for fetching show details and current event status from the network.
*/
internal class ShowProvider {
private val incrementViewCalledMap: MutableMap<String, Boolean> = mutableMapOf()
/**
* Fetches show details for the specified product key, handling the network request and authentication check.
*
* @param showKey The product key for which show details are to be fetched.
* @param callback An optional callback that is invoked upon completion of the request.
* It provides an error message if something goes wrong, or the ShowModel if successful.
*/
suspend fun fetchShow(
showKey: String,
callback: ((APIClientError?, ShowModel?) -> Unit)? = null
) {
getShowDetails(showKey).onError {
callback?.invoke(it, null)
}.onResult {
callback?.invoke(null, it)
Collector.collect(
action = Constants.COLLECTOR_ACTION_SELECT_SHOW_METADATA,
category = Constants.COLLECTOR_CAT_PROCESS,
eventID = it.eventId,
showKey = showKey,
showStatus = it.status,
)
}
}
/**
* Fetches current event details for the specified product key, handling the network request and authentication check.
*
* @param showKey The product key for which current event status is to be fetched.
* @param callback An optional callback that is invoked upon completion of the request.
* It provides an error message if something goes wrong, or the ShowStatusModel if successful.
*/
suspend fun fetchCurrentEvent(
showKey: String,
callback: ((APIClientError?, ShowStatusModel?) -> Unit)? = null
) {
getCurrentEvent(showKey).onError {
callback?.invoke(it, null)
}.onResult {
if (it.streamInCloud == true && it.status == Constants.STATUS_LIVE) {
if (!incrementViewCalledMap.containsKey(showKey) || !incrementViewCalledMap[showKey]!!) {
incrementView(it.eventId!!)
incrementViewCalledMap[showKey] = true
Collector.collect(
action = Constants.COLLECTOR_ACTION_VIEW_COUNT,
category = Constants.COLLECTOR_CAT_PROCESS,
eventID = it.eventId,
showKey = showKey,
showStatus = it.status,
)
}
}
callback?.invoke(null, it)
}
}
/**
* Fetches products for a given show key.
*
* @param showKey The key of the show to fetch products for.
* @param callback The callback to return the result: an error or a list of products.
*/
suspend fun fetchProducts(
showKey: String,
callback: ((APIClientError?, List<ProductModel>?) -> Unit)
) {
getShowProducts(showKey).onError {
callback.invoke(it, null)
}.onResult {
callback.invoke(null, it)
Collector.collect(
action = Constants.COLLECTOR_ACTION_SELECT_SHOW_PRODUCTS,
category = Constants.COLLECTOR_CAT_PROCESS,
showKey = showKey
)
}
}
} | 0 | Kotlin | 0 | 0 | 8ae04bb57e48c5fa6f308efb0fbb92c3d08824fd | 3,917 | android-sdk | Apache License 2.0 |
src/main/kotlin/ru/krindra/vknorthtypes/ads/AdsAccesses.kt | kravandir | 745,597,090 | false | {"Kotlin": 633233} | package ru.krindra.vknorthtypes.ads
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AdsAccesses (
@SerialName("role") val role: AdsAccessRole? = null,
@SerialName("client_id") val clientId: String? = null,
)
| 0 | Kotlin | 0 | 0 | 508d2d1d59c4606a99af60b924c6509cfec6ef6c | 277 | VkNorthTypes | MIT License |
src/main/kotlin/io/rafaeljpc/spring/data/rest/test/config/DemoApplicationConfig.kt | rafaeljpc | 246,989,872 | false | null | package io.rafaeljpc.spring.data.rest.test.config
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
@Configuration
class DemoApplicationConfig {
@Bean
fun objectMapperBuilder(): Jackson2ObjectMapperBuilder? {
val builder = Jackson2ObjectMapperBuilder()
builder.modules(Jackson2HalModule())
.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.serializationInclusion(JsonInclude.Include.NON_NULL)
return builder
}
} | 0 | Kotlin | 0 | 1 | 474300c01b1d87a86ba42dcdb16411c26c03e31b | 812 | spring-data-rest-test | Apache License 2.0 |
gradle/plugin/project/base/src/main/kotlin/ru/pixnews/gradle/base/UnitTestEngine.kt | illarionov | 305,333,284 | false | null | /*
* Copyright 2023 <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 ru.pixnews.gradle.base
public enum class UnitTestEngine {
DISABLE,
JUNIT4,
JUNIT5,
KOTEST,
;
}
| 0 | Kotlin | 0 | 2 | 8912bf1116dd9fe94d110162ff9a302e93af1509 | 714 | Pixnews | Apache License 2.0 |
app/src/main/java/com/kohne/memoryleaks/viewbindingdelegate/DetailsViewBindingDelegateSolutionFragment.kt | maxkohne | 319,732,680 | false | {"Kotlin": 21446} | package com.kohne.memoryleaks.viewbindingdelegate
import androidx.fragment.app.Fragment
import com.kohne.memoryleaks.R
import com.kohne.memoryleaks.databinding.DetailsViewBindingDelegateSolutionFragmentBinding
import com.kohne.memoryleaks.viewBinding
internal class DetailsViewBindingDelegateSolutionFragment : Fragment(R.layout.details_view_binding_delegate_solution_fragment) {
companion object {
fun newInstance() = DetailsViewBindingDelegateSolutionFragment()
}
private val binding by viewBinding(DetailsViewBindingDelegateSolutionFragmentBinding::bind)
} | 0 | Kotlin | 1 | 9 | ec1435760776480aa2c4ab24d1cf32f611bd99f4 | 582 | Android-Memory-Leaks | Apache License 2.0 |
app/src/main/java/com/huwei/sweetmusicplayer/data/Progress.kt | verehu | 37,705,827 | false | null | package com.huwei.sweetmusicplayer.data
/**
*
* @author Ezio
* @date 2018/02/04
*/
data class Progress(var currentPosition: Long, var duration : Long) | 1 | null | 96 | 353 | 81d39fad2f143b21d2828d1a91ac5e76f91982d3 | 155 | SweetMusicPlayer | Apache License 2.0 |
adaptive-kotlin-plugin/testData/box/adat/immutable/openVal.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 2104845, "Java": 23090, "HTML": 7707, "JavaScript": 3880, "Shell": 687} | package hu.simplexion.adaptive.adat
@Adat
class Padding(
override val top: DPixel?,
override val right: DPixel?,
override val bottom: DPixel?,
override val left: DPixel?
) : Surrounding
@Adat
class DPixel(
override val value: Double
) : Track {
override val isFix
get() = true
}
interface Track {
val value: Double
val isFix: Boolean
get() = false
}
interface Surrounding {
val top: DPixel?
val right: DPixel?
val bottom: DPixel?
val left: DPixel?
}
fun box(): String {
if (Padding.adatMetadata.isMutable) return "Fail: Padding.isMutable"
if (Padding.adatMetadata.properties.first().isMutable) return "Fail: top is mutable"
if (DPixel.adatMetadata.isMutable) return "Fail: DPixel.isMutable"
if (DPixel.adatMetadata.properties.first().isMutable) return "Fail: value is mutable"
return "OK"
} | 22 | Kotlin | 0 | 3 | a423e127a406395002bbc663bb2fea6fcad749f1 | 886 | adaptive | Apache License 2.0 |
core/data/src/main/java/cardosofgui/android/pokedexcompose/core/data/di/RepositoryModules.kt | CardosofGui | 609,740,815 | false | null | package cardosofgui.android.pokedexcompose.core.data.di
import cardosofgui.android.pokedexcompose.core.data.repository.PokemonRepositoryImpl
import cardosofgui.android.pokedexcompose.core.data.repository.UserRepositoryImpl
import cardosofgui.android.pokedexcompose.core.repository.PokemonRepository
import cardosofgui.android.pokedexcompose.core.repository.UserRepository
import org.koin.dsl.module
val repositoryModules = module {
single {
PokemonRepositoryImpl(
pokemonApiClient = get(),
pokemonDao = get(),
statsDao = get(),
favoriteDao = get()
) as PokemonRepository
}
single {
UserRepositoryImpl(
context = get()
) as UserRepository
}
} | 0 | Kotlin | 0 | 1 | 67c081c7e0ba18bbb06dd736ffb41699defa3836 | 752 | pokedex-app-compose | MIT License |
app/src/main/java/com/example/nixy/data/NoteDao.kt | EvgenSuit | 732,080,603 | false | {"Kotlin": 29516} | package com.example.nixy.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface NoteDao {
@Query("SELECT * FROM Note")
fun getAllNotes(): Flow<List<Note>>
@Query("SELECT * FROM Note WHERE id = :id")
fun getNote(id: Int): Flow<Note>
@Insert (onConflict = OnConflictStrategy.REPLACE)
suspend fun insertNote(note: Note)
@Delete
suspend fun deleteNote(note: Note)
@Query("SELECT MAX(id) FROM Note")
suspend fun getMaxIndex(): Int
} | 0 | Kotlin | 0 | 0 | 71808bc2576ea5f04c40f3c636a40f8e94e2d88b | 650 | Nixy | MIT License |
src/main/kotlin/com/dmzcoding/walnuts/config/configs.kt | dmzstar | 252,988,095 | false | {"Gradle Kotlin DSL": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "Kotlin": 9, "Java": 1, "Java Properties": 1, "XML": 1, "HTML": 7, "CSS": 1} | package com.dmzcoding.walnuts.config
import com.dmzcoding.walnuts.defaults.DefaultComponents
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import javax.annotation.PostConstruct
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig : WebSecurityConfigurerAdapter(){
val log = LoggerFactory.getLogger(SecurityConfig::class.java)
@PostConstruct
fun onCreate(){
println("=================================== configure web: WebSecurity")
val hints = """
Just to recap, the major building blocks of Spring Security that we’ve seen so far are:
SecurityContextHolder, to provide access to the SecurityContext.
SecurityContext, to hold the Authentication and possibly request-specific security information.
Authentication, to represent the principal in a Spring Security-specific manner.
GrantedAuthority, to reflect the application-wide permissions granted to a principal.
UserDetails, to provide the necessary information to build an Authentication object from your application’s DAOs or other source of security data.
UserDetailsService, to create a UserDetails when passed in a String-based username (or certificate ID or the like).
"""
println(hints)
}
override fun configure(web: WebSecurity) {
web.ignoring().antMatchers("/assets/**","/webjars/**")
super.configure(web)
}
override fun configure(http: HttpSecurity) {
//http.authorizeRequests().antMatchers("/*").authenticated()
http.authorizeRequests().antMatchers("/*").permitAll()
http.formLogin().loginPage("/login").permitAll()
http.logout().logoutUrl("/logout")
.logoutSuccessUrl("/").permitAll()
log.info("SecurityConfigurerInited")
super.configure(http)
}
}
| 1 | null | 1 | 1 | c65e893134b475d68d858823d5dbd19e6aa8380b | 2,480 | walnuts | MIT License |
AndroidDemo/demo/src/main/kotlin/kodein/demo/DemoApplication.kt | jkschneider | 34,063,924 | true | {"Kotlin": 18248} | package kodein.demo
import android.app.Application
import com.github.salomonbrys.kodein.*
import kodein.demo.coffee.CoffeeMaker
import kodein.demo.coffee.CoffeeRation
import kodein.demo.coffee.bindElectricHeater
import kodein.demo.coffee.bindThermosiphon
public class DemoApplication : Application(), KodeinHolder {
override val kodein: Kodein by lazyKodein {
bindThermosiphon()
bindElectricHeater()
bind<CoffeeRation>() with { CoffeeRation(it.instance()) }
bind<Logger>() with instance(Logger())
bind<CoffeeMaker>() with singleton { CoffeeMaker(it.instance(), it.instance(), it.instance(), it.provider()) }
}
}
| 0 | Kotlin | 0 | 0 | 673b4cc8130cd7db1e3e8c88fddeb5451cd02635 | 668 | Kodein | MIT License |
shared/src/commonTest/kotlin/com/github/icarohs7/unoxcore/extensions/CollectionsExtensionsKtTest.kt | icarohs7 | 148,195,302 | false | null | package com.github.icarohs7.unoxcore.extensions
import com.github.icarohs7.unoxcore.utils.shouldEqual
import com.github.icarohs7.unoxcore.utils.typeIs
import kotlin.test.Test
class CollectionsExtensionsKtTest {
@Test
fun should_map_a_map_to_another_type_of_map() {
//Given
val m1 = mapOf("name" to "Icaro", "age" to "21")
val m2 = mapOf(Pair(10, 20), Pair(30, 40))
//When
val r1 = m1.associate { (k, v) -> Pair(k.reversed(), v.reversed()) }
val r2 = m2.associate { (k, v) -> Pair(k * 2, v * 3) }
//Then
r1 typeIs Map::class
r1 shouldEqual mapOf(Pair("eman", "oracI"), Pair("ega", "12"))
r2 typeIs Map::class
r2 shouldEqual mapOf(Pair(20, 60), Pair(60, 120))
}
} | 2 | Kotlin | 0 | 0 | a3c1e6808eb3ccaa2bfb73e182833cbf32b4cf00 | 764 | unox-core | MIT License |
features/news/src/commonMain/kotlin/com/mathroda/news/state/NewsState.kt | MathRoda | 507,060,394 | false | {"Kotlin": 446115, "Swift": 4323, "Ruby": 2379, "Java": 624} | package com.mathroda.news.state
import com.mathroda.domain.NewsDetail
data class NewsState(
val isLoading: Boolean = false,
val news: List<NewsDetail> = emptyList(),
val error: String = ""
)
| 0 | Kotlin | 41 | 297 | cf303ba50bad35a816253bee5b27beee5ea364b8 | 205 | DashCoin | Apache License 2.0 |
app/src/main/java/com/example/alarmit/ui/method/ShakeMethodFragment.kt | ACM-VIT | 545,933,582 | false | {"Kotlin": 6760} | package com.example.alarmit.ui.method
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.alarmit.R
class ShakeMethodFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_shake_method, container, false)
}
} | 3 | Kotlin | 6 | 7 | 588efeed4ba662817ba29fecd4949b752d9fb49c | 543 | AlarmIT | MIT License |
src/test/java/com/example/springboot/http/甘肃/一张图接口/岸线功能分区.kt | DoubleDD | 747,076,483 | false | {"Kotlin": 302923, "Java": 116617} | package com.example.springboot.http.甘肃.一张图接口
import com.example.springboot.http.common.BaseTest
import com.example.springboot.http.common.ServerApi
import org.junit.jupiter.api.Test
class 岸线功能分区 : BaseTest() {
override fun getServer(): ServerApi {
return ServerApi.LOCAL_MA
}
@Test
fun 岸线功能分区详情() {
val projectType = 30
val areaCode = "1240"
get("/api/water/waterLine/queryByCode?projectType=$projectType&areaCode=$areaCode")
}
} | 0 | Kotlin | 0 | 0 | 0a7cb7c5a9241c7931dc79cef3052c5cf4cd62dd | 484 | api-unit-test | MIT License |
thing/src/main/kotlin/so/kciter/thing/normalizer/Extensions.kt | kciter | 622,251,428 | false | null | package so.kciter.thing.normalizer
import java.util.*
fun NormalizationRuleBuilder<String>.trim() =
addNormalizer {
it.trim()
}
fun NormalizationRuleBuilder<String>.trimEnd() =
addNormalizer {
it.trimEnd()
}
fun NormalizationRuleBuilder<String>.trimStart() =
addNormalizer {
it.trimStart()
}
fun NormalizationRuleBuilder<String>.uppercase() =
addNormalizer {
it.uppercase()
}
fun NormalizationRuleBuilder<String>.lowercase() =
addNormalizer {
it.lowercase()
}
fun NormalizationRuleBuilder<String>.replace(oldValue: String, newValue: String) =
addNormalizer {
it.replace(oldValue, newValue)
}
fun NormalizationRuleBuilder<String>.replace(oldValue: String, newValue: String, ignoreCase: Boolean) =
addNormalizer {
it.replace(oldValue, newValue, ignoreCase)
}
fun NormalizationRuleBuilder<String>.replaceFirst(oldValue: String, newValue: String) =
addNormalizer {
it.replaceFirst(oldValue, newValue)
}
fun NormalizationRuleBuilder<String>.replaceFirst(oldValue: String, newValue: String, ignoreCase: Boolean) =
addNormalizer {
it.replaceFirst(oldValue, newValue, ignoreCase)
}
fun NormalizationRuleBuilder<String>.replaceRange(startIndex: Int, endIndex: Int, newValue: String) =
addNormalizer {
it.replaceRange(startIndex, endIndex, newValue)
}
fun NormalizationRuleBuilder<String>.removeRange(startIndex: Int, endIndex: Int) =
addNormalizer {
it.removeRange(startIndex, endIndex)
}
fun NormalizationRuleBuilder<String>.removePrefix(prefix: String) =
addNormalizer {
it.removePrefix(prefix)
}
fun NormalizationRuleBuilder<String>.removeSuffix(suffix: String) =
addNormalizer {
it.removeSuffix(suffix)
}
fun NormalizationRuleBuilder<String>.removeSurrounding(prefix: String, suffix: String) =
addNormalizer {
it.removeSurrounding(prefix, suffix)
}
fun NormalizationRuleBuilder<Map<*, *>>.filterKeys(predicate: (key: Any?) -> Boolean) =
addNormalizer {
it.filterKeys(predicate)
}
fun NormalizationRuleBuilder<Map<*, *>>.filterValues(predicate: (value: Any?) -> Boolean) =
addNormalizer {
it.filterValues(predicate)
}
fun <T> NormalizationRuleBuilder<List<T>>.filter(predicate: (T) -> Boolean) =
addNormalizer {
it.filter(predicate)
}
fun <T> NormalizationRuleBuilder<List<T>>.filterNotNull() =
addNormalizer {
it.filterNotNull()
}
fun <T> NormalizationRuleBuilder<List<T>>.filterNot(predicate: (T) -> Boolean) =
addNormalizer {
it.filterNot(predicate)
}
fun <T> NormalizationRuleBuilder<List<T>>.filterIndexed(predicate: (index: Int, T) -> Boolean) =
addNormalizer {
it.filterIndexed(predicate)
}
fun <T> NormalizationRuleBuilder<List<T>>.map(transform: (T) -> T) =
addNormalizer {
it.map(transform)
}
fun <T> NormalizationRuleBuilder<List<T>>.mapIndexed(transform: (index: Int, T) -> T) =
addNormalizer {
it.mapIndexed(transform)
}
fun <T> NormalizationRuleBuilder<List<T>>.mapNotNull(transform: (T) -> T?) =
addNormalizer {
it.mapNotNull(transform)
}
fun <T> NormalizationRuleBuilder<List<T>>.drop(n: Int) =
addNormalizer {
it.drop(n)
}
fun <T> NormalizationRuleBuilder<List<T>>.dropWhile(predicate: (T) -> Boolean) =
addNormalizer {
it.dropWhile(predicate)
}
fun <T> NormalizationRuleBuilder<List<T>>.take(n: Int) =
addNormalizer {
it.take(n)
}
fun <T> NormalizationRuleBuilder<List<T>>.takeWhile(predicate: (T) -> Boolean) =
addNormalizer {
it.takeWhile(predicate)
}
fun <T, R: Comparable<R>> NormalizationRuleBuilder<List<T>>.sortedBy(selector: (T) -> R?) =
addNormalizer {
it.sortedBy(selector)
}
fun <T, R: Comparable<R>> NormalizationRuleBuilder<List<T>>.sortedByDescending(selector: (T) -> R?) =
addNormalizer {
it.sortedByDescending(selector)
}
fun <T> NormalizationRuleBuilder<List<T>>.sortedWith(comparator: Comparator<in T>) =
addNormalizer {
it.sortedWith(comparator)
}
fun <T> NormalizationRuleBuilder<List<T>>.reversed() =
addNormalizer {
it.reversed()
}
fun <T> NormalizationRuleBuilder<List<T>>.shuffled() =
addNormalizer {
it.shuffled()
}
fun <T> NormalizationRuleBuilder<List<T>>.shuffled(random: Random) =
addNormalizer {
it.shuffled(random)
}
fun <T> NormalizationRuleBuilder<List<T>>.distinct() =
addNormalizer {
it.distinct()
}
fun <T> NormalizationRuleBuilder<List<T>>.distinctBy(selector: (T) -> Any?) =
addNormalizer {
it.distinctBy(selector)
}
| 0 | Kotlin | 4 | 60 | eb4d1bfe5038a619fff8740bbe574af6adce54f4 | 4,483 | thing | MIT License |
bellatrix.web/src/main/java/solutions/bellatrix/web/components/Progress.kt | AutomateThePlanet | 334,964,015 | false | null | /*
* Copyright 2021 Automate The Planet Ltd.
* Author: <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package solutions.bellatrix.web.components
import solutions.bellatrix.web.components.contracts.ComponentDisabled
import solutions.bellatrix.web.components.contracts.ComponentSelected
import solutions.bellatrix.web.components.contracts.ComponentText
import solutions.bellatrix.web.components.contracts.ComponentValue
open class Option : WebComponent(), ComponentText, ComponentValue, ComponentDisabled, ComponentSelected {
override val componentClass: Class<*>
get() = javaClass
override val text: String
get() = defaultGetText()
override val value: String
get() = defaultGetValue()
override val isDisabled: Boolean
get() = defaultGetDisabledAttribute()
override val isSelected: Boolean
get() = findElement().isSelected
} | 1 | Kotlin | 1 | 1 | 5da5e705b47e12c66937d130b3031ac8703b8279 | 1,396 | BELLATRIX-Kotlin | Apache License 2.0 |
app/src/main/java/tellh/com/recyclertreeview/bean/File.kt | Qkyyy | 420,427,094 | true | {"Kotlin": 24221} | package tellh.com.recyclertreeview.bean;
import tellh.com.recyclertreeview.R;
import tellh.com.recyclertreeview_lib.LayoutItemType;
/**
* Created by tlh on 2016/10/1 :)
*/
class File(var fileName: String) : LayoutItemType {
override fun getLayoutId(): Int {
return R.layout.item_file
}
}
| 0 | Kotlin | 0 | 0 | 1ed44017553019428a62305f7dbcecd0ebcc556b | 310 | RecyclerTreeView | Apache License 2.0 |
qatoolkit-inspector-android/src/main/java/com/github/iojjj/bootstrap/pub/qatoolkit/inspector/android/widget/TextViewInspectorConfiguration.kt | Iojjj | 429,845,456 | false | {"Kotlin": 694141} | @file:Suppress("FunctionName")
package com.github.iojjj.bootstrap.pub.qatoolkit.inspector.android.widget
import android.graphics.text.LineBreaker
import android.os.Build
import android.widget.TextView
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.CATEGORY_ORDER_STEP_LARGE
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.CATEGORY_ORDER_STEP_SMALL
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.CATEGORY_ORDER_VIEW_BACKGROUND
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.CategoryInspector
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.INSPECTOR_ORDER_STEP
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.InspectorConfiguration
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.Order
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.asGravityString
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.attribute.ColorAttribute.Companion.color
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.attribute.CommonAttribute.Companion.apiRestricted
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.attribute.DimensionAttribute.Companion.dimension
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.attribute.DimensionAttribute.Companion.textDimension
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.CategoryInspectorBuilder
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.Inspect
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.InspectorBuilder
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.ViewLayoutCategory
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.ApiRestricted
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.Color
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.Dimension
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.Drawable
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.FlatMap
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.Float
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.Int
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.String
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.TextDimension
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.attribute.TintedDrawable
import com.github.iojjj.bootstrap.pub.qatoolkit.inspector.dsl.category.Category
/**
* Implementation of [InspectorConfiguration] for [TextView] type.
*/
// Executing after View's inspector
@Order(1 * INSPECTOR_ORDER_STEP)
class TextViewInspectorConfiguration : InspectorConfiguration<TextView> {
override fun configure(): Iterable<CategoryInspector<TextView>> = Inspect {
ViewLayoutCategory {
Dimension(ATTRIBUTE_MIN_WIDTH) { textView ->
textView.minWidth.takeUnless { it < 0 }
}
Dimension(ATTRIBUTE_MIN_HEIGHT) { textView ->
textView.minHeight.takeUnless { it < 0 }
}
Dimension(ATTRIBUTE_MAX_WIDTH) { textView ->
textView.maxWidth.takeUnless { it < 0 || it == Int.MAX_VALUE }
}
Dimension(ATTRIBUTE_MAX_HEIGHT) { textView ->
textView.maxHeight.takeUnless { it < 0 || it == Int.MAX_VALUE }
}
}
TextViewTextCategory {
String(ATTRIBUTE_TEXT) { textView ->
textView.text.takeUnless { it.isNullOrEmpty() }
}
TextDimension(ATTRIBUTE_TEXT_SIZE) { it.textSize }
Float(ATTRIBUTE_TEXT_SCALE_X) { it.textScaleX }
FlatMap(ATTRIBUTE_AUTO_SIZE) { textView ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (textView.autoSizeTextType == TextView.AUTO_SIZE_TEXT_TYPE_NONE) {
emptyList()
} else {
listOfNotNull(
textView.autoSizeMinTextSize.takeUnless { it == -1 }
?.let { textDimension(ATTRIBUTE_AUTO_SIZE_MIN_TEXT_SIZE, it) },
textView.autoSizeMaxTextSize.takeUnless { it == -1 }
?.let { textDimension(ATTRIBUTE_AUTO_SIZE_MAX_TEXT_SIZE, it) },
textView.autoSizeStepGranularity.takeUnless { it == -1 }
?.let { textDimension(ATTRIBUTE_AUTO_SIZE_STEP_GRANULARITY, it) },
)
}
} else {
listOf(
apiRestricted(
ATTRIBUTE_AUTO_SIZE_MIN_TEXT_SIZE,
Build.VERSION_CODES.O
),
apiRestricted(
ATTRIBUTE_AUTO_SIZE_MAX_TEXT_SIZE,
Build.VERSION_CODES.O
),
apiRestricted(
ATTRIBUTE_AUTO_SIZE_STEP_GRANULARITY,
Build.VERSION_CODES.O
),
)
}
}
Color(ATTRIBUTE_TEXT_COLOR) {
it.textColors?.let { colors ->
colors.getColorForState(it.drawableState, colors.defaultColor)
}
}
}
TextViewShadowCategory {
FlatMap(ATTRIBUTE_SHADOW) {
if (it.shadowRadius <= 0.0f) {
emptyList()
} else {
listOf(
dimension(ATTRIBUTE_SHADOW_RADIUS, it.shadowRadius),
dimension(ATTRIBUTE_SHADOW_DX, it.shadowDx),
dimension(ATTRIBUTE_SHADOW_DY, it.shadowDy),
color(ATTRIBUTE_SHADOW_COLOR, it.shadowColor),
)
}
}
}
TextViewHintCategory {
String(ATTRIBUTE_HINT) { it.hint }
Color(ATTRIBUTE_HINT_COLOR) { it.currentHintTextColor }
}
TextViewParagraphCategory {
Dimension(ATTRIBUTE_LINE_SPACING_EXTRA) { it.lineSpacingExtra }
Float(ATTRIBUTE_LINE_SPACING_MULTIPLIER) { it.lineSpacingMultiplier }
Float(ATTRIBUTE_LETTER_SPACING) { it.letterSpacing }
Int(ATTRIBUTE_MIN_EMS) { textView ->
textView.minEms.takeUnless { it < 0 }
}
Int(ATTRIBUTE_MAX_EMS) { textView ->
textView.maxEms.takeUnless { it < 0 || it == Int.MAX_VALUE }
}
Int(ATTRIBUTE_MIN_LINES) { textView ->
textView.minLines.takeUnless { it < 0 }
}
Int(ATTRIBUTE_MAX_LINES) { textView ->
textView.maxLines.takeUnless { it < 0 || it == Int.MAX_VALUE }
}
Int(ATTRIBUTE_LINE_COUNT) { it.lineCount }
Dimension(ATTRIBUTE_LINE_HEIGHT) { it.lineHeight }
}
TextViewCompoundDrawables {
Dimension(ATTRIBUTE_COMPOUND_DRAWABLE_PADDING) { it.compoundDrawablePadding }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TintedDrawable(ATTRIBUTE_COMPOUND_DRAWABLE_START) { it.compoundDrawablesRelative[0] to it.compoundDrawableTintList }
TintedDrawable(ATTRIBUTE_COMPOUND_DRAWABLE_TOP) { it.compoundDrawablesRelative[1] to it.compoundDrawableTintList }
TintedDrawable(ATTRIBUTE_COMPOUND_DRAWABLE_END) { it.compoundDrawablesRelative[2] to it.compoundDrawableTintList }
TintedDrawable(ATTRIBUTE_COMPOUND_DRAWABLE_BOTTOM) { it.compoundDrawablesRelative[3] to it.compoundDrawableTintList }
} else {
Drawable(ATTRIBUTE_COMPOUND_DRAWABLE_START) { it.compoundDrawablesRelative[0] }
Drawable(ATTRIBUTE_COMPOUND_DRAWABLE_TOP) { it.compoundDrawablesRelative[1] }
Drawable(ATTRIBUTE_COMPOUND_DRAWABLE_END) { it.compoundDrawablesRelative[2] }
Drawable(ATTRIBUTE_COMPOUND_DRAWABLE_BOTTOM) { it.compoundDrawablesRelative[3] }
ApiRestricted("${ATTRIBUTE_COMPOUND_DRAWABLE_START}: Tint", Build.VERSION_CODES.M) {
it.compoundDrawablesRelative[0]
}
ApiRestricted("${ATTRIBUTE_COMPOUND_DRAWABLE_TOP}: Tint", Build.VERSION_CODES.M) {
it.compoundDrawablesRelative[1]
}
ApiRestricted("${ATTRIBUTE_COMPOUND_DRAWABLE_END}: Tint", Build.VERSION_CODES.M) {
it.compoundDrawablesRelative[2]
}
ApiRestricted("${ATTRIBUTE_COMPOUND_DRAWABLE_BOTTOM}: Tint", Build.VERSION_CODES.M) {
it.compoundDrawablesRelative[3]
}
}
}
TextViewOtherCategory {
String(ATTRIBUTE_GRAVITY) { it.gravity.asGravityString() }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String(ATTRIBUTE_JUSTIFICATION_MODE) {
when (val mode = it.justificationMode) {
LineBreaker.JUSTIFICATION_MODE_INTER_WORD -> "Inter Word"
LineBreaker.JUSTIFICATION_MODE_NONE -> "None"
else -> "Unsupported mode: $mode"
}
}
}
String(ATTRIBUTE_ELLIPSIZE) { it.ellipsize?.name }
}
}
@Suppress("MemberVisibilityCanBePrivate")
companion object {
const val CATEGORY_TEXT_VIEW_TEXT: String = "Text View: Text"
const val CATEGORY_TEXT_VIEW_TEXT_SHADOW: String = "Text View: Text Shadow"
const val CATEGORY_TEXT_VIEW_HINT: String = "Text View: Hint"
const val CATEGORY_TEXT_VIEW_PARAGRAPH: String = "Text View: Paragraph"
const val CATEGORY_TEXT_VIEW_COMPOUND_DRAWABLES: String = "Text View: Compound Drawables"
const val CATEGORY_TEXT_VIEW_OTHER: String = "Text View: Other"
const val CATEGORY_ORDER_TEXT_VIEW_FIRST: Int = CATEGORY_ORDER_VIEW_BACKGROUND - CATEGORY_ORDER_STEP_LARGE
const val CATEGORY_ORDER_TEXT_VIEW_TEXT: Int = CATEGORY_ORDER_TEXT_VIEW_FIRST
const val CATEGORY_ORDER_TEXT_VIEW_TEXT_SHADOW: Int = CATEGORY_ORDER_TEXT_VIEW_TEXT + CATEGORY_ORDER_STEP_SMALL
const val CATEGORY_ORDER_TEXT_VIEW_HINT: Int = CATEGORY_ORDER_TEXT_VIEW_TEXT_SHADOW + CATEGORY_ORDER_STEP_SMALL
const val CATEGORY_ORDER_TEXT_VIEW_PARAGRAPH: Int = CATEGORY_ORDER_TEXT_VIEW_HINT + CATEGORY_ORDER_STEP_SMALL
const val CATEGORY_ORDER_TEXT_VIEW_COMPOUND_DRAWABLES: Int = CATEGORY_ORDER_TEXT_VIEW_PARAGRAPH + CATEGORY_ORDER_STEP_SMALL
const val CATEGORY_ORDER_TEXT_VIEW_OTHER: Int = CATEGORY_ORDER_TEXT_VIEW_COMPOUND_DRAWABLES + CATEGORY_ORDER_STEP_SMALL
const val CATEGORY_ORDER_TEXT_VIEW_LAST: Int = CATEGORY_ORDER_TEXT_VIEW_OTHER
const val ATTRIBUTE_TEXT: String = "Text"
const val ATTRIBUTE_TEXT_SIZE: String = "Text size"
const val ATTRIBUTE_TEXT_SCALE_X: String = "Text scale X"
const val ATTRIBUTE_TEXT_COLOR: String = "Text color"
const val ATTRIBUTE_HINT: String = "Hint"
const val ATTRIBUTE_HINT_COLOR: String = "Hint color"
const val ATTRIBUTE_MAX_WIDTH: String = "Max width"
const val ATTRIBUTE_MAX_HEIGHT: String = "Max height"
const val ATTRIBUTE_MIN_WIDTH: String = "Min width"
const val ATTRIBUTE_MIN_HEIGHT: String = "Min height"
const val ATTRIBUTE_MAX_EMS: String = "Max width in ems"
const val ATTRIBUTE_MAX_LINES: String = "Max number of lines"
const val ATTRIBUTE_MIN_EMS: String = "Min width in ems"
const val ATTRIBUTE_MIN_LINES: String = "Min number of lines"
const val ATTRIBUTE_LINE_COUNT: String = "Number of lines"
const val ATTRIBUTE_LINE_HEIGHT: String = "Line height"
const val ATTRIBUTE_LINE_SPACING_MULTIPLIER: String = "Line spacing multiplier"
const val ATTRIBUTE_LINE_SPACING_EXTRA: String = "Line spacing extra"
const val ATTRIBUTE_GRAVITY: String = "Text gravity"
const val ATTRIBUTE_JUSTIFICATION_MODE: String = "Justification mode"
const val ATTRIBUTE_ELLIPSIZE: String = "Ellipsize type"
const val ATTRIBUTE_LETTER_SPACING: String = "Letter-spacing"
const val ATTRIBUTE_AUTO_SIZE: String = "Auto size"
const val ATTRIBUTE_AUTO_SIZE_STEP_GRANULARITY: String = "Auto size: step granularity"
const val ATTRIBUTE_AUTO_SIZE_MIN_TEXT_SIZE: String = "Auto size: min size"
const val ATTRIBUTE_AUTO_SIZE_MAX_TEXT_SIZE: String = "Auto size: max size"
const val ATTRIBUTE_COMPOUND_DRAWABLE_START: String = "Start drawable"
const val ATTRIBUTE_COMPOUND_DRAWABLE_TOP: String = "Top drawable"
const val ATTRIBUTE_COMPOUND_DRAWABLE_END: String = "End drawable"
const val ATTRIBUTE_COMPOUND_DRAWABLE_BOTTOM: String = "Bottom drawable"
const val ATTRIBUTE_COMPOUND_DRAWABLE_PADDING: String = "Padding between text and drawables"
const val ATTRIBUTE_SHADOW: String = "Shadow"
const val ATTRIBUTE_SHADOW_RADIUS: String = "Shadow radius"
const val ATTRIBUTE_SHADOW_DX: String = "Shadow dx"
const val ATTRIBUTE_SHADOW_DY: String = "Shadow dy"
const val ATTRIBUTE_SHADOW_COLOR: String = "Shadow color"
fun <T> InspectorBuilder<T>.TextViewTextCategory(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_TEXT, CATEGORY_ORDER_TEXT_VIEW_TEXT, allowNulls, block)
}
fun <T> InspectorBuilder<T>.TextViewShadowCategory(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_TEXT_SHADOW, CATEGORY_ORDER_TEXT_VIEW_TEXT_SHADOW, allowNulls, block)
}
fun <T> InspectorBuilder<T>.TextViewHintCategory(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_HINT, CATEGORY_ORDER_TEXT_VIEW_HINT, allowNulls, block)
}
fun <T> InspectorBuilder<T>.TextViewParagraphCategory(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_PARAGRAPH, CATEGORY_ORDER_TEXT_VIEW_PARAGRAPH, allowNulls, block)
}
fun <T> InspectorBuilder<T>.TextViewCompoundDrawables(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_COMPOUND_DRAWABLES, CATEGORY_ORDER_TEXT_VIEW_COMPOUND_DRAWABLES, allowNulls, block)
}
fun <T> InspectorBuilder<T>.TextViewOtherCategory(
allowNulls: Boolean = this.allowNulls,
block: CategoryInspectorBuilder<T>.() -> Unit
) {
Category(CATEGORY_TEXT_VIEW_OTHER, CATEGORY_ORDER_TEXT_VIEW_OTHER, allowNulls, block)
}
}
} | 0 | Kotlin | 1 | 3 | 8f131d8132b0deb6a638d2a66fdf1d53911cca32 | 15,210 | QA-Toolkit | MIT License |
shared/src/commonMain/kotlin/domain/DateTimeUtils.kt | youranshul | 652,226,399 | false | {"Kotlin": 79020, "Ruby": 1786, "Swift": 1087, "Shell": 228} | package domain
import util.format
fun String.dateFormat(): String {
val dateFormat = "dd-MMM-yy"
return this.format(dateFormat)
} | 0 | Kotlin | 4 | 22 | 4ad1c746f25f34d07f5b3751e105a7c4f9c2d296 | 139 | KmmMovieBuff | Apache License 2.0 |
lib/ext/src/main/java/taiwan/no/one/ext/extension/Now.kt | SmashKs | 587,383,005 | false | {"Kotlin": 52010} | package taiwan.no.one.ext.extension
import kotlinx.datetime.Clock
inline fun now() = Clock.System.now()
| 0 | Kotlin | 0 | 0 | 25bea0a7e69c017a6d5cb68d72778b6c71910aeb | 106 | TurboDisco | Apache License 2.0 |
app/src/main/java/com/zqf/kotlinwanandroid/http/Response.kt | zqf-dev | 484,351,347 | false | {"Kotlin": 130314, "Java": 98386} | package com.zqf.kotlinwanandroid.http
/**
* Author: zqf
* Date: 2021/11/05
* wanAndroid 返回的数据格式
*/
class Response<T> {
val errorCode = 0
val errorMsg: String = ""
val data: T? = null
override fun toString(): String {
return "Response(errorCode=$errorCode, errorMsg='$errorMsg', data=$data)"
}
} | 0 | Kotlin | 1 | 6 | d13eb0db92a608578943369b39221169b0098297 | 329 | KotlinWanAndroid | Apache License 2.0 |
markout-docusaurus/src/main/kotlin/io/koalaql/markout/docusaurus/DocusaurusRoot.kt | mfwgenerics | 584,628,939 | false | null | package io.koalaql.markout.docusaurus
import io.koalaql.markout.MarkoutDsl
@MarkoutDsl
interface DocusaurusRoot {
@MarkoutDsl
fun configure(block: DocusaurusSettings.() -> Unit)
@MarkoutDsl
fun docs(block: Docusaurus.() -> Unit)
} | 0 | Kotlin | 0 | 7 | f633c572d27abf5f783e1324ebfdbab1b83abb8d | 248 | markout | MIT License |
src/main/kotlin/win/hupubao/views/LoadingFragment.kt | ysdxz207 | 157,818,353 | false | null | package win.hupubao.views
import javafx.scene.image.Image
import javafx.scene.paint.Color
import javafx.stage.Stage
import javafx.stage.StageStyle
import tornadofx.*
class LoadingFragment : Fragment() {
private val mainView: MainView by inject()
override val root = vbox {
imageview(image = Image(resources.stream("/image/loading.gif")))
// 背景透明
style {
backgroundColor += Color.TRANSPARENT
}
}
/**
* 背景透明
*/
override fun onDock() {
currentStage?.scene?.fill = null
}
init {
currentStage?.isResizable = false
}
fun show() {
this.openModal(stageStyle = StageStyle.TRANSPARENT)
// 计算位置,使其居中
val mainX = mainView.currentStage?.x ?: 0.0
val mainY = mainView.currentStage?.y ?: 0.0
val mainWidth = mainView.currentStage?.width ?: 0.0
val mainHeight = mainView.currentStage?.height ?: 0.0
val width = this.currentStage?.width ?: 0.0
val height = this.currentStage?.height ?: 0.0
val x = mainX + (mainWidth.div(2)) - (width.div(2))
val y = mainY + (mainHeight.div(2)) - (height.div(2))
currentStage?.x = x
currentStage?.y = y
}
fun hide() {
currentStage?.hide()
}
} | 1 | Kotlin | 0 | 1 | 0cc30abdbecb712022c81b260859d5e42a472a77 | 1,294 | jmedis | MIT License |
app/src/main/java/com/delet_dis/converta/data/model/SettingsActionType.kt | delet-dis | 387,425,722 | false | null | package com.delet_dis.converta.data.model
import com.delet_dis.converta.R
enum class SettingsActionType(val stringId: Int, val imageId: Int) {
COMMUNICATION_LANGUAGE_PICK(
R.string.changeCommunicationLanguageSettingsAction,
R.drawable.ic_people
),
APPLICATION_OPEN_MODE_PICK(
R.string.changeApplicationOpenModeSettingsAction,
R.drawable.ic_pen
)
} | 0 | Kotlin | 0 | 1 | 90cda1b6a705cf694d8d9a9c83a4b7f42edbcb5a | 397 | Converta | MIT License |
klio-files/src/commonMain/kotlin/org/kodein/memory/file/FileSystem.kt | kosi-libs | 181,659,560 | false | {"C": 2929780, "Kotlin": 313185, "JavaScript": 359} | package org.kodein.memory.file
public expect object FileSystem {
internal val pathSeparator: String
public val tempDirectory: Path
public fun workingDir(): Path
public fun changeWorkingDir(path: Path)
public val roots: List<Path>
} | 0 | C | 0 | 7 | bab7f6ff28ca5cf9031a3d312f56d67fe3151d3c | 255 | Klio | MIT License |
http-api-client/src/test/kotlin/au/com/redcrew/apisdkcreator/httpclient/data/http-response-builder.kt | RedCrewOS | 370,915,550 | false | null | package au.com.redcrew.apisdkcreator.httpclient.data
import au.com.redcrew.apisdkcreator.httpclient.HttpHeaders
import au.com.redcrew.apisdkcreator.httpclient.HttpResponse
fun <T: Any> aHttpResponse() = HttpResponseBuilder<T>()
class HttpResponseBuilder<T: Any> {
private var statusCode = 200
private var statusMessage = "OK"
private val headers = mutableMapOf<String, String>()
private var body: T? = null
fun withStatusCode(code: Int): HttpResponseBuilder<T> {
this.statusCode = code
return this
}
fun withStatusMessage(message: String): HttpResponseBuilder<T> {
this.statusMessage = message
return this
}
fun withHeaders(headers: HttpHeaders): HttpResponseBuilder<T> {
this.headers.clear()
this.headers.putAll(headers)
return this
}
fun addHeader(name: String, value: String): HttpResponseBuilder<T> {
this.headers[name] = value
return this
}
fun withBody(body: T): HttpResponseBuilder<T> {
this.body = body
return this
}
fun build(): HttpResponse<T> = HttpResponse(statusCode, statusMessage, headers, body)
}
| 0 | Kotlin | 0 | 1 | dbf9e49314f5e0b832b4cb37ec9142dc3abfe69a | 1,175 | api-sdk-creator-kotlin | MIT License |
app/src/main/java/com/kirakishou/photoexchange/helper/location/LocationService.kt | chanyaz | 143,974,243 | true | {"Kotlin": 639219} | package com.kirakishou.photoexchange.helper.location
import android.content.Context
import com.kirakishou.photoexchange.helper.database.repository.SettingsRepository
import com.kirakishou.photoexchange.helper.database.repository.TakenPhotosRepository
import com.kirakishou.photoexchange.helper.extension.seconds
import com.kirakishou.photoexchange.mvp.model.other.LonLat
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.util.concurrent.TimeUnit
class LocationService(
private val context: Context,
private val takenPhotosRepository: TakenPhotosRepository,
private val settingsRepository: SettingsRepository
) {
private val TAG = "LocationService"
private val GPS_LOCATION_OBTAINING_MAX_TIMEOUT_MS = 15.seconds()
private val locationManager by lazy { MyLocationManager(context) }
fun getCurrentLocation(): Observable<LonLat> {
if (!takenPhotosRepository.hasPhotosWithEmptyLocation()) {
return Observable.just(LonLat.empty())
}
val gpsPermissionGrantedObservable = Observable.fromCallable {
settingsRepository.isGpsPermissionGranted()
}.publish().autoConnect(2)
val gpsGranted = gpsPermissionGrantedObservable
.filter { permissionGranted -> permissionGranted }
.doOnNext { Timber.tag(TAG).d("Gps permission is granted") }
.flatMap { getCurrentLocationInternal() }
.doOnNext { updateCurrentLocationForAllPhotosWithEmptyLocation(it) }
val gpsNotGranted = gpsPermissionGrantedObservable
.filter { permissionGranted -> !permissionGranted }
.doOnNext { Timber.tag(TAG).d("Gps permission is not granted") }
.map { LonLat.empty() }
return Observable.merge(gpsGranted, gpsNotGranted)
}
private fun updateCurrentLocationForAllPhotosWithEmptyLocation(location: LonLat) {
try {
takenPhotosRepository.updateAllPhotosLocation(location)
} catch (error: Throwable) {
Timber.tag(TAG).e(error)
}
}
private fun getCurrentLocationInternal(): Observable<LonLat> {
return Observable.fromCallable { locationManager.isGpsEnabled() }
.flatMap { isGpsEnabled ->
if (!isGpsEnabled) {
return@flatMap Observable.just(LonLat.empty())
}
return@flatMap RxLocationManager.start(locationManager)
.observeOn(Schedulers.io())
.timeout(GPS_LOCATION_OBTAINING_MAX_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.onErrorReturnItem(LonLat.empty())
}
}
} | 0 | Kotlin | 0 | 0 | 078a56b34b84f7121cac7ffac5ac7d6a0e39fb9a | 2,692 | photoexchange-android | Do What The F*ck You Want To Public License |
app/src/main/java/dev/seabat/android/hellobottomnavi/di/DataSourceModule.kt | seabat | 614,867,401 | false | null | package dev.seabat.android.hellobottomnavi.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.seabat.android.hellobottomnavi.data.datasource.github.GithubApiService
import dev.seabat.android.hellobottomnavi.data.datasource.github.GithubApi
import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaApi
import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaApiService
@Module
@InstallIn(SingletonComponent::class)
object DataSourceModuleModuleProvider {
@Provides
fun provideGithubApiEndpoint(
): GithubApiService {
return GithubApi.githubApiService
}
@Provides
fun provideQiitaApiEndpoint(
): QiitaApiService {
return QiitaApi.qiitaApiService
}
}
| 0 | Kotlin | 0 | 0 | 1a3dbbe590e88f31e6bdacbf29a5ea54a871a693 | 809 | hello-bottom-navigation | Apache License 2.0 |
ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/ProjectJdbcRepositoryExtensions.kt | nemerosa | 19,351,480 | false | {"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4} | package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository
import java.sql.ResultSet
fun AbstractJdbcRepository.toProject(rs: ResultSet) = Project(
id = ID.of(rs.getInt("ID")),
name = rs.getString("name"),
description = rs.getString("description"),
isDisabled = rs.getBoolean("disabled"),
signature = readSignature(rs)
)
| 44 | Kotlin | 25 | 96 | 759f17484c9b507204e5a89524e07df871697e74 | 493 | ontrack | MIT License |
src/main/kotlin/uk/ac/warwick/camcat/system/RequestContext.kt | lol768 | 229,056,652 | false | null | package uk.ac.warwick.camcat.system
import uk.ac.warwick.camcat.system.security.WarwickAuthentication
import uk.ac.warwick.userlookup.User
data class RequestContext(
val path: String,
val auth: WarwickAuthentication?,
val user: User,
val actualUser: User,
val loginUrl: String,
val logoutUrl: String
) {
val masquerading: Boolean = user != actualUser
}
| 0 | Kotlin | 1 | 0 | a300390c009e58e33eec832ca46cc910d171fcf1 | 369 | course-module-catalogue | ISC License |
app/src/main/java/com/example/chessmate/game/ui/chess/square/decoration/DefaultSquareBackground.kt | Pancio-code | 705,812,857 | false | {"Kotlin": 542386} | package com.example.chessmate.game.ui.chess.square.decoration
import com.example.chessmate.ui.theme.square_dark
import com.example.chessmate.ui.theme.square_light
object DefaultSquareBackground : SquareBackground(
lightSquareColor = square_light,
darkSquareColor = square_dark,
)
| 0 | Kotlin | 0 | 0 | 5e904940a7579fe0a3a3998c8547d85c694e3b2e | 289 | ChessMate-MACC | Apache License 2.0 |
src/main/kotlin/net/modcrafters/nebb/blocks/tudors/TileTudors.kt | MinecraftModDevelopmentMods | 103,860,689 | false | null | package net.modcrafters.nebb.blocks.tudors
import net.minecraft.block.state.IBlockState
import net.minecraft.client.renderer.block.model.BakedQuad
import net.minecraft.client.renderer.block.model.IBakedModel
import net.minecraft.client.renderer.vertex.VertexFormat
import net.minecraft.init.Blocks
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.Vec3d
import net.minecraftforge.common.model.TRSRTransformation
import net.minecraftforge.common.util.Constants
import net.modcrafters.nebb.blocks.BaseTile
import net.modcrafters.nebb.getSprite
import net.modcrafters.nebb.parts.BigAABB
import net.modcrafters.nebb.parts.BlockInfo
import net.modcrafters.nebb.parts.PartInfo
import net.modcrafters.nebb.parts.PartTextureInfo
import net.ndrei.teslacorelib.render.selfrendering.RawCube
import javax.vecmath.Matrix4d
import javax.vecmath.Vector3d
class TileTudors : BaseTile() {
private var width = 4.0
override fun createBlockInfo(): BlockInfo {
return TileTudors.getModel(width, mapOf())
}
companion object {
const val PART_CENTER = "center"
const val PART_FRAME = "frame"
fun getModel(stack: ItemStack): BlockInfo {
return getModel(4.0, mapOf(
PART_CENTER to Blocks.WOOL.defaultState,
PART_FRAME to Blocks.PLANKS.defaultState
))
}
private fun getModel(width: Double, textureMap: Map<String, IBlockState>): BlockInfo {
val builder = BlockInfo.getBuilder()
builder.add(PartInfo(PART_CENTER,
BigAABB.withSize(width, width, width, 32 - width * 2, 32 - width * 2, 32 - width * 2)
), textureMap.getOrDefault(PART_CENTER, Blocks.WOOL.defaultState))
builder.add(object: PartInfo(PART_FRAME,
// vertical
BigAABB.withSize(0.0, 0.0, 0.0, width, 32.0, width),
BigAABB.withSize(32.0 - width, 0.0, 0.0, width, 32.0, width),
BigAABB.withSize(32.0 - width, 0.0, 32.0 - width, width, 32.0, width),
BigAABB.withSize(0.0, 0.0, 32.0 - width, width, 32.0, width),
// bottom
BigAABB.withSize(width, 0.0, 0.0, 32.0 - width * 2, width, width),
BigAABB.withSize(32.0 - width, 0.0, width, width, width, 32.0 - width * 2),
BigAABB.withSize(width, 0.0, 32.0 - width, 32.0 - width * 2, width, width),
BigAABB.withSize(0.0, 0.0, width, width, width, 32.0 - width * 2),
// top
BigAABB.withSize(width, 32.0 - width, 0.0, 32.0 - width * 2, width, width),
BigAABB.withSize(32.0 - width, 32.0 - width, width, width, width, 32.0 - width * 2),
BigAABB.withSize(width, 32.0 - width, 32.0 - width, 32.0 - width * 2, width, width),
BigAABB.withSize(0.0, 32.0 - width, width, width, width, 32.0 - width * 2)
) {
override fun bakePartQuads(texture: PartTextureInfo, quads: MutableList<BakedQuad>, partBlockModel: IBakedModel, vertexFormat: VertexFormat, transform: TRSRTransformation) {
super.bakePartQuads(texture, quads, partBlockModel, vertexFormat, transform)
EnumFacing.HORIZONTALS.forEach {
val matrix = Matrix4d()
matrix.setIdentity()
matrix.mul(Matrix4d().also { m ->
m.setIdentity()
m.setTranslation(Vector3d(16.0, 16.0, 16.0))
})
matrix.mul(Matrix4d().also { m ->
m.setIdentity()
val angle = (if (it.axisDirection == EnumFacing.AxisDirection.POSITIVE) 1.0 else -1.0) * Math.PI / 4
when (it.axis) {
EnumFacing.Axis.X -> m.rotX(angle)
EnumFacing.Axis.Z -> m.rotZ(angle)
}
})
data class Quad(val x1: Double, val z1: Double, val x2: Double, val z2: Double)
val (x1, z1, x2, z2) = when (it.axis) {
EnumFacing.Axis.X -> when (it.axisDirection!!) {
EnumFacing.AxisDirection.NEGATIVE -> Quad(0.005, 16.0 - width / 2.0, width, 16.0 + width / 2.0)
EnumFacing.AxisDirection.POSITIVE -> Quad(32.0 - width, 16.0 - width / 2.0, 31.995, 16.0 + width / 2.0)
}
EnumFacing.Axis.Z -> when (it.axisDirection!!) {
EnumFacing.AxisDirection.NEGATIVE -> Quad(16.0 - width / 2.0, 0.005, 16.0 + width / 2.0, width)
EnumFacing.AxisDirection.POSITIVE -> Quad(16.0 - width / 2.0, 32.0 - width, 16.0 + width / 2.0, 31.995)
}
else -> Quad(0.0, 0.0, 0.0, 0.0)
}
RawCube(Vec3d(x1 - 16.0, -4.0 - 16.0, z1 - 16.0), Vec3d(x2 - 16.0, 36.0 - 16.0, z2 - 16.0))
.addFace(it).sprite(partBlockModel.getSprite(texture.block, it)).uv(7f, 0f, 8f, 16f)
.addFace(it.rotateY()).sprite(partBlockModel.getSprite(texture.block, it.rotateY())).uv(7f, 0f, 8f, 16f)
.addFace(it.rotateYCCW()).sprite(partBlockModel.getSprite(texture.block, it.rotateYCCW())).uv(7f, 0f, 8f, 16f)
.bake(quads, vertexFormat, transform, matrix)
}
}
},
textureMap.getOrDefault(PART_FRAME, Blocks.PLANKS.defaultState))
builder.setCacheKeyTransformer { "$width$it" }
return builder.build()
}
}
//#region serialization
override fun readFromNBT(compound: NBTTagCompound) {
super.readFromNBT(compound)
if (compound.hasKey("width", Constants.NBT.TAG_DOUBLE)) {
this.width = compound.getDouble("width")
}
}
override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound {
val nbt = super.writeToNBT(compound)
nbt.setDouble("width", this.width)
return nbt
}
//#endregion
}
| 0 | Kotlin | 0 | 0 | 5b1544c9d88903b1c466873e357bb8fa28750145 | 6,416 | Not-Enough-Building-Blocks | MIT License |
src/main/kotlin/com/pandus/leetcode/solutions/daily/RemoveNodesFromLinkedList.kt | bodyangug | 740,204,714 | false | {"Kotlin": 289421} | package com.pandus.leetcode.solutions.daily
import com.pandus.leetcode.solutions.model.ListNode
// Reference: https://leetcode.com/problems/remove-nodes-from-linked-list
class RemoveNodesFromLinkedList {
fun removeNodes(head: ListNode?): ListNode? {
if (head?.next == null) {
return head
}
val nextNode = removeNodes(head.next)
// If the next node has greater value than head, delete the head
// Return next node, which removes the current head and makes next the new head
if (head.`val` < nextNode!!.`val`) {
return nextNode
}
// Keep the head
head.next = nextNode
return head
}
}
| 0 | Kotlin | 0 | 1 | ab697ba6c2332d0061571e256e79714dbbd6c6b8 | 698 | leetcode-solutions | MIT License |
telegram/src/main/kotlin/com/github/kotlintelegrambot/dispatcher/handlers/Handler.kt | kotlin-telegram-bot | 121,235,631 | false | null | package com.github.kotlintelegrambot.dispatcher.handlers
import com.github.kotlintelegrambot.Bot
import com.github.kotlintelegrambot.entities.Update
/**
* [Handler]s are the components in charge of processing bot updates. Usually, you shouldn't
* implement this interface but rather use the built-in implementations. However, if you need to
* implement some custom updates handling that is not provided by the library, you can
* implement it and add the handler to the [Dispatcher] so it receives the updates.
*/
interface Handler {
/**
* Whether the handler should process the received [update].
*
* @param update Telegram bot update that the handler might want to process.
*
* @return True if the handler should process the update, false otherwise.
*/
fun checkUpdate(update: Update): Boolean
/**
* Code to act on a received [Update].
*
* @param bot Instance of the Telegram bot that received the update.
* @param update The update to be processed.
*/
fun handleUpdate(bot: Bot, update: Update)
}
| 67 | null | 161 | 794 | 18013912c6a8c395b6491c2323a8f5eb7288b4f5 | 1,078 | kotlin-telegram-bot | Apache License 2.0 |
app/src/main/java/pers/zander/kotlinmvvm/practice/model/bean/Banner.kt | Zander2014 | 274,615,470 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 130, "XML": 47, "Java": 2, "Gradle Kotlin DSL": 1, "INI": 1} | package pers.zander.kotlinmvvm.practice.model.bean
/**
* Created by Zander on 2020/6/26.
* Author:Zander
* Mail:<EMAIL>
* Depiction:
*/
data class Banner(val desc: String,
val id: Int,
val imagePath: String,
val isVisible: Int,
val order: Int,
val title: String,
val type: Int,
val url: String) | 0 | Kotlin | 0 | 0 | 4521c3a338e37e87e019cfdd7ed7af833a63f6d3 | 426 | KotlinMVVMPractices | Apache License 2.0 |
automation/espresso/src/main/kotlin/com/instructure/canvas/espresso/mockCanvas/utils/Randomizer.kt | instructure | 179,290,947 | false | null | /*
* Copyright (C) 2019 - present Instructure, Inc.
*
* 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.
*
*/
@file:Suppress("unused")
package com.instructure.canvas.espresso.mockCanvas.utils
import com.github.javafaker.Faker
import java.util.*
/**
* Provides access to numerous convenience functions for generating random data
*
* It is expected that [Randomizer] will be used to generate only scalar values or very lightweight structures
* such as simple data classes. This class is not intended to be used for generating complex items like entire
* Courses or Assignments; high levels of randomization in such items can easily lead to unintended flakiness in tests.
* Instead, generation of these items should generally be implemented in extension functions on [MockCanvas] where
* random data is used only where necessary.
*/
object Randomizer {
private val faker = Faker()
/** Creates a random UUID */
private fun randomUUID() = UUID.randomUUID().toString()
/** Creates a random [FakeName] */
fun randomName() = FakeName(faker.name().firstName(), faker.name().lastName())
/** Creates random name for a course */
fun randomCourseName(): String = faker.educator().course() + " " + randomUUID()
/** Creates a random string from Lorem from the first 'wordCount' words of it. */
fun getLoremWords(wordCount: Int): String = faker.lorem().sentence(wordCount - 1)
/** Creates a random description for a course */
fun randomCourseDescription() : String = faker.lorem().sentence()
/** Creates random name for a course section */
fun randomSectionName(): String = faker.pokemon().name() + " Section"
/** Creates a random password */
fun randomPassword(): String = randomUUID()
/** Creates a random email using a timestamp and a UUID */
fun randomEmail(): String = "${Date().time}@${randomUUID()}.com"
/** Creates a random avatar URL */
fun randomAvatarUrl(): String = faker.avatar().image()
/** Creates a Url to a small image */
fun randomImageUrlSmall(): String = faker.internet().image(64, 64, false, null)
/** Create random text for a conversation subject */
fun randomConversationSubject(): String = faker.chuckNorris().fact()
/** Creates random text for a conversation body */
fun randomConversationBody(): String = faker.lorem().paragraph()
/** Creates a random Term name */
fun randomEnrollmentTitle(): String = "${faker.pokemon()} Term"
/** Creates a random title for a grading period set */
fun randomGradingPeriodSetTitle(): String = "${faker.pokemon().location()} Set"
/** Creates a random grading period name */
fun randomGradingPeriodName(): String = "${faker.pokemon().name()} Grading Period"
/** Creates a random page title with a UUID to avoid Canvas URL collisions */
fun randomPageTitle(): String = faker.gameOfThrones().house() + " " + randomUUID()
/** Creates a random page body */
fun randomPageBody(): String = "<p><strong>" + faker.gameOfThrones().quote() + "</strong></p><p>" + faker.lorem().paragraph() + "</p>"
/** Creates a random Course Group Category name */
fun randomCourseGroupCategoryName(): String = faker.harryPotter().character()
/** Creates random name for an assignment */
fun randomAssignmentName(): String = "${faker.starTrek().character()} ${UUID.randomUUID()}"
}
/** Represents a fake user name */
data class FakeName(val firstName: String, val lastName: String) {
val fullName get() = "$firstName $lastName"
val sortableName get() = "$lastName, $firstName"
}
| 7 | null | 85 | 99 | 1bac9958504306c03960bdce7fbb87cc63bc6845 | 4,132 | canvas-android | Apache License 2.0 |
ui-item/src/main/java/org/kafka/item/detail/ItemDetailViewState.kt | vipulyaara | 170,554,386 | false | null | package org.kafka.item.detail
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.unit.sp
import com.kafka.data.entities.Item
import com.kafka.data.entities.ItemDetail
import com.kafka.data.entities.isAudio
import org.kafka.base.debug
import org.kafka.common.UiMessage
data class ItemDetailViewState(
val isFavorite: Boolean = false,
val itemDetail: ItemDetail? = null,
val itemsByCreator: List<Item>? = null,
val isLoading: Boolean = false,
val message: UiMessage? = null
) {
val isSnackbarError
get() = message != null && itemDetail != null
val isFullScreenError
get() = message != null && itemDetail == null
val isFullScreenLoading: Boolean
get() {
debug { "isFullScreenLoading $isLoading $itemDetail" }
return isLoading && itemDetail == null
}
}
fun ItemDetail.ratingText(color: Color): AnnotatedString {
val annotatedString = AnnotatedString.Builder("✪✪✪✪✪ ")
.apply {
addStyle(SpanStyle(color = color), 0, 3)
addStyle(SpanStyle(letterSpacing = 1.5.sp), 0, length)
}
return annotatedString.toAnnotatedString()
}
val ItemDetail.callToAction
get() = if (isAudio()) "Play" else "Read"
| 0 | Kotlin | 4 | 26 | 41e41fae10351ff316fedd2bcde2e10152cc9a65 | 1,341 | Kafka | Apache License 2.0 |
app/src/main/java/com/eklitstudio/advokatkotilin/data/db/entity/Tarifa.kt | skokomilos | 231,165,269 | false | null | package com.eklitstudio.advokatkotilin.data.db.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import org.jetbrains.annotations.NotNull
@Entity(
tableName = "tarifa_table"
)
data class Tarifa(
@PrimaryKey(autoGenerate = false)
@NotNull
val idTarifa: Int,
@NotNull
val nazivTarife: String,
val idPostupak: Long?,
val idVrstaParnice: Long?){
} | 0 | Kotlin | 0 | 0 | 4fbc8aed05483761aad01ea610d4049dbadf03b4 | 394 | kalkulator_advokatske_tarife | No Limit Public License |
composeApp/src/commonMain/kotlin/de/franzsw/extractor/presentation/components/ActionInfoAssembly.kt | franz-sw | 706,066,803 | false | {"Kotlin": 78228, "Batchfile": 958} | package de.franzsw.extractor.presentation.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import de.franzsw.extractor.data.SharedString
import de.franzsw.extractor.data.toCommonString
@Composable
fun ActionInfoAssembly(
onClickExport: () -> Unit,
onSaveConfigEvents: () -> Unit,
errorMessage: String?,
isError: Boolean,
isLoading: Boolean,
modifier: Modifier = Modifier
) {
Column(
horizontalAlignment = Alignment.Start,
modifier = modifier
.animateContentSize()
.padding(8.dp)
) {
errorMessage?.let {
Text(
text = it,
color = if (isError) MaterialTheme.colorScheme.error else LocalTextStyle.current.color,
modifier = Modifier.padding(8.dp)
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
AnimatedContent(isLoading) {
if (it) {
CircularProgressIndicator()
} else {
Button(onClickExport) {
Text(SharedString.StartExport.toCommonString())
}
}
}
Button(onSaveConfigEvents) {
Text(SharedString.SaveConfig.toCommonString())
}
}
}
} | 0 | Kotlin | 0 | 0 | dc14388d4d4ac7c6922e361a7f33d47df5ae99f9 | 1,746 | ICSExtractor | Apache License 2.0 |
app/src/main/java/net/saoshyant/Life/app/FeedListAdapters/mediaAdapter.kt | amirabbas8 | 168,003,254 | false | {"Java": 353781, "Kotlin": 290317} | package net.saoshyant.Life.app.FeedListAdapters
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.android.volley.VolleyError
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.NetworkImageView
import net.saoshyant.Life.R
import net.saoshyant.Life.activity.VideoPlayer
import net.saoshyant.Life.app.DatabaseHandler
import net.saoshyant.Life.app.MyApplication
import java.util.*
class mediaAdapter(private val activity: Activity, private val mediaList: Array<String>?) : RecyclerView.Adapter<mediaAdapter.MyViewHolder>() {
inner class MyViewHolder constructor(view: View) : RecyclerView.ViewHolder(view) {
val niwImage: NetworkImageView
val videoView: ImageView
init {
niwImage = view.findViewById(R.id.image)
videoView = view.findViewById(R.id.video)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.feed_item_media, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val mediaName = mediaList!![position]
val db1 = DatabaseHandler(activity)
val user: HashMap<String, String>
user = db1.userDetails
user["idNo"]
if ("http://saoshyant.net/postsimages/" == mediaName) {
holder.niwImage.visibility = View.GONE
} else {
holder.niwImage.visibility = View.VISIBLE
try {
holder.niwImage.setImageUrl(mediaName, imageLoader)
} catch (e: Exception) {
}
}
if (mediaName == "") {
holder.videoView.visibility = View.GONE
} else {
holder.videoView.visibility = View.VISIBLE
MyApplication.instance!!.imageLoader.get("http://saoshyant.net/videoThumb/$mediaName", object : ImageLoader.ImageListener {
override fun onErrorResponse(volleyError: VolleyError) {
}
override fun onResponse(imageContainer: ImageLoader.ImageContainer, b: Boolean) {
holder.videoView.background = BitmapDrawable(activity.resources, imageContainer.bitmap)
holder.videoView.setImageResource(R.drawable.icon_video_play)
}
})
holder.videoView.setOnClickListener {
val intent = Intent(activity, VideoPlayer::class.java)
intent.putExtra("videoName", mediaName)
activity.startActivity(intent)
}
}
}
override fun getItemCount(): Int {
return mediaList?.size ?: 0
}
companion object {
private val imageLoader = MyApplication.instance!!.imageLoader
}
}
| 1 | null | 1 | 1 | ef5ac235333ec1dfbd4364769875f4ba1569e488 | 3,089 | life-android-client | MIT License |
api/src/main/kotlin/com/wnsgml972/strada/api/v1/account/service/UserDto.kt | Coffee-Street | 289,485,814 | false | {"Kotlin": 267923, "Shell": 2546, "Dockerfile": 174} | package com.wnsgml972.strada.api.v1.account.service
data class UserDto(
val id: String?,
val isEnabled: Boolean,
)
| 2 | Kotlin | 2 | 2 | 24422867afe6c7f547a93f98083f655ecb80c0ed | 124 | strada | MIT License |
dm-kt/dm-lib/src/test/kotlin/com/ysz/dm/lib/lang/functions/ExtendFunctionsTest.kt | carl10086 | 246,727,202 | false | {"Shell": 5, "Ignore List": 1, "Text": 2, "Gradle": 16, "INI": 2, "Batchfile": 1, "Makefile": 2, "Markdown": 10, "XML": 4, "Kotlin": 141, "Java": 5, "Java Properties": 1, "Lua": 4, "Protocol Buffer": 1, "YAML": 1, "desktop": 1, "Python": 112, "Jupyter Notebook": 12, "SVG": 4, "Go Module": 1, "Go": 3} | package com.ysz.dm.lib.lang.functions
import com.ysz.dm.lib.common.atomictest.eq
import org.junit.jupiter.api.Test
/**
*<pre>
* class desc here
*</pre>
*@author carl.yu
*@since 2023/1/12
**/
internal class ExtendFunctionsTest {
/*扩展了 string 方法, 而且是 this*/
fun String.singleQuote() = "'$this'"
@Test
fun `test singleQuote`() {
"Hi".singleQuote() eq ""
}
} | 2 | null | 1 | 1 | 4992c4d772e942d8c72b8127315fa3635687b0ec | 392 | dm-learning | Apache License 2.0 |
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_11925.plugin.kts | 2011Scape | 578,880,245 | false | {"Kotlin": 8904349, "Dockerfile": 1354} | package gg.rsmod.plugins.content.areas.spawns
/**
* @author <NAME> <<EMAIL>>
*/
spawn_npc(npc = Npcs.MUGGER, x = 2994, z = 9549, walkRadius = 5, direction = Direction.SOUTH)
spawn_npc(npc = Npcs.MUGGER, x = 2993, z = 9551, walkRadius = 5, direction = Direction.SOUTH)
spawn_npc(npc = Npcs.MUGGER, x = 2995, z = 9555, walkRadius = 5, direction = Direction.SOUTH)
spawn_npc(npc = Npcs.MUGGER, x = 2999, z = 9548, walkRadius = 5, direction = Direction.NORTH_WEST)
spawn_npc(npc = Npcs.PIRATE, x = 2993, z = 9568, walkRadius = 5, direction = Direction.SOUTH)
spawn_npc(npc = Npcs.PIRATE, x = 2991, z = 9574, walkRadius = 5, direction = Direction.NORTH_WEST)
spawn_npc(npc = Npcs.PIRATE, x = 2989, z = 9578, walkRadius = 5, direction = Direction.NORTH_WEST)
spawn_npc(npc = Npcs.PIRATE, x = 2991, z = 9583, walkRadius = 5, direction = Direction.NORTH_EAST)
spawn_npc(npc = Npcs.PIRATE, x = 2996, z = 9583, walkRadius = 5, direction = Direction.EAST)
spawn_npc(npc = Npcs.PIRATE, x = 2999, z = 9580, walkRadius = 5, direction = Direction.SOUTH_EAST)
spawn_npc(npc = Npcs.PIRATE, x = 2996, z = 9576, walkRadius = 5, direction = Direction.SOUTH_WEST)
spawn_npc(npc = Npcs.PIRATE, x = 2999, z = 9573, walkRadius = 5, direction = Direction.SOUTH_EAST)
spawn_npc(npc = Npcs.PIRATE, x = 2994, z = 9570, walkRadius = 5, direction = Direction.SOUTH_WEST)
spawn_npc(npc = Npcs.HOBGOBLIN_2688, x = 3006, z = 9580, walkRadius = 5, direction = Direction.SOUTH)
spawn_npc(npc = Npcs.HOBGOBLIN_2688, x = 2999, z = 9595, walkRadius = 5, direction = Direction.NORTH_EAST)
spawn_npc(npc = Npcs.HOBGOBLIN_2688, x = 3002, z = 9593, walkRadius = 5, direction = Direction.SOUTH_EAST)
spawn_npc(npc = Npcs.HOBGOBLIN_2688, x = 3006, z = 9595, walkRadius = 5, direction = Direction.EAST)
| 39 | Kotlin | 143 | 34 | e5400cc71bfa087164153d468979c5a3abc24841 | 1,761 | game | Apache License 2.0 |
src/main/kotlin/com/github/kerubistan/kerub/services/VirtualNetworkService.kt | kerubistan | 19,528,622 | false | null | package com.github.kerubistan.kerub.services
import com.github.kerubistan.kerub.model.VirtualNetwork
import com.wordnik.swagger.annotations.Api
import org.apache.shiro.authz.annotation.RequiresAuthentication
import javax.ws.rs.Consumes
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
@Api("s/r/vnet", description = "Virtual network operations")
@Path("/vnet")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RequiresAuthentication
interface VirtualNetworkService :
RestCrud<VirtualNetwork>,
RestOperations.List<VirtualNetwork>,
AssetService<VirtualNetwork> | 109 | Kotlin | 4 | 14 | 99cb43c962da46df7a0beb75f2e0c839c6c50bda | 631 | kerub | Apache License 2.0 |
kotlin-modules/kotlin-core/kotlin-core-collections-1/src/test/kotlin/cn/tuyucheng/taketoday/collections/transformations/FilterUnitTest.kt | tu-yucheng | 665,975,665 | false | {"Java": 23064539, "JavaScript": 3484231, "HTML": 808829, "Kotlin": 801709, "CSS": 689526, "TypeScript": 669186, "Groovy": 139102, "AspectJ": 71773, "Shell": 60634, "FreeMarker": 41357, "RAML": 38085, "ANTLR": 31940, "SCSS": 29096, "Mustache": 15860, "Gherkin": 15603, "Scala": 15349, "Python": 14777, "HCL": 13943, "Dockerfile": 12656, "Lua": 11459, "Batchfile": 6107, "C++": 4113, "Clojure": 1892, "PLpgSQL": 1888, "Solidity": 1542, "XSLT": 1316, "Starlark": 1268, "Smarty": 1142, "Open Policy Agent": 1042, "Rich Text Format": 810, "Thrift": 609, "Perl": 494, "CLIPS": 383, "C": 321, "Pug": 297, "Makefile": 220, "R": 48, "Handlebars": 12, "Fluent": 1} | package cn.tuyucheng.taketoday.collections.transformations
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class FilterUnitTest {
@Test
fun testFilterWithLambda() {
val input = listOf(1, 2, 3, 4, 5)
val filtered = input.filter { it <= 3 }
assertEquals(listOf(1, 2, 3), filtered)
}
@Test
fun testFilterWithMethodReference() {
val input = listOf(1, 2, 3, 4, 5)
val filtered = input.filter(this::isSmall)
assertEquals(listOf(1, 2, 3), filtered)
}
@Test
fun testFilterNotWithMethodReference() {
val input = listOf(1, 2, 3, 4, 5)
val filtered = input.filterNot(this::isSmall)
assertEquals(listOf(4, 5), filtered)
}
@Test
fun testFilterIndexed() {
val input = listOf(5, 4, 3, 2, 1)
val filtered = input.filterIndexed { index, element -> index < 3 }
assertEquals(listOf(5, 4, 3), filtered)
}
@Test
fun testFilterNotNull() {
val nullable: List<String?> = listOf("Hello", null, "World")
val nonnull: List<String> = nullable.filterNotNull()
assertEquals(listOf("Hello", "World"), nonnull)
}
private fun isSmall(i: Int) = i <= 3
} | 1 | null | 1 | 1 | 1d22d457d31ec5b1f83196958477afd37dbd8939 | 1,111 | taketoday-tutorial4j-backup | MIT License |
src/year_2023/day_10/Day10Test.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_10
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class Day10Test {
@Test
fun testSolutionOne_ExampleOne() {
val sampleText = listOf(
"-L|F7",
"7S-7|",
"L|7||",
"-L-J|",
"L|-JF",
)
val solutionOne = Day10.solutionOne(sampleText)
assertEquals(4, solutionOne)
}
@Test
fun testSolutionOne_ExampleTwo() {
val sampleText = listOf(
"..F7.",
".FJ|.",
"SJ.L7",
"|F--J",
"LJ...",
)
val solutionOne = Day10.solutionOne(sampleText)
assertEquals(8, solutionOne)
}
@Test
fun testSolutionTwo() {
val sampleText = listOf(
"...........",
".S-------7.",
".|F-----7|.",
".||.....||.",
".||.....||.",
".|L-7.F-J|.",
".|..|.|..|.",
".L--J.L--J.",
"...........",
)
val solutionTwo = Day10.solutionTwo(sampleText)
assertEquals(4, solutionTwo)
}
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 1,152 | advent_of_code | Apache License 2.0 |
NavigationDemo/app/src/main/java/com/thk/navigationdemo/parent/ParentMainFragment.kt | taehee28 | 501,526,965 | false | {"Kotlin": 114961, "Java": 5663} | package com.thk.navigationdemo.parent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.thk.navigationdemo.R
import com.thk.navigationdemo.base.BaseFragment
import com.thk.navigationdemo.databinding.FragmentParentMainBinding
class ParentMainFragment : BaseFragment<FragmentParentMainBinding>(FragmentParentMainBinding::inflate) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnDetail.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_parentMainFragment_to_parentDetailFragment)
)
}
} | 0 | Kotlin | 0 | 0 | 4032adc237c9efa3f5a03e5107c6c974b47f8ca6 | 785 | StudyProjects | MIT License |
idea/tests/testData/inspectionsLocal/redundantVisibilityModifier/onlyPrivateIsOkForSealedConstructor.kt | JetBrains | 278,369,660 | false | null | // PROBLEM: none
// ERROR: Constructor must be private in sealed class
// COMPILER_ARGUMENTS: -XXLanguage:-SealedInterfaces
sealed class Foo {
<caret>protected constructor()
} | 0 | Kotlin | 29 | 71 | b6789690db56407ae2d6d62746fb69dc99d68c84 | 179 | intellij-kotlin | Apache License 2.0 |
acc2/src/main/java/com/angcyo/acc2/parse/AccContext.kt | angcyo | 229,037,615 | false | {"Kotlin": 6719989, "JavaScript": 5194} | package com.angcyo.acc2.parse
import android.graphics.Rect
import com.angcyo.library._screenHeight
import com.angcyo.library._screenWidth
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2021/02/01
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class AccContext {
/**比例计算限制*/
var bounds: Rect? = null
/**查找到多少个节点后
* 满足条件时, 中断遍历查找, 提升效率
* 公式参考[com.angcyo.acc2.bean.FilterBean.childCount]
* */
var findLimit: String? = null
/**递归查找深度, 从1开始的.
* 满足条件时, 中断遍历查找, 提升效率
* 公式参考[com.angcyo.acc2.bean.FilterBean.childCount]
* */
var findDepth: String? = null
/**坐标计算时, 比例计算时的参考矩形*/
fun getBound(): Rect {
return bounds ?: Rect(0, 0, _screenWidth, _screenHeight)
}
} | 0 | Kotlin | 6 | 5 | 47013e00b89268a517627f396e50c2c0e889b41e | 756 | UICore | MIT License |
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/wasm/decoder/type/memory/MemoryTypeDecoder.kt | CharlieTap | 743,980,037 | false | {"Kotlin": 1682566, "WebAssembly": 75112} | package io.github.charlietap.chasm.decoder.wasm.decoder.type.memory
import com.github.michaelbull.result.Result
import io.github.charlietap.chasm.ast.type.MemoryType
import io.github.charlietap.chasm.decoder.wasm.error.WasmDecodeError
import io.github.charlietap.chasm.decoder.wasm.reader.WasmBinaryReader
internal typealias MemoryTypeDecoder = (WasmBinaryReader) -> Result<MemoryType, WasmDecodeError>
| 2 | Kotlin | 2 | 43 | addbd2285ab2c9a7f0c12bb0d9fd246241f59513 | 405 | chasm | Apache License 2.0 |
inspector/src/main/kotlin/com/github/weisj/swingdsl/inspector/InspectorIcons.kt | weisJ | 349,581,043 | false | null | /*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.github.weisj.swingdsl.inspector
import com.github.weisj.darklaf.properties.icons.IconLoader
import java.awt.Color
import java.awt.Component
import java.awt.Window
import javax.swing.*
private object ComponentIconMappings {
private val LOADER: IconLoader = IconLoader.get(Inspector::class.java)
private val PROPERTY_MAP: Map<Any, Any> = mapOf(
"inspectorWarningHighlight" to Color(0xF26522),
"inspectorWarningOpacity" to 80,
"fallback.inspectorBackground" to Color(0x9AA7B0),
"fallback.inspectorForeground" to Color(0x231F20),
)
private fun load(name: String): Icon = LOADER.loadSVGIcon(name, 16, 16, true, PROPERTY_MAP)
val INSPECTOR = load("inspector.svg")
val UNKNOWN = load("unknown.svg")
val CLICK_INFO = load("clickInfo.svg")
val MAPPING = mapOf(
JLabel::class.java to load("label.svg"),
JPanel::class.java to load("panel.svg"),
JButton::class.java to load("button.svg"),
JCheckBox::class.java to load("checkBox.svg"),
JRadioButton::class.java to load("radioButton.svg"),
JComboBox::class.java to load("comboBox.svg"),
JList::class.java to load("list.svg"),
JProgressBar::class.java to load("progressbar.svg"),
JScrollBar::class.java to load("scrollbar.svg"),
JScrollPane::class.java to load("scrollPane.svg"),
JSeparator::class.java to load("separator.svg"),
JToolBar.Separator::class.java to load("toolbarSeparator.svg"),
JSlider::class.java to load("slider.svg"),
JSpinner::class.java to load("spinner.svg"),
JSplitPane::class.java to load("splitPane.svg"),
JTabbedPane::class.java to load("tabbedPane.svg"),
JTable::class.java to load("table.svg"),
JTextArea::class.java to load("textArea.svg"),
JTextField::class.java to load("textField.svg"),
JFormattedTextField::class.java to load("formattedTextField.svg"),
JPasswordField::class.java to load("passwordField.svg"),
JTextPane::class.java to load("textPane.svg"),
JEditorPane::class.java to load("editorPane.svg"),
JToolBar::class.java to load("toolbar.svg"),
JTree::class.java to load("tree.svg"),
JLayeredPane::class.java to load("layeredPane.svg"),
Window::class.java to load("window.svg")
)
}
internal fun getInspectorIcon(): Icon = ComponentIconMappings.INSPECTOR
internal fun getClickInfoIcon(): Icon = ComponentIconMappings.CLICK_INFO
internal fun findIconFor(component: Component): Icon {
var aClass: Class<*>? = component.javaClass
var icon: Icon? = null
while (icon == null && aClass != null) {
icon = ComponentIconMappings.MAPPING[aClass]
aClass = aClass.superclass
}
if (icon == null) icon = ComponentIconMappings.UNKNOWN
return icon
}
| 4 | Kotlin | 0 | 6 | 7291a86a000007d74027cc7ec1b332664ea60cb7 | 3,985 | swing-dsl | MIT License |
app/src/main/java/com/example/nhlstats/common/data/cache/MemoryCache.kt | NoNews | 232,546,746 | false | null | package com.example.nhlstats.common.data.cache
interface MemoryCache<K> {
operator fun <T> get(key: K): T?
fun <T> getAll(): List<T>
fun contains(key: K): Boolean
operator fun set(key: K, value: Any)
fun <T> remove(key: K): T?
fun clear()
companion object {
val EMPTY = object : MemoryCache<Any> {
override fun <T> get(key: Any): T? = null
override fun <T> getAll(): List<T> = emptyList()
override fun contains(key: Any): Boolean = false
override fun set(key: Any, value: Any) = Unit
override fun <T> remove(key: Any): T? = null
override fun clear() = Unit
}
}
} | 0 | Kotlin | 0 | 0 | 18f690067cef42cf29577aa691f47b0c77c9d67c | 696 | NHL | Apache License 2.0 |
knotion-core/src/main/kotlin/io/github/rgbrizzlehizzle/knotion/models/database/response/QueryDatabaseResponse.kt | rgbrizzlehizzle | 367,649,156 | false | null | package io.github.rgbrizzlehizzle.knotion.models.database.response
import io.github.rgbrizzlehizzle.knotion.models.page.Page
import kotlinx.serialization.Serializable
@Serializable
@Suppress("ConstructorParameterNaming")
data class QueryDatabaseResponse(val `object`: String, val results: List<Page>)
| 3 | Kotlin | 0 | 1 | 0ea51bc9b1ffb4c590d3724e969b345de3b4d176 | 303 | knotion | MIT License |
wild-monitor-service/src/test/kotlin/wild/monitor/projects/ProjectRepositoryTest.kt | ddubson | 169,662,670 | false | null | package wild.monitor.projects
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@DataJpaTest
internal class ProjectRepositoryTest {
@Autowired
lateinit var testEntityManager: TestEntityManager
@Autowired
lateinit var projectRepository: ProjectRepository
@Test
fun projectRepository_findAllTest() {
val project = Project(projectName = "test_project")
testEntityManager.persist(project)
val projects = projectRepository.findAll()
assertThat(projects[0].projectName).isEqualTo("test_project")
assertThat(projects[0].id).isNotNull()
assertThat(projects[0].dbId).isNotNull()
assertThat(projects[0].createdOn).isNotNull()
assertThat(projects[0].projectKey).isNotNull()
}
@Test
fun projectRepository_saveTest() {
val project = Project(projectName = "test_project")
projectRepository.save(project)
val projects = projectRepository.findAll()
assertThat(projects[0].projectName).isEqualTo("test_project")
assertThat(projects[0].id).isNotNull()
assertThat(projects[0].dbId).isNotNull()
assertThat(projects[0].createdOn).isNotNull()
assertThat(projects[0].projectKey).isNotNull()
}
} | 0 | Kotlin | 0 | 0 | 28bc6535ab639c3ea712383d55f60dbdcb094cf0 | 1,648 | wild-monitor | MIT License |
app/src/main/java/com/capstone/urskripsi/ui/login/ForgotPasswordActivity.kt | Naufal0010 | 429,732,609 | false | null | package com.capstone.urskripsi.ui.login
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Patterns
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.capstone.urskripsi.R
import com.capstone.urskripsi.databinding.ActivityForgotPasswordBinding
import com.capstone.urskripsi.utils.Utility.hide
import com.capstone.urskripsi.utils.Utility.show
import com.capstone.urskripsi.utils.Utility.showToast
import com.capstone.urskripsi.utils.Utility.simpleToolbar
import com.google.firebase.auth.FirebaseAuth
class ForgotPasswordActivity : AppCompatActivity() {
private lateinit var binding: ActivityForgotPasswordBinding
private lateinit var mAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityForgotPasswordBinding.inflate(layoutInflater)
setContentView(binding.root)
mAuth = FirebaseAuth.getInstance()
simpleToolbar(getString(R.string.forgot_password), binding.toolbar.root, true)
binding.apply {
btnForgotPassword.setOnClickListener {
val email = edtEmail.text.toString().trim()
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches() && email.isNotEmpty()) {
edtEmail.error = resources.getString(R.string.invalid_formail_email)
} else if (TextUtils.isEmpty(email)) {
edtEmail.error = resources.getString(R.string.email_empty)
} else {
setForgotPassword()
}
}
tvBackToLogin.setOnClickListener {
startActivity(Intent(this@ForgotPasswordActivity, LoginActivity::class.java))
finish()
}
}
}
private fun setForgotPassword() {
val email = binding.edtEmail.text.toString().trim()
binding.progressBarDialog.root.show()
mAuth.sendPasswordResetEmail(email).addOnSuccessListener {
binding.progressBarDialog.root.hide()
binding.edtEmail.apply {
text.clear()
clearFocus()
}
showToast(getString(R.string.email_send_success), this@ForgotPasswordActivity)
}.addOnFailureListener {
binding.progressBarDialog.root.hide()
showToast(getString(R.string.email_send_failed), this@ForgotPasswordActivity)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 1 | 0 | 46c57498547218b1fda601b5f811511d999bd859 | 2,772 | UrSkripsi | MIT License |
examples/src/tl/telegram/InputFileLocation.kt | andreypfau | 719,064,910 | false | {"Kotlin": 62259} | // This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.telegram
import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer
import io.github.andreypfau.tl.serialization.TLCombinatorId
import io.github.andreypfau.tl.serialization.TLConditional
import kotlin.jvm.JvmName
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonClassDiscriminator
@Serializable
@JsonClassDiscriminator("@type")
public sealed interface InputFileLocation {
@Serializable
@SerialName("inputPeerPhotoFileLocationLegacy")
@TLCombinatorId(0x27D69997)
public data class InputPeerPhotoFileLocationLegacy(
@get:JvmName("flags")
public val flags: Int,
@TLConditional("flags", 0)
@get:JvmName("big")
public val big: Unit? = null,
@get:JvmName("peer")
public val peer: InputPeer,
@SerialName("volume_id")
@get:JvmName("volumeId")
public val volumeId: Long,
@SerialName("local_id")
@get:JvmName("localId")
public val localId: Int,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputStickerSetThumbLegacy")
@TLCombinatorId(0xDBAEAE9)
public data class InputStickerSetThumbLegacy(
@get:JvmName("stickerset")
public val stickerset: InputStickerSet,
@SerialName("volume_id")
@get:JvmName("volumeId")
public val volumeId: Long,
@SerialName("local_id")
@get:JvmName("localId")
public val localId: Int,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputFileLocation")
@TLCombinatorId(0xDFDAABE1)
public data class InputFileLocation(
@SerialName("volume_id")
@get:JvmName("volumeId")
public val volumeId: Long,
@SerialName("local_id")
@get:JvmName("localId")
public val localId: Int,
@get:JvmName("secret")
public val secret: Long,
@SerialName("file_reference")
@get:JvmName("fileReference")
public val fileReference: @Serializable(Base64ByteStringSerializer::class) ByteString,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputEncryptedFileLocation")
@TLCombinatorId(0xF5235D55)
public data class InputEncryptedFileLocation(
@get:JvmName("id")
public val id: Long,
@SerialName("access_hash")
@get:JvmName("accessHash")
public val accessHash: Long,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputDocumentFileLocation")
@TLCombinatorId(0xBAD07584)
public data class InputDocumentFileLocation(
@get:JvmName("id")
public val id: Long,
@SerialName("access_hash")
@get:JvmName("accessHash")
public val accessHash: Long,
@SerialName("file_reference")
@get:JvmName("fileReference")
public val fileReference: @Serializable(Base64ByteStringSerializer::class) ByteString,
@SerialName("thumb_size")
@get:JvmName("thumbSize")
public val thumbSize: String,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputSecureFileLocation")
@TLCombinatorId(0xCBC7EE28)
public data class InputSecureFileLocation(
@get:JvmName("id")
public val id: Long,
@SerialName("access_hash")
@get:JvmName("accessHash")
public val accessHash: Long,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputTakeoutFileLocation")
@TLCombinatorId(0x29BE5899)
public object InputTakeoutFileLocation : tl.telegram.InputFileLocation
@Serializable
@SerialName("inputPhotoFileLocation")
@TLCombinatorId(0x40181FFE)
public data class InputPhotoFileLocation(
@get:JvmName("id")
public val id: Long,
@SerialName("access_hash")
@get:JvmName("accessHash")
public val accessHash: Long,
@SerialName("file_reference")
@get:JvmName("fileReference")
public val fileReference: @Serializable(Base64ByteStringSerializer::class) ByteString,
@SerialName("thumb_size")
@get:JvmName("thumbSize")
public val thumbSize: String,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputPhotoLegacyFileLocation")
@TLCombinatorId(0xD83466F3)
public data class InputPhotoLegacyFileLocation(
@get:JvmName("id")
public val id: Long,
@SerialName("access_hash")
@get:JvmName("accessHash")
public val accessHash: Long,
@SerialName("file_reference")
@get:JvmName("fileReference")
public val fileReference: @Serializable(Base64ByteStringSerializer::class) ByteString,
@SerialName("volume_id")
@get:JvmName("volumeId")
public val volumeId: Long,
@SerialName("local_id")
@get:JvmName("localId")
public val localId: Int,
@get:JvmName("secret")
public val secret: Long,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputPeerPhotoFileLocation")
@TLCombinatorId(0x37257E99)
public data class InputPeerPhotoFileLocation(
@get:JvmName("flags")
public val flags: Int,
@TLConditional("flags", 0)
@get:JvmName("big")
public val big: Unit? = null,
@get:JvmName("peer")
public val peer: InputPeer,
@SerialName("photo_id")
@get:JvmName("photoId")
public val photoId: Long,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputStickerSetThumb")
@TLCombinatorId(0x9D84F3DB)
public data class InputStickerSetThumb(
@get:JvmName("stickerset")
public val stickerset: InputStickerSet,
@SerialName("thumb_version")
@get:JvmName("thumbVersion")
public val thumbVersion: Int,
) : tl.telegram.InputFileLocation {
public companion object
}
@Serializable
@SerialName("inputGroupCallStream")
@TLCombinatorId(0x598A92A)
public data class InputGroupCallStream(
@get:JvmName("flags")
public val flags: Int,
@get:JvmName("call")
public val call: InputGroupCall,
@SerialName("time_ms")
@get:JvmName("timeMs")
public val timeMs: Long,
@get:JvmName("scale")
public val scale: Int,
@SerialName("video_channel")
@TLConditional("flags", 0)
@get:JvmName("videoChannel")
public val videoChannel: Int? = null,
@SerialName("video_quality")
@TLConditional("flags", 0)
@get:JvmName("videoQuality")
public val videoQuality: Int? = null,
) : tl.telegram.InputFileLocation {
public companion object
}
public companion object
}
| 0 | Kotlin | 0 | 1 | 11f05ad1f977235e3e360cd6f6ada6f26993208e | 7,267 | tl-kotlin | MIT License |
core/src/main/java/com/codeart/filmskuy/core/data/source/remote/response/TvShowListResponse.kt | WahyuSeptiadi | 326,314,895 | false | {"Java": 200862, "Kotlin": 90625} | package com.codeart.filmskuy.core.data.source.remote.response
import com.google.gson.annotations.SerializedName
/**
* Created by wahyu_septiadi on 17, January 2021.
* Visit My GitHub --> https://github.com/WahyuSeptiadi
*/
data class TvShowListResponse(
@SerializedName("results")
val tvShowResultResponse: List<TvShowResultResponse>
) | 1 | null | 1 | 1 | a3931acf762ebec00bdf1783142920ef16dc1471 | 349 | AndroidExpert | MIT License |
core/common/src/main/kotlin/info/kinterest/paging/paging.kt | svd27 | 125,085,657 | false | null | package info.kinterest.paging
import info.kinterest.KIEntity
data class Paging(val offset: Int, val size: Int) {
val next: Paging get() = Paging(offset + size, size)
val prev: Paging get() = Paging(maxOf(0, offset - size), size)
companion object {
val ALL = Paging(0, -1)
}
}
data class Page<out E : KIEntity<K>, out K : Any>(val paging: Paging, val entities: List<E>, val more: Int = 0) {
operator fun get(idx: Int): E? = if (idx < entities.size) entities[idx] else null
inline val size: Int get() = entities.size
} | 0 | Kotlin | 0 | 0 | 19f6d1f1a4c4221dc169e705e95b8ce169f0dc6c | 552 | ki | Apache License 2.0 |
app/shared/bitcoin/fake/src/commonMain/kotlin/build/wallet/bitcoin/lightning/LightningInvoiceParserMock.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.bitcoin.lightning
class LightningInvoiceParserMock(
val validInvoices: MutableSet<String> = mutableSetOf(),
) : LightningInvoiceParser {
override fun parse(invoiceString: String): LightningInvoice? =
when (invoiceString) {
in validInvoices ->
LightningInvoice(
paymentHash = "2097674b02a257fa7fa6b758a88b62cdbae8f856d5b6c3bc36a9bb96501758bc",
payeePubKey = "037cc5f9f1da20ac0d60e83989729a204a33cc2d8e80438969fadf35c1c5f1233b",
isExpired = true,
amountMsat = 1000000u
)
else -> null
}
}
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 588 | bitkey | MIT License |
app/src/main/kotlin/com/atherton/upnext/presentation/features/content/adapter/ModelDetailCrewAdapter.kt | DarrenAtherton49 | 167,204,734 | false | null | package com.atherton.upnext.presentation.features.content.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import com.atherton.upnext.R
import com.atherton.upnext.domain.model.CrewMember
import com.atherton.upnext.presentation.util.glide.GlideRequests
import com.atherton.upnext.presentation.util.image.ImageLoader
import com.atherton.upnext.util.extension.inflateLayout
import kotlinx.android.synthetic.main.item_detail_scrolling_item.*
class ModelDetailCrewAdapter(
private val imageLoader: ImageLoader,
private val glideRequests: GlideRequests,
private val onCrewMemberClickListener: (CrewMember) -> Unit
) : ModelDetailAdapter.ScrollingChildAdapter<CrewMember, ModelDetailScrollingViewHolder>(DiffCallback) {
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModelDetailScrollingViewHolder {
return ModelDetailScrollingViewHolder(parent.inflateLayout(R.layout.item_detail_scrolling_item)).apply {
itemView.setOnClickListener {
onCrewMemberClickListener.invoke(getItem(adapterPosition))
}
}
}
override fun onBindViewHolder(holder: ModelDetailScrollingViewHolder, position: Int) {
val crewMember = getItem(position)
imageLoader.load(
with = glideRequests,
url = crewMember.profilePath,
requestOptions = ImageLoader.searchModelPosterRequestOptions,
into = holder.photoImageView
)
holder.firstRowTextView.text = crewMember.name
holder.secondRowTextView.text = crewMember.job
}
override fun getItemId(position: Int): Long = getItem(position).id
companion object {
private object DiffCallback : DiffUtil.ItemCallback<CrewMember>() {
override fun areItemsTheSame(oldItem: CrewMember, newItem: CrewMember): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: CrewMember, newItem: CrewMember): Boolean {
return oldItem == newItem
}
}
}
}
| 92 | Kotlin | 1 | 3 | d3b011167ee6933b419fb34d448d8e0c1fa4a468 | 2,155 | UpNext | Apache License 2.0 |
plugins/world/player/settings/build.plugin.kts | luna-rs | 41,239,479 | false | null | package world.player.settings
import api.bootstrap.plugin
plugin {
name = "Settings"
description =
"""
A plugin that enables toggling settings on the control tabs.
"""
version = "1.0"
authors += "lare96"
} | 52 | null | 42 | 152 | 876bbe43345953a4f700c670eb999b761cc2a624 | 247 | luna | MIT License |
idea/testData/refactoring/move/java/moveClass/moveTopToInner/moveTopLevelClassToNestedClass/after/specificImport.kt | JakeWharton | 99,388,807 | true | null | import B.C.A as X
fun bar() {
val t: X = X()
} | 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 51 | kotlin | Apache License 2.0 |
libnavigation-core/src/main/java/com/mapbox/navigation/core/trip/model/roadobject/border/CountryBorderCrossing.kt | bikemap | 366,568,071 | true | {"Gradle": 37, "JSON": 30, "Markdown": 14, "Java Properties": 2, "Shell": 5, "Ignore List": 23, "Batchfile": 2, "EditorConfig": 1, "Makefile": 1, "YAML": 3, "XML": 324, "JavaScript": 1, "INI": 33, "Proguard": 16, "Text": 34, "Kotlin": 635, "Java": 6, "CSS": 1, "Python": 4} | package com.mapbox.navigation.core.trip.model.roadobject.border
import com.mapbox.navigation.base.trip.model.roadobject.RoadObject
import com.mapbox.navigation.base.trip.model.roadobject.RoadObjectGeometry
import com.mapbox.navigation.core.trip.model.roadobject.RoadObjectType
/**
* Road object type that provides information about country border crossings on the route.
*
* @param countryBorderCrossingInfo administrative info when crossing the country border
* @see RoadObject
* @see RoadObjectType.COUNTRY_BORDER_CROSSING
*/
class CountryBorderCrossing private constructor(
distanceFromStartOfRoute: Double?,
objectGeometry: RoadObjectGeometry,
val countryBorderCrossingInfo: CountryBorderCrossingInfo,
) : RoadObject(
RoadObjectType.COUNTRY_BORDER_CROSSING,
distanceFromStartOfRoute,
objectGeometry
) {
/**
* Transform this object into a builder to mutate the values.
*/
fun toBuilder(): Builder = Builder(
objectGeometry,
countryBorderCrossingInfo
)
.distanceFromStartOfRoute(distanceFromStartOfRoute)
/**
* Indicates whether some other object is "equal to" this one.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as CountryBorderCrossing
if (countryBorderCrossingInfo != other.countryBorderCrossingInfo) return false
return true
}
/**
* Returns a hash code value for the object.
*/
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (countryBorderCrossingInfo?.hashCode() ?: 0)
return result
}
/**
* Returns a string representation of the object.
*/
override fun toString(): String {
return "CountryBorderCrossingAlert(" +
"countryBorderCrossingInfo=$countryBorderCrossingInfo), ${super.toString()}"
}
/**
* Use to create a new instance.
*
* @see CountryBorderCrossing
*/
class Builder(
private val objectGeometry: RoadObjectGeometry,
private val countryBorderCrossingInfo: CountryBorderCrossingInfo
) {
private var distanceFromStartOfRoute: Double? = null
/**
* Add optional distance from start of route.
* If [distanceFromStartOfRoute] is negative, `null` will be used.
*/
fun distanceFromStartOfRoute(distanceFromStartOfRoute: Double?): Builder = apply {
this.distanceFromStartOfRoute = distanceFromStartOfRoute
}
/**
* Build the object instance.
*/
fun build() =
CountryBorderCrossing(
distanceFromStartOfRoute,
objectGeometry,
countryBorderCrossingInfo
)
}
}
| 0 | Kotlin | 0 | 0 | 5de9c3c9484466b641ab8907ce9ed316598bad56 | 2,904 | mapbox-navigation-android | MIT License |
app/src/main/java/app/akilesh/nex/ui/fragments/HomeFragment.kt | Akilesh-T | 165,995,417 | false | null | package app.akilesh.nex.ui.fragments
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import app.akilesh.nex.Const.Package.AIFloatingTouch
import app.akilesh.nex.Const.Package.FacePlusService
import app.akilesh.nex.Const.Package.GameAssistant
import app.akilesh.nex.Const.Package.Gesture
import app.akilesh.nex.Const.Package.Glance
import app.akilesh.nex.Const.Package.JunkCleaner
import app.akilesh.nex.Const.Package.ScreenRecorder
import app.akilesh.nex.Const.Package.SmartBoost
import app.akilesh.nex.Const.Package.TaskManager
import app.akilesh.nex.Const.Package.TrafficControl
import app.akilesh.nex.Const.Package.appName
import app.akilesh.nex.R
import app.akilesh.nex.databinding.FragmentHomeBinding
import app.akilesh.nex.utils.ShortcutUtil
import app.akilesh.nex.utils.ToastAboveFab
class HomeFragment : Fragment() {
private val shortcutUtil = ShortcutUtil()
private lateinit var binding: FragmentHomeBinding
private fun isCallable(intent: Intent): Boolean {
val activities = requireContext().packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY)
return activities.isNotEmpty()
}
private fun launchApp(packageName: String, className: String){
val intent = Intent(Intent.ACTION_MAIN)
intent.setClassName(packageName, className)
if (isCallable(intent))
startActivity(intent)
else {
ToastAboveFab().show(activity, "${appName[className]} is not installed", 0)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.aiDesc.setOnClickListener { launchApp(AIFloatingTouch[0], AIFloatingTouch[1]) }
binding.fwDesc.setOnClickListener { launchApp(TrafficControl[0], TrafficControl[1]) }
binding.faceUnlock.setOnClickListener { launchApp(FacePlusService[0], FacePlusService[1]) }
binding.gaDesc.setOnClickListener { launchApp(GameAssistant[0], GameAssistant[1]) }
binding.gesDesc.setOnClickListener { launchApp(Gesture[0], Gesture[1]) }
binding.glDesc.setOnClickListener { launchApp(Glance[0], Glance[1]) }
binding.jcDesc.setOnClickListener { launchApp(JunkCleaner[0], JunkCleaner[1]) }
binding.srDesc.setOnClickListener { launchApp(ScreenRecorder[0], ScreenRecorder[1]) }
binding.sbDesc.setOnClickListener { launchApp(SmartBoost[0], SmartBoost[1]) }
binding.tmDesc.setOnClickListener { launchApp(TaskManager[0], TaskManager[1]) }
val intent = Intent(Intent.ACTION_MAIN)
binding.aiDesc.setOnLongClickListener {
intent.setClassName(AIFloatingTouch[0], AIFloatingTouch[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
AIFloatingTouch[0], AIFloatingTouch[1],
appName[AIFloatingTouch[1]].toString(), appName[AIFloatingTouch[1]].toString(),
R.drawable.ic_ai)
true
} else {
ToastAboveFab().show(activity, "${appName[AIFloatingTouch[1]]} is not installed", 0)
false
}
}
binding.fwDesc.setOnLongClickListener {
intent.setClassName(TrafficControl[0], TrafficControl[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
TrafficControl[0], TrafficControl[1],
appName[TrafficControl[1]].toString(), appName[TrafficControl[1]].toString(),
R.drawable.ic_data_usage)
true
} else {
ToastAboveFab().show(activity, "${appName[TrafficControl[1]]} is not installed", 0)
false
}
}
binding.faceUnlock.setOnLongClickListener {
intent.setClassName(FacePlusService[0], FacePlusService[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
FacePlusService[0], FacePlusService[1],
appName[FacePlusService[1]].toString(), appName[FacePlusService[1]].toString(),
R.drawable.ic_face)
true
} else {
ToastAboveFab().show(activity, "${appName[FacePlusService[1]]} is not installed", 0)
false
}
}
binding.gaDesc.setOnLongClickListener {
intent.setClassName(GameAssistant[0], GameAssistant[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
GameAssistant[0], GameAssistant[1],
appName[GameAssistant[1]].toString(), appName[GameAssistant[1]].toString(),
R.drawable.ic_game)
true
} else {
ToastAboveFab().show(activity, "${appName[GameAssistant[1]]} is not installed", 0)
false
}
}
binding.gesDesc.setOnLongClickListener {
intent.setClassName(Gesture[0], Gesture[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
Gesture[0], Gesture[1],
appName[Gesture[1]].toString(), appName[Gesture[1]].toString(),
R.drawable.ic_gesture)
true
} else {
ToastAboveFab().show(activity, "${appName[Gesture[1]]} is not installed", 0)
false
}
}
binding.glDesc.setOnLongClickListener {
intent.setClassName(Glance[0], Glance[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
Glance[0], Glance[1],
appName[Glance[1]].toString(), appName[Glance[1]].toString(),
R.drawable.ic_notifications)
true
} else {
ToastAboveFab().show(activity, "${appName[Glance[1]]} is not installed", 0)
false
}
}
binding.jcDesc.setOnLongClickListener {
intent.setClassName(JunkCleaner[0], JunkCleaner[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
JunkCleaner[0], JunkCleaner[1],
appName[JunkCleaner[1]].toString(), appName[JunkCleaner[1]].toString(),
R.drawable.ic_delete_sweep)
true
} else {
ToastAboveFab().show(activity, "${appName[JunkCleaner[1]]} is not installed", 0)
false
}
}
binding.srDesc.setOnLongClickListener {
intent.setClassName(ScreenRecorder[0], ScreenRecorder[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
ScreenRecorder[0], ScreenRecorder[1],
appName[ScreenRecorder[1]].toString(), appName[ScreenRecorder[1]].toString(),
R.drawable.ic_videocam)
true
} else {
ToastAboveFab().show(activity, "${appName[ScreenRecorder[1]]} is not installed", 0)
false
}
}
binding.sbDesc.setOnLongClickListener {
intent.setClassName(SmartBoost[0], SmartBoost[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
SmartBoost[0], SmartBoost[1],
appName[SmartBoost[1]].toString(), appName[SmartBoost[1]].toString(),
R.drawable.ic_smart_boost)
true
} else {
ToastAboveFab().show(activity, "${appName[SmartBoost[1]]} is not installed", 0)
false
}
}
binding.tmDesc.setOnLongClickListener {
intent.setClassName(TaskManager[0], TaskManager[1])
return@setOnLongClickListener if(isCallable(intent)){
shortcutUtil.createShortcut(requireContext(),
TaskManager[0], TaskManager[1],
appName[TaskManager[1]].toString(), appName[TaskManager[1]].toString(),
R.drawable.ic_tm)
true
} else {
ToastAboveFab().show(activity, "${appName[TaskManager[1]]} is not installed", 0)
false
}
}
}
}
| 2 | Kotlin | 0 | 0 | 6f262e67355a19b7e07b6357ea0c8c96a81a4f10 | 9,163 | NEX-App | Apache License 2.0 |
app/src/main/java/vip/yazilim/p2g/android/util/helper/UIHelper.kt | yazilim-vip | 304,487,567 | false | null | package vip.yazilim.p2g.android.util.helper
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.IBinder
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.androidadvance.topsnackbar.TSnackbar
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import vip.yazilim.p2g.android.constant.ColorCodes.ACCENT_BLUE
import vip.yazilim.p2g.android.constant.ColorCodes.ERROR
import vip.yazilim.p2g.android.constant.ColorCodes.WARN
import kotlin.reflect.KFunction0
/**
* @author mustafaarifsisman - 21.01.2020
* @contact [email protected]
*/
class UIHelper {
companion object {
fun View.showSnackBarInfo(message: String) {
val snack: TSnackbar? = TSnackbar.make(this, message, TSnackbar.LENGTH_SHORT)
val snackView = snack?.view
snackView?.setBackgroundColor(Color.parseColor(ACCENT_BLUE))
snack?.show()
}
fun View.showSnackBarError(message: String) {
val snack: TSnackbar? = TSnackbar.make(this, message, TSnackbar.LENGTH_SHORT)
val snackView = snack?.view
snackView?.setBackgroundColor(Color.parseColor(ERROR))
snack?.show()
}
fun View.showSnackBarWarning(message: String) {
val snack: TSnackbar? = TSnackbar.make(this, message, TSnackbar.LENGTH_SHORT)
val snackView = snack?.view
snackView?.setBackgroundColor(Color.parseColor(WARN))
snack?.show()
}
fun View.showSnackBarPlayerError(message: String) {
val snack: TSnackbar? = TSnackbar.make(this, message, TSnackbar.LENGTH_SHORT)
val snackView = snack?.view
snackView?.setBackgroundColor(Color.parseColor(ERROR))
snack?.show()
}
fun View.showSnackBarErrorIndefinite(message: String) {
val snack: TSnackbar? = TSnackbar.make(this, message, TSnackbar.LENGTH_INDEFINITE)
val snackView = snack?.view
snackView?.setBackgroundColor(Color.parseColor(ERROR))
snack?.show()
}
fun Context.showToastShort(message: String) {
val toast: Toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
toast.setGravity(Gravity.BOTTOM, 0, 175)
toast.show()
}
fun Context.showToastLong(message: String) {
val toast: Toast = Toast.makeText(this, message, Toast.LENGTH_LONG)
toast.setGravity(Gravity.BOTTOM, 0, 175)
toast.show()
}
fun Context.closeKeyboard() {
val inputMethodManager =
this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
fun Context.closeKeyboardSoft(viewBinder: IBinder) {
val inputMethodManager =
this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(viewBinder, 0)
}
fun Context.dpFromPx(px: Float): Float {
return px / this.resources.displayMetrics.density
}
fun Context.pxFromDp(dp: Float): Float {
return dp * this.resources.displayMetrics.density
}
@Deprecated("Causes crash if app was backgrounded and tries re-login")
fun Activity.showErrorDialog(
message: String,
kFunction0: KFunction0<Unit>
) {
if (!this.isFinishing) {
val dialogBuilder = MaterialAlertDialogBuilder(this)
.setMessage(message)
.setPositiveButton("OK") { dialog, _ ->
dialog.cancel()
}
val alert = dialogBuilder.create()
alert.setTitle("Error")
alert.show()
alert.setOnCancelListener { kFunction0() }
}
}
@Deprecated("Causes crash if app was backgrounded and tries re-login")
fun Activity.showErrorDialog(message: String) {
if (!this.isFinishing) {
val dialogBuilder = MaterialAlertDialogBuilder(this)
.setMessage(message)
.setPositiveButton("OK") { dialog, _ ->
dialog.cancel()
}
val alert = dialogBuilder.create()
alert.setTitle("Error")
alert.show()
}
}
}
}
| 1 | null | 1 | 1 | d52cc417e46ee9dab9da3b72de9cb3776043bf46 | 4,674 | p2g-android | Apache License 2.0 |
app/src/main/java/com/metropolia/eatthefrog/notification/NotificationChannel.kt | metropolia-mobile-project | 558,353,904 | false | {"Kotlin": 267772} | package com.metropolia.eatthefrog.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import com.metropolia.eatthefrog.constants.CHANNEL_ID
// Taking context as a parameter as the function is outside of the MainActivity
// Otherwise cannot use the getSystemService()
fun createNotificationChannel(context: Context) {
val channel = NotificationChannel(
CHANNEL_ID,
"ChannelName",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Some description"
}
// Register the channel with the system
val notificationManager =
context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
} | 4 | Kotlin | 2 | 1 | 2ae0deeb9527471bd63871a5c166b155b5147f38 | 844 | EatTheFrog | MIT License |
api/src/main/kotlin/com/example/in/common/filter/RateLimitFilter.kt | PARKPARKWOO | 737,782,254 | false | {"Kotlin": 358060, "Dockerfile": 124} | package com.example.`in`.common.filter
import com.example.`in`.common.annotation.PublicEndPoint
import com.example.`in`.common.annotation.RateLimit
import com.example.`in`.common.config.RateLimiter
import com.example.`in`.common.interceptor.getBearerTokenFromHeader
import io.github.bucket4j.BandwidthBuilder
import io.github.bucket4j.Bucket
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpStatus.TOO_MANY_REQUESTS
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerMapping
import org.springframework.web.servlet.support.RequestContextUtils
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
@Component
class RateLimitFilter : OncePerRequestFilter() {
companion object {
// interval
val userQuotaBucket: ConcurrentHashMap<String, Bucket> = ConcurrentHashMap()
/**
* 1회 요청당 약 2000~3000 Token 사용 (운동 입력 안했을때)
* gemini flash 기준 분당 15 요청, 100만 토큰 허용
* draft 하게 계산 했을때 token quota 를 초과하진 않음
* 추후 Batch 로 토큰 계산 및 quota 설정 필요
*/
// greedy
val aiQuotaBucket: ConcurrentHashMap<String, Bucket> = ConcurrentHashMap()
const val AI_API = "ai"
const val TOO_MANY_REQUEST = "Too many requests"
const val AI_QUOTA = 15L
const val AI_REFILL_TOKEN = 1L
const val AI_REFILL_INTERVAL = 1L
val AI_REFILL_UNIT = TimeUnit.MINUTES
}
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain,
) {
val handlerMethod = getHandlerMethod(request)
handlerMethod?.let { handler ->
val annotation = handler.getMethodAnnotation(RateLimit::class.java)
?: return filterChain.doFilter(request, response)
val path = request.servletPath
val key =
if (handler.hasMethodAnnotation(PublicEndPoint::class.java)) {
path
} else {
request.getBearerTokenFromHeader()
}
val rateLimiter = getRateLimiter(annotation, key)
val userBucket = userQuotaBucket.computeIfAbsent(key) { getIntervalBucket(rateLimiter) }
if (path.contains(AI_API)) {
val aiBucket = aiQuotaBucket.computeIfAbsent(path) { getGreedyBucket() }
val aiProbe = aiBucket.tryConsumeAndReturnRemaining(1)
if (!aiProbe.isConsumed) {
response.status = TOO_MANY_REQUESTS.value()
response.writer.write(TOO_MANY_REQUEST)
return
}
}
val userProbe = userBucket.tryConsumeAndReturnRemaining(1)
if (userProbe.isConsumed) {
filterChain.doFilter(request, response)
} else {
response.status = TOO_MANY_REQUESTS.value()
response.writer.write(TOO_MANY_REQUEST)
}
} ?: return filterChain.doFilter(request, response)
}
private fun getHandlerMethod(request: HttpServletRequest): HandlerMethod? {
val handlerMappingBeans: Map<String, HandlerMapping> =
RequestContextUtils.findWebApplicationContext(request)?.getBeansOfType(
HandlerMapping::class.java,
) ?: return null
for (handlerMapping in handlerMappingBeans.values) {
runCatching {
val handler = handlerMapping.getHandler(request)?.handler
if (handler is HandlerMethod) {
return handler
}
}.getOrNull()
}
return null
}
private fun getRateLimiter(
rateLimit: RateLimit,
key: String,
): RateLimiter = RateLimiter.custom()
.key(key)
.timeUnit(rateLimit.timeUnit)
.quota(rateLimit.quota)
.refillInterval(rateLimit.refillInterval)
.refillTokens(rateLimit.refillTokens)
.build()
private fun getIntervalBucket(rateLimiter: RateLimiter): Bucket = Bucket.builder()
.addLimit(
BandwidthBuilder.builder()
.capacity(rateLimiter.quota)
.refillIntervally(
rateLimiter.refillTokens,
Duration.of(rateLimiter.refillInterval, rateLimiter.timeUnit.toChronoUnit()),
)
.build(),
).build()
private fun getGreedyBucket(): Bucket = Bucket.builder()
.addLimit(
BandwidthBuilder.builder()
.capacity(AI_QUOTA)
.refillGreedy(
AI_REFILL_TOKEN,
Duration.of(AI_REFILL_INTERVAL, AI_REFILL_UNIT.toChronoUnit()),
)
.build(),
).build()
}
| 15 | Kotlin | 0 | 0 | fbf1272971e226519cd9919011fff785650994d3 | 5,084 | barbellrobot-backend | Apache License 2.0 |
app/src/main/java/com/example/recycleview/pojo/BaseResponse.kt | sidkiamri | 733,158,336 | false | {"Kotlin": 113149} | package com.example.recycleview.pojo
sealed class BaseResponse<out T> {
data class Success<out T>(val data: T? = null) : BaseResponse<T>()
data class Loading(val nothing: Nothing?=null) : BaseResponse<Nothing>()
data class Error(val msg: String?) : BaseResponse<Nothing>()
} | 0 | Kotlin | 0 | 0 | 9bf93bd95847eb157aa8d9df6edea0ef9e54c3ca | 287 | SearchAndRecycle-Android | MIT License |
app/src/main/java/com/zawzaw/savethelibrary/viewmodel/AuthorViewModel.kt | zawzaww | 115,300,746 | false | null | package com.zawzaw.savethelibrary.viewmodel
import android.arch.lifecycle.ViewModel
/**
* Created by zawzaw on 21/03/18.
*/
class AuthorViewModel : ViewModel()
| 1 | null | 1 | 1 | 05c1e1f1ae8bb47c29adede4d427d26cbc61350b | 165 | savethelibrary | Apache License 2.0 |
app/src/test/java/com/example/currencyexchanger/domain/CommissionFeeManagerTest.kt | tmaciulis22 | 579,377,902 | false | {"Kotlin": 57122} | package com.example.currencyexchanger.domain
import android.content.SharedPreferences
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Test
class CommissionFeeManagerTest {
private val amountToTest = 500.0
private val exchangeRateEurToTest = 2.45
@Test
fun test_calculateFee_zeroFee() {
val expectedFee = 0.0
val mockPrefs = mockk<SharedPreferences>()
every {
mockPrefs.getLong(CommissionFeeManager.TOTAL_CONVERSIONS, 0)
} returns 0
every {
mockPrefs.getLong(CommissionFeeManager.LAST_CONVERSION, any())
} returns System.currentTimeMillis()
every {
mockPrefs.getLong(CommissionFeeManager.CONVERSIONS_TODAY, 0)
} returns 0
val manager = CommissionFeeManager(mockPrefs)
val actualFee = manager.calculateFee(amountToTest, exchangeRateEurToTest)
assertEquals(actualFee, expectedFee, 0.0)
}
@Test
fun test_calculateFee_noFreeConversions() {
val expectedFee = amountToTest * CommissionFeeManager.PERCENTAGE
val mockPrefs = mockk<SharedPreferences>()
every {
mockPrefs.getLong(CommissionFeeManager.TOTAL_CONVERSIONS, 0)
} returns 6
every {
mockPrefs.getLong(CommissionFeeManager.LAST_CONVERSION, any())
} returns System.currentTimeMillis()
every {
mockPrefs.getLong(CommissionFeeManager.CONVERSIONS_TODAY, 0)
} returns 0
val manager = CommissionFeeManager(mockPrefs)
val actualFee = manager.calculateFee(amountToTest, exchangeRateEurToTest)
assertEquals(actualFee, expectedFee, 0.0)
}
@Test
fun test_calculateFee_exceededDailyConversionsThreshold() {
val expectedFee =
amountToTest * CommissionFeeManager.PERCENTAGE_AFTER_THRESHOLD + CommissionFeeManager.EUR_EQUIVALENT * exchangeRateEurToTest
val mockPrefs = mockk<SharedPreferences>()
every {
mockPrefs.getLong(CommissionFeeManager.TOTAL_CONVERSIONS, 0)
} returns 16
every {
mockPrefs.getLong(CommissionFeeManager.LAST_CONVERSION, any())
} returns System.currentTimeMillis()
every {
mockPrefs.getLong(CommissionFeeManager.CONVERSIONS_TODAY, 0)
} returns 16
val manager = CommissionFeeManager(mockPrefs)
val actualFee = manager.calculateFee(amountToTest, exchangeRateEurToTest)
assertEquals(actualFee, expectedFee, 0.0)
}
}
| 0 | Kotlin | 0 | 0 | 82ab7b57aea5c6852d31c0f18e5e05a1bb4fbb73 | 2,557 | currency-exchanger | MIT License |
libs/shapesearcher/src/main/kotlin/mono/shapesearcher/ShapeZoneAddressManager.kt | tuanchauict | 325,686,408 | false | null | package mono.shapesearcher
import mono.graphics.bitmap.MonoBitmap
import mono.shape.shape.AbstractShape
/**
* A model class to convert a shape to addresses which the shape have pixels on.
* This class also cache the addresses belong to the shape along with its version.
*/
internal class ShapeZoneAddressManager(private val getBitmap: (AbstractShape) -> MonoBitmap?) {
private val idToZoneAddressMap: MutableMap<String, VersionizedZoneAddresses> = mutableMapOf()
fun getZoneAddresses(shape: AbstractShape): Set<ZoneAddress> {
val cachedAddresses = getCachedAddresses(shape)
if (cachedAddresses != null) {
return cachedAddresses
}
val bitmap = getBitmap(shape)
if (bitmap == null) {
idToZoneAddressMap.remove(shape.id)
return emptySet()
}
val position = shape.bound.position
val addresses = mutableSetOf<ZoneAddress>()
for (ir in bitmap.matrix.indices) {
bitmap.matrix[ir].forEachIndex { ic, _ ->
val row = ir + position.row
val col = ic + position.column
val address = ZoneAddressFactory.toAddress(row, col)
addresses.add(address)
}
}
val versionizedZoneAddresses = VersionizedZoneAddresses(shape.versionCode, addresses)
idToZoneAddressMap[shape.id] = versionizedZoneAddresses
return versionizedZoneAddresses.addresses
}
private fun getCachedAddresses(shape: AbstractShape): Set<ZoneAddress>? =
idToZoneAddressMap[shape.id]?.takeIf { it.version == shape.versionCode }?.addresses
private class VersionizedZoneAddresses(val version: Int, val addresses: Set<ZoneAddress>)
}
| 15 | Kotlin | 9 | 91 | 21cef26b45c984eee31ea2c3ba769dfe5eddd92e | 1,736 | MonoSketch | Apache License 2.0 |
src/main/kotlin/dev/shtanko/kotlinlang/inline/Inline.kt | ashtanko | 203,993,092 | false | {"Kotlin": 7429739, "Shell": 1168, "Makefile": 1144} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.kotlinlang.inline
inline fun <T> Collection<T>.each(block: (T) -> Unit) {
for (e in this) block(e)
}
inline fun <reified T> membersOf() = T::class.members.map { it.name }
| 6 | Kotlin | 0 | 19 | c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba | 789 | kotlab | Apache License 2.0 |
app/src/main/java/xyz/harmonyapp/olympusblog/fragments/auth/AuthNavHostFragment.kt | sentrionic | 351,882,310 | false | null | package xyz.harmonyapp.olympusblog.fragments.auth
import android.content.Context
import android.os.Bundle
import androidx.annotation.NavigationRes
import androidx.navigation.fragment.NavHostFragment
import xyz.harmonyapp.olympusblog.ui.auth.AuthActivity
class AuthNavHostFragment : NavHostFragment() {
override fun onAttach(context: Context) {
childFragmentManager.fragmentFactory =
(activity as AuthActivity).fragmentFactory
super.onAttach(context)
}
companion object {
const val KEY_GRAPH_ID = "android-support-nav:fragment:graphId"
@JvmStatic
fun create(
@NavigationRes graphId: Int = 0
): AuthNavHostFragment {
var bundle: Bundle? = null
if (graphId != 0) {
bundle = Bundle()
bundle.putInt(KEY_GRAPH_ID, graphId)
}
val result = AuthNavHostFragment()
if (bundle != null) {
result.arguments = bundle
}
return result
}
}
} | 0 | Kotlin | 0 | 0 | 3b784bf9dd60f6cc6889813f2e2932fa3a9b211d | 1,057 | OlympusAndroid | MIT License |
the-vault/src/main/kotlin/org/jesperancinha/smtd/the/vault/TheVaultRunner.kt | jesperancinha | 369,597,921 | false | {"Java": 98494, "Kotlin": 86678, "Makefile": 668, "Shell": 192, "Dockerfile": 184} | package org.jesperancinha.smtd.the.vault
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
@SpringBootApplication
@EnableWebSecurity
open class TheVaultRunner
fun main(args: Array<String>) {
SpringApplication.run(TheVaultRunner::class.java, *args)
} | 2 | Kotlin | 0 | 3 | fdca0dc340690048156aa78862ad0cf0273076b7 | 414 | jeorg-spring-master-test-drives | Apache License 2.0 |
app/src/main/java/in/kaligotla/datastructures/ui/previews/ComposePreviews.kt | deepakkaligotla | 722,852,369 | false | {"Kotlin": 286298} | package `in`.kaligotla.datastructures.ui.previews
import android.content.res.Configuration
import androidx.compose.ui.tooling.preview.Preview
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
annotation class DarkPreview
@Preview
@DarkPreview
annotation class AllPreviews
| 0 | Kotlin | 0 | 0 | 3425e0a1b79645db86b77bee7a1c9212522e2413 | 277 | android_datastructures_algo | The Unlicense |
core/src/main/kotlin/org/eduardoleolim/organizadorpec660/core/role/domain/RoleRepository.kt | eduardoleolim | 673,214,659 | false | {"Kotlin": 832635} | package org.eduardoleolim.organizadorpec660.core.role.domain
import org.eduardoleolim.organizadorpec660.core.shared.domain.criteria.Criteria
interface RoleRepository {
fun matching(criteria: Criteria): List<Role>
}
| 0 | Kotlin | 0 | 0 | 03b792ab9ac76a05b367e5166ef2a53a38a5a38d | 221 | organizador-pec-6-60 | Creative Commons Attribution 4.0 International |
feature-staking-api/src/main/java/com/dfinn/wallet/feature_staking_api/domain/model/BlockNumber.kt | finn-exchange | 500,972,990 | false | null | package com.dfinn.wallet.feature_staking_api.domain.model
import java.math.BigInteger
typealias BlockNumber = BigInteger
| 0 | Kotlin | 0 | 0 | 6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d | 123 | dfinn-android-wallet | Apache License 2.0 |
app/src/main/java/com/kirakishou/photoexchange/di/module/SchedulerProviderModule.kt | K1rakishou | 109,590,033 | false | null | package com.kirakishou.photoexchange.di.module
import com.kirakishou.photoexchange.helper.concurrency.rx.scheduler.NormalSchedulers
import com.kirakishou.photoexchange.helper.concurrency.rx.scheduler.SchedulerProvider
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Created by kirakishou on 3/3/2018.
*/
@Module
open class SchedulerProviderModule {
@Singleton
@Provides
open fun provideSchedulers(): SchedulerProvider {
return NormalSchedulers()
}
} | 0 | Kotlin | 1 | 4 | 15f67029376a98353a01b5523dfb42d183a26bf2 | 498 | photoexchange-android | Do What The F*ck You Want To Public License |
library/src/main/kotlin/com/glovoapp/versioning/SemanticVersion.kt | Glovo | 191,721,113 | false | {"Kotlin": 51750} | package com.glovoapp.versioning;
data class SemanticVersion(
val major: Int,
val minor: Int? = null,
val patch: Int? = null,
val preRelease: String? = null,
val build: String? = null
) : Comparable<SemanticVersion> {
enum class Increment {
MAJOR, MINOR, PATCH;
operator fun times(amount: Int) = this to amount
}
companion object {
// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
private val VERSION_PATTERN =
"(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*)(?:\\.(0|[1-9]\\d*))?)?(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?".toRegex(
RegexOption.IGNORE_CASE
)
fun parse(source: String) = with(VERSION_PATTERN.matchEntire(source)) {
if (this == null) {
throw IllegalArgumentException("Unsupported format for semantic version: $source")
}
SemanticVersion(
major = groupValues[1].toInt(),
minor = groupValues[2].toIntOrNull(),
patch = groupValues[3].toIntOrNull(),
preRelease = groupValues[4].takeIf { it.isNotBlank() },
build = groupValues[5].takeIf { it.isNotBlank() }
)
}
fun String.toVersion() = parse(this)
}
val preReleaseIdentifiers by lazy { preRelease?.split('.') ?: emptyList() }
val buildIdentifiers by lazy { build?.split('.') ?: emptyList() }
operator fun plus(increment: Increment) = plus(increment * 1)
operator fun plus(increment: Pair<Increment, Int>) = when (increment.first) {
Increment.MAJOR -> copy(major = major + increment.second, minor = 0, patch = 0)
Increment.MINOR -> copy(minor = (minor ?: 0) + increment.second, patch = 0)
Increment.PATCH -> copy(patch = (patch ?: 0) + increment.second)
}
// https://semver.org/#spec-item-11
override fun compareTo(other: SemanticVersion) = when {
major != other.major -> major.compareTo(other.major)
minor != other.minor -> minor.compareTo(other.minor)
patch != other.patch -> patch.compareTo(other.patch)
preRelease == null -> if (other.preRelease == null) 0 else 1
other.preRelease == null -> -1
else -> preReleaseIdentifiers.compareTo(other.preReleaseIdentifiers)
}
private fun Int?.compareTo(other: Int?) = when(this) {
null -> if (other == null) 0 else -1
else -> if (other == null) 1 else compareTo(other)
}
private tailrec fun List<String>.compareTo(other: List<String>, index: Int = 0): Int = when {
index >= size -> if (index >= other.size) 0 else -1
index >= other.size -> 1
else -> {
val thisValue = this[index]
val otherValue = other[index]
val thisNumber = thisValue.toIntOrNull()
val otherNumber = otherValue.toIntOrNull()
val compare = when {
thisNumber == null -> if (otherNumber != null) 1 else thisValue.compareTo(otherValue)
otherNumber == null -> -1
else -> thisNumber.compareTo(otherNumber)
}
if (compare != 0) compare else compareTo(other, index + 1)
}
}
private fun String?.prefix(prefix: String) =
if (isNullOrBlank()) "" else prefix + this
override fun toString() = "$major${minor.versionStr}${patch.versionStr}${preRelease.prefix("-")}${build.prefix("+")}"
private inline val Int?.versionStr
get() = when (this) {
null -> ""
else -> ".$this"
}
}
| 2 | Kotlin | 3 | 2 | cdc10255d06506cbde247050f2653f03792b45e8 | 3,726 | gradle-versioning-plugin | BSD-2-Clause Plus Patent License |
src/main/java/entityManager/Utils.kt | Nicholas-Vo | 570,954,285 | false | {"Kotlin": 16949, "Java": 14746} | package entityManager
import org.apache.commons.lang.StringUtils
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.command.CommandSender
import org.bukkit.entity.EntityType
import java.util.*
object Utils {
@JvmStatic
fun locationToString(l: Location): String {
return "x" + l.blockX + ", y" + l.blockY + ", z" + l.blockZ
}
@JvmStatic
fun formatEntity(name: String): String {
return StringUtils.capitalize(name.lowercase(Locale.getDefault()).replace("_", " "))
}
@JvmStatic
fun worldToString(w: World): String {
val name = w.name
if (name == "world") return "overworld"
if (name == "world_nether") return "nether"
return if (name == "world_the_end") "end" else "null"
}
@JvmStatic
fun parseNumber(sender: CommandSender?, number: String, error: String?): Int {
var result = -1
try {
result = number.toInt()
} catch (e: NumberFormatException) {
EntityManager.instance.msg(sender!!, error!!)
}
return result
}
fun count(e: EntityType?, map: MutableMap<EntityType?, Int>) {
map.putIfAbsent(e, 0)
map[e] = map[e]!! + 1
}
} | 0 | Kotlin | 0 | 0 | 0b13c6a6e28b7ef9097f017806d5d8a0ddd23cb5 | 1,226 | EntityManagerKotlin | MIT License |
app/src/main/kotlin/app/newproj/lbrytv/data/repo/SettingsRepository.kt | linimin | 434,503,024 | false | null | /*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package app.newproj.lbrytv.data.repo
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import app.newproj.lbrytv.data.datasource.SettingPagingSource
import app.newproj.lbrytv.data.dto.Setting
import app.newproj.lbrytv.di.SmallPageSize
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Provider
@OptIn(ExperimentalPagingApi::class)
class SettingsRepository @Inject constructor(
private val settingPagingSourceProvider: Provider<SettingPagingSource>,
@SmallPageSize private val pagingConfig: PagingConfig,
) {
fun settings(): Flow<PagingData<Setting>> = Pager(
config = pagingConfig,
pagingSourceFactory = settingPagingSourceProvider::get
).flow
}
| 7 | Kotlin | 3 | 23 | 75bed7e7bae0b1ddaa2b5356b82dbec62c25776e | 1,937 | lbry-androidtv | MIT License |
app/src/main/java/com/franz/easymusicplayer/adapter/RankSelectAdapter.kt | FranzLiszt-1847 | 540,248,051 | false | null | package com.franz.easymusicplayer.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.franz.easymusicplayer.R
import com.franz.easymusicplayer.base.BaseApplication
import com.franz.easymusicplayer.bean.*
import com.franz.easymusicplayer.widgets.GlideRoundTransform
class RankSelectAdapter( beanList: List<SheetPlayBean>) : RecyclerView.Adapter<RankSelectAdapter.ViewHolder>(), View.OnClickListener {
private var beanList: List<SheetPlayBean>
private lateinit var listener: OnSelectRankClickListener
init {
this.beanList = beanList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_rank_sub_normal, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: RankSelectAdapter.ViewHolder, position: Int) {
val bean = beanList[position]
holder.time.text = bean.updateFrequency.toString()
Glide.with(holder.cover)
.asDrawable()
.load(bean.coverImgUrl)
.transform(GlideRoundTransform(BaseApplication.context,10))
.placeholder(R.drawable.icon_default_songs)
.dontAnimate()
.into(holder.cover)
holder.layout.setOnClickListener(this)
holder.layout.tag = position
}
override fun getItemCount(): Int {
return beanList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var time: TextView
var layout: ConstraintLayout
var cover: ImageView
init {
time = itemView.findViewById(R.id.selectRankTime)
layout = itemView.findViewById(R.id.selectRankLayout)
cover = itemView.findViewById(R.id.selectRankCover)
}
}
fun setItemClickListener(listener: OnSelectRankClickListener) {
this.listener = listener
}
interface OnSelectRankClickListener {
fun onClickListener(bean:SheetPlayBean)
}
override fun onClick(v: View?) {
listener?.let {
val tag: Int = v?.tag as Int
it.onClickListener( beanList[tag])
}
}
} | 0 | Kotlin | 2 | 6 | 4344b1759f6648f5166d6ae8fb91ccddc8214184 | 2,459 | EasyMusic | Apache License 2.0 |
mesh-exam/data/src/main/java/io/flaterlab/meshexam/data/worker/entity/AnswerJson.kt | chorobaev | 434,863,301 | false | {"Kotlin": 467494, "Java": 1951} | package io.flaterlab.meshexam.data.worker.entity
data class AnswerJson(
val answer: String,
val isCorrect: Boolean,
val orderNumber: Int
) | 0 | Kotlin | 0 | 2 | 364c4fcb70a461fc02d2a5ef2590ad5f8975aab5 | 151 | mesh-exam | MIT License |
modules/coreui/src/main/kotlin/kekmech/ru/coreui/banner/BannerExt.kt | tonykolomeytsev | 203,239,594 | false | null | package kekmech.ru.coreui.banner
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import kekmech.ru.coreui.R
fun Fragment.showBanner(@StringRes resId: Int, @ColorRes color: Int = R.color.colorRed) =
showBanner(getString(resId), color)
fun Fragment.showBanner(text: String, @ColorRes color: Int = R.color.colorRed) {
findBanner()?.let { container ->
val bannerBackgroundColor = ContextCompat.getColor(requireContext(), color)
container.show(Banner(text, bannerBackgroundColor))
}
}
private fun Fragment.findNetworkStateBanner(): NetworkStateBannerContainer? =
requireActivity().findViewById(R.id.networkStateBannerContainer)
fun Fragment.findBanner(): BannerContainer? =
requireActivity().findViewById<BannerContainer>(R.id.bannerContainer)
?.takeIf { findNetworkStateBanner()?.isVisible != true }
| 9 | Kotlin | 4 | 21 | 4ad7b2fe62efb956dc7f8255d35436695643d229 | 951 | mpeiapp | MIT License |
src/test/kotlin/com/gitTraining/RecursiveFibbonaciTest.kt | PriyankaSP4 | 379,626,494 | true | {"Kotlin": 5996} | package com.gitTraining
import org.assertj.core.api.Java6Assertions.assertThat
import org.junit.Test
class RecursiveFibbonaciTest {
@Test
fun recursive_fibbonaci_works_for_small_numbers() {
val inputs = listOf(1,2,3,4,5,6,7,8,9)
val expectedOutputs = listOf(1,1,2,3,5,8,13,21,34)
for ((input, expectedOutput) in inputs.zip(expectedOutputs)) {
assertThat(computeFibbonaciNumber(input, true)).isEqualTo(expectedOutput)
}
}
}
| 0 | Kotlin | 0 | 0 | bf75d1159bd73570d9acbcd8b0bbf4e6074dfee9 | 482 | git-training | MIT License |
reflekt-plugin/src/test/resources/org/jetbrains/reflekt/plugin/compiler/code-gen/general-standalone-project-calling/reflekt/objects/objects-6.kt | JetBrains-Research | 293,503,377 | false | {"Kotlin": 397259, "Java": 35379} | // FILE: TestCase.kt
import org.jetbrains.reflekt.Reflekt
import org.jetbrains.reflekt.test.helpers.checkObjectsCallResult
import org.jetbrains.reflekt.test.common.*
fun box(): String = checkObjectsCallResult(
{ Reflekt.objects().withSuperTypes().toList() },
emptyList(),
)
| 13 | Kotlin | 9 | 325 | ae53618880e5eb610ddeb2792d63208eade951a8 | 283 | reflekt | Apache License 2.0 |
app/src/main/java/com/payamgr/qrcodemaker/data/model/state/ShowQrCodeState.kt | PayamGerackoohi | 737,574,318 | false | {"Kotlin": 120089, "C++": 90697, "CMake": 2467, "Shell": 271} | package com.payamgr.qrcodemaker.data.model.state
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.PersistState
import com.payamgr.qrcodemaker.data.model.Content
import com.payamgr.qrcodemaker.data.model.ErrorCorrectionCodeLevel
import com.payamgr.qrcodemaker.data.model.QrCode
data class ShowQrCodeState(
val currentContent: Content? = null,
val qrCode: QrCode = QrCode(size = 0, data = booleanArrayOf()),
@PersistState val ecc: ErrorCorrectionCodeLevel = ErrorCorrectionCodeLevel.Medium,
) : MavericksState
| 0 | Kotlin | 0 | 0 | d73d13c17f106bfcc44a1f88f8dca7568f993a00 | 534 | QRCodeMaker | MIT License |
kactoos-jvm/src/main/kotlin/nnl/rocks/kactoos/time/OffsetDateTimeAsText.kt | neonailol | 117,650,092 | false | null | package nnl.rocks.kactoos.time
import nnl.rocks.kactoos.KScalar
import nnl.rocks.kactoos.Text
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
/**
* Formatter for [OffsetDateTime] instances.
*
* @since 0.3
*/
class OffsetDateTimeAsText constructor(
private val formatted: KScalar<String>
) : Text {
constructor(
date: OffsetDateTime,
formatter: DateTimeFormatter = Iso().invoke()
) : this(
{ formatter.format(date) }
)
/**
* Formats the date using the provided format string using the provided
* locale.
* @param date The date to format.
* @param format The format string to use.
* @param locale The locale to use.
*/
constructor(
date: OffsetDateTime,
format: String,
locale: Locale = Locale.getDefault(Locale.Category.FORMAT)
) : this(date, DateTimeFormatter.ofPattern(format, locale))
override fun asString(): String {
return this.formatted()
}
}
| 0 | Kotlin | 1 | 19 | ce10c0bc7e6e65076b8ace90770b9f7648facf4a | 1,030 | kactoos | MIT License |
src/main/java/challenges/mostafa/_5_queue/P5MaxValueOfEquation.kt | ShabanKamell | 342,007,920 | false | {"Kotlin": 737194} | package challenges.mostafa._5_queue
/**
You are given an array points containing the coordinates of points on a 2D plane, sorted by
the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length.
You are also given an integer k.
Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k
and 1 <= i < j <= points.length.
It is guaranteed that there exists at least one pair of points that satisfy
the constraint |xi - xj| <= k.
Example 1:
Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate
the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition
and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
Example 2:
Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values,
and give the value of 0 + 0 + |0 - 3| = 3.
Constraints:
2 <= points.length <= 10^5
points[i].length == 2
-108 <= xi, yi <= 10^8
0 <= k <= 2 * 10^8
xi < xj for all 1 <= i < j <= points.length
xi form a strictly increasing sequence.
https://leetcode.com/problems/max-value-of-equation/description/
*/
internal object P5MaxValueOfEquation {
private fun findMaxValueOfEquation(points: Array<IntArray>, k: Int): Int {
val deque = ArrayDeque<Pair<Int, Int>>()
var maxValue = Int.MIN_VALUE
for ((x, y) in points) {
// Remove the points from the front of the deque whose x-value difference with
// the current point is greater than k. This ensures that we only consider
// points within the constraint |xi - xj| <= k.
while (deque.isNotEmpty() && x - deque.first().first > k) {
deque.removeFirst()
}
// Update the maximum value if the deque is not empty
if (deque.isNotEmpty())
maxValue = maxOf(maxValue, y - deque.first().first + x + deque.first().second)
// Remove points from the deque whose y-value minus x-value is less than the current point's y-value minus x-value
while (deque.isNotEmpty() && deque.last().second - deque.last().first < y - x) {
deque.removeLast()
}
deque.addLast(x to y)
}
return maxValue
}
@JvmStatic
fun main(args: Array<String>) {
val points = arrayOf(
intArrayOf(1, 3),
intArrayOf(2, 0),
intArrayOf(5, 10),
intArrayOf(6, -10)
)
val k = 1
val maxValue = findMaxValueOfEquation(points, k)
println("Maximum value of the equation: $maxValue")
val points2 = arrayOf(
intArrayOf(0, 0),
intArrayOf(3, 0),
intArrayOf(9, 2)
)
val k2 = 3
val maxValue2 = findMaxValueOfEquation(points2, k2)
println("Maximum value of the equation: $maxValue2")
}
} | 0 | Kotlin | 0 | 0 | 9541206dcee97365f43f6c0d935f31d9cfb7e0ae | 3,095 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/models/hmpps/OffenceDto.kt | ministryofjustice | 572,524,532 | false | {"Kotlin": 746805, "Python": 32511, "Shell": 13474, "Dockerfile": 1204, "Makefile": 684} | package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps
data class OffenceDto(
val offenceCode: Number? = null,
val offenceRule: OffenceRuleDto? = null,
)
| 0 | Kotlin | 1 | 2 | d77c78a1644ae597e429cc50b2c1717b84ba68e9 | 174 | hmpps-integration-api | MIT License |
data-export/data-export-application/src/main/kotlin/eu/tib/orkg/prototype/export/predicates/domain/ExportPredicateIdToLabelService.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2627763, "Cypher": 216189, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package eu.tib.orkg.prototype.export.predicates.domain
import com.fasterxml.jackson.databind.ObjectMapper
import eu.tib.orkg.prototype.export.predicates.api.ExportPredicateIdToLabelUseCase
import eu.tib.orkg.prototype.export.shared.domain.FileExportService
import eu.tib.orkg.prototype.statements.spi.PredicateRepository
import eu.tib.orkg.prototype.statements.spi.forEach
import java.io.Writer
import org.springframework.stereotype.Service
private const val DEFAULT_FILE_NAME = "predicate-ids_to_label.json"
@Service
class ExportPredicateIdToLabelService(
private val predicateRepository: PredicateRepository,
private val fileExportService: FileExportService,
private val objectMapper: ObjectMapper
) : ExportPredicateIdToLabelUseCase {
override fun export(writer: Writer) {
objectMapper.createGenerator(writer).use { generator ->
generator.writeStartObject()
predicateRepository.forEach({ predicate ->
generator.writeStringField(predicate.id.value, predicate.label)
}, generator::flush)
generator.writeEndObject()
}
}
override fun export(path: String?) =
fileExportService.writeToFile(path, DEFAULT_FILE_NAME) { export(it) }
}
| 0 | Kotlin | 2 | 5 | 31ef68d87499cff09551febb72ae3d38bfbccb98 | 1,246 | orkg-backend | MIT License |
android/app/src/main/java/com/example/facultiesapp/department/DepartmentInfoViewModel.kt | agakas | 589,229,718 | false | null | package com.example.facultiesapp.department
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.facultiesapp.models.Department
import com.example.facultiesapp.repository.DepartmentRepository
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class DepartmentInfoViewModel: ViewModel() {
val departmentLiveData = MutableLiveData<Department?>()
private val departmentRepository = DepartmentRepository.getInstance()
val defaultErrorHandler: CoroutineContext = CoroutineExceptionHandler { _, error ->
Log.e(
null,
error.message,
error
)
}
fun getDepartment(id: Int) {
viewModelScope.launch(defaultErrorHandler) {
departmentLiveData.postValue(departmentRepository.getDepartmentById(id))
}
}
fun saveDepartment(newDepartment: Department) {
viewModelScope.launch(defaultErrorHandler) {
departmentLiveData.value?.let {oldDepartment ->
departmentRepository.update(newDepartment.copy(id = oldDepartment.id))
} ?: departmentRepository.add(newDepartment)
}
}
} | 0 | Kotlin | 0 | 0 | 96b24fcd0df56b308e8767b8f2434e61f8086e0a | 1,305 | Faculties | MIT License |
app/src/main/java/com/thiosin/cryptoinfo/ui/list/ListFragment.kt | khongi | 246,070,401 | false | null | package com.thiosin.cryptoinfo.ui.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import co.zsmb.rainbowcake.dagger.getViewModelFromFactory
import com.thiosin.cryptoinfo.R
import com.thiosin.cryptoinfo.databinding.FragmentListBinding
import com.thiosin.cryptoinfo.ui.list.models.ListCoin
import com.thiosin.cryptoinfo.ui.util.NavFragment
import timber.log.Timber
class ListFragment : NavFragment<ListViewState, ListViewModel, FragmentListBinding>(),
CoinAdapter.Listener {
private lateinit var adapter: CoinAdapter
override fun provideViewModel() = getViewModelFromFactory()
override fun inflateViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentListBinding {
return FragmentListBinding.inflate(inflater, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.load()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
val navController = findNavController()
val appBarConfiguration = AppBarConfiguration(navController.graph, binding.drawerLayout)
binding.listToolbar.setupWithNavController(navController, appBarConfiguration)
binding.navView.setupWithNavController(navController)
adapter = CoinAdapter()
adapter.listener = this
binding.coinsList.adapter = adapter
binding.refreshLayout.setOnRefreshListener {
viewModel.refresh()
}
val searchItem = binding.listToolbar.menu.findItem(R.id.action_search)
val searchView = (searchItem.actionView) as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
viewModel.search(query)
return true
}
override fun onQueryTextChange(newText: String?): Boolean = true
})
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean = true
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
viewModel.clearSearch()
return true
}
})
}
override fun render(viewState: ListViewState) {
when (viewState) {
Loading -> {
Timber.d("Loading...")
binding.refreshLayout.isRefreshing = true
}
is ListReady -> {
Timber.d("Ready: $viewState")
adapter.submitList(viewState.coins)
binding.refreshLayout.isRefreshing = false
}
}
}
override fun onCoinClicked(coin: ListCoin) {
navigator.navigate(
ListFragmentDirections.actionListFragmentToDetailsFragment(
symbol = coin.symbol,
title = coin.symbol
)
)
}
}
| 1 | null | 1 | 1 | 48fbe0c0743e4d94be744e02064547fa6e66054d | 3,399 | crypto-info | MIT License |
src/main/kotlin/me/tassu/internal/util/kt/ErrorUtils.kt | supertassu | 136,362,780 | false | {"Kotlin": 117793, "Java": 604} | package me.tassu.internal.util.kt
@JvmName("throws")
fun (() -> Any).throws(vararg target: Class<out Throwable>): Boolean {
try {
this()
} catch (e: Throwable) {
val ex = e::class.java
if (target.isEmpty()) return true
return target.stream().anyMatch { ex.isAssignableFrom(it) }
}
return false
}
@JvmName("doesNotThrow")
fun (() -> Any).doesNotThrow(vararg target: Class<out Throwable>): Boolean {
return !this.throws(*target)
} | 1 | Kotlin | 0 | 0 | f0143e1c7e84975b0dd2db13112ec465823793f9 | 483 | Pumpkin | MIT License |
shared/src/commonMain/kotlin/com/wbrawner/twigs/shared/budget/BudgetAction.kt | wbrawner | 143,455,158 | false | {"Kotlin": 243947, "Java": 5411} | package com.wbrawner.twigs.shared.budget
import com.russhwolf.settings.Settings
import com.russhwolf.settings.set
import com.wbrawner.twigs.shared.Action
import com.wbrawner.twigs.shared.Reducer
import com.wbrawner.twigs.shared.Route
import com.wbrawner.twigs.shared.State
import com.wbrawner.twigs.shared.endOfMonth
import com.wbrawner.twigs.shared.replace
import com.wbrawner.twigs.shared.startOfMonth
import com.wbrawner.twigs.shared.transaction.TransactionAction
import com.wbrawner.twigs.shared.user.ConfigAction
import com.wbrawner.twigs.shared.user.UserPermission
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.Month
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
sealed interface BudgetAction : Action {
object OverviewClicked : BudgetAction
data class SetDateRange(val month: Month, val year: Int) : BudgetAction
data class LoadBudgetsSuccess(val budgets: List<Budget>) : BudgetAction
data class LoadBudgetsFailed(val error: Exception) : BudgetAction
data class CreateBudget(
val name: String,
val description: String? = null,
val users: List<UserPermission> = emptyList()
) : BudgetAction
data class SaveBudgetSuccess(val budget: Budget) : BudgetAction
data class SaveBudgetFailure(
val id: String? = null,
val name: String,
val description: String? = null,
val users: List<UserPermission> = emptyList(),
val error: Exception
) : BudgetAction
data class EditBudget(val id: String) : BudgetAction
data class SelectBudget(val id: String?) : BudgetAction
data class BudgetSelected(val id: String) : BudgetAction
data class UpdateBudget(
val id: String,
val name: String,
val description: String? = null,
val users: List<UserPermission> = emptyList()
) : BudgetAction
data class DeleteBudget(val id: String) : BudgetAction
}
const val KEY_LAST_BUDGET = "lastBudget"
class BudgetReducer(
private val budgetRepository: BudgetRepository,
private val settings: Settings
) : Reducer() {
override fun reduce(action: Action, state: () -> State): State = when (action) {
is Action.Back -> {
val currentState = state()
currentState.copy(
editingBudget = false
)
}
is BudgetAction.OverviewClicked -> state().copy(route = Route.Overview)
is BudgetAction.LoadBudgetsSuccess -> state().copy(budgets = action.budgets).also {
dispatch(BudgetAction.SelectBudget(settings.getStringOrNull(KEY_LAST_BUDGET)))
}
is BudgetAction.CreateBudget -> {
launch {
val budget = budgetRepository.create(
Budget(
name = action.name,
description = action.description,
users = action.users
)
)
dispatch(BudgetAction.SaveBudgetSuccess(budget))
}
state().copy(loading = true)
}
is BudgetAction.SetDateRange -> {
val now = Clock.System.now().toLocalDateTime(TimeZone.UTC)
val month = LocalDateTime(action.year, action.month, now.dayOfMonth, 0, 0)
.toInstant(TimeZone.UTC)
val from = startOfMonth(month)
val to = endOfMonth(month)
state().copy(
from = from,
to = to
).also {
dispatch(BudgetAction.BudgetSelected(it.selectedBudget!!))
}
}
is BudgetAction.SaveBudgetSuccess -> {
val currentState = state()
val budgets = currentState.budgets?.toMutableList() ?: mutableListOf()
budgets.replace(action.budget)
budgets.sortBy { it.name }
currentState.copy(
loading = false,
budgets = budgets.toList(),
selectedBudget = action.budget.id,
editingBudget = false
)
}
is ConfigAction.LoginSuccess -> {
launch {
try {
val budgets = budgetRepository.findAll()
dispatch(BudgetAction.LoadBudgetsSuccess(budgets))
} catch (e: Exception) {
dispatch(BudgetAction.LoadBudgetsFailed(e))
}
}
state().copy(loading = true)
}
is ConfigAction.Logout -> state().copy(
budgets = null,
selectedBudget = null,
editingBudget = false
)
// is BudgetAction.EditBudget -> state.copy(
// editingBudget = true,
// selectedBudget = action.id
// )
is BudgetAction.SelectBudget -> {
val currentState = state()
val budgetId = currentState.budgets
?.firstOrNull { it.id == action.id }
?.id
?: currentState.budgets?.firstOrNull()?.id
settings[KEY_LAST_BUDGET] = budgetId
dispatch(BudgetAction.BudgetSelected(budgetId!!))
state()
}
is BudgetAction.BudgetSelected -> state().copy(selectedBudget = action.id)
is TransactionAction.LoadTransactionsSuccess -> {
val balance = action.transactions.sumOf {
if (it.expense) {
it.amount * -1
} else {
it.amount
}
}
state().copy(budgetBalance = balance)
}
// is BudgetAction.UpdateBudget -> state.copy(loading = true).also {
// dispatch(action.async())
// }
// is BudgetAction.DeleteBudget -> state.copy(loading = true).also {
// dispatch(action.async())
// }
//
// is BudgetAsyncAction.UpdateBudgetAsync -> {
// budgetRepository.update(
// Budget(
// id = action.id,
// name = action.name,
// description = action.description,
// users = action.users
// )
// )
// state().copy(
// loading = false,
// editingBudget = false,
// )
// }
// is BudgetAsyncAction.DeleteBudgetAsync -> {
// budgetRepository.delete(action.id)
// val currentState = state()
// val budgets = currentState.budgets?.filterNot { it.id == action.id }
// currentState.copy(
// loading = false,
// budgets = budgets,
// editingBudget = false,
// selectedBudget = null
// )
// }
else -> state()
}
} | 2 | Kotlin | 0 | 2 | a6d50b4e12b77d2fba0c6842d29da6732b50705a | 6,894 | twigs-android | The Unlicense |
dynamic-query-core/src/main/kotlin/br/com/dillmann/dynamicquery/core/specification/group/AndGroupSpecification.kt | lucasdillmann | 766,655,271 | false | {"Kotlin": 110622, "ANTLR": 1294} | package br.com.dillmann.dynamicquery.core.specification.group
import br.com.dillmann.dynamicquery.core.specification.Specification
import javax.persistence.criteria.CriteriaBuilder
/**
* [GroupSpecification] implementation for the AND operator
*
* @param leftExpression Left side expression of the operator
* @param rightExpression Right side expression of the operator
*/
class AndGroupSpecification(leftExpression: Specification, rightExpression: Specification):
GroupSpecification(leftExpression, rightExpression, CriteriaBuilder::and)
| 0 | Kotlin | 0 | 1 | f45a7af14bc6ca21662d472cb97b4fabccc856aa | 550 | dynamic-query | MIT License |
desktop/views/src/testFixtures/kotlin/scene/sceneCharacters/SceneCharactersAssertions.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.desktop.view.scene.sceneCharacters
import com.soyle.stories.common.exists
import com.soyle.stories.domain.character.Character
import com.soyle.stories.domain.character.CharacterArc
import com.soyle.stories.domain.character.CharacterArcSection
import com.soyle.stories.scene.sceneCharacters.SceneCharactersView
import com.soyle.stories.scene.sceneCharacters.includedCharacterItem.IncludedCharacterItemView
import org.junit.jupiter.api.Assertions.*
class SceneCharactersAssertions private constructor(private val view: SceneCharactersView) {
companion object {
fun assertThat(view: SceneCharactersView, assertions: SceneCharactersAssertions.() -> Unit)
{
SceneCharactersAssertions(view).assertions()
}
}
fun hasCharacter(character: Character) {
with(view.driver()) {
assertNotNull(getCharacterItem(character.id))
}
}
fun doesNotHaveCharacter(character: Character) {
with(view.driver()) {
assertNull(getCharacterItem(character.id))
}
}
fun doesNotHaveCharacterNamed(characterName: String) {
with(view.driver()) {
assertNull(getCharacterItemByName(characterName))
}
}
class IncludedCharacterAssertions private constructor(private val view: SceneCharactersView, private val item: IncludedCharacterItemView) {
companion object {
fun SceneCharactersAssertions.andCharacter(characterId: Character.Id, assertions: IncludedCharacterAssertions.() -> Unit) {
IncludedCharacterAssertions(view, view.driver().getCharacterItemOrError(characterId)).assertions()
}
}
fun doesNotHaveDesire() {
val desireInput = view.drive {
getCharacterEditorOrError().desireInput
}
assert(desireInput.text.isNullOrEmpty())
}
fun hasDesire(expectedDesire: String) {
val desireInput = view.drive {
getCharacterEditorOrError().desireInput
}
assertEquals(expectedDesire, desireInput.text ?: "")
}
fun hasMotivationValue(expectedMotivation: String) {
val motivationInput = view.drive {
getCharacterEditorOrError().motivationInput
}
assertEquals(expectedMotivation, motivationInput.text ?: "")
}
fun hasInheritedMotivationValue(expectedInheritedMotivation: String) {
val motivationInput = view.drive {
getCharacterEditorOrError().motivationInput
}
assertEquals(expectedInheritedMotivation, motivationInput.promptText)
}
fun doesNotHaveRole(unexpectedRole: String? = null) {
val characterRole = view.drive {
item.role
}
if (unexpectedRole == null) {
assert(characterRole.text.isNullOrBlank())
assertFalse(characterRole.exists)
} else {
assertNotEquals(unexpectedRole, characterRole.text)
}
}
fun hasRole(expectedRole: String) {
val characterRole = view.drive {
item.role
}
assertEquals(expectedRole, characterRole.text)
assertTrue(characterRole.exists)
}
fun isListingAvailableArcToCover(characterArcId: CharacterArc.Id, expectedName: String) {
}
fun isListingAvailableArcSectionToCover(characterArcId: CharacterArc.Id, sectionId: CharacterArcSection.Id, expectedLabel: String) {
}
fun isListingAvailableArcSectionToCover(sectionId: CharacterArcSection.Id) {
}
}
} | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 3,724 | soyle-stories | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.