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
android/app/src/main/java/com/algorand/android/modules/asb/importbackup/backupselection/ui/mapper/AsbFileSelectionPreviewMapper.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.modules.asb.importbackup.backupselection.ui.mapper import com.algorand.android.customviews.perafileuploadview.model.FileUploadState import com.algorand.android.models.AnnotatedString import com.algorand.android.modules.asb.importbackup.backupselection.ui.model.AsbFileSelectionPreview import com.algorand.android.utils.Event import javax.inject.Inject class AsbFileSelectionPreviewMapper @Inject constructor() { fun mapToAsbFileSelectionPreview( isNextButtonEnabled: Boolean, isPasteButtonVisible: Boolean, fileUploadState: FileUploadState, fileCipherText: String? = null, openFileSelectorEvent: Event<Unit>? = null, showGlobalErrorEvent: Event<Pair<AnnotatedString, AnnotatedString?>>? = null, navToAsbEnterKeyFragmentEvent: Event<String>? = null, showGlobalSuccessEvent: Event<Int>? = null ): AsbFileSelectionPreview { return AsbFileSelectionPreview( isNextButtonEnabled = isNextButtonEnabled, isPasteButtonVisible = isPasteButtonVisible, fileUploadState = fileUploadState, fileCipherText = fileCipherText, openFileSelectorEvent = openFileSelectorEvent, showGlobalErrorEvent = showGlobalErrorEvent, navToAsbEnterKeyFragmentEvent = navToAsbEnterKeyFragmentEvent, showGlobalSuccessEvent = showGlobalSuccessEvent ) } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
2,022
pera-wallet
Apache License 2.0
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/dataformats/FastjsonDataFormatDsl.kt
bearBoy80
564,572,724
true
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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.apache.camel.kotlin.dataformats import java.lang.Class import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import org.apache.camel.kotlin.CamelDslMarker import org.apache.camel.kotlin.DataFormatDsl import org.apache.camel.model.dataformat.JsonDataFormat public fun DataFormatDsl.fastjson(i: FastjsonDataFormatDsl.() -> Unit) { def = FastjsonDataFormatDsl().apply(i).def } @CamelDslMarker public class FastjsonDataFormatDsl { public val def: JsonDataFormat init { def = JsonDataFormat()} public fun unmarshalType(unmarshalType: Class<out Any>) { def.unmarshalType = unmarshalType } public fun contentTypeHeader(contentTypeHeader: Boolean) { def.contentTypeHeader = contentTypeHeader.toString() } public fun contentTypeHeader(contentTypeHeader: String) { def.contentTypeHeader = contentTypeHeader } }
0
Java
0
0
8455c3a9f3dd2c1ad7c765055208b23576005819
1,683
camel
Apache License 2.0
nodecore-spv/src/main/java/org/veriblock/spv/model/DownloadStatus.kt
VeriBlock
179,742,374
false
null
package veriblock.model enum class DownloadStatus { DISCOVERING, DOWNLOADING, READY; fun isDiscovering(): Boolean = DISCOVERING == this fun isDownloading(): Boolean = DOWNLOADING == this }
72
null
16
12
ef06c51c1410ba59da13403b65e367b21dcfed21
228
nodecore
MIT License
app/src/main/java/io/github/initrc/bootstrap/presenter/ColumnPresenter.kt
initrc
88,451,118
false
null
package io.github.initrc.bootstrap.presenter import android.app.Activity import io.github.initrc.bootstrap.R import util.DeviceUtils import util.GridUtils /** * Presenter for the grid column. */ class ColumnPresenter(private val activity: Activity) { var columnCountType = ColumnCountType.STANDARD val resources = activity.resources!! val gridPadding = resources.getDimension(R.dimen.margin).toInt() private var onColumnUpdate: (Int) -> Unit = {} fun getDynamicGridColumnCount(): Int { return when(columnCountType) { ColumnCountType.ONE -> 1 ColumnCountType.STANDARD -> GridUtils.getGridColumnCount(resources) ColumnCountType.DOUBLE -> GridUtils.getGridColumnCount(resources) * 2 } } fun getGridColumnWidthPx(): Int { val gridColumnCount = getDynamicGridColumnCount() val paddingCount = gridColumnCount + 1 val screenWidth = DeviceUtils.getScreenWidthPx(activity) return (screenWidth - gridPadding * paddingCount) / gridColumnCount } /** * @return True if the count is adjusted. */ fun adjustCount(delta: Int): Boolean { if (delta == 0) return false if (columnCountType.ordinal + delta in 0 until ColumnCountType.values().size) { columnCountType = ColumnCountType.values()[columnCountType.ordinal + delta] onColumnUpdate(getDynamicGridColumnCount()) return true } return false } fun setOnColumnUpdateCallback(func: (Int) -> Unit) { onColumnUpdate = func } } enum class ColumnCountType { ONE, STANDARD, DOUBLE }
1
Kotlin
1
1
5b0105448b8b39e0d56eb17153c7801dda96a42d
1,646
android-bootstrap
MIT License
BaseExtend/src/main/java/com/chen/baseextend/room/DataBaseCategory.kt
chen397254698
268,411,455
false
null
package com.chen.baseextend.room /** * Created by chen on 2019/10/11 **/ object DataBaseCategory { const val MANAGER_PROJECT = "manager_project" const val RECEIVE_PROJECT = "receive_project" const val HOME_PROJECT = "home_project" const val TASK_PROJECT = "task_project" const val HOT_PROJECT = "hot_project" const val MANAGER_PROJECT_TYPE = "manager_project_type" const val RECEIVE_PROJECT_TYPE = "receive_project_type" const val PUBLISH_PROJECT_TYPE = "publish_project_type" const val HOME_PROJECT_TYPE = "home_project_type" }
1
Kotlin
14
47
85ffc5e307c6171767e14bbfaf992b8d62ec1cc6
578
EasyAndroid
Apache License 2.0
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/core/viewmodel/FileCellViewModel.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.presentation.core.viewmodel import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel import com.ivanovsky.passnotes.presentation.core.event.Event.Companion.toEvent import com.ivanovsky.passnotes.presentation.core.event.EventProvider import com.ivanovsky.passnotes.presentation.core.model.FileCellModel class FileCellViewModel( override val model: FileCellModel, private val eventProvider: EventProvider ) : BaseCellViewModel(model) { fun onClicked() { eventProvider.send((CLICK_EVENT to model.id).toEvent()) } companion object { val CLICK_EVENT = FileCellViewModel::class.qualifiedName + "_clickEvent" } }
4
null
1
7
dc4abdf847393919f5480129b64240ae0469b74c
692
kpassnotes
Apache License 2.0
app/src/main/java/org/stepik/android/domain/visited_courses/repository/VisitedCoursesRepository.kt
StepicOrg
42,045,161
false
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
package org.stepik.android.domain.visited_courses.repository import io.reactivex.Completable import io.reactivex.Flowable import org.stepik.android.domain.visited_courses.model.VisitedCourse interface VisitedCoursesRepository { fun observeVisitedCourses(): Flowable<List<VisitedCourse>> fun saveVisitedCourse(courseId: Long): Completable fun removedVisitedCourses(): Completable }
13
Kotlin
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
394
stepik-android
Apache License 2.0
app/src/main/java/com/sq26/experience/ui/activity/file/FileOperateActivity.kt
sq26
163,916,153
false
{"Gradle": 3, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 43, "XML": 130, "Kotlin": 77, "AIDL": 4, "HTML": 1}
package com.sq26.experience.ui.activity.file import android.content.ContentResolver import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.activity.addCallback import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.net.toFile import androidx.core.net.toUri import androidx.databinding.DataBindingUtil import androidx.documentfile.provider.DocumentFile import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DividerItemDecoration import com.sq26.experience.R import com.sq26.experience.adapter.CommonListAdapter import com.sq26.experience.adapter.CommonListViewHolder import com.sq26.experience.databinding.ActivityFileManagementBinding import com.sq26.experience.databinding.ItemFileBinding import com.sq26.experience.databinding.ItemParentFileBinding import com.sq26.experience.util.FileUtil import java.util.* class FileOperateActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DataBindingUtil.setContentView<ActivityFileManagementBinding>( this, R.layout.activity_file_management ) .apply { lifecycleOwner = this@FileOperateActivity //父文件夹列表 val parentFileList: MutableList<DocumentFile> = ArrayList() //创建父文件夹目录适配器 val parentFileListAdapter = object : CommonListAdapter<DocumentFile>(DocumentFileDiffCallback()) { override fun createView( parent: ViewGroup, viewType: Int ): CommonListViewHolder<*> { //创建通用视图持有者 return object : CommonListViewHolder<ItemParentFileBinding>( ItemParentFileBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) { //绑定数据 override fun bind(position: Int) { //设置参数 v.documentFile = getItem(position) //设置点击事件 v.setOnClick { //移除从选定位置到结尾的目录 parentFileList.subList(position + 1, parentFileList.size) .clear() //刷新视图 submitList(parentFileList.toList()) } //强制绑定数据 executePendingBindings() } } } } //绑定适配器 rootRecyclerView.adapter = parentFileListAdapter //文件列表 val fileList: MutableList<DocumentFile> = ArrayList() //创建文件适配器 val fileListAdapter = object : CommonListAdapter<DocumentFile>(DocumentFileDiffCallback()) { override fun createView( parent: ViewGroup, viewType: Int ): CommonListViewHolder<*> { return object : CommonListViewHolder<ItemFileBinding>( ItemFileBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) { init { //设置根目录的点击事件 v.root.setOnClickListener { v.item?.let { if (it.isFile) { FileUtil.openFile( this@FileOperateActivity, it.uri ) } else { parentFileList.add(it) parentFileListAdapter.submitList(parentFileList.toList()) submitList(it.listFiles().toList()) } } } //设置根目录的长按事件 v.root.setOnLongClickListener { v.item?.let { AlertDialog.Builder(this@FileOperateActivity) .setMessage("是否删除") .setPositiveButton("是") { _, _ -> Log.d("删除", "有权限") //删除数据 it.delete() //移除对应的documentFile对象 fileList.remove(it) //刷新视图 submitList(fileList.toList()) }.show() } true } } override fun bind(position: Int) { v.item = getItem(position) } } } } //设置分割线 recyclerView.addItemDecoration( DividerItemDecoration( this@FileOperateActivity, DividerItemDecoration.VERTICAL ) ) //绑定适配器 recyclerView.adapter = fileListAdapter //获取根目录路径 val rootUri = intent.getStringExtra("rootUri").orEmpty() //声明一个DocumentFile对象 val documentFile =if (rootUri.toUri().scheme == ContentResolver.SCHEME_FILE){ DocumentFile.fromFile(rootUri.toUri().toFile()) }else{ DocumentFile.fromTreeUri(this@FileOperateActivity, Uri.parse(rootUri)) } documentFile?.let { //加入父目录列表 parentFileList.add(it) //刷新父目录视图 parentFileListAdapter.submitList(parentFileList.toList()) //初始化数据 fileListAdapter.submitList(it.listFiles().toList()) } //添加返回键监听 onBackPressedDispatcher.addCallback { //parentFileList数量大于1说明不是根目录 if (parentFileList.size > 1) { //移除最后一个目录 parentFileList.removeAt(parentFileList.size - 1) //刷新父目录列表 parentFileListAdapter.submitList(parentFileList.toList()) //刷新文件列表 fileListAdapter.submitList(listOf(*parentFileList[parentFileList.size - 1].listFiles())) } else { //关闭返回监听 isEnabled = false //主动调用返回 onBackPressedDispatcher.onBackPressed() onBackPressedDispatcher.hasEnabledCallbacks() } } } } } class DocumentFileDiffCallback : DiffUtil.ItemCallback<DocumentFile>() { //判断唯一标识是否相同 override fun areItemsTheSame( oldItem: DocumentFile, newItem: DocumentFile ): Boolean { return oldItem.uri == newItem.uri } //判断内容是否相同 override fun areContentsTheSame( oldItem: DocumentFile, newItem: DocumentFile ): Boolean { return oldItem.uri == oldItem.uri } }
0
Kotlin
0
0
caf898bb33c66b2751b30a2e1a65257371bd683e
8,773
Android-Study-Demo
Apache License 2.0
app/src/main/java/com/amachikhin/testapplication/features/base/domain/Interactor.kt
shustreek
259,710,149
false
null
package com.amachikhin.testapplication.features.base.domain import com.amachikhin.testapplication.features.base.Cancellable interface Interactor<T : InteractorOut> : Cancellable { fun setupInteractorOut(out: T) }
1
null
1
1
cd17c880561a88d0c77dd625ad699560a2e140ce
221
progress
Apache License 2.0
compiler/testData/diagnostics/tests/exceptions/transformErrorTypeChildrenWhileTransformingPartiallyResolvedType.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FIR_IDENTICAL // ISSUE: KT-67503 @Target(AnnotationTarget.TYPE) annotation class Ann class Inv<T> fun <T> foo(x: Inv<@Ann <!SYNTAX!>*<!>>) {} fun <T> foo2(x: Inv<@Ann<!SYNTAX!><!> >) {}
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
191
kotlin
Apache License 2.0
app/src/main/java/com/geniusforapp/movies/shared/domain/usecases/GetMoviesByTypeUseCase.kt
geniusforapp
91,422,278
false
null
package com.geniusforapp.movies.shared.domain.usecases import com.geniusforapp.movies.shared.data.model.MoviesResponse import com.geniusforapp.movies.shared.domain.repositoreis.MoviesRepository import com.geniusforapp.movies.shared.rx.SchedulerProvider import io.reactivex.Single import javax.inject.Inject import javax.inject.Singleton class GetMoviesByTypeUseCase @Inject constructor(private val moviesRepository: MoviesRepository, private val schedulerProvider: SchedulerProvider) { fun getMovies(type: String, page: Int): Single<MoviesResponse> = moviesRepository.getMovies(type, page).compose(schedulerProvider.ioToMainSingleScheduler()) }
1
Kotlin
5
3
e63a4d948d5a2253b5c3c47196476bb45053df2b
665
movies
Apache License 2.0
resource_management/resource_management.model/src/main/java/org/eclipse/slm/resource_management/model/resource/MatchingResourceDTO.kt
408b7f8b
790,281,437
true
{"JSON": 26, "Maven POM": 62, "Markdown": 31, "Git Attributes": 1, "Text": 2, "Ignore List": 6, "YAML": 184, "XML": 7, "Java": 317, "Kotlin": 208, "HTTP": 11, "JavaScript": 67, "Dotenv": 7, "JSON with Comments": 2, "Dockerfile": 25, "Browserslist": 1, "HTML": 2, "Vue": 117, "SCSS": 2, "Sass": 15, "SVG": 2, "HCL": 16, "Shell": 15, "Nginx": 3, "PowerShell": 4, "SQL": 1, "Python": 1, "Java Properties": 1, "CSS": 3, "INI": 5, "Fluent": 1, "Stylus": 2, "OASv3-yaml": 1}
package org.eclipse.slm.resource_management.model.resource import java.util.* class MatchingResourceDTO( val resourceId: UUID, val capabilityServiceId: UUID, val isCluster: Boolean, ) { }
0
null
0
0
6ccf80fb0f55f4cd65890d689193c8fd47c7db4d
205
slm
Apache License 2.0
analysis/analysis-api/testData/components/diagnosticsProvider/diagnostics/overrideProtectedClassReturnFromLibrary.kt
JetBrains
3,432,266
false
null
// IGNORE_FE10 // KT-64503 // MODULE: lib // MODULE_KIND: LibraryBinary // FILE: TestExposeTypeLib.kt abstract class TestExposeTypeLib { protected abstract fun returnProtectedClass(): ProtectedClass? protected class ProtectedClass } // MODULE: main(lib) // FILE: usage.kt class Usage : TestExposeTypeLib() { override fun returnProtectedClass(): ProtectedClass? = null }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
384
kotlin
Apache License 2.0
roundlinearlayout/src/main/java/tk/dsjin/roundlinearlayout/RoundLinearLayout.kt
dsjin
167,668,606
false
null
/* * Copyright 2019 <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 tk.dsjin.roundlinearlayout import android.content.Context import android.graphics.Canvas import android.graphics.Path import android.graphics.RectF import android.util.AttributeSet import android.util.DisplayMetrics import android.util.TypedValue import android.widget.LinearLayout class RoundLinearLayout: LinearLayout { private var radius : Int private var path : Path constructor(context : Context): super(context) constructor(context: Context, attrs : AttributeSet):super(context, attrs){ val a = context.obtainStyledAttributes(attrs, R.styleable.RoundLinearLayout) radius = convertRadius(a.getInt(R.styleable.RoundLinearLayout_radius, 20)) a.recycle() } constructor(context : Context, attrs : AttributeSet, defStyleAttr : Int):super(context, attrs, defStyleAttr) init { path = Path() radius = 20 } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) setNewPath(w, h) } override fun draw(canvas : Canvas) { val save = canvas.save() canvas.clipPath(path) super.draw(canvas) canvas.restoreToCount(save) } fun setRadius(radius : Int){ this.radius = convertRadius(radius) setNewPath(super.getWidth(), super.getHeight()) invalidate() } private fun convertRadius(radius : Int) : Int{ val displayMetrics : DisplayMetrics = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, radius.toFloat(), displayMetrics).toInt() } private fun setNewPath(w : Int , h : Int){ path.reset() val rect = RectF() rect.set(0f, 0f, w.toFloat(), h.toFloat()) path.addRoundRect(rect, radius.toFloat(), radius.toFloat(), Path.Direction.CW) path.close() } }
0
Kotlin
0
1
5bd942238aa6d58f3859f74a73ae25211709a5a9
2,470
RoundLinearLayout
Apache License 2.0
analysis/analysis-api/testData/components/resolver/singleByPsi/TopLevelCompanionObjectVsLocalClassConstructor2.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
package test class Conflict(i: Int) { companion object { operator fun invoke() {} } } fun test() { class Conflict <caret>Conflict() }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
162
kotlin
Apache License 2.0
app/build/generated/source/navigation-args/debug/ru/hadron/newsapp/ui/fragments/SavedNewsFragmentDirections.kt
ppvkt
280,628,257
false
{"Java": 28518, "Kotlin": 13830}
package ru.hadron.newsapp.ui.fragments import android.os.Bundle import android.os.Parcelable import androidx.navigation.NavDirections import java.io.Serializable import java.lang.UnsupportedOperationException import kotlin.Int import kotlin.Suppress import ru.hadron.newsapp.R import ru.hadron.newsapp.models.Article class SavedNewsFragmentDirections private constructor() { private data class ActionSavedNewsFragmentToArticleFragment( val article: Article ) : NavDirections { override fun getActionId(): Int = R.id.action_savedNewsFragment_to_articleFragment @Suppress("CAST_NEVER_SUCCEEDS") override fun getArguments(): Bundle { val result = Bundle() if (Parcelable::class.java.isAssignableFrom(Article::class.java)) { result.putParcelable("article", this.article as Parcelable) } else if (Serializable::class.java.isAssignableFrom(Article::class.java)) { result.putSerializable("article", this.article as Serializable) } else { throw UnsupportedOperationException(Article::class.java.name + " must implement Parcelable or Serializable or must be an Enum.") } return result } } companion object { fun actionSavedNewsFragmentToArticleFragment(article: Article): NavDirections = ActionSavedNewsFragmentToArticleFragment(article) } }
1
null
1
1
8e65048c15026c9c55b04d68629c6e5e55782d4e
1,351
NewsApp
Apache License 2.0
plugins/kotlin/idea/tests/testData/quickfix/suppress/inspections/codeStructure/statementSuppressedOnStatement.kt
JetBrains
2,489,216
false
null
// "Suppress 'WrapUnaryOperator' for statement " "true" class StatementSuppressedOnFun { fun statementSuppressedOnFun() { <caret>-1.inc() + 1 } } // K1_TOOL: org.jetbrains.kotlin.idea.codeInsight.inspections.shared.WrapUnaryOperatorInspection // K2_TOOL: org.jetbrains.kotlin.idea.codeInsight.inspections.shared.WrapUnaryOperatorInspection // FUS_K2_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix // FUS_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
523
intellij-community
Apache License 2.0
wgpu4k/src/commonMain/kotlin/io.ygdrasil.wgpu/RenderingContext.kt
wgpu4k
773,068,055
false
null
package io.ygdrasil.wgpu expect class RenderingContext: AutoCloseable { val width: Int val height: Int val textureFormat: TextureFormat fun getCurrentTexture(): Texture /** * Schedule this texture to be presented on the owning surface. * * Needs to be called after any work on the texture is scheduled via Queue::submit. * * Platform dependent behavior * On Wayland, present will attach a wl_buffer to the underlying wl_surface and commit the new surface state. If it is desired to do things such as request a frame callback, scale the surface using the viewporter or synchronize other double buffered state, then these operations should be done before the call to present. */ fun present() fun configure(canvasConfiguration: CanvasConfiguration) override fun close() } data class CanvasConfiguration( var device: Device, var format: TextureFormat? = null, var usage: GPUTextureUsageFlags = TextureUsage.renderattachment.value, var viewFormats: Array<String?>? = null, var colorSpace: Any? = null, var alphaMode: CompositeAlphaMode? = null )
0
null
1
2
726c9498ebcd75300ac4e28eab340741aa9f5fcb
1,078
wgpu4k
MIT License
src/main/kotlin/adventofcode2017/potasz/P15DuelGenerators.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz import kotlin.coroutines.experimental.buildIterator object P15DuelGenerators { val A = 16807L val B = 48271L val DIV = 2147483647L val MASK_LOW_16 = 0xFFFFL val MASK_MOD_4 = 0x0003L val MASK_MOD_8 = 0x0007L fun f(x: Long, mul: Long): Long = (x * mul) % DIV fun fA(x: Long) = f(x, A) fun fB(x: Long) = f(x, B) fun solve1Loop(initA: Long, initB: Long): Int { var a = initA var b = initB var count = 0 repeat (40_000_000) { a = fA(a) b = fB(b) if (a and MASK_LOW_16 == b and MASK_LOW_16) count++ } return count } fun solve2Loop(initA: Long, initB: Long): Int { var a = initA var b = initB var count = 0 repeat (5_000_000) { if (a and MASK_LOW_16 == b and MASK_LOW_16) count++ do { a = fA(a) } while (a and MASK_MOD_4 != 0L) do { b = fB(b) } while (b and MASK_MOD_8 != 0L) } return count } fun iterator(init: Long, f: (Long) -> Long, modMask: Long = 0L) = buildIterator { var x = init yield(x) while (true) { do { x = f(x) } while (x and modMask != 0L) yield(x) } } fun compare(iterA: Iterator<Long>, iterB: Iterator<Long>, repeat: Int): Int { var count = 0 repeat(repeat) { if (iterA.next() and MASK_LOW_16 == iterB.next() and MASK_LOW_16) count++ } return count } fun solve1Iter(initA: Long, initB: Long) = compare(iterator(initA, this::fA), iterator(initB, this::fB), 40_000_000) fun solve2Iter(initA: Long, initB: Long) = compare(iterator(initA, this::fA, MASK_MOD_4), iterator(initB, this::fB, MASK_MOD_8), 5_000_000) @JvmStatic fun main(args: Array<String>) { println(solve1Loop(1092455L, 430625591L)) println(solve2Loop(1092455L, 430625591L)) println(solve1Loop(516L, 190L)) println(solve2Loop(516L, 190L)) } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
2,155
adventofcode2017
Apache License 2.0
randomgenkt/src/test/java/com/mitteloupe/randomgenkt/fielddataprovider/ByteFieldDataProviderTest.kt
EranBoudjnah
154,015,466
false
null
package com.mitteloupe.randomgenkt.fielddataprovider import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.Mock import org.mockito.Mockito.doAnswer import org.mockito.junit.MockitoJUnitRunner import java.util.Random /** * Created by <NAME> on 10/08/2018. */ @RunWith(MockitoJUnitRunner::class) class ByteFieldDataProviderTest { private lateinit var cut: ByteFieldDataProvider<Any> @Mock private lateinit var random: Random @Before fun setUp() { cut = ByteFieldDataProvider(random) } @Test fun givenRandomByteValueWhenGenerateThenReturnsSameByte() { // Given doAnswer { invocation -> invocation.getArgument<ByteArray>(0)[0] = 113 null }.`when`(random).nextBytes(any()) // When val result = cut.invoke() // Then assertEquals(113.toByte(), result) } }
0
Kotlin
0
28
c5db0d07a3dda1b9215f767acde7f51d7c958070
1,001
RandomGenKt
MIT License
core/src/main/kotlin/io/github/shaksternano/borgar/core/util/ChannelEnvironment.kt
shaksternano
482,092,089
false
{"Kotlin": 617135}
package io.github.shaksternano.borgar.core.util enum class ChannelEnvironment( val displayName: String, val entityType: String, ) { GUILD("Guild", "guild"), /** * Direct message with this bot. */ DIRECT_MESSAGE("Direct Message", "user"), /** * Direct message between two other users, not with this bot. */ PRIVATE("Direct Message", "private"), GROUP("Group", "group"), ; companion object { val ALL: Set<ChannelEnvironment> = entries.toSet() fun fromEntityType(entityType: String): ChannelEnvironment? = entries.find { it.entityType == entityType } } }
2
Kotlin
3
10
68ae25a13547e9a4b020fe5bf1650e2f9343add1
649
borgar
MIT License
src/main/kotlin/io/github/ydwk/yde/impl/entities/StickerImpl.kt
YDWK
609,956,533
false
null
/* * Copyright 2022 YDWK 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 * * 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 io.github.ydwk.yde.impl.entities import com.fasterxml.jackson.databind.JsonNode import io.github.ydwk.yde.YDE import io.github.ydwk.yde.entities.Guild import io.github.ydwk.yde.entities.Sticker import io.github.ydwk.yde.entities.User import io.github.ydwk.yde.entities.sticker.StickerFormatType import io.github.ydwk.yde.entities.sticker.StickerType import io.github.ydwk.yde.util.EntityToStringBuilder import io.github.ydwk.yde.util.GetterSnowFlake class StickerImpl( override val yde: YDE, override val json: JsonNode, override val idAsLong: Long, ) : Sticker { override val packId: GetterSnowFlake? get() = if (json.has("pack_id")) GetterSnowFlake.of(json.get("pack_id").asLong()) else null override var description: String? = if (json.has("description")) json.get("description").asText() else null override var tags: List<String> = if (json.has("tags")) json.get("tags").map { it.asText() } else emptyList() override var type: StickerType = StickerType.fromInt(json.get("type").asInt()) override var formatType: StickerFormatType = StickerFormatType.fromInt(json.get("format_type").asInt()) override var available: Boolean = json.get("available").asBoolean() override val guild: Guild? get() = if (json.has("guild_id")) yde.getGuildById(json["guild_id"].asLong()) else null override var user: User? = if (json.has("user")) UserImpl(json["user"], json["user"]["id"].asLong(), yde) else null override var sortvarue: Int? = if (json.has("sort_value")) json.get("sort_value").asInt() else null override fun toString(): String { return EntityToStringBuilder(yde, this).name(this.name).toString() } override var name: String = json.get("name").asText() }
7
Kotlin
0
0
28e49a2a0ea89d565d0d289301b7b253ebece77d
2,397
YDE
Apache License 2.0
reelsplayer/src/main/java/com/shahid/iqbal/reelsplayer/actions/PlayerResizeMode.kt
Shahidzbi4213
831,392,350
false
{"Kotlin": 35209}
package com.shahid.iqbal.reelsplayer.actions import com.shahid.iqbal.reelsplayer.actions.PlayerResizeMode.FILL import com.shahid.iqbal.reelsplayer.actions.PlayerResizeMode.FIT import com.shahid.iqbal.reelsplayer.actions.PlayerResizeMode.FIXED_HEIGHT import com.shahid.iqbal.reelsplayer.actions.PlayerResizeMode.FIXED_WIDTH import com.shahid.iqbal.reelsplayer.actions.PlayerResizeMode.ZOOM /* * Created by <NAME> on 7/20/2024. */ /** * Class defining the various modes for resizing video content within the Reels Player. * * @property FIT Adjusts the video size to fit within the player's bounds while maintaining the aspect ratio. * @property FILL Scales the video to fill the entire player bounds, potentially cropping the video if necessary. * @property ZOOM Zooms into the video to fill the player's width or height, which may crop some parts of the video. * @property FIXED_WIDTH Maintains a fixed width for the video, adjusting the height to maintain aspect ratio. * @property FIXED_HEIGHT Maintains a fixed height for the video, adjusting the width to maintain aspect ratio. */ enum class PlayerResizeMode { FIT, FILL, ZOOM, FIXED_WIDTH, FIXED_HEIGHT }
0
Kotlin
1
20
cbaf6d06c81a42ff8a9516dc4ce99ab80e02b86d
1,177
SampleReelsApp
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/factory/events/RequestForPlacementAssessedFactory.kt
ministryofjustice
515,276,548
false
{"Kotlin": 8382511, "Shell": 15748, "Dockerfile": 1667, "Mustache": 383}
package uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.events import io.github.bluegroundltd.kfactory.Factory import io.github.bluegroundltd.kfactory.Yielded import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.events.model.RequestForPlacementAssessed import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.events.model.StaffMember import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomInt import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomStringMultiCaseWithNumbers import java.time.LocalDate import java.util.UUID class RequestForPlacementAssessedFactory : Factory<RequestForPlacementAssessed> { private var applicationId: Yielded<UUID> = { UUID.randomUUID() } private var applicationUrl: Yielded<String> = { randomStringMultiCaseWithNumbers(10) } private var placementApplicationId: Yielded<UUID> = { UUID.randomUUID() } private var assessedBy: Yielded<StaffMember> = { StaffMemberFactory().produce() } private var decision: Yielded<RequestForPlacementAssessed.Decision> = { RequestForPlacementAssessed.Decision.accepted } private var decisionSummary: Yielded<String?> = { randomStringMultiCaseWithNumbers(6) } private var expectedArrival: Yielded<LocalDate> = { LocalDate.now() } private var duration: Yielded<Int> = { randomInt(0, 1000) } fun withApplicationId(applicationId: UUID) = apply { this.applicationId = { applicationId } } fun withApplicationUrl(applicationUrl: String) = apply { this.applicationUrl = { applicationUrl } } fun withPlacementApplicationId(placementApplicationId: UUID) = apply { this.placementApplicationId = { placementApplicationId } } fun withAssessedBy(staffMember: StaffMember) = apply { this.assessedBy = { staffMember } } fun withDecision(decision: RequestForPlacementAssessed.Decision) = apply { this.decision = { decision } } fun withDecisionSummary(decisionSummary: String?) = apply { this.decisionSummary = { decisionSummary } } fun withExpectedArrival(expectedArrival: LocalDate) = apply { this.expectedArrival = { expectedArrival } } fun withDuration(duration: Int) = apply { this.duration = { duration } } override fun produce() = RequestForPlacementAssessed( applicationId = this.applicationId(), applicationUrl = this.applicationUrl(), placementApplicationId = this.placementApplicationId(), assessedBy = this.assessedBy(), decision = this.decision(), decisionSummary = this.decisionSummary(), expectedArrival = this.expectedArrival(), duration = this.duration(), ) }
20
Kotlin
1
5
e7a010b09c8000fbfc33d267db7814f255cd8a46
2,593
hmpps-approved-premises-api
MIT License
example/shared/src/commonMain/kotlin/com/splendo/kaluga/example/shared/model/scientific/converters/VolumeConverters.kt
splendo
191,371,940
false
null
/* Copyright 2023 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.example.shared.model.scientific.converters import com.splendo.kaluga.scientific.DefaultScientificValue import com.splendo.kaluga.scientific.PhysicalQuantity import com.splendo.kaluga.scientific.converter.volume.div import com.splendo.kaluga.scientific.converter.volume.times import com.splendo.kaluga.scientific.unit.* val PhysicalQuantity.Volume.converters get() = listOf<QuantityConverter<PhysicalQuantity.Volume, *>>( QuantityConverterWithOperator("Amount of Substance from Molarity", QuantityConverter.WithOperator.Type.Multiplication, PhysicalQuantity.Molarity) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Volume && rightUnit is Molarity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Amount of Substance from Molar Volume", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.MolarVolume) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Volume && rightUnit is MolarVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Area from Length", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Length) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is CubicMeter && rightUnit is Meter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicNanometer && rightUnit is Nanometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMicrometer && rightUnit is Micrometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMillimeter && rightUnit is Millimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicCentimeter && rightUnit is Centimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicDecimeter && rightUnit is Decimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicDecameter && rightUnit is Decameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicHectometer && rightUnit is Hectometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicKilometer && rightUnit is Kilometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMegameter && rightUnit is Megameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicGigameter && rightUnit is Gigameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is MetricVolume && rightUnit is MetricLength -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is Inch -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicFoot && rightUnit is Foot -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicYard && rightUnit is Yard -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMile && rightUnit is Mile -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is AcreInch && rightUnit is Inch -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is AcreFoot && rightUnit is Foot -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialLength -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialLength -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialLength -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Length -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Energy from Pressure", QuantityConverter.WithOperator.Type.Multiplication, PhysicalQuantity.Pressure) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is CubicCentimeter && rightUnit is Barye -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicCentimeter && rightUnit is BaryeMultiple -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicFoot && rightUnit is PoundSquareFoot -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is PoundSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is OunceSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is KiloPoundSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is KipSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is USTonSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is ImperialTonSquareInch -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is UKImperialPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is USCustomaryPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is UKImperialPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is USCustomaryPressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Pressure -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Length from Area", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Area) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is CubicMeter && rightUnit is SquareMeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicNanometer && rightUnit is SquareNanometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMicrometer && rightUnit is SquareMicrometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMillimeter && rightUnit is SquareMillimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicCentimeter && rightUnit is SquareCentimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicDecimeter && rightUnit is SquareDecimeter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicDecameter && rightUnit is SquareDecameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicHectometer && rightUnit is SquareHectometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicKilometer && rightUnit is SquareKilometer -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMegameter && rightUnit is SquareMegameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicGigameter && rightUnit is SquareGigameter -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is MetricVolume && rightUnit is MetricArea -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicInch && rightUnit is SquareInch -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicFoot && rightUnit is SquareFoot -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicYard && rightUnit is SquareYard -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is CubicMile && rightUnit is SquareMile -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is AcreInch && rightUnit is Acre -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is AcreFoot && rightUnit is Acre -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialArea -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialArea -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialArea -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Area -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Molar Volume from Amount of Substance", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.AmountOfSubstance) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricVolume && rightUnit is AmountOfSubstance -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is AmountOfSubstance -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is AmountOfSubstance -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is AmountOfSubstance -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is AmountOfSubstance -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Specific Volume from Weight", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Weight) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricVolume && rightUnit is MetricWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is UKImperialWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is USCustomaryWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is UKImperialWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is USCustomaryWeight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Weight -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Volumetric Flow from Time", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Time) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricVolume && rightUnit is Time -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is Time -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is Time -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is Time -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Time -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Weight from Density", QuantityConverter.WithOperator.Type.Multiplication, PhysicalQuantity.Density) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricVolume && rightUnit is MetricDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is UKImperialDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is USCustomaryDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is UKImperialDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is USCustomaryDensity -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is Density -> DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator("Weight from Specific Volume", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.SpecificVolume) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricVolume && rightUnit is MetricSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is ImperialSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is UKImperialSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is ImperialVolume && rightUnit is USCustomarySpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is ImperialSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is UKImperialVolume && rightUnit is UKImperialSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is ImperialSpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is USCustomaryVolume && rightUnit is USCustomarySpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) leftUnit is Volume && rightUnit is SpecificVolume -> DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } } )
76
Kotlin
6
180
7952c62c833aa9f905ae2f9cbd7acb9ba76d18ad
20,424
kaluga
Apache License 2.0
coil-base/src/main/java/coil/transition/TransitionTarget.kt
coil-kt
201,684,760
false
null
package coil.transition import android.graphics.drawable.Drawable import android.view.View import coil.target.Target /** * A [Target] that supports applying [Transition]s. */ interface TransitionTarget : Target { /** * The [View] used by this [Target]. */ val view: View /** * The [view]'s current [Drawable]. */ val drawable: Drawable? }
43
null
620
9,812
051e0b20969ff695d69b06cd72a1fdc9e504bf68
381
coil
Apache License 2.0
mbcarkit/src/main/java/com/daimler/mbcarkit/network/model/ApiAccountGroup.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.network.model import com.daimler.mbcarkit.business.model.accountlinkage.AccountLinkageGroup import com.google.gson.annotations.SerializedName internal data class ApiAccountGroup( @SerializedName("accountType") val accountType: ApiAccountType?, @SerializedName("iconUrl") val iconUrl: String?, @SerializedName("name") val name: String?, @SerializedName("bannerImageUrl") val bannerImageUrl: String?, @SerializedName("heading") val bannerTitle: String?, @SerializedName("description") val description: String?, @SerializedName("visible") val visible: Boolean, @SerializedName("accounts") val accounts: List<ApiAccountLinkage>? ) internal fun ApiAccountGroup.toAccountLinkageGroup() = AccountLinkageGroup( accountType?.toAccountType(), iconUrl, name, bannerImageUrl, bannerTitle, description, visible, accounts?.map { it.toAccountLinkage() } ?: emptyList() )
1
Kotlin
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
992
MBSDK-Mobile-Android
MIT License
app/src/main/java/com/wwxiaoqi/wechat_backup/utils/TimeUtils.kt
wwxiaoqi
302,557,758
false
{"Kotlin": 19371, "Shell": 15247, "Java": 1124}
package com.wwxiaoqi.wechat_backup.utils import java.text.SimpleDateFormat import java.util.* /** * 时间工具类 */ object TimeUtils { /*** * 获取当前时间日期 * @return 返回 yyyyMMdd 格式 */ val dataTime: String get() { val format = SimpleDateFormat("yyyyMMdd", Locale.CHINA) return format.format(Calendar.getInstance().time) } }
1
Kotlin
9
51
73df69284236b6c96c592835f415bb7eac71aeda
347
wechat_backup
Apache License 2.0
reactive-logger-example-kotlin/src/test/kotlin/io/github/numichi/reactive/logger/example/kotlin/controller/CoroutineLoggerControllerTest.kt
Numichi
448,675,398
true
{"Kotlin": 386596, "Java": 18115}
package io.github.numichi.reactive.logger.example.kotlin.controller import org.hamcrest.Matchers.isA import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.web.reactive.server.WebTestClient import java.util.* @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureWebTestClient internal class CoroutineLoggerControllerTest { @Autowired lateinit var webTestClient: WebTestClient @Test fun getSnapshotTest() { webTestClient.get() .uri("/coroutine/snapshot") .exchange() .expectBody() .jsonPath("$.length()").isEqualTo(2) .jsonPath("$.userId").value<Any> { isA<Any>(UUID::class.java) } .jsonPath("$.example").isEqualTo("example") } @Test fun getReadTest() { webTestClient.get() .uri("/coroutine/read") .exchange() .expectBody() .jsonPath("$.length()").isEqualTo(1) .jsonPath("$.userId").value<Any> { isA<Any>(UUID::class.java) } } /** * Console example: * ``` * {"message":"log0-information","context":{"userId":"5c827c39-9f5b-478f-b17e-5b8d493f57a7","example":"example"}} * ``` */ @Test fun doInfo0Test() { webTestClient.get() .uri("/coroutine/log0") .exchange() .expectStatus().isOk } /** * Console example (used logger 2x, because called twice in controller): * ``` * {"message":"log1-information","context":{"example":"example","foo":"bar"}} * {"message":"log1-information","context":{"example":"example","foo":"bar"}} * ``` */ @Test fun doInfo1Test() { webTestClient.get() .uri("/coroutine/log1") .exchange() .expectStatus().isOk } /** * Console example: * ``` * {"message":"log2-information","context":{"example":"n/a"}} * ``` */ @Test fun doInfo2Test() { webTestClient.get() .uri("/coroutine/log2") .exchange() .expectStatus().isOk } }
0
Kotlin
4
16
0b2eb0cac1b82c1e5a2771ca7b3166ddc56e3b6e
2,347
reactive-logger
Apache License 2.0
app/src/main/java/com/makaota/mammamskitchen/ui/fragments/OrdersFragment.kt
makaota
690,514,447
false
{"Kotlin": 294570}
package com.makaota.mammamskitchen.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.makaota.mammamskitchen.R import com.makaota.mammamskitchen.databinding.FragmentOrdersBinding import com.makaota.mammamskitchen.firestore.FirestoreClass import com.makaota.mammamskitchen.models.Order import com.makaota.mammamskitchen.ui.adapters.MyOrdersListAdapter import com.shashank.sony.fancytoastlib.FancyToast class OrdersFragment : BaseFragment() { private var _binding: FragmentOrdersBinding? = null private lateinit var swipeRefreshLayout: SwipeRefreshLayout // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentOrdersBinding.inflate(inflater, container, false) val root: View = binding.root swipeRefreshLayout = root.findViewById(R.id.swipe_refresh_layout) refreshPage() return root } override fun onResume() { super.onResume() getMyOrdersList() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun refreshPage(){ swipeRefreshLayout.setOnRefreshListener { getMyOrdersList() //Reload order List Items _binding!!.swipeRefreshLayout.isRefreshing = false } } // Create a function to get the success result of the my order list from cloud firestore. // START /** * A function to get the success result of the my order list from cloud firestore. * * @param ordersList List of my orders. */ fun populateOrdersListInUI(ordersList: ArrayList<Order>) { // Hide the progress dialog. hideProgressDialog() // Populate the orders list in the UI. // START if (ordersList.size > 0) { _binding!!.rvMyOrderItems.visibility = View.VISIBLE _binding!!.tvNoOrdersFound.visibility = View.GONE _binding!!.rvMyOrderItems.layoutManager = LinearLayoutManager(activity) _binding!!.rvMyOrderItems.setHasFixedSize(true) val myOrdersAdapter = MyOrdersListAdapter(requireActivity(), ordersList,this) _binding!!.rvMyOrderItems.adapter = myOrdersAdapter } else { _binding!!.rvMyOrderItems.visibility = View.GONE _binding!!.tvNoOrdersFound.visibility = View.VISIBLE } // END } // END // Create a function to call the firestore class function to get the list of my orders. // START /** * A function to get the list of my orders. */ private fun getMyOrdersList() { // Show the progress dialog. showProgressDialog(resources.getString(R.string.please_wait)) FirestoreClass().getMyOrdersList(this@OrdersFragment) } // END fun deleteDeliveredOrder(orderID: String){ showAlertDialogToDeleteDeliveredOrder(orderID) } // Create a function to show the alert dialog for the confirmation of delete product from cloud firestore. // START /** * A function to show the alert dialog for the confirmation of delete product from cloud firestore. */ private fun showAlertDialogToDeleteDeliveredOrder(orderID: String) { val builder = AlertDialog.Builder(requireActivity()) //set title for alert dialog builder.setTitle(resources.getString(R.string.delete_dialog_title)) //set message for alert dialog builder.setMessage(resources.getString(R.string.delete_order_dialog_message)) builder.setIcon(android.R.drawable.ic_dialog_alert) //performing positive action builder.setPositiveButton(resources.getString(R.string.yes)) { dialogInterface, _ -> // Call the function to delete the product from cloud firestore. // START // Show the progress dialog. showProgressDialog(resources.getString(R.string.please_wait)) // Call the function of Firestore class. FirestoreClass().deleteDeliveredOrder(this, orderID) // END dialogInterface.dismiss() } //performing negative action builder.setNegativeButton(resources.getString(R.string.no)) { dialogInterface, _ -> dialogInterface.dismiss() } // Create the AlertDialog val alertDialog: AlertDialog = builder.create() // Set other dialog properties alertDialog.setCancelable(false) alertDialog.show() } // Create a function to notify the success result of product deleted from cloud firestore. // START /** * A function to notify the success result of product deleted from cloud firestore. */ fun orderDeleteSuccess() { // Hide the progress dialog hideProgressDialog() Toast.makeText( requireActivity(), resources.getString(R.string.order_delete_success_message), Toast.LENGTH_SHORT ).show() // Get the latest products list from cloud firestore. getMyOrdersList() } // END }
0
Kotlin
0
1
50ea5ab768e92a94b8db83a5260df515218599ef
5,554
Mamma-Ms-Kitchen
MIT License
solar/src/main/java/com/chiksmedina/solar/bold/essentionalui/Revote.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.bold.essentionalui import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.bold.EssentionalUiGroup val EssentionalUiGroup.Revote: ImageVector get() { if (_revote != null) { return _revote!! } _revote = Builder( name = "Revote", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(10.4348f, 0.3062f) curveTo(10.7164f, 0.4216f, 10.9004f, 0.6958f, 10.9004f, 1.0001f) verticalLineTo(1.9779f) curveTo(11.2467f, 1.9769f, 11.6074f, 1.9769f, 11.9829f, 1.9769f) lineTo(12.0577f, 1.9769f) curveTo(14.1301f, 1.9769f, 15.7631f, 1.9769f, 17.0391f, 2.151f) curveTo(18.3498f, 2.3299f, 19.3952f, 2.705f, 20.2163f, 3.5386f) curveTo(21.0359f, 4.3706f, 21.4033f, 5.4272f, 21.5788f, 6.7523f) curveTo(21.75f, 8.0455f, 21.75f, 9.7014f, 21.75f, 11.8072f) verticalLineTo(11.9197f) curveTo(21.75f, 14.0255f, 21.75f, 15.6813f, 21.5788f, 16.9745f) curveTo(21.4033f, 18.2997f, 21.0359f, 19.3563f, 20.2163f, 20.1883f) curveTo(19.3952f, 21.0219f, 18.3498f, 21.397f, 17.0391f, 21.5758f) curveTo(15.7631f, 21.75f, 14.1301f, 21.75f, 12.0577f, 21.75f) horizontalLineTo(11.9423f) curveTo(9.8699f, 21.75f, 8.2369f, 21.75f, 6.9608f, 21.5758f) curveTo(5.6502f, 21.397f, 4.6048f, 21.0219f, 3.7837f, 20.1883f) curveTo(2.9641f, 19.3563f, 2.5967f, 18.2997f, 2.4212f, 16.9745f) curveTo(2.25f, 15.6813f, 2.25f, 14.0255f, 2.25f, 11.9197f) verticalLineTo(11.8072f) curveTo(2.25f, 9.7014f, 2.25f, 8.0455f, 2.4212f, 6.7523f) curveTo(2.5967f, 5.4272f, 2.9641f, 4.3706f, 3.7837f, 3.5386f) curveTo(4.0744f, 3.2435f, 4.5493f, 3.2399f, 4.8443f, 3.5306f) curveTo(5.1394f, 3.8213f, 5.143f, 4.2961f, 4.8523f, 4.5912f) curveTo(4.3539f, 5.0972f, 4.0623f, 5.7864f, 3.9083f, 6.9493f) curveTo(3.7515f, 8.1326f, 3.75f, 9.689f, 3.75f, 11.8634f) curveTo(3.75f, 14.0378f, 3.7515f, 15.5943f, 3.9083f, 16.7776f) curveTo(4.0623f, 17.9405f, 4.3539f, 18.6296f, 4.8523f, 19.1356f) curveTo(5.3492f, 19.6401f, 6.0235f, 19.934f, 7.1637f, 20.0896f) curveTo(8.3266f, 20.2483f, 9.8572f, 20.25f, 12.0f, 20.25f) curveTo(14.1428f, 20.25f, 15.6734f, 20.2483f, 16.8363f, 20.0896f) curveTo(17.9765f, 19.934f, 18.6508f, 19.6401f, 19.1477f, 19.1356f) curveTo(19.6461f, 18.6296f, 19.9377f, 17.9405f, 20.0917f, 16.7776f) curveTo(20.2485f, 15.5943f, 20.25f, 14.0378f, 20.25f, 11.8634f) curveTo(20.25f, 9.689f, 20.2485f, 8.1326f, 20.0917f, 6.9493f) curveTo(19.9377f, 5.7864f, 19.6461f, 5.0972f, 19.1477f, 4.5912f) curveTo(18.6508f, 4.0868f, 17.9765f, 3.7929f, 16.8363f, 3.6372f) curveTo(15.6734f, 3.4785f, 14.1428f, 3.4769f, 12.0f, 3.4769f) curveTo(11.6146f, 3.4769f, 11.2486f, 3.4769f, 10.9004f, 3.4779f) verticalLineTo(4.5542f) curveTo(10.9004f, 4.8586f, 10.7165f, 5.1328f, 10.4348f, 5.2482f) curveTo(10.1532f, 5.3636f, 9.8297f, 5.2974f, 9.6161f, 5.0805f) lineTo(7.8657f, 3.3036f) curveTo(7.5781f, 3.0116f, 7.5781f, 2.5429f, 7.8657f, 2.2509f) lineTo(9.6161f, 0.4738f) curveTo(9.8297f, 0.257f, 10.1532f, 0.1907f, 10.4348f, 0.3062f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(16.0303f, 10.0303f) curveTo(16.3232f, 9.7374f, 16.3232f, 9.2626f, 16.0303f, 8.9697f) curveTo(15.7374f, 8.6768f, 15.2626f, 8.6768f, 14.9697f, 8.9697f) lineTo(10.5f, 13.4393f) lineTo(9.0303f, 11.9697f) curveTo(8.7374f, 11.6768f, 8.2626f, 11.6768f, 7.9697f, 11.9697f) curveTo(7.6768f, 12.2625f, 7.6768f, 12.7374f, 7.9697f, 13.0303f) lineTo(9.9697f, 15.0303f) curveTo(10.2626f, 15.3232f, 10.7374f, 15.3232f, 11.0303f, 15.0303f) lineTo(16.0303f, 10.0303f) close() } } .build() return _revote!! } private var _revote: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
5,567
SolarIconSetAndroid
MIT License
app/src/androidTest/java/p/ritika/cricsummit/Challenge1ActivityTest.kt
riti-garg92
802,196,240
false
{"Kotlin": 21711}
package p.ritika.cricsummit import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import org.junit.Rule import org.junit.Test class Challenge1ActivityTest { @get:Rule val composeTestRule = createAndroidComposeRule<Challenge1Activity>() @Test fun testPredictOutcomeButton() { // Click to open the dropdown menu for selecting the bowl composeTestRule.onNodeWithText("Select Bowl").performClick() // Select "Bouncer" from the dropdown menu composeTestRule.onNodeWithText("Bouncer").performClick() // Click to open the dropdown menu for selecting the shot composeTestRule.onNodeWithText("Select Shot").performClick() // Select "SquareCut" from the dropdown menu composeTestRule.onNodeWithText("Straight").performClick() // Click to open the dropdown menu for selecting the timing composeTestRule.onNodeWithText("Select Timing").performClick() // Select "Perfect" from the dropdown menu composeTestRule.onNodeWithText("Early").performClick() // Click the button to predict the outcome composeTestRule.onNodeWithText("Predict Outcome").performClick() } }
0
Kotlin
0
0
36cfc708002a54ec44b7ca8a071c2a7cf08090ed
1,291
CricSummit
MIT License
src/test/kotlin/tel/schich/pgcryptokt/OptionParsingTests.kt
pschichtel
580,590,611
false
null
package tel.schich.pgcryptokt import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import tel.schich.pgcryptokt.pgp.pgp_pub_decrypt import tel.schich.pgcryptokt.pgp.pgp_pub_decrypt_bytea import tel.schich.pgcryptokt.pgp.pgp_pub_encrypt import tel.schich.pgcryptokt.pgp.pgp_pub_encrypt_bytea import tel.schich.pgcryptokt.pgp.pgp_sym_decrypt import tel.schich.pgcryptokt.pgp.pgp_sym_decrypt_bytea import tel.schich.pgcryptokt.pgp.pgp_sym_encrypt import tel.schich.pgcryptokt.pgp.pgp_sym_encrypt_bytea class OptionParsingTests { @Test fun rejectsUnknownOption() { assertThrows<IllegalStateException> { pgp_sym_encrypt("some test", "password", "cipher=aes256") } assertThrows<IllegalStateException> { pgp_sym_encrypt_bytea("some test".toByteArray(), "password", "cipher=aes256") } assertThrows<IllegalStateException> { pgp_sym_decrypt("some test".toByteArray(), "password", "cipher=aes256") } assertThrows<IllegalStateException> { pgp_sym_decrypt_bytea("some test".toByteArray(), "password", "cipher=aes256") } assertThrows<IllegalStateException> { pgp_pub_encrypt("some test", "password".toByteArray(), "cipher=aes256") } assertThrows<IllegalStateException> { pgp_pub_encrypt_bytea("some test".toByteArray(), "password".toByteArray(), "cipher=aes256") } assertThrows<IllegalStateException> { pgp_pub_decrypt("some test".toByteArray(), "password".toByteArray(), options = "cipher=aes256") } assertThrows<IllegalStateException> { pgp_pub_decrypt_bytea("some test".toByteArray(), "password".toByteArray(), options = "cipher=aes256") } } }
2
Kotlin
0
0
2c2825e440a597144041e2c809776fca9e4aa706
1,794
pgcrypto-kt
MIT License
FragViewModel/app/src/main/java/edu/tomerbu/fragviewmodel/ui/main/User.kt
TomerBu
275,783,874
false
null
package edu.tomerbu.fragviewmodel.ui.main class User (var name:String){ }
0
Kotlin
0
0
9d585a10719b6879552188d8a3b53817fc6b7f35
76
Calculator
Apache License 2.0
library/src/main/java/com/utkukutlu/library/cherryslider/ViewPagerAdapter.kt
utkukutlu
179,468,604
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 7, "XML": 17, "Java": 2}
package com.utkukutlu.library.cherryslider import android.content.Context import android.support.v4.view.PagerAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions class ViewPagerAdapter(context: Context?) : PagerAdapter() { private var imageList: List<CherrySliderModel>? = arrayListOf() private var layoutInflater: LayoutInflater? = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater? private var itemClickListener: ItemClickListener? = null override fun isViewFromObject(view: View, obj: Any): Boolean { return view == obj } override fun getCount(): Int { return imageList?.size ?: 0 } override fun instantiateItem(container: ViewGroup, position: Int): View { val itemView = layoutInflater!!.inflate(R.layout.item_cherry_slider, container, false) val imageView = itemView.findViewById<ImageView>(R.id.image_view) val linearLayout = itemView.findViewById<LinearLayout>(R.id.linear_layout) val textView = itemView.findViewById<TextView>(R.id.text_view) if (imageList?.get(position)?.title != null) { linearLayout.visibility = View.VISIBLE textView.text = imageList?.get(position)?.title } else { linearLayout.visibility = View.INVISIBLE } if (imageList?.get(position)?.imageUrl == null) { val img = Glide.with(imageView.context).load(imageList?.get(position)?.imagePath) imageList?.get(position)?.scale?.let { img.apply(getScale(it)) } img.into(imageView) } else { val img = Glide.with(imageView.context).load(imageList?.get(position)?.imageUrl) imageList?.get(position)?.scale?.let { img.apply(getScale(it)) } img.into(imageView) } itemView.setOnClickListener { itemClickListener?.onItemSelected(position) } container.addView(itemView) return itemView } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { container.removeView(obj as RelativeLayout) } fun setItemClickListener(itemClickListener: ItemClickListener) { this.itemClickListener = itemClickListener } fun replaceData(items: List<CherrySliderModel>) { imageList = items notifyDataSetChanged() } private fun getScale(scale: CherrySlider.Scale): RequestOptions { return when { scale == CherrySlider.Scale.FIT_CENTER -> RequestOptions.fitCenterTransform() scale == CherrySlider.Scale.CENTER_CROP -> RequestOptions.centerCropTransform() scale == CherrySlider.Scale.CENTER_INSIDE -> RequestOptions.centerInsideTransform() else -> RequestOptions.centerInsideTransform() } } }
0
Kotlin
0
0
535a9b3f79168b82f83b7c935f3dc1608b88d175
3,115
cherry-slider
Apache License 2.0
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/PerformanceInfoTest.kt
embrace-io
704,537,857
false
{"Kotlin": 3108474, "C": 189946, "Java": 179438, "C++": 13140, "CMake": 4188}
package io.embrace.android.embracesdk import io.embrace.android.embracesdk.payload.DiskUsage import io.embrace.android.embracesdk.payload.PerformanceInfo import org.junit.Assert.assertNotNull import org.junit.Test internal class PerformanceInfoTest { private val diskUsage: DiskUsage = DiskUsage(10000000, 2000000) @Test fun testPerfInfoSerialization() { assertJsonMatchesGoldenFile("perf_info_expected.json", buildPerformanceInfo()) } @Test fun testPerfInfoDeserialization() { val obj = deserializeJsonFromResource<PerformanceInfo>("perf_info_expected.json") assertNotNull(obj) } @Test fun testPerfInfoEmptyObject() { val obj = deserializeEmptyJsonString<PerformanceInfo>() assertNotNull(obj) } private fun buildPerformanceInfo(): PerformanceInfo = PerformanceInfo(diskUsage = diskUsage) }
9
Kotlin
7
130
7ae6904f31de6d7d3e2b5ec5093f8abcd0ccf884
882
embrace-android-sdk
Apache License 2.0
glimpse/core/src/commonMain/kotlin/types/Mat4.kt
glimpse-graphics
319,730,354
false
null
/* * Copyright 2020-2023 Glimpse Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package graphics.glimpse.types import kotlin.reflect.KClass /** * A 4×4 matrix. */ data class Mat4<T>( /** * Elements of this matrix. */ override val elements: List<T>, /** * Type of matrix elements. * * @since v2.0.0 */ override val type: KClass<T> ) : BaseMat<T, Mat4<T>, Vec4<T>>( dimension = MATRIX_DIMENSION ) where T : Number, T : Comparable<T> { private val comatrix: Mat4<T> by lazy { create(transform { row, col -> cofactor(row, col) }) } init { validate() } /** * Returns a 4×4 matrix with given [elements]. */ override fun create(elements: List<T>): Mat4<T> = copy(elements = elements) /** * Returns a 3D vector with given [coordinates]. */ override fun createVector(coordinates: List<T>): Vec4<T> = Vec4.fromList(coordinates, type = this.type) /** * Returns a determinant of this matrix. */ override fun det(): T = indices.map { col -> this[0, col] * cofactor(row = 0, col) }.sum(this.type) private fun cofactor(row: Int, col: Int): T = minor(row = row, col = col) * (if ((row + col) % 2 == 0) one(this.type) else -one(this.type)) private fun minor(row: Int, col: Int): T = submatrix(row, col).det() private fun submatrix(withoutRow: Int, withoutCol: Int): Mat3<T> = Mat3( elements = indices.flatMap { col -> indices.map { row -> row to col } } .filter { (row, col) -> row != withoutRow && col != withoutCol } .map { (row, col) -> this[row, col] }, type = this.type ) /** * Returns an adjugate of this matrix. */ override fun adj(): Mat4<T> = comatrix.transpose() /** * Returns a 4×4 float matrix equal to this matrix. * * @since v2.0.0 */ fun toFloatMatrix(): Mat4<Float> = Mat4(elements = this.elements.map { it.toFloat() }, type = Float::class) /** * Returns a 4×4 double-precision float matrix equal to this matrix. * * @since v2.0.0 */ fun toDoubleMatrix(): Mat4<Double> = Mat4(elements = this.elements.map { it.toDouble() }, type = Double::class) /** * Returns a 2×2 submatrix of this matrix, obtained by deleting the last two rows and the last two columns * of this 4×4 matrix. * * @since v1.1.0 */ fun toMat2(): Mat2<T> = toMat3().toMat2() /** * Returns a 3×3 submatrix of this matrix, obtained by deleting the last row and the last column * of this 4×4 matrix. */ fun toMat3(): Mat3<T> = submatrix( withoutRow = indices.last, withoutCol = indices.last ) companion object { private const val MATRIX_DIMENSION = 4 /** * A 4×4 identity matrix. */ @Deprecated( message = "Use Mat4.identity() instead.", replaceWith = ReplaceWith(expression = "Mat4.identity<Float>()") ) val identity: Mat4<Float> = Mat4( listOf( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ) ) /** * Returns a 4×4 identity matrix. * * @since v2.0.0 */ inline fun <reified T> identity(): Mat4<T> where T : Number, T : Comparable<T> = identity(T::class) /** * Returns a 4×4 identity matrix with elements of given [type]. * * @since v2.0.0 */ fun <T> identity(type: KClass<T>): Mat4<T> where T : Number, T : Comparable<T> { val zero = zero(type) val one = one(type) return Mat4( elements = listOf( one, zero, zero, zero, zero, one, zero, zero, zero, zero, one, zero, zero, zero, zero, one ), type = type ) } } } /** * Returns a new 4×4 matrix from given [elements]. * * @since v2.0.0 */ @Suppress("FunctionNaming") inline fun <reified T> Mat4(elements: List<T>): Mat4<T> where T : Number, T : Comparable<T> = Mat4(elements = elements, type = T::class)
5
Kotlin
0
6
e00a9f22db9e10493e7711d5dd8524eb7b06be77
4,894
glimpse
Apache License 2.0
src/main/kotlin/com/github/dxahtepb/etcdidea/view/editor/actions/DeleteKeyAction.kt
dxahtepb
300,450,509
false
null
package com.github.dxahtepb.etcdidea.view.editor.actions import com.github.dxahtepb.etcdidea.EtcdBundle import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent class DeleteKeyAction : AnAction( EtcdBundle.getMessage("editor.kv.action.deleteKey.text"), EtcdBundle.getMessage("editor.kv.action.deleteKey.description"), AllIcons.General.Remove ) { override fun actionPerformed(e: AnActionEvent) { EtcdEditorActionUtil.getFileEditor(e)?.editorPanel?.deleteSelectedKey() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = EtcdEditorActionUtil.isRowSelected(e) } }
0
Kotlin
0
3
4579b6666382a6bb460d9564bba3908d6e14793d
729
etcd-idea
Apache License 2.0
app/src/main/java/com/notas/inventory/UnionViewModel.kt
rubenesteban
641,077,804
false
null
package com.notas.inventory import android.os.Build import android.os.Environment import androidx.annotation.RequiresApi import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.itextpdf.text.* import com.itextpdf.text.pdf.PdfPTable import com.itextpdf.text.pdf.PdfWriter import com.notas.inventory.data.Item import com.notas.inventory.data.ItemsRepository import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.time.LocalDateTime class UnionViewModel(itemsRepository: ItemsRepository) : ViewModel() { val contracts = LocalContext //var listaInf: ArrayList<Informacion> = arrayListOf() private val TAG: String = "Reebook" val pdfUiState: StateFlow<PdfUiState> = itemsRepository.getAllItemsStream().map { PdfUiState(it) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS), initialValue = PdfUiState() ) companion object { private const val TIMEOUT_MILLIS = 5_000L } private var Work: List<Item> = listOf<Item>() private var Milk: List<Item> = listOf<Item>() private var yun: MutableList<String> = mutableListOf<String>() private var eli: MutableSet<String> = mutableSetOf<String>("") var job: List<String> = listOf<String>() private var tin = itemsRepository.getAllItemsStream() suspend fun checkFlow(f:Flow<List<Item>>): List<Item> { val elo = f.collect{ _ -> Work} val mu = Work return mu } fun listare(a: MutableList<Item>): List<Item> { val ls = a.asSequence().toList() return ls } var can by mutableStateOf("") private set fun checkList(): ArrayList<Item> { viewModelScope.launch { Work = pdfUiState.value.itemList as MutableList<Item> var yup = checkFlow(tin) Milk = yup } val elo = Milk val mu = elo as ArrayList<Item> return mu } fun golf(r: List<Double>): Double { var mil:Double=0.0 for (i in r.indices) { mil += r[i] } return mil } @RequiresApi(Build.VERSION_CODES.O) fun hora(): LocalDateTime? { val datelime = LocalDateTime.now() return datelime } // var elo = pdfUiState.value.itemList // var listaUsuarios1: ArrayList<Item> = elo as ArrayList<Item> // var listaUsuarios1: ArrayList<Item> = arrayListOf() @RequiresApi(Build.VERSION_CODES.O) fun crearPDF(u: List<String>, r: List<Double>, p: List<Int>) { try { val carpeta = "/file-pdf" val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + carpeta val dir = File(path) if (!dir.exists()) { dir.mkdirs() //Toast.makeText(context, "CARPETA CREADA", Toast.LENGTH_SHORT).show() } val h = hora() val file = File(dir, "pdf$h.pdf") val fileOutputStream = FileOutputStream(file) val mas = golf(r).toString() val listUsurious1: Flow<List<Item>> = tin // val listUsurious1: Flow<List<Item>> = tin val documento = Document() PdfWriter.getInstance(documento, fileOutputStream) documento.open() val titulo3 = Paragraph( "\t\t\t Nota de Venta \n\n\n", FontFactory.getFont("arial", 22f, Font.BOLD, BaseColor.BLUE) ) val titulo2 = Paragraph( "\t\t\t Detalles \n\n", FontFactory.getFont("arial", 22f, Font.BOLD, BaseColor.BLUE) ) val titulo1 = Paragraph( "Lista de Compras \n\n", FontFactory.getFont("arial", 22f, Font.BOLD, BaseColor.BLUE) ) //val emo = checkList() //val mik = emo.size.toString() // var listaUsuarios1: ArrayList<Item> = emo documento.add(titulo3) val tabla1 = PdfPTable(3) tabla1.addCell("UNIT") tabla1.addCell("PRODUCT") tabla1.addCell("PRICE") for (i in u.indices) { tabla1.addCell(p[i].toString()) tabla1.addCell(u[i]) tabla1.addCell(r[i].toString()) } tabla1.addCell("") tabla1.addCell("SubTotal =") tabla1.addCell(mas) val tabla2 = PdfPTable(3) tabla2.addCell(h.toString()) tabla2.addCell("Find here:") tabla2.addCell("https://n9.cl/abeja77") documento.add(titulo1) documento.add(tabla1) documento.add(titulo2) documento.add(tabla2) documento.close() } catch (e: FileNotFoundException) { e.printStackTrace(); } catch (e: DocumentException) { e.printStackTrace() } } } data class PdfUiState(val itemList: List<Item> = listOf())
0
Kotlin
0
0
3b0bff5038fe96a908c0343b1e010e5d86b62351
5,447
notas
Apache License 2.0
src/main/kotlin/at/kanzler/codingcompetitionbackend/dto/ResetPasswordDto.kt
KonstiTheProgrammer
458,492,373
false
{"Kotlin": 63612, "HTML": 308, "Dockerfile": 113}
package at.kanzler.codingcompetitionbackend.dto data class ResetPasswordDto(val password: String)
0
Kotlin
0
0
5c7411b072549f21fdd057f6ee9a998a3d641e56
98
CodingCompetitionBackend
MIT License
app/src/main/kotlin/com/qrcode/ai/app/ui/main/ui/no_internet/NoInternetFragment.kt
Lamle200028
696,085,104
false
{"Kotlin": 243666}
package com.qrcode.ai.app.ui.main.ui.no_internet import android.content.Intent import android.net.wifi.WifiManager import android.util.Log import androidx.navigation.fragment.findNavController import com.ads.control.admob.AppOpenManager import com.qrcode.ai.app.R import com.qrcode.ai.app.databinding.FragmentNoInternetBinding import com.qrcode.ai.app.platform.BaseFragment import com.qrcode.ai.app.utils.NetworkUtil class NoInternetFragment : BaseFragment<FragmentNoInternetBinding>() { override fun onResume() { super.onResume() if (NetworkUtil.isInternetAvailable(requireContext())) { findNavController().popBackStack() } AppOpenManager.getInstance().disableAppResume() } override fun setupListener() { binding.btnConnect.setOnClickListener { startActivity(Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)) AppOpenManager.getInstance().disableAdResumeByClickAction() } } override val layoutId: Int = R.layout.fragment_no_internet }
0
Kotlin
0
0
0041146af62f4243a403d6b15c6c3511026efaef
1,041
XmastCall
MIT License
RecyclerViewAppExercise/app/src/main/java/com/example/bruno/recyclerviewappexercise/presenter/NewCoinPresenterImpl.kt
brunokarpo
130,281,888
false
null
package com.example.bruno.recyclerviewappexercise.presenter import com.example.bruno.recyclerviewappexercise.contracts.NewCoinContract import com.example.bruno.recyclerviewappexercise.model.Coin import com.example.bruno.recyclerviewappexercise.repository.CoinRepository class NewCoinPresenterImpl(private val newCoinView: NewCoinContract.NewCoinView): NewCoinContract.NewCoinPresenter { private var coinRepository = CoinRepository.instance override fun addNewCoin(name: String, value: Double) { var coin = Coin() coin.name = name coin.value = value coinRepository.save(coin) newCoinView.completeActivity() } }
0
Kotlin
0
0
1acb5381603e501bd4421d64084438b2e8029654
668
android-kotlin
The Unlicense
app/src/main/java/com/example/kotlin/viewmodel/HomeActivityViewModel.kt
1322688717
647,643,244
false
null
package com.example.kotlin.viewmodel import android.app.Activity import android.widget.Toast import androidx.lifecycle.ViewModel class HomeActivityViewModel : ViewModel() { private var firstTime: Long = 0 // 记录点击返回时第一次的时间毫秒值 fun exitApp(timeInterval: Long, mActivity: Activity) { // 第一次肯定会进入到if判断里面,然后把firstTime重新赋值当前的系统时间 // 然后点击第二次的时候,当点击间隔时间小于2s,那么退出应用;反之不退出应用 if (System.currentTimeMillis() - firstTime >= timeInterval) { Toast.makeText(mActivity, "再按一次推出程序", Toast.LENGTH_SHORT).show() firstTime = System.currentTimeMillis() } else { mActivity.finish() // 销毁当前activity System.exit(0) // 完全退出应用 } } }
0
Kotlin
0
0
2fbc2d0bb9f66911bd7b00c626779861d53669f0
707
kotlin
Apache License 2.0
library/drive/src/main/kotlin/xyz/fcampbell/rxplayservices/drive/RxDriveFolder.kt
francoiscampbell
75,945,848
true
null
package xyz.fcampbell.rxplayservices.drive import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.drive.* import com.google.android.gms.drive.query.Query import io.reactivex.Observable import xyz.fcampbell.rxplayservices.base.RxWrappedApi /** * Wraps [DriveFolder] */ @Suppress("unused") class RxDriveFolder( override val apiClient: Observable<GoogleApiClient>, override val original: DriveFolder ) : RxWrappedApi<DriveFolder>, RxDriveResource<DriveFolder>(apiClient, original) { fun listChildren(): Observable<DriveApi.MetadataBufferResult> { return fromPendingResult { listChildren(it) } } fun queryChildren(query: Query): Observable<DriveApi.MetadataBufferResult> { return fromPendingResult { queryChildren(it, query) } } fun createFile(changeSet: MetadataChangeSet, driveContents: DriveContents): Observable<RxDriveFile> { return fromPendingResult { createFile(it, changeSet, driveContents) } .map { RxDriveFile(apiClient, it.driveFile) } } fun createFile(changeSet: MetadataChangeSet, driveContents: DriveContents, executionOptions: ExecutionOptions): Observable<RxDriveFile> { return fromPendingResult { createFile(it, changeSet, driveContents, executionOptions) } .map { RxDriveFile(apiClient, it.driveFile) } } fun createFolder(changeSet: MetadataChangeSet): Observable<RxDriveFolder> { return fromPendingResult { createFolder(it, changeSet) } .map { RxDriveFolder(apiClient, it.driveFolder) } } }
1
Kotlin
2
10
b7461e4534a81d78f7bf70a6047395b059e61c3c
1,594
RxPlayServices
Apache License 2.0
src/main/java/io/github/light0x00/lightregex/ast/ShorthandToken.kt
light0x00
620,782,615
false
null
package io.github.light0x00.lightregex.ast import io.github.light0x00.lightregex.common.Unicode import java.util.Objects class ShorthandToken(val symbol: Int) : AbstractToken(TokenType.SHORTHAND_SYMBOL) { override fun toString(): String { return "\\" + Unicode.toString(symbol) } override fun copy(): ShorthandToken { return ShorthandToken(symbol) } override fun equals(other: Any?): Boolean { return when (other) { is ShorthandToken -> other.symbol == symbol else -> false } } override fun hashCode(): Int { return Objects.hash(TokenType.SHORTHAND_SYMBOL, symbol) } }
0
Kotlin
0
1
cb80c9a808ef42097153a6d968d866828ee221e6
669
light-regex
MIT License
libraries/apollo-api/src/commonMain/kotlin/com/apollographql/apollo/api/Operations.kt
apollographql
69,469,299
false
null
@file:JvmName("Operations") package com.apollographql.apollo.api import com.apollographql.apollo.annotations.ApolloExperimental import com.apollographql.apollo.api.internal.ResponseParser import com.apollographql.apollo.api.json.JsonReader import com.apollographql.apollo.api.json.JsonWriter import com.apollographql.apollo.api.json.buildJsonString import com.apollographql.apollo.api.json.writeObject import com.apollographql.apollo.exception.ApolloException import com.apollographql.apollo.exception.ApolloNetworkException import com.apollographql.apollo.exception.JsonDataException import com.apollographql.apollo.exception.JsonEncodingException import com.benasher44.uuid.Uuid import com.benasher44.uuid.uuid4 import okio.IOException import okio.use import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads /** * Reads a GraphQL Json response like below to a [ApolloResponse] * ``` * { * "data": ... * "errors": ... * "extensions": ... * } * ``` */ @JvmOverloads fun <D : Operation.Data> Operation<D>.composeJsonRequest( jsonWriter: JsonWriter, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, ) { jsonWriter.writeObject { name("operationName") value(name()) name("variables") writeObject { serializeVariables(this, customScalarAdapters, false) } name("query") value(document()) } } /** * Reads a GraphQL Json response to a [ApolloResponse]. GraphQL Json responses look like so: * * ``` * { * "data": ... * "errors": ... * "extensions": ... * } * ``` * * This method takes ownership of [jsonReader] and will always close it * * @throws IOException if reading [jsonReader] fails * @throws JsonEncodingException if the data is not valid json * @throws JsonDataException if the data is not of the expected type */ @JvmOverloads @Deprecated("Use parseResponse or jsonReader.toApolloResponse() instead", ReplaceWith("parseResponse()")) fun <D : Operation.Data> Operation<D>.parseJsonResponse( jsonReader: JsonReader, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, deferredFragmentIdentifiers: Set<DeferredFragmentIdentifier>? = null, ): ApolloResponse<D> { return jsonReader.use { ResponseParser.parse( it, this, null, customScalarAdapters, deferredFragmentIdentifiers, ) } } /** * Reads a GraphQL Json response like below to a [ApolloResponse]. GraphQL Json responses look like so: * * ``` * { * "data": ... * "errors": ... * "extensions": ... * } * ``` * * By default, this method does not close the [jsonReader] * * @see [toApolloResponse] */ @JvmOverloads fun <D : Operation.Data> Operation<D>.parseResponse( jsonReader: JsonReader, requestUuid: Uuid? = null, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, deferredFragmentIdentifiers: Set<DeferredFragmentIdentifier>? = null, ): ApolloResponse<D> { return try { ResponseParser.parse( jsonReader, this, requestUuid, customScalarAdapters, deferredFragmentIdentifiers, ) } catch (throwable: Throwable) { ApolloResponse.Builder(requestUuid = requestUuid ?: uuid4(), operation = this) .exception(exception = throwable.wrapIfNeeded()) .isLast(true) .build() } } private fun Throwable.wrapIfNeeded(): ApolloException { return if (this is ApolloException) { this } else { ApolloNetworkException( message = "Error while reading JSON response", platformCause = this ) } } /** * writes a successful GraphQL Json response containing "data" to the given sink. * * Use this for testing/mocking a valid GraphQL response */ @JvmOverloads fun <D : Operation.Data> Operation<D>.composeJsonResponse( jsonWriter: JsonWriter, data: D, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, ) { jsonWriter.use { it.writeObject { name("data") adapter().toJson(this, customScalarAdapters, data) } } } @ApolloExperimental fun <D : Operation.Data> Operation<D>.composeJsonResponse( data: D, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, ): String { return buildJsonString { writeObject { name("data") adapter().toJson(this, customScalarAdapters, data) } } } /** * Reads a single [ApolloResponse] from [this]. Returns an error response if [this] contains * more than one JSON response or trailing tokens. * [toApolloResponse] takes ownership and closes [this]. * * @return the parsed [ApolloResponse] * @see parseResponse */ @ApolloExperimental fun <D : Operation.Data> JsonReader.toApolloResponse( operation: Operation<D>, requestUuid: Uuid? = null, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, deferredFragmentIdentifiers: Set<DeferredFragmentIdentifier>? = null, ): ApolloResponse<D> { return use { try { ResponseParser.parse( this, operation, requestUuid, customScalarAdapters, deferredFragmentIdentifiers, ).also { if (peek() != JsonReader.Token.END_DOCUMENT) { throw JsonDataException("Expected END_DOCUMENT but was ${peek()}") } } } catch (throwable: Throwable) { ApolloResponse.Builder(requestUuid = requestUuid ?: uuid4(), operation = operation) .exception(exception = throwable.wrapIfNeeded()) .isLast(true) .build() } } } /** * Reads a [ApolloResponse] from [this]. * The caller is responsible for closing [this]. * * @return the parsed [ApolloResponse] * @see [toApolloResponse] */ @ApolloExperimental fun <D : Operation.Data> JsonReader.parseResponse( operation: Operation<D>, requestUuid: Uuid? = null, customScalarAdapters: CustomScalarAdapters = CustomScalarAdapters.Empty, deferredFragmentIdentifiers: Set<DeferredFragmentIdentifier>? = null, ): ApolloResponse<D> { return try { ResponseParser.parse( this, operation, requestUuid, customScalarAdapters, deferredFragmentIdentifiers, ) } catch (throwable: Throwable) { ApolloResponse.Builder(requestUuid = requestUuid ?: uuid4(), operation = operation) .exception(exception = throwable.wrapIfNeeded()) .isLast(true) .build() } }
164
null
651
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
6,418
apollo-kotlin
MIT License
kgl-vulkan/src/nativeMain/kotlin/com/kgl/vulkan/enums/ShadingRatePaletteEntryNV.kt
BrunoSilvaFreire
223,607,080
true
{"Kotlin": 1880529, "C": 10037}
/** * Copyright [2019] [<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 com.kgl.vulkan.enums import com.kgl.vulkan.utils.VkEnum import cvulkan.* actual enum class ShadingRatePaletteEntryNV(override val value: VkShadingRatePaletteEntryNV) : VkEnum<ShadingRatePaletteEntryNV> { NO_INVOCATIONS(VK_SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV), `16_INVOCATIONS_PER_PIXEL`(VK_SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV), `8_INVOCATIONS_PER_PIXEL`(VK_SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV), `4_INVOCATIONS_PER_PIXEL`(VK_SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV), `2_INVOCATIONS_PER_PIXEL`(VK_SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV), `1_INVOCATION_PER_PIXEL`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV), `1_INVOCATION_PER_2X1_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV), `1_INVOCATION_PER_1X2_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV), `1_INVOCATION_PER_2X2_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV), `1_INVOCATION_PER_4X2_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV), `1_INVOCATION_PER_2X4_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV), `1_INVOCATION_PER_4X4_PIXELS`(VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV); companion object { fun from(value: VkShadingRatePaletteEntryNV): ShadingRatePaletteEntryNV = enumValues<ShadingRatePaletteEntryNV>()[value.toInt()] } }
0
null
0
0
74de23862c29404e7751490331cbafbef310bd63
2,038
kgl
Apache License 2.0
app/src/main/java/wardani/dika/moviedbmandiri/model/ProductionCompany.kt
dikawardani24
292,583,501
false
null
package wardani.dika.moviedbmandiri.model import wardani.dika.moviedbmandiri.api.response.ProductionCompanyResponse data class ProductionCompany( var id: Int, var name: String, var logoPath: String?, var originCountry: String ) { companion object { fun from(productionCompanyResponse: ProductionCompanyResponse): ProductionCompany { return ProductionCompany( id = productionCompanyResponse.id, name = productionCompanyResponse.name, logoPath = productionCompanyResponse.logoPath, originCountry = productionCompanyResponse.originCountry ) } } }
0
Kotlin
0
0
b1992a8398228ac33420d5b13229836c118b0ec2
705
movieDbMandiri
MIT License
core/src/main/kotlin/com/bartlomiejpluta/smnp/evaluation/evaluator/ImportEvaluator.kt
bartlomiej-pluta
247,806,164
false
null
package com.bartlomiejpluta.smnp.evaluation.evaluator import com.bartlomiejpluta.smnp.dsl.ast.model.node.IdentifierNode import com.bartlomiejpluta.smnp.dsl.ast.model.node.ImportNode import com.bartlomiejpluta.smnp.dsl.ast.model.node.Node import com.bartlomiejpluta.smnp.environment.Environment import com.bartlomiejpluta.smnp.error.SmnpException import com.bartlomiejpluta.smnp.evaluation.model.entity.EvaluatorOutput import com.bartlomiejpluta.smnp.evaluation.util.ContextExceptionFactory.wrapWithContext class ImportEvaluator : Evaluator() { override fun supportedNodes() = listOf(ImportNode::class) override fun tryToEvaluate(node: Node, environment: Environment): EvaluatorOutput { val path = (node as ImportNode).path.joinToString(".") { (it as IdentifierNode).token.rawValue } try { environment.loadModule(path) } catch (e: SmnpException) { throw wrapWithContext(e, node.position, environment) } return EvaluatorOutput.ok() } }
0
Kotlin
0
0
88f2089310b2a23b2ce63fb6be23a96db156ea4a
995
smnp-kt
MIT License
kotlin/kotlin-samples/src/main/kotlin/ru/mydesignstudio/kotlin/samples/person/PersonDao.kt
aabarmin
229,590,264
false
{"Java": 315375, "Shell": 9120, "Kotlin": 7474, "HTML": 2057, "Dockerfile": 830, "Ruby": 67}
package ru.mydesignstudio.kotlin.samples.person interface PersonDao { fun findPerson(id: Int): Person fun savePerson(person: Person): Person fun delete(person: Person) fun findAll(): Collection<Person> }
24
Java
0
0
051e7ab98d866ed15e84a0f32b4e1522020a04c8
224
tutorials
MIT License
grovlin-compiler/src/main/kotlin/io/gitlab/arturbosch/grovlin/compiler/backend/builtins/EqualsToJava.kt
arturbosch
80,819,243
false
null
package io.gitlab.arturbosch.grovlin.compiler.backend.builtins import com.github.javaparser.ast.NodeList import com.github.javaparser.ast.expr.BinaryExpr import com.github.javaparser.ast.expr.EnclosedExpr import com.github.javaparser.ast.expr.MethodCallExpr import com.github.javaparser.ast.expr.UnaryExpr import io.gitlab.arturbosch.grovlin.ast.EqualExpression import io.gitlab.arturbosch.grovlin.ast.Expression import io.gitlab.arturbosch.grovlin.ast.ObjectOrTypeType import io.gitlab.arturbosch.grovlin.ast.PrimitiveType import io.gitlab.arturbosch.grovlin.ast.UnequalExpression import io.gitlab.arturbosch.grovlin.compiler.backend.toJava import com.github.javaparser.ast.expr.Expression as JavaExpression /** * @author <NAME> */ fun EqualExpression.builtinToJava(): JavaExpression { return binaryToEquals(left, right) } private fun binaryToEquals(left: Expression, right: Expression): JavaExpression { fun equalsCall(leftExpr: JavaExpression = left.toJava(), rightExpr: JavaExpression = right.toJava()) = MethodCallExpr(leftExpr, "equals", NodeList.nodeList(rightExpr)) val leftType = left.evaluationType val rightType = right.evaluationType return when { leftType is PrimitiveType && rightType is PrimitiveType -> BinaryExpr(left.toJava(), right.toJava(), BinaryExpr.Operator.EQUALS) leftType is ObjectOrTypeType && rightType is ObjectOrTypeType -> equalsCall() leftType is PrimitiveType && rightType is ObjectOrTypeType -> equalsCall(leftExpr = right.toJava(), rightExpr = left.toJava()) leftType is ObjectOrTypeType && rightType is PrimitiveType -> equalsCall() else -> equalsCall() } } fun UnequalExpression.builtinToJava(): JavaExpression = when { left.evaluationType is PrimitiveType && right.evaluationType is PrimitiveType -> BinaryExpr(left.toJava(), right.toJava(), BinaryExpr.Operator.NOT_EQUALS) else -> UnaryExpr(EnclosedExpr(binaryToEquals(left, right)), UnaryExpr.Operator.LOGICAL_COMPLEMENT) }
8
null
1
6
3bfd23cc6fd91864611e785cf2c990b3a9d83e63
1,950
grovlin
Apache License 2.0
app/src/main/kotlin/ir/fallahpoor/releasetracker/features/addlibrary/AddLibraryViewModel.kt
MasoudFallahpour
298,668,650
false
null
package ir.fallahpoor.releasetracker.addlibrary import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import ir.fallahpoor.releasetracker.common.GITHUB_BASE_URL import ir.fallahpoor.releasetracker.data.repository.LibraryRepository import ir.fallahpoor.releasetracker.data.utils.ExceptionParser import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AddLibraryViewModel @Inject constructor( private val libraryRepository: LibraryRepository, private val exceptionParser: ExceptionParser ) : ViewModel() { private val GITHUB_URL_PATH_REGEX = Regex("([-.\\w]+)/([-.\\w]+)", RegexOption.IGNORE_CASE) private val _uiState = MutableStateFlow(AddLibraryScreenUiState()) val uiState: StateFlow<AddLibraryScreenUiState> = _uiState.asStateFlow() fun handleEvent(event: Event) { when (event) { is Event.UpdateLibraryName -> updateLibraryName(event.libraryName) is Event.UpdateLibraryUrlPath -> updateLibraryUrlPath(event.libraryUrlPath) is Event.AddLibrary -> addLibrary(event.libraryName.trim(), event.libraryUrlPath.trim()) is Event.ErrorDismissed -> resetUiState() } } private fun updateLibraryName(libraryName: String) { setUiState(_uiState.value.copy(libraryName = libraryName)) } private fun updateLibraryUrlPath(libraryUrlPath: String) { setUiState(_uiState.value.copy(libraryUrlPath = libraryUrlPath)) } private fun addLibrary(libraryName: String, libraryUrlPath: String) { if (libraryName.isEmpty()) { setUiState(_uiState.value.copy(addLibraryState = AddLibraryState.EmptyLibraryName)) return } if (libraryUrlPath.isEmpty()) { setUiState(_uiState.value.copy(addLibraryState = AddLibraryState.EmptyLibraryUrl)) return } if (!isGithubUrlPath(libraryUrlPath)) { setUiState(_uiState.value.copy(addLibraryState = AddLibraryState.InvalidLibraryUrl)) return } setUiState(_uiState.value.copy(addLibraryState = AddLibraryState.InProgress)) viewModelScope.launch { val uiState: AddLibraryScreenUiState = try { if (libraryAlreadyExists(libraryName)) { _uiState.value.copy(addLibraryState = AddLibraryState.Error("Library already exists")) } else { val libraryVersion: String = libraryRepository.getLibraryVersion(libraryName, libraryUrlPath) libraryRepository.addLibrary( libraryName = libraryName, libraryUrl = GITHUB_BASE_URL + libraryUrlPath, libraryVersion = libraryVersion ) _uiState.value.copy( libraryName = "", libraryUrlPath = "", addLibraryState = AddLibraryState.LibraryAdded ) } } catch (t: Throwable) { val message = exceptionParser.getMessage(t) _uiState.value.copy(addLibraryState = AddLibraryState.Error(message)) } setUiState(uiState) } } private suspend fun libraryAlreadyExists(libraryName: String): Boolean = libraryRepository.getLibrary(libraryName) != null private fun setUiState(uiState: AddLibraryScreenUiState) { _uiState.value = uiState } private fun isGithubUrlPath(url: String): Boolean = GITHUB_URL_PATH_REGEX.matches(url) private fun resetUiState() { setUiState( AddLibraryScreenUiState( libraryName = _uiState.value.libraryName, libraryUrlPath = _uiState.value.libraryUrlPath ) ) } }
6
Kotlin
2
7
f34ab09bbe30e66708792b9f7e862b9e8ff6233b
4,055
ReleaseTracker
Apache License 2.0
app/src/main/java/com/beepiz/cameracoroutines/sample/CamScopes.kt
Beepiz
142,751,813
false
null
package com.beepiz.cameracoroutines.sample import android.os.Handler import android.os.HandlerThread import com.beepiz.cameracoroutines.extensions.HandlerElement import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.android.asCoroutineDispatcher import kotlinx.coroutines.withContext suspend fun withCamContext(block: suspend CoroutineScope.() -> Unit) { val handlerThread = HandlerThread("cam") try { handlerThread.start() val handler = Handler(handlerThread.looper) @Suppress("DEPRECATION") withContext(handler.asCoroutineDispatcher() + HandlerElement(handler), block) } finally { handlerThread.quitSafely() } }
3
Kotlin
4
26
3b4ab174a091d7ee663b7a13f9adb20051311185
685
CameraCoroutines
Apache License 2.0
domain/src/main/java/com/nikitamaslov/domain/util/datetime/DateTime.kt
nikitamasloff
173,980,211
false
null
package com.nikitamaslov.domain.util.datetime import com.nikitamaslov.datetime.calendar.Calendar import com.nikitamaslov.datetime.calendar.inMillis import com.nikitamaslov.datetime.calendar.set import com.nikitamaslov.domain.model.DateTime import com.nikitamaslov.domain.model.Duration import kotlin.math.abs import com.nikitamaslov.datetime.current.currentDateTime as utilCurrentDateTime import com.nikitamaslov.datetime.model.DateTime as UtilDateTime private fun UtilDateTime.mapToDateTime() = DateTime(year, month, dayOfMonth, hour, minute) private fun DateTime.mapToUtilDateTime() = UtilDateTime(year, month, dayOfMonth, hour, minute) internal fun currentDateTime(): DateTime = utilCurrentDateTime().mapToDateTime() internal operator fun DateTime.minus(other: DateTime): Duration { val calendar = Calendar.instance() calendar.set(this.mapToUtilDateTime()) val thisMillis = calendar.inMillis() calendar.set(other.mapToUtilDateTime()) val otherMillis = calendar.inMillis() val diff = abs(thisMillis - otherMillis) return Duration(diff) } internal operator fun Duration.compareTo(other: Duration): Int = this.millis.compareTo(other.millis)
0
null
0
0
110fb59984f7f376c982b68056efed91b6247b4b
1,177
weatherr
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/migration/MigrationExtensions.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.data.migration import io.realm.kotlin.dynamic.DynamicRealmObject import io.realm.kotlin.dynamic.getNullableValue import io.realm.kotlin.dynamic.getValue fun DynamicRealmObject.getString(key: String): String? = try { getValue(key) } catch (e: IllegalArgumentException) { try { getNullableValue(key) } catch (e: IllegalArgumentException) { null } }
27
Kotlin
99
741
635b486158ab4c90224a03dd6b169e9a73914630
455
HTTP-Shortcuts
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Interactive.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.Interactive: ImageVector get() { if (_interactive != null) { return _interactive!! } _interactive = Builder(name = "Interactive", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 511.738f, viewportHeight = 511.738f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(505.749f, 475.591f) lineToRelative(-22.976f, -22.976f) lineToRelative(-36.907f, -36.843f) lineToRelative(59.499f, -59.499f) curveToRelative(8.325f, -8.338f, 8.314f, -21.845f, -0.024f, -30.17f) curveToRelative(-2.197f, -2.193f, -4.846f, -3.881f, -7.763f, -4.945f) lineTo(306.24f, 251.741f) curveToRelative(-22.161f, -8.01f, -46.619f, 3.462f, -54.629f, 25.623f) curveToRelative(-3.385f, 9.366f, -3.387f, 19.622f, -0.006f, 28.99f) lineToRelative(69.611f, 191.339f) curveToRelative(2.484f, 6.85f, 8.292f, 11.958f, 15.403f, 13.547f) curveToRelative(1.521f, 0.331f, 3.073f, 0.495f, 4.629f, 0.491f) curveToRelative(5.658f, -0.001f, 11.083f, -2.25f, 15.083f, -6.251f) lineToRelative(59.435f, -59.605f) lineToRelative(36.843f, 36.843f) lineToRelative(22.976f, 22.976f) curveToRelative(8.475f, 8.185f, 21.98f, 7.95f, 30.165f, -0.525f) curveToRelative(7.984f, -8.267f, 7.984f, -21.373f, 0.0f, -29.641f) lineTo(505.749f, 475.591f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(213.333f, 426.674f) curveTo(95.513f, 426.674f, 0.0f, 331.161f, 0.0f, 213.341f) reflectiveCurveTo(95.513f, 0.007f, 213.333f, 0.007f) reflectiveCurveTo(426.667f, 95.52f, 426.667f, 213.341f) curveToRelative(0.0f, 11.782f, -9.551f, 21.333f, -21.333f, 21.333f) reflectiveCurveTo(384.0f, 225.123f, 384.0f, 213.341f) curveToRelative(0.0f, -94.257f, -76.41f, -170.667f, -170.667f, -170.667f) reflectiveCurveTo(42.667f, 119.084f, 42.667f, 213.341f) reflectiveCurveToRelative(76.41f, 170.667f, 170.667f, 170.667f) curveToRelative(11.782f, 0.0f, 21.333f, 9.551f, 21.333f, 21.333f) reflectiveCurveTo(225.115f, 426.674f, 213.333f, 426.674f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(172.459f, 333.234f) curveToRelative(-2.804f, 0.002f, -5.58f, -0.549f, -8.171f, -1.621f) curveTo(99.003f, 304.497f, 68.06f, 229.592f, 95.175f, 164.306f) reflectiveCurveToRelative(102.021f, -96.228f, 167.306f, -69.113f) curveToRelative(31.335f, 13.015f, 56.221f, 37.939f, 69.188f, 69.294f) curveToRelative(4.689f, 10.809f, -0.272f, 23.372f, -11.08f, 28.061f) curveToRelative(-10.809f, 4.689f, -23.372f, -0.272f, -28.061f, -11.08f) curveToRelative(-0.098f, -0.226f, -0.192f, -0.453f, -0.282f, -0.682f) curveToRelative(-18.06f, -43.531f, -67.989f, -64.179f, -111.519f, -46.119f) reflectiveCurveToRelative(-64.179f, 67.989f, -46.119f, 111.519f) curveToRelative(8.649f, 20.847f, 25.205f, 37.419f, 46.044f, 46.088f) curveToRelative(10.887f, 4.505f, 16.06f, 16.983f, 11.554f, 27.87f) curveToRelative(-3.305f, 7.987f, -11.103f, 13.19f, -19.746f, 13.176f) lineTo(172.459f, 333.234f) close() } } .build() return _interactive!! } private var _interactive: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,082
icons
MIT License
TalkIn/app/src/main/java/com/example/talk_in/User.kt
Ijaiswalshivam
664,282,006
false
{"Dart": 93587, "Kotlin": 45258, "HTML": 2974}
package com.example.talk_in class User { var name: String? = null var email: String? = null var mobile: String? = null var showLocation: Boolean? = null var uid: String? = null constructor(){} constructor(name: String?, email: String?, mobile: String?, showLocation: Boolean?, uid: String?){ this.name = name this.email = email this.mobile = mobile this.showLocation = showLocation this.uid = uid } }
16
Dart
37
19
9cf9ec519843e065b9b46fc7adff48f85a86b708
475
Talk-In
MIT License
component/src/test/java/com/linecorp/lich/component/DelegateToServiceLoaderComponent2.kt
line
200,039,378
false
null
/* * Copyright 2019 LINE Corporation * * 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.linecorp.lich.component import android.content.Context interface DelegateToServiceLoaderComponent2 { fun askToOther(): String companion object : ComponentFactory<DelegateToServiceLoaderComponent2>() { override fun createComponent(context: Context): DelegateToServiceLoaderComponent2 = delegateToServiceLoader(context) } }
3
Kotlin
20
165
2fc3ac01ed57e31208816239f6747d6cdb67de6d
971
lich
Apache License 2.0
baselibs/src/main/java/com/cxz/kotlin/baselibs/base/BaseMvpFragment.kt
iceCola7
157,877,897
false
null
package com.cxz.kotlin.baselibs.base import android.view.View import com.cxz.kotlin.baselibs.ext.showToast import com.cxz.kotlin.baselibs.mvp.IPresenter import com.cxz.kotlin.baselibs.mvp.IView /** * @author chenxz * @date 2018/11/19 * @desc BaseMvpFragment */ abstract class BaseMvpFragment<in V : IView, P : IPresenter<V>> : BaseFragment(), IView { /** * Presenter */ protected var mPresenter: P? = null protected abstract fun createPresenter(): P override fun initView(view: View) { mPresenter = createPresenter() mPresenter?.attachView(this as V) } override fun onDestroyView() { super.onDestroyView() mPresenter?.detachView() this.mPresenter = null } override fun showLoading() { } override fun hideLoading() { } override fun showError(errorMsg: String) { showToast(errorMsg) } override fun showDefaultMsg(msg: String) { showToast(msg) } override fun showMsg(msg: String) { showToast(msg) } }
1
Kotlin
40
160
1a57b38ab15c718f4fce77fc70486cc71a3d507a
1,055
KotlinMVPSamples
Apache License 2.0
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModelExtensions.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet @ExperimentalGradleToolingApi fun KotlinMPPGradleModel.getCompilations(sourceSet: KotlinSourceSet): Set<KotlinCompilation> { return targets.flatMap { target -> target.compilations } .filter { compilation -> compilationDependsOnSourceSet(compilation, sourceSet) } .toSet() } @ExperimentalGradleToolingApi fun KotlinMPPGradleModel.compilationDependsOnSourceSet( compilation: KotlinCompilation, sourceSet: KotlinSourceSet ): Boolean { return compilation.declaredSourceSets.any { sourceSetInCompilation -> sourceSetInCompilation == sourceSet || sourceSetInCompilation.isDependsOn(this, sourceSet) } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
974
intellij-community
Apache License 2.0
day11/Part2.kt
anthaas
317,622,929
false
null
import java.io.File private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { var board = File("input.txt").readLines().map { it.toCharArray() } var nextIter = evolve(board) var same = areSame(board, nextIter) while (!same) { nextIter = evolve(board) same = areSame(board, nextIter) board = nextIter } val occupiedSeats = board.map { it.map { it == OCCUPIED }.count { it } }.sum() println(occupiedSeats) } private fun areSame(board: List<CharArray>, nextIter: List<CharArray>): Boolean { return board.zip(nextIter) .map { outer -> outer.first.zip(outer.second).map { inner -> inner.first == inner.second }.all { it } } .all { it } } private fun countOccupiedNeigboursOf(x: Int, y: Int, board: List<CharArray>): Int { var count = 0 (-1..1).forEach { i -> (-1..1).forEach { j -> count += if (i == 0 && j == 0) 0 else countOccupiedInDirection(Pair(x + i, y + j), i, j, board) } } return count } fun countOccupiedInDirection(position: Pair<Int, Int>, i: Int, j: Int, board: List<CharArray>): Int { var (x, y) = position while (!((x !in 0 until board.size) || (y !in 0 until board[0].size))) { when (board[x][y]) { EMPTY -> return 0 OCCUPIED -> return 1 } x += i y += j } return 0 } private fun evolve(board: List<CharArray>): List<CharArray> { val newBoard = MutableList(board.size) { " ".repeat(board[0].size).toCharArray() } board.forEachIndexed { x, line -> line.forEachIndexed { y, actualPositionSymbol -> newBoard[x][y] = when (actualPositionSymbol) { EMPTY -> if (countOccupiedNeigboursOf(x, y, board) == 0) OCCUPIED else EMPTY OCCUPIED -> if (countOccupiedNeigboursOf(x, y, board) > 4) EMPTY else OCCUPIED else -> actualPositionSymbol } } } return newBoard }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
2,001
Advent-of-Code-2020
MIT License
diskord-core/src/commonMain/kotlin/com/jessecorbett/diskord/api/gateway/model/UserStatusActivity.kt
JesseCorbett
122,362,551
false
{"Kotlin": 447282}
package com.jessecorbett.diskord.api.gateway.model import com.jessecorbett.diskord.api.common.Emoji import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder @Serializable public data class UserStatusActivity( @SerialName("name") val name: String, @SerialName("type") val type: ActivityType, @SerialName("url") val streamUrl: String? = null, @SerialName("created_at") val createdAt: String? = null, @SerialName("timestamps") val timestamps: Timestamps? = null, @SerialName("application_id") val applicationId: String? = null, @SerialName("details") val details: String? = null, @SerialName("state") val partyStatus: String? = null, @SerialName("emoji") val emoji: Emoji? = null, @SerialName("party") val party: ActivityParty? = null, @SerialName("assets") val assets: Assets? = null, @SerialName("secrets") val secrets: RichPresenceSecrets? = null, @SerialName("instance") val activityIsInstanced: Boolean? = null, @SerialName("flags") val activityFlags: Int? = null ) @Serializable public data class Timestamps( @SerialName("start") val startEpochMilli: Long? = null, @SerialName("end") val endEpochMilli: Long? = null ) @Serializable public data class ActivityParty( @SerialName("id") val id: String? = null, @SerialName("size") val size: List<Int>? = null ) @Serializable public data class Assets( @SerialName("large_image") val largeImage: String? = null, @SerialName("large_text") val largeImageText: String? = null, @SerialName("small_image") val smallImage: String? = null, @SerialName("small_text") val smallImageText: String? = null ) @Serializable public data class RichPresenceSecrets( @SerialName("join") val joinParty: String? = null, @SerialName("spectate") val spectate: String? = null, @SerialName("match") val joinInstance: String? = null ) @Serializable(with = ActivityTypeSerializer::class) public enum class ActivityType(public val code: Int) { UNKNOWN(-1), GAME(0), STREAMING(1), LISTENING(2), CUSTOM_STATUS(4), COMPETING(5) } public object ActivityTypeSerializer : KSerializer<ActivityType> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Permissions", PrimitiveKind.INT) override fun deserialize(decoder: Decoder): ActivityType { val value = decoder.decodeInt() return ActivityType.values().find { it.code == value } ?: ActivityType.UNKNOWN } override fun serialize(encoder: Encoder, value: ActivityType) { encoder.encodeInt(value.code) } }
2
Kotlin
17
170
acd004fc650cfa34d545666db9ea15a0eb3461ac
2,904
diskord
Apache License 2.0
benchmark/src/androidTest/java/com/example/benchmark/ExampleBenchmark.kt
Onotole1
224,369,247
false
null
package com.example.benchmark import android.content.Context import android.util.Log import android.view.LayoutInflater import android.widget.FrameLayout import androidx.benchmark.junit4.BenchmarkRule import androidx.benchmark.junit4.measureRepeated import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.random.Random /** * Benchmark, which will execute on an Android device. * * The body of [BenchmarkRule.measureRepeated] is measured in a loop, and Studio will * output the result. Modify your code to see how it affects performance. */ @RunWith(AndroidJUnit4::class) class ExampleBenchmark { @get:Rule val benchmarkRule = BenchmarkRule() @Test fun compoundViewInflate() { val context: Context = ApplicationProvider.getApplicationContext() val inflater = LayoutInflater.from(context) val root = FrameLayout(context) benchmarkRule.measureRepeated { inflater.inflate(R.layout.compound_layout, root, false) } // 2 564 231 ns } @Test fun notCompoundViewInflate() { val context: Context = ApplicationProvider.getApplicationContext() val inflater = LayoutInflater.from(context) val root = FrameLayout(context) benchmarkRule.measureRepeated { inflater.inflate(R.layout.not_compound_layout, root, false) } // 3 670 384 ns } }
0
Kotlin
0
1
fb5dba25789026a9e503eff29137878cae539e4c
1,524
ComposeDrawableTest
Apache License 2.0
app/src/main/java/com/github/nyanfantasia/shizurunotes/data/CampaignSchedule.kt
TragicLifeHu
440,741,412
true
{"Kotlin": 727863}
package com.github.nyanfantasia.shizurunotes.data import com.github.nyanfantasia.shizurunotes.utils.Utils import java.time.LocalDateTime class CampaignSchedule( id: Int, name: String, type: EventType, startTime: LocalDateTime, endTime: LocalDateTime, val category: Int, val campaignType: CampaignType, val value: Double, val systemId: Int ) : EventSchedule(id, name, type, startTime, endTime) { override val title: String by lazy { campaignType.description().format(Utils.roundIfNeed(value / 1000.0)) } val shortTitle: String = campaignType.shortDescription().format(Utils.roundIfNeed(value / 1000.0)) }
0
Kotlin
0
1
7d06e6dfc6268312eff6f5af359ae0c3153a6d50
661
ShizuruNotes
Apache License 2.0
core/src/jvmMain/kotlin/zakadabar/stack/backend/custom/CustomBackend.kt
kondorj
355,137,640
true
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
/* * Copyright © 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.stack.backend.custom import org.slf4j.LoggerFactory import zakadabar.stack.backend.BackendModule /** * Base class for custom backends. */ abstract class CustomBackend : BackendModule { protected open val logger = LoggerFactory.getLogger(this::class.simpleName) !! }
0
null
0
0
2379c0fb031f04a230e753a9afad6bd260f6a0b2
409
zakadabar-stack
Apache License 2.0
plugin-location/src/main/kotlin/me/leon/toolsfx/plugin/LocationServiceType.kt
Leon406
381,644,086
false
null
package me.leon.toolsfx.plugin import me.leon.ext.fromJson import me.leon.ext.readFromNet import me.leon.toolsfx.domain.AmapGeo import me.leon.toolsfx.domain.BaiduGeo import tornadofx.* enum class LocationServiceType(val type: String) : ILocationService { WGS2GCJ("wgs2gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, WGS2BD09("wgs2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2BD09("gcj2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2WGS("gcj2wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092WGS("bd092wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092GCJ("bd092gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, DISTANCE("distance") { override fun process(raw: String, params: MutableMap<String, String>): String { val (p1, p2) = raw.split("-") val (p1Lng, p1Lat) = p1.split(",").map { it.toDouble() } val (p2Lng, p2Lat) = p2.split(",").map { it.toDouble() } return String.format( "%.2f m", CoordinatorTransform.distance(p1Lat, p1Lng, p2Lat, p2Lng) ) } }, GEO_AMPA("geoAmap") { override fun process(raw: String, params: MutableMap<String, String>): String { return ("https://restapi.amap.com/v3/geocode/geo?address=${raw.urlEncoded}" + "&output=json&key=282f521c5c372f233da702769e43bfba") .readFromNet() .also { println(it) } .fromJson(AmapGeo::class.java) .geoInfo() } }, GEO_BD("geoBaidu") { override fun process(raw: String, params: MutableMap<String, String>): String { return ("http://api.map.baidu.com/geocoding/v3/?address=${raw.urlEncoded}" + "&output=json&ak=V0AKhZ3wN8CTU3zx8lGf4QvwyOs5rGIn") .readFromNet() .fromJson(BaiduGeo::class.java) .geoInfo() } }, } val locationServiceTypeMap = LocationServiceType.values().associateBy { it.type } fun String.locationServiceType() = locationServiceTypeMap[this] ?: LocationServiceType.WGS2GCJ
1
Kotlin
57
242
176db4f550a37c7acfd54a302a276b8617b645cf
4,021
ToolsFx
ISC License
plugin-location/src/main/kotlin/me/leon/toolsfx/plugin/LocationServiceType.kt
Leon406
381,644,086
false
null
package me.leon.toolsfx.plugin import me.leon.ext.fromJson import me.leon.ext.readFromNet import me.leon.toolsfx.domain.AmapGeo import me.leon.toolsfx.domain.BaiduGeo import tornadofx.* enum class LocationServiceType(val type: String) : ILocationService { WGS2GCJ("wgs2gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, WGS2BD09("wgs2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2BD09("gcj2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2WGS("gcj2wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092WGS("bd092wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092GCJ("bd092gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, DISTANCE("distance") { override fun process(raw: String, params: MutableMap<String, String>): String { val (p1, p2) = raw.split("-") val (p1Lng, p1Lat) = p1.split(",").map { it.toDouble() } val (p2Lng, p2Lat) = p2.split(",").map { it.toDouble() } return String.format( "%.2f m", CoordinatorTransform.distance(p1Lat, p1Lng, p2Lat, p2Lng) ) } }, GEO_AMPA("geoAmap") { override fun process(raw: String, params: MutableMap<String, String>): String { return ("https://restapi.amap.com/v3/geocode/geo?address=${raw.urlEncoded}" + "&output=json&key=<KEY>") .readFromNet() .also { println(it) } .fromJson(AmapGeo::class.java) .geoInfo() } }, GEO_BD("geoBaidu") { override fun process(raw: String, params: MutableMap<String, String>): String { return ("http://api.map.baidu.com/geocoding/v3/?address=${raw.urlEncoded}" + "&output=json&ak=V0AKhZ3wN8CTU3zx8lGf4QvwyOs5rGIn") .readFromNet() .fromJson(BaiduGeo::class.java) .geoInfo() } }, } val locationServiceTypeMap = LocationServiceType.values().associateBy { it.type } fun String.locationServiceType() = locationServiceTypeMap[this] ?: LocationServiceType.WGS2GCJ
1
Kotlin
57
242
176db4f550a37c7acfd54a302a276b8617b645cf
3,994
ToolsFx
ISC License
src/test/kotlin/test/t5.kt
FALLANGELZOU
539,926,510
false
{"Kotlin": 66070, "Assembly": 74}
package test
0
Kotlin
0
1
479077213a7381c6f08a333e10e7bdaf7861e949
15
Flyer
Apache License 2.0
Operators/src/Main.kt
emmasenzota
751,100,617
false
{"Kotlin": 1553}
fun main() { testStrings(); testOps() testCompare() } fun testStrings(){ var numberOfFlowers : Int = 10; var numberOfFish : Int = 25; // lets print these values in different manner // Remember the declaration is in "var" these values cannot change otherwise errors println("I have $numberOfFlowers flowers and $numberOfFish fish") println("I have a total of ${numberOfFish + numberOfFlowers} of living things \n") } fun testOps(){ // initialization val num : Int = 3; val num1: Double = 4.0; val num2 = num * num1; val num3 = num2 / num; println("Times res= $num2 , and Division res = $num3 \n") } fun testCompare(){ // going to check the RANGE operator and WHEN val students = 236; if(students in 1..25 || students%25 == 0){ println("Make a class of 25 students ${students / 25} times \n") } else{ println("Class not divisible into 25 students ") val studentsHalf = students/2 // half students to determine the range when(studentsHalf){ 0 -> println("No students") in 1..24 -> println("prepare a smaller class, Half of class is $studentsHalf \n") in 25..100 -> println("prepare bigger class, Half of class is $studentsHalf \n") else -> println("Take students into a Dining hall, Half of class is $studentsHalf \n") } } }
0
Kotlin
0
0
6fe25e3394fdd79a65e788838a3d4b228ced88f9
1,404
LearningKotlin
Apache License 2.0
Operators/src/Main.kt
emmasenzota
751,100,617
false
{"Kotlin": 1553}
fun main() { testStrings(); testOps() testCompare() } fun testStrings(){ var numberOfFlowers : Int = 10; var numberOfFish : Int = 25; // lets print these values in different manner // Remember the declaration is in "var" these values cannot change otherwise errors println("I have $numberOfFlowers flowers and $numberOfFish fish") println("I have a total of ${numberOfFish + numberOfFlowers} of living things \n") } fun testOps(){ // initialization val num : Int = 3; val num1: Double = 4.0; val num2 = num * num1; val num3 = num2 / num; println("Times res= $num2 , and Division res = $num3 \n") } fun testCompare(){ // going to check the RANGE operator and WHEN val students = 236; if(students in 1..25 || students%25 == 0){ println("Make a class of 25 students ${students / 25} times \n") } else{ println("Class not divisible into 25 students ") val studentsHalf = students/2 // half students to determine the range when(studentsHalf){ 0 -> println("No students") in 1..24 -> println("prepare a smaller class, Half of class is $studentsHalf \n") in 25..100 -> println("prepare bigger class, Half of class is $studentsHalf \n") else -> println("Take students into a Dining hall, Half of class is $studentsHalf \n") } } }
0
Kotlin
0
0
6fe25e3394fdd79a65e788838a3d4b228ced88f9
1,404
LearningKotlin
Apache License 2.0
src/main/kotlin/common/init/Blocks.kt
Cosmic-Goat
356,115,770
true
{"Kotlin": 25981, "Shell": 1929}
package net.dblsaiko.rswires.common.init import net.dblsaiko.hctm.common.util.delegatedNotNull import net.dblsaiko.hctm.common.util.flatten import net.dblsaiko.rswires.MOD_ID import net.dblsaiko.rswires.common.block.BundledCableBlock import net.dblsaiko.rswires.common.block.InsulatedWireBlock import net.dblsaiko.rswires.common.block.RedAlloyWireBlock import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.minecraft.block.Block import net.minecraft.block.Material import net.minecraft.util.DyeColor import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry import kotlin.properties.ReadOnlyProperty object Blocks { private val tasks = mutableListOf<() -> Unit>() private val WIRE_SETTINGS = FabricBlockSettings.of(Material.STONE) .breakByHand(true) .noCollision() .strength(0.05f, 0.05f) val RED_ALLOY_WIRE by create("red_alloy_wire", RedAlloyWireBlock(WIRE_SETTINGS)) val INSULATED_WIRES by DyeColor.values().associate { it to create("${it.getName()}_insulated_wire", InsulatedWireBlock(WIRE_SETTINGS, it)) }.flatten() val UNCOLORED_BUNDLED_CABLE by create("bundled_cable", BundledCableBlock(WIRE_SETTINGS, null)) val COLORED_BUNDLED_CABLES by DyeColor.values().associate { it to create("${it.getName()}_bundled_cable", BundledCableBlock(WIRE_SETTINGS, it)) }.flatten() private fun <T : Block> create(name: String, block: T): ReadOnlyProperty<Blocks, T> { var regBlock: T? = null tasks += { regBlock = Registry.register(Registry.BLOCK, Identifier(MOD_ID, name), block) } return delegatedNotNull { regBlock } } internal fun register() { tasks.forEach { it() } tasks.clear() } }
0
null
0
0
9e73f148745b25fea9b0c6b729dcb93f348ab4b8
1,695
rswires
MIT License
mvp_list/src/main/kotlin/com/ufkoku/mvp/list/interfaces/IPagingSearchableView.kt
andri7
100,227,140
false
null
/* * Copyright 2017 Ufkoku (https://github.com/Ufkoku/AndroidMVPHelper) * * 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.ufkoku.mvp.list.interfaces import com.ufkoku.mvp_base.presenter.IAsyncPresenter import com.ufkoku.mvp_base.view.IMvpView interface IPagingSearchableView<I, in PR : IPagingResponse<I>> : IMvpView, IAsyncPresenter.ITaskListener { fun setQuery(query: String) fun onFirstPageLoaded(response: PR) fun setItems(items: MutableList<I>, canLoadMore: Boolean, isSearch: Boolean) fun onNextPageLoaded(response: PR) fun onNextPageLoadFailed(code: Int) fun onFirstPageLoadFailed(code: Int) }
1
null
1
1
19e024f8e43d9c19554ad6b43e01f3bc0e66b8a7
1,156
AndroidMVPHelper
Apache License 2.0
src/main/kotlin/com/github/kuro46/embedscript/script/executor/ExecutionLogger.kt
kuro46
158,701,965
false
null
package com.github.kuro46.embedscript.script.executor import com.github.kuro46.embedscript.Configuration import com.github.kuro46.embedscript.script.Script import com.github.kuro46.embedscript.script.ScriptPosition import com.github.kuro46.embedscript.script.ScriptUtils import com.github.kuro46.embedscript.util.PlaceholderData import com.github.kuro46.embedscript.util.Replacer import java.util.StringJoiner import java.util.logging.Logger import org.bukkit.entity.Player /** * @author shirokuro */ class ExecutionLogger(val logger: Logger, val configuration: Configuration) { val replacer = Replacer<LogData>() init { replacer.add(PlaceholderData("<trigger>") { it.player.name }) replacer.add(PlaceholderData("<trigger_world>") { it.player.world.name }) replacer.add(PlaceholderData("<trigger_x>") { it.player.location.blockX }) replacer.add(PlaceholderData("<trigger_y>") { it.player.location.blockY }) replacer.add(PlaceholderData("<trigger_z>") { it.player.location.blockZ }) replacer.add(PlaceholderData("<script_world>") { it.scriptPosition.world }) replacer.add(PlaceholderData("<script_x>") { it.scriptPosition.x }) replacer.add(PlaceholderData("<script_y>") { it.scriptPosition.y }) replacer.add(PlaceholderData("<script_z>") { it.scriptPosition.z }) replacer.add( PlaceholderData("<script>") { val script = it.script val joiner = StringJoiner(" ") for (parentKeyData in script.keys) { for ((key, values) in parentKeyData) { joiner.add("@$key ${ScriptUtils.toString(values)}") } } joiner.toString() } ) } fun log(logData: LogData) { if (!configuration.logConfiguration.enabled) { return } logger.info(replacer.execute(configuration.logConfiguration.format, logData)) } } data class LogData( val player: Player, val scriptPosition: ScriptPosition, val script: Script )
5
Kotlin
0
0
91c716bc2872a6bf21bdb9a816347cb9011f71b0
2,111
EmbedScript
Apache License 2.0
feature/faq/data/src/main/java/com/gigauri/reptiledb/module/feature/faq/data/repository/FaqRepositoryImpl.kt
george-gigauri
758,816,993
false
{"Kotlin": 331680}
package com.gigauri.reptiledb.module.feature.faq.data.repository import com.gigauri.reptiledb.module.core.data.common.safeApiCall import com.gigauri.reptiledb.module.core.domain.common.Resource import com.gigauri.reptiledb.module.feature.faq.data.local.dao.FaqDao import com.gigauri.reptiledb.module.feature.faq.data.mapper.toDomain import com.gigauri.reptiledb.module.feature.faq.data.mapper.toEntity import com.gigauri.reptiledb.module.feature.faq.data.remote.api.FaqApi import com.gigauri.reptiledb.module.feature.faq.domain.model.Faq import com.gigauri.reptiledb.module.feature.faq.domain.repository.FaqRepository import javax.inject.Inject class FaqRepositoryImpl @Inject constructor( private val api: FaqApi, private val dao: FaqDao ) : FaqRepository { override suspend fun getFaq(): Resource<List<Faq>> { return safeApiCall { api.getFaq().map { it.toDomain() } } } override suspend fun getAllFromDatabase(): List<Faq> { return dao.getAll().map { it.toDomain() } } override suspend fun insertAllToDatabase(list: List<Faq>) { dao.insertAll(list.map { it.toEntity() }) } override suspend fun deleteAllFromDatabase() { dao.deleteAll() } }
0
Kotlin
0
2
f256dcd2ba9e4d88135a5399c5b2a71ddff454d0
1,219
herpi-android
Apache License 2.0
src/main/kotlin/com/github/aszecsei/crowtech/common/registries/BlockRegistry.kt
crow-maki
730,847,703
false
{"Kotlin": 102455}
package com.github.aszecsei.crowtech.common.registries import com.github.aszecsei.crowtech.CrowTech import com.github.aszecsei.crowtech.common.blocks.OreBlock import com.github.aszecsei.crowtech.common.materials.Strata import com.github.aszecsei.crowtech.common.materials.properties.MaterialProperty import net.minecraft.world.item.BlockItem import net.minecraft.world.item.Item import net.minecraft.world.level.block.Block import net.minecraftforge.registries.DeferredRegister import net.minecraftforge.registries.ForgeRegistries import net.minecraftforge.registries.RegistryObject import thedarkcolour.kotlinforforge.forge.registerObject import java.util.* object BlockRegistry { val BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, CrowTech.ID) val BLOCK_ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, CrowTech.ID) val ORES = TreeMap<String, RegistryObject<OreBlock>>() init { MaterialRegistry.MATERIALS.forEach { (id, material) -> if (material.properties.containsKey(MaterialProperty.ORE_PROPERTY)) { val oreProp = material.get(MaterialProperty.ORE_PROPERTY) if (oreProp.generate) { for (stratum in oreProp.strata) { val oreId = if (stratum == Strata.STONE) "${id}_ore" else "${stratum.id}_${id}_ore" CrowTech.LOGGER.info("Registering $oreId") val block = BLOCKS.register(oreId) { OreBlock( material.get(MaterialProperty.ORE_PROPERTY), stratum ) } BLOCK_ITEMS.register(oreId) { BlockItem(block.get(), Item.Properties()) } ORES["${id}:${stratum.id}"] = block } } } } } }
0
Kotlin
0
0
f80c0fab4283761835464c599dded3134b0bde7c
1,905
crowtech
MIT License
src/main/kotlin/dto/Intent.kt
Helvia
190,375,471
false
null
package dto data class Intent(val confidence: Double, val name: String)
2
Kotlin
0
0
032856d43ceb033980fa576de007db977a9dc212
72
rasa-kotlin
MIT License
src/Day03.kt
li-xin-yi
573,617,763
false
null
fun main() { fun solvePart1(input: List<String>): Int { var res = 0 for (line in input) { val length = line.length val first = line.substring(0, length / 2).toSet() val second = line.substring(length / 2).toSet() val item = first.intersect(second).first() res += if (item.isUpperCase()) (item - 'A' + 27) else (item - 'a' + 1) } return res } fun solvePart2(input: List<String>): Int { var res = 0 for (i in 0 until input.size step 3) { val first = input[i].toSet() val second = input[i + 1].toSet() val third = input[i + 2].toSet() val item = first.intersect(second).intersect(third).first() res += if (item.isUpperCase()) (item - 'A' + 27) else (item - 'a' + 1) } return res } val testInput = readInput("input/Day03_test") println(solvePart1(testInput)) println(solvePart2(testInput)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
1,002
AoC-2022-kotlin
Apache License 2.0
app/src/main/java/com/agritracker/plus/LoginActivity.kt
FelipeACP
793,833,208
false
{"Kotlin": 102008, "Python": 1401}
package com.agritracker.plus import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.text.TextUtils import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.agritracker.plus.MainApplication import com.agritracker.plus.R import com.agritracker.plus.RegisterActivity import com.google.android.gms.tasks.OnCompleteListener import com.agritracker.plus.User import com.agritracker.plus.UserLocalStorage import com.google.firebase.auth.AuthResult import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class LoginActivity : AppCompatActivity() { private lateinit var inputEmail: EditText private lateinit var inputPassword: EditText private lateinit var auth: FirebaseAuth private lateinit var progressBar: ProgressBar private lateinit var btnLogin: Button private lateinit var btnReset: Button private lateinit var btnRegister: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Get Firebase auth instance auth = Firebase.auth if (auth.currentUser != null) { startActivity(Intent(this, MainActivity::class.java)) finish() } // set the view now setContentView(R.layout.activity_login) inputEmail = findViewById(R.id.email) inputPassword = findViewById(R.id.password) progressBar = findViewById(R.id.progressBar) btnLogin = findViewById(R.id.btn_login) btnReset = findViewById(R.id.btn_reset_password) btnRegister = findViewById(R.id.btn_register) btnRegister.setOnClickListener { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) } btnReset.setOnClickListener { startActivity(Intent(this, ResetPasswordActivity::class.java)) } btnLogin.setOnClickListener { val email = inputEmail.text.toString() val password = inputPassword.text.toString() if (TextUtils.isEmpty(email)) { Toast.makeText(applicationContext, "Enter email address!", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (TextUtils.isEmpty(password)) { Toast.makeText(applicationContext, "Enter password!", Toast.LENGTH_SHORT).show() return@setOnClickListener } progressBar.visibility = View.VISIBLE //authenticate user auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, OnCompleteListener<AuthResult> { task -> progressBar.visibility = View.GONE if (!task.isSuccessful) { // there was an error if (password.length < 6) { inputPassword.error = getString(R.string.minimum_password) } else { Toast.makeText(this@LoginActivity, getString(R.string.auth_failed), Toast.LENGTH_LONG).show() } } else { val user = auth.currentUser UserLocalStorage(this).storeUserData(User(user!!.uid, user.email!!)) startActivity(Intent(this, MainActivity::class.java)) } }) } } override fun onResume() { super.onResume() } }
0
Kotlin
0
0
390e2930e18864c3125a74b242a3c30e94ae3dc5
3,807
agritracker-android
Apache License 2.0
app/src/main/java/com/agritracker/plus/LoginActivity.kt
FelipeACP
793,833,208
false
{"Kotlin": 102008, "Python": 1401}
package com.agritracker.plus import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.text.TextUtils import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.agritracker.plus.MainApplication import com.agritracker.plus.R import com.agritracker.plus.RegisterActivity import com.google.android.gms.tasks.OnCompleteListener import com.agritracker.plus.User import com.agritracker.plus.UserLocalStorage import com.google.firebase.auth.AuthResult import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class LoginActivity : AppCompatActivity() { private lateinit var inputEmail: EditText private lateinit var inputPassword: EditText private lateinit var auth: FirebaseAuth private lateinit var progressBar: ProgressBar private lateinit var btnLogin: Button private lateinit var btnReset: Button private lateinit var btnRegister: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Get Firebase auth instance auth = Firebase.auth if (auth.currentUser != null) { startActivity(Intent(this, MainActivity::class.java)) finish() } // set the view now setContentView(R.layout.activity_login) inputEmail = findViewById(R.id.email) inputPassword = findViewById(R.id.password) progressBar = findViewById(R.id.progressBar) btnLogin = findViewById(R.id.btn_login) btnReset = findViewById(R.id.btn_reset_password) btnRegister = findViewById(R.id.btn_register) btnRegister.setOnClickListener { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) } btnReset.setOnClickListener { startActivity(Intent(this, ResetPasswordActivity::class.java)) } btnLogin.setOnClickListener { val email = inputEmail.text.toString() val password = inputPassword.text.toString() if (TextUtils.isEmpty(email)) { Toast.makeText(applicationContext, "Enter email address!", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (TextUtils.isEmpty(password)) { Toast.makeText(applicationContext, "Enter password!", Toast.LENGTH_SHORT).show() return@setOnClickListener } progressBar.visibility = View.VISIBLE //authenticate user auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, OnCompleteListener<AuthResult> { task -> progressBar.visibility = View.GONE if (!task.isSuccessful) { // there was an error if (password.length < 6) { inputPassword.error = getString(R.string.minimum_password) } else { Toast.makeText(this@LoginActivity, getString(R.string.auth_failed), Toast.LENGTH_LONG).show() } } else { val user = auth.currentUser UserLocalStorage(this).storeUserData(User(user!!.uid, user.email!!)) startActivity(Intent(this, MainActivity::class.java)) } }) } } override fun onResume() { super.onResume() } }
0
Kotlin
0
0
390e2930e18864c3125a74b242a3c30e94ae3dc5
3,807
agritracker-android
Apache License 2.0
RxKit/src/main/java/com/tamsiree/rxkit/RxRegTool.kt
Tamsiree
69,093,112
false
null
package com.tamsiree.rxkit import com.tamsiree.rxkit.RxConstTool.REGEX_CHZ import com.tamsiree.rxkit.RxConstTool.REGEX_DATE import com.tamsiree.rxkit.RxConstTool.REGEX_EMAIL import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD15 import com.tamsiree.rxkit.RxConstTool.REGEX_IDCARD18 import com.tamsiree.rxkit.RxConstTool.REGEX_IP import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_EXACT import com.tamsiree.rxkit.RxConstTool.REGEX_MOBILE_SIMPLE import com.tamsiree.rxkit.RxConstTool.REGEX_TEL import com.tamsiree.rxkit.RxConstTool.REGEX_URL import com.tamsiree.rxkit.RxConstTool.REGEX_USERNAME import com.tamsiree.rxkit.RxDataTool.Companion.isNullString import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern /** * @author Tamsiree * @date 2017/3/15 */ object RxRegTool { //--------------------------------------------正则表达式----------------------------------------- /** * 原文链接:http://caibaojian.com/regexp-example.html * 提取信息中的网络链接:(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? * 提取信息中的邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* * 提取信息中的图片链接:(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? * 提取信息中的IP地址:(\d+)\.(\d+)\.(\d+)\.(\d+) * 提取信息中的中国电话号码(包括移动和固定电话):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14} * 提取信息中的中国邮政编码:[1-9]{1}(\d+){5} * 提取信息中的中国身份证号码:\d{18}|\d{15} * 提取信息中的整数:\d+ * 提取信息中的浮点数(即小数):(-?\d*)\.?\d+ * 提取信息中的任何数字 :(-?\d*)(\.\d+)? * 提取信息中的中文字符串:[\u4e00-\u9fa5]* * 提取信息中的双字节字符串 (汉字):[^\x00-\xff]* */ /** * 判断是否为真实手机号 * * @param mobiles * @return */ @JvmStatic fun isMobile(mobiles: String?): Boolean { val p = Pattern.compile("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$") val m = p.matcher(mobiles) return m.matches() } /** * 验证银卡卡号 * * @param cardNo * @return */ @JvmStatic fun isBankCard(cardNo: String?): Boolean { val p = Pattern.compile("^\\d{16,19}$|^\\d{6}[- ]\\d{10,13}$|^\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4,7}$") val m = p.matcher(cardNo) return m.matches() } /** * 15位和18位身份证号码的正则表达式 身份证验证 * * @param idCard * @return */ @JvmStatic fun validateIdCard(idCard: String?): Boolean { // 15位和18位身份证号码的正则表达式 val regIdCard = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$" val p = Pattern.compile(regIdCard) return p.matcher(idCard).matches() } //=========================================正则表达式============================================= /** * 验证手机号(简单) * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMobileSimple(string: String?): Boolean { return isMatch(REGEX_MOBILE_SIMPLE, string) } /** * 验证手机号(精确) * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMobileExact(string: String?): Boolean { return isMatch(REGEX_MOBILE_EXACT, string) } /** * 验证电话号码 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isTel(string: String?): Boolean { return isMatch(REGEX_TEL, string) } /** * 验证身份证号码15位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard15(string: String?): Boolean { return isMatch(REGEX_IDCARD15, string) } /** * 验证身份证号码18位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard18(string: String?): Boolean { return isMatch(REGEX_IDCARD18, string) } /** * 验证身份证号码15或18位 包含以x结尾 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIDCard(string: String?): Boolean { return isMatch(REGEX_IDCARD, string) } /*********************************** 身份证验证开始 */ /** * 身份证号码验证 1、号码的结构 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码, * 八位数字出生日期码,三位数字顺序码和一位数字校验码。 2、地址码(前六位数) * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。 3、出生日期码(第七位至十四位) * 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 4、顺序码(第十五位至十七位) * 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号, 顺序码的奇数分配给男性,偶数分配给女性。 5、校验码(第十八位数) * (1)十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和 * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 * (2)计算模 Y = mod(S, 11) (3)通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2 */ /** * 功能:身份证的有效验证 * * @param IDStr 身份证号 * @return 有效:返回"有效" 无效:返回String信息 * @throws ParseException */ @JvmStatic fun IDCardValidate(IDStr: String): String { var errorInfo = "" // 记录错误信息 val ValCodeArr = arrayOf("1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2") val Wi = arrayOf("7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2") var Ai = "" // ================ 号码的长度 15位或18位 ================ if (IDStr.length != 15 && IDStr.length != 18) { errorInfo = "身份证号码长度应该为15位或18位。" return errorInfo } // =======================(end)======================== // ================ 数字 除最后以为都为数字 ================ if (IDStr.length == 18) { Ai = IDStr.substring(0, 17) } else if (IDStr.length == 15) { Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15) } if (isNumeric(Ai) == false) { errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。" return errorInfo } // =======================(end)======================== // ================ 出生年月是否有效 ================ val strYear = Ai.substring(6, 10) // 年份 val strMonth = Ai.substring(10, 12) // 月份 val strDay = Ai.substring(12, 14) // 月份 if (isDate("$strYear-$strMonth-$strDay") == false) { errorInfo = "身份证生日无效。" return errorInfo } val gc = GregorianCalendar() val s = SimpleDateFormat("yyyy-MM-dd") try { if (gc[Calendar.YEAR] - strYear.toInt() > 150 || gc.time.time - s.parse( "$strYear-$strMonth-$strDay").time < 0) { errorInfo = "身份证生日不在有效范围。" return errorInfo } } catch (e: NumberFormatException) { e.printStackTrace() } catch (e: ParseException) { e.printStackTrace() } if (strMonth.toInt() > 12 || strMonth.toInt() == 0) { errorInfo = "身份证月份无效" return errorInfo } if (strDay.toInt() > 31 || strDay.toInt() == 0) { errorInfo = "身份证日期无效" return errorInfo } // =====================(end)===================== // ================ 地区码时候有效 ================ val h = GetAreaCode() if (h[Ai.substring(0, 2)] == null) { errorInfo = "身份证地区编码错误。" return errorInfo } // ============================================== // ================ 判断最后一位的值 ================ var TotalmulAiWi = 0 for (i in 0..16) { TotalmulAiWi = (TotalmulAiWi + Ai[i].toString().toInt() * Wi[i].toInt()) } val modValue = TotalmulAiWi % 11 val strVerifyCode = ValCodeArr[modValue] Ai = Ai + strVerifyCode if (IDStr.length == 18) { if (Ai == IDStr == false) { errorInfo = "身份证无效,不是合法的身份证号码" return errorInfo } } else { return "有效" } // =====================(end)===================== return "有效" } /** * 功能:设置地区编码 * * @return Hashtable 对象 */ private fun GetAreaCode(): Hashtable<String, String> { val hashtable = Hashtable<String, String>() hashtable["11"] = "北京" hashtable["12"] = "天津" hashtable["13"] = "河北" hashtable["14"] = "山西" hashtable["15"] = "内蒙古" hashtable["21"] = "辽宁" hashtable["22"] = "吉林" hashtable["23"] = "黑龙江" hashtable["31"] = "上海" hashtable["32"] = "江苏" hashtable["33"] = "浙江" hashtable["34"] = "安徽" hashtable["35"] = "福建" hashtable["36"] = "江西" hashtable["37"] = "山东" hashtable["41"] = "河南" hashtable["42"] = "湖北" hashtable["43"] = "湖南" hashtable["44"] = "广东" hashtable["45"] = "广西" hashtable["46"] = "海南" hashtable["50"] = "重庆" hashtable["51"] = "四川" hashtable["52"] = "贵州" hashtable["53"] = "云南" hashtable["54"] = "西藏" hashtable["61"] = "陕西" hashtable["62"] = "甘肃" hashtable["63"] = "青海" hashtable["64"] = "宁夏" hashtable["65"] = "新疆" hashtable["71"] = "台湾" hashtable["81"] = "香港" hashtable["82"] = "澳门" hashtable["91"] = "国外" return hashtable } /** * 功能:判断字符串是否为数字 * * @param str * @return */ private fun isNumeric(str: String): Boolean { val pattern = Pattern.compile("[0-9]*") val isNum = pattern.matcher(str) return isNum.matches() } /** * 验证邮箱 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isEmail(string: String?): Boolean { return isMatch(REGEX_EMAIL, string) } /** * 验证URL * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isURL(string: String?): Boolean { return isMatch(REGEX_URL, string) } /** * 验证汉字 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isChz(string: String?): Boolean { return isMatch(REGEX_CHZ, string) } /** * 验证用户名 * * 取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isUsername(string: String?): Boolean { return isMatch(REGEX_USERNAME, string) } /** * 验证yyyy-MM-dd格式的日期校验,已考虑平闰年 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isDate(string: String?): Boolean { return isMatch(REGEX_DATE, string) } /** * 验证IP地址 * * @param string 待验证文本 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isIP(string: String?): Boolean { return isMatch(REGEX_IP, string) } /** * string是否匹配regex正则表达式字符串 * * @param regex 正则表达式字符串 * @param string 要匹配的字符串 * @return `true`: 匹配<br></br>`false`: 不匹配 */ @JvmStatic fun isMatch(regex: String?, string: String?): Boolean { return !isNullString(string) && Pattern.matches(regex, string) } /** * 验证固定电话号码 * * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 * * **国家(地区) 代码 :**标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, * 数字之后是空格分隔的国家(地区)代码。 * * **区号(城市代码):**这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— * 对不使用地区或城市代码的国家(地区),则省略该组件。 * * **电话号码:**这包含从 0 到 9 的一个或多个数字 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkPhone(phone: String?): Boolean { val regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$" return Pattern.matches(regex, phone) } /** * 验证整数(正整数和负整数) * * @param digit 一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkDigit(digit: String?): Boolean { val regex = "\\-?[1-9]\\d+" return Pattern.matches(regex, digit) } /** * 验证整数和浮点数(正负整数和正负浮点数) * * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkDecimals(decimals: String?): Boolean { val regex = "\\-?[1-9]\\d+(\\.\\d+)?" return Pattern.matches(regex, decimals) } /** * 验证空白字符 * * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkBlankSpace(blankSpace: String?): Boolean { val regex = "\\s+" return Pattern.matches(regex, blankSpace) } /** * 验证日期(年月日) * * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkBirthday(birthday: String?): Boolean { val regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}" return Pattern.matches(regex, birthday) } /** * 匹配中国邮政编码 * * @param postcode 邮政编码 * @return 验证成功返回true,验证失败返回false */ @JvmStatic fun checkPostcode(postcode: String?): Boolean { val regex = "[1-9]\\d{5}" return Pattern.matches(regex, postcode) } }
70
null
2855
12,025
fa5f88c24594a562c2a9047c40ceeb94de297428
13,378
RxTool
Apache License 2.0
examples/starwars/src/starwars/operations.kt
Gui-Yom
342,984,553
false
null
package starwars object Query { val luke = Human("luke", "Luke Skywalker", mutableListOf(), mutableListOf(), "Tatooine") val r2d2 = Droid("r2d2", "R2-D2", mutableListOf(), mutableListOf(), "Naboo") fun hero(episode: Episode?): Character? { return when (episode) { Episode.NEW_HOPE, Episode.JEDI -> r2d2 Episode.EMPIRE -> luke else -> null } } fun heroes(): List<Character> = listOf(luke, r2d2) } object Mutation { } object Subscription { }
1
Kotlin
1
3
c4d1bc06678129876cb9e05520fb8213640dcddc
519
graphql-dsl
Apache License 2.0
app/src/main/java/com/masterplus/trdictionary/features/settings/domain/JsonParser.kt
Ramazan713
634,957,286
false
null
package com.masterplus.trdictionary.features.settings.domain import java.lang.reflect.Type interface JsonParser { fun toJson(data: Any): String fun <T> fromJson(data: String, type: Type): T }
0
null
0
1
efde17c1a0036bed47a735564f12f831332134cd
204
Turkce-ve-Osmanlica-Sozluk
Apache License 2.0
app/src/main/java/com/challenge/vegetablediscovery/ui/vitaminfilter/VitaminFilterViewHolder.kt
curlx
369,753,105
false
null
package com.challenge.vegetablediscovery.ui.vitaminfilter import androidx.recyclerview.widget.RecyclerView import com.challenge.vegetablediscovery.databinding.ListItemVitaminBinding import com.challenge.vegetablediscovery.domain.model.Vitamin import com.challenge.vegetablediscovery.extension.toBackgrounColor import com.challenge.vegetablediscovery.extension.toNameAndSubGroupName class VitaminFilterViewHolder( private val itemBinding: ListItemVitaminBinding ) : RecyclerView.ViewHolder(itemBinding.root) { fun bind(vitamin: Vitamin) { val (name, subGroupName) = vitamin.toNameAndSubGroupName() itemBinding.vitamin.setVitamin(name, subGroupName, vitamin.toBackgrounColor()) } }
0
Kotlin
1
0
c9d3e9ee466d575a05aa1a6f79bdbd54111352d8
710
vegetable-discovery
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Mp4File.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.Mp4File: ImageVector get() { if (_mp4File != null) { return _mp4File!! } _mp4File = Builder(name = "Mp4File", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(19.0f, 0.0f) lineTo(5.0f, 0.0f) curveTo(2.243f, 0.0f, 0.0f, 2.243f, 0.0f, 5.0f) verticalLineToRelative(14.0f) curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f) horizontalLineToRelative(10.515f) curveToRelative(0.163f, 0.0f, 0.324f, -0.013f, 0.485f, -0.024f) verticalLineToRelative(-4.976f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) horizontalLineToRelative(4.976f) curveToRelative(0.011f, -0.161f, 0.024f, -0.322f, 0.024f, -0.485f) lineTo(24.0f, 5.0f) curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f) close() moveTo(8.658f, 10.069f) curveToRelative(-0.318f, 0.0f, -0.582f, -0.246f, -0.605f, -0.563f) lineToRelative(-0.201f, -2.776f) lineToRelative(-0.644f, 1.416f) curveToRelative(-0.216f, 0.474f, -0.889f, 0.474f, -1.105f, 0.0f) lineToRelative(-0.644f, -1.416f) lineToRelative(-0.201f, 2.776f) curveToRelative(-0.023f, 0.317f, -0.287f, 0.563f, -0.605f, 0.563f) curveToRelative(-0.352f, 0.0f, -0.631f, -0.299f, -0.605f, -0.651f) lineToRelative(0.338f, -4.659f) curveToRelative(0.032f, -0.535f, 0.358f, -0.759f, 0.749f, -0.759f) curveToRelative(0.26f, 0.0f, 0.501f, 0.184f, 0.638f, 0.486f) lineToRelative(0.883f, 1.942f) lineToRelative(0.883f, -1.942f) curveToRelative(0.137f, -0.302f, 0.378f, -0.486f, 0.638f, -0.486f) curveToRelative(0.391f, 0.0f, 0.717f, 0.224f, 0.749f, 0.759f) lineToRelative(0.338f, 4.659f) curveToRelative(0.026f, 0.352f, -0.253f, 0.651f, -0.605f, 0.651f) close() moveTo(12.467f, 7.97f) lineToRelative(-0.717f, 0.003f) verticalLineToRelative(1.471f) curveToRelative(0.0f, 0.345f, -0.28f, 0.625f, -0.625f, 0.625f) reflectiveCurveToRelative(-0.625f, -0.28f, -0.625f, -0.625f) verticalLineToRelative(-4.819f) curveToRelative(0.0f, -0.345f, 0.28f, -0.625f, 0.625f, -0.625f) horizontalLineToRelative(1.342f) curveToRelative(1.109f, 0.0f, 2.012f, 0.891f, 2.012f, 1.985f) reflectiveCurveToRelative(-0.902f, 1.985f, -2.012f, 1.985f) close() moveTo(19.257f, 9.445f) curveToRelative(0.0f, 0.345f, -0.28f, 0.625f, -0.625f, 0.625f) reflectiveCurveToRelative(-0.625f, -0.28f, -0.625f, -0.625f) verticalLineToRelative(-1.471f) horizontalLineToRelative(-1.23f) curveToRelative(-0.828f, -0.002f, -1.499f, -0.673f, -1.499f, -1.501f) verticalLineToRelative(-1.847f) curveToRelative(0.0f, -0.345f, 0.28f, -0.625f, 0.625f, -0.625f) horizontalLineToRelative(0.018f) curveToRelative(0.348f, 0.0f, 0.629f, 0.284f, 0.625f, 0.632f) curveToRelative(-0.006f, 0.514f, -0.011f, 1.136f, -0.014f, 1.586f) curveToRelative(-0.002f, 0.277f, 0.222f, 0.503f, 0.499f, 0.504f) lineToRelative(0.969f, 0.002f) lineToRelative(0.003f, -2.099f) curveToRelative(0.0f, -0.345f, 0.28f, -0.624f, 0.625f, -0.624f) horizontalLineToRelative(0.004f) curveToRelative(0.345f, 0.0f, 0.625f, 0.28f, 0.625f, 0.625f) verticalLineToRelative(4.819f) close() moveTo(13.229f, 5.985f) curveToRelative(0.0f, 0.398f, -0.349f, 0.735f, -0.762f, 0.735f) lineToRelative(-0.71f, 0.003f) lineToRelative(-0.005f, -1.473f) horizontalLineToRelative(0.715f) curveToRelative(0.413f, 0.0f, 0.762f, 0.336f, 0.762f, 0.735f) close() moveTo(19.0f, 18.0f) horizontalLineToRelative(4.54f) curveToRelative(-0.347f, 0.913f, -0.88f, 1.754f, -1.591f, 2.465f) lineToRelative(-1.484f, 1.485f) curveToRelative(-0.712f, 0.711f, -1.552f, 1.244f, -2.465f, 1.591f) verticalLineToRelative(-4.54f) curveToRelative(0.0f, -0.551f, 0.448f, -1.0f, 1.0f, -1.0f) close() } } .build() return _mp4File!! } private var _mp4File: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,789
icons
MIT License
src/main/kotlin/io/github/niraj_rayalla/gdxseer/managedeffekseer/data/GDXseerEasingVector2D.kt
niraj-rayalla
708,301,331
false
{"Kotlin": 115235, "SWIG": 52854, "C++": 34767, "Makefile": 6274, "CMake": 4452, "Objective-C++": 2747}
package io.github.niraj_rayalla.gdxseer.managedeffekseer.data import io.github.niraj_rayalla.gdxseer.effekseer.InternalStructEasingVector2D import io.github.niraj_rayalla.gdxseer.managedeffekseer.EffekseerManagedField import io.github.niraj_rayalla.gdxseer.managedeffekseer.EffekseerManagedObject /** * A [EffekseerManagedObject] for managing [InternalStructEasingVector2D]. */ @Suppress("unused") class GDXseerEasingVector2D(override val source: InternalStructEasingVector2D): EffekseerManagedObject<InternalStructEasingVector2D>(2) { //region Managed Fields val start: EffekseerManagedField<GDXseerRandomVector2D> = EffekseerManagedField( { GDXseerRandomVector2D(this.source.start) }, { this.source.start = it.source }, this) val end: EffekseerManagedField<GDXseerRandomVector2D> = EffekseerManagedField( { GDXseerRandomVector2D(this.source.end) }, { this.source.end = it.source }, this) //endregion }
0
Kotlin
0
3
4cba2cddca7ed99a42e2f7b26973748f2efa154b
975
GDXseer
Apache License 2.0
domain/src/main/kotlin/com/popularmovies/vpaliy/domain/entity/Trailer.kt
vpaliy
86,759,523
false
null
package com.popularmovies.vpaliy.domain.entity data class Trailer( val video: String, val id: String, val title: String )
2
Kotlin
58
334
dd85fd42a71cd0a4244f1efa1c6817e21db961c8
134
android-movies-app
Apache License 2.0
backend/mlreef-rest/src/main/kotlin/com/mlreef/rest/external_api/gitlab/dto/GitlabRegistry.kt
carlasader
430,857,766
true
{"Kotlin": 1788938, "JavaScript": 1408468, "Python": 165260, "SCSS": 147314, "Shell": 123986, "Ruby": 100068, "TypeScript": 53729, "ANTLR": 27697, "CSS": 19114, "Dockerfile": 18068, "HTML": 8484, "PLpgSQL": 3248, "Batchfile": 310}
package com.mlreef.rest.external_api.gitlab.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties import java.io.Serializable import java.time.Instant @JsonIgnoreProperties(ignoreUnknown = true) data class GitlabRegistry( val id: Long, val name: String? = null, val path: String? = null, val projectId: Long, val location: String? = null, val createdAt: Instant? = null, val cleanupPolicyStartedAt: Instant? = null, ) : Serializable
0
null
0
1
5f450508d3ac68ed0ad3ad68e12acb3a0cb120d9
475
mlreef
MIT License
src/main/kotlin/com/krillsson/sysapi/core/connectivity/ExternalIpAddressService.kt
Krillsson
40,235,586
false
{"Kotlin": 450651, "Shell": 10836, "Batchfile": 734, "Dockerfile": 274}
package com.krillsson.sysapi.core.connectivity import retrofit2.Call import retrofit2.http.GET interface ExternalIpAddressService { @GET("/ip") fun getMyIp(): Call<String> }
9
Kotlin
3
97
bfac764b9fbf3633755e8a045e9d18c5b0b488f8
183
sys-API
Apache License 2.0
data/src/main/java/com/clcmo/data/local/source/JobsCacheDataSource.kt
clcmo
566,922,594
false
{"Kotlin": 25449}
package com.clcmo.data.local.source import com.clcmo.data.local.model.AndroidJobCache import kotlinx.coroutines.flow.Flow interface JobsCacheDataSource { fun getJobs(): Flow<List<AndroidJobCache>> fun insertData(jobCache : AndroidJobCache) fun updateData(cacheList: List<AndroidJobCache>) }
2
Kotlin
0
1
0a0c1069c6e2781b2623d771687f8f7f0c617416
305
ModularizatedApp
MIT License
jvm-debugger/test/testData/classNameCalculator/objectLiterals.kt
JetBrains
278,369,660
false
null
/* ObjectLiteralsKt */fun foo() { /* ObjectLiteralsKt$foo$1 */object : Runnable [ override /* ObjectLiteralsKt$foo$2 */fun run() { block /* ObjectLiteralsKt$foo$2$1 */{ print("foo") } } ] } fun block(block: () -> Unit) { block() }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
299
intellij-kotlin
Apache License 2.0
app/src/main/java/com/buychemi/crm/mvp/presenter/LogDetailsPresenter.kt
kai0726shanxi
209,922,638
false
null
package com.buychemi.crm.mvp.presenter import com.buychemi.crm.base.BasePresenter import com.buychemi.crm.mvp.contract.LogDetailsContract import com.buychemi.crm.mvp.contract.LoginContract import com.buychemi.crm.mvp.model.LogDetailsModel import com.buychemi.crm.mvp.model.LoginModel import com.buychemi.crm.net.exception.ExceptionHandle /** * @Author 20342 * @Date 2019/10/15 16:22 */ class LogDetailsPresenter : BasePresenter<LogDetailsContract.View>(), LogDetailsContract.Presenter { private val loginModel: LogDetailsModel by lazy { LogDetailsModel() } override fun getFollowDetails(map: Map<String, String>) { //邮箱发送验证码 checkViewAttached() mRootView?.showLoading() val disposable = loginModel.getFollowDetails(map) .subscribe({ data -> mRootView?.apply { dismissLoading() onFollowDetails(data.data) } }, { throwable -> mRootView?.apply { //处理异常 showError(ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode) } }) addSubscription(disposable) } override fun getLogDetails(map: Map<String, String>) { checkViewAttached() mRootView?.showLoading() val disposable = loginModel.getLogdetaila(map) .subscribe({ data -> mRootView?.apply { dismissLoading() onLogDetails(data.data) } }, { throwable -> mRootView?.apply { //处理异常 showError(ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode) } }) addSubscription(disposable) } }
1
null
1
1
d9abb27fbd3fe5bc30cdc0e7c483ab07a1668ae8
1,924
CRMBuyCheMiProject
Apache License 2.0
management/src/test/kotlin/at/tuwien/ase/cardlabs/management/TestHelper.kt
flofriday
750,336,268
false
{"Kotlin": 524281, "TypeScript": 149533, "Python": 32297, "Scheme": 3611, "Dockerfile": 608, "CSS": 580, "JavaScript": 221, "PowerShell": 185}
package at.tuwien.ase.cardlabs.management import at.tuwien.ase.cardlabs.management.controller.model.account.Account import at.tuwien.ase.cardlabs.management.controller.model.bot.Bot import at.tuwien.ase.cardlabs.management.controller.model.bot.BotCreate import at.tuwien.ase.cardlabs.management.database.repository.AccountRepository import at.tuwien.ase.cardlabs.management.security.CardLabUser import at.tuwien.ase.cardlabs.management.security.authentication.AccessTokenAuthenticationResponse import at.tuwien.ase.cardlabs.management.security.authentication.AuthenticationResponse import at.tuwien.ase.cardlabs.management.security.jwt.JwtTokenService import at.tuwien.ase.cardlabs.management.service.AccountService import at.tuwien.ase.cardlabs.management.service.bot.BotService import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers class TestHelper { companion object { // == Authentication == @JvmStatic fun createUserDetails(id: Long, username: String, email: String): CardLabUser { return CardLabUser(id, username, email) } @JvmStatic fun getInitialAuthenticationTokens( jwtTokenService: JwtTokenService, accountRepository: AccountRepository, username: String, ): AuthenticationResponse { val userAccount = accountRepository.findByUsernameAndDeletedIsNull(username) if (userAccount?.id == null) { throw Exception() } val cardLabUser = CardLabUser(userAccount.id!!, userAccount.username, userAccount.email) val tokenPair = jwtTokenService.generateTokenPair(cardLabUser) return AuthenticationResponse(tokenPair.refreshToken, tokenPair.accessToken) } @JvmStatic fun getAccessToken( objectMapper: ObjectMapper, mockMvc: MockMvc, refreshToken: String ): AccessTokenAuthenticationResponse { val body = createAuthenticationRefreshJSON(refreshToken) val result = mockMvc.perform( MockMvcRequestBuilders.post("/authentication/refresh") .contentType(MediaType.APPLICATION_JSON) .content(body), ) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() return objectMapper.readValue<AccessTokenAuthenticationResponse>(result.response.contentAsString) } @JvmStatic fun createUserDetails(account: Account): CardLabUser { return CardLabUser(account.id!!, account.username, account.email) } // == Account == @JvmStatic fun createAccount( accountService: AccountService, username: String, email: String, location: String?, ): Account { val account = Account( id = null, username = username, email = email, location = location, ) return accountService.create(account) } @JvmStatic fun createAccount(accountService: AccountService): Account { return createAccount( accountService = accountService, username = "test", email = "<EMAIL>", location = null, ) } @JvmStatic fun getAccount(accountService: AccountService, username: String): Account { return accountService.fetchUser(username) } @JvmStatic fun createAccountCreateJSON( username: String, email: String, location: String?, ): String { return """ { "username": "$username", "email": "$email", "location": ${if (location == null) null else "\"" + location + "\""} } """.trimIndent() } @JvmStatic fun createAccountUpdateCreateJSON( location: String?, ): String { return """ { "location": ${if (location == null) null else "\"" + location + "\""} } """.trimIndent() } @JvmStatic fun createAccountLoginJSON(username: String): String { return """ { "username": "$username" } """.trimIndent() } @JvmStatic fun createAuthenticationRefreshJSON(refreshToken: String): String { return """ { "refreshToken": "$refreshToken" } """.trimIndent() } // == Bot == @JvmStatic fun createBot(botService: BotService, user: CardLabUser, name: String, code: String?): Bot { val botCreate = BotCreate( name = name, currentCode = code, ) return botService.create(user, botCreate) } } }
0
Kotlin
0
0
6fc0a6dc80bd4b6adf6d7fee7921af8a361d03eb
5,403
CardLabs
Apache License 2.0
frontend-core/src/jsMain/kotlin/io/github/andrewk2112/kjsbox/frontend/core/hooks/useAppContext.kt
andrew-k-21-12
497,585,003
false
{"Kotlin": 333927, "JavaScript": 7404, "HTML": 726}
package io.github.andrewk2112.kjsbox.frontend.core.hooks import io.github.andrewk2112.kjsbox.frontend.core.designtokens.Context import io.github.andrewk2112.kjsbox.frontend.core.redux.reducers.ContextReducer /** * A getter hook to read the app's [Context] simpler. */ fun useAppContext(): Context = useInjected<ContextReducer>().useSelector()
0
Kotlin
0
2
94ead57b2a47d3b354135723d4ac7b1b982feeae
347
kjs-box
MIT License
app/src/main/java/com/lukasanda/aismobile/ui/main/email/EmailFragment.kt
LukasAnda
190,038,327
false
{"Java": 546002, "Kotlin": 312655}
/* * Copyright 2020 Lukáš Anda. 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.lukasanda.aismobile.ui.main.email import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.util.Log import androidx.appcompat.widget.AppCompatDrawableManager import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import androidx.recyclerview.widget.RecyclerView import com.google.firebase.analytics.FirebaseAnalytics import com.lukasanda.aismobile.R import com.lukasanda.aismobile.core.ACTION_EMAIL_DELETE import com.lukasanda.aismobile.core.AnalyticsTrait import com.lukasanda.aismobile.core.SCREEN_EMAIL import com.lukasanda.aismobile.core.SwipeHelper import com.lukasanda.aismobile.data.db.entity.Email import com.lukasanda.aismobile.databinding.EmailFragmentBinding import com.lukasanda.aismobile.ui.activity.BaseViews import com.lukasanda.aismobile.ui.fragment.BaseFragment import com.lukasanda.aismobile.ui.main.BaseFragmentHandler import com.lukasanda.aismobile.ui.main.email.adapter.EmailAdapter import com.lukasanda.aismobile.ui.recyclerview.bindLinear import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import timber.log.Timber class EmailFragment : BaseFragment<EmailFragment.Views, EmailFragmentBinding, EmailViewModel, EmailFragmentHandler>(), AnalyticsTrait { override val viewModel: EmailViewModel by viewModel { parametersOf(Bundle()) } override fun setBinding(): EmailFragmentBinding = EmailFragmentBinding.inflate(layoutInflater) override fun createViews() = Views() override lateinit var handler: EmailFragmentHandler val adapter = EmailAdapter { handler.showEmailDetail(it) } override fun getAnalytics() = FirebaseAnalytics.getInstance(requireContext()) inner class Views : BaseViews { override fun modifyViews() { postponeEnterTransition() logEvent(SCREEN_EMAIL) handler.setTitle(getString(R.string.emails)) binding?.recycler?.bindLinear(adapter) val swipeHelper: SwipeHelper = object : SwipeHelper() { @SuppressLint("RestrictedApi") override fun instantiateUnderlayButton(viewHolder: RecyclerView.ViewHolder?, underlayButtons: MutableList<UnderlayButton>?) { underlayButtons?.add( UnderlayButton( "", AppCompatDrawableManager.get().getDrawable(requireContext(), R.drawable.ic_delete), Color.parseColor("#E57373"), object : UnderlayButtonClickListener { override fun onClick(pos: Int) { logEvent(ACTION_EMAIL_DELETE) val email = adapter.getEmailAt(pos) viewModel.deleteEmail(email) Log.d("TAG", "Delete clicked") } } )) underlayButtons?.add(UnderlayButton("", AppCompatDrawableManager.get().getDrawable(requireContext(), R.drawable.ic_reply), ContextCompat.getColor(requireContext(), R.color.color_primary_variant), object : UnderlayButtonClickListener { override fun onClick(pos: Int) { val email = adapter.getEmailAt(pos) handler.replyToEmail(email) Log.d("TAG", "Reply clicked") } } )) } } swipeHelper.attachToRecyclerView(binding?.recycler!!) viewModel.emails().observe(viewLifecycleOwner, Observer { Timber.d("I have to show ${it.size} emails") adapter.swapData(it.sortedByDescending { it.date.takeIf { it.isEmpty() }?.let { DateTime.now() } ?: run { DateTime.parse( it.date, DateTimeFormat.forPattern("dd. MM. yyyy HH:mm") ) } }) startPostponedEnterTransition() }) binding?.compose?.setOnClickListener { handler.composeEmail() } } } } interface EmailFragmentHandler : BaseFragmentHandler { fun showEmailDetail(email: Email) fun replyToEmail(email: Email) fun composeEmail() }
1
null
1
1
ab6bcce5b23ebf99ca34fd25ab76983938baae90
5,259
ais-mobile
Apache License 2.0
app/src/main/java/com/sky/xposed/weishi/hook/handler/AutoPlayHandler.kt
sky-wei
130,973,364
false
{"Kotlin": 113909}
/* * Copyright (c) 2018. The sky Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sky.xposed.weishi.hook.handler import android.view.ViewGroup import com.sky.xposed.common.util.Alog import com.sky.xposed.common.util.ToastUtil import com.sky.xposed.weishi.hook.HookManager import de.robv.android.xposed.XposedHelpers class AutoPlayHandler(hookManager: HookManager) : CommonHandler(hookManager), Runnable { private var isPlaying = false fun setAutoPlay(play: Boolean) { if (play) { // 开始自动播放 startPlay() } else { if (isPlaying) ToastUtil.show("停止自动播放") // 关闭自动播放 stopPlay() } } fun startPlay() { startPlay(mUserConfigManager.getAutoPlaySleepTime()) } fun startPlay(delayMillis: Long) { if (!mUserConfigManager.isAutoPlay()) { // 不进行播放处理 return } if (isPlaying) { Alog.d("正在自动播放视频") return } // 标识正在播放 isPlaying = true // 播放下一个 playNext(delayMillis) } fun stopPlay() { isPlaying = false removeCallbacks(this) } private fun playNext(delayMillis: Long) { // 开始播放 postDelayed(this, delayMillis) ToastUtil.show((delayMillis / 1000).toString() + "秒后播放下一个视频") } override fun run() { if (!isPlaying) return val mViewPager = mObjectManager.getViewPager() as? ViewGroup if (mViewPager == null || !mUserConfigManager.isAutoPlay()) { // 停止播放处理 stopPlay() return } if (!mViewPager.isShown) { // 停止播放(界面不可见了) stopPlay() ToastUtil.show("界面切换,自动播放将暂停") return } // 获取当前页 val currentItem = getCurrentPosition() // 切换页面 XposedHelpers.callMethod(mViewPager, mVersionConfig.methodViewPagerSmooth, currentItem + 1) // 继续播放下一个 playNext(mUserConfigManager.getAutoPlaySleepTime()) } }
1
Kotlin
11
38
6577fcfde151466aae0653fb215760fffebbcab5
2,606
xposed-weishi
Apache License 2.0
app/src/main/java/software/tice/walletandroid/ui/screens/ManageDocumentsScreen.kt
TICESoftware
806,917,415
false
{"Kotlin": 469414, "Ruby": 1325}
package software.tice.walletandroid.ui.screens import android.util.Log import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.ramcosta.composedestinations.annotation.Destination import software.tice.walletandroid.R import software.tice.walletandroid.ui.components.DocumentItem import software.tice.walletandroid.ui.components.SwipeToDeleteLazyColumn import software.tice.walletandroid.ui.screens.layout.ScaffoldAction import software.tice.walletandroid.ui.screens.layout.WalletScaffold import software.tice.walletandroid.ui.theme.WalletTheme import software.tice.walletandroid.ui.viewModels.ManageDocumentsViewModel import software.tice.walletandroid.ui.viewModels.ManageDocumentsViewModelType @Destination @Composable fun ManageDocumentsScreen(viewModel: ManageDocumentsViewModelType = hiltViewModel<ManageDocumentsViewModel>()) { val state by viewModel.state.collectAsState() WalletScaffold( title = stringResource(R.string.managedocuments_title), backAction = ScaffoldAction.backAction(viewModel::onBackClick), ) { contentPadding -> Column( modifier = Modifier .padding(contentPadding) .fillMaxSize() ) { val deleteSelected = remember { mutableStateOf(false) } SwipeToDeleteLazyColumn( items = state.documents.sortedByDescending { it.createdAt }, deleteSelected = deleteSelected, deleteMode = state.deleteMode, toggleDeleteMode = { viewModel.toggleDeleteMode() }, deleteEntry = { viewModel.deleteDocument(it) }, ) { DocumentItem( modifier = Modifier.padding(start = 24.dp), document = it, ) { Log.d("testing", "click") } } Spacer(modifier = Modifier.weight(1f)) Row( modifier = Modifier .padding( start = 12.dp, end = 12.dp, bottom = 24.dp, ).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, ) { TextButton( onClick = viewModel::toggleDeleteMode, ) { Text( text = stringResource(if (state.deleteMode) R.string.generic_cancel else R.string.button_select), style = WalletTheme.typography.textButton, color = WalletTheme.colors.buttons, ) } if (state.deleteMode) { TextButton( onClick = { deleteSelected.value = true }, ) { Icon( painter = painterResource(id = R.drawable.ic_delete), contentDescription = null, tint = WalletTheme.colors.destructiveAction, ) Text( text = stringResource(R.string.button_delete_selected), style = WalletTheme.typography.textButton, color = WalletTheme.colors.destructiveAction, ) } } } } } }
0
Kotlin
0
0
9f821a612e795151c9b5cf3f80b115c55ccf5e96
4,368
WalletAndroid
Apache License 2.0
remote/src/main/java/com/ferelin/remote/api/companyProfile/CompanyProfileApi.kt
sarath940
391,107,525
true
{"Kotlin": 768543}
package com.ferelin.remote.api.companyProfile /* * Copyright 2021 <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 * * 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. */ import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query internal interface CompanyProfileApi { @GET("stock/profile2") fun getCompanyProfile( @Query("symbol") symbol: String, @Query("token") token: String ): Call<CompanyProfileResponse> }
0
null
0
0
2c0e4b045786fdf4b4d51bf890a3dbf0cd8099d1
925
Android_Stock_Price
Apache License 2.0
jetbrains-core/tst/software/aws/toolkits/jetbrains/services/lambda/execution/PathMapperTest.kt
mithilarao
176,211,165
false
{"Gradle": 9, "Markdown": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 6, "Kotlin": 277, "Java": 11, "XML": 15, "SVG": 12, "INI": 1, "JSON": 18, "CODEOWNERS": 1}
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.lambda.execution import com.intellij.openapi.util.io.FileUtil import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.nio.file.Files class PathMapperTest { @Rule @JvmField val tempFolder = TemporaryFolder() private lateinit var mapper: PathMapper @Test fun firstMatchWinsLocally() { initMapper { addMapping("local", "remote") addMapping("local2", "remote2") addMapping("local2", "remote2/sub/") } createLocalFile("local2/foo") assertThat(convertToLocal("remote2/foo")).isEqualTo("local2/foo") } @Test fun firstMatchWinsRemotely() { initMapper { addMapping("local", "remote") addMapping("local2", "remote2") addMapping("local2", "remote2/sub/") } assertThat(mapper.convertToRemote(createLocalFile("local2/foo"))).isEqualTo("remote2/foo") } @Test fun onlyPrefixIsReplaced() { initMapper { addMapping("local/sub", "remote/sub/sub") } assertThat(mapper.convertToRemote(createLocalFile("local/sub/foo"))).isEqualTo("remote/sub/sub/foo") } @Test fun matchesAtFolderBoundary() { initMapper { addMapping("local", "remote") addMapping("localFolder", "remote2") } assertThat(mapper.convertToRemote(createLocalFile("localFolder/foo"))).isEqualTo("remote2/foo") } @Test fun fileMustExistLocally() { initMapper { addMapping("local1", "remote") addMapping("local2", "remote") } createLocalFile("local2/foo") assertThat(convertToLocal("remote/foo")).isEqualTo("local2/foo") } @Test fun trailingSlashIsIgnored() { initMapper { addMapping("local/", "remote/") addMapping("local2", "remote2") } assertThat(mapper.convertToRemote(createLocalFile("local/foo"))).isEqualTo("remote/foo") assertThat(convertToLocal("remote/foo")).isEqualTo("local/foo") assertThat(mapper.convertToRemote(createLocalFile("local2/foo"))).isEqualTo("remote2/foo") assertThat(convertToLocal("remote2/foo")).isEqualTo("local2/foo") } @Test fun unknownPathsReturnNull() { initMapper { } assertThat(mapper.convertToRemote(createLocalFile("foo"))).isNull() assertThat(convertToLocal("foo")).isNull() } private fun convertToLocal(remote: String) = mapper.convertToLocal(remote) ?.removePrefix(FileUtil.normalize(tempFolder.root.absolutePath)) ?.removePrefix("/") private fun createLocalFile(path: String): String { val file = tempFolder.root.toPath().resolve(path) Files.createDirectories(file.parent) if (!Files.exists(file)) { Files.createFile(file) } return file.toString() } private fun initMapper(init: MutableList<PathMapping>.() -> Unit) { val mappings = mutableListOf<PathMapping>() mappings.init() mapper = PathMapper(mappings) } private fun MutableList<PathMapping>.addMapping(local: String, remote: String) { val file = tempFolder.root.toPath().resolve(local) Files.createDirectories(file.parent) this.add(PathMapping(file.toString(), remote)) } }
1
null
1
1
396b43084ffba31be1f8ab54b75b704b784f38a1
3,603
jsinbucket
Apache License 2.0
app/src/main/java/com/jesen/opencvface/utils/FileUtil.kt
Jesen0823
397,951,876
false
{"C++": 5533468, "C": 354800, "Kotlin": 87998, "Objective-C": 8344, "Java": 3554, "CMake": 512}
package com.jesen.opencvface.utils import android.content.Context import android.os.Environment import java.io.File import java.io.FileOutputStream import java.lang.Exception import java.text.SimpleDateFormat import java.util.* object FileUtil { @JvmStatic fun copyAssets(context: Context, name: String?) { val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name) if (file.exists()) { file.delete() } try { val fos = FileOutputStream(file) val `is` = context.assets.open(file.absolutePath) var len: Int val b = ByteArray(2048) while (`is`.read(b).also { len = it } != -1) { fos.write(b, 0, len) } fos.close() `is`.close() } catch (e: Exception) { e.printStackTrace() } } @JvmStatic fun getStoragePath(context: Context, type: String?): String { var baseDir: String val state = Environment.getExternalStorageState() if (Environment.MEDIA_MOUNTED == state) { var baseDirFile = context.getExternalFilesDir(type) baseDir = if (baseDirFile != null) { baseDirFile.absolutePath } else { context.filesDir.absolutePath } } else { baseDir = context.filesDir.absolutePath; } return baseDir } @JvmStatic fun createCameraFile(folderName: String = "camera", context: Context): File? { return try { val rootFile = File(getStoragePath(context, Environment.DIRECTORY_DCIM) + File.separator + folderName) if (!rootFile.exists()) rootFile.mkdirs() val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val fileName = "IMG_$timeStamp.jpg" File(rootFile.absolutePath + File.separator + fileName) } catch (e: Exception) { e.printStackTrace() null } } }
1
C++
1
1
c2d557cc19883657fd05c8e11183852971a3f293
2,079
OpencvFace
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/entry/EntryDetailPresenter.kt
saletrak
108,895,760
true
{"Kotlin": 211185}
package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi import io.github.feelfreelinux.wykopmobilny.api.entries.TypedInputStream import io.github.feelfreelinux.wykopmobilny.base.BasePresenter import io.github.feelfreelinux.wykopmobilny.utils.rx.SubscriptionHelperApi class EntryDetailPresenter(private val subscriptionHelper: SubscriptionHelperApi, private val entriesApi: EntriesApi) : BasePresenter<EntryDetailView>() { var entryId = 0 fun loadData() { view?.hideInputToolbar() subscriptionHelper.subscribe( entriesApi.getEntryIndex(entryId), { view?.showEntry(it) }, { view?.showErrorDialog(it) }, this) } fun addComment(body : String, photo: TypedInputStream) { subscriptionHelper.subscribe( entriesApi.addEntryComment(body, entryId, photo), { view?.hideInputbarProgress() view?.resetInputbarState() loadData() // Refresh view }, { view?.hideInputbarProgress() view?.showErrorDialog(it) }, this ) } fun addComment(body : String, photo : String?) { subscriptionHelper.subscribe( entriesApi.addEntryComment(body, entryId, photo), { view?.hideInputbarProgress() view?.resetInputbarState() loadData() // Refresh view }, { view?.hideInputbarProgress() view?.showErrorDialog(it) }, this ) } override fun unsubscribe() { super.unsubscribe() subscriptionHelper.dispose(this) } }
0
Kotlin
0
0
71771c3f1973d72c46020177a3c8dde7ab815b4d
1,903
WykopMobilny
MIT License