path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/nativeMain/kotlin/me/zzp/helper/FileSystemHelper.kt | redraiment | 12,399,146 | false | {"Kotlin": 18071} | package me.zzp.helper
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.posix.fclose
import platform.posix.fopen
import platform.posix.fread
/**
* 读取文件的完整内容。
*/
@OptIn(ExperimentalForeignApi::class)
fun slurp(filename: String): String {
val file = fopen(filename, "r") ?: error("Failed to read file($filename)")
val content = StringBuilder()
val buffer = ByteArray(512)
var startIndex = 0
while (true) {
val capacity = (buffer.size - startIndex).toULong()
val size = fread(buffer.refTo(startIndex), 1U, capacity, file)
val endIndex = size.toInt() + startIndex
if (endIndex > 0) {
var index = 0
while (index < endIndex) {
val value = buffer[index].toInt()
index += if (value and 0b10000000 == 0) {
1
} else if (value and 0b11100000 == 0b11000000 && index + 1 < endIndex) {
2
} else if (value and 0b11110000 == 0b11100000 && index + 2 < endIndex) {
3
} else if (value and 0b11111000 == 0b11110000 && index + 3 < endIndex) {
4
} else {
break
}
}
content.append(buffer.toKString(endIndex = index))
startIndex = endIndex - index
if (startIndex > 0) {
buffer.copyInto(buffer, 0, index, endIndex)
}
} else {
break
}
}
return content.toString().also {
fclose(file)
}
}
| 0 | Kotlin | 1 | 7 | 04c05cc6f79f7b7399361b155490aee3c469a8c8 | 1,654 | linsp | MIT License |
lab/src/main/kotlin/materialui/lab/components/togglebuttongroup/enums/ToggleButtonGroupOrientation.kt | subroh0508 | 167,797,152 | false | null | package materialui.lab.components.togglebuttongroup.enums
@Suppress("EnumEntryName")
enum class ToggleButtonGroupOrientation {
horizontal,
vertical,
}
| 14 | Kotlin | 27 | 81 | a959a951ace3b9bd49dc5405bea150d4d53cf162 | 160 | kotlin-material-ui | MIT License |
identity/src/test/java/com/stripe/android/identity/TestApplication.kt | stripe | 6,926,049 | false | null | package com.stripe.android.identity
import android.app.Application
// A material themed application is needed to inflate MaterialToolbar in IdentityActivity
internal class TestApplication : Application() {
override fun onCreate() {
super.onCreate()
setTheme(R.style.Theme_MaterialComponents_DayNight_NoActionBar)
}
}
| 86 | Kotlin | 584 | 1,078 | 74bf7263f56d53aff2d0035127d84dd40609403d | 343 | stripe-android | MIT License |
javatests/dagger/functional/kotlinsrc/membersinject/MembersWithSameNameTest.kt | andhiratobing | 586,597,662 | false | null | /*
* Copyright (C) 2022 The Dagger 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
*
* 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 dagger.functional.kotlinsrc.membersinject
import com.google.common.truth.Truth.assertThat
import dagger.Binds
import dagger.Component
import dagger.Module
import dagger.Provides
import dagger.functional.kotlinsrc.membersinject.subpackage.MembersWithSameNameParent
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
// https://github.com/google/dagger/issues/755
@RunWith(JUnit4::class)
class MembersWithSameNameTest {
@Test
fun parentInjectsMaskedMembers() {
val parent = MembersWithSameNameParent()
val component = DaggerMembersWithSameNameTest_TestComponent.create()
component.injectParent(parent)
assertThat(parent.parentSameName()).isNotNull()
assertThat(parent.parentSameNameStringWasInvoked()).isTrue()
assertThat(parent.parentSameNameObjectWasInvoked()).isTrue()
}
@Test
fun childInjectsMaskedMembers() {
val child = MembersWithSameNameChild()
val component = DaggerMembersWithSameNameTest_TestComponent.create()
component.injectChild(child)
assertThat(child.parentSameName()).isNotNull()
assertThat(child.parentSameNameStringWasInvoked()).isTrue()
assertThat(child.parentSameNameObjectWasInvoked()).isTrue()
assertThat(child.childSameName()).isNotNull()
assertThat(child.childSameNameStringWasInvoked()).isTrue()
assertThat(child.childSameNameObjectWasInvoked()).isTrue()
}
@Module
internal abstract class TestModule {
@Binds abstract fun bindObject(string: String): Any
companion object {
@Provides fun provideString(): String = ""
}
}
@Component(modules = [TestModule::class])
internal interface TestComponent {
fun injectParent(parent: MembersWithSameNameParent)
fun injectChild(child: MembersWithSameNameChild)
}
}
| 0 | null | 0 | 1 | e209fa9efa1210006ef21569aab53328aa7f374e | 2,390 | dagger | Apache License 2.0 |
app/src/androidTest/java/com/atritripathi/musk/di/TestAppModule.kt | AtriTripathi | 354,453,570 | false | null | package com.atritripathi.musk.di
import android.content.Context
import androidx.room.Room
import com.atritripathi.musk.data.source.local.MuskDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Named
@Module
@InstallIn(SingletonComponent::class)
object TestAppModule {
@Provides
@Named("test_db")
fun provideInMemoryDb(@ApplicationContext context: Context) =
Room.inMemoryDatabaseBuilder(context, MuskDatabase::class.java)
.allowMainThreadQueries().build()
} | 0 | Kotlin | 0 | 2 | d569cadfd0d5f3259e32f8c2aaa1664b20066bfb | 648 | Musk | Apache License 2.0 |
app/src/main/java/vn/loitp/app/activity/customviews/recyclerview/gallerylayoutmanager/GalleryLayoutManagerHorizontalActivity.kt | tplloi | 126,578,283 | false | null | package vn.loitp.app.activity.customviews.recyclerview.gallerylayoutmanager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.annotation.IsFullScreen
import com.annotation.LogTag
import com.core.base.BaseFontActivity
import com.core.common.Constants
import com.views.recyclerview.gallery.GalleryLayoutManager
import com.views.recyclerview.gallery.GalleryLayoutManager.ItemTransformer
import kotlinx.android.synthetic.main.activity_recycler_view_menu_gallery_layout_manager.*
import vn.loitp.app.R
import vn.loitp.app.activity.customviews.recyclerview.normalrecyclerview.Movie
import vn.loitp.app.activity.customviews.recyclerview.normalrecyclerviewwithsingletondata.DummyData.Companion.instance
//https://github.com/BCsl/GalleryLayoutManager
@LogTag("GalleryLayoutManagerHorizontalActivity")
@IsFullScreen(false)
class GalleryLayoutManagerHorizontalActivity : BaseFontActivity() {
private var mAdapter: GalleryAdapter? = null
override fun setLayoutResourceId(): Int {
return R.layout.activity_recycler_view_menu_gallery_layout_manager
}
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAdapter = GalleryAdapter(context = this, moviesList = instance.movieList,
callback = object : GalleryAdapter.Callback {
override fun onClick(movie: Movie, position: Int) {
showShortInformation("Click " + movie.title)
}
override fun onLongClick(movie: Movie, position: Int) {
//do nothing
}
override fun onLoadMore() {
//do nothing
}
})
val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this)
rv.layoutManager = mLayoutManager
rv.itemAnimator = DefaultItemAnimator()
//rv.setAdapter(mAdapter);
val layoutManager = GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL)
layoutManager.attach(rv) //default selected position is 0
//layoutManager.attach(recyclerView, 30);
//...
//setup adapter for your RecycleView
rv.adapter = mAdapter
layoutManager.setCallbackInFling(true) //should receive callback when flinging, default is false
layoutManager.setOnItemSelectedListener { _, _, position -> textView.text = position.toString() + "/" + mAdapter?.itemCount }
// Apply ItemTransformer just like ViewPager
layoutManager.setItemTransformer(ScaleTransformer())
prepareMovieData()
}
private fun prepareMovieData() {
if (instance.movieList.isEmpty()) {
for (i in 0..49) {
val movie = Movie(title = "Loitp $i", genre = "Action & Adventure $i", year = "Year: $i", cover = Constants.URL_IMG)
instance.movieList.add(movie)
}
}
mAdapter?.notifyDataSetChanged()
}
inner class ScaleTransformer : ItemTransformer {
override fun transformItem(layoutManager: GalleryLayoutManager, item: View, fraction: Float) {
item.pivotX = item.width / 2f
item.pivotY = item.height / 2.0f
val scale = 1 - 0.4f * Math.abs(fraction)
item.scaleX = scale
item.scaleY = scale
}
}
}
| 0 | Kotlin | 0 | 6 | 4fe4c945e89819d77aaf6cb76f1de6bbff7868a5 | 3,604 | basemaster | Apache License 2.0 |
android/app_data/src/main/java/com/github/tshion/xapprecipe_data/api_xapp_v1/GetToDoResponse.kt | tshion | 261,409,412 | false | {"Kotlin": 190771, "Swift": 26617, "C#": 18725, "TypeScript": 11347, "SCSS": 9137, "Ruby": 2395, "HTML": 1526, "Makefile": 1481, "JavaScript": 1420, "Shell": 1270, "Dockerfile": 689, "Java": 321, "Objective-C": 119} | package com.github.tshion.xapprecipe_data.api_xapp_v1
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class GetToDoResponse(
val items: List<ToDo>,
)
| 2 | Kotlin | 1 | 1 | 28357a035996d8b89291cbd2ff29df9ae9abe97c | 193 | XAppRecipe | MIT License |
src/main/kotlin/com/rainbow/server/domain/expense/repository/CategoryRepository.kt | DDD-Community | 649,288,543 | false | null | package com.rainbow.server.domain.expense.repository
import com.rainbow.server.domain.expense.entity.Category
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface CategoryRepository:JpaRepository<Category,Long> {
fun findByName(name:String):Category
} | 2 | Kotlin | 0 | 3 | e150ae99d5f99fe094b35962e93fc0085e8f3bfe | 336 | Rainbow-Server | MIT License |
app/src/main/java/org/oppia/android/app/devoptions/markchapterscompleted/MarkChaptersCompletedViewModel.kt | oppia | 148,093,817 | false | null | package org.oppia.android.app.devoptions.markchapterscompleted
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import org.oppia.android.app.fragment.FragmentScope
import org.oppia.android.app.model.ProfileId
import org.oppia.android.app.model.StorySummary
import org.oppia.android.app.viewmodel.ObservableViewModel
import org.oppia.android.domain.devoptions.ModifyLessonProgressController
import org.oppia.android.domain.oppialogger.OppiaLogger
import org.oppia.android.util.data.AsyncResult
import org.oppia.android.util.data.DataProviders.Companion.toLiveData
import javax.inject.Inject
/**
* [ViewModel] for [MarkChaptersCompletedFragment]. It populates the recyclerview with a list of
* [StorySummaryViewModel] which in turn display the story.
*/
@FragmentScope
class MarkChaptersCompletedViewModel @Inject constructor(
private val oppiaLogger: OppiaLogger,
private val modifyLessonProgressController: ModifyLessonProgressController
) : ObservableViewModel() {
private lateinit var profileId: ProfileId
private val itemList = mutableListOf<MarkChaptersCompletedItemViewModel>()
/**
* List of [MarkChaptersCompletedItemViewModel] used to populate recyclerview of
* [MarkChaptersCompletedFragment] to display stories and chapters.
*/
val storySummaryLiveData: LiveData<List<MarkChaptersCompletedItemViewModel>> by lazy {
Transformations.map(storyMapLiveData, ::processStoryMap)
}
private val storyMapLiveData: LiveData<Map<String, List<StorySummary>>> by lazy { getStoryMap() }
private fun getStoryMap(): LiveData<Map<String, List<StorySummary>>> {
return Transformations.map(storyMapResultLiveData, ::processStoryMapResult)
}
private val storyMapResultLiveData:
LiveData<AsyncResult<Map<String, List<StorySummary>>>> by lazy {
modifyLessonProgressController.getStoryMapWithProgress(profileId).toLiveData()
}
private fun processStoryMapResult(
storyMap: AsyncResult<Map<String, List<StorySummary>>>
): Map<String, List<StorySummary>> {
if (storyMap.isFailure()) {
oppiaLogger.e(
"MarkChaptersCompletedFragment",
"Failed to retrieve storyList",
storyMap.getErrorOrNull()!!
)
}
return storyMap.getOrDefault(mapOf())
}
private fun processStoryMap(
storyMap: Map<String, List<StorySummary>>
): List<MarkChaptersCompletedItemViewModel> {
itemList.clear()
var nextStoryIndex: Int
var chapterIndex = 0
storyMap.forEach { storyMapItem ->
storyMapItem.value.forEach { storySummary ->
itemList.add(StorySummaryViewModel(storyName = storySummary.storyName))
chapterIndex++
nextStoryIndex = chapterIndex + storySummary.chapterCount
storySummary.chapterList.forEach { chapterSummary ->
itemList.add(
ChapterSummaryViewModel(
chapterIndex = chapterIndex,
chapterSummary = chapterSummary,
nextStoryIndex = nextStoryIndex,
storyId = storySummary.storyId,
topicId = storyMapItem.key
)
)
chapterIndex++
}
}
}
return itemList
}
fun setProfileId(profileId: ProfileId) {
this.profileId = profileId
}
/** Returns a list of [MarkChaptersCompletedItemViewModel]s. */
fun getItemList(): List<MarkChaptersCompletedItemViewModel> = itemList.toList()
/** Returns a list of [ChapterSummaryViewModel]s mapped to corresponding exploration IDs. */
fun getChapterMap(): Map<String, Pair<String, String>> =
itemList.filterIsInstance<ChapterSummaryViewModel>().associateBy(
{ it.chapterSummary.explorationId },
{ Pair(it.storyId, it.topicId) }
)
}
| 592 | null | 310 | 156 | 36c4a5b7e34ac676b1e5974122bce5058f32910b | 3,717 | oppia-android | Apache License 2.0 |
app/src/main/java/ua/com/radiokot/osmanddisplay/features/track/data/storage/ImportedTracksRepository.kt | Radiokot | 575,442,818 | false | {"Kotlin": 171430, "Java": 73238} | package ua.com.radiokot.osmanddisplay.features.track.data.storage
import android.graphics.Bitmap
import com.mapbox.geojson.GeoJson
import com.mapbox.geojson.LineString
import com.mapbox.geojson.MultiPoint
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.rxkotlin.toCompletable
import io.reactivex.rxkotlin.toSingle
import io.reactivex.schedulers.Schedulers
import ua.com.radiokot.osmanddisplay.base.data.storage.MultipleItemsRepository
import ua.com.radiokot.osmanddisplay.base.data.storage.RepositoryCache
import ua.com.radiokot.osmanddisplay.base.extension.kLogger
import ua.com.radiokot.osmanddisplay.features.track.data.model.ImportedTrackRecord
import java.io.File
import java.util.Date
class ImportedTracksRepository(
private val directory: File,
itemsCache: RepositoryCache<ImportedTrackRecord>,
) : MultipleItemsRepository<ImportedTrackRecord>(itemsCache) {
private val logger = kLogger("ImportedTracksRepo")
override fun getItems(): Single<List<ImportedTrackRecord>> = {
directory
.listFiles { _, name -> name.endsWith(".$GEOJSON_FILE_EXTENSION") }!!
.mapNotNull { file ->
try {
ImportedTrackRecord.fromGeoJsonFile(file)
} catch (e: Exception) {
logger.warn(e) {
"getItems(): record_creation_failed:" +
"\nfile=$file"
}
null
}
}
.sortedByDescending(ImportedTrackRecord::importedAt)
}
.toSingle()
.subscribeOn(Schedulers.io())
.doOnError {
logger.error(it) { "getItems(): error_occurred" }
}
fun importTrack(
name: String,
geometry: LineString,
poi: MultiPoint,
thumbnail: Bitmap,
onlinePreviewUrl: String?,
): Single<ImportedTrackRecord> {
val importedAt = Date()
val id = importedAt.time.toString()
val geoJsonFileName = "$id.$GEOJSON_FILE_EXTENSION"
val thumbnailImageFileName = "${id}_thumbnail.jpg"
return writeThumbnailImageFile(
thumbnail = thumbnail,
fileName = thumbnailImageFileName,
)
.flatMap { thumbnailImageFile ->
writeGeoJsonFile(
geoJson = ImportedTrackRecord.createGeoJson(
name = name,
thumbnailImageFileName = thumbnailImageFileName,
importedAt = importedAt,
geometry = geometry,
poi = poi,
onlinePreviewUrl = onlinePreviewUrl,
),
fileName = geoJsonFileName
)
.map { thumbnailImageFile to it }
}
.map { (thumbnailImageFile, geoJsonFile) ->
ImportedTrackRecord(
name = name,
importedAt = importedAt,
thumbnailImageFile = thumbnailImageFile,
geoJsonFile = geoJsonFile,
onlinePreviewUrl = onlinePreviewUrl,
)
}
.subscribeOn(Schedulers.io())
.doOnSubscribe {
logger.debug {
"importTrack(): start_import:" +
"\nname=$name," +
"\nid=$id"
}
}
.doOnError {
logger.error(it) {
"importTrack(): error_occurred"
}
}
.doOnSuccess {
itemsCache.add(it)
broadcast()
logger.debug {
"importTrack(): imported:" +
"\nrecord=$it"
}
}
}
private fun writeThumbnailImageFile(
thumbnail: Bitmap,
fileName: String,
): Single<File> = {
File(directory.path, fileName).apply {
createNewFile()
outputStream().use { outputStream ->
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
}
}
}
.toSingle()
.subscribeOn(Schedulers.io())
private fun writeGeoJsonFile(
geoJson: GeoJson,
fileName: String,
): Single<File> = {
File(directory.path, fileName).apply {
createNewFile()
writeText(geoJson.toJson())
}
}
.toSingle()
.subscribeOn(Schedulers.io())
fun clear(): Completable = {
directory
.listFiles()
?.forEach(File::delete)
itemsCache.clear()
broadcast()
}
.toCompletable()
.subscribeOn(Schedulers.io())
.doOnSubscribe {
logger.debug { "clear()" }
}
.doOnError {
logger.error(it) {
"clear(): error_occurred"
}
}
private companion object {
private const val GEOJSON_FILE_EXTENSION = "geojson"
}
}
| 0 | Kotlin | 3 | 8 | 728661ecb691e0be51fd0338866ed5e7b4e442c0 | 5,134 | osmand-display-app | MIT License |
android/app/src/main/java/at/krutzler/beershare/repository/BeerRepository.kt | pschulzk | 416,141,663 | false | {"Kotlin": 74532, "Swift": 60587, "Python": 32103, "HTML": 3949, "CSS": 870, "Shell": 95} | package at.krutzler.beershare.repository
import at.krutzler.beershare.webapi.WebApiClient
import org.json.JSONArray
import org.json.JSONObject
class BeerRepository(private val mClient: WebApiClient) {
data class Beer(
val id: Int,
val brand: String,
val type: String,
val liter: Double,
val country: String
) {
override fun toString(): String {
return "$brand $type (${liter}l)"
}
}
fun getAll(callback: ((List<Beer>)->Unit)) {
mClient.get("beer/") { response, error ->
if (error) {
callback.invoke(listOf())
} else {
val list = mutableListOf<Beer>()
val jsonArray = JSONArray(response)
for (i in 0 until jsonArray.length()) {
list.add(fromJson(jsonArray.getJSONObject(i)))
}
callback.invoke(list)
}
}
}
private companion object {
fun fromJson(item: JSONObject): Beer {
return Beer(
item.getInt(Beer::id.name),
item.getString(Beer::brand.name),
item.getString(Beer::type.name),
item.getDouble(Beer::liter.name),
item.getString(Beer::country.name)
)
}
fun toJson(beerCellar: Beer): JSONObject {
return JSONObject("""
{
"id": ${beerCellar.id},
"brand": "${beerCellar.brand}",
"type": "${beerCellar.type}",
"liter": ${beerCellar.liter},
"country": "${beerCellar.country}"
}
""")
}
}
} | 0 | Kotlin | 0 | 0 | 8892e520bf0a53d756f926957ee6abd2b3ca2fa4 | 1,772 | fhtw-beershare | MIT License |
app/src/main/java/eu/ginlo_apps/ginlo/activity/preferences/PreferencesNotificationsActivity.kt | cdskev | 358,279,979 | false | {"Java": 4918351, "Kotlin": 717287, "HTML": 2200} | // Copyright (c) 2020-2022 ginlo.net GmbH
package eu.ginlo_apps.ginlo.activity.preferences
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.Toast
import eu.ginlo_apps.ginlo.R
import eu.ginlo_apps.ginlo.activity.preferences.base.PreferencesBaseActivity
import eu.ginlo_apps.ginlo.controller.PreferencesController
import eu.ginlo_apps.ginlo.data.network.AppConnectivity
import eu.ginlo_apps.ginlo.exception.LocalizedException
import eu.ginlo_apps.ginlo.exception.LocalizedException.GENERATE_AES_KEY_FAILED
import eu.ginlo_apps.ginlo.log.LogUtil
import eu.ginlo_apps.ginlo.util.ConfigUtil
import eu.ginlo_apps.ginlo.util.RuntimeConfig
import eu.ginlo_apps.ginlo.util.SystemUtil
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_chats_textview_show_preview_hint
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_layout_channels
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_layout_services
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_inapp_notifications
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_notifications_channels
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_notifications_chats
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_notifications_groups
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_notifications_services
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_show_preview
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_sounds_channels
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_sounds_chats
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_sounds_groups
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_sounds_services
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_vibrations_channels
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_vibrations_chats
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_vibrations_groups
import kotlinx.android.synthetic.main.activity_preferences_notifications.preferences_notifications_switch_vibrations_services
import javax.inject.Inject
class PreferencesNotificationsActivity : PreferencesBaseActivity() {
@Inject
internal lateinit var appConnectivity: AppConnectivity
override fun onCreateActivity(savedInstanceState: Bundle?) {
preferences_notifications_switch_inapp_notifications.setOnCheckedChangeListener { buttonView, isChecked ->
if (!settingsSwitch) {
try {
preferencesController.setShowInAppNotifications(isChecked)
} catch (e: LocalizedException) {
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
LogUtil.w(this.javaClass.name, e.message, e)
}
}
}
try {
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_inapp_notifications,
preferencesController.getShowInAppNotifications()
)
configurePreviewSwitch()
setChatNotifications()
setGroupNotifications()
if (ConfigUtil.channelsEnabled() || RuntimeConfig.isBAMandant() && simsMeApplication.accountController.isDeviceManaged) {
setChannelNotifications()
} else {
preferences_notifications_layout_channels.visibility = View.GONE
}
if (ConfigUtil.servicesEnabled()) {
setServiceNotifications()
} else {
preferences_notifications_layout_services.visibility = View.GONE
}
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
}
}
override fun getActivityLayout(): Int {
return R.layout.activity_preferences_notifications
}
override fun onResumeActivity() {}
private fun configurePreviewSwitch() {
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && !preferencesController.isNotificationPreviewDisabledByAdmin()) {
preferences_notifications_switch_show_preview.setOnCheckedChangeListener { buttonView, isChecked ->
if (!settingsSwitch) {
try {
preferencesController.setNotificationPreviewEnabled(isChecked, false)
} catch (e: LocalizedException) {
if (GENERATE_AES_KEY_FAILED == e.identifier) {
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
// TODO fehlermeldung
}
LogUtil.w(this.javaClass.name, e.message, e)
}
}
}
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_show_preview,
preferencesController.getNotificationPreviewEnabled()
)
} else {
preferences_notifications_switch_show_preview.visibility = View.GONE
preferences_chats_textview_show_preview_hint?.visibility = View.GONE
}
}
private fun setChatNotifications() {
val isSingleNotificationOn = preferencesController.getNotificationForSingleChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_notifications_chats,
isSingleNotificationOn
)
if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)) {
val isSingleSoundNotificationOn = preferencesController.getSoundForSingleChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_sounds_chats,
isSingleSoundNotificationOn
)
preferences_notifications_switch_sounds_chats.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setSoundForSingleChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
val isSingleVibrationNotificationOn = preferencesController.getVibrationForSingleChatsEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_vibrations_chats,
isSingleVibrationNotificationOn
)
preferences_notifications_switch_vibrations_chats.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, checked ->
if (settingsSwitch) {
return@OnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !checked)
return@OnCheckedChangeListener
}
preferencesController.setVibrationForSingleChatsEnabled(checked)
})
preferences_notifications_switch_sounds_chats.isEnabled = isSingleNotificationOn
preferences_notifications_switch_vibrations_chats.isEnabled = isSingleNotificationOn
} else {
preferences_notifications_switch_sounds_chats.visibility = View.GONE
preferences_notifications_switch_vibrations_chats.visibility = View.GONE
}
preferences_notifications_switch_notifications_chats.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setNotificationForSingleChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
// set mit Ausloesen der Funktion!
preferences_notifications_switch_sounds_chats.isChecked = isChecked
preferences_notifications_switch_vibrations_chats.isChecked = isChecked
preferences_notifications_switch_sounds_chats.isEnabled = isChecked
preferences_notifications_switch_vibrations_chats.isEnabled = isChecked
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
}
private fun setGroupNotifications() {
val isGroupNotificationOn = preferencesController.getNotificationForGroupChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_notifications_groups,
isGroupNotificationOn
)
if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)) {
val isGroupSoundNotificationOn = preferencesController.getSoundForGroupChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_sounds_groups,
isGroupSoundNotificationOn
)
preferences_notifications_switch_sounds_groups.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setSoundForGroupChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
val isGroupVibrationNotificationOn = preferencesController.getVibrationForGroupsEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_vibrations_groups,
isGroupVibrationNotificationOn
)
preferences_notifications_switch_vibrations_groups.setOnCheckedChangeListener { buttonView, checked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !checked)
return@setOnCheckedChangeListener
}
preferencesController.setVibrationForGroupsEnabled(checked)
}
preferences_notifications_switch_sounds_groups.isEnabled = isGroupNotificationOn
preferences_notifications_switch_vibrations_groups.isEnabled = isGroupNotificationOn
} else {
preferences_notifications_switch_sounds_groups.visibility = View.GONE
preferences_notifications_switch_vibrations_groups.visibility = View.GONE
}
preferences_notifications_switch_notifications_groups.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setNotificationForGroupChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
// set mit Ausloesen der Funktion!
preferences_notifications_switch_sounds_groups.isChecked = isChecked
preferences_notifications_switch_vibrations_groups.isChecked = isChecked
preferences_notifications_switch_sounds_groups.isEnabled = isChecked
preferences_notifications_switch_vibrations_groups.isEnabled = isChecked
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
}
private fun setChannelNotifications() {
val isChannelNotificationOn = preferencesController.getNotificationForChannelChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_notifications_channels,
isChannelNotificationOn
)
if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)) {
val isChannelSoundNotificationOn = preferencesController.getSoundForChannelChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_sounds_channels,
isChannelSoundNotificationOn
)
preferences_notifications_switch_sounds_channels.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setSoundForChannelChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
val isChannelVibrationNotificationOn = preferencesController.getVibrationForChannelsEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_vibrations_channels,
isChannelVibrationNotificationOn
)
preferences_notifications_switch_vibrations_channels.setOnCheckedChangeListener { buttonView, checked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !checked)
return@setOnCheckedChangeListener
}
preferencesController.setVibrationForChannelsEnabled(checked)
}
preferences_notifications_switch_sounds_channels.isEnabled = isChannelNotificationOn
preferences_notifications_switch_vibrations_channels.isEnabled = isChannelNotificationOn
} else {
preferences_notifications_switch_sounds_channels.visibility = View.GONE
preferences_notifications_switch_vibrations_channels.visibility = View.GONE
}
preferences_notifications_switch_notifications_channels.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setNotificationForChannelChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
// set mit Ausloesen der Funktion!
preferences_notifications_switch_sounds_channels.isChecked = isChecked
preferences_notifications_switch_vibrations_channels.isChecked = isChecked
preferences_notifications_switch_sounds_channels.isEnabled = isChecked
preferences_notifications_switch_vibrations_channels.isEnabled = isChecked
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
}
private fun setServiceNotifications() {
val isServiceNotificationOn = preferencesController.getNotificationForServiceChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_notifications_services,
isServiceNotificationOn
)
if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)) {
val isServiceSoundNotificationOn = preferencesController.getSoundForServiceChatEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_sounds_services,
isServiceSoundNotificationOn
)
preferences_notifications_switch_sounds_services.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setSoundForServiceChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
val isServiceVibrationNotificationOn = preferencesController.getVibrationForServicesEnabled()
setCompoundButtonWithoutTriggeringListener(
preferences_notifications_switch_vibrations_services,
isServiceVibrationNotificationOn
)
preferences_notifications_switch_vibrations_services.setOnCheckedChangeListener { buttonView, checked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !checked)
return@setOnCheckedChangeListener
}
preferencesController.setVibrationForServicesEnabled(checked)
}
preferences_notifications_switch_sounds_services.isEnabled = isServiceNotificationOn
preferences_notifications_switch_vibrations_services.isEnabled = isServiceNotificationOn
} else {
preferences_notifications_switch_sounds_services.visibility = View.GONE
preferences_notifications_switch_vibrations_services.visibility = View.GONE
}
preferences_notifications_switch_notifications_services.setOnCheckedChangeListener { buttonView, isChecked ->
if (settingsSwitch) {
return@setOnCheckedChangeListener
}
if (!appConnectivity.isConnected()) {
Toast.makeText(
this@PreferencesNotificationsActivity, R.string.backendservice_internet_connectionFailed,
Toast.LENGTH_LONG
).show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
return@setOnCheckedChangeListener
}
try {
showIdleDialog(-1)
preferencesController.setNotificationForServiceChatEnabled(
isChecked,
object : PreferencesController.OnPreferenceChangedListener {
override fun onPreferenceChangedSuccess() {
// set mit Ausloesen der Funktion!
preferences_notifications_switch_sounds_services.isChecked = isChecked
preferences_notifications_switch_vibrations_services.isChecked = isChecked
preferences_notifications_switch_sounds_services.isEnabled = isChecked
preferences_notifications_switch_vibrations_services.isEnabled = isChecked
dismissIdleDialog()
}
override fun onPreferenceChangedFail() {
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
})
} catch (e: LocalizedException) {
LogUtil.w(this.javaClass.name, e.message, e)
dismissIdleDialog()
Toast.makeText(
this@PreferencesNotificationsActivity,
R.string.settings_save_setting_failed,
Toast.LENGTH_LONG
)
.show()
setCompoundButtonWithoutTriggeringListener(buttonView, !isChecked)
}
}
}
}
| 1 | Java | 0 | 5 | 455ca039336ac12f59022f000734227659abf48e | 33,228 | ginlo-android | Apache License 2.0 |
app/src/main/java/com/example/guidemodernapparchitecture/ui/topheadlines/TopHeadlinesActivity.kt | alexjoy001 | 512,629,489 | false | {"Kotlin": 38916} | package com.example.guidemodernapparchitecture.ui.topheadlines
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.guidemodernapparchitecture.ui.common.DisplayNewsItem
import com.example.guidemodernapparchitecture.ui.newsdetail.NewsDetailActivity
import com.example.guidemodernapparchitecture.util.Constants
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class TopHeadlinesActivity : ComponentActivity() {
private val viewModel: TopHeadlineViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column {
AppBar()
DisplayNews()
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
Column {
AppBar()
DisplayNews()
}
}
@Composable
fun AppBar() {
TopAppBar(title = { Text(text = "Guide to Modern Architecture")})
}
@Composable
fun DisplayNews() {
val isLoading = viewModel.topHeadLineUi.collectAsState().value.isLoading
val newsList = viewModel.topHeadLineUi.collectAsState().value.newsList
if (isLoading) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
}
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(newsList.size) { index ->
DisplayNewsItem(newsList[index], onClick = {
val intent = Intent(this@TopHeadlinesActivity, NewsDetailActivity::class.java)
intent.putExtra(Constants.NEWS, newsList[index])
startActivity(intent)
})
}
}
}
}
} | 0 | Kotlin | 0 | 7 | 95e5998cee1faca24cbda97d36db4314801a2e5b | 2,757 | GuideToAndroidModernAppArchitecture | MIT License |
src/test/kotlin/xyz/malkki/gtfs/serialization/writer/ZipGtfsFeedWriterTest.kt | mjaakko | 513,616,737 | false | null | package xyz.malkki.gtfs.serialization.writer
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers
import org.junit.jupiter.api.io.TempDir
import xyz.malkki.gtfs.model.Calendar
import xyz.malkki.gtfs.model.Route
import xyz.malkki.gtfs.model.Stop
import xyz.malkki.gtfs.model.Trip
import xyz.malkki.gtfs.serialization.GtfsConstants
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.time.LocalDate
import java.util.zip.ZipFile
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
class ZipGtfsFeedWriterTest {
@field:TempDir
lateinit var tempFolder: File
@Test
fun `Test writing data to GTFS ZIP archive`() {
val gtfsFile = tempFolder.toPath().resolve("gtfs.zip")
val writer = ZipGtfsFeedWriter(gtfsFile)
writer.use {
it.writeStops(listOf(
Stop(stopId = "1"),
Stop(stopId = "2"),
Stop(stopId = "3")
))
it.writeTrips(listOf(
Trip(routeId = "a", serviceId = "service_a", tripId = "trip_1"),
Trip(routeId = "a", serviceId = "service_a", tripId = "trip_2"),
Trip(routeId = "a", serviceId = "service_a", tripId = "trip_3")
))
it.writeRoutes(listOf(
Route(routeId = "a", routeType = Route.ROUTE_TYPE_BUS)
))
it.writeCalendars(listOf(
Calendar(
serviceId = "service_a",
monday = true,
tuesday = true,
wednesday = true,
thursday = true,
friday = true,
saturday = true,
sunday = true,
startDate = LocalDate.now(),
endDate = LocalDate.now().plusDays(100)
)
))
}
assertThat(Files.size(gtfsFile), Matchers.greaterThan(0))
val zipEntries = ZipFile(gtfsFile.toFile(), StandardCharsets.UTF_8).use { zipFile -> zipFile.entries().toList().map { it.name } }
assertEquals(4, zipEntries.size)
assertContains(zipEntries, GtfsConstants.ROUTES_FILE)
assertContains(zipEntries, GtfsConstants.STOPS_FILE)
assertContains(zipEntries, GtfsConstants.TRIPS_FILE)
assertContains(zipEntries, GtfsConstants.CALENDAR_FILE)
}
} | 1 | Kotlin | 0 | 3 | 85eb70162a337a3a3b7f01944872a9440d33fb10 | 2,453 | gtfs-library | MIT License |
common/domain/src/main/kotlin/no/nav/mulighetsrommet/domain/dto/TiltaksgjennomforingsArenadataDto.kt | navikt | 435,813,834 | false | {"Kotlin": 1133159, "TypeScript": 832905, "SCSS": 37475, "JavaScript": 20654, "PLpgSQL": 7871, "HTML": 1473, "Dockerfile": 683, "CSS": 437, "Shell": 95} | package no.nav.mulighetsrommet.domain.dto
import kotlinx.serialization.Serializable
@Serializable
data class TiltaksgjennomforingsArenadataDto(
val opprettetAar: Int?,
val lopenr: Int?,
val virksomhetsnummer: String?,
val ansvarligNavEnhetId: String?,
val status: String,
) {
companion object {
fun from(tiltaksgjennomforing: TiltaksgjennomforingAdminDto, status: String) = tiltaksgjennomforing.run {
TiltaksgjennomforingsArenadataDto(
opprettetAar = tiltaksnummer?.split("#")?.first()?.toInt(),
lopenr = tiltaksnummer?.split("#")?.get(1)?.toInt(),
virksomhetsnummer = arrangor.organisasjonsnummer,
ansvarligNavEnhetId = arenaAnsvarligEnhet,
status = status,
)
}
}
}
| 6 | Kotlin | 1 | 5 | 952ce7f77ac3b385731f2e3781d2b35deb562254 | 817 | mulighetsrommet | MIT License |
src/Day03Test.kt | gnuphobia | 578,967,785 | false | {"Kotlin": 17559} | import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class Day03Test {
private final val test1: String = "vJrwpWtwJgWrhcsFMMfFFhFp"
private final val test2: String = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL"
private final val test3: String = "PmmdzqPrVvPwwTWBwg"
private final val test4: String = "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn"
private final val test5: String = "ttgJtRGJQctTZtZT"
private final val test6: String = "CrZsJsPPZsGzwwsLwLmpwMDw"
private final val test1Compartment1: String = "vJrwpWtwJgWr"
private final val test1Compartment2: String = "hcsFMMfFFhFp"
private final val test4Compartment1: String = "wMqvLMZHhHMvwLH"
private final val test4Compartment2: String = "jbvcjnnSBnvTQFn"
private final val common1: String = "p"
private final val common2: String = "L"
private final val common3: String = "P"
private final val common4: String = "v"
private final val common5: String = "t"
private final val common6: String = "s"
@Test
fun testConstructor() {
var ruck = Rucksack(test1)
assertNotNull(ruck)
assertEquals(test1, ruck.contents)
assertEquals(test1Compartment1, ruck.compartment1)
assertEquals(test1Compartment2, ruck.compartment2)
}
@Test
fun testConstructor2() {
var ruck = Rucksack(test4)
assertNotNull(ruck)
assertEquals(test4, ruck.contents)
assertEquals(test4Compartment1, ruck.compartment1)
assertEquals(test4Compartment2, ruck.compartment2)
}
@ParameterizedTest
@CsvSource(
"vJrwpWtwJgWrhcsFMMfFFhFp, p",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL, L",
"PmmdzqPrVvPwwTWBwg, P",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn, v",
"ttgJtRGJQctTZtZT, t",
"CrZsJsPPZsGzwwsLwLmpwMDw, s"
)
fun testCommonItem(contents: String, commonItem: String) {
var ruck = Rucksack(contents)
assertEquals(commonItem, ruck.commonItem)
}
@ParameterizedTest
@CsvSource(
"vJrwpWtwJgWrhcsFMMfFFhFp, 16",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL, 38",
"PmmdzqPrVvPwwTWBwg, 42",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn, 22",
"ttgJtRGJQctTZtZT, 20",
"CrZsJsPPZsGzwwsLwLmpwMDw, 19"
)
fun testItemScore(contents: String, expectedPriority: Int) {
var ruck = Rucksack(contents)
assertEquals(expectedPriority, ruck.itemPriority)
}
} | 0 | Kotlin | 0 | 0 | a1b348ec33f85642534c46af8c4a69e7b78234ab | 2,615 | aoc2022kt | Apache License 2.0 |
rpc-io-test/src/main/java/io/patamon/test/tcp/bio/TestServer.kt | IceMimosa | 139,144,504 | false | {"Maven POM": 15, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 42, "Java": 5, "Protocol Buffer": 1, "XML": 2} | package io.patamon.test.tcp.bio
import java.net.ServerSocket
import java.net.Socket
/**
* Desc: test server
* Mail: <EMAIL>
* Created by IceMimosa
* Date: 2017/3/19
*/
object TestServer {
@JvmStatic
fun main(args: Array<String>) {
val server = ServerSocket(18888)
while (true) {
val socket = server.accept()
Thread(ServerThread(socket)).start()
}
}
}
class ServerThread(private val socket: Socket) : Runnable {
override fun run() {
// 获取请求内容
val input = socket.getInputStream()
val reader = input.bufferedReader()
var line = reader.readLine()
while (line != null) {
println(line)
line = reader.readLine() // 会阻塞,对于http请求需要理解 http 请求头组成
}
// 响应
val out = socket.getOutputStream()
val ow = out.writer()
ow.write("server: 我收到啦!!!!")
ow.flush()
// 关闭资源
ow.close()
out.close()
reader.close()
input.close()
socket.close()
}
} | 0 | Kotlin | 0 | 2 | 95cff3fb292c2cea091651f251abb6371a27ef1f | 1,060 | Erpc | MIT License |
app/src/main/java/com/friendly_machines/frbpdoctor/ui/settings/RxBleDevicePreference.kt | daym | 744,679,396 | false | {"Kotlin": 177161} | package com.friendly_machines.frbpdoctor.ui.settings
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.widget.Toast
import androidx.preference.DialogPreference
import androidx.preference.EditTextPreference
import com.friendly_machines.frbpdoctor.R
import com.polidea.rxandroidble3.RxBleDevice
class RxBleDevicePreference(context: Context, attrs: AttributeSet?) : EditTextPreference(context, attrs) {
// class SimpleSummaryProvider private constructor() : SummaryProvider<RxBleDevicePreference?> {
// override fun provideSummary(preference: RxBleDevicePreference): CharSequence? {
// return if (preference.device == null) {
// preference.context.getString(R.string.not_set)
// } else {
// preference.device!!.macAddress
// }
// }
//
// companion object {
// val instance: SimpleSummaryProvider by lazy {
// SimpleSummaryProvider()
// }
// }
// }
//
// init {
// summaryProvider = SimpleSummaryProvider.instance
// }
} | 0 | Kotlin | 1 | 1 | f6c5c0c8320ca29f976b8eb57c397e0db01bc13c | 1,133 | frbpdoctor | BSD 2-Clause FreeBSD License |
app/src/main/java/com/parassidhu/coronavirusapp/di/NetworkModule.kt | Anant00 | 249,819,016 | false | null | package com.parassidhu.coronavirusapp.di
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import com.parassidhu.coronavirusapp.BuildConfig
import com.parassidhu.coronavirusapp.network.ApiClient
import com.parassidhu.coronavirusapp.util.Constants
@Module
class NetworkModule {
@Provides
@Singleton
fun getRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun getOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor,
headerInterceptor: Interceptor
): OkHttpClient {
val httpBuilder = OkHttpClient.Builder()
.addInterceptor(headerInterceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.addNetworkInterceptor(StethoInterceptor())
if (BuildConfig.DEBUG)
httpBuilder.addInterceptor(loggingInterceptor)
return httpBuilder
.protocols(mutableListOf(Protocol.HTTP_1_1))
.build()
}
@Provides
@Singleton
fun getHeaderInterceptor(): Interceptor {
return Interceptor { chain ->
val request =
chain.request().newBuilder()
.addHeader("x-rapidapi-host", "coronavirus-monitor.p.rapidapi.com")
.addHeader("x-rapidapi-key", Constants.API_KEY)
val actualRequest = request.build()
chain.proceed(actualRequest)
}
}
@Provides
@Singleton
fun getLoggingInterceptor(): HttpLoggingInterceptor {
val httpLoggingInterceptor = HttpLoggingInterceptor()
return httpLoggingInterceptor.apply {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
}
}
@Provides
@Singleton
fun getApiClient(retrofit: Retrofit): ApiClient {
return retrofit.create(ApiClient::class.java)
}
/*@Provides
@Singleton
fun getNetworkFlipperPlugin(): NetworkFlipperPlugin {
return NetworkFlipperPlugin()
}*/
@Provides
@Singleton
fun getGlideUrl(): GlideUrl {
return GlideUrl(Constants.MASK_INSTRUCTIONS_URL, LazyHeaders.Builder()
.addHeader("x-rapidapi-host", "coronavirus-monitor.p.rapidapi.com")
.addHeader("x-rapidapi-key", Constants.API_KEY)
.build()
)
}
@Provides
@Singleton
fun getGson(): Gson {
return Gson()
}
@Provides
@Singleton
fun getFirebaseRemoteConfig(): FirebaseRemoteConfig {
return Firebase.remoteConfig
}
} | 1 | null | 1 | 1 | 543c5b164ac92b6a16cd8b2b4a5cba4e25d2ad60 | 3,333 | Coronavirus-Tracker | MIT License |
mobile/src/main/java/co/uk/kenkwok/tulipmania/service/BitfinexWebSocket.kt | kennethkwok | 108,638,140 | false | null | package co.uk.kenkwok.tulipmania.service
import co.uk.kenkwok.tulipmania.models.CryptoType
import io.reactivex.Completable
import io.reactivex.Flowable
/**
* Created by kwokk on 03/01/2018.
*/
interface BitfinexWebSocket {
fun connectWebSocket(): Completable
fun closeWebSocket(): Completable
fun subscribeToTicker(type: CryptoType)
fun unsubscribeFromTicker(channelId: String)
fun getTickerFlowable(): Flowable<String>
} | 1 | null | 1 | 1 | b034e7c3c8678d9e8c475ad8dafd4d005cee67ab | 445 | tulipmania | Creative Commons Attribution 3.0 Unported |
src/main/kotlin/br/com/acmattos/hdc/common/tool/server/prometheus/PrometheusServer.kt | acmattos | 225,613,144 | false | {"Kotlin": 955728, "JavaScript": 151772, "HTML": 26378, "CSS": 4190} | package br.com.acmattos.hdc.common.tool.server.prometheus
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.HTTPServer
import org.eclipse.jetty.server.handler.StatisticsHandler
import org.eclipse.jetty.util.thread.QueuedThreadPool
/**
* @author ACMattos
* @since 09/06/2020.
*/
class PrometheusServer(
private val statisticsHandler: StatisticsHandler,
private val queuedThreadPool: QueuedThreadPool
){
private lateinit var httpServer: HTTPServer
fun start(port: Int): PrometheusServer {
StatisticsHandlerCollector.initialize(statisticsHandler)
QueuedThreadPoolCollector.initialize(queuedThreadPool)
httpServer = HTTPServer(port)
return this
}
fun stop() : PrometheusServer {
StatisticsHandlerCollector.finalize()
QueuedThreadPoolCollector.finalize()
httpServer.close()
CollectorRegistry.defaultRegistry.clear()
return this
}
} | 0 | Kotlin | 0 | 0 | 8d7aec8840ff9cc87eb17921058d23cfc0d2ca6c | 966 | hdc | MIT License |
app/src/main/java/com/vspace/view/fake/FakeLocationFactory.kt | ALEX5402 | 702,138,083 | false | null | package com.vspace.view.fake
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.vspace.data.FakeLocationRepository
class FakeLocationFactory(private val repo: FakeLocationRepository) : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return FakeLocationViewModel(repo) as T
}
}
| 6 | null | 121 | 77 | d318afebf0723b277ddc5f85e985ed4add3ecf59 | 424 | NewBlackbox | MIT License |
src/main/java/com/alcosi/lib/doc/OpenAPIConfig.kt | alcosi | 698,911,809 | false | {"Kotlin": 279427, "Java": 45688, "HTML": 4094, "JavaScript": 1134, "CSS": 203} | /*
* Copyright (c) 2023 Alcosi Group Ltd. and affiliates.
*
* 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.alcosi.lib.doc
import org.apache.commons.io.IOUtils
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.servlet.function.RouterFunction
import org.springframework.web.servlet.function.RouterFunctions
import org.springframework.web.servlet.function.ServerResponse
import java.util.logging.Level
import java.util.logging.Logger
@AutoConfiguration
@ConditionalOnProperty(
prefix = "common-lib.openapi",
name = ["disabled"],
matchIfMissing = true,
havingValue = "false",
)
@EnableConfigurationProperties(OpenAPIProperties::class)
class OpenAPIConfig {
val allowedFileRegex: Regex = "^([a-zA-Z0-9_\\-()])+(\\.\\w{1,4})\$".toRegex()
val logger = Logger.getLogger(this.javaClass.name)
@Bean
@ConditionalOnMissingBean(OpenDocErrorConstructor::class)
fun openApiErrorConstructor(): OpenDocErrorConstructor.Default {
return OpenDocErrorConstructor.Default()
}
@Bean
fun openAPIRoute(
openAPIProperties: OpenAPIProperties,
errorConstructor: OpenDocErrorConstructor,
): RouterFunction<ServerResponse> {
return RouterFunctions
.route()
.GET(openAPIProperties.apiWebPath) {
val fileName = it.pathVariable("fileName")
val rs =
try {
if (!allowedFileRegex.matches(fileName)) {
throw RuntimeException("Bad filename")
}
val resourceToByteArray =
IOUtils.resourceToByteArray("/openapi/$fileName").let { array ->
if (fileName.equals("swagger-initializer.js", true)) {
String(array).replace("@ApiPathName@", openAPIProperties.filePath).toByteArray()
} else {
array
}
}
val type =
if (fileName.endsWith("html", true)) {
MediaType.TEXT_HTML_VALUE
} else if (fileName.endsWith("js", true)) {
"application/javascript; charset=utf-8"
} else if (fileName.endsWith("css", true)) {
"text/css"
} else if (fileName.endsWith("png", true)) {
MediaType.IMAGE_PNG_VALUE
} else if (fileName.endsWith("json", true)) {
MediaType.APPLICATION_JSON_VALUE
} else if (fileName.endsWith("yml", true)) {
MediaType.TEXT_PLAIN_VALUE
} else if (fileName.endsWith("yaml", true)) {
MediaType.TEXT_PLAIN_VALUE
} else {
MediaType.APPLICATION_OCTET_STREAM_VALUE
}
val builder =
ServerResponse.ok()
.header(HttpHeaders.CONTENT_TYPE, type)
if (type == MediaType.APPLICATION_OCTET_STREAM_VALUE) {
builder.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"${fileName}\"")
}
builder.body(resourceToByteArray)
} catch (t: Throwable) {
logger.log(Level.WARNING, "Error in openapi controller", t)
errorConstructor.constructError(t)
}
return@GET rs
}
.build()
}
}
| 0 | Kotlin | 0 | 0 | c1caaf2c7e31e4fb120faa0dea80d1cbfdb427dc | 4,810 | alcosi_commons_library | Apache License 2.0 |
src/main/kotlin/tasks/internal/AnimationScalesSwitch.kt | spring-media | 149,258,929 | false | null | package tasks.internal
import internal.*
class AnimationScalesSwitch(private val persistenceHelper: AnimationScalesPersistenceHelper) {
lateinit var deviceWrapper: DeviceWrapper
private lateinit var androidId: String
private lateinit var currentDeviceValues: LinkedHashMap<String, Float>
private val animationScaleValuesZero = createAnimationsScalesWithValue(scaleValueZero)
private val animationScaleValuesOne = createAnimationsScalesWithValue(scaleValueOne)
fun enableAnimations() {
updateDeviceValues()
when {
currentDeviceValues.hasNoZeros() && persistenceHelper.hasOneEntryForId(androidId) -> {
outputAnimationValues()
}
!currentDeviceValues.hasNoZeros() && persistenceHelper.hasOneEntryForId(androidId) -> {
val valuesToRestore = persistenceHelper.getValuesForDevice(androidId)
setAndOutputAnimationValues(valuesToRestore)
}
currentDeviceValues.hasNoZeros() && !persistenceHelper.hasOneEntryForId(androidId) -> {
outputAnimationValues()
}
!currentDeviceValues.hasNoZeros() && !persistenceHelper.hasOneEntryForId(androidId) -> {
setAndOutputAnimationValues(animationScaleValuesOne)
}
currentDeviceValues.hasNoZeros() && !persistenceHelper.hasConfigFile() -> {
outputAnimationValues()
}
!currentDeviceValues.hasNoZeros() && !persistenceHelper.hasConfigFile() -> {
setAndOutputAnimationValues(animationScaleValuesOne)
}
}
}
fun disableAnimations() {
updateDeviceValues()
when {
currentDeviceValues.areAllZero() && persistenceHelper.hasOneEntryForId(androidId) -> {
println("Animations already disabled for ${deviceWrapper.getDetails()}")
}
currentDeviceValues.areAllZero() && !persistenceHelper.hasOneEntryForId(androidId) -> {
persistenceHelper.appendTextToConfigFileForId(androidId, animationScaleValuesOne)
println("Animations already disabled for ${deviceWrapper.getDetails()}")
}
!currentDeviceValues.areAllZero() && persistenceHelper.hasOneEntryForId(androidId) -> {
persistenceHelper.deleteEntryForId(androidId)
persistenceHelper.appendTextToConfigFileForId(androidId, currentDeviceValues)
setValuesToZero(deviceWrapper)
}
!currentDeviceValues.areAllZero() && !persistenceHelper.hasOneEntryForId(androidId) -> {
persistenceHelper.appendTextToConfigFileForId(androidId, currentDeviceValues)
setValuesToZero(deviceWrapper)
}
}
}
private fun updateDeviceValues() {
androidId = deviceWrapper.getAndroidId()
currentDeviceValues = deviceWrapper.getAnimationValues()
}
private fun outputAnimationValues() {
deviceWrapper.printAnimationValues()
}
private fun setAndOutputAnimationValues(values: LinkedHashMap<String, Float>) {
deviceWrapper.setAnimationValues(values)
deviceWrapper.printAnimationValues()
}
private fun setValuesToZero(deviceWrapper: DeviceWrapper) {
deviceWrapper.setAnimationValues(animationScaleValuesZero)
deviceWrapper.printAnimationValues()
}
}
| 3 | Kotlin | 0 | 9 | 421f0777379d0b3e1d4e51a7f641aaa7bc446b81 | 3,444 | apps-android-testdevicemanager | MIT License |
mail/protocols/pop3/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Commands.kt | thunderbird | 1,326,671 | false | null | package com.fsck.k9.mail.store.pop3
internal object Pop3Commands {
const val STLS_COMMAND = "STLS"
const val USER_COMMAND = "USER"
const val PASS_COMMAND = "PASS"
const val CAPA_COMMAND = "CAPA"
const val AUTH_COMMAND = "AUTH"
const val STAT_COMMAND = "STAT"
const val LIST_COMMAND = "LIST"
const val UIDL_COMMAND = "UIDL"
const val TOP_COMMAND = "TOP"
const val RETR_COMMAND = "RETR"
const val DELE_COMMAND = "DELE"
const val QUIT_COMMAND = "QUIT"
const val STLS_CAPABILITY = "STLS"
const val UIDL_CAPABILITY = "UIDL"
const val TOP_CAPABILITY = "TOP"
const val SASL_CAPABILITY = "SASL"
const val AUTH_PLAIN_CAPABILITY = "PLAIN"
const val AUTH_CRAM_MD5_CAPABILITY = "CRAM-MD5"
const val AUTH_EXTERNAL_CAPABILITY = "EXTERNAL"
}
| 846 | null | 2467 | 9,969 | 8b3932098cfa53372d8a8ae364bd8623822bd74c | 805 | thunderbird-android | Apache License 2.0 |
tmp/arrays/kotlinAndJava/47.kt | mandelshtamd | 249,374,670 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | //File A.java
import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;
public class A {
@NotNull
public String foo() {
return "OK";
}
}
//File B.java
import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;
public class B extends A {
@NotNull
public String foo() {
return super.foo();
}
}
//File I.java
import kotlin.Metadata;
public interface I {
}
//File Main.kt
fun box() = C().foo()
//File C.java
import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;
public final class C extends B implements I {
@NotNull
public String foo() {
return super.foo();
}
}
| 1 | null | 1 | 1 | da010bdc91c159492ae74456ad14d93bdb5fdd0a | 646 | bbfgradle | Apache License 2.0 |
app/src/main/java/com/zaneschepke/wireguardautotunnel/service/shortcut/ShortcutsActivity.kt | zaneschepke | 644,710,160 | false | {"Kotlin": 177872, "HTML": 1349} | package com.zaneschepke.wireguardautotunnel.service.shortcut
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.repository.SettingsDoa
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
import com.zaneschepke.wireguardautotunnel.service.foreground.WireGuardTunnelService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class ShortcutsActivity : AppCompatActivity() {
@Inject
lateinit var settingsRepo : SettingsDoa
private val scope = CoroutineScope(Dispatchers.Main);
private fun attemptWatcherServiceToggle(tunnelConfig : String) {
scope.launch {
val settings = settingsRepo.getAll()
if (settings.isNotEmpty()) {
val setting = settings.first()
if(setting.isAutoTunnelEnabled) {
ServiceManager.toggleWatcherServiceForeground(this@ShortcutsActivity, tunnelConfig)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(intent.getStringExtra(ShortcutsManager.CLASS_NAME_EXTRA_KEY)
.equals(WireGuardTunnelService::class.java.name)) {
intent.getStringExtra(getString(R.string.tunnel_extras_key))?.let {
attemptWatcherServiceToggle(it)
}
when(intent.action){
Action.STOP.name -> ServiceManager.stopVpnService(this)
Action.START.name -> intent.getStringExtra(getString(R.string.tunnel_extras_key))
?.let { ServiceManager.startVpnService(this, it) }
}
}
finish()
}
} | 8 | Kotlin | 4 | 49 | ca3f3fd4392f6078695870c43f6c17d9d4c5d72e | 1,979 | wgtunnel | MIT License |
application/src/main/kotlin/org/rm3l/servicenamesportnumbers/app/scheduling/ScheduledTasks.kt | rm3l | 112,674,955 | false | null | /*
The MIT License (MIT)
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.rm3l.servicenamesportnumbers.app.scheduling
import org.rm3l.servicenamesportnumbers.ServiceNamesPortNumbersClient
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
@Component
class ScheduledTasks(val registryClient: ServiceNamesPortNumbersClient) {
private val logger = LoggerFactory.getLogger(ScheduledTasks::class.java)
@Scheduled(cron = "\${cacheRefresh.cron.expression}")
fun refreshCache() {
try {
logger.info("Updating DB ... ")
registryClient.refreshCache()
logger.info("... Task scheduled. Will be refreshed soon.")
} catch (e: Exception) {
if (logger.isDebugEnabled) {
logger.debug(e.message, e)
}
}
}
}
| 3 | Kotlin | 1 | 3 | 14709fc43efd8f86954870480f1eaf749b7822ad | 1,913 | service-names-port-numbers | MIT License |
app/src/main/kotlin/org/michaelbel/template/app/initializer/VkInitializer.kt | michaelbel | 354,625,997 | false | null | package org.michaelbel.template.app.initializer
import android.content.Context
import androidx.startup.Initializer
import com.vk.api.sdk.VK
@Suppress("unused")
class VkInitializer: Initializer<Unit> {
override fun create(context: Context) {
VK.initialize(context)
}
override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
} | 3 | Kotlin | 1 | 4 | a2faa29432baafc7e80bed321ea569dea1237189 | 366 | android-app-template | Apache License 2.0 |
qcode/src/main/java/com/frameworks/base/utils/CodeCharacterHandler.kt | zqMyself | 183,880,364 | false | {"Gradle": 5, "Java Properties": 2, "Proguard": 3, "Shell": 1, "XML": 40, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Java": 10, "Kotlin": 73} | /*
* Copyright 2017 JessYan
*
* 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.frameworks.base.utils
import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.StringReader
import java.io.StringWriter
import java.util.regex.Pattern
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerException
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
/**
* <pre>
* author : zengqiang
* e-mail : <EMAIL>
* time : 2019/04/11
* desc :处理字符串的工具类
* version : 1.0
</pre> *
*/
class CodeCharacterHandler private constructor() {
init {
throw IllegalStateException("you can't instantiate me!")
}
companion object {
val emojiFilter: InputFilter = object : InputFilter {//emoji过滤器
internal var emoji = Pattern.compile(
"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE or Pattern.CASE_INSENSITIVE)
override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int,
dend: Int): CharSequence? {
val emojiMatcher = emoji.matcher(source)
return if (emojiMatcher.find()) {
""
} else null
}
}
/**
* json 格式化
*
* @param json
* @return
*/
fun jsonFormat(json: String): String {
var json = json
if (TextUtils.isEmpty(json)) {
return "Empty/Null json content"
}
var message: String
try {
json = json.trim { it <= ' ' }
if (json.startsWith("{")) {
val jsonObject = JSONObject(json)
message = jsonObject.toString(4)
} else if (json.startsWith("[")) {
val jsonArray = JSONArray(json)
message = jsonArray.toString(4)
} else {
message = json
}
} catch (e: JSONException) {
message = json
}
return message
}
/**
* xml 格式化
*
* @param xml
* @return
*/
fun xmlFormat(xml: String): String {
if (TextUtils.isEmpty(xml)) {
return "Empty/Null xml content"
}
var message: String
try {
val xmlInput = StreamSource(StringReader(xml))
val xmlOutput = StreamResult(StringWriter())
val transformer = TransformerFactory.newInstance().newTransformer()
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
transformer.transform(xmlInput, xmlOutput)
message = xmlOutput.writer.toString().replaceFirst(">".toRegex(), ">\n")
} catch (e: TransformerException) {
message = xml
}
return message
}
}
}
| 0 | Kotlin | 0 | 0 | 7c3490326b223a53aca6012c3e618dea9d2906c6 | 3,892 | qcode | Apache License 2.0 |
Kotlin-Samples/src/main/kotlin/chapter8/Recipe7.kt | PacktPublishing | 126,314,798 | false | null | package chapter9
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyString
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
/**
* Chapter: Best practices for Android, JUnit and JVM UI frameworks
* Recipe: Mocking dependencies with kotlin-mockito
*/
class Recipe7 {
private val api = mock<RegistrationApi>()
private lateinit var registrationFormController: RegistrationFormController
@Before
fun setup() {
registrationFormController = RegistrationFormController(api = api)
}
@Test
fun `email shouldn't be registered if it's not valid`() {
// given
assertNotNull(registrationFormController)
whenever(api.isEmailAddressAvailable(anyString())) doReturn(true)
// when
registrationFormController.currentEmailAddress = "Hilary"
// then
assertFalse(registrationFormController.checkIfEmailCanBeRegistered())
}
private class RegistrationFormController(val api: RegistrationApi) {
var currentEmailAddress: String = ""
fun isEmailIsValid(): Boolean = currentEmailAddress.contains("@")
fun checkIfEmailCanBeRegistered(): Boolean =
isEmailIsValid() && api.isEmailAddressAvailable(currentEmailAddress)
}
private interface RegistrationApi {
fun isEmailAddressAvailable(email: String): Boolean
}
}
| 0 | Kotlin | 24 | 26 | a9118396250ded6f4466c20fd0dc62ea6a598ed1 | 1,527 | Kotlin-Standard-Library-Cookbook | MIT License |
testutils/testutils-kmp/src/commonTest/kotlin/androidx/kruth/SubjectTest.kt | bentrengrove | 293,227,657 | true | {"Kotlin": 53957973, "Java": 52425692, "C++": 8961065, "Python": 262621, "AIDL": 233835, "Shell": 174666, "ANTLR": 19860, "HTML": 10802, "CMake": 9490, "TypeScript": 7599, "JavaScript": 4865, "C": 4764, "Objective-C++": 3190} | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.kruth
import kotlin.test.Test
import kotlin.test.assertFailsWith
/**
* A mirror of existing tests in official Truth for parity. For additional tests in Kruth, see
* [SubjectKruthTest].
*
* Partially migrated from Truth's source in Github:
* https://github.com/google/truth/blob/master/core/src/test/java/com/google/common/truth/SubjectTest.java
*
* Note: This does not include assertions against failure messages, as Kruth does not currently
* implement the same fact system Truth has yet.
*
* @see SubjectKruthTest for additional tests on top of these migrated ones for Kruth.
*/
class SubjectTest {
@Test
fun toStringsAreIdentical() {
class IntWrapper(val wrapped: Int) {
override fun toString(): String = wrapped.toString()
}
val wrapper = IntWrapper(5)
assertFailsWith<AssertionError> {
assertThat(5).isEqualTo(wrapper)
}
}
@Test
fun isEqualToWithNulls() {
val o: Any? = null
assertThat(o).isEqualTo(null)
}
@Test
fun isEqualToFailureWithNulls() {
val o: Any? = null
assertFailsWith<AssertionError> {
assertThat(o).isEqualTo("a")
}
}
@Test
fun isEqualToStringWithNullVsNull() {
assertFailsWith<AssertionError> {
assertThat("null").isEqualTo(null)
}
}
@Test
fun isEqualToWithSameObject() {
val a: Any = Any()
val b: Any = a
assertThat(a).isEqualTo(b)
}
@Test
fun isEqualToFailureWithObjects() {
val a: Any = Any()
val b: Any = Any()
assertFailsWith<AssertionError> {
assertThat(a).isEqualTo(b)
}
}
@Test
fun isEqualToFailureWithDifferentTypesAndSameToString() {
val a: Any = "true"
val b: Any = true
assertFailsWith<AssertionError> {
assertThat(a).isEqualTo(b)
}
}
@Test
fun isEqualToNullBadEqualsImplementation() {
assertFailsWith<AssertionError> {
assertThat(ThrowsOnEqualsNull()).isEqualTo(null)
}
}
@Test
fun isEqualToSameInstanceBadEqualsImplementation() {
val o: Any = ThrowsOnEquals()
assertThat(o).isEqualTo(o)
}
@Test
fun isInstanceOfExactType() {
assertThat("a").isInstanceOf<String>()
}
@Test
fun isInstanceOfSuperclass() {
assertThat(3).isInstanceOf<Number>()
}
@Test
fun isInstanceOfImplementedInterface() {
assertThat("a").isInstanceOf<CharSequence>()
}
@Test
fun isInstanceOfUnrelatedClass() {
assertFailsWith<AssertionError> {
assertThat(4.5).isInstanceOf<Long>()
}
}
@Test
fun isInstanceOfUnrelatedInterface() {
assertFailsWith<AssertionError> {
assertThat(4.5).isInstanceOf<CharSequence>()
}
}
@Test
fun isInstanceOfClassForNull() {
assertFailsWith<AssertionError> {
assertThat(null as Any?).isInstanceOf<Long>()
}
}
@Test
fun isInstanceOfInterfaceForNull() {
assertFailsWith<AssertionError> {
assertThat(null as Any?).isInstanceOf<CharSequence>()
}
}
@Test
fun disambiguationWithSameToString() {
assertFailsWith<AssertionError> {
assertThat(StringBuilder("foo")).isEqualTo(StringBuilder("foo"))
}
}
}
@Suppress("EqualsOrHashCode")
private class ThrowsOnEquals {
override fun equals(other: Any?): Boolean {
throw UnsupportedOperationException()
}
}
@Suppress("EqualsOrHashCode")
private class ThrowsOnEqualsNull {
override fun equals(other: Any?): Boolean {
// buggy implementation but one that we're working around, at least for now
checkNotNull(other)
return super.equals(other)
}
}
| 0 | Kotlin | 0 | 1 | a9837acd3ec7bed2eb65590aa1e32f26f1cc18cc | 4,489 | androidx | Apache License 2.0 |
tickers/real-time/src/test/kotlin/fund/cyber/markets/ticker/processor/HopTickerProcessorTest.kt | cybercongress | 97,112,173 | false | {"Kotlin": 330007, "HTML": 7008, "Dockerfile": 907} | package fund.cyber.markets.ticker.processor
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import fund.cyber.markets.common.MILLIS_TO_MINUTES
import fund.cyber.markets.common.convert
import fund.cyber.markets.common.model.TokensPair
import fund.cyber.markets.common.model.Trade
import fund.cyber.markets.common.model.TradeType
import fund.cyber.markets.ticker.common.CrossConversion
import fund.cyber.markets.ticker.service.TickerService
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Test
import java.math.BigDecimal
class HopTickerProcessorTest {
private lateinit var hopTickerProcessor: HopTickerProcessor
private val windowHop = 3000L
@Before
fun before() {
val ts = System.currentTimeMillis()
val epochMin = ts convert MILLIS_TO_MINUTES
val trades = mutableListOf(
Trade("TestEx", TokensPair("BTC", "USD"), TradeType.ASK, ts, epochMin, "id", BigDecimal(5L), BigDecimal(10L), BigDecimal(2L)),
Trade("TestEx", TokensPair("XMR", "USD"), TradeType.ASK, ts, epochMin, "id", BigDecimal(100L), BigDecimal(10L), BigDecimal(0.1))
)
val tickerService: TickerService = mock {
on {
pollTrades()
}.doReturn(
trades
)
}
val crossConversion = CrossConversion()
hopTickerProcessor = HopTickerProcessor(tickerService, crossConversion, windowHop)
}
@Test
fun hopTickersTest() {
val tickers = hopTickerProcessor.getHopTickers()
Assertions.assertThat(tickers).hasSize(3)
Assertions.assertThat(tickers["XMR"]?.baseVolume).hasSize(2)
Assertions.assertThat(tickers["XMR"]!!.baseVolume["USD"]!!["ALL"]).isNotNull()
}
} | 17 | Kotlin | 10 | 46 | f3254bc93784f4d570a7d6bfda58f76413cf6444 | 1,802 | cyber-markets | MIT License |
app/src/test/java/com/peter/azure/viewmodel/PrintViewModelTest.kt | peterdevacc | 649,972,321 | false | null | package com.peter.azure.viewmodel
import com.peter.azure.data.entity.*
import com.peter.azure.data.repository.PdfRepository
import com.peter.azure.data.repository.SudokuRepository
import com.peter.azure.data.util.DataResult
import com.peter.azure.ui.print.PdfUiState
import com.peter.azure.ui.print.PrintViewModel
import io.mockk.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
class PrintViewModelTest {
private val sudokuRepository = mockk<SudokuRepository>(relaxed = true)
private val pdfRepository = mockk<PdfRepository>(relaxed = true)
private val viewModel = PrintViewModel(
sudokuRepository, pdfRepository
)
@OptIn(DelicateCoroutinesApi::class)
private val mainThreadSurrogate = newSingleThreadContext("UI thread")
private val magicNum = 600L
private val appName = "AzureNum"
private val gameLevelTitlePrefix = "Game Level"
private val gameLevelTextList = listOf(
"Easy",
"Moderate",
"Hard",
)
private val gameLevelList = listOf(
GameLevel.MODERATE, GameLevel.EASY, GameLevel.MODERATE, GameLevel.EASY,
GameLevel.HARD, GameLevel.HARD
)
@Test
fun `add game level`() = runBlocking {
gameLevelList.forEach {
viewModel.addGameLevel(it)
}
assertEquals(5, viewModel.gameLevelList.value.size)
}
@Test
fun `remove game level`() = runBlocking {
gameLevelList.forEach {
viewModel.removeGameLevel(it)
}
assertTrue(viewModel.gameLevelList.value.isEmpty())
}
@Test
fun `generate Sudoku PDF`() = runBlocking {
launch(Dispatchers.Main) {
// EmptyGameLevelList
viewModel.generateSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
)
delay(magicNum)
coVerify(exactly = 0) {
sudokuRepository.getPrintGameList(viewModel.gameLevelList.value)
pdfRepository.createSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
printGameList = emptyList()
)
}
confirmVerified(sudokuRepository, pdfRepository)
assertTrue(viewModel.pdfUiState.value is PdfUiState.EmptyGameLevelList)
clearAllMocks()
// Loaded
coEvery {
sudokuRepository.getPrintGameList(
viewModel.gameLevelList.value
)
} returns emptyList()
val sudokuPdf = SudokuPdf(File(""), emptyList())
coEvery {
pdfRepository.createSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
printGameList = emptyList()
)
} returns DataResult.Success(sudokuPdf)
viewModel.addGameLevel(GameLevel.EASY)
viewModel.generateSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
)
delay(magicNum)
coVerify(exactly = 1) {
sudokuRepository.getPrintGameList(viewModel.gameLevelList.value)
pdfRepository.createSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
printGameList = emptyList()
)
}
confirmVerified(sudokuRepository, pdfRepository)
assertTrue(viewModel.pdfUiState.value is PdfUiState.Loaded)
val resultSuccess = (viewModel.pdfUiState.value as PdfUiState.Loaded).sudokuPdf
assertEquals(sudokuPdf, resultSuccess)
clearAllMocks()
// Error
coEvery {
sudokuRepository.getPrintGameList(
viewModel.gameLevelList.value
)
} returns emptyList()
coEvery {
pdfRepository.createSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
printGameList = emptyList()
)
} returns DataResult.Error(DataResult.Error.Code.UNKNOWN)
viewModel.addGameLevel(GameLevel.EASY)
viewModel.generateSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
)
delay(magicNum)
coVerify(exactly = 1) {
sudokuRepository.getPrintGameList(viewModel.gameLevelList.value)
pdfRepository.createSudokuPdf(
appName = appName,
gameLevelTitlePrefix = gameLevelTitlePrefix,
gameLevelTextList = gameLevelTextList,
printGameList = emptyList()
)
}
confirmVerified(sudokuRepository, pdfRepository)
assertTrue(viewModel.pdfUiState.value is PdfUiState.Error)
val resultError = (viewModel.pdfUiState.value as PdfUiState.Error).code
assertEquals(DataResult.Error.Code.UNKNOWN, resultError)
}
Unit
}
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() {
Dispatchers.setMain(mainThreadSurrogate)
}
@OptIn(ExperimentalCoroutinesApi::class)
@After
fun clean() {
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
} | 0 | Kotlin | 0 | 0 | 392f587cd2f0205c1bc95019c8ab5eadfdeb65af | 6,183 | Azure | Apache License 2.0 |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/meldekort/dto/MeldekortSammendragEx.kt | navikt | 487,246,438 | false | {"Kotlin": 929152, "Shell": 1318, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.routes.meldekort.dto
import no.nav.tiltakspenger.meldekort.domene.MeldekortSammendrag
import no.nav.tiltakspenger.vedtak.db.serialize
import no.nav.tiltakspenger.vedtak.routes.dto.PeriodeDTO
import no.nav.tiltakspenger.vedtak.routes.dto.toDTO
private data class MeldekortSammendragDTO(
val meldekortId: String,
val periode: PeriodeDTO,
val erUtfylt: Boolean,
)
fun List<MeldekortSammendrag>.toDTO(): String = serialize(map { it.toDTO() })
private fun MeldekortSammendrag.toDTO(): MeldekortSammendragDTO =
MeldekortSammendragDTO(
meldekortId = meldekortId.toString(),
periode = periode.toDTO(),
erUtfylt = erUtfylt,
)
| 9 | Kotlin | 0 | 1 | ff930409c02637e546fc7ed0cba19141e98a85db | 701 | tiltakspenger-vedtak | MIT License |
coreactor/src/main/java/com/sumera/coreactor/internal/assert/ThreadCheck.kt | SumeraMartin | 213,146,164 | false | {"Kotlin": 241583} | package com.sumera.coreactor.internal.assert
import android.os.Looper
import com.sumera.coreactor.error.CoreactorException
internal object MainThreadChecker {
var ignoreCheck = false
fun requireMainThread(methodName: String) {
if (ignoreCheck) {
return
}
if (Looper.getMainLooper().thread != Thread.currentThread()) {
throw CoreactorException("$methodName method is not called on the main thread")
}
}
}
fun requireMainThread(methodName: String) {
MainThreadChecker.requireMainThread(methodName)
}
| 0 | Kotlin | 0 | 4 | ce065d6a0a6573d63ca3262ef4dee11fb3c565af | 575 | Coreactor | MIT License |
lib/stove-testing-e2e-couchbase/src/test/kotlin/com/trendyol/stove/testing/e2e/couchbase/CouchbaseTestSystemTests.kt | Trendyol | 590,452,775 | false | null | package com.trendyol.stove.testing.e2e.couchbase
import com.trendyol.stove.testing.e2e.database.DocumentDatabaseSystem.Companion.shouldGet
import com.trendyol.stove.testing.e2e.system.TestSystem
import com.trendyol.stove.testing.e2e.system.abstractions.ApplicationUnderTest
import io.kotest.core.config.AbstractProjectConfig
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.UUID
class Setup : AbstractProjectConfig() {
override suspend fun beforeProject() {
TestSystem()
.withCouchbase(UUID.randomUUID().toString())
.applicationUnderTest(NoOpApplication())
.run()
}
override suspend fun afterProject() {
TestSystem.instance.close()
}
}
class NoOpApplication : ApplicationUnderTest<Unit> {
override suspend fun start(configurations: List<String>) {
}
override suspend fun stop() {
}
}
class CouchbaseTestSystemTests : FunSpec({
data class ExampleInstance(
val id: String,
val description: String,
)
test("should save and get") {
val id = UUID.randomUUID().toString()
TestSystem.instance
.couchbase()
.saveToDefaultCollection(id, ExampleInstance(id = id, description = testCase.name.testName))
.shouldGet<ExampleInstance>(id) { actual ->
actual.id shouldBe id
actual.description shouldBe testCase.name.testName
}
}
})
| 7 | null | 1 | 6 | c956e5304beda766fe48adc589db47504c8b58b6 | 1,480 | stove4k | Apache License 2.0 |
desktopApp/src/jvmMain/kotlin/com/prof18/feedflow/desktop/search/SearchScreen.desktop.kt | prof18 | 600,257,020 | false | {"Kotlin": 589660, "HTML": 163737, "SCSS": 161629, "Swift": 124027, "CSS": 16810, "Shell": 1591, "JavaScript": 1214} | package com.prof18.feedflow.desktop.search
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.prof18.feedflow.core.model.FeedItemId
import com.prof18.feedflow.core.model.FeedItemUrlInfo
import com.prof18.feedflow.core.model.SearchState
import com.prof18.feedflow.desktop.BrowserManager
import com.prof18.feedflow.desktop.di.DI
import com.prof18.feedflow.desktop.openInBrowser
import com.prof18.feedflow.shared.presentation.SearchViewModel
import com.prof18.feedflow.shared.ui.search.SearchScreenContent
import com.prof18.feedflow.shared.ui.theme.FeedFlowTheme
@Composable
internal fun SearchScreen(
viewModel: SearchViewModel,
navigateBack: () -> Unit,
navigateToReaderMode: (FeedItemUrlInfo) -> Unit,
) {
val browserManager = DI.koin.get<BrowserManager>()
val state: SearchState by viewModel.searchState.collectAsState()
val searchQuery by viewModel.searchQueryState.collectAsState()
SearchScreenContent(
searchState = state,
searchQuery = searchQuery,
updateSearchQuery = { query ->
viewModel.updateSearchQuery(query)
},
navigateBack = navigateBack,
onFeedItemClick = { urlInfo ->
if (browserManager.openReaderMode()) {
navigateToReaderMode(urlInfo)
} else {
openInBrowser(urlInfo.url)
}
viewModel.onReadStatusClick(FeedItemId(urlInfo.id), true)
},
onBookmarkClick = { feedItemId, isBookmarked ->
viewModel.onBookmarkClick(feedItemId, isBookmarked)
},
onReadStatusClick = { feedItemId, isRead ->
viewModel.onReadStatusClick(feedItemId, isRead)
},
onCommentClick = { urlInfo ->
openInBrowser(urlInfo.url)
viewModel.onReadStatusClick(FeedItemId(urlInfo.id), true)
},
)
}
@Preview
@Composable
private fun Preview() {
FeedFlowTheme {
SearchScreenContent(
searchState = SearchState.EmptyState,
searchQuery = "",
updateSearchQuery = {},
navigateBack = {},
onFeedItemClick = {},
onBookmarkClick = { _, _ -> },
onReadStatusClick = { _, _ -> },
onCommentClick = {},
)
}
}
| 22 | Kotlin | 11 | 244 | c2ef5ef0812e17ee15e9cf1446057fd61fb80f8b | 2,416 | feed-flow | Apache License 2.0 |
sample-app/src/main/java/ru/radiationx/kdiffersample/MainViewModel.kt | RadiationX | 360,635,395 | false | null | package ru.radiationx.kdiffersample
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.plus
import ru.radiationx.kdiffersample.data.FeedRepository
import ru.radiationx.kdiffersample.data.entity.PostEntity
class MainViewModel(
private val repository: FeedRepository
) : ViewModel() {
private val _postsItemsState = MutableStateFlow(emptyList<PostEntity>())
val postsItemsState: StateFlow<List<PostEntity>> = _postsItemsState
init {
observePosts()
}
private fun observePosts() {
repository
.observe()
.onEach {
_postsItemsState.value = it
}
.launchIn(viewModelScope + Dispatchers.IO)
}
} | 0 | Kotlin | 0 | 2 | e934abcf21faedaaae37fc82f577e9d0db82a405 | 955 | KDiffer | Apache License 2.0 |
src/main/kotlin/me/melijn/melijnbot/internals/web/rest/stats/StatUtil.kt | ToxicMushroom | 107,187,088 | false | null | package me.melijn.melijnbot.internals.web.rest.stats
import com.sun.management.OperatingSystemMXBean
import me.melijn.melijnbot.MelijnBot
import me.melijn.melijnbot.internals.JvmUsage
import me.melijn.melijnbot.internals.events.eventutil.VoiceUtil
import me.melijn.melijnbot.internals.music.GuildMusicPlayer
import me.melijn.melijnbot.internals.threading.TaskManager
import me.melijn.melijnbot.internals.utils.getSystemUptime
import me.melijn.melijnbot.internals.web.RequestContext
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.utils.data.DataArray
import net.dv8tion.jda.api.utils.data.DataObject
import java.lang.management.ManagementFactory
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.ThreadPoolExecutor
fun computeBaseObject(): DataObject {
val bean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
val (totalMem, usedMem, totalJVMMem, usedJVMMem) = JvmUsage.current(bean)
val threadPoolExecutor = TaskManager.executorService as ForkJoinPool
val scheduledExecutorService = TaskManager.scheduledExecutorService as ThreadPoolExecutor
val dataObject = DataObject.empty()
dataObject.put(
"bot", DataObject.empty()
.put("uptime", ManagementFactory.getRuntimeMXBean().uptime)
.put(
"melijnThreads",
threadPoolExecutor.activeThreadCount + scheduledExecutorService.activeCount + scheduledExecutorService.queue.size
)
.put("ramUsage", usedJVMMem)
.put("ramTotal", totalJVMMem)
.put("jvmThreads", Thread.activeCount())
.put("cpuUsage", bean.processCpuLoad * 100)
)
dataObject.put(
"server", DataObject.empty()
.put("uptime", getSystemUptime())
.put("ramUsage", usedMem)
.put("ramTotal", totalMem)
)
return dataObject
}
fun getPlayersAndQueuedTracks(
jda: JDA,
players: Map<Long, GuildMusicPlayer>
): Pair<Int, Int> {
var queuedTracks = 0
var musicPlayers = 0
for (player in players.values) {
if (jda.guildCache.getElementById(player.guildId) != null) {
if (player.guildTrackManager.iPlayer.playingTrack != null) {
musicPlayers++
}
queuedTracks += player.guildTrackManager.trackSize()
}
}
return Pair(queuedTracks, musicPlayers)
}
fun computeShardStatsObject(
jda: JDA,
queuedTracks: Int,
musicPlayers: Int
) = DataObject.empty()
.put("guildCount", jda.guildCache.size())
.put("userCount", jda.userCache.size())
.put("connectedVoiceChannels", VoiceUtil.getConnectedChannelsAmount(jda))
.put("listeningVoiceChannels", VoiceUtil.getConnectedChannelsAmount(jda, true))
.put("ping", jda.gatewayPing)
.put("status", jda.status)
.put("queuedTracks", queuedTracks)
.put("musicPlayers", musicPlayers)
.put("responses", jda.responseTotal)
.put("id", jda.shardInfo.shardId)
.put("unavailable", jda.guilds.count { it.jda.isUnavailable(it.idLong) })
fun computePublicStatsObject(context: RequestContext): DataArray {
val shardManager = MelijnBot.shardManager
val dataArray = DataArray.empty()
val players = context.lavaManager.musicPlayerManager.getPlayers()
for (shard in shardManager.shardCache) {
val (queuedTracks, musicPlayers) = getPlayersAndQueuedTracks(shard, players)
dataArray.add(computeShardStatsObject(shard, queuedTracks, musicPlayers))
}
return dataArray
}
| 5 | Kotlin | 22 | 80 | 01107bbaad0e343d770b1e4124a5a9873b1bb5bd | 3,524 | Melijn | MIT License |
amazon/firehose/fake/src/test/kotlin/org/http4k/connect/amazon/firehose/RunningFakeFirehoseTest.kt | http4k | 295,641,058 | false | {"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675} | package org.http4k.connect.amazon.firehose
import org.http4k.connect.WithRunningFake
import org.http4k.connect.amazon.FakeAwsContract
class RunningFakeFirehoseTest : FirehoseContract, FakeAwsContract, WithRunningFake(::FakeFirehose)
| 7 | Kotlin | 17 | 37 | 94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c | 235 | http4k-connect | Apache License 2.0 |
app/src/main/java/com/briggin/footballfinder/common/data/FootballStorage.kt | bRiggin | 334,403,976 | false | null | package com.briggin.footballfinder.common.data
import com.briggin.footballfinder.common.domain.PlayerDomain
import com.briggin.footballfinder.common.domain.TeamDomain
interface FootballStorage : FootballApi {
suspend fun updatePlayers(players: List<PlayerDomain>)
suspend fun updateTeams(teams: List<TeamDomain>)
suspend fun getFavouritePlayers(): List<PlayerDomain>
suspend fun likePlayer(id: String)
suspend fun unlikePlayer(id: String)
}
| 0 | Kotlin | 0 | 0 | 5b5975997a0a26405e2db57628b3e3722ce3787a | 464 | footballFinder | MIT License |
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/helpers/japanese/KanaKanjiDetector.kt | MihailsKuzmins | 240,947,625 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 323, "XML": 156, "Java": 1, "JSON": 1} | package jp.mihailskuzmins.sugoinihongoapp.helpers.japanese
object KanaKanjiDetector {
fun hasKanaOrKanji(string: String) = string.any(::isKanaOrKanji)
fun hasKana(string: String) = string.any(::isKana)
fun hasKanji(string: String) = string.any(::isKanji)
fun hasRomaji(string: String) = string.any(::isRomaji)
fun isKanaOrKanji(char: Char) =
isKana(char) || isKanji(char)
fun isKana(char: Char): Boolean {
val unicodeBlock = Character.UnicodeBlock.of(char)
return unicodeBlock === Character.UnicodeBlock.HIRAGANA ||
unicodeBlock === Character.UnicodeBlock.KATAKANA ||
unicodeBlock === Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS
}
fun isKanji(char: Char) =
Character.UnicodeBlock.of(char) === Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS ||
char == '々'
fun isRomaji(char: Char) =
char in 'A'..'Z' || char in 'a'..'z'
fun isPunctuation(char: Char) =
when (char) {
'、' -> true
else -> false
}
} | 1 | null | 1 | 1 | 57e19b90b4291dc887a92f6d57f9be349373a444 | 954 | sugoi-nihongo-android | Apache License 2.0 |
core/src/main/kotlin/gropius/dto/input/issue/CreateLabelInput.kt | ccims | 487,996,394 | false | {"Kotlin": 958426, "TypeScript": 437791, "MDX": 55477, "JavaScript": 25165, "HTML": 17174, "CSS": 4796, "Shell": 2363} | package gropius.dto.input.issue
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import com.expediagroup.graphql.generator.annotations.GraphQLType
import com.expediagroup.graphql.generator.scalars.ID
import gropius.dto.input.common.CreateNamedNodeInput
@GraphQLDescription("Input for the createLabel mutation")
class CreateLabelInput(
@GraphQLDescription("Initial color of the Label")
@GraphQLType("Color")
val color: String,
@GraphQLDescription("IDs of Trackables the Label is added to, at least one required.")
val trackables: List<ID>
) : CreateNamedNodeInput() {
override fun validate() {
super.validate()
if (trackables.isEmpty()) {
throw IllegalArgumentException("At least on trackable is required")
}
}
} | 3 | Kotlin | 1 | 0 | de0ece42541db960a08e1448cf0bd5afd65c996a | 802 | gropius-backend | MIT License |
android-app/src/main/java/dev/johnoreilly/galwaybus/ui/screens/BusStopDeparturesScreen.kt | joreilly | 96,469,751 | false | {"Kotlin": 120294, "Java": 73115, "Swift": 18911, "GLSL": 9264, "Ruby": 3887, "HTML": 572} | package dev.johnoreilly.galwaybus.ui
import androidx.compose.foundation.clickable
import androidx.compose.material3.Text
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.surrus.galwaybus.common.model.GalwayBusDeparture
import dev.johnoreilly.galwaybus.R
import dev.johnoreilly.galwaybus.ui.utils.quantityStringResource
@Composable
fun BusStopDeparture(departure: GalwayBusDeparture, departureSelected : (departure : GalwayBusDeparture) -> Unit) {
ProvideTextStyle(MaterialTheme.typography.bodyMedium) {
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clickable(onClick = { departureSelected(departure) })
.padding(horizontal = 16.dp, vertical = 8.dp).fillMaxWidth()) {
Text(departure.timetableId, fontWeight = FontWeight.Bold,
modifier = Modifier.width(36.dp))
Text(departure.displayName, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f).padding(start = 16.dp))
val minutesUntilDeparture = departure.durationUntilDeparture.inWholeMinutes.toInt()
val departureText = if (minutesUntilDeparture <= 0)
stringResource(R.string.bus_time_due)
else
"$minutesUntilDeparture ${quantityStringResource(R.plurals.mins, minutesUntilDeparture)}"
Text(departureText, modifier = Modifier.padding(start = 16.dp))
}
}
} | 6 | Kotlin | 45 | 545 | a985931652627deb1e12f6fe7c9f0ebbd3068544 | 2,021 | GalwayBus | MIT License |
app/src/main/java/com/example/parliamentmembers/repository/RatingRepository.kt | siddarthsingotam | 871,957,583 | false | {"Kotlin": 20677} | /**
* RatingRepository.kt
*
* Date: 20-Oct-2024
* Author: Siddarth Singotam
*
* This file defines the repository for accessing review data.
* It provides methods to insert reviews and fetch comments for a specific minister from the Room database.
*/
package com.example.parliamentmembers.repository
import com.example.parliamentmembers.data.ratingDao
import com.example.parliamentmembers.models.Review
class RatingRepository(private val ratingDao: ratingDao) {
suspend fun insertComment(comment: Review) {
ratingDao.insert(comment)
}
suspend fun getComments(ministerId: Int): List<Review> {
return ratingDao.getComments(ministerId)
}
} | 0 | Kotlin | 0 | 0 | 554fd260eb7a5a7c59d4d69fa75324bee0acee38 | 679 | ParliamentProject | MIT License |
jOOQ-demo-pro/jOOQ-demo-kotlin/src/main/kotlin/org/jooq/demo/kotlin/db/Public.kt | jOOQ | 487,859,534 | false | {"Scala": 1212012, "Kotlin": 1148952, "Java": 179736, "PLpgSQL": 7914} | /*
* This file is generated by jOOQ.
*/
package org.jooq.demo.kotlin.db
import java.math.BigDecimal
import kotlin.collections.List
import org.jooq.Catalog
import org.jooq.Configuration
import org.jooq.Domain
import org.jooq.Field
import org.jooq.Result
import org.jooq.Table
import org.jooq.Trigger
import org.jooq.demo.kotlin.db.domains.YEAR
import org.jooq.demo.kotlin.db.tables.Actor
import org.jooq.demo.kotlin.db.tables.ActorInfo
import org.jooq.demo.kotlin.db.tables.Address
import org.jooq.demo.kotlin.db.tables.Category
import org.jooq.demo.kotlin.db.tables.City
import org.jooq.demo.kotlin.db.tables.Country
import org.jooq.demo.kotlin.db.tables.Customer
import org.jooq.demo.kotlin.db.tables.CustomerList
import org.jooq.demo.kotlin.db.tables.Film
import org.jooq.demo.kotlin.db.tables.FilmActor
import org.jooq.demo.kotlin.db.tables.FilmCategory
import org.jooq.demo.kotlin.db.tables.FilmInStock
import org.jooq.demo.kotlin.db.tables.FilmList
import org.jooq.demo.kotlin.db.tables.FilmNotInStock
import org.jooq.demo.kotlin.db.tables.Inventory
import org.jooq.demo.kotlin.db.tables.Language
import org.jooq.demo.kotlin.db.tables.NicerButSlowerFilmList
import org.jooq.demo.kotlin.db.tables.Payment
import org.jooq.demo.kotlin.db.tables.PaymentP2007_01
import org.jooq.demo.kotlin.db.tables.PaymentP2007_02
import org.jooq.demo.kotlin.db.tables.PaymentP2007_03
import org.jooq.demo.kotlin.db.tables.PaymentP2007_04
import org.jooq.demo.kotlin.db.tables.PaymentP2007_05
import org.jooq.demo.kotlin.db.tables.PaymentP2007_06
import org.jooq.demo.kotlin.db.tables.Rental
import org.jooq.demo.kotlin.db.tables.RewardsReport
import org.jooq.demo.kotlin.db.tables.SalesByFilmCategory
import org.jooq.demo.kotlin.db.tables.SalesByStore
import org.jooq.demo.kotlin.db.tables.Staff
import org.jooq.demo.kotlin.db.tables.StaffList
import org.jooq.demo.kotlin.db.tables.Store
import org.jooq.demo.kotlin.db.tables.records.CustomerRecord
import org.jooq.demo.kotlin.db.tables.records.FilmInStockRecord
import org.jooq.demo.kotlin.db.tables.records.FilmNotInStockRecord
import org.jooq.demo.kotlin.db.triggers.FILM_FULLTEXT_TRIGGER
import org.jooq.demo.kotlin.db.triggers.LAST_UPDATED
import org.jooq.impl.SchemaImpl
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
open class Public : SchemaImpl("public", DefaultCatalog.DEFAULT_CATALOG) {
public companion object {
/**
* The reference instance of <code>public</code>
*/
val PUBLIC: Public = Public()
}
/**
* The table <code>public.actor</code>.
*/
val ACTOR: Actor get() = Actor.ACTOR
/**
* The table <code>public.actor_info</code>.
*/
val ACTOR_INFO: ActorInfo get() = ActorInfo.ACTOR_INFO
/**
* The table <code>public.address</code>.
*/
val ADDRESS: Address get() = Address.ADDRESS
/**
* The table <code>public.category</code>.
*/
val CATEGORY: Category get() = Category.CATEGORY
/**
* The table <code>public.city</code>.
*/
val CITY: City get() = City.CITY
/**
* The table <code>public.country</code>.
*/
val COUNTRY: Country get() = Country.COUNTRY
/**
* The table <code>public.customer</code>.
*/
val CUSTOMER: Customer get() = Customer.CUSTOMER
/**
* The table <code>public.customer_list</code>.
*/
val CUSTOMER_LIST: CustomerList get() = CustomerList.CUSTOMER_LIST
/**
* The table <code>public.film</code>.
*/
val FILM: Film get() = Film.FILM
/**
* The table <code>public.film_actor</code>.
*/
val FILM_ACTOR: FilmActor get() = FilmActor.FILM_ACTOR
/**
* The table <code>public.film_category</code>.
*/
val FILM_CATEGORY: FilmCategory get() = FilmCategory.FILM_CATEGORY
/**
* The table <code>public.film_in_stock</code>.
*/
val FILM_IN_STOCK: FilmInStock get() = FilmInStock.FILM_IN_STOCK
/**
* Call <code>public.film_in_stock</code>.
*/
fun FILM_IN_STOCK(
configuration: Configuration
, pFilmId: Long?
, pStoreId: Long?
): Result<FilmInStockRecord> = configuration.dsl().selectFrom(org.jooq.demo.kotlin.db.tables.FilmInStock.FILM_IN_STOCK.call(
pFilmId
, pStoreId
)).fetch()
/**
* Get <code>public.film_in_stock</code> as a table.
*/
fun FILM_IN_STOCK(
pFilmId: Long?
, pStoreId: Long?
): FilmInStock = org.jooq.demo.kotlin.db.tables.FilmInStock.FILM_IN_STOCK.call(
pFilmId,
pStoreId
)
/**
* Get <code>public.film_in_stock</code> as a table.
*/
fun FILM_IN_STOCK(
pFilmId: Field<Long?>
, pStoreId: Field<Long?>
): FilmInStock = org.jooq.demo.kotlin.db.tables.FilmInStock.FILM_IN_STOCK.call(
pFilmId,
pStoreId
)
/**
* The table <code>public.film_list</code>.
*/
val FILM_LIST: FilmList get() = FilmList.FILM_LIST
/**
* The table <code>public.film_not_in_stock</code>.
*/
val FILM_NOT_IN_STOCK: FilmNotInStock get() = FilmNotInStock.FILM_NOT_IN_STOCK
/**
* Call <code>public.film_not_in_stock</code>.
*/
fun FILM_NOT_IN_STOCK(
configuration: Configuration
, pFilmId: Long?
, pStoreId: Long?
): Result<FilmNotInStockRecord> = configuration.dsl().selectFrom(org.jooq.demo.kotlin.db.tables.FilmNotInStock.FILM_NOT_IN_STOCK.call(
pFilmId
, pStoreId
)).fetch()
/**
* Get <code>public.film_not_in_stock</code> as a table.
*/
fun FILM_NOT_IN_STOCK(
pFilmId: Long?
, pStoreId: Long?
): FilmNotInStock = org.jooq.demo.kotlin.db.tables.FilmNotInStock.FILM_NOT_IN_STOCK.call(
pFilmId,
pStoreId
)
/**
* Get <code>public.film_not_in_stock</code> as a table.
*/
fun FILM_NOT_IN_STOCK(
pFilmId: Field<Long?>
, pStoreId: Field<Long?>
): FilmNotInStock = org.jooq.demo.kotlin.db.tables.FilmNotInStock.FILM_NOT_IN_STOCK.call(
pFilmId,
pStoreId
)
/**
* The table <code>public.inventory</code>.
*/
val INVENTORY: Inventory get() = Inventory.INVENTORY
/**
* The table <code>public.language</code>.
*/
val LANGUAGE: Language get() = Language.LANGUAGE
/**
* The table <code>public.nicer_but_slower_film_list</code>.
*/
val NICER_BUT_SLOWER_FILM_LIST: NicerButSlowerFilmList get() = NicerButSlowerFilmList.NICER_BUT_SLOWER_FILM_LIST
/**
* The table <code>public.payment</code>.
*/
val PAYMENT: Payment get() = Payment.PAYMENT
/**
* The table <code>public.payment_p2007_01</code>.
*/
val PAYMENT_P2007_01: PaymentP2007_01 get() = PaymentP2007_01.PAYMENT_P2007_01
/**
* The table <code>public.payment_p2007_02</code>.
*/
val PAYMENT_P2007_02: PaymentP2007_02 get() = PaymentP2007_02.PAYMENT_P2007_02
/**
* The table <code>public.payment_p2007_03</code>.
*/
val PAYMENT_P2007_03: PaymentP2007_03 get() = PaymentP2007_03.PAYMENT_P2007_03
/**
* The table <code>public.payment_p2007_04</code>.
*/
val PAYMENT_P2007_04: PaymentP2007_04 get() = PaymentP2007_04.PAYMENT_P2007_04
/**
* The table <code>public.payment_p2007_05</code>.
*/
val PAYMENT_P2007_05: PaymentP2007_05 get() = PaymentP2007_05.PAYMENT_P2007_05
/**
* The table <code>public.payment_p2007_06</code>.
*/
val PAYMENT_P2007_06: PaymentP2007_06 get() = PaymentP2007_06.PAYMENT_P2007_06
/**
* The table <code>public.rental</code>.
*/
val RENTAL: Rental get() = Rental.RENTAL
/**
* The table <code>public.rewards_report</code>.
*/
val REWARDS_REPORT: RewardsReport get() = RewardsReport.REWARDS_REPORT
/**
* Call <code>public.rewards_report</code>.
*/
fun REWARDS_REPORT(
configuration: Configuration
, minMonthlyPurchases: Int?
, minDollarAmountPurchased: BigDecimal?
): Result<CustomerRecord> = configuration.dsl().selectFrom(org.jooq.demo.kotlin.db.tables.RewardsReport.REWARDS_REPORT.call(
minMonthlyPurchases
, minDollarAmountPurchased
)).fetch()
/**
* Get <code>public.rewards_report</code> as a table.
*/
fun REWARDS_REPORT(
minMonthlyPurchases: Int?
, minDollarAmountPurchased: BigDecimal?
): RewardsReport = org.jooq.demo.kotlin.db.tables.RewardsReport.REWARDS_REPORT.call(
minMonthlyPurchases,
minDollarAmountPurchased
)
/**
* Get <code>public.rewards_report</code> as a table.
*/
fun REWARDS_REPORT(
minMonthlyPurchases: Field<Int?>
, minDollarAmountPurchased: Field<BigDecimal?>
): RewardsReport = org.jooq.demo.kotlin.db.tables.RewardsReport.REWARDS_REPORT.call(
minMonthlyPurchases,
minDollarAmountPurchased
)
/**
* The table <code>public.sales_by_film_category</code>.
*/
val SALES_BY_FILM_CATEGORY: SalesByFilmCategory get() = SalesByFilmCategory.SALES_BY_FILM_CATEGORY
/**
* The table <code>public.sales_by_store</code>.
*/
val SALES_BY_STORE: SalesByStore get() = SalesByStore.SALES_BY_STORE
/**
* The table <code>public.staff</code>.
*/
val STAFF: Staff get() = Staff.STAFF
/**
* The table <code>public.staff_list</code>.
*/
val STAFF_LIST: StaffList get() = StaffList.STAFF_LIST
/**
* The table <code>public.store</code>.
*/
val STORE: Store get() = Store.STORE
override fun getCatalog(): Catalog = DefaultCatalog.DEFAULT_CATALOG
override fun getDomains(): List<Domain<*>> = listOf(
YEAR
)
override fun getTriggers(): List<Trigger> = listOf(
FILM_FULLTEXT_TRIGGER,
LAST_UPDATED
)
override fun getTables(): List<Table<*>> = listOf(
Actor.ACTOR,
ActorInfo.ACTOR_INFO,
Address.ADDRESS,
Category.CATEGORY,
City.CITY,
Country.COUNTRY,
Customer.CUSTOMER,
CustomerList.CUSTOMER_LIST,
Film.FILM,
FilmActor.FILM_ACTOR,
FilmCategory.FILM_CATEGORY,
FilmInStock.FILM_IN_STOCK,
FilmList.FILM_LIST,
FilmNotInStock.FILM_NOT_IN_STOCK,
Inventory.INVENTORY,
Language.LANGUAGE,
NicerButSlowerFilmList.NICER_BUT_SLOWER_FILM_LIST,
Payment.PAYMENT,
PaymentP2007_01.PAYMENT_P2007_01,
PaymentP2007_02.PAYMENT_P2007_02,
PaymentP2007_03.PAYMENT_P2007_03,
PaymentP2007_04.PAYMENT_P2007_04,
PaymentP2007_05.PAYMENT_P2007_05,
PaymentP2007_06.PAYMENT_P2007_06,
Rental.RENTAL,
RewardsReport.REWARDS_REPORT,
SalesByFilmCategory.SALES_BY_FILM_CATEGORY,
SalesByStore.SALES_BY_STORE,
Staff.STAFF,
StaffList.STAFF_LIST,
Store.STORE
)
}
| 5 | Scala | 8 | 16 | 750c111ee207cb54659bc33f05b80fb1d92e3a8d | 10,951 | demo | Apache License 2.0 |
app/src/main/java/com/example/eshfeenygraduationproject/eshfeeny/more/MoreFragment.kt | YoussefmSaber | 595,215,406 | false | null | package com.example.eshfeenygraduationproject.eshfeeny.more
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.eshfeenygraduationproject.R
import com.example.eshfeenygraduationproject.authentication.AuthenticationActivity
import com.example.eshfeenygraduationproject.databinding.FragmentMoreBinding
import com.example.eshfeenygraduationproject.eshfeeny.publicViewModel.UserViewModel
class MoreFragment : Fragment() {
private var binding: FragmentMoreBinding? = null
private lateinit var viewModel: UserViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentMoreBinding.inflate(inflater)
viewModel = ViewModelProvider(this)[UserViewModel::class.java]
binding?.myAccount?.setOnClickListener {
findNavController().navigate(R.id.action_moreFragment2_to_myAccountFragment)
}
binding?.Alarm?.setOnClickListener {
findNavController().navigate(R.id.action_moreFragment2_to_alarmFragment)
}
binding?.BmiBmr?.setOnClickListener {
findNavController().navigate(R.id.action_moreFragment2_to_bmiAndBmrFragment)
}
binding?.logoutButton?.setOnClickListener {
viewModel.deleteUserFromDatabase()
val intent = Intent(
activity,
AuthenticationActivity::class.java
)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
return binding?.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
} | 1 | Kotlin | 1 | 4 | 208987a79afaba8a8d06ceea557bd1647fbb536a | 2,016 | Eshfeeny | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/stepfunctions/ActivityPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.stepfunctions
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.stepfunctions.ActivityProps
@Generated
public fun buildActivityProps(initializer: @AwsCdkDsl ActivityProps.Builder.() -> Unit):
ActivityProps = ActivityProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e9a0ff020b0db2b99e176059efdb124bf822d754 | 395 | aws-cdk-kt | Apache License 2.0 |
app/src/main/java/com/example/findoraapi/Models/MyResponse.kt | NPMpayela | 865,330,819 | false | {"Kotlin": 49658} | package com.example.findoraapi.Models
data class MyResponse(
val message: String,
val success: Boolean
) | 0 | Kotlin | 0 | 0 | 1d36e12621f38e95997bdc89d48508d5796c9820 | 113 | FindoraFinalOPSC7312-Part2 | MIT License |
app/src/main/java/com/jjewuz/justnotes/Fragments/NotesFragment.kt | jjewuz | 529,199,124 | false | null | package com.jjewuz.justnotes.Fragments
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.SearchView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import com.google.android.material.bottomappbar.BottomAppBar
import com.google.android.material.card.MaterialCardView
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.jjewuz.justnotes.Activities.AddEditNoteActivity
import com.jjewuz.justnotes.Activities.ModalBottomSheet
import com.jjewuz.justnotes.Category.Category
import com.jjewuz.justnotes.Category.CategoryViewModel
import com.jjewuz.justnotes.Notes.Note
import com.jjewuz.justnotes.Notes.NoteClickInterface
import com.jjewuz.justnotes.Notes.NoteDatabase
import com.jjewuz.justnotes.Notes.NoteLongClickInterface
import com.jjewuz.justnotes.Notes.NoteRVAdapter
import com.jjewuz.justnotes.Notes.NoteViewModal
import com.jjewuz.justnotes.Notes.NoteWidget
import com.jjewuz.justnotes.R
import com.jjewuz.justnotes.Utils.OnSwipeTouchListener
class NotesFragment : Fragment(), NoteClickInterface, NoteLongClickInterface {
lateinit var viewModal: NoteViewModal
lateinit var notesRV: RecyclerView
lateinit var progressBar: ProgressBar
lateinit var addFAB: FloatingActionButton
lateinit var nothing: TextView
lateinit var viewIcon: MenuItem
private lateinit var bottomAppBar: BottomAppBar
private lateinit var labelGroup: ChipGroup
lateinit var noteRVAdapter: NoteRVAdapter
lateinit var allItems: LiveData<List<Note>>
private lateinit var searchView: SearchView
private lateinit var reminderButton: ImageView
private lateinit var sharedPref: SharedPreferences
private lateinit var categoryViewModel: CategoryViewModel
private var selectedCategoryId: Int = -1
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
sharedPref = requireActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE)
var reverse = sharedPref.getBoolean("reversed", false)
var isGrid = sharedPref.getBoolean("grid", false)
val v = inflater.inflate(R.layout.fragment_notes, container, false)
bottomAppBar = v.findViewById(R.id.bottomAppBar)
notesRV = v.findViewById(R.id.notes)
progressBar = v.findViewById(R.id.progress_bar)
addFAB = v.findViewById(R.id.idFAB)
nothing = v.findViewById(R.id.nothing)
labelGroup = v.findViewById(R.id.chipGroup)
ViewCompat.setOnApplyWindowInsetsListener(addFAB) { vi, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
val params = vi.layoutParams as ViewGroup.MarginLayoutParams
params.bottomMargin = insets.bottom + 20
params.rightMargin = insets.right + 40
vi.layoutParams = params
WindowInsetsCompat.CONSUMED
}
ViewCompat.setOnApplyWindowInsetsListener(notesRV) { vi, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
val params = vi.layoutParams as ViewGroup.MarginLayoutParams
params.leftMargin = insets.left
params.rightMargin = insets.right
vi.layoutParams = params
WindowInsetsCompat.CONSUMED
}
reminderButton = v.findViewById(R.id.reminders)
reminderButton.setOnClickListener {
replaceFragment(TodoFragment())
}
val searchPanel = v.findViewById<LinearLayout>(R.id.searchBar)
ViewCompat.setOnApplyWindowInsetsListener(searchPanel) { vi, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
val params = vi.layoutParams as ViewGroup.MarginLayoutParams
params.topMargin = insets.bottom + 90
vi.layoutParams = params
WindowInsetsCompat.CONSUMED
}
if (isGrid){
val layoutManager = GridLayoutManager(requireActivity(), 2, VERTICAL, reverse)
notesRV.layoutManager = layoutManager
}else{
val layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, reverse)
notesRV.layoutManager = layoutManager
}
val categoryDao = NoteDatabase.getDatabase(requireContext()).getCategoryDao()
noteRVAdapter = NoteRVAdapter(requireActivity(), this, this, categoryDao )
notesRV.adapter = noteRVAdapter
viewModal = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)
)[NoteViewModal::class.java]
allItems = viewModal.getNotes()
categoryViewModel = ViewModelProvider(this)[CategoryViewModel::class.java]
categoryViewModel.allCategories.observe(viewLifecycleOwner) { categories ->
setupCategoryChips(categories)
}
bottomAppBar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.sorting -> {
reverse = !reverse
with (sharedPref.edit()){
putBoolean("reversed", reverse)
apply()
}
val fragmentManager = parentFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.place_holder, NotesFragment())
fragmentTransaction.commit ()
true
}
R.id.style -> {
isGrid = !isGrid
with (sharedPref.edit()){
putBoolean("grid", isGrid)
apply()
}
val fragmentManager = parentFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.place_holder, NotesFragment())
fragmentTransaction.commit ()
true
}
else -> false
}
}
updateList(allItems)
noteRVAdapter.registerAdapterDataObserver(object : AdapterDataObserver() {
override fun onChanged() {
progressBar.visibility = View.GONE
val count = noteRVAdapter.itemCount
if (count == 0){
notesRV.visibility = View.GONE
nothing.visibility = View.VISIBLE
} else {
notesRV.visibility = View.VISIBLE
nothing.visibility = View.GONE
}
}
})
bottomAppBar.setNavigationOnClickListener {
val modalBottomSheet = ModalBottomSheet()
modalBottomSheet.show(parentFragmentManager, ModalBottomSheet.TAG)
}
addFAB.setOnClickListener {
val intent = Intent(requireActivity(), AddEditNoteActivity::class.java)
startActivity(intent)
}
context?.let {
bottomAppBar?.setOnTouchListener(object : OnSwipeTouchListener(it) {
override fun onSwipeLeft() {
replaceFragment(TodoFragment())
super.onSwipeLeft()
}
override fun onSwipeRight() {
replaceFragment(TodoFragment())
super.onSwipeRight()
}
})
}
searchView = v.findViewById(R.id.search_bar)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
allItems = query?.let { viewModal.getQuery(it) }!!
updateList(allItems)
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
allItems = if (newText == ""){
viewModal.getNotes()
} else {
newText?.let { viewModal.getQuery(it) }!!
}
updateList(allItems)
return false
}
})
return v
}
private fun setupCategoryChips(categories: List<Category>) {
labelGroup.removeAllViews()
val lText = resources.getString(R.string.label_selected)
for (category in categories) {
val chip = Chip(requireContext())
chip.text = category.name
if (category.name == "jjewuz" || category.name == "JustNotes"){
chip.chipIcon = ResourcesCompat.getDrawable(resources ,R.drawable.star, context?.theme)
}
chip.isClickable = true
chip.isCheckable = true
chip.isChecked = category.id == selectedCategoryId
chip.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
Toast.makeText(requireContext(), "${lText} ${chip.text}", Toast.LENGTH_SHORT).show()
selectedCategoryId = category.id
updateList(viewModal.getLabel(selectedCategoryId))
} else {
selectedCategoryId = -1
updateList(allItems)
}
}
labelGroup.addView(chip)
}
}
private fun openNote(note: Note){
val intent = Intent(requireActivity(), AddEditNoteActivity::class.java)
intent.putExtra("noteType", "Edit")
intent.putExtra("noteTitle", note.noteTitle)
intent.putExtra("noteDescription", note.noteDescription)
intent.putExtra("timestamp", note.timeStamp)
intent.putExtra("security", note.security)
intent.putExtra("label", note.label)
intent.putExtra("noteId", note.id)
intent.putExtra("categoryId", note.categoryId)
startActivity(intent)
}
override fun onNoteClick(note: Note, num: Int) {
openNote(note)
}
override fun onNoteLongClick(note: Note) {
val builder = MaterialAlertDialogBuilder(requireContext())
val inf = requireActivity().layoutInflater.inflate(R.layout.note_options, null)
val edit = inf.findViewById<MaterialCardView>(R.id.edit)
val widget = inf.findViewById<MaterialCardView>(R.id.tohome)
val delete = inf.findViewById<MaterialCardView>(R.id.delete)
builder.setIcon(R.drawable.note)
builder.setTitle(note.noteTitle)
builder.setView(inf)
.setPositiveButton(R.string.close) { _, _ ->
}
builder.create()
val editor = builder.show()
delete.setOnClickListener {
MaterialAlertDialogBuilder(requireActivity())
.setTitle(R.string.delWarn)
.setIcon(R.drawable.delete)
.setMessage(R.string.delete_warn)
.setNegativeButton(resources.getString(R.string.neg)) { dialog, which ->
}
.setPositiveButton(R.string.pos) { dialog, which ->
viewModal.deleteNote(note)
updateList(allItems)
editor.cancel()
Toast.makeText(requireActivity(), R.string.deleted, Toast.LENGTH_LONG).show()
}
.show()
}
edit.setOnClickListener {
openNote(note)
editor.cancel()
}
widget.setOnClickListener {
val sharedPreferences = context?.getSharedPreferences("widget_prefs", Context.MODE_PRIVATE)
sharedPreferences?.edit()?.putInt("note_id", note.id)?.apply()
pushWidget()
Toast.makeText(requireContext(), R.string.note_set_to_widget, Toast.LENGTH_SHORT).show()
editor.cancel()
}
}
private fun pushWidget(){
val intent = Intent(requireActivity(), NoteWidget::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids: IntArray = AppWidgetManager.getInstance(requireActivity()).getAppWidgetIds(ComponentName(requireActivity(), NoteWidget::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
requireActivity().sendBroadcast(intent)
}
fun replaceFragment(fragment : Fragment){
val fragmentManager = parentFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
fragmentTransaction.replace(R.id.place_holder, fragment)
fragmentTransaction.commit ()
}
private fun updateList(items: LiveData<List<Note>>){
items.observe(viewLifecycleOwner) { list ->
list?.let {
noteRVAdapter.updateList(it)
}
}
}
} | 1 | null | 7 | 135 | c74d51d484a5d95b65ee6f58d883a212546785c4 | 14,037 | JustNotes | MIT License |
src/main/kotlin/me/rerere/discordij/listener/EditingListeners.kt | re-ovo | 612,879,485 | false | null | package me.rerere.discordij.listener
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager.PostStartupActivity
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFrame
import me.rerere.discordij.service.TimeService
class AppListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
}
override fun applicationDeactivated(ideFrame: IdeFrame) {
}
}
class ProjectListener : PostStartupActivity(), ProjectManagerListener {
override fun runActivity(project: Project) {
service<TimeService>().onProjectOpened(project)
}
override fun projectClosing(project: Project) {
service<TimeService>().onProjectClosed(project)
}
}
class FileListener: FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
val service = service<TimeService>()
service.onFileOpened(source.project, file)
}
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
val service = service<TimeService>()
service.onFileClosed(source.project, file)
}
override fun selectionChanged(event: FileEditorManagerEvent) {
event.newFile?.let {
val service = service<TimeService>()
service.onFileChanged(event.manager.project, it)
}
}
} | 0 | Kotlin | 0 | 7 | e4e2254567127d8f0d4cff2dd112e7ef1964c53e | 1,783 | discord-ij | MIT License |
sharedTest/src/main/java/org/listenbrainz/sharedtest/mocks/MockListensRepository.kt | metabrainz | 550,726,972 | false | {"Kotlin": 1481175, "Ruby": 423} | package org.listenbrainz.sharedtest.mocks
import android.graphics.drawable.Drawable
import org.listenbrainz.android.model.CoverArt
import org.listenbrainz.android.model.ListenBrainzExternalServices
import org.listenbrainz.android.model.ListenSubmitBody
import org.listenbrainz.android.model.Listens
import org.listenbrainz.android.model.PostResponse
import org.listenbrainz.android.model.ResponseError
import org.listenbrainz.android.model.TokenValidation
import org.listenbrainz.android.repository.listens.ListensRepository
import org.listenbrainz.android.util.Resource
import org.listenbrainz.sharedtest.testdata.ListensRepositoryTestData.listensTestData
class MockListensRepository : ListensRepository {
override suspend fun fetchUserListens(username: String?): Resource<Listens> {
return if(username.isNullOrEmpty()){
ResponseError.DOES_NOT_EXIST.asResource()
} else{
Resource(Resource.Status.SUCCESS, listensTestData)
}
}
override suspend fun fetchCoverArt(mbid: String): Resource<CoverArt> {
TODO("Not yet implemented")
}
override suspend fun validateToken(token: String): Resource<TokenValidation> {
TODO("Not yet implemented")
}
override fun getPackageIcon(packageName: String): Drawable? {
TODO("Not yet implemented")
}
override fun getPackageLabel(packageName: String): String {
TODO("Not yet implemented")
}
override suspend fun submitListen(
token: String,
body: ListenSubmitBody
): Resource<PostResponse> {
TODO("Not yet implemented")
}
override suspend fun getLinkedServices(
token: String?,
username: String?
): Resource<ListenBrainzExternalServices> {
TODO("Not yet implemented")
}
} | 25 | Kotlin | 31 | 99 | 573ab0ec6c5b87ea963f013174159ddfcd123976 | 1,800 | listenbrainz-android | Apache License 2.0 |
app/src/androidTest/java/br/com/sommelier/ui/component/SommelierTopBarTest.kt | ronaldocoding | 665,333,427 | false | null | package br.com.sommelier.ui.component
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.test.assertContentDescriptionEquals
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import br.com.sommelier.R
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalMaterial3Api::class)
class SommelierTopBarTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun givenSommelierTopBarDefaultProperties_WhenRendered_ThenShouldAssertDefaultState() {
composeTestRule.setContent {
SommelierTopBar()
}
composeTestRule.onNodeWithTag("SommelierTopBar")
.assertIsDisplayed()
composeTestRule.onNodeWithTag("SommelierTopBarTitle")
.assertIsDisplayed()
.assertTextEquals("Title")
composeTestRule.onNodeWithTag("SommelierTopBarLeftButton")
.assertDoesNotExist()
composeTestRule.onNodeWithTag("SommelierTopBarRightButton")
.assertDoesNotExist()
}
@Test
fun givenSommelierTopBarWithLeftButton_WhenRendered_ThenShouldAssertDefaultState() {
composeTestRule.setContent {
SommelierTopBar(
leftButton = SommelierTopBarButton.Enabled(
icon = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
)
}
composeTestRule.onNodeWithTag("SommelierTopBar")
.assertIsDisplayed()
composeTestRule.onNodeWithTag("SommelierTopBarTitle")
.assertIsDisplayed()
.assertTextEquals("Title")
composeTestRule.onNodeWithTag("SommelierTopBarLeftButton")
.assertIsDisplayed()
.assertContentDescriptionEquals("Back")
.assertHasClickAction()
.performClick()
composeTestRule.onNodeWithTag("SommelierTopBarRightButton")
.assertDoesNotExist()
}
@Test
fun givenSommelierTopBarWithRightButton_WhenRendered_ThenShouldAssertDefaultState() {
composeTestRule.setContent {
SommelierTopBar(
rightButton = SommelierTopBarButton.Enabled(
icon = ImageVector.vectorResource(id = R.drawable.ic_edit),
contentDescription = "Edit"
)
)
}
composeTestRule.onNodeWithTag("SommelierTopBar")
.assertIsDisplayed()
composeTestRule.onNodeWithTag("SommelierTopBarTitle")
.assertIsDisplayed()
.assertTextEquals("Title")
composeTestRule.onNodeWithTag("SommelierTopBarRightButton")
.assertIsDisplayed()
.assertContentDescriptionEquals("Edit")
.assertHasClickAction()
.performClick()
composeTestRule.onNodeWithTag("SommelierTopBarLeftButton")
.assertDoesNotExist()
}
@Test
fun givenSommelierTopBarWithLeftAndRightButton_WhenRendered_ThenShouldAssertDefaultState() {
composeTestRule.setContent {
SommelierTopBar(
leftButton = SommelierTopBarButton.Enabled(
icon = Icons.Default.ArrowBack,
contentDescription = "Back"
),
rightButton = SommelierTopBarButton.Enabled(
icon = ImageVector.vectorResource(id = R.drawable.ic_edit),
contentDescription = "Edit"
)
)
}
composeTestRule.onNodeWithTag("SommelierTopBar")
.assertIsDisplayed()
composeTestRule.onNodeWithTag("SommelierTopBarTitle")
.assertIsDisplayed()
.assertTextEquals("Title")
composeTestRule.onNodeWithTag("SommelierTopBarLeftButton")
.assertIsDisplayed()
.assertContentDescriptionEquals("Back")
.assertHasClickAction()
.performClick()
composeTestRule.onNodeWithTag("SommelierTopBarRightButton")
.assertIsDisplayed()
.assertContentDescriptionEquals("Edit")
.assertHasClickAction()
.performClick()
}
}
| 0 | Kotlin | 0 | 1 | 5038ec2bd31c0e83247ff73788d20f8da1d509c7 | 4,586 | sommelier | MIT License |
compat/src/main/kotlin/dev/sanmer/hidden/compat/impl/AppOpsServiceCompatImpl.kt | SanmerApps | 720,492,308 | false | {"Kotlin": 278332, "Java": 21449, "AIDL": 4659} | package dev.sanmer.hidden.compat.impl
import android.app.AppOpsManagerHidden
import android.os.IBinder
import android.os.IInterface
import com.android.internal.app.IAppOpsService
import dev.sanmer.hidden.compat.proxy.AppOpsCallbackProxy
import dev.sanmer.hidden.compat.stub.IAppOpsCallback
import dev.sanmer.hidden.compat.stub.IAppOpsServiceCompat
internal class AppOpsServiceCompatImpl(
private val original: IAppOpsService
) : IAppOpsServiceCompat.Stub() {
private val callbacks = mutableMapOf<IBinder, IInterface>()
override fun checkOperation(code: Int, uid: Int, packageName: String): Int {
return original.checkOperation(code, uid, packageName)
}
override fun getPackagesForOps(ops: IntArray): List<AppOpsManagerHidden.PackageOps> {
return original.getPackagesForOps(ops) ?: emptyList()
}
override fun getOpsForPackage(
uid: Int,
packageName: String,
ops: IntArray?
): List<AppOpsManagerHidden.PackageOps> {
return original.getOpsForPackage(uid, packageName, ops) ?: emptyList()
}
override fun getUidOps(uid: Int, ops: IntArray?): List<AppOpsManagerHidden.PackageOps> {
return original.getUidOps(uid, ops) ?: emptyList()
}
override fun setUidMode(code: Int, uid: Int, mode: Int) {
original.setUidMode(code, uid, mode)
}
override fun setMode(code: Int, uid: Int, packageName: String, mode: Int) {
original.setMode(code, uid, packageName, mode)
}
override fun resetAllModes(reqUserId: Int, reqPackageName: String?) {
original.resetAllModes(reqUserId, reqPackageName)
}
override fun startWatchingMode(op: Int, packageName: String?, callback: IAppOpsCallback) {
val binder = callback.asBinder()
val proxy = AppOpsCallbackProxy(callback)
callbacks[binder] = proxy
original.startWatchingMode(op, packageName, proxy)
}
override fun stopWatchingMode(callback: IAppOpsCallback) {
val binder = callback.asBinder()
val proxy = callbacks.remove(binder)
if (proxy is com.android.internal.app.IAppOpsCallback) {
original.stopWatchingMode(proxy)
}
}
} | 1 | Kotlin | 5 | 250 | ca7d362abe66c904495f1c5a09874c4d95f570ed | 2,193 | PI | MIT License |
android/src/main/kotlin/work/ksprogram/meta_audio/MetaAudioPlugin.kt | SKKbySSK | 338,010,846 | false | {"Dart": 11849, "Swift": 8234, "Kotlin": 4216, "Ruby": 2326, "Objective-C": 691, "Java": 559} | package work.ksprogram.meta_audio
import android.media.MediaMetadataRetriever
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
/** MetaAudioPlugin */
class MetaAudioPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "meta_audio")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
val path = call.arguments as? String
if (path == null) {
result.error("ERR_PATH", null, null)
return
}
when (call.method) {
"metadata" -> {
getMetadata(path, result)
}
"artwork" -> {
getArtwork(path, result)
}
"artwork_exists" -> {
checkArtworkExists(path, result)
}
else -> result.notImplemented()
}
}
private fun getMetadata(path: String, result: Result) {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
val durationMsStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
val title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)
val album = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)
val artist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
val genre = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE)
val composer = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER)
val trackNumberStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)
val trackCountStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS)
val yearStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
retriever.close()
}
retriever.release()
var duration = durationMsStr?.toDoubleOrNull()
if (duration != null) {
duration *= 1e3
}
val trackNumber = trackNumberStr?.toIntOrNull()
val trackCount = trackCountStr?.toIntOrNull()
val year = yearStr?.toIntOrNull()
result.success(hashMapOf(
"duration" to duration?.toInt(),
"title" to title,
"album" to album,
"artist" to artist,
"genre" to genre,
"composer" to composer,
"trackNumber" to trackNumber,
"trackCount" to trackCount,
"year" to year
))
}
private fun checkArtworkExists(path: String, result: Result) {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
val picture = retriever.embeddedPicture
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
retriever.close()
}
retriever.release()
result.success(picture != null)
}
private fun getArtwork(path: String, result: Result) {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
val picture = retriever.embeddedPicture
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
retriever.close()
}
retriever.release()
result.success(picture)
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
| 1 | Dart | 1 | 1 | 13f607a8133829ebce072f2c55d8cf1225bf293b | 4,078 | meta_audio | MIT License |
core/design-system/src/main/java/little/goose/design/system/component/dialog/DialogState.kt | MReP1 | 525,822,587 | false | {"Kotlin": 667872} | package little.goose.design.system.component.dialog
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
@Composable
fun rememberDialogState() = rememberSaveable(
saver = Saver(
save = { it.isShow },
restore = { DialogState(it) }
)
) { DialogState(false) }
@Stable
class DialogState(
_isShow: Boolean
) {
var isShow by mutableStateOf(_isShow)
private set
fun show() {
isShow = true
}
fun dismiss() {
isShow = false
}
} | 1 | Kotlin | 27 | 99 | a6ee70d1b3dcf4b9b24ca00bbed725e8374e105a | 583 | LittleGooseOffice | MIT License |
kotlin-electron/src/jsMain/generated/electron/ProcessMemoryInfo.kt | JetBrains | 93,250,841 | false | {"Kotlin": 11411371, "JavaScript": 154302} | package electron
typealias ProcessMemoryInfo = electron.core.ProcessMemoryInfo
| 28 | Kotlin | 173 | 1,250 | 9e9dda28cf74f68b42a712c27f2e97d63af17628 | 81 | kotlin-wrappers | Apache License 2.0 |
entity-service/src/test/kotlin/com/egm/stellio/entity/model/EntityTest.kt | stellio-hub | 257,818,724 | false | null | package com.egm.stellio.entity.model
import com.egm.stellio.shared.util.JsonLdUtils
import com.egm.stellio.shared.util.JsonLdUtils.JSONLD_ID
import com.egm.stellio.shared.util.JsonLdUtils.JSONLD_TYPE
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_CREATED_AT_PROPERTY
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_LOCATION_PROPERTY
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_MODIFIED_AT_PROPERTY
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_OBSERVATION_SPACE_PROPERTY
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_OPERATION_SPACE_PROPERTY
import com.egm.stellio.shared.util.toUri
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.time.Instant
import java.time.ZoneOffset
class EntityTest {
private val entity = Entity(
id = "urn:ngsi-ld:beehive:01".toUri(),
types = listOf("Beehive"),
createdAt = Instant.now().atZone(ZoneOffset.UTC),
modifiedAt = Instant.now().atZone(ZoneOffset.UTC)
)
@Test
fun `it should serialize entity without createdAt and modifiedAt if not specified`() {
val serializedEntity = entity.serializeCoreProperties(false)
Assertions.assertFalse(serializedEntity.contains(NGSILD_CREATED_AT_PROPERTY))
Assertions.assertFalse(serializedEntity.contains(NGSILD_MODIFIED_AT_PROPERTY))
Assertions.assertFalse(serializedEntity.contains(NGSILD_LOCATION_PROPERTY))
Assertions.assertEquals(setOf(JSONLD_ID, JSONLD_TYPE), serializedEntity.keys)
}
@Test
fun `it should serialize entity with createdAt and modifiedAt if specified`() {
val serializedEntity = entity.serializeCoreProperties(true)
Assertions.assertTrue(serializedEntity.contains(NGSILD_CREATED_AT_PROPERTY))
Assertions.assertTrue(serializedEntity.contains(NGSILD_MODIFIED_AT_PROPERTY))
Assertions.assertFalse(serializedEntity.contains(NGSILD_LOCATION_PROPERTY))
}
@Test
fun `it should serialize entity with location if specified`() {
val entityWithLocation = entity.copy(location = "POINT (24.30623 60.07966)")
val serializedEntity = entityWithLocation.serializeCoreProperties(true)
Assertions.assertTrue(serializedEntity.contains(NGSILD_LOCATION_PROPERTY))
Assertions.assertEquals(
mapOf(JSONLD_TYPE to "GeoProperty", JsonLdUtils.NGSILD_GEOPROPERTY_VALUE to "POINT (24.30623 60.07966)"),
serializedEntity[NGSILD_LOCATION_PROPERTY]
)
Assertions.assertFalse(serializedEntity.contains(NGSILD_OPERATION_SPACE_PROPERTY))
Assertions.assertFalse(serializedEntity.contains(NGSILD_OBSERVATION_SPACE_PROPERTY))
}
@Test
fun `it should serialize entity with all geo properties if specified`() {
val entityWithLocation = entity.copy(
location = "POINT (24.30623 60.07966)",
operationSpace = "POINT (25.30623 62.07966)",
observationSpace = "POINT (26.30623 58.07966)"
)
val serializedEntity = entityWithLocation.serializeCoreProperties(true)
Assertions.assertTrue(serializedEntity.contains(NGSILD_LOCATION_PROPERTY))
Assertions.assertEquals(
mapOf(JSONLD_TYPE to "GeoProperty", JsonLdUtils.NGSILD_GEOPROPERTY_VALUE to "POINT (24.30623 60.07966)"),
serializedEntity[NGSILD_LOCATION_PROPERTY]
)
Assertions.assertTrue(serializedEntity.contains(NGSILD_OPERATION_SPACE_PROPERTY))
Assertions.assertEquals(
mapOf(JSONLD_TYPE to "GeoProperty", JsonLdUtils.NGSILD_GEOPROPERTY_VALUE to "POINT (25.30623 62.07966)"),
serializedEntity[NGSILD_OPERATION_SPACE_PROPERTY]
)
Assertions.assertTrue(serializedEntity.contains(NGSILD_OBSERVATION_SPACE_PROPERTY))
Assertions.assertEquals(
mapOf(JSONLD_TYPE to "GeoProperty", JsonLdUtils.NGSILD_GEOPROPERTY_VALUE to "POINT (26.30623 58.07966)"),
serializedEntity[NGSILD_OBSERVATION_SPACE_PROPERTY]
)
}
}
| 50 | Kotlin | 8 | 16 | 38bc7189a5fec1b14a46e86fc35e1ee7d842d8c0 | 4,016 | stellio-context-broker | Apache License 2.0 |
android-keystore-compat/src/main/kotlin/cz/koto/misak/keystorecompat/KeystoreCompatInitProvider.kt | ziacto | 93,989,614 | true | {"Kotlin": 113773, "Java": 7849} | package cz.koto.misak.keystorecompat
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.net.Uri
/**
* Content provider able to initialize library with the context of hosted application without needs to initialize library manually.
* The only pre-condition is, that hosted application has applicationId defined.
* When missing this pre-condition IllegalStateException is thrown.
*/
class KeystoreCompatInitProvider : ContentProvider() {
override fun insert(uri: Uri?, values: ContentValues?): Uri? {
return null
}
override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
return null
}
override fun onCreate(): Boolean {
val context = context
KeystoreCompat.init(context)
return true
}
override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
return 0
}
override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
return 0
}
override fun getType(uri: Uri?): String? {
return null
}
override fun attachInfo(context: Context, providerInfo: ProviderInfo?) {
if (providerInfo == null) {
throw NullPointerException("KeystoreCompatInitProvider ProviderInfo cannot be null.")
}
// So if the authorities equal the library internal ones, the developer forgot to set his applicationId
if ("cz.koto.misak.keystorecompat.KeystoreCompatInitProvider" == providerInfo.authority) {
throw IllegalStateException("Incorrect provider authority in manifest. Most likely due to a " + "missing applicationId variable in application\'s build.gradle.")
}
super.attachInfo(context, providerInfo)
}
}
| 0 | Kotlin | 0 | 0 | 3549cbe330f5b9fbac13dca68c578228f825c6bb | 2,003 | security-showcase-android | Apache License 2.0 |
opala-core/src/main/kotlin/com/tiarebalbi/opala/common/FileUtils.kt | tiarebalbi | 298,968,362 | false | null | package com.tiarebalbi.opala.common
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
object FileUtils {
fun notExists(path: String): Boolean {
return !exists(path)
}
fun exists(path: String): Boolean {
return Files.exists(Path.of(path))
}
fun createDirectories(path: String) {
Files.createDirectories(Path.of(path))
}
fun createFile(path: String, content: String): File {
Files.createFile(Path.of(path))
val file = File(path)
val stream = FileOutputStream(file)
stream.write(content.toByteArray())
stream.close()
return file
}
fun deleteIfExists(path: String) {
Files.deleteIfExists(Path.of(path))
}
fun recursiveDelete(path: String) {
Files.walk(Path.of(path))
.sorted(Comparator.reverseOrder())
.forEach { Files.deleteIfExists(it) }
}
}
| 0 | Kotlin | 0 | 0 | ae62e94f0b2cb494f327c686bc6b6c857fae71c9 | 966 | opala | MIT License |
src_old/main/kotlin/com/pumpkin/core/imgui/ImGuiProfiler.kt | FauxKiwi | 315,724,386 | false | null | package com.pumpkin.core.imgui
import com.pumpkin.core.Timestep
import com.pumpkin.core.renderer.Renderer2D
import com.pumpkin.core.window.Window
import glm_.vec2.Vec2
import imgui.ImGui
import imgui.WindowFlag
import imgui.max
object ImGuiProfiler {
var showProfiler = false
private var values0 = FloatArray(100)
private var valuesOffset = 0
fun onAttach() {
showProfiler = true
}
fun onDetach() {
showProfiler = false
}
fun onUpdate(ts: Timestep) {
values0[valuesOffset] = if (ImGui.io.framerate == 0f) values0[max(valuesOffset-1, 0)] else 1000 / ImGui.io.framerate
valuesOffset++
if (valuesOffset >= 100) valuesOffset = 0
}
fun onImGuiRender() = with(ImGui) {
ImGui.begin("Profiler", ::showProfiler, WindowFlag.NoCollapse.i)
ImGui.text("Your Framerate is: ${ImGui.io.framerate}")
ImGui.text("Update time: ${1000 / ImGui.io.framerate}")
val overlay = "min ${String.format("%.3f", values0.min())} max ${String.format("%.3f", values0.max())}"
ImGui.plotLines(
"Frametime",
values0,
valuesOffset/*, scaleMin = 0f, scaleMax = 60f*/,
overlayText = overlay,
graphSize = Vec2(0f, 80f)
)
ImGui.checkbox("VSync", Window.getWindow()::vSync)
ImGui.text("Drawing ${Renderer2D.quadCount} quads (${Renderer2D.quadCount * 4} vertices, ${Renderer2D.quadCount * 6} indices)")
ImGui.text("Draw calls: ${Renderer2D.drawCalls}")
ImGui.end()
}
} | 0 | Kotlin | 0 | 2 | b384f2a430c0f714237e07621a01f094d9f5ee75 | 1,559 | Pumpkin-Engine | Apache License 2.0 |
task/src/main/kotlin/com/oneliang/ktx/frame/task/TaskManager.kt | oneliang | 262,052,605 | false | {"Kotlin": 1447233, "Java": 255657, "C": 27979, "HTML": 3956} | package com.oneliang.ktx.frame.task
import com.oneliang.ktx.frame.coroutine.Coroutine
import com.oneliang.ktx.util.logging.LoggerManager
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
class TaskManager(maxThreads: Int=1) {
companion object {
private val logger = LoggerManager.getLogger(TaskManager::class)
}
private val executorService = Executors.newFixedThreadPool(maxThreads)
private val coroutine = Coroutine(executorService.asCoroutineDispatcher())
private val taskJobMap = ConcurrentHashMap<Int, Pair<Task, Job>>()
private val cancelledTaskMap = ConcurrentHashMap<Int, Task>()
/**
* task definition
*/
abstract class Task {
@Volatile
internal var running = false
internal suspend fun internalRun() {
this.running = true
run()
this.running = false
}
/**
* run
*/
abstract suspend fun run()
/**
* cancel callback
*/
open suspend fun cancelCallback() {
}
}
/**
* launch
*/
fun startTask(
task: Task,
priority: Boolean = false
): Job {
if (priority) {
this.cancelAllTask()
}
val hashCode = task.hashCode()
val job = this.coroutine.launch {
try {
task.internalRun()
} catch (e: Throwable) {
try {
task.cancelCallback()
} catch (e: Throwable) {
logger.error("cancelCallback exception, task hashCode:%s", e, hashCode)
} finally {
this.cancelledTaskMap[hashCode] = task
}
logger.error("cancelling coroutine job, task hashCode:%s", e, hashCode)
} finally {
this.taskJobMap.remove(task.hashCode())
if (priority) {
this.restoreAllCancelledTask()
}
}
}
this.taskJobMap[hashCode] = task to job
return job
}
/**
* cancel all task
*/
fun cancelAllTask() {
logger.debug("cancel all task, task job map size:%s".format(this.taskJobMap.size))
this.taskJobMap.forEach { (key, taskJob) ->
val (task, job) = taskJob
if (!task.running) {
this.cancelledTaskMap[task.hashCode()] = task
}
job.cancel()
}
logger.debug("cancel all task, cancelled task map size:%s".format(this.cancelledTaskMap.size))
}
/**
* restore all cancelled task
*/
fun restoreAllCancelledTask() {
logger.debug("restore all cancelled task, cancelled task map size:%s".format(this.cancelledTaskMap.size))
this.cancelledTaskMap.forEach { (_, task) ->
this.startTask(task)
}
}
} | 0 | Kotlin | 1 | 0 | 5bdc8c38ebaf33452cfeb4ab803acc51a0a87663 | 3,008 | frame-kotlin | Apache License 2.0 |
opendc-simulator/opendc-simulator-compute/src/main/kotlin/org/opendc/simulator/compute/workload/SimWorkloadLifecycle.kt | atlarge-research | 79,902,234 | false | null | /*
* Copyright (c) 2021 AtLarge Research
*
* 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 org.opendc.simulator.compute.workload
import org.opendc.simulator.compute.SimMachineContext
import org.opendc.simulator.flow.FlowConnection
import org.opendc.simulator.flow.FlowSource
/**
* A helper class to manage the lifecycle of a [SimWorkload]
*/
public class SimWorkloadLifecycle(private val ctx: SimMachineContext) {
/**
* The resource consumers which represent the lifecycle of the workload.
*/
private val waiting = HashSet<Wrapper>()
/**
* Wait for the specified [source] to complete before ending the lifecycle of the workload.
*/
public fun waitFor(source: FlowSource): FlowSource {
val wrapper = Wrapper(source)
waiting.add(wrapper)
return wrapper
}
/**
* Complete the specified [Wrapper].
*/
private fun complete(wrapper: Wrapper) {
if (waiting.remove(wrapper) && waiting.isEmpty()) {
ctx.close()
}
}
/**
* A [FlowSource] that wraps [delegate] and informs [SimWorkloadLifecycle] that is has completed.
*/
private inner class Wrapper(private val delegate: FlowSource) : FlowSource {
override fun onStart(conn: FlowConnection, now: Long) {
delegate.onStart(conn, now)
}
override fun onPull(conn: FlowConnection, now: Long, delta: Long): Long {
return delegate.onPull(conn, now, delta)
}
override fun onConverge(conn: FlowConnection, now: Long, delta: Long) {
delegate.onConverge(conn, now, delta)
}
override fun onStop(conn: FlowConnection, now: Long, delta: Long) {
try {
delegate.onStop(conn, now, delta)
} finally {
complete(this)
}
}
override fun toString(): String = "SimWorkloadLifecycle.Wrapper[delegate=$delegate]"
}
}
| 9 | Kotlin | 14 | 41 | 578394adfb5f1f835b7d8e24f68094968706dfaa | 2,991 | opendc | MIT License |
app/src/main/java/com/tans/tweather2/repository/ImagesRepository.kt | Tans5 | 150,855,032 | false | null | package com.tans.tweather2.repository
import com.tans.tweather2.api.service.BingService
import com.tans.tweather2.db.ImagesDao
import com.tans.tweather2.entites.Images
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxkotlin.zipWith
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
class ImagesRepository @Inject constructor(private val bingService: BingService,
private val imagesDao: ImagesDao) {
fun getImages(): Observable<Images> = getLatestImagesLocal()
.switchIfEmpty(getImagesRemote())
.flatMapObservable { images ->
dateLongIsToday(images.dateLong)
.flatMapObservable { isToday ->
if (isToday) {
Observable.just(images)
} else {
Single.concat(listOf(Single.just<Images>(images),
getImagesRemote())).toObservable()
}
}
}
private fun getImagesRemote(): Single<Images> = bingService.getImages()
.zipWith(formatImageDateString(Date()))
.map { (images, dateString) ->
images.copy(dateLong = dateString.toLong())
}
.flatMap { images ->
insertImages(images).toSingleDefault(images)
}
private fun getLatestImagesLocal(): Maybe<Images> = imagesDao.queryLatestImages()
private fun insertImages(images: Images): Completable = imagesDao.insert(images = images)
/**
* eg: 20190418
*/
private fun formatImageDateString(date: Date): Single<String> = Single.fromCallable {
SimpleDateFormat("yyyyMMdd").format(date)
}
private fun dateLongIsToday(dateLong: Long): Single<Boolean> = formatImageDateString(Date())
.map { dateString ->
dateLong == dateString.toLong()
}
} | 0 | Kotlin | 0 | 0 | 1d996a4b2ab4c160759f936459d5163e265e8257 | 2,100 | tWeather2 | Apache License 2.0 |
libs/pandautils/src/test/java/com/instructure/pandautils/features/calendar/filter/CalendarFilterViewModelTest.kt | instructure | 179,290,947 | false | null | /*
* Copyright (C) 2024 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.instructure.pandautils.features.calendar.filter
import android.content.res.Resources
import com.instructure.canvasapi2.models.CanvasContext
import com.instructure.canvasapi2.models.Course
import com.instructure.canvasapi2.models.Group
import com.instructure.canvasapi2.models.User
import com.instructure.canvasapi2.utils.ApiPrefs
import com.instructure.canvasapi2.utils.ContextKeeper
import com.instructure.canvasapi2.utils.DataResult
import com.instructure.pandautils.R
import com.instructure.pandautils.features.calendar.CalendarRepository
import com.instructure.pandautils.room.calendar.daos.CalendarFilterDao
import com.instructure.pandautils.room.calendar.entities.CalendarFilterEntity
import com.instructure.pandautils.utils.ThemePrefs
import com.instructure.pandautils.utils.backgroundColor
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class CalendarFilterViewModelTest {
private val calendarRepository: CalendarRepository = mockk(relaxed = true)
private val calendarFilterDao: CalendarFilterDao = mockk(relaxed = true)
private val apiPrefs: ApiPrefs = mockk(relaxed = true)
private val resources: Resources = mockk(relaxed = true)
private lateinit var viewModel: CalendarFilterViewModel
private val testDispatcher = UnconfinedTestDispatcher(TestCoroutineScheduler())
@Before
fun setUp() {
ContextKeeper.appContext = mockk(relaxed = true)
coEvery { calendarRepository.getCalendarFilterLimit() } returns 10
every { resources.getString(R.string.calendarFilterExplanationLimited, any()) } returns "Limit 10"
coEvery { resources.getString(R.string.calendarFilterLimitSnackbar, any()) } returns "Filter limit reached"
Dispatchers.setMain(testDispatcher)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `Create error UI state when there is an error fetching the filters`() {
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Fail()
createViewModel()
assertTrue(viewModel.uiState.value.error)
}
@Test
fun `Initialize filters from all the possible filters from repository and create UI state with the correct checked status`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10",
)
assertEquals(expectedUiState, uiState)
}
@Test
fun `Retry loads filters again`() {
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Fail()
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
assertTrue(viewModel.uiState.value.error)
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
viewModel.handleAction(CalendarFilterAction.Retry)
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10")
assertEquals(expectedUiState, uiState)
}
@Test
fun `Toggle filter updates filters and saves them into the database`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(expectedUiState, uiState)
viewModel.handleAction(CalendarFilterAction.ToggleFilter("course_1"))
viewModel.handleAction(CalendarFilterAction.ToggleFilter("user_5"))
val newUiState = viewModel.uiState.value
val newExpectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", true, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", false, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(newExpectedUiState, newUiState)
coVerify { calendarFilterDao.insertOrUpdate(any()) }
}
@Test
fun `Show and dismiss snackbar when filter limit is reached`() {
coEvery { calendarRepository.getCalendarFilterLimit() } returns 2
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(expectedUiState, uiState)
viewModel.handleAction(CalendarFilterAction.ToggleFilter("user_5"))
val newUiState = viewModel.uiState.value
val newExpectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10", snackbarMessage = "Filter limit reached"
)
assertEquals(newExpectedUiState, newUiState)
viewModel.handleAction(CalendarFilterAction.SnackbarDismissed)
assertEquals(newExpectedUiState.copy(snackbarMessage = null), viewModel.uiState.value)
}
@Test
fun `Send filter closed event without change when filters were not changed`() = runTest {
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(Course(1, name = "Course")),
CanvasContext.Type.GROUP to listOf(Group(3, name = "Group"))
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
viewModel.filtersClosed()
val events = mutableListOf<CalendarFilterViewModelAction>()
backgroundScope.launch(testDispatcher) {
viewModel.events.toList(events)
}
val expectedEvent = CalendarFilterViewModelAction.FiltersClosed(false)
assertEquals(expectedEvent, events.last())
}
@Test
fun `Send filter closed event with change when filters were changed`() = runTest {
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(Course(1, name = "Course")),
CanvasContext.Type.GROUP to listOf(Group(3, name = "Group"))
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
viewModel.handleAction(CalendarFilterAction.ToggleFilter("user_5"))
viewModel.filtersClosed()
val events = mutableListOf<CalendarFilterViewModelAction>()
backgroundScope.launch(testDispatcher) {
viewModel.events.toList(events)
}
val expectedEvent = CalendarFilterViewModelAction.FiltersClosed(true)
assertEquals(expectedEvent, events.last())
}
@Test
fun `Select all selects all filters and saves them into the database`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", false, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(expectedUiState, uiState)
viewModel.handleAction(CalendarFilterAction.SelectAll)
val newUiState = viewModel.uiState.value
val newExpectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", true, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(newExpectedUiState, newUiState)
coVerify { calendarFilterDao.insertOrUpdate(any()) }
}
@Test
fun `Select all selects only filters up to the limit if filters are limited`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCalendarFilterLimit() } returns 2
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf()
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", false, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", false, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(expectedUiState, uiState)
viewModel.handleAction(CalendarFilterAction.SelectAll)
val newUiState = viewModel.uiState.value
val newExpectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", true, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", false, group.backgroundColor)),
explanationMessage = "Limit 10", snackbarMessage = "Filter limit reached"
)
assertEquals(newExpectedUiState, newUiState)
coVerify { calendarFilterDao.insertOrUpdate(any()) }
}
@Test
fun `Deselect all deselects all filters and saves them into the database`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(expectedUiState, uiState)
viewModel.handleAction(CalendarFilterAction.DeselectAll)
val newUiState = viewModel.uiState.value
val newExpectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", false, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", false, group.backgroundColor)),
explanationMessage = "Limit 10"
)
assertEquals(newExpectedUiState, newUiState)
coVerify { calendarFilterDao.insertOrUpdate(any()) }
}
@Test
fun `Do not show explanation and make select all available when filter limit is -1`() {
val course = Course(1, name = "Course")
val group = Group(3, name = "Group")
coEvery { calendarRepository.getCalendarFilterLimit() } returns -1
coEvery { calendarRepository.getCanvasContexts() } returns DataResult.Success(
mapOf(
CanvasContext.Type.USER to listOf(User(5, name = "User")),
CanvasContext.Type.COURSE to listOf(course),
CanvasContext.Type.GROUP to listOf(group)
)
)
coEvery { calendarFilterDao.findByUserIdAndDomain(any(), any()) } returns CalendarFilterEntity(
userId = "1",
userDomain = "domain.com",
filters = setOf("course_1", "group_3")
)
createViewModel()
val uiState = viewModel.uiState.value
val expectedUiState = CalendarFilterScreenUiState(
listOf(CalendarFilterItemUiState("user_5", "User", false, ThemePrefs.brandColor)),
listOf(CalendarFilterItemUiState("course_1", "Course", true, course.backgroundColor)),
listOf(CalendarFilterItemUiState("group_3", "Group", true, group.backgroundColor)),
selectAllAvailable = true,
explanationMessage = null
)
assertEquals(expectedUiState, uiState)
}
private fun createViewModel() {
viewModel = CalendarFilterViewModel(calendarRepository, calendarFilterDao, apiPrefs, resources)
}
} | 7 | null | 98 | 127 | ca6e2aeaeedb851003af5497e64c22e02dbf0db8 | 19,744 | canvas-android | Apache License 2.0 |
src/main/kotlin/org/sendoh/route/CarRentalRoute.kt | HungUnicorn | 246,826,509 | false | null | package org.sendoh.route
import io.undertow.server.HttpServerExchange
import org.sendoh.web.json.JsonSerde.JsonSerdeException
import org.sendoh.web.ApiHandler
import org.sendoh.exception.CarRentalException
import org.sendoh.exchange.CarRentalExchange
import org.sendoh.service.CarRentalService
/**
* Define how to handle car rental request and api response
*
* */
class CarRentalRoute {
private var apiHandler: ApiHandler
private var carRentalExchange: CarRentalExchange
private var carRentalService: CarRentalService
constructor(apiHandler: ApiHandler, carRentalExchange: CarRentalExchange,
carRentalService: CarRentalService) {
this.apiHandler = apiHandler
this.carRentalExchange = carRentalExchange
this.carRentalService = carRentalService
}
fun post(exchange: HttpServerExchange) {
try {
val request = carRentalExchange.post(exchange)
val carRental = carRentalService.start(request)
apiHandler.ok(exchange, carRental)
} catch (e: JsonSerdeException) {
apiHandler.badRequest(exchange, "Invalid rental with error: $e")
} catch (e: CarRentalException) {
apiHandler.badRequest(exchange, "Invalid rental with error: $e")
}
}
fun delete(exchange: HttpServerExchange) {
try {
val request = carRentalExchange.delete(exchange)
val carRental = carRentalService.stop(request)
apiHandler.ok(exchange, carRental)
} catch (e: JsonSerdeException) {
apiHandler.badRequest(exchange, "Invalid rental with error: $e")
} catch (e: CarRentalException) {
apiHandler.badRequest(exchange, "Invalid rental with error: $e")
}
}
fun get(exchange: HttpServerExchange) {
val carLicenseNo = carRentalExchange.carLicenseNo(exchange)
val rental = carRentalService.getRental(carLicenseNo)
if (rental == null) {
apiHandler.notFound(exchange, "Rent car $carLicenseNo not found")
return
}
apiHandler.ok(exchange, rental)
}
fun listWithDistance(exchange: HttpServerExchange) {
val locationWithDistance = carRentalExchange.locationWithDistance(exchange)
val cars = carRentalService.listUnRentedNearbyCars(locationWithDistance.location,
locationWithDistance.distanceInMeter.toDouble())
if (cars.isEmpty()) {
apiHandler.notFound(exchange, "No car to rent within ${locationWithDistance.distanceInMeter}m")
return
}
apiHandler.ok(exchange, cars)
}
}
| 0 | Kotlin | 0 | 0 | 62214734f52157f2fa1828d055f5d4558da0ed11 | 2,645 | car-booking | MIT License |
agent/src/main/kotlin/org/nessus/didcomm/service/WalletService.kt | tdiesler | 578,916,709 | false | null | /*-
* #%L
* Nessus DIDComm :: Services :: Agent
* %%
* Copyright (C) 2022 Nessus
* %%
* 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.
* #L%
*/
package org.nessus.didcomm.service
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import id.walt.crypto.KeyAlgorithm
import id.walt.servicematrix.BaseService
import id.walt.servicematrix.ServiceProvider
import mu.KotlinLogging
import org.hyperledger.aries.api.multitenancy.CreateWalletTokenRequest
import org.nessus.didcomm.agent.AgentConfiguration
import org.nessus.didcomm.agent.AriesAgent
import org.nessus.didcomm.did.Did
import org.nessus.didcomm.did.DidMethod
import org.nessus.didcomm.model.AgentType
import org.nessus.didcomm.model.StorageType
import org.nessus.didcomm.model.Wallet
import org.nessus.didcomm.wallet.*
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.io.path.isReadable
class WalletService : BaseService() {
private val log = KotlinLogging.logger {}
override val implementation get() = serviceImplementation<WalletService>()
companion object: ServiceProvider {
private val implementation = WalletService()
override fun getService() = implementation
}
init {
initAcaPyWallets()
}
val modelService get() = ModelService.getService()
val wallets get() = modelService.wallets
fun createWallet(config: WalletConfig): Wallet {
val maybeWallet = findByName(config.name)
val agentType = config.agentType ?: AgentType.NESSUS
val storageType = config.storageType ?: StorageType.IN_MEMORY
if (config.mayExist && maybeWallet != null) {
check(maybeWallet.agentType == agentType) {"Wallet ${config.name} exists, with other agent: ${maybeWallet.agentType}"}
check(maybeWallet.storageType == storageType) {"Wallet ${config.name} exists, with other type: ${maybeWallet.storageType}"}
return maybeWallet
}
val wallet = when(config.agentType!!) {
AgentType.ACAPY -> AcapyWalletPlugin().createWallet(config)
AgentType.NESSUS -> NessusWalletPlugin().createWallet(config)
}
addWallet(wallet)
return wallet
}
fun addWallet(wallet: Wallet) {
modelService.addWallet(wallet)
}
fun removeWallet(id: String): Wallet? {
val wallet = modelService.getWallet(id)
if (wallet != null) {
wallet.walletPlugin.removeWallet(wallet)
modelService.removeWallet(id)
}
return wallet
}
fun findByName(name: String): Wallet? {
return modelService.findWallet { it.name.lowercase() == name.lowercase() }
}
/**
* Create a Did for the given wallet
*
* Nessus Dids are created locally and have their associated keys in the {@see KeyStoreService}
*/
fun createDid(wallet: Wallet, method: DidMethod?, algorithm: KeyAlgorithm?, seed: String?): Did {
val did = wallet.walletPlugin.createDid(wallet, method, algorithm, seed)
wallet.addDid(did)
return did
}
/**
* Get the (optional) public Did for the given wallet
*/
fun getPublicDid(wallet: Wallet): Did? {
return wallet.walletPlugin.publicDid(wallet)
}
fun removeConnections(wallet: Wallet) {
wallet.walletPlugin.removeConnections(wallet)
}
// Private ---------------------------------------------------------------------------------------------------------
@Suppress("UNCHECKED_CAST")
private fun initAcaPyWallets() {
val agentConfig = AgentConfiguration.defaultConfiguration
val adminClient = AriesAgent.adminClient(agentConfig)
// Initialize wallets from Siera config
readSieraConfig()?.filterKeys { k -> k != "default" }?.forEach {
val walletName = it.key
val values = it.value as Map<String, String>
val agent = values["agent"] ?: "aca-py"
check(agent == "aca-py") { "Unsupported agent: $agent" }
val endpointUrl = values["endpoint"] as String
val authToken = values["auth_token"]
val walletRecord = adminClient.multitenancyWallets(walletName).get().firstOrNull()
walletRecord?.run {
val walletId = walletRecord.walletId
val wallet = AcapyWallet(
walletId,
walletName,
AgentType.ACAPY,
StorageType.INDY,
endpointUrl,
authToken=authToken
)
addWallet(wallet)
}
}
// Initialize wallets from AcaPy
adminClient.multitenancyWallets(null).get()
.filter { modelService.getWallet(it.walletId) == null }
.forEach {
val walletId = it.walletId
val alias = it.settings.walletName
val storageType = StorageType.valueOf(it.settings.walletType.name)
val tokReq = CreateWalletTokenRequest.builder().build()
val tokRes = adminClient.multitenancyWalletToken(walletId, tokReq).get()
val wallet = AcapyWallet(
walletId,
alias,
AgentType.ACAPY,
storageType,
agentConfig.userUrl,
authToken=tokRes.token
)
addWallet(wallet)
}
log.info { "Done Wallet Init ".padEnd(180, '=') }
}
@Suppress("UNCHECKED_CAST")
private fun readSieraConfig(): Map<String, Any>? {
val mapper = ObjectMapper(YAMLFactory()).registerKotlinModule()
val homeDir = System.getenv("HOME")
val configPath = Paths.get("$homeDir/.config/siera/config.yaml")
return if (configPath.isReadable()) {
Files.newBufferedReader(configPath).use {
val config = mapper.readValue(it, Map::class.java)
return config["configurations"] as Map<String, Any>
}
} else null
}
}
interface WalletPlugin {
fun createWallet(config: WalletConfig): Wallet
fun removeWallet(wallet: Wallet)
fun createDid(
wallet: Wallet,
method: DidMethod?,
algorithm: KeyAlgorithm? = null,
seed: String? = null): Did
fun publicDid(wallet: Wallet): Did?
fun removeConnections(wallet: Wallet)
}
| 11 | Kotlin | 0 | 3 | 80841110386491e3ff206330f45e16c28e3637c5 | 7,059 | nessus-didcomm | Apache License 2.0 |
app/src/main/java/com/example/weatherapptest/presentation/weatherdetails/composables/WeatherDetails.kt | cresidian | 671,887,728 | false | null | package com.example.weatherapptest.presentation.weatherdetails.composables
import androidx.compose.foundation.layout.*
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.weatherapptest.domain.model.responses.WeatherDetailsResponse
import com.example.weatherapptest.util.convertMillisecondsToDate
@Composable
fun WeatherDetail(weatherDetailsResponse: WeatherDetailsResponse) {
Card(
elevation = 8.dp,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
backgroundColor = Color.White
) {
val location = weatherDetailsResponse.name
val temperatureInKelvin = weatherDetailsResponse.temperatureDetails.temp
val temperatureInCelsius = (temperatureInKelvin - 273.15).toInt()
val requestDate = if (weatherDetailsResponse.createdAt == null) {
convertMillisecondsToDate(System.currentTimeMillis())
} else {
convertMillisecondsToDate(weatherDetailsResponse.createdAt)
}
Column(Modifier.padding(24.dp)) {
Text("Location: $location", color = Color.Gray)
Text("Current Temperature: $temperatureInCelsius °C", color = Color.Gray)
Text("Date: $requestDate", color = Color.Gray)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
Text("More Details", color = Color.Gray)
}
}
}
} | 0 | Kotlin | 0 | 0 | 982f38d8448999c8a0ec1eab8798e7de2de912ec | 1,667 | weather-app-test | MIT License |
mobile/src/main/java/com/siliconlabs/bledemo/common/other/CardViewListDecoration.kt | SiliconLabs | 85,345,875 | false | null | package com.siliconlabs.bledemo.common.other
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.siliconlabs.bledemo.R
class CardViewListDecoration : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildViewHolder(view).adapterPosition
val verticalSpacing = parent.context.resources.getDimensionPixelSize(
R.dimen.recycler_view_card_view_vertical_separation)
val horizontalMargin = parent.context.resources.getDimensionPixelSize(
R.dimen.recycler_view_card_view_horizontal_margin)
outRect.left = horizontalMargin
outRect.right = horizontalMargin
outRect.top = if (position == 0) verticalSpacing else 0
outRect.bottom = verticalSpacing
}
} | 20 | null | 70 | 96 | 501d1a7554593db61325f5ac3aa0865eb616d00b | 916 | EFRConnect-android | Apache License 2.0 |
mongodb/src/main/kotlin/io/qalipsis/examples/mongodb/MongoDbSaveAndSearch.kt | qalipsis | 295,792,028 | false | null | /*
* Copyright 2022 AERIS IT Solutions GmbH
*
* 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 io.qalipsis.examples.mongodb
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.mongodb.reactivestreams.client.MongoClients
import io.kotest.assertions.asClue
import io.kotest.assertions.assertSoftly
import io.kotest.matchers.ints.shouldBeExactly
import io.qalipsis.api.annotations.Scenario
import io.qalipsis.api.executionprofile.regular
import io.qalipsis.api.scenario.scenario
import io.qalipsis.api.steps.map
import io.qalipsis.api.steps.verify
import io.qalipsis.examples.utils.BatteryState
import io.qalipsis.examples.utils.BatteryStateContract
import io.qalipsis.examples.utils.DatabaseConfiguration
import io.qalipsis.examples.utils.ScenarioConfiguration.NUMBER_MINION
import io.qalipsis.plugins.jackson.csv.csvToObject
import io.qalipsis.plugins.jackson.jackson
import io.qalipsis.plugins.mongodb.mongodb
import io.qalipsis.plugins.mongodb.save.save
import io.qalipsis.plugins.mongodb.search.search
import org.bson.Document
class MongoDbSaveAndSearch {
private val objectMapper = ObjectMapper().also {
it.registerModule(JavaTimeModule())
}
@Scenario("mongodb-save-and-search")
fun scenarioSaveAndSearch() {
//we define the scenario, set the name, number of minions and rampUp
scenario {
minionsCount = NUMBER_MINION
profile {
regular(periodMs = 1000, minionsCountProLaunch = minionsCount)
}
}
.start()
.jackson() //we start the jackson step to fetch data from the csv file. we will use the csvToObject method to map csv entries to list of utils.BatteryState object
.csvToObject(BatteryState::class) {
classpath("battery-levels.csv")
// we define the header of the csv file
header {
column("deviceId")
column("timestamp")
column("batteryLevel").integer()
}
unicast()
}
.map { it.value } // we transform the output of the CSV reader entries to utils.BatteryState
.mongodb()// we start the mongodb step to save data in mongodb database
.save {
//setup connection of the database
connect {
MongoClients.create(DatabaseConfiguration.SERVER_LINK)
}
query {
database { _, _ ->
DatabaseConfiguration.DATABASE
}
collection { _, _ ->
DatabaseConfiguration.COLLECTION
}
documents { _, input ->
listOf(Document.parse(objectMapper.writeValueAsString(input)))
}
}
}
.map { it.input }
.mongodb()
.search {
name = "search"
connect {
MongoClients.create(DatabaseConfiguration.SERVER_LINK)
}
search {
database { _, _ -> DatabaseConfiguration.DATABASE }
collection { _, _ -> DatabaseConfiguration.COLLECTION }
query { _, input ->
Document(
mapOf(
BatteryStateContract.DEVICE_ID to input.deviceId,
BatteryStateContract.TIMESTAMP to input.timestamp.epochSecond
)
)
}
}
}
.map {
it.input to it.documents.map { document ->
objectMapper.readValue(document.toJson(), BatteryState::class.java)
}
}
.verify { result ->
result.asClue {
assertSoftly {
it.second.size shouldBeExactly 1
it.first.batteryLevel shouldBeExactly it.second.first().batteryLevel
}
}
}
}
} | 2 | Kotlin | 0 | 0 | 3b57c8dd4ffa6b169f1a6477eb1b4610b51a1c2c | 4,786 | qalipsis-examples | Apache License 2.0 |
app/src/main/java/com/monotonic/digits/Superscripts.kt | pensono | 128,152,524 | false | {"Markdown": 2, "Gradle": 3, "Text": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 45, "XML": 58, "ANTLR": 2, "Java": 6, "SVG": 5} | package com.monotonic.digits
import kotlin.math.absoluteValue
val superscriptMap = listOf('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹')
val superscriptMinus = '⁻'
fun prettyExponent(number: Int): String {
if (number == 1) {
return ""
}
val stringRepresentation = number.absoluteValue.toString()
val superscript = stringRepresentation.map { char -> superscriptMap[char - '0'] }.joinToString("")
val sign = if (number < 0) superscriptMinus.toString() else ""
return sign + superscript
}
/**
* Turn any superscripts in the input into regular digits
*/
fun unsuperscript(input: String): String {
var result = input
for (i in 0 until 10) {
result = result.replace(superscriptMap[i], '0' + i)
}
return result.replace(superscriptMinus, '-')
}
/**
* Parse a number which could contain superscripts
*/
fun parseNumber(input: String) = Integer.parseInt(unsuperscript(input))
/**
* True if a number is a digit or a superscript or a negative sign
*/
fun isNumber(input: Char) = input.isDigit() || superscriptMap.contains(input) || input == '-' || input == superscriptMinus | 2 | Kotlin | 0 | 1 | c867fd23ac75b2a2f699c0320024f7d330df92bd | 1,134 | Digits | MIT License |
app/src/main/java/com/dht/interest/music/MusicFragment.kt | Sotardust | 233,010,320 | false | {"Java": 482520, "Kotlin": 375635} | package com.dht.interest.music
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.dht.baselib.base.BaseActivity
import com.dht.baselib.base.BaseFragment
import com.dht.baselib.callback.RecycleItemClickCallBack
import com.dht.baselib.util.VerticalDecoration
import com.dht.interest.R
import com.dht.interest.databinding.FragmentMusicBinding
import com.dht.interest.util.Key
import com.dht.music.cloud.CloudDiskActivity
import com.dht.music.download.DownloadActivity
import com.dht.music.local.LocalActivity
import com.dht.music.recentplay.RecentPlayActivity
import kotlinx.android.synthetic.main.fragment_music.*
/**
* @author Administrator
*/
class MusicFragment : BaseFragment() {
private lateinit var mViewModel: MusicViewModel
private lateinit var mBinding: FragmentMusicBinding
private var musicAdapter: MusicAdapter? = null
override fun onCreateView(
@NonNull inflater: LayoutInflater, @Nullable container: ViewGroup?,
@Nullable savedInstanceState: Bundle?
): View? {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_music, container, false)
return mBinding.root
}
override fun onActivityCreated(@Nullable savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mViewModel = ViewModelProviders.of(this).get(MusicViewModel::class.java)
mBinding.musicViewModel = mViewModel
bindViews()
}
override fun bindViews() {
super.bindViews()
val layoutManager =
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
musicAdapter = MusicAdapter(recycleItemClickCallBack)
val list = listOf(*resources.getStringArray(R.array.musicList))
musicAdapter!!.setChangeList(list)
mBinding.recyclerView.adapter = musicAdapter
mBinding.recyclerView.layoutManager = layoutManager
mBinding.recyclerView.addItemDecoration(VerticalDecoration(3))
}
override fun onResume() {
super.onResume()
if (musicTitleView != null) {
musicTitleView!!.setActivity(activity as BaseActivity)
musicTitleView!!.updateView()
}
mViewModel.endListData
.observe(this, Observer {
musicAdapter?.setEndList(it)
})
}
private val recycleItemClickCallBack: RecycleItemClickCallBack<String> =
object : RecycleItemClickCallBack<String>() {
override fun onItemClickListener(
value: String?,
position: Int?
) {
super.onItemClickListener(value, position)
when (position) {
0 -> startActivity(
Intent(activity, LocalActivity::class.java).putExtra(Key.IBINDER, arguments)
)
1 -> startActivity(
Intent(activity, RecentPlayActivity::class.java).putExtra(
Key.IBINDER,
arguments
)
)
2 -> startActivity(
Intent(activity, CloudDiskActivity::class.java).putExtra(
Key.IBINDER,
arguments
)
)
3 -> startActivity(
Intent(activity, DownloadActivity::class.java).putExtra(
Key.IBINDER,
arguments
)
)
else -> {
}
}
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
}
companion object {
fun newInstance(): MusicFragment {
return MusicFragment()
}
}
} | 1 | null | 1 | 1 | cb410886655fb44cc3ee522e16c7bbd28fd899e3 | 4,318 | Interest | Apache License 2.0 |
Kotiln/bacic_concept/core/src/main/kotlin/com/example/core/b_methodDefinitionAndCall/localFunction/LocalFunction.kt | bekurin | 558,176,225 | false | {"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1} | package com.example.core.b_methodDefinitionAndCall.localFunction
class User(
val id: Int,
val name: String = "",
val address: String = ""
)
fun saveUser(user: User) {
if (user.name.isEmpty()) {
throw IllegalStateException(
"Can't save user ${user.id}: empty name"
)
}
if (user.address.isEmpty()) {
throw IllegalStateException(
"Can't save user ${user.id}: empty address"
)
}
println("user save!")
}
fun saveUserLocalFun(user: User) {
fun validate(user: User,
value: String,
fieldName: String) {
if (value.isEmpty()) {
throw IllegalStateException(
"Can't save user ${user.id}: empty $fieldName"
)
}
}
validate(user, user.name, "Name")
validate(user, user.address, "Address")
println("user save!")
}
fun main() {
val user = User(3, "hangman", "seoul")
val userWithoutName = User(3, address = "seoul")
val userWithoutAddress = User(3, "hangman")
saveUser(user)
// saveUser(userWithoutName)
// saveUser(userWithoutAddress)
saveUserLocalFun(user)
// saveUserLocalFun(userWithoutName)
// saveUserLocalFun(userWithoutAddress)
} | 0 | Java | 0 | 2 | ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d | 1,284 | blog_and_study | MIT License |
src/org/magiclib/combatgui/buttons/MagicCombatButtonAction.kt | MagicLibStarsector | 583,789,919 | false | {"Markdown": 4, "Text": 4, "Ant Build System": 2, "JSON": 15, "XML": 17, "Ignore List": 2, "Java": 119, "Kotlin": 78, "YAML": 1, "Shell": 2, "HTML": 2435, "SVG": 25, "CSS": 5, "JavaScript": 7, "Batchfile": 1, "Java Properties": 2} | package org.magiclib.combatgui.buttons
/**
* Implement this and override execute to instruct buttons what they should do when clicked.
*
* Example implementation:
* ```java
* public class ExampleButtonAction implements MagicCombatButtonAction {
* @Override
* public void execute() {
* Global.getLogger(this.getClass()).info("Button was clicked. This message should show up in starsector.log");
* }
* }
* ```
*
* @author Jannes
* @since 1.3.0
*/
interface MagicCombatButtonAction {
/**
* Will get executed when button is clicked.
*
* Example implementation:
* ```java
* @Override
* public void execute() {
* Global.getLogger(this.getClass()).info("Button was clicked. This message should show up in starsector.log");
* }
* ```
*/
fun execute()
} | 16 | Java | 2 | 9 | 8e6e7b6992f322d7172d84967a7e5656d35889af | 842 | MagicLib | MIT License |
sample-app-feature1/src/main/java/com/teamwork/android/samples/clean/feature1/detail/Feature1DetailsPresenter.kt | Teamwork | 130,834,398 | false | {"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Proguard": 6, "Java": 8, "XML": 35, "Kotlin": 44} | package com.teamwork.android.samples.clean.feature1.detail
import com.teamwork.android.samples.clean.business.Interactor
import com.teamwork.android.samples.clean.business.feature1.detail.Feature1DetailsInteractor
import com.teamwork.android.samples.clean.core.BasePresenter
import com.teamwork.android.samples.clean.entity.feature1.Entity1
import javax.inject.Inject
class Feature1DetailsPresenter @Inject constructor(private val interactor: Feature1DetailsInteractor)
: BasePresenter<Feature1DetailsView>() {
private val callback: Feature1DetailsCallback = Feature1DetailsCallback()
override fun onViewCreated(view: Feature1DetailsView) {
super.onViewCreated(view)
interactor.registerCallback(callback)
}
override fun onViewDestroyed() {
super.onViewDestroyed()
interactor.unregisterCallback()
}
}
private class Feature1DetailsCallback : Interactor.Callback<Entity1> {
override fun onDataLoaded(data: Entity1) {
TODO("not implemented")
}
override fun onDataLoadError(exception: Exception) {
TODO("not implemented")
}
} | 1 | null | 1 | 1 | 0218a1f1a3fd169f83b8ae35e69d2b1d651d4c0c | 1,118 | android-clean-architecture | Apache License 2.0 |
app/src/main/java/com/sleewell/sleewell/mvp/help/HelpSignalmenActivity.kt | TitouanFi | 427,797,671 | true | {"Kotlin": 554160, "HTML": 385717, "Java": 102120, "CSS": 12842, "JavaScript": 7278} | package com.sleewell.sleewell.mvp.help
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.sleewell.sleewell.BuildConfig
import com.sleewell.sleewell.R
class HelpSignalmenActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_help_signalement)
val versionCode = BuildConfig.VERSION_CODE
val versionName = BuildConfig.VERSION_NAME
val versionText = findViewById<TextView>(R.id.textVersion)
versionText.text = getString(R.string.version_app, versionName, versionCode.toString())
val urlReport = getString(R.string.url_report)
val buttonSignal = findViewById<Button>(R.id.buttonProblemSignal)
buttonSignal.setOnClickListener {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("$urlReport?version=$versionName-$versionCode")
)
)
}
val buttonReturn = findViewById<ImageButton>(R.id.imageReturnHelp)
buttonReturn.setOnClickListener {
finish()
}
}
} | 0 | Kotlin | 0 | 0 | e1980017127869159b0742b63273fa342ae0c9da | 1,350 | Sleewell-Android | MIT License |
feature/welcome/src/main/java/com/hellguy39/hellnotes/feature/welcome/WelcomeRoute.kt | HellGuy39 | 572,830,054 | false | null | package com.hellguy39.hellnotes.feature.welcome
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.rememberPagerState
import com.hellguy39.hellnotes.core.ui.navigations.navigateToHome
import com.hellguy39.hellnotes.feature.welcome.util.OnBoardingPage
@OptIn(ExperimentalPagerApi::class)
@Composable
fun WelcomeRoute(
welcomeViewModel: WelcomeViewModel = hiltViewModel(),
onFinish: () -> Unit = {}
) {
val pages = listOf(
OnBoardingPage.First,
OnBoardingPage.Second,
OnBoardingPage.Third
)
val pagerState = rememberPagerState()
WelcomeScreen(
pages = pages,
pagerState = pagerState,
onFinish = {
welcomeViewModel.saveOnBoardingState(completed = true)
onFinish()
}
)
} | 0 | Kotlin | 0 | 5 | 0086c5185b19d2e33aa699554a6f9231e0ca1419 | 957 | HellNotes | Apache License 2.0 |
kalman1d/src/main/java/uk/nhs/kalman1d/internal/Weights.kt | klinker41 | 330,272,308 | true | {"Kotlin": 76046} | package uk.nhs.kalman1d.internal
import kotlin.math.pow
internal class Weights(alpha: Double, beta: Double, kappa: Double) {
val meanWeights: Vector<MeanWeights>
val covarianceWeights: Vector<CovarianceWeights>
val scale: Value<Scale>
companion object {
val augmentedDimension = 3.0
val numberOfSigmaPoints = 2 * augmentedDimension.toInt() + 1
}
init {
val lambda = alpha.pow(2) * (augmentedDimension + kappa) - augmentedDimension
scale = Value(augmentedDimension + lambda)
val common = scale.inverse().rawValue * 0.5
meanWeights = weights(lambda / scale.rawValue, common)
covarianceWeights = weights((lambda / scale.rawValue) + (1 - alpha.pow(2) + beta), common)
}
} | 0 | Kotlin | 0 | 0 | 31e7235d807b5701fee138ff8ca38b2174edad59 | 756 | riskscore-kt-public | MIT License |
src/jvmTest/kotlin/LargestIslandKtTest.kt | Yvee1 | 594,173,330 | false | {"Kotlin": 469064, "Python": 37235, "HTML": 1269} | import patterns.Island
import patterns.largestIslandAt
import patterns.p0
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class LargestIslandKtTest {
@ParameterizedTest
@MethodSource("convexIslandInstances")
fun testLargestConvexIslandAt(instance: PartitionInstance, expected: Island) {
assertIslands(expected, instance.largestIslandAt(instance.points.maxBy { it.pos.x }, instance.points).original())
}
private fun assertIslands(expected: Island, actual: Island){
assertEquals(expected.points.toSet(), actual.points.toSet())
assertEquals(expected.weight, actual.weight)
}
private fun convexIslandInstances(): Stream<Arguments> {
val pts0 = listOf(
2 p0 0,
0 p0 0,
1 p0 1,
)
val pts1 = listOf(
4 p0 0,
0 p0 0,
1 p0 2,
2 p0 3,
3 p0 2,
)
val pts2 = listOf(
1 p0 0,
0 p0 0,
0 p0 1,
1 p0 1,
)
val pts3 = listOf(
0 p0 0,
0 p0 1,
0 p0 2,
0 p0 3,
0 p0 4,
0 p0 5,
)
return Stream.of(
Arguments.of(
PartitionInstance(pts0),
Island(pts0, pts0.size)
),
Arguments.of(
PartitionInstance(pts1),
Island(pts1, pts1.size)
),
Arguments.of(
PartitionInstance(pts2),
Island(pts2, pts2.size)
),
Arguments.of(
PartitionInstance(pts3),
Island(pts3, pts3.size)
),
)
}
} | 0 | Kotlin | 0 | 1 | 0869a819628b49032f8bc5a5c06f8c9e036651d2 | 2,006 | SimpleSets | MIT License |
client/slack-spring-test-api-client/src/test/kotlin/io/olaph/slack/client/test/group/oauth/MockOauthAccessUnitTest.kt | gitter-badger | 181,514,383 | true | {"Kotlin": 338538} | package io.olaph.slack.client.test.group.oauth
import MockMethodTestHelper
import com.nhaarman.mockitokotlin2.mock
import io.olaph.slack.client.test.MockSlackClient
import io.olaph.slack.dto.jackson.group.oauth.ErrorOauthAccessResponse
import io.olaph.slack.dto.jackson.group.oauth.OauthAccessRequest
import io.olaph.slack.dto.jackson.group.oauth.SuccessFullOauthAccessResponse
import io.olaph.slack.dto.jackson.group.oauth.sample
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
class MockOauthAccessUnitTest {
@DisplayName("Test Oauth Access")
@Test
fun testOauthAccess() {
val successFunction: (SuccessFullOauthAccessResponse?) -> Any = mock {}
val failureFunction: (ErrorOauthAccessResponse?) -> Any = mock {}
val mockSlackClient = MockSlackClient()
MockMethodTestHelper.verify({ mockSlackClient.oauth().access() },
successFunction, SuccessFullOauthAccessResponse.sample(),
failureFunction, ErrorOauthAccessResponse.sample(),
OauthAccessRequest.sample()
)
}
} | 0 | Kotlin | 0 | 0 | 429fa4293cb5c5bf67d7d543f92d4cc7a81eea4f | 1,097 | slack-spring-boot-starter | MIT License |
azure-take-out-kt/src/main/kotlin/moe/scarlet/azure_take_out_kt/task/OrderTask.kt | MukjepScarlet | 832,723,175 | false | {"Kotlin": 126087} | package moe.scarlet.azure_take_out_kt.task
import moe.scarlet.azure_take_out_kt.extension.logger
import moe.scarlet.azure_take_out_kt.pojo.Orders
import moe.scarlet.azure_take_out_kt.service.OrdersService
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class OrderTask(private val ordersService: OrdersService) {
/**
* 处理超时订单 / 每分钟
*/
@Scheduled(cron = "0 * * * * ?")
fun checkTimeout() {
logger.info("开始处理超时订单...")
ordersService.updateBatchById(
ordersService.listByStatusAndOrderTimeLt(
Orders.Status.PENDING_PAYMENT,
LocalDateTime.now().minusMinutes(15L)
).map {
it.copy(status = Orders.Status.CANCELLED, cancelReason = "超时未支付", cancelTime = LocalDateTime.now())
}
)
}
/**
* 处理一直派送中的订单 / 每天1点
*/
@Scheduled(cron = "0 0 1 * * ?")
fun checkDelivery() {
logger.info("开始清理派送中订单...")
ordersService.updateBatchById(
ordersService.listByStatusAndOrderTimeLt(
Orders.Status.DELIVERY_IN_PROGRESS,
LocalDateTime.now().minusHours(1L)
).map {
it.copy(status = Orders.Status.COMPLETED, cancelTime = LocalDateTime.now())
}
)
}
} | 0 | Kotlin | 0 | 0 | 66e7891ba5a80c3561875edf79ce9dcb045e1801 | 1,391 | AzureTakeOut-Kotlin | MIT License |
src/client/kotlin/grauly/attunate/rendering/beams/Beam.kt | Grauly | 840,553,706 | false | {"Kotlin": 22101, "Java": 1031, "GLSL": 882} | package grauly.attunate.rendering.beams
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext
import net.minecraft.client.render.BufferBuilder
import net.minecraft.util.math.MathHelper
import net.minecraft.util.math.Vec3d
import java.awt.Color
import java.security.InvalidParameterException
open class Beam(
private val beamPoints: List<BeamPoint>,
private val beamColor: Color,
var widthMultiplier: Double = 1.0
) {
init {
if (beamPoints.size < 2) throw InvalidParameterException("must specify at least 2 beam points")
}
fun render(ctx: WorldRenderContext, buffer: BufferBuilder) {
val camPos = ctx.camera().pos
val beamNormal = beamPoints.first().pos.subtract(camPos)
beamPoints.reduce { accumulate: BeamPoint, current: BeamPoint ->
val segmentDelta = current.pos.subtract(accumulate.pos)
val localUp = beamNormal.crossProduct(segmentDelta).normalize()
beamSegment(current, accumulate, localUp, ctx, buffer)
current
}
}
fun createSlice(anchor: Double, factor: Double): Beam {
val beamLength = length()
val anchorDistance = beamLength * anchor
val earlyCutoff = anchorDistance - (anchorDistance * factor)
val lateCutoff = anchorDistance + ((beamLength - anchorDistance) * factor)
val earlySegment = createLerpSegment(earlyCutoff)
val lateSegment = createLerpSegment(lateCutoff)
val sliceBeamSegments = beamPoints
.dropLast(beamPoints.size - (lateSegment?.first ?: beamPoints.size))
.drop(earlySegment?.first ?: 0)
.toMutableList()
if (earlySegment != null) sliceBeamSegments.add(0, earlySegment.second)
if (lateSegment != null) sliceBeamSegments.add(lateSegment.second)
return Beam(sliceBeamSegments, beamColor, widthMultiplier)
}
private fun createLerpSegment(beamPos: Double): Pair<Int, BeamPoint>? {
var distance = 0.0
var dropIndices = 1
beamPoints.reduce { previous: BeamPoint, current: BeamPoint ->
val beamDelta = current.pos.subtract(previous.pos)
val segmentLength = beamDelta.length()
if (distance + segmentLength < beamPos) {
distance += segmentLength
dropIndices++
return@reduce current
}
val segmentFac = (beamPos - distance) / segmentLength
return Pair(dropIndices, lerpSegment(previous, current, segmentFac))
}
return null
}
private fun findSegmentLerp(beamPointFac: Double): Double {
var length = 0.0
beamPoints.subList(1, beamPoints.size)
.fold(beamPoints.first()) { accumulate: BeamPoint, current: BeamPoint ->
val segmentDelta = current.pos.subtract(accumulate.pos)
val segmentLength = segmentDelta.length()
if (length + segmentLength > beamPointFac) {
//now figure out the segment fac
val segmentFac = beamPointFac - length
return segmentFac / segmentLength
}
length += segmentLength
current
}
return 0.0
}
private fun findBoundPoints(distance: Double): Pair<BeamPoint, BeamPoint> {
var length = 0.0
beamPoints.subList(1, beamPoints.size)
.fold(beamPoints.first()) { accumulate: BeamPoint, current: BeamPoint ->
val segmentDelta = current.pos.subtract(accumulate.pos)
val segmentLength = segmentDelta.length()
if (length + segmentLength > distance) return Pair(accumulate, current)
length += segmentLength
current
}
return Pair(beamPoints.last(), beamPoints.last())
}
fun lerpSegment(a: BeamPoint, b: BeamPoint, fac: Double): BeamPoint {
val pos = a.pos.lerp(b.pos, fac)
val width = MathHelper.lerp(fac, a.width, b.width)
val color = lerpColorRGBA((a.color ?: beamColor), (b.color ?: beamColor), fac)
return BeamPoint(pos, width, color)
}
private fun lerpColorRGBA(from: Color, to: Color, fac: Double): Color {
val r = lerpInt(fac, from.red, to.red)
val g = lerpInt(fac, from.green, to.green)
val b = lerpInt(fac, from.blue, to.blue)
val a = lerpInt(fac, from.alpha, to.alpha)
return Color(r, g, b, a)
}
private fun lerpColorHSVA(from: Color, to: Color, fac: Double): Color {
val hsvColorFrom = toHSV(from)
val hsvColorTo = toHSV(to)
val h = lerpHue(hsvColorFrom.h, hsvColorTo.h, fac.toFloat())
val s = MathHelper.lerp(fac.toFloat(), hsvColorFrom.s, hsvColorTo.s)
val v = MathHelper.lerp(fac.toFloat(), hsvColorFrom.v, hsvColorTo.v)
val interpolated = toRGB(HSVColor(h, s, v))
val a = lerpInt(fac, from.alpha, to.alpha)
return Color(interpolated.red, interpolated.green, interpolated.blue, a)
}
private fun lerpHue(from: Float, to: Float, fac: Float): Float {
if (from == to) return from
if (from > to) return lerpHue(to, from, fac)
val maxCCW = to - from
val maxCW = (from + 1) - to
var h = if (maxCW <= maxCCW) {
to + maxCW * fac
} else {
to - maxCCW * fac
}
if (h < 0) h += 1
if (h > 1) h -= 1
return h
}
private fun toHSV(color: Color): HSVColor {
val hsvvals = Color.RGBtoHSB(color.red, color.green, color.blue, null)
return HSVColor(hsvvals[0], hsvvals[1], hsvvals[2])
}
private fun toRGB(color: HSVColor): Color {
return Color.getHSBColor(color.h, color.s, color.v)
}
private fun lerpInt(fac: Double, a: Int, b: Int): Int {
if (a == b) return a
if (b >= a) return lerpInt(1-fac, b, a)
return a - ((a - b) * fac).toInt()
}
private fun length(): Double {
var length = 0.0
beamPoints.subList(1, beamPoints.size)
.fold(beamPoints.first()) { accumulate: BeamPoint, current: BeamPoint ->
length += accumulate.pos.distanceTo(current.pos)
current
}
return length
}
open fun pointWidth(point: BeamPoint): Double {
return point.width * widthMultiplier
}
private fun beamSegment(from: BeamPoint, to: BeamPoint, up: Vec3d, ctx: WorldRenderContext, buffer: BufferBuilder) {
//halving this bc of UV shenanigans
//upper half
fixBufferColor(buffer, to.color ?: beamColor)
beamVertex(to.pos, buffer, ctx, 1f, .5f)
beamVertex(to.pos.add(up.multiply(pointWidth(to))), buffer, ctx, 1f, 0f)
fixBufferColor(buffer, from.color ?: beamColor)
beamVertex(from.pos.add(up.multiply(pointWidth(from))), buffer, ctx, 0f, 0f)
beamVertex(from.pos, buffer, ctx, 0f, .5f)
//lower half
fixBufferColor(buffer, to.color ?: beamColor)
beamVertex(to.pos.subtract(up.multiply(pointWidth(to))), buffer, ctx, 1f, 1f)
beamVertex(to.pos, buffer, ctx, 1f, .5f)
fixBufferColor(buffer, from.color ?: beamColor)
beamVertex(from.pos, buffer, ctx, 0f, .5f)
beamVertex(from.pos.subtract(up.multiply(pointWidth(from))), buffer, ctx, 0f, 1f)
buffer.unfixColor()
}
private fun fixBufferColor(buffer: BufferBuilder, color: Color) {
buffer.fixedColor(color.red, color.green, color.blue, color.alpha)
}
private fun beamVertex(
pos: Vec3d,
buffer: BufferBuilder,
ctx: WorldRenderContext,
u: Float,
v: Float
) {
val wPos = pos.subtract(ctx.camera().pos)
buffer.vertex(
ctx.matrixStack().peek().positionMatrix,
wPos.getX().toFloat(),
wPos.getY().toFloat(),
wPos.getZ().toFloat()
)
.texture(u, v)
.next()
}
}
data class BeamPoint(val pos: Vec3d, val width: Double = 0.1, val color: Color? = null)
data class HSVColor(val h: Float, val s: Float, val v: Float)
| 0 | Kotlin | 0 | 0 | 121cd43d8c35f653417d60c67cb2fe3e27346bfe | 8,167 | Attunate | Creative Commons Zero v1.0 Universal |
lint-rules-androidarch-lint/src/test/java/fr/afaucogney/mobile/android/lint/helper/AndroidStub.kt | afaucogney | 314,580,067 | true | {"Kotlin": 340326, "Shell": 1027} | package fr.niji.mobile.android.socle.lint.helper
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.kotlin
val activitySupportStub = kotlin("""
package android.support.v7.app
class AppCompatActivity
""").indented()
val fragmentSupportStub = kotlin("""
package android.support.v4.app
class Fragment
""").indented() | 0 | Kotlin | 0 | 0 | 69180be08e8c36d5971827a8113447e3ba7be166 | 375 | lint-rules | Apache License 2.0 |
app/src/main/java/com/sunnyweather/android/logic/dao/ActivityDao.kt | FatBallFish | 281,006,635 | false | null | package com.sunnyweather.android.logic.dao
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.preference.PreferenceManager
import com.sunnyweather.android.BaseActivity
import java.lang.RuntimeException
/**
* @description
* @author FatBallFish
* @Date 2021/2/2 14:25
* */
object ActivityDao {
const val REQUEST_LOGIN = 100
const val REQUEST_VOICE_LOGIN = 101;
const val REQUEST_REGISTER = 200;
}
/**
* 获得SharedPreferences的配置。
* String 类型默认值为 ""
* Int 类型默认值为 0
* Float 类型默认值为 0F
* Long 类型默认值为 0L
* Boolean 类型默认值为 false
* 其他类型抛出 RuntimeException错误
*/
inline fun <reified T> Activity.getConfig(
key: String,
default: T? = null,
db: String = "default"
): T {
val preference: SharedPreferences
var _key: String = key
Log.i(BaseActivity.TAG, "T的类型:${T::class.java.simpleName}")
when (db) {
"default" -> {
preference = PreferenceManager.getDefaultSharedPreferences(this)
}
"flutter" -> {
preference =
this.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
_key = "flutter.$key"
}
else -> {
preference = this.getSharedPreferences(db, Context.MODE_PRIVATE)
}
}
when (T::class.java.simpleName) {
"String" -> {
return preference.getString(_key, if (default != null) default as String else "") as T
}
"Int" -> {
return preference.getInt(_key, if (default != null) default as Int else 0) as T
}
"Float" -> {
return preference.getFloat(_key, if (default != null) default as Float else 0F) as T
}
"Long" -> {
return preference.getLong(_key, if (default != null) default as Long else 0L) as T
}
"Boolean" -> {
return preference.getBoolean(
_key,
if (default != null) default as Boolean else false
) as T
}
else -> {
throw RuntimeException("invalid value type")
}
}
}
inline fun <reified T> Activity.setConfig(key: String, value: T, db: String = "default") {
val preference: SharedPreferences
var _key: String = key
when (db) {
"default" -> {
preference = PreferenceManager.getDefaultSharedPreferences(this)
}
"flutter" -> {
preference =
this.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
_key = "flutter.$key"
}
else -> {
preference = this.getSharedPreferences(db, Context.MODE_PRIVATE)
}
}
Log.i(BaseActivity.TAG, "T的类型:${T::class.java.simpleName}")
when (T::class.java.simpleName) {
"String" -> {
preference.edit().putString(_key, value as String).apply()
}
"Int", "Integer" -> {
preference.edit().putInt(_key, value as Int).apply()
}
"Float" -> {
preference.edit().putFloat(_key, value as Float).apply()
}
"Long" -> {
preference.edit().putLong(_key, value as Long).apply()
}
"Boolean" -> {
preference.edit().putBoolean(_key, value as Boolean).apply()
}
else -> {
throw RuntimeException("invalid value type")
}
}
}
fun Activity.removeConfig(key: String, db: String = "default") {
val preference: SharedPreferences
var _key: String = key
when (db) {
"default" -> {
preference = PreferenceManager.getDefaultSharedPreferences(this)
}
"flutter" -> {
preference =
this.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
_key = "flutter.$key"
}
else -> {
preference = this.getSharedPreferences(db, Context.MODE_PRIVATE)
}
}
preference.edit().remove(_key).apply()
} | 0 | Kotlin | 0 | 0 | 5a4c9add87b3a6c2ac18318fadc797b839604f4f | 4,048 | SunnyWeather | Apache License 2.0 |
remote/src/main/java/com/vlad1m1r/bltaxi/remote/TaxiProviderRemoteImpl.kt | pranavlathigara | 251,697,390 | true | {"Kotlin": 148833, "HTML": 15579} | package com.vlad1m1r.bltaxi.remote
import com.vlad1m1r.bltaxi.domain.Language
import com.vlad1m1r.bltaxi.domain.model.ItemTaxi
internal class TaxiProviderRemoteImpl(private val taxiService: TaxiService) :
TaxiProviderRemote {
override suspend fun getTaxis(language: Language): List<ItemTaxi> =
taxiService.taxis(language.code).map { it.toItemTaxi() }
}
| 0 | null | 0 | 1 | 1c31ac80dedcbced669cd9c9da61819c0b0c4bfc | 371 | BLTaxi | Apache License 2.0 |
redukt-core/src/commonTest/kotlin/com/daftmobile/redukt/core/closure/EmptyDispatchClosureTest.kt | DaftMobile | 597,542,701 | false | null | package com.daftmobile.redukt.core.closure
import com.daftmobile.redukt.core.ClosureElementA
import io.kotest.assertions.throwables.shouldThrowUnit
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import kotlin.test.Test
internal class EmptyDispatchClosureTest {
@Test
fun findShouldReturnNull() {
EmptyDispatchClosure
.find(ClosureElementA)
.shouldBeNull()
}
@Test
fun getShouldReturnThrowMissingClosureElementException() {
shouldThrowUnit<MissingClosureElementException> {
EmptyDispatchClosure[ClosureElementA]
}
}
@Test
fun splitShouldReturnEmptyList() {
EmptyDispatchClosure.scatter().shouldBeEmpty()
}
@Test
fun plusOperatorShouldReturnRightSide() {
val rightSide = ClosureElementA()
(EmptyDispatchClosure + rightSide) shouldBe rightSide
}
@Test
fun minusAnyKeyShouldReturnThis() {
(EmptyDispatchClosure - ClosureElementA) shouldBe EmptyDispatchClosure
}
} | 0 | Kotlin | 0 | 4 | a67dc67645a04cb6be1a1c0bcd64997ba83ae03d | 1,096 | ReduKt | MIT License |
app/src/main/java/com/e444er/cleanmovie/feature_movie_tv_detail/domain/use_cases/GetMovieDetailUseCase.kt | e444er | 597,756,971 | false | null | package com.e444er.cleanmovie.feature_movie_tv_detail.domain.use_cases
import com.e444er.cleanmovie.R
import com.e444er.cleanmovie.core.presentation.util.UiText
import com.e444er.cleanmovie.core.util.Resource
import com.e444er.cleanmovie.feature_movie_tv_detail.data.dto.detail.movie.toMovieDetail
import com.e444er.cleanmovie.feature_movie_tv_detail.domain.models.detail.MovieDetail
import com.e444er.cleanmovie.feature_movie_tv_detail.domain.repository.DetailRepository
import com.e444er.cleanmovie.feature_movie_tv_detail.domain.util.HandleUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okio.IOException
import retrofit2.HttpException
import timber.log.Timber
import javax.inject.Inject
class GetMovieDetailUseCase @Inject constructor(
private val detailRepository: DetailRepository
) {
operator fun invoke(
language: String,
movieId: Int
): Flow<Resource<MovieDetail>> {
return flow {
try {
val response =
detailRepository.getMovieDetail(language = language, movieId = movieId)
val result = response.toMovieDetail()
val movieDetail = result.copy(
ratingValue = HandleUtils.calculateRatingBarValue(result.voteAverage),
convertedRuntime = HandleUtils.convertRuntimeAsHourAndMinutes(result.runtime)
)
emit(Resource.Success(movieDetail))
} catch (e: IOException) {
emit(Resource.Error(UiText.StringResource(R.string.internet_error)))
} catch (e: HttpException) {
emit(Resource.Error(UiText.StringResource(R.string.oops_something_went_wrong)))
} catch (e: Exception) {
Timber.e(e)
emit(Resource.Error(UiText.StringResource(R.string.oops_something_went_wrong)))
}
}
}
} | 0 | Kotlin | 0 | 0 | 1c939de424b4eb254fd4258f4e56e4399bdfb3cd | 1,923 | KinoGoClean | Apache License 2.0 |
app/src/main/java/com/iproyal/sdkdemo/BootStartupReceiver.kt | IPRoyal | 655,631,729 | false | {"Kotlin": 9172} | package com.iproyal.sdkdemo
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.iproyal.sdk.common.sdk.Pawns
class BootStartupReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent?.action.equals(Intent.ACTION_BOOT_COMPLETED, true)) {
Pawns.getInstance().startSharing(context)
}
}
} | 0 | Kotlin | 1 | 2 | a7c7904bf7ad8a73c5ad963d95a00544988280c7 | 451 | android-pawns-sdk-demo | Apache License 2.0 |
src/main/kotlin/ro/horatiu_udrea/cs_ubb_timetable_parser/scraper/WebsiteTimetableScraper.kt | horatiu-udrea | 772,972,204 | false | {"Kotlin": 27372} | package ro.horatiu_udrea.cs_ubb_timetable_parser.scraper
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import it.skrape.core.htmlDocument
import it.skrape.selects.DocElement
import ro.horatiu_udrea.cs_ubb_timetable_parser.TimetableSet
import ro.horatiu_udrea.cs_ubb_timetable_parser.models.*
import java.net.URI
context(ro.horatiu_udrea.cs_ubb_timetable_parser.ProgramConfiguration)
class WebsiteTimetableScraper(private val httpClient: HttpClient) : TimetableScraper {
override suspend fun scrapeTimetableIndex(timetableSet: TimetableSet): ScrapedIndex? {
val url = getTimetableSetIndexUrl(timetableSet)
val response = httpClient.get(url)
if (response.status != HttpStatusCode.OK) return null
// The charset from the response is wrong or nonexistent, so we're overriding it here
val decoder = charset("ISO-8859-2").newDecoder()
val webpage = httpClient.get(url).body<ByteReadPacket>().let(decoder::decode)
return htmlDocument(webpage) {
val bachelors = findFirst("table") { scrapeTableItems() }
val masters = findSecond("table") { scrapeTableItems() }
ScrapedIndex(bachelors, masters)
}
}
override suspend fun scrapeTimetable(timetableSet: TimetableSet, link: String): ScrapedTimetable {
val url = URI(getTimetableSetIndexUrl(timetableSet)).resolve(link).toString()
// The charset from the response is wrong or nonexistent, so we're overriding it here
val decoder = charset("ISO-8859-2").newDecoder()
val webpage = httpClient.get(url).body<ByteReadPacket>().let(decoder::decode)
return htmlDocument(webpage) {
val groups = findAll("h1").asSequence().drop(1).map { it.text }
val timetables = findAll("table").asSequence().map { table ->
runCatching { table.findAll("tr:not(:has(th))") }.getOrDefault(emptyList()).map { row ->
val cells = row.findAll("td")
val day = cells[0].text
val time: String = cells[1].text
val frequency = cells[2].text
val (room, roomLink) = cells[3].getLinkFromElement()
val formation = cells[4].text
val type = cells[5].text
val (subject, subjectLink) = cells[6].getLinkFromElement()
val (teacher, teacherLink) = cells[7].getLinkFromElement()
ScrapedClassInfo(
day,
time,
frequency,
room,
roomLink,
formation,
type,
subject,
subjectLink,
teacher,
teacherLink
)
}
}
val allGroupTimetables = groups.zip(timetables) { groupName, timetable ->
ScrapedGroupTimetable(groupName, timetable)
}.toList()
ScrapedTimetable(allGroupTimetables)
}
}
private fun DocElement.scrapeTableItems() = findAll("tr:not(:has(th))").map { row ->
val cells = row.findAll("td")
val name = cells.first().text
val scrapedYears = cells.asSequence()
.drop(1)
.filter { it.text.isNotEmpty() }
.map { cell ->
val (linkText, link) = cell.getLinkFromElement()
ScrapedYear(linkText, link)
}.toList()
ScrapedTableItem(name, scrapedYears)
}
private fun DocElement.getLinkFromElement(): Pair<String, String> =
findFirst("a") {
text to attribute("href")
}
}
| 1 | Kotlin | 0 | 23 | 526b6873c5de1bf5428befdaae8f2b9932d87c49 | 3,904 | cs-ubb-timetable-parser | MIT License |
src/main/kotlin/ro/horatiu_udrea/cs_ubb_timetable_parser/scraper/WebsiteTimetableScraper.kt | horatiu-udrea | 772,972,204 | false | {"Kotlin": 27372} | package ro.horatiu_udrea.cs_ubb_timetable_parser.scraper
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import it.skrape.core.htmlDocument
import it.skrape.selects.DocElement
import ro.horatiu_udrea.cs_ubb_timetable_parser.TimetableSet
import ro.horatiu_udrea.cs_ubb_timetable_parser.models.*
import java.net.URI
context(ro.horatiu_udrea.cs_ubb_timetable_parser.ProgramConfiguration)
class WebsiteTimetableScraper(private val httpClient: HttpClient) : TimetableScraper {
override suspend fun scrapeTimetableIndex(timetableSet: TimetableSet): ScrapedIndex? {
val url = getTimetableSetIndexUrl(timetableSet)
val response = httpClient.get(url)
if (response.status != HttpStatusCode.OK) return null
// The charset from the response is wrong or nonexistent, so we're overriding it here
val decoder = charset("ISO-8859-2").newDecoder()
val webpage = httpClient.get(url).body<ByteReadPacket>().let(decoder::decode)
return htmlDocument(webpage) {
val bachelors = findFirst("table") { scrapeTableItems() }
val masters = findSecond("table") { scrapeTableItems() }
ScrapedIndex(bachelors, masters)
}
}
override suspend fun scrapeTimetable(timetableSet: TimetableSet, link: String): ScrapedTimetable {
val url = URI(getTimetableSetIndexUrl(timetableSet)).resolve(link).toString()
// The charset from the response is wrong or nonexistent, so we're overriding it here
val decoder = charset("ISO-8859-2").newDecoder()
val webpage = httpClient.get(url).body<ByteReadPacket>().let(decoder::decode)
return htmlDocument(webpage) {
val groups = findAll("h1").asSequence().drop(1).map { it.text }
val timetables = findAll("table").asSequence().map { table ->
runCatching { table.findAll("tr:not(:has(th))") }.getOrDefault(emptyList()).map { row ->
val cells = row.findAll("td")
val day = cells[0].text
val time: String = cells[1].text
val frequency = cells[2].text
val (room, roomLink) = cells[3].getLinkFromElement()
val formation = cells[4].text
val type = cells[5].text
val (subject, subjectLink) = cells[6].getLinkFromElement()
val (teacher, teacherLink) = cells[7].getLinkFromElement()
ScrapedClassInfo(
day,
time,
frequency,
room,
roomLink,
formation,
type,
subject,
subjectLink,
teacher,
teacherLink
)
}
}
val allGroupTimetables = groups.zip(timetables) { groupName, timetable ->
ScrapedGroupTimetable(groupName, timetable)
}.toList()
ScrapedTimetable(allGroupTimetables)
}
}
private fun DocElement.scrapeTableItems() = findAll("tr:not(:has(th))").map { row ->
val cells = row.findAll("td")
val name = cells.first().text
val scrapedYears = cells.asSequence()
.drop(1)
.filter { it.text.isNotEmpty() }
.map { cell ->
val (linkText, link) = cell.getLinkFromElement()
ScrapedYear(linkText, link)
}.toList()
ScrapedTableItem(name, scrapedYears)
}
private fun DocElement.getLinkFromElement(): Pair<String, String> =
findFirst("a") {
text to attribute("href")
}
}
| 1 | Kotlin | 0 | 23 | 526b6873c5de1bf5428befdaae8f2b9932d87c49 | 3,904 | cs-ubb-timetable-parser | MIT License |
android-sdk/src/main/java/com/payline/mobile/androidsdk/payment/domain/PaymentWebSdkActionHandler.kt | PaylineByMonext | 219,547,940 | false | null | package com.payline.mobile.androidsdk.payment.domain
import com.payline.mobile.androidsdk.core.data.ContextInfoKey
import com.payline.mobile.androidsdk.core.data.ContextInfoResult
import com.payline.mobile.androidsdk.core.domain.SdkAction
import com.payline.mobile.androidsdk.core.domain.SdkResultBroadcaster
import com.payline.mobile.androidsdk.core.domain.web.ScriptActionExecutor
import com.payline.mobile.androidsdk.core.domain.web.WebSdkActionDelegate
import org.json.JSONArray
internal object PaymentWebSdkActionHandler: WebSdkActionDelegate.Handler {
override fun canHandleAction(action: SdkAction): Boolean {
return action is PaymentSdkAction
}
private fun getLanguageCode(actionExecutor: ScriptActionExecutor, broadcaster: SdkResultBroadcaster) {
actionExecutor.executeAction(PaymentScriptAction.GetLanguageCode) {
broadcaster.broadcast(
PaymentSdkResult.DidGetLanguageCode(
it
)
)
}
}
private fun getIsSandbox(actionExecutor: ScriptActionExecutor, broadcaster: SdkResultBroadcaster) {
actionExecutor.executeAction(PaymentScriptAction.IsSandbox) {
broadcaster.broadcast(
PaymentSdkResult.DidGetIsSandbox(
it.toBoolean()
)
)
}
}
private fun getContextInfo(action: PaymentSdkAction.GetContextInfo, actionExecutor: ScriptActionExecutor, broadcaster: SdkResultBroadcaster) {
actionExecutor.executeAction(PaymentScriptAction.GetContextInfo(action.key)) {
val parsed = when (action.key) {
ContextInfoKey.AMOUNT_SMALLEST_UNIT, ContextInfoKey.CURRENCY_DIGITS ->
ContextInfoResult.Int(action.key, it.toInt())
ContextInfoKey.ORDER_DETAILS -> {
if (it == "null") {
ContextInfoResult.ObjectArray(
action.key,
JSONArray()
)
} else {
ContextInfoResult.ObjectArray(
action.key,
JSONArray(it)
)
}
}
else -> ContextInfoResult.String(action.key, it)
}
broadcaster.broadcast(
PaymentSdkResult.DidGetContextInfo(
parsed
)
)
}
}
private fun endToken(action: PaymentSdkAction.EndToken, actionExecutor: ScriptActionExecutor) {
actionExecutor.executeAction(PaymentScriptAction.EndToken(action.handledByMerchant, action.additionalData)) {}
}
override fun handle(action: SdkAction, actionExecutor: ScriptActionExecutor, broadcaster: SdkResultBroadcaster) {
if(action !is PaymentSdkAction) return
when(action) {
is PaymentSdkAction.GetLanguageCode -> getLanguageCode(actionExecutor, broadcaster)
is PaymentSdkAction.IsSandbox -> getIsSandbox(actionExecutor, broadcaster)
is PaymentSdkAction.GetContextInfo -> getContextInfo(action, actionExecutor, broadcaster)
is PaymentSdkAction.EndToken -> endToken(action, actionExecutor)
}
}
}
| 6 | Kotlin | 1 | 0 | 46d47f99c816d9b1fb32acb67968f7d28137fe18 | 3,316 | payline-android-sdk | MIT License |
linea/src/commonMain/kotlin/compose/icons/lineaicons/weather/Windgust.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineaicons.weather
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.lineaicons.WeatherGroup
public val WeatherGroup.Windgust: ImageVector
get() {
if (_windgust != null) {
return _windgust!!
}
_windgust = Builder(name = "Windgust", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp,
viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(44.0f, 40.0f)
curveToRelative(0.0f, 3.866f, 3.134f, 7.0f, 7.0f, 7.0f)
reflectiveCurveToRelative(7.0f, -3.134f, 7.0f, -7.0f)
reflectiveCurveToRelative(-3.134f, -7.0f, -7.0f, -7.0f)
horizontalLineTo(0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(49.0f, 19.0f)
curveToRelative(0.0f, -3.866f, 3.134f, -7.0f, 7.0f, -7.0f)
reflectiveCurveToRelative(7.0f, 3.134f, 7.0f, 7.0f)
reflectiveCurveToRelative(-3.134f, 7.0f, -7.0f, 7.0f)
horizontalLineTo(0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(27.0f, 45.0f)
curveToRelative(0.0f, 2.761f, 2.239f, 5.0f, 5.0f, 5.0f)
reflectiveCurveToRelative(5.0f, -2.239f, 5.0f, -5.0f)
reflectiveCurveToRelative(-2.239f, -5.0f, -5.0f, -5.0f)
horizontalLineTo(0.0f)
}
}
.build()
return _windgust!!
}
private var _windgust: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,790 | compose-icons | MIT License |
app/src/main/java/com/example/android/uamp/fragments/NowPlayingFragment.kt | Android-Music-Player-Apps | 174,511,263 | false | {"Kotlin": 218957, "Java": 19747, "Python": 12040, "HTML": 7718, "Shell": 1529} | /*
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.fragments
import android.net.Uri
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.example.android.uamp.R
import com.example.android.uamp.databinding.FragmentNowplayingBinding
import com.example.android.uamp.utils.InjectorUtils
import com.example.android.uamp.viewmodels.MainActivityViewModel
import com.example.android.uamp.viewmodels.NowPlayingFragmentViewModel
import com.example.android.uamp.viewmodels.NowPlayingFragmentViewModel.NowPlayingMetadata
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import kotlinx.android.synthetic.main.fragment_nowplaying.adContainer
/**
* A fragment representing the current media item being played.
*/
class NowPlayingFragment : Fragment() {
private val mainActivityViewModel by activityViewModels<MainActivityViewModel> {
InjectorUtils.provideMainActivityViewModel(requireContext())
}
private val nowPlayingViewModel by viewModels<NowPlayingFragmentViewModel> {
InjectorUtils.provideNowPlayingFragmentViewModel(requireContext())
}
private lateinit var adView: AdView
lateinit var binding: FragmentNowplayingBinding
private var initialLayoutComplete = false
// Determine the screen width (less decorations) to use for the ad width.
// If the ad hasn't been laid out, default to the full screen width.
private val adSize: AdSize
get() {
val display = activity?.windowManager?.defaultDisplay
val outMetrics = DisplayMetrics()
display?.getMetrics(outMetrics)
val density = outMetrics.density
var adWidthPixels = adContainer.width.toFloat()
if (adWidthPixels == 0f) {
adWidthPixels = outMetrics.widthPixels.toFloat()
}
val adWidth = (adWidthPixels / density).toInt()
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidth)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentNowplayingBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Always true, but lets lint know that as well.
val context = activity ?: return
// Initialize playback duration and position to zero
view.findViewById<TextView>(R.id.duration).text =
NowPlayingMetadata.timestampToMSS(context, 0L)
val positionTextView = view.findViewById<TextView>(R.id.position)
.apply { text = NowPlayingMetadata.timestampToMSS(context, 0L) }
// Attach observers to the LiveData coming from this ViewModel
nowPlayingViewModel.mediaMetadata.observe(viewLifecycleOwner,
Observer { mediaItem -> updateUI(view, mediaItem) })
nowPlayingViewModel.mediaButtonRes.observe(viewLifecycleOwner,
Observer { res ->
binding.mediaButton.setImageResource(res)
})
nowPlayingViewModel.mediaPosition.observe(viewLifecycleOwner,
Observer { pos ->
binding.position.text = NowPlayingMetadata.timestampToMSS(context, pos)
})
nowPlayingViewModel.mediaPosition.observe(viewLifecycleOwner,
Observer { pos ->
binding.position.text =
NowPlayingMetadata.timestampToMSS(context, pos)
})
// Setup UI handlers for buttons
binding.mediaButton.setOnClickListener {
nowPlayingViewModel.mediaMetadata.value?.let { mainActivityViewModel.playMediaId(it.id) }
}
// Initialize playback duration and position to zero
binding.duration.text = NowPlayingMetadata.timestampToMSS(context, 0L)
binding.position.text = NowPlayingMetadata.timestampToMSS(context, 0L)
// Initialize banner ad
initAdaptiveBannerAd()
// Clear focus
mainActivityViewModel.clearSearchFocus()
}
override fun onPause() {
adView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
adView.resume()
}
override fun onDestroy() {
adView.destroy()
super.onDestroy()
}
/**
* Internal function used to update all UI elements except for the current item playback
*/
private fun updateUI(view: View, metadata: NowPlayingMetadata) = with(binding) {
if (metadata.albumArtUri == Uri.EMPTY) {
albumArt.setImageResource(R.drawable.ic_album_black_24dp)
} else {
Glide.with(view)
.load(metadata.albumArtUri)
.into(albumArt)
}
title.text = metadata.title
subtitle.text = metadata.subtitle
duration.text = metadata.duration
}
private fun initAdaptiveBannerAd() {
adView = AdView(context)
adContainer.addView(adView)
// Since we're loading the banner based on the adContainerView size, we need to wait
// until this view is laid out before we can get the width.
adContainer.viewTreeObserver.addOnGlobalLayoutListener {
if (!initialLayoutComplete) {
initialLayoutComplete = true
loadBanner()
}
}
}
private fun loadBanner() {
adView.adUnitId = getString(R.string.banner_now_playing_ad_unit_id)
adView.adSize = adSize
// Create an ad request.
val adRequest = AdRequest.Builder().build()
// Start loading the ad in the background.
adView.loadAd(adRequest)
}
companion object {
fun newInstance() = NowPlayingFragment()
}
}
// This is an ad unit ID for a test ad. Replace with your own banner ad unit ID.
private const val BANNER_AD_UNIT_ID = "ca-app-pub-3940256099942544/9214589741"
| 1 | Kotlin | 0 | 2 | 8107a656023b7dcfbe6521d463652e4d35607286 | 7,041 | korol-i-shut | Apache License 2.0 |
data/src/main/java/com/techsensei/data/repository/ProfileRepositoryImpl.kt | zeeshanali-k | 410,526,232 | false | null | package com.techsensei.data.repository
import android.content.Context
import android.net.Uri
import android.util.Log
import com.techsensei.data.network.ProfileClient
import com.techsensei.domain.model.ProfileImage
import com.techsensei.domain.model.Resource
import com.techsensei.domain.repository.ProfileRepository
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.ByteArrayOutputStream
import java.io.FileInputStream
import java.io.IOException
class ProfileRepositoryImpl(
private val profileClient: ProfileClient,
private val context: Context
) : ProfileRepository {
private val TAG = "ProfileRepositoryImpl"
override suspend fun updateProfileImage(
fileUri: String,
userId: Int
): Resource<ProfileImage> {
return try {
val byteArrayOutputStream = getStream(fileUri)
val requestBody = RequestBody.create(
"image/*".toMediaTypeOrNull(),byteArrayOutputStream!!.toByteArray()
)
byteArrayOutputStream?.let {
it.close()
}
// File name is handled on server side
val part = MultipartBody.Part.createFormData("profile", "file", requestBody)
Resource.Success(ProfileImage(profileClient.updateProfileImage(part, userId).url!!))
} catch (e: Exception) {
Log.d(TAG, "updateProfileImage: ${e.localizedMessage}")
Log.d(TAG, "updateProfileImage: ${e.cause}")
Resource.Error("Failed to update profile image")
}
}
private fun getStream(fileUri:String): ByteArrayOutputStream? {
val fileInputStream: FileInputStream
val byteArrayOutputStream: ByteArrayOutputStream
val file: ByteArray
try {
byteArrayOutputStream = ByteArrayOutputStream()
fileInputStream = context
.contentResolver
.openInputStream(Uri.parse(fileUri)) as FileInputStream
file = ByteArray(4096)
while (fileInputStream.read(file) != -1) {
byteArrayOutputStream.write(file)
}
fileInputStream.close()
return byteArrayOutputStream
} catch (e: IOException) {
Log.d(
TAG,
"getStream: " + e.message
)
}
return null
}
} | 0 | Kotlin | 0 | 4 | 470b95803cdda7b8b3161ea7ba3f661adae86485 | 2,474 | Gup | Apache License 2.0 |
core/src/main/java/com/bruno13palhano/core/data/di/CoroutinesScopesModule.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1380539} | package com.bruno13palhano.core.data.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import javax.inject.Qualifier
import javax.inject.Singleton
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class ApplicationScope
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IOScope
@InstallIn(SingletonComponent::class)
@Module
object CoroutinesScopesModule {
@Singleton
@ApplicationScope
@Provides
fun providesCoroutineScope(
@Dispatcher(ShopDaniManagementDispatchers.DEFAULT) dispatcher: CoroutineDispatcher
): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher)
@Singleton
@IOScope
@Provides
fun providesIOScope(
@Dispatcher(ShopDaniManagementDispatchers.IO) dispatcher: CoroutineDispatcher
): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher)
} | 0 | Kotlin | 0 | 2 | c55b8f8f9fccb42ce9b5a99a309e41bd2ec0b5b2 | 1,059 | shop-dani-management | MIT License |
datastores/datastores-jvm/src/main/kotlin/info/kinterest/datastores/jvm/DataStoreConfig.kt | svd27 | 125,085,657 | false | null | package info.kinterest.datastores.jvm
import info.kinterest.jvm.datastores.DataStoreConfig
class DataStoreConfigImpl(override val name : String, override val type : String, override val config : Map<String,Any?>) : DataStoreConfig | 0 | Kotlin | 0 | 0 | 19f6d1f1a4c4221dc169e705e95b8ce169f0dc6c | 233 | ki | Apache License 2.0 |
app/src/main/java/com/example/foodfood/api/nutritionSummary/Data.kt | CAUSOLDOUTMEN | 690,046,919 | false | {"Kotlin": 196710} | package com.example.foodfood.api.nutritionSummary
data class Data(
val baseNutrition: BaseNutrition,
val checkDate: String,
val nutritionSumType: Int,
val ratioCarbohydrate: Double,
val ratioFat: Double,
val ratioKcal: Double,
val ratioProtein: Double,
val totalCarbohydrate: Int,
val totalFat: Int,
val totalKcal: Int,
val totalProtein: Int,
val userId: Long
) | 1 | Kotlin | 0 | 0 | c0eb1fd0ef4f567c91d71e6ba2c25760d2cea9f1 | 410 | Diareat_frontend | Apache License 2.0 |
examples/kotlin/src/main/kotlin/com/example/authors/postgresql/Models.kt | kyleconroy | 193,160,679 | false | null | // Code generated by sqlc. DO NOT EDIT.
package com.example.authors
data class Author (
val id: Long,
val name: String,
val bio: String?
)
| 165 | null | 301 | 4,843 | fc7bf6dc2e308f0666d14a97542050a05cf18902 | 148 | dinosql | MIT License |
examples/kotlin/src/main/kotlin/com/example/authors/postgresql/Models.kt | kyleconroy | 193,160,679 | false | null | // Code generated by sqlc. DO NOT EDIT.
package com.example.authors
data class Author (
val id: Long,
val name: String,
val bio: String?
)
| 165 | null | 301 | 4,843 | fc7bf6dc2e308f0666d14a97542050a05cf18902 | 148 | dinosql | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.