path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/jp/cordea/libros/viewmodel/MainListItemViewModel.kt | CORDEA | 77,815,915 | false | null | package jp.cordea.libros.viewmodel
import jp.cordea.libros.model.Book
/**
* Created by <NAME> on 2016/12/31.
*/
class MainListItemViewModel(val book: Book) | 0 | Kotlin | 0 | 0 | dfa4eecf51c8b4eb83ab9bcf534b948463339e70 | 159 | libros-android | Apache License 2.0 |
app/src/main/java/com/dimanem/android/nba/rssreader/vo/Item.kt | dimanem | 120,907,545 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 27, "XML": 14, "Java": 8} | package com.dimanem.android.nba.rssreader.vo
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
/**
* Created by dimanemets on 09/02/2018.
*/
@Root(name = "item")
class Item {
@set:Element(name = "title")
@get:Element(name = "title")
var title: String? = null
@set:Element(name = "link")
@get:Element(name = "link")
var link: String? = null
@set:Element(name = "description", required = false)
@get:Element(name = "description", required = false)
var description: String? = null
@set:Element(name = "pubDate")
@get:Element(name = "pubDate")
var pubDate: String? = null
}
| 1 | null | 1 | 1 | 091919171bf312510d2bb5999793398825da6e4c | 651 | nba-rss-android | MIT License |
app/src/main/java/com/example/fooddeliveryapp/ui/restaurantlisting/IRestaurantOnClick.kt | esraemirli | 389,731,577 | false | null | package com.example.fooddeliveryapp.ui.restaurantlisting
import com.example.fooddeliveryapp.model.entity.restaurant.Restaurant
interface IRestaurantOnClick {
fun onClick(restaurant: Restaurant)
} | 0 | Kotlin | 4 | 2 | fffff877238cbc5cfcc01e93bf0c14027b9600ea | 201 | FoodDeliveryApp | MIT License |
src/main/kotlin/com/vk/admstorm/configuration/runanything/RunAnythingConfigurationFactory.kt | VKCOM | 454,408,302 | false | null | package com.vk.admstorm.configuration.runanything
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.openapi.project.Project
open class RunAnythingConfigurationFactory(type: ConfigurationType) : ConfigurationFactory(type) {
override fun getId() = RunAnythingConfigurationType.ID
override fun createTemplateConfiguration(project: Project) =
RunAnythingConfiguration(project, this, "Run anything")
override fun getOptionsClass() = RunAnythingConfigurationOptions::class.java
}
| 32 | Kotlin | 3 | 9 | a0f16edbaab1b37ae08b7244df9d0585b7949042 | 597 | admstorm | MIT License |
src/main/kotlin/org/move/cli/manifest/AptosConfigYaml.kt | pontem-network | 279,299,159 | false | null | package org.move.cli.manifest
import com.intellij.util.io.readText
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.error.YAMLException
import java.nio.file.Path
data class AptosConfigYaml(
val configYamlPath: Path,
val profiles: Set<String>
) {
companion object {
fun fromPath(configYamlPath: Path): AptosConfigYaml? {
val yaml =
try {
Yaml().load<Map<String, Any>>(configYamlPath.readText())
} catch (e: YAMLException) {
// TODO: error notification?
return null
}
@Suppress("UNCHECKED_CAST")
val profiles = (yaml["profiles"] as? Map<*, *>)?.keys as? Set<String> ?: return null
return AptosConfigYaml(configYamlPath, profiles)
}
}
}
| 3 | null | 29 | 69 | 505651ca90cace4ba9f128d81b93d77fe3a0b94f | 832 | intellij-move | MIT License |
src/main/kotlin/org/github/holgerbrandl/desimuk/Resource.kt | gitter-badger | 300,953,650 | true | {"Kotlin": 31394} | package org.github.holgerbrandl.desimuk;
import java.util.*
class Resource(name: String, val isPreemptive: Boolean = false) : Component(name = name, process = null) {
fun availableQuantity(): Int {
TODO()
}
fun release(quantity: Int) {
TODO("Not yet implemented")
}
val requesters = PriorityQueue<Component>()
val claimers = PriorityQueue<Component>()
}
| 0 | null | 0 | 0 | 627f5725869c892ff620f1fc6b3541e60423c51e | 400 | desimuk | MIT License |
app/src/main/java/com/dartharrmi/resipi/ui/recipe_list/RecipesListFragment.kt | jArrMi | 283,382,558 | false | {"Kotlin": 135482} | package com.dartharrmi.resipi.ui.recipe_list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.Toast
import androidx.appcompat.widget.SearchView.OnQueryTextListener
import androidx.navigation.fragment.findNavController
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.dartharrmi.resipi.R
import com.dartharrmi.resipi.base.ResipiFragment
import com.dartharrmi.resipi.base.adapter.OnRecyclerViewItemClickListener
import com.dartharrmi.resipi.databinding.FragmentRecipeListBinding
import com.dartharrmi.resipi.domain.Recipe
import com.dartharrmi.resipi.ui.recipe_list.adapter.LoadingFooterAdapter
import com.dartharrmi.resipi.ui.recipe_list.adapter.RecipesAdapter
import com.dartharrmi.resipi.utils.gone
import com.dartharrmi.resipi.utils.hideKeyBoard
import com.dartharrmi.resipi.utils.visible
import kotlinx.android.synthetic.main.fragment_recipe_list.*
import kotlinx.android.synthetic.main.fragment_recipe_list.view.*
import org.koin.androidx.scope.currentScope
import org.koin.androidx.viewmodel.ext.android.viewModel
import retrofit2.HttpException
import java.io.IOException
class RecipesListFragment: ResipiFragment<FragmentRecipeListBinding>() {
private companion object {
const val ARG_QUERY = "KEY_QUERY"
}
private var isFirstLoading = true
private var query = ""
private val viewModel by currentScope.viewModel(this, RecipesListViewModel::class)
private lateinit var recipesAdapter: RecipesAdapter
override fun getLayoutId() = R.layout.fragment_recipe_list
override fun getVariablesToBind(): Map<Int, Any> = emptyMap()
override fun initObservers() = Unit
override fun onCreate(savedInstanceState: Bundle?) {
requireActivity().setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
}
@ExperimentalPagingApi
override fun initView(inflater: LayoutInflater, container: ViewGroup?) {
super.initView(inflater, container)
recipesAdapter = RecipesAdapter(requireContext(), object: OnRecyclerViewItemClickListener {
override fun onItemClicked(item: Any?) {
item?.let {
findNavController().navigate(RecipesListFragmentDirections.actionDestRecipeListToDestRecipeDetails(it as Recipe))
}
}
}).apply {
addLoadStateListener { loadState ->
if (loadState.source.refresh is LoadState.Loading) {
dataBinding.root.rvRecipesList.gone()
dataBinding.root.animLoading.visible()
dataBinding.root.animLoading.playAnimation()
isFirstLoading = false
} else {
dataBinding.root.rvRecipesList.visible()
dataBinding.root.animLoading.gone()
dataBinding.root.animLoading.cancelAnimation()
}
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
?: loadState.refresh as? LoadState.Error
errorState?.let {
val text = if (it.error is IOException) {
getString(R.string.internet_error)
} else {
it.error
}
Toast.makeText(
requireContext(),
"\uD83D\uDE28 Wooops! ${text}",
Toast.LENGTH_LONG
).show()
}
}
withLoadStateFooter(footer = LoadingFooterAdapter { retry() })
}
with(dataBinding.root) {
rvRecipesList.apply {
layoutManager = LinearLayoutManager(getViewContext())
adapter = recipesAdapter
viewTreeObserver
.addOnGlobalLayoutListener(object: OnGlobalLayoutListener {
override fun onGlobalLayout() {
rvRecipesList.viewTreeObserver.removeOnGlobalLayoutListener(this)
val appBarHeight: Int = [email protected]
rvRecipesList.translationY = -appBarHeight.toFloat()
rvRecipesList.layoutParams.height =
rvRecipesList.height + appBarHeight
}
})
}
svSearchRecipe.queryHint = getString(R.string.search_view_hint)
svSearchRecipe.setOnQueryTextListener(object: OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
[email protected] = query.orEmpty()
emptyState.gone()
search(query.orEmpty())
requireActivity().hideKeyBoard()
return true
}
override fun onQueryTextChange(newText: String?): Boolean = false
})
}
}
override fun onResume() {
super.onResume()
if (recipesAdapter.itemCount > 0) {
emptyState.gone()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(ARG_QUERY, query)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
savedInstanceState?.let {
if (it.containsKey(ARG_QUERY)) {
query = it.getString(ARG_QUERY).orEmpty()
search(query)
} else {
search(query)
}
}
}
private fun search(query: String) {
viewModel.getRecipes(query).doOnError {
Toast.makeText(
requireContext(),
"\uD83D\uDE28 Wooops",
Toast.LENGTH_LONG
).show()
}.subscribe { t ->
recipesAdapter.submitData(lifecycle, t)
}
}
} | 0 | Kotlin | 0 | 2 | 31898d545f6ae6dc23869502b41450ab734d877b | 6,463 | resipi | MIT License |
module_weather/src/main/java/com/example/module_weather/ApiManager.kt | SerendipityMatthew | 165,219,273 | true | {"Kotlin": 51533, "Java": 5543} | package com.example.module_weather
import com.example.commonsdk.http.RetrofitInstance
import com.example.commonservice.weather.WeatherService
/**
* @author
* @Date 2019/1/1
* @description
* @since 1.0.0
*/
val url = "https://www.apiopen.top/"
class ApiManager private constructor() {
private var iWeather: WeatherService = build(url, WeatherService::class.java)
fun getIWeather(): WeatherService {
return iWeather
}
private fun <T> build(host: String, cls: Class<T>): T {
return RetrofitInstance
.getInstance()
.getRetrofit(host)
.create(cls)
}
companion object {
var instance = ApiManager()
private set
fun reset() {
instance = ApiManager()
}
}
} | 0 | Kotlin | 0 | 0 | c6c6a95e0227a0f5a38267abcb6a452cab066b2e | 788 | ModularsArchitectureDemo | Apache License 2.0 |
app/src/main/kotlin/moe/linux/boilerplate/api/github/GithubApiModel.kt | ky0615 | 74,832,313 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 1, "XML": 26, "Kotlin": 35} | package moe.linux.boilerplate.api.github
import com.google.gson.annotations.SerializedName
import nz.bradcampbell.paperparcel.PaperParcel
import nz.bradcampbell.paperparcel.PaperParcelable
import java.util.*
@PaperParcel
data class CommitsResponse(
val sha: String,
val commit: Commit,
val url: String,
val author: User,
val committer: User
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelable.Creator(CommitsResponse::class.java)
}
}
@PaperParcel
data class Commit(
val author: CommitUser,
val committer: CommitUser,
val message: String,
val url: String,
@SerializedName("comment_count")
val commentCount: Int
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelable.Creator(Commit::class.java)
}
}
@PaperParcel
data class CommitUser(
val name: String,
val email: String,
val date: Date
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelable.Creator(CommitUser::class.java)
}
}
data class User(
val login: String,
val id: Int,
val avatar_url: String
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelable.Creator(User::class.java)
}
} | 0 | Kotlin | 1 | 2 | bbf10c0ef2048c72129aaf75e6578942988cdf64 | 1,289 | KotlinAndroidBoilerplate | MIT License |
app/src/main/java/com/amirdaryabak/runningapp/services/ForegroundOnlyLocationService.kt | amirdaryabak | 368,950,009 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 11, "Proguard": 1, "Kotlin": 47, "XML": 100, "Java": 3, "PureBasic": 1, "Diff": 1} | package com.amirdaryabak.runningapp.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.location.Location
import android.os.*
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import com.amirdaryabak.runningapp.R
import com.amirdaryabak.runningapp.models.Feature
import com.amirdaryabak.runningapp.models.GeoJson
import com.amirdaryabak.runningapp.other.Constants
import com.amirdaryabak.runningapp.other.TrackingUtility
import com.amirdaryabak.runningapp.ui.MainActivity
import com.google.android.gms.location.*
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
private const val TAG = "ForegroundService"
private const val NOTIFICATION_ID = 12345678
private const val NOTIFICATION_CHANNEL_ID = "Service"
@AndroidEntryPoint
class ForegroundOnlyLocationService : LifecycleService() {
companion object {
val isTracking = MutableLiveData<Boolean>()
var geoJson = GeoJson()
var lastIndexOfFeatures: Int = 0
var isServicePaused = false
var serviceKilled = false
var latLngBounds: LatLngBounds.Builder = LatLngBounds.Builder()
val timeRunInMillis = MutableLiveData<Long>()
val locationsList = MutableLiveData<Location?>()
/***
* START 10
* RUNNING 20
* PAUSED 30
* FINISHED 40
*/
var currentState = 10
}
private val timeRunInSeconds = MutableLiveData<Long>()
private var configurationChange = false
private var serviceRunningInForeground = false
private val localBinder = LocalBinder()
private lateinit var notificationManager: NotificationManager
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
var isFirstRun = true
override fun onCreate() {
super.onCreate()
postInitialValues()
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
locationRequest = LocationRequest.create().apply {
interval = TimeUnit.SECONDS.toMillis(5)
fastestInterval = TimeUnit.SECONDS.toMillis(5)
maxWaitTime = TimeUnit.SECONDS.toMillis(10)
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
val lastLocation = locationResult.lastLocation
locationsList.postValue(lastLocation)
Timber.d("amir location: %s", "${lastLocation.latitude}, ${lastLocation.longitude}")
}
}
timeRunInSeconds.observe(this) {
if (serviceRunningInForeground) {
notificationManager.notify(
NOTIFICATION_ID,
generateNotification(it, isTimerEnabled)
)
}
}
}
private fun postInitialValues() {
isTracking.postValue(false)
timeRunInMillis.postValue(0L)
timeRunInSeconds.postValue(0L)
geoJson = GeoJson()
latLngBounds = LatLngBounds.Builder()
locationsList.postValue(null)
currentState = 10
lapTime = 0L
timeRun = 0L
timeStarted = 0L
lastSecondTimestamp = 0L
}
private fun killService() {
isFirstRun = true
serviceKilled = true
pauseService()
isServicePaused = false
postInitialValues()
stopForeground(true)
stopSelf()
}
private fun pauseService() {
isServicePaused = true
unsubscribeToLocationUpdates()
isTracking.postValue(false)
isTimerEnabled = false
if (serviceRunningInForeground) {
notificationManager.notify(
NOTIFICATION_ID,
generateNotification(timeRunInSeconds.value!!, isTimerEnabled)
)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
intent?.let {
when (it.action) {
Constants.ACTION_START_OR_RESUME_SERVICE -> {
if (isFirstRun) {
currentState = 20
subscribeToLocationUpdates()
isFirstRun = false
} else {
currentState = 20
isServicePaused = false
subscribeToLocationUpdates()
Timber.d("Resuming service...")
geoJson.features.add(Feature())
lastIndexOfFeatures += 1
startTimer()
}
}
Constants.ACTION_PAUSE_SERVICE -> {
currentState = 30
Timber.d("Paused service")
pauseService()
}
Constants.ACTION_STOP_SERVICE -> {
currentState = 40
Timber.d("Stopped service")
killService()
}
}
}
return START_REDELIVER_INTENT
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
stopForeground(true)
serviceRunningInForeground = false
configurationChange = false
return localBinder
}
override fun onRebind(intent: Intent) {
stopForeground(true)
serviceRunningInForeground = false
configurationChange = false
super.onRebind(intent)
}
override fun onUnbind(intent: Intent): Boolean {
// NOTE: If this method is called due to a configuration change in MainActivity,
// we do nothing.
if (!configurationChange) {
val notification = generateNotification(timeRunInSeconds.value!!, isTimerEnabled)
startForeground(NOTIFICATION_ID, notification)
isTracking.postValue(true)
serviceRunningInForeground = true
}
return true
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy()")
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
configurationChange = true
}
private fun subscribeToLocationUpdates() {
startService(Intent(applicationContext, ForegroundOnlyLocationService::class.java))
try {
startTimer()
fusedLocationProviderClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.getMainLooper()
)
} catch (unlikely: SecurityException) {
Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
}
}
private fun unsubscribeToLocationUpdates() {
try {
val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)
removeTask.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "Location Callback removed.")
} else {
Log.d(TAG, "Failed to remove Location Callback.")
}
}
} catch (unlikely: SecurityException) {
Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
}
}
private fun generateNotification(
timeRunInSeconds: Long,
isTimerEnabled: Boolean
): Notification {
val titleText = "سرویس در حال انجام"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID, titleText, NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(notificationChannel)
}
val bigTextStyle = NotificationCompat.BigTextStyle()
.setBigContentTitle(titleText)
val activityPendingIntent = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java).also {
it.action = Constants.ACTION_SHOW_TRACKING_FRAGMENT
},
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationCompatBuilder =
NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
val notificationActionText = if (isTimerEnabled) "Pause" else "Resume"
val pendingIntent = if (isTimerEnabled) {
val pauseIntent = Intent(this, ForegroundOnlyLocationService::class.java).apply {
action = Constants.ACTION_PAUSE_SERVICE
}
PendingIntent.getService(this, 1, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT)
} else {
val resumeIntent = Intent(this, ForegroundOnlyLocationService::class.java).apply {
action = Constants.ACTION_START_OR_RESUME_SERVICE
}
PendingIntent.getService(this, 2, resumeIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
notificationCompatBuilder
// .setStyle(bigTextStyle)
.setContentTitle(titleText)
.setContentText(TrackingUtility.getFormattedStopWatchTime(timeRunInSeconds * 1000L))
.setSmallIcon(R.drawable.ic_launch)
.setDefaults(NotificationCompat.DEFAULT_LIGHTS)
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(activityPendingIntent)
/*if (isTimerEnabled) {
notificationCompatBuilder.addAction(
R.drawable.ic_launch,
notificationActionText,
pendingIntent
)
} else {
notificationCompatBuilder.addAction(
R.drawable.ic_launch,
notificationActionText,
pendingIntent
)
}*/
return notificationCompatBuilder.build()
}
/*private fun updateNotificationTrackingState(isTracking: Boolean) {
val notificationActionText = if(isTracking) "Pause" else "Resume"
val pendingIntent = if(isTracking) {
val pauseIntent = Intent(this, TrackingService::class.java).apply {
action = Constants.ACTION_PAUSE_SERVICE
}
PendingIntent.getService(this, 1, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT)
} else {
val resumeIntent = Intent(this, TrackingService::class.java).apply {
action = Constants.ACTION_START_OR_RESUME_SERVICE
}
PendingIntent.getService(this, 2, resumeIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
curNotificationBuilder.javaClass.getDeclaredField("mActions").apply {
isAccessible = true
set(curNotificationBuilder, ArrayList<NotificationCompat.Action>())
}
if (!serviceKilled) {
curNotificationBuilder = baseNotificationBuilder
.addAction(R.drawable.ic_pause_black_24dp, notificationActionText, pendingIntent)
notificationManager.notify(Constants.NOTIFICATION_ID, curNotificationBuilder.build())
}
}*/
private var isTimerEnabled = false
private var lapTime = 0L
private var timeRun = 0L
private var timeStarted = 0L
private var lastSecondTimestamp = 0L
private fun startTimer() {
isTracking.postValue(true)
timeStarted = System.currentTimeMillis()
isTimerEnabled = true
CoroutineScope(Dispatchers.Main).launch {
while (isTracking.value!!) {
// time difference between now and timeStarted
lapTime = System.currentTimeMillis() - timeStarted
// post the new lapTime
timeRunInMillis.postValue(timeRun + lapTime)
if (timeRunInMillis.value!! >= lastSecondTimestamp + 1000L) {
timeRunInSeconds.postValue(timeRunInSeconds.value!! + 1)
lastSecondTimestamp += 1000L
}
delay(Constants.TIMER_UPDATE_INTERVAL)
}
timeRun += lapTime
}
}
inner class LocalBinder : Binder() {
internal val service: ForegroundOnlyLocationService
get() = this@ForegroundOnlyLocationService
}
}
| 1 | null | 1 | 1 | 175d9079fbab5fb4100e2b8809dd1268bbc8972a | 13,326 | Piyado | Apache License 2.0 |
src/all/kamyroll/src/eu/kanade/tachiyomi/animeextension/all/kamyroll/AccessTokenInterceptor.kt | tom2411 | 406,731,462 | true | {"Kotlin": 2528349, "Java": 9693} | package eu.kanade.tachiyomi.animeextension.all.kamyroll
import android.content.SharedPreferences
import eu.kanade.tachiyomi.network.POST
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.net.HttpURLConnection
class AccessTokenInterceptor(val baseUrl: String, val json: Json, val preferences: SharedPreferences) : Interceptor {
private val deviceId = randomId()
override fun intercept(chain: Interceptor.Chain): Response {
val accessToken = getAccessToken()
val request = chain.request().newBuilder()
.header("authorization", accessToken)
.build()
val response = chain.proceed(request)
if (response.code == HttpURLConnection.HTTP_UNAUTHORIZED) {
synchronized(this) {
response.close()
val newAccessToken = refreshAccessToken()
// Access token is refreshed in another thread.
if (accessToken != newAccessToken) {
return chain.proceed(newRequestWithAccessToken(request, newAccessToken))
}
// Need to refresh an access token
val updatedAccessToken = refreshAccessToken()
// Retry the request
return chain.proceed(newRequestWithAccessToken(request, updatedAccessToken))
}
}
return response
}
private fun newRequestWithAccessToken(request: Request, accessToken: String): Request {
return request.newBuilder()
.header("authorization", accessToken)
.build()
}
private fun getAccessToken(): String {
return preferences.getString("access_token", null) ?: ""
}
private fun refreshAccessToken(): String {
val client = OkHttpClient().newBuilder().build()
val formData = FormBody.Builder()
.add("device_id", deviceId)
.add("device_type", "aniyomi")
.add("access_token", "HMbQeThWmZq4t7w")
.build()
val response = client.newCall(POST(url = "$baseUrl/auth/v1/token", body = formData)).execute()
val parsedJson = json.decodeFromString<AccessToken>(response.body!!.string())
val token = "${parsedJson.token_type} ${parsedJson.access_token}"
preferences.edit().putString("access_token", token).apply()
return token
}
// Random 15 length string
private fun randomId(): String {
return (0..14).joinToString("") {
(('0'..'9') + ('a'..'f')).random().toString()
}
}
}
| 0 | Kotlin | 0 | 0 | a327ce14950e5e76359185e643a58301df48be34 | 2,706 | aniyomi-extensions | Apache License 2.0 |
compiler/testData/moduleProtoBuf/simple/FooMultiFilePart1.kt | JakeWharton | 99,388,807 | true | null | @file:JvmMultifileClass
@file:JvmName("MultiFoo")
package foo
fun multiFile1() {}
| 179 | Kotlin | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 84 | kotlin | Apache License 2.0 |
src/main/kotlin/com/github/tmarsteel/voxamplibrarian/reactapp/IdGenerator.kt | tmarsteel | 594,242,131 | false | {"Kotlin": 239649, "CSS": 9092, "HTML": 4210} | package com.github.tmarsteel.voxamplibrarian.reactapp
object IdGenerator {
private var counter: Int = 0
fun getUniqueId(): String = "${counter++}"
} | 5 | Kotlin | 1 | 3 | c9799506ca2a9af934dd81d4eddd49892618e167 | 157 | vox-amp-librarian | MIT License |
core-network/src/main/kotlin/com/skydoves/chatgpt/core/network/initializer/NetworkInitializer.kt | SacredSuperStar | 827,276,224 | false | null | /*
* Designed and developed by 2022 skydoves (Jaewoong Eum)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.chatgpt.core.network.initializer
import android.content.Context
import androidx.startup.Initializer
import com.skydoves.chatgpt.core.network.di.NetworkEntryPoint
import com.skydoves.chatgpt.core.network.operator.ClearCacheGlobalOperator
import com.skydoves.sandwich.SandwichInitializer
import javax.inject.Inject
class NetworkInitializer : Initializer<Unit> {
@set:Inject
internal lateinit var globalOperator: ClearCacheGlobalOperator<Any>
override fun create(context: Context) {
NetworkEntryPoint.resolve(context).inject(this)
SandwichInitializer.sandwichOperators = mutableListOf(globalOperator)
}
override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}
| 36 | null | 398 | 7 | 3df96756631d3df5f8ff8fb1243a8f85b78c013e | 1,342 | Android-ChatGPT | Apache License 2.0 |
core-network/src/main/kotlin/com/skydoves/chatgpt/core/network/initializer/NetworkInitializer.kt | SacredSuperStar | 827,276,224 | false | null | /*
* Designed and developed by 2022 skydoves (Jaewoong Eum)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.chatgpt.core.network.initializer
import android.content.Context
import androidx.startup.Initializer
import com.skydoves.chatgpt.core.network.di.NetworkEntryPoint
import com.skydoves.chatgpt.core.network.operator.ClearCacheGlobalOperator
import com.skydoves.sandwich.SandwichInitializer
import javax.inject.Inject
class NetworkInitializer : Initializer<Unit> {
@set:Inject
internal lateinit var globalOperator: ClearCacheGlobalOperator<Any>
override fun create(context: Context) {
NetworkEntryPoint.resolve(context).inject(this)
SandwichInitializer.sandwichOperators = mutableListOf(globalOperator)
}
override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}
| 36 | null | 398 | 7 | 3df96756631d3df5f8ff8fb1243a8f85b78c013e | 1,342 | Android-ChatGPT | Apache License 2.0 |
tga-analysis/src/main/kotlin/org/plan/research/tga/analysis/junit/JUnitRunner.kt | plan-research | 762,333,893 | false | {"Kotlin": 130793, "Python": 46545, "Makefile": 1267} | @file:Suppress("UNUSED_VARIABLE")
package org.plan.research.tga.analysis.junit
import org.plan.research.tga.analysis.compilation.CompilationResult
import org.plan.research.tga.core.util.asArray
import org.vorpal.research.kthelper.collection.mapToArray
import org.vorpal.research.kthelper.logging.log
import java.io.PrintWriter
import java.io.StringWriter
import java.net.URLClassLoader
class JUnitRunner {
fun run(compilationResult: CompilationResult) = buildSet {
for ((testName, _) in compilationResult.compilableTests) {
addAll(run(compilationResult, testName))
}
}
fun run(compilationResult: CompilationResult, testName: String): Set<StackTrace> = try {
val classLoader = URLClassLoader(compilationResult.fullClassPath.mapToArray { it.toUri().toURL() })
val testClass = classLoader.loadClass(testName)
val jcClass = classLoader.loadClass("org.junit.runner.JUnitCore")
@Suppress("DEPRECATION")
val jc = jcClass.newInstance()
val computerClass = classLoader.loadClass("org.junit.runner.Computer")
@Suppress("DEPRECATION")
val returnValue = jcClass.getMethod("run", computerClass, Class::class.java.asArray())
.invoke(jc, computerClass.newInstance(), arrayOf(testClass))
val resultClass = classLoader.loadClass("org.junit.runner.Result")
val failureClass = classLoader.loadClass("org.junit.runner.notification.Failure")
val throwableField = failureClass.getDeclaredField("fThrownException").also {
it.isAccessible = true
}
(resultClass.getDeclaredField("failures")
.also { it.isAccessible = true }
.get(returnValue) as List<*>)
.mapNotNull { throwableField.get(it) as? Throwable? }
.mapTo(mutableSetOf()) {
val w = StringWriter()
it.printStackTrace(PrintWriter(w))
StackTrace.parse(w.toString())
}
} catch (e: Throwable) {
log.error("Error when executing test $testName, ", e)
emptySet()
}
}
| 0 | Kotlin | 1 | 1 | 6d8fbe321ff5e5e7808364bb9af91b83f439e2ab | 2,100 | tga-pipeline | Apache License 2.0 |
httpserver/src/test/kotlin/tbdex/sdk/httpserver/handlers/SubmitMessageTest.kt | TBD54566975 | 696,627,382 | false | {"Kotlin": 262477, "Shell": 3034} | package tbdex.sdk.httpserver.handlers;
import ServerTest
import TestData.aliceDid
import TestData.createOrder
import TestData.createQuote
import TestData.pfiDid
import de.fxlae.typeid.TypeId
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.application.ApplicationCall
import io.ktor.server.request.receiveText
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import tbdex.sdk.httpclient.models.ErrorResponse
import tbdex.sdk.httpserver.models.Callbacks
import tbdex.sdk.httpserver.models.ExchangesApi
import tbdex.sdk.httpserver.models.SubmitCloseCallback
import tbdex.sdk.protocol.models.Close
import tbdex.sdk.protocol.models.CloseData
import tbdex.sdk.protocol.serialization.Json
import kotlin.test.Ignore
import kotlin.test.assertContains
import kotlin.test.assertEquals
class SubmitMessageTest {
@Nested
inner class SubmitMessageServerTest : ServerTest() {
@Test
fun `returns BadRequest if exchangeId of message does not match URL`() = runBlocking {
val order = createOrder(TypeId.generate("rfq").toString())
order.sign(aliceDid)
val response = client.put("/exchanges/1234") {
contentType(ContentType.Application.Json)
setBody(order)
}
val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java)
assertEquals(HttpStatusCode.BadRequest, response.status)
assertContains(errorResponse.errors.first().detail, "Exchange ID of message must match URL")
}
@Test
fun `returns BadRequest if message is not a valid Order or Close`() = runBlocking {
val quote = createQuote(TypeId.generate("rfq").toString())
quote.sign(pfiDid)
val response = client.put("/exchanges/${quote.metadata.exchangeId}") {
contentType(ContentType.Application.Json)
setBody(quote)
}
val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java)
assertEquals(HttpStatusCode.BadRequest, response.status)
assertContains(errorResponse.errors.first().detail, "Message must be a valid Order or Close message")
}
}
@Nested
inner class SubmitMessageMockkTest {
private lateinit var applicationCall: ApplicationCall
private lateinit var exchangesApi: ExchangesApi
private val callback: Callbacks = Callbacks()
private val exchangeId = TypeId.generate("rfq").toString()
private val close: Close = Close.create(
to = "did:ex:pfi",
from = "did:ex:alice",
exchangeId = exchangeId,
closeData = CloseData(
reason = "test"
)
)
@BeforeEach
fun setUp() {
applicationCall = mockk(relaxed = true)
exchangesApi = mockk(relaxed = true)
}
@Test
@Ignore
fun `verify callback is invoked upon successful rfq submission`() = runBlocking {
// todo ApplicationCall.receiveText() is an extension function
// need to find another way to mock it
coEvery { applicationCall.parameters["exchangeId"] } returns close.metadata.exchangeId
coEvery { applicationCall.receiveText() } returns Json.stringify(close)
coVerify(exactly = 1) { submitClose(applicationCall, exchangesApi, any<SubmitCloseCallback>(), close)}
}
}
} | 33 | Kotlin | 3 | 5 | c1b7da23d1acc18cc75e31bd7906a1edfbb16d60 | 3,575 | tbdex-kt | Apache License 2.0 |
app/src/main/java/ru/sukharev/focustimer/utils/views/CustomNumberPicker.kt | SukharevPavel | 142,678,404 | false | null | package ru.sukharev.focustimer.utils.views
import android.content.Context
import android.view.View
import android.widget.EditText
import android.widget.NumberPicker
import ru.sukharev.focustimer.R
class CustomNumberPicker(context: Context) : NumberPicker(context) {
override fun addView(child: View) {
super.addView(child)
updateView(child)
}
override fun addView(child: View, index: Int, params: android.view.ViewGroup.LayoutParams) {
super.addView(child, index, params)
updateView(child)
}
override fun addView(child: View, params: android.view.ViewGroup.LayoutParams) {
super.addView(child, params)
updateView(child)
}
private fun updateView(view: View) {
if (view is EditText) {
view.textSize = context.resources.getDimension(R.dimen.number_picker_text_size)
}
}
} | 0 | Kotlin | 0 | 0 | 178910345ef9dbe021936e5bfdf3f4a462124a42 | 885 | FocusTimer | MIT License |
CnuNoticeApp/app/src/main/java/com/mtjin/cnunoticeapp/views/univ_notice/NoticeActivity.kt | mtjin | 266,342,647 | false | null | package com.mtjin.cnunoticeapp.views.univ_notice
import android.os.Bundle
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.firebase.analytics.FirebaseAnalytics
import com.mtjin.cnunoticeapp.R
import com.mtjin.cnunoticeapp.base.BaseActivity
import com.mtjin.cnunoticeapp.databinding.ActivityNoticeBinding
class NoticeActivity : BaseActivity<ActivityNoticeBinding>(R.layout.activity_notice) {
private var mFirebaseAnalytics: FirebaseAnalytics? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)
initNavigation()
}
private fun initNavigation() {
val navController = findNavController(R.id.main_nav_host)
binding.mainBottomNavigation.setupWithNavController(navController)
}
}
| 1 | Kotlin | 0 | 6 | 36db5edff842eb414b90f0854da6a482e8d786d3 | 903 | cnu-notice-app-releaseversion | MIT License |
features/home/src/main/java/com/fappslab/features/home/data/source/HomeDataSource.kt | F4bioo | 628,097,763 | false | null | package com.fappslab.features.home.data.source
import com.fappslab.features.home.domain.model.Apps
import io.reactivex.Single
internal interface HomeDataSource {
fun getApps(): Single<Apps>
}
| 0 | Kotlin | 0 | 0 | d3e0405eae2038ea13c352daa8bc976da85914a4 | 198 | faurecia-aptoide-challenge | MIT License |
src/main/kotlin/com/tencent/bk/devops/atom/task/service/JobResourceApi.kt | ci-plugins | 272,638,419 | false | {"Kotlin": 73870, "Java": 857} | package com.tencent.bk.devops.atom.task.service
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.tencent.bk.devops.atom.task.pojo.FastPushFileRequestV2
import com.tencent.bk.devops.atom.task.utils.OkhttpUtils
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody
import org.slf4j.LoggerFactory
class JobResourceApi {
companion object {
private val objectMapper = ObjectMapper().registerModule(KotlinModule())
private val logger = LoggerFactory.getLogger(JobResourceApi::class.java)
}
fun fastPushFileV2(pushFileRequest: FastPushFileRequestV2, esbHost: String): Long {
val url = "$esbHost/api/c/compapi/v2/job/fast_push_file/"
val requestBody = objectMapper.writeValueAsString(pushFileRequest)
val taskInstanceId = sendTaskRequest(requestBody, url)
if (taskInstanceId <= 0) {
// 失败处理
logger.error("start jobDevOpsFastPushfile failed")
throw RuntimeException("start jobDevOpsFastPushfile failed")
}
return taskInstanceId
}
fun getTaskResult(appId: String, appSecret: String, bizId: String, taskInstanceId: Long, operator: String, esbHost: String): TaskResult {
try {
val url = "$esbHost/api/c/compapi/v2/job/get_job_instance_status/?bk_app_code=$appId&bk_app_secret=$appSecret&bk_username=$operator&bk_biz_id=$bizId&job_instance_id=$taskInstanceId"
OkhttpUtils.doGet(url).use { resp ->
val responseStr = resp.body()!!.string()
val response: Map<String, Any> = jacksonObjectMapper().readValue(responseStr)
if (response["code"] == 0) {
val responseData = response["data"] as Map<String, Any>
val instanceData = responseData["job_instance"] as Map<String, Any>
val status = instanceData["status"] as Int
return when (status) {
3 -> {
logger.info("Job execute task finished and success")
TaskResult(true, true, "Success")
}
4 -> {
logger.error("Job execute task failed")
TaskResult(true, false, "Job failed")
}
else -> {
logger.info("Job execute task running")
TaskResult(false, false, "Job Running")
}
}
} else {
val msg = response["message"] as String
logger.error("job execute failed, msg: $msg")
throw RuntimeException("job execute failed, msg: $msg")
}
}
} catch (e: Exception) {
logger.error("execute job error", e)
throw RuntimeException("execute job error: ${e.message}")
}
}
private fun sendTaskRequest(requestBody: String, url: String): Long {
val httpReq = Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json"), requestBody))
.build()
OkhttpUtils.doHttp(httpReq).use { resp ->
val responseStr = resp.body()!!.string()
logger.info("response headers: {}", resp.headers())
logger.info("response body: $responseStr")
if (resp.code() != 200) {
logger.info("Response code error!|{}", resp.code())
throw RuntimeException("start job failed, resp code error!")
}
val response: Map<String, Any> = jacksonObjectMapper().readValue(responseStr)
if (response["code"] == 0) {
val responseData = response["data"] as Map<String, Any>
val taskInstanceId = responseData["job_instance_id"].toString().toLong()
logger.info("start job success, taskInstanceId: $taskInstanceId")
return taskInstanceId
} else {
val msg = response["message"] as String
logger.error("start job failed, msg: $msg")
throw RuntimeException("start job failed, msg: $msg")
}
}
}
data class TaskResult(val isFinish: Boolean, val success: Boolean, val msg: String)
}
| 3 | Kotlin | 3 | 1 | 5130cc9aefe1be2f436745c98841905a84a24588 | 4,554 | pushJobFile | MIT License |
core/designsystem/src/main/java/com/example/hnotes/core/designsystem/component/TopAppBar.kt | hmzgtl16 | 851,784,002 | false | {"Kotlin": 596179} | package com.example.hnotes.core.designsystem.component
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SearchBarDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarColors
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.example.hnotes.core.designsystem.icon.HNotesIcons
import com.example.hnotes.core.designsystem.theme.HNotesTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HNotesTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit,
actions: @Composable RowScope.() -> Unit,
colors: TopAppBarColors = TopAppBarDefaults.centerAlignedTopAppBarColors(),
isCenterAligned: Boolean = true,
) {
if (isCenterAligned) {
CenterAlignedTopAppBar(
title = title,
modifier = modifier,
navigationIcon = navigationIcon,
actions = actions,
colors = colors
)
}
if (!isCenterAligned) {
TopAppBar(
title = title,
modifier = modifier,
navigationIcon = navigationIcon,
actions = actions,
colors = colors
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HNotesSearchAppBar(
searchBar: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit,
colors: TopAppBarColors = TopAppBarDefaults.topAppBarColors(),
) {
TopAppBar(
title = searchBar,
modifier = modifier,
navigationIcon = navigationIcon,
colors = colors
)
}
@OptIn(ExperimentalMaterial3Api::class)
@ThemePreviews
@Composable
private fun HNotesSingleActionTopAppBarPreview() {
HNotesTheme {
HNotesTopAppBar(
title = {
Text(
text = stringResource(id = android.R.string.untitled),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(
onClick = {},
content = {
Icon(
imageVector = HNotesIcons.Search,
contentDescription = "Navigation icon",
tint = MaterialTheme.colorScheme.onSurface,
)
}
)
},
actions = {
IconButton(
onClick = {},
content = {
Icon(
imageVector = HNotesIcons.Settings,
contentDescription = "Action icon",
tint = MaterialTheme.colorScheme.onSurface,
)
},
)
}
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@ThemePreviews
@Composable
private fun HNotesMultiActionsTopAppBarPreview() {
HNotesTheme {
HNotesTopAppBar(
title = {
Text(
text = stringResource(id = android.R.string.untitled),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(
onClick = {},
content = {
Icon(
imageVector = HNotesIcons.Close,
contentDescription = "Navigation icon",
tint = MaterialTheme.colorScheme.onSurface,
)
}
)
},
actions = {
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = HNotesIcons.PinBorder,
contentDescription = "Action 3",
tint = MaterialTheme.colorScheme.onSurface,
)
}
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = HNotesIcons.Delete,
contentDescription = "Action 3",
tint = MaterialTheme.colorScheme.onSurface,
)
}
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = HNotesIcons.MoreVert,
contentDescription = "Action 3",
tint = MaterialTheme.colorScheme.onSurface,
)
}
},
isCenterAligned = false
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@ThemePreviews
@Composable
private fun HNotesSearchAppBarPreview() {
HNotesTheme {
HNotesSearchAppBar(
searchBar = {
HNotesSearchBar(
inputField = {
SearchBarDefaults.InputField(
query = "",
onQueryChange = {},
onSearch = {},
expanded = false,
onExpandedChange = {},
placeholder = {
Text(text = stringResource(id = android.R.string.search_go))
},
leadingIcon = {
Icon(
imageVector = HNotesIcons.Search,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
},
trailingIcon = {
HNotesIconButton(
onClick = {},
icon = {
Icon(
imageVector = HNotesIcons.Close,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
}
)
}
)
},
expanded = false,
onExpandedChange = {},
content = {}
)
},
navigationIcon = {
IconButton(
onClick = {},
content = {
Icon(
imageVector = HNotesIcons.Back,
contentDescription = "Navigation icon",
tint = MaterialTheme.colorScheme.onSurface,
)
}
)
}
)
}
} | 0 | Kotlin | 0 | 1 | 17adddc10a17af2db22adc5093f78b29b1ef3636 | 7,685 | HNotes | MIT License |
guides/micronaut-oauth2-client-credentials-cognito/bookrecommendation/kotlin/src/test/kotlin/example/micronaut/BookControllerTest.kt | micronaut-projects | 326,986,278 | false | {"Java": 2207487, "Groovy": 1129386, "Kotlin": 977645, "JavaScript": 110091, "HTML": 93452, "CSS": 30567, "Shell": 5473, "AppleScript": 1063, "Python": 47} | /*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.StreamingHttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import jakarta.inject.Inject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable
import reactor.core.publisher.Flux
@MicronautTest
class BookControllerTest {
@Inject
@field:Client("/")
lateinit var client: StreamingHttpClient
@DisabledIfEnvironmentVariable(named = "CI", matches = "true")
@Test
fun testRetrieveBooks() {
val books = Flux
.from(client.jsonStream(HttpRequest.GET<Any>("/books"), BookRecommendation::class.java))
.collectList()
.block()
assertEquals(1, books.size)
assertEquals("Building Microservices", books[0].name)
}
}
| 209 | Java | 31 | 36 | 9f04eb978f4882e883adffb6c95d6a6928d79b29 | 1,580 | micronaut-guides | Creative Commons Attribution 4.0 International |
shared/src/commonMain/kotlin/com/presta/customer/ui/components/rootSavings/DefaultRootSavingsComponent.kt | morgan4080 | 678,697,424 | false | null | package com.presta.customer.ui.components.rootSavings
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.router.stack.ChildStack
import com.arkivanov.decompose.router.stack.StackNavigation
import com.arkivanov.decompose.router.stack.childStack
import com.arkivanov.decompose.router.stack.pop
import com.arkivanov.decompose.router.stack.push
import com.arkivanov.decompose.router.stack.replaceAll
import com.arkivanov.decompose.value.Value
import com.arkivanov.essenty.lifecycle.Lifecycle
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import com.arkivanov.mvikotlin.core.store.StoreFactory
import com.presta.customer.network.payments.data.PaymentTypes
import com.presta.customer.prestaDispatchers
import com.presta.customer.ui.components.addSavings.AddSavingsComponent
import com.presta.customer.ui.components.addSavings.DefaultAddSavingsComponent
import com.presta.customer.ui.components.savings.DefaultSavingsComponent
import com.presta.customer.ui.components.savings.SavingsComponent
import com.presta.customer.ui.components.savingsTransactionHistory.DefaultSavingsTransactionHistoryComponent
import com.presta.customer.ui.components.savingsTransactionHistory.SavingsTransactionHistoryComponent
class DefaultRootSavingsComponent(
componentContext: ComponentContext,
val storeFactory: StoreFactory,
private val pop: () -> Unit = {},
private val processTransaction: (
correlationId: String,
amount: Double,
mode: PaymentTypes
) -> Unit,
): RootSavingsComponent, ComponentContext by componentContext {
private val savingsNavigation = StackNavigation<ConfigSavings>()
private val _childSavingsStack =
childStack(
source = savingsNavigation,
initialConfiguration = ConfigSavings.SavingsHome,
handleBackButton = true,
childFactory = ::createSavingsChild,
key = "applySavingsStack"
)
override val childSavingsStack: Value<ChildStack<*, RootSavingsComponent.ChildSavings>> = _childSavingsStack
private fun createSavingsChild(config: ConfigSavings, componentContext: ComponentContext): RootSavingsComponent.ChildSavings =
when (config) {
is ConfigSavings.SavingsHome -> RootSavingsComponent.ChildSavings.SavingsHomeChild(
savingsHomeComponent(componentContext)
)
is ConfigSavings.AddSavings -> RootSavingsComponent.ChildSavings.AddSavingsChild(
addSavingsComponent(componentContext, config)
)
is ConfigSavings.SavingsTransactionHistory -> RootSavingsComponent.ChildSavings.TransactionHistoryChild(
savingsTransactionHistoryComponent(componentContext)
)
}
private fun savingsHomeComponent(componentContext: ComponentContext): SavingsComponent =
DefaultSavingsComponent(
componentContext = componentContext,
storeFactory = storeFactory,
mainContext = prestaDispatchers.main,
onPop = {
pop()
},
onAddSavingsClicked = { sharePrice ->
savingsNavigation.push(ConfigSavings.AddSavings(sharePrice))
},
onSeeAlClicked = {
savingsNavigation.push(ConfigSavings.SavingsTransactionHistory)
}
)
private fun addSavingsComponent(componentContext: ComponentContext, config: ConfigSavings.AddSavings): AddSavingsComponent =
DefaultAddSavingsComponent(
componentContext = componentContext,
storeFactory = storeFactory,
mainContext = prestaDispatchers.main,
sharePrice = config.sharePrice,
onConfirmClicked = {correlationId, amount, mode ->
processTransaction(correlationId, amount, mode)
},
onBackNavClicked = {
savingsNavigation.pop()
}
)
private fun savingsTransactionHistoryComponent(componentContext: ComponentContext): SavingsTransactionHistoryComponent =
DefaultSavingsTransactionHistoryComponent(
componentContext = componentContext
)
private sealed class ConfigSavings : Parcelable {
@Parcelize
object SavingsHome: ConfigSavings()
@Parcelize
data class AddSavings(val sharePrice: Double): ConfigSavings()
@Parcelize
object SavingsTransactionHistory: ConfigSavings()
}
init {
lifecycle.subscribe(
object : Lifecycle.Callbacks {
override fun onResume() {
super.onResume()
savingsNavigation.replaceAll(ConfigSavings.SavingsHome)
}
}
)
}
} | 0 | Kotlin | 0 | 0 | d26cc0013c5bedf29d2f349b86e90052a0aca64e | 4,819 | kotlin-multiplatform | Apache License 2.0 |
app/src/main/java/com/azhar/infopendakian/activities/ListGunungActivity.kt | AzharRivaldi | 377,387,752 | false | null | package com.azhar.infopendakian.activities
import android.app.Activity
import android.content.res.Configuration
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.azhar.infopendakian.R
import com.azhar.infopendakian.activities.ListGunungActivity
import com.azhar.infopendakian.adapter.ListGunungAdapter
import com.azhar.infopendakian.model.ModelGunung
import com.azhar.infopendakian.model.ModelMain
import kotlinx.android.synthetic.main.activity_list_gunung.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.util.*
class ListGunungActivity : AppCompatActivity() {
lateinit var listGunungAdapter: ListGunungAdapter
lateinit var modelMain: ModelMain
var modelGunung: MutableList<ModelGunung> = ArrayList()
var strLokasiGunung: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_gunung)
//set transparent statusbar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
window.statusBarColor = Color.TRANSPARENT
}
setSupportActionBar(toolbar)
assert(supportActionBar != null)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
//get data intent
modelMain = intent.getSerializableExtra(LIST_GUNUNG) as ModelMain
if (modelMain != null) {
strLokasiGunung = modelMain.strLokasi
tvLokasi.setText(strLokasiGunung)
//set data adapter to recyclerview
listGunungAdapter = ListGunungAdapter(this, modelGunung)
if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
rvListGunung.setLayoutManager(GridLayoutManager(this, 2))
} else {
rvListGunung.setLayoutManager(GridLayoutManager(this, 3))
}
rvListGunung.setAdapter(listGunungAdapter)
rvListGunung.setHasFixedSize(true)
//method untuk menampilkan data gunung
getListGunung()
}
}
private fun getListGunung() {
try {
val stream = assets.open("nama_gunung.json")
val size = stream.available()
val buffer = ByteArray(size)
stream.read(buffer)
stream.close()
val strContent = String(buffer, StandardCharsets.UTF_8)
try {
val jsonObject = JSONObject(strContent)
val jsonArray = jsonObject.getJSONArray("gunung")
for (i in 0 until jsonArray.length()) {
val jsonObjectData = jsonArray.getJSONObject(i)
if (jsonObjectData.getString("lokasi") == strLokasiGunung) {
val jsonArrayMountain = jsonObjectData.getJSONArray("nama_gunung")
for (j in 0 until jsonArrayMountain.length()) {
val dataApi = ModelGunung()
val objectMountain = jsonArrayMountain.getJSONObject(j)
dataApi.strImageGunung = objectMountain.getString("image_gunung")
dataApi.strNamaGunung = objectMountain.getString("nama")
dataApi.strLokasiGunung = objectMountain.getString("lokasi")
dataApi.strDeskripsi = objectMountain.getString("deskripsi")
dataApi.strInfoGunung = objectMountain.getString("info_gunung")
dataApi.strJalurPendakian = objectMountain.getString("jalur_pendakian")
dataApi.strLat = objectMountain.getDouble("lat")
dataApi.strLong = objectMountain.getDouble("lon")
modelGunung.add(dataApi)
}
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
} catch (ignored: IOException) {
Toast.makeText(this@ListGunungActivity, "Oops, ada yang tidak beres. Coba ulangi beberapa saat lagi.",
Toast.LENGTH_SHORT).show()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
const val LIST_GUNUNG = "LIST_GUNUNG"
fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) {
val window = activity.window
val layoutParams = window.attributes
if (on) {
layoutParams.flags = layoutParams.flags or bits
} else {
layoutParams.flags = layoutParams.flags and bits.inv()
}
window.attributes = layoutParams
}
}
} | 0 | Kotlin | 5 | 8 | c63d042860f9994a56aeaba7f369b63c6296acb4 | 5,875 | Info-Pendakian-Gunung | Apache License 2.0 |
listing/listing_presentation/src/main/java/com/example/listing_presentation/ListingAdapter.kt | zainshah412-eng | 795,665,313 | false | {"Kotlin": 40136, "Java": 349} | package com.example.listing_presentation
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.listing_domain.model.University
import com.example.listing_presentation.databinding.ViewHolderUniversityBinding
class ListingAdapter(
var onItemClickListner: OnItemClickListener,
) : RecyclerView.Adapter<ListingAdapter.MyViewHolder>() {
private var list = listOf<University>()
fun setData(list: List<University>) {
try {
this.list = list
notifyDataSetChanged()
} catch (e:Exception){
Log.wtf("Error",e.toString())
}
}
inner class MyViewHolder(val viewDataBinding: ViewHolderUniversityBinding) :
RecyclerView.ViewHolder(viewDataBinding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding =
ViewHolderUniversityBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.viewDataBinding.apply {
val item = list[position]
tvHeadlines.text = item.name
tvContent.text = item.stateProvince
box.setOnClickListener {
onItemClickListner.onItemClicked(item)
}
}
}
override fun getItemCount(): Int {
return this.list.size
}
}
interface OnItemClickListener {
fun onItemClicked(item: University)
} | 0 | Kotlin | 0 | 0 | 3613dedb663ec925e9ecbc66c2af517998825e1e | 1,603 | TestAssignment | Apache License 2.0 |
app/src/main/java/com/musicplayer/aow/sharedata/bluetooth/DeviceListAdapter.kt | zuezhome | 109,855,339 | false | null | package com.musicplayer.aow.sharedata.bluetooth
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.musicplayer.aow.R
import java.util.ArrayList
class DeviceListAdapter(context: Context, private val mViewResourceId: Int, private val mDevices: ArrayList<BluetoothDevice>) : ArrayAdapter<BluetoothDevice>(context, mViewResourceId, mDevices) {
private val mLayoutInflater: LayoutInflater
init {
mLayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
convertView = mLayoutInflater.inflate(mViewResourceId, null)
val device = mDevices[position]
if (device != null) {
val deviceName = convertView!!.findViewById(R.id.tvDeviceName) as TextView
val deviceAdress = convertView.findViewById(R.id.tvDeviceAddress) as TextView
if (deviceName != null) {
deviceName.text = device.name
}
if (deviceAdress != null) {
deviceAdress.text = device.address
}
}
return convertView
}
}
| 0 | Kotlin | 0 | 0 | 52936ff79d8abbfb226ad443ddb7b0fab3ea0774 | 1,397 | kstudio | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/databrew/FilesLimitPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.databrew
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.databrew.CfnDataset
@Generated
public fun buildFilesLimitProperty(initializer: @AwsCdkDsl
CfnDataset.FilesLimitProperty.Builder.() -> Unit): CfnDataset.FilesLimitProperty =
CfnDataset.FilesLimitProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 439 | aws-cdk-kt | Apache License 2.0 |
live-test/src/test/kotlin/com/classpass/moderntreasury/ModernTreasuryLiveTest.kt | classpass | 361,006,691 | false | null | /**
* Copyright 2024 ClassPass
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.classpass.moderntreasury
import com.classpass.moderntreasury.client.ModernTreasuryClient
import com.classpass.moderntreasury.client.asyncModernTreasuryClient
import com.classpass.moderntreasury.config.ModernTreasuryConfig
import java.io.IOException
import java.lang.IllegalArgumentException
import java.util.Properties
/**
* Extend this class to write a test that hits the live modern treasury api, using credentials in live-tests.properties
*/
open class ModernTreasuryLiveTest {
companion object {
fun nextId() = Math.random().toString()
}
private val props = Properties()
val client: ModernTreasuryClient
init {
val inputStream = ClassLoader.getSystemResourceAsStream("live-tests.properties")
try {
props.load(inputStream)
if (!props.getProperty("apiKey").contains("test")) {
throw IllegalArgumentException("Live tests must use the test API Key!")
}
client =
asyncModernTreasuryClient(
ModernTreasuryConfig(props.getProperty("orgId"), props.getProperty("apiKey"))
) {
println("In ModernTreasuryLiveTest, rate limit remaining was $it")
}
} catch (e: IOException) {
throw Exception("Unable to load live-tests.properties", e)
}
}
}
| 3 | Kotlin | 0 | 5 | 7b99c4c289ebac71ad925e42e5df04144ff870aa | 1,997 | moderntreasury-client | Apache License 2.0 |
idea/testData/copyPaste/imports/Invoke.kt | erokhins | 10,382,997 | true | {"Java": 15969828, "Kotlin": 11078102, "JavaScript": 176060, "Protocol Buffer": 42992, "HTML": 26117, "Lex": 16668, "ANTLR": 9689, "CSS": 9358, "Groovy": 5204, "Shell": 4638, "Batchfile": 3703, "IDL": 3251} | package a
class A {
}
fun A.invoke() {
}
<selection>fun f(a: A) {
a()
}</selection> | 0 | Java | 0 | 1 | ff00bde607d605c4eba2d98fbc9e99af932accb6 | 90 | kotlin | Apache License 2.0 |
src/main/kotlin/br/com/erospv/services/impl/ProductServiceImpl.kt | erospv | 470,316,193 | false | {"Kotlin": 15405} | package br.com.erospv.services.impl
import br.com.erospv.dto.ProductReq
import br.com.erospv.dto.ProductRes
import br.com.erospv.exceptions.AlreadyExistsException
import br.com.erospv.repository.ProductRepository
import br.com.erospv.services.ProductService
import br.com.erospv.utils.toDomain
import br.com.erospv.utils.toProductRes
import jakarta.inject.Singleton
@Singleton
class ProductServiceImpl(private val productRepository: ProductRepository) : ProductService {
override fun create(req: ProductReq): ProductRes {
verifyName(req.name)
val createdProduct = productRepository.save(req.toDomain())
return createdProduct.toProductRes()
}
private fun verifyName(name: String) {
productRepository.findByNameIgnoreCase(name)?.let {
throw AlreadyExistsException(name)
}
}
} | 0 | Kotlin | 0 | 0 | 07478055c9d6db18882c8d4c09bc4632abd2ff58 | 844 | micronaut-grpc_products-service | MIT License |
shared/misc/menu/src/commonMain/kotlin/com/edugma/features/misc/menu/MiscMenuScreens.kt | Edugma | 474,423,768 | false | {"Kotlin": 1065114, "Swift": 1255, "Shell": 331, "HTML": 299} | package com.edugma.features.misc.menu
import com.edugma.core.navigation.MainDestination
import com.edugma.core.navigation.misc.MiscMenuScreens
import com.edugma.features.misc.settings.settingsScreens
import com.edugma.navigation.core.graph.NavGraphBuilder
import com.edugma.navigation.core.graph.composeScreen
import com.edugma.navigation.core.graph.graph
fun NavGraphBuilder.miscMenuScreens() {
graph(MainDestination.Misc, MiscMenuScreens.Menu) {
composeScreen(MiscMenuScreens.Menu) { MiscMenuScreen() }
settingsScreens()
}
}
| 1 | Kotlin | 0 | 3 | 9660ee06a27500076b6ee54196e1b75c4e5be862 | 553 | app | MIT License |
Labo5/app/src/main/java/ch/heigvd/daa/labo5/utils/PerformanceTester.kt | DrC0okie | 729,163,391 | false | {"Kotlin": 28304} | package ch.heigvd.daa.labo5.utils
import android.graphics.Bitmap
import android.util.Log
import ch.heigvd.daa.labo5.utils.ImageDownloader.decode
import ch.heigvd.daa.labo5.utils.ImageDownloader.download
import kotlinx.coroutines.CoroutineDispatcher as CD
import kotlinx.coroutines.CoroutineScope as CS
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import java.net.URL
import java.util.concurrent.Executors
/**
* Object for testing the performance of various CoroutineDispatchers.
*
* Provides functionality to execute and measure the performance of downloading a list of images
* using different CoroutineDispatchers. This is used to determine the most efficient dispatcher
* for parallel image downloading tasks.
* @author <NAME>, <NAME>
*/
object PerformanceTester {
/**
* A list of pairs of dispatcher names and their corresponding CoroutineDispatcher.
*/
val dispatcherPairs = listOf(
"IO" to Dispatchers.IO,
"2 Threads" to Executors.newFixedThreadPool(2).asCoroutineDispatcher(),
"8 Threads" to Executors.newFixedThreadPool(8).asCoroutineDispatcher(),
"16 Threads" to Executors.newFixedThreadPool(16).asCoroutineDispatcher(),
"32 Threads" to Executors.newFixedThreadPool(32).asCoroutineDispatcher()
)
/**
* Tests the performance of different dispatchers for image downloading tasks.
* @param items A list of URLs for the images to be downloaded.
* @param testScope The CoroutineScope in which the download tasks will be executed.
* @param uiScope The CoroutineScope for updating the UI with the test progress.
* @param updateUI A lambda function to update the UI with the current testing status.
* @param updateProgress A lambda function to update the UI with the progress of the tests.
* @return A list of [TestResult] containing the dispatcher names and their respective durations.
*/
suspend fun testDispatcherPerformance(
items: List<URL>,
testScope: CS,
uiScope: CS,
updateUI: (String) -> Unit,
updateProgress: (Int) -> Unit
): List<TestResult> {
val results = mutableListOf<TestResult>()
testScope.async {
dispatcherPairs.forEachIndexed { index, (name, dispatcher) ->
uiScope.launch { updateUI("Testing $name dispatcher...") }.join()
results.add(TestResult(name, getDuration(items, dispatcher, testScope)))
uiScope.launch { updateUI("Testing complete!"); updateProgress(index + 1) }.join()
}
}.await()
return results
}
/**
* Calculates the duration taken to download a list of images using a specified dispatcher.
* @param items The list of URLs for the images to be downloaded.
* @param disp The CoroutineDispatcher to be used for the download tasks.
* @param scope The CoroutineScope in which the download tasks will be executed.
* @return The duration (in milliseconds) taken to complete all download tasks.
*/
private suspend fun getDuration(items: List<URL>, disp: CD, scope: CS): Long {
val startTime = System.currentTimeMillis()
scope.launch(disp) { items.map { url -> launch { downloadImage(url) } }.joinAll() }.join()
return System.currentTimeMillis() - startTime
}
/**
* Attempts to download and decode an image from a given URL.
* @param url The URL of the image to be downloaded and decoded.
* @return A Bitmap of the downloaded image, or null if the download or decoding fails.
*/
private suspend fun downloadImage(url: URL): Bitmap? {
return try {
decode(download(url)!!)
} catch (e: Exception) {
Log.e("ImageDownload", "Error downloading image from $url", e)
null
}
}
} | 0 | Kotlin | 0 | 0 | aa4b59377f0251c52f066da4f689f99d14c6bcf9 | 3,968 | HEIG_DAA_Labo5 | MIT License |
app/src/main/java/com/example/sunnyweather/SunnyWeatherApplication.kt | xllxwd | 271,354,128 | false | null | package com.example.sunnyweather
import android.app.Application
import android.content.Context
/*******************************************************************
* SunnyWeatherApplication.java 2020-06-11
* <P>
* class desc:<br/>
* </p>
* @author:Xiell
******************************************************************/
class SunnyWeatherApplication : Application() {
companion object{
const val TOKEN = "0trT1DiIOP96TV8L"
lateinit var context : Context
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
} | 0 | Kotlin | 0 | 0 | c5022804895abfcf64a23507c6f21d51eba18ed9 | 592 | SunnyWeather | Apache License 2.0 |
common/api/src/commonMain/kotlin/com/denchic45/stuiversity/api/course/model/CourseResponse.kt | denchic45 | 435,895,363 | false | {"Kotlin": 2103689, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867} | package com.denchic45.stuiversity.api.course.model
import com.denchic45.stuiversity.api.course.subject.model.SubjectResponse
import com.denchic45.stuiversity.util.UUIDSerializer
import kotlinx.serialization.Serializable
import java.util.*
@Serializable
data class CourseResponse(
@Serializable(UUIDSerializer::class)
val id: UUID,
val name: String,
val subject: SubjectResponse?,
val archived: Boolean
)
| 0 | Kotlin | 0 | 7 | 93947301de4c4a9cb6c3d9fa36903f857c50e6c2 | 427 | Studiversity | Apache License 2.0 |
shared/src/commonMain/kotlin/com/mbta/tid/mbta_app/model/StopDetailsDepartures.kt | mbta | 718,216,969 | false | {"Kotlin": 1254365, "Swift": 613197, "Shell": 4593, "Ruby": 4129} | package com.mbta.tid.mbta_app.model
import com.mbta.tid.mbta_app.model.response.AlertsStreamDataResponse
import com.mbta.tid.mbta_app.model.response.GlobalResponse
import com.mbta.tid.mbta_app.model.response.NearbyResponse
import com.mbta.tid.mbta_app.model.response.PredictionsStreamDataResponse
import com.mbta.tid.mbta_app.model.response.ScheduleResponse
import com.mbta.tid.mbta_app.model.response.VehiclesStreamDataResponse
import kotlinx.datetime.Instant
data class StopDetailsDepartures(val routes: List<PatternsByStop>) {
val allUpcomingTrips = routes.flatMap { it.allUpcomingTrips() }
val upcomingPatternIds = allUpcomingTrips.mapNotNull { it.trip.routePatternId }.toSet()
fun filterVehiclesByUpcoming(vehicles: VehiclesStreamDataResponse): Map<String, Vehicle> {
val routeIds = allUpcomingTrips.map { it.trip.routeId }.toSet()
return vehicles.vehicles.filter { routeIds.contains(it.value.routeId) }
}
fun autoFilter(): StopDetailsFilter? {
if (routes.size != 1) {
return null
}
val route = routes.first()
val directions = route.patterns.map { it.directionId() }.toSet()
if (directions.size != 1) {
return null
}
val direction = directions.first()
return StopDetailsFilter(route.routeIdentifier, direction)
}
companion object {
fun fromData(
stop: Stop,
global: GlobalResponse,
schedules: ScheduleResponse?,
predictions: PredictionsStreamDataResponse?,
alerts: AlertsStreamDataResponse?,
pinnedRoutes: Set<String>,
filterAtTime: Instant
): StopDetailsDepartures? {
val allStopIds =
if (global.patternIdsByStop.containsKey(stop.id)) {
listOf(stop.id)
} else {
stop.childStopIds.filter { global.stops.containsKey(it) }
}
val staticData = NearbyStaticData(global, NearbyResponse(allStopIds))
val routes =
staticData
.withRealtimeInfo(
global,
null,
schedules,
predictions,
alerts,
filterAtTime,
showAllPatternsWhileLoading = true,
hideNonTypicalPatternsBeyondNext = null,
filterCancellations = false,
pinnedRoutes
)
?.flatMap { it.patternsByStop }
return routes?.let { StopDetailsDepartures(it) }
}
}
}
| 10 | Kotlin | 0 | 2 | ddd64e58d541054904f5a9f03a2b67b51987a830 | 2,713 | mobile_app | MIT License |
app/src/main/kotlin/com/hermesjunior/imagesearcher/imageuploader/ImageUploader.kt | OHermesJunior | 289,141,195 | false | null | package com.hermesjunior.imagesearcher.imageuploader
import java.io.File
/**
* Uploads a file (image), and gives a URL for the image.
*/
interface ImageUploader {
fun upload(file: File, callback: UploadCallback): Boolean
interface UploadCallback {
fun onResult(responseStr: String)
}
}
| 8 | Kotlin | 4 | 9 | 7f4754d578defbac50db76146f941c8d18e0d1f4 | 311 | imagesearcher | Apache License 2.0 |
android/app/src/main/kotlin/com/example/growth_app/MainActivity.kt | ccaian | 370,147,791 | false | {"Dart": 457173, "Swift": 404, "Kotlin": 127, "Objective-C": 38} | package com.example.growth_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | f4076ac3f0684f74b80dc99c765179ef3939e61f | 127 | Team-13-ITP-SE-39 | MIT License |
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyTypeHintsUtil.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInsight.hint
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.codeInsight.hints.presentation.SpacePresentation
import com.intellij.psi.*
fun PresentationFactory.buildRepresentation(type: PsiType, postfix: String = ""): InlayPresentation {
return type.accept(object : PsiTypeVisitor<InlayPresentation>() {
private val visitor = this
override fun visitClassType(classType: PsiClassType): InlayPresentation {
val classParameters = if (classType.hasParameters()) {
listOf(smallText("<"),
*classType.parameters.map { it.accept(visitor) }.intersperse(smallText(", ")).toTypedArray(),
smallText(">"))
}
else {
emptyList()
}
return seq(
psiSingleReference(smallText(classType.name)) { classType.resolve() },
*classParameters.toTypedArray()
)
}
override fun visitArrayType(arrayType: PsiArrayType): InlayPresentation {
return seq(
arrayType.componentType.accept(visitor),
smallText("[]")
)
}
override fun visitWildcardType(wildcardType: PsiWildcardType): InlayPresentation {
val boundRepresentation = wildcardType.bound?.accept(visitor)
val boundKeywordRepresentation = when {
wildcardType.isExtends -> seq(smallText(" extends "), boundRepresentation!!)
wildcardType.isSuper -> seq(smallText(" super "), boundRepresentation!!)
else -> SpacePresentation(0, 0)
}
return seq(
smallText("?"),
boundKeywordRepresentation
)
}
override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): InlayPresentation {
return smallText(primitiveType.name)
}
}).run { if (postfix.isEmpty()) this else seq(this, smallText(postfix)) }
}
private fun <T> Iterable<T>.intersperse(delimiter: T): List<T> {
val collector = mutableListOf<T>()
for (element in this) {
if (collector.isNotEmpty()) {
collector.add(delimiter)
}
collector.add(element)
}
return collector
}
fun PresentationFactory.buildRepresentation(typeParameterList: PsiTypeParameterList): InlayPresentation {
return typeParameterList.typeParameters.map { typeParameter ->
val name = typeParameter.name!!
val bound = typeParameter.extendsListTypes.map { buildRepresentation(it) }.intersperse(smallText(" & "))
if (bound.isEmpty()) {
smallText(name)
}
else {
seq(smallText("$name extends "),
seq(*bound.toTypedArray())
)
}
}.intersperse(smallText(", "))
.run {
seq(smallText("<"),
*this.toTypedArray(),
smallText(">"))
}
.let { roundWithBackground(it) }
} | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 2,951 | intellij-community | Apache License 2.0 |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SetResultActionType.kt | Waboodoo | 34,525,124 | false | null | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class SetResultActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = SetResultAction(
value = actionDTO.getString(0) ?: "",
)
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 1,
)
companion object {
private const val TYPE = "set_result"
private const val FUNCTION_NAME = "setResult"
}
}
| 18 | Kotlin | 100 | 749 | 72abafd7e3bbe68647a109cb4d5a1d3b97a73d31 | 628 | HTTP-Shortcuts | MIT License |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/appmesh/GrpcGatewayRouteMatchDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.appmesh
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.services.appmesh.GatewayRouteHostnameMatch
import software.amazon.awscdk.services.appmesh.GrpcGatewayRouteMatch
import software.amazon.awscdk.services.appmesh.HeaderMatch
/**
* The criterion for determining a request match for this GatewayRoute.
*
* Example:
*
* ```
* VirtualGateway gateway;
* VirtualService virtualService;
* gateway.addGatewayRoute("gateway-route-grpc", GatewayRouteBaseProps.builder()
* .routeSpec(GatewayRouteSpec.grpc(GrpcGatewayRouteSpecOptions.builder()
* .routeTarget(virtualService)
* .match(GrpcGatewayRouteMatch.builder()
* .hostname(GatewayRouteHostnameMatch.endsWith(".example.com"))
* .build())
* .build()))
* .build());
* ```
*/
@CdkDslMarker
public class GrpcGatewayRouteMatchDsl {
private val cdkBuilder: GrpcGatewayRouteMatch.Builder = GrpcGatewayRouteMatch.builder()
private val _metadata: MutableList<HeaderMatch> = mutableListOf()
/**
* @param hostname Create host name based gRPC gateway route match.
*/
public fun hostname(hostname: GatewayRouteHostnameMatch) {
cdkBuilder.hostname(hostname)
}
/**
* @param metadata Create metadata based gRPC gateway route match.
* All specified metadata must match for the route to match.
*/
public fun metadata(vararg metadata: HeaderMatch) {
_metadata.addAll(listOf(*metadata))
}
/**
* @param metadata Create metadata based gRPC gateway route match.
* All specified metadata must match for the route to match.
*/
public fun metadata(metadata: Collection<HeaderMatch>) {
_metadata.addAll(metadata)
}
/**
* @param port The port to match from the request.
*/
public fun port(port: Number) {
cdkBuilder.port(port)
}
/**
* @param rewriteRequestHostname When `true`, rewrites the original request received at the
* Virtual Gateway to the destination Virtual Service name.
* When `false`, retains the original hostname from the request.
*/
public fun rewriteRequestHostname(rewriteRequestHostname: Boolean) {
cdkBuilder.rewriteRequestHostname(rewriteRequestHostname)
}
/**
* @param serviceName Create service name based gRPC gateway route match.
*/
public fun serviceName(serviceName: String) {
cdkBuilder.serviceName(serviceName)
}
public fun build(): GrpcGatewayRouteMatch {
if(_metadata.isNotEmpty()) cdkBuilder.metadata(_metadata)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 2,825 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/ui/recent/animehistory/RemoveAnimeHistoryDialog.kt | jmir1 | 358,887,741 | true | null | package eu.kanade.tachiyomi.ui.recent.animehistory
import android.app.Dialog
import android.os.Bundle
import com.bluelinelabs.conductor.Controller
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Anime
import eu.kanade.tachiyomi.data.database.models.AnimeHistory
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.widget.DialogCheckboxView
class RemoveAnimeHistoryDialog<T>(bundle: Bundle? = null) : DialogController(bundle)
where T : Controller, T : RemoveAnimeHistoryDialog.Listener {
private var anime: Anime? = null
private var animehistory: AnimeHistory? = null
constructor(target: T, anime: Anime, animehistory: AnimeHistory) : this() {
this.anime = anime
this.animehistory = animehistory
targetController = target
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val activity = activity!!
// Create custom view
val dialogCheckboxView = DialogCheckboxView(activity).apply {
setDescription(R.string.dialog_with_checkbox_remove_description_anime)
setOptionDescription(R.string.dialog_with_checkbox_reset_anime)
}
return MaterialAlertDialogBuilder(activity)
.setTitle(R.string.action_remove)
.setView(dialogCheckboxView)
.setPositiveButton(R.string.action_remove) { _, _ -> onPositive(dialogCheckboxView.isChecked()) }
.setNegativeButton(android.R.string.cancel, null)
.create()
}
private fun onPositive(checked: Boolean) {
val target = targetController as? Listener ?: return
val anime = anime ?: return
val animehistory = animehistory ?: return
target.removeAnimeHistory(anime, animehistory, checked)
}
interface Listener {
fun removeAnimeHistory(anime: Anime, animehistory: AnimeHistory, all: Boolean)
}
}
| 92 | Kotlin | 58 | 843 | 28301d09b99a87dc63c788905e7e74b101f0faf8 | 2,011 | aniyomi | Apache License 2.0 |
global_module/src/main/java/com/asadkhan/global_module/domain/WeatherListData.kt | Asad-Khan-Aasanjobs | 211,473,342 | false | null | package com.asadkhan.global_module.domain
import android.annotation.SuppressLint
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@SuppressLint("ParcelCreator")
@Parcelize
data class WeatherListData(
@SerializedName("data")
val `data`: List<WeatherDataPoint>
) : Parcelable
| 0 | Kotlin | 0 | 0 | 72cb111001925b278e1b383c51b1184c7a40a972 | 350 | weather-app-rupeek | Apache License 2.0 |
example/src/main/java/com/iteo/android_navigation/list/ItemsFilterDialog.kt | Iteo | 266,980,734 | false | null | package com.iteo.android_navigation.list
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.iteo.advanced_navigation_plugin.getPreviousFragment
import com.iteo.android_navigation.R
import kotlinx.android.synthetic.main.dialog_filters.blue
import kotlinx.android.synthetic.main.dialog_filters.green
import kotlinx.android.synthetic.main.dialog_filters.red
import javax.inject.Inject
class ItemsFilterDialog @Inject constructor(
private val viewModelFactory: ViewModelProvider.Factory
) : DialogFragment() {
private lateinit var viewModel: ListViewModel
private val parameters by lazy {
ItemsFilterDialogArgs.fromBundle(arguments ?: Bundle())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.dialog_filters, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(getPreviousFragment(), viewModelFactory)[ListViewModel::class.java]
if (parameters.currentColor != -1) {
red.isChecked = parameters.currentColor == Color.RED
green.isChecked = parameters.currentColor == Color.GREEN
blue.isChecked = parameters.currentColor == Color.BLUE
}
red.setOnCheckedChangeListener { compoundButton, checked ->
if (checked) {
viewModel.search(Color.RED)
green.isChecked = false
blue.isChecked = false
}
checkForAllUnchecked()
}
green.setOnCheckedChangeListener { compoundButton, checked ->
if (checked) {
viewModel.search(Color.GREEN)
red.isChecked = false
blue.isChecked = false
}
checkForAllUnchecked()
}
blue.setOnCheckedChangeListener { compoundButton, checked ->
if (checked) {
viewModel.search(Color.BLUE)
green.isChecked = false
red.isChecked = false
}
checkForAllUnchecked()
}
}
private fun checkForAllUnchecked() {
if (!green.isChecked && !red.isChecked && !blue.isChecked) {
viewModel.search(null)
}
}
}
| 0 | Kotlin | 1 | 3 | 445012b7a1b01b5e7209670655c1a55db49e4975 | 2,598 | advanced_navigation_plugin | Apache License 2.0 |
app/src/main/java/com/ncs/o2/UI/Auth/AuthScreenActivity.kt | arpitmx | 647,358,015 | false | {"Kotlin": 607996} | package com.ncs.o2.UI.Auth
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.fragment.NavHostFragment
import com.google.firebase.auth.FirebaseAuth
import com.ncs.o2.Domain.Utility.Issue
import com.ncs.o2.R
import com.ncs.o2.UI.Auth.ChooserScreen.ChooserFragment
import com.ncs.o2.UI.MainActivity
import com.ncs.o2.databinding.ActivityAuthScreenBinding
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class AuthScreenActivity @Inject constructor() : AppCompatActivity() {
private val binding: ActivityAuthScreenBinding by lazy {
ActivityAuthScreenBinding.inflate(layoutInflater)
}
@Issue("Fragment duplicate on configuration change, implement that.")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val isDetailsAdded = intent.getStringExtra("isDetailsAdded")
val isPhotoAdded = intent.getStringExtra("isPhotoAdded")
val showchooser = intent.getStringExtra("showchooser")
val navHostFragment = supportFragmentManager.findFragmentById(R.id.navhost) as NavHostFragment
val navController = navHostFragment.navController
if (isDetailsAdded=="false" && showchooser=="false"){
navController.navigate(R.id.userDetailsFragment)
}
else if(isPhotoAdded=="false" && showchooser=="false"){
navController.navigate(R.id.profilePictureSelectionFragment)
}
else if(isPhotoAdded=="false" && isDetailsAdded=="false" && showchooser=="false"){
navController.navigate(R.id.userDetailsFragment)
}
else if (isPhotoAdded=="false" && isDetailsAdded=="false" && showchooser=="true"){
navController.navigate(R.id.chooserFragment)
}
setUpViews()
}
private fun setUpViews() {
}
} | 1 | Kotlin | 2 | 0 | b7e488a708a0bbae503c07fc7d12ab61b4f3c7e2 | 1,962 | O2 | MIT License |
dao/interfaces/IDAOCategory.kt | joychen03 | 604,384,582 | false | null | package itb.jiafumarc.street.dao.interfaces
import itb.jiafumarc.street.models.Category
interface IDAOCategory {
suspend fun getAllCategories() : List<Category>
suspend fun getAllCategoriesWithCount() : List<Category>
suspend fun getCategory(id : Int) : Category?
suspend fun addCategory(category: Category) : Category?
suspend fun updateCategory(category: Category) : Boolean
suspend fun deleteCategory(id : Int) : Boolean
} | 0 | Kotlin | 0 | 0 | db8b66c1517baf6f4587de6f45edeba5ee30c60f | 457 | street | MIT License |
src/main/kotlin/realjenius/ketris/Clock.kt | realjenius | 371,806,859 | false | null | package realjenius.ketris
import java.time.Duration
/**
* The core clock logic for a gravity-based tetris-like game.
*/
class Clock {
private var framesPieceActive: Int = 0
private var timeSimulated: Double = 0.0
private var gravity: Int = 0
fun loopUntil(predicate: () -> Boolean, action: () -> Unit) {
while (!predicate()) {
val loopStart = System.nanoTime()
action()
val duration = LOOP_TIME.minus(Duration.ofNanos(System.nanoTime() - loopStart)).toMillis()
if (duration > 0) Thread.sleep(duration)
}
}
fun newPiece() {
framesPieceActive = 0
timeSimulated = 0.0
}
fun adjustGravity(gravity: Int) {
this.gravity = (gravity - 1).coerceAtMost(CELLS_PER_FRAME_PER_LEVEL.size - 1)
}
fun checkForGravity(frames: Int = 1): Int {
framesPieceActive += frames
var drop = 0
while (framesPieceActive > timeSimulated) {
drop++
timeSimulated += (1 / CELLS_PER_FRAME_PER_LEVEL[gravity])
}
return drop
}
companion object {
private val LOOP_TIME = Duration.ofMillis(1000L / 60L)
val CELLS_PER_FRAME_PER_LEVEL = listOf(
0.01667,
0.021017,
0.026977,
0.035256,
0.04693,
0.06361,
0.0879,
0.1236,
0.1775,
0.2598,
0.388,
0.59,
0.92,
1.46,
2.36
)
}
} | 0 | Kotlin | 0 | 0 | 748d691356a583f6fea7de1be3a164b22e666f7b | 1,345 | ketris | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/autoscaling/BasicLifecycleHookPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.autoscaling
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.autoscaling.BasicLifecycleHookProps
@Generated
public fun buildBasicLifecycleHookProps(initializer: @AwsCdkDsl
BasicLifecycleHookProps.Builder.() -> Unit): BasicLifecycleHookProps =
BasicLifecycleHookProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 445 | aws-cdk-kt | Apache License 2.0 |
app/src/main/java/com/zobaer53/zedmovies/ui/wishlist/WishlistScreen.kt | zobaer53 | 661,586,013 | false | {"Kotlin": 498107, "JavaScript": 344099, "C++": 10825, "CMake": 2160} |
package com.zobaer53.zedmovies.ui.wishlist
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.zobaer53.zedmovies.ui.designsystem.component.zedMoviesMessage
import com.zobaer53.zedmovies.ui.designsystem.component.ZedMoviesSwipeRefresh
import com.zobaer53.zedmovies.ui.designsystem.theme.zedMoviesTheme
import com.zobaer53.zedmovies.data.model.MovieDetails
import com.zobaer53.zedmovies.data.model.TvShowDetails
import com.zobaer53.zedmovies.ui.smallcomponent.zedMoviesCenteredError
import com.zobaer53.zedmovies.ui.smallcomponent.MediaTabPager
import com.zobaer53.zedmovies.ui.smallcomponent.VerticalMovieItem
import com.zobaer53.zedmovies.ui.smallcomponent.VerticalMovieItemPlaceholder
import com.zobaer53.zedmovies.ui.smallcomponent.VerticalTvShowItem
import com.zobaer53.zedmovies.ui.smallcomponent.VerticalTvShowItemPlaceholder
import com.zobaer53.zedmovies.R
import com.zobaer53.zedmovies.ui.smallcomponent.mapper.asUserMessage
@Composable
internal fun WishlistRoute(
onMovieClick: (Int) -> Unit,
onTvShowClick: (Int) -> Unit,
modifier: Modifier = Modifier,
viewModel: WishlistViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
WishlistScreen(
uiState = uiState,
onRefreshMovies = { viewModel.onEvent(WishlistEvent.RefreshMovies) },
onRefreshTvShows = { viewModel.onEvent(WishlistEvent.RefreshTvShows) },
onMovieClick = onMovieClick,
onTvShowClick = onTvShowClick,
onRetry = { viewModel.onEvent(WishlistEvent.Retry) },
onOfflineModeClick = { viewModel.onEvent(WishlistEvent.ClearError) },
modifier = modifier
)
}
@Composable
private fun WishlistScreen(
uiState: WishlistUiState,
onRefreshMovies: () -> Unit,
onRefreshTvShows: () -> Unit,
onMovieClick: (Int) -> Unit,
onTvShowClick: (Int) -> Unit,
onRetry: () -> Unit,
onOfflineModeClick: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(modifier = modifier.windowInsetsPadding(WindowInsets.safeDrawing)) {
if (uiState.error != null) {
zedMoviesCenteredError(
errorMessage = uiState.error.asUserMessage(),
onRetry = onRetry,
shouldShowOfflineMode = uiState.isOfflineModeAvailable,
onOfflineModeClick = onOfflineModeClick
)
} else {
MediaTabPager(
moviesTabContent = {
MoviesContainer(
movies = uiState.movies,
isLoading = uiState.isMoviesLoading,
onRefresh = onRefreshMovies,
onClick = onMovieClick
)
},
tvShowsTabContent = {
TvShowsContainer(
tvShows = uiState.tvShows,
isLoading = uiState.isTvShowsLoading,
onRefresh = onRefreshTvShows,
onClick = onTvShowClick
)
}
)
}
}
}
@Composable
private fun MoviesContainer(
movies: List<MovieDetails>,
isLoading: Boolean,
onRefresh: () -> Unit,
onClick: (Int) -> Unit,
modifier: Modifier = Modifier,
emptyContent: @Composable LazyItemScope.() -> Unit = {
zedMoviesMessage(
modifier = Modifier.fillParentMaxSize(),
messageResourceId = R.string.no_movie_wishlist,
imageResourceId = R.drawable.no_wishlist_results
)
}
) {
ZedMoviesSwipeRefresh(
modifier = modifier,
isRefreshing = isLoading,
onRefresh = onRefresh
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(zedMoviesTheme.spacing.medium),
contentPadding = PaddingValues(zedMoviesTheme.spacing.extraMedium)
) {
when {
movies.isNotEmpty() -> {
items(movies) { movie ->
VerticalMovieItem(movie = movie, onClick = onClick)
}
}
isLoading -> {
items(PlaceholderCount) { VerticalMovieItemPlaceholder() }
}
else -> item(content = emptyContent)
}
}
}
}
@Composable
private fun TvShowsContainer(
tvShows: List<TvShowDetails>,
isLoading: Boolean,
onRefresh: () -> Unit,
onClick: (Int) -> Unit,
modifier: Modifier = Modifier,
emptyContent: @Composable LazyItemScope.() -> Unit = {
zedMoviesMessage(
modifier = Modifier.fillParentMaxSize(),
messageResourceId = R.string.no_tv_show_wishlist,
imageResourceId = R.drawable.no_wishlist_results
)
}
) {
ZedMoviesSwipeRefresh(
modifier = modifier,
isRefreshing = isLoading,
onRefresh = onRefresh
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(zedMoviesTheme.spacing.medium),
contentPadding = PaddingValues(zedMoviesTheme.spacing.extraMedium)
) {
when {
tvShows.isNotEmpty() -> {
items(tvShows) { tvShow ->
VerticalTvShowItem(tvShow = tvShow, onClick = onClick)
}
}
isLoading -> {
items(PlaceholderCount) { VerticalTvShowItemPlaceholder() }
}
else -> item(content = emptyContent)
}
}
}
}
private const val PlaceholderCount = 20
| 0 | Kotlin | 3 | 6 | 1e70d46924b711942b573364745fa74ef1f8493f | 6,411 | NoFlix | Apache License 2.0 |
app/src/main/java/com/alirezaafkar/phuzei/data/api/AlbumsApi.kt | alirezaafkar | 153,698,863 | false | {"Kotlin": 68284} | package com.alirezaafkar.phuzei.data.api
import com.alirezaafkar.phuzei.data.model.Album
import com.alirezaafkar.phuzei.data.model.AlbumsResponse
import com.alirezaafkar.phuzei.data.model.SharedAlbumsResponse
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Created by Alireza Afkar on 14/9/2018AD.
*/
interface AlbumsApi {
@GET("albums")
fun getAlbums(@Query("pageToken") pageToken: String? = null): Single<AlbumsResponse>
@GET("sharedAlbums")
fun getSharedAlbums(@Query("pageToken") pageToken: String? = null): Single<SharedAlbumsResponse>
@GET("albums/{albumId}")
fun getAlbum(@Path("albumId") id: String): Single<Album>
}
| 4 | Kotlin | 4 | 17 | 81129034cfb7e625b09320c6e0397e2c4e51a883 | 721 | phuzei | Apache License 2.0 |
client/standalone/src/main/kotlin/ai/flowstorm/client/standalone/ui/AnimatedImage.kt | flowstorm | 327,536,541 | false | {"Kotlin": 670822, "Shell": 4198, "Dockerfile": 697, "Batchfile": 207, "Python": 111} | package ai.flowstorm.client.standalone.ui
import javafx.animation.Interpolator
import javafx.animation.Transition
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.util.Duration
import kotlin.math.floor
import kotlin.math.min
open class AnimatedImage(private val imageView: ImageView, private val path: String, count: Int, duration: Double, private val callback: Callback) : Transition() {
interface Callback {
fun onLastFrame()
}
private val sequence = getImageSequence(path, count)
private var lastIndex = 0
private val maxIndex = sequence.size - 1
init {
imageView.image = sequence[0]
cycleCount = 1
cycleDuration = Duration.millis(duration)
interpolator = Interpolator.LINEAR
}
override fun interpolate(k: Double) {
val index = min(floor(k * sequence.size).toInt(), maxIndex)
if (index != lastIndex) {
imageView.image = sequence[index]
lastIndex = index
if (index == maxIndex) {
callback.onLastFrame()
}
}
}
override fun toString() = "${this::class.simpleName}(path = $path)"
companion object {
fun getImageSequence(path: String, count: Int, ext: String = "png"): List<Image> {
val sequence = mutableListOf<Image>()
for (i in 1..count) {
val name = path + "%04d".format(i) + "." + ext
sequence.add(Image(javaClass.getResourceAsStream(name)))
}
return sequence
}
}
} | 1 | Kotlin | 5 | 9 | 53dae04fa113963d632ea4d44e184885271b0322 | 1,584 | core | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_PANORAMA.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Panorama */
object FA_PANORAMA: Icon {
override val name get() = "Panorama"
override val unicode get() = "e209"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M578.2 66.06C409.8 116.6 230.2 116.6 61.8 66.06C31 56.82 0 79.88 0 112v319.9c0 32.15 30.1 55.21 61.79 45.97c168.4-50.53 347.1-50.53 516.4-.002C608.1 487.2 640 464.1 640 431.1V112C640 79.88 609 56.82 578.2 66.06zM128 224C110.3 224 96 209.7 96 192s14.33-32 32-32c17.68 0 32 14.33 32 32S145.7 224 128 224zM474.3 388.6C423.4 380.3 371.8 376 320 376c-50.45 0-100.7 4.043-150.3 11.93c-14.14 2.246-24.11-13.19-15.78-24.84l49.18-68.56C206.1 290.4 210.9 288 216 288s9.916 2.441 12.93 6.574l32.46 44.51l93.3-139.1C357.7 194.7 362.7 192 368 192s10.35 2.672 13.31 7.125l109.1 165.1C498.1 375.9 488.1 390.8 474.3 388.6z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | 1358935395f9254cab27852457e2aa6c58902e16 | 1,821 | fontawesome-kt | Apache License 2.0 |
KNativeDownloader/src/commonMain/kotlin/com/cristianmg/knativedownloader/data/KNativeDownloadRepository.kt | CristianMG | 212,796,103 | false | null | package com.cristianmg.knativedownloader.data
import com.cristianmg.knativedownloader.data.database.Database
import com.cristianmg.knativedownloader.database.KNativeDownloaderDatabase
import com.cristianmg.knativedownloader.model.FileDownload
/**
* Repository to wrapper all petition
* @property database KNativeDownloaderDatabase instance sqldelight database implementation
* @constructor
*/
class KNativeDownloadRepository(
private val database: KNativeDownloaderDatabase
) {
companion object {
/**
* Singleton instance
*/
val instance: KNativeDownloadRepository by lazy { KNativeDownloadRepository(Database.instance) }
}
/***
* Insert in database a download waiting for engine start to download
* @param file FileDownload
*/
fun insertDownload(file: FileDownload) {
database.downloadQueries.insert(file.url, file.uuid, file.sizeFile, file.extension, file.downloadedPath)
}
/***
* Delete download from queue
* @param url String
*/
fun deleteDownload(url: String) {
database.downloadQueries.remove(url)
}
fun getDownloadAtLimit(limit: Long): List<FileDownload> {
return database.downloadQueries.selectAll(limit)
.executeAsList()
.map {
FileDownload(it.url, it.size_file, it.uuid, it.extension, it.downloaded_path)
}
}
}
| 0 | Kotlin | 0 | 0 | 61602c608a6610d9115c76db680d261b6a61fdb3 | 1,435 | KNativeDownloader | Apache License 2.0 |
app/src/main/java/com/kosgei/posts/data/repositories/PostRepository.kt | Iamkosgei | 388,196,494 | false | null | package com.kosgei.posts.data.repositories
import androidx.lifecycle.LiveData
import com.kosgei.posts.data.local.dao.PostDao
import com.kosgei.posts.data.models.Post
import com.kosgei.posts.data.remote.PostApiService
import com.kosgei.posts.utils.ResultWrapper
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import timber.log.Timber
import java.io.IOException
import java.net.SocketException
import java.net.UnknownHostException
import javax.inject.Inject
interface PostRepository {
suspend fun fetchPosts(): Flow<ResultWrapper<List<Post>>>
suspend fun getPosts(): List<Post>
suspend fun savePosts(posts: List<Post>)
}
class PostRepositoryImpl @Inject constructor(
private val postApiService: PostApiService,
private val postDao: PostDao
) : PostRepository {
override suspend fun fetchPosts(): Flow<ResultWrapper<List<Post>>> {
return flow {
//get cached posts
val cachedPost = getPosts()
if (cachedPost.isNotEmpty()) {
//show minimal loading
emit(ResultWrapper.loading(data = cachedPost))
} else {
//show full loading
emit(ResultWrapper.loading(data = null))
}
try {
val postResponse = postApiService.getPosts()
if (postResponse.isSuccessful) {
postResponse.body().let {
val postLists = mutableListOf<Post>()
it?.forEach { post ->
postLists.add(post)
}
savePosts(postLists)
emit(ResultWrapper.success(data = postLists))
}
} else {
emit(
ResultWrapper.error(
data = if (cachedPost.isNotEmpty()) cachedPost else null,
message = postResponse.message()
)
)
}
} catch (e: Exception) {
if (e is IOException) {
emit(
ResultWrapper.error(
data = if (cachedPost.isNotEmpty()) cachedPost else null,
message = "Please check your internet connection and try again."
)
)
} else {
emit(
ResultWrapper.error(
data = if (cachedPost.isNotEmpty()) cachedPost else null,
message = e.message ?: e.toString()
)
)
}
}
}
}
override suspend fun getPosts(): List<Post> {
return postDao.getAllPosts()
}
override suspend fun savePosts(posts: List<Post>) {
return postDao.insertPosts(posts)
}
} | 0 | Kotlin | 0 | 0 | f5f88573eae24c1a2234c6757929d028bc548fe0 | 2,974 | PostsApp | MIT License |
src/main/kotlin/ee/carlrobert/codegpt/settings/service/codegpt/CodeGPTAvailableModels.kt | carlrobertoh | 602,041,947 | false | null | package ee.carlrobert.codegpt.settings.service.codegpt
object CodeGPTAvailableModels {
@JvmStatic
val CHAT_MODELS: List<CodeGPTModel> = listOf(
CodeGPTModel("Llama 3 (70B)", "meta-llama/Llama-3-70b-chat-hf"),
CodeGPTModel("Llama 3 (8B)", "meta-llama/Llama-3-8b-chat-hf"),
CodeGPTModel("Code Llama (70B)", "codellama/CodeLlama-70b-Instruct-hf"),
CodeGPTModel("Mixtral (8x22B)", "mistralai/Mixtral-8x22B-Instruct-v0.1"),
CodeGPTModel("DBRX (132B)", "databricks/dbrx-instruct"),
CodeGPTModel("DeepSeek Coder (33B)", "deepseek-ai/deepseek-coder-33b-instruct"),
CodeGPTModel("WizardLM-2 (8x22B)", "microsoft/WizardLM-2-8x22B")
)
@JvmStatic
val CODE_MODELS: List<CodeGPTModel> = listOf(
CodeGPTModel("StarCoder (16B)", "starcoder-16b"),
CodeGPTModel("Code Llama (70B)", "codellama/CodeLlama-70b-hf"),
CodeGPTModel("Code Llama Python (70B)", "codellama/CodeLlama-70b-Python-hf"),
CodeGPTModel("WizardCoder Python (34B)", "WizardLM/WizardCoder-Python-34B-V1.0"),
CodeGPTModel("Phind Code LLaMA v2 (34B)", "Phind/Phind-CodeLlama-34B-v2")
)
@JvmStatic
fun findByCode(code: String?): CodeGPTModel? {
return CHAT_MODELS.union(CODE_MODELS).firstOrNull { it.code == code }
}
}
data class CodeGPTModel(val name: String, val code: String) | 88 | null | 174 | 820 | f260a71d1b6e1a61731cd1649b4fec64e78064ea | 1,367 | CodeGPT | Apache License 2.0 |
app/src/main/java/com/mycompany/advioo/repo/CityRepository.kt | demirelarda | 609,874,629 | false | null | package com.mycompany.advioo.repo
import com.mycompany.advioo.api.CityAPI
import com.mycompany.advioo.models.city.CityResponse
import com.mycompany.advioo.util.Resource
import javax.inject.Inject
class CityRepository @Inject constructor(
private val cityAPI: CityAPI
): CityRepositoryInterface {
override suspend fun getCities(): Resource<CityResponse> {
return try{
val response = cityAPI.getCities()
if(response.isSuccessful){
response.body()?.let {
return@let Resource.success(it)
} ?: Resource.error("Error",null)
}
else{
Resource.error("Error",null)
}
}
catch (e:java.lang.Exception){
Resource.error("No Data", null)
}
}
} | 0 | Kotlin | 0 | 0 | 092240cd5de976186b94312eddf4f03d1c553bfa | 816 | Advioo | FSF All Permissive License |
app/src/main/java/com/po4yka/todoapp/fragment/list/ListFragment.kt | po4yka | 306,096,660 | false | null | package com.po4yka.todoapp.fragment.list
import android.app.AlertDialog
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.po4yka.todoapp.R
import com.po4yka.todoapp.data.models.ToDoData
import com.po4yka.todoapp.data.viewmodel.ToDoViewModel
import com.po4yka.todoapp.databinding.FragmentListBinding
import com.po4yka.todoapp.fragment.SharedViewModel
import com.po4yka.todoapp.fragment.list.adapter.ListAdapter
import com.po4yka.todoapp.utils.hideKeyboard
import com.po4yka.todoapp.utils.observeOnce
class ListFragment : Fragment(), SearchView.OnQueryTextListener {
private val mToDoViewModel: ToDoViewModel by viewModels()
private val mSharedViewModel: SharedViewModel by viewModels()
private var _binding: FragmentListBinding? = null
private val binding get() = _binding!!
private val adapter: ListAdapter by lazy { ListAdapter() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Data binding
_binding = FragmentListBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.mSharedViewModel = mSharedViewModel
// Setup RecyclerView
setupRecyclerview()
// Observe LiveData
mToDoViewModel.getAllData.observe(
viewLifecycleOwner,
{ data ->
mSharedViewModel.checkIfDatabaseEmpty(data)
adapter.setData(data)
binding.recycleView.scheduleLayoutAnimation()
}
)
// Set Menu
setHasOptionsMenu(true)
// Hide soft keyboard
hideKeyboard(requireActivity())
return binding.root
}
private fun setupRecyclerview() {
val recyclerView = binding.recycleView
recyclerView.adapter = adapter
recyclerView.layoutManager =
StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
// Swipe to Delete
swipeToDelete(recyclerView)
}
private fun swipeToDelete(recycleView: RecyclerView) {
val swipeToDeleteCallback = object : SwipeToDelete() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val deletedItem = adapter.dataList[viewHolder.adapterPosition]
// Delete Item
mToDoViewModel.deleteItem(deletedItem)
adapter.notifyItemRemoved(viewHolder.adapterPosition)
// Restore Deleted Item
restoreDeletedData(viewHolder.itemView, deletedItem)
}
}
val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallback)
itemTouchHelper.attachToRecyclerView(recycleView)
}
private fun restoreDeletedData(view: View, deletedItem: ToDoData) {
val snackbar = Snackbar.make(
view,
"Deleted '${deletedItem.title}'",
Snackbar.LENGTH_LONG
)
snackbar.setAction("Undo") {
mToDoViewModel.insertData(deletedItem)
}
snackbar.show()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.list_fragment_menu, menu)
val search = menu.findItem(R.id.menu_search)
val searchView = search.actionView as? SearchView
searchView?.isSubmitButtonEnabled = true
searchView?.setOnQueryTextListener(this)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_delete_all -> confirmRemoval()
R.id.menu_priority_high -> mToDoViewModel.sortByHighPriority.observe(
viewLifecycleOwner,
{
adapter.setData(it)
}
)
R.id.menu_priority_low -> mToDoViewModel.sortByLowPriority.observe(
viewLifecycleOwner,
{
adapter.setData(it)
}
)
}
return super.onOptionsItemSelected(item)
}
// Show AlertDialog to confirm removal of all items from Database Table
private fun confirmRemoval() {
val builder = AlertDialog.Builder(requireContext())
builder.setPositiveButton("Yes") { _, _ ->
mToDoViewModel.deleteAll()
Toast.makeText(
requireContext(),
"Successfully Removed Everything",
Toast.LENGTH_SHORT
).show()
}
builder.setNegativeButton("No") { _, _ -> }
builder.setTitle("Delete everything?")
builder.setMessage("Are you sure you want to delete everything?")
builder.create().show()
}
override fun onQueryTextSubmit(query: String?): Boolean {
if (query != null) {
searchThroughDatabase(query)
}
return true
}
override fun onQueryTextChange(query: String?): Boolean {
if (query != null) {
searchThroughDatabase(query)
}
return true
}
private fun searchThroughDatabase(query: String) {
val searchQuery = "%$query%"
mToDoViewModel.searchDatabase(searchQuery).observeOnce(
viewLifecycleOwner,
{ list ->
list?.let {
adapter.setData(it)
}
}
)
}
override fun onDestroyView() {
super.onDestroyView()
// avoid memory leaks
_binding = null
}
}
| 0 | Kotlin | 0 | 1 | a2470c5c796b5b8014a69f91b2e44fa893666ba4 | 5,891 | to-do-app | MIT License |
asmTransformClasses/build-logic/plugins/src/main/kotlin/CustomPlugin.kt | android | 259,259,613 | false | {"Kotlin": 188710, "Java": 1991} | /*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import com.android.build.gradle.AppPlugin
import com.android.build.api.instrumentation.FramesComputationMode
import com.android.build.api.instrumentation.InstrumentationScope
import com.android.build.api.artifact.ScopedArtifact
import com.android.build.api.variant.ScopedArtifacts
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.configurationcache.extensions.capitalized
import org.gradle.kotlin.dsl.register
import java.nio.file.Files
/**
* This custom plugin will register a callback that is applied to all variants.
*/
class CustomPlugin : Plugin<Project> {
override fun apply(project: Project) {
// Registers a callback on the application of the Android Application plugin.
// This allows the CustomPlugin to work whether it's applied before or after
// the Android Application plugin.
project.plugins.withType(AppPlugin::class.java) {
// Queries for the extension set by the Android Application plugin.
// This is the second of two entry points into the Android Gradle plugin
val androidComponents =
project.extensions.getByType(ApplicationAndroidComponentsExtension::class.java)
// Registers a callback to be called, when a new variant is configured
androidComponents.onVariants { variant ->
// Call the transformClassesWith API: supply the class visitor factory, and specify the scope and
// parameters
variant.instrumentation.transformClassesWith(
ExampleClassVisitorFactory::class.java,
InstrumentationScope.PROJECT
) { params ->
params.newMethodName.set("transformedMethod")
}
// -- Verification --
// the following is just to validate the recipe and is not actually part of the recipe itself
val taskName = "check${variant.name.capitalized()}AsmTransformation"
val taskProvider = project.tasks.register<CheckAsmTransformationTask>(taskName) {
output.set(
project.layout.buildDirectory.dir("intermediates/$taskName")
)
}
// This creates a dependency on the classes in the project scope, which will run the
// necessary tasks to build the classes artifact and trigger the transformation
variant.artifacts
.forScope(ScopedArtifacts.Scope.PROJECT)
.use(taskProvider)
.toGet(
ScopedArtifact.CLASSES,
CheckAsmTransformationTask::projectJars,
CheckAsmTransformationTask::projectDirectories,
)
}
}
}
} | 4 | Kotlin | 205 | 1,939 | 5e1c39ac595b64b4d7d14a899eb1371beeb12cf0 | 3,570 | gradle-recipes | Apache License 2.0 |
components/ledger/ledger-utxo-flow/src/main/kotlin/net/corda/ledger/utxo/flow/impl/flows/finality/v1/UtxoFinalityBaseV1.kt | corda | 346,070,752 | false | null | package net.corda.ledger.utxo.flow.impl.flows.finality.v1
import net.corda.ledger.common.data.transaction.TransactionStatus
import net.corda.ledger.common.flow.flows.Payload
import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerPersistenceService
import net.corda.ledger.utxo.flow.impl.transaction.UtxoSignedTransactionInternal
import net.corda.ledger.utxo.flow.impl.transaction.verifier.UtxoLedgerTransactionVerificationService
import net.corda.sandbox.CordaSystemFlow
import net.corda.utilities.debug
import net.corda.v5.application.crypto.DigitalSignatureAndMetadata
import net.corda.v5.application.flows.CordaInject
import net.corda.v5.application.flows.FlowEngine
import net.corda.v5.application.flows.SubFlow
import net.corda.v5.application.membership.MemberLookup
import net.corda.v5.application.messaging.FlowSession
import net.corda.v5.base.annotations.Suspendable
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.v5.ledger.utxo.VisibilityChecker
import net.corda.v5.ledger.utxo.transaction.UtxoSignedTransaction
import org.slf4j.Logger
import java.security.InvalidParameterException
/**
* Initiator will notify the receiver side with FATAL if the notarization error cannot be recovered and the
* transaction can be updated to INVALID.
*/
enum class FinalityNotarizationFailureType(val value: String) {
FATAL("F"),
UNKNOWN("U");
companion object {
fun String.toFinalityNotarizationFailureType() = when {
this.equals(FATAL.value, ignoreCase = true) -> FATAL
this.equals(UNKNOWN.value, ignoreCase = true) -> UNKNOWN
else -> throw InvalidParameterException("FinalityNotarizationFailureType '$this' is not supported")
}
}
}
@CordaSystemFlow
abstract class UtxoFinalityBaseV1 : SubFlow<UtxoSignedTransaction> {
@CordaInject
lateinit var persistenceService: UtxoLedgerPersistenceService
@CordaInject
lateinit var transactionVerificationService: UtxoLedgerTransactionVerificationService
@CordaInject
lateinit var flowEngine: FlowEngine
@CordaInject
lateinit var memberLookup: MemberLookup
@CordaInject
lateinit var visibilityChecker: VisibilityChecker
abstract val log: Logger
@Suspendable
protected fun verifySignature(
transaction: UtxoSignedTransactionInternal,
signature: DigitalSignatureAndMetadata,
sessionToNotify: FlowSession? = null
) {
try {
log.debug { "Verifying signature($signature) of transaction: $transaction.id" }
transaction.verifySignatorySignature(signature)
log.debug {
"Successfully verified signature($signature) by ${signature.by} (key id) for transaction $transaction.id"
}
} catch (e: Exception) {
val message = "Failed to verify transaction signature($signature) by ${signature.by} (key id) for " +
"transaction ${transaction.id}. Message: ${e.message}"
log.warn(message)
persistInvalidTransaction(transaction)
sessionToNotify?.send(Payload.Failure<List<DigitalSignatureAndMetadata>>(message))
throw e
}
}
@Suspendable
protected fun verifyAndAddSignature(
transaction: UtxoSignedTransactionInternal,
signature: DigitalSignatureAndMetadata
): UtxoSignedTransactionInternal {
verifySignature(transaction, signature)
return transaction.addSignature(signature)
}
@Suspendable
protected fun verifyAndAddNotarySignature(
transaction: UtxoSignedTransactionInternal,
signature: DigitalSignatureAndMetadata
): UtxoSignedTransactionInternal {
try {
transaction.verifyNotarySignature(signature)
log.debug {
"Successfully verified signature($signature) by notary ${transaction.notaryName} for transaction ${transaction.id}"
}
} catch (e: Exception) {
val message ="Failed to verify transaction's signature($signature) by notary ${transaction.notaryName} for " +
"transaction ${transaction.id}. Message: ${e.message}"
log.warn(message)
persistInvalidTransaction(transaction)
throw e
}
return transaction.addSignature(signature)
}
@Suspendable
protected fun verifyTransaction(signedTransaction: UtxoSignedTransaction) {
try {
transactionVerificationService.initialVerify(signedTransaction.toLedgerTransaction())
} catch(e: Exception){
persistInvalidTransaction(signedTransaction)
throw e
}
}
@Suspendable
protected fun persistInvalidTransaction(transaction: UtxoSignedTransaction) {
persistenceService.persist(transaction, TransactionStatus.INVALID)
log.debug { "Recorded transaction as invalid: ${transaction.id}" }
}
@Suspendable
protected fun verifyExistingSignatures(
initialTransaction: UtxoSignedTransactionInternal,
sessionToNotify: FlowSession? = null
) {
if (initialTransaction.signatures.isEmpty()){
val message = "Received initial transaction without signatures."
log.warn(message)
persistInvalidTransaction(initialTransaction)
sessionToNotify?.send(Payload.Failure<List<DigitalSignatureAndMetadata>>(message))
throw CordaRuntimeException(message)
}
initialTransaction.signatures.forEach {
verifySignature(initialTransaction, it, sessionToNotify)
}
}
}
| 14 | null | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 5,620 | corda-runtime-os | Apache License 2.0 |
jvm/core/src/main/kotlin/com/intuit/player/jvm/core/plugins/logging/PlayerLoggingConfig.kt | player-ui | 513,673,239 | false | {"TypeScript": 1094580, "Kotlin": 649267, "Swift": 513693, "Starlark": 93030, "JavaScript": 19036, "Ruby": 17488, "Shell": 7964, "MDX": 2336, "Smarty": 660, "C": 104, "Java": 103, "CSS": 46} | package com.intuit.player.jvm.core.plugins.logging
/** Base configuration for [Logging] */
public open class PlayerLoggingConfig
| 61 | TypeScript | 26 | 63 | d6664c44b6ba1db35ebb32094eca9404b6d1ee4d | 130 | player | MIT License |
app/src/main/java/com/kenchen/capstonenewsapp/ui/newslist/ArticleView.kt | AscentionOne | 529,527,068 | false | null | package com.kenchen.capstonenewsapp.ui.newslist
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.bumptech.glide.Glide
import com.kenchen.capstonenewsapp.R
import com.kenchen.capstonenewsapp.databinding.ArticleViewBinding
class ArticleView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0,
) : ConstraintLayout(context, attrs, defStyleAttr, defStyleRes) {
private val binding = ArticleViewBinding.inflate(LayoutInflater.from(context), this)
fun setTitleText(name: String) {
binding.titleTextView.text = resources.getString(R.string.news_title, name)
}
fun setAuthorText(name: String?) {
binding.authorTextView.text = resources.getString(R.string.news_author, name ?: "Unknown")
}
fun setNewsImage(imageUrl: String) {
Glide.with(this)
.load(imageUrl)
.into(binding.newsImageView)
}
}
| 0 | Kotlin | 0 | 0 | e18d3021e62b99ea81c91bc310dfd74f5d43cb40 | 1,067 | CapstoneNewsApp | MIT License |
src/main/kotlin/ws/WebSocketSession.kt | paroquet | 230,206,935 | false | null | package ws
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.atomic.AtomicBoolean
class WebSocketSession(
rawInput: InputStream,
rawOutput: OutputStream,
private val endpoint: SimpleEndPoint
) : Session {
private val readHandler = ReadHandler(rawInput, endpoint)
private val writeHandler = WriteHandler(rawOutput)
private val isOpen: AtomicBoolean = AtomicBoolean(false)
@Volatile
private var sentClose = false
override fun sendText(payload: String) {
doWrite(createTextFrame(payload))
}
override fun sendBinary(payload: ByteArray) {
doWrite(createBinaryFrame(payload))
}
override fun close(closeReason: Int, reasonPhrase: String) {
sendClose(closeReason, reasonPhrase)
markSignalClose(closeReason, reasonPhrase)
}
override fun isOpen(): Boolean = isOpen.get()
fun handle() {
markSignalOpen()
try {
readHandler.readLoop(readCallback)
} catch (e: EOFException) {
markSignalClose(UNEXPECTED_CONDITION, "EOF while reading")
} catch (e: IOException) {
markSignalClose(CLOSED_ABNORMALLY, "")
throw e
}
}
private val readCallback = object : ReadCallback {
override fun onCompleteFrame(opcode: Byte, payload: ByteArray, payloadLen: Int) {
when (opcode) {
Frame.OPCODE_CONNECTION_CLOSE -> handleClose(payload, payloadLen)
Frame.OPCODE_CONNECTION_PING -> handlePing(payload, payloadLen)
Frame.OPCODE_CONNECTION_PONG -> handlePong(payload, payloadLen)
Frame.OPCODE_TEXT_FRAME -> handleTextFrame(payload, payloadLen)
Frame.OPCODE_BINARY_FRAME -> handleBinaryFrame(payload, payloadLen)
else -> signalError(IOException("Unsupport frame opcode = $opcode"))
}
}
}
private fun doWrite(frame: Frame) {
if (signalErrorIfNotOpen()) return
writeHandler.write(frame, errorWriteCallback)
}
private fun handleClose(payload: ByteArray, payloadLen: Int) {
val closeCode: Int
val closeReason: String
if (payloadLen >= 2) {
val part1 = payload[0].toInt() and 0xff shl 8
val part2 = payload[1].toInt() and 0xff
closeCode = part1 or part2
closeReason = if (payloadLen > 2) String(payload, 2, payloadLen - 2) else ""
} else {
closeCode = CLOSED_ABNORMALLY
closeReason = "Unparseable close frame"
}
if (!sentClose) {
sendClose(NORMAL_CLOSURE, "received close frame")
}
markSignalClose(closeCode, closeReason)
}
private fun sendClose(closeCode: Int, closeReason: String) {
doWrite(createCloseFrame(closeCode, closeReason))
markSignalClose(closeCode, closeReason)
}
private fun handlePing(payload: ByteArray, payloadLen: Int) {
doWrite(createPongFrame(payload, payloadLen))
}
private fun handlePong(payload: ByteArray, payloadLen: Int) {
// do nothing ..
}
private fun handleTextFrame(payload: ByteArray, payloadLen: Int) {
endpoint.onMessage(this, String(payload, 0, payloadLen))
}
private fun handleBinaryFrame(payload: ByteArray, payloadLen: Int) {
endpoint.onMessage(this, payload, payloadLen)
}
private fun markSignalOpen() {
if (!isOpen.get()) {
isOpen.set(true)
endpoint.onOpen(this)
}
}
private fun markSignalClose(closeCode: Int, reasonPhrase: String) {
if (isOpen.get()) {
isOpen.set(false)
endpoint.onClose(this, closeCode, reasonPhrase)
}
}
private fun signalError(e: IOException) {
endpoint.onError(this, e)
}
private fun signalErrorIfNotOpen(): Boolean {
if (!isOpen()) {
signalError(IOException("Session is closed"))
return true
}
return false
}
private val errorWriteCallback = object : WriteCallback {
override fun onFailure(e: IOException) = signalError(e)
override fun onSuccess() {}
}
} | 0 | Kotlin | 1 | 0 | aa438fc6691c3b74e1feafa26e2b117d69b35582 | 3,881 | websocket-server | MIT License |
src/main/kotlin/me/atroxego/pauladdons/utils/UpdateManager.kt | AtroxEGO | 582,035,132 | false | null | package me.atroxego.pauladdons.utils
import PaulAddons
import kotlinx.coroutines.launch
import me.atroxego.pauladdons.gui.RequestUpdateGui
import me.atroxego.pauladdons.gui.UpdateGui
import me.atroxego.pauladdons.utils.core.GithubRelease
import net.minecraft.client.gui.GuiMainMenu
import net.minecraft.util.Util
import net.minecraftforge.client.event.GuiOpenEvent
import net.minecraftforge.fml.common.eventhandler.EventPriority
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import org.json.JSONTokener
import java.awt.Desktop
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLDecoder
import kotlin.concurrent.thread
object UpdateManager {
val updateGetter = UpdateGetter()
val updateDownloadURL: String
get() = "https://github.com/AtroxEGO/PaulAddonsKotlin/releases/latest/download/PaulAddons-${updateGetter.updateObj!!.tagName}.jar"
init {
try {
PaulAddons.IO.launch { updateGetter.run() }
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fun getJarNameFromUrl(url: String): String {
return url.split(Regex("/")).last()
}
fun scheduleCopyUpdateAtShutdown(jarName: String) {
Runtime.getRuntime().addShutdownHook(Thread {
try {
println("Attempting to apply PaulAddons update.")
val oldJar = PaulAddons.jarFile
if (oldJar == null || !oldJar.exists() || oldJar.isDirectory) {
println("Old jar file not found.")
return@Thread
}
println("Copying updated jar to mods.")
val newJar = File(File(PaulAddons.modDir, "updates"), jarName)
println("Copying to mod folder")
val nameNoExtension = jarName.substringBeforeLast(".")
println("1")
val newExtension = jarName.substringAfterLast(".")
println("2")
val newLocation = File(
oldJar.parent,
"${if (oldJar.name.startsWith("!")) "!" else ""}${nameNoExtension}${if (oldJar.endsWith(".temp.jar") && newExtension == oldJar.extension) ".temp.jar" else ".$newExtension"}"
)
println("3")
newLocation.createNewFile()
println("4")
newJar.copyTo(newLocation, true)
println("5")
newJar.delete()
println("6")
if (oldJar.delete()) {
println("10")
println("successfully deleted the files. skipping install tasks")
println("11")
return@Thread
} else println("Fricckers!")
println("9")
println("Running delete task")
val taskFile = File(File(PaulAddons.modDir, "updates"), "tasks").listFiles()?.last()
if (taskFile == null) {
println("Task doesn't exist")
return@Thread
}
val runtime = Utils.getJavaRuntime()
if (Util.getOSType() == Util.EnumOS.OSX) {
val sipStatus = Runtime.getRuntime().exec("csrutil status")
sipStatus.waitFor()
if (!sipStatus.inputStream.use { it.bufferedReader().readText() }
.contains("System Integrity Protection status: disabled.")) {
println("SIP is NOT disabled, opening Finder.")
Desktop.getDesktop().open(oldJar.parentFile)
return@Thread
}
}
println("Using runtime $runtime")
Runtime.getRuntime().exec("\"$runtime\" -jar \"${taskFile.absolutePath}\" \"${oldJar.absolutePath}\"")
println("Successfully applied PaulAddons update.")
} catch (ex: Throwable) {
println("Failed to apply PaulAddons Update.")
ex.printStackTrace()
}
})
}
fun downloadDeleteTask() {
thread(name = "PaulAddons-update-downloader-thread") {
val version = HttpUtils.sendGet("https://raw.githubusercontent.com/AtroxEGO/PaulAddonsUpdater/master/latest", null)
val url = "https://github.com/AtroxEGO/PaulAddonsUpdater/releases/latest/download/$version"
val directory = File(File(PaulAddons.modDir, "updates"), "tasks")
try {
val st = URL(url).openConnection() as HttpURLConnection
st.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"
)
st.connect()
if (st.responseCode != HttpURLConnection.HTTP_OK) {
println("$url returned status code ${st.responseCode}")
return@thread
}
if (!directory.exists() && !directory.mkdirs()) {
println("Couldn't create update file directory")
return@thread
}
val urlParts = url.split("/".toRegex()).toTypedArray()
val fileSaved = File(directory, URLDecoder.decode(urlParts[urlParts.size - 1], "UTF-8"))
val fis = st.inputStream
val fos: OutputStream = FileOutputStream(fileSaved)
val data = ByteArray(1024)
var count: Int
while (fis.read(data).also { count = it } != -1) {
fos.write(data, 0, count)
}
fos.flush()
fos.close()
fis.close()
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun onGuiOpen(e: GuiOpenEvent) {
if (e.gui !is GuiMainMenu) return
if (updateGetter.updateObj == null) return
if (UpdateGui.complete) return
if (PaulAddons.currentGui == null) PaulAddons.currentGui = RequestUpdateGui()
}
class UpdateGetter {
@Volatile
var updateObj: GithubRelease? = null
suspend fun run() {
println("Checking Updates...")
val response =
"{data:${HttpUtils.sendGet("https://api.github.com/repos/AtroxEGO/PaulAddonsKotlin/releases", null)}}"
val jsonObject = JSONTokener(response).nextValue() as org.json.JSONObject
val jsonArray = jsonObject.getJSONArray("data").getJSONObject(0)
val latestReleaseBody = jsonArray["body"].toString()
val latestTag = jsonArray["tag_name"].toString()
val uploader = jsonArray.getJSONObject("author").get("login").toString()
val currentVersion = PaulAddons.VERSION.toDouble()
val latestVersion = latestTag.toDouble()
println("$currentVersion < $latestVersion")
if (currentVersion < latestVersion) updateObj = GithubRelease(latestTag, uploader, latestReleaseBody)
}
}
} | 0 | Kotlin | 0 | 6 | ee973c379ebdf2d4bc962f8f545592d97f0bd9a7 | 7,306 | PaulAddonsKotlin | The Unlicense |
persian/src/main/java/io/github/madmaximuus/persian/colorPicker/view/inputs/HsvInput.kt | MADMAXIMUUS | 689,789,834 | false | {"Kotlin": 845470} | package io.github.madmaximuus.persian.colorPicker.view.inputs
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import io.github.madmaximuus.persian.forms.PersianForm
import io.github.madmaximuus.persian.forms.PersianFormContent
import io.github.madmaximuus.persian.forms.PersianFormSubheadConfig
import io.github.madmaximuus.persian.foundation.spacing
@Composable
fun HsvInput(
value: Triple<Float, Float, Float>,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.extraExtraSmall)
) {
PersianForm(
modifier = Modifier.weight(1f),
subhead = PersianFormSubheadConfig(
text = "H"
),
content = PersianFormContent.Input(
value = "%.1f".format(value.first),
onValueChange = {},
readOnly = true
)
)
PersianForm(
modifier = Modifier.weight(1f),
subhead = PersianFormSubheadConfig(
text = "S"
),
content = PersianFormContent.Input(
value = "%.1f".format(value.second * 100),
onValueChange = {},
readOnly = true
)
)
PersianForm(
modifier = Modifier.weight(1f),
subhead = PersianFormSubheadConfig(
text = "V"
),
content = PersianFormContent.Input(
value = "%.1f".format(value.third * 100),
onValueChange = {},
readOnly = true
)
)
}
} | 0 | Kotlin | 1 | 1 | 1ccf0c0860a5ea07b9819792d52c02c241b65643 | 1,836 | Persian | MIT License |
jetpackDemo/app/src/main/java/com/bosh/jetpackdemo/repository/SpRepository.kt | chinabosh | 459,409,095 | false | {"C": 1019759, "Kotlin": 93765, "CMake": 1880, "Makefile": 1214, "C++": 263} | package com.bosh.jetpackdemo.repository
import com.bosh.jetpackdemo.utils.SpUtils
import javax.inject.Inject
/**
* 同一管理sp
* @author lzq
* @date 2022/6/21
*/
class SpRepository @Inject constructor(
private val sp: SpUtils
) {
private val keyDefaultProvince = "key_default_province"
fun setDefaultProvince(prov: String) {
sp.putString(keyDefaultProvince, prov)
}
fun getDefaultProvince(): String {
return sp.getString(keyDefaultProvince, "")
}
} | 0 | C | 0 | 2 | 69a17252ded23af1425c76d9f5acbc0522f13462 | 492 | jetpackDemo | MIT License |
app/src/main/java/com/rmnivnv/cryptomoon/ui/news/NewsFragment.kt | ivnvrmn | 98,931,608 | false | null | package com.rmnivnv.cryptomoon.ui.news
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.rmnivnv.cryptomoon.R
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.news_fragment.*
import com.twitter.sdk.android.core.Callback
import com.twitter.sdk.android.core.Result
import com.twitter.sdk.android.core.TwitterException
import com.twitter.sdk.android.core.TwitterSession
import com.twitter.sdk.android.core.models.Tweet
import javax.inject.Inject
/**
* Created by ivanov_r on 26.09.2017.
*/
class NewsFragment : DaggerFragment(), INews.View {
@Inject lateinit var presenter: INews.Presenter
private var tweets: ArrayList<Tweet> = ArrayList()
private lateinit var recView: RecyclerView
private lateinit var adapter: NewsAdapter
private lateinit var linearLayoutManager: LinearLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.onCreate(tweets)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
inflater.inflate(R.layout.news_fragment, container, false)!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecView()
twitter_login_btn.callback = object : Callback<TwitterSession>() {
override fun success(result: Result<TwitterSession>?) {
presenter.onSuccessLogin(result)
}
override fun failure(exception: TwitterException?) {
}
}
news_swipe_refresh.setOnRefreshListener { presenter.onSwipeUpdate() }
news_fab.setOnClickListener { presenter.onFabClicked() }
}
override fun onStart() {
super.onStart()
presenter.onStart()
}
override fun onStop() {
super.onStop()
presenter.onStop()
}
private fun setupRecView() {
recView = news_rec_view
linearLayoutManager = LinearLayoutManager(activity)
recView.layoutManager = linearLayoutManager
adapter = NewsAdapter(tweets)
recView.adapter = adapter
recView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
presenter.onScrolled(dy, linearLayoutManager.childCount, linearLayoutManager.itemCount, linearLayoutManager.findFirstVisibleItemPosition())
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
twitter_login_btn.onActivityResult(requestCode, resultCode, data)
}
override fun hideLoginBtn() {
twitter_login_btn.visibility = View.GONE
}
override fun showLoginBtn() {
twitter_login_btn.visibility = View.VISIBLE
}
override fun showRecView() {
news_rec_view.visibility = View.VISIBLE
}
override fun updateInsertedTweets(startPos: Int, count: Int) {
adapter.notifyItemRangeInserted(startPos, count)
}
override fun showLoading() {
news_loading.visibility = View.VISIBLE
}
override fun hideLoading() {
news_loading.visibility = View.GONE
}
override fun hideSwipeRefreshing() {
news_swipe_refresh.isRefreshing = false
}
override fun showSearchDialog(query: String) {
val dialog = SearchDialog()
val bundle = Bundle()
bundle.putString("query", query)
dialog.arguments = bundle
dialog.show(childFragmentManager, "searchDialog")
}
override fun showEmptyNews() {
news_empty_text.visibility = View.VISIBLE
}
override fun hideEmptyNews() {
news_empty_text.visibility = View.GONE
}
override fun showFab() {
news_fab.visibility = View.VISIBLE
}
override fun hideFab() {
news_fab.visibility = View.GONE
}
} | 2 | Kotlin | 14 | 113 | 4d1651ce680fbf49e71cafb7d49e2d49d059b5fd | 4,240 | CryptoMoon | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/manageaccount/publickeys/PublicKeysModule.kt | horizontalsystems | 142,825,178 | false | {"Kotlin": 4800349, "Shell": 6112, "Ruby": 1350} | package io.horizontalsystems.bankwallet.modules.manageaccount.publickeys
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.entities.Account
import io.horizontalsystems.bankwallet.modules.manageaccount.showextendedkey.ShowExtendedKeyModule.DisplayKeyType.AccountPublicKey
import io.horizontalsystems.hdwalletkit.HDExtendedKey
object PublicKeysModule {
const val ACCOUNT_KEY = "account_key"
fun prepareParams(account: Account) = bundleOf(ACCOUNT_KEY to account)
class Factory(private val account: Account) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PublicKeysViewModel(account, App.evmBlockchainManager) as T
}
}
data class ViewState(
val evmAddress: String? = null,
val extendedPublicKey: ExtendedPublicKey? = null
)
data class ExtendedPublicKey(
val hdKey: HDExtendedKey,
val accountPublicKey: AccountPublicKey
)
} | 100 | Kotlin | 340 | 778 | 454cb88a3f4687d77ffc3d2d878462f23b4b9dab | 1,155 | unstoppable-wallet-android | MIT License |
makrdown-blog/src/main/java/daggerok/app/web/RoutesConfig.kt | daggerok | 102,229,956 | false | null | package daggerok.app.web
import daggerok.app.jdbc.Article
import daggerok.app.jdbc.ArticleRepository
import daggerok.app.jdbc.Post
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.ClassPathResource
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.RenderingResponse
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.body
import org.springframework.web.reactive.function.server.router
import reactor.core.publisher.toFlux
import reactor.core.publisher.toMono
import reactor.core.scheduler.Schedulers.elastic
import java.time.LocalDateTime
import java.util.*
@Configuration
class RoutesConfig(private val articleRepository: ArticleRepository,
private val markdownConverter: MarkdownConverter) {
fun Post.render() = ArticleToBeRendered(
id,
title,
markdownConverter.invoke(content),
updatedAt,
createdAt,
markdownConverter.invoke(headline),
username
)
data class ArticleToBeRendered(
val articleId: Long? = null,
val articleTitle: String? = null,
val articleContent: String? = null,
val articleUpdatedAt: LocalDateTime? = null,
val articleCreatedAt: LocalDateTime? = null,
val articleHeadline: String? = null,
val authorUsername: String? = null
)
@Bean
fun routes() = router {
("/").nest {
contentType(MediaType.TEXT_HTML)
GET("/") {
//ok().render("index", mapOf("message" to "ololo trololo"))
RenderingResponse.create("index")
.modelAttribute("articles", articleRepository
.findLatest20Articles()
.toFlux()
.map { it.render() }
.subscribeOn(elastic()))
.build()
.cast(ServerResponse::class.java)
}
GET("/article/{id}") {
val id = it.pathVariable("id").toLong()
RenderingResponse.create("article")
.modelAttribute("article", articleRepository
.findPost(id)
.orElseThrow { RuntimeException("article $id wan't found.") }
.toMono()
.map { it.render() }
.subscribeOn(elastic()))
.build()
.cast(ServerResponse::class.java)
}
contentType(MediaType.APPLICATION_JSON_UTF8)
GET("/api/{id}") {
val id = it.pathVariable("id").toLong()
ServerResponse.ok().body(
articleRepository.findById(id)
.toMono()
.subscribeOn(elastic())
)
}
GET("/api/**") {
ServerResponse.ok().body(
articleRepository.findAll()
.toFlux()
.subscribeOn(elastic())
)
}
POST("/api/{id}") {
val id = it.pathVariable("id").toLong()
ServerResponse.ok().body(
articleRepository.findById(id)
.orElseThrow { RuntimeException("article $id wan't found.") }
.toMono()
.map { it.copy(content = """${it.content ?: ""} | updated""") }
.map { articleRepository.save(it) }
.subscribeOn(elastic())
)
}
POST("/api/**") {
val string = UUID.randomUUID().toString()
ServerResponse.ok().body(
articleRepository.save(Article(string, string, string))
.toMono()
.subscribeOn(elastic())
)
}
}
resources("/**", ClassPathResource("/public"))
}
}
| 10 | Java | 38 | 97 | 11340b9fe8b0b53445d7ed869d409d378999e334 | 3,685 | spring-5-examples | MIT License |
drivers/jvm/core/src/main/kotlin/io/pact/plugins/jvm/core/Library.kt | mefellows | 435,380,272 | true | {"Kotlin": 111741, "Rust": 93228, "Groovy": 16726} | package io.pact.plugins.jvm.core
class PactPluginNotFoundException(val name: String, val version: String?) :
RuntimeException("Plugin $name with version ${version ?: "any"} was not found")
class PactPluginEntryNotFoundException(val type: String) :
RuntimeException("No interaction type of '$type' was found in the catalogue")
| 0 | null | 0 | 0 | aa19339ba20b9f4dc9bb6fc2e387d3e8cfd94474 | 334 | pact-plugins | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/test/ClawTest.kt | Petelax | 671,336,777 | false | {"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "XML": 20, "Java": 67, "Kotlin": 66} | package org.firstinspires.ftc.teamcode.drive.test
import com.arcrobotics.ftclib.hardware.ServoEx
import com.arcrobotics.ftclib.hardware.SimpleServo
import com.qualcomm.robotcore.eventloop.opmode.OpMode
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
@TeleOp(group = "test")
class ClawTest: OpMode() {
private lateinit var left: SimpleServo
private lateinit var right: SimpleServo
override fun init() {
left = SimpleServo(hardwareMap, "clawLeft", -10.0, 10.0)
right = SimpleServo(hardwareMap, "clawLeft", -10.0, 10.0)
left.position = 0.0
right.position = 0.0
}
override fun loop() {
if (gamepad1.a) {
left.position = 0.8
right.position = 0.2
}
if (gamepad1.b) {
left.position = 0.2
right.position = 0.8
}
if (gamepad1.x) {
left.position = 0.0
right.position = 0.0
}
}
} | 0 | Java | 0 | 0 | a66accb94638fb15c099bf5a86a2938c348881b9 | 956 | FTC16413-CenterStage | BSD 3-Clause Clear License |
src/main/kotlin/com/chillibits/coronaaid/jackson/JacksonJtsGeometryXMLSerializer.kt | StudentsAgainstCovid19 | 264,461,326 | false | null | package com.chillibits.coronaaid.jackson
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.geom.LineString
import org.locationtech.jts.geom.Polygon
import java.lang.UnsupportedOperationException
class JacksonJtsGeometryXMLSerializer: JsonSerializer<Geometry>() {
override fun serialize(geometry: Geometry, generator: JsonGenerator, ctx: SerializerProvider?) {
if(geometry is Polygon) {
serializePolygon(geometry, generator)
} else {
throw UnsupportedOperationException("JtsGeometryXMLSerializer: Unsupported geometry type!")
}
}
private fun serializePolygon(geometry: Polygon, generator: JsonGenerator) {
generator.writeStartObject()
generator.writeStringField("name", "Polygon")
serializeLineString(geometry.exteriorRing, generator)
for(i in 0 until geometry.numInteriorRing) {
val ring = geometry.getInteriorRingN(i)
serializeLineString(ring, generator)
}
generator.writeEndObject()
}
private fun serializeLineString(lineStr: LineString, generator: JsonGenerator) {
generator.writeObjectFieldStart("ring")
for(cord in lineStr.coordinates) {
generator.writeObjectFieldStart("point")
generator.writeNumberField("lon", cord.x)
generator.writeNumberField("lat", cord.y)
generator.writeEndObject()
}
generator.writeEndObject()
}
override fun handledType() = Geometry::class.java
} | 5 | Kotlin | 0 | 4 | a38fa08cdcde65f9b5da816b9e0812581c8e90ab | 1,693 | corona-aid-api | RSA Message-Digest License |
keel-intent/src/test/kotlin/com/netflix/spinnaker/keel/intent/processor/converter/PipelineConverterTest.kt | amitkhurdhara1990 | 126,823,024 | true | {"Kotlin": 358363, "Shell": 2094} | /*
* Copyright 2018 Netflix, 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.
*/
package com.netflix.spinnaker.keel.intent.processor.converter
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.config.KeelProperties
import com.netflix.spinnaker.config.configureObjectMapper
import com.netflix.spinnaker.hamkrest.shouldEqual
import com.netflix.spinnaker.keel.dryrun.ChangeSummary
import com.netflix.spinnaker.keel.front50.model.PipelineConfig
import com.netflix.spinnaker.keel.intent.JenkinsTrigger
import com.netflix.spinnaker.keel.intent.PipelineFlags
import com.netflix.spinnaker.keel.intent.PipelineProperties
import com.netflix.spinnaker.keel.intent.PipelineSpec
import com.netflix.spinnaker.keel.intent.PipelineStage
import com.netflix.spinnaker.keel.intent.Trigger
import com.netflix.spinnaker.kork.jackson.ObjectMapperSubtypeConfigurer.ClassSubtypeLocator
import org.junit.jupiter.api.Test
object PipelineConverterTest {
val mapper = configureObjectMapper(
ObjectMapper(),
KeelProperties(),
listOf(ClassSubtypeLocator(Trigger::class.java, listOf("com.netflix.spinnaker.keel.intent")))
)
val subject = PipelineConverter(mapper)
@Test
fun `should convert spec to system state`() {
subject.convertToState(spec).also {
it.application shouldEqual spec.application
it.name shouldEqual spec.name
it.limitConcurrent shouldEqual spec.flags.limitConcurrent
it.keepWaitingPipelines shouldEqual spec.flags.keepWaitingPipelines
it.executionEngine shouldEqual spec.properties.executionEngine
it.spelEvaluator shouldEqual spec.properties.spelEvaluator
it.stages shouldEqual listOf(
mapOf(
"showAdvancedOptions" to false,
"baseLabel" to "release",
"user" to "<EMAIL>",
"type" to "bake",
"storeType" to "ebs",
"refId" to "bake1",
"requisiteStageRefIds" to listOf<String>(),
"enhancedNetworking" to false,
"regions" to listOf("us-east-1", "us-west-2"),
"extendedAttributes" to mapOf<Any, Any>(),
"cloudProviderType" to "aws",
"vmType" to "hvm",
"package" to "keel",
"baseOs" to "xenial"
)
)
it.triggers?.size shouldEqual 1
it.triggers?.get(0)?.also { trigger ->
trigger["type"] shouldEqual "jenkins"
trigger["enabled"] shouldEqual true
trigger["master"] shouldEqual "spinnaker"
trigger["job"] shouldEqual "SPINNAKER-package-keel"
trigger["propertyFile"] to ""
}
it.parameterConfig shouldEqual listOf()
it.notifications shouldEqual listOf()
}
}
@Test
fun `should convert system state to spec`() {
val result = subject.convertFromState(state)
result shouldEqual spec
}
@Test
fun `should convert spec to orchestration job`() {
subject.convertToJob(spec, ChangeSummary("test")).also {
it.size shouldEqual 1
it[0]["type"] shouldEqual "savePipeline"
}
}
val spec = PipelineSpec(
application = "keel",
name = "Bake",
stages = listOf(
PipelineStage().apply {
this["showAdvancedOptions"] = false
this["baseLabel"] = "release"
this["user"] = "<EMAIL>"
this["kind"] = "bake"
this["storeType"] = "ebs"
this["refId"] = "bake1"
this["dependsOn"] = listOf<String>()
this["enhancedNetworking"] = false
this["regions"] = listOf("us-east-1", "us-west-2")
this["extendedAttributes"] = mapOf<Any, Any>()
this["cloudProviderType"] = "aws"
this["vmType"] = "hvm"
this["package"] = "keel"
this["baseOs"] = "xenial"
}
),
triggers = listOf(
JenkinsTrigger(mapOf(
"enabled" to true,
"master" to "spinnaker",
"job" to "SPINNAKER-package-keel",
"propertyFile" to ""
))
),
parameters = listOf(),
notifications = listOf(),
flags = PipelineFlags().apply {
this["limitConcurrent"] = true
this["keepWaitingPipelines"] = true
},
properties = PipelineProperties().apply {
this["executionEngine"] = "v3"
}
)
val state = PipelineConfig(
application = "keel",
name = spec.name,
parameterConfig = listOf(),
triggers = listOf(
mapOf(
"type" to "jenkins",
"enabled" to true,
"master" to "spinnaker",
"job" to "SPINNAKER-package-keel",
"propertyFile" to ""
)
),
notifications = listOf(),
stages = listOf(
mapOf(
"showAdvancedOptions" to false,
"baseLabel" to "release",
"user" to "<EMAIL>",
"type" to "bake",
"storeType" to "ebs",
"refId" to "bake1",
"requisiteStageRefIds" to listOf<String>(),
"enhancedNetworking" to false,
"regions" to listOf("us-east-1", "us-west-2"),
"extendedAttributes" to mapOf<Any, Any>(),
"cloudProviderType" to "aws",
"vmType" to "hvm",
"package" to "keel",
"baseOs" to "xenial"
)
),
spelEvaluator = null,
executionEngine = "v3",
limitConcurrent = true,
keepWaitingPipelines = true,
id = null,
index = null,
stageCounter = null,
lastModifiedBy = null,
updateTs = null
)
}
| 0 | Kotlin | 0 | 0 | db755ed4b692a38dcb53d3e5290a36c702ea0ef0 | 5,832 | keel | Apache License 2.0 |
app/src/main/java/io/github/takusan23/jetpackcomposesampleapp/screen/GravitiyCenterScreen.kt | takusan23 | 326,149,019 | false | null | package io.github.takusan23.jetpackcomposesampleapp.screen
import androidx.compose.foundation.layout.*
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Android
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
/**
* 真ん中に表示するサンプル
* */
@Composable
fun CenterContentScreen() {
Column {
Card(
modifier = Modifier.padding(10.dp).fillMaxWidth().height(100.dp),
backgroundColor = Color.Cyan,
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Text(text = "まんなかに居座る Row")
Icon(imageVector = Icons.Outlined.Android)
}
}
Card(
modifier = Modifier.padding(10.dp).fillMaxWidth().height(100.dp),
backgroundColor = Color.Cyan,
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(text = "まんなかに居座る Column")
Icon(imageVector = Icons.Outlined.Android)
}
}
}
} | 0 | Kotlin | 0 | 0 | 4b532246bc7a30759a50500ae66005cd8678d27b | 1,467 | JetpackComposeSampleApp | Apache License 2.0 |
syftlib/src/main/java/fl/wearable/autosport/networking/datamodels/webRTC/JoinRoom.kt | FL-Wearable | 284,693,631 | false | null | package fl.wearable.autosport.networking.datamodels.webRTC
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import fl.wearable.autosport.networking.datamodels.NetworkModels
@Serializable
internal data class JoinRoomRequest(
@SerialName("worker_id")
val workerId: String,
@SerialName("scope_id")
val scopeId: String
) : NetworkModels()
@Serializable
internal data class JoinRoomResponse(
@SerialName("worker_id")
val workerId: String,
@SerialName("scope_id")
val scopeId: String
) : NetworkModels() | 0 | Kotlin | 1 | 3 | 276aee68722432afb2264a3aa27b8ea941873e4f | 565 | Trainer | Apache License 2.0 |
Samples/Legacy/src/androidTest/java/dev/testify/sample/scenario/clients/details/ScenarioClientDetailsViewScreenshotTest.kt | ndtp | 469,416,892 | false | {"Kotlin": 818091, "Shell": 1136} | /*
* The MIT License (MIT)
*
* Copyright (c) 2024 ndtp
*
* 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 dev.testify.sample.scenario.clients.details
import androidx.test.core.app.launchActivity
import dev.testify.annotation.ScreenshotInstrumentation
import dev.testify.annotation.TestifyLayout
import dev.testify.sample.R
import dev.testify.sample.clients.details.ClientDetailsView
import dev.testify.sample.clients.details.ClientDetailsViewState
import dev.testify.sample.test.TestHarnessActivity
import dev.testify.scenario.ScreenshotScenarioRule
import org.junit.Rule
import org.junit.Test
class ScenarioClientDetailsViewScreenshotTest {
@get:Rule
val rule = ScreenshotScenarioRule(
rootViewId = R.id.harness_root,
enableReporter = true
)
@TestifyLayout(R.layout.view_client_details)
@ScreenshotInstrumentation
@Test
fun default() {
launchActivity<TestHarnessActivity>().use { scenario ->
rule
.withScenario(scenario)
.setViewModifications { harnessRoot ->
val viewState = ClientDetailsViewState(
name = "<NAME>",
avatar = R.drawable.avatar1,
heading = "This is the heading",
address = "1 Address Street\nCity, State, Country\nZ1PC0D3",
phoneNumber = "1-234-567-8910"
)
val view = harnessRoot.getChildAt(0) as ClientDetailsView
view.render(viewState)
rule.activity.title = viewState.name
}
.assertSame()
}
}
@TestifyLayout(layoutResName = "dev.testify.sample:layout/view_client_details")
@ScreenshotInstrumentation
@Test
fun usingLayoutResName() {
launchActivity<TestHarnessActivity>().use { scenario ->
rule
.withScenario(scenario)
.setViewModifications { harnessRoot ->
val viewState = ClientDetailsViewState(
name = "Using Res Name",
avatar = R.drawable.avatar1,
heading = "This is the heading",
address = "1 Address Street\nCity, State, Country\nZ1PC0D3",
phoneNumber = "1-234-567-8910"
)
val view = harnessRoot.getChildAt(0) as ClientDetailsView
view.render(viewState)
rule.activity.title = viewState.name
}
.assertSame()
}
}
}
| 39 | Kotlin | 5 | 99 | 6698806da6b56e5d9184b59f9e380c5798e615e0 | 3,673 | android-testify | MIT License |
app/src/main/java/chat/rocket/android/preferences/di/PreferencesFragmentModule.kt | powermobileweb | 170,920,708 | false | null | package chat.rocket.android.preferences.di
import chat.rocket.android.dagger.scope.PerFragment
import chat.rocket.android.preferences.presentation.PreferencesView
import chat.rocket.android.preferences.ui.PreferencesFragment
import dagger.Module
import dagger.Provides
@Module
class PreferencesFragmentModule {
@Provides
@PerFragment
fun preferencesView(frag: PreferencesFragment): PreferencesView {
return frag
}
} | 0 | Kotlin | 1 | 7 | 3c6dc69e04ac9f96ea90cc614261355d18863b45 | 442 | Rocket.Chat.Android | MIT License |
app/src/main/java/cc/aoeiuv020/actionrecorder/util/view.kt | AoEiuV020 | 110,344,642 | false | null | @file:Suppress("unused")
package cc.aoeiuv020.actionrecorder.util
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import android.view.View
import androidx.core.app.NotificationCompat
import cc.aoeiuv020.actionrecorder.R
import cc.aoeiuv020.actionrecorder.ui.MainActivity
import org.jetbrains.anko.intentFor
/**
*
* Created by AoEiuV020 on 2017.11.11-22:10:59.
*/
fun Context.notify(id: Int, text: String? = null, title: String? = null, noCancel: Boolean = false): Notification? {
val icon = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
R.mipmap.ic_launcher_round
} else {
R.mipmap.ic_launcher_foreground
}
val channelId = "channel_default"
val name = "default"
val notification = NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(icon)
.setSound(null)
.setContentIntent(PendingIntent.getActivity(this, 1, intentFor<MainActivity>(), 0))
.build()
if (noCancel) {
notification.flags = notification.flags or Notification.FLAG_NO_CLEAR
}
val manager = (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (manager.getNotificationChannel(channelId) == null) {
val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_DEFAULT)
channel.setSound(null, null)
manager.createNotificationChannel(channel)
}
}
manager.notify(id, notification)
return notification
}
fun Context.cancel(id: Int) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(id)
}
fun View.hide() {
visibility = View.GONE
}
fun View.show() {
visibility = View.VISIBLE
}
fun View.show(show: Boolean) {
if (show) {
show()
} else {
hide()
}
}
| 1 | Kotlin | 0 | 3 | ca3cab65aad287146992dabb790eac484472bfc3 | 2,095 | ScreenLockRecorder | MIT License |
cryptography-providers/webcrypto/src/jsMain/kotlin/internal/Keys.js.kt | whyoleg | 492,907,371 | false | {"Kotlin": 1074574, "JavaScript": 318} | /*
* Copyright (c) 2024 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.whyoleg.cryptography.providers.webcrypto.internal
internal actual external interface CryptoKey
internal actual external interface CryptoKeyPair {
actual val privateKey: CryptoKey
actual val publicKey: CryptoKey
}
internal actual val CryptoKey.algorithm: Algorithm get() = keyAlgorithm(this)
@Suppress("UNUSED_PARAMETER")
private fun keyAlgorithm(key: CryptoKey): Algorithm = js("key.algorithm").unsafeCast<Algorithm>()
| 10 | Kotlin | 20 | 302 | 69b77a88b4b81109704475ed02be48d263d1a1c8 | 544 | cryptography-kotlin | Apache License 2.0 |
app/src/main/java/com/clean/arch/mvvm/ui/movie/MovieViewModel.kt | Vova-SH | 387,110,908 | false | null | package com.clean.arch.mvvm.ui.movie
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.clean.arch.mvvm.data.entities.Actor
import com.clean.arch.mvvm.data.entities.Movie
import com.clean.arch.mvvm.data.repositories.MovieRepository
import com.clean.arch.mvvm.utils.State
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class MovieViewModel(
private val repository: MovieRepository,
private val movie: Movie
) : ViewModel() {
val stateMovie: LiveData<State<Movie>> = liveData {
emit(State.Loading())
withContext(Dispatchers.IO) {
try {
emit(State.Success(repository.getMovie(movie.id)))
} catch (e: Exception) {
emit(State.Error<Movie>(e))
}
}
}
val stateActors: LiveData<State<List<Actor>>> = liveData {
emit(State.Loading())
withContext(Dispatchers.IO) {
try {
emit(State.Success(repository.getMovieCredits(movie.id)))
} catch (e: Exception) {
emit(State.Error<List<Actor>>(e))
}
}
}
} | 0 | Kotlin | 2 | 0 | 6c3c16a1c82569a26c7c27f7fff44160ccb73e5a | 1,191 | Samsung-Bootcamp-2021 | Creative Commons Attribution 4.0 International |
androidApp/src/main/java/dev/fummicc1/viary/android/ui/viaryList/ViaryItem.kt | fummicc1 | 356,189,749 | false | null | package dev.fummicc1.viary.android.ui.viaryList
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import dev.fummicc1.viary.android.R
import dev.fummicc1.viary.shared.db.Viary
@Composable
fun ViaryItem(viary: Viary, modifier: Modifier = Modifier) {
var toggleDetailVisibility: Boolean by remember {
mutableStateOf(false)
}
Column(modifier = Modifier
.clickable {
toggleDetailVisibility = toggleDetailVisibility.not()
}
.padding(12.dp)) {
Row() {
Image(
painterResource(
id = if (toggleDetailVisibility) R.drawable.ic_baseline_keyboard_arrow_down_24 else R.drawable.ic_baseline_keyboard_arrow_right_24
), contentDescription = null,
colorFilter = ColorFilter.tint(MaterialTheme.colors.primary)
)
Text(text = viary.title)
}
if (toggleDetailVisibility) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Surface(
color = MaterialTheme.colors.primary,
modifier = Modifier.padding(),
shape = RoundedCornerShape(8.dp)
) {
Text(
text = viary.content,
fontWeight = FontWeight.Light,
modifier = modifier.padding(12.dp)
)
}
}
}
}
} | 2 | Kotlin | 0 | 0 | 711e5ec7e74c6dd60dd04dc05546f6908fa8b0c5 | 2,216 | Viary | MIT License |
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/Dispatcher.kt | sys1yagi | 88,990,462 | false | null | package com.sys1yagi.mastodon4j.api
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class Dispatcher {
val executorService: ExecutorService = Executors.newFixedThreadPool(1, { r ->
val thread = Thread(r)
thread.isDaemon = true
return@newFixedThreadPool thread
})
val lock = ReentrantLock()
val shutdownTime = 1000L
fun invokeLater(task: Runnable) = executorService.execute(task)
fun shutdown() {
lock.withLock {
executorService.shutdown()
if (!executorService.awaitTermination(shutdownTime, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow()
}
}
}
}
| 3 | null | 18 | 91 | b7fbb565abd024ce113e3a6f0caf2eb9bbc10fc7 | 833 | mastodon4j | MIT License |
src/main/java/org/runestar/cs2/cfa/Construct.kt | naxy0 | 388,274,367 | true | {"Kotlin": 120162, "Java": 19324} | package org.runestar.cs2.cfa
import org.runestar.cs2.ir.Expression
import org.runestar.cs2.ir.Instruction
import java.util.ArrayList
interface Construct {
var next: Construct?
class Seq(
val instructions: MutableList<Instruction> = ArrayList()
) : Construct {
override var next: Construct? = null
}
class Branch(var condition: Expression.Operation, var body: Construct)
class If(
val branches: MutableList<Branch> = ArrayList()
) : Construct {
var elze: Construct? = null
override var next: Construct? = null
}
class While(
val condition: Expression.Operation
): Construct {
lateinit var body: Construct
override var next: Construct? = null
}
class Switch(
val expression: Expression,
val cases: Map<Set<Int>, Construct>
) : Construct {
var default: Construct? = null
override var next: Construct? = null
}
} | 0 | null | 0 | 0 | 2588d0b14db5f7b998df7d2282182aca2311a913 | 995 | cs2 | MIT License |
sosialhjelp-common-selftest/src/main/kotlin/no/nav/sosialhjelp/selftest/Results.kt | navikt | 267,318,486 | false | null | package no.nav.sosialhjelp.selftest
import com.fasterxml.jackson.annotation.JsonIgnore
data class DependencyCheckResult(
val endpoint: String,
val result: Result,
val address: String,
val errorMessage: String?,
val type: DependencyType,
val importance: Importance,
val responseTime: String?,
@JsonIgnore
val throwable: Throwable?
)
data class SelftestResult(
val appName: String,
val version: String,
val result: Result,
val dependencyCheckResults: List<DependencyCheckResult>
)
enum class DependencyType {
REST, DB
}
enum class Importance {
CRITICAL, WARNING
}
enum class Result {
OK, WARNING, ERROR
}
| 0 | Kotlin | 0 | 0 | 002ad2595bbd9dff24d12bb1582346a9536ec8c8 | 673 | sosialhjelp-common | MIT License |
app/src/main/java/com/cerist/summer/virtualassistant/Repositories/AirConditionerRepository.kt | FdevTech | 350,458,396 | false | null | package com.cerist.summer.virtualassistant.Repositories
import android.util.Log
import com.cerist.summer.virtualassistant.Entities.BroadLinkProfile
import com.cerist.summer.virtualassistant.Utils.Data.Status
import com.polidea.rxandroidble2.RxBleConnection
import com.polidea.rxandroidble2.RxBleDevice
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Executor
class AirConditionerRepository(private val broadLinkRepository: BroadLinkRepository,
private val bluetoothExecutor: Executor) : IRepository {
companion object {
private val TAG = "AirConditionerRepo"
}
val broadLinkConnection: Observable<RxBleConnection>
val broadLinkConnectionState:Observable<RxBleConnection.RxBleConnectionState>
init {
broadLinkConnection = broadLinkRepository.broadLinkConnection
broadLinkConnectionState = broadLinkRepository.broadLinkConnectionState
}
fun getAirConditionerPowerState(bleConnection: RxBleConnection)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
Log.d(TAG,"Reading the air conditioner power state characteristic")
it.readCharacteristic(UUID.fromString(BroadLinkProfile.AirConditionerProfile.STATE_CHARACTERISTIC_UUID))
.toObservable()}
.flatMap {
Observable.just(it.toString(Charset.defaultCharset()).toInt()) }
.flatMap {
when (it) {
0 -> Observable.just(BroadLinkProfile.AirConditionerProfile.State.OFF)
1 -> Observable.just(BroadLinkProfile.AirConditionerProfile.State.ON)
else -> Observable.error(Throwable(Status.OPERATION_ERROR))
}}
.share()!!
fun getAirConditionerMode(bleConnection: RxBleConnection)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
Log.d(TAG,"Reading the air conditioner mode characteristic")
it.readCharacteristic(UUID.fromString(BroadLinkProfile.AirConditionerProfile.MODE_CHARACTERISTIC_UUID))
.toObservable()}
.flatMap {
Observable.just(it.toString(Charset.defaultCharset()).toInt()) }
.flatMap {
when (it) {
0 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.SLEEP)
1 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.ENERGY_SAVER)
2 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.FUN)
3 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.COOL)
else -> Observable.error(Throwable(Status.OPERATION_ERROR))
}}
.share()!!
fun getAirConditionerTemp(bleConnection: RxBleConnection)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
Log.d(TAG,"Reading the air conditioner temperature characteristic")
it.readCharacteristic(UUID.fromString(BroadLinkProfile.AirConditionerProfile.TEMPERATURE_UP_CHARACTERISTIC_UUID))
.toObservable()}
.flatMap {
Observable.just(it.toString(Charset.defaultCharset()).toInt()) }
.flatMap {
if(it in BroadLinkProfile.AirConditionerProfile.MIN_TEMP
.. BroadLinkProfile.AirConditionerProfile.MAX_TEMP)
Observable.just(it)
else
Observable.error(Throwable(Status.OPERATION_ERROR))
}
.share()!!
fun setAirConditionerPowerState(bleConnection: RxBleConnection,state: BroadLinkProfile.AirConditionerProfile.State)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
Log.d(TAG,"Writing the air conditioner power state characteristic")
it.writeCharacteristic(UUID.fromString( BroadLinkProfile.AirConditionerProfile.STATE_CHARACTERISTIC_UUID),
byteArrayOf(state.value.toByte())).toObservable()
}
.flatMap {
Observable.just(it[0].toInt())
}
.flatMap {
when (it) {
0 -> Observable.just(BroadLinkProfile.AirConditionerProfile.State.OFF)
1 -> Observable.just(BroadLinkProfile.AirConditionerProfile.State.ON)
else -> Observable.error(Throwable(Status.OPERATION_ERROR))
}
}
.share()!!
fun setAirConditionerMode(bleConnection: RxBleConnection,mode:BroadLinkProfile.AirConditionerProfile.Mode)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
Log.d(TAG,"Writing the air conditioner mode characteristic")
it.writeCharacteristic(UUID.fromString( BroadLinkProfile.AirConditionerProfile.MODE_CHARACTERISTIC_UUID), byteArrayOf(mode.value.toByte())).toObservable()
}
.flatMap {
Observable.just(it[0].toInt())
}
.flatMap {
when (it) {
0 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.SLEEP)
1 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.ENERGY_SAVER)
2 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.FUN)
3 -> Observable.just(BroadLinkProfile.AirConditionerProfile.Mode.COOL)
else -> Observable.error(Throwable(Status.OPERATION_ERROR))
}}
.share()!!
fun setAirConditionerTemp(bleConnection: RxBleConnection,temperature:Int)
= Observable.just(bleConnection)
.observeOn(Schedulers.from(bluetoothExecutor))
.flatMap {
if(temperature in BroadLinkProfile.AirConditionerProfile.MIN_TEMP
.. BroadLinkProfile.AirConditionerProfile.MAX_TEMP)
Observable.just(it)
else
Observable.error(Throwable(Status.OPERATION_ERROR))
}
.flatMap { getAirConditionerTemp(it) }
.flatMap {
Log.d(TAG,"Writing the air conditioner temperature characteristic")
if(temperature > it)
bleConnection.writeCharacteristic(UUID.fromString( BroadLinkProfile.AirConditionerProfile.TEMPERATURE_UP_CHARACTERISTIC_UUID),
byteArrayOf(temperature.toByte())).toObservable()
else
bleConnection.writeCharacteristic(UUID.fromString( BroadLinkProfile.AirConditionerProfile.TEMPERATURE_DOWN_CHARACTERISTIC_UUID),
byteArrayOf(temperature.toByte())).toObservable()
}
.flatMap{
Observable.just(it[0].toInt())
}
.share()!!
} | 0 | Kotlin | 0 | 0 | 3ab66a9fc551cc6cddaa617a7b9940bb9dcdee6a | 8,381 | Selma | MIT License |
view/mongo/src/main/kotlin/io/holunda/polyflow/view/mongo/task/TaskRepositoryExtension.kt | margue | 384,111,593 | true | {"Kotlin": 647631} | package io.holunda.polyflow.view.mongo.task
interface TaskRepositoryExtension : TaskCountByApplicationRepositoryExtension, TaskUpdatesExtension
| 0 | null | 0 | 0 | d5797861e5d7126dcdfd5e5b9cca8478f887cf68 | 145 | camunda-bpm-taskpool | Apache License 2.0 |
app/src/main/java/com/taitascioredev/android/chucknorrisquotes/dagger/module/NetModule.kt | phanghos | 115,355,159 | false | null | package com.taitascioredev.android.chucknorrisquotes.dagger.module
import com.taitascioredev.android.chucknorrisquotes.data.net.ChuckNorrisApi
import com.taitascioredev.android.chucknorrisquotes.data.net.ChuckNorrisService
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
/**
* Created by rrtatasciore on 24/12/17.
*/
@Module
class NetModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
return OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(ChuckNorrisApi.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideChuckNorrisApi(retrofit: Retrofit): ChuckNorrisApi = retrofit.create(ChuckNorrisApi::class.java)
@Provides
@Singleton
fun provideChuckNorrisService(chuckNorrisApi: ChuckNorrisApi): ChuckNorrisService = ChuckNorrisService(chuckNorrisApi)
} | 0 | Kotlin | 0 | 2 | c1914d52a37a9bc4d5ae41d168fedd0439690f40 | 1,596 | mvi-kotlin-rxjava-livedata-dagger-example | MIT License |
ybatis/src/test/kotlin/com.sununiq/loader/YbatisLoaderTest.kt | Sitrone | 155,659,453 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Maven POM": 3, "XML": 3, "Kotlin": 44, "Java": 12, "YAML": 1} | package com.sununiq.loader
import com.sununiq.Ybatis
import com.sununiq.domain.User
import com.sununiq.entity.Table
import com.sununiq.handler.TableMapper
import com.sununiq.handler.token.TokenParser
import com.sununiq.util.getResourceAsString
import com.sununiq.util.parseXml
import com.sununiq.util.println
import com.sununiq.util.transform2String
import org.apache.commons.lang3.StringEscapeUtils
import org.junit.Test
import org.w3c.dom.Document
import org.w3c.dom.Node
import java.util.*
class YbatisLoaderTest {
private val target = """
<insert id="insertSelective"
keyProperty="@{primaryColumns.0.jdbcName}" useGeneratedKeys="true"
parameterType="@{domainClassName}">
insert into @{tableName}
(
<enhancer:foreach list="primaryColumns" var="elem"
split=",">
`@{elem.jdbcName}`
</enhancer:foreach>
<enhancer:foreach list="normalColumns" var="elem">
<if test="@{elem.javaName} != null">
,`@{elem.jdbcName}`
</if>
</enhancer:foreach>
)
values (
<enhancer:foreach list="primaryColumns" var="elem">
#{@{elem.javaName}}
</enhancer:foreach>
<enhancer:foreach list="normalColumns" var="elem">
<if test="@{elem.javaName} != null">
, #{@{elem.javaName}}
</if>
</enhancer:foreach>
)
</insert>
""".trimIndent()
private val tokenParser = TokenParser()
@Test
fun testParseSpecialTag() {
val document = parseXml(getResourceAsString("ybatis.xml"))
// val document = parseXml(target)
val table = initTable()
val element = document.documentElement
doHandleSpecialNode(element, table, document)
val parse = tokenParser.parse(table, transform2String(element))
StringEscapeUtils.unescapeXml(parse).println()
}
private fun initTable(): Table {
val tableMapper = TableMapper()
return tableMapper.mapper2Table(User::class.java, "com.sununiq.domain")
}
/**
* 递归 dfs遍历
*/
private fun doHandleSpecialNode(node: Node, table: Table, document: Document) {
if (node.hasChildNodes()) {
for (i in 0 until node.childNodes.length) {
doHandleSpecialNode(node.childNodes.item(i), table, document)
}
}
val parentNode = node.parentNode
Ybatis.assistHandlers.forEach {
if (node.nodeName == it.key) {
val parseResult = it.value.process(table, node, tokenParser)
val textNode = document.createTextNode(parseResult)
parentNode.replaceChild(textNode, node)
}
}
}
private fun doHandleNormalNode(node: Node, table: Table, document: Document) {
doHandleAttribute(node, table)
if (node.hasChildNodes()) {
for (i in 0 until node.childNodes.length) {
doHandleNormalNode(node.childNodes.item(i), table, document)
}
} else {
val parentNode = node.parentNode
val source = transform2String(node)
val parse = tokenParser.parse(table, source)
parentNode.replaceChild(document.createTextNode(parse), node)
}
}
private fun doHandleAttribute(node: Node, table: Table) {
if (!node.hasAttributes()) return
val attributes = node.attributes
for (i in 0 until attributes.length) {
val item = attributes.item(i)
item.nodeValue = tokenParser.parse(table, item.nodeValue)
}
}
/**
* dfs遍历处理自定义的标签
*/
private fun doHandleSpecialNode1(node: Node, table: Table, document: Document) {
val stack = Stack<Node>()
stack.push(node)
while (stack.isNotEmpty()) {
val curNode = stack.pop()
if (curNode.hasChildNodes()) {
for (i in 0 until curNode.childNodes.length) {
stack.push(curNode.childNodes.item(i))
}
}
if (Ybatis.assistHandlers.containsKey(curNode.nodeName)) {
val parentNode = curNode.parentNode
Ybatis.assistHandlers.entries.forEach {
if (curNode.nodeName == it.key) {
val parseResult = it.value.process(table, curNode, tokenParser)
val textNode = document.createTextNode(parseResult)
parentNode.replaceChild(textNode, curNode)
}
}
}
}
}
} | 1 | null | 1 | 1 | e06616a6f541f45ec7f61707667eda6af04d15e1 | 4,845 | mybatis-enhancer | MIT License |
core/src/commonMain/kotlin/org/kobjects/greenspun/core/memory/Memory.kt | kobjects | 340,712,554 | false | {"Kotlin": 118522, "Ruby": 1673} | package org.kobjects.greenspun.core.memory
import org.kobjects.greenspun.core.binary.WasmOpcode
import org.kobjects.greenspun.core.func.LocalRuntimeContext
import org.kobjects.greenspun.core.module.ModuleWriter
import org.kobjects.greenspun.core.tree.AbstractLeafNode
import org.kobjects.greenspun.core.tree.CodeWriter
import org.kobjects.greenspun.core.type.I32
import org.kobjects.greenspun.core.type.Type
class MemorySize() : AbstractLeafNode() {
override fun eval(context: LocalRuntimeContext) =
context.instance.memory.buffer.size / 65536
override fun toString(writer: CodeWriter) = writer.write("MemorySize()")
override fun toWasm(writer: ModuleWriter) = writer.write(WasmOpcode.MEMORY_SIZE)
override val returnType: Type
get() = I32
} | 0 | Kotlin | 0 | 0 | 0276fab4f536016b1133575ffc9c940fc24a0509 | 779 | greenspun | Apache License 2.0 |
src/main/kotlin/StringJoin.kt | jayTobi | 119,671,405 | false | null | @file:JvmName("StringJoin")
//this defines the name for the created Java class
//must be placed before package declaration
package strings
//top level property
//without const getter will be generated for Java (var: get + set)
//with const it will be public static final field in the generated class
const val DEFAULT_ELEMENT_SEPARATOR = "/ "
//package declaration - no need for special folder layout as in Java
//this function without an encapsulating class is called a TOP LEVEL function
// (It will be created as a static function in a Java class (StringJoin see annotation above), so it can also be used in Java)
/**
* (TOP LEVEL) function takes a Collection of elements and appends each element to a String that is returned.
*
* @param collection The collection with elements that will be appended one after another
* @param separator Separator used between values, default value is "; " (used if parameter is not provided)
* @param prefix Prefix used before the first element, i.e. the start of the String, default is "<"
* @param postfix Postfix used after the first element, i.e. the end of the String, default is ">"
*/
@JvmOverloads //annotation creates overloaded Java methods, because default values for parameters are not supported in Java
fun <T> joinToString(collection: Collection<T>,
separator: String = "; ", //variable name with type and default value
prefix: String = "<",
postfix: String = ">"): String { //: String at the end defines the return type of the function
val result = StringBuilder(prefix) //no var needed - although val can't be reassigned the object can be altered
//using destructuring declarations (unpack single composite value into multiple variables) and special withIndex method
for ((index, element) in collection.withIndex()) {
if (index > 0) {
result.append(separator)
}
result.append(element)
}
result.append(postfix)
return result.toString()
} | 0 | Kotlin | 0 | 0 | 9d088eddb92dfbbe2d7d464eab900036f3a21750 | 2,026 | kotlin-examples | Apache License 2.0 |
dslitem/src/main/java/com/angcyo/item/LibEx.kt | angcyo | 231,295,668 | false | null | package com.angcyo.item
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.InputFilter
import android.text.TextPaint
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.OverScroller
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.annotation.Px
import androidx.core.content.ContextCompat
import androidx.core.widget.ScrollerCompat
import androidx.core.widget.TextViewCompat
import com.angcyo.dsladapter.DslViewHolder
import com.angcyo.dsladapter.L
import com.angcyo.dsladapter.internal.ThrottleClickListener
import com.angcyo.item.base.LibInitProvider
import com.angcyo.widget.DslButton
import com.angcyo.widget.edit.SingleTextWatcher
import com.angcyo.widget.span.undefined_int
import java.util.*
import kotlin.math.max
import kotlin.math.min
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2020/04/27
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
fun Int.remove(value: Int): Int = this and value.inv()
fun Int.add(value: Int): Int = this or value
fun TextView.addFlags(add: Boolean, flat: Int) {
val paint: TextPaint = paint
paint.addPaintFlags(add, flat)
postInvalidate()
}
fun Paint.addPaintFlags(add: Boolean, flat: Int) {
flags = if (add) {
flags.add(flat)
} else {
flags.remove(flat)
}
}
/**文本的宽度*/
fun Paint.textWidth(text: String?): Float {
if (text == null) {
return 0f
}
return measureText(text)
}
/**文本的高度*/
fun Paint?.textHeight(): Float = this?.run { descent() - ascent() } ?: 0f
/**
* 设置是否加粗文本
*/
fun TextView.setBoldText(bool: Boolean) {
addFlags(bool, Paint.FAKE_BOLD_TEXT_FLAG)
}
fun TextView.setLeftIco(id: Int) {
setLeftIco(loadDrawable(id))
}
fun TextView.setLeftIco(drawable: Drawable?) {
val compoundDrawables: Array<Drawable?> = compoundDrawables
setCompoundDrawablesWithIntrinsicBounds(
drawable, compoundDrawables[1], compoundDrawables[2], compoundDrawables[3]
)
}
fun TextView.setRightIco(@DrawableRes id: Int) {
setRightIco(loadDrawable(id))
}
fun TextView.setRightIco(drawable: Drawable?) {
val compoundDrawables: Array<Drawable?> = compoundDrawables
setCompoundDrawablesWithIntrinsicBounds(
compoundDrawables[0], compoundDrawables[1], drawable, compoundDrawables[3]
)
}
fun View.loadDrawable(@DrawableRes id: Int): Drawable? {
return context?.loadDrawable(id)
}
fun Context.loadDrawable(id: Int): Drawable? {
if (id <= 0) {
return null
}
return try {
ContextCompat.getDrawable(this, id)?.initBounds()
} catch (e: Exception) {
L.w(e)
null
}
}
/**初始化bounds*/
fun Drawable.initBounds(width: Int = undefined_int, height: Int = undefined_int): Drawable {
if (bounds.isEmpty) {
val w = if (width == undefined_int) minimumWidth else width
val h = if (height == undefined_int) minimumHeight else height
bounds.set(0, 0, w, h)
}
return this
}
fun ViewGroup.inflate(@LayoutRes layoutId: Int, attachToRoot: Boolean = true): View {
if (layoutId == -1) {
return this
}
val rootView = LayoutInflater.from(context).inflate(layoutId, this, false)
if (attachToRoot) {
addView(rootView)
}
return rootView
}
fun TextView?.string(trim: Boolean = true): String {
if (this == null) {
return ""
}
var rawText = if (TextUtils.isEmpty(text)) {
""
} else {
text.toString()
}
if (trim) {
rawText = rawText.trim { it <= ' ' }
}
return rawText
}
/**只要文本改变就通知*/
fun EditText.onTextChange(
defaultText: CharSequence? = string(), shakeDelay: Long = -1L,//去频限制, 负数表示不开启
listener: (CharSequence) -> Unit
) {
addTextChangedListener(object : SingleTextWatcher() {
var mainHandle: Handler? = null
val callback: Runnable = Runnable {
listener.invoke(lastText ?: "")
}
init {
if (shakeDelay >= 0) {
mainHandle = Handler(Looper.getMainLooper())
}
}
var lastText: CharSequence? = defaultText
override fun onTextChanged(sequence: CharSequence?, start: Int, before: Int, count: Int) {
super.onTextChanged(sequence, start, before, count)
mainHandle?.removeCallbacks(callback)
val text = sequence?.toString() ?: ""
if (TextUtils.equals(lastText, text)) {
} else {
lastText = text
if (mainHandle == null) {
callback.run()
} else {
mainHandle?.postDelayed(callback, shakeDelay)
}
}
}
})
}
/**
* 从一个对象中, 获取指定的成员对象
*/
fun Any?.getMember(member: String): Any? {
return this?.run { this.getMember(this.javaClass, member) }
}
fun Any?.getMember(
cls: Class<*>, member: String
): Any? {
var result: Any? = null
try {
val memberField = cls.getDeclaredField(member)
memberField.isAccessible = true
result = memberField[this]
} catch (e: Exception) {
//L.i("错误:" + cls.getSimpleName() + " ->" + e.getMessage());
}
return result
}
fun Any?.getCurrVelocity(): Float {
return when (this) {
is OverScroller -> currVelocity
is ScrollerCompat -> currVelocity
else -> {
0f
}
}
}
fun MotionEvent.isTouchDown(): Boolean {
return actionMasked == MotionEvent.ACTION_DOWN
}
fun MotionEvent.isTouchFinish(): Boolean {
return actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL
}
fun MotionEvent.isTouchMove(): Boolean {
return actionMasked == MotionEvent.ACTION_MOVE
}
/**清空所有[TextWatcher]*/
fun TextView.clearListeners() {
try {
val mListeners: ArrayList<*>? =
getMember(TextView::class.java, "mListeners") as? ArrayList<*>
mListeners?.clear()
} catch (e: Exception) {
L.e(e)
}
}
fun TextView?.setMaxLine(maxLine: Int = 1) {
this?.run {
if (maxLine <= 1) {
isSingleLine = true
ellipsize = TextUtils.TruncateAt.END
maxLines = 1
} else {
isSingleLine = false
maxLines = maxLine
}
}
}
/**设置文本, 并且将光标至于文本最后面*/
fun TextView.setInputText(text: CharSequence? = null, selection: Boolean = true) {
setText(text)
if (selection && this is EditText) {
setSelection(min(text?.length ?: 0, getText().length))
}
}
fun View?.padding(p: Int) {
this?.setPadding(p, p, p, p)
}
@ColorInt
fun _color(@ColorRes id: Int): Int {
return getColor(id)
}
@Px
fun _dimen(@DimenRes id: Int, context: Context = LibInitProvider.contentProvider): Int {
return getDimen(id, context)
}
@Px
fun getDimen(@DimenRes id: Int, context: Context = LibInitProvider.contentProvider): Int {
return context.getDimen(id)
}
@Px
fun Context.getDimen(@DimenRes id: Int): Int {
return resources.getDimensionPixelOffset(id)
}
@ColorInt
fun getColor(@ColorRes id: Int): Int {
return ContextCompat.getColor(LibInitProvider.contentProvider, id)
}
fun View?.visible(value: Boolean = true) {
this?.visibility = if (value) View.VISIBLE else View.GONE
}
fun View?.gone(value: Boolean = true) {
this?.visibility = if (value) View.GONE else View.VISIBLE
}
fun Int.getSize(): Int {
return View.MeasureSpec.getSize(this)
}
fun Int.getMode(): Int {
return View.MeasureSpec.getMode(this)
}
/**match_parent*/
fun Int.isExactly(): Boolean {
return getMode() == View.MeasureSpec.EXACTLY
}
/**wrap_content*/
fun Int.isAtMost(): Boolean {
return getMode() == View.MeasureSpec.AT_MOST
}
fun Int.isUnspecified(): Boolean {
return getMode() == View.MeasureSpec.UNSPECIFIED
}
/**未指定大小*/
fun Int.isNotSpecified(): Boolean {
return isAtMost() || isUnspecified()
}
/**点击事件*/
fun View?.clickIt(action: (View) -> Unit) {
this?.setOnClickListener(action)
}
/**隐藏软键盘*/
fun View.hideSoftInput() {
val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.hideSoftInputFromWindow(windowToken, 0)
}
/**显示软键盘*/
fun View.showSoftInput() {
if (this is EditText) {
requestFocus()
val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.showSoftInput(this, 0)
}
}
fun TextView.addFilter(filter: InputFilter) {
val oldFilters = filters
val newFilters = arrayOfNulls<InputFilter>(oldFilters.size + 1)
System.arraycopy(oldFilters, 0, newFilters, 0, oldFilters.size)
newFilters[oldFilters.size] = filter
filters = newFilters
}
/**移除指定[InputFilter]*/
fun TextView.removeFilter(predicate: InputFilter.() -> Boolean) {
val oldFilters = filters
val removeList = mutableListOf<InputFilter>()
oldFilters.forEach {
if (it.predicate()) {
removeList.add(it)
}
}
if (removeList.isEmpty()) {
return
}
val list = oldFilters.toMutableList().apply {
removeAll(removeList)
}
filters = list.toTypedArray()
}
fun TextView.leftIco() = TextViewCompat.getCompoundDrawablesRelative(this)[0]
fun TextView.topIco() = TextViewCompat.getCompoundDrawablesRelative(this)[1]
fun TextView.rightIco() = TextViewCompat.getCompoundDrawablesRelative(this)[2]
fun TextView.bottomIco() = TextViewCompat.getCompoundDrawablesRelative(this)[3]
/**恢复选中范围*/
fun EditText.restoreSelection(start: Int, stop: Int) {
val length = text.length
val _start = if (start in 0..length) {
start
} else {
-1
}
val _stop = if (stop in 0..length) {
stop
} else {
-1
}
if (_stop >= 0) {
val min = min(max(0, _start), _stop)
val max = max(max(0, _start), _stop)
setSelection(min, max)
} else if (_start >= 0) {
setSelection(_start)
}
}
fun View.save(canvas: Canvas, paint: Paint? = null): Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), paint)
} else {
canvas.saveLayer(
0f, 0f, width.toFloat(), height.toFloat(), paint, Canvas.ALL_SAVE_FLAG
)
}
}
fun View.viewRect(result: RectF = RectF()): RectF {
result.set(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat())
return result
}
fun View.viewRect(result: Rect = Rect()): Rect {
result.set(0, 0, measuredWidth, measuredHeight)
return result
}
fun View.drawRect(rect: Rect) {
rect.set(paddingLeft, paddingTop, measuredWidth - paddingRight, measuredHeight - paddingBottom)
}
fun Collection<*>?.size() = this?.size ?: 0
/**判断2个列表中的数据是否改变过*/
fun <T> Collection<T>?.isChange(other: List<T>?): Boolean {
if (this.size() != other.size()) {
return true
}
this?.forEachIndexed { index, t ->
if (t != other?.getOrNull(index)) {
return true
}
}
return false
}
fun DslViewHolder.button(@IdRes id: Int): DslButton? = v(id)
fun Any?.string(def: CharSequence = ""): CharSequence {
return when {
this == null -> return def
this is TextView -> text ?: def
this is CharSequence -> this
else -> this.toString()
}
}
fun Any.toStr(): String = when (this) {
is String -> this
else -> toString()
}
/**点击事件节流处理*/
fun View?.throttleClickIt(action: (View) -> Unit) {
this?.setOnClickListener(ThrottleClickListener(action = action))
}
val View.drawLeft get() = paddingLeft
val View.drawTop get() = paddingTop
val View.drawRight get() = measuredWidth - paddingRight
val View.drawBottom get() = measuredHeight - paddingBottom
val View.drawWidth get() = drawRight - drawLeft
val View.drawHeight get() = drawBottom - drawTop
val View.drawCenterX get() = drawLeft + drawWidth / 2
val View.drawCenterY get() = drawTop + drawHeight / 2 | 0 | Kotlin | 2 | 13 | 92c5a7c665636c7af4c1f497c41657653ae80326 | 12,494 | DslItem | MIT License |
app/src/main/java/com/netchar/wallpaperify/ui/photos/PhotosFragment.kt | netchar | 171,912,089 | false | null | /*
* Copyright © 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netchar.wallpaperify.ui.photos
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import androidx.appcompat.widget.Toolbar
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.netchar.common.base.BaseFragment
import com.netchar.common.extensions.*
import com.netchar.common.poweradapter.adapter.EndlessRecyclerDataSource
import com.netchar.common.poweradapter.adapter.RecyclerAdapter
import com.netchar.repository.pojo.ErrorMessage
import com.netchar.repository.pojo.PhotoPOJO
import com.netchar.wallpaperify.R
import com.netchar.wallpaperify.di.ViewModelFactory
import com.netchar.wallpaperify.di.modules.GlideApp
import com.netchar.wallpaperify.ui.home.HomeFragmentDirections
import kotlinx.android.synthetic.main.fragment_photos.*
import kotlinx.coroutines.ObsoleteCoroutinesApi
import javax.inject.Inject
@ObsoleteCoroutinesApi
class PhotosFragment : BaseFragment() {
init {
setHasOptionsMenu(true)
}
@Inject
lateinit var viewModelFactory: ViewModelFactory
private lateinit var viewModel: PhotosViewModel
override val layoutResId: Int = R.layout.fragment_photos
private val dataSource: EndlessRecyclerDataSource by lazy {
val photoRenderer = PhotosRenderer(GlideApp.with(this), ::onItemClick)
EndlessRecyclerDataSource(mutableListOf(photoRenderer), ::onLoadMoreItems)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = injectViewModel(viewModelFactory)
setupViews()
observe()
}
private fun setupViews() {
latest_recycler.setHasFixedSize(true)
latest_recycler.adapter = RecyclerAdapter(dataSource)
latest_recycler.onLoadMore = ::onLoadMoreItems
latest_swipe.setOnRefreshListener {
viewModel.refresh()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_photos_filter, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.photos_menu_filter_option -> consume {
showFilterDialog()
}
}
return super.onOptionsItemSelected(item)
}
private fun showFilterDialog() {
val currentSortBy = viewModel.ordering.value
val filterDialog = PhotosFilterDialogFragment.getInstance(currentSortBy)
filterDialog.listener = { options ->
options.sortBy?.let { sortBy -> viewModel.orderBy(sortBy) }
}
filterDialog.show(childFragmentManager, filterDialog::class.java.simpleName)
}
private fun onLoadMoreItems() {
viewModel.loadMore()
}
private fun observe() {
viewModel.photos.observe { photos ->
dataSource.setData(photos.asRecyclerItems())
}
viewModel.refreshing.observe {
latest_swipe.postAction { isRefreshing = it }
}
viewModel.error.observe {
dataSource.applyState(EndlessRecyclerDataSource.State.ERROR)
snack(getStringSafe(it.errorMessage.messageRes), Snackbar.LENGTH_LONG)
}
viewModel.toast.observe {
toast(getStringSafe(it.messageRes))
}
viewModel.errorPlaceholder.observe {
toggleError(it)
}
}
private fun toggleError(error: ErrorMessage) {
latest_recycler.inverseBooleanVisibility(error.isVisible)
with(latest_error) {
booleanVisibility(error.isVisible)
if (isVisible()) {
message = getStringSafe(error.errorMessage.messageRes)
imageResource = error.errorImageRes
}
}
}
private fun onItemClick(model: PhotoPOJO, imageView: ImageView) {
val toolbar = activity!!.findViewById<Toolbar>(R.id.toolbar)
val extras = FragmentNavigatorExtras(
toolbar to toolbar.transitionName
)
val action = HomeFragmentDirections.actionGlobalPhotoDetailsFragment(model.urls.regular, "")
action.photoId = model.id
action.photoDescription = model.description ?: ""
findNavController().navigate(action, extras)
}
}
fun List<PhotoPOJO>.asRecyclerItems() = map { PhotoRecyclerItem(it) } | 1 | Kotlin | 3 | 4 | 2bcccb5a5cc161831a11c7976eb2cb1ba7c90923 | 5,151 | Wallpaperify | Apache License 2.0 |
app/src/main/java/com/netchar/wallpaperify/ui/photos/PhotosFragment.kt | netchar | 171,912,089 | false | null | /*
* Copyright © 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netchar.wallpaperify.ui.photos
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import androidx.appcompat.widget.Toolbar
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.netchar.common.base.BaseFragment
import com.netchar.common.extensions.*
import com.netchar.common.poweradapter.adapter.EndlessRecyclerDataSource
import com.netchar.common.poweradapter.adapter.RecyclerAdapter
import com.netchar.repository.pojo.ErrorMessage
import com.netchar.repository.pojo.PhotoPOJO
import com.netchar.wallpaperify.R
import com.netchar.wallpaperify.di.ViewModelFactory
import com.netchar.wallpaperify.di.modules.GlideApp
import com.netchar.wallpaperify.ui.home.HomeFragmentDirections
import kotlinx.android.synthetic.main.fragment_photos.*
import kotlinx.coroutines.ObsoleteCoroutinesApi
import javax.inject.Inject
@ObsoleteCoroutinesApi
class PhotosFragment : BaseFragment() {
init {
setHasOptionsMenu(true)
}
@Inject
lateinit var viewModelFactory: ViewModelFactory
private lateinit var viewModel: PhotosViewModel
override val layoutResId: Int = R.layout.fragment_photos
private val dataSource: EndlessRecyclerDataSource by lazy {
val photoRenderer = PhotosRenderer(GlideApp.with(this), ::onItemClick)
EndlessRecyclerDataSource(mutableListOf(photoRenderer), ::onLoadMoreItems)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = injectViewModel(viewModelFactory)
setupViews()
observe()
}
private fun setupViews() {
latest_recycler.setHasFixedSize(true)
latest_recycler.adapter = RecyclerAdapter(dataSource)
latest_recycler.onLoadMore = ::onLoadMoreItems
latest_swipe.setOnRefreshListener {
viewModel.refresh()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_photos_filter, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.photos_menu_filter_option -> consume {
showFilterDialog()
}
}
return super.onOptionsItemSelected(item)
}
private fun showFilterDialog() {
val currentSortBy = viewModel.ordering.value
val filterDialog = PhotosFilterDialogFragment.getInstance(currentSortBy)
filterDialog.listener = { options ->
options.sortBy?.let { sortBy -> viewModel.orderBy(sortBy) }
}
filterDialog.show(childFragmentManager, filterDialog::class.java.simpleName)
}
private fun onLoadMoreItems() {
viewModel.loadMore()
}
private fun observe() {
viewModel.photos.observe { photos ->
dataSource.setData(photos.asRecyclerItems())
}
viewModel.refreshing.observe {
latest_swipe.postAction { isRefreshing = it }
}
viewModel.error.observe {
dataSource.applyState(EndlessRecyclerDataSource.State.ERROR)
snack(getStringSafe(it.errorMessage.messageRes), Snackbar.LENGTH_LONG)
}
viewModel.toast.observe {
toast(getStringSafe(it.messageRes))
}
viewModel.errorPlaceholder.observe {
toggleError(it)
}
}
private fun toggleError(error: ErrorMessage) {
latest_recycler.inverseBooleanVisibility(error.isVisible)
with(latest_error) {
booleanVisibility(error.isVisible)
if (isVisible()) {
message = getStringSafe(error.errorMessage.messageRes)
imageResource = error.errorImageRes
}
}
}
private fun onItemClick(model: PhotoPOJO, imageView: ImageView) {
val toolbar = activity!!.findViewById<Toolbar>(R.id.toolbar)
val extras = FragmentNavigatorExtras(
toolbar to toolbar.transitionName
)
val action = HomeFragmentDirections.actionGlobalPhotoDetailsFragment(model.urls.regular, "")
action.photoId = model.id
action.photoDescription = model.description ?: ""
findNavController().navigate(action, extras)
}
}
fun List<PhotoPOJO>.asRecyclerItems() = map { PhotoRecyclerItem(it) } | 1 | Kotlin | 3 | 4 | 2bcccb5a5cc161831a11c7976eb2cb1ba7c90923 | 5,151 | Wallpaperify | Apache License 2.0 |
github-crawler-core/src/test/java/com/societegenerale/githubcrawler/GitHubCrawlerPropertiesTest.kt | societe-generale | 136,929,288 | false | null | package com.societegenerale.githubcrawler
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
class GitHubCrawlerPropertiesTest {
@Test
fun cant_have_both_inclusion_and_exclusion_patterns_configured() {
assertThatThrownBy {
GitHubCrawlerProperties(
repositoriesToInclude = listOf("pattern1"),
repositoriesToExclude = listOf("pattern2")
)
}.isInstanceOf(IllegalStateException::class.java)
}
} | 13 | null | 19 | 97 | f25da66c6c64f2c167671f49129ff59c6ef74760 | 484 | github-crawler | Apache License 2.0 |
users-core/src/commonMain/kotlin/tz/co/asoft/IUserPrinciple.kt | aSoft-Ltd | 337,750,917 | false | null | package tz.co.asoft
interface IUserPrinciple : IPrinciple {
val user: User
} | 0 | Kotlin | 1 | 1 | 5b5ad625425194dd957780a16a1ff8d1c8ecb25c | 81 | users | MIT License |
asyncawait-android/src/main/kotlin/com/nhaarman/async/RunOnUi.kt | nhaarman | 71,654,190 | false | null | package com.nhaarman.async
import android.os.Handler
import android.os.Looper
import android.os.Message
var uiRunner: UIRunner = HandlerUIRunner()
internal fun runOnUi(action: () -> Unit) {
uiRunner.runOnUi(action)
}
interface UIRunner {
fun runOnUi(action: () -> Unit)
}
class SynchronousRunner : UIRunner {
override fun runOnUi(action: () -> Unit) {
action()
}
}
class HandlerUIRunner : UIRunner {
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
(msg.obj as? (() -> Unit))?.invoke()
}
}
override fun runOnUi(action: () -> Unit) {
handler.obtainMessage(0, action).sendToTarget()
}
}
| 2 | Kotlin | 2 | 98 | d3edba9c53fb73511c6a5118bba2e4736bb3e2f5 | 729 | AsyncAwait-Android | Apache License 2.0 |
app/src/main/java/me/wsj/fengyun/utils/WeatherUtil.kt | HotWordland | 393,217,127 | false | null | package me.wsj.fengyun.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat
import me.wsj.fengyun.R
class WeatherUtil {
companion object {
@JvmStatic
fun getWarningRes(context: Context, level: String): Pair<Drawable, Int> {
val result: Pair<Drawable, Int>
val res = context.resources
when (level) {
"黄色", "Yellow" -> {
result =
res.getDrawable(R.drawable.shape_yellow_alarm) to res.getColor(
R.color.white
)
}
"橙色", "Orange" -> {
result =
res.getDrawable(R.drawable.shape_orange_alarm) to res.getColor(
R.color.white
)
}
"红色", "Red" -> {
result =
res.getDrawable(R.drawable.shape_red_alarm) to res.getColor(
R.color.white
)
}
"白色", "White" -> {
result =
res.getDrawable(R.drawable.shape_white_alarm) to res.getColor(
R.color.black
)
}
else -> {
result =
res.getDrawable(R.drawable.shape_blue_alarm) to res.getColor(
R.color.white
)
}
}
return result
}
@JvmStatic
fun getF(value: String): Long {
return try {
var i = value.toInt().toLong()
i = Math.round(i * 1.8 + 32)
i
} catch (e: Exception) {
0
}
}
@JvmStatic
fun bitmapResize(src: Bitmap, pxX: Float, pxY: Float): Bitmap {
//压缩图片
val matrix = Matrix()
matrix.postScale(pxX / src.width, pxY / src.height)
return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)
}
@JvmStatic
fun getAirBackground(context: Context, aqi: String): Drawable? {
val num = aqi.toInt()
val drawable = when {
num <= 50 -> {
R.drawable.shape_aqi_excellent
}
num <= 100 -> {
R.drawable.shape_aqi_good
}
num <= 150 -> {
R.drawable.shape_aqi_low
}
num <= 200 -> {
R.drawable.shape_aqi_mid
}
num <= 300 -> {
R.drawable.shape_aqi_bad
}
else -> {
R.drawable.shape_aqi_serious
}
}
return ResourcesCompat.getDrawable(context.resources, drawable, null)
}
/**
* 获取星期
*
* @param num 0-6
* @return 星期
*/
@JvmStatic
fun getWeek(num: Int): String {
var week = " "
when (num) {
1 -> week = "周一"
2 -> week = "周二"
3 -> week = "周三"
4 -> week = "周四"
5 -> week = "周五"
6 -> week = "周六"
7 -> week = "周日"
}
return week
}
}
} | 0 | null | 0 | 1 | 94855d5a65a5898339886503f85e0548d749b48f | 3,640 | FengYunWeather | Apache License 2.0 |
kblog/src/main/kotlin/io/kblog/domain/Role.kt | hsdllcw | 228,341,455 | false | null | package io.kblog.domain
import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.security.core.GrantedAuthority
import javax.persistence.*
import javax.xml.bind.annotation.XmlTransient
/**
* The Role class.
* @author hsdllcw on 2020/4/6.
* @version 1.0.0
*/
@Entity
@Table(name = "kblog_role")
class Role(
@Id
override var id: Int? = null,
override var name: String? = null,
override var description: String? = null,
override var allAuthority: Boolean = false,
@XmlTransient
@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
var users: MutableSet<User> = mutableSetOf()
) : GrantedAuthority, Base.RoleVo() {
private var authority: String? = null
fun setAuthority(authority: String) {
this.authority = authority
}
override fun getAuthority(): String {
return this.authority!!
}
} | 0 | Kotlin | 0 | 1 | 659135e598e634b688e5bd31c98bec5a782c2a3f | 934 | KBlog | MIT License |
app/src/main/java/com/mindvalley/mindvalleyapp/domain/model/IconAsset.kt | ishtian-revee | 828,630,879 | false | {"Kotlin": 105571} | package com.mindvalley.mindvalleyapp.domain.model
data class IconAsset(
val thumbnailUrl: String?,
val url: String?
)
| 0 | Kotlin | 0 | 0 | 554b3791541c11f394523e269be7cebe978cf058 | 127 | mindvalley-coding-challenge | MIT License |
compiler/testData/diagnostics/tests/typealias/inhreritedTypeAliasQualifiedByDerivedClass.fir.kt | android | 263,405,600 | false | null | // !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_PARAMETER -TOPLEVEL_TYPEALIASES_ONLY
open class Base {
typealias Nested = String
}
class Derived : Base()
fun test(x: Derived.Nested) = x
fun Base.testWithImplicitReceiver(x: Nested) {
val y: Nested = x
} | 0 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 258 | kotlin | Apache License 2.0 |
app/src/main/java/com/gobinda/notepad/ui/screens/noteList/NoteListEmptyView.kt | gobinda1547 | 772,135,935 | false | {"Kotlin": 120416} | package com.gobinda.notepad.ui.screens.noteList
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.gobinda.notepad.R
import com.gobinda.notepad.ui.screens.common.TestTag
@Composable
fun NoteListEmptyView(onTextClicked: () -> Unit) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Text(
modifier = Modifier
.testTag(TestTag.NoteListEmptyView_Main_Text)
.clickable { onTextClicked.invoke() },
text = stringResource(id = R.string.text_click_to_add_new_note),
fontSize = 18.sp,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Medium
)
}
} | 0 | Kotlin | 0 | 1 | 76baccd61cc71523cd5c64112559a53c174e0efa | 1,198 | Notepad-Android-App | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.