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/kotlin/com/merxury/blocker/view/PreferenceItemView.kt
lihenggui
115,417,337
false
{"Kotlin": 2128259, "Java": 24192, "Shell": 14152, "AIDL": 771}
/* * Copyright 2023 Blocker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.merxury.blocker.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import com.merxury.blocker.R import com.merxury.blocker.databinding.PreferenceItemViewBinding class PreferenceItemView : ConstraintLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initAttrs(context, attrs) } constructor(context: Context, attrs: AttributeSet?, attributeSetId: Int) : super( context, attrs, attributeSetId, ) { initAttrs(context, attrs) } private val binding: PreferenceItemViewBinding = PreferenceItemViewBinding.inflate(LayoutInflater.from(context), this, true) private fun initAttrs(context: Context, attrs: AttributeSet?) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.PreferenceItemView) val title = typedArray.getString(R.styleable.PreferenceItemView_item_title) val summary = typedArray.getString(R.styleable.PreferenceItemView_item_summary) typedArray.recycle() binding.title.text = title binding.summary.text = summary } fun setSummary(summary: String?) { binding.summary.text = summary } }
25
Kotlin
54
988
9696c391c64d1aa4a74384d22b4433fb7c67c890
1,976
blocker
Apache License 2.0
app/src/main/java/de/chrisward/theyworkforyou/customview/CircleView.kt
chrisward
166,674,561
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 2, "XML": 18, "Kotlin": 31}
package de.chrisward.theyworkforyou.customview import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View class CircleView : View { var circleColor = Color.WHITE set(color) { field = color invalidate() } private var paint: Paint? = null constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } fun init() { paint = Paint() paint!!.isAntiAlias = true } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val width = width val height = height val paddingLeft = paddingLeft val paddingRight = paddingRight val paddingTop = paddingTop val paddingBottom = paddingBottom val contentWidth = width - (paddingLeft + paddingRight) val contentHeight = height - (paddingTop + paddingBottom) val radius = Math.min(contentWidth, contentHeight) / 2 val cx = paddingLeft + contentWidth / 2 val cy = paddingTop + contentHeight / 2 paint!!.color = this.circleColor canvas.drawCircle(cx.toFloat(), cy.toFloat(), radius.toFloat(), paint!!) } }
1
null
1
1
dcc4300dbad63f458efd26f80adaa16114cb7c2e
1,513
theyworkforyou
Apache License 2.0
src/main/kotlin/org/cirruslabs/utils/bazel/model/kotlin/KotlinTestPackageInfo.kt
cirruslabs
267,932,378
false
null
package org.cirruslabs.utils.bazel.model.kotlin import org.cirruslabs.utils.bazel.model.base.PackageInfo import org.cirruslabs.utils.bazel.model.base.PackageRegistry class KotlinTestPackageInfo( fullyQualifiedName: String, targetPath: String, val testNames: List<String> ) : PackageInfo(fullyQualifiedName, targetPath, "tests") { override fun generateBuildFile(packageRegistry: PackageRegistry): String { val dependencyTargets = (directPackageDependencies + fullyQualifiedName) .map { packageRegistry.findInfo(it) } .flatten() val dependencyPaths = dependencyTargets.mapNotNull { pkg -> when { pkg is KotlinTestPackageInfo && pkg.fullyQualifiedName.contentEquals(fullyQualifiedName) -> null pkg is KotlinTestPackageInfo -> "//${pkg.targetPath}:lib" else -> pkg.fullTargetLocation } } val deps = dependencyPaths.toSortedSet().joinToString(separator = "\n") { "\"$it\"," } val result = StringBuilder() result.append("""# GENERATED load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library", "kt_jvm_test") kt_jvm_library( name = "lib", srcs = glob(["*.kt"]), visibility = ["//visibility:public"], deps = [ "@com_github_jetbrains_kotlin//:kotlin-test", ${deps.prependIndent(" ")} ], ) """ ) testNames.forEach { testName -> result.append(""" kt_jvm_test( name = "$testName", srcs = ["$testName.kt"], test_class = "$fullyQualifiedName.$testName", visibility = ["//visibility:public"], deps = [ ":lib" ], )""" ) } return result.toString() } }
3
Kotlin
2
14
1347ac0281c0c65b3da0d046d9ac01514d2a20ac
1,586
bazel-project-generator
MIT License
android/src/main/java/com/google/samples/apps/iosched/ui/widget/NavDrawerItemView.kt
brentwatson
70,599,432
true
{"Kotlin": 1011666, "Java": 642168, "HTML": 44216, "JavaScript": 19470, "CSS": 6214, "Shell": 5083}
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.widget import android.content.Context import android.content.res.ColorStateList import android.support.annotation.DrawableRes import android.support.annotation.StringRes import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.util.AttributeSet import android.view.LayoutInflater import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.google.samples.apps.iosched.R /** * A compound view for nav drawer items. This neatly encapsulates states, tinting text and * icons and setting a background when in state_activated. */ class NavDrawerItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ForegroundLinearLayout(context, attrs!!) { private var mIconTints: ColorStateList? = null init { orientation = LinearLayout.HORIZONTAL LayoutInflater.from(context).inflate(R.layout.navdrawer_item_view, this, true) val a = context.obtainStyledAttributes(attrs, R.styleable.NavDrawerItemView) if (a.hasValue(R.styleable.NavDrawerItemView_iconTints)) { mIconTints = a.getColorStateList(R.styleable.NavDrawerItemView_iconTints) } } fun setContent(@DrawableRes iconResId: Int, @StringRes titleResId: Int) { if (iconResId > 0) { val icon = DrawableCompat.wrap(ContextCompat.getDrawable(context, iconResId)) if (mIconTints != null) { DrawableCompat.setTintList(icon, mIconTints) } (findViewById(R.id.icon) as ImageView).setImageDrawable(icon) } (findViewById(R.id.title) as TextView).setText(titleResId) } }
0
Kotlin
0
0
e6f4a8ad4d1c84f55bfb5c3140c171af1792343b
2,370
iosched
Apache License 2.0
app/src/main/java/ch/admin/foitt/pilotwallet/platform/database/domain/usecase/implementation/CloseAppDatabaseImpl.kt
e-id-admin
775,912,525
false
{"Kotlin": 1303531}
package ch.admin.foitt.pilotwallet.platform.database.domain.usecase.implementation import ch.admin.foitt.pilotwallet.platform.database.domain.model.DatabaseWrapper import ch.admin.foitt.pilotwallet.platform.database.domain.usecase.CloseAppDatabase import javax.inject.Inject class CloseAppDatabaseImpl @Inject constructor( private val databaseWrapper: DatabaseWrapper, ) : CloseAppDatabase { override suspend fun invoke() { databaseWrapper.close() } }
0
Kotlin
0
3
3494eb2a5e7dfa1b5054359c88b467c5fc6a384c
474
eidch-pilot-android-wallet
MIT License
app/src/main/java/com/chirag/worldofplayassignment/ui/dashboard/viewmodels/DashboardDetailsVewModel.kt
chenky2981988
258,511,186
false
null
package com.chirag.worldofplayassignment.ui.dashboard.viewmodels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.chirag.worldofplayassignment.data.model.StoryDetails /** * Created by <NAME> on 26/4/20. */ class DashboardDetailsVewModel : ViewModel() { private var storyDetails = MutableLiveData<StoryDetails>() init { storyDetails.value = StoryDetails() } fun setStoryDetails(story: StoryDetails) { storyDetails.value = story } }
0
Kotlin
0
0
355d62a02bfab30fb79668c97a952be80db0c0d1
515
WorldOfPlayAssignment
MIT License
app/src/main/java/com/zhyea/bamboo/general/ZyDialog.kt
zhyea
318,011,229
false
null
package com.zhyea.bamboo.general import android.app.Activity import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.graphics.PixelFormat.OPAQUE import android.graphics.PixelFormat.TRANSLUCENT import android.view.* import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE import com.zhyea.bamboo.R import com.zhyea.bamboo.reader.BambooApp import java.lang.ref.WeakReference import java.util.* /** * er */ open class ZyDialog(context: Context, resetWindow: Boolean, clearFlags: Boolean) : Dialog(context, R.style.AppTheme) { /** * d */ private val dismissListener: DialogInterface.OnDismissListener? = null /** * b */ private var layout: ZyLayout? = null init { var window: Window? = null if (clearFlags) { window = getWindow() window!!.clearFlags(WindowManager.LayoutParams.ANIMATION_CHANGED) } for (format in TRANSLUCENT..OPAQUE) { if (!resetWindow) { break } window!!.setFormat(format) getWindow()!!.addFlags(FLAG_NOT_TOUCHABLE) } } constructor(context: Context, paramBoolean1: Boolean, clearFlags: Boolean, resId: Int) : this(context, paramBoolean1, clearFlags) { window!!.setWindowAnimations(resId) } /** * a */ private fun onUserInteraction() { if (context is Activity) { val a = context as Activity a.onUserInteraction() } } /** * c */ private fun dialog(): Dialog? { for (reference in showingDialogs) { val dialog = reference.get() if (null != dialog) { return dialog } } return null } /** * b */ private fun window(): Window? { val dialog: Dialog? = dialog() if (null != dialog) { return dialog.window } if (context is Activity) { return (context as Activity).window } return null } override fun dismiss() { val itr = showingDialogs.iterator() while (itr.hasNext()) { val dialog = itr.next().get() if (dialog === this) { itr.remove() } } dismissListener?.onDismiss(this) val act: Activity? = BambooApp.get()!!.getCurrentActivity() if (null != act && !act.isFinishing) { super.dismiss() } } override fun dispatchKeyEvent(keyEvent: KeyEvent): Boolean { onUserInteraction() return super.dispatchKeyEvent(keyEvent) } override fun dispatchTouchEvent(motionEvent: MotionEvent): Boolean { onUserInteraction() return super.dispatchTouchEvent(motionEvent) } override fun dispatchTrackballEvent(motionEvent: MotionEvent): Boolean { onUserInteraction() return super.dispatchTrackballEvent(motionEvent) } override fun setContentView(resId: Int) { setContentView(LayoutInflater.from(context).inflate(resId, null)) } override fun setContentView(view: View) { setContentView(view, null) } override fun setContentView(paramView: View, layoutParams: ViewGroup.LayoutParams?) { var params = layoutParams this.layout = ZyLayout(context) val tmp: ZyLayout? = this.layout if (params == null) { params = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT) } tmp!!.addView(paramView, params) super.setContentView(this.layout!!, ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)) } override fun show() { if (!isShowing) { val attributes = window!!.attributes attributes.width = MATCH_PARENT attributes.height = MATCH_PARENT val win: Window? = window() if (win != null) { attributes.flags = (-0x11 and win.attributes.flags) or (FLAG_NOT_TOUCHABLE and attributes.flags) } window!!.attributes = attributes showingDialogs.addFirst(WeakReference<Dialog>(this)) } super.show() } companion object { private val showingDialogs: LinkedList<WeakReference<Dialog>> = LinkedList() private var dismissListener: DialogInterface.OnDismissListener? = null fun dialog(): Dialog? { for (e in this.showingDialogs) { val d = e.get() if (null != d) { return d } } return null } fun set(listener: DialogInterface.OnDismissListener) { dismissListener = listener } } }
0
Kotlin
0
0
d9092b831f55e46566a2346b5312514fe7e7264d
4,916
bamboo
MIT License
pickerview/src/main/java/com/bigkoo/pickerview/view/WheelOptions.kt
neo-turak
674,130,168
false
null
package com.bigkoo.pickerview.view import android.graphics.Typeface import android.view.View import com.bigkoo.pickerview.R import com.bigkoo.pickerview.adapter.ArrayWheelAdapter import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener import com.contrarywind.listener.OnItemSelectedListener import com.contrarywind.view.WheelView import com.contrarywind.view.WheelView.DividerType class WheelOptions<T>( var view: View, //切换时,还原第一项 private val isRestoreItem: Boolean ) { private val wvOption1: WheelView = view.findViewById<View>(R.id.options1) as WheelView private val wvOption2: WheelView = view.findViewById<View>(R.id.options2) as WheelView private val wvOption3: WheelView = view.findViewById<View>(R.id.options3) as WheelView private var mOptions1Items: List<T>? = null private var mOptions2Items: List<List<T>>? = null private var mOptions3Items: List<List<List<T>>> ? = null private var linkage = true //默认联动 private var wheelListenerOption1: OnItemSelectedListener? = null private var wheelListenerOption2: OnItemSelectedListener? = null private var optionsSelectChangeListener: OnOptionsSelectChangeListener? = null init { // 初始化时显示的数据 } fun setPicker( options1Items: List<T>?, options2Items: List<List<T>>?, options3Items: List<List<List<T>>>? ) { mOptions1Items = options1Items mOptions2Items = options2Items mOptions3Items = options3Items // 选项1 if (mOptions1Items!=null){ wvOption1.setAdapter(ArrayWheelAdapter(mOptions1Items!!)) // 设置显示数据 wvOption1.currentItem = 0 // 初始化时显示的数据 } // 选项2 if (mOptions2Items != null) { wvOption2.setAdapter(ArrayWheelAdapter(mOptions2Items!![0])) // 设置显示数据 } wvOption2.currentItem = wvOption2.currentItem // 初始化时显示的数据 // 选项3 if (mOptions3Items != null) { wvOption3.setAdapter(ArrayWheelAdapter(mOptions3Items!![0][0])) // 设置显示数据 } wvOption3.currentItem = wvOption3.currentItem wvOption1.setIsOptions(true) wvOption2.setIsOptions(true) wvOption3.setIsOptions(true) if (mOptions2Items == null) { wvOption2.visibility = View.GONE } else { wvOption2.visibility = View.VISIBLE } if (mOptions3Items == null) { wvOption3.visibility = View.GONE } else { wvOption3.visibility = View.VISIBLE } // 联动监听器 wheelListenerOption1 = object : OnItemSelectedListener { override fun onItemSelected(index: Int) { var opt2Select = 0 if (mOptions2Items == null) { //只有1级联动数据 if (optionsSelectChangeListener != null) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, 0, 0 ) } } else { if (!isRestoreItem) { opt2Select = wvOption2.currentItem //上一个opt2的选中位置 //新opt2的位置,判断如果旧位置没有超过数据范围,则沿用旧位置,否则选中最后一项 opt2Select = if (opt2Select >= mOptions2Items!![index].size - 1) mOptions2Items!![index].size - 1 else opt2Select } wvOption2.setAdapter(ArrayWheelAdapter<Any?>(mOptions2Items!![index])) wvOption2.currentItem = opt2Select if (mOptions3Items != null) { wheelListenerOption2!!.onItemSelected(opt2Select) } else { //只有2级联动数据,滑动第1项回调 if (optionsSelectChangeListener != null) { optionsSelectChangeListener!!.onOptionsSelectChanged( index, opt2Select, 0 ) } } } } } wheelListenerOption2 = object : OnItemSelectedListener { override fun onItemSelected(index: Int) { var index1 = index if (mOptions3Items != null) { var opt1Select = wvOption1.currentItem opt1Select = if (opt1Select >= mOptions3Items!!.size - 1) mOptions3Items!!.size - 1 else opt1Select index1 = if (index1 >= mOptions2Items!![opt1Select].size - 1) mOptions2Items!![opt1Select].size - 1 else index1 var opt3 = 0 if (!isRestoreItem) { // wv_option3.getCurrentItem() 上一个opt3的选中位置 //新opt3的位置,判断如果旧位置没有超过数据范围,则沿用旧位置,否则选中最后一项 opt3 = if (wvOption3.currentItem >= mOptions3Items!![opt1Select][index1].size - 1) mOptions3Items!![opt1Select][index1].size - 1 else wvOption3.currentItem } wvOption3.setAdapter(ArrayWheelAdapter<Any?>(mOptions3Items!![wvOption1.currentItem][index1])) wvOption3.currentItem = opt3 //3级联动数据实时回调 if (optionsSelectChangeListener != null) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, index1, opt3 ) } } else { //只有2级联动数据,滑动第2项回调 if (optionsSelectChangeListener != null) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, index1, 0 ) } } } } // 添加联动监听 if (options1Items != null && linkage) { wvOption1.setOnItemSelectedListener(wheelListenerOption1!!) } if (options2Items != null && linkage) { wvOption2.setOnItemSelectedListener(wheelListenerOption2!!) } if (options3Items != null && linkage && optionsSelectChangeListener != null) { wvOption3.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(index: Int) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, wvOption2.currentItem, index ) } }) } } //不联动情况下 fun setNPicker(options1Items: List<T>?, options2Items: List<T>?, options3Items: List<T>?) { // 选项1 if (options1Items!=null){ wvOption1.setAdapter(ArrayWheelAdapter(options1Items)) // 设置显示数据 wvOption1.currentItem = 0 // 初始化时显示的数据 } // 选项2 if (options2Items != null) { wvOption2.setAdapter(ArrayWheelAdapter(options2Items)) // 设置显示数据 } wvOption2.currentItem = wvOption2.currentItem // 初始化时显示的数据 // 选项3 if (options3Items != null) { wvOption3.setAdapter(ArrayWheelAdapter(options3Items)) // 设置显示数据 } wvOption3.currentItem = wvOption3.currentItem wvOption1.setIsOptions(true) wvOption2.setIsOptions(true) wvOption3.setIsOptions(true) if (optionsSelectChangeListener != null) { wvOption1.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(index: Int) { optionsSelectChangeListener!!.onOptionsSelectChanged( index, wvOption2.currentItem, wvOption3.currentItem ) } }) } if (options2Items == null) { wvOption2.visibility = View.GONE } else { wvOption2.visibility = View.VISIBLE if (optionsSelectChangeListener != null) { wvOption2.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(index: Int) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, index, wvOption3.currentItem ) } }) } } if (options3Items == null) { wvOption3.visibility = View.GONE } else { wvOption3.visibility = View.VISIBLE if (optionsSelectChangeListener != null) { wvOption3.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(index: Int) { optionsSelectChangeListener!!.onOptionsSelectChanged( wvOption1.currentItem, wvOption2.currentItem, index ) } }) } } } fun setTextContentSize(textSize: Int) { wvOption1.setTextSize(textSize.toFloat()) wvOption2.setTextSize(textSize.toFloat()) wvOption3.setTextSize(textSize.toFloat()) } private fun setLineSpacingMultiplier() {} /** * 设置选项的单位 * * @param label1 单位 * @param label2 单位 * @param label3 单位 */ fun setLabels(label1: String?, label2: String?, label3: String?) { if (label1 != null) { wvOption1.setLabel(label1) } if (label2 != null) { wvOption2.setLabel(label2) } if (label3 != null) { wvOption3.setLabel(label3) } } /** * 设置x轴偏移量 */ fun setTextXOffset(x_offset_one: Int, x_offset_two: Int, x_offset_three: Int) { wvOption1.setTextXOffset(x_offset_one) wvOption2.setTextXOffset(x_offset_two) wvOption3.setTextXOffset(x_offset_three) } /** * 设置是否循环滚动 * * @param cyclic 是否循环 */ fun setCyclic(cyclic: Boolean) { wvOption1.setCyclic(cyclic) wvOption2.setCyclic(cyclic) wvOption3.setCyclic(cyclic) } /** * 设置字体样式 * * @param font 系统提供的几种样式 */ fun setTypeface(font: Typeface?) { wvOption1.setTypeface(font!!) wvOption2.setTypeface(font) wvOption3.setTypeface(font) } /** * 分别设置第一二三级是否循环滚动 * * @param cyclic1,cyclic2,cyclic3 是否循环 */ fun setCyclic(cyclic1: Boolean, cyclic2: Boolean, cyclic3: Boolean) { wvOption1.setCyclic(cyclic1) wvOption2.setCyclic(cyclic2) wvOption3.setCyclic(cyclic3) } val currentItems: IntArray /** * 返回当前选中的结果对应的位置数组 因为支持三级联动效果,分三个级别索引,0,1,2。 * 在快速滑动未停止时,点击确定按钮,会进行判断,如果匹配数据越界,则设为0,防止index出错导致崩溃。 * * @return 索引数组 */ get() { val currentItems = IntArray(3) currentItems[0] = wvOption1.currentItem if (mOptions2Items != null && mOptions2Items!!.size > 0) { //非空判断 currentItems[1] = if (wvOption2.currentItem > mOptions2Items!![currentItems[0]].size - 1) 0 else wvOption2.currentItem } else { currentItems[1] = wvOption2.currentItem } if (mOptions3Items != null && mOptions3Items!!.size > 0) { //非空判断 currentItems[2] = if (wvOption3.currentItem > mOptions3Items!![currentItems[0]][currentItems[1]].size - 1) 0 else wvOption3.currentItem } else { currentItems[2] = wvOption3.currentItem } return currentItems } fun setCurrentItems(option1: Int, option2: Int, option3: Int) { if (linkage) { itemSelected(option1, option2, option3) } else { wvOption1.currentItem = option1 wvOption2.currentItem = option2 wvOption3.currentItem = option3 } } private fun itemSelected(opt1Select: Int, opt2Select: Int, opt3Select: Int) { if (mOptions1Items != null) { wvOption1.currentItem = opt1Select } if (mOptions2Items != null) { wvOption2.setAdapter(ArrayWheelAdapter<Any?>(mOptions2Items!![opt1Select])) wvOption2.currentItem = opt2Select } if (mOptions3Items != null) { wvOption3.setAdapter(ArrayWheelAdapter<Any?>(mOptions3Items!![opt1Select][opt2Select])) wvOption3.currentItem = opt3Select } } /** * 设置间距倍数,但是只能在1.2-4.0f之间 * * @param lineSpacingMultiplier */ fun setLineSpacingMultiplier(lineSpacingMultiplier: Float) { wvOption1.setLineSpacingMultiplier(lineSpacingMultiplier) wvOption2.setLineSpacingMultiplier(lineSpacingMultiplier) wvOption3.setLineSpacingMultiplier(lineSpacingMultiplier) } /** * 设置分割线的颜色 * * @param dividerColor */ fun setDividerColor(dividerColor: Int) { wvOption1.setDividerColor(dividerColor) wvOption2.setDividerColor(dividerColor) wvOption3.setDividerColor(dividerColor) } /** * 设置分割线的类型 * * @param dividerType */ fun setDividerType(dividerType: DividerType?) { wvOption1.setDividerType(dividerType) wvOption2.setDividerType(dividerType) wvOption3.setDividerType(dividerType) } /** * 设置分割线之间的文字的颜色 * * @param textColorCenter */ fun setTextColorCenter(textColorCenter: Int) { wvOption1.setTextColorCenter(textColorCenter) wvOption2.setTextColorCenter(textColorCenter) wvOption3.setTextColorCenter(textColorCenter) } /** * 设置分割线以外文字的颜色 * * @param textColorOut */ fun setTextColorOut(textColorOut: Int) { wvOption1.setTextColorOut(textColorOut) wvOption2.setTextColorOut(textColorOut) wvOption3.setTextColorOut(textColorOut) } /** * Label 是否只显示中间选中项的 * * @param isCenterLabel */ fun isCenterLabel(isCenterLabel: Boolean) { wvOption1.isCenterLabel(isCenterLabel) wvOption2.isCenterLabel(isCenterLabel) wvOption3.isCenterLabel(isCenterLabel) } fun setOptionsSelectChangeListener(optionsSelectChangeListener: OnOptionsSelectChangeListener?) { this.optionsSelectChangeListener = optionsSelectChangeListener } fun setLinkage(linkage: Boolean) { this.linkage = linkage } /** * 设置最大可见数目 * * @param itemsVisible 建议设置为 3 ~ 9之间。 */ fun setItemsVisible(itemsVisible: Int) { wvOption1.setItemsVisibleCount(itemsVisible) wvOption2.setItemsVisibleCount(itemsVisible) wvOption3.setItemsVisibleCount(itemsVisible) } fun setAlphaGradient(isAlphaGradient: Boolean) { wvOption1.setAlphaGradient(isAlphaGradient) wvOption2.setAlphaGradient(isAlphaGradient) wvOption3.setAlphaGradient(isAlphaGradient) } }
0
Kotlin
0
0
f847ab8eef540b29770be1b2287311d4872ee256
15,444
Android-PickerView
Apache License 2.0
src/main/kotlin/io/spring/shinyay/test/repository/BookRepository.kt
shinyay
390,724,472
false
null
package io.spring.shinyay.test.repository import io.spring.shinyay.test.entity.Book import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface BookRepository : JpaRepository<Book, Long> { fun findBookByIsbn(isbn: String): MutableList<Book> }
0
Kotlin
0
0
18546ad871aa7569fb41b9959adf4a5f9c8bc98c
322
testcontainers-mysql-jpa-gs
MIT License
app/src/main/java/com/anibalbastias/android/marvelapp/base/api/data/dataStoreFactory/common/main/MainData.kt
anibalbastiass
173,621,278
false
null
package com.anibalbastias.android.marvelapp.base.api.data.dataStoreFactory.common.main import com.anibalbastias.android.marvelapp.base.api.data.dataStoreFactory.series.model.SeriesItemData import com.google.gson.annotations.SerializedName class MainData { @field:SerializedName("offset") var offset: Int? = null @field:SerializedName("limit") var limit: Int? = null @field:SerializedName("total") var total: Int? = null @field:SerializedName("count") var count: Int? = null @field:SerializedName("results") var results: List<SeriesItemData>? = null // var results: List<SectionData>? = null }
0
Kotlin
1
5
6dc4765788e5a83aa4337034a5cca97d703e5a75
642
AAD-Prepare-Exam
MIT License
src/main/kotlin/services/RadarrHistory.kt
Ather
161,568,528
false
null
/* * Copyright 2018 <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 app.ather.radarr.services import app.ather.radarr.model.history.HistoryResponse import app.ather.radarr.model.history.HistorySortKey import app.ather.radarr.model.paging.SortDirection import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface RadarrHistory { @GET("history") operator fun get( @Query("page") page: Int, @Query("pageSize") pageSize: Int? = null, @Query("sortKey") sortKey: HistorySortKey? = null, @Query("sortDir") sortDir: SortDirection? = null, @Query("movieId") movieId: Int? = null ): Call<HistoryResponse> }
0
Kotlin
0
0
7313476abe3a0a2db135ffce1c91b3a5f206b74e
1,227
radarr-kotlin
Apache License 2.0
wing/src/main/java/com/zhan/ktwing/provider/ContextProvider.kt
hyzhan43
209,910,611
false
null
package com.zhan.ktwing.provider import android.app.Application import android.content.Context import com.zhan.ktwing.KtWing /** * author: HyJame * date: 2019-12-04 * desc: 默认初始化 KtWing, 并提供 全局 applicationContext */ object ContextProvider { private lateinit var application: Application fun attachContext(context: Context?) { application = context as? Application ?: throw RuntimeException("init KtWing error !") // init KtWing KtWing.init(application) } }
0
Kotlin
0
1
78ffbadf90f1f4d646156bf107208ed80af744f4
508
KtWing
Apache License 2.0
src/main/kotlin/moe/kyubey/akatsuki/utils/I18n.kt
Kyuubey
103,563,776
false
null
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.utils import java.util.* object I18n { fun parse(str: String, values: Map<String, Any>): String { val regex = "\\{\\{([^}]+)}}".toRegex() var new = str while (regex.containsMatchIn(new)) { val match = regex.find(new)?.groupValues if (values.contains(match?.get(1)) && match != null) { new = new.replace(match[0], values[match[1]].toString()) } } return new } fun permission(lang: ResourceBundle, perm: String): String = lang.getString( perm.split("_")[0].toLowerCase() + perm.split("_").getOrElse(1, { "" }).toLowerCase().capitalize() ) fun langToCode(lang: String): String = when (lang.toLowerCase()) { "dutch" -> "nl_NL" "english" -> "en_US" "japanese" -> "ja_JP" "french" -> "fr_FR" "spanish" -> "es_ES" "german" -> "de_DE" else -> "en_US" } }
2
Kotlin
0
3
384376309fbad669af8ffe81b7fa5d200943ba0e
2,146
Akatsuki
MIT License
src/main/kotlin/moe/kyubey/akatsuki/utils/I18n.kt
Kyuubey
103,563,776
false
null
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.utils import java.util.* object I18n { fun parse(str: String, values: Map<String, Any>): String { val regex = "\\{\\{([^}]+)}}".toRegex() var new = str while (regex.containsMatchIn(new)) { val match = regex.find(new)?.groupValues if (values.contains(match?.get(1)) && match != null) { new = new.replace(match[0], values[match[1]].toString()) } } return new } fun permission(lang: ResourceBundle, perm: String): String = lang.getString( perm.split("_")[0].toLowerCase() + perm.split("_").getOrElse(1, { "" }).toLowerCase().capitalize() ) fun langToCode(lang: String): String = when (lang.toLowerCase()) { "dutch" -> "nl_NL" "english" -> "en_US" "japanese" -> "ja_JP" "french" -> "fr_FR" "spanish" -> "es_ES" "german" -> "de_DE" else -> "en_US" } }
2
Kotlin
0
3
384376309fbad669af8ffe81b7fa5d200943ba0e
2,146
Akatsuki
MIT License
src/main/kotlin/network/message/encoder/FallbackEncoder.kt
KatiumDev
488,028,614
false
null
/* * Copyright 2022 Katium Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package katium.client.qq.network.message.encoder import katium.client.qq.chat.QQChat import katium.client.qq.network.QQClient import katium.client.qq.network.message.pb.PbMessageElement import katium.core.message.content.MessageContent object FallbackEncoder : MessageEncoder<MessageContent> { override suspend fun encode( client: QQClient, context: QQChat, message: MessageContent, withGeneralFlags: Boolean, isStandalone: Boolean ) = arrayOf(PbMessageElement(text = PbMessageElement.Text(string = message.asString()))) }
0
Kotlin
0
6
996181191d9a01fd58c0cee055e582d173f6b6d9
1,139
katium-client-tencent-qq
Apache License 2.0
app/src/main/java/com/example/gymrat/StartAndHome/CalculatorFragment.kt
Faokunn
746,999,154
false
{"Kotlin": 118172}
import android.app.AlertDialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.gymrat.Models.AuthManager import com.example.gymrat.Models.LoginResponse import com.example.gymrat.R import com.example.gymrat.api.RetrofitClient import com.example.gymrat.databinding.FragmentCalculatorBinding import retrofit2.Call import retrofit2.Callback import retrofit2.Response class CalculatorFragment : Fragment() { private lateinit var binding: FragmentCalculatorBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentCalculatorBinding.inflate(inflater, container, false) ArrayAdapter.createFromResource( requireContext(), R.array.gender_options, android.R.layout.simple_spinner_item ).also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.genderSpinner.adapter = adapter } ArrayAdapter.createFromResource( requireContext(), R.array.active_options, android.R.layout.simple_spinner_item ).also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.physicalActivitySpinner.adapter = adapter } binding.continueButton.setOnClickListener { calculateTDEE() } binding.back.setOnClickListener { findNavController().navigate(R.id.action_calculatorFragment_to_homiesFragment) } return binding.root } private fun calculateTDEE() { val weightStr = binding.weight.text.toString() val heightStr = binding.height.text.toString() val ageStr = binding.age.text.toString() if (weightStr.isNotEmpty() && heightStr.isNotEmpty() && ageStr.isNotEmpty()) { val weight = weightStr.toDoubleOrNull() val height = heightStr.toDoubleOrNull() val age = ageStr.toDoubleOrNull() val activityLevel = binding.physicalActivitySpinner.selectedItemPosition if (weight != null && height != null && age != null) { val bmr: Double = when (binding.genderSpinner.selectedItemPosition) { 0 -> 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age) 1 -> 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age) else -> 0.0 } val tdee: Double = when (activityLevel) { 0 -> bmr * 1.375 1 -> bmr * 1.55 2 -> bmr * 1.725 else -> 0.0 } val maintenanceCalories = tdee.toInt() val deficitCalories = (tdee - 300).toInt() val surplusCalories = (tdee + 300).toInt() showResultsDialog(maintenanceCalories, deficitCalories, surplusCalories) } } } private fun showResultsDialog(maintenanceCalories: Int, deficitCalories: Int, surplusCalories: Int) { val builder = AlertDialog.Builder(requireContext()) builder.setTitle("TDEE Calculation Results") .setMessage( "Maintenance Calorie: $maintenanceCalories\n" + "Deficit Calorie: $deficitCalories\n" + "Surplus Calorie: $surplusCalories" ) .setPositiveButton("Add") { _, _ -> val user_id = AuthManager.instance.userid val maintenance = maintenanceCalories.toString() val surplus = surplusCalories.toString() val deficit = deficitCalories.toString() RetrofitClient.instance.updateCalories(user_id!!, maintenance, surplus, deficit) .enqueue(object : Callback<LoginResponse> { override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) { if (response.isSuccessful) { findNavController().navigate(R.id.action_calculatorFragment_to_homiesFragment) } else { Toast.makeText(context, response.message(), Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<LoginResponse>, t: Throwable) { } }) } .setNegativeButton("OK") { _, _ -> } .show() } }
0
Kotlin
0
0
38bbe5519fcb3e9a613cc563790aa63dbdd75c04
4,961
gymrat-app
Apache License 2.0
kover-gradle-plugin/src/main/kotlin/kotlinx/kover/gradle/aggregation/project/instrumentation/JvmTestTaskInstrumentation.kt
Kotlin
394,574,917
false
{"Kotlin": 710220, "Java": 23398}
/* * Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.kover.gradle.aggregation.project.instrumentation import kotlinx.kover.gradle.aggregation.commons.names.KoverPaths import org.gradle.api.Named import org.gradle.api.artifacts.Configuration import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.RegularFile import org.gradle.api.provider.Provider import org.gradle.api.tasks.* import org.gradle.api.tasks.testing.Test import org.gradle.process.CommandLineArgumentProvider import java.io.File internal object JvmOnFlyInstrumenter { /** * Add online instrumentation to all JVM test tasks. */ fun instrument( tasks: TaskCollection<Test>, jarConfiguration: Configuration, filter: InstrumentationFilter ) { tasks.configureEach { val binReportProvider = project.layout.buildDirectory.map { dir -> dir.file(KoverPaths.binReportPath(name)) } doFirst { // delete report so that when the data is re-measured, it is not appended to an already existing file // see https://github.com/Kotlin/kotlinx-kover/issues/489 binReportProvider.get().asFile.delete() } // Always excludes android classes, see https://github.com/Kotlin/kotlinx-kover/issues/89 val androidClasses = setOf( // Always excludes android classes, see https://github.com/Kotlin/kotlinx-kover/issues/89 "android.*", "com.android.*", // excludes JVM internal classes, in some cases, errors occur when trying to instrument these classes, for example, when using JaCoCo + Robolectric. There is also no point in instrumenting them in Kover. "jdk.internal.*" ) val excludedClassesWithAndroid = filter.copy(excludes = filter.excludes + androidClasses) dependsOn(jarConfiguration) jvmArgumentProviders += JvmTestTaskArgumentProvider( temporaryDir, project.objects.fileCollection().from(jarConfiguration), excludedClassesWithAndroid, binReportProvider ) } } } internal data class InstrumentationFilter( @get:Input val includes: Set<String>, @get:Input val excludes: Set<String> ) /** * Provider of additional JVM string arguments for running a test task. */ private class JvmTestTaskArgumentProvider( private val tempDir: File, // relative sensitivity for file is a comparison by file name and its contents @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) val jarFiles: ConfigurableFileCollection, @get:Nested val filter: InstrumentationFilter, @get:OutputFile val reportProvider: Provider<RegularFile> ) : CommandLineArgumentProvider, Named { @Internal override fun getName(): String { return "koverArgumentsProvider" } override fun asArguments(): MutableIterable<String> { val files = jarFiles.files if (files.size != 1) { return mutableSetOf() } val jarFile = files.single() return buildKoverJvmAgentArgs(jarFile, tempDir, reportProvider.get().asFile, filter.excludes) .toMutableList() } } private fun buildKoverJvmAgentArgs( jarFile: File, tempDir: File, binReportFile: File, excludedClasses: Set<String> ): List<String> { val argsFile = tempDir.resolve("kover-agent.args") argsFile.writeAgentArgs(binReportFile, excludedClasses) return mutableListOf("-javaagent:${jarFile.canonicalPath}=file:${argsFile.canonicalPath}") } private fun File.writeAgentArgs(binReportFile: File, excludedClasses: Set<String>) { binReportFile.parentFile.mkdirs() val binReportPath = binReportFile.canonicalPath printWriter().use { pw -> pw.append("report.file=").appendLine(binReportPath) excludedClasses.forEach { e -> pw.append("exclude=").appendLine(e) } } }
57
Kotlin
52
1,332
800d2449262ec6f586c5fc80ae71d66ef6d79a29
4,161
kotlinx-kover
Apache License 2.0
app/src/main/java/com/mebk/pan/vm/DownloadViewModel.kt
mebk-org
346,362,454
false
null
package com.mebk.pan.vm import android.app.Application import androidx.lifecycle.* import com.mebk.pan.application.MyApplication import com.mebk.pan.utils.REQUEST_SUCCESS import com.mebk.pan.utils.RetrofitClient import kotlinx.coroutines.launch class DownloadViewModel(application: Application) : AndroidViewModel(application) { private val application = getApplication<MyApplication>() val downloadClientInfo = MutableLiveData<String>() fun download(id: String) = viewModelScope.launch { val pair = application.repository.getDownloadClient(id) if (pair.first ==REQUEST_SUCCESS) { downloadClientInfo.value = pair.second } else { downloadClientInfo.value = "获取下载链接失败,请重试" } } }
1
null
1
3
84f0879e19708a4863699e0d751c685ae6739336
754
MebkPan
Apache License 2.0
ui-artifact-list/src/main/java/reactivecircus/releaseprobe/artifactlist/ArtifactListFragment.kt
ReactiveCircus
142,655,149
false
null
package reactivecircus.releaseprobe.artifactlist import android.os.Bundle import android.view.View import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import reactivecircus.releaseprobe.artifactlist.databinding.FragmentArtifactListBinding import reactivecircus.releaseprobe.core.base.BaseFragment const val ARG_COLLECTION_KEY = "ARG_COLLECTION_KEY" class ArtifactListFragment : BaseFragment(R.layout.fragment_artifact_list) { private val viewModel by viewModel<ArtifactListViewModel> { parametersOf( requireNotNull(requireArguments().getString(ARG_COLLECTION_KEY)) ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentArtifactListBinding.bind(view) // TODO } }
7
Kotlin
4
8
b97fb5b8f161f29b70db1de6446af76166f42aa4
872
release-probe
MIT License
src/apps/kotlin/slatekit-samples/src/main/kotlin/slatekit/samples/common/data/MovieMapper3.kt
slatekit
55,942,000
false
{"Text": 42, "Ignore List": 42, "YAML": 3, "Markdown": 22, "Gradle": 79, "Shell": 46, "Batchfile": 40, "Java Properties": 25, "Kotlin": 884, "JSON": 12, "INI": 9, "EditorConfig": 26, "Java": 13, "SQL": 1, "XML": 4, "Swift": 3}
package slatekit.samples.common.data import slatekit.data.core.LongId import slatekit.data.core.Meta import slatekit.data.core.Table import slatekit.entities.mapper.EntityMapper import slatekit.entities.mapper.EntitySettings import slatekit.meta.models.Model import slatekit.samples.common.models.Movie /** * Option 3: Schema automatically loaded from annotation * Pros: More convenient due to setting up schema once, no manual encoding/decoding * Cons: Less performant than manual */ object MovieMapper3 : EntityMapper<Long, Movie>( model = Model.load(Movie::class), meta = Meta(LongId { m -> m.id }, Table("movie")), idClass = Long::class, enClass = Movie::class, settings = EntitySettings(true))
3
Kotlin
13
112
d17b592aeb28c5eb837d894e98492c69c4697862
736
slatekit
Apache License 2.0
app/src/main/java/com/czech/muvies/features/home/MoviesFragment.kt
segunfrancis
369,744,478
true
{"Kotlin": 237173}
package com.czech.muvies.features.home import android.os.Bundle import androidx.fragment.app.Fragment import android.view.View import androidx.fragment.app.viewModels import com.czech.muvies.R import com.czech.muvies.databinding.MoviesFragmentBinding import com.czech.muvies.features.home.epoxy.MainMovieHolder import com.czech.muvies.features.home.epoxy.MovieHeaderHolder import com.czech.muvies.features.home.epoxy.SubMovieHolder import com.czech.muvies.models.* import com.czech.muvies.models.Movies.MoviesResult.* import com.czech.muvies.network.MoviesApiService import com.czech.muvies.repository.MovieRepository import com.czech.muvies.utils.* import com.czech.muvies.utils.epoxy.BaseEpoxyController import com.czech.muvies.utils.epoxy.carouselNoSnap import timber.log.Timber class MoviesFragment : Fragment(R.layout.movies_fragment) { private val binding: MoviesFragmentBinding by viewBinding(MoviesFragmentBinding::bind) private val viewModel by viewModels<MoviesViewModel> { MovieViewModelFactory(MovieRepository((MoviesApiService.getService()))) } private val controller: MovieAdapterController by lazy { MovieAdapterController() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.movieEpoxyRecyclerView.adapter = controller.adapter viewModel.movieResponse.observe(viewLifecycleOwner) { result -> when (result) { is Result.Loading -> handleLoading() is Result.Error -> handleError(result.error) is Result.Success -> handleSuccess(result.data) } } } private fun handleError(error: Throwable) = with(binding) { root.showErrorMessage(error.localizedMessage) lottieProgress.makeGone() Timber.e(error) } private fun handleLoading() { binding.lottieProgress.makeVisible() } private fun handleSuccess(data: List<Movies.MoviesResult>) { binding.lottieProgress.makeGone() controller.data = data controller.requestModelBuild() } inner class MovieAdapterController : BaseEpoxyController<Movies.MoviesResult?>() { override fun buildModels() { data?.let { movies -> val movieMap = movies.groupBy { it?.movieCategory } movieMap.keys.forEachIndexed { index, movieCategory -> carouselNoSnap { MovieHeaderHolder { title -> //requireView().showMessage(title) movieCategory?.let { launchFragment(NavigationDeepLinks.toAllMovies(it.value, it.formattedName)) } }.apply { title = movieCategory!!.formattedName id(movieCategory.name.plus(index)) addTo(this@MovieAdapterController) } id(movieCategory?.name.plus(" carousel")) models(movies.filter { movie -> movie?.movieCategory == movieCategory }.mapIndexed { index, moviesResult -> if (moviesResult?.movieCategory == MovieCategory.IN_THEATER) { MainMovieHolder { launchFragment(NavigationDeepLinks.toMovieDetails(it, moviesResult.title)) }.apply { moviesResult.let { title = it.title imageUrl = it.posterPath movieId = it.id } id(index) } } else { SubMovieHolder { launchFragment(NavigationDeepLinks.toMovieDetails(it, moviesResult?.title ?: "")) }.apply { moviesResult?.let { title = it.title imageUrl = it.posterPath movieId = it.id } id(index) } } }) } } } } } }
0
Kotlin
0
1
82c9a919ce8f7558f69beea01676dc8e48ccd36e
4,669
Muvies
MIT License
data/src/main/java/com/depromeet/threedays/data/mapper/AchievementMapper.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.data.mapper import com.depromeet.threedays.data.entity.achievement.AchievementEntity import com.depromeet.threedays.domain.entity.achievement.Achievement fun AchievementEntity.toAchievement(): Achievement { return Achievement( id = id, nextAchievementDate = nextAchievementDate, habitId = habitId, achievementDate = achievementDate, sequence = sequence, ) }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
440
three-days-android
MIT License
app/src/main/java/wardani/dika/moviedbmandiri/DikaApp.kt
dikawardani24
292,583,501
false
null
package wardani.dika.moviedbmandiri import androidx.multidex.MultiDexApplication class DikaApp : MultiDexApplication()
0
Kotlin
0
0
b1992a8398228ac33420d5b13229836c118b0ec2
120
movieDbMandiri
MIT License
livingdoc-tests/src/main/kotlin/org/livingdoc/example/Calculator.kt
LivingDoc
85,412,044
false
null
package org.livingdoc.example /** * A simple calculator implementation * * This will be our first system under test (SUT) in this project */ class Calculator { /** * @return the sum of two numbers */ fun sum(a: Float, b: Float): Float { return a + b } /** * @param a the minuend * @param b the subtrahend * @return the difference of two numbers */ fun diff(a: Float, b: Float): Float { return a - b } /** * @return the product of two numbers */ fun multiply(a: Float, b: Float): Float { return a * b } /** * @param a the dividend * @param b the divisor * @return the quotient of two numbers */ fun divide(a: Float, b: Float): Float { return a / b } }
34
null
16
14
f3d52b8bacbdf81905e4b4a753d75f584329b297
800
livingdoc
Apache License 2.0
example/shared/src/commonMain/kotlin/lottiefiles/SortOrder.kt
alexzhirkevich
730,724,501
false
{"Kotlin": 891763, "Swift": 601, "HTML": 211}
package lottiefiles internal enum class SortOrder { Popular, Newest, Oldest }
5
Kotlin
7
232
46b008cd7cf40a84261b20c5888359f08368016a
82
compottie
MIT License
app/src/main/java/com/sunil/kotlincoroutneexample/base/BaseViewModel.kt
sunil676
182,536,306
false
null
package com.maiconhellmann.architecture.view import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.support.annotation.CallSuper /** */ abstract class AbstractViewModel : ViewModel() { /** * Handle data loading */ val isDataLoading = MutableLiveData<Boolean>() /** * Handle errors */ val exception = MutableLiveData<Throwable>() @CallSuper override fun onCleared() { super.onCleared() } open fun setLoading(isLoading: Boolean? = true) { isDataLoading.value = isLoading if (isLoading == true) { exception.value = null } } open fun setError(t: Throwable) { exception.value = t } }
5
Kotlin
4
2
38700fbca2ee2144644377b938b4fa25d9741e7b
751
KotlinCoroutinKoinMvvm
Apache License 2.0
android/app/src/main/kotlin/com/example/bookbuddies/MainActivity.kt
niltoneapontes
434,191,252
false
{"Dart": 114682, "HTML": 3701, "Ruby": 1353, "Swift": 495, "Kotlin": 123, "Objective-C": 38}
package br.com.bookbuddies import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
2
271390d6d9481b54d8f44f619e3f9717e39ebe43
123
book-buddies
MIT License
build-logic/src/main/kotlin/io/truthencode/TestExtensions.kt
adarro
48,509,636
false
{"Scala": 2298447, "HTML": 593837, "Java": 107826, "CSS": 35640, "ANTLR": 11312, "Pug": 8653, "Kotlin": 5891, "Scaml": 1461, "Shell": 773, "Gherkin": 273, "Batchfile": 25}
package io.truthencode.djaxonomy.etc import net.pearx.kasechange.toCamelCase import org.gradle.api.Project import org.gradle.api.attributes.TestSuiteType import org.gradle.api.plugins.jvm.JvmTestSuite import org.gradle.api.provider.Property import org.gradle.kotlin.dsl.invoke import org.gradle.kotlin.dsl.provideDelegate enum class KotlinTestKits { KoTest, KotlinTest, None, } enum class TestMode { REFLECT, KAPT, KSP, } interface KotlinTestKitExtension { val useKotlinTestKit: Property<KotlinTestKits> } class KotlinTestKitClassExtension(val useKotlinTestKit: Property<KotlinTestKits>) interface KotlinAnnotationProcessingExtension { val kotlinTestMode: Property<TestMode> } enum class TestTypes { Unit(TestSuiteType.UNIT_TEST), Integration(TestSuiteType.INTEGRATION_TEST), Functional(TestSuiteType.FUNCTIONAL_TEST), Performance(TestSuiteType.PERFORMANCE_TEST), Acceptance("acceptance-test"), Custom("custom-test"), ; var id: String? = null var defaultName: String? = null var testSuiteType: String? = null val knownSuiteNames = listOf( TestSuiteType.UNIT_TEST, TestSuiteType.FUNCTIONAL_TEST, TestSuiteType.INTEGRATION_TEST, TestSuiteType.PERFORMANCE_TEST, ) constructor() constructor(id: String) { this.id = id this.defaultName = when (id) { TestSuiteType.UNIT_TEST -> "test" else -> id.toCamelCase() } if (knownSuiteNames.contains(id)) { this.testSuiteType = id } } companion object { fun fromTestSuiteType(id: String): TestTypes { return when (id) { TestSuiteType.UNIT_TEST -> Unit TestSuiteType.INTEGRATION_TEST -> Integration TestSuiteType.FUNCTIONAL_TEST -> Functional TestSuiteType.PERFORMANCE_TEST -> Performance "acceptance-test" -> Acceptance // Static Duck-typing ATM else -> Custom } } fun fromNamingConvention(key: String): TestTypes { return TestTypes.values().find { it.defaultName == key } ?: Custom } } } class TestBuildSupport(proj: Project) { private val koTestVersion: String by proj val applyMockito = { suite: JvmTestSuite -> suite.useJUnitJupiter() suite.dependencies { implementation("org.mockito:mockito-junit-jupiter:4.6.1") } } val applyKoTest = { suite: JvmTestSuite -> suite.useJUnitJupiter() suite.dependencies { implementation("io.kotest:kotest-runner-junit5:$koTestVersion") implementation("io.kotest:kotest-assertions-core:$koTestVersion") implementation("io.kotest:kotest-property:$koTestVersion") } } }
21
Scala
3
2
4e0d23b506db9c29528dafb569e4a2aee212c33e
2,893
ddo-calc
Apache License 2.0
app/src/main/java/com/ciscowebex/androidsdk/kitchensink/messaging/spaces/members/MembershipActivity.kt
webex
137,331,913
false
{"Kotlin": 921538}
package com.ciscowebex.androidsdk.kitchensink.messaging.spaces.members import android.content.Context import android.content.Intent import android.os.Bundle import androidx.databinding.DataBindingUtil import com.ciscowebex.androidsdk.kitchensink.BaseActivity import com.ciscowebex.androidsdk.kitchensink.R import com.ciscowebex.androidsdk.kitchensink.databinding.ActivityMembershipBinding import com.ciscowebex.androidsdk.kitchensink.utils.Constants class MembershipActivity : BaseActivity() { companion object { fun getIntent(context: Context, spaceId: String): Intent { val intent = Intent(context, MembershipActivity::class.java) intent.putExtra(Constants.Intent.SPACE_ID, spaceId) return intent } } lateinit var binding: ActivityMembershipBinding private lateinit var spaceId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) spaceId = intent.getStringExtra(Constants.Intent.SPACE_ID) ?: "" DataBindingUtil.setContentView<ActivityMembershipBinding>(this, R.layout.activity_membership) .apply { val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() val fragment = MembershipFragment.newInstance(spaceId) fragmentTransaction.add(R.id.membershipFragment, fragment) fragmentTransaction.commit() } } }
8
Kotlin
19
14
f6ce3ab0d33275c7e59a9d5465d3fa635b5e28bd
1,541
webex-android-sdk-example
MIT License
tutorial/src/androidTest/kotlin/com/kaspersky/kaspresso/tutorial/tutorial/NotificationActivityTest.kt
sophie5363
867,609,889
false
{"Kotlin": 758946, "Shell": 1880, "Makefile": 387}
package com.kaspersky.kaspresso.tutorial import androidx.test.ext.junit.rules.activityScenarioRule import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import com.kaspersky.kaspresso.tutorial.screen.MainScreen import com.kaspersky.kaspresso.tutorial.screen.NotificationActivityScreen import com.kaspersky.kaspresso.tutorial.screen.NotificationScreen import org.junit.Rule import org.junit.Test class NotificationActivityTest : TestCase() { @get: Rule val activityRule = activityScenarioRule<MainActivity>() @Test fun checkNotification() = run { step("Open notification activity") { MainScreen { notificationActivityButton { isVisible() isClickable() click() } } } step("show notification") { NotificationActivityScreen { showNotificationButton { isVisible() isClickable() click() } } } step("Check notification texts") { NotificationScreen { title.isDisplayed() title.hasText("Notification Title") content.isDisplayed() content.hasText("Notification Content") } } } }
0
Kotlin
0
0
bd8d7fcc2daa31a6721349aa72df1bd783962edf
1,370
tutoKaspresso
Apache License 2.0
library/src/test/java/software/amazon/location/tracking/BackgroundTrackingWorkerTest.kt
aws-geospatial
775,000,374
false
{"Kotlin": 111631}
package software.amazon.location.tracking import android.content.Context import android.location.Location import android.os.Build import android.os.Looper import androidx.room.RoomDatabase import androidx.work.Constraints import androidx.work.Data import androidx.work.PeriodicWorkRequest import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkerParameters import com.amazonaws.internal.keyvaluestore.AWSKeyValueStore import com.amazonaws.services.geo.AmazonLocationClient import com.amazonaws.services.geo.model.BatchUpdateDevicePositionResult import com.google.android.gms.location.CurrentLocationRequest import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationAvailability import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.gson.GsonBuilder import io.mockk.coEvery import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkConstructor import io.mockk.mockkStatic import io.mockk.runs import io.mockk.unmockkAll import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import software.amazon.location.auth.LocationCredentialsProvider import software.amazon.location.tracking.TestConstants.TEST_CLIENT_CONFIG import software.amazon.location.tracking.TestConstants.TEST_IDENTITY_POOL_ID import software.amazon.location.tracking.TestConstants.TEST_LATITUDE import software.amazon.location.tracking.TestConstants.TEST_LONGITUDE import software.amazon.location.tracking.aws.AmazonTrackingHttpClient import software.amazon.location.tracking.config.LocationTrackerConfig import software.amazon.location.tracking.database.LocationEntry import software.amazon.location.tracking.database.LocationEntryDao_Impl import software.amazon.location.tracking.filters.TimeLocationFilter import software.amazon.location.tracking.providers.BackgroundTrackingWorker import software.amazon.location.tracking.providers.LocationProvider import software.amazon.location.tracking.util.StoreKey import software.amazon.location.tracking.util.TrackingSdkLogLevel import java.util.UUID import kotlin.concurrent.thread import kotlin.test.assertNotNull class BackgroundTrackingWorkerTest { @Mock lateinit var context: Context @Mock lateinit var workerParameters: WorkerParameters private lateinit var backgroundTrackingWorker: BackgroundTrackingWorker private lateinit var locationClientConfig: LocationTrackerConfig private lateinit var locationCredentialsProvider: LocationCredentialsProvider private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private lateinit var gsonBuilderMock: GsonBuilder @Before fun setUp() { context = mockk(relaxed = true) workerParameters = mockk<WorkerParameters>(relaxed = true) mockkConstructor(AWSKeyValueStore::class) every { anyConstructed<AWSKeyValueStore>().get("apiKey") } returns "testApiKey" every { anyConstructed<AWSKeyValueStore>().get("region") } returns "us-east-1" every { anyConstructed<AWSKeyValueStore>().put(any(), any<String>()) } just runs every { anyConstructed<AWSKeyValueStore>().clear() } just runs locationCredentialsProvider = mockk() locationClientConfig = LocationTrackerConfig( trackerName = TestConstants.TRACKER_NAME, logLevel = TrackingSdkLogLevel.DEBUG, accuracy = Priority.PRIORITY_HIGH_ACCURACY, latency = 1000, frequency = 5000, waitForAccurateLocation = false, minUpdateIntervalMillis = 5000, ) val locationClientConfig = mockk<LocationTrackerConfig>() every { locationClientConfig.logLevel } returns TrackingSdkLogLevel.DEBUG every { locationClientConfig.locationFilters } returns mutableListOf(TimeLocationFilter()) every { locationClientConfig.trackerName } returns TestConstants.TRACKER_NAME gsonBuilderMock = mockk() every { gsonBuilderMock.create() } returns mockk() every { gsonBuilderMock.registerTypeAdapter(any(), any()) } returns gsonBuilderMock mockkConstructor(AmazonTrackingHttpClient::class) mockkConstructor(LocationProvider::class) mockkConstructor(RoomDatabase::class) mockkConstructor(AmazonLocationClient::class) mockkConstructor(LocationCredentialsProvider::class) every { locationCredentialsProvider.getCredentialsProvider() } returns mockk() fusedLocationProviderClient = mockk() mockkStatic(LocationServices::class) every { LocationServices.getFusedLocationProviderClient(context) } returns fusedLocationProviderClient mockkStatic(Build.VERSION::class) val location = mock(Location::class.java) `when`(location.latitude).thenReturn(TEST_LATITUDE) `when`(location.longitude).thenReturn(TEST_LONGITUDE) every { fusedLocationProviderClient.getCurrentLocation( ofType(CurrentLocationRequest::class), any() ) } answers { Tasks.forResult(location) } val mockTask: Task<Void?> = mockk() coEvery { fusedLocationProviderClient.removeLocationUpdates(any<LocationCallback>()) } returns mockTask every { fusedLocationProviderClient.locationAvailability } returns mockk() val locationAvailability = mockk<LocationAvailability>() every { locationAvailability.isLocationAvailable } returns true coEvery { fusedLocationProviderClient.locationAvailability } returns Tasks.forResult( locationAvailability ) mockkStatic(Looper::class) val mainLooper = mockk<Looper>() every { Looper.getMainLooper() } returns mainLooper val mainThread = thread { } every { mainLooper.thread } returns mainThread mockkConstructor(Location::class) mockkConstructor(LocationTracker::class) every { anyConstructed<Location>().time } returns System.currentTimeMillis() every { anyConstructed<Location>().longitude } returns TEST_LONGITUDE every { anyConstructed<Location>().latitude } returns TEST_LATITUDE val location1 = LocationEntry(1, 10.0, 20.0, System.currentTimeMillis(), 5.0f) val locations = listOf(location1) mockkConstructor(LocationEntryDao_Impl::class) coEvery { anyConstructed<LocationEntryDao_Impl>().getAllEntries() } returns locations coEvery { anyConstructed<LocationEntryDao_Impl>().insert(any()) } just runs coEvery { anyConstructed<LocationEntryDao_Impl>().deleteEntriesByIds(any()) } just runs coEvery { anyConstructed<LocationEntryDao_Impl>().deleteEntryById(any()) } just runs val mockBatchUpdateDevicePositionResult = mockk<BatchUpdateDevicePositionResult>() coEvery { anyConstructed<AmazonLocationClient>().batchUpdateDevicePosition(any()) } returns mockBatchUpdateDevicePositionResult } @Test fun testDoWork() { val location = mock(Location::class.java) `when`(location.latitude).thenReturn(TEST_LATITUDE) `when`(location.longitude).thenReturn(TEST_LONGITUDE) every { context.applicationContext } returns mockk() every { anyConstructed<AWSKeyValueStore>().get("method") } returns "cognito" every { anyConstructed<AWSKeyValueStore>().get("identityPoolId") } returns TEST_IDENTITY_POOL_ID every { anyConstructed<AWSKeyValueStore>().get(StoreKey.CLIENT_CONFIG) } returns TEST_CLIENT_CONFIG runBlocking { every { runBlocking { anyConstructed<LocationTracker>().getDeviceLocation(any()) } } returns location backgroundTrackingWorker = BackgroundTrackingWorker(context, workerParameters) val result = backgroundTrackingWorker.doWork() assertNotNull(result) } } @Test fun testEnqueueWork() { mockkStatic(WorkManager::class) every { WorkManager.getInstance(context).enqueue(ofType(PeriodicWorkRequest::class)) } returns mockk() runBlocking { val result = BackgroundTrackingWorker.enqueueWork(context) assertNotNull(result) } } @Test fun testCancelWork() { mockkStatic(WorkManager::class) every { WorkManager.getInstance(context).cancelAllWorkByTag(any()) } returns mockk() runBlocking { val result = BackgroundTrackingWorker.cancelWork(context) assertNotNull(result) } } @Test fun isWorkRunning() { mockkStatic(WorkManager::class) val mockWorkInfoList = listOf( createWorkInfo(WorkInfo.State.RUNNING), ) every { WorkManager.getInstance(context).getWorkInfosByTag(any()).get() } returns mockWorkInfoList runBlocking { val result = BackgroundTrackingWorker.isWorkRunning(context) assertNotNull(result) } } private fun createWorkInfo(state: WorkInfo.State): WorkInfo { val id = UUID.randomUUID() return WorkInfo( id = id, state = state, tags = emptySet(), outputData = Data.EMPTY, progress = Data.EMPTY, runAttemptCount = 1, generation = 0, constraints = Constraints.NONE, initialDelayMillis = 0, periodicityInfo = null, nextScheduleTimeMillis = 0, stopReason = WorkInfo.STOP_REASON_APP_STANDBY ) } @After fun tearDown() { unmockkAll() } }
1
Kotlin
3
1
e43401f2f58b8c5796ed14cbcf77951651b1c377
10,018
amazon-location-mobile-tracking-sdk-android
Apache License 2.0
packages/HilltopCrawler/src/main/kotlin/nz/govt/eop/hilltop_crawler/Application.kt
Greater-Wellington-Regional-Council
528,176,417
false
{"Kotlin": 231043, "TypeScript": 111538, "Batchfile": 47265, "PLpgSQL": 42581, "Shell": 37231, "ASL": 6123, "JavaScript": 2960, "Dockerfile": 2376, "CSS": 860, "HTML": 554}
package nz.govt.eop.hilltop_crawler import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableScheduling @SpringBootApplication @EnableScheduling @EnableConfigurationProperties(ApplicationConfiguration::class) class Application {} fun main(args: Array<String>) { System.setProperty("com.sun.security.enableAIAcaIssuers", "true") runApplication<Application>(*args) }
12
Kotlin
1
3
82c0566e79f1f18f1c861bc7676648a4ff60e702
566
Environmental-Outcomes-Platform
MIT License
app/src/main/java/com/ph03nix_x/capacityinfo/interfaces/PremiumInterface.kt
Ph03niX-X
204,125,869
false
null
package com.ph03nix_x.capacityinfo.interfaces import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.widget.Toast import androidx.preference.PreferenceManager import com.android.billingclient.api.AcknowledgePurchaseParams import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingClient.BillingResponseCode import com.android.billingclient.api.BillingClient.ProductType import com.android.billingclient.api.BillingClientStateListener import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.BillingResult import com.android.billingclient.api.ProductDetails import com.android.billingclient.api.Purchase import com.android.billingclient.api.PurchasesUpdatedListener import com.android.billingclient.api.QueryProductDetailsParams import com.android.billingclient.api.QueryPurchaseHistoryParams import com.android.billingclient.api.queryPurchaseHistory import com.ph03nix_x.capacityinfo.PREMIUM_ID import com.ph03nix_x.capacityinfo.R import com.ph03nix_x.capacityinfo.TOKEN_COUNT import com.ph03nix_x.capacityinfo.TOKEN_PREF import com.ph03nix_x.capacityinfo.activities.MainActivity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Created by Ph03niX-X on 04.12.2021 * <EMAIL> */ @SuppressLint("StaticFieldLeak") interface PremiumInterface: PurchasesUpdatedListener { companion object { private var mProductDetailsList: List<ProductDetails>? = null var premiumContext: Context? = null var premiumActivity: Activity? = null var billingClient: BillingClient? = null var isPremium = false } override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) { if (billingResult.responseCode == BillingResponseCode.OK && purchases != null) { for (purchase in purchases) { CoroutineScope(Dispatchers.Default).launch { handlePurchase(purchase) } } } else if (billingResult.responseCode == BillingResponseCode.ITEM_ALREADY_OWNED) { val pref = PreferenceManager.getDefaultSharedPreferences(premiumContext!!) if(purchases != null) pref.edit().putString(TOKEN_PREF, purchases[0].purchaseToken).apply() val tokenPref = pref.getString(TOKEN_PREF, null) isPremium = tokenPref != null && tokenPref.count() >= TOKEN_COUNT MainActivity.instance?.toolbar?.menu?.findItem(R.id.premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.history_premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.clear_history)?.isVisible = true } } fun initiateBilling(isPurchasePremium: Boolean = false) { billingClient = BillingClient.newBuilder(premiumContext!!) .setListener(purchasesUpdatedListener()).enablePendingPurchases().build() if (billingClient?.connectionState == BillingClient.ConnectionState.DISCONNECTED) startConnection(isPurchasePremium) } private fun startConnection(isPurchasePremium: Boolean) { billingClient?.startConnection(object : BillingClientStateListener { override fun onBillingSetupFinished(billingResult: BillingResult) { if (billingResult.responseCode == BillingResponseCode.OK) { if(isPurchasePremium) purchasePremium() else querySkuDetails() } } override fun onBillingServiceDisconnected() {} }) } private fun purchasesUpdatedListener() = PurchasesUpdatedListener { _, purchases -> if (purchases != null) { for (purchase in purchases) { CoroutineScope(Dispatchers.Default).launch { handlePurchase(purchase) } } } } private suspend fun handlePurchase(purchase: Purchase) { val pref = PreferenceManager.getDefaultSharedPreferences(premiumContext!!) if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) { if (!purchase.isAcknowledged) { val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.purchaseToken) withContext(Dispatchers.IO) { billingClient?.acknowledgePurchase(acknowledgePurchaseParams.build()) { if (it.responseCode == BillingResponseCode.OK) { pref.edit().putString(TOKEN_PREF, purchase.purchaseToken).apply() val tokenPref = pref.getString(TOKEN_PREF, null) isPremium = tokenPref != null && tokenPref.count() >= TOKEN_COUNT Toast.makeText(premiumContext, R.string.premium_features_unlocked, Toast.LENGTH_LONG).show() MainActivity.instance?.toolbar?.menu?.findItem(R.id.premium) ?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.history_premium) ?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.clear_history) ?.isVisible = true } } } } else { pref.edit().putString(TOKEN_PREF, purchase.purchaseToken).apply() val tokenPref = pref.getString(TOKEN_PREF, null) isPremium = tokenPref != null && tokenPref.count() >= TOKEN_COUNT Toast.makeText(premiumContext, R.string.premium_features_unlocked, Toast.LENGTH_LONG).show() MainActivity.instance?.toolbar?.menu?.findItem(R.id.premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.history_premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.clear_history)?.isVisible = true } } else if (purchase.purchaseState == Purchase.PurchaseState.PENDING) { pref.edit().putString(TOKEN_PREF, purchase.purchaseToken).apply() val tokenPref = pref.getString(TOKEN_PREF, null) isPremium = tokenPref != null && tokenPref.count() >= TOKEN_COUNT Toast.makeText(premiumContext, R.string.premium_features_unlocked, Toast.LENGTH_LONG) .show() MainActivity.instance?.toolbar?.menu?.findItem(R.id.premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.history_premium)?.isVisible = false MainActivity.instance?.toolbar?.menu?.findItem(R.id.clear_history)?.isVisible = true } } private fun querySkuDetails() { val productList = mutableListOf(QueryProductDetailsParams.Product.newBuilder().apply { setProductId(PREMIUM_ID) setProductType(ProductType.INAPP) }.build()) val queryProductDetailsParams = QueryProductDetailsParams.newBuilder() .setProductList(productList).build() billingClient?.queryProductDetailsAsync(queryProductDetailsParams) { billingResult, productDetailsList -> if (billingResult.responseCode == BillingResponseCode.OK) mProductDetailsList = productDetailsList } } fun purchasePremium() { if(!mProductDetailsList.isNullOrEmpty()) { val productDetailsParamsList = listOf(BillingFlowParams.ProductDetailsParams .newBuilder().setProductDetails(mProductDetailsList!![0]).build()) val billingFlowParams = BillingFlowParams.newBuilder() .setProductDetailsParamsList(productDetailsParamsList) .build() billingClient?.launchBillingFlow(premiumActivity!!, billingFlowParams) } } fun checkPremium() { val pref = PreferenceManager.getDefaultSharedPreferences(premiumContext!!) var tokenPref = pref.getString(TOKEN_PREF, null) if(tokenPref != null && tokenPref.count() >= TOKEN_COUNT) { isPremium = true return } else if(tokenPref != null && tokenPref.count() < TOKEN_COUNT) pref.edit().remove(TOKEN_PREF).apply() if(billingClient?.isReady != true) initiateBilling() val params = QueryPurchaseHistoryParams.newBuilder() .setProductType(ProductType.INAPP) CoroutineScope(Dispatchers.IO).launch { val purchaseHistoryResult = billingClient?.queryPurchaseHistory(params.build()) val purchaseHistoryRecordList = purchaseHistoryResult?.purchaseHistoryRecordList if(!purchaseHistoryRecordList.isNullOrEmpty()) { pref.edit().putString(TOKEN_PREF, purchaseHistoryRecordList[0].purchaseToken).apply() tokenPref = pref.getString(TOKEN_PREF, null) isPremium = tokenPref != null && (tokenPref?.count() ?: 0) >= TOKEN_COUNT } } } }
0
Kotlin
2
19
baadea15e02947d68bedf0485cd194f36836d5ce
9,429
CapacityInfo
Apache License 2.0
harvey-app-example/src/main/kotlin/hu/juzraai/harvey/example/data/TaskState.kt
juzraai
93,308,169
false
null
package hu.juzraai.harvey.example.data /** * @author <NAME> */ data class TaskState( var phase: String )
0
Kotlin
0
0
c608c5623b5e5951f756480475636ff83d83f5dc
109
harvey
The Unlicense
src/builder/BuilderTest.kt
imshyam
187,470,617
false
null
package builder import builder.implementation.CarBuilder import builder.implementation.CarBuilderImpl class CarBuildDirector(private val carBuilder: CarBuilder) { fun construct() = carBuilder.setWheels(4).setColor("Red").build() } fun main() { val carBuilder = CarBuilderImpl() val carBuildDirector = CarBuildDirector(carBuilder) println(carBuildDirector.construct()) }
0
Kotlin
0
0
6375a5e9a1dac9cffba89b99f0df91d4ca1fae00
388
design-patterns-kotlin
MIT License
src/commonMain/kotlin/event/data/Event.kt
tmindibaev
318,188,722
false
null
package event.data import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport import kotlin.js.JsName @ExperimentalJsExport @JsExport @JsName("Event") data class Event( val name: String, // TODO: seems like IR compiler can't compile Nullable types into js yet // val date: String? = null, // val place: String? = null val date: String, val place: String // TODO: think about non-exportable types // comment by authors: w: source-map argument is not supported yet // val extras: Map<EventExtraType, String> = emptyMap() )
0
Kotlin
0
0
457ea764a8bd817e021713f2e84f0c5dc8dc6a4c
564
together-vibe-shared-models
Apache License 2.0
core/src/com/quillraven/masamune/event/MapEvent.kt
Quillraven
162,866,864
false
null
package com.quillraven.masamune.event import com.badlogic.gdx.maps.tiled.TiledMap import com.badlogic.gdx.maps.tiled.TiledMapTileLayer import com.badlogic.gdx.utils.Array import com.quillraven.masamune.map.EMapType class MapEvent { internal var oldType = EMapType.UNDEFINED internal var newType = EMapType.UNDEFINED internal lateinit var map: TiledMap internal var width = 0f internal var height = 0f internal lateinit var bgdLayers: Array<TiledMapTileLayer> internal lateinit var fgdLayers: Array<TiledMapTileLayer> }
0
Kotlin
4
3
998707bf891e3d7db38200f6bf9727593da0f69f
548
Masamune
MIT License
shared/src/commonMain/kotlin/Model.kt
petrumo
271,764,859
false
{"Swift": 6156, "Kotlin": 4389, "Objective-C": 467}
package sample import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Model ( @SerialName("id") val id : String, @SerialName("favorite") val favorite : Boolean, @SerialName("title") val title : String )
0
Swift
0
0
6cd6f2b516052b3b48a0127cb250ef68e34c06aa
283
KotlinKommon
MIT License
src/main/kotlin/dev/resolvt/plugin/ide/service/CredentialsService.kt
verkhovin
383,521,945
false
null
package dev.resolvt.plugin.ide.service import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.generateServiceName import com.intellij.ide.passwordSafe.PasswordSafe import dev.resolvt.plugin.client.model.Tokens class CredentialsService { private val objectMapper: ObjectMapper = ObjectMapper().also { it.registerKotlinModule() } companion object { private const val TOKENS_KEY = "Tokens" private const val CREDENTIALS_USERNAME = "tokens" } fun saveTokens(tokens: Tokens) { val tokensAttribute = createCredentialAttributes(TOKENS_KEY) val tokensJson = objectMapper.writeValueAsString(tokens) val credentials = Credentials(CREDENTIALS_USERNAME, tokensJson) PasswordSafe.instance.set(tokensAttribute, credentials) } fun clearTokens() { val tokensAttribute = createCredentialAttributes(TOKENS_KEY) PasswordSafe.instance.set(tokensAttribute, null) } fun getTokens(): Tokens? { val tokensJson = PasswordSafe.instance.getPassword(createCredentialAttributes(TOKENS_KEY)) ?: return null return objectMapper.readValue(tokensJson) } fun getAccessToken() = getTokens()?.accessToken!! fun getRefreshToken() = getTokens()?.refreshToken!! private fun createCredentialAttributes(key: String) = CredentialAttributes(generateServiceName("Resolvt", key)) }
0
Kotlin
0
0
4b608f0c9ccde79b4587e015c6412ecf45eb70e3
1,642
resolvt-idea-plugin
MIT License
app/src/main/java/com/ramos/diego/destinos/ui/components/DestinoItem.kt
DiegoFortRamos
715,758,834
false
{"Kotlin": 13280}
package com.ramos.diego.destinos.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button 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.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight 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 com.ramos.diego.destinos.R import com.ramos.diego.destinos.model.Destinos @Composable fun DestinoItem(destinos: Destinos) { Surface(shape = RoundedCornerShape(15.dp), shadowElevation = 4.dp) { Column( modifier = Modifier .height(250.dp) .width(280.dp) ) { Box( modifier = Modifier .fillMaxWidth() .height(100.dp) ) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(destinos.imagemDestino), contentDescription = null, contentScale = ContentScale.Crop ) } Column( modifier = Modifier .fillMaxWidth() .padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( destinos.tituloDestino, fontWeight = FontWeight(700), fontSize = 18.sp ) Text( destinos.descricaoTitulo, modifier = Modifier.padding(top = 8.dp), textAlign = TextAlign.Center ) Button( onClick = {/*TODO*/ }, modifier = Modifier .width(100.dp) .padding(top = 20.dp) ) { Text("Saiba Mais", fontSize = 10.sp) } } } } } @Preview(showBackground = true) @Composable private fun DestinoItemPreview() { DestinoItem( Destinos( tituloDestino = "Rio de Janeiro", descricaoTitulo = "Conheça a cidade maravilhosa", imagemDestino = R.drawable.ic_launcher_background ) ); }
0
Kotlin
0
0
06981a69b30c664b1823084a4b3f76387f6e51bc
2,950
Destinos-App
MIT License
common_base_ui/src/main/java/com/fido/common/common_base_ui/ext/RvExt.kt
SevenUpup
588,455,697
false
null
package com.fido.common.common_base_ui.ext import androidx.recyclerview.widget.RecyclerView /** @author FiDo @description: @date :2023/6/13 8:58 */ /** * Rv是否滚动到底部 */ fun RecyclerView.isSlideToBottom(): Boolean = (this.computeVerticalScrollExtent() + this.computeVerticalScrollOffset() >= this.computeVerticalScrollRange()) /** * (1)的值表示是否能向上滚动,false表示已经滚动到底部 */ val RecyclerView.canScrollUp get() = this.canScrollVertically(1) /** * (-1)的值表示是否能向下滚动,false表示已经滚动到顶部 */ val RecyclerView.canScrollDown get() = this.canScrollVertically(-1)
0
Kotlin
0
2
f26362014d4876ee7aed10cf13fad422e39e2fa5
559
common_utils
Apache License 2.0
sample-reports/src/androidTest/java/com/rubensousa/carioca/sample/reports/OpenNotificationScenario.kt
rubensousa
853,775,838
false
{"Kotlin": 336232}
/* * Copyright 2024 Rúben Sousa * * 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.rubensousa.carioca.sample.reports import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiDevice import com.rubensousa.carioca.report.android.stage.InstrumentedScenario import com.rubensousa.carioca.report.android.stage.InstrumentedStageScope class OpenNotificationScenario : InstrumentedScenario("Open Notification") { private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) override fun run(scope: InstrumentedStageScope) = with(scope) { screenshot("Before opening notifications") step("Request notification open") { device.openNotification() } step("Wait for animation") { Thread.sleep(1000L) screenshot("Notification") } screenshot("After opening notifications") } }
2
Kotlin
0
1
bc33dbf0f8b288e1950483c5711eebc1c910f8ac
1,452
Carioca
Apache License 2.0
app/src/main/java/com/wright/beers20/presentation/screens/beerdetails/BeerDetailsFragment.kt
Sloox
409,553,597
false
{"Kotlin": 26271}
package com.wright.beers20.presentation.screens.beerdetails import android.os.Bundle import android.view.View import android.widget.TextView import androidx.fragment.app.viewModels import com.wright.beers20.R import com.wright.beers20.commons.BaseFragment import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class BeerDetailsFragment : BaseFragment<BeerDetailsViewState>(R.layout.fragment_beer_details) { private val textViewName: TextView get() = requireView().findViewById(R.id.textview_name) override val viewModel: BeerDetailsViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.onStartWithNavArguments(arguments?.getInt("beerId") ?: 0) } override fun renderViewState(newViewState: BeerDetailsViewState) { if (newViewState.beer.name.isNullOrBlank()) { textViewName.text = "Loading..." } else textViewName.text = newViewState.beer.name + " id: ${newViewState.beer.id}" } }
0
Kotlin
0
0
a6ab8a747846e9192a3f097f397b3da1286848f1
1,068
Beer2.0
Apache License 2.0
app/src/main/java/com/matthew/carvalhodagenais/modernaconverter/ui/ConvertFragment.kt
mcd-3
275,522,842
false
null
package com.matthew.carvalhodagenais.modernaconverter.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.matthew.carvalhodagenais.modernaconverter.MainActivity import com.matthew.carvalhodagenais.modernaconverter.R import com.matthew.carvalhodagenais.modernaconverter.adapters.CurrencySpinnerAdapter import com.matthew.carvalhodagenais.modernaconverter.data.entities.Currency import com.matthew.carvalhodagenais.modernaconverter.databinding.FragmentConverterBinding import com.matthew.carvalhodagenais.modernaconverter.listeners.ButtonListenerGenerator import com.matthew.carvalhodagenais.modernaconverter.listeners.SpinnerListenerGenerator import com.matthew.carvalhodagenais.modernaconverter.utils.CurrencyArrayUtil import com.matthew.carvalhodagenais.modernaconverter.viewmodels.ConvertViewModel import kotlinx.android.synthetic.main.fragment_converter.* class ConvertFragment: Fragment() { private lateinit var viewModel: ConvertViewModel private lateinit var currencies: Array<Currency> private lateinit var spinnerAdapter: CurrencySpinnerAdapter private var fromCurrency: Currency? = null private var toCurrency: Currency? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = (activity as MainActivity).convertViewModel currencies = CurrencyArrayUtil().getAllSupportedCurrencies(requireContext()) fromCurrency = currencies[CurrencyArrayUtil.USD_INDEX] toCurrency = currencies[CurrencyArrayUtil.EUR_INDEX] val binding = DataBindingUtil.inflate<FragmentConverterBinding>( inflater, R.layout.fragment_converter, container, false ).apply { viewmodel = viewModel } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Set adapter and listener for button val blg = ButtonListenerGenerator() val buttonListener = blg.generateConvertListener( requireContext(), content_motion_layout, currency_edit_text, submit_button, base_text, conversion_text, swap_image_view, viewModel, this, fromCurrency, toCurrency ) submit_button.setOnClickListener(buttonListener) // Set adapter, selection, and listeners for spinners spinnerAdapter = CurrencySpinnerAdapter(requireContext(), currencies) val slg = SpinnerListenerGenerator() val spinnerListener = slg.generateCurrencyListener( fromCurrency, toCurrency, currency_button_left, currency_button_right ) currency_button_left.adapter = spinnerAdapter currency_button_left.setSelection(spinnerAdapter.getPosition(fromCurrency)) currency_button_left.onItemSelectedListener = spinnerListener currency_button_right.adapter = spinnerAdapter currency_button_right.setSelection(spinnerAdapter.getPosition(toCurrency)) currency_button_right.onItemSelectedListener = spinnerListener } }
2
Kotlin
0
1
1dd53672ab5fc4503e01bc74ef71ec2b3cbef849
3,372
moderna-currency-converter
MIT License
profilers-ui/testSrc/com/android/tools/profilers/memory/LiveMemoryFootprintViewTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.profilers.com.android.tools.profilers.memory import com.android.sdklib.AndroidVersion import com.android.testutils.MockitoKt import com.android.testutils.MockitoKt.mock import com.android.testutils.MockitoKt.whenever import com.android.tools.adtui.RangeTooltipComponent import com.android.tools.adtui.TooltipView import com.android.tools.adtui.TreeWalker import com.android.tools.adtui.model.DefaultTimeline import com.android.tools.adtui.model.FakeTimer import com.android.tools.adtui.model.Timeline import com.android.tools.adtui.model.TooltipModel import com.android.tools.adtui.model.ViewBinder import com.android.tools.adtui.stdui.ContextMenuItem import com.android.tools.idea.transport.faketransport.FakeGrpcChannel import com.android.tools.idea.transport.faketransport.FakeTransportService import com.android.tools.profiler.proto.Common import com.android.tools.profilers.FakeIdeProfilerComponents import com.android.tools.profilers.FakeIdeProfilerServices import com.android.tools.profilers.ProfilerClient import com.android.tools.profilers.ProfilerTooltipMouseAdapter import com.android.tools.profilers.SessionProfilersView import com.android.tools.profilers.StageView import com.android.tools.profilers.StageWithToolbarView import com.android.tools.profilers.StreamingStage import com.android.tools.profilers.StudioProfilers import com.android.tools.profilers.StudioProfilersView import com.android.tools.profilers.event.FakeEventService import com.android.tools.profilers.memory.LiveMemoryFootprintModel import com.android.tools.profilers.memory.LiveMemoryFootprintView import com.google.common.truth.Truth.assertThat import com.intellij.testFramework.DisposableRule import com.intellij.ui.components.JBPanel import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.spy import org.mockito.Mockito.times import org.mockito.Mockito.verify import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel open class LiveMemoryFootprintViewTest { protected var myTimer = FakeTimer() private val myComponents = FakeIdeProfilerComponents() private val myIdeServices = FakeIdeProfilerServices() private val myTransportService = FakeTransportService(myTimer, true, AndroidVersion.VersionCodes.S, Common.Process.ExposureLevel.PROFILEABLE) @get:Rule val myGrpcChannel = FakeGrpcChannel("MainMemoryProfilerLiveViewTest", myTransportService, FakeEventService()) @get:Rule val disposableRule = DisposableRule() private lateinit var myProfilersView: StudioProfilersView private lateinit var myModel: LiveMemoryFootprintModel private lateinit var profilers: StudioProfilers @Before fun setUp() { profilers = StudioProfilers(ProfilerClient(myGrpcChannel.channel), myIdeServices, myTimer) // Advance the clock to make sure StudioProfilers has a chance to select device + process. myTimer.tick(FakeTimer.ONE_SECOND_IN_NS) profilers.setPreferredProcess(FakeTransportService.FAKE_DEVICE_NAME, FakeTransportService.FAKE_PROCESS_NAME, null) // One second must be enough for new devices (and processes) to be picked up myTimer.tick(FakeTimer.ONE_SECOND_IN_NS) myModel = LiveMemoryFootprintModel(profilers) myModel.enter() myProfilersView = SessionProfilersView(profilers, myComponents, disposableRule.disposable) } @Test fun testTooltipComponentAsFirstElement() { val memoryFootprintView = LiveMemoryFootprintView(myProfilersView, myModel) val myTimeline: Timeline = DefaultTimeline() val myContent = JPanel(BorderLayout()) val rangeTooltipComponent = RangeTooltipComponent(myTimeline, myContent) memoryFootprintView.populateUi(rangeTooltipComponent); val treeWalker = TreeWalker(memoryFootprintView.component) val tooltipComponent = treeWalker.descendants().filterIsInstance(RangeTooltipComponent::class.java) // Check for tooltip presence in live view component assertThat(tooltipComponent.size).isEqualTo(1) val usageView = getMainComponent(memoryFootprintView) // Check for tooltip to be first element of usage view assertThat(usageView.getComponent(0)).isInstanceOf(RangeTooltipComponent::class.java) } @Test fun testJPanelComponentAsSecondElementOfMainComponent() { val memoryFootprintView = LiveMemoryFootprintView(myProfilersView, myModel) val myTimeline: Timeline = DefaultTimeline() val myContent = JPanel(BorderLayout()) val rangeTooltipComponent = RangeTooltipComponent(myTimeline, myContent) memoryFootprintView.populateUi(rangeTooltipComponent); val treeWalker = TreeWalker(memoryFootprintView.component) val tooltipComponent = treeWalker.descendants().filterIsInstance(RangeTooltipComponent::class.java) // Check for tooltip presence in live view component assertThat(tooltipComponent.size).isEqualTo(1) val usageView = getMainComponent(memoryFootprintView) // Check for tooltip to be first element of usage view assertThat(usageView.getComponent(1)).isInstanceOf(JBPanel::class.java) } @Test fun testWithoutPopulateUiCalledComponentIsEmpty() { val memoryFootprintView = LiveMemoryFootprintView(myProfilersView, myModel) val treeWalker = TreeWalker(memoryFootprintView.component) val tooltipComponent = treeWalker.descendants().filterIsInstance(RangeTooltipComponent::class.java) // Check for tooltip presence in live view component assertThat(tooltipComponent.size).isEqualTo(0) val usageView = getMainComponent(memoryFootprintView) assertThat(usageView.size.height).isEqualTo(0) assertThat(usageView.size.width).isEqualTo(0) } @Test fun testHasContextMenuItems() { myComponents.clearContextMenuItems() val memoryFootprintView = LiveMemoryFootprintView(myProfilersView, myModel) val myTimeline: Timeline = DefaultTimeline() val myContent = JPanel(BorderLayout()) val tooltipComponent = RangeTooltipComponent(myTimeline, myContent) memoryFootprintView.populateUi(tooltipComponent); val items = myComponents.allContextMenuItems // 4 items and 1 separator, garbage collection and seperator // Attach, Detach, Separator, Zoom in, Zoom out assertThat(items.size).isEqualTo(8) assertThat(items[0].text).isEqualTo(ContextMenuItem.SEPARATOR.text) assertThat(items[1].text).isEqualTo("Force garbage collection") assertThat(items[2].text).isEqualTo(ContextMenuItem.SEPARATOR.text) assertThat(items[3].text).isEqualTo(StageWithToolbarView.ATTACH_LIVE) assertThat(items[4].text).isEqualTo(StageWithToolbarView.DETACH_LIVE) assertThat(items[5].text).isEqualTo(ContextMenuItem.SEPARATOR.text) assertThat(items[6].text).isEqualTo(StageWithToolbarView.ZOOM_IN) assertThat(items[7].text).isEqualTo(StageWithToolbarView.ZOOM_OUT) } @Test fun testToolbarHasGcButton() { val memoryFootprintView = LiveMemoryFootprintView(myProfilersView, myModel) val toolbar = memoryFootprintView.toolbar.getComponent(0) as JPanel assertThat(toolbar.components).asList().containsExactly( memoryFootprintView.garbageCollectionButton, ) } @Test fun testShowTooltipComponentAfterRegisterToolTip() { val memoryFootprintView = spy( LiveMemoryFootprintView(myProfilersView, myModel)) val tooltipComponent = mock<JComponent>() Mockito.doReturn(tooltipComponent).whenever(memoryFootprintView).tooltipComponent val myTimeline: Timeline = DefaultTimeline() val myContent = JPanel(BorderLayout()) val rangeTooltipComponent = RangeTooltipComponent(myTimeline, myContent) memoryFootprintView.populateUi(rangeTooltipComponent); val binder = ViewBinder<StageView<*>, TooltipModel, TooltipView>() val stage = mock<StreamingStage>() memoryFootprintView.registerTooltip(binder, rangeTooltipComponent, stage) verify(stage, times(1)).tooltip = MockitoKt.any(TooltipModel::class.java) verify(tooltipComponent, times(1)).addMouseListener(MockitoKt.any(ProfilerTooltipMouseAdapter::class.java)) } private fun getMainComponent(stageView: LiveMemoryFootprintView) = TreeWalker(stageView.component) .descendants() .filterIsInstance<JPanel>() .first() }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
8,884
android
Apache License 2.0
src/main/kotlin/com/github/jpvos/keylogger/plugin/toolwindow/charts/ActionsByTypeChart.kt
jpv-os
754,880,241
false
{"Kotlin": 67552}
package com.github.jpvos.keylogger.plugin.toolwindow.charts import com.github.jpvos.keylogger.plugin.KeyloggerBundle import com.github.jpvos.keylogger.plugin.services.DatabaseService import com.github.jpvos.keylogger.plugin.util.components.UpdatablePanel import com.intellij.openapi.components.service import com.intellij.ui.JBColor import org.knowm.xchart.PieChart import org.knowm.xchart.PieChartBuilder import org.knowm.xchart.XChartPanel import org.knowm.xchart.style.PieStyler class ActionsByTypeChart : UpdatablePanel() { private val chart: PieChart = PieChartBuilder() .title(KeyloggerBundle.message("charts.pieType.title")) .width(200) .height(200) .build() .apply { styler.apply { isLegendVisible = false isPlotBorderVisible = false isChartTitleBoxVisible = false isLabelsVisible = true labelType = PieStyler.LabelType.NameAndValue isForceAllLabelsVisible = true chartBackgroundColor = JBColor.background() plotBackgroundColor = JBColor.background() chartFontColor = JBColor.foreground() } } override val panel = XChartPanel(chart) override fun update() { val db = service<DatabaseService>().connection val actions = db.queryActionMap() actions.toList().map { it.first }.forEach { val seriesName = it.type.name if (!chart.seriesMap.containsKey(seriesName)) { chart.addSeries(seriesName, 0) } chart.updatePieSeries( seriesName, actions.filter { action -> action.key.type == it.type }.values.sum() ) } panel.repaint() } }
2
Kotlin
0
2
c9c67e6b919c5808c4126697ffb8eb26d4a4ed97
1,811
Keylogger
Apache License 2.0
logger/core/src/main/kotlin/org/sollecitom/chassis/logger/core/implementation/LongestPrefixMatchLoggingLevelEnabler.kt
sollecitom
669,483,842
false
{"Kotlin": 808742, "Java": 30834}
package org.sollecitom.chassis.logger.core.implementation import org.sollecitom.chassis.logger.core.LoggingLevel import org.sollecitom.chassis.logger.core.implementation.datastructure.Trie import org.sollecitom.chassis.logger.core.implementation.datastructure.mutableTrieOf internal class LongestPrefixMatchLoggingLevelEnabler(private val prefixMap: Map<String, LoggingLevel>, private val defaultMinimumLoggingLevel: LoggingLevel) : (LoggingLevel, String) -> Boolean { private val trie: Trie = mutableTrieOf(prefixMap.keys) override fun invoke(level: LoggingLevel, loggerName: String): Boolean { val longestPrefixMatch = trie.searchLongestPrefixWord(loggerName) val minimumLevel = prefixMap[longestPrefixMatch] ?: defaultMinimumLoggingLevel return level >= minimumLevel } }
0
Kotlin
0
2
a9ffd2d2fd649fc1c967098da9add4aac73a74b0
814
chassis
MIT License
build-logic/convention/src/main/kotlin/AndroidApplicationFirebaseConventionPlugin.kt
f33lnothin9
674,320,726
false
null
import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies import ru.resodostudios.cashsense.libs class AndroidApplicationFirebaseConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.google.gms.google-services") apply("com.google.firebase.firebase-perf") apply("com.google.firebase.crashlytics") } dependencies { val bom = libs.findLibrary("firebase-bom").get() add("implementation", platform(bom)) "implementation"(libs.findLibrary("firebase.analytics").get()) "implementation"(libs.findLibrary("firebase.performance").get()) "implementation"(libs.findLibrary("firebase.crashlytics").get()) } } } }
0
null
3
8
25a7a2a80e2872c5dd910eef16d6f1a38cde839d
915
cashsense
Apache License 2.0
app/src/main/java/com/tzion/jetpackmovies/domain/posters/PosterService.kt
4mr0m3r0
156,536,164
false
{"Kotlin": 151737}
package com.tzion.jetpackmovies.domain.posters import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.tzion.jetpackmovies.domain.boundary.RemoteFacade import com.tzion.jetpackmovies.domain.entities.Movie import com.tzion.jetpackmovies.domain.posters.pager.PostingPagingSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow class PosterService( private val remoteFacade: RemoteFacade, private val movie: Movie, ) { var pagingPosters: Flow<PagingData<Movie.Poster>> = emptyFlow() private set fun findByTitle(title: String?): Flow<PagingData<Movie.Poster>> { val verifiedTitle = movie.verifyTitleAndGetTrimValue(title) return Pager( config = PagingConfig( pageSize = remoteFacade.pageSize, enablePlaceholders = false ), pagingSourceFactory = { PostingPagingSource(remoteFacade, verifiedTitle) } ).flow } }
4
Kotlin
4
15
11b983e57bc1508a6ec5ca738af70c4f9a8ea9aa
1,039
movies-jetpack-sample
MIT License
src/main/kotlin/no/nav/pensjon/simulator/uttak/UttakUtil.kt
navikt
753,551,695
false
{"Kotlin": 1687999, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.uttak import no.nav.pensjon.simulator.alder.Alder import no.nav.pensjon.simulator.core.krav.UttakGradKode import no.nav.pensjon.simulator.search.IntegerDiscriminator import no.nav.pensjon.simulator.search.SearchForMinimum import no.nav.pensjon.simulator.tech.time.DateUtil.MAANEDER_PER_AAR import java.time.LocalDate // SimulatorPensjonTidUtil + SimulatorUttaksalderUtil object UttakUtil { /** * Antall år fra alder når alderspensjonen tidligst kan tas ut til alder der alle har ubetinget rett til å ta ut minsteytelsen. * Før 2026 var disse alderne henholdsvis 62 og 67 år. * F.o.m. 2026 vil alderne være dynamiske, men differansen vil være den samme (5 år). */ const val ANTALL_AAR_MELLOM_NEDRE_ALDERSGRENSE_OG_NORMALDER = 5 /** * Antall måneder fra alder når alderspensjonen tidligst kan tas ut til alder der alle har ubetinget rett til å ta ut minsteytelsen. * Før 2026 var disse alderne henholdsvis 62 og 67 år. * F.o.m. 2026 vil alderne være dynamiske, men differansen vil være den samme (5 år). */ private const val ANTALL_KANDIDAT_MAANEDER = ANTALL_AAR_MELLOM_NEDRE_ALDERSGRENSE_OG_NORMALDER * MAANEDER_PER_AAR val indexedUttakGrader = mapOf( UttakGradKode.P_80 to 0, UttakGradKode.P_60 to 1, UttakGradKode.P_50 to 2, UttakGradKode.P_40 to 3, UttakGradKode.P_20 to 4 ) /** * Uttaksdato er første dag i måneden etter "aldersdato". * "aldersdato" er datoen da aldersinnehaveren har en gitt alder (aldersdato = fødselsdato + alder) */ fun uttakDato(foedselDato: LocalDate, uttakAlder: Alder): LocalDate = foedselDato.plusYears(uttakAlder.aar.toLong()) .plusMonths((uttakAlder.maaneder + 1).toLong()) .withDayOfMonth(1) // In PEN used by SimulatorLavesteUttaksalderFinder (TMU) fun forsteUttakDato( foedselDato: LocalDate, tidligstUttakAlder: Alder, maxAlder: Alder, discriminator: IntegerDiscriminator ): LocalDate { val antallKandidatMaaneder = maxAlder.antallMaanederEtter(tidligstUttakAlder) val antallMaaneder = SearchForMinimum(discriminator).search(antallKandidatMaaneder) val tilleggMaaneder = if (antallMaaneder < 0) ANTALL_KANDIDAT_MAANEDER else antallMaaneder return uttakDato(foedselDato, tidligstUttakAlder).plusMonths(tilleggMaaneder.toLong()) } fun uttakDatoKandidat(foedselDato: LocalDate, lavesteUttakAlder: Alder, antallMaaneder: Int): LocalDate = uttakDato(foedselDato, lavesteUttakAlder).plusMonths(antallMaaneder.toLong()) //fun alderForrigeMaaned(alder: UttaksalderAlderDto) = Alder(alder.aar, alder.maaneder).minusMaaneder(1) /*V4 * * Finner høyeste sluttalder (til og med) for gradert uttak. * Det er alderen man har måneden før startalder for helt uttak. * / fun gradertUttakMaxTomAlder(spec: DatobasertUttakSpec, alderIfNotGradert: Alder): Alder { val alder: UttaksalderAlderDto = heltUttakFomAlder(spec, alderIfNotGradert) if (alder.aar < 0) { throw InvalidArgumentException("Ugyldig alder for helt uttak (f.o.m. = ${spec.gradertUttak?.heltUttakFom}) => år = ${alder.aar}") } return alderForrigeMaaned(alder) } */ /** * Gets a map of indexed uttaksgrader, excluding uttaksgrader greater than the given maxUttakGrad. * The index starts at zero. * Index zero represents the greatest uttaksgrad in the map. * The greatest index represents the smallest uttaksgrad (20 %). */ fun indexedUttakGradSubmap(maxUttakGrad: UttakGradKode): Map<Int, UttakGradKode> { val indexShift = indexedUttakGrader[maxUttakGrad] ?: 0 return indexedUttakGrader .filter { it.value >= indexShift } .map { (grad, index) -> index - indexShift to grad } .toMap() } /*V4 private fun heltUttakFomAlder(spec: DatobasertUttakSpec, alderIfNotGradert: Alder): UttaksalderAlderDto = spec.gradertUttak?.let { with(alderDato(spec.foedselDato, it.heltUttakFom).alder) { UttaksalderAlderDto(aar = this.aar, maaneder = this.maaneder) } } ?: dto(alderIfNotGradert) */ }
1
Kotlin
0
0
1f7f146757ea054e29a6d82aa656cb21c9c61961
4,309
pensjonssimulator
MIT License
principles/src/kotlin/isp/Searcher.kt
InternetED
206,913,193
false
null
package kotlin.isp /** *@date: 2019/1/6 : 下午 06:55 *@author: Ed *@email: <EMAIL> **/ class Searcher { fun searchActress(girl: BasePrettyGirl) { println("search a actress!") girl.goodLooking() girl.niceFigure() girl.greatTemperament() } }
0
Kotlin
0
0
381f02ba52dc0ae343ec34804f9c24b956246aae
282
Design-Pattern-Exercise
Apache License 2.0
server/src/main/kotlin/com/thoughtworks/archguard/code/module/domain/springcloud/feignclient/FeignClientService.kt
archguard
460,910,110
false
{"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
package com.thoughtworks.archguard.code.module.domain.springcloud.feignclient import com.thoughtworks.archguard.code.module.domain.JAnnotationRepository import com.thoughtworks.archguard.code.module.domain.springcloud.SpringCloudServiceRepository import org.archguard.protocol.http.HttpRequest import com.thoughtworks.archguard.code.module.domain.springcloud.httprequest.HttpRequestService import org.archguard.model.Dependency import org.archguard.protocol.feigh.FeignClient import org.archguard.protocol.feigh.FeignClientArg import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.lang.annotation.ElementType @Service class FeignClientService( val jAnnotationRepository: JAnnotationRepository, val springCloudServiceRepository: SpringCloudServiceRepository, val httpRequestService: HttpRequestService ) { private val log = LoggerFactory.getLogger(FeignClientService::class.java) fun getFeignClients(): List<FeignClient> { val feignClientAnnotations = jAnnotationRepository.getJAnnotationWithValueByName("feign.FeignClient") .filter { it.targetType == ElementType.TYPE.name } return feignClientAnnotations.map { FeignClient(it.targetId, FeignClientArg(it.values.orEmpty())) } } fun getFeignClientMethodDependencies(): List<Dependency<HttpRequest>> { val feignClientMethodDependencies = mutableListOf<Dependency<HttpRequest>>() val feignClients = getFeignClients() val httpRequestMethods = httpRequestService.getHttpRequests() val services = mutableMapOf<String, MutableList<HttpRequest>>() httpRequestMethods.forEach { val serviceName = springCloudServiceRepository.getServiceNameByMethodId(it.targetId) services[serviceName]?.add(it) ?: services.put(serviceName, mutableListOf(it)) } feignClients.forEach { val serviceName = it.arg.name val methods = springCloudServiceRepository.getMethodIdsByClassId(it.targetId) val callers = httpRequestMethods.filter { method -> method.targetId in methods } .map { method -> margeFeignClientArgToMethod(it.arg, method) } val callees = services.getOrDefault(serviceName, mutableListOf()) feignClientMethodDependencies.addAll(callers.flatMap { caller -> mapToMethod( caller, callees ).map { callee -> Dependency(caller, callee) } }) } return feignClientMethodDependencies } private fun margeFeignClientArgToMethod(feignClientArg: FeignClientArg, method: HttpRequest): HttpRequest { return method.apply { arg.paths = arg.paths.map { feignClientArg.path + it } } } private fun mapToMethod(caller: HttpRequest, callees: List<HttpRequest>): List<HttpRequest> { return callees.filter { it.arg.paths.any { calleePath -> caller.arg.paths.any { callerPath -> matchPath(callerPath, calleePath) } } && it.arg.methods.intersect(caller.arg.methods.toSet()).isNotEmpty() } } private fun matchPath(callerPath: String, calleePath: String): Boolean { val regex = Regex("""\{[^/]*}""") val callerPathStr = callerPath.replace(regex, "any") val calleePathRegex = calleePath.replace(regex, """[^/]*""") return Regex(calleePathRegex).matches(callerPathStr) } }
1
Kotlin
89
575
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
3,497
archguard
MIT License
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/apiTest/kotlin/com/android/build/api/apiTest/groovy/WorkerEnabledTransformationTest.kt
jomof
502,039,754
true
{"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.apiTest.groovy import com.android.build.api.apiTest.VariantApiBaseTest import com.android.build.api.variant.impl.BuiltArtifactsImpl import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome import org.junit.Test import java.io.File import kotlin.test.assertNotNull class WorkerEnabledTransformationTest: VariantApiBaseTest(TestType.Script, ScriptingLanguage.Groovy) { @Test fun workerEnabledTransformation() { given { tasksToInvoke.add(":app:copyDebugApks") addModule(":app") { buildFile = """ plugins { id 'com.android.application' } import java.io.Serializable import java.nio.file.Files import javax.inject.Inject import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.workers.WorkerExecutor import com.android.build.api.artifact.SingleArtifact import com.android.build.api.artifact.ArtifactTransformationRequest import com.android.build.api.variant.BuiltArtifact ${testingElements.getCopyApksTask()} android { ${testingElements.addCommonAndroidBuildLogic()} } androidComponents { onVariants(selector().all(), { variant -> TaskProvider copyApksProvider = tasks.register('copy' + variant.getName() + 'Apks', CopyApksTask) ArtifactTransformationRequest request = variant.artifacts.use(copyApksProvider) .wiredWithDirectories( { it.getApkFolder() }, { it.getOutFolder()}) .toTransformMany(SingleArtifact.APK.INSTANCE) copyApksProvider.configure { it.transformationRequest.set(request) } }) } """.trimIndent() testingElements.addManifest(this) } } withDocs { index = // language=markdown """ # Test TransformationRequest This sample shows how to transform the artifact. It copies the build apk to the specified directory. ## To Run ./gradlew copydebugApks """.trimIndent() } check { assertNotNull(this) Truth.assertThat(output).contains("BUILD SUCCESSFUL") val task = task(":app:copydebugApks") assertNotNull(task) Truth.assertThat(task.outcome).isEqualTo(TaskOutcome.SUCCESS) val outFolder = File(testProjectDir.root, "${testName.methodName}/app/build/intermediates/apk/copydebugApks") Truth.assertThat(outFolder.listFiles()?.asList()?.map { it.name }).containsExactly( "app-debug.apk", BuiltArtifactsImpl.METADATA_FILE_NAME ) } } }
1
null
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
3,948
CppBuildCacheWorkInProgress
Apache License 2.0
app/src/main/java/com/hcl/notflixpoc/core/network/di/NetworkModule.kt
lwysAndroid
582,826,801
false
{"Kotlin": 86707}
package com.hcl.notflixpoc.core.network.di import com.hcl.notflixpoc.core.network.retrofit.MoviesNetworkDataSource import com.hcl.notflixpoc.core.network.retrofit.RetrofitMoviesNetwork import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface NetworkModule { @Binds fun bindsMoviesNetworkDataSource( moviesNetworkDataSource: RetrofitMoviesNetwork ): MoviesNetworkDataSource }
0
Kotlin
0
1
8e63148fea7b7183cb82f0a52cee27c5d1b0fc22
520
NotflixPoC
Apache License 2.0
src/main/java/cn/zzstc/lzm/common/ui/vm/AddressListVm.kt
zz-xlab
226,285,515
false
null
package cn.zzstc.lzm.common.ui.vm import androidx.databinding.ObservableArrayList import androidx.lifecycle.ViewModel import cn.zzstc.lzm.common.BR import cn.zzstc.lzm.common.BaseApp import cn.zzstc.lzm.common.R import cn.zzstc.lzm.common.adapter.ListAdapter import cn.zzstc.lzm.common.data.entity.AddressType import cn.zzstc.lzm.common.data.entity.ServerAddress import cn.zzstc.lzm.common.data.model.ServerAddressModel class AddressListVm :ViewModel(){ private val serverAddressModel= ServerAddressModel() var adapter:ListAdapter<ServerAddress>?=null var serverAddressList = ObservableArrayList<ServerAddress>() init { serverAddressList.addAll(serverAddressModel.getAll()) adapter= ListAdapter(BaseApp.instance(), R.layout.item_server_address,BR.address,serverAddressList) } fun save(newAddress: CharSequence) { serverAddressModel.insert(ServerAddress(newAddress.toString(),AddressType.Other,false)) serverAddressList.clear() serverAddressList.addAll(serverAddressModel.getAll()) adapter!!.notifyDataSetChanged() } fun removeAddress(index:Int){ serverAddressModel.deleteById(serverAddressList[index]) serverAddressList.removeAt(index) adapter!!.notifyDataSetChanged() } }
0
Kotlin
1
9
743952fd1c875ef86ba21830c75c23b318ee5d16
1,289
xbrick-base
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/renderer/IpcMainEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron.renderer typealias IpcMainEvent = electron.core.IpcMainEvent
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
80
kotlin-wrappers
Apache License 2.0
core/src/main/kotlin/com/atlassian/migration/datacenter/core/fs/captor/QueueWatcher.kt
andrewpowell
269,599,826
true
{"TSQL": 599562, "Java": 455015, "Kotlin": 212757, "TypeScript": 182843, "JavaScript": 20409, "Python": 3813, "HTML": 2599, "Makefile": 2424, "Shell": 1292, "Dockerfile": 703}
package com.atlassian.migration.datacenter.core.fs.captor interface QueueWatcher { fun awaitQueueDrain() : Boolean }
0
null
0
0
a35f6282e4e596e454db773c0415dce6a21b9064
121
dc-migration-assistant
Apache License 2.0
app/src/main/java/com/example/photor/PhotorApplication.kt
aliciawyy
259,623,823
false
null
package com.example.photor import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build const val NOTIFICATION_CHANNEL_ID = "photor_poll" class PhotorApplication : Application() { override fun onCreate() { super.onCreate() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.notification_channel_name) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance) getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel) } } }
0
Kotlin
0
0
122d23b9dcbfbea6658ce4be4a00c99a84d42c05
714
photor
MIT License
HW18/src/main/kotlin/ru/otus/spring/kushchenko/hw18/service/LibraryService.kt
ElenaKushchenko
139,555,821
false
{"Kotlin": 821703, "HTML": 46397, "TypeScript": 32941, "CSS": 751, "Dockerfile": 203}
package ru.otus.spring.kushchenko.hw18.service /** * Created by Елена on Июль, 2018 */ interface LibraryService { fun takeBook(bookId: String, userId: String) fun returnBook(bookId: String, userId: String) }
0
Kotlin
0
0
0286627b4e66873c28d18174d125b63e5723e4f7
218
otus-spring-2018-06-hw
MIT License
common-util/src/main/kotlin/com/luggsoft/common/util/Memoized2.kt
luggsoft
257,786,821
false
null
package com.luggsoft.common.util import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap /** * TODO * * @param missingValue * @param TResult * @property block * @property cache */ data class Memoized2<TParam1, TParam2, out TResult>( private val block: (TParam1, TParam2) -> TResult, private val cache: ConcurrentMap<Tuple2<TParam1, TParam2>, TResult> = ConcurrentHashMap() ) : (TParam1, TParam2) -> TResult, Map<Tuple2<TParam1, TParam2>, TResult> by cache { /** * TODO * * @param missingValue * @return */ override fun invoke(param1: TParam1, param2: TParam2): TResult { val key = Tuple2(param1, param2) val provider = this.block.partial(param1, param2) return this.cache.getOrPut(key, provider) } }
0
Kotlin
0
0
bd0dafe8b359775412fdf508f3bbeedc87229262
814
common
MIT License
iyzi-co-sdk/src/main/java/com/android/iyzicosdk/data/model/request/IyziCoCreateDepositRegisteredCardRequest.kt
iyzico
403,959,301
false
null
package com.android.iyzicosdk.data.model.request import com.google.gson.annotations.SerializedName internal data class IyziCoCreateDepositRegisteredCardRequest( @SerializedName("amount") var amount: String?, @SerializedName("cardToken") var cardToken: String?, @SerializedName("channelType") var channelType: String?, @SerializedName("clientIp") var clientIp: String?, @SerializedName("currencyCode") var currencyCode: String?, @SerializedName("initialRequestId") var initialRequestId: String? )
2
Kotlin
0
1
7ef8da4d74ae7e1c5876723434d82c99173f8374
546
iyzico-sdk-android
MIT License
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/annotation/Annotation.kt
netomi
265,488,804
false
null
/* * Copyright (c) 2020-2022 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tinygears.bat.dexfile.annotation import org.tinygears.bat.dexfile.* import org.tinygears.bat.dexfile.TYPE_ANNOTATION_ITEM import org.tinygears.bat.dexfile.annotation.AnnotationVisibility.Companion.of import org.tinygears.bat.dexfile.annotation.visitor.AnnotationVisitor import org.tinygears.bat.dexfile.io.DexDataInput import org.tinygears.bat.dexfile.io.DexDataOutput import org.tinygears.bat.dexfile.value.EncodedAnnotationValue import org.tinygears.bat.dexfile.value.EncodedValue.Companion.readAnnotationValue import org.tinygears.bat.dexfile.visitor.ReferencedIDVisitor import java.util.* /** * A class representing an annotation item inside a dex file. * * @see <a href="https://source.android.com/devices/tech/dalvik/dex-format#annotation-item">annotation item @ dex format</a> */ @DataItemAnn( type = TYPE_ANNOTATION_ITEM, dataAlignment = 1, dataSection = true) class Annotation private constructor(visibility: AnnotationVisibility = AnnotationVisibility.BUILD, annotationValue: EncodedAnnotationValue = EncodedAnnotationValue.empty()) : DataItem() { var visibility: AnnotationVisibility = visibility private set var annotationValue: EncodedAnnotationValue = annotationValue private set override val isEmpty: Boolean get() = false override fun read(input: DexDataInput) { val visibilityValue = input.readUnsignedByte() visibility = of(visibilityValue) annotationValue = readAnnotationValue(input) } override fun write(output: DexDataOutput) { output.writeUnsignedByte(visibility.value) annotationValue.writeValue(output, 0) } fun accept(dexFile: DexFile, visitor: AnnotationVisitor) { visitor.visitAnnotation(dexFile, this) } internal fun referencedIDsAccept(dexFile: DexFile, visitor: ReferencedIDVisitor) { annotationValue.referencedIDsAccept(dexFile, visitor) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false val o = other as Annotation return visibility == o.visibility && annotationValue == o.annotationValue } override fun hashCode(): Int { return Objects.hash(visibility, annotationValue) } override fun toString(): String { return "Annotation[visibility='${visibility.simpleName}',value=${annotationValue}]" } companion object { fun of(visibility: AnnotationVisibility, value: EncodedAnnotationValue): Annotation { return Annotation(visibility, value) } internal fun read(input: DexDataInput): Annotation { val annotation = Annotation() annotation.read(input) return annotation } } }
1
null
3
10
5f5ec931c47dd34f14bd97230a29413ef1cf219c
3,501
bat
Apache License 2.0
JKodiWrapper/src/main/java/com/cf/jkodiwrapper/types/list/ListFilterMusicVideos.kt
cfe86
172,903,714
false
{"Kotlin": 548780}
package com.cf.jkodiwrapper.types.list import com.cf.jkodiwrapper.methods.video.params.filter.entity.musicvideos.AbstractMusicVideoFilter import com.cf.jkodiwrapper.types.list.filter.musicvideos.AndListFilterMusicVideos import com.cf.jkodiwrapper.types.list.filter.musicvideos.OrListFilterMusicVideos import com.cf.jkodiwrapper.types.list.filter.musicvideos.RuleListFilterMusicVideos abstract class ListFilterMusicVideos : AbstractMusicVideoFilter() { companion object { @JvmStatic fun getOrFilter(or: List<ListFilterMusicVideos>) = OrListFilterMusicVideos(or) @JvmStatic fun getAndFilter(and: List<ListFilterMusicVideos>) = AndListFilterMusicVideos(and) @JvmStatic fun getRuleFilter(rule: ListFilterRuleMusicVideos) = RuleListFilterMusicVideos(rule) } }
0
Kotlin
0
0
58a62f9cd275dd70eb0e054b1a959a6a8aec02b5
815
JKodiWrapper
MIT License
notification_filter/notification_filter_domain/src/main/java/ly/com/tahaben/notification_filter_domain/model/IntentSender.kt
tahaak67
508,754,612
false
{"Kotlin": 614590}
package ly.com.tahaben.notification_filter_domain.model data class IntentSender( val creatorPackage: String?, val creatorUid: Int? )
17
Kotlin
4
96
f7efae3a6d3b0ba52b3cdf082727f6beb8eb74d9
142
Farhan
Apache License 2.0
reaktive/src/jvmCommonMain/kotlin/com/badoo/reaktive/scheduler/CreateIoScheduler.kt
badoo
174,194,386
false
null
package com.badoo.reaktive.scheduler import java.util.concurrent.TimeUnit actual fun createIoScheduler(): Scheduler = ExecutorServiceScheduler( CachedExecutorServiceStrategy( keepAliveTimeoutMillis = TimeUnit.MINUTES.toMillis(1L), threadFactory = ThreadFactoryImpl("IO") ) )
8
null
49
956
c712c70be2493956e7057f0f30199994571b3670
325
Reaktive
Apache License 2.0
app/src/main/java/com/example/githubrepositories/model/Owner.kt
andreicampigotto
502,786,811
false
{"Kotlin": 20265}
package com.example.githubrepositories.model import com.google.gson.annotations.SerializedName import java.io.Serializable data class Owner( // @SerializedName("id") // val id: Long, @SerializedName("login") val login: String?, @SerializedName("avatar_url") val avatar_url: String?, // @SerializedName("name") // val name: String, // @SerializedName("html_url") // val html_url: String, // @SerializedName("bio") // val bio: String, ) : Serializable
0
Kotlin
0
1
174147a7f7f366e14fafd2f90fd708d8ac94e3b1
491
GitHubRepositories
MIT License
backend/data/src/main/kotlin/io/tolgee/formats/apple/in/strings/StringsFileProcessor.kt
tolgee
303,766,501
false
{"Kotlin": 3510751, "TypeScript": 2367440, "JavaScript": 18552, "MDX": 17612, "Shell": 12678, "Java": 9890, "Dockerfile": 9472, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.formats.apple.`in`.strings import io.tolgee.exceptions.ImportCannotParseFileException import io.tolgee.formats.ImportFileProcessor import io.tolgee.formats.ImportMessageConvertorType import io.tolgee.formats.StringWrapper import io.tolgee.formats.apple.`in`.guessLanguageFromPath import io.tolgee.formats.apple.`in`.guessNamespaceFromPath import io.tolgee.service.dataImport.processors.FileProcessorContext class StringsFileProcessor( override val context: FileProcessorContext, ) : ImportFileProcessor() { private var state = State.OUTSIDE private var key: String? = null private var value: String? = null private var wasLastCharEscape = false private var currentComment: StringBuilder? = null private var lastChar: Char? = null override fun process() { parseFileToContext() context.namespace = guessNamespaceFromPath(context.file.name) } private fun parseFileToContext() { context.file.data.decodeToString().forEachIndexed { index, char -> if (!wasLastCharEscape && char == '\\') { wasLastCharEscape = true return@forEachIndexed } when (state) { State.OUTSIDE -> { if (char == '\"') { state = State.INSIDE_KEY key = "" } if (char == '=') { if (key == null) { throw ImportCannotParseFileException(context.file.name, "Unexpected '=' character on position $index") } state = State.EXPECT_VALUE } if (char == '/' && lastChar == '/') { currentComment = null state = State.INSIDE_INLINE_COMMENT } if (lastChar == '/' && char == '*') { currentComment = null state = State.INSIDE_BLOCK_COMMENT } } State.EXPECT_VALUE -> { if (char == '\"') { state = State.INSIDE_VALUE value = "" } } State.INSIDE_KEY -> { when { char == '\"' && !wasLastCharEscape -> state = State.OUTSIDE wasLastCharEscape && char == 'n' -> key += "\n" wasLastCharEscape && char == 'r' -> key += "\r" else -> key += char } } State.INSIDE_VALUE -> { when { char == '\"' && !wasLastCharEscape -> { state = State.OUTSIDE onPairParsed() key = null value = null } wasLastCharEscape && char == 'n' -> value += "\n" wasLastCharEscape && char == 'r' -> value += "\r" else -> value += char } } State.INSIDE_INLINE_COMMENT -> { // inline comment is ignored if (char == '\n' && !wasLastCharEscape) { state = State.OUTSIDE } } State.INSIDE_BLOCK_COMMENT -> { when { lastChar == '*' && char == '/' && !wasLastCharEscape -> { currentComment?.let { it.deleteCharAt(it.length - 1) } state = State.OUTSIDE } wasLastCharEscape && char == 'n' -> addToCurrentComment("\n") wasLastCharEscape && char == 'r' -> addToCurrentComment("\r") else -> addToCurrentComment(char.toString()) } } } lastChar = char wasLastCharEscape = false } } private fun addToCurrentComment(char: CharSequence) { currentComment = (currentComment ?: StringBuilder()).also { it.append(char) } } private fun onPairParsed() { val converted = ImportMessageConvertorType.STRINGS.importMessageConvertor!!.convert( rawData = value, languageTag = languageName, convertPlaceholders = context.importSettings.convertPlaceholdersToIcu, isProjectIcuEnabled = context.projectIcuPlaceholdersEnabled, ).message context.addKeyDescription(key ?: return, currentComment?.toString()) context.addTranslation( key ?: return, languageName, converted, rawData = StringWrapper(value), convertedBy = ImportMessageConvertorType.STRINGS, ) currentComment = null } private val languageName: String by lazy { guessLanguageFromPath(context.file.name) } enum class State { OUTSIDE, INSIDE_INLINE_COMMENT, INSIDE_BLOCK_COMMENT, INSIDE_KEY, INSIDE_VALUE, EXPECT_VALUE, } }
155
Kotlin
85
1,156
96654f5afa4eb9203eee41f8318576fcc61490c1
4,451
tolgee-platform
Apache License 2.0
live/test/src/commonTest/kotlin/cinematic/internal/Effect.kt
aSoft-Ltd
630,232,457
false
{"Kotlin": 47216, "Java": 2426}
package cinematic.internal internal class Effect(private val fn: () -> Unit) : SignalDependency { override fun execute() { fn() } override fun update() { execute() } }
0
Kotlin
0
0
0b22cb99480edea8a50039c4c6db6d5ea791e568
202
cinematic
MIT License
skellig-test-step-processing/src/main/kotlin/org/skellig/teststep/processing/value/extractor/ToNumberValueExtractor.kt
skellig-framework
263,021,995
false
{"Kotlin": 793363, "CSS": 525608, "Java": 185441, "HTML": 11313, "FreeMarker": 9740, "ANTLR": 2041}
package org.skellig.teststep.processing.value.extractor import org.skellig.teststep.processing.exception.ValueExtractionException import java.math.BigDecimal abstract class ToNumberTestStepValueExtractor : ValueExtractor { protected fun getParseException(value: Any?): ValueExtractionException = ValueExtractionException("Failed to extract numeric value from type ${value?.javaClass?.simpleName} for value: $value") } class ToIntTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toInt() ?: (value as? String ?: throw getParseException(value)).toInt() } override fun getExtractFunctionName(): String { return "toInt" } } class ToByteTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toByte() ?: (value as? String ?: throw getParseException(value)).toByte() } override fun getExtractFunctionName(): String { return "toByte" } } class ToShortTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toShort() ?: (value as? String ?: throw getParseException(value)).toShort() } override fun getExtractFunctionName(): String { return "toShort" } } class ToLongTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toLong() ?: (value as? String ?: throw getParseException(value)).toLong() } override fun getExtractFunctionName(): String { return "toLong" } } class ToFloatTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toFloat() ?: (value as? String ?: throw getParseException(value)).toFloat() } override fun getExtractFunctionName(): String { return "toFloat" } } class ToDoubleTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Number)?.toDouble() ?: (value as? String ?: throw getParseException(value)).toDouble() } override fun getExtractFunctionName(): String { return "toDouble" } } class ToBigDecimalTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return when (value) { is BigDecimal -> value is Number -> BigDecimal(value.toString()) else -> (value as? String ?: throw getParseException(value)).toBigDecimal() } } override fun getExtractFunctionName(): String { return "toBigDecimal" } } class ToBooleanTestStepValueExtractor : ToNumberTestStepValueExtractor() { override fun extractFrom(name: String, value: Any?, args: Array<Any?>): Any { return (value as? Boolean)?: (value as? String ?: throw getParseException(value)).toBoolean() } override fun getExtractFunctionName(): String { return "toBoolean" } }
14
Kotlin
0
2
1378e884bfa9dcd0ef0c760fb870c61691ede2dc
3,411
skellig-core
Apache License 2.0
src/main/kotlin/com/abrahammenendez/personalwebsite/utils/WithAuditTimestamps.kt
abrahammenendez
541,302,910
false
{"Kotlin": 13293}
package com.abrahammenendez.personalwebsite.utils import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent import org.springframework.stereotype.Component import java.time.Instant /** * This interface provides `createdOn` and `updatedOn` timestamp fields. * When this object is saved to MongoDB, these fields are automatically set and updated using [AuditTimestampsEventListener]. * * Note that the `updatedOn` field will be set on any save operation, irrespective of whether the fields on the object have changed. * * Ensure that you override the required variables in your constructor: * ``` * override var createdOn: Instant? = null, * override var updatedOn: Instant? = null, * ``` * * @property createdOn When this object was first persisted * @property updatedOn When this object was last persisted * * @see AuditTimestampsEventListener */ interface WithAuditTimestamps { var createdOn: Instant? var updatedOn: Instant? } /** * An event listener that updates the `createdOn` and `updatedOn` fields of objects * using the [WithAuditTimestamps] interface, before they are serialised and saved to MongoDB. * * The `updatedOn` field will be set on any save operation, irrespective of whether the fields on the object have changed. * The `createdOn` field will only be set the first time it is null * * @see WithAuditTimestamps */ @Component class AuditTimestampsEventListener : AbstractMongoEventListener<WithAuditTimestamps>() { override fun onBeforeConvert(event: BeforeConvertEvent<WithAuditTimestamps>) { val now = Instant.now() event.source.updatedOn = now if (event.source.createdOn == null) { event.source.createdOn = now } super.onBeforeConvert(event) } }
2
Kotlin
0
0
a035a4925e060441ed0d4ec292bcd8a71fb4ff69
1,870
personal-website-be
MIT License
template/core/data/src/main/kotlin/core/data/datasource/network/NetworkSource.kt
kotlitecture
738,057,168
false
{"Kotlin": 385471, "HTML": 891}
package core.data.datasource.network import core.data.datasource.DataSource import kotlinx.coroutines.flow.Flow /** * Interface for accessing network-related information. */ interface NetworkSource : DataSource { /** * Retrieves a flow representing the online status of the device. * * @return A flow emitting Boolean values indicating the online status. */ fun isOnline(): Flow<Boolean> /** * Retrieves the IP address of the device. * * @return The IP address of the device, or null if unavailable. */ suspend fun getIp(): String? }
0
Kotlin
0
0
4ba09e90973f8110cf22e645ce8727323e7d07e5
596
template-android-compose
MIT License
src/main/kotlin/ru/ereshkin_a_v/deanerybackend/rating/entities/RatingListElement.kt
AlexEreh
793,810,424
false
{"Kotlin": 55276}
package ru.ereshkin_a_v.deanerybackend.rating.entities import jakarta.persistence.* import ru.ereshkin_a_v.deanerybackend.model.util.BaseEntity import ru.ereshkin_a_v.deanerybackend.student.entities.Student @Entity class RatingListElement( @ManyToOne(cascade = [CascadeType.ALL]) @JoinColumn(name = "rating_list_id") var ratingList: RatingList? = null, @ManyToOne @JoinColumn(name = "student_id") var student: Student? = null, @Column(name = "score") var score: Int? = null ): BaseEntity()
0
Kotlin
0
0
d4e4dcb831d3c9653caa90725a85ba406deae32d
523
deanery-backend
Do What The F*ck You Want To Public License
ksolana/src/main/java/com/guness/ksolana/rpc/Cluster.kt
guness
435,816,472
false
null
package com.guness.ksolana.rpc /** * Created by guness on 6.12.2021 19:44 */ enum class Cluster(val endpoint: String) { DEVNET("https://api.devnet.solana.com"), TESTNET("https://api.testnet.solana.com"), MAINNET("https://api.mainnet-beta.solana.com"); }
0
Kotlin
1
1
5e1060efece78f9a6e4345cc69390ddc5897a57a
270
kSolana
MIT License
app/src/main/java/com/netizenchar/view/BotWebActivity.kt
menma977
261,123,574
false
{"Kotlin": 49579}
package com.netizenchar.view import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.ProgressBar import android.widget.TextView import com.netizenchar.MainActivity import com.netizenchar.R class BotWebActivity : AppCompatActivity() { private lateinit var balance: TextView private lateinit var progressBar: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bot_web) balance = findViewById(R.id.textViewBalance) progressBar = findViewById(R.id.progressBar) Thread() { var time = System.currentTimeMillis() var i = 0 while (i in 0..10) { val delta = System.currentTimeMillis() - time if (delta >= 1000) { time = System.currentTimeMillis() if (i == 100) { progressBar.progress = 100 break } else { progressBar.progress = i } i++ } } runOnUiThread { progressBar.visibility = ProgressBar.GONE balance.text = intent.getSerializableExtra("profit").toString() } }.start() } override fun onBackPressed() { super.onBackPressed() val goTo = Intent(this, MainActivity::class.java) startActivity(goTo) finish() } }
0
Kotlin
0
0
32cff9d1427a3394f62e8d5b3c812159b536cb5d
1,374
Netizen-Trades
Apache License 2.0
learnpaging/src/main/java/com/simplation/learnpaging/paging/MovieAdapter.kt
Simplation
324,966,218
false
null
package com.simplation.learnpaging.paging import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.simplation.learnpaging.R import com.simplation.learnpaging.model.Movie import com.squareup.picasso.Picasso class MovieAdapter(diffCallback: DiffUtil.ItemCallback<Movie>) : PagedListAdapter<Movie, MovieAdapter.MovieViewHolder>(diffCallback) { inner class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val ivImage: ImageView = itemView.findViewById(R.id.ivImage) val tvTitle: TextView = itemView.findViewById(R.id.tvTitle) val tvYear: TextView = itemView.findViewById(R.id.tvYear) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.movie_item, parent, false) return MovieViewHolder(view) } override fun onBindViewHolder(holder: MovieViewHolder, position: Int) { val movie = getItem(position) if (movie != null) { Picasso.get().load(movie.images.small) .placeholder(android.R.drawable.btn_default_small) .error(android.R.drawable.stat_notify_error) .into(holder.ivImage) holder.tvTitle.text = movie.title holder.tvYear.text = movie.year } else { holder.ivImage.setImageResource(android.R.drawable.btn_default_small) holder.tvTitle.text = "" holder.tvYear.text = "" } } }
0
Kotlin
0
1
901858d2b6cb98770182701a8c446ad1a0b0f0db
1,757
LearnJetpack
Apache License 2.0
demo/desktop/src/desktopMain/kotlin/com/mylibrary/demo/Main.kt
Qawaz
609,083,998
false
null
package com.mylibrary.demo import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.window.singleWindowApplication import com.wakaztahir.common.MDPreviewEditor import com.wakaztahir.common.rememberColorScheme fun main() = singleWindowApplication(title = "Markdown Editor") { MaterialTheme(rememberColorScheme()) { val scrollState = rememberScrollState() Box(modifier = Modifier.fillMaxSize()) { MDPreviewEditor(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter(scrollState = scrollState), ) } } }
0
Kotlin
0
0
452a1af1b43a6360371c09b76294c3de6d005541
1,194
audioplayer-compose
MIT License
subprojects/test-runner/test-inhouse-runner/src/main/kotlin/com/avito/android/runner/ReportUncaughtHandler.kt
avito-tech
230,265,582
false
{"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
package com.avito.android.runner import com.avito.logger.LoggerFactory import com.avito.logger.create internal class ReportUncaughtHandler( loggerFactory: LoggerFactory, private val globalExceptionHandler: Thread.UncaughtExceptionHandler?, private val nonCriticalErrorMessages: Set<String> ) : Thread.UncaughtExceptionHandler { private val logger = loggerFactory.create<ReportUncaughtHandler>() override fun uncaughtException(t: Thread, e: Throwable) { if (e.message in nonCriticalErrorMessages) { logger.verbose("Non critical error caught by ReportUncaughtHandler. ${e.message}") } else { logger.warn("Application crashed", e) InHouseInstrumentationTestRunner.instance.reportUnexpectedIncident(incident = e) globalExceptionHandler?.uncaughtException(t, e) } } }
4
Kotlin
50
414
4dc43d73134301c36793e49289305768e68e645b
863
avito-android
MIT License
app/src/main/java/com/chatspring/appsetting/LoginState.kt
goatpang
642,752,766
false
{"Kotlin": 134006}
package com.chatspring.appsetting import android.app.Application class LoginState : Application() { companion object{ var isLoggedIn: Boolean = false } }
0
Kotlin
1
1
23f41e7014704d6298d683b1904b884faddb1a8c
169
ChatSpring
Apache License 2.0
core/src/main/kotlin/uk/tvidal/kraft/message/raft/AppendAckMessage.kt
tvidal-net
99,751,401
false
null
package uk.tvidal.kraft.message.raft import uk.tvidal.kraft.RaftNode import uk.tvidal.kraft.message.raft.RaftMessageType.APPEND_ACK data class AppendAckMessage( override val from: RaftNode, final override val term: Long, val ack: Boolean, val matchIndex: Long ) : AbstractRaftMessage(APPEND_ACK) { override fun text() = "ack=$ack matchIndex=$matchIndex" override fun toString() = super.toString() }
1
Kotlin
0
0
9cfca67330b27c1f2f834dc430d3a369d2538255
430
kraft
MIT License
13-apigateway/apigateway-idently/src/main/kotlin/com/nao4j/otus/architect/apigateway/idently/service/TokenService.kt
nao4j
306,106,999
false
null
package com.nao4j.otus.architect.apigateway.idently.service import com.nimbusds.jose.jwk.JWKSet import com.nimbusds.jwt.JWT interface TokenService { fun generateJwt(payload: TokenPayload): JWT fun generateJwk(): JWKSet } data class TokenPayload(val login: String, val firstName: String, val lastName: String)
1
null
1
1
b20089772dfccd6b4e7bb5a1c40f9143c27e6028
321
software-architect-otus
MIT License
plugins/kotlin/project-tests/project-tests-base/test/org/jetbrains/kotlin/idea/project/test/base/actions/executors/ProjectActionExecutor.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.project.test.base.actions.executors import com.intellij.openapi.application.runWriteAction import com.intellij.psi.PsiManager import org.jetbrains.kotlin.idea.project.test.base.actions.ActionExecutionResultError import org.jetbrains.kotlin.idea.project.test.base.metrics.MetricsCollector import org.jetbrains.kotlin.idea.project.test.base.metrics.MetricsData import org.jetbrains.kotlin.idea.performance.tests.utils.commitAllDocuments abstract class ProjectActionExecutor<R : Any, CONTEXT> { protected abstract fun performAction(context: CONTEXT, collector: MetricsCollector, data: ProjectActionExecutorData): R? protected abstract fun checkResultForValidity(result: R, context: CONTEXT): ActionExecutionResultError.InvalidActionExecutionResult? protected abstract fun setUp(data: ProjectActionExecutorData): CONTEXT protected abstract fun tearDown(context: CONTEXT, data: ProjectActionExecutorData) fun execute(data: ProjectActionExecutorData): MetricsData { val context = setUp(data) prepare(data) return performActionAndGetMetricsData(context, data) } private fun prepare(data: ProjectActionExecutorData) { commitAllDocuments() runWriteAction { invalidateBaseCaches(data) data.profile.frontendConfiguration.invalidateCaches(data.project) } System.gc() } private fun performActionAndGetMetricsData(context: CONTEXT, data: ProjectActionExecutorData): MetricsData { val collector = MetricsCollector(data.iteration) try { val result = performAction(context, collector, data) validateResult(result, context, collector, data) } finally { tearDown(context, data) } return collector.getMetricsData() } private fun invalidateBaseCaches(data: ProjectActionExecutorData) { PsiManager.getInstance(data.project).apply { dropResolveCaches() dropPsiCaches() } } private fun validateResult( result: R?, context: CONTEXT, collector: MetricsCollector, data: ProjectActionExecutorData, ) { if (result != null && data.profile.checkForValidity) { val validationResult = checkResultForValidity(result, context) if (validationResult != null) { collector.reportFailure(validationResult) } } } }
236
null
4946
15,650
32f33d7b7126014b860912a5b6088ffc50fc241d
2,597
intellij-community
Apache License 2.0
native/native.tests/testData/framework/kt56233/Kt56233.kt
JetBrains
3,432,266
false
null
enum class SimpleEnum { ONE, TWO }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
43
kotlin
Apache License 2.0
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/flows/flow_intermediate_operators/2_filter.kt
regxl2
775,843,577
false
{"Kotlin": 283103}
package com.lukaslechner.coroutineusecasesonandroid.flows.flow_intermediate_operators import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flowOf suspend fun main(){ flowOf(1, 2, 3, 4, 5) .filter{ value -> value%2==1 } .collect{ emittedValue -> println(emittedValue) } // by using filter operator, we have filtered out the values of flow which are odd flowOf("Abhishek", "Gaurav", "Ashish", "Prasanjeet", "Rishab", null) .filterNotNull() .collect{ emittedValue -> println(emittedValue) } // by using filerNotNull operator, we can filter the values which are not null. flowOf<Any>(1, "A", 2, "B", 3, "C") .filterIsInstance<Int>() .collect{emittedValue -> println(emittedValue)} // by using filterIsInstance, we can filter out values based on their type. // for example, in this case, it is filter the values of Int type. }
0
Kotlin
0
0
3c88fd943d408ffae7ae429b9f05607d21da2f38
1,011
coroutine-and-flows
Apache License 2.0
sweetdependency-gradle-plugin/src/main/java/com/highcapable/sweetdependency/manager/transaction/DependencyMigrationTemplateTransaction.kt
HighCapable
643,245,749
false
{"Kotlin": 298044}
/* * SweetDependency - An easy autowire and manage dependencies Gradle plugin. * Copyright (C) 2019-2024 HighCapable * https://github.com/HighCapable/SweetDependency * * Apache License Version 2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is created by fankes on 2023/6/1. */ package com.highcapable.sweetdependency.manager.transaction import com.highcapable.sweetdependency.SweetDependency import com.highcapable.sweetdependency.document.DependencyDocument import com.highcapable.sweetdependency.document.RootConfigDocument import com.highcapable.sweetdependency.gradle.entity.DependencyVersion import com.highcapable.sweetdependency.gradle.factory.fullName import com.highcapable.sweetdependency.gradle.factory.libraries import com.highcapable.sweetdependency.gradle.factory.plugins import com.highcapable.sweetdependency.gradle.helper.GradleHelper import com.highcapable.sweetdependency.gradle.wrapper.type.LibraryDependencyType import com.highcapable.sweetdependency.manager.GradleTaskManager import com.highcapable.sweetdependency.manager.content.Dependencies import com.highcapable.sweetdependency.plugin.config.content.SweetDependencyConfigs import com.highcapable.sweetdependency.utils.debug.SLog import com.highcapable.sweetdependency.utils.parseFileSeparator import com.highcapable.sweetdependency.utils.toFile import com.highcapable.sweetdependency.utils.yaml.Yaml /** * 依赖迁移模版管理类 */ internal object DependencyMigrationTemplateTransaction { /** 模板文件头部内容 */ private const val TEMPLATE_FILE_HEADER_CONTENT = """ # SweetDependency project configuration template file # Template files are automatically generated using Gradle task "${GradleTaskManager.CREATE_DEPENDENCIES_MIGRATION_TEMPLATE_TASK_NAME}" # The automatically generated configuration is determined according to your project # Please adjust these contents at any time in actual use, the generated content is for reference only, and its availability is unknown # You can copy the content of the corresponding node in the template file to the project configuration file, and then delete this file # You can visit ${SweetDependency.PROJECT_URL} for more help # # SweetDependency 项目配置模板文件 # 模版文件是使用 Gradle Task "${GradleTaskManager.CREATE_DEPENDENCIES_MIGRATION_TEMPLATE_TASK_NAME}" 自动生成的 # 自动生成的配置根据你的项目决定,请在实际使用中随时调整这些内容,生成的内容仅供参考,其可用性未知 # 你可以复制模板文件中对应节点的内容到项目配置文件,然后删除此文件 # 你可以前往 ${SweetDependency.PROJECT_URL} 以获得更多帮助 """ /** 模板文件扩展名 */ private const val TEMPLATE_FILE_EXT_NAME = "template.yaml" /** 模板文件头部内容 */ private val templateFileHeaderContent = TEMPLATE_FILE_HEADER_CONTENT.trimIndent() /** 排除的部分内置插件名称前缀数组 */ private val exclusionPluginPrefixs = arrayOf("org.gradle", "com.android.internal") /** 生成模板使用的文档实例 */ private val document = RootConfigDocument() /** 创建模版 */ internal fun createTemplate() { SLog.info("Starting analyze projects dependencies structure", SLog.ANLZE) GradleHelper.allProjects.forEach { subProject -> val projectName = subProject.fullName() subProject.plugins().onEach { if (exclusionPluginPrefixs.any { prefix -> it.id.startsWith(prefix) }) return@onEach if (Dependencies.hasPlugin { key, _ -> key.current == it.id }) return@onEach if (document.plugins == null) document.plugins = mutableMapOf() val declareDocument = DependencyDocument(version = DependencyVersion.AUTOWIRE_VERSION_NAME) document.plugins?.set(it.id, declareDocument) }.apply { if (isNotEmpty()) SLog.info("Found $size plugins in project \"$projectName\"", SLog.LINK) } subProject.libraries().onEach { if (Dependencies.hasLibrary { key, _ -> key.current == it.toString() }) return@onEach if (document.libraries == null) document.libraries = mutableMapOf() if (it.type == LibraryDependencyType.EXTERNAL) document.libraries?.also { entities -> if (entities[it.groupId] == null) entities[it.groupId] = mutableMapOf() val declareDocument = DependencyDocument(version = it.version.existed) entities[it.groupId]?.set(it.artifactId, declareDocument) } }.apply { if (isNotEmpty()) SLog.info("Found $size libraries in project \"$projectName\"", SLog.LINK) } }; saveTemplateFile() } /** 保存模版到文件 */ private fun saveTemplateFile() { if (document.plugins?.isEmpty() == true) document.plugins = null if (document.libraries?.isEmpty() == true) document.libraries = null if (document.plugins?.isNotEmpty() == true || document.libraries?.isNotEmpty() == true) { val templateFilePath = SweetDependencyConfigs.configs.configFilePath .let { it.toFile().let { e -> "${e.parent}/${e.name.split(".")[0]}.$TEMPLATE_FILE_EXT_NAME" } }.parseFileSeparator() Yaml.parseToFile(document, templateFilePath) { "$templateFileHeaderContent\n\n${replace("\"", "")}" } SLog.info("Template file is created at $templateFilePath", SLog.DONE) document.plugins?.clear() document.libraries?.clear() } else SLog.info("No suitable dependencies can be found in all projects to create template file, nothing to do", SLog.IGNORE) } }
0
Kotlin
0
32
2cbf00e997d1788caa398df7b899d96f571caa87
5,965
SweetDependency
Apache License 2.0
library/src/main/kotlin/ca/allanwang/kau/kpref/KPref.kt
ziacto
93,989,073
true
{"Kotlin": 86168, "Java": 1168}
package ca.allanwang.kau.kpref import android.content.Context import android.content.SharedPreferences /** * Created by <NAME> on 2017-06-07. */ open class KPref { lateinit private var c: Context lateinit internal var PREFERENCE_NAME: String private var initialized = false fun initialize(c: Context, preferenceName: String) { if (initialized) throw KPrefException("KPref object $preferenceName has already been initialized; please only do so once") initialized = true this.c = c.applicationContext PREFERENCE_NAME = preferenceName } internal val sp: SharedPreferences by lazy { if (!initialized) throw KPrefException("KPref object has not yet been initialized; please initialize it with a context and preference name") c.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) } internal val prefMap: MutableMap<String, KPrefDelegate<*>> = mutableMapOf() fun reset() { prefMap.values.forEach { it.invalidate() } } }
0
Kotlin
0
0
c00f9e2674f5109a64f1f50873ce08089a2fce33
1,022
KAU
Apache License 2.0
app/src/main/java/com/grindr/android/framerate/ui/MyBaseFragment.kt
Wesley-Ong
244,570,817
false
null
package com.grindr.android.framerate.ui import android.os.Bundle import androidx.fragment.app.Fragment import com.grindr.android.framerate.tracer.registerTracer /** * Got called when fragment visibility changed. */ interface OnHiddenChangedListener { fun onHidden(hidden: Boolean) } abstract class MyBaseFragment : Fragment() { private val visibilityChangedListeners = ArrayList<OnHiddenChangedListener>() override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) visibilityChangedListeners.forEach { it.onHidden(hidden) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) registerTracer() } override fun onDestroy() { super.onDestroy() visibilityChangedListeners.clear() } fun addOnHiddenChangedListener(l: OnHiddenChangedListener) { visibilityChangedListeners.add(l) } fun removeOnHiddenChangedListener(l: OnHiddenChangedListener) { visibilityChangedListeners.remove(l) } }
0
Kotlin
0
0
dd68d67786f6bcbb19acbeef44f8ddc2efb5d0c1
1,057
AndroidFramerateSample
Apache License 2.0
shared/src/commonTest/kotlin/ru/olegivo/repeatodo/list/presentation/TasksSorterByCompletionTest.kt
olegivo
503,480,894
false
null
/* * Copyright (C) 2023 Oleg Ivashchenko <[email protected]> * * This file is part of RepeaTodo. * * RepeaTodo is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * RepeaTodo PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * RepeaTodo. */ package ru.olegivo.repeatodo.list.presentation import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import ru.olegivo.repeatodo.domain.FakeDateTimeProvider import ru.olegivo.repeatodo.domain.models.randomTask import ru.olegivo.repeatodo.kotest.FreeSpec import ru.olegivo.repeatodo.randomInt import ru.olegivo.repeatodo.randomString import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds class TasksSorterByCompletionTest: FreeSpec() { private val dateTimeProvider = FakeDateTimeProvider() init { "instance" - { val isTaskCompleted = FakeIsTaskCompletedUseCase() val tasksSorter: TasksSorter = TasksSorterByCompletion( dateTimeProvider = dateTimeProvider, isTaskCompleted = isTaskCompleted ) "empty -> empty" { tasksSorter.sort(emptyList()).shouldBeEmpty() } "not completed, then completed" { val thresholdMinutes = randomInt(from = 10, until = 30) val threshold = dateTimeProvider.getCurrentInstant() - thresholdMinutes.minutes isTaskCompleted.considerAsCompletedAfter = threshold val completed = createTask(minutesAgo = thresholdMinutes - 1) val notCompleted = completed.copy(lastCompletionDate = getInstant(minutesAgo = thresholdMinutes)) val tasks = listOf(completed, notCompleted) tasksSorter.sort(tasks) .shouldContainExactly(notCompleted, completed) } "never completed, then completed" { val completed = createTask(minutesAgo = randomInt()) val neverCompleted = completed.copy(lastCompletionDate = null) val tasks = listOf(completed, neverCompleted) tasksSorter.sort(tasks) .shouldContainExactly(neverCompleted, completed) } "never completed: by shortest periodicity" { val periodicity1 = createTask( minutesAgo = null, daysPeriodicity = 1 ) val periodicity2 = createTask( minutesAgo = null, daysPeriodicity = 2 ) val tasks = listOf(periodicity2, periodicity1) tasksSorter.sort(tasks) .shouldContainExactly(periodicity1, periodicity2) } "never completed + same periodicity: by title" { val title1 = createTask( minutesAgo = null, daysPeriodicity = 1, title = "1" ) val title2 = createTask( minutesAgo = null, daysPeriodicity = 1, title = "2" ) val tasks = listOf(title2, title1) tasksSorter.sort(tasks) .shouldContainExactly(title1, title2) } "completed: by oldest last completion (differs by days)" { val completedNow = createTask( minutesAgo = 0 ) val completedInPreviousDay = completedNow.copy( lastCompletionDate = dateTimeProvider.getCurrentStartOfDayInstant() - 1.seconds ) val tasks = listOf(completedNow, completedInPreviousDay) tasksSorter.sort(tasks) .shouldContainExactly(completedInPreviousDay, completedNow) } "completed + same last completion: by shortest periodicity" { val periodicity1 = createTask( minutesAgo = 1, daysPeriodicity = 1 ) val periodicity2 = createTask( minutesAgo = 1, daysPeriodicity = 2 ) val tasks = listOf(periodicity2, periodicity1) tasksSorter.sort(tasks) .shouldContainExactly(periodicity1, periodicity2) } "completed + same last completion + same periodicity: by title" { val title1 = createTask( minutesAgo = 1, daysPeriodicity = 1, title = "1" ) val title2 = createTask( minutesAgo = 1, daysPeriodicity = 1, title = "2" ) val tasks = listOf(title2, title1) tasksSorter.sort(tasks) .shouldContainExactly(title1, title2) } } } private fun createTask( minutesAgo: Int?, daysPeriodicity: Int = randomInt(), title: String = randomString() ) = randomTask().copy( lastCompletionDate = minutesAgo?.let { getInstant(it) }, daysPeriodicity = daysPeriodicity, title = title ) private fun getInstant(minutesAgo: Int) = dateTimeProvider.getCurrentInstant() - minutesAgo.minutes }
2
Kotlin
0
0
611dbe643164eb1f48791243eef68b4ef09c1ee8
5,961
RepeaTodo
MIT License
src/Day02.kt
F-bh
579,719,291
false
{"Kotlin": 5785}
enum class Result (val points: Int) { Win(6), Draw(3), Lose(0); companion object { fun parse(input: Char): Result { return mapOf( 'X' to Lose, 'Y' to Draw, 'Z' to Win )[input]!! } } } enum class Choice(val points: Int) { Rock(1), Paper(2), Scissor(3); operator fun plus(enemyChoice: Choice): Int { return lookupTwoChoice[Pair(this, enemyChoice)]!!.points + this.points } companion object { fun parse(input: Char): Choice? { return mapOf( 'A' to Rock, 'B' to Paper, 'C' to Scissor, )[input] } private val lookupTwoChoice = mapOf( Pair(Rock, Scissor) to Result.Win, Pair(Rock, Rock) to Result.Draw, Pair(Rock, Paper) to Result.Lose, Pair(Paper, Rock) to Result.Win, Pair(Paper, Paper) to Result.Draw, Pair(Paper, Scissor) to Result.Lose, Pair(Scissor, Paper) to Result.Win, Pair(Scissor, Scissor) to Result.Draw, Pair(Scissor, Rock) to Result.Lose, ) val lookupChoiceAndRes = lookupTwoChoice.entries.associate { (k, v) -> Pair(k.second, v) to k.first } } } fun main() { val input = readDayInput(2) .map { line -> line.split(" ") } .map {strings -> Pair(strings[0].toCharArray()[0], strings[1].toCharArray()[0])} //part 1 println(p1(input)) //part 2 println(p2(input)) } fun p1(input: List<Pair<Char, Char>>): Int { fun parse(input: Char): Choice { return Choice.parse(input) ?: mapOf( 'X' to Choice.Rock, 'Y' to Choice.Paper, 'Z' to Choice.Scissor, )[input]!! } return input.sumOf { pair -> parse(pair.second) + parse(pair.first) } } fun p2(input: List<Pair<Char, Char>>): Int { return input .map { pair -> Pair(Choice.parse(pair.first), Result.parse(pair.second)) } .sumOf { duel -> duel.second.points + Choice.lookupChoiceAndRes[duel]!!.points } }
0
Kotlin
0
0
19fa2db8842f166daf3aaffd201544658f41d9e0
2,195
Christmas2022
Apache License 2.0
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/ui/views/LabelledSpinner.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.framework.ui.views import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.appcompat.widget.LinearLayoutCompat import androidx.core.content.res.use import ch.rmy.android.framework.databinding.LabelledSpinnerBinding import ch.rmy.android.framework.extensions.indexOfFirstOrNull import ch.rmy.android.framework.extensions.layoutInflater import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull class LabelledSpinner @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : LinearLayoutCompat(context, attrs, defStyleAttr) { private val binding = LabelledSpinnerBinding.inflate(layoutInflater, this) private val _selectionChanges = MutableStateFlow<String?>(null) val selectionChanges: Flow<String> = _selectionChanges.asStateFlow().filterNotNull() var items: List<Item> = emptyList() set(value) { field = value binding.spinner.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, value.map { it.value ?: it.key }) } fun setItemsFromPairs(items: List<Pair<String, String>>) { this.items = items.map { (key, value) -> Item(key, value) } } fun setItemsFromPairs(vararg items: Pair<String, String>) { setItemsFromPairs(items.asList()) } init { orientation = VERTICAL binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, id: Long) { selectedItem = items[position].key } override fun onNothingSelected(p0: AdapterView<*>?) { } } if (attrs != null) { context.obtainStyledAttributes(attrs, ATTRIBUTE_IDS).use { a -> binding.label.text = a.getText(ATTRIBUTE_IDS.indexOf(android.R.attr.text)) ?: "" } } } var selectedItem: String = "" set(value) { val index = items .indexOfFirstOrNull { it.key == value } ?: return val before = field field = value binding.spinner.setSelection(index) if (before != value && before.isNotEmpty()) { _selectionChanges.value = value } } data class Item(val key: String, val value: String? = null) companion object { private val ATTRIBUTE_IDS = intArrayOf(android.R.attr.text) } }
29
Kotlin
94
671
b364dfef22569ad326ee92492079790eaef4399d
2,764
HTTP-Shortcuts
MIT License
app/src/main/kotlin/net/kibotu/heartrateometer/MainActivity.kt
CaptainSeaSoul
266,795,716
true
{"Kotlin": 42043, "Java": 15185}
package net.kibotu.heartrateometer import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import net.kibotu.heartrateometer.app.R import java.io.File import java.io.FileInputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.util.* class MainActivity : AppCompatActivity() { enum class Status { Calm, Average, Stressed, Panic } private val FILE_TO_STORE_HISTORY = "historyMap" private var historyMap: HashMap<Date, Int> = hashMapOf() private var status: Status? = null set(value) { field = value statusView.text = value?.toString() ?: "status unknown" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // retrieving history data val f = File("$filesDir/$FILE_TO_STORE_HISTORY") if (f.isFile && f.canRead()) { val fileInputStream = FileInputStream(f) val objectInputStream = ObjectInputStream(fileInputStream) historyMap = objectInputStream.readObject() as HashMap<Date, Int> objectInputStream.close() } // retrieving previous saved status status = bpmToStat(historyMap.maxBy { it.key }?.value) // measure measureButton.setOnClickListener { val intent = Intent(this, MeasureActivity::class.java) startActivityForResult(intent, 1) } // play playButton.setOnClickListener { if (status != null) { val intent = Intent(this, GameActivity::class.java) intent.putExtra("velocityMove", getSpeed()) startActivity(intent) } else { val toast = Toast.makeText(applicationContext, "First measure the heartbeat!", Toast.LENGTH_SHORT) toast.show() } } // stats statsButton.setOnClickListener { if (historyMap.size > 1) { val intent = Intent(this, StatsActivity::class.java) intent.putExtra("historyMap", historyMap) startActivity(intent) } else { val toast = Toast.makeText(applicationContext, "First measure the heartbeat at least 2 time!", Toast.LENGTH_SHORT) toast.show() } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // working with measurement results if (data != null) when (requestCode) { 1 -> setStatus(data.getIntExtra("bpm", 0)) } } private fun setStatus(bpm: Int) { if (bpm != 0) { // assigning status according to the measurement status = bpmToStat(bpm) // saving the result in the history historyMap[Calendar.getInstance().time] = bpm val fileOutputStream = openFileOutput(FILE_TO_STORE_HISTORY, Context.MODE_PRIVATE) val objectOutputStream = ObjectOutputStream(fileOutputStream) objectOutputStream.writeObject(historyMap) objectOutputStream.close() } } private fun bpmToStat(bpm: Int?): Status? { if (bpm != null) return when { bpm <= 70 -> Status.Calm bpm in 71..85 -> Status.Average bpm in 86..120 -> Status.Stressed bpm > 120 -> Status.Panic else -> null } return null } private fun getSpeed(): Int { // status to int return when (status) { null -> 0 Status.Calm -> 5 Status.Average -> 7 Status.Stressed -> 10 Status.Panic -> 15 } } }
0
Kotlin
0
0
08efa90950ffc2964688a54497ed1228f5371fde
4,028
Heart-Rate-Ometer
Apache License 2.0
JetStreamCompose/jetstream/src/main/java/com/google/jetstream/presentation/screens/videoPlayer/VideoPlayerScreenViewModel.kt
android
192,011,831
false
null
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.jetstream.presentation.screens.videoPlayer import androidx.compose.runtime.Immutable import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.jetstream.data.entities.MovieDetails import com.google.jetstream.data.repositories.MovieRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class VideoPlayerScreenViewModel @Inject constructor( savedStateHandle: SavedStateHandle, repository: MovieRepository, ) : ViewModel() { val uiState = savedStateHandle .getStateFlow<String?>(VideoPlayerScreen.MovieIdBundleKey, null) .map { id -> if (id == null) { VideoPlayerScreenUiState.Error } else { val details = repository.getMovieDetails(movieId = id) VideoPlayerScreenUiState.Done(movieDetails = details) } }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = VideoPlayerScreenUiState.Loading ) } @Immutable sealed class VideoPlayerScreenUiState { object Loading : VideoPlayerScreenUiState() object Error : VideoPlayerScreenUiState() data class Done(val movieDetails: MovieDetails) : VideoPlayerScreenUiState() }
46
null
324
998
dba6602e2543ad467b7d4b44e99d118635c21c97
2,095
tv-samples
Apache License 2.0
liteapi-tl/src/liteserver/LiteServerRunMethodResult.kt
ton-community
448,983,229
false
{"Kotlin": 1194581}
package org.ton.lite.api.liteserver import kotlinx.io.bytestring.ByteString import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.ton.api.tonnode.TonNodeBlockIdExt import org.ton.tl.* import kotlin.jvm.JvmName import kotlin.jvm.JvmStatic @Serializable @SerialName("liteServer.runMethodResult") public data class LiteServerRunMethodResult internal constructor( @get:JvmName("mode") val mode: Int, @get:JvmName("id") val id: TonNodeBlockIdExt, @SerialName("shardblk") @get:JvmName("shardBlock") val shardBlock: TonNodeBlockIdExt, @SerialName("shard_proof") @get:JvmName("shardProof") @Serializable(ByteStringBase64Serializer::class) val shardProof: ByteString?, @get:JvmName("proof") @Serializable(ByteStringBase64Serializer::class) val proof: ByteString?, @SerialName("state_proof") @get:JvmName("stateProof") @Serializable(ByteStringBase64Serializer::class) val stateProof: ByteString?, @SerialName("init_c7") @get:JvmName("initC7") @Serializable(ByteStringBase64Serializer::class) val initC7: ByteString?, @SerialName("lib_extras") @get:JvmName("libExtras") @Serializable(ByteStringBase64Serializer::class) val libExtras: ByteString?, @SerialName("exit_code") @get:JvmName("exitCode") val exitCode: Int, @get:JvmName("result") @Serializable(ByteStringBase64Serializer::class) val result: ByteString? ) { public companion object : TlCodec<LiteServerRunMethodResult> by LiteServerRunMethodResultTlConstructor { @JvmStatic public fun mode( hasProof: Boolean = false, hasStateProof: Boolean = false, hasResult: Boolean = false, hasInitC7: Boolean = false, hasLibExtras: Boolean = false, ): Int { var mode = 0 if (hasProof) mode = mode or 1 if (hasStateProof) mode = mode or 2 if (hasResult) mode = mode or 4 if (hasInitC7) mode = mode or 8 if (hasLibExtras) mode = mode or 16 return mode } } } private object LiteServerRunMethodResultTlConstructor : TlConstructor<LiteServerRunMethodResult>( schema = "liteServer.runMethodResult mode:# id:tonNode.blockIdExt shardblk:tonNode.blockIdExt shard_proof:mode.0?bytes proof:mode.0?bytes state_proof:mode.1?bytes init_c7:mode.3?bytes lib_extras:mode.4?bytes exit_code:int result:mode.2?bytes = liteServer.RunMethodResult" ) { override fun encode(writer: TlWriter, value: LiteServerRunMethodResult) { writer.writeInt(value.mode) val mode = value.mode writer.write(TonNodeBlockIdExt, value.id) writer.write(TonNodeBlockIdExt, value.shardBlock) writer.writeNullable(mode, 0, value.shardProof) { writeBytes(it) } writer.writeNullable(mode, 0, value.proof) { writeBytes(it) } writer.writeNullable(mode, 1, value.stateProof) { writeBytes(it) } writer.writeNullable(mode, 3, value.initC7) { writeBytes(it) } writer.writeNullable(mode, 4, value.libExtras) { writeBytes(it) } writer.writeInt(value.exitCode) writer.writeNullable(mode, 2, value.result) { writeBytes(it) } } override fun decode(reader: TlReader): LiteServerRunMethodResult { val mode = reader.readInt() val id = reader.read(TonNodeBlockIdExt) val shardblk = reader.read(TonNodeBlockIdExt) val shardProof = reader.readNullable(mode, 0) { readByteString() } val proof = reader.readNullable(mode, 0) { readByteString() } val stateProof = reader.readNullable(mode, 1) { readByteString() } val initC7 = reader.readNullable(mode, 3) { readByteString() } val libExtras = reader.readNullable(mode, 4) { readByteString() } val exitCode = reader.readInt() val result = reader.readNullable(mode, 2) { readByteString() } return LiteServerRunMethodResult( mode, id, shardblk, shardProof, proof, stateProof, initC7, libExtras, exitCode, result ) } }
21
Kotlin
24
80
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
4,219
ton-kotlin
Apache License 2.0
konfork-core/src/commonMain/kotlin/io/github/konfork/core/builders/ValidatorBuilder.kt
konfork
557,451,504
false
{"Kotlin": 142473, "Java": 904}
package io.github.konfork.core.builders import io.github.konfork.core.* import io.github.konfork.core.internal.* import io.github.konfork.core.internal.ConditionalValidator import io.github.konfork.core.internal.ConstraintValidator import io.github.konfork.core.internal.EagerValidatorNode import io.github.konfork.core.internal.LazyValidatorNode import io.github.konfork.core.internal.MappedContextValidator import io.github.konfork.core.internal.MappedKeyValidator import io.github.konfork.core.internal.MappedValueValidator import io.github.konfork.core.internal.OnEachValidator import io.github.konfork.core.internal.RequiredValidator interface ValidatorBuilder<C, T, E> { fun build(): Validator<C, T, E> } class PropertyValidatorBuilder<C, T, V, E>( private val subBuilder: ValidatorBuilder<C, V, E>, private val name: String, private val mapFn: (T) -> V, ) : ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = MappedKeyValidator( MappedValueValidator(subBuilder.build(), mapFn), ) { ".$name$it" } } class LazyValidatorNodeBuilder<C, T, E>( private val subBuilder: ValidatorsBuilder<C, T, E>, ) : ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = LazyValidatorNode(subBuilder.build()) } class EagerValidatorNodeBuilder<C, T, E>( private val subBuilder: ValidatorsBuilder<C, T, E>, ) : ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = EagerValidatorNode(subBuilder.build()) } class IterableValidatorBuilder<C, T, E>( private val subBuilder: ValidatorBuilder<C, T, E>, ) : ValidatorBuilder<C, Iterable<T>, E> { override fun build(): Validator<C, Iterable<T>, E> = OnEachValidator(subBuilder.build()) { _, index, name -> "[$index]$name" } } class ArrayValidatorBuilder<C, T, E>( private val subBuilder: ValidatorBuilder<C, T, E>, ) : ValidatorBuilder<C, Array<T>, E> { override fun build(): Validator<C, Array<T>, E> = MappedValueValidator( OnEachValidator(subBuilder.build()) { _, index, name -> "[$index]$name" }, Array<T>::toList, ) } class MapValidatorBuilder<C, K, V, E>( private val subBuilder: ValidatorBuilder<C, Map.Entry<K, V>, E>, ) : ValidatorBuilder<C, Map<K, V>, E> { override fun build(): Validator<C, Map<K, V>, E> = MappedValueValidator( OnEachValidator(subBuilder.build()) { entry, _, name -> ".${entry.key.toString()}${name.removePrefix(".value")}" }, Map<K, V>::entries, ) } class MapValueValidatorBuilder<C, K, V, E>( private val subBuilder: ValidatorBuilder<C, V, E>, ) : ValidatorBuilder<C, Map<K, V>, E> { override fun build(): Validator<C, Map<K, V>, E> = MappedValueValidator( OnEachValidator( MappedValueValidator(subBuilder.build(), Map.Entry<K, V>::value) ) { entry, _, name -> ".${entry.key.toString()}$name" }, Map<K, V>::entries, ) } class MapKeyValidatorBuilder<C, K, V, E>( private val subBuilder: ValidatorBuilder<C, K, E>, ) : ValidatorBuilder<C, Map<K, V>, E> { override fun build(): Validator<C, Map<K, V>, E> = MappedValueValidator( OnEachValidator( MappedKeyValidator(MappedValueValidator(subBuilder.build(), Map.Entry<K, V>::key)) { "#key$it" } ) { entry, _, name -> ".${entry.key.toString()}$name" }, Map<K, V>::entries, ) } class OptionalValidatorBuilder<C, T : Any, E>( private val subBuilder: ValidatorBuilder<C, T, E>, ) : ValidatorBuilder<C, T?, E> { override fun build(): Validator<C, T?, E> = ConditionalValidator( { it != null }, MappedValueValidator(subBuilder.build()) { it!! }, ) } class RequiredValidatorBuilder<C, T : Any, E>( hint: HintBuilder<C, T?, E>, private val subBuilder: ValidatorBuilder<C, T, E>, ) : ValidatorBuilder<C, T?, E> { val constraintBuilder: ConstraintValidatorBuilder<C, T?, E> = ConstraintValidatorBuilder(hint, emptyList()) { _, value -> value != null } override fun build(): Validator<C, T?, E> = RequiredValidator( constraintBuilder.build(), subBuilder.build(), ) } class PrebuildValidatorBuilder<C, T, S, E>( private val validator: Validator<S, T, E>, private val mapFn: (C) -> S, ) : ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = MappedContextValidator(validator, mapFn) } class ConstraintValidatorBuilder<C, T, E>( private var hint: HintBuilder<C, T, E>, private val arguments: HintArguments, private val test: (C, T) -> Boolean, ) : ValidatorBuilder<C, T, E>, ConstraintBuilder<C, T, E> { override fun build(): Validator<C, T, E> = ConstraintValidator(hint, arguments, test) override infix fun hint(hint: HintBuilder<C, T, E>): ConstraintValidatorBuilder<C, T, E> { this.hint = hint return this } } class ConditionalValidatorBuilder<C, T, E>( private val cond: C.(T) -> Boolean, private val subBuilder: ValidatorBuilder<C, T, E>, ): ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = ConditionalValidator(cond, subBuilder.build()) } class MappedContextValueBuilder<C, T, V, E>( private val subBuilder: ValidatorBuilder<C, V, E>, private val mapFn: C.(T) -> V, ): ValidatorBuilder<C, T, E> { override fun build(): Validator<C, T, E> = MappedContextValueValidator(subBuilder.build(), mapFn) }
1
Kotlin
0
4
b75e6b96aa7c80efa5095a7763a22fcf614b10d8
5,618
konfork
MIT License
redwood-protocol-guest/src/commonMain/kotlin/app/cash/redwood/protocol/guest/GuestProtocolAdapter.kt
cashapp
305,409,146
false
null
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.redwood.protocol.guest import app.cash.redwood.RedwoodCodegenApi import app.cash.redwood.protocol.ChangesSink import app.cash.redwood.protocol.ChildrenTag import app.cash.redwood.protocol.EventSink import app.cash.redwood.protocol.Id import app.cash.redwood.protocol.ModifierElement import app.cash.redwood.protocol.PropertyTag import app.cash.redwood.protocol.WidgetTag import app.cash.redwood.widget.Widget import app.cash.redwood.widget.WidgetSystem import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json /** * Connects the guest (composition) of a Redwood UI to the host of that UI. * * Guest widgets use this to send view tree updates to the host, and to receive user events from the * host. * * This interface is for generated code use only. */ public interface ProtocolBridge : EventSink { @RedwoodCodegenApi public val json: Json /** * Host versions prior to 0.10.0 contained a bug where they did not recursively remove widgets * from the protocol map which leaked any child views of a removed node. We can work around this * on the guest side by synthesizing removes for every node in the subtree. */ @RedwoodCodegenApi public val synthesizeSubtreeRemoval: Boolean /** * The provider of factories of widgets which record property changes and whose children changes * are also recorded. You **must** attach returned widgets to [root] or the children of a widget * in the tree beneath [root] in order for it to be tracked. */ public val widgetSystem: WidgetSystem<Unit> /** * The root of the widget tree onto which [widgetSystem]-produced widgets can be added. Changes to * this instance are recorded as changes to [Id.Root] and [ChildrenTag.Root]. */ public val root: Widget.Children<Unit> public fun initChangesSink(changesSink: ChangesSink) public fun emitChanges() @RedwoodCodegenApi public fun nextId(): Id @RedwoodCodegenApi public fun appendCreate( id: Id, tag: WidgetTag, ) @RedwoodCodegenApi public fun <T> appendPropertyChange( id: Id, tag: PropertyTag, serializer: KSerializer<T>, value: T, ) @RedwoodCodegenApi public fun appendPropertyChange( id: Id, tag: PropertyTag, value: Boolean, ) /** * There's a bug in kotlinx.serialization where decodeFromDynamic() is broken for UInt values * larger than MAX_INT. For example, 4294967295 is incorrectly encoded as -1. We work around that * here by special casing that type. * * https://github.com/Kotlin/kotlinx.serialization/issues/2713 */ @RedwoodCodegenApi public fun appendPropertyChange( id: Id, tag: PropertyTag, value: UInt, ) @RedwoodCodegenApi public fun appendModifierChange( id: Id, elements: List<ModifierElement>, ) @RedwoodCodegenApi public fun appendAdd( id: Id, tag: ChildrenTag, index: Int, child: ProtocolWidget, ) @RedwoodCodegenApi public fun appendMove( id: Id, tag: ChildrenTag, fromIndex: Int, toIndex: Int, count: Int, ) @RedwoodCodegenApi public fun appendRemove( id: Id, tag: ChildrenTag, index: Int, count: Int, removedIds: List<Id> = listOf(), ) @RedwoodCodegenApi public fun removeWidget(id: Id) }
131
null
70
1,612
97e88b4f738bb0e210bd77752ff5b3fa8f66153c
3,900
redwood
Apache License 2.0
docs/archive/game-bill/src/main/kotlin/org/mmo/bill/server/tcp/BillTcpChannelInitializer.kt
jzyong
130,787,756
false
{"Java": 771381, "Kotlin": 10744, "Batchfile": 2116, "Dockerfile": 1647, "Scala": 531, "HTML": 420, "Shell": 346, "Mustache": 116}
package org.mmo.bill.server.tcp import io.netty.channel.ChannelInitializer import io.netty.channel.socket.SocketChannel import io.netty.handler.timeout.IdleStateHandler import org.mmo.bill.service.BillExecutorService import org.mmo.engine.io.netty.config.NettyProperties import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component /** * channel初始化 */ @Component @Scope("prototype") class BillTcpChannelInitializer :ChannelInitializer<SocketChannel>(){ @Autowired private var nettyProperties:NettyProperties?=null @Autowired private var tcpService:BillTcpService?=null @Autowired private var billExecutorService:BillExecutorService?=null override fun initChannel(ch: SocketChannel) { ch.pipeline().addLast("Codec",BillTcpByteToMessageCodec()) ch.pipeline().addLast("MessageHandler",BillTcpServerHandler(billExecutorService,tcpService)) val nettyServerConfig = nettyProperties!!.serverConfigs[0] val bothIdleTime = Math.min(nettyServerConfig.readerIdleTime, nettyServerConfig.writerIdleTime) ch.pipeline().addLast("IdleStateHandler", IdleStateHandler(nettyServerConfig.readerIdleTime, nettyServerConfig.writerIdleTime, bothIdleTime)) } }
3
Java
109
289
f3143b94dfc034f260781619305bc6a97d555e5c
1,334
GameServer4j
MIT License
src/main/kotlin/db/GeneratedCalendar.kt
Paulpanther
851,898,428
false
{"Kotlin": 36011, "Dockerfile": 837}
package db import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.jsonArray import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.javatime.date import org.jetbrains.exposed.sql.javatime.datetime import org.jetbrains.exposed.sql.javatime.time import org.jetbrains.exposed.sql.transactions.transaction import utils.DateSerializer import utils.DateTimeSerializer import utils.LocalDateSlice import utils.LocalTimeSlice import utils.TimeSerializer import java.time.DateTimeException import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneId object GeneratedCalendars : IntIdTable("generated_calendar") { val name = varchar("name", 255).uniqueIndex() val content = binary("content") val startOfDay = time("startOfDay") val endOfDay = time("endOfDay") val timezone = varchar("timezone", 255) val startDate = date("startDate") val endDate = date("endDate") val sections = varchar("sections", 255) val lastChanged = datetime("lastChanged") } private val json = Json { isLenient = true } class GeneratedCalendar(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<GeneratedCalendar>(GeneratedCalendars) { fun parseSections(raw: String): List<LocalTimeSlice> { var sections = try { json.parseToJsonElement(raw).jsonArray.map { json.decodeFromJsonElement<LocalTimeSlice>(it) } } catch (e: Exception) { throw IllegalArgumentException("sections could not be parsed. Format: '[{start: '08:00', end: '12:00'], {start: '12:00', end: '18:00'}]'") } if (sections.isEmpty()) throw IllegalArgumentException("Given sections must not be empty") sections.forEach { if (it.start > it.end) throw IllegalArgumentException("The start time of a section must be earlier then the end time.") } sections = sections.sortedBy { it.start } var lastEnd = LocalTime.MIN for (section in sections) { if (section.start < lastEnd) throw IllegalArgumentException("Sections must not be overlapping") lastEnd = section.end } return sections } fun parseTimezone(str: String): ZoneId { return try { ZoneId.of(str) } catch (e: DateTimeException) { throw IllegalArgumentException("Given query parameter 'timezone' could not be resolved") } } } var name by GeneratedCalendars.name var content by GeneratedCalendars.content var startOfDay by GeneratedCalendars.startOfDay var endOfDay by GeneratedCalendars.endOfDay var timezone by GeneratedCalendars.timezone var startDate by GeneratedCalendars.startDate var endDate by GeneratedCalendars.endDate var sections by GeneratedCalendars.sections var lastChanged by GeneratedCalendars.lastChanged val sectionList get() = parseSections(sections) val timezoneId get() = parseTimezone(timezone) val timeframe get() = LocalDateSlice(startDate, endDate) val inputCalendars by InputCalendar referrersOn InputCalendars.generated fun toData() = GeneratedCalendarData( name, content.toString(Charsets.UTF_8), startOfDay, endOfDay, timezone, startDate, endDate, sections, lastChanged, transaction { inputCalendars.map { it.toData() } } ) } @Serializable data class GeneratedCalendarData( val name: String, val content: String, @Serializable(with = TimeSerializer::class) val startOfDay: LocalTime, @Serializable(with = TimeSerializer::class) val endOfDay: LocalTime, val timezone: String, @Serializable(with = DateSerializer::class) val startDate: LocalDate, @Serializable(with = DateSerializer::class) val endDate: LocalDate, val sections: String, @Serializable(with = DateTimeSerializer::class) val lastChanged: LocalDateTime, val inputCalendars: List<InputCalendarData> )
0
Kotlin
0
0
2433322a27e36454c47fc430789e0e57dc452e2f
4,098
obfuscal
MIT License
src/main/kotlin/com/keycodetech/springkotlin/MovieController.kt
jeancl
114,985,721
false
null
package com.keycodetech.springkotlin import com.keycodetech.springkotlin.exceptions.NotFoundException import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController import org.springframework.web.servlet.support.ServletUriComponentsBuilder import java.net.URI import java.util.Optional import javax.validation.Valid @RestController class MoviesController(private val repository: MoviesRepository) { @CrossOrigin @GetMapping("/api/movies") fun findAll() = repository.findAll() @CrossOrigin @PostMapping("/api/movies") fun create(@Valid @RequestBody movie: Movie): ResponseEntity<Any> { val savedMovie = repository.save(movie) val location: URI = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(savedMovie._id) .toUri() return ResponseEntity.created(location).build() } @CrossOrigin @PutMapping("/api/movies/{id}") fun update(@RequestBody movie: Movie) = repository.save(movie) @CrossOrigin @GetMapping("/api/movies/search/{title}") fun findByTitle(@PathVariable title: String) = repository.findByTitle(title) @CrossOrigin @GetMapping("/api/movies/{id}") fun findById(@PathVariable id: String): Optional<Movie> { val movie = repository.findById(id) if(!movie.isPresent()) throw NotFoundException(String.format("id-%s",id)) return movie } @CrossOrigin @DeleteMapping("/api/movies/{id}") fun remove(@PathVariable id: String) { if(!repository.existsById(id)) throw NotFoundException(String.format("id-%s",id)) repository.deleteById(id) } }
0
Kotlin
0
0
88e59ba53639b33bdb760988fa35f40905c40ebe
2,032
springkotlin
Apache License 2.0
src/main/kotlin/render/client/model/objects/SimpleTexturedBox.kt
2xsaiko
123,460,493
false
null
package therealfarfetchd.quacklib.render.client.model.objects import net.minecraft.util.EnumFacing.* import therealfarfetchd.math.Vec3 import therealfarfetchd.quacklib.api.render.Quad import therealfarfetchd.quacklib.api.render.mkQuad import therealfarfetchd.quacklib.api.render.texture.AtlasTexture class SimpleTexturedBox(from: Vec3, to: Vec3, val tex: AtlasTexture, rotate: Boolean = false) : Iterable<Quad> { @Suppress("UnnecessaryVariable") val quads = run { // val p1 = from val p2 = Vec3(from.x, from.y, to.z) // val p3 = Vec3(to.x, from.y, to.z) val p4 = Vec3(to.x, from.y, from.z) val p5 = Vec3(from.x, to.y, from.z) // val p6 = Vec3(from.x, to.y, to.z) val p7 = to // val p8 = Vec3(to.x, to.y, from.z) listOf( mkQuad(tex, DOWN, p7, p5, rotate = rotate), mkQuad(tex, UP, p2, p4, rotate = rotate), mkQuad(tex, NORTH, p7, p2, rotate = rotate), mkQuad(tex, SOUTH, p4, p5, rotate = rotate), mkQuad(tex, WEST, p4, p7, rotate = rotate), mkQuad(tex, EAST, p2, p5, rotate = rotate) ) } override fun iterator(): Iterator<Quad> = quads.iterator() }
6
Kotlin
2
4
76c9a55f186c699fb4458f2a4a40a483ab3e3ef2
1,137
QuackLib
MIT License
app/src/main/java/com/synaptikos/geochat/ChatActivity.kt
daemon
97,455,308
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 2, "XML": 17, "Kotlin": 24}
package com.synaptikos.geochat import android.os.Bundle import android.support.v7.app.AppCompatActivity class ChatActivity : AppCompatActivity() { override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) this.setContentView(R.layout.activity_chat) } }
1
null
1
1
a4548edc4271de3fdfa88df0b2737eac7c7c6d71
273
geochat
MIT License
app/src/main/java/com/bpdevop/mediccontrol/ui/viewmodels/VaccinationViewModel.kt
bpdevop
839,980,935
false
{"Kotlin": 693059}
package com.bpdevop.mediccontrol.ui.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bpdevop.mediccontrol.core.utils.UiState import com.bpdevop.mediccontrol.data.model.Vaccine import com.bpdevop.mediccontrol.data.repository.VaccinationRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class VaccinationViewModel @Inject constructor( private val repository: VaccinationRepository, ) : ViewModel() { private val _vaccinationHistoryState = MutableStateFlow<UiState<List<Vaccine>>>(UiState.Idle) val vaccinationHistoryState: StateFlow<UiState<List<Vaccine>>> = _vaccinationHistoryState private val _addVaccineState = MutableStateFlow<UiState<String>>(UiState.Idle) val addVaccineState: StateFlow<UiState<String>> = _addVaccineState private val _updateVaccineState = MutableStateFlow<UiState<String>>(UiState.Idle) val updateVaccineState: StateFlow<UiState<String>> = _updateVaccineState private val _deleteVaccineState = MutableStateFlow<UiState<String>>(UiState.Idle) val deleteVaccineState: StateFlow<UiState<String>> = _deleteVaccineState fun getVaccinationHistory(patientId: String) { viewModelScope.launch { _vaccinationHistoryState.value = UiState.Loading val result = repository.getVaccinationHistory(patientId) _vaccinationHistoryState.value = result } } fun addVaccine(patientId: String, vaccine: Vaccine) { viewModelScope.launch { _addVaccineState.value = UiState.Loading val result = repository.addVaccineToPatient(patientId, vaccine) _addVaccineState.value = result } } fun editVaccine(patientId: String, vaccine: Vaccine) { viewModelScope.launch { _updateVaccineState.value = UiState.Loading val result = repository.editVaccine(patientId, vaccine) _updateVaccineState.value = result } } fun deleteVaccine(patientId: String, vaccineId: String) { viewModelScope.launch { _deleteVaccineState.value = UiState.Loading val result = repository.deleteVaccine(patientId, vaccineId) _deleteVaccineState.value = result getVaccinationHistory(patientId) } } fun resetAddVaccineState() { _addVaccineState.value = UiState.Idle } fun resetUpdateVaccineState() { _updateVaccineState.value = UiState.Idle } fun resetDeleteVaccineState() { _deleteVaccineState.value = UiState.Idle } }
0
Kotlin
0
0
68aa078786199aca908f03965c617f096d91a384
2,751
MedicControl
MIT License