path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/org/jetbrains/kotlincodeanomaliespublisher/main.kt
petukhovv
124,805,879
false
null
package org.jetbrains.kotlincodeanomaliespublisher import com.xenomachina.argparser.ArgParser import org.jetbrains.kotlincodeanomaliespublisher.structures.AnomalyType import org.jetbrains.kotlincodeanomaliespublisher.structures.ProcessMethod fun main(args : Array<String>) { val parser = ArgParser(args) val anomaliesFolder by parser.storing("-d", "--directory", help="path to folder with grouped anomaly source code files") val type by parser.mapping("--cst" to AnomalyType.CST, "--bytecode" to AnomalyType.BYTECODE, help = "anomalies type (--cst or --bytecode)") val processMethod by parser.mapping("--append" to ProcessMethod.APPEND, "--overwrite" to ProcessMethod.OVERWRITE, help = "anomalies site config file process method (--append or --overwrite)") val publisherName by parser.storing("-p", "--publisher_name", help="path to folder with grouped anomaly source code files") Runner.run(anomaliesFolder, type, processMethod, publisherName) }
0
Kotlin
1
1
3821684cfd8b4f56ac3934b3b9c1f0788c04a1fa
974
kotlin-code-anomalies-publisher
Apache License 2.0
secdra-service/src/main/kotlin/com/junjie/secdraservice/serviceimpl/CommentMessageServiceImpl.kt
fuzeongit
154,359,683
false
null
package com.junjie.secdraservice.serviceimpl import com.junjie.secdracore.util.DateUtil import com.junjie.secdradata.database.primary.dao.CommentMessageDAO import com.junjie.secdradata.database.primary.entity.CommentMessage import com.junjie.secdraservice.service.CommentMessageService import org.springframework.data.jpa.domain.Specification import org.springframework.stereotype.Service import java.util.* import javax.persistence.criteria.Predicate @Service class CommentMessageServiceImpl(private val commentMessageDAO: CommentMessageDAO) : CommentMessageService { override fun save(commentMessage: CommentMessage): CommentMessage { return commentMessageDAO.save(commentMessage) } override fun list(authorId: String): List<CommentMessage> { return commentMessageDAO.findAllByAuthorIdOrderByCreateDateDesc(authorId) } override fun countUnread(authorId: String): Long { return commentMessageDAO.countByAuthorIdAndReview(authorId, false) } override fun listUnread(authorId: String): List<CommentMessage> { return commentMessageDAO.findAllByAuthorIdAndReviewOrderByCreateDateDesc(authorId, false) } override fun deleteByMonthAgo() { val specification = Specification<CommentMessage> { root, _, criteriaBuilder -> val predicatesList = ArrayList<Predicate>() predicatesList.add(criteriaBuilder.greaterThan(root.get("createDate"), DateUtil.addDate(Date(), 0, -30, 0, 0, 0, 0, 0))) criteriaBuilder.and(*predicatesList.toArray(arrayOfNulls<Predicate>(predicatesList.size))) } val list = commentMessageDAO.findAll(specification) for (item in list) { commentMessageDAO.delete(item) } return } }
1
Kotlin
4
11
f75c32e5fb834d456a3182f71aee08029a1629d3
1,762
secdra
MIT License
app/src/main/java/com/vicky7230/sunny/ui/weather/WeatherActivity.kt
vicky7230
188,676,424
false
null
package com.vicky7230.sunny.ui.weather import android.Manifest import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.IntentSender import android.content.pm.PackageManager import android.content.res.ColorStateList import android.graphics.Color import android.os.Bundle import android.util.DisplayMetrics import android.view.Menu import android.view.MenuItem import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import com.google.android.gms.common.api.ResolvableApiException import com.google.android.gms.location.* import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.android.gms.tasks.Task import com.google.android.material.snackbar.Snackbar import com.vicky7230.sunny.R import com.vicky7230.sunny.ui.about.AboutActivity import com.vicky7230.sunny.ui.add_city.AddCityActivity import com.vicky7230.sunny.ui.base.BaseActivity import com.vicky7230.sunny.ui.saved_cities.SavedCitiesActivity import com.vicky7230.sunny.ui.weather.city.CityWeatherFragment import com.vicky7230.sunny.ui.weather.currentLocation.CurrentLocationWeatherFragment import com.vicky7230.sunny.utils.ThemeUtils import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.* import org.greenrobot.eventbus.EventBus import timber.log.Timber import javax.inject.Inject class WeatherActivity : BaseActivity(), OnSuccessListener<LocationSettingsResponse>, OnFailureListener, HasSupportFragmentInjector { private val REQUEST_REMOVE_CITY = 666 private val REQUEST_CHECK_SETTINGS = 888 private val REQUEST_ADD_CITY = 777 private val LOCATION_PERMISSION_REQUEST = 999 @Inject lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var viewPagerAdapter: ViewPagerAdapter @Inject lateinit var compositeDisposable: CompositeDisposable @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var weatherViewModel: WeatherViewModel private var locationRequest: LocationRequest? = null private var locationCallback: LocationCallback? = null private var fusedLocationClient: FusedLocationProviderClient? = null override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) weatherViewModel = ViewModelProvider( this@WeatherActivity, viewModelFactory )[WeatherViewModel::class.java] init() } private fun init() { setSupportActionBar(toolbar as Toolbar?) supportActionBar?.title = "" if (ThemeUtils.isNight()) changeRings() animateSunAndMoon() add_city_button.setOnClickListener { if (viewPagerAdapter.count < 5) startActivityForResult( AddCityActivity.getStartIntent(this@WeatherActivity), REQUEST_ADD_CITY ) else { Snackbar.make( container, "You cannot add more than 4 cities. Click Remove to remove cities.", Snackbar.LENGTH_LONG ) .setActionTextColor(Color.parseColor("#eccd30")) .setAction("REMOVE") { startActivityForResult( SavedCitiesActivity.getStartIntent(this@WeatherActivity), REQUEST_REMOVE_CITY ) } .show() } } view_pager.offscreenPageLimit = 4 view_pager.adapter = viewPagerAdapter setupViewPager() } private fun changeRings() { rings.setBackgroundResource(R.drawable.circular_rings_dark) sun_and_moon.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FFFFFF")) add_city_button.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#403C48")) } private fun animateSunAndMoon() { val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) val height = displayMetrics.heightPixels val width = displayMetrics.widthPixels val animation = ObjectAnimator.ofFloat(sun_and_moon, "translationX", width.toFloat()) animation.duration = 5000 animation.repeatCount = ValueAnimator.INFINITE animation.repeatMode = ValueAnimator.REVERSE animation.start() } private fun setupViewPager() { viewPagerAdapter.removeFragments() viewPagerAdapter.addFragment(CurrentLocationWeatherFragment.newInstance()) compositeDisposable.add( Observable.defer { Observable.just(weatherViewModel.getSavedCities()) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ cityList -> cityList.forEach { viewPagerAdapter.addFragment(CityWeatherFragment.newInstance(it.cityName)) } }, { Timber.e(it) showError(it.localizedMessage) }) ) } public override fun onResume() { super.onResume() if (hasPermissions( arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) ) ) { checkLocationSettings() } else { requestPermissionsSafely( arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) , LOCATION_PERMISSION_REQUEST ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == LOCATION_PERMISSION_REQUEST) { if (grantResults.size == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) { checkLocationSettings() } else showError("Permission Denied.") } else super.onRequestPermissionsResult(requestCode, permissions, grantResults) } private fun checkLocationSettings() { locationRequest = LocationRequest.create().apply { interval = 10000 fastestInterval = 5000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } locationRequest?.let { val builder = LocationSettingsRequest.Builder() .addLocationRequest(it) .setAlwaysShow(true) val client: SettingsClient = LocationServices.getSettingsClient(this) val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder?.build()) task.addOnSuccessListener(this@WeatherActivity) task.addOnFailureListener(this@WeatherActivity) } } @SuppressLint("MissingPermission") override fun onSuccess(locationSettingsResponse: LocationSettingsResponse?) { locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { locationResult ?: return Timber.d("Location : ${locationResult.locations[0].latitude}, ${locationResult.locations[0].longitude}") //Post to CurrentLocationWeatherFragment EventBus.getDefault().post(locationResult.locations[0]) } } fusedLocationClient = FusedLocationProviderClient(this@WeatherActivity) fusedLocationClient?.requestLocationUpdates( locationRequest, locationCallback, null /* Looper */ ) } override fun onFailure(exception: Exception) { if (exception is ResolvableApiException) { try { exception.startResolutionForResult(this@WeatherActivity, REQUEST_CHECK_SETTINGS) } catch (sendEx: IntentSender.SendIntentException) { Timber.e(sendEx) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_CHECK_SETTINGS -> when (resultCode) { Activity.RESULT_OK -> Timber.d("User agreed to make required location settings changes.") Activity.RESULT_CANCELED -> { checkLocationSettings() } } REQUEST_ADD_CITY -> { if (resultCode == Activity.RESULT_OK) { setupViewPager() } } REQUEST_REMOVE_CITY -> { if (resultCode == Activity.RESULT_OK) { setupViewPager() } } } } override fun onPause() { super.onPause() stopLocationUpdates() } private fun stopLocationUpdates() { fusedLocationClient?.removeLocationUpdates(locationCallback) } override fun supportFragmentInjector(): AndroidInjector<Fragment> { return fragmentDispatchingAndroidInjector } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_weather_activity, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.saved_cities -> { startActivityForResult( SavedCitiesActivity.getStartIntent(this@WeatherActivity), REQUEST_REMOVE_CITY ) true } R.id.about -> { startActivity(AboutActivity.getStartIntent(this@WeatherActivity)) true } else -> super.onOptionsItemSelected(item) } } override fun onDestroy() { compositeDisposable.dispose() super.onDestroy() } }
0
Kotlin
5
6
f46bf5ab713070e338618392780b9cbeca3bf1cf
10,957
Sunny
Apache License 2.0
core/domain/src/main/java/com/season/winter/core/domain/database/ImageDatabaseRoomDao.kt
winter-love-dev
660,596,555
false
{"Kotlin": 266095}
package com.season.winter.core.domain.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.season.winter.core.domain.entity.ImageNameUrlPairEntity import kotlinx.coroutines.flow.Flow @Dao interface ImageDatabaseRoomDao { // Fetchers 쿼리 // OnConflictStrategy.REPLACE: 중복 primary 값을 덮어 씌우기 @Query("SELECT * FROM image_name_url_pair_entity WHERE file_name = :fileName LIMIT 1") suspend fun checkForSearchImageData(fileName: String): ImageNameUrlPairEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertImageDataList(fileName: List<ImageNameUrlPairEntity>) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertImageData(fileName: ImageNameUrlPairEntity) @Query("DELETE FROM image_name_url_pair_entity") fun clear() // 조회 쿼리 @Query("SELECT * FROM image_name_url_pair_entity") fun getImageDataList(): Flow<List<ImageNameUrlPairEntity>>? @Query("SELECT * FROM image_name_url_pair_entity WHERE file_name = :fileName LIMIT 1") suspend fun getImage(fileName: String): ImageNameUrlPairEntity? }
0
Kotlin
0
0
d84a7f228b553a631bccaf2352be0ae88ed22b8e
1,176
CatchBottle
Apache License 2.0
androidApp/src/main/java/com/marcocastope/mcsports/android/di/AppModule.kt
marcocastope
630,538,499
false
null
package com.marcocastope.mcsports.android.di import com.marcocastope.mcsports.android.ui.home.HomeViewModel import com.marcocastope.mcsports.android.ui.livescore.LiveScoreViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val appModule = module { viewModel { HomeViewModel(get(), get()) } viewModel { LiveScoreViewModel(get()) } }
0
Kotlin
0
0
06d9f702d169759a699e36425fee7cbc48ab36f4
375
McSports
MIT License
app/src/main/java/com/theapache64/topcorn/data/local/Converters.kt
HarshDhakate
437,835,535
false
null
package com.<NAME>.MoviesMad.data.local import androidx.room.TypeConverter class Converters { @TypeConverter fun fromStringList(list: List<String>): String { return list.joinToString(",") } @TypeConverter fun fromStringToList(string: String): List<String> { return string.split(",") } }
0
Kotlin
0
0
ab64de10afbfc38c1c111325288c727b6c1f66ad
329
Mad_Assignment_2
Apache License 2.0
src/test/kotlin/com/zupacademy/henio/pix/RemoveChaveControllerTest.kt
HenioJunior
402,023,059
true
{"Kotlin": 44282, "Smarty": 1962, "Dockerfile": 171}
package com.zupacademy.henio.pix import com.zupacademy.henio.pix.exceptions.GlobalExceptionHandler import com.zupacademy.henio.pix.grpc.KeymanagerRemoveGrpcServiceGrpc import com.zupacademy.henio.pix.grpc.RemoveChavePixResponse import com.zupacademy.henio.pix.shared.grpc.KeyManagerGrpcFactory import io.grpc.Status import io.grpc.StatusRuntimeException import io.micronaut.context.annotation.Factory import io.micronaut.context.annotation.Replaces import io.micronaut.http.HttpRequest import io.micronaut.http.HttpStatus import io.micronaut.http.client.HttpClient import io.micronaut.http.client.annotation.Client import io.micronaut.http.hateoas.JsonError import io.micronaut.test.extensions.junit5.annotation.MicronautTest import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers.any import org.mockito.BDDMockito.given import org.mockito.Mockito import java.util.* import javax.inject.Inject import javax.inject.Singleton @MicronautTest internal class RemoveChaveControllerTest { @field:Inject lateinit var removeStub: KeymanagerRemoveGrpcServiceGrpc.KeymanagerRemoveGrpcServiceBlockingStub @field:Inject @field:Client("/") lateinit var httpClient: HttpClient val clienteId = UUID.randomUUID().toString() val pixId = UUID.randomUUID().toString() @Test fun `deve remover uma chave pix existente`() { val respostaGrpc = RemoveChavePixResponse.newBuilder() .setClienteId(clienteId) .setPixId(pixId) .build() given(removeStub.remove(any())).willReturn(respostaGrpc) val request = HttpRequest.DELETE<Any>("/api/clientes/$clienteId/pix/$pixId") val response = httpClient.toBlocking().exchange(request, Any::class.java) Assertions.assertEquals(HttpStatus.OK, response.status) } @Test fun `deve retornar 404 quando a chave nao existe`() { val mensagem = "Chave não encontrada" val excecao = StatusRuntimeException( Status.NOT_FOUND .withDescription(mensagem)) val response = GlobalExceptionHandler().handle(HttpRequest.DELETE<Any>("/"), excecao) with(response) { assertEquals(HttpStatus.NOT_FOUND, status) assertNotNull(body()) assertEquals(mensagem, (body() as JsonError).message) } } @Test fun `deve retornar 403 quando o cliente nao e dono da chave`() { val mensagem = "Cliente não é dono da chave" val excecao = StatusRuntimeException( Status.PERMISSION_DENIED .withDescription(mensagem)) val response = GlobalExceptionHandler().handle(HttpRequest.DELETE<Any>("/"), excecao) with(response) { assertEquals(HttpStatus.FORBIDDEN, status) assertNotNull(body()) assertEquals(mensagem, (body() as JsonError).message) } } @Factory @Replaces(factory = KeyManagerGrpcFactory::class) internal class RemoveStubFactory { @Singleton fun deletaChave() = Mockito.mock(KeymanagerRemoveGrpcServiceGrpc.KeymanagerRemoveGrpcServiceBlockingStub::class.java) } }
0
Kotlin
0
0
64442d63dcdd7dddab56481c3174a44ee0666879
3,413
orange-talents-06-template-pix-keymanager-rest
Apache License 2.0
generator/src/test/kotlin/com/android/gradle/replicator/generator/fixtures/BaseTest.kt
android
281,446,649
false
null
/* * Copyright (C) 2020 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 com.android.gradle.replicator.generator.fixtures import com.android.gradle.replicator.generator.BuildGenerator import org.junit.Rule import org.junit.rules.TemporaryFolder import org.junit.runners.Parameterized import java.io.File abstract class BaseTest { companion object { @JvmStatic @Parameterized.Parameters(name = "kts_{0}") fun kts(): List<Boolean> { return listOf(true, false) } } @Parameterized.Parameter(0) @JvmField var ktsMode: Boolean = false @get:Rule val testFolder = TemporaryFolder() protected fun generateWithStructure(structure: String): File { val jsonFile = testFolder.newFile() jsonFile.writeText(structure) val output = testFolder.newFolder() val params = TestParams( jsonFile = jsonFile, destination = output, kts = ktsMode ) BuildGenerator(params).generate() return output } val buildFileName: String get() = if (ktsMode) "build.gradle.kts" else "build.gradle" val settingsFileName: String get() = if (ktsMode) "settings.gradle.kts" else "settings.gradle" fun select(kts: String, groovy: String): String = if (ktsMode) kts else groovy }
3
Kotlin
27
87
dcdbd2d77b0a3e511c5da0ef960668bfec9f25a3
1,904
project-replicator
Apache License 2.0
PADCX_HealthCareApp_NCT/doctor/src/main/java/com/padcx/doctor/views/viewholders/BasePreviousConsultListViewHolder.kt
NayChiThin
316,665,297
false
null
package com.padcx.doctor.views.viewholders import android.view.View import com.padcx.shared.views.viewholders.BaseViewHolder import com.padcx.shared.data.vos.ConsultVO abstract class BasePreviousConsultListViewHolder(itemView:View) : BaseViewHolder<ConsultVO>(itemView){ }
0
Kotlin
0
0
80f24209ef34e56a6db6bfef72d115c7125dc4d8
274
PADCX_HealthCareApp_NCT
Apache License 2.0
app/src/main/java/konsum/gandalf/mealmate/recipe/ui/fragments/RecipeSearchFragment.kt
KonsumGandalf
586,627,095
false
null
package konsum.gandalf.mealmate.recipe.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import dagger.hilt.android.AndroidEntryPoint import konsum.gandalf.mealmate.databinding.FragmentRecipeSearchBinding import konsum.gandalf.mealmate.recipe.ui.adapter.AreaAdapter import konsum.gandalf.mealmate.recipe.ui.adapter.CategoryAdapter import konsum.gandalf.mealmate.recipe.ui.adapter.RecipeAdapter import konsum.gandalf.mealmate.recipe.ui.viewmodels.RecipeSearchResultViewModel import konsum.gandalf.mealmate.recipe.ui.viewmodels.RecipeSearchViewModel import konsum.gandalf.mealmate.utils.ui.ChipsGridBuilder @AndroidEntryPoint class RecipeSearchFragment : Fragment() { private lateinit var binding: FragmentRecipeSearchBinding private val recipeViewModel by viewModels<RecipeSearchViewModel>() private val recipeResultViewModel by viewModels<RecipeSearchResultViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) recipeViewModel.getCategories() recipeViewModel.getRandomRecipes() recipeViewModel.getAreas() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentRecipeSearchBinding.inflate(inflater, container, false) registerAreas() registerCategories() registerRandomRecipes() registerSearchView() registerResultRv() return binding.root } private fun registerAreas() { recipeViewModel.currentAreas.observe(viewLifecycleOwner) { areas -> areas?.let { binding.recipeSearchAreaContainer.layoutManager = ChipsGridBuilder.buildLayout(requireContext()) binding.recipeSearchAreaContainer.adapter = AreaAdapter(it, recipeViewModel.currentSelectedAreas) } } } private fun registerCategories() { recipeViewModel.currentCategories.observe(viewLifecycleOwner) { categories -> categories?.let { binding.recipeSearchCategoriesRv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) binding.recipeSearchCategoriesRv.adapter = CategoryAdapter(requireContext(), it, recipeViewModel.currentSelectedCategories) } } } private fun registerRandomRecipes() { recipeViewModel.randomRecipesEvaluations.observe(viewLifecycleOwner) { evaluations -> evaluations?.let { evals -> binding.recipeSearchRandomRecipeRv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) recipeViewModel.currentRandomRecipes.value?.let { recipes -> binding.recipeSearchRandomRecipeRv.adapter = RecipeAdapter(recipes, evals) } } } } private fun registerResultRv() { recipeResultViewModel.filteredRecipesEvaluations.observe(viewLifecycleOwner) { evaluations -> evaluations?.let { evals -> binding.recipeSearchPreviewRv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) recipeResultViewModel.currentFilteredRecipes.value?.let { recipes -> binding.recipeSearchPreviewRv.adapter = RecipeAdapter(recipes, evals) } binding.recipeSearchPreviewRv.setBackgroundColor(android.graphics.Color.WHITE) } } } private fun registerSearchView() { binding.recipeSearchSearchView.editText.setOnEditorActionListener { v, actionId, event -> binding.recipeSearchSearchBar.text = binding.recipeSearchSearchView.text recipeResultViewModel.getFilteredRecipes( binding.recipeSearchSearchBar.text.toString(), recipeViewModel.currentSelectedAreas.value!!, recipeViewModel.currentSelectedCategories.value!! ) false } binding.recipeSearchSearchBar.setOnMenuItemClickListener { menuItem -> true } } }
0
Kotlin
0
1
cae793002ae065f2b06e0da6e76e448b0201bd74
4,462
mealmate
MIT License
Todo/src/commonMain/kotlin/io/nacular/doodle/examples/NativeLinkStyler.kt
linhtran04
378,655,764
true
{"Kotlin": 104185, "HTML": 1962}
package io.nacular.doodle.examples import io.nacular.doodle.controls.buttons.HyperLink import io.nacular.doodle.core.Behavior /** * Adapter interface to wrap `NativeHyperLinkBehaviorBuilder`--which is JS only--and make it available to * common code. */ interface NativeLinkStyler { /** * Gets a native [HyperLink] [Behavior] that "wraps" [behavior]. The end result is a fully * customized look-feel controlled by [behavior], with native hyperlink traversal provided * by the native wrapper. */ operator fun invoke(link: HyperLink, behavior: Behavior<HyperLink>): Behavior<HyperLink> }
0
null
0
0
647ba646dea65d9637f534aa0a2abea7859255a9
618
doodle-tutorials
MIT License
app/src/main/java/software/orpington/rozkladmpk/home/NewsContract.kt
frysztak
178,226,007
false
null
package software.orpington.rozkladmpk.home import software.orpington.rozkladmpk.BaseView import software.orpington.rozkladmpk.data.model.NewsItem interface NewsContract { interface Presenter { fun attachView(view: View) fun detachView() fun loadMostRecentNews() fun showMoreClicked() } interface View : BaseView { fun showMostRecentNews(news: NewsItem) fun showNewsDetail(news: NewsItem) } }
0
Kotlin
0
0
afcddfdddfd7490af4fe0994a5b647c8161c45f1
459
niebieskie-tramwaje
MIT License
app/src/test/java/com/kiwiandroiddev/sc2buildassistant/feature/translate/data/CachedSupportedLanguagesAgentTest.kt
kiwiandroiddev
93,439,255
false
{"Java": 312136, "Kotlin": 187776}
package com.kiwiandroiddev.sc2buildassistant.feature.translate.data import com.kiwiandroiddev.sc2buildassistant.feature.cache.Cache import com.kiwiandroiddev.sc2buildassistant.feature.translate.data.cache.CachedSupportedLanguagesAgent import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.LanguageCode import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.datainterface.SupportedLanguagesAgent import com.kiwiandroiddev.sc2buildassistant.subscribeTestObserver import com.nhaarman.mockito_kotlin.verify import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.never import org.mockito.MockitoAnnotations import java.io.IOException /** * Created by matthome on 6/08/17. */ class CachedSupportedLanguagesAgentTest { @Mock lateinit var mockSupportedLanguagesAgent: SupportedLanguagesAgent @Mock lateinit var mockCache: Cache<Array<LanguageCode>> lateinit var cachedSupportedLanguagesAgent: SupportedLanguagesAgent val EXPECTED_CACHE_KEY = "SUPPORTED_LANGUAGES" @Before fun setUp() { MockitoAnnotations.initMocks(this) cachedSupportedLanguagesAgent = CachedSupportedLanguagesAgent( mockSupportedLanguagesAgent, mockCache ) setupDefaultMockBehaviors() } private fun setupDefaultMockBehaviors() { `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.empty()) } @Test fun supportedLanguages_cacheMiss_getsFromBackingAgentAndPutsInCache() { val TEST_LANGUAGE_CODES = arrayOf("en", "de", "zh") var cacheUpdated = false `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.fromIterable(TEST_LANGUAGE_CODES.toList())) `when`(mockCache.get(EXPECTED_CACHE_KEY)) .thenReturn(Single.error(Cache.NoValueForKey())) `when`(mockCache.put(com.nhaarman.mockito_kotlin.any(), com.nhaarman.mockito_kotlin.any())) .thenReturn(Completable.fromAction { cacheUpdated = true }) cachedSupportedLanguagesAgent.supportedLanguages() .subscribeTestObserver() .assertNoErrors() .assertComplete() verify(mockCache).get(EXPECTED_CACHE_KEY) verify(mockSupportedLanguagesAgent).supportedLanguages() assertThat(cacheUpdated).isTrue() verify(mockCache).put(EXPECTED_CACHE_KEY, TEST_LANGUAGE_CODES) } @Test fun supportedLanguages_cacheHit_doesntHitBackingAgent() { `when`(mockCache.get(EXPECTED_CACHE_KEY)) .thenReturn(Single.just(arrayOf("en", "de", "zh"))) cachedSupportedLanguagesAgent.supportedLanguages() .subscribeTestObserver() .assertNoErrors() .assertComplete() verify(mockCache).get(EXPECTED_CACHE_KEY) verify(mockSupportedLanguagesAgent, never()).supportedLanguages() } @Test fun supportedLanguages_cacheMissAndCachePutWillFail_recoversByJustReturningCodesFromBackingAgent() { val TEST_LANGUAGE_CODES = arrayOf("en", "de", "zh") `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.fromIterable(TEST_LANGUAGE_CODES.toList())) `when`(mockCache.get(EXPECTED_CACHE_KEY)) .thenReturn(Single.error(Cache.NoValueForKey())) `when`(mockCache.put(com.nhaarman.mockito_kotlin.any(), com.nhaarman.mockito_kotlin.any())) .thenReturn(Completable.error(IOException("disk full"))) cachedSupportedLanguagesAgent.supportedLanguages() .subscribeTestObserver() .assertNoErrors() .assertComplete() verify(mockCache).get(EXPECTED_CACHE_KEY) verify(mockSupportedLanguagesAgent).supportedLanguages() verify(mockCache).put(EXPECTED_CACHE_KEY, TEST_LANGUAGE_CODES) } }
1
null
1
1
83c7b27afae29a81689be2b5fbc74b84c4934ddb
4,150
starcraft-2-build-player
MIT License
src/commonMain/kotlin/com/jessecorbett/diskord/util/Json.kt
iLemonBr
304,697,089
true
{"Kotlin": 303386}
package com.jessecorbett.diskord.util import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration /** * [JsonConfiguration] that modifies [JsonConfiguration.Stable]. */ internal val jsonConfiguration = JsonConfiguration.Stable.copy(ignoreUnknownKeys = true, isLenient = true, useArrayPolymorphism = true) /** * Default [Json] instance. */ internal val defaultJson = Json(jsonConfiguration) /** * Relaxed [Json] instance that omits null values from (de-)serialized objects. */ internal val relaxedJson = Json(jsonConfiguration.copy(encodeDefaults = false))
0
null
0
1
a49da4b3c162a2e6177437b5499b328ee01ea32a
598
Diskord
Apache License 2.0
app/src/main/java/github/sachin2dehury/musicplayer/exoplayer/MediaMetadataCompatExt.kt
sachin2dehury
318,585,413
false
null
package github.sachin2dehury.musicplayer.exoplayer import android.support.v4.media.MediaMetadataCompat import github.sachin2dehury.musicplayer.data.entities.Song fun MediaMetadataCompat.toSong(): Song? { return description?.let { song -> Song( song.mediaId ?: "", song.title.toString(), song.subtitle.toString(), song.mediaUri.toString(), song.iconUri.toString(), ) } }
0
Kotlin
0
1
f64ac670e0fd32e74b191ddbbcee200ce5124267
455
MusicPlayer
Apache License 2.0
chat_ui/src/main/java/com/camerash/skygear/chat/ui/holder/IncomingImageMessageView.kt
Camerash
148,086,046
false
null
package com.camerash.skygear.chat.ui.holder import android.view.View import com.camerash.skygear.chat.ui.model.ImageMessage import com.camerash.skygear.chatkit.messages.MessageHolders class IncomingImageMessageView(itemView: View) : MessageHolders.IncomingImageMessageViewHolder<ImageMessage>(itemView) { var senderAvatarMessageView: SenderAvatarMessageView? = null var usernameMessageView: UsernameMessageView? = null var timeMessageView: IncomingTimeMessageView? = null init { usernameMessageView = UsernameMessageView(itemView) timeMessageView = IncomingTimeMessageView(itemView) senderAvatarMessageView = SenderAvatarMessageView(itemView) } override fun onBind(message: ImageMessage) { super.onBind(message) usernameMessageView?.onBind(message) timeMessageView?.onBind(message) senderAvatarMessageView?.onBind(message) } }
0
Kotlin
0
1
9b08cf07a3bd2f273053ab200ada014cfc661cd2
915
skygear-chat-ui
Apache License 2.0
middleware/src/main/java/com/anytypeio/anytype/middleware/discovery/NsdDiscoveryListener.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.middleware.discovery import android.net.nsd.NsdManager import android.net.nsd.NsdServiceInfo import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import service.DiscoveryObserver import timber.log.Timber class NsdDiscoveryListener( private val scope: CoroutineScope, private val dispatcher: CoroutineDispatcher, private val nsdManager: NsdManager ) : NsdManager.DiscoveryListener { @Volatile private var observer: DiscoveryObserver? = null private val resolveSemaphore = Semaphore(1) fun registerObserver(observer: DiscoveryObserver) { try { this.observer = observer } catch (e: Exception) { Timber.e("Error while registering observer") } } fun unregisterObserver() { try { this.observer = null } catch (e: Exception) { Timber.e("Error while unregistering observer") } } override fun onDiscoveryStarted(regType: String) { Timber.d("Mdns discovery started with regType: $regType") } override fun onServiceFound(service: NsdServiceInfo) { scope.launch(dispatcher) { val observer = observer ?: return@launch resolveSemaphore.acquire() nsdManager.resolveService(service, ResolveListener(observer, resolveSemaphore)) } } override fun onServiceLost(service: NsdServiceInfo) { Timber.d("Mdns discovery lost with service: $service") } override fun onDiscoveryStopped(serviceType: String) { Timber.d("Mdns discovery stopped: $serviceType") } override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { Timber.e("Mdns discovery start failed: $serviceType, error: $errorCode") } override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { Timber.e("Mdns discovery stop failed: $serviceType, error: $errorCode") } }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
2,058
anytype-kotlin
RSA Message-Digest License
themes/new-ui/new-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/expui/standalone/control/ActionButton.kt
JetBrains
440,164,967
false
null
@file:Suppress("MatchingDeclarationName") package org.jetbrains.jewel.themes.expui.standalone.control import androidx.compose.foundation.Indication import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import org.jetbrains.jewel.themes.expui.standalone.style.AreaColors import org.jetbrains.jewel.themes.expui.standalone.style.AreaProvider import org.jetbrains.jewel.themes.expui.standalone.style.DisabledAreaProvider import org.jetbrains.jewel.themes.expui.standalone.style.HoverAreaProvider import org.jetbrains.jewel.themes.expui.standalone.style.LocalAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.LocalDisabledAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.LocalHoverAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.LocalNormalAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.LocalPressedAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.PressedAreaProvider import org.jetbrains.jewel.themes.expui.standalone.style.areaBackground import org.jetbrains.jewel.themes.expui.standalone.theme.LightTheme class ActionButtonColors( override val normalAreaColors: AreaColors, override val hoverAreaColors: AreaColors, override val pressedAreaColors: AreaColors, override val disabledAreaColors: AreaColors ) : AreaProvider, HoverAreaProvider, PressedAreaProvider, DisabledAreaProvider { @Composable fun provideArea(enabled: Boolean, content: @Composable () -> Unit) { CompositionLocalProvider( LocalAreaColors provides if (enabled) normalAreaColors else disabledAreaColors, LocalNormalAreaColors provides normalAreaColors, LocalDisabledAreaColors provides disabledAreaColors, LocalHoverAreaColors provides hoverAreaColors, LocalPressedAreaColors provides pressedAreaColors, content = content ) } } val LocalActionButtonColors = compositionLocalOf { LightTheme.ActionButtonColors } @Composable fun ActionButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RoundedCornerShape(6.dp), indication: Indication? = HoverOrPressedIndication(shape), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, colors: ActionButtonColors = LocalActionButtonColors.current, content: @Composable BoxScope.() -> Unit ) { colors.provideArea(enabled) { Box( modifier.areaBackground(shape = shape).clickable( interactionSource = interactionSource, indication = indication, enabled = enabled, onClick = onClick, role = Role.Button ), propagateMinConstraints = true ) { content() } } }
17
null
8
318
817adc042a029698983c9686d0f1497204bfdf14
3,421
jewel
Apache License 2.0
app/src/main/kotlin/com/github/nomisrev/androidarrowplayground/ui/main/MainActivity.kt
nomisRev
123,711,466
false
null
package com.github.nomisrev.androidarrowplayground.ui.main import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.github.nomisrev.androidarrowplayground.R import com.github.nomisrev.androidarrowplayground.onClick import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val instances = instances() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) validation.onClick { instances.navigator().goToValidation() } tictactoe.onClick { instances.navigator().goToTicTacToe() } } }
0
Kotlin
0
3
876b31cbb0f01cef26fcfe9c8ccbff8a34007b50
724
AndroidArrowPlayground
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/muix/tree/view/TreeItemContent.kt
karakum-team
387,062,541
false
{"Kotlin": 1395285, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/x-tree-view/TreeItemContent") package muix.tree.view import web.cssom.ClassName import web.html.HTMLElement external interface TreeItemContentProps : react.dom.html.HTMLAttributes<HTMLElement>, react.PropsWithClassName { override var className: ClassName? /** * Override or extend the styles applied to the component. */ var classes: dynamic /** * The tree item label. */ var label: react.ReactNode? /** * The id of the item. */ var itemId: String /** * The icon to display next to the tree item's label. */ var icon: react.ReactNode? /** * The icon to display next to the tree item's label. Either an expansion or collapse icon. */ var expansionIcon: react.ReactNode? /** * The icon to display next to the tree item's label. Either a parent or end icon. */ var displayIcon: react.ReactNode? } /** * @ignore - internal component. */ external val TreeItemContent: react.FC<TreeItemContentProps>
0
Kotlin
5
35
94a6fb01da33181e516144509e5a92105ac32d2a
1,092
mui-kotlin
Apache License 2.0
app/src/main/java/classes/WordBdHelper.kt
icEngineer-tech
313,282,872
false
{"Kotlin": 14972}
package classes import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.content.Context class WordBdHelper(context:Context?): SQLiteOpenHelper(context, "WordsGame.db",null,1) { companion object { val THE_TABLE = "Tmot" val THE_SCORE="TScore" val COL_MOT = "mot" val COL_TAILLE = "taille" val COL_TYPE = "type" val COL_GENRE="genre" val COL_SCORE="score" } override fun onCreate(db: SQLiteDatabase) { val CREATE_WORDS_TABLE = ("CREATE TABLE " + THE_TABLE + "(" + COL_MOT + " TEXT PRIMARY KEY, " + COL_TAILLE + " INTEGER NOT NULL, " + COL_TYPE + " TEXT NOT NULL, " + COL_GENRE+" TEXT NOT NULL "+");") db?.execSQL(CREATE_WORDS_TABLE) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { TODO("Not yet implemented") } }
0
Kotlin
0
0
05b4e3bbbda70fcea3fd8baca96830a4a7ba1a4c
937
WordGame
MIT License
sample/src/main/java/io/denison/typedvalue/sample/ui/animation/AnimationPresenter.kt
YuriDenison
126,976,818
false
null
package io.denison.typedvalue.sample.ui.animation import io.denison.typedvalue.sample.mvp.presenter.BasePresenter import io.denison.typedvalue.sample.preferences.AppPreferences import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber import javax.inject.Inject class AnimationPresenter @Inject constructor( private val appPreferences: AppPreferences ) : BasePresenter<AnimationView>() { override fun attachView(view: AnimationView) { super.attachView(view) appPreferences.animationTypeValue.asObservable().startWith(appPreferences.animationTypeValue.get()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDetach(onNext = view::bindTo, onError = Timber::e) appPreferences.scaleValue.asObservable().startWith(appPreferences.scaleValue.get()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDetach(onNext = view::bindTo, onError = Timber::e) } }
1
Kotlin
2
19
df82eb36b61336badade897534fbeb92fdb2029e
1,063
typedvalue
Apache License 2.0
sample/src/main/java/io/denison/typedvalue/sample/ui/animation/AnimationPresenter.kt
YuriDenison
126,976,818
false
null
package io.denison.typedvalue.sample.ui.animation import io.denison.typedvalue.sample.mvp.presenter.BasePresenter import io.denison.typedvalue.sample.preferences.AppPreferences import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber import javax.inject.Inject class AnimationPresenter @Inject constructor( private val appPreferences: AppPreferences ) : BasePresenter<AnimationView>() { override fun attachView(view: AnimationView) { super.attachView(view) appPreferences.animationTypeValue.asObservable().startWith(appPreferences.animationTypeValue.get()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDetach(onNext = view::bindTo, onError = Timber::e) appPreferences.scaleValue.asObservable().startWith(appPreferences.scaleValue.get()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDetach(onNext = view::bindTo, onError = Timber::e) } }
1
Kotlin
2
19
df82eb36b61336badade897534fbeb92fdb2029e
1,063
typedvalue
Apache License 2.0
app/src/main/java/be/hogent/faith/faith/skyscraper/startscreen/SkyscraperViewholderFactory.kt
hydrolythe
353,694,404
false
null
package be.hogent.faith.faith.skyscraper.startscreen import android.view.LayoutInflater import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import be.hogent.faith.R import be.hogent.faith.faith.models.goals.Goal import be.hogent.faith.faith.models.goals.GoalColor import be.hogent.faith.faith.skyscraper.startscreen.SkyscraperViewHolder.SkyscraperNavigationListener import com.jakewharton.rxbinding4.widget.afterTextChangeEvents import io.reactivex.rxjava3.disposables.CompositeDisposable import kotlinx.android.synthetic.main.skyscraper_rv_blue.view.skyscraper_base import kotlinx.android.synthetic.main.skyscraper_rv_blue.view.skyscraper_panel import kotlinx.android.synthetic.main.skyscraper_rv_blue.view.txt_goal_description import org.koin.core.KoinComponent import java.util.concurrent.TimeUnit object SkyscraperViewHolderFactory { fun createViewHolder( parent: ViewGroup, viewType: Int, skyscraperNavigationListener: SkyscraperNavigationListener, skyscraperPanelTextListener: SkyscraperPanelTextListener ): SkyscraperViewHolder { val skyscraperLayoutFile = when (viewType) { SkyscraperColors.SKYSCRAPER_BLUE.value -> R.layout.skyscraper_rv_blue SkyscraperColors.SKYSCRAPER_YELLOW.value -> R.layout.skyscraper_rv_yellow SkyscraperColors.SKYSCRAPER_RED.value -> R.layout.skyscraper_rv_red SkyscraperColors.SKYSCRAPER_DARK_GREEN.value -> R.layout.skyscraper_rv_dark_green SkyscraperColors.SKYSCRAPER_GREEN.value -> R.layout.skyscraper_rv_green else -> R.layout.skyscraper_rv_blue } val view: ConstraintLayout = LayoutInflater.from(parent.context) .inflate(skyscraperLayoutFile, parent, false) as ConstraintLayout return SkyscraperViewHolder(view, skyscraperNavigationListener, skyscraperPanelTextListener) } } class SkyscraperViewHolder( val view: ConstraintLayout, private val skyscraperNavigationListener: SkyscraperNavigationListener, private val skyscraperPanelTextListener: SkyscraperPanelTextListener ) : RecyclerView.ViewHolder(view), KoinComponent { private var disposables = CompositeDisposable() fun bind(goal: Goal) { val baseDrawable = when (goal.goalColor) { GoalColor.GREEN -> R.drawable.skyscraper_green_base GoalColor.RED -> R.drawable.skyscraper_red_base GoalColor.YELLOW -> R.drawable.skyscraper_yellow_base GoalColor.BLUE -> R.drawable.skyscraper_blue_base GoalColor.DARKGREEN -> R.drawable.skyscraper_darkgreen_base } val panelDrawable = when (goal.goalColor) { GoalColor.GREEN -> R.drawable.skyscraper_green_panel GoalColor.RED -> R.drawable.skyscraper_red_panel GoalColor.YELLOW -> R.drawable.skyscraper_yellow_panel GoalColor.BLUE -> R.drawable.skyscraper_blue_panel GoalColor.DARKGREEN -> R.drawable.skyscraper_darkgreen_panel } val textColor = when (goal.goalColor) { GoalColor.YELLOW -> R.color.black else -> R.color.color_white } view.skyscraper_base.setImageResource(baseDrawable) view.skyscraper_panel.setImageResource(panelDrawable) view.txt_goal_description.setText(goal.description) view.txt_goal_description.tag = goal view.txt_goal_description.setTextColor(ContextCompat.getColor(view.context, textColor)) view.skyscraper_base.setOnClickListener { skyscraperNavigationListener.openGoalScreenFor(goal) } disposables.add(view.txt_goal_description.afterTextChangeEvents() .skip(1) .debounce(1, TimeUnit.SECONDS) .map { skyscraperPanelTextListener.onPanelTextChanged(goal, it.editable.toString()) } .subscribe()) } fun unbind() { disposables.dispose() } interface SkyscraperNavigationListener { fun openGoalScreenFor(goal: Goal) fun deleteSkyscraper(goal: Goal) } }
0
Kotlin
0
0
14c6aec4b3c0a42bc73a7f779964d166fffeea20
4,179
FAITHAndroid
The Unlicense
src/benchmarks/kotlin/com/github/quillraven/fleks/benchmark/fleks.kt
Quillraven
413,555,458
false
null
package com.github.quillraven.fleks.benchmark import com.github.quillraven.fleks.* import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit data class FleksPosition(var x: Float = 0f, var y: Float = 0f) data class FleksLife(var life: Float = 0f) data class FleksSprite(var path: String = "", var animationTime: Float = 0f) @AllOf([FleksPosition::class]) class FleksSystemSimple( private val positions: ComponentMapper<FleksPosition> ) : IteratingSystem() { override fun onTickEntity(entity: Entity) { positions[entity].x++ } } @AllOf([FleksPosition::class]) @NoneOf([FleksLife::class]) @AnyOf([FleksSprite::class]) class FleksSystemComplex1( private val positions: ComponentMapper<FleksPosition>, private val lifes: ComponentMapper<FleksLife>, private val sprites: ComponentMapper<FleksSprite> ) : IteratingSystem() { private var actionCalls = 0 override fun onTickEntity(entity: Entity) { if (actionCalls % 2 == 0) { positions[entity].x++ configureEntity(entity) { lifes.add(it) } } else { configureEntity(entity) { positions.remove(it) } } sprites[entity].animationTime++ ++actionCalls } } @AnyOf([FleksPosition::class, FleksLife::class, FleksSprite::class]) class FleksSystemComplex2( private val positions: ComponentMapper<FleksPosition>, private val lifes: ComponentMapper<FleksLife>, ) : IteratingSystem() { override fun onTickEntity(entity: Entity) { configureEntity(entity) { lifes.remove(it) positions.add(it) } } } @State(Scope.Benchmark) open class FleksStateAddRemove { lateinit var world: World @Setup(value = Level.Iteration) fun setup() { world = World { entityCapacity = NUM_ENTITIES } } } @State(Scope.Benchmark) open class FleksStateSimple { lateinit var world: World @Setup(value = Level.Iteration) fun setup() { world = World { entityCapacity = NUM_ENTITIES system<FleksSystemSimple>() } repeat(NUM_ENTITIES) { world.entity { add<FleksPosition>() } } } } @State(Scope.Benchmark) open class FleksStateComplex { lateinit var world: World @Setup(value = Level.Iteration) fun setup() { world = World { entityCapacity = NUM_ENTITIES system<FleksSystemComplex1>() system<FleksSystemComplex2>() } repeat(NUM_ENTITIES) { world.entity { add<FleksPosition>() add<FleksSprite>() } } } } @Fork(1) @Warmup(iterations = WARMUPS) @Measurement(iterations = ITERATIONS, time = TIME, timeUnit = TimeUnit.SECONDS) open class FleksBenchmark { @Benchmark fun addRemove(state: FleksStateAddRemove) { repeat(NUM_ENTITIES) { state.world.entity { add<FleksPosition>() } } repeat(NUM_ENTITIES) { state.world.remove(Entity(it)) } } @Benchmark fun simple(state: FleksStateSimple) { repeat(WORLD_UPDATES) { state.world.update(1f) } } @Benchmark fun complex(state: FleksStateComplex) { repeat(WORLD_UPDATES) { state.world.update(1f) } } }
2
Kotlin
3
16
1d59527c7c9a2f5e214d7f4ac7ed6a772f2101c8
3,357
Fleks
MIT License
ui-home/src/main/java/dev/sasikanth/twine/home/HomeViewModel.kt
msasikanth
516,650,081
false
{"Kotlin": 364930}
package dev.sasikanth.twine.home import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import dagger.hilt.android.lifecycle.HiltViewModel import dev.sasikanth.twine.common.utils.TweetLinkParser import dev.sasikanth.twine.data.clipboard.Clipboard import dev.sasikanth.twine.data.database.entities.RecentConversation import dev.sasikanth.twine.data.database.repository.TweetsRepository import dev.sasikanth.twine.data.sync.ConversationSyncQueue import dev.sasikanth.twine.data.sync.ConversationSyncQueueItem import dev.sasikanth.twine.data.sync.Status import dev.sasikanth.twine.home.usecase.PagedSourceUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val clipboard: Clipboard, private val tweetLinkParser: TweetLinkParser, private val conversationSyncQueue: ConversationSyncQueue, private val tweetsRepository: TweetsRepository, pagedRecentConversationsUseCase: PagedSourceUseCase<RecentConversation> ) : ViewModel() { private val defaultUiState = HomeUiState.DEFAULT private val _homeUiState = MutableStateFlow(defaultUiState) val homeUiState: StateFlow<HomeUiState> get() = _homeUiState.asStateFlow() val recentConversations = pagedRecentConversationsUseCase .invoke( pagingSourceFactory = { tweetsRepository.recentConversations() } ) .cachedIn(viewModelScope) init { viewModelScope.launch { conversationSyncQueue .queue() .collect { syncQueue -> _homeUiState.update { it.onSyncQueueLoaded(syncQueue) } } } } fun tweetUrlChanged(tweetUrl: String?) { _homeUiState.update { it.onTweetUrlChanged(tweetUrl = tweetUrl) } } fun pasteUrl() { val clipboardContent = clipboard.content if (!clipboardContent.isNullOrBlank()) { tweetUrlChanged(tweetUrl = clipboardContent) validateAndSync() } } fun clearUrl() { tweetUrlChanged(tweetUrl = null) } fun validateAndSync() { val tweetLink = _homeUiState.value.tweetUrl.orEmpty() val isAValidTweetLink = tweetLinkParser.isAValidTweetUrl(tweetLink = tweetLink) if (!isAValidTweetLink) { _homeUiState.update { it.invalidUrl() } } else { val tweetId = tweetLinkParser.getId(tweetLink)!! val tweetBy = tweetLinkParser.getUserName(tweetLink)!! val conversationSyncQueueItem = ConversationSyncQueueItem( tweetId = tweetId, tweetBy = tweetBy ) conversationSyncQueue.add(conversationSyncQueueItem) clearUrl() } } fun cancelSync(item: ConversationSyncQueueItem) { conversationSyncQueue.remove(item) } fun retrySync(item: ConversationSyncQueueItem) { conversationSyncQueue.remove(item) conversationSyncQueue.add(item.updateStatus(Status.Enqueued)) } }
1
Kotlin
0
27
6c259de1a818da155a29a3837a85326e1b132955
3,069
tweet-unroll-android
Apache License 2.0
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ec2/CfnEnclaveCertificateIamRoleAssociationPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.ec2 import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.ec2.CfnEnclaveCertificateIamRoleAssociationProps /** * Properties for defining a `CfnEnclaveCertificateIamRoleAssociation`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ec2.*; * CfnEnclaveCertificateIamRoleAssociationProps cfnEnclaveCertificateIamRoleAssociationProps = * CfnEnclaveCertificateIamRoleAssociationProps.builder() * .certificateArn("certificateArn") * .roleArn("roleArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-enclavecertificateiamroleassociation.html) */ @CdkDslMarker public class CfnEnclaveCertificateIamRoleAssociationPropsDsl { private val cdkBuilder: CfnEnclaveCertificateIamRoleAssociationProps.Builder = CfnEnclaveCertificateIamRoleAssociationProps.builder() /** * @param certificateArn The ARN of the ACM certificate with which to associate the IAM role. */ public fun certificateArn(certificateArn: String) { cdkBuilder.certificateArn(certificateArn) } /** * @param roleArn The ARN of the IAM role to associate with the ACM certificate. * You can associate up to 16 IAM roles with an ACM certificate. */ public fun roleArn(roleArn: String) { cdkBuilder.roleArn(roleArn) } public fun build(): CfnEnclaveCertificateIamRoleAssociationProps = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
1,795
awscdk-dsl-kotlin
Apache License 2.0
src/main/kotlin/com/github/fabianloewe/imagediff/extractors/lsb/Types.kt
fabianloewe
753,265,420
false
{"Kotlin": 44750}
package com.github.fabianloewe.imagediff.extractors.lsb enum class ColorChannel { RED, GREEN, BLUE, ALPHA }
0
Kotlin
0
0
b3cb397fc7ed4b6f15741002b13aef156c7df22a
112
image-diff
MIT License
mobile/src/main/java/universum/mind/synergy/device/headset/data/MeditationDataObservable.kt
roman104
131,326,615
false
null
/* * ************************************************************************************************* * Copyright 2018 Universum Studios * ************************************************************************************************* * 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 universum.mind.synergy.device.headset.data import io.reactivex.Observer import universum.mind.synergy.device.headset.Headset import universum.mind.synergy.device.headset.OnMeditationListener /** * @author <NAME> */ internal class MeditationDataObservable(headset: Headset) : HeadsetDataObservable<MeditationData>(headset) { companion object { const val TAG = "MeditationDataObservable" } override fun onCreateDataDisposable(headset: Headset, observer: Observer<in MeditationData>): DataDisposable<MeditationData> = MeditationDataDisposable(headset, observer) private class MeditationDataDisposable(headset: Headset, observer: Observer<in MeditationData>) : HeadsetDataObservable.DataDisposable<MeditationData>(TAG, headset, observer), OnMeditationListener { override fun onRegisterDataListener(headset: Headset) = headset.registerOnMeditationListener(this) override fun onMeditationChanged(data: MeditationData) { if (isDisposed) { return } notifyNext(data) } override fun onUnregisterDataListener(headset: Headset) = headset.unregisterOnMeditationListener(this) } }
1
Kotlin
0
0
76158c92b7a636b365cb899ce25a828d3b944567
2,256
MakerfaireVienna2018-android
Apache License 2.0
kpermissions/src/test/kotlin/com/fondesa/kpermissions/extension/PermissionRequestExtensionsTest.kt
naseemakhtar994
198,167,072
true
{"Kotlin": 123298, "Groovy": 16841}
/* * Copyright (c) 2018 Fondesa * * 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.fondesa.kpermissions.extension import android.Manifest import com.fondesa.kpermissions.request.PermissionRequest import com.fondesa.kpermissions.request.runtime.nonce.PermissionNonce import com.nhaarman.mockitokotlin2.* import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner /** * Tests for PermissionRequestExtensions.kt extensions. */ @RunWith(RobolectricTestRunner::class) class PermissionRequestExtensionsTest { private val request = mock<PermissionRequest>() @Test fun onAcceptedInvoked() { val expectedPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) var executedPermissions: Array<out String>? = null val acceptedCaptor = argumentCaptor<PermissionRequest.AcceptedListener>() // The permissions will be assigned to the variable if the method is notified. request.onAccepted { executedPermissions = it } // Capture the listener. verify(request).acceptedListener(acceptedCaptor.capture()) verifyNoMoreInteractions(request) // Invoke the method on the captured listener. acceptedCaptor.lastValue.onPermissionsAccepted(expectedPermissions) assertEquals(expectedPermissions, executedPermissions) } @Test fun onDeniedInvoked() { val expectedPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) var executedPermissions: Array<out String>? = null val deniedCaptor = argumentCaptor<PermissionRequest.DeniedListener>() // The permissions will be assigned to the variable if the method is notified. request.onDenied { executedPermissions = it } // Capture the listener. verify(request).deniedListener(deniedCaptor.capture()) verifyNoMoreInteractions(request) // Invoke the method on the captured listener. deniedCaptor.lastValue.onPermissionsDenied(expectedPermissions) assertEquals(expectedPermissions, executedPermissions) } @Test fun onPermanentlyDeniedInvoked() { val expectedPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) var executedPermissions: Array<out String>? = null val permDeniedCaptor = argumentCaptor<PermissionRequest.PermanentlyDeniedListener>() // The permissions will be assigned to the variable if the method is notified. request.onPermanentlyDenied { executedPermissions = it } // Capture the listener. verify(request).permanentlyDeniedListener(permDeniedCaptor.capture()) verifyNoMoreInteractions(request) // Invoke the method on the captured listener. permDeniedCaptor.lastValue.onPermissionsPermanentlyDenied(expectedPermissions) assertEquals(expectedPermissions, executedPermissions) } @Test fun onShouldShowRationaleInvoked() { val expectedPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) val expectedNonce = object : PermissionNonce { override fun use() = Unit } var executedPermissions: Array<out String>? = null var executedNonce: PermissionNonce? = null val rationaleCaptor = argumentCaptor<PermissionRequest.RationaleListener>() // The permissions and the nonce will be assigned to the variables if the method is notified. request.onShouldShowRationale { permissions, nonce -> executedPermissions = permissions executedNonce = nonce } // Capture the listener. verify(request).rationaleListener(rationaleCaptor.capture()) verifyNoMoreInteractions(request) // Invoke the method on the captured listener. rationaleCaptor.lastValue.onPermissionsShouldShowRationale( expectedPermissions, expectedNonce ) assertEquals(expectedPermissions, executedPermissions) assertEquals(expectedNonce, executedNonce) } @Test fun listenersAddedWithDSL() { // Add the listeners with the DSL. request.listeners { onAccepted { } onDenied { } onPermanentlyDenied { } onShouldShowRationale { _, _ -> } } // Verify that all listeners are added. verify(request).acceptedListener(any()) verify(request).deniedListener(any()) verify(request).permanentlyDeniedListener(any()) verify(request).rationaleListener(any()) verifyNoMoreInteractions(request) } }
0
Kotlin
0
0
cc45352c7ce17cc06b1fa11bdf8c622966762b97
5,163
KPermissions
Apache License 2.0
src/main/kotlin/com/tony/liu/plugins/gradle/tree/utils/NodeTextUtils.kt
TonyLiu0112
683,707,324
false
{"Kotlin": 51189, "Java": 6691}
package com.tony.liu.plugins.gradle.tree.utils import org.apache.commons.lang3.StringUtils class NodeTextUtils { companion object { fun getArtifactId(nodeText: String): String { return if (StringUtils.countMatches(nodeText, " : ") == 2) { nodeText.split(" : ")[1] } else { nodeText.split(" : ")[0] } } fun getScope(nodeText: String): String { return StringUtils.substringBetween(nodeText, "[", "]").trim() } } }
0
Kotlin
0
8
80ec890ca8bff586b63c9fc97f24ae75d7ae4349
537
gradle-tree
Apache License 2.0
app/src/main/java/com/krygodev/singlesplanet/repository/ProfileRepositoryImpl.kt
krygo-dev
419,788,067
false
{"Kotlin": 155940}
package com.krygodev.singlesplanet.repository import android.net.Uri import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.HttpException import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageException import com.krygodev.singlesplanet.model.User import com.krygodev.singlesplanet.model.serializeToMap import com.krygodev.singlesplanet.util.Constants import com.krygodev.singlesplanet.util.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.tasks.await import java.io.IOException class ProfileRepositoryImpl( private val _firebaseFirestore: FirebaseFirestore, private val _firebaseStorage: FirebaseStorage ) : ProfileRepository { override suspend fun getUserData(uid: String): Flow<Resource<User>> = flow { emit(Resource.Loading()) try { val result = _firebaseFirestore.collection(Constants.USER_COLLECTION).document(uid).get().await() .toObject(User::class.java) emit(Resource.Success(result!!)) } catch (e: HttpException) { emit(Resource.Error(message = "Something went wrong!")) } catch (e: IOException) { emit(Resource.Error(message = "Couldn't reach server, check your internet connection!")) } catch (e: FirebaseFirestoreException) { emit(Resource.Error(message = e.localizedMessage!!)) } } override suspend fun setOrUpdateUserData(user: User): Flow<Resource<Void>> = flow { emit(Resource.Loading()) try { val result = _firebaseFirestore.collection(Constants.USER_COLLECTION).document(user.uid!!) .update(user.serializeToMap()).await() emit(Resource.Success(result)) } catch (e: HttpException) { emit(Resource.Error(message = "Something went wrong!")) } catch (e: IOException) { emit(Resource.Error(message = "Couldn't reach server, check your internet connection!")) } catch (e: FirebaseFirestoreException) { emit(Resource.Error(message = e.localizedMessage!!)) } } override suspend fun uploadUserPhoto(uid: String, photoURI: Uri): Flow<Resource<Uri>> = flow { emit(Resource.Loading()) try { val result = _firebaseStorage.getReference(Constants.USERS_PHOTOS) .child("$uid.jpg") .putFile(photoURI) .await() val downloadUri = result.storage.downloadUrl.await() emit(Resource.Success(downloadUri)) } catch (e: HttpException) { emit(Resource.Error(message = "Something went wrong!")) } catch (e: IOException) { emit(Resource.Error(message = "Couldn't reach server, check your internet connection!")) } catch (e: StorageException) { emit(Resource.Error(message = e.localizedMessage!!)) } } }
0
Kotlin
0
0
7c4383045a9cf6f6b13aeaa5f016ae714d5dcf1c
3,120
Singles-Planet-Dating-Mobile-App
MIT License
assemblyadapter-common-recycler/src/main/java/androidx/recyclerview/widget/HighPerformanceSpanSizeLookup.kt
panpf
42,781,599
false
null
/* * Copyright (C) 2021 panpf <<EMAIL>> * * 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.recyclerview.widget import android.util.SparseIntArray import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup class HighPerformanceSpanSizeLookup(private val wrapper: SpanSizeLookup) : SpanSizeLookup() { val mSpanSizeCache = SparseIntArray() init { isSpanGroupIndexCacheEnabled = true isSpanIndexCacheEnabled = true } override fun getSpanSize(position: Int): Int { var spanSize = mSpanSizeCache.get(position, -1) if (spanSize == -1) { spanSize = wrapper.getSpanSize(position) mSpanSizeCache.put(position, spanSize) } return spanSize } override fun getSpanGroupIndex(adapterPosition: Int, spanCount: Int): Int { var spanGroupIndex = mSpanGroupIndexCache.get(adapterPosition, -1) if (spanGroupIndex == -1) { spanGroupIndex = super.getSpanGroupIndex(adapterPosition, spanCount) mSpanGroupIndexCache.put(adapterPosition, spanGroupIndex) } return spanGroupIndex } override fun getSpanIndex(position: Int, spanCount: Int): Int { var spanIndex = mSpanIndexCache.get(position, -1) if (spanIndex == -1) { spanIndex = super.getSpanIndex(position, spanCount) mSpanIndexCache.put(position, spanIndex) } return spanIndex } override fun invalidateSpanGroupIndexCache() { super.invalidateSpanGroupIndexCache() mSpanSizeCache.clear() } }
0
Kotlin
33
169
00cf02eb1b2be82685a2997d5473579246e256c8
2,103
assembly-adapter
Apache License 2.0
library/src/main/java/com/inteniquetic/ass/cipher/StorageAlgorithmsCipher.kt
prongbang
834,765,764
false
{"Kotlin": 30554}
package com.inteniquetic.ass.cipher enum class StorageAlgorithmsCipher { AES_CBC_PKCS7_PADDING, AES_GCM_NO_PADDING }
0
Kotlin
0
0
b5ce39492596c44f367ac50d37ed01899b73adb1
125
android-secure-storage
MIT License
FirstProjectInfnet/app/src/main/java/com/poc/firstprojectinfnet/home/navigation/RedirectHomeFlowEnum.kt
OsvaldoAironInfnet
614,215,531
false
null
package com.poc.firstprojectinfnet.home.navigation import com.poc.commom.base.views.navigation.NavigationScreen import com.poc.firstprojectinfnet.R import com.poc.firstprojectinfnet.home.presentation.HomeListFragment enum class RedirectHomeFlowEnum(val navigationScreen: NavigationScreen) { HOME_LIST_FRAGMENT( navigationScreen = NavigationScreen( R.id.homeListFragment, HomeListFragment::class.java.name ) ) }
0
Kotlin
0
0
7ea9f5daf0d64374c29b6054db166f92ae2d4c76
448
Tasks
MIT License
netcode-mcbe/src/main/kotlin/com/valaphee/netcode/mcbeautomation/PacketCodec.kt
valaphee
431,915,568
false
{"Kotlin": 1365906}
/* * Copyright (c) 2021-2022, Valaphee. * * 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.valaphee.netcode.mcbeautomation import com.fasterxml.jackson.module.kotlin.convertValue import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import io.netty.buffer.ByteBufInputStream import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.MessageToMessageCodec import io.netty.handler.codec.http.websocketx.TextWebSocketFrame import java.util.UUID import kotlin.reflect.KClass /** * @author Kevin Ludwig */ class PacketCodec( private val events: Map<String, KClass<out Event>> ) : MessageToMessageCodec<TextWebSocketFrame, Packet>() { private val responses = mutableMapOf<UUID, KClass<out CommandResponse>>() override fun encode(context: ChannelHandlerContext, message: Packet, out: MutableList<Any>) { if (message.header.messagePurpose == Packet.Header.MessagePurpose.CommandRequest && message.body is Command) responses[message.header.requestId!!] = message.body.responseType out.add(TextWebSocketFrame(objectMapper.writeValueAsString(message))) } override fun decode(context: ChannelHandlerContext, `in`: TextWebSocketFrame, out: MutableList<Any>) { val packet = objectMapper.readValue<Packet>(ByteBufInputStream(`in`.content())) out.add(when (packet.header.messagePurpose) { Packet.Header.MessagePurpose.CommandResponse -> responses.remove(packet.header.requestId)?.let { Packet(packet.header, objectMapper.convertValue(packet.body, it.java)) } ?: packet Packet.Header.MessagePurpose.Error -> objectMapper.convertValue<Error>(packet.body!!) Packet.Header.MessagePurpose.Event -> events[packet.header.eventName]?.let { Packet(packet.header, objectMapper.convertValue(packet.body, it.java)) } ?: packet Packet.Header.MessagePurpose.EventSubscribe, Packet.Header.MessagePurpose.EventUnsubscribe -> objectMapper.convertValue<EventRequest>(packet.body!!) else -> packet }) } companion object { const val Name = "automation-codec" private val objectMapper = jacksonObjectMapper() } }
0
Kotlin
0
2
4230a7ed71665360df32601956795b9ce8e2eb6c
2,737
netcode
Apache License 2.0
data/src/main/kotlin/ru/khiraevmalik/theguardiannews/NewsRepositoryImpl.kt
Hiraev
278,637,711
false
null
package ru.khiraevmalik.theguardiannews import ru.khiraevmalik.theguardiannews.api.Api import ru.khiraevmalik.theguardiannews.api.NewsApi import ru.khiraevmalik.theguardiannews.converters.NewsConverter import ru.khiraevmalik.theguardiannews.news.News class NewsRepositoryImpl( private val newsApi: NewsApi ) : NewsRepository { override suspend fun loadNews(pageNumber: Int, pageSize: Int): ContentResult<List<News>> { return try { val result = newsApi.fetchNews(pageNumber, pageSize, Api.TheGuardian.Params.OrderByValue.newest) ContentResult.Success(NewsConverter.convert(result)) } catch (throwable: Throwable) { ContentResult.Error(throwable) } } override suspend fun searchNews(pageNumber: Int, pageSize: Int, query: String): ContentResult<List<News>> { return try { val result = newsApi.searchNews(pageNumber, pageSize, query, Api.TheGuardian.Params.OrderByValue.newest) ContentResult.Success(NewsConverter.convert(result)) } catch (throwable: Throwable) { ContentResult.Error(throwable) } } }
0
Kotlin
0
0
7ea7eb210a4d258aa04d8e1a079e74098c89fbd6
1,147
TheGuardianNews
Apache License 2.0
src/main/kotlin/com/avaquo/starry/queries/Filter.kt
Pairjax
430,216,321
false
{"Kotlin": 35882, "Java": 529}
package com.avaquo.starry.queries import com.avaquo.starry.ids.IDs import com.avaquo.starry.ids.Table import com.avaquo.starry.world.Store /** * A search for an entity based on specific terms. * @param store Reference to the world's storage * @param terms The list of Terms used to compare to a given entity. */ open class Filter( private val store: Store, val terms: MutableList<Term> ) { /** * A robust search tool for finding specific entities in the world based on its individual elements. * @return A list of all entities matching the given terms. */ fun search(): IDs { val foundEntities: IDs = mutableListOf() store.tables.map { table -> if (store.getEntity(table[0]).type.containsAll(terms.map { it.idType })) { foundEntities += table terms.map { term -> if (term.parameter != null) { foundEntities -= trimEntities(term.parameter, table) } } } } return foundEntities } /** * Helper function to find non-matching entities. * @param parameter The specific data to be compared with. * @param table A list of all entities which are being checked * @return A list of all entities which do not match the specified parameter. */ private fun trimEntities(parameter: Any, table: Table): IDs { val trimEntities: IDs = mutableListOf() table.map { e -> if (isInvalidParameter(store.getEntity(e).ids, parameter)) trimEntities += e } return trimEntities } /** Checks if a single entity contains the desired parameter */ private fun isInvalidParameter(elements: IDs, parameter: Any): Boolean { elements.map { if (store.getElement(it) == parameter) return false } return true } }
0
Kotlin
0
1
9b4501de0513ff46110f86e91f02f1dbba9d2ac5
1,897
StarryECS
MIT License
mealkitary-application/src/main/kotlin/com/mealkitary/shop/application/port/output/LoadShopPort.kt
le2sky
640,586,872
false
{"Kotlin": 261380}
package com.mealkitary.shop.application.port.output import com.mealkitary.shop.domain.shop.Shop interface LoadShopPort { fun loadAllShop(): List<Shop> fun loadOneShopById(shopId: Long): Shop }
3
Kotlin
0
2
96d994def17d6114b9cec8c2e043dac68711fb2c
204
mealkitary-server
Apache License 2.0
app/src/main/java/com/example/hiretop/ui/screens/messaging/ChatListScreen.kt
Renekakpo
757,782,501
false
{"Kotlin": 573394}
package com.example.hiretop.ui.screens.messaging import android.util.Log 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.Row import androidx.compose.foundation.layout.Spacer 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.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Badge import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.hiretop.R import com.example.hiretop.models.ChatItemUI import com.example.hiretop.models.UIState import com.example.hiretop.ui.extras.FailurePopup import com.example.hiretop.ui.extras.HireTopCircularProgressIndicator import com.example.hiretop.viewModels.ChatViewModel import com.google.gson.Gson import java.net.URLEncoder @Composable fun ChatListScreen( modifier: Modifier = Modifier, navController: NavController, chatViewModel: ChatViewModel = hiltViewModel() ) { val candidateProfileId by chatViewModel.candidateProfileId.collectAsState(null) val enterpriseProfileId by chatViewModel.enterpriseProfileId.collectAsState(null) val isEnterpriseAccount by chatViewModel.isEnterpriseAccount.collectAsState(null) val chatItemsUI by chatViewModel.chatItemsUI.collectAsState() var uiState by remember { mutableStateOf(UIState.LOADING) } var onErrorMessage by remember { mutableStateOf<String?>(null) } if (!onErrorMessage.isNullOrEmpty()) { FailurePopup( errorMessage = "$onErrorMessage", onDismiss = { onErrorMessage = null } ) } LaunchedEffect(chatViewModel) { if (isEnterpriseAccount == null) { uiState = UIState.LOADING } else { if (isEnterpriseAccount == true) { if (enterpriseProfileId == null) { uiState = UIState.FAILURE } else { chatViewModel.getChatItemsUI( profileId = "$enterpriseProfileId", isEnterpriseAccount = isEnterpriseAccount!!, onSuccess = { uiState = if (chatItemsUI.isNullOrEmpty()) { UIState.FAILURE } else { UIState.SUCCESS } }, onFailure = { onErrorMessage = it uiState = UIState.FAILURE } ) } } else { if (candidateProfileId == null) { uiState = UIState.FAILURE } else { chatViewModel.getChatItemsUI( profileId = "$candidateProfileId", isEnterpriseAccount = isEnterpriseAccount!!, onSuccess = { uiState = if (it.isEmpty()) { UIState.FAILURE } else { UIState.SUCCESS } }, onFailure = { onErrorMessage = it uiState = UIState.FAILURE } ) } } } } when (uiState) { UIState.LOADING -> { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { // Display loader while fetching data HireTopCircularProgressIndicator() } } UIState.FAILURE -> { val failureInfo = if (enterpriseProfileId == null) { stringResource(R.string.enterprise_empty_chat_list_text) } else { stringResource(R.string.candidate_empty_chat_list_text) } Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { // Display text prompting user info Text( text = failureInfo, style = MaterialTheme.typography.titleMedium, modifier = Modifier .wrapContentSize() .padding(16.dp), textAlign = TextAlign.Center ) } } UIState.SUCCESS -> { Column( modifier = modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.background) .padding(15.dp) ) { Text( text = stringResource(R.string.discussions_text), style = MaterialTheme.typography.headlineMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.wrapContentWidth() ) Spacer(modifier = Modifier.height(20.dp)) if (!chatItemsUI.isNullOrEmpty()) { LazyColumn(verticalArrangement = Arrangement.spacedBy(15.dp)) { itemsIndexed(chatItemsUI!!) { _, chatItemUI -> ChatItemRow( chatItemUI = chatItemUI, onChatItemClicked = { try { val encodedURL = URLEncoder.encode(it.pictureUrl, "UTF-8") val chatItemUIJson = Gson().toJson(it.copy(pictureUrl = encodedURL)) navController.navigate(route = "${ChatScreen.route}/$chatItemUIJson") } catch (e: Exception) { Log.d("onChatItemClicked", "${e.message}") } } ) } } } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatItemRow(chatItemUI: ChatItemUI, onChatItemClicked: (ChatItemUI) -> Unit) { Row( modifier = Modifier .fillMaxWidth() .background(color = MaterialTheme.colorScheme.background) .padding(horizontal = 5.dp, vertical = 5.dp) .clickable { onChatItemClicked(chatItemUI) }, verticalAlignment = Alignment.CenterVertically ) { AsyncImage( model = ImageRequest.Builder(context = LocalContext.current) .data(chatItemUI.pictureUrl?.let { URLEncoder.encode(it, "UTF-8") }) .crossfade(true) .build(), contentDescription = stringResource(R.string.chat_item_profile_image_desc), contentScale = ContentScale.Crop, error = painterResource(id = R.drawable.user_profile_placeholder), placeholder = painterResource(id = R.drawable.user_profile_placeholder), modifier = Modifier .size(60.dp) .padding(4.dp) .clip(CircleShape) ) Spacer(modifier = Modifier.width(5.dp)) Column(modifier = Modifier.weight(1f)) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Text( text = if (chatItemUI.profileName.isNullOrEmpty()) stringResource(R.string.unknown_text) else chatItemUI.profileName, style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.wrapContentWidth() ) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Text( text = chatItemUI.offerTitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.wrapContentWidth() ) Spacer(modifier = Modifier.weight(1f)) if (chatItemUI.unreadMessageCount > 0) { Badge( modifier = Modifier.size(30.dp), containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary ) { Text( text = if (chatItemUI.unreadMessageCount > 99) "+99" else "$chatItemUI.unreadMessageCount", style = MaterialTheme.typography.bodySmall, modifier = Modifier.align(alignment = Alignment.CenterVertically) ) } } } } } }
0
Kotlin
0
0
50977e5855fd8a3f532bdd1f6881549fed49356a
11,146
hiretop
MIT License
modules/features/common/src/commonMain/kotlin/com/makeevrserg/kmmplayground/presentation/counter/store/CounterStore.kt
makeevrserg
583,260,374
false
{"Kotlin": 105522, "Swift": 18712, "Ruby": 357}
package com.makeevrserg.kmmplayground.presentation.counter.store import com.arkivanov.mvikotlin.core.store.Store import com.makeevrserg.kmmplayground.presentation.counter.store.CounterStore.Intent import com.makeevrserg.kmmplayground.presentation.counter.store.CounterStore.Label import com.makeevrserg.kmmplayground.presentation.counter.store.CounterStore.State interface CounterStore : Store<Intent, State, Label> { sealed interface Intent { object Increment : Intent object Decrement : Intent } sealed interface Label { object OnIncremented : Label object OnDecremented : Label } data class State( val value: Long = 0L ) }
0
Kotlin
0
1
4a1ff9f6cb52ed49c53d0bf383791e81c0eb8f29
694
KMM-Playground
MIT License
app/src/main/kotlin/com/ceh9/portfolio/common/AppViewModel.kt
CeH9
202,865,791
false
null
package com.ceh9.portfolio.common import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ceh9.portfolio.common.domain.useCases.SystemThemeInteractor import com.ceh9.portfolio.common.presentation.navigation.NavigationAction import com.ceh9.portfolio.common.presentation.navigation.Router import com.ceh9.portfolio.common.presentation.utils.Event import com.ceh9.portfolio.common.utils.mapSuspend import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch /** * Created by CeH9 on 07.10.2019 */ class AppViewModel( private val mIsProcessRestored: Boolean, private val mUncaughtCoExHandler: CoroutineExceptionHandler, private val mSystemThemeInteractor: SystemThemeInteractor, private val mRouter: Router ) : ViewModel() { fun eventNavigationAction(): LiveData<Event<NavigationAction>> { return mRouter.eventNavigationAction() } init { viewModelScope.launch(mUncaughtCoExHandler) { mSystemThemeInteractor.getCurrentTheme() .mapSuspend { themeId -> mSystemThemeInteractor.setCurrentTheme(themeId) } } } }
0
Kotlin
0
0
d4efdcffbee64a02cdb82d73d4f707f322964c40
1,220
Portfolio
MIT License
app/src/main/java/com/roadster/roam/basesetup/module/AppModule.kt
Atul206
510,028,347
false
{"Kotlin": 118252}
package com.roadster.roam.basesetup.module import com.roadster.roam.basesetup.ui.main.BlankViewModel import com.roadster.roam.basesetup.ui.main.ExampleUseCase import com.roadster.roam.basesetup.ui.main.MainViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module var appModule = module { single { ExampleUseCase() } viewModel { MainViewModel(get()) } viewModel { BlankViewModel() } }
0
Kotlin
1
0
46ed3bd53e40ec7edf5a6063c6f8f8e556dc2225
426
baserepo
MIT License
app/src/main/java/vegabobo/languageselector/ui/screen/main/MainScreenVm.kt
VegaBobo
641,658,205
false
{"Kotlin": 66857, "Java": 2997, "AIDL": 507}
package vegabobo.languageselector.ui.screen.main import android.app.Application import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Handler import android.os.Looper import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.topjohnwu.superuser.Shell import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import rikka.shizuku.Shizuku import vegabobo.languageselector.BuildConfig import vegabobo.languageselector.RootReceivedListener import javax.inject.Inject @HiltViewModel class MainScreenVm @Inject constructor( val app: Application ) : ViewModel() { private val _uiState = MutableStateFlow(MainScreenState()) val uiState: StateFlow<MainScreenState> = _uiState.asStateFlow() fun loadOperationMode() { if(Shell.getShell().isAlive) Shell.getShell().close() Shell.getShell() if(Shell.isAppGrantedRoot() == true) { _uiState.update { it.copy(operationMode = OperationMode.ROOT) } RootReceivedListener.onRootReceived() return } val isAvail = Shizuku.pingBinder() && Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED if (isAvail) { _uiState.update { it.copy(operationMode = OperationMode.SHIZUKU) } return } _uiState.update { it.copy(operationMode = OperationMode.NONE) } } init { loadOperationMode() fillListOfApps() } fun fillListOfApps(getAlsoSystemApps: Boolean = false) { _uiState.value.listOfApps.clear() viewModelScope.launch(Dispatchers.IO) { val packageList = getInstalledPackages(getAlsoSystemApps).map { AppInfo( appIcon = app.packageManager.getAppIcon(it), appName = app.packageManager.getLabel(it), appPackageName = it.packageName, ) } val sortedList = packageList.sortedBy { it.appName.lowercase() } _uiState.value.listOfApps.addAll(sortedList) _uiState.update { it.copy(isLoading = false) } } } fun getInstalledPackages(getAlsoSystemApps: Boolean = false): List<ApplicationInfo> { return app.packageManager.getInstalledApplications( PackageManager.ApplicationInfoFlags.of(0) ).mapNotNull { if (!it.enabled) null else if (BuildConfig.APPLICATION_ID == it.packageName) null else if (getAlsoSystemApps) it else if (it.flags and ApplicationInfo.FLAG_SYSTEM == 0) it else null } } fun toggleDropdown() { val newDropdownVisibility = !uiState.value.isDropdownVisible _uiState.update { it.copy(isDropdownVisible = newDropdownVisibility) } } fun toggleSystemAppsVisibility() { val newShowSystemApps = !uiState.value.isShowingSystemApps _uiState.update { it.copy( isSystemAppDialogVisible = false, isLoading = true, isShowingSystemApps = newShowSystemApps ) } fillListOfApps(newShowSystemApps) toggleDropdown() } fun onToggleDisplaySystemApps() { if (!uiState.value.isShowingSystemApps) { val newSystemDialogWarnVisibility = !uiState.value.isSystemAppDialogVisible _uiState.update { it.copy(isSystemAppDialogVisible = newSystemDialogWarnVisibility) } } else { toggleSystemAppsVisibility() _uiState.update { it.copy(isShowingSystemApps = false) } } } fun onClickProceedShizuku() { loadOperationMode() } fun toggleSearch() { val newSearchVisibility = !uiState.value.isSearchVisible if (!newSearchVisibility) _uiState.update { it.copy(searchTextFieldValue = "") } _uiState.update { it.copy(isSearchVisible = newSearchVisibility) } } val searchQuery = mutableStateOf("") private val handler = Handler(Looper.getMainLooper()) private var workRunnable: Runnable? = null fun onSearchTextFieldChange(newText: String) { _uiState.update { it.copy(searchTextFieldValue = newText) } if (workRunnable != null) handler.removeCallbacks(workRunnable!!) workRunnable = Runnable { searchQuery.value = newText } handler.postDelayed(workRunnable!!, 1000) } }
4
Kotlin
11
256
013dd83a3bf12ec0abca5d586c6d76a94c6f1136
4,881
Language-Selector
Apache License 2.0
src/main/kotlin/com/guidovezzoni/gradle/smartproperties/gradle/ConfigScriptBlock.kt
guidovezzoni
246,418,881
false
{"Kotlin": 32846}
package com.guidovezzoni.gradle.smartproperties.gradle import java.io.File /** * Config script block for plugin configuration */ open class ConfigScriptBlock { constructor() @Suppress("unused") constructor(name: String) { this.name = name } var name: String? = null var sourceFile: File? = null var ciEnvironmentPrefix: String? = null var dontRenameProperties: Boolean? = null }
3
Kotlin
0
1
3010397cfab60be1ea81b7bbfc06b5964d88be15
426
smart-properties
Apache License 2.0
app/src/main/java/com/bartonsolutions/ledkovac/MainActivity.kt
Pebin
377,947,797
false
{"Kotlin": 18542}
package com.bartonsolutions.ledkovac import android.Manifest.permission.CAMERA import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import com.bartonsolutions.ledkovac.Constants.SERVER_PORT import com.vmadalin.easypermissions.EasyPermissions import kotlinx.android.synthetic.main.activity_main.* import okhttp3.OkHttpClient import okhttp3.Request import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors typealias RedColorListener = (isRed: Boolean) -> Unit typealias ColorListener = (hsv: FloatArray) -> Unit private const val REQUEST_CODE_CAMERA_PERMISSION = 123 private const val TAG = "MainActivity" class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener { private var dataCounter: TextView? = null private var integrationStatus: TextView? = null private var fpsCount: TextView? = null private var hsvText: TextView? = null private var dataCount: Int = 0 private var database: DatabaseHelper? = null private var lastDetected = false private val client: OkHttpClient = OkHttpClient() private var ipAddress: String? = null private var sendingThread: SyncThread? = null val lastFrames: Queue<Long> = LinkedList() private lateinit var cameraExecutor: ExecutorService public override fun onCreate(savedInstanceState: Bundle?) { Log.i(TAG, "called onCreate") super.onCreate(savedInstanceState) if (!EasyPermissions.hasPermissions(this, CAMERA)) { EasyPermissions.requestPermissions( this, getString(R.string.camera_permissions), REQUEST_CODE_CAMERA_PERMISSION, CAMERA ) } startCamera() window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) setContentView(R.layout.activity_main) cameraExecutor = Executors.newSingleThreadExecutor() database = DatabaseHelper(this) dataCount = database!!.getFlashesCount() dataCounter = findViewById<View>(R.id.number_of_detected_flashes) as TextView integrationStatus = findViewById<View>(R.id.integration_status) as TextView fpsCount = findViewById<View>(R.id.fps_count) as TextView hsvText = findViewById<View>(R.id.hsv_text) as TextView val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) sharedPreferences.registerOnSharedPreferenceChangeListener(this) ipAddress = sharedPreferences.getString("ip_address", null) if (!ipAddress.isNullOrEmpty()) { testEndpoint() } sendingThread = SyncThread(this) sendingThread!!.start() } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(camera_view.surfaceProvider) } val imageAnalyzer = ImageAnalysis.Builder() .build() .also { it.setAnalyzer(cameraExecutor, RedColorAnalyzer({ isRed -> if (isRed && !lastDetected) { database?.insertFlash(Date()) dataCount += 1 runOnUiThread{ dataCounter?.text = dataCount.toString() } lastDetected = true } if (!isRed && lastDetected) { lastDetected = false } update_fps() }, { hsv -> runOnUiThread { hsvText?.text = String.format("%.2f --- %.2f --- %.2f", hsv[0], hsv[1], hsv[2]) } })) } // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle( this, cameraSelector, preview, imageAnalyzer ) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_settings) { startActivity(Intent(this, SettingsActivity::class.java)) } return super.onOptionsItemSelected(item) } fun update_fps() { val newTime = System.currentTimeMillis() if (lastFrames.size < 5) { lastFrames.add(newTime) return } val lastFrameTime = lastFrames.remove() val delta = newTime - lastFrameTime val fps = String.format("%.1f", 5 / (delta.toDouble() / 1000)) runOnUiThread{ fpsCount?.text = "FPS: $fps" } } private fun testEndpoint() { Thread { try { val request = Request.Builder() .url("http://$ipAddress:$SERVER_PORT/") .get() .build() val response = client.newCall(request).execute() response.close() Log.d(TAG, response.body.toString()) setIntegrationStatus(true) } catch (ex: Exception) { Log.e(TAG, ex.toString()) setIntegrationStatus(false) } }.start() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { ipAddress = sharedPreferences!!.getString("ip_address", null) testEndpoint() } fun setIntegrationStatus(working: Boolean) { runOnUiThread{ integrationStatus?.text = "$ipAddress - ${if (working) "✔" else "❌"}" } } }
0
Kotlin
0
0
0d29c99f4c8714e0e70aa0d25ebf9ad71db70013
7,587
ledkovac-client
MIT License
src/main/kotlin/de/debuglevel/simplebenchmark/benchmarks/BenchmarkConfiguration.kt
debuglevel
294,937,712
false
null
package de.debuglevel.simplebenchmark.benchmarks import javax.validation.constraints.Min import javax.validation.constraints.NotBlank open class BenchmarkConfiguration { @NotBlank var enabled: Boolean = false @NotBlank @Min(1L) var iterations: Int = 1 @NotBlank @Min(0L) var baseline: Double = 1.0 }
0
Kotlin
0
0
cd0a6c18506873d491cb0287005ec8056ebaaf32
335
simple-benchmark
The Unlicense
aquarius/src/main/java/ru/haroncode/aquarius/core/clicker/Clickers.kt
HaronCode
296,919,440
false
null
package ru.haroncode.aquarius.core.clicker import android.view.View import androidx.recyclerview.widget.RecyclerView object Clickers { fun <ItemModel, VH : RecyclerView.ViewHolder> none(): Clicker<ItemModel, VH> = NoneClicker() fun <ItemModel, VH : RecyclerView.ViewHolder> default( consumer: (ItemModel) -> Unit ): Clicker<ItemModel, VH> = DefaultClicker(consumer) internal class NoneClicker<ItemModel, VH : RecyclerView.ViewHolder> : Clicker<ItemModel, VH> { override fun onBindClicker(holder: VH) = Unit override fun invoke(holder: VH, view: View, item: ItemModel) = Unit override fun onUnbindClicker(holder: VH) = Unit } }
0
Kotlin
0
4
5ec7e67f6559e057eb7227e485438f03d3cb334f
687
Aquarius
The Unlicense
app/src/main/java/com/kshitijpatil/tazabazar/ui/orders/OrdersViewModel.kt
Kshitij09
395,308,440
false
null
package com.kshitijpatil.tazabazar.ui.orders import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.kshitijpatil.tazabazar.domain.GetUserOrdersUseCase import com.kshitijpatil.tazabazar.domain.ObserveSessionStateUseCase import com.kshitijpatil.tazabazar.domain.Result import com.kshitijpatil.tazabazar.domain.SessionState import com.kshitijpatil.tazabazar.model.Order import com.kshitijpatil.tazabazar.util.UiState import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import timber.log.Timber class OrdersViewModel( private val getUserOrdersUseCase: GetUserOrdersUseCase, private val observeSessionStateUseCase: ObserveSessionStateUseCase ) : ViewModel() { private val _userOrdersState = MutableStateFlow<UiState<List<Order>>>(UiState.Idle) val userOrdersState: StateFlow<UiState<List<Order>>> get() = _userOrdersState.asStateFlow() private val _isLoggedIn = MutableStateFlow(false) val isLoggedIn: StateFlow<Boolean> = observeSessionStateUseCase() .map { it is SessionState.LoggedIn } .stateIn(viewModelScope, SharingStarted.Eagerly, false) private var _selectedOrder: Order? = null /** this field should only be accessed when updateSelectedOrder was succeeded */ val selectedOrder: Order get() = _selectedOrder!! init { viewModelScope.launch { observeLoggedInState() } } private suspend fun observeLoggedInState() { isLoggedIn.collect { loggedIn -> // if the user isn't logged-in anymore and there were fetched // orders for that user, clear them if (!loggedIn && userOrdersState.value is UiState.Success) { _userOrdersState.emit(UiState.Idle) } // load/reload user orders when state changes to logged-in if (loggedIn) loadUserOrders() } } /** Sets the selected order by searching [userOrdersState]'s list by [orderId] * @return true if the current [userOrdersState] is [UiState.Success] and [orderId] * was found in the available list, false otherwise. */ fun updateSelectedOrderById(orderId: String): Boolean { val currentOrderState = _userOrdersState.value if (currentOrderState is UiState.Success) { _selectedOrder = currentOrderState.value.find { it.orderId == orderId } return _selectedOrder != null } return false } private suspend fun loadUserOrders() { Timber.d("called") _userOrdersState.emit(UiState.Loading()) val userOrdersState = when (val result = getUserOrdersUseCase(Unit)) { is Result.Error -> UiState.Error Result.Loading -> UiState.Loading() is Result.Success -> UiState.Success(result.data) } _userOrdersState.emit(userOrdersState) } fun refreshOrdersList() { viewModelScope.launch { loadUserOrders() } } }
8
Kotlin
2
1
d709b26d69cf46c3d6123a217190f098b79a6562
2,975
TazaBazar
Apache License 2.0
ParkingCalc/app/src/main/java/com/isoft/parkingcalc/ParkingApplication.kt
VishnuPrabhu
223,960,704
false
null
package com.isoft.parkingcalc import android.app.Application import androidx.room.Room import com.isoft.parkingcalc.db.VehicleDatabase import com.isoft.parkingcalc.di.ApplicationModule import com.isoft.parkingcalc.di.DaggerApplicationComponent import com.isoft.parkingcalc.di.DatabaseModule class ParkingApplication: Application() { companion object { public lateinit var db: VehicleDatabase } override fun onCreate() { super.onCreate() // Having some issues while integrating dagger. so for now I am using legacy approach of creating singleton instance of db // val applicationComponent = DaggerApplicationComponent // .builder() // .applicationModule(ApplicationModule(this)) // .databaseModule(DatabaseModule(this)) // .build() // applicationComponent.inject(this) db = Room.databaseBuilder(this, VehicleDatabase::class.java, "vehicle_database" ).allowMainThreadQueries().build() } }
0
Kotlin
0
1
bee430ad334a4b446b68d62f2d434f14e47e67e8
1,101
InterviewProblemSolution
Apache License 2.0
core/ui/src/main/java/in/surajsau/jisho/ui/theme/components/JishoScaffold.kt
surajsau
489,927,815
false
null
package `in`.surajsau.jisho.ui.theme.components import androidx.compose.foundation.layout.PaddingValues import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Snackbar import androidx.compose.material3.SnackbarData import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterial3Api::class) @Composable fun JishoScaffold( modifier: Modifier = Modifier, topBar: @Composable () -> Unit, bottomBar: @Composable () -> Unit = {}, snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, content: @Composable (PaddingValues) -> Unit, ) { Scaffold( modifier = modifier, topBar = topBar, bottomBar = bottomBar, snackbarHost = { SnackbarHost( hostState = snackbarHostState, snackbar = { snackBarData -> JishoSnackBar(snackBarData) } ) }, content = content ) } @Composable fun JishoSnackBar( snackBarData: SnackbarData ) { Snackbar( containerColor = MaterialTheme.colorScheme.primaryContainer, actionColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, snackbarData = snackBarData ) } @Preview @Composable fun Preview() { JishoScaffold( topBar = {}, content = {} ) }
0
Kotlin
0
1
f926cd4111d7d19f1f4853cff13200b4d00f5760
1,690
Multiplatform-Jisho
Apache License 2.0
app/src/main/java/com/sunnyweather/android/ui/weather/WeatherViewModel.kt
guokun1998
357,155,529
false
null
package com.sunnyweather.android.ui.weather import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.sunnyweather.android.logic.Repository import com.sunnyweather.android.logic.model.Location import com.sunnyweather.android.logic.model.Place class WeatherViewModel : ViewModel() { private val locationLiveData = MutableLiveData<Location>() var locationLng = "" var locationLat = "" var placeName = "" // 监听locationLiveData变化时,刷新天气 val weatherLiveData = Transformations.switchMap(locationLiveData) { location -> Repository.refreshWeather(location.lng, location.lat) } // 刷新天气,通过更改locationLiveData触发监听而刷新 fun refreshWeather(lng: String, lat: String) { locationLiveData.value = Location(lng, lat) } /** * 变更当前主页天气地点 */ fun changeLocation(place: Place) { placeName = place.name locationLat = place.location.lat locationLng = place.location.lng } }
0
Kotlin
0
0
0e1f1be2240d842b422c353fe24aaf74b624542b
1,029
SunnyWeather
Apache License 2.0
content-types/content-types-core-model/src/main/kotlin/org/orkg/contenttypes/domain/ComparisonConfig.kt
TIBHannover
197,416,205
false
{"Kotlin": 6060326, "Cypher": 220506, "Python": 4881, "Shell": 2904, "Groovy": 1936, "HTML": 240, "Batchfile": 82}
package org.orkg.contenttypes.domain data class ComparisonConfig( val predicates: List<String>, val contributions: List<String>, val transpose: Boolean, val type: ComparisonType, val shortCodes: List<String> = emptyList() ) enum class ComparisonType { PATH, MERGE }
0
Kotlin
0
4
c80778b8800a0ad6698eecfa6bdb0e198aa8f7bb
296
orkg-backend
MIT License
tanker-bindings/src/androidTest/kotlin/io/tanker/api/Datastore.kt
TankerHQ
160,205,806
false
{"Kotlin": 204429, "Python": 9014, "Java": 1665, "Assembly": 693, "CMake": 384, "C++": 373, "Shell": 174}
package io.tanker.api import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.Rule import org.junit.rules.TemporaryFolder import com.sun.jna.* import io.tanker.bindings.DatastoreLib import io.tanker.datastore.* typealias AdminPointer = Pointer @Suppress("FunctionName") internal interface DatastoreTestsLib : DatastoreLib, Library { companion object { fun create(): DatastoreTestsLib { System.setProperty("jna.debug_load", "true") return Native.load("tankerdatastoretests", DatastoreTestsLib::class.java) } } fun tanker_run_datastore_test(datastore_options: DatastoreOptions, persistent_path: String): Int } class DatastoreTests : TankerSpec() { @Rule @JvmField var tempFolder = TemporaryFolder() @Test fun runs_datastore_tests() { val datastoreTests = DatastoreTestsLib.create() val datastoreOptions = DatastoreOptions(datastoreTests) val ret = datastoreTests.tanker_run_datastore_test(datastoreOptions, tempFolder.root.toString()) assertThat(ret).withFailMessage("Datastore tests have failed, please read logcat's output") .isEqualTo(0) } }
0
Kotlin
1
13
8bba26a4b6376669ea53712def3dcac6387005f7
1,215
sdk-android
Apache License 2.0
presentation/src/main/java/com/bugeto/presentation/di/AppModule.kt
maysambabaei
240,897,471
false
null
package com.bugeto.presentation.di import androidx.room.Room import com.bugeto.data.api.RemoteNewsApi import com.bugeto.data.db.NewsDatabase import com.bugeto.data.entities.NewsDataEntityMapper import com.bugeto.data.entities.NewsEntityDataMapper import com.bugeto.data.repository.NewsCacheImpl import com.bugeto.domain.usecases.GetNewsUseCase import com.bugeto.data.repository.NewsRemoteImpl import com.bugeto.data.repository.NewsRepositoryImpl import com.bugeto.domain.repositories.NewsRepository import com.bugeto.presentation.common.AsyncFlowableTransformer import org.koin.android.viewmodel.ext.koin.viewModel import org.koin.dsl.module.module import com.bugeto.presentation.news.NewsViewModel import com.bugeto.presentation.mappers.NewsEntityMapper import org.koin.android.ext.koin.androidApplication import retrofit2.Retrofit val mRepositoryModules = module { single(name = "remote") { NewsRemoteImpl(api = get(API)) } single(name = "local") { NewsCacheImpl(database = get(DATABASE), entityToDataMapper = NewsEntityDataMapper(), dataToEntityMapper = NewsDataEntityMapper()) } single { NewsRepositoryImpl(remote = get("remote"), cache = get("local")) as NewsRepository } } val mUseCaseModules = module { factory(name = "getNewsUseCase") { GetNewsUseCase(transformer = AsyncFlowableTransformer(), repositories = get()) } } val mNetworkModules = module { single(name = RETROFIT_INSTANCE) { createNetworkClient(BASE_URL) } single(name = API) { (get(RETROFIT_INSTANCE) as Retrofit).create(RemoteNewsApi::class.java) } } val mLocalModules = module { single(name = DATABASE) { Room.databaseBuilder(androidApplication(), NewsDatabase::class.java, "news_articles").build() } } val mViewModels = module { viewModel { NewsViewModel(getNewsUseCase = get(GET_NEWS_USECASE), mapper = NewsEntityMapper()) } } private const val BASE_URL = "https://newsapi.org/v2/" private const val RETROFIT_INSTANCE = "Retrofit" private const val API = "Api" private const val GET_NEWS_USECASE = "getNewsUseCase" private const val REMOTE = "remote response" private const val DATABASE = "database"
0
Kotlin
0
0
594b6e65d21cf8583558332cea7a29436461b9ec
2,152
KotlinCleanArchitecture
Apache License 2.0
library/src/main/java/cz/mroczis/netmonster/core/Types.kt
mroczis
199,189,308
false
{"Kotlin": 482369}
package cz.mroczis.netmonster.core /** * Numeric value representing some sort of time stamp in milliseconds */ typealias Milliseconds = Long /** * Subscription id as a unique identifier per SIM card in the device */ typealias SubscriptionId = Int
19
Kotlin
71
334
b63cee478b2e637a5d982160090df23e4be8f75c
252
netmonster-core
Apache License 2.0
app/src/main/java/com/wackalooon/ecometer/base/Event.kt
Wackaloon
56,212,468
false
{"Kotlin": 33112}
package com.wackalooon.ecometer.base interface Event { }
0
Kotlin
0
0
40986f366aded16446ce00674323f1ba462c4900
58
EcoMeter
Apache License 2.0
shared/src/androidMain/kotlin/com/jittyandiyan/shared/core/architecture/view/KMMActivity.kt
jittya
361,707,096
false
null
package com.jittyandiyan.shared.core.architecture.view import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.viewbinding.ViewBinding import com.jittyandiyan.shared.core.architecture.viewModel.BaseViewModel import com.jittyandiyan.shared.core.liveData.kLifecycle import com.jittyandiyan.shared.core.platform.expectations.BundleX abstract class KMMActivity<ViewModel,UIViewBinding> : AppCompatActivity() where ViewModel : BaseViewModel<*>,UIViewBinding:ViewBinding { private lateinit var viewModel: ViewModel private var progressDialog: ProgressDialog? = null lateinit var binding:UIViewBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=viewBindingInflate() viewModel = initializeViewModel() viewModel.setLifeCycle(this.kLifecycle()) intent.extras?.keySet()?.filterNotNull()?.forEach { key -> getViewModel().setBundleValue(key, intent.extras!![key]) } setContentView(binding.root) } override fun onResume() { super.onResume() viewModel.onInit() } override fun onDestroy() { super.onDestroy() viewModel.onDetached() } fun getViewModel(): ViewModel { return viewModel } abstract fun initializeViewModel(): ViewModel abstract fun viewBindingInflate():UIViewBinding fun setPageTitle(title: String) { this.title=title } fun showPopUpMessage(message: String) { AlertDialog.Builder(this).setMessage(message) .setPositiveButton( "OK" ) { dialog, which -> dialog?.dismiss() } .create().show() } fun showPopUpMessage(title: String, message: String) { AlertDialog.Builder(this).setTitle(title).setMessage(message) .setPositiveButton( "OK" ) { dialog, which -> dialog?.dismiss() } .create().show() } fun showLoading(loadingLabel: String) { progressDialog = ProgressDialog(this) progressDialog?.setMessage(loadingLabel) progressDialog?.show() } fun dismissLoading() { progressDialog?.dismiss() } fun openActivity(activity: Class<*>, bundle: BundleX) { var intent = Intent(this, activity) intent.putExtras(bundle.bundle) startActivity(intent) } fun openActivity(activity: Class<*>) { var intent = Intent(this, activity) startActivity(intent) } }
0
Kotlin
6
125
3a30c984b215b6df4a90d4a7a5ce965127b9ca09
2,671
KMMT
MIT License
app/src/main/java/com/aappeye/foreksty/data/repository/ForecastRepositoryImpl.kt
ihjohny
198,017,929
false
null
package com.aappeye.foreksty.data.repository import android.util.Log import androidx.lifecycle.LiveData import com.aappeye.foreksty.data.db.CurrentWeatherDao import com.aappeye.foreksty.data.db.DailyWeatherDao import com.aappeye.foreksty.data.db.HourlyWeatherDao import com.aappeye.foreksty.data.db.WeatherLocationDao import com.aappeye.foreksty.data.db.entity.CurrentWeatherEntry import com.aappeye.foreksty.data.db.entity.DailyWeatherEntry import com.aappeye.foreksty.data.db.entity.HourlyWeatherEntry import com.aappeye.foreksty.data.db.entity.WeatherLocationEntry import com.aappeye.foreksty.data.network.WeatherNetworkDataSource import com.aappeye.foreksty.data.network.response.WeatherResponse import com.aappeye.foreksty.data.provider.LocationProvider import com.aappeye.foreksty.data.provider.SettingsProvider import kotlinx.coroutines.* import org.threeten.bp.ZonedDateTime import javax.inject.Inject class ForecastRepositoryImpl @Inject constructor( private val currentWeatherDao: CurrentWeatherDao, private val hourlyWeatherDao: HourlyWeatherDao, private val dailyWeatherDao: DailyWeatherDao, private val weatherLocationDao: WeatherLocationDao, private val weatherNetworkDataSource: WeatherNetworkDataSource, private val settingsProvider: SettingsProvider, private val locationProvider: LocationProvider ) : ForecastRepository { init { weatherNetworkDataSource.apply { downloadedWeather.observeForever { newWeather -> presistFetchedWeather(newWeather) } } } private suspend fun initWeatherData() { val lastWeatherLocation = weatherLocationDao.getLocationNonLive() if (lastWeatherLocation == null || isUpdateFreq(lastWeatherLocation.zonedDateTime)) { fetchWeather() } } private fun presistFetchedWeather(fetchedWeather: WeatherResponse) { GlobalScope.launch(Dispatchers.IO) { currentWeatherDao.upsert(fetchedWeather.currentWeatherEntry) hourlyWeatherDao.deleteOldEntries() hourlyWeatherDao.insert(fetchedWeather.hourlyWeatherEntries.hourlyentries) dailyWeatherDao.deleteOldEntries() dailyWeatherDao.insert(fetchedWeather.dailyWeatherEntries.dailyentries) weatherLocationDao.upsert( WeatherLocationEntry( fetchedWeather.latitude, fetchedWeather.longitude, fetchedWeather.timezone, fetchedWeather.currentWeatherEntry.time ) ) } } override suspend fun getCurrentWeather(): LiveData<CurrentWeatherEntry> { return withContext(Dispatchers.IO) { return@withContext currentWeatherDao.getWeather() } } override suspend fun getHourlyWeatherList(): LiveData<List<HourlyWeatherEntry>> { return withContext(Dispatchers.IO) { return@withContext hourlyWeatherDao.getHourlyWeather() } } override suspend fun getTodayWeather(): LiveData<DailyWeatherEntry> { return withContext(Dispatchers.IO) { return@withContext dailyWeatherDao.getTodayWeather() } } override suspend fun getDailyWeatherList(): LiveData<List<DailyWeatherEntry>> { return withContext(Dispatchers.IO) { return@withContext dailyWeatherDao.getDailyWeather() } } override suspend fun getWeatherLocation(): LiveData<WeatherLocationEntry> { return withContext(Dispatchers.IO) { initWeatherData() return@withContext weatherLocationDao.getLocation() } } private suspend fun fetchWeather() { weatherNetworkDataSource.fetchWeather( locationProvider.getPreferredLocationString(), settingsProvider.getPreferredLanguage() ) } private fun isUpdateFreq(lastFetchTime: ZonedDateTime): Boolean { val updateFrequency = settingsProvider.getPreferredUpdateFrequency().toLong() val minutesAgo = ZonedDateTime.now().minusMinutes(updateFrequency) //update frequency return lastFetchTime.isBefore(minutesAgo) } }
0
Kotlin
0
5
30f80e8f604b92bce1e7c13b8bc9e260d57980a1
4,189
Foreksty
Apache License 2.0
17-rxbindings/projects/starter/app/src/test/java/com/raywenderlich/android/hexcolor/ViewModelTest.kt
kodecocodes
289,350,935
false
{"Shell": 1914}
package com.raywenderlich.android.hexcolor import androidx.arch.core.executor.testing.InstantTaskExecutorRule import io.mockk.mockk import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.internal.schedulers.TrampolineScheduler import io.reactivex.rxjava3.schedulers.TestScheduler import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule class ViewModelTest { @get:Rule var rule: TestRule = InstantTaskExecutorRule() @Test fun `color is red when hex string is FF0000`() { val viewModel = buildViewModel() viewModel.digitClicked("F") viewModel.digitClicked("F") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") Assert.assertEquals(viewModel.colorNameLiveData.value, ColorName.RED.toString()) } @Test fun `color is red when hex string is FF0000 using test scheduler`() { val testScheduler = TestScheduler() val viewModel = buildViewModel( backgroundScheduler = testScheduler, mainScheduler = testScheduler ) viewModel.digitClicked("F") viewModel.digitClicked("F") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") Assert.assertEquals(viewModel.colorNameLiveData.value, null) testScheduler.triggerActions() Assert.assertEquals(viewModel.colorNameLiveData.value, ColorName.RED.toString()) } @Test fun `hex subject is reset after clear is clicked`() { val viewModel = buildViewModel() viewModel.digitClicked("F") viewModel.digitClicked("F") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") viewModel.digitClicked("0") Assert.assertEquals("#FF0000", viewModel.hexStringSubject.value) viewModel.clearClicked() Assert.assertEquals("#", viewModel.hexStringSubject.value) } private fun buildViewModel( backgroundScheduler: Scheduler = TrampolineScheduler.instance(), mainScheduler: Scheduler = TrampolineScheduler.instance() ): ColorViewModel { return ColorViewModel( backgroundScheduler, mainScheduler, mockk(), mockk() ) } }
1
Shell
16
35
6961389dd1ebf85b992ad88fd711c98d31276390
2,264
rxa-materials
Apache License 2.0
app/src/main/java/com/fprieto/hms/wearable/presentation/ui/di/FragmentBindingModule.kt
ferPrieto
359,387,500
false
null
package com.fprieto.hms.wearable.presentation.ui.di import androidx.fragment.app.FragmentFactory import com.fprieto.hms.wearable.android.InjectingFragmentFactory import dagger.Binds import dagger.Module @Module abstract class FragmentBindingModule { @Binds abstract fun bindFragmentFactory(factory: InjectingFragmentFactory): FragmentFactory }
0
Kotlin
1
9
b1488e6baafed6d4ff98b615bde46e01b4aa7a9a
354
HMS-Wearable-Example
Apache License 2.0
app/src/main/java/com/dev/moviehut/view/MovieListAdapter.kt
sarojkmri
367,659,414
false
null
package com.dev.moviehut.view import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.dev.moviehut.R import com.dev.moviehut.data.model.Movie import com.dev.moviehut.data.remote.EndPoints import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.movie_item_view.view.* class MovieAdapter(private val context: Context, private var movies: List<Movie>) : RecyclerView.Adapter<MovieAdapter.ItemViewHolder>() { private val clickSubject = PublishSubject.create<Movie>() val clickEvent: Observable<Movie> = clickSubject inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var nameTextView: TextView = itemView.nameTextView var dateTextView: TextView = itemView.dateTextView var movieImageView: ImageView = itemView.movieImageView } fun update(movies: List<Movie>) { this.movies = movies notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val itemView: View = LayoutInflater.from(parent.context) .inflate(R.layout.movie_item_view, parent, false) return ItemViewHolder(itemView) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val movie = movies[position] movie.let { currMovie -> holder.nameTextView.text = currMovie.title holder.dateTextView.text = currMovie.releaseDate Glide.with(context) .load(EndPoints.PHOTO_BASE_URL + currMovie.posterPath) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(holder.movieImageView) holder.itemView.setOnClickListener { clickSubject.onNext(currMovie) } } } override fun getItemCount(): Int { return movies.size } }
0
Kotlin
0
0
92d8c1fdf85bf5f1eff1a39f3851e3bef2901eb1
2,176
MoviehutRepo
MIT License
app/src/main/java/org/oppia/app/options/RouteToReadingTextSizeListener.kt
The-Fuse
290,502,917
true
{"Kotlin": 3041512, "Starlark": 85090, "Java": 27484, "Shell": 1855}
package org.oppia.app.options /** Listener for when an activity should route to a [ReadingTextSizeActivity]. */ interface RouteToReadingTextSizeListener { fun routeReadingTextSize(readingTextSize: String?) }
0
null
0
0
6ee99027a169c501855271b80c0a86ab2cf84420
211
oppia-android
Apache License 2.0
domain/src/main/java/com/vkochenkov/wordlegame/Repository.kt
Kochenkov
469,035,279
false
{"Kotlin": 57431}
package com.vkochenkov.wordlegame import com.vkochenkov.wordlegame.model.Cell import com.vkochenkov.wordlegame.model.Language interface Repository { fun isWordPresent(word: String) : Boolean fun getRandomWord(): List<Char> fun getKeyboard(): List<List<Cell>> fun getLength(): Int fun getLanguage(): Language fun setLanguage(lang: Language) fun getRows(): Int }
10
Kotlin
0
0
7f78b9638f2107d892a0765168818630132b0753
397
AndroidApp-WordleGame
Apache License 2.0
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/models/chat/Message.kt
xebia-functional
629,411,216
false
null
package com.xebia.functional.xef.llm.models.chat data class Message(val role: Role, val content: String, val name: String) { companion object { suspend fun systemMessage(message: suspend () -> String) = Message(role = Role.SYSTEM, content = message(), name = Role.SYSTEM.name) suspend fun userMessage(message: suspend () -> String) = Message(role = Role.USER, content = message(), name = Role.USER.name) suspend fun assistantMessage(message: suspend () -> String) = Message(role = Role.ASSISTANT, content = message(), name = Role.ASSISTANT.name) } }
20
Kotlin
7
81
fe1cca34bb9a8cac63f77b9a1b5ab97964432b1e
587
xef
Apache License 2.0
app/src/main/java/com/example/teknosa/ui/login/LoginActivity.kt
baranac12
377,786,338
false
null
package com.example.teknosa.ui.login import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Gravity.apply import android.widget.Toast import androidx.core.view.GravityCompat.apply import androidx.lifecycle.Observer import com.bumptech.glide.util.Util import com.example.teknosa.R import com.example.teknosa.Utils.Utils import com.example.teknosa.data.model.LoginResponseItem import com.example.teknosa.databinding.ActivityLoginBinding import com.example.teknosa.ui.list.ListViewModel class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding var loginViewModel: LoginViewModel? = null var loginList: List<LoginResponseItem>? = null lateinit var kullaniciAdi: String var alinanaKullaniciAdi: String = "" lateinit var parola: String var alinanParola: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) init(); } private fun init() { binding.apply { btnDontLogin.setOnClickListener { Utils.openNextActivity( Utils.ACTIVITY_SEC.CATEGORY_AC, applicationContext, this@LoginActivity ) } btnLogin.setOnClickListener{ alinanaKullaniciAdi = emailText.text.toString() alinanParola = parolaText.text.toString() initViewModel() } } } fun initViewModel() { loginViewModel = LoginViewModel() loginViewModel?.apply { allTeknosaLiveData?.observe(this@LoginActivity, Observer { it.run { loginList = it for (login: LoginResponseItem in it!!) { kullaniciAdi = login.kullaniciAdi parola = login.parola if (alinanaKullaniciAdi.equals(kullaniciAdi) && alinanParola.equals(parola)) { Utils.mesajGonder(this@LoginActivity,getString(R.string.loginGirisTrue),Utils.MESAJ_UZUNLUK.SHORT) Utils.openNextActivity( Utils.ACTIVITY_SEC.CATEGORY_AC, applicationContext, this@LoginActivity ) }else if(alinanaKullaniciAdi.equals("") || alinanParola.equals("")){ Utils.mesajGonder(this@LoginActivity,getString(R.string.loginGirisNull),Utils.MESAJ_UZUNLUK.SHORT) } else if (alinanaKullaniciAdi.equals(kullaniciAdi)== false && alinanParola.equals(parola)== false) { Utils.mesajGonder( this@LoginActivity, getString(R.string.loginGirisFalse), Utils.MESAJ_UZUNLUK.LONG ) } } } error?.observe(this@LoginActivity, Observer { it.run { } }) loading?.observe(this@LoginActivity, Observer { it.run { } }) }) } } }
0
Kotlin
0
0
5912f2f381970f3a74de56c993c04afdf719797c
3,685
Teknosa
Apache License 2.0
client/core/shared/src/commonMain/kotlin/com/oztechan/ccc/client/core/shared/model/OldPurchase.kt
Oztechan
102,633,334
false
null
package com.oztechan.ccc.client.core.shared.model data class OldPurchase( val date: Long, val type: PremiumType )
19
Kotlin
26
262
ed69a750e7dab82aef6115003243b8e6d5d9f54f
123
CCC
Apache License 2.0
app/src/main/java/com/mkdev/vpnnewdesign/adapter/ConnectionDiffCallback.kt
msddev
398,879,947
false
null
package com.mkdev.vpnnewdesign.adapter import androidx.recyclerview.widget.DiffUtil import com.mkdev.vpnnewdesign.models.ConnectionModel class ConnectionDiffCallback( private val oldList: List<ConnectionModel>, private val newList: List<ConnectionModel> ) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition] override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].isSelected == newList[newItemPosition].isSelected } }
0
Kotlin
3
5
efc2a40d83174c4b079853601d9a651dc837b001
721
VPN-Material-UI-Sample
Apache License 2.0
mobikulOC/src/main/java/webkul/opencart/mobikul/model/GetProduct/ProductPrev.kt
fortunedev223
435,488,584
false
{"Kotlin": 1128789, "Java": 655153}
package webkul.opencart.mobikul.model.GetProduct /** * Created by manish.choudhary on 3/8/17. */ import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class ProductPrev : Parcelable { @SerializedName("product_id") @Expose var productId: String? = null @SerializedName("name") @Expose var name: String? = null protected constructor(`in`: Parcel) { productId = `in`.readString() name = `in`.readString() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(productId) dest.writeString(name) } companion object { @JvmField val CREATOR: Parcelable.Creator<ProductPrev> = object : Parcelable.Creator<ProductPrev> { override fun createFromParcel(`in`: Parcel): ProductPrev { return ProductPrev(`in`) } override fun newArray(size: Int): Array<ProductPrev?> { return arrayOfNulls(size) } } } }
0
Kotlin
0
0
fe2513dab910dc471810fa37d6c01c848712c295
1,160
Boutiquey_Android
MIT License
core/src/commonMain/kotlin/work/socialhub/ktumblr/api/AuthResource.kt
uakihir0
790,148,281
false
{"Kotlin": 104222, "Ruby": 2171, "Shell": 2118, "Makefile": 288}
package work.socialhub.ktumblr.api import work.socialhub.ktumblr.api.request.auth.AuthAuthorizeUrlRequest import work.socialhub.ktumblr.api.request.auth.AuthOAuth2TokenRefreshRequest import work.socialhub.ktumblr.api.request.auth.AuthOAuth2TokenRequest import work.socialhub.ktumblr.api.response.Response import work.socialhub.ktumblr.api.response.auth.AuthOAuth2TokenResponse import kotlin.js.JsExport @JsExport interface AuthResource { fun authorizeUrl( request: AuthAuthorizeUrlRequest ): String fun oAuth2Token( request: AuthOAuth2TokenRequest ): Response<AuthOAuth2TokenResponse> fun oAuth2TokenRefresh( request: AuthOAuth2TokenRefreshRequest ): Response<AuthOAuth2TokenResponse> }
0
Kotlin
0
1
1dcf73e589421dec7dfb2b7195f2b818dcacabdc
739
ktumblr
MIT License
composeApp/src/commonMain/kotlin/screens/Mobile/CryptoListScreen.kt
FernandoSini
803,072,673
false
{"Kotlin": 93174, "Swift": 636}
package screens.Mobile import androidx.compose.foundation.ExperimentalFoundationApi 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.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import cafe.adriel.voyager.core.screen.Screen import coil3.compose.AsyncImage import coil3.compose.LocalPlatformContext import coil3.request.ImageRequest import coil3.request.crossfade import coil3.size.Size import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.DecimalMode import com.ionspin.kotlin.bignum.decimal.RoundingMode import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import models.CryptoCoin import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.ui.tooling.preview.Preview import screens.Mobile.view.CryptoViewModel import screens.Mobile.view.ThemeViewModel import utlis.ThemeUI import utlis.round class CryptoListScreen : Screen { @OptIn( ExperimentalResourceApi::class, ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class, ExperimentalFoundationApi::class, ) @Composable @Preview override fun Content() { var searchText by remember { mutableStateOf("") } var loading by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() //var errorMessage by remember { mutableStateOf("") } //val cryptos by remember { mutableStateOf(emptySet<CryptoCoin>()) } val cryptoViewModel = viewModel<CryptoViewModel>() { CryptoViewModel() } val themeViewModel = viewModel<ThemeViewModel>() { ThemeViewModel() } val isDarkMode = themeViewModel.isDarkMode.collectAsState() val cryptos by cryptoViewModel.cryptoCoins.collectAsState() val errorMessage by cryptoViewModel.errorMessage.collectAsState() loading = cryptoViewModel.loading.collectAsState().value val pullRefreshState = rememberPullRefreshState( refreshing = loading, onRefresh = { cryptoViewModel.fetchCryptoCoins(searchText) }, refreshThreshold = 30.dp, refreshingOffset = 60.dp ) LaunchedEffect(searchText) { scope.launch { cryptoViewModel.fetchCryptoCoins(searchText); } } if (loading) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { CircularProgressIndicator( Modifier.height(50.dp).width(50.dp), ThemeUI().textFieldColor ) } } else { Box(modifier = Modifier.pullRefresh(pullRefreshState)) { CryptoItems(cryptos.toMutableList(), errorMessage, pullRefreshState, loading, isDarkMode.value) PullRefreshIndicator( refreshing = loading, state = pullRefreshState, modifier = Modifier.align(Alignment.TopCenter) ) } } } @OptIn( ExperimentalResourceApi::class, ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class, ExperimentalFoundationApi::class, ) @Composable @Preview fun CryptoItems( cryptos: List<CryptoCoin>, errorMessage: String, pullRefreshState: PullRefreshState, loading: Boolean, isDarkMode: Boolean, ) { val MILLION = 1000000L val BILLION = 1000000000L val TRILLION = 1000000000000L if (!cryptos.isNullOrEmpty()) { LazyVerticalGrid( columns = GridCells.Adaptive(minSize = 400.dp), verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.padding(top = 20.dp) ) { items(cryptos) { Card( colors = CardDefaults.cardColors(if (!isDarkMode) ThemeUI().lightGray else ThemeUI().cardItemBlue), modifier = Modifier.height(50.dp).padding(horizontal = 15.dp).clickable { if (it.links !== null) { } }, content = { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.padding(start = 15.dp, end = 15.dp) ) { Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth(0.5f).padding(top = 5.dp), content = { Text( it.rank.toString(), style = TextStyle(color = if (!isDarkMode) ThemeUI().primaryBackground else ThemeUI().white) ) Spacer(Modifier.padding(10.dp)) Column( horizontalAlignment = Alignment.Start, ) { AsyncImage( ImageRequest.Builder( LocalPlatformContext.current ).data(it.png64 ?: it.png32).crossfade(true) .size(Size.ORIGINAL).build(), contentDescription = null, modifier = Modifier.size(40.dp), ) } Spacer(Modifier.padding(5.dp)) Column( horizontalAlignment = Alignment.Start, content = { Text( it.code.toString(), style = TextStyle(color = if (!isDarkMode) ThemeUI().primaryBackground else ThemeUI().white), fontSize = 14.sp, ) Text( it.name.toString(), style = TextStyle(color =if (!isDarkMode) ThemeUI().primaryBackground else ThemeUI().white), fontSize = 12.sp, ) }, ) }, ) Spacer(Modifier.padding(10.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Column(horizontalAlignment = Alignment.Start) { Text( "\$${it.rate?.round(2).toString()}", style = TextStyle(color = if (!isDarkMode) ThemeUI().primaryBackground else ThemeUI().white), textAlign = TextAlign.Start, ) } Spacer(Modifier.padding(5.dp)) Column(horizontalAlignment = Alignment.Start) { Text( when { it?.cap == null -> "null" it.cap < MILLION -> "\$${it?.cap.toString()}k" it.cap < BILLION -> "\$${ it?.cap?.times(100)?.div(MILLION) ?.times(0.01) }M" it.cap < TRILLION -> "\$${ it?.cap?.times(100)?.div(BILLION)?.times(0.01) ?.round(2) }B" else -> "\$${ it?.cap?.times(100)?.div(TRILLION)?.times(0.01) }T" }, style = TextStyle(color = if (!isDarkMode) ThemeUI().primaryBackground else ThemeUI().white), textAlign = TextAlign.Start, ) } } } } ) } } } else { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(errorMessage, style = TextStyle(color = Color.White), color = ThemeUI().white) } } } }
0
Kotlin
0
0
859d1100e3e8b62dfa89a4fc384e50fa59c987a6
12,192
cryptoApp
Apache License 2.0
domain/src/main/kotlin/com/bykov/footea/models/FootballTeamDetails.kt
grine4ka
419,372,892
false
null
package com.bykov.footea.models data class FootballTeamDetails( val id: Int, val name: String, val country: String, val venue: String, val badgeUrl: String )
7
Kotlin
0
1
e1431d8f4d4f84048f21fd0d45a7466886e60301
179
footea
MIT License
MapGenerator/src/main/kotlin/Generator/GraphGenerator.kt
Mopchik
489,210,419
false
{"Kotlin": 59364, "Assembly": 354}
package generator import kotlin.random.Random class GraphGenerator(val mapSize:Int) { private var matr:MutableList<MutableList<Int>> private val n:Int private val kOfEdges:Double init{ matr = ArrayList() n = Random.nextInt((mapSize / 3.0).toInt(), (mapSize).toInt()) kOfEdges = (mapSize.toDouble() / n) * (mapSize.toDouble() / n) / Random.nextInt(20,30) } fun generateGraphMatr():MutableList<MutableList<Int>>{ for(i in 0 until n){ matr.add(ArrayList()) } val notConnected = (0 until n).toMutableList() val isBlack = MutableList(n){false} isBlack[0] = false notConnected.remove(0) generateEdges(notConnected, 0, isBlack) return matr } private fun generateEdges(notConnected:MutableList<Int>, v:Int, isBlack:MutableList<Boolean>){ if(notConnected.isNotEmpty()) { val t = notConnected.random() matr[v].add(t) matr[t].add(v) notConnected.remove(t) } var koef:Double //var i = 0 // while(i < notConnected.size){ // if(matr[v].size > 2) koef /= (matr[v].size) // if(Random.nextDouble(matr.size.toDouble()) < koef) { // matr[v].add(notConnected[i]) // matr[notConnected[i]].add(v) // notConnected.removeAt(i) // } else i++ // } val range = (0 until matr.size).filter{it != v}.toMutableList() val koefOfFirst = kOfEdges val koefOfNext = 0.4 koef = koefOfFirst range.forEach { if(!matr[v].contains(it)) { if(matr[v].size >= 2) koef /= (matr[v].size) if (Random.nextDouble(matr.size.toDouble()) <=koef) { matr[v].add(it) matr[it].add(v) if(koef == koefOfFirst) koef = koefOfNext if(notConnected.contains(it)){ notConnected.remove(it) } } } } val matrixCopy = ArrayList<Int>() matr[v].forEach { matrixCopy.add(it) } matrixCopy.forEach{ if(!isBlack[it]){ isBlack[it] = true generateEdges(notConnected, it, isBlack) } } } }
0
Kotlin
0
1
a92762772284c7d44ecd192f8f67559cdb96a70e
2,386
MapGenerator
Apache License 2.0
app/src/main/java/com/tugrulbo/foodrecipe/data/remote/RemoteDataSource.kt
tugrulbo
524,135,237
false
{"Kotlin": 59790}
package com.tugrulbo.foodrecipe.data.remote import com.tugrulbo.foodrecipe.data.model.FoodRecipe import retrofit2.Response import javax.inject.Inject class RemoteDataSource @Inject constructor( private val foodRecipeApi: FoodRecipeApi ) { suspend fun getRecipes(queries: Map<String,String>):Response<FoodRecipe>{ return foodRecipeApi.getRecipes(queries) } suspend fun searchRecipes(queries: Map<String, String>):Response<FoodRecipe>{ return foodRecipeApi.searchRecipes(queries) } }
0
Kotlin
0
1
ef8febbd131a55a6c3b3e452b3c21e8f63b28002
521
FoodRecipeApp
MIT License
ui/ui-gift/src/main/java/CreateGiftHandler.kt
breadwallet
37,503,422
false
null
/** * BreadWallet * * Created by <NAME> <<EMAIL>> on 12/1/20. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.uigift import android.security.keystore.UserNotAuthenticatedException import android.text.format.DateUtils import android.util.Base64 import com.breadwallet.breadbox.BreadBox import com.breadwallet.breadbox.addressFor import com.breadwallet.breadbox.createExportablePaperWallet import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.defaultUnit import com.breadwallet.breadbox.estimateFee import com.breadwallet.breadbox.estimateMaximum import com.breadwallet.breadbox.feeForSpeed import com.breadwallet.breadbox.getSize import com.breadwallet.breadbox.toBigDecimal import com.breadwallet.crypto.Amount import com.breadwallet.crypto.TransferState import com.breadwallet.crypto.errors.ExportablePaperWalletError import com.breadwallet.crypto.errors.FeeEstimationError import com.breadwallet.crypto.errors.FeeEstimationInsufficientFundsError import com.breadwallet.crypto.errors.LimitEstimationError import com.breadwallet.crypto.errors.LimitEstimationInsufficientFundsError import com.breadwallet.crypto.errors.TransferSubmitError import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.platform.entities.GiftMetaData import com.breadwallet.platform.entities.TxMetaDataValue import com.breadwallet.platform.interfaces.AccountMetaDataProvider import com.breadwallet.repository.RatesRepository import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.security.BrdUserManager import com.breadwallet.tools.util.EventUtils import com.breadwallet.ui.uigift.CreateGift.E import com.breadwallet.ui.uigift.CreateGift.F import com.breadwallet.ui.uigift.CreateGift.PaperWalletError import com.breadwallet.ui.uigift.CreateGift.MaxEstimateError import com.breadwallet.ui.uigift.CreateGift.FeeEstimateError import drewcarlson.mobius.flow.subtypeEffectHandler import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.withContext private const val GIFT_BASE_URL = "https://brd.com/x/gift" fun createCreateGiftingHandler( currencyId: String, breadBox: BreadBox, userManager: BrdUserManager, rates: RatesRepository, giftBackup: GiftBackup, metaDataManager: AccountMetaDataProvider ) = subtypeEffectHandler<F, E> { addFunction<F.CreatePaperWallet> { val wallet = breadBox.wallet(currencyId).first() try { val exportableWallet = wallet.walletManager.createExportablePaperWallet() val privateKey = checkNotNull(exportableWallet.key.orNull()).encodeAsPrivate() val address = checkNotNull(exportableWallet.address.orNull()).toString() val encodedPrivateKey = Base64.encode(privateKey, Base64.NO_PADDING).toString(Charsets.UTF_8) val url = "$GIFT_BASE_URL/$encodedPrivateKey" E.OnPaperWalletCreated(privateKey.toString(Charsets.UTF_8), address, url) } catch (e: ExportablePaperWalletError) { logError("Failed to create exportable paper wallet", e) E.OnPaperWalletFailed(PaperWalletError.UNKNOWN) } } addConsumer<F.BackupGift> { (address, privateKey) -> giftBackup.putGift(GiftCopy(address, privateKey)) } addFunction<F.DeleteGiftBackup> { (address) -> giftBackup.removeUnusedGift(address) E.OnGiftBackupDeleted } addFunction<F.EstimateFee> { (address, amount, transferSpeed) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val networkFee = wallet.feeForSpeed(transferSpeed) val coreAmount = Amount.create(amount.toDouble(), wallet.unit) if (coreAddress == null) { logError("Invalid address provided") E.OnFeeFailed(FeeEstimateError.INVALID_TARGET) } else { try { E.OnFeeUpdated(wallet.estimateFee(coreAddress, coreAmount, networkFee)) } catch (e: FeeEstimationError) { logError("Failed to estimate fee", e) when (e) { is FeeEstimationInsufficientFundsError -> E.OnFeeFailed(FeeEstimateError.INSUFFICIENT_BALANCE) else -> E.OnFeeFailed(FeeEstimateError.SERVER_ERROR) } } } } addFunction<F.EstimateMax> { (address, transferSpeed, fiatCurrencyCode) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val networkFee = wallet.feeForSpeed(transferSpeed) if (coreAddress == null) { E.OnMaxEstimateFailed(MaxEstimateError.INVALID_TARGET) } else { try { var max = wallet.estimateMaximum(coreAddress, networkFee) if (max.unit != wallet.defaultUnit) { max = checkNotNull(max.convert(wallet.defaultUnit).orNull()) } val fiatPerCryptoUnit = rates.getFiatPerCryptoUnit( max.currency.code, fiatCurrencyCode ) E.OnMaxEstimated(max.toBigDecimal() * fiatPerCryptoUnit, fiatPerCryptoUnit) } catch (e: LimitEstimationError) { logError("Failed to estimate max", e) when (e) { is LimitEstimationInsufficientFundsError -> E.OnMaxEstimateFailed(MaxEstimateError.INSUFFICIENT_BALANCE) else -> E.OnMaxEstimateFailed(MaxEstimateError.SERVER_ERROR) } } } } addFunction<F.SendTransaction> { (address, amount, feeBasis) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val coreAmount = Amount.create(amount.toDouble(), wallet.unit) val phrase = try { userManager.getPhrase() } catch (e: UserNotAuthenticatedException) { logDebug("Authentication cancelled") return@addFunction E.OnTransferFailed } if (coreAddress == null) { logError("Invalid address provided") E.OnTransferFailed } else { val transfer = wallet.createTransfer(coreAddress, coreAmount, feeBasis, null).orNull() if (transfer == null) { logError("Failed to create transfer") E.OnTransferFailed } else { try { wallet.walletManager.submit(transfer, phrase) val transferHash = transfer.hashString() breadBox.walletTransfer(wallet.currency.code, transferHash) .mapNotNull { tx -> when (checkNotNull(tx.state.type)) { TransferState.Type.CREATED, TransferState.Type.SIGNED -> null TransferState.Type.INCLUDED, TransferState.Type.PENDING, TransferState.Type.SUBMITTED -> { EventUtils.pushEvent(EventUtils.EVENT_GIFT_SEND) E.OnTransactionSent(transferHash) } TransferState.Type.DELETED, TransferState.Type.FAILED -> { logError("Failed to submit transfer ${tx.state.failedError.orNull()}") E.OnTransferFailed } } }.first() } catch (e: TransferSubmitError) { logError("Failed to submit transfer", e) E.OnTransferFailed } } } } addFunction<F.SaveGift> { effect -> withContext(NonCancellable) { giftBackup.markGiftIsUsed(effect.address) val wallet = breadBox.wallet(currencyId).first() val transfer = breadBox.walletTransfer(wallet.currency.code, effect.txHash).first() metaDataManager.putTxMetaData( transfer, TxMetaDataValue( BRSharedPrefs.getDeviceId(), "", effect.fiatCurrencyCode, effect.fiatPerCryptoUnit.toDouble(), wallet.walletManager.network.height.toLong(), transfer.fee.toBigDecimal().toDouble(), transfer.getSize()?.toInt() ?: 0, (System.currentTimeMillis() / DateUtils.SECOND_IN_MILLIS).toInt(), gift = GiftMetaData( keyData = effect.privateKey, recipientName = effect.recipientName ) ) ) E.OnGiftSaved } } }
36
null
450
385
dfbbfbfc92dae054e47f245e1ce2ac8a39e65e57
10,025
breadwallet-android
MIT License
ChatroomService/src/main/java/io/agora/chatroom/UICustomType.kt
apex-wang
728,010,838
false
{"Kotlin": 497622}
package io.agora.chatroom import android.text.TextUtils import io.agora.chatroom.model.UIConstant enum class UICustomMsgType(name: String) { /** * 系统消息 成员加入 */ CHATROOMUIKITUSERJOIN(UIConstant.CHATROOM_UIKIT_USER_JOIN), /** * 礼物消息 */ CHATROOMUIKITGIFT(UIConstant.CHATROOM_UIKIT_GIFT); companion object { fun fromName(name: String?): UICustomMsgType? { for (type in UICustomMsgType.values()) { if (TextUtils.equals(type.name, name)) { return type } } return null } } }
0
Kotlin
0
0
20b1ff03d06d87d44565e322ccf9abced24264c5
619
test
MIT License
app/src/main/kotlin/ch/empa/openbisio/interfaces/CreatableEntity.kt
empa-scientific-it
618,383,912
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ch.empa.openbisio.interfaces import ch.ethz.sis.openbis.generic.asapi.v3.dto.common.create.ICreation interface CreatableEntity : Entity { val identifier: Identifier /** * Returns a Creation object that can be used * to create the openbis entity */ fun persist(): List<ICreation> }
0
Kotlin
0
0
f61b168531320739a3450e9c3f0bb2a0f0299ce0
913
instanceio
Apache License 2.0
app/src/main/java/net/ldasilva/expertisetest/ui/movie/list/MovieListViewModel.kt
ldasilva-net
186,191,066
false
null
package net.ldasilva.expertisetest.ui.movie.list import androidx.lifecycle.ViewModel import net.ldasilva.expertisetest.data.SearchMovieType import net.ldasilva.expertisetest.data.repository.MovieRepository class MovieListViewModel( private val movieRepository: MovieRepository ) : ViewModel() { suspend fun getMovies(query: String, searchMovieType: SearchMovieType) { return movieRepository.getMovies(query, searchMovieType) } val movies = movieRepository.movies }
0
Kotlin
1
4
8a3b921fa84021b5166239529701751e7e82d14c
496
android-expertise-test
MIT License
app/src/main/java/io/github/fate_grand_automata/ui/launcher/ScriptLauncherResponse.kt
estella2012
720,234,144
false
{"Kotlin": 905461, "Ruby": 714}
package io.github.fate_grand_automata.ui.launcher sealed class ScriptLauncherResponse { data object Cancel : ScriptLauncherResponse() data object FP : ScriptLauncherResponse() data class Lottery( val giftBox: GiftBox? ) : ScriptLauncherResponse() data class GiftBox( val maxGoldEmberStackSize: Int, val maxGoldEmberTotalCount: Int ) : ScriptLauncherResponse() data object CEBomb : ScriptLauncherResponse() data class SkillUpgrade( val shouldUpgradeSkill1: Boolean, val upgradeSkill1: Int, val shouldUpgradeSkill2: Boolean, val upgradeSkill2: Int, val shouldUpgradeSkill3: Boolean, val upgradeSkill3: Int, ) : ScriptLauncherResponse() data object ServantEnhancement : ScriptLauncherResponse() data object PlayButtonDetection : ScriptLauncherResponse() data object SupportImageMaker : ScriptLauncherResponse() data object Battle : ScriptLauncherResponse() } class ScriptLauncherResponseBuilder( val canBuild: () -> Boolean, val build: () -> ScriptLauncherResponse )
0
Kotlin
0
0
660d7db1660332ebb3b14cc1e53b8e6c702b9792
1,103
FGA
MIT License
app/src/main/java/com/wkxjc/wanandroid/common/bean/PublicAccountsBean.kt
wkxjc
246,898,873
false
null
package com.wkxjc.wanandroid.common.bean
0
Kotlin
0
1
ccb6e3be80ba985e3c6dff789b2093b6dbe80ee2
42
WanAndroid
Apache License 2.0
tv_usecase/src/test/java/com/bytebyte6/usecase/SearchCountryImageTest.kt
bytebyte6
324,579,353
false
null
package com.bytebyte6.usecase import com.bytebyte6.testdata.countries import com.bytebyte6.data.entity.Country import com.bytebyte6.image.SearchImageImpl import com.bytebyte6.usecase.work.SearchCountryImage import org.junit.Test class SearchCountryImageTest { @Test fun test() { val dataManager = object : com.bytebyte6.testdata.TestDataManager() { override fun getCountries(): List<Country> { return countries } val ups = mutableListOf<Country>() override fun updateCountry(countries: List<Country>) { ups.addAll(countries) } } val countryImageSearch = SearchCountryImage(dataManager, SearchImageImpl()) countryImageSearch.searchCountryImage() dataManager.ups.forEach { assert(it.image.isNotEmpty()) } } }
0
Kotlin
7
9
3c22f2baad651c3df53b3615fd6fc28263621a42
874
Tv
Apache License 2.0
src/main/kotlin/stellarwitch7/ram/cca/entity/ModEntityComponents.kt
StellarWitch7
843,940,487
false
{"Kotlin": 7051}
package stellarwitch7.ram.cca.entity import org.ladysnake.cca.api.v3.entity.RespawnCopyStrategy import stellarwitch7.libstellar.registry.cca.entity.CCAEntityComponentRegistrar import stellarwitch7.ram.RandomAccessMind import stellarwitch7.ram.cca.RAMComponent //TODO: something something private can't access Kotlin whatnot object ModEntityComponents : CCAEntityComponentRegistrar() { override val modID: String = RandomAccessMind.MOD_ID val ram = register("ram", RAMComponent::class, ::RAMComponent, RespawnCopyStrategy.LOSSLESS_ONLY) }
0
Kotlin
0
1
dd9ab1053dc76139d15d473c3d85c3bdb695e151
548
ram
MIT License
website/src/main/java/info/xiaomo/website/XiaomoMain.kt
tangyinbo
109,561,532
true
{"Kotlin": 323648, "CSS": 117781, "FreeMarker": 7915, "HTML": 6836, "Java": 2501, "Ruby": 37}
package info.xiaomo.website import info.xiaomo.website.view.UserView import io.swagger.annotations.ApiOperation import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.autoconfigure.domain.EntityScan import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.stereotype.Controller import org.springframework.transaction.annotation.EnableTransactionManagement import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter import springfox.documentation.annotations.ApiIgnore import springfox.documentation.builders.ApiInfoBuilder import springfox.documentation.builders.PathSelectors import springfox.documentation.builders.RequestHandlerSelectors import springfox.documentation.service.ApiInfo import springfox.documentation.spi.DocumentationType import springfox.documentation.spring.web.plugins.Docket import springfox.documentation.swagger2.annotations.EnableSwagger2 /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! * Created by IntelliJ IDEA. * * @author : xiaomo * github: https://github.com/xiaomoinfo * email: xiaomo@xiaomo.info * * * Date: 2016/4/1 15:38 * Description: 后台管理启动器 * Copyright(©) 2015 by xiaomo. */ @EnableAutoConfiguration @ComponentScan("info.xiaomo") @EntityScan("info.xiaomo.*.model") @EnableTransactionManagement @EnableJpaRepositories("info.xiaomo.*.dao") @EnableCaching @EnableSwagger2 @Controller class XiaomoMain : WebMvcConfigurerAdapter() { @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) fun index(): String? { return UserView.INDEX.viewName } /** * 接口 * * @return 接口 */ @RequestMapping(value = "/api", method = arrayOf(RequestMethod.GET)) @ApiIgnore @ApiOperation(value = "重定向到api首页") fun api(): ModelAndView { return ModelAndView("redirect:/swagger-ui.html") } @Bean fun createRestApi(): Docket { return Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("info.xiaomo.website")) .paths(PathSelectors.any()) .build() } private fun apiInfo(): ApiInfo { return ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("api根地址:http://api.xiaomo.info:8080/") .termsOfServiceUrl("https://xiaomo.info/") .contact("小莫") .version("1.0") .build() } companion object { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { SpringApplication.run(XiaomoMain::class.java, *args) } } }
0
Kotlin
0
0
23d20b605e842d32f53c8b7e0effe92e52475c65
3,242
SpringBootUnity
MIT License
core/src/main/kotlin/com/muedsa/snapshot/rendering/box/RenderColoredBox.kt
muedsa
736,941,747
false
{"Kotlin": 595873}
package com.muedsa.snapshot.rendering.box import com.muedsa.geometry.Offset import com.muedsa.geometry.Size import com.muedsa.snapshot.rendering.PaintingContext import org.jetbrains.skia.Paint class RenderColoredBox( var color: Int, ) : RenderSingleChildBox() { override fun paint(context: PaintingContext, offset: Offset) { val size = definiteSize if (size > Size.ZERO) { val paint = Paint() paint.color = color context.canvas.drawRect(offset combine size, paint) } child?.let { context.paintChild(it, offset + it.parentData!!.offset) } } }
0
Kotlin
0
1
15eea1ed32843abd3c453a919ab828592a3a9e93
644
snapshot
MIT License
src/main/daos/Metadata.kt
ncent-archive
150,326,270
false
{"Kotlin": 352866, "JavaScript": 7544, "Makefile": 563, "Shell": 222}
package main.daos import com.fasterxml.jackson.databind.ObjectMapper import framework.models.BaseIntEntity import framework.models.BaseIntEntityClass import framework.models.BaseIntIdTable import org.jetbrains.exposed.dao.EntityID import kotlin.reflect.full.primaryConstructor /** * Metadata will be a key-value store * * @property id * @property key * @property value */ class Metadata(id: EntityID<Int>) : BaseIntEntity(id, Metadatas) { companion object : BaseIntEntityClass<Metadata>(Metadatas) var key by Metadatas.key var value by Metadatas.value override fun toMap(): MutableMap<String, Any?> { var map = super.toMap() map.put("key", key) map.put("value", value) return map } } object Metadatas : BaseIntIdTable("metadatas") { val key = varchar("md_key", 256) val value = varchar("md_value", 256) } data class MetadatasNamespace(val key: String, val value: String)
16
Kotlin
2
2
802160f3332c4b6d63d4219067848e38a689c48b
942
ncent-api-v2
MIT License
app/src/main/java/com/emerjbl/ultra8/chip8/machine/Disassembler.kt
jblebrun
10,089,457
false
{"Kotlin": 123397, "Shell": 816}
package com.emerjbl.ultra8.chip8.machine sealed interface Segment { data class Code(val instruction: List<Chip8Instruction>) : Segment data class Data(val bytes: List<UByte>) : Segment } private val byteFormat = HexFormat { number { this.prefix = "0x" } } class Disassembly( /** The disassembled segments. These represent the contiguous byte-code. */ val segments: List<Segment> ) { override fun toString(): String = segments.joinToString("\n\n") { segment -> when (segment) { is Segment.Code -> { segment.instruction.joinToString(prefix = "CODE:\n", separator = "\n") { " $it" } } is Segment.Data -> { segment.bytes.chunked(8) .joinToString(prefix = "DATA:\n", separator = "\n") { chunk -> " ${chunk.joinToString(" ") { it.toHexString(byteFormat) }}" } } } } } private sealed interface SegmentBuilder { fun build(): Segment class Code : SegmentBuilder { val instructions = mutableListOf<Chip8Instruction>() override fun build(): Segment.Code = Segment.Code(instructions) } class Data : SegmentBuilder { val bytes = mutableListOf<UByte>() override fun build(): Segment.Data = Segment.Data(bytes) } } private class DisassemblyBuilder { private val segments = mutableListOf<SegmentBuilder>() fun build(): Disassembly = Disassembly(segments.map { it.build() }) fun data(): SegmentBuilder.Data = segments.lastOrNull().let { currentSegment -> when (currentSegment) { is SegmentBuilder.Data -> currentSegment else -> SegmentBuilder.Data().also { segments += it } } } fun code(): SegmentBuilder.Code = segments.lastOrNull().let { currentSegment -> when (currentSegment) { is SegmentBuilder.Code -> currentSegment else -> SegmentBuilder.Code().also { segments += it } } } } private sealed interface Item { class Instruction(val i: Chip8Instruction) : Item class DataByte(val b: UByte) : Item } private fun UByteArray.asItems(): Sequence<Item> { data class IndexedItem(val idx: Int, val item: Item?) return generateSequence(IndexedItem(0, null)) { (idx, _) -> when { // All done idx >= this.size -> null // Last byte, must be data byte idx + 1 >= this.size -> IndexedItem(idx + 1, Item.DataByte(this[idx])) // Could be instruction else -> { val inst = Chip8Instruction(this[idx].toInt(), this[idx + 1].toInt()) if (inst.asm == null) { // Not instruction, consume one byte IndexedItem(idx + 1, Item.DataByte(this[idx])) } else { // Instruction, consume both bytes IndexedItem(idx + 2, Item.Instruction(inst)) } } } }.mapNotNull { it.item } } /** * A fairly naive disassembler. * * It progresses through the byte array, attempting to interpret a two-byte sequence as an * instruction. When it can't, it switches to a data segment, until it detects valid opcodes again. * * This is not robust against a lot of structures, but it's a start. */ fun disassemble(code: UByteArray): Disassembly = code.asItems().fold(DisassemblyBuilder()) { disAssembly, item -> disAssembly.apply { when (item) { is Item.DataByte -> data().bytes += item.b is Item.Instruction -> code().instructions += item.i } } }.build()
2
Kotlin
0
0
8e0bc70811dfe46571ee1cdabd6e552194373d67
3,715
ultra8
MIT License
app/src/main/java/grack/dev/moviedagger/ui/movie/catalogue/CatalogueFragment.kt
Rarj
186,447,222
false
{"Kotlin": 80078}
package grack.dev.moviedagger.ui.movie.catalogue import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.google.gson.Gson import com.jakewharton.rxbinding3.view.clicks import dagger.android.support.AndroidSupportInjection import grack.dev.moviedagger.AppConstant import grack.dev.moviedagger.AppConstant.DURATION_THROTTLE import grack.dev.moviedagger.AppConstant.INTENT_KEY_HEADER import grack.dev.moviedagger.R import grack.dev.moviedagger.data.repository.models.general.Movies import grack.dev.moviedagger.data.repository.models.general.Result import grack.dev.moviedagger.databinding.FragmentCatalogueBinding import grack.dev.moviedagger.ui.detail.DetailActivity import grack.dev.moviedagger.ui.movie.catalogue.model.Child import grack.dev.moviedagger.ui.movie.catalogue.model.SectionItem import grack.dev.moviedagger.ui.movie.more.MoreActivity import grack.dev.moviedagger.ui.movie.search.SearchActivity import grack.dev.moviedagger.utils.ClickListener import grack.dev.moviedagger.utils.MarginItemDecoration import java.util.concurrent.TimeUnit import javax.inject.Inject class CatalogueFragment(private var movies: Movies) : Fragment() { @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var binding: FragmentCatalogueBinding private lateinit var catalogueAdapter: CatalogueAdapter private lateinit var viewModel: CatalogueViewModel private var child = ArrayList<Child>() private val section = ArrayList<SectionItem>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) } @SuppressLint("CheckResult") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProviders.of(this, viewModelFactory).get(CatalogueViewModel::class.java) binding = DataBindingUtil.inflate( inflater, R.layout.fragment_catalogue, container, false ) binding.viewModel = viewModel binding.lifecycleOwner = this populateMovie() catalogueAdapter = CatalogueAdapter(activity, section, object : ClickListener<Result> { override fun onItemClick(t: Result?) { startActivityDetail(t) } }, object : ClickListener<String> { override fun onItemClick(t: String?) { startActivityMore(t, movies) } }) binding.recyclerCatalogue.adapter = catalogueAdapter binding.recyclerCatalogue.layoutManager = LinearLayoutManager(context) binding.recyclerCatalogue.addItemDecoration(MarginItemDecoration(16)) catalogueAdapter.notifyDataSetChanged() binding.buttonSearch.clicks() .throttleFirst(DURATION_THROTTLE, TimeUnit.MILLISECONDS) .subscribe { startActivity(Intent(activity, SearchActivity::class.java)) } return binding.root } private fun populateMovie() { movies.nowPlaying.forEachIndexed { index, result -> if (index <= 4) { child.add(Child(result)) } } section.add(SectionItem(resources.getString(R.string.movie_caption_now_playing), child)) child = ArrayList() movies.topRated.forEachIndexed { index, result -> if (index <= 4) { child.add(Child(result)) } } section.add(SectionItem(resources.getString(R.string.movie_caption_top_rated), child)) child = ArrayList() movies.popular.forEachIndexed { index, result -> if (index <= 4) { child.add(Child(result)) } } section.add(SectionItem(resources.getString(R.string.movie_caption_popular), child)) child = ArrayList() movies.upcoming.forEachIndexed { index, result -> if (index <= 4) { child.add(Child(result)) } } section.add(SectionItem(resources.getString(R.string.movie_caption_upcoming), child)) } private fun startActivityMore(header: String?, movies: Movies) { val intent = Intent(activity, MoreActivity::class.java) intent.putExtra(AppConstant.INTENT_KEY, Gson().toJson(movies)) intent.putExtra(INTENT_KEY_HEADER, header) startActivity(intent) } private fun startActivityDetail(data: Result?) { val bundle = Bundle() bundle.putString(AppConstant.INTENT_KEY, Gson().toJson(data)) val detailActivity = DetailActivity() detailActivity.arguments = bundle detailActivity.isCancelable = false detailActivity.show(activity!!.supportFragmentManager, detailActivity.tag) } }
0
Kotlin
0
1
e91621462d0583ee3586c6b7ce16fd8da8513edb
4,829
Simple-dagger
Apache License 2.0
app/src/main/java/com/emretnkl/myshopapp/feature/basket/adapter/BasketProductAdapter.kt
emretnkl
559,308,167
false
null
package com.emretnkl.myshopapp.feature.basket.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.emretnkl.myshopapp.R import com.emretnkl.myshopapp.data.model.BasketProduct class BasketProductAdapter(private val basketProductList : ArrayList<BasketProduct>) : RecyclerView.Adapter<BasketProductAdapter.BasketProductViewHolder>() { var listener: BasketOnClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BasketProductViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_basket_product,parent,false) return BasketProductViewHolder(itemView) } override fun onBindViewHolder(holder: BasketProductViewHolder, position: Int) { val basketProduct : BasketProduct = basketProductList[position] holder.title.text = basketProduct.title holder.price.text = basketProduct.price holder.quantity.text = basketProduct.quantity.toString() Glide.with(holder.itemView.context) .load(basketProduct.image) .into(holder.image) holder.increaseButton.setOnClickListener { listener?.onIncreaseButtonClicked(basketProduct) } holder.decreaseButton.setOnClickListener { listener?.onDecreaseButtonClicked(basketProduct) } } override fun getItemCount(): Int { return basketProductList.size } class BasketProductViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) { //id image title price quantity val image : ImageView = itemView.findViewById(R.id.ivBasketItemImage) val title : TextView = itemView.findViewById(R.id.tvBasketItemTitle) val price : TextView = itemView.findViewById(R.id.tvBasketItemPrice) val quantity : TextView = itemView.findViewById(R.id.tvBasketItemQuantity) val increaseButton: TextView = itemView.findViewById(R.id.bttnIncreaseBasketQuantity) val decreaseButton: TextView = itemView.findViewById(R.id.bttnDecreaseBasketQuantity) } fun setBasketOnClickListener(listener: BasketOnClickListener){ this.listener = listener } } interface BasketOnClickListener { fun onIncreaseButtonClicked(item: BasketProduct) fun onDecreaseButtonClicked(item: BasketProduct) }
0
Kotlin
0
1
77ee7168cf5484f38f0665082c7dd26b38973622
2,514
MyShopApp
Apache License 2.0
src/main/kotlin/br/com/zup/edu/shared/filter/ExceptionHandler.kt
almiracioly
347,077,154
true
{"Kotlin": 34204}
package br.com.zup.edu.shared.filter import io.grpc.* import java.lang.Exception interface ExceptionHandler<E : Exception> { fun handle(e: E): StatusWithDetails fun supports(e: Exception): Boolean data class StatusWithDetails( val status: Status, val metaData: Metadata = Metadata(), ) { constructor(se: StatusRuntimeException) : this(se.status, se.trailers!!) // constructor(sp: com.google.rpc.Status) : this(Status) fun asRuntimeException(): StatusRuntimeException { return status.asRuntimeException(metaData) } } }
0
Kotlin
0
0
1a418f8b4d9e3f8cd4f1449083e8af0407d96427
607
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/br/com/zup/edu/shared/filter/ExceptionHandler.kt
almiracioly
347,077,154
true
{"Kotlin": 34204}
package br.com.zup.edu.shared.filter import io.grpc.* import java.lang.Exception interface ExceptionHandler<E : Exception> { fun handle(e: E): StatusWithDetails fun supports(e: Exception): Boolean data class StatusWithDetails( val status: Status, val metaData: Metadata = Metadata(), ) { constructor(se: StatusRuntimeException) : this(se.status, se.trailers!!) // constructor(sp: com.google.rpc.Status) : this(Status) fun asRuntimeException(): StatusRuntimeException { return status.asRuntimeException(metaData) } } }
0
Kotlin
0
0
1a418f8b4d9e3f8cd4f1449083e8af0407d96427
607
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
app/src/test/kotlin/com/octo/mob/octomeuh/settings/presenter/SettingsPresenterImplTest.kt
rpradal
61,704,332
false
null
package com.octo.mob.octomeuh.settings.presenter import com.octo.mob.octomeuh.countdown.manager.PreferencesPersistor import com.octo.mob.octomeuh.countdown.model.RepetitionMode import com.octo.mob.octomeuh.settings.model.RepetitionModeDescription import com.octo.mob.octomeuh.settings.screen.SettingsScreen import com.octo.mob.octomeuh.settings.utils.AppInformation import com.octo.mob.octomeuh.transversal.HumanlyReadableDurationsConverter import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations @Suppress("IllegalIdentifier") class SettingsPresenterImplTest { @Mock lateinit var preferencePersistor: PreferencesPersistor @Mock lateinit var settingsScreen: SettingsScreen @Mock lateinit var appInformation: AppInformation @Mock lateinit var humanlyReadablenformation: HumanlyReadableDurationsConverter lateinit var settingsPresenter: SettingsPresenterImpl @Before fun setUp() { MockitoAnnotations.initMocks(this) settingsPresenter = SettingsPresenterImpl(preferencePersistor, humanlyReadablenformation, appInformation) } @Test fun `When SettingsScreen is attached to the presenter repetition mode should be updated`() { // Given Mockito.`when`(preferencePersistor.getRepetitionMode()).thenReturn(RepetitionMode.STEP_BY_STEP) // When settingsPresenter.attach(settingsScreen) // Then Mockito.verify(settingsScreen).showCurrentRepetitionMode(RepetitionModeDescription.STEP_BY_STEP) } @Test fun `When current repetition mode is step by step we should display a selection with step by step preselected`() { // Given settingsPresenter.attach(settingsScreen) Mockito.`when`(preferencePersistor.getRepetitionMode()).thenReturn(RepetitionMode.STEP_BY_STEP) // When settingsPresenter.onRepetitionModeChangeRequest() // Then Mockito.verify(settingsScreen).showRepetitionModeSelection(RepetitionModeDescription.values(), 1) } @Test fun `When current repetition mode is lopp we should display a selection with loop preselected`() { // Given settingsPresenter.attach(settingsScreen) Mockito.`when`(preferencePersistor.getRepetitionMode()).thenReturn(RepetitionMode.LOOP) // When settingsPresenter.onRepetitionModeChangeRequest() // Then Mockito.verify(settingsScreen).showRepetitionModeSelection(RepetitionModeDescription.values(), 0) } @Test fun `When duration selection is called then we should display the duration selection view`() { // Given settingsPresenter.attach(settingsScreen) // When settingsPresenter.onDurationChangeRequest() // Then Mockito.verify(settingsScreen).showDurationSelection() } @Test fun `When a repetition mode is selected we should update the displayed value`() { // Given settingsPresenter.attach(settingsScreen) // When settingsPresenter.onRepetitionModeSelected(RepetitionModeDescription.STEP_BY_STEP) // Then Mockito.verify(settingsScreen).showCurrentRepetitionMode(RepetitionModeDescription.STEP_BY_STEP) Mockito.verify(preferencePersistor).saveRepetitionMode(RepetitionMode.STEP_BY_STEP) } }
2
Kotlin
1
1
28a873d52b9196e886eb42e44f30e28530d921b7
3,405
OCTOMeuh
MIT License
src/main/java/at/petrak/hexcasting/common/casting/operators/math/logic/OpEquality.kt
najlitarvan
482,865,156
true
{"Java Properties": 1, "Groovy": 1, "Text": 3, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Gradle": 1, "Ignore List": 1, "Kotlin": 146, "Java": 140, "JSON": 630, "TOML": 1, "INI": 1}
package at.petrak.hexcasting.common.casting.operators.math.logic import at.petrak.hexcasting.api.spell.ConstManaOperator import at.petrak.hexcasting.api.spell.Operator.Companion.spellListOf import at.petrak.hexcasting.api.spell.SpellDatum import at.petrak.hexcasting.api.spell.casting.CastingContext import net.minecraft.world.phys.Vec3 import kotlin.math.abs class OpEquality(val invert: Boolean) : ConstManaOperator { override val argc = 2 override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> { val lhs = args[0] val rhs = args[1] return spellListOf(if (checkEquals(lhs.payload, rhs.payload) != invert) 1.0 else 0.0) } private fun checkEquals(a: Any, b: Any, recursionsLeft: Int = 64): Boolean { return when { a is Double && b is Double -> abs(a - b) < 0.0001 a is Vec3 && b is Vec3 -> a.subtract(b).lengthSqr() < 0.0000001 a is List<*> && b is List<*> -> { if (a.size != b.size || recursionsLeft == 0) return false for (i in a.indices) if (!checkEquals((a[i] as SpellDatum<*>).payload, (b[i] as SpellDatum<*>).payload, recursionsLeft - 1)) return false true } else -> a == b } } }
0
null
0
0
526360b1d0a8e1559896b4755f1222158e1fdb67
1,358
HexMod
MIT License
RobotCode2024/src/main/kotlin/frc/lib/behaviorTree/nodes/BehaviorTreeNode.kt
3015RangerRobotics
802,925,561
false
{"Text": 2, "Git Attributes": 5, "Gradle": 2, "JSON": 19, "Shell": 1, "Ignore List": 12, "Batchfile": 1, "Markdown": 5, "YAML": 12, "INI": 1, "Java": 119, "Kotlin": 106, "XML": 25, "Ruby": 3, "OpenStep Property List": 9, "Swift": 11, "CMake": 15, "C": 8, "C++": 27, "Dart": 69}
package frc.lib.behaviorTree.nodes import frc.lib.behaviorTree.BehaviorTreeDebug import frc.lib.behaviorTree.Blackboard import frc.lib.behaviorTree.ExecutionStatus abstract class BehaviorTreeNode(private val uuid: String) { fun initialize(blackboard: Blackboard) { handleInitialize(blackboard) BehaviorTreeDebug.setActive(uuid) } protected abstract fun handleInitialize(blackboard: Blackboard) fun execute(blackboard: Blackboard): ExecutionStatus { val status = handleExecute(blackboard) if (status != ExecutionStatus.Running) { BehaviorTreeDebug.setInactive(uuid) } return status } protected abstract fun handleExecute(blackboard: Blackboard): ExecutionStatus fun abort(blackboard: Blackboard) { handleAbort(blackboard) BehaviorTreeDebug.setInactive(uuid) } protected abstract fun handleAbort(blackboard: Blackboard) }
0
Java
1
5
60a1c9b5cb1d4957e68a242bc44e9cd5b5967155
885
2024Public
MIT License
hello-algo/hello-algo-main/zh-hant/codes/kotlin/chapter_dynamic_programming/climbing_stairs_dp.kt
CoderDream
402,249,596
false
{"Maven POM": 206, "XML": 643, "Text": 661, "Ignore List": 121, "Markdown": 677, "YAML": 235, "JSON": 112, "JavaScript": 832, "EditorConfig": 9, "Browserslist": 15, "HTML": 431, "robots.txt": 1, "SVG": 21, "Vue": 121, "Java": 4312, "Java Properties": 58, "SQL": 25, "Batchfile": 33, "Shell": 71, "Dockerfile": 23, "INI": 150, "SubRip Text": 78, "Git Attributes": 1, "Python": 261, "CMake": 75, "C++": 264, "Zig": 104, "Go Module": 2, "Go": 270, "Swift": 178, "Microsoft Visual Studio Solution": 2, "C#": 172, "C": 164, "JSON with Comments": 27, "Kotlin": 170, "Ruby": 120, "Dart": 170, "TOML": 2, "Rust": 172, "CSS": 185, "SRecode Template": 4, "Nginx": 2, "Groovy": 6, "Mustache": 4, "Less": 16, "SCSS": 14, "Perl": 2, "Vim Script": 4, "Java Server Pages": 8, "Fluent": 5, "Roff Manpage": 23, "Roff": 36, "FreeMarker": 1}
/** * File: climbing_stairs_dp.kt * Created Time: 2024-01-25 * Author: curtishd (<EMAIL>) */ package chapter_dynamic_programming /* 爬樓梯:動態規劃 */ fun climbingStairsDP(n: Int): Int { if (n == 1 || n == 2) return n // 初始化 dp 表,用於儲存子問題的解 val dp = IntArray(n + 1) // 初始狀態:預設最小子問題的解 dp[1] = 1 dp[2] = 2 // 狀態轉移:從較小子問題逐步求解較大子問題 for (i in 3..n) { dp[i] = dp[i - 1] + dp[i - 2] } return dp[n] } /* 爬樓梯:空間最佳化後的動態規劃 */ fun climbingStairsDPComp(n: Int): Int { if (n == 1 || n == 2) return n var a = 1 var b = 2 for (i in 3..n) { val temp = b b += a a = temp } return b } /* Driver Code */ fun main() { val n = 9 var res = climbingStairsDP(n) println("爬 $n 階樓梯共有 $res 種方案") res = climbingStairsDPComp(n) println("爬 $n 階樓梯共有 $res 種方案") }
1
Java
5
5
1af9462ce13a6fd1125a160e418b549c4510fa30
848
java-architect-util
Apache License 2.0
abstract-factory/src/main/kotlin/com/github/ftfetter/oopdesignpatterns/abstractfactory/factory/ClassFactory.kt
ftfetter
206,670,571
false
{"Java": 15364, "Kotlin": 4473}
package com.github.ftfetter.oopdesignpatterns.abstractfactory.factory import com.github.ftfetter.oopdesignpatterns.abstractfactory.armor.Armor import com.github.ftfetter.oopdesignpatterns.abstractfactory.weapon.Weapon interface ClassFactory { fun name(): String fun armor(): Armor fun weapon(): Weapon }
1
null
1
1
05be9d5b55c84c429a193da76b1b25fe56ffe5f4
317
oop-design-patterns
MIT License
app/src/main/java/io/suyong/kakaobridge/Config.kt
khu-suyong
261,373,882
false
null
package io.suyong.kakaobridge object Config { val KAKAOTALK = "com.kakao.talk" }
0
Kotlin
0
1
5bf08f176cb5f029989214dcab0133d3078428d4
85
linux-kakaotalk-android
MIT License
library/src/main/java/com/wahidabd/library/utils/common/PhoneUtils.kt
wahidabd
609,474,062
false
null
package com.wahidabd.library.utils.common import com.google.i18n.phonenumbers.NumberParseException import com.google.i18n.phonenumbers.PhoneNumberUtil import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat import com.google.i18n.phonenumbers.Phonenumber private fun formatNumber( phoneNumber: String, format: PhoneNumberFormat, countryCode: String ): String? { val phoneUtil = PhoneNumberUtil.getInstance() return try { val phone: Phonenumber.PhoneNumber = phoneUtil.parse(phoneNumber, countryCode) phoneUtil.format(phone, format) }catch (e: NumberParseException){ e.printStackTrace() null } } fun formatNumberToE164( phoneNumber: String, countryCode: String ): String = formatNumber(phoneNumber, PhoneNumberFormat.E164, countryCode).toString() fun formatNumberToInternational( phoneNumber: String, countryCode: String ): String = formatNumber(phoneNumber, PhoneNumberFormat.INTERNATIONAL, countryCode).toString() fun formatNumberToNational( phoneNumber: String, countryCode: String ): String = formatNumber(phoneNumber, PhoneNumberFormat.NATIONAL, countryCode).toString() fun formatNumberToRFC3966( phoneNumber: String, countryCode: String ): String = formatNumber(phoneNumber, PhoneNumberFormat.RFC3966, countryCode).toString() fun isValidNumber( phoneNumber: String, countryCode: String ): Boolean { val phoneUtil = PhoneNumberUtil.getInstance() return try { val phone = phoneUtil.parse(phoneNumber, countryCode) phoneUtil.isValidNumber(phone) }catch (e: NumberParseException){ e.printStackTrace() false } }
1
Kotlin
0
0
9e0d6cad1b927387ed38e696fcba93d934e3fa37
1,681
one-library
MIT License
performance-jump-search/src/test/java/com/jesperancinha/performance/test/jumpsearch/AllSingleTests.kt
jesperancinha
43,874,844
false
{"Kotlin": 26723, "Makefile": 1629, "Shell": 400}
package com.jesperancinha.performance.test.jumpsearch import org.junit.platform.suite.api.SelectClasses import org.junit.platform.suite.api.Suite @Suite @SelectClasses( JumpSearchFileSameStepMethod0Test::class, JumpSearchFileSameStepMethodStreams0Test::class, JumpSearchFileSameStepMethodStreams0Test::class ) class AllSingleTests
0
Kotlin
1
2
3c9cb4dcac97e73863f5ff71e97c718d6f2fdd35
345
performance-projects
Apache License 2.0
performance-jump-search/src/test/java/com/jesperancinha/performance/test/jumpsearch/AllSingleTests.kt
jesperancinha
43,874,844
false
{"Kotlin": 26723, "Makefile": 1629, "Shell": 400}
package com.jesperancinha.performance.test.jumpsearch import org.junit.platform.suite.api.SelectClasses import org.junit.platform.suite.api.Suite @Suite @SelectClasses( JumpSearchFileSameStepMethod0Test::class, JumpSearchFileSameStepMethodStreams0Test::class, JumpSearchFileSameStepMethodStreams0Test::class ) class AllSingleTests
0
Kotlin
1
2
3c9cb4dcac97e73863f5ff71e97c718d6f2fdd35
345
performance-projects
Apache License 2.0
app/src/main/java/com/bharathvishal/messagecommunicationusingwearabledatalayer/Utils/Botresponse.kt
CBNU-IMY
571,782,360
false
{"Kotlin": 96645}
package com.bharathvishal.messagecommunicationusingwearabledatalayer.Utils import android.util.Log import com.bharathvishal.messagecommunicationusingwearabledatalayer.Api.RetrofitBuilder import com.bharathvishal.messagecommunicationusingwearabledatalayer.Dto.CorpusDto import com.bharathvishal.messagecommunicationusingwearabledatalayer.Dto.CorpusDto2 import com.bharathvishal.messagecommunicationusingwearabledatalayer.Utils.Constants.OPEN_GOOGLE import com.bharathvishal.messagecommunicationusingwearabledatalayer.Utils.Constants.OPEN_SEARCH /* import com.codepalace.chatbot.Api.CorpusApi import com.codepalace.chatbot.Api.RetrofitBuilder import com.codepalace.chatbot.Dto.CorpusDto import com.codepalace.chatbot.Dto.CorpusDto2 import com.codepalace.chatbot.utils.Constants.OPEN_GOOGLE import com.codepalace.chatbot.utils.Constants.OPEN_SEARCH */ import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.sql.Date import java.sql.Timestamp import java.text.SimpleDateFormat import kotlinx.coroutines.* object BotResponse { fun basicResponses(_message: String, _corpuslist: List<CorpusDto>): String { val random = (0..2).random() val message =_message.toLowerCase() var corpuslist=_corpuslist return when { //Flips a coin message.contains("flip") && message.contains("coin") -> { val r = (0..1).random() val result = if (r == 0) "heads" else "tails" "I flipped a coin and it landed on $result" } //Math calculations message.contains("solve") -> { val equation: String? = message.substringAfterLast("solve") return try { val answer = SolveMath.solveMath(equation ?: "0") "$answer" } catch (e: Exception) { "Sorry, I can't solve that." } } //Hello message.contains("hello") -> { println("corpuslist mansinn = ${corpuslist}") // println("second name = ${name}") corpuslist.get(2).system_response1 /* when (random) { // 0 -> sexmessage /* 1 -> "Sup" 2 -> "Buongiorno!"*/ // else -> "error" }*/ } //How are you? message.contains("how are you") -> { when (random) { 0 -> "I'm doing fine, thanks!" 1 -> "I'm hungry..." 2 -> "Pretty good! How about you?" else -> "error" } } //What time is it? message.contains("time") && message.contains("?")-> { val timeStamp = Timestamp(System.currentTimeMillis()) val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm") val date = sdf.format(Date(timeStamp.time)) date.toString() } //Open Google message.contains("open") && message.contains("google")-> { OPEN_GOOGLE } //Search on the internet message.contains("search")-> { OPEN_SEARCH } //When the programme doesn't understand... else -> { when (random) { 0 -> "무슨 말인지 잘 모르겠어..." 1 -> "미안 다시 한 번 말해줄래??" 2 -> "뭐라고 했지??" else -> "error" } } } } fun Corpuslist2(_corpuslist : CorpusDto){ var corpuslist=_corpuslist val call = RetrofitBuilder.corpusapi.getAllByMaincategoryResponse("상처") var corpus = CorpusDto2("test") corpus.system_response1="test2" println("corpus = ${corpus}") Thread{ call.enqueue(object : Callback<List<CorpusDto>> { // 비동기 방식 통신 메소드 override fun onResponse( // 통신에 성공한 경우 call: Call<List<CorpusDto>>, response: Response<List<CorpusDto>> ) { if(response.isSuccessful()){ // 응답 잘 받은 경우 corpuslist= response.body()!!.get(0) println("corpuslist = ${corpuslist}") println("response.body() = ${response.body()}") corpus.system_response1=response.body()?.get(0)!!.system_response1 println("second corpus = ${corpus}") }else{ // 통신 성공 but 응답 실패 Log.d("RESPONSE", "FAILURE") } } override fun onFailure(call: Call<List<CorpusDto>>, t: Throwable) { // 통신에 실패한 경우 Log.d("CONNECTION FAILURE: ", t.localizedMessage) } }) }.start() try{ Thread.sleep(50) } catch(e: Exception){ e.printStackTrace() } println("third corpus = ${corpus}") } }
0
Kotlin
0
0
61b7f0b8c37d6c8f452baa652cece31831516426
5,186
WearOs-for-Sound-
MIT License