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
koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/mvvm/MVVMFragment.kt
henriquehorbovyi
277,036,450
true
{"Kotlin": 494681, "HTML": 8351, "Java": 8282, "JavaScript": 4873, "CSS": 827, "Shell": 466}
package org.koin.sample.androidx.mvvm import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.junit.Assert.* import org.koin.android.ext.android.getKoin import org.koin.androidx.scope.lifecycleScope import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.stateSharedViewModel import org.koin.androidx.viewmodel.ext.android.stateViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import org.koin.sample.android.R import org.koin.sample.androidx.components.ID import org.koin.sample.androidx.components.mvvm.SavedStateViewModel import org.koin.sample.androidx.components.mvvm.SimpleViewModel import org.koin.sample.androidx.components.scope.Session class MVVMFragment(val session: Session) : Fragment() { val shared: SimpleViewModel by sharedViewModel { parametersOf(ID) } val simpleViewModel: SimpleViewModel by viewModel { parametersOf(ID) } val saved by stateViewModel<SavedStateViewModel> { parametersOf(ID) } val sharedSaved: SavedStateViewModel by sharedViewModel { parametersOf(ID) } val sharedSaved2 by stateSharedViewModel<SavedStateViewModel> { parametersOf(ID) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.mvvm_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) assertNotNull(session) assertNotEquals(shared, simpleViewModel) assertNotEquals((requireActivity() as MVVMActivity).savedVm, saved) assertEquals((requireActivity() as MVVMActivity).simpleViewModel, shared) assertEquals((requireActivity() as MVVMActivity).savedVm, sharedSaved) assertEquals((requireActivity() as MVVMActivity).savedVm, sharedSaved) assertEquals((requireActivity() as MVVMActivity).savedVm, sharedSaved) assertEquals((requireActivity() as MVVMActivity).savedVm, sharedSaved2) assertEquals(sharedSaved, sharedSaved2) assertEquals(requireActivity().lifecycleScope.get<Session>().id, getKoin().getProperty("session_id")) } }
0
null
0
1
4f4647725fcdd5591df00c527340f34624e92f6e
2,412
koin
Apache License 2.0
src/main/kotlin/Application.kt
Dead-Doctor
449,460,175
false
null
// TODO: the application stores all global states and the logic to change them, it should be possible to control the application over cli or ui (and maybe others?) class Application { }
0
Kotlin
0
0
579f39e4a073172e051fb3ca500c290a0092a52b
187
CircuitConstructor
MIT License
braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetCreateParamsTest.kt
braintrustdata
752,086,100
false
{"Kotlin": 5588048, "Shell": 3637, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.braintrustdata.api.models import java.time.LocalDate import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.util.UUID import org.junit.jupiter.api.Test import org.assertj.core.api.Assertions.assertThat import org.apache.hc.core5.http.ContentType import com.braintrustdata.api.core.ContentTypes import com.braintrustdata.api.core.JsonNull import com.braintrustdata.api.core.JsonString import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.MultipartFormValue import com.braintrustdata.api.models.* import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetCreateParams.DatasetCreateBody class DatasetCreateParamsTest { @Test fun createDatasetCreateParams() { DatasetCreateParams.builder() .name("name") .description("description") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @Test fun getBody() { val params = DatasetCreateParams.builder() .name("name") .description("description") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() val body = params.getBody() assertThat(body).isNotNull assertThat(body.name()).isEqualTo("name") assertThat(body.description()).isEqualTo("description") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } @Test fun getBodyWithoutOptionalFields() { val params = DatasetCreateParams.builder() .name("name") .build() val body = params.getBody() assertThat(body).isNotNull assertThat(body.name()).isEqualTo("name") } }
1
Kotlin
0
2
515b9f0161f26c9de6880936bf5410e23fc2c40a
1,776
braintrust-java
Apache License 2.0
app/src/main/java/bg/zahov/app/ui/history/HistoryAdapter.kt
HauntedMilkshake
698,074,119
false
{"Kotlin": 390308}
package bg.zahov.app.ui.history import android.view.View import bg.zahov.app.data.model.Units import bg.zahov.app.data.model.Workout import bg.zahov.app.util.BaseAdapter import bg.zahov.app.util.timeToString import bg.zahov.app.util.toFormattedString import bg.zahov.fitness.app.R import com.google.android.material.textview.MaterialTextView class HistoryAdapter(private val units: Units = Units.METRIC) : BaseAdapter<Workout>( areItemsTheSame = { oldItem, newItem -> oldItem.id == newItem.id }, areContentsTheSame = { oldItem, newItem -> oldItem == newItem }, layoutResId = R.layout.item_past_workout ) { var itemClickListener: ItemClickListener<Workout>? = null override fun createViewHolder(view: View): WorkoutAdapterViewHolder = WorkoutAdapterViewHolder(view) inner class WorkoutAdapterViewHolder(view: View) : BaseViewHolder<Workout>(view) { private val title = view.findViewById<MaterialTextView>(R.id.workout_name) private val date = view.findViewById<MaterialTextView>(R.id.workout_date) private val duration = view.findViewById<MaterialTextView>(R.id.duration) private val volume = view.findViewById<MaterialTextView>(R.id.volume) private val prs = view.findViewById<MaterialTextView>(R.id.pr_count) private val exercises = view.findViewById<MaterialTextView>(R.id.exercises) private val bestSets = view.findViewById<MaterialTextView>(R.id.best_sets) override fun bind(item: Workout) { title.text = item.name date.text = item.date.toFormattedString() duration.text = item.duration?.timeToString() volume.text = "${item.volume ?: 0} ${if (units == Units.METRIC) "kg" else "lbs"}" prs.text = item.personalRecords.toString() exercises.text = item.exercises.joinToString("\n") { "${if (it.sets.isNotEmpty()) "${it.sets.size} x " else ""}${it.name} " } bestSets.text = item.exercises.joinToString("\n") { "${it.bestSet.firstMetric ?: 0} x ${it.bestSet.secondMetric ?: 0}" } itemView.setOnClickListener { itemClickListener?.onWorkoutClick(item, bindingAdapterPosition) } } } interface ItemClickListener<T> { fun onWorkoutClick(item: T, position: Int) } }
0
Kotlin
1
2
0aaba6d6f4392cb034d20b94e178ebe916ae78e6
2,370
fitness_app
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/roguelike_dungeon/RogueCellInfo.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.activity.roguelike_dungeon import org.anime_game_servers.core.base.Version.GI_2_2_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.ProtoModel @AddedIn(GI_2_2_0) @ProtoModel internal interface RogueCellInfo { var cellConfigId: Int var cellId: Int var cellType: Int var dungeonId: Int var state: RogueCellState }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
455
anime-game-multi-proto
MIT License
app/src/main/kotlin/ru/maksonic/beresta/ui/MainActivity.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.AnimatedContent import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.with import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.WindowCompat import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import com.google.accompanist.navigation.animation.AnimatedNavHost import com.google.accompanist.navigation.animation.rememberAnimatedNavController import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import ru.maksonic.beresta.feature.theme_picker.api.ThemePickerApi import ru.maksonic.beresta.language_engine.shell.provider.BerestaLanguage import ru.maksonic.beresta.navigation.graph_builder.GraphBuilder import ru.maksonic.beresta.navigation.router.Destination import ru.maksonic.beresta.navigation.router.navigator.AppNavigator import ru.maksonic.beresta.ui.theme.AppTheme import ru.maksonic.beresta.ui.theme.HighContrastTheme import ru.maksonic.beresta.ui.theme.SystemComponentColor import ru.maksonic.beresta.ui.theme.color.PaletteStore import ru.maksonic.beresta.ui.theme.color.background import ru.maksonic.beresta.ui.widget.SurfacePro class MainActivity : ComponentActivity() { private companion object { private const val THEME_CHANGE_INITIAL_ALPHA = 0f //If the value is less than .9f, then friezes are visible when changing the theme private const val THEME_CHANGE_TARGET_ALPHA = .9f } private val sandbox: MainActivitySandbox by viewModel() private val navigator: AppNavigator by inject() private val graphBuilder: GraphBuilder by inject() private val darkModeChecker: ThemePickerApi.DarkModeChecker by inject() private val splashVisibility = MutableStateFlow(true) @OptIn(ExperimentalAnimationApi::class) override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) updateSplashState() installSplashScreen() super.onCreate(savedInstanceState) setContent { navigator.navController = rememberAnimatedNavController() val model = sandbox.model.collectAsStateWithLifecycle(lifecycle).value val isDarkTheme = isSystemInDarkTheme() darkModeChecker.checkSystemDarkTheme(isDarkTheme) AnimatedContent( modifier = Modifier.fillMaxSize(), targetState = model.theme, transitionSpec = { fadeIn( initialAlpha = THEME_CHANGE_INITIAL_ALPHA, animationSpec = tween(300, 0) ) with fadeOut( targetAlpha = THEME_CHANGE_TARGET_ALPHA, animationSpec = tween(300, 0) ) }, label = "MainActivityContentAnimation", ) { animatedTheme -> initTheme( theme = animatedTheme, isDark = isDarkTheme, language = model.languageProvider, palette = model.themePalette ).invoke { SystemComponentColor(theme = model.theme, isDarkTheme = isDarkTheme) SurfacePro(color = background) { AnimatedNavHost( navController = navigator.navController, startDestination = Destination.route, modifier = Modifier .fillMaxSize() ) { graphBuilder.buildGraph(graphBuilder = this) } } } } } } private fun initTheme( theme: AppTheme, isDark: Boolean, language: BerestaLanguage, palette: PaletteStore, ): @Composable (content: @Composable () -> Unit) -> Unit = when (theme) { AppTheme.SYSTEM -> { content -> AppTheme( darkTheme = isDark, provideLanguages = language, palette = palette, content = content ) } AppTheme.LIGHT -> { content -> AppTheme( darkTheme = false, provideLanguages = language, palette = palette, content = content ) } AppTheme.DARK -> { content -> AppTheme( darkTheme = true, provideLanguages = language, palette = palette, content = content ) } AppTheme.HIGH_CONTRAST -> { content -> HighContrastTheme( darkTheme = true, provideLanguages = language, palette = palette.dark, content = content ) } } private fun updateSplashState() { lifecycleScope.launch { splashVisibility.update { true } delay(50) splashVisibility.update { false } } } }
0
Kotlin
0
0
b1c3480b9e715f7f02302b955af64cf032e4224a
6,088
Beresta
MIT License
lazycolumnscreen/crosslibrary/src/sharedTest/java/com/example/road/to/effective/snapshot/testing/lazycolumnscreen/crosslibrary/parameterized/CoffeeDrinkListComposableParameterizedTest.kt
sergio-sastre
394,010,429
false
null
package com.example.road.to.effective.snapshot.testing.lazycolumnscreen.crosslibrary.parameterized import com.example.road.to.effective.snapshot.testing.lazycolumnscreen.AppTheme import com.example.road.to.effective.snapshot.testing.lazycolumnscreen.CoffeeDrinkList import com.example.road.to.effective.snapshot.testing.testannotations.HappyPath import com.example.road.to.effective.snapshot.testing.testannotations.UnhappyPath import org.junit.Test import org.junit.Rule import org.junit.runner.RunWith import org.junit.runners.Parameterized import sergio.sastre.uitesting.utils.crosslibrary.runners.ParameterizedScreenshotTestAndroidJUnit4 /** * You can execute these tests from the command line with different screenshot testing libraries as follows: * 1. Record task: * 1. Paparazzi: ./gradlew :lazycolumnscreen:crosslibrary:recordPaparazziDebug * 2. Shot: ./gradlew :lazycolumnscreen:crosslibrary:executeScreenshotTests -Precord -PscreenshotLibrary=shot * 3. Dropshots: ./gradlew :lazycolumnscreen:crosslibrary:connectedAndroidTest -Pdropshots.record -PscreenshotLibrary=dropshots * * 2. Verify task: * 1. Paparazzi: ./gradlew :lazycolumnscreen:crosslibrary:verifyPaparazziDebug * 2. Shot: ./gradlew :lazycolumnscreen:crosslibrary:executeScreenshotTests -PscreenshotLibrary=shot * 3. Dropshots: ./gradlew :lazycolumnscreen:crosslibrary:connectedAndroidTest -PscreenshotLibrary=dropshots */ @RunWith(ParameterizedScreenshotTestAndroidJUnit4::class) class CoffeeDrinkListComposableParameterizedHappyPathTest( private val testItem: HappyPathTestItem, ) { companion object { @JvmStatic @Parameterized.Parameters fun testItemProvider(): Array<HappyPathTestItem> = HappyPathTestItem.values() } @get:Rule val screenshotRule = defaultCrossLibraryScreenshotTestRule(config = testItem.item) @HappyPath @Test fun snapComposable() { screenshotRule.snapshot(name = "CoffeeDrinkListComposable_${testItem.name}_Parameterized") { AppTheme { CoffeeDrinkList(coffeeDrink = coffeeDrink) } } } } @RunWith(ParameterizedScreenshotTestAndroidJUnit4::class) class CoffeeDrinkListComposableParameterizedUnhappyPathTest( private val testItem: UnhappyPathTestItem, ) { companion object { @JvmStatic @Parameterized.Parameters fun testItemProvider(): Array<UnhappyPathTestItem> = UnhappyPathTestItem.values() } @get:Rule val screenshotRule = defaultCrossLibraryScreenshotTestRule(config = testItem.item) @UnhappyPath @Test fun snapComposable() { screenshotRule.snapshot(name = "CoffeeDrinkListComposable_${testItem.name}_Parameterized") { AppTheme { CoffeeDrinkList(coffeeDrink = coffeeDrink) } } } }
3
Kotlin
10
136
9f37bb5b8f6dd1ea2c3eca73d00830463cef5226
2,852
Android-screenshot-testing-playground
MIT License
conductor-client/src/main/kotlin/com/openlattice/hazelcast/serializers/CollaborationStreamSerializer.kt
openlattice
101,697,464
false
null
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.SetStreamSerializers import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.openlattice.collaborations.Collaboration import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.mapstores.TestDataFactory import org.springframework.stereotype.Component @Component class CollaborationStreamSerializer : TestableSelfRegisteringStreamSerializer<Collaboration> { override fun generateTestValue(): Collaboration { return TestDataFactory.collaboration() } override fun getTypeId(): Int { return StreamSerializerTypeIds.COLLABORATION.ordinal } override fun getClazz(): Class<out Collaboration> { return Collaboration::class.java } override fun write(out: ObjectDataOutput, obj: Collaboration) { UUIDStreamSerializerUtils.serialize(out, obj.id) out.writeUTF(obj.name) out.writeUTF(obj.title) out.writeUTF(obj.description) SetStreamSerializers.fastUUIDSetSerialize(out, obj.organizationIds) } override fun read(input: ObjectDataInput): Collaboration { val id = UUIDStreamSerializerUtils.deserialize(input) val name = input.readString()!! val title = input.readString()!! val description = input.readString()!! val organizationIds = SetStreamSerializers.fastOrderedUUIDSetDeserialize(input) return Collaboration(id, name, title, description, organizationIds) } }
2
Kotlin
3
4
b836eea0a17128089e0dbe6719495413b023b2fb
1,647
openlattice
Apache License 2.0
app/src/main/java/com/arjanvlek/oxygenupdater/activities/InstallActivity.kt
iGotYourBackMr
254,597,651
true
{"Kotlin": 640563, "Java": 101703}
package com.arjanvlek.oxygenupdater.activities import android.graphics.drawable.Drawable import android.os.Bundle import android.util.DisplayMetrics import android.view.MenuItem import android.widget.Toast import android.widget.Toast.LENGTH_LONG import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.fragment.app.commit import androidx.lifecycle.observe import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.arjanvlek.oxygenupdater.R import com.arjanvlek.oxygenupdater.extensions.setImageResourceWithAnimation import com.arjanvlek.oxygenupdater.fragments.InstallGuideFragment import com.arjanvlek.oxygenupdater.fragments.InstallMethodChooserFragment import com.arjanvlek.oxygenupdater.models.AppLocale import com.arjanvlek.oxygenupdater.models.UpdateData import com.arjanvlek.oxygenupdater.utils.RootAccessChecker import com.arjanvlek.oxygenupdater.viewmodels.InstallViewModel import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.google.android.material.appbar.AppBarLayout import com.google.android.material.tabs.TabLayoutMediator import kotlinx.android.synthetic.main.activity_install.* import org.koin.androidx.viewmodel.ext.android.viewModel import kotlin.math.abs /** * @author [Adhiraj Singh Chauhan](https://github.com/adhirajsinghchauhan) */ class InstallActivity : SupportActionBarActivity() { private var showDownloadPage = true private var updateData: UpdateData? = null private val installViewModel by viewModel<InstallViewModel>() private val appBarOffsetChangeListenerForMethodChooserFragment = AppBarLayout.OnOffsetChangedListener { _, verticalOffset -> fragmentContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = appBar.totalScrollRange - abs(verticalOffset) } } private val appBarOffsetChangeListenerForViewPager = AppBarLayout.OnOffsetChangedListener { _, verticalOffset -> viewPagerContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = appBar.totalScrollRange - abs(verticalOffset) } } private val installGuidePageChangeCallback = object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) = handleInstallGuidePageChangeCallback(position) } override fun onCreate( savedInstanceState: Bundle? ) = super.onCreate(savedInstanceState).also { setContentView(R.layout.activity_install) showDownloadPage = intent == null || intent.getBooleanExtra(INTENT_SHOW_DOWNLOAD_PAGE, true) if (intent != null) { updateData = intent.getParcelableExtra(INTENT_UPDATE_DATA) } installViewModel.firstInstallGuidePageLoaded.observe(this) { if (it) { handleInstallGuidePageChangeCallback(0) } } installViewModel.toolbarTitle.observe(this) { collapsingToolbarLayout.title = getString(it) } installViewModel.toolbarSubtitle.observe(this) { collapsingToolbarLayout.subtitle = if (it != null) getString(it) else null } installViewModel.toolbarImage.observe(this) { collapsingToolbarImage.setImageResourceWithAnimation(it, android.R.anim.fade_in) } initialize() } private fun initialize() { RootAccessChecker.checkRootAccess { isRooted -> if (isFinishing) { return@checkRootAccess } rootStatusCheckLayout.isVisible = false if (isRooted) { installViewModel.fetchServerStatus().observe(this) { serverStatus -> if (serverStatus.automaticInstallationEnabled) { openMethodSelectionPage() } else { Toast.makeText(this, getString(R.string.install_guide_automatic_install_disabled), LENGTH_LONG).show() openInstallGuide() } } } else { Toast.makeText(this, getString(R.string.install_guide_no_root), LENGTH_LONG).show() openInstallGuide() } } } private fun openMethodSelectionPage() = supportFragmentManager.commit { setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) replace( R.id.fragmentContainer, InstallMethodChooserFragment().apply { arguments = bundleOf(INTENT_UPDATE_DATA to updateData) }, INSTALL_METHOD_CHOOSER_FRAGMENT_TAG ) addToBackStack(INSTALL_METHOD_CHOOSER_FRAGMENT_TAG) } fun setupAppBarForMethodChooserFragment() { appBar.post { // adjust bottom margin on first load fragmentContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = appBar.totalScrollRange } // adjust bottom margin on scroll appBar.addOnOffsetChangedListener(appBarOffsetChangeListenerForMethodChooserFragment) } } private fun setupAppBarForViewPager() { appBar.post { // adjust bottom margin on first load viewPagerContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = appBar.totalScrollRange } // adjust bottom margin on scroll appBar.addOnOffsetChangedListener(appBarOffsetChangeListenerForViewPager) } } fun resetAppBarForMethodChooserFragment() { appBar.post { // reset bottom margin on first load fragmentContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = 0 } // remove listener appBar.removeOnOffsetChangedListener(appBarOffsetChangeListenerForMethodChooserFragment) } } fun resetAppBarForViewPager() { appBar.post { // reset bottom margin on first load viewPagerContainer.updateLayoutParams<CoordinatorLayout.LayoutParams> { bottomMargin = 0 } // remove listener appBar.removeOnOffsetChangedListener(appBarOffsetChangeListenerForViewPager) } } fun openInstallGuide() = setupViewPager() private fun hideViewPager() { fragmentContainer.isVisible = true viewPagerContainer.isVisible = false resetAppBarForViewPager() } private fun setupViewPager() { fragmentContainer.isVisible = false viewPagerContainer.isVisible = true viewPager.apply { offscreenPageLimit = 4 // Install guide is 5 pages max. So there can be only 4 off-screen adapter = InstallGuidePagerAdapter() // attach TabLayout to ViewPager2 TabLayoutMediator(tabLayout, this) { _, _ -> }.attach() registerOnPageChangeCallback(installGuidePageChangeCallback) } setupButtonsForViewPager() resetAppBarForMethodChooserFragment() setupAppBarForViewPager() } private fun setupButtonsForViewPager() { previousPageButton.setOnClickListener { viewPager.currentItem-- } nextPageButton.setOnClickListener { if (viewPager.currentItem == viewPager.adapter!!.itemCount - 1) { onBackPressed() } else { viewPager.currentItem++ } } } private fun handleInstallGuidePageChangeCallback(position: Int) { previousPageButton.isEnabled = position != 0 nextPageButton.apply { rotation = if (position == viewPager.adapter!!.itemCount - 1) { setImageResource(R.drawable.checkmark) 0f } else { setImageResource(R.drawable.expand) 90f } } val pageNumber = position + if (showDownloadPage) 1 else 2 installViewModel.installGuideCache[pageNumber]?.run { collapsingToolbarLayout.title = if (AppLocale.get() == AppLocale.NL) dutchTitle else englishTitle collapsingToolbarLayout.subtitle = getString( R.string.install_guide_subtitle, position + 1, if (showDownloadPage) NUMBER_OF_INSTALL_GUIDE_PAGES else NUMBER_OF_INSTALL_GUIDE_PAGES - 1 ) if (!isDefaultPage && useCustomImage) { // Fetch the custom image from the server. Glide.with(this@InstallActivity) .load(completeImageUrl(imageUrl, fileExtension)) .listener(object : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean { collapsingToolbarImage.isVisible = true return false } override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { collapsingToolbarImage.isVisible = true return false } }) // Load a "no entry" sign to show that the image failed to load. .error(R.drawable.error_image) .into(collapsingToolbarImage) } else { val imageResourceId = resources.getIdentifier( RESOURCE_ID_PREFIX + pageNumber + RESOURCE_ID_IMAGE, RESOURCE_ID_PACKAGE_DRAWABLE, packageName ) collapsingToolbarImage.setImageResourceWithAnimation(imageResourceId, android.R.anim.fade_in) } } } private fun completeImageUrl(imageUrl: String?, fileExtension: String?): String { val imageVariant: String = when (resources.displayMetrics.densityDpi) { DisplayMetrics.DENSITY_LOW -> IMAGE_VARIANT_LDPI DisplayMetrics.DENSITY_MEDIUM -> IMAGE_VARIANT_MDPI DisplayMetrics.DENSITY_TV -> IMAGE_VARIANT_TVDPI DisplayMetrics.DENSITY_HIGH -> IMAGE_VARIANT_HDPI DisplayMetrics.DENSITY_280, DisplayMetrics.DENSITY_XHIGH -> IMAGE_VARIANT_XHDPI DisplayMetrics.DENSITY_360, DisplayMetrics.DENSITY_400, DisplayMetrics.DENSITY_420, DisplayMetrics.DENSITY_XXHIGH -> IMAGE_VARIANT_XXHDPI DisplayMetrics.DENSITY_560, DisplayMetrics.DENSITY_XXXHIGH -> IMAGE_VARIANT_XXXHDPI else -> IMAGE_VARIANT_DEFAULT } return "${imageUrl}_$imageVariant.$fileExtension" } override fun onDestroy() = super.onDestroy().also { viewPager?.unregisterOnPageChangeCallback(installGuidePageChangeCallback) } /** * Handles the following cases: * * Once the installation is being started, there is no way out => do nothing * * If [InstallGuideFragment] is being displayed, and was opened from [InstallMethodChooserFragment], switch back to [fragmentContainer] * * If [InstallGuideFragment] was opened directly after checking for root (meaning if the device isn't rooted), call [finish] * * If [InstallMethodChooserFragment] is the only fragment being displayed (meaning [FragmentManager.getBackStackEntryCount] returns `1`, call [finish] * * Otherwise just call `super`, which respects [FragmentManager]'s back stack */ override fun onBackPressed() = when { // Once the installation is being started, there is no way out. !installViewModel.canGoBack -> Toast.makeText(this, R.string.install_going_back_not_possible, LENGTH_LONG).show() // if InstallGuide is being displayed, and was opened from `InstallMethodChooserFragment`, switch back to fragmentContainer // if it was opened directly after checking for root (meaning if the device isn't rooted), call `finish()` viewPagerContainer.isVisible -> { if (supportFragmentManager.backStackEntryCount == 0) { finish() } else { hideViewPager() // update toolbar state to reflect values set in `InstallMethodChooserFragment` installViewModel.updateToolbarTitle(R.string.install_method_chooser_title) installViewModel.updateToolbarSubtitle(R.string.install_method_chooser_subtitle) installViewModel.updateToolbarImage(R.drawable.list_select) setupAppBarForMethodChooserFragment() viewPager.unregisterOnPageChangeCallback(installGuidePageChangeCallback) } } supportFragmentManager.backStackEntryCount == 1 -> finish() else -> super.onBackPressed() } /** * Respond to the action bar's Up/Home button. * Delegate to [onBackPressed] if [android.R.id.home] is clicked, otherwise call `super` */ override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> onBackPressed().let { true } else -> super.onOptionsItemSelected(item) } companion object { private const val RESOURCE_ID_IMAGE = "_image" private const val RESOURCE_ID_PACKAGE_DRAWABLE = "drawable" private const val IMAGE_VARIANT_LDPI = "ldpi" private const val IMAGE_VARIANT_MDPI = "mdpi" private const val IMAGE_VARIANT_TVDPI = "tvdpi" private const val IMAGE_VARIANT_HDPI = "hdpi" private const val IMAGE_VARIANT_XHDPI = "xhdpi" private const val IMAGE_VARIANT_XXHDPI = "xxhdpi" private const val IMAGE_VARIANT_XXXHDPI = "xxxhdpi" private const val IMAGE_VARIANT_DEFAULT = "default" const val RESOURCE_ID_PREFIX = "install_guide_page_" const val INTENT_SHOW_DOWNLOAD_PAGE = "show_download_page" const val INTENT_UPDATE_DATA = "update_data" const val NUMBER_OF_INSTALL_GUIDE_PAGES = 5 const val INSTALL_METHOD_CHOOSER_FRAGMENT_TAG = "InstallMethodChooser" const val AUTOMATIC_INSTALL_FRAGMENT_TAG = "AutomaticInstall" } /** * A [FragmentStateAdapter] that returns a fragment corresponding to one of the sections/tabs/pages */ private inner class InstallGuidePagerAdapter : FragmentStateAdapter(this) { /** * This is called to instantiate the fragment for the given page. * Returns an instance of [InstallGuideFragment] */ override fun createFragment(position: Int) = InstallGuideFragment.newInstance( (position + if (showDownloadPage) 1 else 2), position == 0 ) /** * Show the predefined amount of total pages */ override fun getItemCount() = if (showDownloadPage) { NUMBER_OF_INSTALL_GUIDE_PAGES } else { NUMBER_OF_INSTALL_GUIDE_PAGES - 1 } } }
0
null
0
0
884766371e62969831f2933ba790bbec4c2c1613
15,348
oxygen-updater
MIT License
src/main/kotlin/novah/frontend/ModuleRefs.kt
stackoverflow
255,379,925
false
null
/** * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package novah.frontend import novah.ast.source.* import novah.data.Reflection import novah.data.Reflection.collectType import novah.frontend.error.CompilerProblem import novah.frontend.error.Errors import novah.frontend.error.Severity import novah.frontend.typechecker.* import novah.main.DeclRef import novah.main.FullModuleEnv import novah.main.NovahClassLoader import novah.main.TypeDeclRef import novah.ast.source.Type as SType typealias VarRef = String typealias ModuleName = String fun resolveImports(mod: Module, modules: Map<String, FullModuleEnv>, env: Env): List<CompilerProblem> { val visible = { (_, tvis): Map.Entry<String, DeclRef> -> tvis.visibility == Visibility.PUBLIC } val visibleType = { (_, tvis): Map.Entry<String, TypeDeclRef> -> tvis.visibility == Visibility.PUBLIC } fun makeError(span: Span): (String) -> CompilerProblem = { msg -> CompilerProblem(msg, span, mod.sourceName, mod.name.value) } fun makeWarn(span: Span): (String) -> CompilerProblem = { msg -> CompilerProblem(msg, span, mod.sourceName, mod.name.value, null, Severity.WARN) } val resolved = mutableMapOf<VarRef, ModuleName>() val resolvedTypealiases = mutableListOf<Decl.TypealiasDecl>() val errors = mutableListOf<CompilerProblem>() for (imp in mod.imports) { val mkError = makeError(imp.span()) val mkWarn = makeWarn(imp.span()) val mname = imp.module.value val m = if (mname == PRIM) primModuleEnv else modules[mname]?.env if (m == null) { errors += mkError(Errors.moduleNotFound(mname)) continue } val typealiases = modules[mname]?.aliases?.associate { it.name to it } ?: emptyMap() when (imp) { // Import all declarations, types and type aliases from this module is Import.Raw -> { if (warnOnRawImport(imp)) errors += mkWarn(Errors.IMPORT_RAW) val alias = if (imp.alias != null) "${imp.alias}." else "" m.types.filter(visibleType).forEach { name, (type, _) -> resolved["$alias$name"] = mname env.extendType("$mname.$name", type) } m.decls.filter(visible).forEach { name, (type, _, isInstance) -> resolved["$alias$name"] = mname env.extend("$mname.$name", type) if (isInstance) env.extendInstance("$mname.$name", type) } typealiases.filter { (_, ta) -> ta.visibility == Visibility.PUBLIC }.forEach { (_, ta) -> resolvedTypealiases += ta } } // Import defined declarations and types unqualified, plus everything qualified if there's an alias is Import.Exposing -> { if (imp.alias != null) { val alias = "${imp.alias}." m.types.filter(visibleType).forEach { name, (type, _) -> resolved["$alias$name"] = mname env.extendType("$mname.$name", type) } m.decls.filter(visible).forEach { name, (type, _, isInstance) -> resolved["$alias$name"] = mname env.extend("$mname.$name", type) if (isInstance) env.extendInstance("$mname.$name", type) } typealiases.filter { (_, ta) -> ta.visibility == Visibility.PUBLIC }.forEach { (_, ta) -> resolvedTypealiases += ta } } for (ref in imp.defs) { when (ref) { is DeclarationRef.RefVar -> { val declRef = m.decls[ref.name] if (declRef == null) { errors += mkError(Errors.cannotFindInModule("declaration ${ref.name}", mname)) continue } if (declRef.visibility == Visibility.PRIVATE) { errors += mkError(Errors.cannotImportInModule("declaration ${ref.name}", mname)) continue } val fname = "$mname.${ref.name}" resolved[ref.name] = mname env.extend(fname, declRef.type) if (declRef.isInstance) env.extendInstance(fname, declRef.type) } is DeclarationRef.RefType -> { val talias = typealiases[ref.name] if (talias != null) { if (talias.visibility == Visibility.PRIVATE) { errors += mkError(Errors.cannotImportInModule("type ${ref.name}", mname)) continue } resolvedTypealiases += talias continue } val declRef = m.types[ref.name] if (declRef == null) { errors += mkError(Errors.cannotFindInModule("type ${ref.name}", mname)) continue } if (declRef.visibility == Visibility.PRIVATE) { errors += mkError(Errors.cannotImportInModule("type ${ref.name}", mname)) continue } env.extendType("$mname.${ref.name}", declRef.type) resolved[ref.name] = mname when { ref.ctors == null -> { } ref.ctors.isEmpty() -> { for (ctor in declRef.ctors) { val ctorDecl = m.decls[ctor]!! // cannot fail if (ctorDecl.visibility == Visibility.PRIVATE) { errors += mkError(Errors.cannotImportInModule("constructor $ctor", mname)) continue } env.extend("$mname.$ctor", ctorDecl.type) resolved[ctor] = mname } } else -> { for (ctor in ref.ctors) { val name = ctor.value val ctorDecl = m.decls[ctor.value] if (ctorDecl == null) { errors += mkError(Errors.cannotFindInModule("constructor $name", mname)) continue } if (ctorDecl.visibility == Visibility.PRIVATE) { errors += mkError(Errors.cannotImportInModule("constructor $name", mname)) continue } env.extend("$mname.$name", ctorDecl.type) resolved[name] = mname } } } } } } } } } mod.resolvedImports = resolved mod.resolvedTypealiases = resolvedTypealiases return errors } /** * Resolves all java imports in this module. */ fun resolveForeignImports(mod: Module, cl: NovahClassLoader, tc: Typechecker): List<CompilerProblem> { val errors = mutableListOf<CompilerProblem>() fun makeError(span: Span): (String) -> CompilerProblem = { msg -> CompilerProblem(msg, span, mod.sourceName, mod.name.value) } val typealiases = mutableMapOf<String, String>() for (type in mod.foreigns) { val fqType = type.type val clazz = cl.safeFindClass(fqType) if (clazz == null) { errors += makeError(type.span)(Errors.classNotFound(fqType)) continue } tc.env.extendType(fqType, collectType(tc, clazz)) if (type.alias != null) { if (mod.resolvedImports.containsKey(type.alias)) errors += makeError(type.span)(Errors.duplicatedImport(type.alias)) typealiases[type.alias] = fqType } else { val alias = fqType.split('.').last() if (mod.resolvedImports.containsKey(alias)) errors += makeError(type.span)(Errors.duplicatedImport(alias)) typealiases[alias] = fqType } } typealiases.putAll(resolveImportedTypealiases(mod.resolvedTypealiases)) mod.foreignTypes = typealiases return errors } private fun resolveImportedTypealiases(tas: List<Decl.TypealiasDecl>): Map<String, String> { return tas.mapNotNull { ta -> if (ta.expanded != null) { val name = ta.expanded!!.simpleName() if (name != null) ta.name to Reflection.novahToJava(name) else null } else null }.toMap() } /** * Makes sure all types used by a public * type alias are also public */ fun validatePublicAliases(ast: Module): List<CompilerProblem> { val errors = mutableListOf<CompilerProblem>() ast.decls.filterIsInstance<Decl.TypealiasDecl>().filter { it.visibility == Visibility.PUBLIC }.forEach { ta -> val consts = mutableListOf<String>() ta.expanded?.everywhereUnit { t -> if (t is SType.TConst) { consts += t.name } } val types = ast.decls.filterIsInstance<Decl.TypeDecl>().associateBy { it.name } consts.forEach { name -> val ty = types[name] if (ty != null && ty.visibility == Visibility.PRIVATE) { errors += CompilerProblem( Errors.TYPEALIAS_PUB, ta.span, ast.sourceName, ast.name.value ) } } } return errors } private val allowedRawModules = setOf(PRIM, CORE_MODULE, TEST_MODULE, COMPUTATION_MODULE) private fun warnOnRawImport(imp: Import.Raw): Boolean = imp.alias == null && imp.module.value !in allowedRawModules
0
null
0
9
f3f2b12e178c5288197f6c6d591e8d304f5baf5d
11,390
novah
Apache License 2.0
src/main/java/uk/ac/shef/tracker/core/database/tables/TrackerTableActivities.kt
oakgroup
630,448,719
false
{"Kotlin": 375304}
/* * Copyright (c) 2023. This code was developed by <NAME>, The University of Sheffield. All rights reserved. No part of this code can be used without the explicit written permission by the author */ package uk.ac.shef.tracker.core.database.tables import android.content.Context import androidx.annotation.WorkerThread import uk.ac.shef.tracker.core.database.engine.TrackerDatabase import uk.ac.shef.tracker.core.database.models.TrackerDBActivity import uk.ac.shef.tracker.core.database.queries.TrackerActivities import uk.ac.shef.tracker.core.utils.Logger /** * Utility class to execute the queries for the activities table handling the exceptions with a specific [Logger] message * This class should be used for all the operations, do not access directly the [TrackerActivities] dao */ object TrackerTableActivities { /** * @param context an instance of [Context] * @return all the models in the database table */ @WorkerThread fun getAll(context: Context): List<TrackerDBActivity> { try { return TrackerDatabase.getInstance(context).getActivities().getAll() } catch (e: Exception) { e.printStackTrace() Logger.e("Error on getting all activities from database ${e.localizedMessage}") } return arrayListOf() } /** * Get all the models in the database table between a start and an end time * * @param context an instance of [Context] * @param start the start timestamp * @param end the end timestamp * @return all the models found */ @WorkerThread fun getBetween(context: Context, start: Long, end: Long): List<TrackerDBActivity> { try { return TrackerDatabase.getInstance(context).getActivities().getBetween(start, end) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on getting all activities between $start and $end from database ${e.localizedMessage}") } return arrayListOf() } /** * Get all the models in the database that have not been uploaded * * @param context an instance of [Context] * @return all the models found */ @WorkerThread fun getNotUploaded(context: Context): List<TrackerDBActivity> { try { return TrackerDatabase.getInstance(context).getActivities().getNotUploaded() } catch (e: Exception) { e.printStackTrace() Logger.e("Error on getting not uploaded activities from database ${e.localizedMessage}") } return arrayListOf() } /** * Get the count of the models in the database that have not been uploaded * Searching only for models before a specific timestamp * * @param context an instance of [Context] * @param millis the models that have a greater timestamp than this won't be considered * @return the count of all the models found */ @WorkerThread fun getNotUploadedCountBefore(context: Context, millis: Long): Int { try { return TrackerDatabase.getInstance(context).getActivities().getNotUploadedCountBefore(millis) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on getting not uploaded count before for activities from database ${e.localizedMessage}") } return 0 } /** * Get the model by the identifier * * @param context an instance of [Context] * @param idActivity the model identifier * @return the model if found */ @WorkerThread fun getById(context: Context, idActivity: Int): TrackerDBActivity? { try { return TrackerDatabase.getInstance(context).getActivities().getById(idActivity) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on getting activity by id $idActivity from database ${e.localizedMessage}") } return null } /** * Insert a list of models into the database * If the model already exists, according to its primary key and indices, the model won't be inserted * * @param context an instance of [Context] * @param models the list of models to insert */ @WorkerThread fun insert(context: Context, models: List<TrackerDBActivity>) { try { TrackerDatabase.getInstance(context).getActivities().insert(models) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on insert activities to database ${e.localizedMessage}") } } /** * Update a list of models into the database * If the model already exists, according to its primary key and indices, the model will be updated * * @param context an instance of [Context] * @param models the list of models to update */ @WorkerThread fun update(context: Context, models: List<TrackerDBActivity>) { try { TrackerDatabase.getInstance(context).getActivities().update(models) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on update activities to database ${e.localizedMessage}") } } /** * Delete a model from the database * * @param context an instance of [Context] * @param idActivity the model identifier */ @WorkerThread fun delete(context: Context, idActivity: Int) { try { TrackerDatabase.getInstance(context).getActivities().delete(idActivity) } catch (e: Exception) { e.printStackTrace() Logger.e("Error on delete activity with id $idActivity from database ${e.localizedMessage}") } } /** * Delete all the models from this database table * * @param context an instance of [Context] */ @WorkerThread fun truncate(context: Context) { try { TrackerDatabase.getInstance(context).getActivities().truncate() } catch (e: Exception) { e.printStackTrace() Logger.e("Error on truncate activities from database ${e.localizedMessage}") } } }
0
Kotlin
0
0
6038c18049427eff461c04fa490f9ea177740dc3
6,170
android-bhf-tracker
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/screen/Welcome.kt
QArtur99
351,395,561
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.screen import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.navigate import com.example.androiddevchallenge.R import com.example.androiddevchallenge.ui.data.ScreenState import com.example.androiddevchallenge.ui.theme.shapes @Composable fun Welcome(isDarkTheme: Boolean, navController: NavController) { val backgroundRes = if (isDarkTheme) R.drawable.dark_welcome_bg else R.drawable.light_welcome_bg val illosRes = if (isDarkTheme) R.drawable.dark_welcome_illos else R.drawable.light_welcome_illos val logo = if (isDarkTheme) R.drawable.dark_logo else R.drawable.light_logo Box( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colors.primary), ) { Background(backgroundRes) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally, ) { Image( modifier = Modifier .fillMaxWidth() .padding(top = 144.dp, start = 88.dp, bottom = 48.dp), imageVector = ImageVector.vectorResource(id = illosRes), contentDescription = stringResource(R.string.welcome_illos), contentScale = ContentScale.FillBounds, ) Image( painter = painterResource(id = logo), contentDescription = stringResource(id = R.string.app_name) ) Text( modifier = Modifier.paddingFromBaseline(top = 32.dp, bottom = 40.dp), text = stringResource(R.string.welcome_subtitle), color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.subtitle1, ) Button( onClick = { /*TODO*/ }, shape = shapes.medium, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.secondary ), modifier = Modifier .padding(start = 16.dp, end = 16.dp, bottom = 8.dp) .fillMaxWidth() .height(48.dp) ) { Text( text = stringResource(R.string.welcome_btn_sign_up), color = MaterialTheme.colors.onSecondary, style = MaterialTheme.typography.button, ) } Text( modifier = Modifier .clickable { navController.navigate(route = ScreenState.Login) }, text = stringResource(R.string.welcome_btn_log_in), color = MaterialTheme.colors.onPrimary, style = MaterialTheme.typography.button, ) } } } @Composable private fun Background(backgroundRes: Int) { Image( modifier = Modifier .fillMaxWidth() .fillMaxHeight(), imageVector = ImageVector.vectorResource(id = backgroundRes), contentDescription = "welcome background", contentScale = ContentScale.FillBounds, ) }
0
Kotlin
0
1
3b20d843dedc7dce934c3ed7be139194c401832e
5,032
Bloom
Apache License 2.0
library/src/main/java/com/base/library/widget/RefreshLayout.kt
liweihua802
312,457,893
false
null
package com.base.library.widget import android.content.Context import android.util.AttributeSet import com.base.library.R import com.scwang.smart.refresh.header.ClassicsHeader import com.scwang.smart.refresh.layout.SmartRefreshLayout /** * @时间 2020/11/2 14:39 * @author liweihua * @描述 下拉刷新,默认经典刷新头,不启用加载更多 */ class RefreshLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : SmartRefreshLayout(context, attrs) { init { //设置默认id id = R.id.smart_refresh_layout //设置经典刷新头 setRefreshHeader(ClassicsHeader(context)) //是否启用越界拖动 setEnableOverScrollDrag(true) //是否启用上拉加载功能 setEnableLoadMore(false) //是否在列表不满一页时候开启上拉加载功能 setEnableLoadMoreWhenContentNotFull(false) } }
0
Kotlin
0
0
c343c9e9197222a4c9fc1172f6d39f9d27858fea
788
kotlin-base
Apache License 2.0
app/src/androidTest/java/com/example/testingdemo/ui/screens/interopcard/InteropCardScreenTest.kt
dan-0
664,356,148
false
null
package com.example.testingdemo.ui.screens.interopcard import androidx.compose.foundation.layout.Box import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import com.example.testingdemo.R import com.example.testingdemo.data.UserData import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test class InteropCardScreenTest { @get:Rule val composeTestRule = createComposeRule() @OptIn(ExperimentalComposeUiApi::class) @Test fun displayed() { val userData = UserData( userId = 0, userName = "Dan Lowe", userImageUrl = "stub", species = "Human" ) composeTestRule.setContent { Box( modifier = Modifier.semantics { testTagsAsResourceId = true } ) { InteropCardScreen(userData = userData) } } composeTestRule.onNodeWithTag("userCardImage") .assertExists() .assertContentDescriptionEquals("User profile photo for ${userData.userName}") // Note using Espresso because we have an Android View onView(withId(R.id.user_card_name_label)) .check(matches(withText("User name:"))) onView(withId(R.id.user_card_name_value)) .check(matches(withText(userData.userName))) onView(withId(R.id.user_card_species_label)) .check(matches(withText("Species:"))) onView(withId(R.id.user_card_species_value)) .check(matches(withText(userData.species))) val device = UiDevice.getInstance(getInstrumentation()) val userCardImage = device.findObject(By.res("userCardImage")) assertEquals(userCardImage.contentDescription, "User profile photo for ${userData.userName}") } }
0
Kotlin
0
0
2a40fe89f948a0394a63d0e118c90eb6a42892bc
2,329
UiTestDemo
MIT License
mvplifecycler/src/main/java/com/android/mvp/lifecycle/MainActivity.kt
7449
69,446,568
false
{"Gradle": 55, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 83, "XML": 299, "Kotlin": 132, "Java": 260, "Checksums": 6, "Java Properties": 2, "HTML": 2, "JSON": 3, "CSS": 1, "JavaScript": 7}
package com.android.mvp.lifecycle import android.os.Bundle import android.widget.Toast import com.android.mvp.lifecycle.base.BaseActivity import com.android.mvp.lifecycle.mvp.MainPresenter import com.android.mvp.lifecycle.mvp.MainPresenterImpl import com.android.mvp.lifecycle.mvp.MainView class MainActivity : BaseActivity<MainPresenter>(), MainView { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) presenter.netWork() } override fun initPresenter(): MainPresenter = MainPresenterImpl(this) override fun showLoading() {} override fun hideLoading() {} override fun showToast() { Toast.makeText(this, "show", Toast.LENGTH_LONG).show() } }
0
Java
35
31
e9317e538de09bfb7c1ec8ddd709211f51368049
786
AndroidDevelop
Apache License 2.0
korge/src/commonTest/kotlin/com/soywiz/korge/input/MouseDragComponentTest.kt
korlibs
80,095,683
false
null
package com.soywiz.korge.input import com.soywiz.korev.MouseButton import com.soywiz.korge.tests.ViewsForTesting import com.soywiz.korge.view.ViewsTest import com.soywiz.korge.view.solidRect import com.soywiz.korim.color.Colors import com.soywiz.korma.geom.Point import com.soywiz.korma.geom.SizeInt import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals class MouseDragComponentTest : ViewsForTesting( virtualSize = SizeInt(100, 100), windowSize = SizeInt(200, 200), ) { @Test fun testStageScale() = viewsTest { assertEquals(2.0, stage.scale) assertEquals(1.0, views.ag.devicePixelRatio) } @Test fun testMouseCoords() = viewsTest { val rect = solidRect(100, 100, Colors.RED) rect.draggable() val deltaX = 20 val deltaY = 10 mouseMoveTo(10, 10) mouseDown(MouseButton.LEFT) mouseMoveTo(10 + deltaX, 10 + deltaY) mouseUp(MouseButton.LEFT) assertEquals(Point(deltaX / stage.scale, deltaY / stage.scale), rect.pos) } }
102
Kotlin
64
1,192
7fa8c9981d09c2ac3727799f3925363f1af82f45
1,078
korge
Apache License 2.0
src/commonMain/kotlin/api/models/Product.kt
kotlinfunc
565,100,240
false
null
/** * Yandex Music Api * * Swagger документация для Yandex Music API. * * The version of the OpenAPI document: 1.0.0 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package api.models import api.models.LicenceTextPart import api.models.Price import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * продаваемый продукт * * @param productId Уникальный идентификатор. * @param type Тип продаваемого. * @param commonPeriodDuration Длительность общего периода. * @param duration Длительность. * @param trialDuration Длительность испытательного срока. * @param price * @param feature Предоставляемая возможность. * @param debug Отладочный продукт. * @param plus Даёт ли подписку \"Плюс\". * @param cheapest Самый дешёвый (лучшее предложение). * @param title Заголовок продукта. * @param familySub Семейная ли подписка. * @param fbImage Картинка для превью на facebook. * @param fbName Заголовок превью на facebook. * @param family Доступно ли для семьи. * @param features Список предоставляемых возможностей. * @param description Описание. * @param available Доступна ли покупка. * @param trialAvailable Доступен ли пробный период. * @param trialPeriodDuration Длительность пробного периода. * @param introPeriodDuration Длительность вступительного периода TODO. * @param introPrice * @param startPeriodDuration Длительность первого срока (за меньшую цену). * @param startPrice * @param licenceTextParts * @param vendorTrialAvailable Доступен испытательный срок продавца TODO. * @param buttonText Текст кнопки. * @param buttonAdditionalText Дополнительный текст кнопки. * @param paymentMethodTypes Способы оплаты. */ @Serializable data class Product ( /* Уникальный идентификатор. */ @SerialName(value = "productId") val productId: kotlin.String? = null, /* Тип продаваемого. */ @SerialName(value = "type") val type: kotlin.String? = null, /* Длительность общего периода. */ @SerialName(value = "commonPeriodDuration") val commonPeriodDuration: kotlin.String? = null, /* Длительность. */ @SerialName(value = "duration") val duration: kotlin.Double? = null, /* Длительность испытательного срока. */ @SerialName(value = "trialDuration") val trialDuration: kotlin.Double? = null, @SerialName(value = "price") val price: Price? = null, /* Предоставляемая возможность. */ @SerialName(value = "feature") val feature: kotlin.String? = null, /* Отладочный продукт. */ @SerialName(value = "debug") val debug: kotlin.Boolean? = null, /* Даёт ли подписку \"Плюс\". */ @SerialName(value = "plus") val plus: kotlin.Boolean? = null, /* Самый дешёвый (лучшее предложение). */ @SerialName(value = "cheapest") val cheapest: kotlin.Boolean? = null, /* Заголовок продукта. */ @SerialName(value = "title") val title: kotlin.String? = null, /* Семейная ли подписка. */ @SerialName(value = "familySub") val familySub: kotlin.Boolean? = null, /* Картинка для превью на facebook. */ @SerialName(value = "fbImage") val fbImage: kotlin.String? = null, /* Заголовок превью на facebook. */ @SerialName(value = "fbName") val fbName: kotlin.String? = null, /* Доступно ли для семьи. */ @SerialName(value = "family") val family: kotlin.Boolean? = null, /* Список предоставляемых возможностей. */ @SerialName(value = "features") val features: kotlin.collections.List<kotlin.String>? = null, /* Описание. */ @SerialName(value = "description") val description: kotlin.String? = null, /* Доступна ли покупка. */ @SerialName(value = "available") val available: kotlin.Boolean? = null, /* Доступен ли пробный период. */ @SerialName(value = "trialAvailable") val trialAvailable: kotlin.Boolean? = null, /* Длительность пробного периода. */ @SerialName(value = "trialPeriodDuration") val trialPeriodDuration: kotlin.String? = null, /* Длительность вступительного периода TODO. */ @SerialName(value = "introPeriodDuration") val introPeriodDuration: kotlin.String? = null, @SerialName(value = "introPrice") val introPrice: Price? = null, /* Длительность первого срока (за меньшую цену). */ @SerialName(value = "startPeriodDuration") val startPeriodDuration: kotlin.String? = null, @SerialName(value = "startPrice") val startPrice: Price? = null, @SerialName(value = "licenceTextParts") val licenceTextParts: LicenceTextPart? = null, /* Доступен испытательный срок продавца TODO. */ @SerialName(value = "vendorTrialAvailable") val vendorTrialAvailable: kotlin.Boolean? = null, /* Текст кнопки. */ @SerialName(value = "buttonText") val buttonText: kotlin.String? = null, /* Дополнительный текст кнопки. */ @SerialName(value = "buttonAdditionalText") val buttonAdditionalText: kotlin.String? = null, /* Способы оплаты. */ @SerialName(value = "paymentMethodTypes") val paymentMethodTypes: kotlin.collections.List<kotlin.String>? = null )
0
null
0
0
4ac5e027fb2f63eb7235ce2add8be6d36002d711
5,263
yandex-music-kotlin
Do What The F*ck You Want To Public License
user-error-server/src/main/kotlin/net/plshark/usererror/server/role/impl/UserGroupsRepositoryImpl.kt
twinklehawk
138,668,802
false
null
package net.plshark.usererror.server.role.impl import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import net.plshark.usererror.role.Group import net.plshark.usererror.role.Role import net.plshark.usererror.server.role.UserGroupsRepository import org.springframework.r2dbc.core.DatabaseClient import org.springframework.r2dbc.core.await import org.springframework.stereotype.Repository /** * User groups repository using spring data */ @Repository class UserGroupsRepositoryImpl(private val client: DatabaseClient) : UserGroupsRepository { override fun findGroupsByUserId(userId: Long): Flow<Group> { val sql = "SELECT * FROM groups g INNER JOIN user_groups ug ON g.id = ug.group_id WHERE ug.user_id = :id" return client.sql(sql) .bind("id", userId) .map { row -> GroupsRepositoryImpl.mapRow(row) } .all() .asFlow() } override fun findGroupRolesByUserId(userId: Long): Flow<Role> { val sql = "SELECT r.* from roles r, user_groups ug, group_roles gr WHERE ug.user_id = :userId AND " + "gr.group_id = ug.group_id AND r.id = gr.role_id" return client.sql(sql) .bind("userId", userId) .map { row -> RolesRepositoryImpl.mapRow(row) } .all() .asFlow() } override suspend fun insert(userId: Long, groupId: Long) { return client.sql("INSERT INTO user_groups (user_id, group_id) values (:userId, :groupId)") .bind("userId", userId) .bind("groupId", groupId) .await() } override suspend fun deleteById(userId: Long, groupId: Long) { return client.sql("DELETE FROM user_groups WHERE user_id = :userId AND group_id = :groupId") .bind("userId", userId) .bind("groupId", groupId) .await() } }
10
null
1
1
de43c003235a141076722eb45640dea1202f9809
1,873
bad-users
Apache License 2.0
server/src/test/kotlin/io/rippledown/model/rule/IsSuggestionTest.kt
TimLavers
513,037,911
false
{"Kotlin": 1246446, "Gherkin": 96905}
package io.rippledown.model.rule import io.kotest.matchers.shouldBe import io.rippledown.model.condition.isCondition import io.rippledown.model.condition.tr import kotlin.test.Test class IsSuggestionTest: ConditionFactoryTestBase() { @Test fun createFor() { IsSuggestion.invoke(tsh, null) shouldBe null with(IsSuggestion.invoke(tsh, tr("whatever"))!!) { isEditable() shouldBe false editableCondition() shouldBe null initialSuggestion() shouldBe isCondition(null, tsh, "whatever") } } }
1
Kotlin
0
0
a247b6cd8aad5688dd8f4711df1af6f2d1300edd
559
OpenRDR
MIT License
app/src/main/java/com/pandulapeter/beagle/appDemo/feature/main/examples/simpleSetup/SimpleSetupFragment.kt
pandulapeter
209,092,048
false
{"Kotlin": 850334, "Ruby": 497}
package com.pandulapeter.beagle.appDemo.feature.main.examples.simpleSetup import androidx.lifecycle.viewModelScope import com.pandulapeter.beagle.appDemo.R import com.pandulapeter.beagle.appDemo.feature.main.examples.ExamplesDetailFragment import com.pandulapeter.beagle.appDemo.feature.main.examples.simpleSetup.list.SimpleSetupAdapter import com.pandulapeter.beagle.appDemo.feature.main.examples.simpleSetup.list.SimpleSetupListItem import com.pandulapeter.beagle.common.contracts.module.Module import com.pandulapeter.beagle.modules.* import org.koin.androidx.viewmodel.ext.android.viewModel class SimpleSetupFragment : ExamplesDetailFragment<SimpleSetupViewModel, SimpleSetupListItem>(R.string.case_study_simple_setup_title) { override val viewModel by viewModel<SimpleSetupViewModel>() override fun createAdapter() = SimpleSetupAdapter( scope = viewModel.viewModelScope, onSectionHeaderSelected = viewModel::onSectionHeaderSelected ) override fun getBeagleModules(): List<Module<*>> = mutableListOf<Module<*>>().apply { add(AppInfoButtonModule()) add(DeveloperOptionsButtonModule()) add(ForceCrashButtonModule()) add(ScreenshotButtonModule()) add(ScreenRecordingButtonModule()) add(GalleryButtonModule()) add(ScreenCaptureToolboxModule()) add(KeylineOverlaySwitchModule()) add(AnimationDurationSwitchModule(onValueChanged = { viewModel.refreshItems() })) add(LifecycleLogListModule()) add(DeviceInfoModule()) add(BugReportButtonModule()) } companion object { fun newInstance() = SimpleSetupFragment() } }
14
Kotlin
27
491
f07df4647c91a36917d92cf9c128bcf44b03b732
1,663
beagle
Apache License 2.0
app/src/main/java/com/yousufsyed/fetchrewards/di/AppModule.kt
yousufsyed
512,902,555
false
{"Kotlin": 20387}
package com.yousufsyed.fetchrewards.di import android.app.Application import android.content.Context import com.yousufsyed.fetchrewards.network.DefaultRewardsRestClient import com.yousufsyed.fetchrewards.network.RewardsApi import com.yousufsyed.fetchrewards.network.RewardsRestClient import com.yousufsyed.fetchrewards.network.data.RewardItem import com.yousufsyed.fetchrewards.provider.* import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class AppModule { @Singleton @Provides fun provideContext(application: Application): Context = application.applicationContext @Provides fun getOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .build() @Provides fun getGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create() @[Provides Singleton] fun getRewardsApi( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory ): RewardsApi = Retrofit.Builder() .baseUrl("https://fetch-hiring.s3.amazonaws.com") .addConverterFactory(gsonConverterFactory) .client(okHttpClient) .build() .create(RewardsApi::class.java) @Provides fun rewardsRestClient(impl: DefaultRewardsRestClient): RewardsRestClient = impl @Provides fun rewardsProvider(impl: DefaultRewardsProvider): RewardsProvider = impl @Provides fun getDispatcherProvider(impl: DefaultDispatcherProvider): DispatcherProvider = impl @Provides fun getEventLogger(impl: DefaultEventLogger): EventLogger = impl @Provides fun rewardsConverter(impl: DefaultRewardsConverter): RewardsConverter<RewardItem> = impl @[Provides Singleton] fun networkAvailabilityProvider(impl: DefaultNetworkAvailabilityProvider): NetworkAvailabilityProvider = impl }
0
Kotlin
0
0
8cfd7ecb22c78be191f9ec794ee2019d1a2dce90
1,922
FetchRewards
Apache License 2.0
app/src/main/java/com/yousufsyed/fetchrewards/di/AppModule.kt
yousufsyed
512,902,555
false
{"Kotlin": 20387}
package com.yousufsyed.fetchrewards.di import android.app.Application import android.content.Context import com.yousufsyed.fetchrewards.network.DefaultRewardsRestClient import com.yousufsyed.fetchrewards.network.RewardsApi import com.yousufsyed.fetchrewards.network.RewardsRestClient import com.yousufsyed.fetchrewards.network.data.RewardItem import com.yousufsyed.fetchrewards.provider.* import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class AppModule { @Singleton @Provides fun provideContext(application: Application): Context = application.applicationContext @Provides fun getOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .build() @Provides fun getGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create() @[Provides Singleton] fun getRewardsApi( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory ): RewardsApi = Retrofit.Builder() .baseUrl("https://fetch-hiring.s3.amazonaws.com") .addConverterFactory(gsonConverterFactory) .client(okHttpClient) .build() .create(RewardsApi::class.java) @Provides fun rewardsRestClient(impl: DefaultRewardsRestClient): RewardsRestClient = impl @Provides fun rewardsProvider(impl: DefaultRewardsProvider): RewardsProvider = impl @Provides fun getDispatcherProvider(impl: DefaultDispatcherProvider): DispatcherProvider = impl @Provides fun getEventLogger(impl: DefaultEventLogger): EventLogger = impl @Provides fun rewardsConverter(impl: DefaultRewardsConverter): RewardsConverter<RewardItem> = impl @[Provides Singleton] fun networkAvailabilityProvider(impl: DefaultNetworkAvailabilityProvider): NetworkAvailabilityProvider = impl }
0
Kotlin
0
0
8cfd7ecb22c78be191f9ec794ee2019d1a2dce90
1,922
FetchRewards
Apache License 2.0
app/src/main/java/com/mobologicplus/kotlinmvpandroid/inject/component/FriendsDetailComponent.kt
sunil676
93,224,230
false
null
package com.mobologicplus.kotlinmvpandroid.inject.component import com.mobologicplus.kotlinmvpandroid.inject.module.FriendsDetailModule import com.mobologicplus.kotlinmvpandroid.inject.module.FriendsModule import com.mobologicplus.kotlinmvpandroid.inject.scope.PerActivity import com.mobologicplus.kotlinmvpandroid.ui.FriendsDetailFragment import dagger.Component /** * Created by 20125908 on 6/5/2017. */ @PerActivity @Component( modules = arrayOf(FriendsDetailModule::class)) interface FriendsDetailComponent { fun inject(friendsDetailFragment: FriendsDetailFragment) }
0
Kotlin
12
28
85f650174a5e200d346271c01440f93bf17d52dc
579
KotlinMVPAndroid
Apache License 2.0
fly-http/src/main/java/com/tiamosu/fly/http/cache/stategy/NoStrategy.kt
tiamosu
241,047,431
false
null
package com.tiamosu.fly.http.cache.stategy import com.tiamosu.fly.http.cache.RxCache import com.tiamosu.fly.http.cache.model.CacheResult import io.reactivex.rxjava3.core.Observable /** * 描述:网络加载,不缓存 * * @author tiamosu * @date 2020/3/10. */ @Suppress("unused") class NoStrategy : IStrategy { override fun <T> execute( rxCache: RxCache, cacheKey: String?, cacheTime: Long, source: Observable<T> ): Observable<CacheResult<T>> { return source.map { t -> CacheResult(false, t) } } }
0
null
5
9
cd937913f981303ab8a223ef1e508e8144c4ee2e
538
X-MVVMFly
Apache License 2.0
app/src/main/java/com/slava/taboolatest/articles/adapter/ArticlesDiffUtilCallBack.kt
dogsoldier85
271,006,646
false
null
package com.slava.taboolatest.articles.adapter import androidx.recyclerview.widget.DiffUtil import com.slava.taboolatest.articles.entities.BaseDataModel class ArticlesDiffUtilCallBack( private val oldList: List<BaseDataModel>, private val newList: List<BaseDataModel> ) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldList.size } override fun getNewListSize(): Int { return newList.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].type == newList[newItemPosition].type } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = oldList[oldItemPosition] val new = newList[newItemPosition] return old == new } }
0
Kotlin
1
0
df6bd891b556633649cda7d3460d78aae5c8bd48
841
TaboolaTestApp
Apache License 2.0
server/apigateway/src/main/kotlin/jetty/socket/MySessionSocket.kt
fzuleta
123,956,049
false
null
package jetty.socket import com.google.gson.GsonBuilder import com.google.gson.JsonObject import org.apache.shiro.subject.Subject import org.eclipse.jetty.websocket.api.Session import org.eclipse.jetty.websocket.api.annotations.* import java.io.IOException import java.util.concurrent.ConcurrentHashMap import javax.servlet.http.HttpSession @WebSocket(maxTextMessageSize = 64 * 1024) class MySessionSocket(var httpSession: HttpSession?, var reference: String, private var subject: Subject?) { var wsSession: Session? = null init { if (this.reference != "") { MySessionSocket.sockets.put(this.reference, this) } } /* ================================================================================================= */ @OnWebSocketConnect fun onOpen(wsSession: Session) { this.wsSession = wsSession } @OnWebSocketMessage fun onMessage(msg: String) { val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().create() try { val m = gson.fromJson(msg, JsonObject::class.java) var ret: JsonObject? = null var data: JsonObject? = null val command = if (m.has("command")) m.get("command").asString else null if (command != null) { m.remove("command") when (command) { "hookMeUp" -> { } }// Functions.trace("====== SOCKET HOOK"); // Functions.trace("DATA"); // Functions.trace(data); // if user_references and message if (data != null && data.has("user_references") && data.has("command")) { val user_references = data.get("user_references").asJsonArray for (i in 0 until user_references.size()) { val ref = user_references.get(i).asString val socket = MySessionSocket.getClient(ref) socket?.sendClient(data.toString()) } } } } catch (e: Exception) { e.printStackTrace() } System.out.printf("Got msg: %s%n", msg) } @OnWebSocketError fun onError(cause: Throwable) { cause.printStackTrace(System.err) } @OnWebSocketClose fun onClose(statusCode: Int, reason: String) { this.wsSession = null /* Cleanup */ if (this.reference != "") { this.subject = null if (MySessionSocket.sockets.containsKey(this.reference)) { MySessionSocket.sockets.remove(this.reference) } } } fun sendClient(str: String) { try { this.wsSession!!.remote.sendString(str) } catch (e: IOException) { e.printStackTrace() } } companion object { /* ================================================================================================= */ /* STATIC */ /* ================================================================================================= */ private val sockets = ConcurrentHashMap<String, MySessionSocket>() fun broadcastMessage(msg: String) { for (client in sockets.values) { client.sendClient(msg) } } fun getClient(reference: String): MySessionSocket? { var client: MySessionSocket? = null // Functions.trace("Finding: " + reference + " / " + MySessionSocket.sockets.containsKey(reference)); if (MySessionSocket.sockets.containsKey(reference)) { client = MySessionSocket.sockets[reference] } return client } } }
0
Kotlin
2
9
dcc54b04ae2a5f945eecc55a1108ca5453f1da3d
3,868
sample-users-microservice
Apache License 2.0
app/src/main/java/com/futag/futag/presentation/ui/fragment/login/register/RegisterViewModel.kt
FUTAG-Software
365,867,008
false
{"Kotlin": 158142}
package com.futag.futag.presentation.ui.fragment.login.register import android.net.Uri import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.futag.futag.model.UserModel import com.futag.futag.util.Constants.FOOD_NOTIFICATION import com.futag.futag.util.Constants.FUTAG_NOTIFICATION import com.futag.futag.util.Constants.IMAGES import com.futag.futag.util.Constants.USERS import com.google.firebase.Timestamp import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.storage.ktx.storage import java.util.* class RegisterViewModel : ViewModel() { private val auth = Firebase.auth private val db = Firebase.firestore private val storage = Firebase.storage val animation = MutableLiveData<Boolean>() val dataConfirmation = MutableLiveData<Boolean>() val errorMessage = MutableLiveData<String?>() fun registerToApp( email: String, password: String, name: String, surname: String, birthday: String, selectedImage: Uri?, ) { registerToAppUsingFirebase(email, password, name, surname, birthday, selectedImage) } private fun registerToAppUsingFirebase( email: String, password: String, name: String, surname: String, birthday: String, selectedImage: Uri?, ) { errorMessage.value = null animation.value = true auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { authState -> if (authState.isSuccessful) { val registrationTime = Timestamp.now() val activeUserUid = auth.currentUser?.uid if (selectedImage != null) { var imageReferenceLink: String? val profileImageName: String? val reference = storage.reference val uuid = UUID.randomUUID() profileImageName = "${uuid}.jpeg" val imageReference = reference.child(IMAGES).child(profileImageName) imageReference.putFile(selectedImage).addOnSuccessListener { val uploadedImageReference = reference.child(IMAGES).child(profileImageName) uploadedImageReference.downloadUrl.addOnSuccessListener { uri -> imageReferenceLink = uri.toString() if (imageReferenceLink != null) { val user = UserModel( name, surname, email, activeUserUid!!, birthday, imageReferenceLink, profileImageName, registrationTime ) db.collection(USERS) .document(activeUserUid).set(user) .addOnCompleteListener { success -> if (success.isSuccessful) { dataConfirmation.value = true animation.value = false FirebaseMessaging.getInstance() .subscribeToTopic(FOOD_NOTIFICATION) FirebaseMessaging.getInstance() .subscribeToTopic(FUTAG_NOTIFICATION) } }.addOnFailureListener { exception -> animation.value = false errorMessage.value = exception.localizedMessage } } } }.addOnFailureListener { exception -> animation.value = false errorMessage.value = exception.localizedMessage } } else { val user = UserModel( name, surname, email, activeUserUid!!, birthday, null, null, registrationTime ) db.collection(USERS) .document(activeUserUid).set(user).addOnCompleteListener { success -> if (success.isSuccessful) { dataConfirmation.value = true animation.value = false FirebaseMessaging.getInstance().subscribeToTopic( FOOD_NOTIFICATION ) FirebaseMessaging.getInstance().subscribeToTopic( FUTAG_NOTIFICATION ) } }.addOnFailureListener { exception -> animation.value = false errorMessage.value = exception.localizedMessage } } } }.addOnFailureListener { authError -> animation.value = false errorMessage.value = authError.localizedMessage } } }
0
Kotlin
1
9
61e221679ae4385fff7f0667f9e4e0e28195c127
5,802
FUTAG-Android
MIT License
app/src/main/kotlin/com/example/android/anko/sample/sign_in/bl/SignInBL.kt
vsouhrada
82,647,572
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 5, "Kotlin": 6}
package com.example.android.anko.sample.sign_in.bl import com.example.android.anko.sample.sign_in.model.AuthCredentials /** * @author vsouhrada * @since */ class SignInBL : ISignInBL { override fun checkUserCredentials(credentials: AuthCredentials): Boolean { return ("frosty".equals(credentials.username) && "snowman".equals(credentials.password)) } }
0
Kotlin
2
7
8e1928dff20a79aa96a62ff79acce2046c8d4e64
366
android-anko-sample
Apache License 2.0
shared/src/commonMain/kotlin/org/chiachat/app/ui/theme/CchIcons.kt
abueide
576,041,973
false
{"Kotlin": 53648, "Swift": 516, "Ruby": 103}
package org.chiachat.app.ui.theme import com.soywiz.korio.file.VfsFile import com.soywiz.korio.file.std.resourcesVfs enum class CchIcons(val file: VfsFile) { DARK_MODE(resourcesVfs["icons/material/dark_mode.png"]), LIGHT_MODE(resourcesVfs["icons/material/light_mode.png"]) }
0
Kotlin
0
0
eeb4dd4003380b9ff9f479e627b0ecb5f4dce50d
281
chiachat-ios-demo
MIT License
app/src/test/java/app/data/foundation/net/ErrorAdapterTest.kt
cfirmo33
84,732,848
false
{"Java Properties": 2, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Proguard": 1, "Java": 58, "Kotlin": 4}
/* * Copyright 2017 Victor Albertos * * 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. * * String json = "{\"message\":\"such a nice error\"}"; String prettified = adaptError(json); assertEquals(prettified, "such a nice error"); */ package app.data.foundation.net import org.junit.Assert.assertEquals import org.junit.Test class ErrorAdapterTest { @Test fun test() { val json = "{\"message\":\"such a nice error\"}" val prettified = adaptError(json) assertEquals(prettified, "such a nice error") } }
1
null
1
1
acf3a8e368fb99461440d022b3f81c639518d431
1,054
KDirtyAndroid
Apache License 2.0
src/main/kotlin/com/thelastpickle/tlpstress/commands/Info.kt
phanirajl
144,058,099
true
{"Kotlin": 54340, "Shell": 704}
package com.thelastpickle.tlpstress.commands import com.beust.jcommander.Parameter import com.thelastpickle.tlpstress.Plugin class Info : IStressCommand { @Parameter(required = true) var profile = "" override fun execute() { // Description // Schema // Field options val plugin = Plugin.getPlugins().get(profile)!! for(cql in plugin.instance.schema()) { println(cql) } } }
0
Kotlin
0
0
40cb2d28fdee18a06a6c38a81f121d9b83a9e004
454
tlp-stress
Apache License 2.0
gaia-sdk-java/gaia-sdk-graphql/src/main/kotlin/gaia/sdk/request/type/Code.kt
leftshiftone
218,051,248
false
{"Python": 597076, "TypeScript": 553203, "Kotlin": 517386, "JavaScript": 6976, "ANTLR": 2281}
package gaia.sdk.request.type import gaia.sdk.client.Type import gaia.sdk.request.intf.* import gaia.sdk.client.Input import gaia.sdk.Uuid import gaia.sdk.ISO8601 import gaia.sdk.Struct import gaia.sdk.request.input.* import gaia.sdk.request.enumeration.* /** * this type represents the code information */ class Code: Type() { /** * The code id */ fun identityId() { add {"identityId" } } /** * The code reference id */ fun reference() { add {"reference" } } /** * The name of the code */ fun qualifier() { add {"qualifier" } } /** * Detailed description about the code */ fun appendent() { add {"appendent" } } /** * The code dictionary. The key is a file name and the value is the code */ fun code() { add {"code" } } /** * The list of labels of the code */ fun labellist() { add {"labellist" } } /** * The type of the code */ fun type() { add {"type" } } }
8
Python
2
1
10190c1de4b2b5f1d4a5f014602c4ccc5c11bee4
1,097
gaia-sdk
MIT License
brd-android/buy/src/main/java/com/rockwallet/buy/ui/features/paymentmethod/PaymentMethodFragment.kt
rockwalletcode
598,550,195
false
null
package com.rockwallet.buy.ui.features.paymentmethod import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.rockwallet.buy.R import com.rockwallet.buy.databinding.FragmentPaymentMethodBinding import com.rockwallet.common.data.model.PaymentInstrument import com.rockwallet.common.ui.base.RockWalletView import com.rockwallet.common.ui.dialog.RockWalletBottomSheet import com.rockwallet.common.ui.dialog.RockWalletGenericDialog import com.rockwallet.common.utils.RockWalletToastUtil import kotlinx.coroutines.flow.collect import kotlinx.parcelize.Parcelize class PaymentMethodFragment : Fragment(), RockWalletView<PaymentMethodContract.State, PaymentMethodContract.Effect> { private lateinit var binding: FragmentPaymentMethodBinding private val viewModel: PaymentMethodViewModel by viewModels() private val adapter = PaymentMethodSelectionAdapter( clickCallback = { viewModel.setEvent(PaymentMethodContract.Event.PaymentInstrumentClicked(it)) }, optionsClickCallback = { viewModel.setEvent(PaymentMethodContract.Event.PaymentInstrumentOptionsClicked(it)) } ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment_payment_method, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentPaymentMethodBinding.bind(view) with(binding) { toolbar.setBackButtonClickListener { viewModel.setEvent(PaymentMethodContract.Event.BackClicked) } toolbar.setDismissButtonClickListener { viewModel.setEvent(PaymentMethodContract.Event.DismissClicked) } cvAddCard.setOnClickListener { viewModel.setEvent(PaymentMethodContract.Event.AddCardClicked) } val layoutManager = LinearLayoutManager(context) rvListCards.adapter = adapter rvListCards.layoutManager = layoutManager rvListCards.setHasFixedSize(true) } // collect UI state lifecycleScope.launchWhenStarted { viewModel.state.collect { render(it) } } // collect UI effect lifecycleScope.launchWhenStarted { viewModel.effect.collect { handleEffect(it) } } // listen for options bottom sheet dialog result parentFragmentManager.setFragmentResultListener(PaymentMethodOptionsBottomSheet.REQUEST_KEY, this) { _, bundle -> val result = bundle.getString(RockWalletBottomSheet.EXTRA_RESULT_KEY) val paymentInstrument = bundle.getParcelable<PaymentInstrument>( PaymentMethodOptionsBottomSheet.EXTRA_PAYMENT_INSTRUMENT ) if (result == PaymentMethodOptionsBottomSheet.RESULT_KEY_REMOVE && paymentInstrument != null) { viewModel.setEvent(PaymentMethodContract.Event.RemoveOptionClicked(paymentInstrument)) } } // listen for removal confirmation dialog result requireActivity().supportFragmentManager.setFragmentResultListener(PaymentMethodViewModel.REQUEST_CONFIRMATION_DIALOG, this) { _, bundle -> val result = bundle.getString(RockWalletGenericDialog.EXTRA_RESULT) val paymentInstrument = bundle.getParcelable<PaymentInstrument>( PaymentMethodViewModel.EXTRA_CONFIRMATION_DIALOG_DATA ) if (result == PaymentMethodViewModel.RESULT_CONFIRMATION_DIALOG_REMOVE && paymentInstrument != null) { viewModel.setEvent( PaymentMethodContract.Event.PaymentInstrumentRemovalConfirmed(paymentInstrument) ) } } } override fun render(state: PaymentMethodContract.State) { adapter.submitList(state.paymentInstruments) binding.toolbar.setShowDismissButton(state.showDismissButton) binding.content.isVisible = !state.initialLoadingIndicator binding.loadingIndicator.isVisible = state.initialLoadingIndicator binding.fullScreenLoadingView.root.isVisible = state.fullScreenLoadingIndicator } override fun handleEffect(effect: PaymentMethodContract.Effect) { when (effect) { is PaymentMethodContract.Effect.Back -> { parentFragmentManager.setFragmentResult( REQUEST_KEY, bundleOf(RESULT_KEY to effect.result) ) findNavController().popBackStack() } PaymentMethodContract.Effect.Dismiss -> activity?.finish() is PaymentMethodContract.Effect.AddCard -> findNavController().navigate( PaymentMethodFragmentDirections.actionAddCard(effect.flow) ) is PaymentMethodContract.Effect.ShowError -> RockWalletToastUtil.showError(binding.root, effect.message) is PaymentMethodContract.Effect.ShowToast -> RockWalletToastUtil.showInfo(binding.root, effect.message) is PaymentMethodContract.Effect.ShowConfirmationDialog -> RockWalletGenericDialog.newInstance(effect.args) .show(parentFragmentManager) is PaymentMethodContract.Effect.ShowOptionsBottomSheet -> PaymentMethodOptionsBottomSheet.newInstance(effect.paymentInstrument) .show(parentFragmentManager) } } companion object { const val REQUEST_KEY = "request_payment_method" const val RESULT_KEY = "result_payment_method" } sealed class Result: Parcelable { @Parcelize data class Cancelled(val dataUpdated: Boolean): Result() @Parcelize data class Selected(val paymentInstrument: PaymentInstrument): Result() } }
0
Kotlin
0
0
5eea47948c125678a59ada98bc95f865c81b8531
6,461
oss-wallet-android
MIT License
src/main/kotlin/pub/carkeys/logparse/DataCenter.kt
jlkeesey
499,976,228
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package pub.carkeys.logparse /** * Defines all the known data centers and their servers. */ class DataCenter(val name: String, val region: Region, val servers: Set<String>) { enum class Region { EUROPE, JAPAN, NORTH_AMERICA, } @Suppress("SpellCheckingInspection") companion object { private val aether = DataCenter( name = "Aether", region = Region.NORTH_AMERICA, servers = setOf( "Adamantoise", "Cactuar", "Faerie", "Gilgamesh", "Jenova", "Midgardsormr", "Sargatanas", "Siren", ) ) private val chaos = DataCenter( name = "Chaos", region = Region.EUROPE, servers = setOf( "Cerberus", "Louisoix", "Moogle", "Omega", "Ragnarok", "Spriggan", ) ) private val crystal = DataCenter( name = "Crystal", region = Region.NORTH_AMERICA, servers = setOf( "Balmung", "Brynhildr", "Coeurl", "Diabolos", "Goblin", "Malboro", "Mateus", "Zalera", ) ) private val elemental = DataCenter( name = "Elemental", region = Region.JAPAN, servers = setOf( "Aegis", "Atomos", "Carbuncle", "Garuda", "Gungir", "Kujata", "Ramuh", "Tonberry", "Typhon", "Unicorn", ) ) private val gaia = DataCenter( name = "Gaia", region = Region.JAPAN, servers = setOf( "Alexander", "Bahamut", "Durandal", "Fenrir", "Ifrit", "Ridill", "Tiamat", "Ultima", "Valefor", "Yojimbo", "Zeromus", ) ) private val light = DataCenter( name = "Light", region = Region.EUROPE, servers = setOf( "Lich", "Odin", "Phoenix", "Shiva", "Twintania", "Zodiark", ) ) private val mana = DataCenter( name = "Mana", region = Region.JAPAN, servers = setOf( "Anima", "Asura", "Belias", "Chocobo", "Hades", "Ixion", "Mandragora", "Masamune", "Pandaemonium", "Shinryu", "Titan", ) ) private val primal = DataCenter( name = "Primal", region = Region.NORTH_AMERICA, servers = setOf( "Behemoth", "Excalibur", "Exodus", "Famfrit", "Hyperion", "Lamia", "Leviathan", "Ultros", ) ) val DEFAULT = crystal private val mutableCenters = mapOf( aether.name to aether, chaos.name to chaos, crystal.name to crystal, elemental.name to elemental, gaia.name to gaia, light.name to light, mana.name to mana, primal.name to primal, ) fun addCenter(dataCenter: DataCenter) { } val centers: Map<String, DataCenter> = mutableCenters } }
0
Kotlin
0
0
683d0bfc539d8b984aa777740839ccaeeb3d0476
4,341
logparse
Apache License 2.0
src/main/kotlin/spritz/value/task/DefinedTaskValue.kt
SpritzLanguage
606,570,819
false
null
package spritz.value.task import spritz.SpritzEnvironment import spritz.error.interpreting.TypeMismatchError import spritz.interpreter.Interpreter import spritz.interpreter.RuntimeResult import spritz.interpreter.context.Context import spritz.lexer.position.Position import spritz.parser.node.Node import spritz.util.ANONYMOUS import spritz.util.RequiredArgument import spritz.value.NothingValue import spritz.value.NullValue import spritz.value.PrimitiveValue import spritz.value.Value /** * A value representing a task that has been defined in a script. * * @author surge * @since 03/03/2023 */ class DefinedTaskValue(identifier: String, val arguments: List<RequiredArgument>, val body: Node, val expression: Boolean, val returnType: Value?) : TaskValue(identifier) { override fun asJvmValue() = this override fun execute(passed: List<Value>, start: Position, end: Position, context: Context): RuntimeResult { val result = RuntimeResult() val interpreter = Interpreter() // we want to allow references to variables that have been defined in the current context // if this is an anonymous function, so we just check this identifier against the [ANONYMOUS] // identifier. val execContext = if (identifier == ANONYMOUS) context else generateExecuteContext() // attempt to check and populate the arguments result.register(this.checkAndPopulate(arguments, passed, start, end, execContext)) if (result.shouldReturn()) { return result } // execute the task val value = result.register(interpreter.visit(this.body, execContext)) if (result.error != null) { return result } // get the returned value val returnValue = (if (expression) value else null) ?: (result.returnValue ?: NothingValue().position(start, end)).givenContext(context) // make sure the returned value conforms to the given return type. if (returnValue !is NullValue && returnType != null && !(PrimitiveValue.check(returnValue, returnType) || returnValue.type == returnType.type)) { return result.failure(TypeMismatchError( "Returned value did not conform to type '${returnType.type}' (got '${returnValue.type}')", returnValue.start, returnValue.end, context )) } return result.success(returnValue) } override fun clone(): DefinedTaskValue { return DefinedTaskValue(identifier, arguments, body, expression, returnType).position(this.start, this.end).givenContext(this.context) as DefinedTaskValue } }
0
Kotlin
0
23
f50d81fa2d5aa7784ac4c76717603eea079c8db2
2,679
Spritz
The Unlicense
reactive-crypto-upbit/src/main/kotlin/com/njkim/reactivecrypto/upbit/UpbitRestClient.kt
xottohub
190,314,299
true
{"Kotlin": 285772, "Java": 66535}
/* * Copyright 2019 namjug-kim * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.njkim.reactivecrypto.upbit import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import com.njkim.reactivecrypto.core.common.model.account.Balance import com.njkim.reactivecrypto.core.common.model.currency.Currency import com.njkim.reactivecrypto.upbit.model.UpbitApiException import com.njkim.reactivecrypto.upbit.model.UpbitBalance import com.njkim.reactivecrypto.upbit.model.UpbitErrorResponse import org.springframework.http.codec.json.Jackson2JsonDecoder import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.util.MimeTypeUtils import org.springframework.web.reactive.function.client.ExchangeFilterFunction import org.springframework.web.reactive.function.client.ExchangeStrategies import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono import org.springframework.web.util.UriComponentsBuilder import java.time.Instant class UpbitRestClient { private val baseUrl = "https://api.upbit.com" inner class privateClient( val accessToken: String, val secretToken: String ) { fun getBalance(): Map<Currency, Balance> { val uri = UriComponentsBuilder.fromHttpUrl(baseUrl) .path("/v1/accounts") .encode() .build() .toUri() return createPrivateWebClient() .get() .uri(uri) .retrieve() .upbitErrorHandling() .bodyToMono<List<UpbitBalance>>() .block()!! .map { Pair( it.currency, Balance( it.currency, it.balance, it.locked ) ) } .toMap() } private fun createPrivateWebClient(): WebClient { val exchangeFilterFunction = ExchangeFilterFunction { request, next -> val query = request.url().query val algorithm = Algorithm.HMAC256(accessToken) val builder = JWT.create() .withClaim("access_key", secretToken) .withClaim("nonce", Instant.now().toEpochMilli().toString()) .withClaim("query", query) val token = builder.sign(algorithm) val headers = request.headers() headers.add("Authorization", "Bearer $token") next.exchange(request) } return defaultWebClientBuilder() .filter(exchangeFilterFunction) .build() } } fun defaultWebClientBuilder(): WebClient.Builder { val strategies = ExchangeStrategies.builder() .codecs { clientCodecConfigurer -> clientCodecConfigurer.defaultCodecs() .jackson2JsonEncoder( Jackson2JsonEncoder( UpbitJsonObjectMapper().objectMapper(), MimeTypeUtils.APPLICATION_JSON ) ) clientCodecConfigurer.defaultCodecs() .jackson2JsonDecoder( Jackson2JsonDecoder( UpbitJsonObjectMapper().objectMapper(), MimeTypeUtils.APPLICATION_JSON ) ) } .build() return WebClient.builder() .exchangeStrategies(strategies) } } fun WebClient.ResponseSpec.upbitErrorHandling(): WebClient.ResponseSpec = onStatus({ it.isError }, { clientResponse -> clientResponse.bodyToMono(UpbitErrorResponse::class.java) .map { UpbitApiException(clientResponse.statusCode(), it) } })
0
Kotlin
0
0
528df33d1d1adb8fe02d0c7a40fc6f10b18f57c4
4,579
reactive-crypto
Apache License 2.0
MissionControl/src/main/java/com/noahbres/missioncontrol/MissionControl.kt
NoahBres
185,848,998
false
null
package com.noahbres.missioncontrol import android.app.Activity import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import com.noahbres.missioncontrol.webserver.WebServer import com.noahbres.missioncontrol.websocket.SocketListener import com.noahbres.missioncontrol.websocket.WebSocket import org.java_websocket.handshake.ClientHandshake import java.util.* class MissionControl(activity : Activity, sendSensorData : Boolean) : SocketListener, SensorEventListener { companion object { const val TAG = "MissionControl" } private val activity = activity private val webServer = WebServer() private val webSocket = WebSocket() private var sendSensorData = sendSensorData private var sensorManager : SensorManager? = null private var sensorAccelerometer : Sensor? = null init { webSocket.addSocketListener(this) } fun start() { Log.i(TAG, "Mission Control starting") webServer.start() webSocket.start() // sensorManager = activity.getSystemService(Context.SENSOR_SERVICE) as SensorManager val localSensorManager = activity.getSystemService(Context.SENSOR_SERVICE) as SensorManager sensorManager = localSensorManager sensorAccelerometer = localSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) if(sendSensorData) turnOnSensorReading() } fun stop() { webServer.stop() webSocket.stop() } private fun turnOnSensorReading() { this.sendSensorData = true sensorManager?.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_GAME) } private fun turnOffSensorReading() { this.sendSensorData = false sensorManager?.unregisterListener(this) } override fun onOpen(conn: org.java_websocket.WebSocket, handshake: ClientHandshake) { webSocket.sendMessage(conn, LogModel("testing ", "init", Date())) } override fun onMessage(conn: org.java_websocket.WebSocket?, msg: String?) { Log.i("MissionControl", "Message: $msg") } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { } override fun onSensorChanged(event: SensorEvent?) { if(event?.sensor?.type != Sensor.TYPE_ACCELEROMETER) return // Log.i(TAG, "" + event.values[0] + ", " + event.values[1]) // webSocket.sendMessage() webSocket.broadcast(LogModel("${event.values[0]}, ${event.values[1]}", "accelerometer", Date())) } }
1
null
1
1
e5fef44a0f4f5821edb9ef4b4c658d5f69eda883
2,649
ftc-testing
MIT License
app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/core/mvp/MvpAnkoPresenter.kt
vsouhrada
77,144,360
false
null
package com.vsouhrada.kotlin.android.anko.fibo.core.mvp import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.hannesdorfmann.mosby.mvp.MvpView /** * @author vsouhrada * @since 0.1.0 */ open class MvpAnkoPresenter<A: MvpAnkoView, V : MvpView> : MvpBasePresenter<V>() { //protected val ui }
1
Kotlin
6
29
f13d80e93f3075708fc5e3bfd92799b51f12ada2
308
kotlin-anko-demo
Apache License 2.0
Myjava/projects/src/com/learn/day04/01. 封装.kt
turbohiro
158,934,823
false
{"Java": 96641, "Kotlin": 46735, "HTML": 27149, "Shell": 16087, "Batchfile": 6794}
package com.learn.day04 fun main(args:Array<String>){ val machine = Washmachine("Haier",12) machine.opendoor() println("放入牛仔裤") machine.closedoor() machine.Selectmode(1) machine.start() //setMotorspeed(1000) 这个函数不能被用户使用,因此用private函数 } /* 程序员A:定义洗衣机的类型 */ class Washmachine(var brand:String, var l:Int){ //保存用户输入的模式 var mode =0 //默认模式 全局变量 //01 开门 fun opendoor(){ println("打开洗衣机门。。。") } //02 关门 fun closedoor(){ println("关闭洗衣机门。。。") } fun start(){ when(mode){ 0-> { println("请选择模式") } 1->{ println("开始放水。。。") println("水放满了。。。") println("模式为轻柔模式") setMotorspeed(1000) println("衣服洗好了。。。") } 2->{ println("开始放水。。。") println("水放满了。。。") println("模式为狂柔模式") setMotorspeed(5000) println("衣服洗好了。。。") } else->{ println("模式设置错误") } } } //用户设置模式 fun Selectmode(mode:Int){ this.mode = mode } private fun setMotorspeed(speed:Int){ println("当前洗衣转速为${speed}") } }
1
null
1
1
55268b5c1c5e202641fd1acfce4e842d8567f9e0
1,289
kotlin_learning
MIT License
app/src/main/java/com/zzr/jetpacktest/kotlin_test/CoroutineDemo.kt
zrzhong
288,220,143
false
{"Gradle Kotlin DSL": 2, "Java Properties": 2, "Gradle": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 173, "XML": 104, "Java": 22, "HTML": 3, "INI": 1}
package com.zzr.jetpacktest.kotlin_test import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.flow.* /** * @Author zzr * @Desc * @Date 2020/11/30 */ fun main() { runBlocking(Dispatchers.Unconfined) { // testFlow1() // testFlow2() // testFlow3() channelTest() // testCon() } } private suspend fun testCon() { supervisorScope { // val a = async { // delay(1000) // println("1") // } // val b = async { // delay(100) // println("2") // } // a.await() // b.await() val result = withContext(Dispatchers.Default) { delay(200) println("1: ${System.currentTimeMillis()}") "hello" } val result2 = withContext(Dispatchers.Default) { delay(200) println("2: ${System.currentTimeMillis()}") "world" } println("result=$result ,result2=$result2") } } private fun CoroutineScope.channelTest() { //1.生成 channel val channel = Channel<Int>() //2.channel 发送数据 launch { for (i in 1..5) { delay(200) channel.send(i * i) } channel.close() } val channel2 = produce<Int> { for (i in 1..5) { delay(200) send(i * i) } close() } //3.channel接收数据 launch { // channel.receive() for (y in channel2) { println("get $y") } } } private suspend fun testFlow3() { //取消flow val f = flow { for (i in 1..3) { delay(500) println("emit $i") emit(i) } } withTimeoutOrNull(1600) { f.collect { delay(500) println("consume $it") } } println("cancel") } private suspend fun testFlow2() { flow { for (i in 1..3) { println("$i emit") emit(i) } }.filter { println("$it filter") it % 2 != 0 }.map { println("$it map") "${it * it} money" }.collect { println("i got $it") } } private suspend fun testFlow1() { createFlow() .flowOn(Dispatchers.IO) .catch { e -> println(e.printStackTrace()) } .onCompletion { t: Throwable? -> println("completion${t}") } .collect { println("数据消费 thread==${Thread.currentThread().name}") println(it) } } fun buffer() { flow { List(100) { emit(it) } }.buffer() } private fun createFlow2(): Flow<Int> { return channelFlow { send(1) withContext(Dispatchers.IO) { send(2) } } } private fun createFlow(): Flow<Int> { // return listOf("1","3").asFlow() // return setOf("5,"7).asFlow() // return (1..10).asFlow() println("数据产生 thread==${Thread.currentThread().name}") // return flowOf(1, 2, 3, 4, 5, 6) return flow { for (i in 1..10) { emit(i) } } } private suspend fun getResult(num: Int): Int { return withContext(Dispatchers.IO) { num * num } }
1
null
1
1
7765544fd6df3d615dadbe03f7df1daaac7aa1ab
3,379
JetpackTest
Apache License 2.0
src/jacksonMapper/JsonParser.kt
dijks090
125,920,387
false
null
package jacksonMapper import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.databind.JsonNode class JsonParser { fun parseJson(json: String) : List<Queue> { val mapper: ObjectMapper = ObjectMapper().registerModule(KotlinModule()) val module = SimpleModule() module.addDeserializer(Queue::class.java, ItemDeserializer()) mapper.registerModule(module) return mapper.readValue(json) } } class ItemDeserializer: StdDeserializer<Queue>(Queue::class.java) { override fun deserialize(parser: JsonParser, ctxt: DeserializationContext?): Queue { while (parser.nextToken() != JsonToken.END_OBJECT) { val node: JsonNode = parser.codec.readTree(parser) val prios = mutableListOf<Int>() node.get("queue-lengths").get("priorities")?.elements()?.forEach { prios.add( it.asInt()) } return Queue(node.get("queue-name").textValue(), prios.asReversed()) } return Queue() } } data class Queue(val name: String = "", val priorities: MutableList<Int>? = mutableListOf() )
0
Kotlin
0
0
27b67fd6034e56fcf62027ddf3e8886a7b5408aa
1,492
kotlin-koans
MIT License
clearnet/src/main/java/clearnet/models.kt
xelevra
176,962,795
true
{"Gradle": 6, "Markdown": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Kotlin": 51, "Java": 35, "Proguard": 1, "XML": 2, "INI": 1}
package clearnet.model import clearnet.InvocationBlockType import clearnet.InvocationStrategy import clearnet.RPCRequest import clearnet.interfaces.ConversionStrategy import clearnet.interfaces.IInvocationStrategy import clearnet.interfaces.IRequestExecutor import clearnet.interfaces.ISerializer import io.reactivex.subjects.ReplaySubject import io.reactivex.subjects.Subject import java.lang.reflect.Type abstract class PostParams( val httpRequestType: String, val requestParams: Map<String, String>, open val requestBody: Any?, val resultType: Type, val requestExecutor: IRequestExecutor, val invocationStrategy: MergedInvocationStrategy, val expiresAfter: Long, val conversionStrategy: ConversionStrategy, var headers: Map<String, String>, val bindable: Boolean = true, val maxBatchSize: Int = 1, val subject: Subject<Any> = ReplaySubject.create<Any>().toSerialized() ) { abstract val requestTypeIdentifier: String abstract val flatRequest: String abstract val cacheKey: String } class RpcPostParams( requestParams: Map<String, String>, override val requestBody: RPCRequest, resultType: Type, requestExecutor: IRequestExecutor, invocationStrategy: MergedInvocationStrategy, expiresAfter: Long, conversionStrategy: ConversionStrategy, headers: Map<String, String>, bindable: Boolean = true, maxBatchSize: Int, serializer: ISerializer) : PostParams( "POST", requestParams, requestBody, resultType, requestExecutor, invocationStrategy, expiresAfter, conversionStrategy, headers, bindable, maxBatchSize ) { override val requestTypeIdentifier = requestBody.method override val flatRequest: String override val cacheKey: String init { flatRequest = serializer.serialize(requestBody) val id = requestBody.id requestBody.id = 0 // we have to make this hook for making cache not store actual request id as key val ccacheKey = serializer.serialize(requestBody) requestBody.id = id cacheKey = ccacheKey } } class MergedInvocationStrategy(strategies: Array<InvocationStrategy>) { private val algorithm: Map<InvocationBlockType, IInvocationStrategy.Decision> private val metaData: MutableMap<String, String> operator fun get(index: InvocationBlockType): IInvocationStrategy.Decision = algorithm[index] ?: IInvocationStrategy.Decision(emptyArray(), emptyArray()) @Synchronized operator fun get(key: String) = metaData[key] @Synchronized operator fun set(key: String, value: String?) { if (value == null) metaData.remove(key) else metaData[key] = value } init { val mergedAlgorithm = mutableMapOf<InvocationBlockType, IInvocationStrategy.Decision>() val mergedMeta = mutableMapOf<String, String>() strategies.forEach { mergedAlgorithm.putAll(it.algorithm) mergedMeta.putAll(it.metaData) } algorithm = mergedAlgorithm metaData = mergedMeta } } data class RpcErrorResponse(val code: Long?, val message: String?, val data: Any?) { override fun toString() = "Code: $code, $message. \n $data" } data class RpcInnerError(var message: String?, var error: String?) { override fun toString() = "$error\n$message" } data class RpcInnerErrorResponse(val error: String?, val error_description: String?) { override fun toString() = "$error\n$error_description" }
0
Kotlin
0
0
e9a6e5658b358110d90d0cd7129a9d77ff18af49
3,664
clearnet
Apache License 2.0
road-runner-master/core/src/main/kotlin/com/acmerobotics/roadrunner/trajectory/TrajectoryBuilder.kt
FTC9977
236,473,259
false
{"Java": 342491, "Kotlin": 295529}
package com.acmerobotics.roadrunner.trajectory import com.acmerobotics.roadrunner.geometry.Pose2d import com.acmerobotics.roadrunner.path.Path import com.acmerobotics.roadrunner.profile.MotionState import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryConstraints private fun zeroPosition(state: MotionState) = MotionState(0.0, state.v, state.a, state.j) /** * Builder for trajectories with *dynamic* constraints. */ class TrajectoryBuilder private constructor( startPose: Pose2d?, startHeading: Double?, trajectory: Trajectory?, t: Double?, private val constraints: TrajectoryConstraints, private val start: MotionState, private val resolution: Double ) : BaseTrajectoryBuilder(startPose, startHeading, trajectory, t) { /** * Create a builder from a start pose and motion state. This is the recommended constructor for creating * trajectories from rest. */ @JvmOverloads constructor( startPose: Pose2d, startHeading: Double = startPose.heading, constraints: TrajectoryConstraints, start: MotionState = MotionState(0.0, 0.0, 0.0), resolution: Double = 0.25 ) : this(startPose, startHeading, null, null, constraints, start, resolution) /** * Create a builder from an active trajectory. This is useful for interrupting a live trajectory and smoothly * transitioning to a new one. */ @JvmOverloads constructor( trajectory: Trajectory, t: Double, constraints: TrajectoryConstraints, resolution: Double = 0.25 ) : this(null, null, trajectory, t, constraints, zeroPosition(trajectory.profile[t]), resolution) override fun buildTrajectory( path: Path, temporalMarkers: List<RelativeTemporalMarker>, spatialMarkers: List<SpatialMarker> ): Trajectory { val goal = MotionState(path.length(), 0.0, 0.0) return TrajectoryGenerator.generateTrajectory( path, constraints, start, goal, temporalMarkers, spatialMarkers, resolution ) } }
1
null
1
1
67352e90dbb1c5106e00548a81bd6c4544b0cbc6
2,140
Skystone_MP
MIT License
build-tools/src/main/kotlin/org/jetbrains/kotlin/TestDirectives.kt
mrakakuy
183,616,525
true
{"Kotlin": 8748196, "C++": 864291, "C": 126706, "Groovy": 122444, "Objective-C++": 88178, "Objective-C": 78062, "Swift": 72056, "JavaScript": 18399, "Python": 12840, "Shell": 11287, "Batchfile": 7437, "HTML": 5145, "Dockerfile": 2799, "Pascal": 1698, "CSS": 1656, "Java": 782}
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin import java.nio.file.Paths import java.util.regex.Pattern /** * Creates files from the given source file that may contain different test directives. * * @return list of file names to be compiled */ fun KonanTest.buildCompileList(outputDirectory: String): List<String> { val result = mutableListOf<String>() val srcFile = project.file(source) // Remove diagnostic parameters in external tests. val srcText = srcFile.readText().replace(Regex("<!.*?!>(.*?)<!>")) { match -> match.groupValues[1] } if (srcText.contains("// WITH_COROUTINES")) { val coroutineHelpersFileName = "$outputDirectory/helpers.kt" createFile(coroutineHelpersFileName, createTextForHelpers(true)) result.add(coroutineHelpersFileName) } val filePattern = Pattern.compile("(?m)// *FILE: *(.*)") val matcher = filePattern.matcher(srcText) if (!matcher.find()) { // There is only one file in the input val filePath = "$outputDirectory/${srcFile.name}" registerKtFile(result, filePath, srcText) } else { // There are several files var processedChars = 0 while (true) { val filePath = "$outputDirectory/${matcher.group(1)}" val start = processedChars val nextFileExists = matcher.find() val end = if (nextFileExists) matcher.start() else srcText.length val fileText = srcText.substring(start, end) processedChars = end registerKtFile(result, filePath, fileText) if (!nextFileExists) break } } return result } internal fun createFile(file: String, text: String) = Paths.get(file).run { parent.toFile() .takeUnless { it.exists() } ?.mkdirs() toFile().writeText(text) } internal fun registerKtFile(sourceFiles: MutableList<String>, newFilePath: String, newFileContent: String) { createFile(newFilePath, newFileContent) if (newFilePath.endsWith(".kt")) { sourceFiles.add(newFilePath) } }
1
Kotlin
0
2
1c6a2a711bc866b37a48076ff732413711bf966d
2,215
kotlin-native
Apache License 2.0
platform/lang-impl/src/com/intellij/internal/SetCaretVisualAttributesAction.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.CaretVisualAttributes import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.CheckBoxWithColorChooser import com.intellij.ui.EnumComboBoxModel import com.intellij.ui.UIBundle import com.intellij.ui.components.JBTextField import com.intellij.ui.layout.* import com.intellij.util.ObjectUtils class SetCaretVisualAttributesAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val editor = e.getData(CommonDataKeys.EDITOR) ?: return val carets = editor.caretModel.allCarets if (carets.isEmpty()) return val dialog = CaretVisualAttributesDialog(project, carets.first().visualAttributes) if (dialog.showAndGet()) { val attributes = dialog.attributes for (caret in carets) { caret.visualAttributes = attributes } } } override fun update(e: AnActionEvent) { val presentation = e.presentation val project = e.project val editor = ObjectUtils.tryCast(e.getData(CommonDataKeys.EDITOR), EditorImpl::class.java) presentation.isEnabled = project != null && editor != null } } @Suppress("DEPRECATION") class CaretVisualAttributesDialog(project: Project, attributes: CaretVisualAttributes?) : DialogWrapper(project) { private val colorChooser: CheckBoxWithColorChooser private var weight: CaretVisualAttributes.Weight = attributes?.weight ?: CaretVisualAttributes.Weight.NORMAL private var shape: CaretVisualAttributes.Shape = attributes?.shape ?: CaretVisualAttributes.Shape.DEFAULT private var thickness: Float = attributes?.thickness ?: 1.0f init { title = "Set CaretVisualAttributes" colorChooser = CheckBoxWithColorChooser(" ", attributes?.color != null, attributes?.color) init() } val attributes: CaretVisualAttributes get() = CaretVisualAttributes(colorChooser.color, weight, shape, thickness) override fun createCenterPanel() = panel { row("Colour:") { colorChooser() } row("Weight:") { comboBox(EnumComboBoxModel(CaretVisualAttributes.Weight::class.java), { weight }, { weight = it!! }) } row("Shape:") { comboBox(EnumComboBoxModel(CaretVisualAttributes.Shape::class.java), { shape }, { shape = it!! }) } row("Thickness:") { floatTextField({ thickness }, { thickness = it }, 0f, 1.0f) } } private fun Cell.floatTextField(getter: () -> Float, setter: (Float) -> Unit, min: Float, max: Float, columns: Int? = null): CellBuilder<JBTextField> { PropertyBinding(getter, setter) return textField( { getter().toString() }, { value -> value.toFloatOrNull()?.let { floatValue -> setter(floatValue.coerceIn(min, max)) } }, columns ).withValidationOnInput { val value = it.text.toFloatOrNull() when { value == null -> error(UIBundle.message("please.enter.a.number")) value < min || value > max -> error(UIBundle.message("please.enter.a.number.from.0.to.1", min, max)) else -> null } } } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
3,474
intellij-community
Apache License 2.0
idea/testData/inspectionsLocal/conventionNameCalls/replaceCallWithBinaryOperator/functionLiteralArgument.kt
JakeWharton
99,388,807
true
null
fun test() { class Test { operator fun plus(fn: () -> Test): Test = fn() } val test = Test() test.pl<caret>us { Test() } }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
159
kotlin
Apache License 2.0
src/main/kotlin/skywolf46/exp4kotlin/tokenizer/Tokenizer.kt
milkyway0308
441,351,663
true
{"Java": 154990, "Kotlin": 3635}
package skywolf46.exp4kotlin.tokenizer class Tokenizer { }
0
Java
0
0
b8455b2dfe36f2fd06ae9df8e357a19cd656be93
59
exp4kotlin
Apache License 2.0
app/src/main/java/com/franjo/android/bakingapp/presentation/base/BaseActivity.kt
fgrsetic
112,379,733
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 1, "JSON": 1, "Proguard": 1, "Java": 7, "XML": 44, "Kotlin": 46}
package com.franjo.android.bakingapp.presentation.base import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import com.franjo.android.bakingapp.R import com.franjo.android.bakingapp.databinding.ActivityBaseBinding import dagger.hilt.android.AndroidEntryPoint // This is a single activity application that uses the Navigation library // Content is displayed by Fragments @AndroidEntryPoint class BaseActivity : AppCompatActivity() { private var appBarConfiguration: AppBarConfiguration? = null private lateinit var binding: ActivityBaseBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_base) setSupportActionBar(binding.myToolbar) binding.myToolbar.title = "" val supportFragmentManager = supportFragmentManager val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment? val navController: NavController if (navHostFragment != null) { navController = navHostFragment.navController appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build() NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration!!) } } override fun onSupportNavigateUp(): Boolean { val navController = Navigation.findNavController(this, R.id.nav_host_fragment) return (NavigationUI.navigateUp(navController, appBarConfiguration!!) || super.onSupportNavigateUp()) } }
1
null
1
1
1cd3a99a1560453914bda665a0b10729fc8fb316
1,911
BakingApp
Apache License 2.0
idea/tests/testData/inspectionsLocal/replaceToStringWithStringTemplate/simple.kt
JetBrains
278,369,660
false
null
// WITH_RUNTIME fun test(): String { val x = 1 return x.<caret>toString() }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
83
intellij-kotlin
Apache License 2.0
app/src/main/java/com/example/weatherapp/data/AverageDayOfWeek.kt
Kirishhaa
668,767,900
false
null
package com.example.weatherapp.data data class AverageDayOfWeek( val dt: Long, val name: String, val temp: Double, val feelLikeTemp: Double, val iconID: String, )
0
Kotlin
0
0
63a3fd15ca1b372f5e0d9dde1898bcc66a2a00a6
183
WeatherLit
MIT License
platforms/android/Dezel/dezel/src/main/java/ca/logaritm/dezel/view/graphic/RadialGradient.kt
logaritmdev
174,257,253
false
{"SVG": 1, "Git Config": 1, "JSON with Comments": 2, "Markdown": 1, "JSON": 3, "Ignore List": 5, "EditorConfig": 1, "Text": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "XML": 29, "JavaScript": 4, "Kotlin": 197, "Java": 11, "C": 46, "C++": 121, "Makefile": 2, "Objective-C": 9, "OpenStep Property List": 3, "Swift": 185, "TSX": 17}
package ca.logaritm.dezel.view.graphic open class RadialGradient(value: String) { }
6
Kotlin
1
1
507022b806e0ffb91bfe87336c6642634c5123a0
85
dezel
MIT License
lib_appbasic/src/main/kotlin/android/os/ExtLooper.kt
CListery
494,658,527
false
{"Kotlin": 149275, "Java": 4863}
@file:JvmName("ExtLooper") package android.os /** * 检查调用线程是否在当前线程 */ val Looper.isCurrentLooper get(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { isCurrentThread } else { Thread.currentThread() == thread } }
0
Kotlin
0
0
9d85eb1abf83b0313805bf196a6fe65ac5504a87
295
AppBasic
MIT License
domain/src/main/java/com/chaitanya/domain/usecases/home/HomeUseCase.kt
Chaity243
277,506,748
false
null
package com.chaitanya.domain.usecases.home import com.chaitanya.domain.common.ResultState import com.chaitanya.domain.entity.HomeEntity import com.chaitanya.domain.usecases.BaseUseCase import io.reactivex.Single /** * Created by <NAME> on 28/5/2020. */ interface HomeUseCase : BaseUseCase { /* Single Observable is used here as list of Addresses will be fetched at once.*/ fun fetchAddresses( queryString: String, city: String ): Single<ResultState<HomeEntity.SearchResponse>> }
0
Kotlin
0
0
4da338bfd2f088636e314bb796ce81228ef2222d
512
Remote-Search-Clean-Architecture
MIT License
e-core-library/src/main/java/jp/team/eworks/e_core_library/view/SnackBarView.kt
entan05
357,849,286
false
null
package jp.team.eworks.e_core_library.view import android.content.Context import android.graphics.Outline import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.view.ViewOutlineProvider import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import jp.team.eworks.e_core_library.R import jp.team.eworks.e_core_library.view.view_interface.SnackBarViewInterface class SnackBarView: ConstraintLayout, SnackBarViewInterface { companion object { fun newInstance(context: Context, message: String): SnackBarView = SnackBarView(context).also { it.message = message } } override val hideDelayMillis: Long get() = 5000 private var _hiddenProcess: (() -> Unit)? = null override var hiddenProcess: (() -> Unit)? get() = _hiddenProcess set(value) { _hiddenProcess = value } var message: String set(value) { snackBarTextView.text = value } get() = snackBarTextView.text.toString() private val snackBarTextView: TextView constructor(context: Context): this(context, null) constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttrs: Int): super( context, attrs, defStyleAttrs ) { View.inflate(context, R.layout.view_snack_bar, this) snackBarTextView = findViewById(R.id.snack_bar_text) findViewById<View>(R.id.snack_bar_background).apply { outlineProvider = object: ViewOutlineProvider() { override fun getOutline(view: View?, outline: Outline?) { view?.let { val radius = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 6f, context.resources.displayMetrics ) outline?.setRoundRect(0, 0, it.width, it.height, radius) it.clipToOutline = true } } } setOnClickListener { requestHidden() } } } }
4
Kotlin
0
0
67d4e914ee1829bab13ae202891ad393f8051afa
2,344
eLibraries
Apache License 2.0
src/main/kotlin/me/friedfat/chiccenapi/bossbar/BossbarCooldown.kt
friedFat
680,492,584
false
null
package me.friedfat.chiccenapi.bossbar import me.friedfat.chiccenapi.utils.repeating import org.bukkit.boss.BarColor import org.bukkit.boss.BarFlag import org.bukkit.boss.BarStyle import kotlin.time.Duration abstract class BossbarCooldown(title: (Int) -> String, private val duration: Duration, barColor: BarColor, flags: Set<BarFlag> = setOf(), private var smooth: Boolean = true) : BossbarText(title(duration.inWholeSeconds.toInt()), barColor, BarStyle.SOLID, flags) { fun start(){ repeating { wait(100 * if(smooth) 1 else 10) bossbar.progress -= 1/duration.inWholeSeconds / if(smooth) 10 else 1 if(bossbar.progress <= 0){ super.remove() stop() onEnd() } } } abstract fun onEnd() }
0
Kotlin
0
0
3fd0ede374a38bd834822acd15b61dcf1b7229cd
812
ChiccenAPI
Apache License 2.0
app/src/main/java/com/dharam/offers/ui/dashboard/offers/OffersItemFragment.kt
Dharm1806
294,115,176
false
null
package com.dharam.offers.ui.dashboard.offers import android.app.ProgressDialog import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.google.gson.Gson import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType import com.smarteist.autoimageslider.SliderAnimations import com.smarteist.autoimageslider.SliderView import com.dharam.offers.R import com.dharam.offers.constants.Constants import com.dharam.offers.databinding.FragmentTabItemBinding import com.dharam.offers.repository.responseModel.Coupons import com.dharam.offers.repository.responseModel.OffersResponse import com.dharam.offers.repository.responseModel.SliderItem import com.dharam.offers.utills.Resource import com.dharam.offers.utills.Utills import java.util.* import kotlin.collections.ArrayList class OffersItemFragment : Fragment(), OnItemClickListener { private var position: Int = 0 private lateinit var binding: FragmentTabItemBinding private lateinit var mOffersViewModel: OffersViewModel private var mProgressDialog: ProgressDialog? = null private lateinit var mCouponsAdapter: CouponsAdapter private var mCouponsList = ArrayList<Coupons>() private lateinit var mSliderAdapterExample: SliderAdapterExample var latitude: String? = null var longitude: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate( inflater, R.layout.fragment_tab_item, container, false ) val view: View = binding.root binding.lifecycleOwner = this return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mProgressDialog = activity?.let { Utills.initializeProgressBar(it, R.style.AppTheme_WhiteAccent) } mOffersViewModel = ViewModelProviders.of(this).get(OffersViewModel::class.java) binding.offersViewModel = (mOffersViewModel) mSliderAdapterExample = SliderAdapterExample(requireActivity()); binding.imageSlider.setSliderAdapter(mSliderAdapterExample); binding.imageSlider.setIndicatorAnimation(IndicatorAnimationType.WORM); //set indicator animation by using IndicatorAnimationType. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!! binding.imageSlider.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); binding.imageSlider.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH); binding.imageSlider.setIndicatorSelectedColor(Color.WHITE); binding.imageSlider.setIndicatorUnselectedColor(Color.GRAY); binding.imageSlider.setScrollTimeInSec(4); //set scroll delay in seconds : binding.imageSlider.startAutoCycle(); showProgressBar() getOffersResponse() mCouponsAdapter = CouponsAdapter(mCouponsList, this, requireActivity()) binding.listOffers.adapter = mCouponsAdapter binding.listOffers.layoutManager = LinearLayoutManager( requireContext(), LinearLayoutManager.VERTICAL, false ) mOffersViewModel.getOffersResponse().observe(requireActivity(), Observer { when (it) { is Resource<OffersResponse> -> { handleResponse(it) } } }) binding?.tvMap.setOnClickListener { val gmmIntentUri = Uri.parse(java.lang.String.format(Locale.ENGLISH, "geo:%f,%f", latitude?.toFloat(), longitude?.toFloat())) val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) mapIntent.setPackage("com.google.android.apps.maps") startActivity(mapIntent) } binding.tvCall.setOnClickListener { Utills?.callPhoneNumber(requireActivity()) } } fun getOffersResponse() { if (Utills.verifyAvailableNetwork(activity = requireActivity())) { Log.e("api call making", "yes") mOffersViewModel.getOffersCount() } } /* @Override override fun onPrepareOptionsMenu(menu: Menu) { val item: MenuItem = menu.findItem(R.id.sos) Log.e("userType", mDashboardViewModel.getUserType()) item.isVisible = false //mDashboardViewModel.getUserType() == UserTypes.PATIENT.toString() }*/ private fun handleResponse(it: Resource<OffersResponse>) { Log.e("it.data", "${Gson().toJson(it)}, ${it.data}") when (it.status) { Resource.Status.LOADING -> showProgressBar() Resource.Status.SUCCESS -> { // showObservations(it.data?.body!!) if (it.data?.statusCode == 200) { binding.tvNoRecordFound.visibility = View.GONE showResponse(it.data) } else { binding.listOffers.visibility = View.GONE if (it.data == null || it.data.result == null) { binding.tvNoRecordFound.visibility = View.VISIBLE } if (it.data != null && it.data.APICODERESULT != null) { showError(it.data.APICODERESULT) } } } Resource.Status.ERROR -> { Log.e("error", "erryr") showError(it.exception!!) } } } private fun showResponse(data: OffersResponse?) { Log.e("size", "${Gson().toJson(data)}") if (data != null) { Constants.mOffersResponse = data } latitude = data?.result?.latitudes longitude = data?.result?.longitude hideProgressbar() if (data?.result?.banner != null) { //var bannerList:List<SliderItem> for (banner in data?.result?.banner) { mSliderAdapterExample.addItem(SliderItem(banner)) Log.e("banner", "$banner") } } if (data != null && !data?.result?.cupons?.isEmpty()) { binding.listOffers.visibility = View.VISIBLE mCouponsList.clear() mCouponsList.addAll(data.result.cupons) mCouponsAdapter.notifyDataSetChanged() binding.tvNoRecordFound.visibility = View.GONE } else { // Utills.showAlertMessage(requireActivity(), getString(R.string.no_record_found)) binding.tvNoRecordFound.visibility = View.VISIBLE binding.listOffers.visibility = View.GONE } } private fun showProgressBar() { //mProgressDialog?.show() } private fun showError(error: String) { showMessage(error) hideProgressbar() } private fun hideProgressbar() { // mProgressDialog?.hide() } private fun showMessage(message: String) { Toast.makeText(activity, message, Toast.LENGTH_LONG).show() } override fun onItemRedeem(mCoupons: Coupons) { Utills.hideKeyboard(requireActivity()) Toast.makeText(requireActivity(), "redeem ${mCoupons.title}", Toast.LENGTH_LONG).show() val bundle = bundleOf("observation" to mCoupons) // findNavController().navigate(R.id.homeToPatientDetails, bundle) } }
1
null
1
1
0422510bd133b12827f2e61cbec03c1a05cc2235
7,863
Tablayout-with-recycler-view-and-slider-in-kotlin-mvvm-and-data-binding
Apache License 2.0
src/main/kotlin/com/netflix/dgs/plugin/DgsCustomContext.kt
Netflix
418,599,475
false
{"Kotlin": 87975, "Java": 15193, "HTML": 4053}
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.dgs.plugin import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile data class DgsCustomContext( override val name: String, val psiClass: PsiElement, val psiFile: PsiFile ): NamedNavigationComponent { override val psiAnnotation = psiClass override val type = DgsComponentType.CUSTOM_CONTEXT }
6
Kotlin
11
22
12a6221e51700119fa26323f975cd235b53d6b96
941
dgs-intellij-plugin
Apache License 2.0
app/src/main/java/com/example/liziweather/logic/dao/PlaceDao.kt
freezeailis
631,947,522
false
null
package com.example.liziweather.logic.dao import android.content.Context import android.util.Log import androidx.core.content.edit import com.example.liziweather.LiziWeatherApplication import com.example.liziweather.logic.model.Place import com.google.gson.Gson import com.google.gson.GsonBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext object PlaceDao { private val sharedPreferences = LiziWeatherApplication.context. getSharedPreferences("LiziWeather", Context.MODE_PRIVATE) fun hasPlaceCache(): Boolean{ return sharedPreferences.contains("place") && sharedPreferences.getString("place", " ") != "" } fun getPlace(): Place? { return Gson().fromJson(sharedPreferences.getString("place", ""), Place::class.java) } fun savePlace(place: Place) { sharedPreferences.edit { putString("place", Gson().toJson(place)) apply() } } }
0
Kotlin
0
0
0b98ac2aa6522c3d07421d4c8e89b5cb96b13173
1,017
LiziWeather
Apache License 2.0
module_pics/src/main/java/com/fxc/pics/pic/network/interceptors/AuthorizationInterceptor.kt
T-Oner
116,654,059
false
null
package com.fxc.pics.pic.network.interceptors import com.fxc.pics.pic.network.url.APPLICATION_ID import okhttp3.Interceptor import okhttp3.Response /** * @author fxc * @date 2018/3/4 */ class AuthorizationInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val newRequest = chain.request().newBuilder() .addHeader("Authorization", "Client-ID $APPLICATION_ID") // .addHeader("client_id", APPLICATION_ID) .build() return chain.proceed(newRequest) } }
0
Kotlin
0
4
d01264e7a5fae74c13655a742bed79de674527d0
507
Pics
Apache License 2.0
mvvm2/src/main/java/me/mqn/mvvm2/di/RemoteModule.kt
Morteza-QN
864,434,747
false
{"Kotlin": 44088}
package me.mqn.mvvm2.di // @Module // @InstallIn(SingletonComponent::class) object RemoteModule { // @Named(Constants.Name.BASEURL) // @Provides // @Singleton // fun provideBaseUrl() = "BuildConfig.BASE_URL" // fun provideBaseUrl() = Api.BASE_URL // @Named(Constants.Name.CONNECTION_TIMEOUT) // @Provides // @Singleton // fun provideConnectionTimeout() = "Api.CONNECTION_TIMEOUT" // @Named(Constants.Name.PING_INTERVAL) // @Provides // @Singleton // fun providePingInterval() = "Api.PING_INTERVAL" /** Lenient *//* @Provides @Singleton fun provideGsonLenient(): Gson = GsonBuilder().setLenient().create() */ /** Interceptor *//* @Singleton @Provides fun provideAuthInterceptor( @ApplicationContext context: Context, sessionManager: SessionManager, ): AuthInterceptor = AuthInterceptor(context, sessionManager) */ /** Authenticator *//* @Singleton @Provides fun provideAuthAuthenticator( sessionManager: SessionManager, authApiService: AuthApiService, ): AuthAuthenticator = AuthAuthenticator(sessionManager, authApiService) */ /** level body*//* @Provides @Singleton fun provideBodyInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Level.BASIC } else { HttpLoggingInterceptor.Level.NONE } } */ /* @Provides @Singleton fun provideChucker(@ApplicationContext context: Context): Interceptor { // Config Chucker val chuckerCollector = ChuckerCollector( context = context, // Toggles visibility of the push notification showNotification = true, // Allows to customize the retention period of collected data // retentionPeriod = RetentionManager.Period.ONE_HOUR ) return ChuckerInterceptor.Builder(context) // The previously created Collector .collector(chuckerCollector) // The max body content length in bytes, after this responses will be truncated. .maxContentLength(250_000L) // List of headers to replace with ** in the Chucker UI .redactHeaders(Api.AUTHORIZATION) // Read the whole response body even when the client does not consume the response completely. // This is useful in case of parsing errors or when the response body // is closed before being read like in Retrofit with Void and Unit types. .alwaysReadResponseBody(true) // Use decoder when processing request and response bodies. // When multiple decoders are installed they are applied in an order they were added. // .addBodyDecoder(decoder) // Controls Android shortcut creation. Available in SNAPSHOTS versions only at the moment // .createShortcut(true) .build() } */ /** config okhttp client*//* @Provides @Singleton fun provideOkhttpClient( @Named(Constants.Name.CONNECTION_TIMEOUT) timeout: Long, @Named(Constants.Name.PING_INTERVAL) ping: Long, // tokenManager: TokenManager, authInterceptor: AuthInterceptor, // authAuthenticator: AuthAuthenticator, chuckerInterceptor: Interceptor, body: HttpLoggingInterceptor, ): OkHttpClient { return OkHttpClient.Builder() *//*.addInterceptor { chain -> val token = runBlocking { tokenManager.fetchToken().first().toString() } chain.proceed( request = chain.request().newBuilder().also { it.addHeader(Api.AUTHORIZATION, "${Api.PREFIX_JWT_TOKEN}$token") it.addHeader(Constants.ACCEPT, Constants.APPLICATION_JSON) it.addHeader(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON) }.build() ) }.also { client -> client.addInterceptor(body) client.addInterceptor(ChuckerInterceptor) }*//* // okhttp integration sentry integration .eventListener(eventListener = SentryOkHttpEventListener()) .addInterceptor( interceptor = SentryOkHttpInterceptor( captureFailedRequests = true, // By default, only HTTP client errors with a response code between 500 and 599 are captured as error events failedRequestStatusCodes = listOf( HttpStatusCodeRange(400, 599), ), // HTTP client errors from every target (.* regular expression) // failedRequestTargets = listOf("myapi.com") ), ) .addInterceptor(interceptor = body) .addInterceptor(interceptor = chuckerInterceptor) .addInterceptor(interceptor = authInterceptor) // .authenticator(authAuthenticator) .connectTimeout(timeout, TimeUnit.SECONDS) .readTimeout(timeout, TimeUnit.SECONDS) .writeTimeout(timeout, TimeUnit.SECONDS) // .retryOnConnectionFailure(true) .pingInterval( interval = ping, unit = TimeUnit.SECONDS, ) .protocols(listOf(Protocol.HTTP_1_1)) // todo: fix error wms wifi .build() } */ /** RetrofitBuilder*//* @Provides @Singleton fun provideRetrofitBuilder( @Named(Constants.Name.BASEURL) baseUrl: String, gson: Gson, okHttpClient: OkHttpClient, ): Retrofit.Builder = Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) */ /** AuthAPIService*//* @Provides @Singleton fun provideAuthAPIService(retrofit: Retrofit.Builder): AuthApiService = retrofit.build().create(AuthApiService::class.java) */ /** APIService*//* @Provides @Singleton fun provideAPIService(retrofit: Retrofit.Builder): ApiService = retrofit.build().create(ApiService::class.java) */ /* @Provides @Singleton fun provideInventoryAPIService(retrofit: Retrofit.Builder): InventoryApiService = retrofit.build().create(InventoryApiService::class.java) */ } // object NetworkModule // @Module // @InstallIn(SingletonComponent::class) // class NetworkModule { /* @Provides fun provideHttpClient(): HttpClient = MiniTalesHttpClientBuilder() .protocol(URLProtocol.HTTP) .host(BuildConfig.MINI_TALES_HOST) .port(8080) .build() */ /* @Provides fun provideRequestHandler(client: HttpClient) = RequestHandler(client) */ // }
0
Kotlin
0
0
f9ee95ea479cf95644ec486df3b60bd145d87bef
6,785
Sample-Code-Android
Apache License 2.0
api/src/main/java/danbroid/kipfs/utils/misc.kt
danbrough
409,364,798
false
null
package danbroid.kipfs.utils import java.nio.charset.Charset import java.util.* open class SingletonHolder<out T : Any, in A>(creator: (A) -> T) { private var creator: ((A) -> T)? = creator @Volatile private var instance: T? = null fun getInstance(arg1: A): T = instance ?: synchronized(this) { instance ?: creator!!.invoke(arg1).also { instance = it creator = null } } } open class SingletonHolder2<out T : Any, in A, in B>(creator: (A, B) -> T) { private var creator: ((A, B) -> T)? = creator @Volatile private var instance: T? = null fun getInstance(arg1: A, arg2: B): T = instance ?: synchronized(this) { instance ?: creator!!.invoke(arg1, arg2).also { instance = it creator = null } } } open class SingletonHolder3<out T : Any, in A, in B, in C>(creator: (A, B, C) -> T) { private var creator: ((A, B, C) -> T)? = creator @Volatile private var instance: T? = null fun getInstance(arg1: A, arg2: B, arg3: C): T = instance ?: synchronized(this) { instance ?: creator!!.invoke(arg1, arg2, arg3).also { instance = it creator = null } } } /** * Generate a random id. */ fun randomUUID() = UUID.randomUUID().toString().replace("-", "") private val charset = Charset.forName("Latin1") fun String.requestData(): ByteArray = toByteArray(charset)
0
Kotlin
0
1
1b9203c8fb6ff561781f741294a84b49323099d1
1,349
kipfs
Apache License 2.0
app/src/main/java/com/myapp/medled/screens/auth/LoginFragment.kt
F-Y-E-F
307,081,321
false
null
package com.myapp.medled.screens.auth import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.myapp.medled.R import com.myapp.medled.authentication.Authentication import com.myapp.medled.helpers.Helpers import kotlinx.android.synthetic.main.fragment_login.* class LoginFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_login, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupNavigation() signInButton.setOnClickListener { loginWithEmailAndPassword() } onEnterClicked() } private fun setupNavigation() { loginBackButton.setOnClickListener { requireActivity().onBackPressed() } } //--------| Login to app With Email and Password |------------ private fun loginWithEmailAndPassword() { val authentication: Authentication = Authentication() authentication.loginWithEmailAndPassword( loginEmailInput.text.toString(), loginPasswordInput.text.toString(), requireView() ) } //============================================================= //-----------------| Log in to app by enter click on keyboard when put the password |------------------ private fun onEnterClicked(){ Helpers().keyboardEnterButtonClick(loginPasswordInput){ signInButton.performClick() } } //===================================================================================================== }
0
Kotlin
0
1
e13b29a1be0cda44071d6326fff65025464dc0fd
1,790
medled-compiled-version
The Unlicense
ShaderBlur/src/main/java/good/damn/shaderblur/post/GaussianBlur.kt
GoodDamn
605,415,476
false
{"Kotlin": 23178}
package good.damn.shaderblur.post import android.graphics.Bitmap import android.graphics.Canvas import android.opengl.GLES20.* import android.opengl.GLUtils import android.util.Log import android.view.View import good.damn.shaderblur.opengl.OpenGLUtils import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.nio.ShortBuffer class GaussianBlur { private val TAG = "GaussianBlur" var texture: IntArray? = null var scaleFactor = 0.18f set(value) { field = value mSWidth = mWidth * scaleFactor mSHeight = mHeight * scaleFactor } private lateinit var mTargetView: View private var mSWidth = 0f private var mSHeight = 0f private var mWidth = 0f private var mHeight = 0f private lateinit var mVertexBuffer: FloatBuffer private lateinit var mIndicesBuffer: ShortBuffer private var mVBlurProgram = 0 private var mHBlurProgram = 0 private val mCanvas = Canvas() private var mInputBitmap: Bitmap? = null private var mBlurHDepthBuffer: IntArray? = null private var mBlurHFrameBuffer: IntArray? = null private val mVBlurShaderCode = "precision mediump float;" + "uniform vec2 u_res;" + "uniform sampler2D u_tex;" + "uniform float resFactor;" + "float gauss(float inp, float aa, float stDevSQ) {" + "return aa * exp(-(inp*inp)/stDevSQ);" + "}" + "vec2 downScale(float scale, vec2 inp) {" + "vec2 scRes = u_res * scale;" + "vec2 r = inp / scRes;" + "return vec2(float(int(r.x))*scRes.x, float(int(r.y))*scRes.y);" + "}" + "void main () {" + "float stDev = 8.0;" + "float stDevSQ = 2.0 * stDev * stDev;" + "float aa = 0.398 / stDev;" + "vec2 crs = vec2(gl_FragCoord.x, u_res.y-gl_FragCoord.y);" + "const float rad = 7.0;" + "vec4 sum = vec4(0.0);" + "float normDistSum = 0.0;" + "float gt;" + "for (float i = -rad; i <= rad;i++) {" + "gt = gauss(i,aa,stDevSQ);" + "normDistSum += gt;" + "sum += texture2D(u_tex, vec2(crs.x,crs.y+i)/u_res * resFactor) * gt;" + "}" + "gl_FragColor = sum / vec4(normDistSum);" + "}" private val mHBlurShaderCode = "precision mediump float;" + "uniform vec2 u_res;" + "uniform vec2 tex_res;" + "uniform sampler2D u_tex;" + "float gauss(float inp, float aa, float stDevSQ) {" + "return aa * exp(-(inp*inp)/stDevSQ);" + "}" + "void main () {" + "float stDev = 8.0;" + "float stDevSQ = 2.0 * stDev * stDev;" + "float aa = 0.398 / stDev;" + "const float rad = 7.0;" + "vec4 sum = vec4(0.0);" + "float normDistSum = 0.0;" + "float gt;" + "for (float i = -rad; i <= rad;i++) {" + "gt = gauss(i,aa,stDevSQ);" + "normDistSum += gt;" + "sum += texture2D(u_tex, vec2(gl_FragCoord.x+i,gl_FragCoord.y)/u_res) * gt;" + "}" + "gl_FragColor = sum / vec4(normDistSum);" + "}" constructor( targetView: View ) { mTargetView = targetView } fun create( vertexBuffer: FloatBuffer, indicesBuffer: ShortBuffer, mVertexShaderCode: String ) { mVertexBuffer = vertexBuffer mIndicesBuffer = indicesBuffer mVBlurProgram = glCreateProgram() glAttachShader( mVBlurProgram, OpenGLUtils.loadShader(GL_VERTEX_SHADER, mVertexShaderCode) ) glAttachShader( mVBlurProgram, OpenGLUtils.loadShader(GL_FRAGMENT_SHADER, mVBlurShaderCode) ) glLinkProgram(mVBlurProgram) mHBlurProgram = glCreateProgram() glAttachShader( mHBlurProgram, OpenGLUtils.loadShader(GL_VERTEX_SHADER, mVertexShaderCode) ) glAttachShader( mHBlurProgram, OpenGLUtils.loadShader(GL_FRAGMENT_SHADER, mHBlurShaderCode) ) glLinkProgram(mHBlurProgram) } fun layout( width: Int, height: Int ) { deleteFBO() mWidth = width.toFloat() mHeight = height.toFloat() mSWidth = mWidth * scaleFactor mSHeight = mHeight * scaleFactor mInputBitmap = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888) texture = intArrayOf(1) mBlurHFrameBuffer = intArrayOf(1) mBlurHDepthBuffer = intArrayOf(1) glGenFramebuffers(1, mBlurHFrameBuffer, 0) glGenRenderbuffers(1, mBlurHDepthBuffer, 0) glGenTextures(1, texture, 0) configTexture(texture!![0]) val w = mSWidth.toInt() val h = mSHeight.toInt() configBuffers(w,h,mBlurHDepthBuffer!![0]) } fun clean() { if (mVBlurProgram != 0) { glDeleteProgram(mVBlurProgram) } if (mHBlurProgram != 0) { glDeleteProgram(mHBlurProgram) } deleteFBO() } fun draw() { drawBitmap() horizontal() vertical() } private fun deleteFBO() { if (mInputBitmap != null && !mInputBitmap!!.isRecycled) { mInputBitmap!!.recycle() } if (mBlurHFrameBuffer != null) { glDeleteFramebuffers(1, mBlurHFrameBuffer!!, 0) } if (texture != null) { glDeleteTextures(1, texture!!, 0) } if (mBlurHDepthBuffer != null) { glDeleteRenderbuffers(1, mBlurHDepthBuffer!!, 0) } } private fun horizontal() { glViewport(0, 0, mSWidth.toInt(), mSHeight.toInt()) glBindFramebuffer(GL_FRAMEBUFFER, mBlurHFrameBuffer!![0]) glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture!![0], 0) glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mBlurHDepthBuffer!![0]) if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { Log.d(TAG, "onDrawFrame: FRAME_BUFFER_NOT_COMPLETE") return } glUseProgram(mHBlurProgram) glClearColor(0f, 1f, 0f, 1f) glClear(GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT) val positionHandle = glGetAttribLocation(mHBlurProgram, "position") glEnableVertexAttribArray(positionHandle) glVertexAttribPointer( positionHandle, 2, GL_FLOAT, false, 8, mVertexBuffer ) GLUtils.texImage2D(GL_TEXTURE_2D, 0, mInputBitmap, 0) glGenerateMipmap(GL_TEXTURE_2D) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture!![0]) glUniform1i(glGetUniformLocation(mHBlurProgram, "u_tex"), 0) glUniform2f( glGetUniformLocation(mHBlurProgram, "u_res"), mSWidth, mSHeight ) glUniform2f( glGetUniformLocation(mHBlurProgram, "tex_res"), mSWidth, mSHeight ) glDrawElements( GL_TRIANGLES, mIndicesBuffer.capacity(), // rect GL_UNSIGNED_SHORT, mIndicesBuffer ) glDisableVertexAttribArray(positionHandle) } private fun vertical() { glBindFramebuffer( GL_FRAMEBUFFER, 0 ) glUseProgram(mVBlurProgram) glViewport(0,0, mWidth.toInt(), mHeight.toInt() ) glClearColor(1f, 1f, 1f, 1f) glClear(GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT) val positionHandle = glGetAttribLocation(mVBlurProgram, "position") glEnableVertexAttribArray(positionHandle) glVertexAttribPointer( positionHandle, 2, GL_FLOAT, false, 8, mVertexBuffer ) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture!![0]) glUniform1i(glGetUniformLocation(mVBlurProgram, "u_tex"), 0) glUniform1f(glGetUniformLocation(mVBlurProgram, "resFactor"), scaleFactor) glUniform2f( glGetUniformLocation(mVBlurProgram, "u_res"), mWidth, mHeight ) glDrawElements( GL_TRIANGLES, mIndicesBuffer.capacity(), // rect GL_UNSIGNED_SHORT, mIndicesBuffer ) glDisableVertexAttribArray(positionHandle) } private fun configTexture(texture: Int) { glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) } private fun configBuffers( w:Int, h:Int, depthBuffer: Int ) { val buf = IntArray(w * h) val mTexBuffer = ByteBuffer.allocateDirect(buf.size * Float.SIZE_BYTES) .order(ByteOrder.nativeOrder()).asIntBuffer() glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, mTexBuffer ) glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer) glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, w, h ) } private fun drawBitmap() { mCanvas.setBitmap(mInputBitmap) mCanvas.translate(0f, -mTargetView.scrollY.toFloat()) mTargetView.draw(mCanvas) } }
0
Kotlin
0
1
93da7f1b59ef8df463917200216fb54e3f7779d3
10,483
DynamicBlurView_with_OpenGL_Android
MIT License
features/history/presentation/src/main/java/com/feragusper/smokeanalytics/features/history/presentation/navigation/HistoryNavigator.kt
feragusper
679,444,925
false
{"Kotlin": 257666, "Ruby": 645}
package com.feragusper.smokeanalytics.features.history.presentation.navigation import com.feragusper.smokeanalytics.libraries.architecture.presentation.navigation.MVINavigator class HistoryNavigator( val navigateUp: () -> Unit ) : MVINavigator { companion object { const val ROUTE = "history_graph" const val START = "history" } }
9
Kotlin
0
0
82aebba8d59beea3ffbd5179fd4b2e52047195bc
362
SmokeAnalytics
Apache License 2.0
atomik/src/iosMain/kotlin/me/kevinschildhorn/atomik/color/base/AtomikColor.kt
KevinSchildhorn
522,216,678
false
null
package me.kevinschildhorn.atomik.color.base import platform.UIKit.UIColor actual class AtomikColor actual constructor(hex: Long) { val platformColor: UIColor init { val a = (hex and 0xFF000000 shr 24).toDouble() / 255 val r = (hex and 0xFF0000 shr 16).toDouble() / 255 val g = (hex and 0xFF00 shr 8).toDouble() / 255 val b = (hex and 0xFF).toDouble() / 255 this.platformColor = UIColor(red = r, green = g, blue = b, alpha = a) } }
0
Kotlin
0
0
09e9acfeef8f019fcb1abe886c139f2b17871b7b
488
FoToPresenter
MIT License
mbloggerkit/src/main/java/com/daimler/mbloggerkit/export/MBLoggerKitFileProvider.kt
Daimler
199,815,262
false
null
package com.daimler.mbloggerkit.export import android.content.Context import android.net.Uri import android.os.Build import androidx.core.content.FileProvider import java.io.File class MBLoggerKitFileProvider : FileProvider() { companion object { fun getUriForFile(context: Context, file: File): Uri { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { getUriForFile(context, authority(context), file) } else { Uri.fromFile(file) } } /* MUST be the same as declared in the manifest. */ private fun authority(context: Context) = "${context.applicationContext.packageName}.provider" } }
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
719
MBSDK-Mobile-Android
MIT License
src/main/kotlin/com/pms/placemanagementsystemserverside/dto/ProfessorLackPostRequest.kt
sge-sistema-gerenciador-de-espacos
178,943,974
false
null
package com.pms.placemanagementsystemserverside.dto data class ProfessorLackPostRequest(val professorId: Long, val date: String)
0
Kotlin
0
0
d402ddb56d523062a4cfbff245a1c4d49aec7ba6
129
place-management-system-server-side
MIT License
app/src/main/java/com/rorpage/purtyweather/services/PurtyWeatherService.kt
jacobharris919
308,646,184
true
{"Kotlin": 27595, "Java": 1149}
package com.rorpage.purtyweather.services import android.app.job.JobParameters import android.app.job.JobService import com.rorpage.purtyweather.managers.ServiceManager import com.rorpage.purtyweather.util.WeatherUpdateScheduler import timber.log.Timber class PurtyWeatherService : JobService() { override fun onStartJob(params: JobParameters): Boolean { Timber.d("onStartJob") ServiceManager.startUpdateWeatherService(applicationContext) WeatherUpdateScheduler.scheduleJob(applicationContext) return true } override fun onStopJob(params: JobParameters): Boolean { Timber.d("onStopJob") return true } }
0
Kotlin
0
0
5c13f60714393eea3f77d4f535540b4be01c9539
669
purty-weather
MIT License
J-Slider/src/main/java/com/jummania/animations/Spinner.kt
Jumman04
716,177,357
false
{"Kotlin": 98806}
package com.jummania.animations import android.view.View import androidx.viewpager.widget.ViewPager import kotlin.math.abs /** * Created by Jummania on 17,November,2023. * Email: [email protected] * Dhaka, Bangladesh. */ internal class Spinner : ViewPager.PageTransformer { override fun transformPage(page: View, position: Float) { val angle = Math.toRadians((90 * position).toDouble()) page.translationX = -position * page.width page.scaleX = 0.7f + abs(position) / 3 page.scaleY = 0.7f + abs(position) / 3 page.rotation = angle.toFloat() } }
0
Kotlin
4
9
d7f706c890655d9b6a41a1884fd0ca5b17628641
607
Jummania-Slider
MIT License
net.akehurst.language/agl-processor/src/commonTest/kotlin/agl/sppt/test_SPPTParser.kt
annekekleppe
401,383,080
true
{"Kotlin": 1783981, "ANTLR": 64742, "Rascal": 17698, "Java": 6985}
/** * Copyright (C) 2018 Dr. <NAME> (http://dr.david.h.akehurst.net) * * 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 net.akehurst.language.agl.sppt import net.akehurst.language.agl.ast.GrammarBuilderDefault import net.akehurst.language.agl.ast.NamespaceDefault import net.akehurst.language.agl.grammar.grammar.ConverterToRuntimeRules import net.akehurst.language.agl.parser.InputFromString import net.akehurst.language.agl.runtime.structure.RuntimeRuleChoiceKind import net.akehurst.language.agl.runtime.structure.RuntimeRuleSetBuilder import net.akehurst.language.api.sppt.SPPTNode import kotlin.test.* class test_SPPTParser { @Test fun construct() { val gb = GrammarBuilderDefault(NamespaceDefault("test"), "test") val grammar = gb.grammar val converter = ConverterToRuntimeRules(grammar) val rrb = converter.builder val sut = SPPTParserDefault(rrb) assertNotNull(sut) } @Test fun leaf_literal() { val rrb = RuntimeRuleSetBuilder() rrb.literal("a") val sut = SPPTParserDefault(rrb) val input = InputFromString(10,"") val actual = sut.leaf("'a'", "a", input, 0,1) assertNotNull(actual) assertTrue(actual.isLeaf) assertFalse(actual.isPattern) assertFalse(actual.isEmptyLeaf) assertEquals("a", actual.matchedText) assertEquals(1, actual.matchedTextLength) assertFalse(actual.isBranch) assertFalse(actual.isSkip) } @Test fun leaf_pattern() { val rrb = RuntimeRuleSetBuilder() rrb.pattern("[a-z]") val sut = SPPTParserDefault(rrb) val input = InputFromString(10,"") val actual = sut.leaf("\"[a-z]\"", "a", input, 0,1) assertNotNull(actual) assertTrue(actual.isLeaf) assertTrue(actual.isPattern) assertFalse(actual.isEmptyLeaf) assertEquals("a", actual.matchedText) assertEquals(1, actual.matchedTextLength) assertFalse(actual.isBranch) assertFalse(actual.isSkip) } @Test fun emptyLeaf() { val rrb = RuntimeRuleSetBuilder() rrb.rule("a").empty() val sut = SPPTParserDefault(rrb) val input = InputFromString(10,"") val actual = sut.emptyLeaf("a", input, 0,1) assertNotNull(actual) assertTrue(actual.isLeaf) assertFalse(actual.isPattern) assertTrue(actual.isEmptyLeaf) assertEquals("", actual.matchedText) assertEquals(0, actual.matchedTextLength) assertFalse(actual.isBranch) assertFalse(actual.isSkip) } @Test fun branch_empty() { val rrb = RuntimeRuleSetBuilder() rrb.rule("a").empty() val sut = SPPTParserDefault(rrb) val input = InputFromString(10,"") val actual = sut.branch(input, "a", 0, listOf<SPPTNode>(sut.emptyLeaf("a", input, 0,1))) assertNotNull(actual) assertFalse(actual.isLeaf) assertFalse(actual.isEmptyLeaf) assertEquals("", actual.matchedText) assertEquals(0, actual.matchedTextLength) assertTrue(actual.isBranch) assertFalse(actual.isSkip) } @Test fun parse_leaf_literal() { val rrb = RuntimeRuleSetBuilder() rrb.literal("a") val sut = SPPTParserDefault(rrb) val treeString = """ 'a' """.trimIndent() val actual = sut.addTree(treeString) assertNotNull(actual) assertEquals(" 'a'", actual.toStringAll) } @Test fun parse_leaf_literal_backslash() { val rrb = RuntimeRuleSetBuilder() rrb.literal("BS","\\\\") val sut = SPPTParserDefault(rrb) val treeString = """ BS : '\' """.trimIndent() val actual = sut.addTree(treeString) assertNotNull(actual) assertEquals(" '\\'", actual.toStringAll) } @Test fun parse_leaf_pattern() { val rrb = RuntimeRuleSetBuilder() rrb.pattern("[a-z]") val sut = SPPTParserDefault(rrb) val treeString = """ "[a-z]" : 'a' """.trimIndent() val actual = sut.addTree(treeString) assertNotNull(actual) assertEquals("\"[a-z]\" : 'a'", actual.toStringAll.trim()) } @Test fun parse_branch_empty() { val rrb = RuntimeRuleSetBuilder() rrb.rule("a").empty() val sut = SPPTParserDefault(rrb) val treeString = """ a { §empty } """.trimIndent() val actual = sut.addTree(treeString) assertNotNull(actual) assertEquals(" a { §empty.a }", actual.toStringAll) } @Test fun parse_branch() { val rrb = RuntimeRuleSetBuilder() val lit = rrb.literal("a") rrb.rule("a").choice(RuntimeRuleChoiceKind.LONGEST_PRIORITY, lit) val sut = SPPTParserDefault(rrb) val treeString = """ a { 'a' } """.trimIndent() val actual = sut.addTree(treeString) assertNotNull(actual) assertEquals(" a { 'a' }", actual.toStringAll) } }
0
Kotlin
0
0
05b0049c4b50585ab1e9481706839c8fc5e661fd
5,662
net.akehurst.language
Apache License 2.0
core/src/org/river/exertion/ecs/system/SymbologySystem.kt
exertionriver
345,650,250
false
null
package org.river.exertion.ecs.system import com.badlogic.ashley.core.Entity import com.badlogic.ashley.systems.IntervalIteratingSystem import ktx.ashley.allOf import org.river.exertion.ai.internalSymbol.core.symbolAction.SymbolModifyAction import org.river.exertion.ai.internalSymbol.perceivedSymbols.AnxietySymbol import org.river.exertion.ai.internalSymbol.perceivedSymbols.MomentElapseSymbol import org.river.exertion.ai.messaging.SymbolMessage import org.river.exertion.ai.messaging.TimingTableMessage import org.river.exertion.ecs.component.ConditionComponent import org.river.exertion.ecs.component.MomentComponent import org.river.exertion.ecs.component.SymbologyComponent import org.river.exertion.ecs.entity.IEntity import org.river.exertion.ecs.entity.character.ICharacter import org.river.exertion.s2d.ui.UITimingTable class SymbologySystem : IntervalIteratingSystem(allOf(SymbologyComponent::class).get(), 1/10f) { override fun processEntity(entity: Entity) { //clear circularity check for moment SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay.circularity.clear() val entityMomentDelta = (-MomentComponent.getFor(entity)!!.systemMoment * this.interval) / ICharacter.getFor(entity)!!.moment //moment is in tenths of a second val entityMomentSymbolInstance = SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay.symbolDisplay.firstOrNull { it.symbolObj == MomentElapseSymbol } if (entityMomentSymbolInstance != null) SymbolModifyAction.executeImmediate(IEntity.getFor(entity)!!, SymbolMessage(symbolInstance = entityMomentSymbolInstance.apply { this.deltaPosition = entityMomentDelta })) //clear circularity check for anxiety SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay.circularity.clear() val entityAnxietySymbolInstance = SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay.symbolDisplay.firstOrNull { it.symbolObj == AnxietySymbol } if (entityAnxietySymbolInstance != null) { val entityAnxietyDelta = ConditionComponent.getFor(entity)!!.mIntAnxiety - entityAnxietySymbolInstance.position SymbolModifyAction.executeImmediate(IEntity.getFor(entity)!!, SymbolMessage(symbolInstance = entityAnxietySymbolInstance.apply { this.deltaPosition = entityAnxietyDelta })) } //rebuild plans from state of internalSymbolDisplay SymbologyComponent.getFor(entity)!!.internalSymbology.internalFocusDisplay.rebuildPlans(SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay, entityMomentDelta) SymbologyComponent.getFor(entity)!!.internalSymbology.internalSymbolDisplay.mergeAndUpdateFacets() UITimingTable.send(timingTableMessage = TimingTableMessage(label = "symbolSystem", value = interval)) UITimingTable.send(timingTableMessage = TimingTableMessage(label = "${ICharacter.getFor(entity)!!.entityName} moment delta", value = entityMomentDelta)) } }
0
Kotlin
0
2
058c7ec60da78953c3141a7e866047eb2f453a3b
3,057
koboldCave
MIT License
sbjfx-demo/src/main/kotlin/net/lustenauer/sbjfx/demo/views/HelloWorldView.kt
incluedu
484,928,873
false
null
package net.lustenauer.sbjfx.demo.views import net.lustenauer.sbjfx.lib.AbstractFxmlView import net.lustenauer.sbjfx.lib.anotations.FXMLView @FXMLView(value = "/helloWorld.fxml") class HelloWorldView : AbstractFxmlView()
0
Kotlin
0
1
6d730fa86df3da5719794866c44fdb94d9d9be01
224
sbjfx
MIT License
filesystem/src/commonMain/kotlin/posix/PosixFileMetadataView.kt
zhanghai
793,868,814
false
{"Kotlin": 345432}
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhanghai.kotlin.filesystem.posix import me.zhanghai.kotlin.filesystem.FileMetadataView public interface PosixFileMetadataView : FileMetadataView { override suspend fun readMetadata(): PosixFileMetadata public suspend fun setMode(mode: Set<PosixModeBit>) public suspend fun setOwnership(userId: Int? = null, groupId: Int? = null) }
0
Kotlin
2
16
c9d582ef847582572835369f3ab2234f8aecb0f7
954
filesystem-kt
Apache License 2.0
src/main/java/com/metriql/warehouse/spi/services/segmentation/SegmentationQueryGenerator.kt
metriql
370,169,788
false
null
package com.metriql.warehouse.spi.services.segmentation import com.metriql.report.segmentation.SegmentationQuery import com.metriql.warehouse.spi.bridge.WarehouseMetriqlBridge import com.metriql.warehouse.spi.services.ServiceQueryDSL import com.metriql.warehouse.spi.services.ServiceQueryGenerator import com.metriql.warehouse.spi.services.ServiceSupport typealias SegmentationQueryGenerator = ServiceQueryGenerator<Segmentation, SegmentationQuery, ServiceSupport> data class Segmentation( val columnNames: List<String>, val dimensions: List<WarehouseMetriqlBridge.RenderedField>, val measures: List<WarehouseMetriqlBridge.RenderedField>, val tableReference: String, val limit: Int?, val tableAlias: String, val joins: Set<String>?, val whereFilter: String?, val groups: Set<String>?, val groupIdx: Set<Int>?, val havingFilter: String?, val orderByIdx: Set<String>?, val orderBy: Set<String>? ) : ServiceQueryDSL
30
Kotlin
19
253
10fa42434c19d1dbfb9a3d04becea679bb82d0f1
968
metriql
Apache License 2.0
airin-gradle-plugin/src/main/kotlin/io/morfly/airin/plugin/ProjectTransformer.kt
Morfly
368,910,388
false
{"Kotlin": 84682}
package io.morfly.airin.plugin import io.morfly.airin.ComponentConflictResolution import io.morfly.airin.ComponentId import io.morfly.airin.ConfigurationName import io.morfly.airin.FeatureComponent import io.morfly.airin.ModuleComponent import io.morfly.airin.GradleModule import io.morfly.airin.GradleModuleDecorator import io.morfly.airin.MissingComponentResolution import io.morfly.airin.dsl.AirinProperties import io.morfly.airin.label.GradleLabel import io.morfly.airin.label.Label import io.morfly.airin.label.MavenCoordinates import org.gradle.api.Project import org.gradle.api.artifacts.ExternalDependency import org.gradle.api.artifacts.ProjectDependency data class ModuleConfiguration( val module: GradleModule, val component: ModuleComponent? ) interface ProjectTransformer { fun invoke(project: Project): ModuleConfiguration } class DefaultProjectTransformer( private val components: Map<ComponentId, ModuleComponent>, private val properties: AirinProperties, private val decorator: GradleModuleDecorator, private val artifactCollector: ArtifactDependencyCollector ) : ProjectTransformer { private val cache = mutableMapOf<ProjectPath, ModuleConfiguration>() override fun invoke(project: Project): ModuleConfiguration { cache[project.path]?.let { return it } val isSkipped = project.path in properties.skippedProjects val packageComponent = if (!isSkipped) project.pickPackageComponent(components, properties) else null val featureComponents = if (packageComponent == null) emptyList() else project.pickFeatureComponents(packageComponent) val module = GradleModule( name = project.name, isRoot = project.rootProject.path == project.path, label = GradleLabel(path = project.path, name = project.name), dirPath = project.projectDir.path, relativeDirPath = project.projectDir.relativeTo(project.rootDir).path, moduleComponentId = packageComponent?.id, featureComponentIds = featureComponents.map { it.id }.toSet(), originalDependencies = project.prepareDependencies() ) with(decorator) { module.decorate(project) } val config = ModuleConfiguration( module = module, component = module.moduleComponentId?.let(components::getValue) ) cache[project.path] = config return config } private fun Project.pickPackageComponent( components: Map<ComponentId, ModuleComponent>, properties: AirinProperties ): ModuleComponent? { val suitableComponents = components.values .filter { !it.ignored } .filter { it.canProcess(this) } return when { suitableComponents.isEmpty() -> when (properties.onMissingComponent) { MissingComponentResolution.Fail -> error("No package component found for $path") MissingComponentResolution.Ignore -> null } suitableComponents.size > 1 -> when (properties.onComponentConflict) { ComponentConflictResolution.Fail -> error("Unable to pick suitable package component for $path out of ${suitableComponents.map { it.javaClass }}") ComponentConflictResolution.UsePriority -> suitableComponents.maxByOrNull { it.priority } ComponentConflictResolution.Ignore -> null } else -> suitableComponents.first() } } private fun Project.pickFeatureComponents( component: ModuleComponent ): List<FeatureComponent> = component.subcomponents.values .filterIsInstance<FeatureComponent>() .filter { !it.ignored } .filter { it.canProcess(this) } private fun Project.prepareDependencies(): Map<ConfigurationName, List<Label>> = artifactCollector .invoke(this) .mapValues { (_, dependencies) -> dependencies.mapNotNull { when (it) { is ExternalDependency -> MavenCoordinates(it.group!!, it.name, it.version) is ProjectDependency -> with(it.dependencyProject) { GradleLabel(path = path, name = name) } else -> null } } } } fun ProjectTransformer.invoke(projects: Map<ProjectPath, Project>): Map<ProjectPath, ModuleConfiguration> = projects.mapValues { (_, project) -> invoke(project) }
1
Kotlin
3
31
0891ce67c744e9b49ddf0714247ae1b7131df03e
4,624
airin
Apache License 2.0
window/window-java/src/main/java/androidx/window/java/embedding/OverlayControllerCallbackAdapter.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.window.java.embedding import androidx.core.util.Consumer import androidx.window.RequiresWindowSdkExtension import androidx.window.WindowSdkExtensions import androidx.window.embedding.ActivityStack import androidx.window.embedding.OverlayController import androidx.window.embedding.OverlayCreateParams import androidx.window.embedding.OverlayInfo import androidx.window.java.core.CallbackToFlowAdapter import java.util.concurrent.Executor /** * An adapted interface for [OverlayController] that provides callback shaped APIs to report the * latest [OverlayInfo]. * * It should only be used if [OverlayController.overlayInfo] is not available. For example, an app * is written in Java and cannot use Flow APIs. * * @param controller an [OverlayController] that can be obtained by [OverlayController.getInstance]. * @constructor creates a callback adapter of [OverlayController.overlayInfo] flow API. */ class OverlayControllerCallbackAdapter(private val controller: OverlayController) { private val callbackToFlowAdapter = CallbackToFlowAdapter() /** * Registers a listener for updates of [OverlayInfo] that [overlayTag] is associated with. * * If there is no active overlay [ActivityStack], the reported [OverlayInfo.activityStack] and * [OverlayInfo.currentOverlayAttributes] will be `null`. * * Note that launching an overlay [ActivityStack] only supports on the device with * [WindowSdkExtensions.extensionVersion] equal to or larger than 5. If * [WindowSdkExtensions.extensionVersion] is less than 5, this flow will always report * [OverlayInfo] without associated [OverlayInfo.activityStack]. * * @param overlayTag the overlay [ActivityStack]'s tag which is set through * [OverlayCreateParams] * @param executor the [Executor] to dispatch the [OverlayInfo] change * @param consumer the [Consumer] that will be invoked on the [executor] when there is an update * to [OverlayInfo]. */ @RequiresWindowSdkExtension(5) fun addOverlayInfoListener( overlayTag: String, executor: Executor, consumer: Consumer<OverlayInfo> ) { callbackToFlowAdapter.connect(executor, consumer, controller.overlayInfo(overlayTag)) } /** * Unregisters a listener that was previously registered via [addOverlayInfoListener]. * * @param consumer the previously registered [Consumer] to unregister. */ @RequiresWindowSdkExtension(5) fun removeOverlayInfoListener(consumer: Consumer<OverlayInfo>) { callbackToFlowAdapter.disconnect(consumer) } }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
3,250
androidx
Apache License 2.0
Learning English App/app/src/main/java/com/tnmd/learningenglishapp/common/AppScaffold.kt
TranDatk
681,201,834
false
{"Kotlin": 304024}
package com.tnmd.learningenglishapp.common import android.annotation.SuppressLint import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.hilt.navigation.compose.hiltViewModel import com.tnmd.learningenglishapp.ui.theme.BackGroundColor import io.getstream.chat.android.ui.channel.list.viewmodel.ChannelListViewModel import kotlinx.coroutines.launch @SuppressLint("CoroutineCreationDuringComposition") @Composable fun AppScaffold( drawerState: DrawerState = rememberDrawerState(initialValue = DrawerValue.Open), onIconClicked: () -> Unit = {}, viewModel: ChannelListViewModel= hiltViewModel(), content: @Composable () -> Unit, ) { val scope = rememberCoroutineScope() ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet(drawerContainerColor = BackGroundColor) { AppDrawer( onIconClicked = onIconClicked, ) } }, content = content ) }
0
Kotlin
0
1
11d2e1598431b87bc71df80798fd6df77dba9a22
1,374
LearningEngishApplication
MIT License
src/main/kotlin/ui/IOField.kt
i-am-arunkumar
393,908,591
true
{"Kotlin": 100873}
package ui import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.ui.LabeledComponent import com.intellij.ui.EditorTextField import java.awt.Dimension import kotlin.math.min /** * Text Field UI used in editing Input/Output of Testcases */ class IOField(labelText: String, document: Document) : LabeledComponent<IOField.Field>() { init { text = labelText component = Field(document) } override fun getPreferredSize(): Dimension { val preferredSize = super.getPreferredSize() preferredSize.height = min(preferredSize.height, parent.height / 2) return preferredSize } class Field(document: Document) : EditorTextField(document, null, FileTypes.PLAIN_TEXT) { override fun createEditor(): EditorEx { val editor = super.createEditor() editor.isOneLineMode = false editor.setHorizontalScrollbarVisible(true) editor.setVerticalScrollbarVisible(true) updateBorder(editor) return editor } } }
0
null
0
0
4f72acfdb83c7917faa397818bd198b67fd3d6d8
1,156
AutoCp
MIT License
app/src/main/java/com/qlive/qnlivekit/MainActivity.kt
qiniu
538,322,435
false
{"Kotlin": 1143492, "Java": 484578}
package com.qlive.qnlivekit import android.Manifest import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.text.SpannableString import android.text.Spanned import android.text.TextUtils import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.view.View import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.qlive.sdk.QLive import com.qlive.sdk.QUserInfo import com.qlive.core.QLiveCallBack import com.qlive.qnlivekit.App.Companion.demo_url import com.qlive.qnlivekit.databinding.ActivityMainBinding import com.qlive.qnlivekit.uitil.* import com.qlive.uikitcore.activity.BaseBindingActivity import com.qlive.uikitcore.dialog.LoadingDialog import com.qlive.uikitcore.ext.asToast import com.qlive.uikitcore.ext.permission.PermissionAnywhere import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import okhttp3.FormBody import okhttp3.Request import okio.Buffer import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class MainActivity : BaseBindingActivity<ActivityMainBinding>() { override fun init() { PermissionAnywhere.requestPermission(this, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ) ) { _, _, _ -> } //登陆按钮 binding.btLoginLogin.setOnClickListener { val phone = binding.etLoginPhone.text.toString() ?: "" val code = binding.etLoginVerificationCode.text.toString() ?: "" if (phone.isEmpty()) { Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (code.isEmpty()) { Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (!binding.cbAgreement.isSelected) { Toast.makeText(this, "请同意 七牛云服务用户协议 和 隐私权政策", Toast.LENGTH_SHORT).show() return@setOnClickListener } // QLive.getLiveUIKit().getPage(RoomPage::class.java).anchorCustomLayoutID = R.layout.my_activity_room_pusher lifecycleScope.launch { LoadingDialog.showLoading(supportFragmentManager) try { //demo登陆 login(phone, code) SpUtil.get("login").saveData("phone", phone) //登陆 auth() //绑定用户信息 setUser() //启动跳转到直播列表 startActivity(Intent(this@MainActivity, DemoSelectActivity::class.java)) } catch (e: Exception) { e.printStackTrace() } finally { LoadingDialog.cancelLoadingDialog() } } } initOtherView() val lastPhone = SpUtil.get("login").readString("phone", "") if (!TextUtils.isEmpty(lastPhone)) { binding.etLoginPhone.setText(lastPhone) binding.etLoginVerificationCode.setText("8888") } } private suspend fun auth() = suspendCoroutine<Unit> { coroutine -> QLive.auth(object : QLiveCallBack<Void> { override fun onError(code: Int, msg: String?) { Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() coroutine.resumeWithException(Exception("getTokenError")) } override fun onSuccess(data: Void?) { coroutine.resume(Unit) } }) } /** * //绑定用户信息 绑定后房间在线用户能返回绑定设置的字段 */ private suspend fun setUser() = suspendCoroutine<Unit> { coroutine -> //绑定用户信息 绑定后房间在线用户能返回绑定设置的字段 QLive.setUser(QUserInfo().apply { // avatar ="https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg" avatar = UserManager.user!!.data.avatar //设置当前用户头像 nick = UserManager.user!!.data.nickname //设置当前用户昵称 extension = HashMap<String, String>().apply { put("phone", "13141616037") put("customFiled", "i am customFile") } }, object : QLiveCallBack<Void> { override fun onError(code: Int, msg: String?) { Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() coroutine.resumeWithException(Exception("getTokenError")) } override fun onSuccess(data: Void?) { coroutine.resume(Unit) } }) } //demo自己的登陆 private suspend fun login(phoneNumber: String, smsCode: String) = suspendCoroutine<Unit> { ct -> Thread { try { val body = FormBody.Builder() .add("phone", phoneNumber) .add("smsCode", smsCode) .build() val buffer = Buffer() body.writeTo(buffer) val request = Request.Builder() .url("${demo_url}/v1/signUpOrIn") // .addHeader(headerKey, headerValue) .addHeader("Content-Type", "application/x-www-form-urlencoded") .post(body) .build(); val call = OKHttpManger.okHttp.newCall(request); val resp = call.execute() val code = resp.code val userJson = resp.body?.string() val user = JsonUtils.parseObject(userJson, BZUser::class.java) UserManager.onLogin(user!!) ct.resume(Unit) } catch (e: Exception) { e.printStackTrace() ct.resumeWithException(Exception(e.message)) } }.start() } private fun timeJob() { lifecycleScope.launch(Dispatchers.Main) { try { binding.tvSmsTime.isClickable = false repeat(60) { binding.tvSmsTime.text = (60 - it).toString() delay(1000) } binding.tvSmsTime.text = "获取验证码" binding.tvSmsTime.isClickable = true } catch (e: Exception) { e.printStackTrace() } } } private fun initOtherView() { binding.tvSmsTime.setOnClickListener { val phone = binding.etLoginPhone.text.toString() ?: "" if (phone.isEmpty()) { return@setOnClickListener } lifecycleScope.launch(Dispatchers.IO) { try { val body = FormBody.Builder() .add("phone", phone) .build() val buffer = Buffer() body.writeTo(buffer) val request = Request.Builder() .url("${demo_url}/v1/getSmsCode") // .addHeader(headerKey, headerValue) .addHeader("Content-Type", "application/x-www-form-urlencoded") .post(body) .build(); val call = OKHttpManger.okHttp.newCall(request); val resp = call.execute() timeJob() } catch (e: Exception) { e.printStackTrace() } } } binding.cbAgreement.setOnClickListener { binding.cbAgreement.isSelected = !binding.cbAgreement.isSelected } val tips = "我已阅读并同意 七牛云服务用户协议 和 隐私权政策" val spannableString = SpannableString(tips) spannableString.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { WebActivity.start("https://www.qiniu.com/privacy-right", this@MainActivity) } }, tips.length - 5, tips.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { WebActivity.start("https://www.qiniu.com/user-agreement", this@MainActivity) } }, tips.length - 18, tips.length - 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan( StyleSpan(Typeface.BOLD), tips.length - 5, tips.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spannableString.setSpan( StyleSpan(Typeface.BOLD), tips.length - 18, tips.length - 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spannableString.setSpan( ForegroundColorSpan(Color.parseColor("#007AFF")), tips.length - 5, tips.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spannableString.setSpan( ForegroundColorSpan(Color.parseColor("#007AFF")), tips.length - 18, tips.length - 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) binding.cbAgreement.movementMethod = LinkMovementMethod.getInstance();//设置可点击状态 binding.cbAgreement.text = spannableString } }
0
Kotlin
4
5
6a13f808c2c36d62944e7a206a1524dba07a9cec
9,514
QNLiveKit_Android
MIT License
test/src/main/java/kort/tool/test/extension/TestCoroutineExtension.kt
kortchang
208,978,764
false
null
package kort.tool.test.extension import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.jupiter.api.extension.* /** * Created by Kort on 2019-07-04. */ @ExperimentalCoroutinesApi class TestCoroutineExtension : Extension, BeforeAllCallback, AfterAllCallback { private val testDispatcher = TestCoroutineDispatcher() override fun beforeAll(context: ExtensionContext?) { Dispatchers.setMain(testDispatcher) } override fun afterAll(context: ExtensionContext?) { Dispatchers.resetMain() } }
0
Kotlin
0
0
4bcfbab7aa9d6a456f8d14a896963a3bf35b2373
713
android-unit-test-extension
Apache License 2.0
differ/src/main/kotlin/org/analyzer/differ/Differ.kt
Mazurel
646,197,926
false
{"Kotlin": 57796, "Java": 43282, "Python": 15141}
package org.analyzer.kotlin.differ import java.io.File import org.analyzer.kotlin.log.LogFile import org.analyzer.kotlin.log.LogLine enum class DifferEntryType { OK, MISSING, ADDITIONAL } enum class LogType { BASELINE(), CHECKED } data class DifferEntry( val type: DifferEntryType, val self: LogLine?, val other: LogLine?, ) class Differ() { private val handlers: MutableMap<DifferEntryType, (DifferEntry) -> Unit> = mutableMapOf() private var lineLoadedHandler: ((LogType, LogLine) -> Unit)? = null public fun loadBaseline(logs: File): LogFile { val reader = logs.bufferedReader() return LogFile(reader) { if (this.lineLoadedHandler != null) { this.lineLoadedHandler!!(LogType.BASELINE, it) } } } public fun loadChecked(logs: File): LogFile { val reader = logs.bufferedReader() return LogFile(reader) { if (this.lineLoadedHandler != null) { this.lineLoadedHandler!!(LogType.CHECKED, it) } } } public fun compareLogs(baseline: LogFile, checked: LogFile) { val entries: MutableList<DifferEntry> = mutableListOf() if (checked.lines.size >= baseline.lines.size) { val matchedLinesFromBaseline = checked.matchWith(baseline) matchedLinesFromBaseline.withIndex().forEach { (i, lineFromBaseline) -> val checkedLine = checked.lines[i] if (lineFromBaseline == null) { entries.add(DifferEntry(DifferEntryType.ADDITIONAL, checkedLine, null)) } else { entries.add(DifferEntry(DifferEntryType.OK, checkedLine, lineFromBaseline)) } } } else { val matchedLinesFromChecked = baseline.matchWith(checked) matchedLinesFromChecked.withIndex().forEach { (i, lineFromChecked) -> val baselineLine = baseline.lines[i] if (lineFromChecked == null) { entries.add(DifferEntry(DifferEntryType.MISSING, null, baselineLine)) } else { entries.add(DifferEntry(DifferEntryType.OK, lineFromChecked, baselineLine)) } } } for (entry in entries) { handlers.get(entry.type).let { func -> if (func == null) { throw RuntimeException("Unresolvable differ entry: $entry") } func(entry) } } } fun onOk(handler: (LogLine, LogLine) -> Unit) { this.handlers.put(DifferEntryType.OK) { handler(it.self!!, it.other!!) } } fun onMissing(handler: (LogLine) -> Unit) { this.handlers.put(DifferEntryType.MISSING) { handler(it.other!!) } } fun onAdditional(handler: (LogLine) -> Unit) { this.handlers.put(DifferEntryType.ADDITIONAL) { handler(it.self!!) } } fun onLineLoaded(handler: (LogType, LogLine) -> Unit) { this.lineLoadedHandler = handler } }
0
Kotlin
0
0
d3bb29a8999d554176e9bf9c7cac8d33f058c4f1
2,755
analyzer
MIT License
src/main/kotlin/item/ItemFood.kt
jerbtrundles
590,724,669
false
null
package item import item.template.ItemTemplateFood class ItemFood( name: String, description: String, weight: Double, value: Int, keywords: List<String>, var bites: Int ) : ItemBase(name, description, weight, value, keywords) { constructor(template: ItemTemplateFood): this( template.name, template.description, template.weight, template.value, template.keywords, template.bites ) }
0
Kotlin
0
0
7bd191cab0484a812dba315e75827f61840bfa59
464
kotlin-mud
MIT License
solar/src/main/java/com/chiksmedina/solar/outline/__ShoppingEcommerce.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.outline import androidx.compose.ui.graphics.vector.ImageVector import com.chiksmedina.solar.OutlineSolar import com.chiksmedina.solar.outline.shoppingecommerce.Bag import com.chiksmedina.solar.outline.shoppingecommerce.Bag2 import com.chiksmedina.solar.outline.shoppingecommerce.Bag3 import com.chiksmedina.solar.outline.shoppingecommerce.Bag4 import com.chiksmedina.solar.outline.shoppingecommerce.Bag5 import com.chiksmedina.solar.outline.shoppingecommerce.BagCheck import com.chiksmedina.solar.outline.shoppingecommerce.BagCross import com.chiksmedina.solar.outline.shoppingecommerce.BagHeart import com.chiksmedina.solar.outline.shoppingecommerce.BagMusic import com.chiksmedina.solar.outline.shoppingecommerce.BagMusic2 import com.chiksmedina.solar.outline.shoppingecommerce.BagSmile import com.chiksmedina.solar.outline.shoppingecommerce.Cart import com.chiksmedina.solar.outline.shoppingecommerce.Cart2 import com.chiksmedina.solar.outline.shoppingecommerce.Cart3 import com.chiksmedina.solar.outline.shoppingecommerce.Cart4 import com.chiksmedina.solar.outline.shoppingecommerce.Cart5 import com.chiksmedina.solar.outline.shoppingecommerce.CartCheck import com.chiksmedina.solar.outline.shoppingecommerce.CartCross import com.chiksmedina.solar.outline.shoppingecommerce.CartLarge import com.chiksmedina.solar.outline.shoppingecommerce.CartLarge2 import com.chiksmedina.solar.outline.shoppingecommerce.CartLarge3 import com.chiksmedina.solar.outline.shoppingecommerce.CartLarge4 import com.chiksmedina.solar.outline.shoppingecommerce.CartLargeMinimalistic import com.chiksmedina.solar.outline.shoppingecommerce.CartPlus import com.chiksmedina.solar.outline.shoppingecommerce.Shop import com.chiksmedina.solar.outline.shoppingecommerce.Shop2 import com.chiksmedina.solar.outline.shoppingecommerce.ShopMinimalistic import kotlin.collections.List as KtList object ShoppingEcommerceGroup val OutlineSolar.ShoppingEcommerce: ShoppingEcommerceGroup get() = ShoppingEcommerceGroup private var _AllIcons: KtList<ImageVector>? = null val ShoppingEcommerceGroup.AllIcons: KtList<ImageVector> get() { if (_AllIcons != null) { return _AllIcons!! } _AllIcons = listOf( Bag, Bag2, Bag3, Bag4, Bag5, BagCheck, BagCross, BagHeart, BagMusic, BagMusic2, BagSmile, Cart, Cart2, Cart3, Cart4, Cart5, CartCheck, CartCross, CartLarge, CartLarge2, CartLarge3, CartLarge4, CartLargeMinimalistic, CartPlus, Shop, Shop2, ShopMinimalistic ) return _AllIcons!! }
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,589
SolarIconSetAndroid
MIT License
datastore/src/commonMain/kotlin/migrations/token.kt
niallkh
855,100,709
false
{"Kotlin": 1892361, "Swift": 21492}
package kosh.datastore.migrations import arrow.optics.dsl.at import arrow.optics.typeclasses.At import kosh.domain.entities.NetworkEntity import kosh.domain.entities.TokenEntity import kosh.domain.models.ChainId import kosh.domain.state.AppState import kosh.domain.state.tokens import kosh.domain.utils.Copy import kosh.domain.utils.pmap import kosh.ui.resources.Icons internal fun Copy<AppState>.token( chainId: ChainId, name: String, symbol: String, decimals: UByte, icon: String = symbol.lowercase(), ) { val token = TokenEntity( networkId = NetworkEntity.Id(chainId), name = name, symbol = symbol, decimals = decimals, icon = Icons.icon(icon), type = TokenEntity.Type.Native ) AppState.tokens.at(At.pmap(), token.id) set token }
0
Kotlin
0
3
e0149252019f8b47ceede5c0c1eb78c0a1e1c203
816
kosh
MIT License
src/test/kotlin/com/github/kotlin_everywhere/rpc/test/nested.kt
kotlin-everywhere
55,945,851
false
null
package com.github.kotlin_everywhere.rpc.test import com.github.kotlin_everywhere.rpc.Remote import org.junit.Assert.assertEquals import org.junit.Test class NestTest { @Test fun testNested() { class Admin : Remote() { val index = get<String>("/") } val remote = object : Remote() { val index = get<String>("/") val admin = Admin() } remote.apply { index { "index" } admin.apply { index { "admin.index" } } } assertEquals("index", remote.client.get("/").result<String>()) assertEquals("admin.index", remote.client.get("/admin/").result<String>()) remote.serverClient { assertEquals("index", it.get("/").result<String>()) assertEquals("admin.index", it.get("/admin/").result<String>()) } } @Test fun testPrefixSeparator() { class C(urlPrefix: String? = null) : Remote(urlPrefix) { val index = get<String>("/c") } class B : Remote() { val index = get<String>("/") } class A : Remote() { val index = get<String>("/") val b = B() val c = C("") } val a = A().apply { index { "a.index" } b.index { "b.index" } c.index { "c.index" } } assertEquals("a.index", a.client.get("/").result<String>()) assertEquals("b.index", a.client.get("/b/").result<String>()) assertEquals("c.index", a.client.get("/c").result<String>()) } }
0
Kotlin
0
0
cbd80592a3049b60ab405261498cb49e7a8de5e8
1,625
rpc-servlet
MIT License
app/src/main/java/com/unitewikiapp/unitewiki/views/dialogfragments/WritingDialogFragment.kt
jhj0517
656,711,299
false
{"Kotlin": 94842, "Java": 9115}
package com.unitewikiapp.unitewiki.views.dialogfragments import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import androidx.fragment.app.DialogFragment import com.unitewikiapp.unitewiki.databinding.DialogWritingcancelBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class WritingDialogFragment: DialogFragment(){ lateinit var onButtonClick: OnDialogButtonClick override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return activity?.let { val builder = AlertDialog.Builder(it) val binding = DialogWritingcancelBinding.inflate(LayoutInflater.from(context)) binding.YES.setOnClickListener { onButtonClick.onOKClick() } binding.NO.setOnClickListener { onButtonClick.onNOClick() } builder.setView(binding.root) builder.create() } ?: throw IllegalStateException("Activity cannot be null") } interface OnDialogButtonClick{ fun onOKClick() fun onNOClick() } fun setListener(onDialogButtonClick: OnDialogButtonClick){ this.onButtonClick = onDialogButtonClick } }
0
Kotlin
0
0
77cc04f97829de79da04895ce5442aaf69bf59a5
1,261
UniteWiki
Apache License 2.0
plugins/core/src/main/kotlin/de/fayard/refreshVersions/core/extensions/text/CharSequence.kt
Splitties
150,827,271
false
{"Kotlin": 808317, "Shell": 2793, "Just": 1182, "Java": 89, "Groovy": 24}
package de.fayard.refreshVersions.core.extensions.text internal fun CharSequence.indexOfPrevious(char: Char, startIndex: Int): Int { if (startIndex !in 0..lastIndex) throw IndexOutOfBoundsException(startIndex) for (i in startIndex downTo 0) { val c = this[i] if (c == char) return i } return -1 } internal inline fun CharSequence.indexOfFirst( startIndex: Int, predicate: (Char) -> Boolean ): Int { if (startIndex !in 0..lastIndex) throw IndexOutOfBoundsException(startIndex) for (i in startIndex..lastIndex) { if (predicate(this[i])) return i } return -1 } internal interface SkippableIterationScope { fun skipIteration(offset: Int) } internal inline fun CharSequence.forEachIndexedSkippable( action: SkippableIterationScope.(index: Int, c: Char) -> Unit ) { var index = 0 val scope = object : SkippableIterationScope { override fun skipIteration(offset: Int) { index += offset } } while (index < length) { val currentIndex = index++ val c = this[currentIndex] scope.action(currentIndex, c) } }
113
Kotlin
109
1,606
df624c0fb781cb6e0de054a2b9d44808687e4fc8
1,144
refreshVersions
MIT License
jetbrains-core/src/software/aws/toolkits/jetbrains/services/sqs/actions/PurgeQueueNodeAction.kt
JetBrains
223,485,227
true
{"Kotlin": 4152201, "C#": 95783, "Java": 35575, "Dockerfile": 1985}
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.sqs.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import software.amazon.awssdk.services.sqs.SqsClient import software.aws.toolkits.jetbrains.core.awsClient import software.aws.toolkits.jetbrains.core.explorer.actions.SingleResourceNodeAction import software.aws.toolkits.jetbrains.services.sqs.SqsQueueNode import software.aws.toolkits.resources.message class PurgeQueueNodeAction : SingleResourceNodeAction<SqsQueueNode>(message("sqs.purge_queue.action")), DumbAware { override fun actionPerformed(selected: SqsQueueNode, e: AnActionEvent) { val project = selected.nodeProject val client: SqsClient = project.awsClient() PurgeQueueAction(project, client, selected.queue).actionPerformed(e) } }
6
Kotlin
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
957
aws-toolkit-jetbrains
Apache License 2.0
Dropspot/app/src/main/java/com/example/dropspot/binding/CustomBindingAdapters.kt
bertve
602,652,590
false
null
package com.example.dropspot.binding import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import androidx.databinding.BindingAdapter import com.example.dropspot.R import com.example.dropspot.data.model.AppUser import com.google.android.material.navigation.NavigationView @BindingAdapter("rankingImgFromScore") fun bindRankingImgFromScore(view: ImageView, score: Int) { when (score) { 0 -> view.setImageResource(R.drawable.ic_zero) 1 -> view.setImageResource(R.drawable.ic_one) 2 -> view.setImageResource(R.drawable.ic_two) 3 -> view.setImageResource(R.drawable.ic_three) 4 -> view.setImageResource(R.drawable.ic_four) 5 -> view.setImageResource(R.drawable.ic_five) else -> view.setImageResource(R.drawable.ic_zero) } } @BindingAdapter("LikeImgFromLiked") fun bindLikeImgFromSpotAlreadyLiked(view: ImageView, alreadyLiked: Boolean) { if (alreadyLiked) { view.setImageResource(R.drawable.ic_like_filled) } else { view.setImageResource(R.drawable.ic_like_outlined) } } @BindingAdapter("navViewPresentationFromUser") fun bindNavViewFromUser(v: NavigationView, user: AppUser?) { if (user != null) { v.getHeaderView(0).findViewById<TextView>(R.id.nav_username).text = user.username v.getHeaderView(0).findViewById<TextView>(R.id.nav_username).visibility = View.VISIBLE v.getHeaderView(0).findViewById<ProgressBar>(R.id.user_loading).visibility = View.GONE } else { v.getHeaderView(0).findViewById<TextView>(R.id.nav_username).visibility = View.GONE v.getHeaderView(0).findViewById<ProgressBar>(R.id.user_loading).visibility = View.VISIBLE } }
0
Kotlin
0
0
998b366a0fdaf7993d0ee2383423e076c7c5ce06
1,754
dropspot-android
MIT License
src/main/kotlin/dev/d1s/beamimageboarduploader/service/StorageService.kt
d1snin
720,253,583
false
{"Kotlin": 55691, "Shell": 205, "Dockerfile": 171}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.d1s.beamimageboarduploader.service import dev.d1s.beamimageboarduploader.bot.TelegramBot import dev.d1s.beamimageboarduploader.config.ApplicationConfig import dev.d1s.beamimageboarduploader.s3.MinioClientFactory import dev.inmo.tgbotapi.extensions.api.files.downloadFileStream import dev.inmo.tgbotapi.extensions.api.get.getFileAdditionalInfo import dev.inmo.tgbotapi.types.files.PhotoSize import io.ktor.http.* import io.ktor.utils.io.jvm.javaio.* import io.minio.PutObjectArgs import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.koin.core.component.KoinComponent import org.koin.core.component.inject import org.lighthousegames.logging.logging interface StorageService { suspend fun uploadFile(photoSize: PhotoSize): Result<Url> } class DefaultStorageService : StorageService, KoinComponent { private val minioClientFactory by inject<MinioClientFactory>() private val minio by lazy { minioClientFactory.minio } private val bot by inject<TelegramBot>() private val requestExecutor by lazy { bot.requestExecutor } private val config by inject<ApplicationConfig>() private val mutex = Mutex() private val log = logging() override suspend fun uploadFile(photoSize: PhotoSize): Result<Url> = runCatching { mutex.withLock { val bucket = config.minio.bucketName val fileId = photoSize.fileId val uniqueFileId = photoSize.fileUniqueId val objectName = "$uniqueFileId.jpg" log.i { "Uploading file '$objectName' to bucket '$bucket'" } val file = requestExecutor.downloadFileStream(fileId).toInputStream() val fileSize = requestExecutor.getFileAdditionalInfo(fileId).fileSize requireNotNull(fileSize) { "File size is null" } log.d { "File size: $fileSize" } val args = PutObjectArgs.builder() .bucket(bucket) .`object`(objectName) .stream(file, fileSize, DEFAULT_PART_SIZE) .contentType(ContentType.Image.JPEG.toString()) .build() minio.putObject(args) val url = URLBuilder(config.minio.endpoint).apply { path(bucket, objectName) }.build() url } } private companion object { private const val DEFAULT_PART_SIZE = -1L } }
0
Kotlin
0
0
9238666d0532bed60ab93cd3079ddd29cd554a7c
3,240
beam-imageboard-uploader
Apache License 2.0
src/main/kotlin/no/nav/syfo/client/ClientsEnvironment.kt
navikt
602,146,320
false
null
package no.nav.syfo.client data class ClientsEnvironment( val padm2: ClientEnvironment, val syfotilgangskontroll: ClientEnvironment, val dialogmeldingpdfgen: OpenClientEnvironment, val dokarkiv: ClientEnvironment, ) data class ClientEnvironment( val baseUrl: String, val clientId: String, ) data class OpenClientEnvironment( val baseUrl: String, )
3
Kotlin
0
0
5cf87000d5a2970514473f63fb44f03b2edc8dd5
379
isbehandlerdialog
MIT License
app/src/main/java/com/vshyrochuk/topcharts/screens/chartpreview/ReleaseDateFormatter.kt
Mc231
524,970,692
false
null
package com.vshyrochuk.topcharts.screens.chartpreview import java.text.SimpleDateFormat import java.util.Locale object ReleaseDateFormatter { fun format( releaseDate: String, inputFormat: String = "yyyy-MM-dd", outputFormat: String = "MMM d, yyyy", locale: Locale = Locale.US ): String { val inputFormatter = SimpleDateFormat(inputFormat, locale) try { val inputDate = inputFormatter.parse(releaseDate) val outputFormatter = SimpleDateFormat(outputFormat, locale) if (inputDate != null) { return outputFormatter.format(inputDate) } return releaseDate } catch (e: Exception) { e.printStackTrace() return releaseDate } } }
0
Kotlin
0
0
8b9f6ae00d38e69b81cc466adb14bb7d2b48c20f
800
Top-Charts
MIT License
android/app/src/main/kotlin/com/dnk/drag3/MainActivity.kt
dkumamoto
474,433,905
false
{"Dart": 3736, "Swift": 1158, "Kotlin": 118, "Objective-C": 38}
package com.dnk.drag3 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
0bd12a1a23abab881d534ea6ed45ee8f50564d5d
118
flutter-drag-3
MIT License
androidApp/src/main/java/com/saitawngpha/movienoshareui/android/home/MovieListItem.kt
saitawngpha
785,641,482
false
{"Kotlin": 34408, "Swift": 6982}
package com.saitawngpha.movienoshareui.android.home import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.saitawngpha.movienoshareui.android.R import com.saitawngpha.movienoshareui.domain.model.Movie /** * @Author: ၸၢႆးတွင်ႉၾႃႉ * @Date: 12/04/2024. */ @Composable fun MovieListItem( modifier: Modifier = Modifier, movie: Movie, onMovieClick: (Movie) -> Unit ) { Card( modifier = Modifier .height(220.dp) .clickable { onMovieClick(movie) }, shape = RoundedCornerShape(8.dp) ) { Column { Box( modifier = modifier .weight(1f), contentAlignment = Alignment.Center ) { AsyncImage( model = movie.imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = modifier .fillMaxSize() .clip(RoundedCornerShape(bottomStart = 2.dp, bottomEnd = 2.dp)) ) Surface( color = Color.Black.copy(alpha = 0.6f), modifier = modifier .size(50.dp), shape = CircleShape ) { Image( imageVector = Icons.Default.PlayArrow, //painter = painterResource(id = R.drawable.play_button), contentDescription = null, modifier = modifier .padding(5.dp) .align(Alignment.Center), colorFilter = ColorFilter.tint(Color.White) ) } } Column( modifier = modifier .padding(10.dp) ) { Text( text = movie.title, style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis ) Spacer(modifier = modifier.height(4.dp)) Text( text = movie.releaseDate, style = MaterialTheme.typography.caption, ) } } } }
0
Kotlin
0
0
7f985a7cb350a610d2a7bb6c0ea803447803dc53
3,756
MovieApp
MIT License
floating_video/src/main/java/com/xeinebiu/floating/video/model/VideoItem.kt
xeinebiu
315,275,090
false
null
package com.xeinebiu.floating.video.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class VideoItem( val id: String, val streams: List<Stream>, val subtitles: List<Subtitle>, ) : Parcelable
0
Kotlin
3
8
d3f48993586750c87a647297ccda54bf0794cccd
242
android_floating_video
MIT License
md-compose-core/src/commonMain/kotlin/com/wakaztahir/markdowncompose/editor/utils/TextFormatter.kt
Qawaz
485,501,273
false
null
package com.wakaztahir.markdowncompose.editor.utils import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.* import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.TextUnit import com.wakaztahir.markdowncompose.utils.TAG_URL abstract class TextFormatter { var isBold by mutableStateOf(false) var isItalic by mutableStateOf(false) var isStrikeThrough by mutableStateOf(false) var isLink by mutableStateOf(false) abstract var value: TextFieldValue /** appends the linked [text] at [index] **/ fun appendLink( text: String, link: String, index: Int = if (value.selection.reversed) value.selection.end else value.selection.start ) { value = value.copy(annotatedString = buildAnnotatedString { append(text = value.annotatedString.subSequence(startIndex = 0, endIndex = index)) append(text = text) append( text = value.annotatedString.subSequence( startIndex = index, endIndex = value.annotatedString.length ) ) addStringAnnotation(tag = TAG_URL, annotation = link, start = index, end = index + text.length) addStyle( SpanStyle(fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline), start = index, end = index + text.length ) }) } /** makes text at [start] till [end] a link **/ fun appendLink(link: String, start: Int = value.selection.start, end: Int = value.selection.end) { value = value.copy(annotatedString = buildAnnotatedString { append(value.annotatedString) val startIndex = if (start < end) start else end val endIndex = if (end > start) end else start addStringAnnotation(tag = TAG_URL, annotation = link, start = startIndex, end = endIndex) addStyle( SpanStyle(fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline), start = startIndex, end = endIndex ) }) } fun resetState() { isBold = false isItalic = false isStrikeThrough = false isLink = false } } /** checks whether the [AnnotatedString.Range] contains [TextRange] **/ internal fun <T> AnnotatedString.Range<T>.contains(range: TextRange): Boolean = range.min >= start && range.max <= end /** checks whether the [TextRange] contains [AnnotatedString.Range] **/ internal fun <T> TextRange.contains(style: AnnotatedString.Range<T>): Boolean = min <= style.start && style.end <= max /** updates formatter state from [style] **/ private fun TextFormatter.updateState(style: SpanStyle) { if ((style.fontWeight?.weight ?: 400) > 400) { isBold = true } if (style.fontStyle == FontStyle.Italic) { isItalic = true } if (style.textDecoration == TextDecoration.LineThrough) { isStrikeThrough = true } } /** updates formatter state from its value **/ internal fun TextFormatter.updateState() { resetState() for (it in value.annotatedString.spanStyles) { if (it.contains(value.selection)) { updateState(it.item) } } for (it in value.annotatedString.getStringAnnotations(TAG_URL, value.selection.min, value.selection.max)) { if (it.contains(value.selection)) { isLink = true } } } /** searches for [char] from 0 till endIndex (excluding) in string in reverse order **/ private fun String.reverseIndexOf(char: Char, endIndex: Int): Int { if (endIndex - 1 < 0) return -1 var index = -1 for (i in (endIndex - 1) downTo 0) { if (this[i] == char) { index = i break } } return index } /** finds the range for the current word under the cursor (if selection is collapsed) (if not found , returns whole) **/ private fun TextFieldValue.getCurrentWordRange(): TextRange { val index = selection.start var start: Int var end: Int start = text.reverseIndexOf( char = ' ', endIndex = index ) if (start == -1) { start = text.reverseIndexOf( char = '\n', endIndex = index ) } end = text.indexOf( char = ' ', startIndex = index ) if (end == -1) { end = text.indexOf( char = '\n', startIndex = index ) } start = if (start < 0) 0 else minOf(start + 1, text.length) if (end < 0 || end > text.length) end = text.length return TextRange(start = start, end = end) } /** applies the [style] to selection , if there's no selection then current word or whole text **/ private fun TextFormatter.selectionStyle(style: SpanStyle) { val styleSelection: TextRange = if (value.selection.collapsed) { value.getCurrentWordRange() } else { value.selection } if (!styleSelection.collapsed && styleSelection.max <= value.text.length) { value = value.copy(annotatedString = buildAnnotatedString { append(value.annotatedString) addStyle( style = style, start = styleSelection.min, end = styleSelection.max ) }) updateState() } } /** replaces the style in selection or current word or whole text **/ internal fun TextFormatter.replaceStyle( filterSpanStyle: (AnnotatedString.Range<SpanStyle>) -> Boolean = { true }, filterParagraphStyle: (AnnotatedString.Range<ParagraphStyle>) -> Boolean = { true }, removeNewEmptySpanStyles: Boolean = true, removeNewEmptyParagraphStyles: Boolean = true, replaceSpanStyle: ((AnnotatedString.Range<SpanStyle>) -> AnnotatedString.Range<SpanStyle>?)? = null, replaceParagraphStyle: ((AnnotatedString.Range<ParagraphStyle>) -> AnnotatedString.Range<ParagraphStyle>?)? = null ) { val styleSelection: TextRange = if (value.selection.collapsed) { value.getCurrentWordRange() } else { value.selection } if (!styleSelection.collapsed && styleSelection.max <= value.text.length) { val spanStyles: MutableList<AnnotatedString.Range<SpanStyle>> = value.annotatedString.spanStyles.toMutableList() val newParagraphStyles: MutableList<AnnotatedString.Range<ParagraphStyle>> = value.annotatedString.paragraphStyles.toMutableList() if (replaceSpanStyle != null) { val sItr = spanStyles.listIterator() while (sItr.hasNext()) { val spanStyle = sItr.next() if ( (styleSelection.collapsed && spanStyle.contains(styleSelection)) || styleSelection.contains(spanStyle) ) { if (filterSpanStyle(spanStyle)) { replaceSpanStyle(spanStyle).let { newSpanStyle -> if (newSpanStyle == null || removeNewEmptySpanStyles && newSpanStyle.item.isEmpty()) { sItr.remove() } else { sItr.set(newSpanStyle) } } } } } } if (replaceParagraphStyle != null) { val pItr = newParagraphStyles.listIterator() while (pItr.hasNext()) { val paragraphStyle = pItr.next() if ( (styleSelection.collapsed && paragraphStyle.contains(styleSelection)) || styleSelection.contains(paragraphStyle) ) { if (filterParagraphStyle(paragraphStyle)) { replaceParagraphStyle(paragraphStyle).let { newParagraphStyle -> if (newParagraphStyle == null || removeNewEmptyParagraphStyles && newParagraphStyle.item.isEmpty()) { pItr.remove() } else { pItr.set(newParagraphStyle) } } } } } } value = value.copy( annotatedString = AnnotatedString( text = value.annotatedString.text, spanStyles = spanStyles, paragraphStyles = newParagraphStyles ) ) updateState() } } /** checks if all span style's properties are null **/ internal fun SpanStyle.isEmpty(): Boolean = color == Color.Unspecified && fontSize == TextUnit.Unspecified && fontWeight == null || fontWeight == FontWeight.Normal && fontStyle == null || fontStyle == FontStyle.Normal && fontSynthesis == null && fontFamily == null && fontFeatureSettings == null && letterSpacing == TextUnit.Unspecified && baselineShift == null && textGeometricTransform == null && localeList == null && background == Color.Unspecified && textDecoration == null || textDecoration == TextDecoration.None && shadow == null /** checks if all span style's properties are null **/ internal fun ParagraphStyle.isEmpty(): Boolean = textAlign == null && textDirection == null && lineHeight == TextUnit.Unspecified && textIndent == null // Bold Functions //fun TextFormatter.toggleBold() fun TextFormatter.makeBold() { replaceStyle( filterSpanStyle = { it.item.fontWeight == FontWeight.Normal }, removeNewEmptySpanStyles = false, replaceSpanStyle = { it.copy(item = it.item.copy(fontWeight = FontWeight.Bold)) } ) selectionStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) } fun TextFormatter.removeBold() = replaceStyle( filterSpanStyle = { it.item.fontWeight != FontWeight.Normal }, replaceSpanStyle = { it.copy(item = it.item.copy(fontWeight = FontWeight.Normal)) } ) // Italic Functions //fun TextFormatter.toggleItalic() fun TextFormatter.makeItalic() { replaceStyle( filterSpanStyle = { it.item.fontStyle == FontStyle.Normal }, removeNewEmptySpanStyles = false, replaceSpanStyle = { it.copy(item = it.item.copy(fontStyle = FontStyle.Italic)) } ) selectionStyle(style = SpanStyle(fontStyle = FontStyle.Italic)) } fun TextFormatter.removeItalic() = replaceStyle( filterSpanStyle = { it.item.fontStyle == FontStyle.Italic }, replaceSpanStyle = { it.copy(item = it.item.copy(fontStyle = FontStyle.Normal)) } ) // Strike Through Functions //fun TextFormatter.toggleStrikeThrough() fun TextFormatter.makeStrikeThrough() { replaceStyle( filterSpanStyle = { it.item.textDecoration != TextDecoration.LineThrough }, removeNewEmptySpanStyles = false, replaceSpanStyle = { it.copy(item = it.item.copy(textDecoration = TextDecoration.LineThrough)) } ) selectionStyle(style = SpanStyle(textDecoration = TextDecoration.LineThrough)) } fun TextFormatter.removeStrikeThrough() = replaceStyle( filterSpanStyle = { it.item.textDecoration == TextDecoration.LineThrough }, replaceSpanStyle = { it.copy(item = it.item.copy(textDecoration = TextDecoration.None)) } )
0
Kotlin
0
0
5293904088ab9ace4d4b1e7e7788437cadd513d6
11,667
markdown-compose
MIT License
plugin/src/main/kotlin/io/github/vacxe/danger/shellcheck/reporter/DefaultFindingsDangerReporter.kt
Vacxe
771,841,549
false
{"Kotlin": 4872}
package io.github.vacxe.danger.shellcheck.reporter import io.github.vacxe.danger.shellcheck.model.Finding import io.github.vacxe.danger.shellcheck.model.Level import systems.danger.kotlin.sdk.DangerContext class DefaultFindingsDangerReporter( private val context: DangerContext, private val inline: Boolean, ) : FindingsDangerReporter { override fun report( finding: Finding, ) { val message = createMessage(finding) val severity = finding.level val file = finding.file val line = finding.line if (inline) { report(message, severity, file, line) } else { report(message, severity) } } private fun report( message: String, severity: Level, ) { when (severity) { Level.INFO, Level.STYLE -> context.message(message) Level.WARNING -> context.warn(message) Level.ERROR -> context.fail(message) } } private fun report( message: String, severity: Level, filePath: String, line: Int, ) { when (severity) { Level.INFO, Level.STYLE -> context.message(message, filePath, line) Level.WARNING -> context.warn(message, filePath, line) Level.ERROR -> context.fail(message, filePath, line) } } private fun createMessage(finding: Finding): String { val message = finding.message.let { "**Shellcheck**: $it" } val rule = finding.code.let { "**Code**: [$it](https://www.shellcheck.net/wiki/SC$it)" } return listOfNotNull( "", // start message with blank line message, rule, ).joinToString(separator = "\n") } }
0
Kotlin
0
0
fb506b31e2bdcf4638f832922910dd506c7e371e
1,759
danger-kotlin-shellcheck
Apache License 2.0
app/src/main/java/dev/jatzuk/servocontroller/ui/DevicesFragment.kt
jatzuk
287,108,596
false
null
package dev.jatzuk.servocontroller.ui import android.os.Bundle import android.view.Gravity import android.view.View import android.widget.Toast import androidx.fragment.app.Fragment import com.airbnb.lottie.LottieDrawable import dagger.hilt.android.AndroidEntryPoint import dev.jatzuk.servocontroller.R import dev.jatzuk.servocontroller.databinding.FragmentDevicesBinding import dev.jatzuk.servocontroller.databinding.LayoutToastBinding import dev.jatzuk.servocontroller.mvp.devicesFragment.DevicesFragmentContract import javax.inject.Inject @AndroidEntryPoint class DevicesFragment : Fragment(R.layout.fragment_devices), DevicesFragmentContract.View { private var binding: FragmentDevicesBinding? = null private var toastBinding: LayoutToastBinding? = null @Inject lateinit var presenter: DevicesFragmentContract.Presenter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentDevicesBinding.bind(view) toastBinding = LayoutToastBinding.inflate(layoutInflater) binding?.layoutEnableHardwareRequest?.button?.apply { setOnClickListener { presenter.onEnableHardwareButtonPressed() } } presenter.apply { createTabLayout(binding!!) onViewCreated() } } override fun updateTabLayoutVisibility(isVisible: Boolean) { binding?.apply { layoutLinear.visibility = if (isVisible) View.VISIBLE else View.GONE val hardwareRequestVisibility = if (isVisible) View.GONE else View.VISIBLE layoutEnableHardwareRequest.apply { lav.visibility = hardwareRequestVisibility button.visibility = hardwareRequestVisibility } } } override fun updateButtonText(text: String) { binding?.layoutEnableHardwareRequest?.button?.apply { this.text = getString(R.string.enable, text) } } override fun showAnimation(resourceId: Int, speed: Float, timeout: Long) { binding?.layoutEnableHardwareRequest?.lav?.apply { visibility = View.VISIBLE setAnimation(resourceId) this.speed = speed repeatCount = LottieDrawable.INFINITE enableMergePathsForKitKatAndAbove(true) playAnimation() } } override fun stopAnimation() { binding?.layoutEnableHardwareRequest?.lav?.apply { visibility = View.GONE cancelAnimation() } } override fun showToast(message: String, length: Int) { try { toastBinding?.textView?.text = message Toast(requireContext()).apply { view = toastBinding!!.root setGravity(Gravity.TOP, 0, MainActivity.toastOffset) duration = length show() } } catch (e: IllegalArgumentException) { Toast.makeText(requireContext(), message, length).show() } } override fun onDestroyView() { binding = null toastBinding = null super.onDestroyView() } override fun onDestroy() { presenter.onDestroy() super.onDestroy() } }
0
Kotlin
0
0
f38842b990910f66a950fe26de561fc605dddae0
3,295
Servo-Controller
Apache License 2.0
Behavioral/TemplateMethod/kotlin/CaffeineBeverage.kt
ZoranPandovski
106,878,264
false
null
abstract class CaffeineBeverage { fun prepareRecipe() { boilWater() brew() pourInCup() addCondiments() } abstract fun brew() abstract fun addCondiments() fun boilWater() { println("Boil some water") } fun pourInCup() { println("Pour beverage in a cup") } }
10
null
297
331
f9270600778fbd8b6cd38ff88aada8ccca51b8e1
341
design-patterns
Creative Commons Zero v1.0 Universal
fuzzer/fuzzing_output/crashing_tests/verified/minimized/innerClass1.kt1449999796.kt_minimized.kt
ItsLastDay
102,885,402
false
null
class Outer { inner class Inner { val y = box + "K" } } tailrec fun box() = Outer().Inner().y
2
Kotlin
1
6
56f50fc307709443bb0c53972d0c239e709ce8f2
93
KotlinFuzzer
MIT License