path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/trifork/timandroid/token/TokenFragment.kt
trifork
431,052,684
false
{"Kotlin": 51367}
package com.trifork.timandroid.token import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import com.trifork.timandroid.R import com.trifork.timandroid.TIM import com.trifork.timandroid.databinding.FragmentTokenBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject enum class TokenType { Access, Refresh } @AndroidEntryPoint class TokenFragment : Fragment() { private var binding: FragmentTokenBinding? = null @Inject lateinit var viewModel: TokenViewModel val args: TokenFragmentArgs by navArgs() //TODO(Can we utilize di better?) @Inject lateinit var tim: TIM override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentTokenBinding.inflate(inflater, container, false) binding?.textViewTitleToken?.text = when (args.tokenType) { TokenType.Access -> context?.getString(R.string.fragment_token_text_view_title_access_token) TokenType.Refresh -> context?.getString(R.string.fragment_token_text_view_title_refresh_token) } viewModel.setTokenType(args.tokenType) lifecycleScope.launch { viewModel.jwtToken.collect { binding?.textViewToken?.text = it?.token binding?.textViewExpiration?.text = it?.expire.toString() } } return binding?.root } }
1
Kotlin
1
0
535991fedd2c69006cc4df7891675653ab35cd99
1,716
TIM-Example-Android
MIT License
kotter/src/commonMain/kotlin/com/varabyte/kotter/platform/internal/system/ShutdownHook.kt
varabyte
397,769,020
false
{"Kotlin": 488088}
package com.varabyte.kotter.platform.internal.system internal expect fun onShutdown(dispose: () -> Unit)
12
Kotlin
16
507
53f5313ea424c81c69bf397754326df910a6508e
106
kotter
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/s3/RedirectProtocol.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.s3 public enum class RedirectProtocol( private val cdkObject: software.amazon.awscdk.services.s3.RedirectProtocol, ) { HTTP(software.amazon.awscdk.services.s3.RedirectProtocol.HTTP), HTTPS(software.amazon.awscdk.services.s3.RedirectProtocol.HTTPS), ; public companion object { internal fun wrap(cdkObject: software.amazon.awscdk.services.s3.RedirectProtocol): RedirectProtocol = when (cdkObject) { software.amazon.awscdk.services.s3.RedirectProtocol.HTTP -> RedirectProtocol.HTTP software.amazon.awscdk.services.s3.RedirectProtocol.HTTPS -> RedirectProtocol.HTTPS } internal fun unwrap(wrapped: RedirectProtocol): software.amazon.awscdk.services.s3.RedirectProtocol = wrapped.cdkObject } }
0
Kotlin
0
4
b1af417dc38eb29bba6244f8da914964c5e7fa3d
963
kotlin-cdk-wrapper
Apache License 2.0
cogboard-app/src/main/kotlin/com/cognifide/cogboard/security/JwtAuthHandlerFactory.kt
wttech
199,830,591
false
{"JavaScript": 338125, "Kotlin": 178733, "HTML": 2154, "Shell": 951, "Dockerfile": 433}
package com.cognifide.cogboard.security import com.cognifide.cogboard.utils.ExtensionFunctions.toJWT import io.knotx.server.api.security.AuthHandlerFactory import io.vertx.core.json.JsonObject import io.vertx.ext.auth.KeyStoreOptions import io.vertx.reactivex.core.Vertx import io.vertx.reactivex.ext.auth.jwt.JWTAuth import io.vertx.reactivex.ext.web.handler.AuthHandler import io.vertx.reactivex.ext.web.handler.JWTAuthHandler class JwtAuthHandlerFactory : AuthHandlerFactory { override fun getName(): String = "jwtAuthHandlerFactory" override fun create(vertx: Vertx?, config: JsonObject?): AuthHandler { val keyStoreOptions = KeyStoreOptions(config) return JWTAuthHandler.create(JWTAuth.create(vertx, keyStoreOptions.toJWT())) } }
56
JavaScript
9
15
fc2e392bc072ea5738b6172a5b1f01609b4e6f13
767
cogboard
Apache License 2.0
katan-api/src/main/kotlin/me/devnatan/katan/api/io/FileSystemAccessor.kt
KatanPanel
182,468,654
false
null
/* * Copyright 2020-present <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 me.devnatan.katan.api.io import me.devnatan.katan.api.Descriptor interface FileSystemAccessor { suspend fun newSession(holder: Descriptor): FileSystemSession }
0
Kotlin
7
48
4ba33e0ff126134e6d02b672bbccf72bf2defad5
774
Katan
Apache License 2.0
api/src/main/kotlin/io/github/legion2/tosca_orchestrator/orchestrator/artifact/ReconcilerInterface.kt
Legion2
350,881,803
false
null
package io.github.legion2.tosca_orchestrator.orchestrator.artifact object ReconcilerLifecycleInterface { const val name = "Reconciler" const val reconcileOperation = "reconcile" const val deletionOperation = "delete" }
6
Kotlin
0
3
fb4ef1a7bf3d79d258da2b6779381a87e0c435e9
232
ritam
Apache License 2.0
android-core/src/main/kotlin/org/mint/android/rule/input/RegexInputGenerator.kt
ing-bank
620,378,707
false
null
package org.mint.android.rule.input import com.github.curiousoddman.rgxgen.RgxGen import org.mint.android.AndroidState data class RegexInputGenerator(val regex: String) : (AndroidState) -> String { private val rgx = RgxGen(regex) override fun invoke(s: AndroidState): String = rgx.generate() }
0
Kotlin
2
4
abf96d311b3ebb1bba2a331a353126c653225be9
305
mint
MIT License
src/main/kotlin/no/nav/syfo/huskelapp/domain/Oppfolgingsgrunn.kt
navikt
696,687,106
false
{"Kotlin": 117434, "Dockerfile": 226}
package no.nav.syfo.huskelapp.domain enum class Oppfolgingsgrunn { TA_KONTAKT_SYKEMELDT, TA_KONTAKT_ARBEIDSGIVER, TA_KONTAKT_BEHANDLER, VURDER_DIALOGMOTE_SENERE, FOLG_OPP_ETTER_NESTE_SYKMELDING, VURDER_TILTAK_BEHOV, VURDER_ARBEIDSUFORHET, FRISKMELDING_TIL_ARBEIDSFORMIDLING, ANNET, }
1
Kotlin
0
0
28604244b7aa972f6b14feed03f98fd59e65d4a3
321
ishuskelapp
MIT License
sqldelight-gradle-plugin/src/test/integration-multiplatform/src/androidMain/kotlin/com/squareup/sqldelight/integration/android.kt
mycoola-zz
162,573,643
true
{"Kotlin": 554975, "Java": 9356, "Shell": 1970, "HTML": 57}
package com.squareup.sqldelight.integration import com.squareup.sqldelight.db.SqlDatabase import com.squareup.sqldelight.sqlite.driver.SqliteJdbcOpenHelper import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.TimeUnit actual fun createSqlDatabase(): SqlDatabase { return SqliteJdbcOpenHelper().apply { QueryWrapper.Schema.create(getConnection()) } } actual class MPWorker actual constructor(){ private val executor = Executors.newSingleThreadExecutor() actual fun <T> runBackground(backJob: () -> T): MPFuture<T> { return MPFuture(executor.submit(backJob) as Future<T>) } actual fun requestTermination() { executor.shutdown() executor.awaitTermination(30, TimeUnit.SECONDS) } } actual class MPFuture<T>(private val future:Future<T>) { actual fun consume():T = future.get() }
0
Kotlin
0
0
19bd1645268b11d7433a47a0af8e653a07181f61
860
sqldelight
Apache License 2.0
app/src/main/java/com/oratakashi/covid19/ui/theme/ThemeDialogFragment.kt
oratakashi
248,692,046
false
null
package com.oratakashi.covid19.ui.theme import android.os.Bundle import com.google.android.material.bottomsheet.BottomSheetDialogFragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import butterknife.ButterKnife import butterknife.OnClick import com.oratakashi.covid19.R import com.oratakashi.covid19.data.db.Sessions import com.oratakashi.covid19.root.App import kotlinx.android.synthetic.main.fragment_theme_dialog.* class ThemeDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_theme_dialog, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { ButterKnife.bind(this, view) when(App.sessions!!.getTheme()){ "basic" -> { tvBasicStatus.visibility = View.VISIBLE } "advance" -> { tvAdvanceStatus.visibility = View.VISIBLE } } } @OnClick(R.id.cvBasic) fun onBasic(){ parent.onThemeChanged("basic") dismiss() } @OnClick(R.id.cvAdvance) fun onAdvance(){ parent.onThemeChanged("advance") dismiss() } companion object { lateinit var parent : ThemeInterfaces fun newInstance(interfaces: ThemeInterfaces): ThemeDialogFragment = ThemeDialogFragment().apply { parent = interfaces } } }
0
Kotlin
0
6
2558cb2d6baf24ef7f93cfe00dd12decf3d35eba
1,718
COVID19_Tracker
Apache License 2.0
app/src/main/java/com/merative/healthpass/models/OfflineModeException.kt
digitalhealthpass
563,978,682
false
{"Kotlin": 1047923, "HTML": 79495, "Python": 22113, "Java": 1959}
package com.merative.healthpass.models import retrofit2.HttpException import retrofit2.Response class OfflineModeException(response: Response<*>) : HttpException(response)
0
Kotlin
0
0
2b086f6fad007d1a574f8f0511fff0e65e100930
173
dhp-android-app
Apache License 2.0
android/app/src/main/kotlin/com/example/flutter_firstapp/MainActivity.kt
JordiDeSanta
338,121,067
false
{"Dart": 3836, "Swift": 404, "Kotlin": 133, "Objective-C": 38}
package com.example.flutter_firstapp import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
1149b1f304cbd9f6309a79d4bdb23ae9ac80d33d
133
Flutter-First-App
MIT License
data/local/src/commonMain/kotlin/io/spherelabs/data/local/db/otp/OtpDigitEntity.kt
getspherelabs
687,455,894
false
{"Kotlin": 645187, "Ruby": 6822, "Swift": 1167, "Shell": 226}
package io.spherelabs.data.local.db.otp enum class OtpDigitEntity(val number: Long) { SIX(6), EIGHT(8); companion object { operator fun invoke(number: Long): OtpDigitEntity? { return fromRaw(number) } private fun fromRaw(number: Long): OtpDigitEntity? { return values().find { it.number == number } } } }
25
Kotlin
21
134
09ce4d285d7dc88e265ca0534272f20c7254b82c
380
anypass-kmp
Apache License 2.0
app/src/main/java/com/newbiechen/nbreader/ui/page/read/ReadActivity.kt
newbiechen1024
239,496,581
false
null
package com.newbiechen.nbreader.ui.page.read import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.newbiechen.nbreader.R import com.newbiechen.nbreader.data.entity.BookEntity import com.newbiechen.nbreader.databinding.ActivityReadBinding import com.newbiechen.nbreader.ui.component.adapter.PageAnimAdapter import com.newbiechen.nbreader.ui.component.adapter.ReadCatalogAdapter import com.newbiechen.nbreader.ui.component.book.BookController import com.newbiechen.nbreader.ui.component.book.OnLoadListener import com.newbiechen.nbreader.ui.component.book.text.engine.PagePosition import com.newbiechen.nbreader.ui.component.book.text.engine.PageProgress import com.newbiechen.nbreader.ui.component.decoration.DividerDecoration import com.newbiechen.nbreader.ui.component.decoration.SpaceDecoration import com.newbiechen.nbreader.ui.component.extension.closeDrawer import com.newbiechen.nbreader.ui.component.extension.isDrawerOpen import com.newbiechen.nbreader.ui.component.extension.openDrawer import com.newbiechen.nbreader.ui.component.widget.page.DefaultActionCallback import com.newbiechen.nbreader.ui.component.widget.page.OnPageListener import com.newbiechen.nbreader.ui.component.widget.page.PageAnimType import com.newbiechen.nbreader.ui.component.widget.page.action.TapMenuAction import com.newbiechen.nbreader.uilts.SystemBarUtil import com.newbiechen.nbreader.ui.page.base.BaseBindingActivity /** * author : newbiechen * date : 2019-08-25 16:28 * description :书籍阅读页面 */ class ReadActivity : BaseBindingActivity<ActivityReadBinding>(), View.OnClickListener { companion object { private const val TAG = "ReadActivity" private const val EXTRA_BOOK = "extra_book" fun startActivity(context: Context, book: BookEntity) { val intent = Intent(context, ReadActivity::class.java) intent.putExtra(EXTRA_BOOK, book) context.startActivity(intent) } } private lateinit var mViewModel: ReadViewModel private lateinit var mBook: BookEntity private lateinit var mBookController: BookController private lateinit var mCatalogAdapter: ReadCatalogAdapter private lateinit var mTvPageTitle: TextView private lateinit var mTvPageTip: TextView override fun initContentView(): Int = R.layout.activity_read override fun initData(savedInstanceState: Bundle?) { super.initData(savedInstanceState) mBook = intent.getParcelableExtra(EXTRA_BOOK) } override fun initView() { super.initView() mDataBinding.apply { // 初始化 toolbar supportActionBar(toolbar) // 设置颜色半透明 overStatusBar(toolbar) // 隐藏系统状态栏 hideSystemBar() // 初始化点击事件 tvCategory.setOnClickListener(this@ReadActivity) tvNightMode.setOnClickListener(this@ReadActivity) tvSetting.setOnClickListener(this@ReadActivity) tvBright.setOnClickListener(this@ReadActivity) menuFrame.setOnClickListener(this@ReadActivity) initPageView() initSlideView() initMenu() } } /** * 初始化侧滑栏 */ private fun initSlideView() { mDataBinding.apply { // 初始化侧滑栏 dlSlide.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) // 允许手势关闭侧滑栏 dlSlide.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerStateChanged(newState: Int) { } override fun onDrawerSlide(drawerView: View, slideOffset: Float) { } override fun onDrawerClosed(drawerView: View) { dlSlide.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) } override fun onDrawerOpened(drawerView: View) { dlSlide.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) // 让状态栏消失 hideSystemBar() } }) // 设置背景图片 val slideBg = Drawable.createFromStream(assets.open("wallpaper/paper.jpg"), null) llSlideContainer.background = slideBg // 初始化目录标题 tvBookTitle.text = mBook.title // 初始化 RecyclerView mCatalogAdapter = ReadCatalogAdapter() mCatalogAdapter.setOnItemClickListener { _, value -> // 通知切换章节 mBookController.skipChapter(value.index) // 关闭滑动 dlSlide.closeDrawer() } rvCatalog.apply { layoutManager = LinearLayoutManager(context) adapter = mCatalogAdapter addItemDecoration( DividerDecoration( dividerColor = context.resources.getColor(R.color.read_catalog_divider) ) ) } } } private fun initPageView() { val pageView = mDataBinding.pvBook val pageHeaderView = LayoutInflater.from(this).inflate(R.layout.layout_page_header, pageView, false) mTvPageTitle = pageHeaderView.findViewById(R.id.tv_title) val pageFooterView = LayoutInflater.from(this).inflate(R.layout.layout_page_footer, pageView, false) mTvPageTip = pageFooterView.findViewById(R.id.tv_page_tip) pageView.apply { // 设置顶部和底部 setHeaderView(pageHeaderView) setFooterView(pageFooterView) // 将页面控制器,封装为书籍控制器 mBookController = BookController(getPageController()) // 设置页面监听 mBookController.setPageListener(object : OnPageListener { override fun onPreparePage(pagePosition: PagePosition, pageProgress: PageProgress) { // TODO:异步加载书籍,会导致异步获取到了章节,但是还没有发送给 catalogAdapter 就回调了。 if (mCatalogAdapter.getItem(pagePosition.chapterIndex) == null) { return } // TODO:使用 DataBinding 会导致数据更新不及时的问题,所以 headerView 和 footerView 禁止使用 onPagePositionChange(pagePosition, pageProgress) } override fun onPageChange(pagePosition: PagePosition, pageProgress: PageProgress) { onPagePositionChange(pagePosition, pageProgress) } }) // 设置页面事件监听 mBookController.setPageActionListener(object : DefaultActionCallback() { override fun onTapMenuAction(action: TapMenuAction) { toggleMenu() } }) } } /** * 初始化菜单 */ private fun initMenu() { // 初始化翻页动画 mDataBinding.rvReadAnim.apply { layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false) adapter = PageAnimAdapter().also { // 添加数据 it.refreshItems(PageAnimType.values().toList()) // 设置点击事件监听 it.setOnItemClickListener { pos, value -> mDataBinding.pvBook.setPageAnim(value) } } addItemDecoration( SpaceDecoration( horizonSpace = context.resources.getDimension(R.dimen.space_read_setting_page_anim) .toInt(), isBetween = true ) ) } } private fun onPagePositionChange(pagePosition: PagePosition, pageProgress: PageProgress) { // 设置顶部信息 mTvPageTitle.text = resources.getString( R.string.read_chapter_title, mCatalogAdapter.getItem(pagePosition.chapterIndex)!!.title ) // 设置底部信息 mTvPageTip.text = resources.getString( R.string.read_page_tip, pageProgress.pageIndex + 1, pageProgress.pageCount ) } private fun showSystemBar() { //显示 SystemBarUtil.showUnStableStatusBar(this) } private fun hideSystemBar() { //隐藏 SystemBarUtil.hideStableStatusBar(this) // SystemBarUtil.hideStableNavBar(this) } override fun processLogic() { super.processLogic() mViewModel = ViewModelProvider(this).get(ReadViewModel::class.java) // 需要对 viewmodel 做一次初始化操作 mViewModel.init(this) mDataBinding.viewModel = mViewModel // 打开书籍 openBook() } private fun openBook() { // TODO:需要有加载完成动画 var loadDialog: ProgressDialog? = null mBookController.setOnLoadListener(object : OnLoadListener { override fun onLoading() { // 弹出一个 Loading Dialog loadDialog = ProgressDialog.show( this@ReadActivity, "等待书籍加载完成", "Loading. Please wait...", true ) } override fun onLoadSuccess() { // 关闭 loading Dialog loadDialog!!.cancel() // 显示章节信息 mCatalogAdapter.refreshItems(mBookController.getChapters()) // 更新 page 信息 val pageProgress = mBookController.getCurProgress() val pagePosition = mBookController.getCurPosition() if (pageProgress != null && pagePosition != null) { onPagePositionChange(pagePosition, pageProgress) } // 刷新页面 mDataBinding.executePendingBindings() } override fun onLoadFailure(e: Throwable) { // 关闭 loading Dialog loadDialog!!.cancel() } }) addDisposable(mBookController.open(this, mBook)) } override fun onBackPressed() { when { mDataBinding.dlSlide.isDrawerOpen() -> mDataBinding.dlSlide.closeDrawer() mViewModel.isShowMenu.get()!! -> mViewModel.isShowMenu.set(false) else -> super.onBackPressed() } } private fun toggleMenu() { mViewModel.apply { if (isShowMenu.get()!!) { hideSystemBar() } else { showSystemBar() } isShowMenu.set(!isShowMenu.get()!!) } } private fun toggleNightMode() { mViewModel.apply { isNightMode.set(!isNightMode.get()!!) } } override fun onClick(v: View?) { mViewModel.apply { when (v!!.id) { R.id.tv_night_mode -> { toggleNightMode() } R.id.tv_category -> { // 关闭菜单 isShowMenu.set(false) // 打开抽屉 mDataBinding.dlSlide.openDrawer() } R.id.tv_setting -> { // 创建 dialog isShowMenu.set(false) isShowSettingMenu.set(true) } R.id.tv_bright -> { isShowMenu.set(false) isShowBrightMenu.set(true) } R.id.menu_frame -> { when { isShowSettingMenu.get()!! -> isShowSettingMenu.set(false) isShowBrightMenu.get()!! -> isShowBrightMenu.set(false) else -> toggleMenu() } } } } } override fun onDestroy() { super.onDestroy() // 关闭书籍 mBookController.close() } }
5
Kotlin
8
37
e423b13915578ab95c1683bfa7a70e59f19f2eab
12,029
NBReader
Apache License 2.0
PoliFitnessApp/app/src/main/java/com/uca/polifitnessapp/data/db/dao/UserDao.kt
PoliFitness-App
638,055,292
false
null
package com.uca.polifitnessapp.data.db.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import com.uca.polifitnessapp.data.db.models.UserModel @Dao interface UserDao { //Funcion para obtener todos los usuarios @Query("SELECT * FROM user_table") suspend fun getAllUsers(): List<UserModel> // Funcion para eliminar un usuario @Query("DELETE FROM user_table WHERE _id = :id") suspend fun deleteUser(id: String) //Funcion para insertar un usuario @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertUser(user: UserModel) //Funcion para obtener un usuario por id @Query("SELECT * FROM user_table WHERE _id = :id") suspend fun getUserById(id: String): UserModel? //Funcion para actualizar un usuario @Update suspend fun updateUser(user: UserModel) //Funcion para eliminar un usuario @Query("SELECT * FROM user_table LIMIT 1") suspend fun getUser(): UserModel? //Funcion para actualizar IMC e ICC @Query("UPDATE user_table SET imc = :imc, icc = :icc WHERE _id = :id") suspend fun updateImcIccUser(id: Int, imc: Float, icc: Float) }
0
Kotlin
0
0
f034cc0e75e4e3646172c951fb565dafa37dc1ab
1,298
PoliFitnessApp
MIT License
app/src/main/java/com/jpb/scratchtappy/usp/mdcomp.kt
jpbandroid
517,991,180
false
null
package com.jpb.scratchtappy.usp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.jpb.scratchtappy.usp.MDComponent class mdcomp : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_mdcomp) val ab: androidx.appcompat.app.ActionBar? = supportActionBar ab?.setTitle("MD Components") ab?.setSubtitle("ADL, Holo, MD, MD3") } }
9
Kotlin
0
1
1c734e8770e9482c79449654a918e33a4d8243d7
498
USP
Apache License 2.0
frontend/kobweb-core/src/jsMain/kotlin/com/varabyte/kobweb/core/PageContext.kt
varabyte
389,223,226
false
null
package com.varabyte.kobweb.core import androidx.compose.runtime.* import com.varabyte.kobweb.navigation.Router import kotlinx.browser.window /** * Various contextual information useful for a page. * * Access it using [rememberPageContext] either in the page itself or within any composable nested inside of it. * * ``` * @Page * @Composable * fun SettingsPage() { * val ctx = rememberPageContext() * val userName = ctx.params["username"] ?: "Unknown user" * ... * } */ class PageContext(val router: Router) { companion object { internal val active by lazy { mutableStateOf<PageContext?>(null) } } internal val mutableParams = mutableMapOf<String, String>() /** * The slug for the current page. * * In the URL: "https://example.com/a/b/c/slug?x=1&y=2#id", the slug is "slug" */ val slug: String get() = window.location.pathname.substringAfterLast('/') /** * Params extracted either from the URL's query parameters OR from a dynamic route * * For example: * * ``` * /users/posts?user=123&post=11 * ``` * * and/or * * ``` * /users/123/posts/11 * * # for a URL registered as "/users/{user}/posts/{post}" * ``` * * will generate a mapping of "user" to 123 and "post" to 11 */ val params: Map<String, String> = mutableParams /** * The post-hash fragment of a URL, if specified. * * For example, `/a/b/c/#fragment-id` will be the value `fragment-id` */ var fragment: String? = null internal set } /** * A property which indicates if this current page is being rendered as part of a Kobweb export. * * While it should be rare that you'll need to use it, it can be useful to check if you want to avoid doing some * side-effect that shouldn't happen at export time, like sending page visit analytics to a server for example. */ val PageContext.isExporting: Boolean get() = params.containsKey("_kobwebIsExporting") /** * Returns the active page's context. * * This will throw an exception if not called within the scope of a `@Page` annotated composable. */ @Composable fun rememberPageContext(): PageContext = remember { PageContext.active.value ?: error("`rememberPageContext` called outside of the scope of a `@Page` annotated method.") }
85
Kotlin
21
570
54bb2756f40fc119179aaa0f0ad2b358d78affff
2,352
kobweb
Apache License 2.0
app/src/main/java/com/example/androidhub/ui/adapter/ImageAdapter.kt
Zhangw1998
241,874,696
false
null
package com.example.androidhub.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.androidhub.R import com.example.androidhub.bean.ImageData import kotlinx.android.synthetic.main.item_image.view.* class ImageAdapter(val imgList: List<ImageData>): RecyclerView.Adapter<ImageAdapter.ViewHolder>() { inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) { fun bind(data: ImageData) { with(itemView) { tv_name.text = data.name Glide.with(this) .load(data.url) .into(iv_img) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return imgList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(imgList[position]) } }
0
Kotlin
0
0
38473aa4a9d8505a4299ee867faef09e25dd2d9c
1,178
AndroidHub
Apache License 2.0
app/src/main/java/com/traveloka/chatbot/core/domain/usecase/ChatUseCase.kt
harhar-sumbogo
492,164,774
false
{"Kotlin": 41851}
package com.traveloka.chatbot.core.domain.usecase import androidx.lifecycle.LiveData import com.traveloka.chatbot.core.data.Result import com.traveloka.chatbot.core.domain.model.MessageModel interface ChatUseCase { fun createUser(token: String): LiveData<String> fun createGroup(token: String): LiveData<Result<String>> fun sendMessage(message: MessageModel, token: String): LiveData<Result<MessageModel>> fun loadCacheMessage(): LiveData<List<MessageModel>> fun deleteCacheChat() }
0
Kotlin
1
3
b30ed94216b273cb117404bc638e7f230a671d33
508
ChatBotTraveloka
Apache License 2.0
shared/src/commonMain/kotlin/de/paulweber/spenderino/viewmodel/ViewModel.kt
pumapaul
456,565,521
false
{"Kotlin": 315206, "Swift": 77223, "Ruby": 57}
package de.paulweber.spenderino.viewmodel import co.touchlab.kermit.Logger import de.paulweber.spenderino.utility.CFlow import de.paulweber.spenderino.utility.wrap import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import org.koin.core.component.KoinComponent interface AlertRoute { val alert: AlertViewModel } interface Navigating { val viewModel: HasOnBack } interface HasOnBack { fun onBackButton() } interface ViewModeling<Action, Route, State> : HasOnBack { val wrappedState: CFlow<State> val wrappedRoute: CFlow<Route?> val state: StateFlow<State> val route: StateFlow<Route?> fun perform(action: Action) fun routeToNull() } abstract class ViewModel<Action, Route, State>( state: State, route: Route? = null, protected val onBack: () -> Unit = {} ) : ViewModeling<Action, Route, State>, KoinComponent { override val wrappedState: CFlow<State> get() = mutableState.wrap() override val wrappedRoute: CFlow<Route?> get() = mutableRoute.wrap() override val state: StateFlow<State> get() = mutableState override val route: StateFlow<Route?> get() = mutableRoute private val mutableState = MutableStateFlow(state) private val mutableRoute = MutableStateFlow(route) protected val scope = CoroutineScope(Dispatchers.Default) protected fun setState(state: State) { if (state != this.state.value) { Logger.d("${this::class.simpleName}-STATE: $state") mutableState.value = state } } protected fun setRoute(route: Route?) { if (route != this.route.value) { Logger.d("${this::class.simpleName}-ROUTE: $route") mutableRoute.value = route } } override fun onBackButton() { Logger.d("${this::class.simpleName} onBack()") onBack() } override fun routeToNull() { Logger.d("${this::class.simpleName} routeToNull()") setRoute(null) } }
0
Kotlin
0
3
61bf26f94940b6a84840f28b62817eefa9f21231
2,101
Spenderino
MIT No Attribution
app/src/main/java/com/example/echangeapp/domain/usecases/ReadAvailableCurrencyAmountUseCase.kt
dtx12
273,499,039
false
null
package com.example.echangeapp.domain.usecases import com.example.echangeapp.domain.models.Currency import com.example.echangeapp.domain.models.CurrencyAmount import com.example.echangeapp.domain.repositories.AvailableCurrencyRepository import javax.inject.Inject class ReadAvailableCurrencyAmountUseCase @Inject constructor(private val availableCurrencyRepo: AvailableCurrencyRepository) { fun execute(base: Currency): CurrencyAmount { return availableCurrencyRepo.read(base) } }
0
Kotlin
0
0
61b3a2265811262ce413a246230fa7418cd7e2c8
499
ExchangeTestTask
MIT License
modules/manual/src/main/kotlin/com.r3.corda.finance.manual/types/ManualPayment.kt
dazraf
174,323,076
true
{"Kotlin": 192264}
package com.r3.corda.finance.manual.types import com.r3.corda.finance.obligation.contracts.types.Payment import com.r3.corda.finance.obligation.contracts.types.PaymentReference import com.r3.corda.finance.obligation.contracts.types.PaymentStatus import com.r3.corda.lib.tokens.money.FiatCurrency import net.corda.core.contracts.Amount /** Represents a manual payment. */ data class ManualPayment( override val paymentReference: PaymentReference, override val amount: Amount<FiatCurrency>, override var status: PaymentStatus = PaymentStatus.SENT ) : Payment<FiatCurrency> { override fun toString(): String { return "Amount: $amount, manual reference: $paymentReference, Status: $status" } }
0
Kotlin
0
0
8af0e751139b76a77714f8d84ec302337cbccf50
731
corda-settler
Apache License 2.0
agora.post/src/commonMain/kotlin/org/agorahq/agora/post/viewmodel/PostViewModel.kt
agorahq
228,175,670
false
null
package org.agorahq.agora.post.viewmodel import org.agorahq.agora.core.api.view.ViewModel data class PostViewModel( val id: String, val ownerId: String, val abstract: String, val excerpt: String, val title: String, val tags: String, val content: String, val publicationDate: String? = null, val isPublished: Boolean = false, val url: String? = null ) : ViewModel
28
Kotlin
0
0
a7aeabc25d31e11090f37733de2b8ec138d1de3b
445
agora
Apache License 2.0
libraries/csm.cloud.common.event-consumer/src/main/kotlin/com/bosch/pt/csm/cloud/common/businesstransaction/jpa/JpaEventOfBusinessTransactionRepository.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2022 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.common.businesstransaction.jpa import java.time.LocalDateTime import java.util.UUID import org.springframework.data.jpa.repository.JpaRepository interface JpaEventOfBusinessTransactionRepository : JpaRepository<EventOfBusinessTransactionEntity, Long> { fun countAllByCreationDateLessThan(creationDate: LocalDateTime): Int fun findFirstByEventProcessorNameOrderByConsumerOffsetAsc( eventProcessorName: String ): EventOfBusinessTransactionEntity? fun findAllByTransactionIdentifierAndEventProcessorName( transactionIdentifier: UUID, eventProcessorName: String ): Collection<EventOfBusinessTransactionEntity> fun removeAllByTransactionIdentifierAndEventProcessorName( transactionIdentifier: UUID, eventProcessorName: String ) }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
1,034
bosch-pt-refinemysite-backend
Apache License 2.0
src/main/kotlin/com/example/dmzj_api/vo/ResultVO.kt
suppiac
510,615,371
false
null
package com.example.dmzj_api.vo data class ResultVO( var code: Int = 0, var msg: String = "", var res: Any? = null, )
0
Kotlin
1
2
a3c6641befa809fef2ebe74796db123d607c416f
130
dmzj_api
Apache License 2.0
common/src/desktopTest/kotlin/components/projectselection/ProjectSelectionComponentTest.kt
Wavesonics
499,367,913
false
null
package components.projectselection import com.akuleshov7.ktoml.Toml import com.arkivanov.decompose.ComponentContext import com.arkivanov.essenty.lifecycle.Lifecycle import com.darkrockstudios.apps.hammer.common.data.ExampleProjectRepository import com.darkrockstudios.apps.hammer.common.data.projectsrepository.ProjectsRepository import com.darkrockstudios.apps.hammer.common.dependencyinjection.createJsonSerializer import com.darkrockstudios.apps.hammer.common.dependencyinjection.createTomlSerializer import com.darkrockstudios.apps.hammer.common.fileio.okio.toHPath import com.darkrockstudios.apps.hammer.common.globalsettings.GlobalSettings import com.darkrockstudios.apps.hammer.common.globalsettings.GlobalSettingsRepository import com.darkrockstudios.apps.hammer.common.projectselection.ProjectSelectionComponent import getProjectsDirectory import io.mockk.* import io.mockk.InternalPlatformDsl.toStr import kotlinx.serialization.json.Json import okio.fakefilesystem.FakeFileSystem import org.junit.Before import org.junit.Test import org.koin.dsl.bind import org.koin.dsl.module import utils.BaseTest import kotlin.test.assertEquals class ProjectSelectionComponentTest : BaseTest() { lateinit var ffs: FakeFileSystem lateinit var toml: Toml lateinit var json: Json lateinit var context: ComponentContext lateinit var lifecycle: Lifecycle lateinit var lifecycleCallbacks: MutableList<Lifecycle.Callbacks> lateinit var globalSettingsRepository: GlobalSettingsRepository lateinit var projectsRepository: ProjectsRepository lateinit var exampleProjectRepository: ExampleProjectRepository @Before override fun setup() { super.setup() ffs = FakeFileSystem() toml = createTomlSerializer() json = createJsonSerializer() context = mockk() lifecycle = mockk() lifecycleCallbacks = mutableListOf() globalSettingsRepository = mockk() projectsRepository = mockk() exampleProjectRepository = mockk() val testModule = module { single { globalSettingsRepository } bind GlobalSettingsRepository::class single { projectsRepository } bind ProjectsRepository::class single { exampleProjectRepository } bind ExampleProjectRepository::class } setupKoin(testModule) every { context.lifecycle } returns lifecycle every { lifecycle.subscribe(capture(lifecycleCallbacks)) } just Runs every { lifecycle.unsubscribe(any()) } just Runs val projectsDir = getProjectsDirectory() every { projectsRepository.getProjectsDirectory() } returns projectsDir.toHPath() ffs.createDirectories(projectsDir) val globalSettings = GlobalSettings( projectsDirectory = projectsDir.toStr(), ) every { globalSettingsRepository.globalSettings } returns globalSettings } @Test fun `Initialize ProjectSelectionComponent - No Example project`() { every { exampleProjectRepository.shouldInstallFirstTime() } returns false val component = ProjectSelectionComponent( componentContext = context, showProjectDirectory = false, onProjectSelected = {}, ) verify(exactly = 0) { exampleProjectRepository.install() } } @Test fun `Initialize ProjectSelectionComponent - Install Example project`() { every { exampleProjectRepository.shouldInstallFirstTime() } returns true every { exampleProjectRepository.install() } just Runs val component = ProjectSelectionComponent( componentContext = context, showProjectDirectory = false, onProjectSelected = {}, ) verify(exactly = 1) { exampleProjectRepository.install() } } @Test fun `Create Project - Fail`() { every { exampleProjectRepository.shouldInstallFirstTime() } returns false val projectNameSlot = slot<String>() every { projectsRepository.createProject(capture(projectNameSlot)) } returns false val component = ProjectSelectionComponent( componentContext = context, showProjectDirectory = false, onProjectSelected = {}, ) val testProjectName = "Test Project" component.createProject(testProjectName) assertEquals(testProjectName, projectNameSlot.captured) } @Test fun `Create Project - Succeed`() { every { exampleProjectRepository.shouldInstallFirstTime() } returns false val projectNameSlot = slot<String>() every { projectsRepository.createProject(capture(projectNameSlot)) } returns true val component = ProjectSelectionComponent( componentContext = context, showProjectDirectory = false, onProjectSelected = {}, ) val testProjectName = "Test Project" component.createProject(testProjectName) assertEquals(testProjectName, projectNameSlot.captured) // TODO now verify that the project list is reloaded } }
0
Kotlin
0
2
0284e04ded922c95867d7dcc7296e016fca4ce51
4,610
hammer-editor
MIT License
service/src/main/java/io/axoniq/handonaxon/conferencetracker/model/Conference.kt
Hands-on-Axon
701,250,533
false
{"Kotlin": 7602}
package io.axoniq.handonaxon.conferencetracker.model import io.axoniq.handonaxon.conferencetracker.api.* import org.axonframework.commandhandling.CommandHandler import org.axonframework.common.IdentifierFactory import org.axonframework.eventsourcing.EventSourcingHandler import org.axonframework.modelling.command.AggregateIdentifier import org.axonframework.modelling.command.AggregateLifecycle import org.axonframework.modelling.command.AggregateMember import org.axonframework.modelling.command.ForwardMatchingInstances import org.axonframework.spring.stereotype.Aggregate import java.util.* @Aggregate class Conference() { @AggregateIdentifier lateinit var conferenceId: String @AggregateMember(eventForwardingMode = ForwardMatchingInstances::class) val editions = mutableMapOf<String, ConferenceEdition>() @CommandHandler constructor(command: AddConferenceCommand): this() { // Validate the command // Generate an Event notifying the change produced by the Command val conferenceId = IdentifierFactory.getInstance().generateIdentifier() //This is equivalent in Axon to //val conferenceId = UUID.randomUUID().toString();; AggregateLifecycle.apply(ConferenceAddedEvent( conferenceId = conferenceId, name = command.name, website = command.website, location = command.location, family = command.family )) } @CommandHandler fun newEdition(command: AddConferenceEditionCommand): String { //validate //trigger corresponding event val editionId = UUID.randomUUID().toString().split("-").first AggregateLifecycle.apply(ConferenceEditionAddedEvent( conferenceId = conferenceId, editionId = editionId, year = command.year, startDate = command.startDate, venue = command.venue )) return editionId; } @EventSourcingHandler fun handle(event: ConferenceAddedEvent) { this.conferenceId = event.conferenceId } @EventSourcingHandler fun handle(event: ConferenceEditionAddedEvent) { this.editions[event.editionId] = ConferenceEdition(event.editionId, event.startDate) } }
0
Kotlin
0
0
823e28bad902318eb1044e459aa8587df80c1726
2,266
conference-tracker-sample
Apache License 2.0
app/src/main/java/com/mohmmed/mosa/eg/news/domain/usecase/news/NewsUseCases.kt
M4A28
817,807,588
false
{"Kotlin": 98711}
package com.mohmmed.mosa.eg.news.domain.usecase.news data class NewsUseCases( val getNews: GetNews, val searchNews: SearchNewsUseCases, val upsertArticle: UpsertArticle, val deleteArticle: DeleteArticle, val selectArticle: SelectArticle, val selectArticles: SelectArticles )
0
Kotlin
0
1
46e8d13441058464d9542c0c3babfd58e0ccdeaf
300
News
MIT License
app/src/main/java/com/zeroone/recyclo/ui/dashboard/waste/WasteFragment.kt
mohammad-firmansyah
642,413,824
false
null
package com.zeroone.recyclo.ui.dashboard.waste import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.floatingactionbutton.FloatingActionButton import com.zeroone.recyclo.R import com.zeroone.recyclo.ui.dashboard.waste.add.AddActivity // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [WasteFragment.newInstance] factory method to * create an instance of this fragment. */ class WasteFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_waste, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fab = view.findViewById<FloatingActionButton>(R.id.addToFav) fab.setOnClickListener { startActivity(Intent(view.context, AddActivity::class.java)) } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment WasteFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = WasteFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
0
1dae6245009f40723cc8f0bd4976c1d53a7c5026
2,415
ReCyclo
MIT License
04_collections/01.List.kt
alidehkhodaei
617,526,016
false
null
package `04_collections` fun main() { // List val list = listOf(1, 2, 3, 4, 5) val list2 = mutableListOf(1, 2, 3, 4, 5) val numbers = mutableListOf(1, 2, 3) numbers.add(4) // Adds the specified element to the end of the list numbers.remove(3) // Removes the first occurrence of the specified element from the list numbers[1] // Returns the element at the specified index in the list println(numbers) }
0
Kotlin
4
55
a9c9fe2922d5a8c6ad839de2064e56582a851bfc
435
kotlin-cheatsheet
MIT License
src/main/kotlin/nrxus/droptoken/persistence/DropToken.kt
nrxus
245,327,294
false
null
package nrxus.droptoken.persistence import javax.persistence.* @Entity class DropToken( @ElementCollection val originalPlayers: List<String>, @ElementCollection val currentPlayers: MutableList<String>, @Column(nullable = false) var state: State, @Column(nullable = false) var turn: Int, @ElementCollection // flattened list of all the player tokens // a -1 player token means the space is empty // an existing player token represents the player # that placed the token // based on its original player position var tokens: MutableList<Int>, @Column(nullable = true) var winner: String?, @OneToMany(cascade = [CascadeType.ALL], mappedBy = "dropToken", fetch = FetchType.LAZY) val moves: MutableList<Move>, @Id @GeneratedValue val id: Long = 0 ) { companion object { fun new(players: List<String>) = DropToken( originalPlayers = players, currentPlayers = players.toMutableList(), state = State.IN_PROGRESS, turn = 0, tokens = mutableListOf(), winner = null, moves = mutableListOf() ) } enum class State { IN_PROGRESS, DONE } }
0
Kotlin
0
0
4c969c69d213425cfd0117ca512a4d500b8eccf8
1,341
drop-token
MIT License
src/main/kotlin/bpm/mc/registries/ModTiles.kt
sincyn
850,591,647
false
{"Kotlin": 1001776}
package bpm.mc.registries import bpm.Bpm import bpm.booostrap.ModRegistry import bpm.mc.block.EnderControllerTileEntity import net.minecraft.core.registries.Registries import net.minecraft.world.level.block.entity.BlockEntityType import net.neoforged.bus.api.IEventBus import net.neoforged.neoforge.registries.DeferredRegister object ModTiles : ModRegistry<BlockEntityType<*>> { override val registry: DeferredRegister<BlockEntityType<*>> = DeferredRegister.create( Registries.BLOCK_ENTITY_TYPE, Bpm.ID ) val ENDER_CONTROLLER_TILE_ENTITY: BlockEntityType<EnderControllerTileEntity> by register { registry.register("ender_pipe_controller") { _ -> BlockEntityType.Builder.of(::EnderControllerTileEntity, ModBlocks.ENDER_CONTROLLER).build(null) } } }
1
Kotlin
1
0
0975bc4ac8c5d128db93525c4602e42cd321f281
856
bpm
MIT License
src/main/kotlin/bpm/mc/registries/ModTiles.kt
sincyn
850,591,647
false
{"Kotlin": 1001776}
package bpm.mc.registries import bpm.Bpm import bpm.booostrap.ModRegistry import bpm.mc.block.EnderControllerTileEntity import net.minecraft.core.registries.Registries import net.minecraft.world.level.block.entity.BlockEntityType import net.neoforged.bus.api.IEventBus import net.neoforged.neoforge.registries.DeferredRegister object ModTiles : ModRegistry<BlockEntityType<*>> { override val registry: DeferredRegister<BlockEntityType<*>> = DeferredRegister.create( Registries.BLOCK_ENTITY_TYPE, Bpm.ID ) val ENDER_CONTROLLER_TILE_ENTITY: BlockEntityType<EnderControllerTileEntity> by register { registry.register("ender_pipe_controller") { _ -> BlockEntityType.Builder.of(::EnderControllerTileEntity, ModBlocks.ENDER_CONTROLLER).build(null) } } }
1
Kotlin
1
0
0975bc4ac8c5d128db93525c4602e42cd321f281
856
bpm
MIT License
app/src/main/java/com/softaai/dsa_kotlin/priorityqueue/AbstractPriorityQueue.kt
amoljp19
537,774,597
false
{"Kotlin": 139041}
package com.softaai.dsa_kotlin.priorityqueue /** * Created by amoljp19 on 11/18/2022. * softAai Apps. */ abstract class AbstractPriorityQueue<T> : Queue<T> { abstract val heap : Heap<T> get override val count: Int get() = heap.count override val isEmpty: Boolean get() = heap.isEmpty override fun enqueue(element: T): Boolean { heap.insert(element) return true } override fun dequeue(): T? = heap.remove() override fun peek(): T? = heap.peek() }
0
Kotlin
0
1
3dabfbb1e506bec741aed3aa13607a585b26ac4c
521
DSA_KOTLIN
Apache License 2.0
app/src/main/java/com/pawegio/homebudget/login/LoginFragment.kt
pawegio
193,266,818
false
{"Kotlin": 132199, "Shell": 858}
package com.pawegio.homebudget.login import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.koin.androidx.viewmodel.ext.android.getViewModel import splitties.views.onClick class LoginFragment : Fragment() { private val ui by lazy { LoginUi(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = ui.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewModel = getViewModel<LoginViewModel>() ui.signInButton.onClick { viewModel.actions.accept(LoginAction.SelectSignIn) } } }
2
Kotlin
6
7
7ab504bdec5ea253d6c3fe015801be669f2c0e88
810
HomeBudget
Apache License 2.0
module_base/src/main/java/kylec/me/base/user/UserDao.kt
lovelyefyyucui
228,560,285
false
{"Kotlin": 97529, "Java": 41712}
package kylec.me.base.user import com.vicpin.krealmextensions.delete import com.vicpin.krealmextensions.query import com.vicpin.krealmextensions.save /** * Created by KYLE on 2019/5/9 - 10:55 */ object UserDao { fun queryUser(username: String) = query<User> { equalTo("username", username) }.firstOrNull() fun saveUser(user: User) = user.save() fun deleteUser(username: String) = delete<User> { equalTo("username", username) } }
0
null
0
0
0e2a293792d90548f2253c38e59b647aafd0605a
448
KJWanAndroid
Apache License 2.0
build-logic/convention/src/main/kotlin/UiFeatureModulePlugin.kt
Reach2027
741,563,053
false
{"Kotlin": 61951}
import com.reach.modernandroid.configureComposeLibraries import org.gradle.api.Plugin import org.gradle.api.Project class UiFeatureModulePlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply { apply("reach.android.library") } configureComposeLibraries() } } }
0
Kotlin
0
1
f20bc1d1bdc1a9df5b748e3e3bce875f6a76e2df
383
ModernAndroid
Apache License 2.0
app/src/main/java/dev/dvdciri/sampleapp/postdetails/mapper/PostDetailsToUiModelsMapper.kt
dvdciri
174,832,272
false
null
package dev.dvdciri.sampleapp.postdetails.mapper import dev.dvdciri.sampleapp.domain.model.PostDetails import dev.dvdciri.sampleapp.post.mapper.PostToPostUiModelMapper import dev.dvdciri.sampleapp.ui.ItemUiModel class PostDetailsToUiModelsMapper constructor( private val userToAuthorUiModelMapper: UserToAuthorUiModelMapper, private val postToPostUiModelMapper: PostToPostUiModelMapper ) { fun mapToPresentation(postDetails: PostDetails): List<ItemUiModel> { return listOf( postToPostUiModelMapper.mapToPresentation(postDetails.post), userToAuthorUiModelMapper.mapToPresentation(postDetails.author) ) } }
2
Kotlin
0
1
8e091dd06f4b639f1dc62448d9f6cbb15efc6ed0
664
SampleApp-Android
Apache License 2.0
app/src/main/java/com/funny/app/gif/memes/ui/maker/model/MineViewModel.kt
yibulaxi
616,417,403
false
{"Java": 1087519, "Kotlin": 361539}
package com.funny.app.gif.memes.ui.maker.model import com.funny.app.gif.memes.ui.maker.PickActivity import com.xm.lib.base.inters.IBaseView import com.xm.lib.base.model.BaseViewModelKt import com.xm.lib.manager.IntentManager class MineViewModel: BaseViewModelKt<IBaseView>() { override fun onCreated() { } fun onClickChooseVideo() { IntentManager.startActivity(mCxt, PickActivity::class.java) } }
1
null
1
1
16c57fc7e91d945966c0876e404f33e75a89c8e9
424
GifSearch
Apache License 2.0
src/main/java/auth/api/BitbucketOAuth2Client.kt
rupebac
127,289,581
false
{"Java": 16240, "Kotlin": 11941, "JavaScript": 8480, "HTML": 3346}
package auth.api import org.apache.http.NameValuePair import org.apache.http.client.entity.UrlEncodedFormEntity import org.apache.http.client.methods.HttpPost import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.message.BasicNameValuePair import org.apache.http.protocol.HTTP import org.apache.http.util.EntityUtils import java.io.FileInputStream import java.io.IOException import java.util.* class BitbucketOAuth2Client { private val client_id:String private val client_secret:String init{ val props = Properties() val file = FileInputStream("src/main/resources/config.properties") props.load(file) client_id = props.getProperty("prop.bitbucket.client_id") client_secret = props.getProperty("prop.bitbucket.client_secret") } fun buildRedirectUrl(): String { return "$BITBUCKET_OAUTH2_AUTHORIZE?client_id=$client_id&response_type=code&state=xyz" } @Throws(IOException::class) fun getAccessToken(authorizationCode: String): String { val params = defaultParams params.add(BasicNameValuePair("code", authorizationCode)) params.add(BasicNameValuePair("grant_type", "authorization_code")) val token = performPost(params) return token } @Throws(IOException::class) fun refreshToken(refreshToken: String): String { val params = defaultParams params.add(BasicNameValuePair("refresh_token", refreshToken)) params.add(BasicNameValuePair("grant_type", "refresh_token")) val token = performPost(params) return token } private val defaultParams: MutableList<NameValuePair> get() { val params = ArrayList<NameValuePair>() params.add(BasicNameValuePair("client_id", client_id)) params.add(BasicNameValuePair("client_secret", client_secret)) return params } @Throws(IOException::class) private fun performPost(params: List<NameValuePair>): String { val post = HttpPost(BITBUCKET_OAUTH2_ACCESS_TOKEN) post.entity = UrlEncodedFormEntity(params, HTTP.UTF_8) val httpClient = HttpClientBuilder.create().build() val response = httpClient.execute(post) return EntityUtils.toString(response.entity, "UTF-8") } companion object { private val BITBUCKET_OAUTH2_AUTHORIZE = "https://bitbucket.org/site/oauth2/authorize" private val BITBUCKET_OAUTH2_ACCESS_TOKEN = "https://bitbucket.org/site/oauth2/access_token" } }
1
null
1
1
72e10cf4359c6d5ae44399d7c9df04778176451c
2,554
hard-worker-activity-stream
MIT License
mobile-app/src/main/kotlin/org/vivlaniv/nexohub/entities/cards/NewDeviceCard.kt
vityaman-edu
759,345,689
false
{"Kotlin": 214062}
package org.vivlaniv.nexohub.entities.cards import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import org.vivlaniv.nexohub.DeviceInfo import org.vivlaniv.nexohub.entities.cards.pictures.DeviceCanvas import org.vivlaniv.nexohub.entities.cards.pictures.DeviceFrame @Composable fun NewDeviceCard(device: DeviceInfo, onClick: () -> Unit) { Card( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { Surface( color = MaterialTheme.colorScheme.inversePrimary ) { Row( modifier = Modifier .fillMaxWidth() .clickable { onClick() }, verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier.weight(6f), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically ) { DeviceFrame { DeviceCanvas(type = device.type) } Column { Text( modifier = Modifier.padding(4.dp), text = device.type, fontSize = 20.sp, fontWeight = FontWeight.Bold ) } } Icon( modifier = Modifier.weight(1f), imageVector = Icons.Filled.Add, contentDescription = null ) } } } }
7
Kotlin
0
0
467b9f68b6a85ae20e91345aeabf8cc742ff73ed
2,423
nexo-hub
The Unlicense
o11nplugin-contrail-workflow-dsl/src/main/kotlin/net/juniper/contrail/vro/workflows/dsl/DataBinding.kt
tungstenfabric
237,744,206
false
null
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. */ package net.juniper.contrail.vro.workflows.dsl import net.juniper.contrail.vro.config.listElementProperty import net.juniper.contrail.vro.workflows.model.ParameterQualifier import net.juniper.contrail.vro.workflows.model.ParameterType import net.juniper.contrail.vro.workflows.model.any abstract class DataBinding<in Type : Any> { abstract val qualifier: ParameterQualifier? } object NoDataBinding : DataBinding<Any>() { override val qualifier: ParameterQualifier? get() = null } class FromParameterValue(val parameter: String) : DataBinding<Any>() { override val qualifier: ParameterQualifier? get() = bindDataTo(parameter, any) } class NullStateOfProperty(val item: String, val propertyPath: String) : DataBinding<Boolean>() { override val qualifier: ParameterQualifier? get() = bindValueToNullableState(item, propertyPath) } class FromSimplePropertyValue<Type : Any>( val item: String, val property: String, val type: ParameterType<Type> ) : DataBinding<Type>() { override val qualifier: ParameterQualifier? get() = bindValueToSimpleProperty(item, property, type) } class FromComplexPropertyValue<Type : Any>( val item: String, val propertyPath: String, val type: ParameterType<Type> ) : DataBinding<Type>() { override val qualifier: ParameterQualifier? get() = bindValueToComplexProperty(item, propertyPath, type) } class FromAction<Type : Any>(val actionCall: ActionCall, val type: ParameterType<Type>) : DataBinding<Type>() { override val qualifier: ParameterQualifier? get() = bindValueToAction(actionCall, type) } fun <Type : Any> fromAction(actionName: String, type: ParameterType<Type>, setup: ActionCallBuilder.() -> Unit): DataBinding<Type> = FromAction(actionCallTo(actionName).apply(setup).create(), type) fun <Type : Any> fromListElementProperty( parentItem: String, elementItem: String, propertyPrefix: String, propertyName: String, type: ParameterType<Type> ) = fromAction(listElementProperty, type) { parameter(parentItem) parameter(elementItem) string(propertyPrefix) string(propertyName.capitalize()) }
6
Kotlin
3
0
2a041934116d2d92a04f554222ea1512a9f09ffb
2,246
tf-vro-plugin
Apache License 2.0
src/main/kotlin/com/newardassociates/pptbuilder/text/TextProcessor.kt
tedneward
231,859,399
false
null
package com.newardassociates.pptbuilder.text import com.newardassociates.pptbuilder.Presentation import com.newardassociates.pptbuilder.Processor import com.newardassociates.pptbuilder.Section import com.newardassociates.pptbuilder.Slide import java.io.FileWriter class TextProcessor(options: Options) : Processor(options) { override val processorExtension : String = "txt" override fun write(outputFilename: String) { } var tabCount = 0 fun tabs() : String { var ret = "" for (i in 1..tabCount) ret += "_" return ret } override fun processPresentationNode(presentation: Presentation) { println("Presentation: ${presentation.title}") } override fun processSection(section: Section) { println("Section: ${section.title}") } override fun processSlide(slide: Slide) { println("Slide: ${slide.title}") } }
4
Kotlin
2
6
f4d70cd1edaa7098a0f31a32eef8c0570f7dd218
912
pptbuilder
Apache License 2.0
app/src/main/java/com/myth/ticketmasterapp/data/eventmodels/Embedded.kt
MichaelGift
634,539,469
false
{"Kotlin": 113077}
package com.myth.ticketmasterapp.data.eventmodels data class Embedded( val events: List<Event> )
0
Kotlin
1
0
398821b347414a3f5ea711143b5fcc6f266738a7
101
Event-Finder-App
MIT License
compiler/src/main/kotlin/se/ansman/kotshi/Options.kt
ansman
95,685,398
false
{"Kotlin": 410998, "Shell": 128}
package se.ansman.kotshi object Options { const val createAnnotationsUsingConstructor = "kotshi.createAnnotationsUsingConstructor" const val useLegacyDataClassRenderer = "kotshi.useLegacyDataClassRenderer" const val generatedAnnotation = "kotshi.generatedAnnotation" val possibleGeneratedAnnotations = setOf(Types.Java.generatedJDK9, Types.Java.generatedPreJDK9) .associateBy { it.canonicalName } }
3
Kotlin
43
746
45b2eceb8b38cb2362ca4854f1f50b1d97f603eb
424
kotshi
Apache License 2.0
src/test/kotlin/io/ankburov/videocontentserver/integration/MpegDashContentStorageEndpointTest.kt
AnkBurov
130,724,056
false
{"JavaScript": 28929, "Kotlin": 26659, "CSS": 17226, "HTML": 9298}
package io.ankburov.videocontentserver.integration import io.ankburov.videocontentserver.model.MpegDto import org.apache.commons.lang3.StringUtils import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.core.io.ClassPathResource import org.springframework.test.context.junit4.SpringRunner import ru.rgs.k6.extension.bodyNotNull import ru.rgs.k6.extension.generateBody import ru.rgs.k6.extension.isDashXml import ru.rgs.k6.extension.ok @RunWith(SpringRunner::class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MpegDashContentStorageEndpointTest { private val expectedFile = ClassPathResource("samples/with_sound.mp4") @Autowired private lateinit var restTemplate: TestRestTemplate @Test fun convertMp4AndGetMpd() { val (folderName, mpdFile) = restTemplate.postForEntity("/upload", generateBody(expectedFile), MpegDto::class.java) .ok() .bodyNotNull() val url = "/dash-storage/$folderName/$mpdFile" val mpd = restTemplate.getForEntity(url, String::class.java) .ok() .isDashXml() .bodyNotNull() Assert.assertTrue(StringUtils.containsIgnoreCase(mpd, "MPD")) } }
0
JavaScript
1
6
cf6225d0aa15d5f01763a70a194c348622fe3083
1,474
Video-content-server
MIT License
android/src/main/kotlin/dsishokov/yandex_sign/YandexSignPlugin.kt
Ishokov-Dzhafar
200,657,506
false
{"Dart": 3606, "Swift": 3132, "Ruby": 3122, "Kotlin": 2472, "Objective-C": 373}
package dsishokov.yandex_sign import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import io.flutter.plugin.common.PluginRegistry.Registrar import android.util.Base64 import android.util.Log import java.net.URLEncoder import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.EncodedKeySpec import java.security.KeyFactory import java.security.Signature class YandexSignPlugin: MethodCallHandler { companion object { @JvmStatic fun registerWith(registrar: Registrar) { val channel = MethodChannel(registrar.messenger(), "yandex_sign") channel.setMethodCallHandler(YandexSignPlugin()) } } override fun onMethodCall(call: MethodCall, result: Result) { if (call.method == "getSignUrl") { result.success(getSignUrl(call.arguments)) } else { result.notImplemented() } } private fun getSignUrl(arguments: Any): String { val params = arguments as Map<String, *> val url = params["url"] as String val key = params["androidKey"] as String val data = sha256rsa(key, url) return data } // Формирует подпись с помощью ключа. fun sha256rsa(key: String, data: String): String { val trimmedKey = key.replace("-----BEGIN RSA PRIVATE KEY-----", "") .replace("-----END RSA PRIVATE KEY-----", "") .replace("\\s".toRegex(), "") Log.d("KOTLIN", trimmedKey) try { val result = Base64.decode(trimmedKey, Base64.DEFAULT) val factory = KeyFactory.getInstance("RSA") val keySpec = PKCS8EncodedKeySpec(result) val signature = Signature.getInstance("SHA256withRSA") signature.initSign(factory.generatePrivate(keySpec)) signature.update(data.toByteArray()) val encrypted = signature.sign() return URLEncoder.encode(Base64.encodeToString(encrypted, Base64.NO_WRAP), "UTF-8") } catch (e: Exception) { throw SecurityException("Error calculating cipher data. SIC!") } } }
1
Dart
0
2
68e6c553706b5065b2afbed0bdd727cadf022cc0
2,098
yandex_sign
MIT License
app/src/main/java/com/az/learncompose/pokedex/ui/view/pokemonlist/PokemonListView.kt
azhar1038
380,442,537
false
null
package com.az.learncompose.pokedex.ui.view.pokemonlist import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment.Companion.Center import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource 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.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import coil.request.ImageRequest import com.az.learncompose.pokedex.R import com.az.learncompose.pokedex.data.models.PokedexListEntry import com.az.learncompose.pokedex.ui.theme.RobotoCondensed @Composable fun PokemonListView( navController: NavController, viewModel: PokemonListViewModel = hiltViewModel() ) { Surface( color = MaterialTheme.colors.background, modifier = Modifier.fillMaxSize() ) { Column { Spacer(Modifier.height(20.dp)) Image( painter = painterResource(R.drawable.ic_international_pokemon_logo), contentDescription = "Pokemon Logo", modifier = Modifier .fillMaxWidth() .align(CenterHorizontally) ) SearchBar( hint = "Search...", modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { viewModel.searchPokemonList(it) } Spacer(Modifier.height(16.dp)) PokemonList( navController = navController ) } } } @Composable fun SearchBar( modifier: Modifier = Modifier, hint: String = "", onSearch: (String) -> Unit = {}, ) { var text by remember { mutableStateOf("") } var isHintDisplayed by remember { mutableStateOf(text == "") } Box(modifier = modifier) { BasicTextField( value = text, onValueChange = { text = it isHintDisplayed = it == "" onSearch(it) }, maxLines = 1, singleLine = true, textStyle = TextStyle(color = Color.Black), modifier = Modifier .fillMaxWidth() .shadow(5.dp, shape = CircleShape) .background(Color.White, shape = CircleShape) .padding(horizontal = 20.dp, vertical = 16.dp) // .onFocusChanged { // isHintDisplayed = it.isFocused // } ) if (isHintDisplayed) { Text( hint, color = Color.LightGray, modifier = Modifier .padding(horizontal = 20.dp, vertical = 15.dp) ) } } } @Composable fun PokemonList( navController: NavController, viewModel: PokemonListViewModel = hiltViewModel() ) { val pokemonList by remember { viewModel.pokemonList } val endReached by remember { viewModel.endReached } val isLoading by remember { viewModel.isLoading } val loadError by remember { viewModel.loadError } val isSearching by remember { viewModel.isSearching } LazyColumn(contentPadding = PaddingValues(16.dp)) { val itemCount = if (pokemonList.size % 2 == 0) { pokemonList.size / 2 } else { pokemonList.size / 2 + 1 } items(itemCount) { if (it >= itemCount - 1 && !endReached && !isLoading && !isSearching) { viewModel.loadPokemonPaginated() } PokedexRow(rowIndex = it, entries = pokemonList, navController = navController) } } Box( contentAlignment = Center, modifier = Modifier.fillMaxSize() ) { if (isLoading) { CircularProgressIndicator(color = MaterialTheme.colors.primary) } if (loadError.isNotEmpty()) { RetrySection(error = loadError) { viewModel.loadPokemonPaginated() } } } } @Composable fun PokedexEntry( entry: PokedexListEntry, navController: NavController, modifier: Modifier = Modifier, viewModel: PokemonListViewModel = hiltViewModel() ) { val context = LocalContext.current val defaultDominantColor = MaterialTheme.colors.surface var dominantColor by remember { mutableStateOf(defaultDominantColor) } var bitmap by remember { mutableStateOf<Bitmap?>(null) } val request = ImageRequest.Builder(context) .data(entry.imageUrl) .crossfade(true) .build() LaunchedEffect(key1 = entry.imageUrl) { bitmap = viewModel.getBitmap(request) if (bitmap != null) { viewModel.calcDominantColor(bitmap!!) { dominantColor = it } } } Box( contentAlignment = Center, modifier = modifier .shadow(5.dp, shape = RoundedCornerShape(10.dp)) .clip(RoundedCornerShape(10.dp)) .aspectRatio(1f) .background( Brush.verticalGradient( listOf( dominantColor, defaultDominantColor, ) ) ) .clickable { navController.navigate( "pokemon_detail/${dominantColor.toArgb()}/${entry.pokemonName}" ) } ) { Column( horizontalAlignment = CenterHorizontally ) { if (bitmap == null) { CircularProgressIndicator( modifier = Modifier.scale(0.5f) ) } else { Image( bitmap = bitmap!!.asImageBitmap(), contentDescription = "${entry.pokemonName} image", modifier = Modifier.size(100.dp) ) } Text( text = entry.pokemonName, fontFamily = RobotoCondensed, fontSize = 20.sp, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) } } } @Composable fun PokedexRow( rowIndex: Int, entries: List<PokedexListEntry>, navController: NavController, ) { Column { Row { PokedexEntry( entry = entries[rowIndex * 2], navController = navController, modifier = Modifier.weight(1f) ) Spacer(Modifier.width(16.dp)) if (entries.size >= rowIndex * 2 + 2) { PokedexEntry( entry = entries[rowIndex * 2 + 1], navController = navController, modifier = Modifier.weight(1f) ) } else { Spacer(Modifier.weight(1f)) } } Spacer(Modifier.height(16.dp)) } } @Composable fun RetrySection( error: String, onRetry: () -> Unit ) { Column { Text(error, color = Color.Red, fontSize = 18.sp) Spacer(Modifier.height(8.dp)) Button( onClick = onRetry, modifier = Modifier.align(CenterHorizontally) ) { Text("Retry") } } }
0
Kotlin
0
0
5aeaa3fb01723fc0c39d55c6de97cdf11d49e04b
8,215
Pokedex-V1
MIT License
app/src/main/java/com/dicoding/moviesdb_compose/ui/component/NavigationBottomBar.kt
AlvinPradanaAntony
644,579,788
false
null
package com.dicoding.moviesdb_compose.ui.component import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Info import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import com.dicoding.moviesdb_compose.R import com.dicoding.moviesdb_compose.ui.component.navigation.NavigationItem import com.dicoding.moviesdb_compose.ui.component.navigation.NavigationRouteScreen import com.dicoding.moviesdb_compose.ui.theme.MoviesDB_ComposeTheme @Composable fun BottomBar( navController: NavHostController, modifier: Modifier = Modifier, ) { BottomNavigation( elevation = 4.dp, modifier = modifier .shadow(48.dp) .clip(RoundedCornerShape(28.dp)) ) { val navigationItems = listOf( NavigationItem( title = stringResource(R.string.menu_home), icon = Icons.Default.Home, screen = NavigationRouteScreen.Home ), NavigationItem( title = stringResource(R.string.menu_favourite), icon = Icons.Default.Favorite, screen = NavigationRouteScreen.Favourite ), NavigationItem( title = stringResource(R.string.menu_about), icon = Icons.Default.AccountCircle, screen = NavigationRouteScreen.About ), ) val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route BottomNavigation { navigationItems.map { item -> val curentSelected = currentRoute == item.screen.route BottomNavigationItem( icon = { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon( imageVector = item.icon, contentDescription = item.title ) if(curentSelected) { Text( text = item.title, textAlign = TextAlign.Center, fontSize = 10.sp ) } } }, selected = curentSelected, unselectedContentColor = LocalContentColor.current.copy(alpha = ContentAlpha.disabled), onClick = { navController.navigate(item.screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } restoreState = true launchSingleTop = true } } ) } } } } @Preview(showBackground = true) @Composable fun NavBarItemPreview() { MoviesDB_ComposeTheme { BottomBar( navController = NavHostController(LocalContext.current), modifier = Modifier ) } }
0
Kotlin
0
0
cae5a63e27ec15d50de240e3dbf71576e072a97a
4,280
MovieDB_Compose
Apache License 2.0
cxrv/src/test/kotlin/com/xiaocydx/cxrv/multitype/MutableMultiTypeTest.kt
xiaocydx
460,257,515
false
{"Kotlin": 1363378}
/* * Copyright 2022 xiaocydx * * 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.xiaocydx.cxrv.multitype import android.os.Build import com.google.common.truth.Truth.assertThat import io.mockk.spyk import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * [MutableMultiType]的单元测试 * * @author xcc * @date 2021/10/12 */ @Config(sdk = [Build.VERSION_CODES.Q]) @RunWith(RobolectricTestRunner::class) internal class MutableMultiTypeTest { private val testDelegate: TestDelegate = spyk(TestDelegate()) private val typeADelegate: TypeADelegate = spyk(TypeADelegate()) private val typeBDelegate: TypeBDelegate = spyk(TypeBDelegate()) @Test fun registerArray() { val delegate = object : AbsTestDelegate<Array<TestItem>>() {} val result = runCatching { mutableMultiTypeOf<Any>().init { register(delegate) } } assertThat(result.exceptionOrNull()).isNotNull() } @Test fun registerInterface() { val delegate = object : AbsTestDelegate<TestInterface>() {} val result = runCatching { mutableMultiTypeOf<Any>().init { register(delegate) } } assertThat(result.exceptionOrNull()).isNotNull() } @Test fun registerAnnotation() { val delegate = object : AbsTestDelegate<TestAnnotation>() {} val result = runCatching { mutableMultiTypeOf<Any>().init { register(delegate) } } assertThat(result.exceptionOrNull()).isNotNull() } @Test fun registerOneToOne() { mutableMultiTypeOf<Any>().init { register(testDelegate) assertThat(size).isEqualTo(1) assertRegistered(testDelegate) } } @Test fun registerOneToMany() { mutableMultiTypeOf<TypeTestItem>().init { register(typeADelegate) { it.type == TestType.TYPE_A } register(typeBDelegate) { it.type == TestType.TYPE_B } assertThat(size).isEqualTo(2) assertRegistered(typeADelegate) assertRegistered(typeBDelegate) } } @Test fun registerOneToManyCheckTypeGroups() { var exception: IllegalArgumentException? = null try { mutableMultiTypeOf<TypeTestItem>().init { register(typeADelegate) register(typeBDelegate) } } catch (e: IllegalArgumentException) { exception = e } assertThat(exception).apply { isNotNull() hasMessageThat().contains(typeADelegate.javaClass.simpleName) hasMessageThat().contains(typeBDelegate.javaClass.simpleName) } } @Test fun registerOneToOneAndOneToMany() { mutableMultiTypeOf<Any>().init { register(testDelegate) register(typeADelegate) { it.type == TestType.TYPE_A } register(typeBDelegate) { it.type == TestType.TYPE_B } assertThat(size).isEqualTo(3) assertRegistered(testDelegate) assertRegistered(typeADelegate) assertRegistered(typeBDelegate) } } @Test fun getTypeBySubClassItem() { val testDelegate = TestDelegate() val typeADelegate = TypeADelegate() val typeBDelegate = TypeBDelegate() val multiType = mutableMultiTypeOf<Any>().init { register(testDelegate) register(typeADelegate) { it.type == TestType.TYPE_A } register(typeBDelegate) { it.type == TestType.TYPE_B } } class TestItemSub : TestItem() class TypeTestItemSub(type: TestType) : TypeTestItem(type) val testItemSub = TestItemSub() val typeTestItemSubA = TypeTestItemSub(TestType.TYPE_A) val typeTestItemSubB = TypeTestItemSub(TestType.TYPE_B) assertThat(multiType.itemAt(testItemSub)?.delegate).isEqualTo(testDelegate) assertThat(multiType.itemAt(typeTestItemSubA)?.delegate).isEqualTo(typeADelegate) assertThat(multiType.itemAt(typeTestItemSubB)?.delegate).isEqualTo(typeBDelegate) } private fun <T : Any> MultiType<T>.assertRegistered(delegate: ViewTypeDelegate<*, *>) { assertThat(keyAt(delegate.viewType)?.delegate).isEqualTo(delegate) } private inline fun <T : Any> MutableMultiTypeImpl<T>.init( block: MutableMultiType<T>.() -> Unit ) = apply { block() complete() } private interface TestInterface private annotation class TestAnnotation }
0
Kotlin
0
9
83ca90dc5c8ac6892c1cdfdb026b8afb187e48fd
5,109
CXRV
Apache License 2.0
src/main/kotlin/com/lykke/matching/engine/services/MultiLimitOrderService.kt
Ecoblockchain
83,384,454
true
{"Kotlin": 357467, "Java": 39764, "Protocol Buffer": 3149}
package com.lykke.matching.engine.services import com.lykke.matching.engine.daos.LimitOrder import com.lykke.matching.engine.daos.TradeInfo import com.lykke.matching.engine.logging.MetricsLogger import com.lykke.matching.engine.messages.MessageWrapper import com.lykke.matching.engine.messages.ProtocolMessages import com.lykke.matching.engine.order.OrderStatus import com.lykke.matching.engine.outgoing.messages.JsonSerializable import com.lykke.matching.engine.outgoing.messages.OrderBook import com.lykke.matching.engine.utils.RoundingUtils import org.apache.log4j.Logger import java.util.ArrayList import java.util.Date import java.util.UUID import java.util.concurrent.BlockingQueue class MultiLimitOrderService(val limitOrderService: GenericLimitOrderService, val orderBookQueue: BlockingQueue<OrderBook>, val rabbitOrderBookQueue: BlockingQueue<JsonSerializable>): AbsractService<ProtocolMessages.MultiLimitOrder> { companion object { val LOGGER = Logger.getLogger(MultiLimitOrderService::class.java.name) val METRICS_LOGGER = MetricsLogger.getLogger() } private var messagesCount: Long = 0 private var logCount = 1000 private var totalPersistTime: Double = 0.0 private var totalTime: Double = 0.0 override fun processMessage(messageWrapper: MessageWrapper) { val startTime = System.nanoTime() val message = parse(messageWrapper.byteArray) LOGGER.debug("Got multi limit order id: ${message.uid}, client ${message.clientId}, assetPair: ${message.assetPairId}") val orders = ArrayList<LimitOrder>(message.ordersList.size) val now = Date() var cancelBuySide = false var cancelSellSide = false message.ordersList.forEach { currentOrder -> val uid = UUID.randomUUID().toString() orders.add(LimitOrder(uid, uid, message.assetPairId, message.clientId, currentOrder.volume, currentOrder.price, OrderStatus.InOrderBook.name, Date(message.timestamp), now, currentOrder.volume, null)) if (message.cancelAllPreviousLimitOrders) { if (currentOrder.volume > 0) { cancelBuySide = true } else { cancelSellSide = true } } } val ordersToCancel = ArrayList<LimitOrder>() if (message.cancelAllPreviousLimitOrders) { if (cancelBuySide) { ordersToCancel.addAll(limitOrderService.getAllPreviousOrders(message.clientId, message.assetPairId, true)) } if (cancelSellSide) { ordersToCancel.addAll(limitOrderService.getAllPreviousOrders(message.clientId, message.assetPairId, false)) } } val orderBook = limitOrderService.getOrderBook(message.assetPairId).copy() ordersToCancel.forEach { order -> orderBook.removeOrder(order) } var buySide = false var sellSide = false orders.forEach { order -> orderBook.addOrder(order) limitOrderService.addOrder(order) limitOrderService.putTradeInfo(TradeInfo(order.assetPairId, order.isBuySide(), order.price, now)) if (order.isBuySide()) buySide = true else sellSide = true } limitOrderService.setOrderBook(message.assetPairId, orderBook) val startPersistTime = System.nanoTime() limitOrderService.cancelLimitOrders(ordersToCancel) limitOrderService.addOrders(orders) val endPersistTime = System.nanoTime() val orderBookCopy = orderBook.copy() if (buySide) { val newOrderBook = OrderBook(message.assetPairId, true, now, orderBookCopy.getOrderBook(true)) orderBookQueue.put(newOrderBook) rabbitOrderBookQueue.put(newOrderBook) } if (sellSide) { val newOrderBook = OrderBook(message.assetPairId, false, now, orderBookCopy.getOrderBook(false)) orderBookQueue.put(newOrderBook) rabbitOrderBookQueue.put(newOrderBook) } messageWrapper.writeResponse(ProtocolMessages.Response.newBuilder().setUid(message.uid).build()) val endTime = System.nanoTime() messagesCount++ totalPersistTime += (endPersistTime - startPersistTime).toDouble() / logCount totalTime += (endTime - startTime).toDouble() / logCount if (messagesCount % logCount == 0L) { LOGGER.info("Total time: ${convertToString(totalTime)}. " + " Persist time: ${convertToString(totalPersistTime)}, ${RoundingUtils.roundForPrint2(100*totalPersistTime/totalTime)} %") totalPersistTime = 0.0 totalTime = 0.0 } } private fun parse(array: ByteArray): ProtocolMessages.MultiLimitOrder { return ProtocolMessages.MultiLimitOrder.parseFrom(array) } private fun convertToString(value: Double): String { if ((value / 100000).toInt() == 0) { //microseconds return "${RoundingUtils.roundForPrint(value / 1000)} micros ($value nanos)" } else { //milliseconds return "${RoundingUtils.roundForPrint(value / 1000000)} millis ($value nanos)" } } }
0
Kotlin
0
0
064d092cc845e0c35ded5b750dd928aa0e86f644
5,336
MatchingEngine
MIT License
Commuzy-Frontend/app/src/main/java/com/example/commuzy/SignInActivity.kt
Sun-zhenghao-BU
717,859,913
false
{"Kotlin": 105289}
package com.example.commuzy import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.WindowManager import android.widget.Button import com.example.commuzy.databinding.ActivitySignInBinding import android.widget.Toast import androidx.core.content.ContextCompat import com.example.commuzy.datamodel.UserInfo import com.example.commuzy.models.User import com.example.commuzy.ui.Auth.SignInFragment import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class SignInActivity : UserAuthBaseActivity () { private lateinit var binding: ActivitySignInBinding private lateinit var database: DatabaseReference private lateinit var auth: FirebaseAuth private lateinit var buttonSignIn: Button private lateinit var buttonSignUp: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) with(window) { addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) statusBarColor = ContextCompat.getColor(this@SignInActivity, R.color.black) navigationBarColor = ContextCompat.getColor(this@SignInActivity, R.color.black) } binding = ActivitySignInBinding.inflate(layoutInflater) setContentView(binding.root) database = FirebaseDatabase.getInstance().reference auth = FirebaseAuth.getInstance() buttonSignIn=findViewById(R.id.buttonSignIn) buttonSignUp=findViewById(R.id.buttonSignUp) setProgressBar(R.id.progressBar) // 根据你的进度条ID调整 // 点击监听器 with(binding) { buttonSignIn.setOnClickListener { signIn() } buttonSignUp.setOnClickListener { signUp() } } } override fun onStart() { super.onStart() // Check auth on Activity start auth.currentUser?.let { onAuthSuccess(it) } } private fun signIn() { Log.d(SignInFragment.TAG, "signIn") if (!validateForm()) { return } showProgressBar() val email = binding.fieldEmail.text.toString() val password = binding.fieldPassword.text.toString() auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> Log.d(SignInFragment.TAG, "signIn:onComplete:" + task.isSuccessful) hideProgressBar() if (task.isSuccessful) { onAuthSuccess(task.result?.user!!) } else { Toast.makeText( this, "Sign In Failed", Toast.LENGTH_SHORT, ).show() } } } private fun signUp() { Log.d(SignInFragment.TAG, "signUp") if (!validateForm()) { return } showProgressBar() val email = binding.fieldEmail.text.toString() val password = binding.fieldPassword.text.toString() auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> Log.d(SignInFragment.TAG, "createUser:onComplete:" + task.isSuccessful) hideProgressBar() if (task.isSuccessful) { onAuthSuccess(task.result?.user!!) } else { Toast.makeText( this, "Sign Up Failed", Toast.LENGTH_SHORT, ).show() } } } private fun onAuthSuccess(user: FirebaseUser) { val username = usernameFromEmail(user.email!!) // Write new user val newUser = UserInfo(id = user.uid, name = username, email = user.email!!) val appDatabase = (application as MainApplication).database CoroutineScope(Dispatchers.IO).launch { appDatabase.databaseDao().insertUser(newUser) } writeNewUser(user.uid, username, user.email) // Go to MainActivity val intent = Intent(this, MainActivity::class.java) startActivity(intent) } private fun usernameFromEmail(email: String): String { return if (email.contains("@")) { email.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] } else { email } } private fun validateForm(): Boolean { var result = true if (TextUtils.isEmpty(binding.fieldEmail.text.toString())) { binding.fieldEmail.error = "Required" result = false } else { binding.fieldEmail.error = null } if (TextUtils.isEmpty(binding.fieldPassword.text.toString())) { binding.fieldPassword.error = "Required" result = false } else { binding.fieldPassword.error = null } return result } private fun writeNewUser(userId: String, name: String, email: String?) { val user = User(name, email) database.child("users").child(userId).setValue(user) } }
1
Kotlin
0
0
6f899e66ce4061cac4962971957ba8b49ae683bc
5,431
ComMuzy
MIT License
app/src/main/java/com/anesabml/producthunt/ui/postDetails/adapter/ProductLinkImageItemViewHolder.kt
anesabml
259,275,022
false
{"Kotlin": 96195}
package com.anesabml.producthunt.ui.postDetails.adapter import androidx.recyclerview.widget.RecyclerView import coil.api.load import com.anesabml.lib.extension.hide import com.anesabml.producthunt.databinding.ItemProductLinkImageBinding import com.anesabml.producthunt.model.Media class ProductLinkImageItemViewHolder(private val binding: ItemProductLinkImageBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(media: Media) { binding.imageView.load(media.url) { crossfade(true) listener { _, _ -> binding.progressBar.hide() } } } }
0
Kotlin
2
11
36c26c92b4114c357f507c547062b782f52758e3
624
hunt
MIT License
common/src/main/kotlin/org/valkyrienskies/tournament/blocks/RedstoneConnectingBlock.kt
alex-s168
648,266,124
false
{"Kotlin": 311448, "Java": 42190}
package org.valkyrienskies.tournament.blocks import net.minecraft.core.Direction import net.minecraft.world.level.block.state.BlockState interface RedstoneConnectingBlock { fun canConnectTo(state: BlockState, direction: Direction): Boolean }
4
Kotlin
10
8
48f2da03fab0f937805231929b7c145c69b1dab1
247
VS_tournament_continued
Apache License 2.0
example/in-memory/eda/test/specification/src/test/kotlin/org/sollecitom/chassis/core/example/inmemory/eda/test/specification/InMemoryEventDrivenArchitectureTests.kt
sollecitom
669,483,842
false
{"Kotlin": 842185, "Java": 30834}
package org.sollecitom.chassis.core.example.inmemory.eda.test.specification import assertk.assertThat import assertk.assertions.isEqualTo import kotlinx.coroutines.CoroutineStart.UNDISPATCHED import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import kotlinx.datetime.Instant import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS import org.sollecitom.chassis.core.domain.identity.Id import org.sollecitom.chassis.core.domain.lifecycle.stopBlocking import org.sollecitom.chassis.core.domain.naming.Name import org.sollecitom.chassis.core.example.inmemory.eda.domain.InboundMessage import org.sollecitom.chassis.core.test.utils.random import org.sollecitom.chassis.core.test.utils.testProvider import org.sollecitom.chassis.core.utils.CoreDataGenerator import org.sollecitom.chassis.core.utils.RandomGenerator import org.sollecitom.chassis.core.utils.TimeGenerator import org.sollecitom.chassis.kotlin.extensions.text.string import org.sollecitom.chassis.messaging.domain.* import org.sollecitom.chassis.messaging.test.utils.create import org.sollecitom.chassis.messaging.test.utils.matches import java.util.concurrent.ConcurrentHashMap import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @TestInstance(PER_CLASS) private class InMemoryEventDrivenArchitectureTests : CoreDataGenerator by CoreDataGenerator.testProvider { private val timeout = 10.seconds private val framework: EventPropagationFramework = InMemoryEventPropagationFramework(timeGenerator = this, options = InMemoryEventPropagationFramework.Options(consumerPollingDelay = 50.milliseconds)) @Test fun `consuming an already produced message`() = runTest(timeout = timeout) { val topic = newTopic() val userId = newId.ulid.monotonic() val command = SubscribeUser(userId) val event = CommandWasReceivedEvent(command) val outboundMessage = outboundMessage(event) val producer = newProducer<CommandWasReceivedEvent>() val consumer = newConsumer<CommandWasReceivedEvent>(topics = setOf(topic)) val producedMessageId = producer.produce(outboundMessage, topic) val receivedMessage = consumer.receive() assertThat(receivedMessage.id).isEqualTo(producedMessageId) assertThat(receivedMessage.topic).isEqualTo(topic) assertThat(receivedMessage.producerName).isEqualTo(producer.name) assertThat(receivedMessage).matches(outboundMessage) } @Test fun `awaiting for a message to be produced`() = runTest(timeout = timeout) { val topic = newTopic() val userId = newId.ulid.monotonic() val command = SubscribeUser(userId) val event = CommandWasReceivedEvent(command) val outboundMessage = outboundMessage(event) val producer = newProducer<CommandWasReceivedEvent>() val consumer = newConsumer<CommandWasReceivedEvent>(topics = setOf(topic)) val consumingMessage = async(start = UNDISPATCHED) { consumer.receive() } val producedMessageId = producer.produce(outboundMessage, topic) val receivedMessage = consumingMessage.await() assertThat(receivedMessage.id).isEqualTo(producedMessageId) assertThat(receivedMessage.topic).isEqualTo(topic) assertThat(receivedMessage.producerName).isEqualTo(producer.name) assertThat(receivedMessage).matches(outboundMessage) } private suspend fun newTopic(persistent: Boolean = true, tenant: Name = Name.random(), namespaceName: Name = Name.random(), namespace: Topic.Namespace? = Topic.Namespace(tenant = tenant, name = namespaceName), name: Name = Name.random()): Topic = Topic.create(persistent, tenant, namespaceName, namespace, name).also { framework.createTopic(it) } private fun <VALUE> newProducer(name: Name = Name.random()): MessageProducer<VALUE> = framework.newProducer(name) private fun <VALUE> newConsumer(topics: Set<Topic>, name: Name = Name.random(), subscriptionName: Name = Name.random()): MessageConsumer<VALUE> = framework.newConsumer(topics, name, subscriptionName) } interface EventPropagationFramework { fun <VALUE> newProducer(name: Name): MessageProducer<VALUE> fun <VALUE> newConsumer(topics: Set<Topic>, name: Name, subscriptionName: Name): MessageConsumer<VALUE> suspend fun createTopic(topic: Topic) } class InMemoryEventPropagationFramework(private val timeGenerator: TimeGenerator, private val options: Options) : EventPropagationFramework, TimeGenerator by timeGenerator { private val messageStorage = MessageStorage() private val offsets = mutableMapOf<Name, PartitionOffset>() override fun <VALUE> newProducer(name: Name): MessageProducer<VALUE> = InnerProducer(name) override fun <VALUE> newConsumer(topics: Set<Topic>, name: Name, subscriptionName: Name): MessageConsumer<VALUE> = InnerConsumer(topics.single(), name, subscriptionName, options.consumerPollingDelay) // TODO remove the single after making it work with multiple override suspend fun createTopic(topic: Topic) { } private fun Topic.partitionForMessage(message: Message<*>): Topic.Partition { return Topic.Partition(index = 1) } private suspend fun <VALUE> Topic.send(message: Message<VALUE>, producerName: Name): Message.Id = synchronized(this) { val partition = partitionFor(message) messageStorage.topicPartition<VALUE>(this, partition).append { offset -> val messageId = MessageId(offset = offset, topic = this, partition = partition) val publishedAt = clock.now() message.inbound(messageId, publishedAt, producerName) { } } } private fun <VALUE> Message<VALUE>.inbound(id: MessageId, publishedAt: Instant, producerName: Name, acknowledge: suspend (ReceivedMessage<VALUE>) -> Unit): InboundMessage<VALUE> = InboundMessage(id, key, value, properties, publishedAt, producerName, context, acknowledge) private fun partitionFor(message: Message<*>): Topic.Partition { return Topic.Partition(index = 1) // TODO change } private suspend fun <VALUE> nextMessage(topic: Topic, consumerName: Name, subscriptionName: Name, pollingDelay: Duration): ReceivedMessage<VALUE> { val partition = partitionFor(topic, consumerName, subscriptionName) val offset = partitionOffset(subscriptionName).getAndIncrement(topic, partition) val partitionStorage = messageStorage.topicPartition<VALUE>(topic, partition) // TODO use a set here return partitionStorage.messageAtOffset(offset, pollingDelay) } private fun partitionOffset(subscriptionName: Name) = offsets.computeIfAbsent(subscriptionName) { PartitionOffset() } private class PartitionOffset { private val offsetByPartition: MutableMap<TopicPartition, Long> = ConcurrentHashMap() fun getAndIncrement(topic: Topic, partition: Topic.Partition): Long { val next = offsetByPartition.compute(TopicPartition(topic, partition)) { _, currentOrNull -> val current = currentOrNull ?: 0L current + 1 }!! return next - 1 } } private fun partitionFor(topic: Topic, consumerName: Name, subscriptionName: Name): Topic.Partition { // TODO make this a set return Topic.Partition(index = 1) // TODO change } private class MessageStorage { private val partitions = ConcurrentHashMap<TopicPartition, TopicPartitionStorage<*>>() fun <VALUE> topicPartition(topic: Topic, partition: Topic.Partition): TopicPartitionStorage<VALUE> { return partitions.computeIfAbsent(TopicPartition(topic, partition)) { TopicPartitionStorage<VALUE>(topic, partition) } as TopicPartitionStorage<VALUE> } } private data class TopicPartition(val topic: Topic, val partition: Topic.Partition) private class TopicPartitionStorage<VALUE>(private val topic: Topic, private val partition: Topic.Partition) { private val storage = mutableListOf<ReceivedMessage<VALUE>>() fun append(messageForOffset: (offset: Long) -> ReceivedMessage<VALUE>): MessageId = synchronized(this) { val offset = storage.size.toLong() storage.add(messageForOffset(offset)) MessageId(offset, topic, partition) } suspend fun messageAtOffset(offset: Long, pollingDelay: Duration): ReceivedMessage<VALUE> = coroutineScope { if (storage.size > offset.toInt()) return@coroutineScope storage[offset.toInt()] async(start = UNDISPATCHED) { while (storage.size <= offset.toInt()) { delay(pollingDelay) } storage[offset.toInt()] }.await() } } private inner class InnerProducer<VALUE>(override val name: Name) : MessageProducer<VALUE> { override suspend fun produce(message: Message<VALUE>, topic: Topic) = topic.send(message = message, producerName = name) override suspend fun stop() { } override fun close() = stopBlocking() } private inner class InnerConsumer<VALUE>(private val topic: Topic, override val name: Name, override val subscriptionName: Name, private val pollingDelay: Duration) : MessageConsumer<VALUE> { override val topics: Set<Topic> = setOf(topic) // TODO change after making it work with multiple topics override suspend fun receive(): ReceivedMessage<VALUE> { return nextMessage(topic, name, subscriptionName, pollingDelay) } override suspend fun stop() { } override fun close() = stopBlocking() } data class Options(val consumerPollingDelay: Duration) } data class MessageId(val offset: Long, override val topic: Topic, override val partition: Topic.Partition?) : Message.Id { override fun compareTo(other: Message.Id): Int { check(topic == other.topic) { "Cannot compare message IDs on different topics" } if (partition != null) { check(partition == other.partition) { "Cannot compare message IDs on different partitions" } } other as MessageId return offset.compareTo(other.offset) } } context(RandomGenerator) private fun <VALUE> outboundMessage(value: VALUE, key: String = random.string(wordLength = 10), properties: Map<String, String> = emptyMap(), context: Message.Context = Message.Context()): Message<VALUE> = OutboundMessage(key, value, properties, context) data class CommandWasReceivedEvent(val command: Command) // TODO add more to this sealed interface Command data class SubscribeUser(val userId: Id) : Command data class UnsubscribeUser(val userId: Id) : Command
0
Kotlin
0
2
4b008030b4035ec5975aa4dd092e5c95c9462f3f
10,913
chassis
MIT License
webshareinfo/src/main/java/com/kevin/webshareinfo/WebShareInfo.kt
xuehuayous
320,485,074
false
null
package com.kevin.webshareinfo import android.webkit.WebView import org.json.JSONException import org.json.JSONObject /** * WebShareInfo * * @author <EMAIL>, Created on 2020-12-11 14:27:30 * Major Function:<b>WebShareInfo</b> * <p/> * Note: If you modify this class please fill in the following content as a record. * @author mender,Modified Date Modify Content: */ /** * Get the share info from webView * * @param callback the callback function */ fun WebView.getShareInfo(callback: (shareInfo: WebShareInfo) -> Unit) { evaluateJavascript( """ (function () { var params = {}; var metas = document.getElementsByTagName('meta'); for (var i = 0; i < metas.length; i++) { if (metas[i].getAttribute("property") == "og:title") { params.title = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "og:url") { params.url = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "og:description") { params.description = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "og:image") { params.image = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "og:site_name") { params.site_name = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "og:type") { params.type = metas[i].getAttribute("content"); } } return params; })() """.trimIndent() ) { params -> val shareInfo = WebShareInfo() try { val ogJsonObject = JSONObject(params) if (!ogJsonObject.isNull("title")) { shareInfo.title = ogJsonObject.getString("title") } if (!ogJsonObject.isNull("url")) { shareInfo.url = ogJsonObject.getString("url") } if (!ogJsonObject.isNull("image")) { shareInfo.image = ogJsonObject.getString("image") } if (!ogJsonObject.isNull("description")) { shareInfo.description = ogJsonObject.getString("description") } if (!ogJsonObject.isNull("site_name")) { shareInfo.siteName = ogJsonObject.getString("site_name") } if (!ogJsonObject.isNull("type")) { shareInfo.type = ogJsonObject.getString("type") } } catch (e: JSONException) { e.printStackTrace() } callback(shareInfo) } } class WebShareInfo { /** * The title of your object as it should appear within the graph, e.g., "The Rock". */ var title: String? = null /** * The canonical URL of your object that will be used as its permanent ID in the graph, e.g., "https://www.imdb.com/title/tt0117500/". */ var url: String? = null /** * An image URL which should represent your object within the graph. */ var image: String? = null /** * A one to two sentence description of your object. */ var description: String? = null /** * If your object is part of a larger web site, the name which should be displayed for the overall site. e.g., "IMDb". */ var siteName: String? = null /** * The type of your object, e.g., "video.movie". Depending on the type you specify, other properties may also be required. */ var type: String? = null }
0
Kotlin
0
2
cbd504e2aeffba99762aa67c595395524fe3e2f2
3,698
Android-WebShareInfo
Apache License 2.0
kotlinc-plugin/src/main/kotlin/org/jetbrains/research/ktglean/indexers/ClassDeclarationsIndexer.kt
e2e4b6b7
476,404,280
false
{"Kotlin": 85849, "ANTLR": 2903}
package org.jetbrains.research.ktglean.indexers import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.declarations.FirRegularClass import org.jetbrains.research.ktglean.factories.GleanClassFactory import org.jetbrains.research.ktglean.indexers.base.FirRegularClassIndexer import org.jetbrains.research.ktglean.storage.FactsStorage import org.koin.core.component.KoinComponent import org.koin.core.component.inject class ClassDeclarationsIndexer(private val storage: FactsStorage) : FirRegularClassIndexer(), KoinComponent { private val builder: GleanClassFactory by inject() override fun index(declaration: FirRegularClass, context: CheckerContext) { storage.addFact(builder.getClassDeclaration(declaration, context)) } }
0
Kotlin
0
4
84b9d903f16cf9300bf5d0c0930b37b7e480b0dd
796
KtGlean
Apache License 2.0
app/src/main/java/com/example/glidetest/DetailActivity.kt
dangkhai98nd
193,250,850
false
null
package com.example.glidetest import android.annotation.SuppressLint import android.app.Activity import android.app.ProgressDialog import android.graphics.Color import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.util.Log import android.view.View import android.view.WindowManager import android.widget.RelativeLayout import android.widget.TextView import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions.bitmapTransform import com.example.glidetest.Models.ApiImages import com.example.glidetest.Models.ApiVideos import com.example.glidetest.Models.Video import com.example.glidetest.adapter.BackdropAdapter import com.example.glidetest.adapter.VideoAdapter import com.example.glidetest.api.Client import com.example.glidetest.api.Service import com.example.glidetest.utils.RecyclerViewOnClickListener import com.example.retrofittest.Models.Movie import com.google.android.youtube.player.YouTubeInitializationResult import com.google.android.youtube.player.YouTubePlayer import com.google.android.youtube.player.YouTubePlayerFragment import jp.wasabeef.glide.transformations.BlurTransformation import kotlinx.android.synthetic.main.activity_detail.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response @Suppress("DEPRECATION") class DetailActivity : AppCompatActivity() { var adapter: BackdropAdapter? = null var adapter_videos: VideoAdapter? = null var recyclerViewVideos: androidx.recyclerview.widget.RecyclerView? = null var imagesBackdrop: List<ApiImages.Image> = listOf() var imagesPoster: List<ApiImages.Image> = listOf() var movieID: Int? = null var movie: Movie? = null var videos: List<Video>? = null var pd: ProgressDialog? = null var youTubeFragment: YouTubePlayerFragment? = null var youTubePlayerVideos: YouTubePlayer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) pd = ProgressDialog(this) pd?.setMessage("Load ...") pd?.setCancelable(false) pd?.show() movieID = intent?.extras?.getInt("movieID") adapter = BackdropAdapter(this@DetailActivity) recycle_view_backdrop?.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator() recycle_view_backdrop?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager( this@DetailActivity, androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL, false ) recycle_view_backdrop?.adapter = adapter loadJSONTrailer() transparentStatusBar() } private fun transparentStatusBar() { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false) window.statusBarColor = Color.TRANSPARENT // window.navigationBarColor = Color.TRANSPARENT } private fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) { val win = activity.window val winParams = win.attributes if (on) { winParams.flags = winParams.flags or bits } else { winParams.flags = winParams.flags and bits.inv() } win.attributes = winParams } private fun populateRecyclerViewVideos() { adapter_videos = VideoAdapter(this, videos) recyclerViewVideos?.adapter = adapter_videos recyclerViewVideos?.addOnItemTouchListener( RecyclerViewOnClickListener(this, object : RecyclerViewOnClickListener.OnItemClickListener { override fun onItemClick(view: View, position: Int) { if (youTubeFragment != null && youTubePlayerVideos != null) { adapter_videos?.setSelectedPosition(position) youTubePlayerVideos?.loadVideo(videos?.get(position)?.key) } } }) ) } private fun setUpRecyclerViewVideos() { recyclerViewVideos = recycle_view_video recyclerViewVideos?.setHasFixedSize(true) recyclerViewVideos?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager( this, androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL, false ) } private fun loadJSONImage() { try { val client: Client? = Client() val service: Service? = client!!.getClient()?.create(Service::class.java) val call: Call<ApiImages>? = service?.getApiImages(movieID ?: return) call?.run { enqueue(object : Callback<ApiImages> { override fun onFailure(call: Call<ApiImages>, t: Throwable) { Log.d("Error ", t.message) Toast.makeText( this@DetailActivity, "Error Fetching Data!", Toast.LENGTH_SHORT ).show() } override fun onResponse(call: Call<ApiImages>, response: Response<ApiImages>) { imagesBackdrop = response.body()?.backdrops ?: listOf() imagesPoster = response.body()?.posters ?: listOf() loadJSONDetail() adapter?.addAll(imagesBackdrop) if (imagesBackdrop.size != 0) { backdrop_txt.text = "Backdrop : " } else { backdrop_txt.visibility = TextView.GONE } } }) } } catch (e: Exception) { Log.d("Error ", e.message) Toast.makeText(this@DetailActivity, e.toString(), Toast.LENGTH_SHORT).show() } } private fun loadJSONDetail() { try { val client: Client? = Client() val service: Service? = client!!.getClient()?.create(Service::class.java) val call: Call<Movie>? = service?.getApiMovieDetail(movieID ?: return) call?.run { enqueue(object : Callback<Movie> { override fun onFailure(call: Call<Movie>, t: Throwable) { Log.d("Error ", t.message) Toast.makeText( this@DetailActivity, "Error Fetching Data!", Toast.LENGTH_SHORT ).show() } @SuppressLint("SetTextI18n") override fun onResponse(call: Call<Movie>, response: Response<Movie>) { movie = response.body() Glide.with(this@DetailActivity) .load(movie?.get_poster_path()) .thumbnail(Glide.with(this@DetailActivity).load(R.drawable.icon_load)) .fitCenter() .into(thumbnail_image_header) var image_background : String? = movie?.poster_path if (imagesPoster.size > 1) image_background = imagesPoster[1].get_image_path() if (image_background != null) { Glide.with(this@DetailActivity) .load(image_background) .apply(bitmapTransform(BlurTransformation(22))) .into(backgroud_image) } thumbnail_image_header.clipToOutline = true name.text = movie?.name userrating.text = "Rating : ${movie?.vote_average.toString()}" val runtime = movie?.runtime if (runtime != null) { time.text = "Time : ${runtime / 60}h${runtime % 60}" } else { time.visibility = TextView.GONE } releasedate.text = "Release date : ${movie?.release_date}" plotsynopsis.text = "Overview : ${movie?.overview}" pd?.dismiss() } }) } } catch (e: Exception) { Log.d("Error ", e.message) Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show() } } private fun loadJSONTrailer() { try { val client: Client? = Client() val service: Service? = client!!.getClient()?.create(Service::class.java) val call: Call<ApiVideos>? = service?.getApiMovieVideos(movieID ?: return) call?.run { enqueue(object : Callback<ApiVideos> { override fun onFailure(call: Call<ApiVideos>, t: Throwable) { Log.d("Error ", t.message) Toast.makeText( this@DetailActivity, "Error Fetching Data Trailer!", Toast.LENGTH_SHORT ).show() } override fun onResponse(call: Call<ApiVideos>, response: Response<ApiVideos>) { videos = response.body()?.results loadJSONImage() if (videos != null) { youTubeFragment = fragmentManager.findFragmentById(R.id.videoyoutube) as YouTubePlayerFragment youTubeFragment?.initialize(BuildConfig.API_KEY, object : YouTubePlayer.OnInitializedListener { override fun onInitializationSuccess( provider: YouTubePlayer.Provider, youTubePlayer: YouTubePlayer, b: Boolean ) { youTubePlayerVideos = youTubePlayer val vote_average: Float = (movie?.vote_average ?: 0.0F) youTubePlayerVideos?.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT) if (vote_average < 5) { youTubePlayerVideos?.cueVideo(videos?.get(0)?.key) } else { youTubePlayerVideos?.loadVideo(videos?.get(0)?.key) } setUpRecyclerViewVideos() populateRecyclerViewVideos() } override fun onInitializationFailure( provider: YouTubePlayer.Provider, youTubeInitializationResult: YouTubeInitializationResult ) { } }) } else { layout_video.visibility = RelativeLayout.GONE } } }) } } catch (e: Exception) { Log.d("Error ", e.message) Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
0
7ebbeab3ca4637f8178f979750861d2d7972f49f
12,119
MovieApp
Apache License 2.0
code/backend/Odin/src/main/kotlin/pt/isel/odin/http/controllers/department/models/UpdateDepartmentOutputModel.kt
Rafael4DC
767,594,795
false
{"Kotlin": 380088, "TypeScript": 256706, "C#": 13106, "PowerShell": 1924, "JavaScript": 1734, "HTML": 263}
package pt.isel.odin.http.controllers.department.models import pt.isel.odin.http.controllers.fieldstudy.models.GetFieldStudyOutputModel import pt.isel.odin.model.Department /** * Represents the output model for updating a department. * * @property id The department id. * @property name The department name. * @property fieldsStudy The department fields study. * * @constructor Creates a [UpdateDepartmentOutputModel] from a [Department]. */ data class UpdateDepartmentOutputModel( val id: Long, val name: String, val fieldsStudy: List<GetFieldStudyOutputModel> ) { constructor(department: Department) : this( id = department.id!!, name = department.name, fieldsStudy = department.fieldsStudy .map { GetFieldStudyOutputModel(it) } ) }
61
Kotlin
0
2
89098f83607781fa838773eae7cef1781cd85a07
801
AssemblyOdin
MIT License
app/src/main/java/com/example/dumb_charades/screens/title/TitleFragment.kt
Ranawatt
253,177,607
false
null
package com.example.dumb_charades.screens.title import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import com.example.dumb_charades.R import com.example.dumb_charades.databinding.TitleFragmentBinding class TitleFragment : Fragment() { companion object { fun newInstance() = TitleFragment() } private lateinit var viewModel: TitleViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding: TitleFragmentBinding = DataBindingUtil.inflate( inflater, R.layout.title_fragment, container, false) viewModel = ViewModelProviders.of(this).get(TitleViewModel::class.java) binding.playGameButton.setOnClickListener { findNavController().navigate(TitleFragmentDirections.actionTitleToGame()) } binding.movieButton.setOnClickListener { findNavController().navigate(TitleFragmentDirections.actionTitleDestinationToMovieFragment2()) } return binding.root } }
0
Kotlin
0
1
45edc3cd758f83d505b3784d6d653ce5542d6319
1,405
Dumb-Charades
The Unlicense
app/src/main/java/com/rerere/iwara4a/api/paging/LikeSource.kt
Sagar19RaoRane
400,201,403
true
{"Kotlin": 419813}
package com.rerere.iwara4a.api.paging import android.util.Log import androidx.paging.PagingSource import androidx.paging.PagingState import com.rerere.iwara4a.model.index.MediaPreview import com.rerere.iwara4a.model.session.SessionManager import com.rerere.iwara4a.repo.MediaRepo private const val TAG = "LikeSource" class LikeSource( private val mediaRepo: MediaRepo, private val sessionManager: SessionManager ) : PagingSource<Int, MediaPreview>() { override fun getRefreshKey(state: PagingState<Int, MediaPreview>): Int { return 0 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MediaPreview> { val page = params.key ?: 0 Log.i(TAG, "load: Trying to load like list: $page") val response = mediaRepo.getLikePage(sessionManager.session, page) return if(response.isSuccess()){ val data = response.read() Log.i(TAG, "load: Success load like list (datasize=${data.mediaList.size}, hasNext=${data.hasNext})") LoadResult.Page( data = data.mediaList, prevKey = if(page <= 0) null else page - 1, nextKey = if(data.hasNext) page + 1 else null ) } else { LoadResult.Error(Exception(response.errorMessage())) } } }
0
null
0
0
5409dba4a563ac2bfb930640fc4c898fa6a79484
1,322
iwara4a
Apache License 2.0
sessionize/lib/src/commonMain/kotlin/co/touchlab/sessionize/file/FileLoader.kt
archiegq21
373,171,044
true
{"Kotlin": 222919, "Swift": 80064, "HTML": 7463, "Python": 3852, "Ruby": 2327, "Objective-C": 537, "Shell": 36}
package co.touchlab.sessionize.file fun interface FileLoader { fun load(filePrefix: String, fileType: String): String? }
0
Kotlin
0
0
8c3ec05448d586037c924f245f77fcd0150f0476
125
DroidconKotlin
Apache License 2.0
src/main/kotlin/org/valkyrienskies/core/collision/CollisionResultTimeToCollision.kt
ValkyrienSkies
329,044,944
false
null
package org.valkyrienskies.core.collision import org.joml.Vector3d import org.joml.Vector3dc data class CollisionResultTimeToCollision internal constructor( internal var _initiallyColliding: Boolean, internal var _collisionAxis: Vector3d, internal var _timeToCollision: Double ) : CollisionResultTimeToCollisionc { override val initiallyColliding: Boolean get() = _initiallyColliding override val collisionAxis: Vector3dc get() { if (initiallyColliding) throw CollidingException("Cannot access collisionAxis because we are colliding!") if (_timeToCollision == Double.POSITIVE_INFINITY) throw NeverCollidingException( "Cannot access collisionAxis because we will never collide!" ) return _collisionAxis } override val timeToCollision: Double get() { if (initiallyColliding) throw CollidingException("Cannot access timeToCollision because we are colliding!") return _timeToCollision } companion object { internal fun createEmptyCollisionResultTimeToCollision(): CollisionResultTimeToCollision { return CollisionResultTimeToCollision(false, Vector3d(), Double.POSITIVE_INFINITY) } } }
2
Kotlin
0
1
a9623e844643f6fa3cb38cbaed6ef1f349aaa205
1,265
vs-core
Apache License 2.0
src/main/kotlin/me/fzzyhmstrs/imbued_deco/registry/RegisterEntity.kt
fzzyhmstrs
753,897,475
false
{"Kotlin": 63800, "Java": 4059}
package me.fzzyhmstrs.imbued_deco.registry import me.fzzyhmstrs.amethyst_imbuement.AI import me.fzzyhmstrs.fzzy_core.coding_util.FzzyPort import me.fzzyhmstrs.fzzy_core.entity_util.EntityBuilder import me.fzzyhmstrs.imbued_deco.entity.ImbuedHopperBlockEntity import me.fzzyhmstrs.imbued_deco.entity.PlaceablePotionBlockEntity import me.fzzyhmstrs.imbued_deco.entity.TinyCauldronBlockEntity import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityType object RegisterEntity: EntityBuilder() { fun <T: BlockEntity> BlockEntityType<T>.register(name: String): BlockEntityType<T> { return FzzyPort.BLOCK_ENTITY_TYPE.register(AI.identity(name), this) } val IMBUED_HOPPER_BLOCK_ENTITY = buildBlockEntity({ p, s -> ImbuedHopperBlockEntity(p, s) }, RegisterBlock.IMBUED_HOPPER).register("imbued_hopper_entity") val PLACEABLE_POTION_BLOCK_ENTITY = buildBlockEntity({ p, s -> PlaceablePotionBlockEntity(p, s) }, RegisterBlock.PLACEABLE_POTION).register("placeable_potion_entity") val TINY_CAULDRON_BLOCK_ENTITY = buildBlockEntity({ p, s -> TinyCauldronBlockEntity(p, s) }, RegisterBlock.TINY_CAULDRON).register("tiny_cauldron_entity") fun registerAll(){} }
0
Kotlin
0
0
23868d0ab09c78af9b1a8c6afd05b2934e1bf629
1,219
id
MIT License
app/src/test/java/com/openwallet/ui/activity/fragment/profile/faq/FaqViewModelTest.kt
hsbc
742,467,592
false
{"Kotlin": 502702, "Java": 40426}
package com.openwallet.ui.activity.fragment.profile.faq import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.openwallet.base.BaseViewModel import com.openwallet.ext.request import com.openwallet.network.ApiRepository import com.openwallet.network.ApiService import com.openwallet.network.exception.ExceptionEngineImpl import com.openwallet.network.state.ResultState import com.openwallet.network.state.paresResult import com.openwallet.ui.activity.fragment.logout.model.LogoutResponse import com.openwallet.ui.activity.fragment.profile.changepassword.model.ChangePasswordViewModel import com.openwallet.ui.activity.fragment.profile.faq.model.FaqData import com.openwallet.ui.activity.fragment.wallet.model.NetworkResponse import com.openwallet.ui.activity.rule.MainCoroutineRule import io.mockk.* import junit.framework.TestCase import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner import retrofit2.Retrofit @OptIn(ExperimentalCoroutinesApi::class) @RunWith(MockitoJUnitRunner::class) class FaqViewModelTest : TestCase() { @get:Rule var mainCoroutineRule = MainCoroutineRule() // 解决 viewModelScope.launch @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() private val testCoroutineDispatcher = mainCoroutineRule.testDispatcher val retrofit = mockk<Retrofit>() val ipfsRetrofit = mockk<Retrofit>() val apiService = mockk<ApiService>() val apiRepository = mockk<ApiRepository>() val viewModel = FaqViewModel(apiRepository) @Before public override fun setUp() { super.setUp() MockKAnnotations.init(this) } public override fun tearDown() {} @Test fun testGetFaqList() = runBlocking { viewModel.exceptionEngine = ExceptionEngineImpl() val faqData = FaqData("answer",1,"question","1",false) val dataList = mutableListOf(faqData) var response = NetworkResponse<MutableList<FaqData>>("message",true,dataList) val resultState = ResultState.onAppSuccess(response) var expectedResult = MutableLiveData<ResultState<NetworkResponse<MutableList<FaqData>>>>() expectedResult.value = resultState every { retrofit.create(ApiService::class.java) } returns apiService coEvery { apiRepository.getFaqList() } coAnswers { response } val actualResult = viewModel.getFaqList() //verify { viewModel.getFaqList() } assertEquals(expectedResult.value,actualResult.value) } }
0
Kotlin
0
1
b72ac403ce1e38139ab42548967e08e6db347ddd
2,707
OpenWallet-aOS
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/FishBones.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.FishBones: ImageVector get() { if (_fishBones != null) { return _fishBones!! } _fishBones = Builder(name = "FishBones", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(6.5f, 19.0f) curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) close() moveTo(24.0f, 7.0f) curveToRelative(0.0f, 1.178f, -0.78f, 2.0f, -1.898f, 2.0f) horizontalLineToRelative(-4.976f) lineToRelative(1.437f, 1.438f) lineToRelative(-1.414f, 1.414f) lineToRelative(-1.793f, -1.793f) lineToRelative(-1.269f, 1.269f) lineToRelative(2.543f, 2.543f) lineToRelative(-1.414f, 1.414f) lineToRelative(-2.543f, -2.543f) lineToRelative(-1.4f, 1.4f) lineToRelative(3.293f, 3.293f) lineToRelative(-1.414f, 1.414f) lineToRelative(-3.293f, -3.293f) lineToRelative(-1.061f, 1.061f) curveToRelative(1.156f, 1.375f, 1.997f, 3.022f, 2.408f, 4.826f) lineToRelative(0.186f, 0.814f) lineToRelative(-0.769f, 0.327f) curveToRelative(-2.27f, 0.966f, -5.328f, 1.416f, -9.622f, 1.416f) lineTo(0.0f, 24.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -4.294f, 0.45f, -7.352f, 1.415f, -9.622f) lineToRelative(0.327f, -0.769f) lineToRelative(0.815f, 0.186f) curveToRelative(1.804f, 0.411f, 3.451f, 1.251f, 4.826f, 2.407f) lineToRelative(1.062f, -1.062f) lineToRelative(-3.293f, -3.293f) lineToRelative(1.414f, -1.414f) lineToRelative(3.293f, 3.293f) lineToRelative(1.4f, -1.4f) lineToRelative(-2.543f, -2.543f) lineToRelative(1.414f, -1.414f) lineToRelative(2.543f, 2.543f) lineToRelative(1.269f, -1.269f) lineToRelative(-1.793f, -1.793f) lineToRelative(1.415f, -1.414f) lineToRelative(1.437f, 1.437f) lineTo(15.001f, 1.898f) curveToRelative(0.0f, -1.118f, 0.822f, -1.898f, 2.0f, -1.898f) curveToRelative(1.423f, 0.0f, 3.447f, 0.989f, 3.905f, 3.095f) curveToRelative(2.105f, 0.458f, 3.095f, 2.482f, 3.095f, 3.905f) close() moveTo(9.024f, 21.051f) curveToRelative(-0.938f, -2.862f, -3.213f, -5.137f, -6.076f, -6.075f) curveToRelative(-0.582f, 1.749f, -0.886f, 4.021f, -0.94f, 7.016f) curveToRelative(2.996f, -0.055f, 5.267f, -0.358f, 7.016f, -0.94f) close() moveTo(22.0f, 7.0f) curveToRelative(0.0f, -0.02f, -0.117f, -2.0f, -2.0f, -2.0f) horizontalLineToRelative(-1.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -1.858f, -1.931f, -1.997f, -1.998f, -2.0f) lineToRelative(-0.002f, 5.0f) horizontalLineToRelative(5.0f) close() } } .build() return _fishBones!! } private var _fishBones: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,487
icons
MIT License
app/src/main/java/io/korti/muffle/viewmodel/AddMufflePointActivityViewModel.kt
korti11
224,637,960
false
null
/* * Copyright 2020 Korti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.korti.muffle.viewmodel import android.graphics.Bitmap import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.gms.maps.model.Circle import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import io.korti.muffle.database.dao.MufflePointDao import io.korti.muffle.database.entity.MufflePoint import io.korti.muffle.location.LocationManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject import kotlin.math.atan class AddMufflePointActivityViewModel @Inject constructor( locationManager: LocationManager, private val mufflePointDao: MufflePointDao ) : ViewModel() { companion object { private val TAG = AddMufflePointActivityViewModel::class.java.simpleName } val mapCameraPosition = MutableLiveData(LatLng(0.0, 0.0)) val mapCircle = MutableLiveData<Circle>() val mapMarker = MutableLiveData<Marker>() val mapZoom = MutableLiveData<Float>(getZoomLevel(150)) init { viewModelScope.launch { val location = locationManager.getLastKnownLocation() mapCameraPosition.value = LatLng(location.latitude, location.longitude) } } fun updateCameraPosition(pos: LatLng) { mapCameraPosition.value = pos } fun updateRadius(radius: Int) { val newRadius = radius.toDouble() + 100 val zoomLevel = getZoomLevel(radius) Log.d(TAG, "Current Radius: ${mapCircle.value?.radius}, Current Zoom: ${mapZoom.value}") Log.d(TAG, "Radius: $newRadius, Zoom: $zoomLevel") mapCircle.value?.radius = newRadius mapZoom.value = zoomLevel } fun saveMufflePoint( name: String, image: Bitmap, ringtoneVolume: Int, mediaVolume: Int, notificationVolume: Int, alarmVolume: Int ) { viewModelScope.launch { withContext(Dispatchers.IO) { var latitude = 0.0 var longitude = 0.0 var radius = 0.0 withContext(Dispatchers.Main) { latitude = mapMarker.value!!.position.latitude longitude = mapMarker.value!!.position.longitude radius = mapCircle.value!!.radius } val base64Image = MufflePoint.bitmapToBase64(image) mufflePointDao.insertAll( MufflePoint( name = name, lat = latitude, lng = longitude, radius = radius, image = base64Image, ringtoneVolume = ringtoneVolume, mediaVolume = mediaVolume, notificationVolume = notificationVolume, alarmVolume = alarmVolume ) ) } } } private fun getZoomLevel(radius: Int): Float { return 15F - (2.201F * atan(radius / 400.0).toFloat()) } }
5
Kotlin
0
0
d97e3dc9ab8f275a1b3f036c47d3a779be631177
3,833
muffle
Apache License 2.0
app/src/main/java/com/implementing/cozyspace/domain/usecase/diary/GetAllDiaryEntryUseCase.kt
Brindha-m
673,871,291
false
{"Kotlin": 635264}
package com.implementing.cozyspace.domain.usecase.diary import com.implementing.cozyspace.domain.repository.diary.DiaryRepository import com.implementing.cozyspace.model.Diary import com.implementing.cozyspace.util.Order import com.implementing.cozyspace.util.OrderType import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class GetAllDiaryEntryUseCase @Inject constructor( private val diaryRepository: DiaryRepository ) { operator fun invoke(order: Order) : Flow<List<Diary>> { return diaryRepository.getAllEntries().map { entries -> when (order.orderType) { is OrderType.ASC -> { when (order) { is Order.Alphabetical -> entries.sortedBy { it.title } is Order.DateCreated -> entries.sortedBy { it.createdDate } is Order.DateModified -> entries.sortedBy { it.updatedDate } else -> entries.sortedBy { it.updatedDate } } } is OrderType.DESC -> { when (order) { is Order.Alphabetical -> entries.sortedByDescending { it.title } is Order.DateCreated -> entries.sortedByDescending { it.createdDate } is Order.DateModified -> entries.sortedByDescending { it.updatedDate } else -> entries.sortedByDescending { it.updatedDate } } } } } } }
0
Kotlin
0
2
2f6c1b06d5cc7b7957843b17d0cb6551cb6cf6fd
1,567
DoodSpace-Todos.Notes.Doodles
Apache License 2.0
shared/src/commonMain/kotlin/Screen.kt
mohamad-abuzaid
816,930,223
false
{"Kotlin": 153863, "JavaScript": 1271, "HTML": 643, "Swift": 576, "Shell": 228, "Ruby": 101}
import model.Recipe /** * Created by "<NAME>" on 25/05/2023. * Email: <EMAIL> */ sealed interface Screens { data object RecipesList : Screens data class RecipeDetails( val recipe: Recipe ) : Screens }
1
Kotlin
0
0
225772a8d2880ef812340b82248ea57bc50abf89
224
KMP-Recipes
Apache License 2.0
app/src/main/kotlin/com/akagiyui/drive/component/DatabaseLogAppender.kt
AkagiYui
647,653,830
false
{"Kotlin": 227183, "Java": 87795, "HTML": 812, "Dockerfile": 658}
package com.akagiyui.drive.component import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.AppenderBase import org.springframework.stereotype.Component /** * 日志数据库记录器 * * @author AkagiYui */ @Component class DatabaseLogAppender : AppenderBase<ILoggingEvent>() { override fun append(p0: ILoggingEvent) { // TODO 自定义log处理器,将log信息存储到数据库 } }
4
Kotlin
2
9
6ff345645dfa83944ca4d36c02f9fa7b2162697f
382
KenkoDrive
MIT License
Solutions/solution_twentyOne_kotlin.kt
akebu6
424,142,622
false
null
fun main() { val (s, sn) = readln().split(" ") val n = sn.toInt() println(s.drop(n) + s.take(n)) }
3
Kotlin
11
1
cbdfc945ab9a13a2fb5847e7118d5027c94fd5e9
112
Code-Practice
MIT License
character/ui-character-details/src/main/java/com/example/ui_character_details/ui/CharacterDetailsEvent.kt
shahzadansari
649,266,330
false
{"Kotlin": 48647}
package com.example.ui_character_details.ui sealed class CharacterDetailsEvent { data class GetCharacterFromCache(val id: Int) : CharacterDetailsEvent() object RemoveHeadFromQueue : CharacterDetailsEvent() }
0
Kotlin
3
43
cb6dd154e9c8bc5e8210465e587ef212df7b81b9
217
RickAndMorty
MIT License
backend/src/main/kotlin/men/brakh/bsuirstudent/domain/ParentAware.kt
N1ghtF1re
184,453,033
false
null
package men.brakh.bsuirstudent.domain; /** * Interface which have to implement child entities. * @param <T> Parent identifier's type. */ interface ParentAware<T>: BaseEntity<T> { val parentId: T }
0
Kotlin
0
9
a4cd806c4658eb2aa736aa40daf47b19d39df80f
205
Bsuir-Additional-Api
Apache License 2.0
src/main/kotlin/infrastructure/provider/ManagerProviderImpl.kt
SmartOperatingBlock
602,467,135
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package infrastructure.provider import infrastructure.database.DatabaseManager import infrastructure.digitaltwins.DigitalTwinManager /** * Provider that creates the different managers. */ class ManagerProviderImpl : ManagerProvider { private val digitalTwinManager = DigitalTwinManager() private val databaseManager = DatabaseManager() override val roomDigitalTwinManager = digitalTwinManager override val roomDatabaseManager = databaseManager override val medicalTechnologyDigitalTwinManager = digitalTwinManager override val medicalTechnologyDatabaseManager = databaseManager }
1
Kotlin
0
1
610ebd9dd89b48ba68a310c3bcddd58bb407fab5
815
building-management-microservice
MIT License
peekaboo-ui/src/androidMain/kotlin/com/preat/peekaboo/ui/gallery/repository/PeekabooGalleryRepositoryImpl.kt
onseok
721,608,337
false
{"Kotlin": 114387}
/* * Copyright 2024 onseok * * 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.preat.peekaboo.ui.gallery.repository import android.content.Context import app.cash.paging.PagingSource import com.preat.peekaboo.ui.gallery.datasource.PeekabooGalleryDataSource import com.preat.peekaboo.ui.gallery.model.PeekabooMediaImage import com.preat.peekaboo.ui.gallery.util.createCursor import com.preat.peekaboo.ui.gallery.util.fetchPagePicture internal class PeekabooGalleryRepositoryImpl(private val context: Context) : PeekabooGalleryRepository { override suspend fun getCount(): Int { val cursor = context.createCursor(Int.MAX_VALUE, 0) ?: return 0 val count = cursor.count cursor.close() return count } override suspend fun getByOffset(offset: Int): PeekabooMediaImage? { return context.fetchPagePicture(1, offset).firstOrNull() } override fun getPicturePagingSource(): PagingSource<Int, PeekabooMediaImage> { return PeekabooGalleryDataSource { limit, offset -> context.fetchPagePicture(limit, offset) } } }
5
Kotlin
12
99
961403aa03c2d0be1f8259debf87aaac699e62b2
1,600
peekaboo
Apache License 2.0
demo/src/main/java/com/dima6120/demo/shaders/ShaderManager.kt
dima6120
298,513,503
false
null
package com.dima6120.demo.shaders import android.content.Context import com.dima6120.oglHelper.Shader import com.dima6120.oglHelper.ShaderManagerBase import com.dima6120.oglHelper.enums.ShaderType class ShaderManager : ShaderManagerBase() { override fun loadShaders(context: Context) { loadShadersFromAssets(context, ShaderType.FRAGMENT, "shaders/fs") loadShadersFromAssets(context, ShaderType.VERTEX, "shaders/vs") for (shaderName in ShaderName.values()) { addShader( shaderName.name, shaderName.vs, shaderName.fs, shaderName.attributes, shaderName.uniforms ) } } fun getShader(shaderName: ShaderName) = getShader(shaderName.name) }
0
Kotlin
0
0
d997580dd751d6ba82a6ad5ffbb56a7099aa63ba
785
OGLHelper
Apache License 2.0
librender/src/main/java/com/xyq/librender/utils/TextureHelper.kt
sifutang
519,498,265
false
{"C": 3029226, "Shell": 440458, "Roff": 269462, "Kotlin": 187172, "Makefile": 136105, "C++": 123528, "Awk": 42864, "CMake": 29005, "M4": 19284, "Java": 13131, "DIGITAL Command Language": 10718, "Assembly": 8352, "Batchfile": 3562, "GLSL": 2822, "Module Management System": 2083, "Dockerfile": 988}
package com.xyq.librender.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.opengl.GLES30 import android.opengl.GLUtils import android.util.Log class TextureHelper { companion object { private const val TAG = "TextureHelper" private const val DEBUG = true fun loadTexture(context: Context, resId: Int): Int { val textureObjectIds = OpenGLTools.createTextureIds(1) if (textureObjectIds[0] == 0) { if (DEBUG) { Log.w(TAG, "loadTexture: Could not generate a new OpenGL texture object.") } return 0 } val options = BitmapFactory.Options() options.inScaled = false val bitmap = BitmapFactory.decodeResource(context.resources, resId, options) if (bitmap == null) { if (DEBUG) { Log.w(TAG, "loadTexture: Resource Id $resId could not be decoded") } OpenGLTools.deleteTextureIds(textureObjectIds) return 0 } GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureObjectIds[0]) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR_MIPMAP_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0) GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, GLES30.GL_NONE) bitmap.recycle() return textureObjectIds[0] } fun loadTexture(bitmap: Bitmap): Int { val textureObjectIds = OpenGLTools.createTextureIds(1) if (textureObjectIds[0] == 0) { if (DEBUG) { Log.w(TAG, "loadTexture: Could not generate a new OpenGL texture object.") } return -1 } GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureObjectIds[0]) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR_MIPMAP_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0) GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, GLES30.GL_NONE) return textureObjectIds[0] } } }
0
C
8
28
f21ce990df19745e691fba007046190888639d22
3,055
ffmpeg-demo
Apache License 2.0
src/main/kotlin/net/greemdev/mod/util/MixinUtil.kt
GreemDev
452,819,836
false
null
package net.greemdev.mod.util import java.util.* import java.util.concurrent.ThreadLocalRandom fun String.chopRest(str: String): String = if (contains(str)) substring(0, this.indexOf(str)) else this object MixinUtil { @JvmStatic fun isInRange(value: Int, lower: Int, upper: Int, inclusiveUpper: Boolean): Boolean { return value >= lower && (value < upper || (value <= upper && inclusiveUpper)) } @JvmStatic fun isInRange(value: Int, lower: Int, upper: Int): Boolean { return isInRange(value, lower, upper, false) } /** * Allows easy randomization: serves a `x in y` chance purpose, where x is [lowerBound] and y is [upperBound]. * Example: rng(1, 100) ("1 in 100 chance") will only return true if the internal randomizer returns the lower bound, * this example will return true once every one hundred times statistically speaking. * * both bounds are inclusive */ @JvmStatic fun rng(lowerBound: Number, upperBound: Number): Boolean { val lower = "$lowerBound".chopRest(".") //ignore decimal points and the digits after it val upper = "$upperBound".chopRest(".") return ThreadLocalRandom.current().nextLong(lower.toLong(), upper.toLong().inc()) == lowerBound } @JvmStatic val romanTreeMap = TreeMap<Int, String>().apply { put(1000, "M") put(900, "CM") put(500, "D") put(400, "CD") put(100, "C") put(90, "XC") put(50, "L") put(40, "XL") put(10, "X") put(9, "IX") put(5, "V") put(4, "IV") put(1, "I") } @JvmStatic fun romanFromArabic(number: Int): String? { if (number >= 4000) return "$number" if (number == 0) return "N" val l = romanTreeMap.floorKey(number) return if (number == l) { romanTreeMap[number] } else romanTreeMap[l] + romanFromArabic(number - l) } }
0
Kotlin
0
1
a03c67a20b53400df9f867af2731adba81751976
1,966
ModpackCore
MIT License
ByteBank - Heritage, Polimorfism and Interface/src/br/com/brenofarias/bytebank/model/SavingsAccount.kt
BrenoFariasdaSilva
435,834,837
false
null
package br.com.brenofarias.bytebank.model class SavingsAccount( owner: Client, number: Int ) : Account( owner = owner, number = number ) { override fun withdraw(value: Double): Boolean { if (this.balance >= value) { this.balance -= value return true } return false } }
0
Kotlin
0
0
5baf6b864de5b347d1efb763a513614a8580daf1
341
Kotlin
MIT License
core/src/main/kotlin/io/github/gunkim/game/application/service/BoardService.kt
gunkim
374,385,822
false
null
package io.github.gunkim.game.application.service import io.github.gunkim.game.application.usecase.board.MoveUseCase import io.github.gunkim.game.domain.Gamers import io.github.gunkim.game.domain.Rooms import io.github.gunkim.game.domain.Users import io.github.gunkim.game.domain.vo.MoveType import org.springframework.stereotype.Service import java.util.UUID @Service class BoardService( private val rooms: Rooms, private val users: Users, private val gamers: Gamers, ) : MoveUseCase { override fun move(roomId: UUID, userId: UUID, type: MoveType) { val room = rooms.find(roomId) val user = users.find(userId) val gamer = room.move(user, type).findGamer(user) gamers.save(gamer) } }
0
Kotlin
0
1
1846af9d73e136570ab96a367080a0964925d3ce
739
2048-online
MIT License
features/home/src/main/kotlin/com/redmadrobot/home/presentation/HomeViewModel.kt
RedMadRobot
329,271,152
false
null
package com.redmadrobot.home.presentation import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.redmadrobot.base_cards.toCardViewState import com.redmadrobot.core.extensions.safeLaunch import com.redmadrobot.core_navigation.navigation.Router import com.redmadrobot.core_navigation.navigation.screens.Screens import com.redmadrobot.core_network.ApolloApi import com.redmadrobot.core_network.CardsListQuery import com.redmadrobot.core_presentation.extensions.update import com.redmadrobot.core_presentation.model.Content import com.redmadrobot.core_presentation.model.Loading import com.redmadrobot.core_presentation.model.Stub import com.redmadrobot.home.presentation.state.HomeViewState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val api: ApolloApi, private val router: Router, private val savedStateHandle: SavedStateHandle ) : ViewModel() { companion object { private const val SCROLL_TO_LAST_POSITION_KEY = "SCROLL_TO_LAST_POSITION_KEY" } private val _viewState = MutableStateFlow(HomeViewState(cards = Loading())) val viewState: StateFlow<HomeViewState> = _viewState // Fix negative arrangement: in initial state the list have a wrong position var scrollToLastPosition = savedStateHandle.get<Boolean>(SCROLL_TO_LAST_POSITION_KEY) ?: true private set init { loadCards() } fun onRetryClicked() = loadCards() fun onLastPositionScrolled() { savedStateHandle.set(SCROLL_TO_LAST_POSITION_KEY, false) scrollToLastPosition = false } private fun loadCards() { _viewState.update { copy(cards = Loading()) } viewModelScope.safeLaunch( { val cards = api.query(CardsListQuery()).cards _viewState.update { copy(cards = Content(cards.map(CardsListQuery.Card::toCardViewState))) } }, onError = { throwable -> _viewState.update { copy(cards = Stub(throwable)) } } ) } fun onCardClicked(id: String) { router.navigate(Screens.toDetails(id)) } }
0
Kotlin
1
9
12803311fa77b76ad1156f62bae1ebbf3c4cfd94
2,344
android-mad-showcase
MIT License
app/src/main/java/com/sundbybergsit/cromfortune/ui/home/OpinionatedStockOrderWrapperListAdapter.kt
Sundbybergs-IT
2,808,467
false
null
package com.sundbybergsit.cromfortune.ui.home import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.os.ConfigurationCompat import androidx.fragment.app.FragmentManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.sundbybergsit.cromfortune.R import com.sundbybergsit.cromfortune.currencies.CurrencyRateRepository import com.sundbybergsit.cromfortune.ui.AdapterItem import com.sundbybergsit.cromfortune.ui.AdapterItemDiffUtil import com.sundbybergsit.cromfortune.ui.home.view.DeleteStockOrderDialogFragment import com.sundbybergsit.cromfortune.ui.home.view.HomePersonalStocksFragment import com.sundbybergsit.cromfortune.ui.home.view.OpinionatedStockOrderWrapperAdapterItem import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* class OpinionatedStockOrderWrapperListAdapter( private val context: Context, private val fragmentManager: FragmentManager, private val readOnly: Boolean, ) : ListAdapter<AdapterItem, RecyclerView.ViewHolder>(AdapterItemDiffUtil<AdapterItem>()) { override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = getItem(position) when (holder) { is StockViewHolder -> { holder.bind(item as OpinionatedStockOrderWrapperAdapterItem) } } } override fun getItemViewType(position: Int): Int = when (val item = getItem(position)!!) { is HeaderAdapterItem -> { R.layout.listrow_stock_order_header } is OpinionatedStockOrderWrapperAdapterItem -> { R.layout.listrow_stock_order_item } else -> { throw IllegalArgumentException("Unexpected item: " + item.javaClass.canonicalName) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { R.layout.listrow_stock_order_header -> HeaderViewHolder(LayoutInflater.from(parent.context) .inflate(viewType, parent, false)) R.layout.listrow_stock_order_item -> StockViewHolder(context = context, adapter = this, fragmentManager = fragmentManager, itemView = LayoutInflater.from(parent.context) .inflate(viewType, parent, false), readOnly = readOnly) else -> throw IllegalArgumentException("Unexpected viewType: $viewType") } } internal class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) internal class StockViewHolder( private val context: Context, private val fragmentManager: FragmentManager, itemView: View, private val adapter: OpinionatedStockOrderWrapperListAdapter, private val readOnly : Boolean ) : RecyclerView.ViewHolder(itemView) { var formatter = SimpleDateFormat("yyyy-MM-dd", ConfigurationCompat.getLocales(context.resources.configuration).get(0)) fun bind(item: OpinionatedStockOrderWrapperAdapterItem) { itemView.requireViewById<TextView>(R.id.textView_listrowStockOrderItem_date).text = formatter.format(Date(item.opinionatedStockOrderWrapper.stockOrder.dateInMillis)) itemView.requireViewById<TextView>(R.id.textView_listrowStockOrderItem_quantity).text = item.opinionatedStockOrderWrapper.stockOrder.quantity.toString() if (!readOnly) { itemView.setOnLongClickListener { val dialog = DeleteStockOrderDialogFragment(context = context, adapter = adapter, stockOrder = item.opinionatedStockOrderWrapper.stockOrder) dialog.show(fragmentManager, HomePersonalStocksFragment.TAG) true } } val pricePerStock = item.opinionatedStockOrderWrapper.stockOrder.pricePerStock val format: NumberFormat = NumberFormat.getCurrencyInstance() if (pricePerStock < 1) { format.maximumFractionDigits = 3 } else { format.maximumFractionDigits = 2 } format.currency = Currency.getInstance(item.opinionatedStockOrderWrapper.stockOrder.currency) itemView.requireViewById<TextView>(R.id.textView_listrowStockOrderItem_price).text = format.format(pricePerStock) val rateInSek: Double = (CurrencyRateRepository.currencyRates.value as CurrencyRateRepository.ViewState.VALUES) .currencyRates.find { currencyRate -> currencyRate.iso4217CurrencySymbol == item.opinionatedStockOrderWrapper.stockOrder.currency }!!.rateInSek itemView.requireViewById<TextView>(R.id.textView_listrowStockOrderItem_total).text = format.format(item.opinionatedStockOrderWrapper.stockOrder.getTotalCost(rateInSek)) itemView.setBackgroundColor(getBuyOrSellColor(item.opinionatedStockOrderWrapper.stockOrder.orderAction)) itemView.requireViewById<TextView>(R.id.textView_listrowStockOrderItem_verdict).text = (if (item.opinionatedStockOrderWrapper.isApprovedByAlgorithm()) { "\uD83D\uDC4D" } else { "\uD83D\uDC4E" }) } @ColorInt private fun getBuyOrSellColor(orderAction: String): Int { return if (orderAction == "Buy") { ContextCompat.getColor(context, android.R.color.holo_green_light) } else { ContextCompat.getColor(context, android.R.color.holo_red_light) } } } }
18
Kotlin
0
0
e58b98d17c6c4f7d360f8274ad25c709c7505e1f
5,903
Crom-Fortune
The Unlicense
app/src/main/java/xyz/leomurca/sporteventtracker/ui/theme/Color.kt
leomurca
815,376,543
false
{"Kotlin": 46715}
package xyz.leomurca.sporteventtracker.ui.theme import androidx.compose.ui.graphics.Color val Orange = Color(0xFFFFab30) val FlameOrange = Color(0xFFE7410F) val ElectricBlue = Color(0xFF0094FF) val DarkGray = Color(0xFF343434) val Black = Color(0xFF000000) val White = Color(0xFFFFFFFF)
0
Kotlin
0
0
f0b1eafb2810b9c7f9595fd04562503a7b4ad6e5
289
sport-event-tracker
MIT License
app/src/main/java/com/jordantuffery/githubreader/viewcontroler/ReposActivity.kt
TufferyJordan
131,753,901
false
null
package com.jordantuffery.githubreader.viewcontroler import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.ArrayAdapter import com.jordantuffery.githubreader.GithubInterface import com.jordantuffery.githubreader.R import com.jordantuffery.githubreader.model.RepoDetails import kotlinx.android.synthetic.main.activity_repos.* class ReposActivity : AppCompatActivity(), ReposListener { private val github = GithubInterface() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_repos) github.requestRepos(intent.extras.getString(MainActivity.EXTRA_REPOS_URL), this) } override fun onReceiveReposList(reposArray: Array<RepoDetails>) { val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, reposArray.map { it.full_name }) repo_list_view.adapter = adapter } } interface ReposListener { fun onReceiveReposList(reposArray: Array<RepoDetails>) }
0
Kotlin
0
0
93ccbc7c11561fabd0dc5abdefa5c4ada092a381
1,041
github-app
Apache License 2.0
src/main/kotlin/me/w2x/rest/repository/UserRepository.kt
wancaibida
327,922,315
false
null
package me.w2x.rest.repository import me.w2x.rest.entity.User import org.springframework.data.repository.CrudRepository /** * Created by <NAME> on 1/20/21. */ interface UserRepository : CrudRepository<User, String> { fun findByUsername(username: String): User? }
0
Kotlin
0
0
ec70a7afad6db264da96ef8c8d6ae8f878381024
271
spring-rest-token
Apache License 2.0
lib/src/main/java/co/uk/androidsolution/lib/model/OnboardingModel.kt
bastami82
219,193,739
false
null
package co.uk.androidsolution.lib.model import androidx.annotation.Keep import org.parceler.Parcel import org.parceler.ParcelConstructor @Keep @Parcel(Parcel.Serialization.BEAN) data class OnboardingModel @ParcelConstructor constructor( val slides: List<SlideModel>, val portraitOnly: Boolean = true, val shouldHideSkip: Boolean = false )
0
Kotlin
0
5
04f5a957881e8e9ab44c5c4adb6fb524800cd79d
352
Easy-onBoarding
Apache License 2.0
app/src/main/java/com/example/filler/gui/shared/Utils.kt
oriolagobat
494,453,008
false
null
package com.example.filler.gui.shared import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.view.View import android.view.Window import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.preference.PreferenceManager import com.example.filler.R fun hideNavBar(activity: Activity) { val window: Window = activity.window val decorView: View = activity.window.decorView WindowCompat.setDecorFitsSystemWindows(window, false) val controllerCompat = WindowInsetsControllerCompat(window, decorView) controllerCompat.hide(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.navigationBars()) controllerCompat.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } fun closeKeyboardClearFocus( context: AppCompatActivity, editText: EditText ) { val focused: View? = context.currentFocus focused?.let { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(focused.windowToken, 0) } // Clear the EditText focus editText.clearFocus() } fun getValidMailOrError( context: AppCompatActivity, editText: EditText, ): String { closeKeyboardClearFocus(context, editText) val mail = editText.text.toString() val defaultMail = context.getString(R.string.results_default_mail) // Not the default mail, must check if (mail != defaultMail && !validMail(mail)) { editText.error = context.getString(R.string.results_mail_text_error) } return editText.text.toString() } // Checks if a mail is valid private fun validMail(mail: String): Boolean = android.util.Patterns.EMAIL_ADDRESS.matcher(mail).matches() // Returns the preferences manager fun getPreferences(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) // Returns true if the user wants music fun sound(context: Context): Boolean { val sharedPreferences = getPreferences(context) val musicKey = context.getString(R.string.pref_music_key) return sharedPreferences.getBoolean(musicKey, true) // Music on by default }
1
Kotlin
0
1
27f15dfa611d15b9a15888bf87a408b992c3ef04
2,476
Filler-Game-2
MIT License
app/src/main/java/com/breezelinktelecom/features/login/ShopFeedbackDao.kt
DebashisINT
851,532,207
false
{"Kotlin": 15739075, "Java": 1026627}
package com.breezelinktelecom.features.login import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.breezelinktelecom.app.AppConstant import com.breezelinktelecom.app.domain.ProductListEntity @Dao interface ShopFeedbackDao { @Insert fun insert(vararg obj: ShopFeedbackEntity) @Query("DELETE FROM " + AppConstant.TBL_SHOP_FEEDBACK) fun deleteAll() @Query("select * FROM " + AppConstant.TBL_SHOP_FEEDBACK +" where shop_id=:shop_id order by date_time desc") fun getAllByShopID(shop_id:String):List<ShopFeedbackEntity> @Query("select * FROM " + AppConstant.TBL_SHOP_FEEDBACK ) fun getAll():List<ShopFeedbackEntity> }
0
Kotlin
0
0
6b0e10f53cfab02f3790b9064bd705ee3dc87fef
687
LinkTelecom
Apache License 2.0
spring-framework-basic/src/main/kotlin/com/person/vincent/conditional/MacOSCondition.kt
lufei4
147,490,906
true
{"Kotlin": 64874, "HTML": 1458, "PLpgSQL": 1360}
package com.person.vincent.conditional import org.springframework.context.annotation.Condition import org.springframework.context.annotation.ConditionContext import org.springframework.core.type.AnnotatedTypeMetadata /** * Author: vincent * Date: 2018-01-22 11:34:00 * Comment: 重写 matches 方法来判定是否是 Mac OS 操作系统 */ class MacOSCondition : Condition { override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean { return context.environment.getProperty("os.name").contains("Mac OS") } }
0
Kotlin
0
0
1f544d82dfb81c9b87d4900c1601aa76b29a1b9e
536
spring-boot-with-kotlin-examples
Apache License 2.0
spring-framework-basic/src/main/kotlin/com/person/vincent/conditional/MacOSCondition.kt
lufei4
147,490,906
true
{"Kotlin": 64874, "HTML": 1458, "PLpgSQL": 1360}
package com.person.vincent.conditional import org.springframework.context.annotation.Condition import org.springframework.context.annotation.ConditionContext import org.springframework.core.type.AnnotatedTypeMetadata /** * Author: vincent * Date: 2018-01-22 11:34:00 * Comment: 重写 matches 方法来判定是否是 Mac OS 操作系统 */ class MacOSCondition : Condition { override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean { return context.environment.getProperty("os.name").contains("Mac OS") } }
0
Kotlin
0
0
1f544d82dfb81c9b87d4900c1601aa76b29a1b9e
536
spring-boot-with-kotlin-examples
Apache License 2.0
kucukBitmapOlustur.kt
ekremgunes
561,780,613
false
null
fun kucukBitmapOlustur(kullanicininBitmap : Bitmap , MaximumBoyut :Int): Bitmap? { var width = kullanicininBitmap.width var height = kullanicininBitmap.height val bitmapOran = width.toDouble() / height.toDouble() if(bitmapOran > 1 ){ //görsel yataydır width = MaximumBoyut; var kisaltilmisHeight = width / bitmapOran height = kisaltilmisHeight.toInt() }else{ height = MaximumBoyut; var kisaltilmisWidth = height * bitmapOran width = kisaltilmisWidth.toInt() } return Bitmap.createScaledBitmap(kullanicininBitmap,width,height,true) }
0
Kotlin
0
2
3d6ed5d119bd7f57655c52c9b8d37b7fa6f294f0
686
Kotlin-Basics
MIT License
clck/app/src/main/java/com/example/primaryengine/framework/AudioK.kt
MaximRybinsky
351,463,250
false
null
package com.example.primaryengine.framework interface AudioK { fun newMusic(filename : String) : MusicK fun newSound(filename: String) : SoundK }
0
Kotlin
0
0
3001a77afd2bf0a45423465f8d1f9a1f3c9081f7
155
AppleClicker
MIT License
src/main/kotlin/kotlinmud/event/impl/PlayerLoggedInEvent.kt
brandonlamb
275,313,206
true
{"Kotlin": 435931, "Dockerfile": 133, "Shell": 126}
package kotlinmud.event.impl import kotlinmud.io.model.Client import kotlinmud.player.model.MobCard class PlayerLoggedInEvent(val client: Client, val mobCard: MobCard)
0
null
0
0
fc03c6230b9b3b66cd63994e74ddd7897732d527
170
kotlinmud
MIT License
ui/src/commonMain/kotlin/ru/mironov/logistics/ui/screens/parceldata/ParcelDataViewModel.kt
mironoff2007
655,211,419
false
{"Kotlin": 210350, "Ruby": 1788, "Swift": 708, "Shell": 228}
package ru.mironov.logistics.ui.screens.parceldata import com.mironov.database.parcel.ParcelsDbSource import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import me.tatarka.inject.annotations.Inject import ru.mironov.common.Logger import ru.mironov.domain.model.Parcel import ru.mironov.domain.viewmodel.ViewModel import ru.mironov.logistics.ui.SingleEventFlow @Inject class ParcelDataViewModel( private val parcelsDbSource: ParcelsDbSource, val logger: Logger ) : ViewModel() { val result = SingleEventFlow<Boolean>() private val _loading = MutableStateFlow(false) val loading: StateFlow<Boolean> get() { return _loading.asStateFlow() } private val _parcel = MutableStateFlow<Parcel?>(null) val parcel: StateFlow<Parcel?> get() { return _parcel.asStateFlow() } fun onScreenOpened(args: String?) { viewModelScope.launch { try { logger.logD(LOG_TAG, "Parcel data screen is opened") getParcel(args!!) } catch (e: Exception) { logger.logE(LOG_TAG, e.stackTraceToString()) } } } private suspend fun getParcel(args: String) { val parcelData = Json.decodeFromString<ParcelDataArg>(args) val parcel = parcelData.parcel _parcel.emit(parcel) } companion object { private const val LOG_TAG = "ParcelDataVM" } }
0
Kotlin
0
0
5755168e0eb42a1fdc03fea493f57d578b5ee08d
1,617
logistics_kmm
Apache License 2.0
features/directory/src/main/kotlin/app/dapk/st/directory/DirectoryViewModel.kt
ShadowJonathan
471,471,233
true
{"Kotlin": 586327, "Java": 13756, "Shell": 763, "Prolog": 113}
package app.dapk.st.directory import androidx.lifecycle.viewModelScope import app.dapk.st.directory.DirectoryScreenState.Content import app.dapk.st.directory.DirectoryScreenState.EmptyLoading import app.dapk.st.viewmodel.DapkViewModel import app.dapk.st.viewmodel.MutableStateFactory import app.dapk.st.viewmodel.defaultStateFactory import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch class DirectoryViewModel( private val shortcutHandler: ShortcutHandler, private val directoryUseCase: DirectoryUseCase, factory: MutableStateFactory<DirectoryScreenState> = defaultStateFactory(), ) : DapkViewModel<DirectoryScreenState, DirectoryEvent>( initialState = EmptyLoading, factory, ) { private var syncJob: Job? = null fun start() { syncJob = viewModelScope.launch { directoryUseCase.state().onEach { shortcutHandler.onDirectoryUpdate(it.map { it.overview }) if (it.isNotEmpty()) { state = Content(it) } }.collect() } } fun stop() { syncJob?.cancel() } }
0
null
0
0
2ab2253e7a1335f8c25b5e69be0dc1ec9c254958
1,199
small-talk
Apache License 2.0
api/src/main/kotlin/de/hanno/hpengine/model/Instance.kt
hannomalie
330,376,962
false
{"Kotlin": 1006958, "GLSL": 659737, "JavaScript": 3160, "Shell": 137, "Batchfile": 65}
package de.hanno.hpengine.model import de.hanno.hpengine.Parentable import de.hanno.hpengine.Transform import de.hanno.hpengine.lifecycle.Updatable import de.hanno.hpengine.model.animation.AnimationController import de.hanno.hpengine.model.material.Material import de.hanno.hpengine.transform.AABB class Instance( val transform: Transform = Transform(), var materials: List<Material> = listOf(), val animationController: AnimationController? = null, val boundingVolume: AABB = AABB(), ) : Parentable<Instance>, Updatable { override val children = ArrayList<Instance>() override var parent: Instance? = null set(value) { transform.parent = value?.parent?.transform field = value } override fun addChild(child: Instance) { transform.addChild(child.transform) if (!hasChildInHierarchy(child)) { children.add(child) } } override fun removeChild(child: Instance) { transform.removeChild(child.transform) children.remove(child) } override fun update(deltaSeconds: Float) { animationController?.update(deltaSeconds) } }
0
Kotlin
0
0
7f3a721922067409d52f522c49178c5d3bd8003b
1,167
hpengine
MIT License
src/main/kotlin/com/springkt/demo/model/entity/User.kt
gemingjia
708,003,205
false
{"Kotlin": 7547}
package com.springkt.demo.model.entity import java.time.LocalDateTime /** * @author Ge Mingjia * @date 2023/10/21 */ data class User( val id: Int, val userAccount: String, val userPassword: String, val userName: String?, val userAvatar: String?, val userProfile: String?, val userRole: String, val createTime: LocalDateTime, val updateTime: LocalDateTime, val isDelete: Boolean )
0
Kotlin
0
2
ec65a94c9ef825098b3d112a42776e2bf5c8d6ae
424
springboot-kotlin-initialize
MIT License
app/src/main/java/com/example/androiddevchallenge/di/modules/RepositoryModule.kt
klikiooo
794,901,581
false
{"Kotlin": 80357}
package com.example.androiddevchallenge.di.modules import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface RepositoryModule { // @Binds // fun providePetRepository(petRepository: PetRepository) : PetRepository }
0
Kotlin
0
0
591c94eb691459b30069fbdc36e61ac343de96ab
321
ad
The Unlicense
app/src/main/kotlin/com/myweatherapp/ui/view/detail/DetailActivity.kt
uniflow-kt
215,817,717
false
null
package com.myweatherapp.ui.view.detail import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar import com.myweatherapp.R import com.myweatherapp.domain.model.weather.DailyForecastId import com.myweatherapp.domain.model.weather.getColorFromCode import com.myweatherapp.ui.navigation.param import com.myweatherapp.ui.view.Arguments import io.uniflow.android.livedata.onStates import io.uniflow.core.flow.data.UIError import io.uniflow.core.flow.data.UIState import kotlinx.android.synthetic.main.activity_detail.* import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf /** * Weather DetailState View */ class DetailActivity : AppCompatActivity() { // Get all needed data private val detailId: String by param(Arguments.WEATHER_DETAIL_ID) private val detailViewModel: DetailViewModel by viewModel { parametersOf(DailyForecastId(detailId)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) onStates(detailViewModel) { state -> when (state) { //omit Loading & Empty state is DetailState -> showDetail(state) is UIState.Failed -> showError(state.error) } } detailViewModel.getDetail() } private fun showError(error: UIError?) { Snackbar.make( weatherItem, getString(R.string.loading_error) + " - $error", Snackbar.LENGTH_LONG ).show() } private fun showDetail(weather: DetailState) { weatherIcon.text = weather.icon weatherDay.text = weather.day weatherText.text = weather.fullText weatherWindText.text = weather.wind weatherTempText.text = weather.temperature weatherHumidityText.text = weather.humidity weatherItem.background.setTint(getColorFromCode(weather.color)) // Set back on background click weatherItem.setOnClickListener { onBackPressed() } } }
0
Kotlin
3
13
4d4aa55e3a784f261d4c5711376f9435e04d2718
2,149
weatherapp-uniflow
Apache License 2.0
src/main/kotlin/com/aoverin/invest/services/StockMarketApi.kt
a-overin
776,842,962
false
{"Kotlin": 29524, "Procfile": 81}
package com.aoverin.invest.services import com.aoverin.invest.models.StockCost import com.aoverin.invest.models.StockInfo import java.time.LocalDate interface StockMarketApi { fun getStockCostByDateAndCode(code: String, date: LocalDate): StockCost? fun getStockInfoByDateAndCode(code: String, date: LocalDate): StockInfo? }
0
Kotlin
0
0
c158362f77d0f0addf999d1551064a4d8adf6b30
335
invest-v2
Apache License 2.0