path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/de/agiledojo/kata/checkoutservice/CheckoutApplication.kt
cfisch3r
766,937,865
false
{"Kotlin": 12032}
package de.agiledojo.kata.checkoutservice import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class CheckoutApplication fun main(args: Array<String>) { runApplication<CheckoutApplication>(*args) }
0
Kotlin
0
0
abfe9f7c0de756a86fdd09cbf5bcb531c7a189bc
287
potter-service
The Unlicense
tokisaki-server/src/main/kotlin/io/micro/server/robot/infra/po/RobotEntity.kt
spcookie
730,690,607
false
{"Kotlin": 232855, "Java": 24191}
package io.micro.server.robot.infra.po import io.micro.core.base.BaseEnum import io.micro.core.persistence.BaseEntity import io.micro.server.auth.infra.po.UserEntity import jakarta.persistence.* import org.hibernate.annotations.Fetch import org.hibernate.annotations.FetchMode import org.hibernate.proxy.HibernateProxy @Table(name = "tokisaki_robot") @Entity class RobotEntity : BaseEntity() { @ManyToOne @Fetch(FetchMode.JOIN) @JoinColumn(name = "user_id", nullable = false) var user: UserEntity? = null @Column(name = "robot_name", nullable = false) var name: String? = null @Column(name = "robot_account", nullable = false) var account: String? = null @Column(name = "robot_password") var password: String? = null @Enumerated(EnumType.ORDINAL) @Column(name = "robot_type", nullable = false) var type: Type? = null @Enumerated(EnumType.ORDINAL) @Column(name = "robot_state", nullable = false) var state: State? = null @Column(name = "robot_remark") var remark: String? = null @OneToMany(fetch = FetchType.EAGER, cascade = [CascadeType.PERSIST, CascadeType.REFRESH]) @JoinColumn(name = "robot_id") var functions: MutableSet<UseFunctionEntity>? = null @Column(name = "robot_cmd_prefix", nullable = false) var cmdPrefix: String? = null enum class Type(override var title: String, override var code: String) : BaseEnum<String> { QQ("逆向QQ机器人", "113.01"); } enum class State(override var title: String, override var code: String) : BaseEnum<String> { Create("已创建", "114.01"), LoggingIn("登录中", "114.02"), LoggingFail("登录失败", "114.03"), Online("在线", "114.04"), Offline("离线", "114.05"), Closed("已关闭", "114.06"), ALL("所有", "114.07"); } final override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false val oEffectiveClass = if (other is HibernateProxy) other.hibernateLazyInitializer.persistentClass else other.javaClass val thisEffectiveClass = if (this is HibernateProxy) this.hibernateLazyInitializer.persistentClass else this.javaClass if (thisEffectiveClass != oEffectiveClass) return false other as RobotEntity return id != null && id == other.id } final override fun hashCode(): Int = if (this is HibernateProxy) this.hibernateLazyInitializer.persistentClass.hashCode() else javaClass.hashCode() }
0
Kotlin
0
0
eedb3574eb0c5c7f35c479447a7b6eac4c390cb0
2,533
Tokisaki
Apache License 2.0
app/src/main/kotlin/com/fibelatti/pinboard/features/posts/domain/usecase/AddPost.kt
fibelatti
165,537,939
false
null
package com.fibelatti.pinboard.features.posts.domain.usecase import com.fibelatti.core.functional.Result import com.fibelatti.core.functional.UseCaseWithParams import com.fibelatti.core.functional.map import com.fibelatti.pinboard.features.posts.domain.PostsRepository import com.fibelatti.pinboard.features.posts.domain.model.Post import com.fibelatti.pinboard.features.tags.domain.model.Tag import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import javax.inject.Inject class AddPost @Inject constructor( private val postsRepository: PostsRepository, private val validateUrl: ValidateUrl ) : UseCaseWithParams<Post, AddPost.Params>() { override suspend fun run(params: Params): Result<Post> = validateUrl(params.url).map { withContext(NonCancellable) { postsRepository.add( url = params.url, title = params.title, description = params.description, private = params.private, readLater = params.readLater, tags = params.tags, replace = params.replace, hash = params.hash, ) } } data class Params( val url: String, val title: String, val description: String? = null, val private: Boolean? = null, val readLater: Boolean? = null, val tags: List<Tag>? = null, val replace: Boolean = true, val hash: String? = null, ) { constructor(post: Post) : this( url = post.url, title = post.title, description = post.description, private = post.private, readLater = post.readLater, tags = post.tags, hash = post.hash, ) } }
5
Kotlin
8
89
374976944d5ff5063e4281f8307ff259afd0731c
1,862
pinboard-kotlin
Apache License 2.0
app/src/main/java/org/stepic/droid/ui/fragments/NewCommentFragment.kt
abhirocks1211
205,717,847
true
{"Java": 1818802, "Kotlin": 1403557, "CSS": 3790, "Shell": 618, "Prolog": 98}
package org.stepic.droid.ui.fragments import android.app.Activity import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.Toast import kotlinx.android.synthetic.main.new_comment_fragment.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.base.FragmentBase import org.stepic.droid.ui.activities.NewCommentActivity import org.stepic.droid.ui.dialogs.DiscardTextDialogFragment import org.stepic.droid.ui.dialogs.LoadingProgressDialog import org.stepic.droid.ui.util.BackButtonHandler import org.stepic.droid.ui.util.OnBackClickListener import org.stepic.droid.ui.util.initCenteredToolbar import org.stepic.droid.util.ProgressHelper import org.stepic.droid.web.CommentsResponse import retrofit2.Call import retrofit2.Callback import retrofit2.Response class NewCommentFragment : FragmentBase(), OnBackClickListener { companion object { private val discardTextRequestCode = 913 private val targetKey = "targetKey" private val parentKey = "parentKey" fun newInstance(target: Long, parent: Long?): Fragment { val args = Bundle() if (parent != null) { args.putLong(parentKey, parent) } args.putLong(targetKey, target) val fragment = NewCommentFragment() fragment.arguments = args return fragment } } private var target: Long? = null private var parent: Long? = null private var isCommentSending: Boolean = false private lateinit var loadingProgressDialog: LoadingProgressDialog private var sendMenuItem: MenuItem? = null private var backButtonHandler: BackButtonHandler? = null override fun onAttach(context: Context?) { super.onAttach(context) (activity as? BackButtonHandler)?.setBackClickListener(this) } override fun onDetach() { backButtonHandler?.removeBackClickListener(this) backButtonHandler = null super.onDetach() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?) = inflater?.inflate(R.layout.new_comment_fragment, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) target = arguments.getLong(NewCommentFragment.targetKey) parent = arguments.getLong(NewCommentFragment.parentKey) if (parent == 0L) { parent = null } setHasOptionsMenu(true) initToolbar() initProgressDialog() } private fun initProgressDialog() { loadingProgressDialog = LoadingProgressDialog(context) } override fun onResume() { super.onResume() if (!inputCommentForm.isFocused) { inputCommentForm.requestFocus() } inputCommentForm.postDelayed({ showSoftKeypad(inputCommentForm) }, 300) } private fun initToolbar() { initCenteredToolbar(R.string.new_comment_title, true, -1) } private fun showSoftKeypad(editTextView: View) { val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(editTextView, InputMethodManager.SHOW_IMPLICIT) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) inflater?.inflate(R.menu.new_comment_menu, menu) sendMenuItem = menu?.findItem(R.id.action_send_comment) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.action_send_comment -> { sendComment() return true } } return super.onOptionsItemSelected(item) } private fun sendComment() { analytic.reportEvent(Analytic.Comments.CLICK_SEND_COMMENTS) val text: String = textResolver.replaceWhitespaceToBr(inputCommentForm.text.toString()) if (text.isEmpty()) { Toast.makeText(context, R.string.feedback_fill_fields, Toast.LENGTH_SHORT).show() } else if (!isCommentSending) { fun enableMenuItem(needEnable: Boolean = true) { sendMenuItem?.isEnabled = needEnable if (needEnable) { sendMenuItem?.icon?.alpha = 255 } else { sendMenuItem?.icon?.alpha = 128 } } isCommentSending = true enableMenuItem(false) ProgressHelper.activate(loadingProgressDialog) fun onFinishTryingSending() { isCommentSending = false ProgressHelper.dismiss(loadingProgressDialog) enableMenuItem(true) } api.postComment(text, target!!, parent).enqueue(object : Callback<CommentsResponse> { override fun onResponse(call: Call<CommentsResponse>?, response: Response<CommentsResponse>?) { if (response?.isSuccessful ?: false && response?.body()?.comments != null) { analytic.reportEvent(Analytic.Comments.COMMENTS_SENT_SUCCESSFULLY) val newComment = response.body()?.comments?.firstOrNull() if (newComment != null) { val data = Intent() //set id, target, parent data.putExtra(NewCommentActivity.keyComment, newComment) activity?.setResult(Activity.RESULT_OK, data) } Toast.makeText(App.getAppContext(), R.string.comment_sent, Toast.LENGTH_SHORT).show() onFinishTryingSending() activity?.finish() } else { Toast.makeText(App.getAppContext(), R.string.comment_denied, Toast.LENGTH_SHORT).show() onFinishTryingSending() } } override fun onFailure(call: Call<CommentsResponse>?, t: Throwable?) { Toast.makeText(App.getAppContext(), R.string.connectionProblems, Toast.LENGTH_LONG).show() onFinishTryingSending() } }) } } override fun onBackClick(): Boolean { if (inputCommentForm.text?.isNotBlank() ?: false) { val dialog = DiscardTextDialogFragment.newInstance() dialog.setTargetFragment(this, discardTextRequestCode) if (!dialog.isAdded) { analytic.reportEvent(Analytic.Comments.SHOW_CONFIRM_DISCARD_TEXT_DIALOG) dialog.show(fragmentManager, null) } return true } else { return false } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && requestCode == discardTextRequestCode) { analytic.reportEvent(Analytic.Comments.SHOW_CONFIRM_DISCARD_TEXT_DIALOG_SUCCESS) activity?.finish() } } }
1
Java
1
1
8a2ead7334b6b26a281b3a7842e6502fd96b2cc5
7,567
stepik-android
Apache License 2.0
app/src/main/java/com/example/habit/data/Mapper/SocialMapper/FollowMapper.kt
vickatGit
663,121,210
false
{"Kotlin": 482474, "Java": 4691}
package com.example.habit.data.Mapper.SocialMapper import com.example.habit.data.Mapper.SocialMapper.UserMapper.toUser import com.example.habit.data.network.model.FollowModel.FollowerModel import com.example.habit.data.network.model.FollowModel.FollowingModel import com.example.habit.domain.models.Follow.Follow import com.example.habit.domain.models.User.User object FollowMapper { fun FollowerModel.toFollow(): Follow { val users = mutableListOf<User>() this.users?.map { it?.follows?.let { users.add(it.toUser()) } } return Follow(users) } fun FollowingModel.toFollow(): Follow { val users = mutableListOf<User>() this.users?.map { it?.to?.let { users.add(it.toUser()) } } return Follow(users) } }
0
Kotlin
0
0
67559162f6501881b4fbd9ff807e6e13023fc087
866
HB
MIT License
app-android/src/main/java/dev/sergiobelda/todometer/app/android/ui/navhost/TodometerNavHost.kt
serbelga
301,817,067
false
{"Kotlin": 616474, "Swift": 767}
/* * Copyright 2022 Sergio Belda * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.sergiobelda.todometer.app.android.ui.navhost import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import dev.sergiobelda.todometer.app.android.ui.about.AboutRoute import dev.sergiobelda.todometer.app.android.ui.addtask.AddTaskRoute import dev.sergiobelda.todometer.app.android.ui.addtasklist.AddTaskListRoute import dev.sergiobelda.todometer.app.android.ui.edittask.EditTaskRoute import dev.sergiobelda.todometer.app.android.ui.edittasklist.EditTaskListRoute import dev.sergiobelda.todometer.app.android.ui.home.HomeRoute import dev.sergiobelda.todometer.app.android.ui.settings.SettingsRoute import dev.sergiobelda.todometer.app.android.ui.taskdetails.TaskDetailsRoute import dev.sergiobelda.todometer.app.feature.about.ui.AboutDestination import dev.sergiobelda.todometer.app.feature.about.ui.GitHubUrl import dev.sergiobelda.todometer.app.feature.about.ui.PrivacyPolicyUrl import dev.sergiobelda.todometer.app.feature.about.ui.navigateToAbout import dev.sergiobelda.todometer.app.feature.addtask.ui.AddTaskDestination import dev.sergiobelda.todometer.app.feature.addtask.ui.navigateToAddTask import dev.sergiobelda.todometer.app.feature.addtasklist.ui.AddTaskListDestination import dev.sergiobelda.todometer.app.feature.addtasklist.ui.navigateToAddTaskList import dev.sergiobelda.todometer.app.feature.edittask.ui.EditTaskDestination import dev.sergiobelda.todometer.app.feature.edittask.ui.navigateToEditTask import dev.sergiobelda.todometer.app.feature.edittasklist.ui.EditTaskListDestination import dev.sergiobelda.todometer.app.feature.edittasklist.ui.navigateToEditTaskList import dev.sergiobelda.todometer.app.feature.home.ui.HomeDestination import dev.sergiobelda.todometer.app.feature.settings.ui.SettingsDestination import dev.sergiobelda.todometer.app.feature.settings.ui.navigateToSettings import dev.sergiobelda.todometer.app.feature.taskdetails.ui.TaskDetailsDestination import dev.sergiobelda.todometer.app.feature.taskdetails.ui.navigateToTaskDetails import dev.sergiobelda.todometer.common.android.extensions.launchActivity import dev.sergiobelda.todometer.common.android.extensions.openWebPage import dev.sergiobelda.todometer.common.navigation.Action @OptIn(ExperimentalComposeUiApi::class) @Composable internal fun TodometerNavHost( navController: NavHostController, action: Action, modifier: Modifier = Modifier ) { val context = LocalContext.current val keyboardController = LocalSoftwareKeyboardController.current val navigateBackAction: () -> Unit = { keyboardController?.hide() action.navigateUp() } NavHost( navController = navController, startDestination = HomeDestination.route, modifier = modifier ) { composable(HomeDestination.route) { HomeRoute( navigateToAddTaskList = action.navigateToAddTaskList, navigateToEditTaskList = action.navigateToEditTaskList, navigateToAddTask = action.navigateToAddTask, navigateToTaskDetails = action.navigateToTaskDetails, navigateToSettings = action.navigateToSettings, navigateToAbout = action.navigateToAbout ) } composable( TaskDetailsDestination.route, deepLinks = listOf(TaskDetailsDestination.taskDetailNavDeepLink) ) { navBackStackEntry -> val taskId = TaskDetailsDestination.navArgsTaskId(navBackStackEntry) TaskDetailsRoute( taskId = taskId, navigateToEditTask = { action.navigateToEditTask(taskId) }, navigateBack = navigateBackAction ) } composable(AddTaskListDestination.route) { AddTaskListRoute(navigateBack = navigateBackAction) } composable(EditTaskListDestination.route) { EditTaskListRoute(navigateBack = navigateBackAction) } composable( AddTaskDestination.route, deepLinks = listOf(AddTaskDestination.addTaskNavDeepLink) ) { AddTaskRoute(navigateBack = navigateBackAction) } composable(EditTaskDestination.route) { backStackEntry -> val taskId = EditTaskDestination.navArgsTaskId(backStackEntry) EditTaskRoute(taskId = taskId, navigateBack = navigateBackAction) } composable(SettingsDestination.route) { SettingsRoute( navigateBack = navigateBackAction ) } composable(AboutDestination.route) { AboutRoute( navigateToGitHub = { context.openWebPage(GitHubUrl) }, navigateToPrivacyPolicy = { context.openWebPage(PrivacyPolicyUrl) }, navigateToOpenSourceLicenses = { context.launchActivity<OssLicensesMenuActivity>() }, navigateBack = navigateBackAction ) } } }
9
Kotlin
31
488
517c9161ec1ef53d223993e66d50895fda7f4959
5,918
Todometer-KMP
Apache License 2.0
app/src/main/kotlin/com/boscatov/schedulercw/view/adapter/project/ProjectDiffUtil.kt
23alot
160,862,563
false
null
package com.boscatov.schedulercw.view.adapter.add_project import androidx.recyclerview.widget.DiffUtil import com.boscatov.schedulercw.data.entity.Project /** * Created by boscatov on 14.04.2019. */ class AddProjectDiffUtil( private val oldList: List<Project>, private val newList: List<Project> ): DiffUtil.Callback() { override fun getNewListSize(): Int = newList.count() override fun getOldListSize(): Int = oldList.count() override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = oldList[oldItemPosition] val new = newList[newItemPosition] return old.projectName == new.projectName } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = oldList[oldItemPosition] val new = newList[newItemPosition] return old.projectId == new.projectId } }
0
Kotlin
0
0
28ef14d8134a8555b1f2dee62bce9bef5ad6f607
910
scheduler-cw
Apache License 2.0
app/src/main/java/com/bytedance/ttgame/dagger2application/dagger/ActivitySubcomponent.kt
CreateChance
725,986,477
false
{"Kotlin": 23567}
package com.bytedance.ttgame.dagger2application.dagger import com.bytedance.ttgame.dagger2application.MainActivity import com.bytedance.ttgame.dagger2application.SecondActivity import dagger.Subcomponent /** * * * @author 高超(gaochao.cc) * @since 2023/12/1 */ @Subcomponent(modules = [ActivityMutableDataModule::class]) interface ActivitySubcomponent { fun inject(target: MainActivity) fun inject(target: SecondActivity) @Subcomponent.Factory interface Factory { fun create(): ActivitySubcomponent } }
0
Kotlin
0
0
507abee830e8028a14ca96b39e2c15bec8b9c380
538
Dagger2Application
Apache License 2.0
plugins/kotlin/idea/tests/testData/inspectionsLocal/unnecessaryOptInAnnotation/typeAlias.kt
ingokegel
72,937,917
false
null
// WITH_STDLIB // COMPILER_ARGUMENTS: -Xopt-in=kotlin.RequiresOptIn @RequiresOptIn @Target(AnnotationTarget.TYPEALIAS) annotation class Marker class A { fun foo() {} } @Marker typealias B = A @OptIn(Marker::class<caret>) fun bar() { val x = A() x.foo() }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
271
intellij-community
Apache License 2.0
demo/src/main/kotlin/com/otaliastudios/cameraview/demo/PicturePreviewActivity.kt
natario1
97,580,115
false
{"Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 34, "YAML": 7, "Proguard": 2, "Java": 242, "XML": 33, "Kotlin": 6, "Ruby": 1, "HTML": 9, "SVG": 2, "CSS": 7}
package com.otaliastudios.cameraview.demo import android.content.Intent import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.otaliastudios.cameraview.CameraUtils import com.otaliastudios.cameraview.PictureResult import com.otaliastudios.cameraview.controls.PictureFormat import com.otaliastudios.cameraview.size.AspectRatio import java.io.File class PicturePreviewActivity : AppCompatActivity() { companion object { var pictureResult: PictureResult? = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_picture_preview) val result = pictureResult ?: run { finish() return } val imageView = findViewById<ImageView>(R.id.image) val captureResolution = findViewById<MessageView>(R.id.nativeCaptureResolution) val captureLatency = findViewById<MessageView>(R.id.captureLatency) val exifRotation = findViewById<MessageView>(R.id.exifRotation) val delay = intent.getLongExtra("delay", 0) val ratio = AspectRatio.of(result.size) captureLatency.setTitleAndMessage("Approx. latency", "$delay milliseconds") captureResolution.setTitleAndMessage("Resolution", "${result.size} ($ratio)") exifRotation.setTitleAndMessage("EXIF rotation", result.rotation.toString()) try { result.toBitmap(1000, 1000) { bitmap -> imageView.setImageBitmap(bitmap) } } catch (e: UnsupportedOperationException) { imageView.setImageDrawable(ColorDrawable(Color.GREEN)) Toast.makeText(this, "Can't preview this format: " + result.getFormat(), Toast.LENGTH_LONG).show() } if (result.isSnapshot) { // Log the real size for debugging reason. val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeByteArray(result.data, 0, result.data.size, options) if (result.rotation % 180 != 0) { Log.e("PicturePreview", "The picture full size is ${result.size.height}x${result.size.width}") } else { Log.e("PicturePreview", "The picture full size is ${result.size.width}x${result.size.height}") } } } override fun onDestroy() { super.onDestroy() if (!isChangingConfigurations) { pictureResult = null } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.share, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.share) { Toast.makeText(this, "Sharing...", Toast.LENGTH_SHORT).show() val extension = when (pictureResult!!.format) { PictureFormat.JPEG -> "jpg" PictureFormat.DNG -> "dng" else -> throw RuntimeException("Unknown format.") } val file = File(filesDir, "picture.$extension") CameraUtils.writeToFile(pictureResult!!.data, file) { file -> if (file != null) { val context = this@PicturePreviewActivity val intent = Intent(Intent.ACTION_SEND) intent.type = "image/*" val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file) intent.putExtra(Intent.EXTRA_STREAM, uri) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) startActivity(intent) } else { Toast.makeText(this@PicturePreviewActivity, "Error while writing file.", Toast.LENGTH_SHORT).show() } } return true } return super.onOptionsItemSelected(item) } }
117
Java
917
4,876
b279ffaf57919b7dffccc8879a0cb1eeb542c1ca
4,306
CameraView
MIT License
src/main/kotlin/org/arend/codeInsight/completion/Constants.kt
JetBrains
96,068,447
false
{"Kotlin": 2644104, "Lex": 16187, "Java": 5894, "HTML": 2144, "CSS": 1108, "JavaScript": 713}
package org.arend.codeInsight.completion import org.arend.psi.ArendElementTypes.* val FIXITY_KWS = listOf(INFIX_LEFT_KW, INFIX_RIGHT_KW, INFIX_NON_KW, NON_ASSOC_KW, LEFT_ASSOC_KW, RIGHT_ASSOC_KW).map { it.toString() } val STATEMENT_WT_KWS = listOf(FUNC_KW, SFUNC_KW, LEMMA_KW, TYPE_KW, CONS_KW, DATA_KW, CLASS_KW, RECORD_KW, INSTANCE_KW, OPEN_KW, MODULE_KW, META_KW, PLEVELS_KW, HLEVELS_KW).map { it.toString() } val CLASS_MEMBER_KWS = listOf(FIELD_KW, PROPERTY_KW, OVERRIDE_KW, DEFAULT_KW).map { it.toString() } val SIGMA_TELE_START_KWS = listOf(PROPERTY_KW).map { it.toString() } val DATA_UNIVERSE_KW = listOf("\\Type", "\\Set", PROP_KW.toString(), "\\oo-Type", "\\hType") val BASIC_EXPRESSION_KW = listOf(PI_KW, SIGMA_KW, LAM_KW, HAVE_KW, HAVES_KW, LET_KW, LETS_KW, CASE_KW, SCASE_KW).map { it.toString() } val LEVEL_KWS = listOf(MAX_KW, SUC_KW).map { it.toString() } val LPH_KW_LIST = listOf(LP_KW, LH_KW, OO_KW).map { it.toString() } val PH_LEVELS_KW_LIST = listOf(PLEVELS_KW, HLEVELS_KW).map { it.toString() } val ELIM_WITH_KW_LIST = listOf(ELIM_KW, WITH_KW).map { it.toString() } val COERCE_LEVEL_KWS = listOf(COERCE_KW, LEVEL_KW).map { it.toString() } val NEW_KW_LIST = listOf(NEW_KW.toString(), EVAL_KW.toString(), PEVAL_KW.toString()) val TRUNCATED_DATA_KW = "$TRUNCATED_KW $DATA_KW" val AS_KW_LIST = listOf(AS_KW.toString()) val USING_KW_LIST = listOf(USING_KW.toString()) val HIDING_KW_LIST = listOf(HIDING_KW.toString()) val EXTENDS_KW_LIST = listOf(EXTENDS_KW.toString()) val DATA_KW_LIST = listOf(DATA_KW.toString()) val IMPORT_KW_LIST = listOf(IMPORT_KW.toString()) val WHERE_KW_LIST = listOf(WHERE_KW.toString()) val WHERE_KW_FULL = WHERE_KW_LIST.map { "$it {}" } val FAKE_NTYPE_LIST = listOf("\\n-Type") val IN_KW_LIST = listOf(IN_KW.toString()) val WITH_KW_LIST = listOf(WITH_KW.toString()) val WITH_KW_FULL = WITH_KW_LIST.map { "$it {}" } val LEVEL_KW_LIST = listOf(LEVEL_KW.toString()) val COERCE_KW_LIST = listOf(COERCE_KW.toString()) val USE_KW_LIST = listOf(USE_KW.toString()) val RETURN_KW_LIST = listOf(RETURN_KW.toString()) val COWITH_KW_LIST = listOf(COWITH_KW.toString()) val ELIM_KW_LIST = listOf(ELIM_KW.toString()) val CLASSIFYING_KW_LIST = listOf(CLASSIFYING_KW.toString()) val NO_CLASSIFYING_KW_LIST = listOf(NO_CLASSIFYING_KW.toString()) val TRUNCATED_DATA_KW_LIST = listOf(TRUNCATED_DATA_KW) val TRUNCATED_KW_LIST = listOf(TRUNCATED_KW.toString()) val ALIAS_KW_LIST = listOf(ALIAS_KW.toString()) val LEVELS_KW_LIST = listOf(LEVELS_KW.toString()) val STRICT_KW_LIST = listOf(STRICT_KW.toString()) val HLEVELS_KW_LIST = listOf(HLEVELS_KW.toString()) val LOCAL_STATEMENT_KWS = STATEMENT_WT_KWS + TRUNCATED_DATA_KW_LIST val GLOBAL_STATEMENT_KWS = STATEMENT_WT_KWS + TRUNCATED_DATA_KW_LIST + IMPORT_KW_LIST val HU_KW_LIST = USING_KW_LIST + HIDING_KW_LIST val DATA_OR_EXPRESSION_KW = DATA_UNIVERSE_KW + BASIC_EXPRESSION_KW + NEW_KW_LIST val LPH_LEVEL_KWS = LPH_KW_LIST + LEVEL_KWS
73
Kotlin
15
90
b11d0906f9a0d9680675a418cdc50b98e2d33c92
2,916
intellij-arend
Apache License 2.0
cbordata/src/main/java/com/ul/ims/gmdl/cbordata/request/DataElements.kt
prashantkspatil
377,765,486
true
{"Kotlin": 1392515, "Java": 421643}
/* * Copyright (C) 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ul.ims.gmdl.cbordata.request import co.nstant.`in`.cbor.CborBuilder import co.nstant.`in`.cbor.CborEncoder import co.nstant.`in`.cbor.model.DataItem import co.nstant.`in`.cbor.model.SimpleValue import co.nstant.`in`.cbor.model.UnicodeString import com.ul.ims.gmdl.cbordata.generic.AbstractCborStructure import java.io.ByteArrayOutputStream class DataElements private constructor( val dataElements: Map<String, Boolean> ) : AbstractCborStructure() { override fun encode(): ByteArray { val outputStream = ByteArrayOutputStream() var builder = CborBuilder() val structureMap = builder.addMap() dataElements.entries.forEach { structureMap.put(it.key, it.value) } builder = structureMap.end() // TODO: Use nonCanonical when cbor-java 0.9 is out. CborEncoder(outputStream).encode(builder.build()) return outputStream.toByteArray() } fun toCborMap(): co.nstant.`in`.cbor.model.Map { val map = co.nstant.`in`.cbor.model.Map() dataElements.entries.forEach { map.put(UnicodeString(it.key), convert(it.value)) } return map } class Builder { private var dataElements: Map<String, Boolean> = linkedMapOf() fun dataElements(namespaces: Map<String, Boolean>) = apply { this.dataElements = namespaces } fun decode(dataItem: DataItem) = apply { (dataItem as? co.nstant.`in`.cbor.model.Map)?.let { val map = linkedMapOf<String, Boolean>() dataItem.keys.forEach { key -> (key as? UnicodeString)?.let { string -> (dataItem[key] as? SimpleValue)?.let { simpleValue -> map.put(string.string, convert(simpleValue)) } } } this.dataElements = map } } private fun convert(value: SimpleValue): Boolean { return value == SimpleValue.TRUE } fun build(): DataElements { return DataElements(dataElements) } } private fun convert(value: Boolean): DataItem { return if (value) { SimpleValue.TRUE } else { SimpleValue.FALSE } } }
0
null
0
0
a6c3a6077ef5e7774ff70929ae4f33968ce6f598
2,948
mdl-ref-apps
Apache License 2.0
core/src/main/java/com/mobilepqi/core/data/source/remote/response/profil/PutProfilResponse.kt
acalapatih
708,105,917
false
{"Kotlin": 524790}
package com.mobilepqi.core.data.source.remote.response.profil import com.google.gson.annotations.SerializedName data class PutProfilResponse( @field:SerializedName("data") val data: Data? = null, @field:SerializedName("message") val message: String? = null, @field:SerializedName("status") val status: Int? = null ) { data class Data( @field:SerializedName("errors") val errors: String? = null, @field:SerializedName("role") val role: String? = null, @field:SerializedName("address") val address: String? = null, @field:SerializedName("birth") val birth: String? = null, @field:SerializedName("created_at") val createdAt: String? = null, @field:SerializedName("avatar") val avatar: String? = null, @field:SerializedName("faculty") val faculty: String? = null, @field:SerializedName("nim") val nim: String? = null, @field:SerializedName("major") val major: String? = null, @field:SerializedName("updated_at") val updatedAt: String? = null, @field:SerializedName("phone") val phone: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("email") val email: String? = null ) }
0
Kotlin
0
0
e4c7c4a93d1c2b1632a45c827b9df76652b0d0f7
1,246
MobilePQI_mobileApps
MIT License
compiler/testData/diagnostics/tests/Constants.fir.kt
JetBrains
3,432,266
false
null
// !CHECK_TYPE fun varargByte(vararg v: Byte) = v fun varargShort(vararg v: Short) = v fun varargInt(vararg v: Int) = v fun varargLong(vararg v: Long) = v fun varargFloat(vararg v: Float) = v fun varargDouble(vararg v: Double) = v fun <T> testFun(p: T) {} fun test() { checkSubtype<Byte>(1) checkSubtype<Short>(1) checkSubtype<Int>(1) checkSubtype<Long>(1) checkSubtype<Long>(0x001) checkSubtype<Int>(0b001) checkSubtype<Double>(0.1) checkSubtype<Float>(0.1.toFloat()) checkSubtype<Double>(1e5) checkSubtype<Float>(1e-5.toFloat()) checkSubtype<Double>(<!ARGUMENT_TYPE_MISMATCH!>1<!>) checkSubtype<Float>(<!ARGUMENT_TYPE_MISMATCH!>1<!>) 1 <!CAST_NEVER_SUCCEEDS!>as<!> Byte 1 <!USELESS_CAST!>as Int<!> 0xff <!CAST_NEVER_SUCCEEDS!>as<!> Long 1.1 <!CAST_NEVER_SUCCEEDS!>as<!> Int checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>1.1<!>) varargByte(0x77, 1, 3, <!ARGUMENT_TYPE_MISMATCH!>200<!>, 0b111) varargShort(0x777, 1, 2, 3, <!ARGUMENT_TYPE_MISMATCH!>200000<!>, 0b111) varargInt(0x77777777, <!ARGUMENT_TYPE_MISMATCH!>0x7777777777<!>, 1, 2, 3, 2000000000, 0b111) varargLong(0x777777777777, 1, 2, 3, 200000, 0b111) varargFloat(<!ARGUMENT_TYPE_MISMATCH!>1<!>, <!ARGUMENT_TYPE_MISMATCH!>1.0<!>, <!ARGUMENT_TYPE_MISMATCH!>-0.1<!>, <!ARGUMENT_TYPE_MISMATCH!>1e4<!>, <!ARGUMENT_TYPE_MISMATCH!>1e-4<!>, <!ARGUMENT_TYPE_MISMATCH!>-1e4<!>) varargDouble(<!ARGUMENT_TYPE_MISMATCH!>1<!>, 1.0, -0.1, 1e4, 1e-4, -1e4) testFun(1.0) testFun<Float>(<!ARGUMENT_TYPE_MISMATCH!>1.0<!>) testFun(1.0.toFloat()) testFun<Float>(1.0.toFloat()) }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,639
kotlin
Apache License 2.0
domain/src/main/kotlin/io/exflo/domain/ContractEvents.kt
freight-trust
244,709,841
true
{"Java": 472760, "Kotlin": 463936, "JavaScript": 49927, "Dockerfile": 5903, "Shell": 2278}
/* * Copyright (c) 2020 41North. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.exflo.domain import com.google.flatbuffers.FlatBufferBuilder import io.exflo.domain.extensions.toFlatBuffer import io.exflo.domain.fb.events.ApprovalForAll.createApprovalForAll import io.exflo.domain.fb.events.AuthorizedOperator.createAuthorizedOperator import io.exflo.domain.fb.events.Burned.createBurned import io.exflo.domain.fb.events.ContractEvent.ApprovalForAll import io.exflo.domain.fb.events.ContractEvent.AuthorizedOperator import io.exflo.domain.fb.events.ContractEvent.Burned import io.exflo.domain.fb.events.ContractEvent.FungibleApproval import io.exflo.domain.fb.events.ContractEvent.FungibleTransfer import io.exflo.domain.fb.events.ContractEvent.Minted import io.exflo.domain.fb.events.ContractEvent.NonFungibleApproval import io.exflo.domain.fb.events.ContractEvent.NonFungibleTransfer import io.exflo.domain.fb.events.ContractEvent.RevokedOperator import io.exflo.domain.fb.events.ContractEvent.Sent import io.exflo.domain.fb.events.ContractEvent.TransferBatch import io.exflo.domain.fb.events.ContractEvent.TransferSingle import io.exflo.domain.fb.events.ContractEvent.URI import io.exflo.domain.fb.events.FungibleApproval.createFungibleApproval import io.exflo.domain.fb.events.FungibleTransfer.createFungibleTransfer import io.exflo.domain.fb.events.Minted.createMinted import io.exflo.domain.fb.events.NonFungibleApproval.createNonFungibleApproval import io.exflo.domain.fb.events.NonFungibleTransfer.createNonFungibleTransfer import io.exflo.domain.fb.events.RevokedOperator.createRevokedOperator import io.exflo.domain.fb.events.Sent.createSent import io.exflo.domain.fb.events.TransferBatch.createTransferBatch import io.exflo.domain.fb.events.TransferSingle.createTransferSingle import io.exflo.domain.fb.events.URI.createURI import org.hyperledger.besu.ethereum.core.Address import org.hyperledger.besu.util.bytes.BytesValue import org.hyperledger.besu.util.uint.UInt256 interface ContractEvent { val contract: Address fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> } object ContractEvents { data class FungibleApproval( override val contract: Address, val owner: Address, val spender: Address, val value: UInt256 ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val ownerOffset = owner.toFlatBuffer(bb) val spenderOffset = spender.toFlatBuffer(bb) val valueOffset = value.toFlatBuffer(bb) return Pair( FungibleApproval, createFungibleApproval(bb, contractOffset, ownerOffset, spenderOffset, valueOffset) ) } } data class FungibleTransfer( override val contract: Address, val from: Address, val to: Address, val value: UInt256 ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val fromOffset = from.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val valueOffset = value.toFlatBuffer(bb) return Pair( FungibleTransfer, createFungibleTransfer(bb, contractOffset, fromOffset, toOffset, valueOffset) ) } } data class NonFungibleApproval( override val contract: Address, val owner: Address, val approved: Address, val tokenId: UInt256 ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val ownerOffset = owner.toFlatBuffer(bb) val approvedOffset = approved.toFlatBuffer(bb) val tokenIdOffset = tokenId.toFlatBuffer(bb) return Pair( NonFungibleApproval, createNonFungibleApproval( bb, contractOffset, ownerOffset, approvedOffset, tokenIdOffset ) ) } } data class ApprovalForAll( override val contract: Address, val owner: Address, val operator: Address, val approved: Boolean ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val ownerOffset = owner.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) return Pair( ApprovalForAll, createApprovalForAll(bb, contractOffset, ownerOffset, operatorOffset, approved) ) } } data class NonFungibleTransfer( override val contract: Address, val from: Address, val to: Address, val tokenId: UInt256 ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val fromOffset = from.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val tokenIdOffset = tokenId.toFlatBuffer(bb) return Pair( NonFungibleTransfer, createNonFungibleTransfer(bb, contractOffset, fromOffset, toOffset, tokenIdOffset) ) } } data class Sent( override val contract: Address, val operator: Address, val from: Address, val to: Address, val amount: UInt256, val data: BytesValue, val operatorData: BytesValue ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val fromOffset = from.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val amountOffset = amount.toFlatBuffer(bb) val dataOffset = bb.createByteVector(data.extractArray()) val operatorDataOffset = bb.createByteVector(operatorData.extractArray()) return Pair( Sent, createSent( bb, contractOffset, operatorOffset, fromOffset, toOffset, amountOffset, dataOffset, operatorDataOffset ) ) } } data class Minted( override val contract: Address, val operator: Address, val to: Address, val amount: UInt256, val data: BytesValue, val operatorData: BytesValue ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val amountOffset = amount.toFlatBuffer(bb) val dataOffset = bb.createByteVector(data.extractArray()) val operatorDataOffset = bb.createByteVector(operatorData.extractArray()) return Pair( Minted, createMinted( bb, contractOffset, operatorOffset, toOffset, amountOffset, dataOffset, operatorDataOffset ) ) } } data class Burned( override val contract: Address, val operator: Address, val to: Address, val amount: UInt256, val data: BytesValue, val operatorData: BytesValue ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val amountOffset = amount.toFlatBuffer(bb) val dataOffset = bb.createByteVector(data.extractArray()) val operatorDataOffset = bb.createByteVector(operatorData.extractArray()) return Pair( Burned, createBurned( bb, contractOffset, operatorOffset, toOffset, amountOffset, dataOffset, operatorDataOffset ) ) } } data class AuthorizedOperator( override val contract: Address, val operator: Address, val holder: Address ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val holderOffset = holder.toFlatBuffer(bb) return Pair( AuthorizedOperator, createAuthorizedOperator(bb, contractOffset, operatorOffset, holderOffset) ) } } data class RevokedOperator( override val contract: Address, val operator: Address, val holder: Address ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val holderOffset = holder.toFlatBuffer(bb) return Pair( RevokedOperator, createRevokedOperator(bb, contractOffset, operatorOffset, holderOffset) ) } } data class TransferSingle( override val contract: Address, val operator: Address, val from: Address, val to: Address, val id: UInt256, val value: UInt256 ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val fromOffset = from.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val idOffset = id.toFlatBuffer(bb) val valueOffset = value.toFlatBuffer(bb) return Pair( TransferSingle, createTransferSingle( bb, contractOffset, operatorOffset, fromOffset, toOffset, idOffset, valueOffset ) ) } } data class TransferBatch( override val contract: Address, val operator: Address, val from: Address, val to: Address, val ids: List<UInt256>, val values: List<UInt256> ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val operatorOffset = operator.toFlatBuffer(bb) val fromOffset = from.toFlatBuffer(bb) val toOffset = to.toFlatBuffer(bb) val idsOffset = ids .map { it.toFlatBuffer(bb) } .let { bb.createVectorOfTables(it.toIntArray()) } val valuesOffset = values .map { it.toFlatBuffer(bb) } .let { bb.createVectorOfTables(it.toIntArray()) } return Pair( TransferBatch, createTransferBatch( bb, contractOffset, operatorOffset, fromOffset, toOffset, idsOffset, valuesOffset ) ) } } data class URI( override val contract: Address, val id: UInt256, val value: String ) : ContractEvent { override fun toFlatBuffer(bb: FlatBufferBuilder): Pair<Byte, Int> { val contractOffset = contract.toFlatBuffer(bb) val idOffset = id.toFlatBuffer(bb) val valueOffset = bb.createString(value) return Pair( URI, createURI(bb, contractOffset, valueOffset, idOffset) ) } } }
1
null
1
1
ec2c7cabd905343cd0d0252482624d537d39c962
13,190
exflo
Apache License 2.0
app/src/main/java/com/musical/instrument/simulator/app/database/AppDatabase.kt
daovu97
813,488,266
false
{"Kotlin": 224082, "Java": 149657}
package com.musical.instrument.simulator.app.database import androidx.room.AutoMigration import androidx.room.Database import androidx.room.RoomDatabase import com.musical.instrument.simulator.app.model.AudioFile @Database( entities = [AudioFile::class], version = 2, autoMigrations = [AutoMigration(from = 1, to = 2)] ) abstract class AppDatabase : RoomDatabase() { abstract fun audioDao(): AudioDao }
0
Kotlin
0
0
714fbd3f48c359e4dfa16a6455a44d6617028d93
421
MusicInstrument
MIT License
src/main/kotlin/ok/work/etoroapi/controller/PositionsController.kt
ok24601
240,984,198
false
null
package ok.work.etoroapi.controller import ok.work.etoroapi.client.EtoroHttpClient import ok.work.etoroapi.client.EtoroPosition import ok.work.etoroapi.client.EtoroPositionForUpdate import ok.work.etoroapi.model.Position import ok.work.etoroapi.model.ofString import ok.work.etoroapi.transactions.Transaction import org.json.JSONObject import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/positions") class PositionsController { @Autowired lateinit var httpClient: EtoroHttpClient @GetMapping fun getPositions(@RequestHeader(defaultValue = "Demo") mode: String): List<EtoroPosition> { return httpClient.getPositions(ofString(mode)) } @GetMapping(value = ["/history"]) fun getHistoryPositions(@RequestParam(defaultValue = "100") limit: String, @RequestParam(defaultValue = "1") page: String, @RequestParam(defaultValue = "") StartTime: String, @RequestHeader(defaultValue = "Demo") mode: String): List<EtoroPosition> { return httpClient.getHistoryPositions(limit, page, StartTime, ofString(mode)) } @PostMapping(value = ["/open"]) fun openPosition(@RequestBody position: Position, @RequestHeader(defaultValue = "Demo") mode: String): Transaction { return httpClient.openPosition(position, ofString(mode)) } @PutMapping(value = ["/update"]) fun updatePosition(@RequestBody etoroPosition: EtoroPositionForUpdate, @RequestHeader(defaultValue = "Demo") mode: String): Transaction { return httpClient.updatePosition(etoroPosition, ofString(mode)) } @DeleteMapping(value = ["/close"]) fun closePosition(id: String, @RequestHeader(defaultValue = "Demo") mode: String) { httpClient.deletePosition(id, ofString(mode)) } }
31
null
46
94
b5044cb62dcd5f32b5677c316a37a46355891ef6
1,824
etoro-api
ISC License
app/src/test/java/com/github/forrest321/util/DefaultConfig.kt
forrest321
185,419,848
false
null
package com.github.forrest321.util object DefaultConfig { //The api level that Roboelectric will use to run the unit tests val EMULATE_SDK = 24 }
0
Kotlin
0
1
04cd52d6a8ec778f29a7e0c6fada71e20e662433
154
QLT
The Unlicense
komapper-core/src/main/kotlin/org/komapper/core/Dialect.kt
komapper
349,909,214
false
null
package org.komapper.core import org.komapper.core.dsl.builder.DryRunSchemaStatementBuilder import org.komapper.core.dsl.builder.EntityUpsertStatementBuilder import org.komapper.core.dsl.builder.OffsetLimitStatementBuilder import org.komapper.core.dsl.builder.OffsetLimitStatementBuilderImpl import org.komapper.core.dsl.builder.SchemaStatementBuilder import org.komapper.core.dsl.context.EntityUpsertContext import org.komapper.core.dsl.metamodel.EntityMetamodel import java.util.regex.Pattern import kotlin.reflect.KClass @ThreadSafe interface Dialect { val driver: String val openQuote: String get() = "\"" val closeQuote: String get() = "\"" val escapeSequence: String get() = "\\" fun replacePlaceHolder(index: Int, placeHolder: StatementPart.PlaceHolder): CharSequence { return placeHolder } fun formatValue(value: Any?, valueClass: KClass<*>): String fun enquote(name: String): String { return openQuote + name + closeQuote } fun escape(text: String, escapeSequence: String? = null): String { val literal = escapeSequence ?: this.escapeSequence val escapePattern = createEscapePattern(literal) val matcher = escapePattern.matcher(text) return matcher.replaceAll("${Regex.escapeReplacement(literal)}$0") } @Suppress("RegExpDuplicateCharacterInClass") fun createEscapePattern(escapeSequence: String): Pattern { val targetChars = "[${Regex.escape("$escapeSequence%_")}]" return Pattern.compile(targetChars) } fun getDataTypeName(klass: KClass<*>): String fun getOffsetLimitStatementBuilder(offset: Int, limit: Int): OffsetLimitStatementBuilder { return OffsetLimitStatementBuilderImpl(this, offset, limit) } fun getSequenceSql(sequenceName: String): String fun getSchemaStatementBuilder(): SchemaStatementBuilder fun <ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>> getEntityUpsertStatementBuilder( context: EntityUpsertContext<ENTITY, ID, META>, entities: List<ENTITY> ): EntityUpsertStatementBuilder<ENTITY> fun supportsAliasForDeleteStatement() = true fun supportsNullOrdering(): Boolean = true } internal object DryRunDialect : Dialect { override val driver: String = "dry_run" override fun formatValue(value: Any?, valueClass: KClass<*>): String { return if (value == null) { "null" } else { when (valueClass) { String::class -> "'$value'" else -> value.toString() } } } override fun getDataTypeName(klass: KClass<*>): String { throw UnsupportedOperationException() } override fun getSequenceSql(sequenceName: String): String { throw UnsupportedOperationException() } override fun getSchemaStatementBuilder(): SchemaStatementBuilder { return DryRunSchemaStatementBuilder } override fun <ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>> getEntityUpsertStatementBuilder( context: EntityUpsertContext<ENTITY, ID, META>, entities: List<ENTITY> ): EntityUpsertStatementBuilder<ENTITY> { throw UnsupportedOperationException() } }
6
Kotlin
0
16
7092a2bd24b609a1816bf05c89730259ff45178d
3,257
komapper
Apache License 2.0
app/src/main/kotlin/com/mr3y/podcaster/service/ServiceMediaPlayer.kt
mr3y-the-programmer
720,570,256
false
{"Kotlin": 944363, "HTML": 196}
package com.mr3y.podcaster.service import androidx.annotation.OptIn import androidx.annotation.VisibleForTesting import androidx.media3.common.C import androidx.media3.common.ForwardingPlayer import androidx.media3.common.MediaItem import androidx.media3.common.PlaybackException import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import com.mr3y.podcaster.core.data.PodcastsRepository import com.mr3y.podcaster.core.model.CurrentlyPlayingEpisode import com.mr3y.podcaster.core.model.PlayingStatus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlin.math.abs import kotlin.time.Duration.Companion.seconds /** * Encapsulate media session's player operations to make it testable & isolated from Service class. */ @OptIn(UnstableApi::class) class ServiceMediaPlayer( private val player: Player, private val podcastsRepository: PodcastsRepository, ) : ForwardingPlayer(player) { @VisibleForTesting internal val currentlyPlayingEpisode = MutableStateFlow<CurrentlyPlayingEpisode?>(null) fun startListeningForUpdatesIn(scope: CoroutineScope) { scope.launch { podcastsRepository.getCurrentlyPlayingEpisode().collectLatest { currentEpisode -> currentlyPlayingEpisode.update { currentEpisode } currentlyPlayingEpisode.value?.let { (episode, _, speed) -> val duration = player.duration // episode's durationInSec is sometimes reported as an approximate value, // so we update it to match the exact value of the content duration. if (duration != C.TIME_UNSET && episode.durationInSec?.toLong() != (duration / 1000)) { podcastsRepository.updateEpisodeDuration((duration / 1000).toInt(), episode.id) podcastsRepository.updateCurrentlyPlayingEpisodeSpeed(speed) } } while (true) { val episodeId = player.currentMediaItem?.mediaId?.toLongOrNull() ?: break val progressInSec = player.currentPosition.div(1000) if (progressInSec != 0L && player.isPlaying) { currentlyPlayingEpisode.value?.let { (episode, _, _) -> if (episode.durationInSec == null) return@let if (!episode.isCompleted && abs(episode.durationInSec!!.toLong() - progressInSec) <= 1) { podcastsRepository.markEpisodeAsCompleted(episode.id) } } podcastsRepository.updateEpisodePlaybackProgress(progressInSec.toInt(), episodeId) } delay(1.seconds) } } } } fun attachPlayerListener() { player.apply { addListener( object : Player.Listener { // Sync state between session & our app UI override fun onPlayWhenReadyChanged( playWhenReady: Boolean, reason: Int, ) { val playingStatus = when { playWhenReady -> PlayingStatus.Playing playbackState == Player.STATE_BUFFERING -> PlayingStatus.Loading else -> PlayingStatus.Paused } currentlyPlayingEpisode.value?.let { (episode, _, _) -> val isAboutToPlay = playingStatus == PlayingStatus.Loading || playingStatus == PlayingStatus.Playing episode.durationInSec?.let { if (episode.progressInSec == null) return@let val hasReachedEndOfEpisode = abs((it * 1000).toLong() - currentPosition) <= 1000L && abs(episode.progressInSec!! - it) <= 1 if (isAboutToPlay && hasReachedEndOfEpisode) { seekTo(0L) podcastsRepository.updateEpisodePlaybackProgress(progressInSec = 0, episodeId = episode.id) } } } podcastsRepository.updateCurrentlyPlayingEpisodeStatus(playingStatus) } override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT) { currentlyPlayingEpisode.value?.let { (episode, _, _) -> if (!episode.isCompleted) { podcastsRepository.markEpisodeAsCompleted(episode.id) } } } if (mediaItem != null) { val nextEpisode = podcastsRepository.getEpisodeFromQueue(mediaItem.mediaId.toLong()) currentlyPlayingEpisode.value?.let { (currentEpisode, playingStatus, playingSpeed) -> if (currentEpisode.id != nextEpisode.id) { val hasReachedEndOfEpisode = nextEpisode.durationInSec?.let { dur -> nextEpisode.progressInSec?.let { progress -> (dur - progress) <= 1 } ?: false } ?: false val position = if (hasReachedEndOfEpisode) { podcastsRepository.updateEpisodePlaybackProgress(progressInSec = 0, episodeId = nextEpisode.id) 0L } else { nextEpisode.progressInSec?.times(1000)?.toLong() ?: 0L } podcastsRepository.setCurrentlyPlayingEpisode(CurrentlyPlayingEpisode(nextEpisode, playingStatus, playingSpeed)) seekTo(position) } } } } override fun onPlayerError(error: PlaybackException) { // TODO: log the error for better investigation podcastsRepository.updateCurrentlyPlayingEpisodeStatus(PlayingStatus.Error) } }, ) } } }
9
Kotlin
3
68
5113b7c03c5d8df6e3a0a74260912460cace5fbf
6,883
Podcaster
Apache License 2.0
app/src/main/java/ru/spb/dair/roadmovie/MainActivity.kt
dair
146,125,648
false
null
package ru.spb.dair.roadmovie import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.content.Context.ACTIVITY_SERVICE import android.app.ActivityManager import android.content.Context import android.content.Intent import android.widget.TextView import android.widget.Toast import android.content.ComponentName import ru.spb.dair.roadmovie.MyService.LocalBinder import android.os.IBinder import android.content.ServiceConnection import android.content.pm.PackageManager import android.content.pm.PackageManager.PERMISSION_GRANTED import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.view.View.INVISIBLE import android.view.View.VISIBLE import java.util.* import kotlin.concurrent.scheduleAtFixedRate class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback { lateinit var _mainButton: Button lateinit var _unloadLabel: TextView lateinit var _speedLabel: TextView lateinit var _timePassed: TextView private var mBoundService: MyService? = null private var mShouldUnbind: Boolean = false private lateinit var timer: Timer private val mConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = (service as MyService.LocalBinder).service } override fun onServiceDisconnected(className: ComponentName) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null } } fun doBindService() { // Attempts to establish a connection with the service. We use an // explicit class name because we want a specific service // implementation that we know will be running in our own process // (and thus won't be supporting component replacement by other // applications). if (bindService(Intent(this@MainActivity, MyService::class.java), mConnection, Context.BIND_AUTO_CREATE)) { mShouldUnbind = true } } fun doUnbindService() { if (mShouldUnbind) { // Release information about the service's state. unbindService(mConnection) mShouldUnbind = false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) _mainButton = this.findViewById<Button>(R.id.main_button) _mainButton.setOnClickListener { onButtonClick() } _unloadLabel = this.findViewById(R.id.unloadLabel) _unloadLabel.visibility = INVISIBLE _speedLabel = this.findViewById(R.id.lastSpeed) _speedLabel.text = "" _timePassed = this.findViewById(R.id.timePassed) _timePassed.text = "" } private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name == service.service.className) { return true } } return false } override fun onResume() { super.onResume() if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 42); } if (isMyServiceRunning(MyService::class.java)) { doBindService() } updateButtonText() timer = Timer("updateTimer") timer.scheduleAtFixedRate(1000, 1000, { runOnUiThread { updateButtonText() } }) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (grantResults.isNotEmpty()) { if (grantResults[0] == PERMISSION_GRANTED) { // whatever } } } override fun onPause() { timer.cancel() if (isMyServiceRunning(MyService::class.java)) { doUnbindService() } super.onPause() } private fun updateButtonText() { if (isMyServiceRunning(MyService::class.java)) { _mainButton.text = "Остановить поездку" if (mBoundService != null) { val unload = mBoundService!!.userNotified if (unload) { _unloadLabel.visibility = VISIBLE } else { _unloadLabel.visibility = INVISIBLE } _speedLabel.text = (mBoundService!!.lastSpeedFound * 3.6).toString() var secPassed = mBoundService!!._totalTimePassed / 1000 val minPassed = secPassed / 60 secPassed = secPassed % 60 _timePassed.text = String.format("%02d:%02d", minPassed, secPassed) } } else { _mainButton.text = "Начать поездку" _unloadLabel.visibility = INVISIBLE _speedLabel.text = "" _timePassed.text = "" } } private fun onButtonClick() { val intent = Intent(this, MyService::class.java) if (!isMyServiceRunning(MyService::class.java)) { startService(intent) doBindService() } else { mBoundService?.userNotified = false doUnbindService() stopService(intent) } updateButtonText() } }
0
Kotlin
0
0
cdbf9e99987e44a2041c8c9ba27309a20bc225ed
6,392
roadmovie-android
Apache License 2.0
projects/vocabulary/worder/src/main/kotlin/com/example/worder/starter/Application.kt
roskenet
295,683,964
false
{"HTML": 708028, "Jupyter Notebook": 571597, "TeX": 547996, "Java": 447619, "Makefile": 214272, "JavaScript": 204557, "CMake": 113090, "Kotlin": 88563, "TypeScript": 61333, "Clojure": 36776, "CSS": 25303, "C++": 19374, "Red": 13104, "Python": 12901, "Shell": 12248, "SCSS": 5588, "Go": 4797, "Dockerfile": 2073, "C": 1687, "Vim Script": 1092, "PLpgSQL": 818, "Assembly": 384, "Rust": 308, "Gherkin": 207, "Procfile": 177, "C#": 147, "PHP": 94, "Less": 91, "Ruby": 73, "sed": 26, "Batchfile": 21, "Groovy": 21}
package com.example.worder.starter import org.springframework.boot.CommandLineRunner class Application : CommandLineRunner { override fun run(vararg args: String?) { println("Hello World!") } }
0
HTML
1
0
39975a0248f2e390f799bdafde1170322267761b
211
playground
MIT License
src/main/java/cn/origin/cube/event/EventManager.kt
jiyun233
535,282,475
false
{"Kotlin": 97032, "Java": 81332}
package cn.origin.cube.event import cn.origin.cube.Cube import cn.origin.cube.event.events.world.Render3DEvent import cn.origin.cube.utils.Utils import net.minecraft.client.Minecraft import net.minecraft.client.renderer.GlStateManager import net.minecraftforge.client.event.ClientChatEvent import net.minecraftforge.client.event.RenderGameOverlayEvent import net.minecraftforge.client.event.RenderWorldLastEvent import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.InputEvent import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent import org.lwjgl.input.Keyboard class EventManager { val mc: Minecraft = Minecraft.getMinecraft() init { MinecraftForge.EVENT_BUS.register(this) } @SubscribeEvent fun onKeyInput(event: InputEvent.KeyInputEvent) { if (event.isCanceled || !Keyboard.getEventKeyState() || Keyboard.getEventKey() <= 0) return for (module in Cube.moduleManager!!.allModuleList) { if (module.keyBind.value.keyCode <= 0) continue if (Keyboard.isKeyDown(module.keyBind.value.keyCode)) module.toggle() } } @SubscribeEvent fun onTick(event: ClientTickEvent) { if (Utils.nullCheck()) return Cube.moduleManager!!.onUpdate() } @SubscribeEvent fun onLogin(event: ClientConnectedToServerEvent) { if (Utils.nullCheck()) return Cube.moduleManager!!.onLogin() } @SubscribeEvent fun onLogout(event: ClientDisconnectionFromServerEvent) { if (Utils.nullCheck()) return Cube.moduleManager!!.onLogout() } @SubscribeEvent fun onRender2D(e: RenderGameOverlayEvent.Text) { if (e.type == RenderGameOverlayEvent.ElementType.TEXT) { Cube.moduleManager!!.onRender2D() } } @SubscribeEvent fun onWorldRender(event: RenderWorldLastEvent) { if (event.isCanceled) return mc.profiler.startSection("CubeBase") GlStateManager.disableTexture2D() GlStateManager.enableBlend() GlStateManager.disableAlpha() GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0) GlStateManager.shadeModel(7425) GlStateManager.disableDepth() GlStateManager.glLineWidth(1.0f) val render3dEvent = Render3DEvent(event.partialTicks) Cube.moduleManager!!.onRender3D(render3dEvent) GlStateManager.glLineWidth(1.0f) GlStateManager.shadeModel(7424) GlStateManager.disableBlend() GlStateManager.enableAlpha() GlStateManager.enableTexture2D() GlStateManager.enableDepth() GlStateManager.enableCull() GlStateManager.enableCull() GlStateManager.depthMask(true) GlStateManager.enableTexture2D() GlStateManager.enableBlend() GlStateManager.enableDepth() mc.profiler.endSection() } @SubscribeEvent fun onChat(event: ClientChatEvent) { if (event.message.startsWith(Cube.commandPrefix)) { Cube.commandManager.run(event.message) event.isCanceled = true; Minecraft.getMinecraft().ingameGUI.chatGUI.addToSentMessages(event.message); } } }
4
Kotlin
1
16
d0ba15713b92f517a4c9894c08d31cca6f71db5b
3,465
CubeBase
MIT License
trixnity-client/src/commonMain/kotlin/net/folivo/trixnity/client/MatrixClientConfiguration.kt
benkuly
330,904,570
false
null
package net.folivo.trixnity.client import io.ktor.client.* import kotlinx.coroutines.CoroutineName import net.folivo.trixnity.api.client.defaultTrixnityHttpClientFactory import net.folivo.trixnity.client.store.Room import net.folivo.trixnity.client.store.TimelineEvent import net.folivo.trixnity.core.model.events.ClientEvent.RoomEvent import net.folivo.trixnity.core.model.events.m.room.Membership import org.koin.core.module.Module import kotlin.coroutines.CoroutineContext import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds data class MatrixClientConfiguration( /** * Set a name for this instance. This is used to set a [CoroutineName] to the [CoroutineContext]. */ var name: String? = null, /** * Allow to save [TimelineEvent]s unencrypted. */ var storeTimelineEventContentUnencrypted: Boolean = true, /** * Sets the own bookmark to the latest messages sent by this client. */ var setOwnMessagesAsFullyRead: Boolean = false, /** * Automatically join upgraded rooms. */ var autoJoinUpgradedRooms: Boolean = true, /** * Delete a room, when it's membership is [Membership.LEAVE]. */ var deleteRoomsOnLeave: Boolean = true, /** * Set the delay, after which a sent outbox message is deleted. The delay is checked each time a sync is received. */ var deleteSentOutboxMessageDelay: Duration = 10.seconds, /** * Specifies how long values are kept in the cache when not used by anyone. */ var cacheExpireDurations: CacheExpireDurations = CacheExpireDurations.default(1.minutes), /** * The timeout for the normal sync loop. */ var syncLoopTimeout: Duration = 30.seconds, /** * Set custom delays for the sync loop. */ var syncLoopDelays: SyncLoopDelays = SyncLoopDelays.default(), /** * Allows you to customize, which [Room.lastRelevantEventId] is set. */ var lastRelevantEventFilter: (RoomEvent<*>) -> Boolean = { it is RoomEvent.MessageEvent<*> }, /** * Set custom [HttpClient]. */ var httpClientFactory: (config: HttpClientConfig<*>.() -> Unit) -> HttpClient = defaultTrixnityHttpClientFactory(), /** * Inject and override modules into Trixnity. You should always apply [createDefaultTrixnityModules] first. * * For example: * ```kotlin * modules = createDefaultTrixnityModules() + customModule * ``` */ var modules: List<Module> = createDefaultTrixnityModules(), ) { data class SyncLoopDelays( val syncLoopDelay: Duration, val syncLoopErrorDelay: Duration ) { companion object { fun default() = SyncLoopDelays( syncLoopDelay = 2.seconds, syncLoopErrorDelay = 5.seconds ) } } data class CacheExpireDurations( val globalAccountDate: Duration, val deviceKeys: Duration, val crossSigningKeys: Duration, val keyVerificationState: Duration, val mediaCacheMapping: Duration, val olmSession: Duration, val inboundMegolmSession: Duration, val inboundMegolmMessageIndex: Duration, val outboundMegolmSession: Duration, val roomAccountData: Duration, val roomState: Duration, val timelineEvent: Duration, val timelineEventRelation: Duration, val roomUser: Duration, val roomUserReceipts: Duration, val secretKeyRequest: Duration, val roomKeyRequest: Duration, val roomOutboxMessage: Duration, val room: Duration, ) { companion object { fun default(duration: Duration) = CacheExpireDurations( globalAccountDate = duration, deviceKeys = duration, crossSigningKeys = duration, keyVerificationState = duration, mediaCacheMapping = duration, olmSession = duration, inboundMegolmSession = duration, inboundMegolmMessageIndex = duration, outboundMegolmSession = duration, roomAccountData = duration, roomState = duration, timelineEvent = duration, timelineEventRelation = duration, roomUser = duration, roomUserReceipts = duration, secretKeyRequest = duration, roomKeyRequest = duration, roomOutboxMessage = duration / 2, room = duration * 10, ) } } }
0
null
3
30
96c656e1c20d60518b61884efe88ceaa9e899d75
4,757
trixnity
Apache License 2.0
sample-todo/src/main/java/com/airbnb/mvrx/todomvrx/views/HorizontalLoader.kt
airbnb
139,500,036
false
null
package com.airbnb.mvrx.todomvrx.views import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ProgressBar import com.airbnb.epoxy.ModelProp import com.airbnb.epoxy.ModelView import com.airbnb.mvrx.todomvrx.todoapp.R @ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT) class HorizontalLoader @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val progressBar by lazy { findViewById<ProgressBar>(R.id.progress_bar) } init { View.inflate(context, R.layout.horizontal_loader, this) } /** * When not loading, the progress bar is invisible so it still takes up the same space * at the top of the screen instead of the views snapping. */ @ModelProp fun setLoading(loading: Boolean) { progressBar.visibility = if (loading) View.VISIBLE else View.INVISIBLE } }
61
null
498
5,816
e920c4b0fe73183a3bb51e648066ebd5f7be3e8c
1,030
mavericks
Apache License 2.0
android/src/ti/airship/events/PushReceivedEvent.kt
urbanairship
56,192,548
false
{"Swift": 56947, "Kotlin": 52710, "JavaScript": 6487, "Shell": 3263, "Objective-C": 1883, "Ruby": 678, "Makefile": 627}
/* Copyright Airship and Contributors */ package ti.airship.events import com.urbanairship.push.NotificationInfo import com.urbanairship.push.PushMessage import ti.airship.TiAirshipModule class PushReceivedEvent : Event { override val data: Map<String, Any> override val name: String = TiAirshipModule.eventPushReceived constructor(pushMessage: PushMessage) { data = pushMessage.eventPayload() } constructor(notificationInfo: NotificationInfo) { data = notificationInfo.eventPayload() } }
1
Swift
9
9
40cc52a9629d75f467012097839b6c67841bd33d
533
titanium-module
Apache License 2.0
app/src/main/java/codeguru/gocapture/ImageFragment.kt
codeguru42
555,696,471
false
null
package codeguru.gocapture import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import codeguru.gocapture.databinding.FragmentImageBinding import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class ImageFragment : Fragment() { private val args: ImageFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment val binding = FragmentImageBinding.inflate(inflater, container, false) val repository = GoCaptureRepository(requireActivity()) val imageUri = Uri.parse(args.imageUri) binding.imageView.setImageURI(imageUri) val processingView = binding.processing.processingView processingView.visibility = View.GONE binding.uploadButton.setOnClickListener { CoroutineScope(Dispatchers.IO).launch { withContext(Dispatchers.Main) { processingView.visibility = View.VISIBLE } repository.processImage(imageUri, processingView) withContext(Dispatchers.Main) { processingView.visibility = View.GONE } } } return binding.root } }
8
Kotlin
0
1
b9706d859436f937e2d13146a2651c51a7021ea7
1,571
go-capture-android
MIT License
app/src/main/java/app/grapheneos/camera/ui/seekbar/ZoomBar.kt
GrapheneOS
397,136,540
false
null
package com.google.android.GoogleCamera.ui.seekbar import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.os.Handler import android.os.Looper import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.widget.AppCompatSeekBar import androidx.camera.core.ZoomState import androidx.transition.Fade import androidx.transition.Transition import androidx.transition.TransitionManager import com.google.android.GoogleCamera.CamConfig import com.google.android.GoogleCamera.R import com.google.android.GoogleCamera.ui.activities.MainActivity import kotlin.math.roundToInt class ZoomBar : AppCompatSeekBar { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) companion object { private const val PANEL_VISIBILITY_DURATION = 2000L } private val closePanelHandler: Handler = Handler(Looper.getMainLooper()) private val closePanelRunnable = Runnable { hidePanel() } @SuppressLint("InflateParams") private var thumbView: View = LayoutInflater.from(context) .inflate(R.layout.zoom_bar_thumb, null, false) private lateinit var mainActivity: MainActivity private lateinit var camConfig: CamConfig fun setMainActivity(mainActivity: MainActivity) { this.mainActivity = mainActivity camConfig = mainActivity.camConfig } fun showPanel() { togglePanel(View.VISIBLE) closePanelHandler.removeCallbacks(closePanelRunnable) closePanelHandler.postDelayed(closePanelRunnable, PANEL_VISIBILITY_DURATION) } private fun hidePanel() { togglePanel(View.GONE) } private fun togglePanel(visibility: Int) { val transition: Transition = Fade() if (visibility == View.GONE) { transition.duration = 300 } else { transition.duration = 0 } transition.addTarget(R.id.zoom_bar_panel) TransitionManager.beginDelayedTransition( mainActivity.window.decorView.rootView as ViewGroup, transition ) mainActivity.zoomBarPanel.visibility = visibility } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(h, w, oldh, oldw) } fun updateThumb(shouldShowPanel: Boolean = true) { val zoomState: ZoomState? = camConfig.camera?.cameraInfo?.zoomState ?.value if (shouldShowPanel) { showPanel() } else { hidePanel() } var zoomRatio = 1.0f var linearZoom = 0.0f if (zoomState != null) { zoomRatio = zoomState.zoomRatio linearZoom = zoomState.linearZoom } progress = (linearZoom * 100).roundToInt() val textView: TextView = thumbView.findViewById(R.id.progress) as TextView val text = String.format("%.1fx", zoomRatio) textView.text = text thumbView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) val bitmap = Bitmap.createBitmap( thumbView.measuredWidth, thumbView.measuredHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) thumbView.layout(0, 0, thumbView.measuredWidth, thumbView.measuredHeight) thumbView.draw(canvas) thumb = BitmapDrawable(resources, bitmap) onSizeChanged(width, height, 0, 0) } @Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(heightMeasureSpec, widthMeasureSpec) setMeasuredDimension(measuredHeight, measuredWidth) } override fun onDraw(c: Canvas) { c.rotate(-90f) c.translate(-height.toFloat(), 0f) super.onDraw(c) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (!isEnabled) { return false } when (event.action) { MotionEvent.ACTION_MOVE, MotionEvent.ACTION_DOWN -> { var progress = max - (max * event.y / height).toInt() if (progress < 1) progress = 1 if (progress > 100) progress = 100 camConfig.camera?.cameraControl?.setLinearZoom(progress / 100f) } MotionEvent.ACTION_CANCEL -> { } } return true } }
7
null
86
849
3c8bfd2f0cd1a5044890c85908dfb073879deaef
4,832
Camera
MIT License
src/main/java/net/eduard/api/server/MineSystem.kt
EduardMaster
103,982,025
false
null
package net.eduard.api.server import org.bukkit.Location import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack import org.bukkit.material.MaterialData interface MineSystem : PluginSystem{ fun hasMine(name : String) : Boolean fun getMine(name: String) : MineModule? fun getMine(location: Location) : MineModule? interface MineModule{ fun destroy(player : Player) : Map<MaterialData, Double> fun clear(y : Int,player : Player) : Map<MaterialData, Double> fun clear(x : Int,z : Int,player : Player) : Map<MaterialData, Double> fun regen() fun setType(type : MaterialData) fun setTypes(vararg type : MaterialData) fun autoRegen() } }
0
null
5
7
bb778365ce76fabbdbc516b918b4feedee7edf12
724
MineToolkit
MIT License
src/main/kotlin/io/github/jsonmockr/configuration/model/GeneratorConfig.kt
json-mockr
608,903,747
false
null
package io.github.jsonmockr.configuration.model data class GeneratorConfig(val name: String, val quantity: Int)
3
Kotlin
0
6
1f82378676182e78ca9aa5d52084205091a1f13c
113
json-mockr
MIT License
app/src/main/java/com/example/anidea/howmuchgrams.kt
Wodjess
673,471,308
false
null
package com.example.anidea import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.net.toUri import com.example.anidea.databinding.ActivityHowmuchgramsBinding class howmuchgrams : AppCompatActivity() { lateinit var BindingClass: ActivityHowmuchgramsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) BindingClass = ActivityHowmuchgramsBinding.inflate(layoutInflater) setContentView(BindingClass.root) BindingClass.textView4.text = intent.getStringExtra("Name") BindingClass.textView16.text = "Б: " + intent.getStringExtra("potein") BindingClass.textView17.text = "Ж: " + intent.getStringExtra("fat") BindingClass.textView18.text = "У: " + intent.getStringExtra("carb") BindingClass.textView22.text = "Всего каллорий: " + intent.getStringExtra("calories") try { BindingClass.imageView61.setImageResource(R.drawable.foodimg) } catch (e:Exception) { Log.d("LeshkaKartoshka", e.toString()) } BindingClass.button4.setOnClickListener(){ val i = Intent() if(BindingClass?.howmuchgramsstring?.text.toString().isNotEmpty()){ try { var Abs: Double = 0.toDouble() Abs = BindingClass?.howmuchgramsstring?.text.toString().toDouble() i.putExtra("export", BindingClass?.howmuchgramsstring?.text.toString()) setResult(100,i) finish() } catch (e:java.lang.Exception){ val builder22 = AlertDialog.Builder(this) builder22.setTitle("Произошла ошибка") builder22.setMessage("Проверьте данные") builder22.setNeutralButton("Oк") { dialogInterface, i -> } builder22.show() } } } } }
0
Kotlin
0
0
413218abdce872298ba11ceada528d8c1c70f784
2,134
AnIdea
MIT License
leetcode2/src/leetcode/odd-even-linked-list.kt
hewking
68,515,222
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 104, "Java": 88, "JSON": 1, "XML": 5}
package leetcode import leetcode.structure.ListNode /** * 328. 奇偶链表 * https://leetcode-cn.com/problems/odd-even-linked-list/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-18 21:09 * 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 示例 1: 输入: 1->2->3->4->5->NULL 输出: 1->3->5->2->4->NULL 示例 2: 输入: 2->1->3->5->6->4->7->NULL 输出: 2->3->6->7->1->5->4->NULL 说明: 应当保持奇数节点和偶数节点的相对顺序。 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/odd-even-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object OddEvenLinkedList { class Solution { /** * 思路: * 解决链表问题最好的办法是在脑中或者纸上把链表画出来。 * 画个图 就一目了然了 */ fun oddEvenList(head: ListNode?): ListNode? { var p1 = head var p2 = head?.next var evenP1 = head?.next while (p2?.next != null) { p1?.next = p2.next p1 = p2.next p2.next = p1.next p2 = p1.next } p1?.next = evenP1 return head } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,205
leetcode
MIT License
bookcase-web/src/main/kotlin/com/github/vhromada/bookcase/web/BookcaseWebConfiguration.kt
vhromada
127,519,826
false
null
package com.github.vhromada.bookcase.web import com.github.vhromada.bookcase.BookcaseConfiguration import com.github.vhromada.common.entity.Account import com.github.vhromada.common.provider.AccountProvider import com.github.vhromada.common.provider.TimeProvider import com.github.vhromada.common.provider.UuidProvider import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import java.time.LocalDateTime import java.util.UUID /** * A class represents Spring configuration for bookcase. * * @author <NAME> */ @Configuration @Import(BookcaseConfiguration::class) class BookcaseWebConfiguration : WebMvcConfigurer { @Bean fun passwordEncoder(): PasswordEncoder { return BCryptPasswordEncoder() } @Bean fun accountProvider(): AccountProvider { return object : AccountProvider { override fun getAccount(): Account { return SecurityContextHolder.getContext().authentication.principal as Account } } } @Bean fun timeProvider(): TimeProvider { return object : TimeProvider { override fun getTime(): LocalDateTime { return LocalDateTime.now() } } } @Bean fun uuidProvider(): UuidProvider { return object : UuidProvider { override fun getUuid(): String { return UUID.randomUUID().toString() } } } }
0
Kotlin
0
0
c3b6da21b0be7cdc5a13ceb3f04937316207bf77
1,825
Bookcase
MIT License
app/src/main/java/com/edricchan/studybuddy/utils/UiUtils.kt
EdricChan03
100,260,817
false
{"Kotlin": 710001, "Ruby": 202}
package com.edricchan.studybuddy.utils import android.content.Context import com.edricchan.studybuddy.R import com.edricchan.studybuddy.ui.modules.main.MainActivity import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.floatingactionbutton.FloatingActionButton /** * Utilities for the UI (user interface). * @param context The context to be used for the class. */ class UiUtils(val context: Context) { /** * The [FloatingActionButton] set on the [BottomAppBar]. */ val bottomAppBarFab: FloatingActionButton? = if (context is MainActivity) { context.findViewById(R.id.fab) } else { null } /** * The [BottomAppBar] of the [MainActivity] layout. */ val bottomAppBar: BottomAppBar? = if (context is MainActivity) { context.findViewById(R.id.bottomAppBar) } else { null } companion object { /** * Retrieves an instance of the class. * @param context The context to be used for the class. */ fun getInstance(context: Context) = UiUtils(context) } }
30
Kotlin
11
8
2d54a64c4dcd1808cc5fe487f2ce49f3e6f1e796
1,127
studybuddy-android
MIT License
plugin/src/org/jetbrains/haskell/sdk/HaskellSdkAdditionalData.kt
riazanovskiy
54,122,929
false
null
package org.jetbrains.haskell.sdk import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.projectRoots.SdkAdditionalData import com.intellij.openapi.projectRoots.SdkModel import org.jdom.Element import org.jetbrains.haskell.util.OSUtil public class HaskellSdkAdditionalData(cabalPath: String?, cabalLibPath: String?) : SdkAdditionalData, Cloneable { private var myCabalPath: String? = cabalPath private var myCabalDataPath: String? = cabalLibPath public override fun clone() : Any { return super<Cloneable>.clone() } public fun save(element: Element): Unit { if (myCabalPath != null) { element.setAttribute(CABAL_PATH, myCabalPath!!) } if (myCabalDataPath != null) { element.setAttribute(CABAL_DATA_PATH, myCabalDataPath!!) } } public fun getCabalPath(): String { return if (myCabalPath == null) "" else myCabalPath!! } public fun getCabalDataPath(): String { return if (myCabalDataPath == null) "" else myCabalDataPath!! } public fun setCabalPath(cabalPath: String?): Unit { this.myCabalPath = cabalPath } companion object { private val CABAL_PATH = "cabal_path" private val CABAL_DATA_PATH = "cabal_data_path" fun getDefaultCabalPath() : String { return "/usr/bin/cabal" } fun getDefaultCabalDataPath() : String { return OSUtil.getCabalData() } public fun load(element: Element): HaskellSdkAdditionalData { val data = HaskellSdkAdditionalData(null, null) data.myCabalPath = element.getAttributeValue(CABAL_PATH) ?: getDefaultCabalPath() data.myCabalDataPath = element.getAttributeValue(CABAL_DATA_PATH) ?: getDefaultCabalDataPath() return data } } }
1
null
1
1
51de5fa74691f12e25dde7b51047b9210013aec5
1,919
haskell-idea-plugin
Apache License 2.0
src/main/kotlin/simulation/BGPAdvertisementInitializer.kt
FAWC438
443,940,908
false
{"Kotlin": 185867}
package simulation import bgp.BGP import bgp.BGPRoute import core.routing.NodeID import core.routing.Topology import core.simulator.Advertisement import core.simulator.RandomDelayGenerator import core.simulator.Time import io.InterdomainAdvertisementReader import io.InterdomainTopologyReader import io.ParseException import io.parseInterdomainExtender import ui.Application import java.io.File import java.io.IOException sealed class BGPAdvertisementInitializer( // 必须的 private val topologyFile: File, // Optional (with defaults) var repetitions: Int = DEFAULT_REPETITIONS, var minDelay: Time = DEFAULT_MINDELAY, var maxDelay: Time = DEFAULT_MAXDELAY, var threshold: Time = DEFAULT_THRESHOLD, var reportDirectory: File = DEFAULT_REPORT_DIRECTORY, var reportNodes: Boolean = false, var outputMetadata: Boolean = false, var outputTrace: Boolean = false, // Optional (without defaults) var seed: Long? = null, var stubsFile: File? = null, var forcedMRAI: Time? = null ) : Initializer<BGPRoute> { companion object { const val DEFAULT_REPETITIONS = 1 const val DEFAULT_THRESHOLD = 1_000_000 const val DEFAULT_MINDELAY = 1 const val DEFAULT_MAXDELAY = 1 val DEFAULT_REPORT_DIRECTORY = File(System.getProperty("user.dir")) // 当前工作目录 fun with(topologyFile: File, advertiserIDs: Set<NodeID>): BGPAdvertisementInitializer = UsingDefaultSet(topologyFile, advertiserIDs) fun with(topologyFile: File, advertisementsFile: File): BGPAdvertisementInitializer = UsingFile(topologyFile, advertisementsFile) } /** * 这是报告文件的基本输出名称。基本输出名称不包含扩展名。子类应根据其规范提供名称。 */ abstract val outputName: String /** * 初始化模拟。它设置要运行的可执行程序和运行它们的运行器。 */ override fun initialize(application: Application, metadata: Metadata): Pair<Runner<BGPRoute>, Execution<BGPRoute>> { // 如果没有设置种子,则基于当前时间为每个新的初始化生成一个新的种子 val seed = seed ?: System.currentTimeMillis() // 根据文件类型附加扩展名 val basicReportFile = File(reportDirectory, outputName.plus(".basic.csv")) val nodesReportFile = File(reportDirectory, outputName.plus(".nodes.csv")) val metadataFile = File(reportDirectory, outputName.plus(".meta.txt")) val traceFile = File(reportDirectory, outputName.plus(".trace.txt")) // 设置消息延迟生成器 val messageDelayGenerator = try { RandomDelayGenerator.with(minDelay, maxDelay, seed) } catch (e: IllegalArgumentException) { throw InitializationException(e.message) } // 加载拓扑 val topology: Topology<BGPRoute> = application.loadTopology(topologyFile) { InterdomainTopologyReader(topologyFile, forcedMRAI).use { it.read() } } val advertisements = application.setupAdvertisements { // 子类决定了通告的配置方式,请参阅此文件底部的子类 initAdvertisements(application, topology) } // 一次执行需要的参数 val runner = RepetitionRunner( application, topology, advertisements, threshold, repetitions, messageDelayGenerator, metadataFile = if (outputMetadata) metadataFile else null // null 告诉程序不要打印元数据 ) // 模拟执行入口,即每次重复执行的入口 val execution = SimpleAdvertisementExecution<BGPRoute>().apply { dataCollectors.add(BasicDataCollector(basicReportFile)) if (reportNodes) { dataCollectors.add(NodeDataCollector(nodesReportFile)) } if (outputTrace) { dataCollectors.add(TraceReporter(traceFile)) } } metadata["Topology file"] = topologyFile.name stubsFile?.apply { metadata["Stubs file"] = name } metadata["Advertiser(s)"] = advertisements.map { it.advertiser.id }.joinToString() metadata["Minimum Delay"] = minDelay.toString() metadata["Maximum Delay"] = maxDelay.toString() metadata["Threshold"] = threshold.toString() forcedMRAI?.apply { metadata["MRAI"] = forcedMRAI.toString() } return Pair(runner, execution) } /** * 子类应使用此方法来初始化通告以在模拟中发生。这些定义的方式取决于实现。 * * @return 模拟中出现的初始化通告列表 */ protected abstract fun initAdvertisements(application: Application, topology: Topology<BGPRoute>) : List<Advertisement<BGPRoute>> // ----------------------------------------------------------------------------------------------------------------- // // Subclasses // // ----------------------------------------------------------------------------------------------------------------- /** * 基于一组预定义的通告客户 ID 进行初始化。每个 ID 都映射到一个通告者。可以从拓扑或存根文件中获取通告者。 * * 它为每个通告者生成一个通告,默认路由对应self BGP route,advertising time为0。 */ private class UsingDefaultSet(topologyFile: File, val advertiserIDs: Set<NodeID>) : BGPAdvertisementInitializer(topologyFile) { init { // 验证构造函数中是否提供了至少 1 个通告者 ID if (advertiserIDs.isEmpty()) { throw IllegalArgumentException("initializer requires at least 1 advertiser") } } /** * 输出名称(不包括扩展名)对应于拓扑文件名和通告者的 ID。 * 例如,如果拓扑文件名为“topology.topo”,通告者 ID 为 10 和 12,则输出文件名为“topology_10-12”。 */ override val outputName: String = topologyFile.nameWithoutExtension + "_${advertiserIDs.joinToString("-")}" /** * 为 ID 集中指定的每个广告商创建一个通告。 * * @throws InitializationException if the advertisers can not be found in the topology or stubs file * @throws ParseException if the stubs file format is invalid * @throws IOException if an IO error occurs * @return 模拟中出现的初始化通告列表 */ override fun initAdvertisements(application: Application, topology: Topology<BGPRoute>) : List<Advertisement<BGPRoute>> { // 从指定 ID 中查找所有通告者 val advertisers = application.readStubsFile(stubsFile) { AdvertiserDB(topology, stubsFile, BGP(), ::parseInterdomainExtender) .get(advertiserIDs.toList()) } // 该模式下,节点将自身BGP路由设置为默认路由 // 使用通告文件配置不同的路由 return advertisers.map { Advertisement(it, BGPRoute.self()) }.toList() } } /** * 基于通告文件的初始化。该文件描述了在每次模拟执行中出现的一组通告。 * * 通告文件中描述的通告者 ID 映射到实际通告者。可以从拓扑或存根文件中获取通告者。 */ private class UsingFile(topologyFile: File, val advertisementsFile: File) : BGPAdvertisementInitializer(topologyFile) { /** * 输出名称(不包括扩展名)对应于带有通告文件名的拓扑文件名。 * * 例如,如果拓扑文件名为“topology.topo”,广告文件名为“advertisements.adv”,则输出基本名称为“topology-advertisements” */ override val outputName: String = "${topologyFile.nameWithoutExtension}-${advertisementsFile.nameWithoutExtension}" /** * 通告是从通告文件中获取的 * * @return 模拟中出现的初始化通告列表 * @throws InitializationException if the advertisers can not be found in the topology or stubs file * @throws ParseException if the advertisements file format or the stubs file format are invalid * @throws IOException if an IO error occurs */ @Throws(InitializationException::class, ParseException::class, IOException::class) override fun initAdvertisements(application: Application, topology: Topology<BGPRoute>) : List<Advertisement<BGPRoute>> { val advertisingInfo = application.readAdvertisementsFile(advertisementsFile) { InterdomainAdvertisementReader(advertisementsFile).use { it.read() } } // 根据通告文件中包含的 ID 查找所有广告商 val advertisers = application.readStubsFile(stubsFile) { AdvertiserDB(topology, stubsFile, BGP(), ::parseInterdomainExtender) .get(advertisingInfo.map { it.advertiserID }) } val advertisersByID = advertisers.associateBy { it.id } return advertisingInfo.map { val advertiser = advertisersByID[it.advertiserID] ?: throw IllegalStateException("can not happen") Advertisement(advertiser, it.defaultRoute, it.time) } } } }
0
Kotlin
0
3
8a1f75ee37535ba87d98c3e0fe93d79e5fb83c38
8,412
BGP-ASPA
MIT License
kafkistry-record-structure/src/main/kotlin/com/infobip/kafkistry/recordstructure/MergingContext.kt
infobip
456,885,171
false
null
package com.infobip.kafkistry.recordstructure import com.infobip.kafkistry.model.* import com.infobip.kafkistry.model.PayloadType import com.infobip.kafkistry.model.RecordFieldType import kotlin.math.absoluteValue open class MergingContext( properties: RecordAnalyzerProperties, now: Long = generateTimestamp(), ) : ProcessingContext(properties, now) { fun timestampWrappedUnknownRecordsStructure( headersFields: List<TimestampWrapper<TimestampWrappedRecordField>>?, nullable: Boolean ) = TimestampWrappedRecordsStructure( PayloadType.UNKNOWN, timestampWrappedHeaderFields = headersFields, timestampWrappedJsonFields = null, nullable = wrapNow(nullable) ) /** * Simply add the newer fields to the existent ones * from: @TimestampWrappedRecordsStructure * to: @TimestampWrappedRecordsStructure */ infix fun TimestampWrappedRecordsStructure.merge( other: TimestampWrappedRecordsStructure ): TimestampWrappedRecordsStructure { if (payloadType != PayloadType.JSON && other.payloadType != PayloadType.JSON) { return timestampWrappedUnknownRecordsStructure( headersFields = timestampWrappedHeaderFields merge other.timestampWrappedHeaderFields, nullable = (nullable mergeBoolean other.nullable).field, ) } return TimestampWrappedRecordsStructure( PayloadType.JSON, timestampWrappedHeaderFields = timestampWrappedHeaderFields merge other.timestampWrappedHeaderFields, timestampWrappedJsonFields = timestampWrappedJsonFields merge other.timestampWrappedJsonFields, nullable = nullable mergeBoolean other.nullable, ) } infix fun List<TimestampWrapper<TimestampWrappedRecordField>>?.merge( other: List<TimestampWrapper<TimestampWrappedRecordField>>? ): List<TimestampWrapper<TimestampWrappedRecordField>>? { if (this == null || other == null || this == other) { return other ?: this } val thisIsTooOldDynamicField = size == 1 && first().let { it.field.name == null && it.timestamp.tooOld() } if (thisIsTooOldDynamicField) { return other } val thisNames = this.map { it.field.name }.toSet() val otherNames = other.map { it.field.name }.toSet() if (isNotEmpty() && other.isNotEmpty()) { infix fun Int.differentMagnitude(other: Int): Boolean { val thresholdDiff = properties.cardinalityDiffThreshold val thresholdFactor = properties.cardinalityMagnitudeFactorThreshold return (this - other).absoluteValue > thresholdDiff && (this > thresholdFactor * other || thresholdFactor * this < other) } fun Collection<String?>.hasDynamicFieldNames() = any { it?.isDynamicName() ?: true } fun commonNames() = thisNames.intersect(otherNames) fun namesCountDiffTooMuch() = thisNames.size.differentMagnitude(otherNames.size) fun isDynamic() = thisNames.hasDynamicFieldNames() || otherNames.hasDynamicFieldNames() || namesCountDiffTooMuch() || commonNames().isEmpty() if (isDynamic()) { //we have variable/dynamic key(s) return (this + other) .groupBy { it.field.type } .map { (_, values) -> values.squashAsVariable() } } } val thisNulls = filter { it.field.type == RecordFieldType.NULL }.associateBy { it.field.name } val otherNulls = other.filter { it.field.type == RecordFieldType.NULL }.associateBy { it.field.name } val thisFields = associateBy { it.field.name to it.field.type } val otherFields = other.associateBy { it.field.name to it.field.type } return (thisFields.keys + otherFields.keys).distinct().mapNotNull { key -> val fieldName = key.first val thisField = thisFields[key] val otherField = otherFields[key] val thisNull = thisNulls[fieldName] val otherNull = otherNulls[fieldName] when { //don't output NULL type if there is matching name of non-NULL type thisField.isNullType() && (fieldName in otherNames) && !otherField.isNullType() -> null otherField.isNullType() && (fieldName in thisNames) && !thisField.isNullType() -> null //do actual merge thisField != null && otherField != null -> thisField merge otherField //mark as nullable thisField != null -> if (otherNull != null || fieldName !in otherNames) thisField.asNullable() else thisField otherField != null -> if (thisNull != null || fieldName !in thisNames) otherField.asNullable() else otherField else -> null } } } private fun TimestampWrapper<TimestampWrappedRecordField>?.isNullType() = this?.field?.type == RecordFieldType.NULL private fun String.isDynamicName(): Boolean { if (isBlank()) return true if (!get(0).isJavaIdentifierStart()) return true return !all { it.isJavaIdentifierPart() } } private fun List<TimestampWrapper<TimestampWrappedRecordField>>.squashAsVariable(): TimestampWrapper<TimestampWrappedRecordField> { return first().withField { field -> field.copy( name = null, value = asSequence().map { it.field.value }.reduce { acc, wrappers -> acc merge wrappers }, children = asSequence().map { it.field.children }.reduce { acc, wrappers -> acc merge wrappers } ) } } private fun TimestampWrapper<TimestampWrappedRecordField>.asNullable() = withField { it.copy(nullable = wrapNow(true)) } infix fun TimestampWrapper<TimestampWrappedRecordField>.merge( other: TimestampWrapper<TimestampWrappedRecordField> ): TimestampWrapper<TimestampWrappedRecordField> { if (field == other.field) { return other } return wrapNow( TimestampWrappedRecordField( nullable = field.nullable mergeBoolean other.field.nullable, name = other.field.name, type = when (other.field.type) { RecordFieldType.NULL -> field.type else -> other.field.type }, children = when { field.children != other.field.children -> field.children merge other.field.children else -> other.field.children }, value = field.value merge other.field.value, ) ) } private infix fun TimestampWrapper<Boolean>.mergeBoolean( other: TimestampWrapper<Boolean> ): TimestampWrapper<Boolean> = when { field -> when (!other.field && timestamp.tooOld()) { true -> wrapNow(false) false -> this } else -> wrapNow(field || other.field) } infix fun TimestampWrappedFieldValue?.merge( other: TimestampWrappedFieldValue? ): TimestampWrappedFieldValue? { if (this == null || other == null || this == other) { return other ?: this } val mergedHighCardinality = highCardinality mergeBoolean other.highCardinality fun <T> List<T>.takeIfNotHighCardinality(): List<T> = when { isHighCardinality() -> emptyList() mergedHighCardinality.field -> emptyList() else -> this } val mergedValues = when (mergedHighCardinality.field) { true -> emptyList() false -> values mergeValueSet other.values } return TimestampWrappedFieldValue( highCardinality = mergedHighCardinality mergeBoolean wrapNow(mergedValues.isHighCardinality()), tooBig = tooBig mergeBoolean other.tooBig, values = mergedValues.takeIfNotHighCardinality(), ) } private fun List<*>.isHighCardinality() = size > properties.valueSampling.maxCardinality private infix fun <T> List<TimestampWrapper<T>>.mergeValueSet( other: List<TimestampWrapper<T>> ): List<TimestampWrapper<T>> { return sequenceOf(this, other) .flatten() .filter { !it.timestamp.tooOld() } .groupingBy { it.field } .reduce { _, accumulator, element -> if (accumulator.timestamp > element.timestamp) accumulator else element } .values.toList() } }
1
null
6
42
62403993a76fdf60b4cae3a87c5be0abe4fb3a88
8,811
kafkistry
Apache License 2.0
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRDataContextRepository.kt
hieuprogrammer
284,920,751
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.plugins.github.api.GHGQLRequests import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.api.GHRepositoryPath import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.data.GHRepositoryOwnerName import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.request.search.GithubIssueSearchType import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.GHPRDiffRequestModelImpl import org.jetbrains.plugins.github.pullrequest.data.service.* import org.jetbrains.plugins.github.pullrequest.search.GHPRSearchQueryHolderImpl import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.util.* import java.io.IOException import java.util.concurrent.CompletableFuture @Service internal class GHPRDataContextRepository(private val project: Project) { private val repositories = mutableMapOf<GHRepositoryCoordinates, LazyCancellableBackgroundProcessValue<GHPRDataContext>>() @RequiresEdt fun acquireContext(repository: GHRepositoryCoordinates, remote: GitRemoteUrlCoordinates, account: GithubAccount, requestExecutor: GithubApiRequestExecutor): CompletableFuture<GHPRDataContext> { return repositories.getOrPut(repository) { val contextDisposable = Disposer.newDisposable() LazyCancellableBackgroundProcessValue.create { indicator -> ProgressManager.getInstance().submitIOTask(indicator) { try { loadContext(indicator, account, requestExecutor, repository, remote) } catch (e: Exception) { if (e !is ProcessCanceledException) LOG.info("Error occurred while creating data context", e) throw e } }.successOnEdt { ctx -> if (Disposer.isDisposed(contextDisposable)) { Disposer.dispose(ctx) } else { Disposer.register(contextDisposable, ctx) } ctx } }.also { it.addDropEventListener { Disposer.dispose(contextDisposable) } } }.value } @RequiresEdt fun clearContext(repository: GHRepositoryCoordinates) { repositories.remove(repository)?.drop() } @RequiresBackgroundThread @Throws(IOException::class) private fun loadContext(indicator: ProgressIndicator, account: GithubAccount, requestExecutor: GithubApiRequestExecutor, parsedRepositoryCoordinates: GHRepositoryCoordinates, remoteCoordinates: GitRemoteUrlCoordinates): GHPRDataContext { indicator.text = GithubBundle.message("pull.request.loading.account.info") val accountDetails = GithubAccountInformationProvider.getInstance().getInformation(requestExecutor, indicator, account) indicator.checkCanceled() indicator.text = GithubBundle.message("pull.request.loading.repo.info") val repositoryInfo = requestExecutor.execute(indicator, GHGQLRequests.Repo.find(GHRepositoryCoordinates(account.server, parsedRepositoryCoordinates.repositoryPath))) ?: throw IllegalArgumentException( "Repository ${parsedRepositoryCoordinates.repositoryPath} does not exist at ${account.server} or you don't have access.") val currentUser = GHUser(accountDetails.nodeId, accountDetails.login, accountDetails.htmlUrl, accountDetails.avatarUrl!!, accountDetails.name) indicator.text = GithubBundle.message("pull.request.loading.user.teams.info") val repoOwner = repositoryInfo.owner val currentUserTeams = if (repoOwner is GHRepositoryOwnerName.Organization) SimpleGHGQLPagesLoader(requestExecutor, { GHGQLRequests.Organization.Team.findByUserLogins(account.server, repoOwner.login, listOf(currentUser.login), it) }).loadAll(indicator) else emptyList() indicator.checkCanceled() // repository might have been renamed/moved val apiRepositoryPath = repositoryInfo.path val apiRepositoryCoordinates = GHRepositoryCoordinates(account.server, apiRepositoryPath) val securityService = GHPRSecurityServiceImpl(GithubSharedProjectSettings.getInstance(project), account, currentUser, currentUserTeams, repositoryInfo) val detailsService = GHPRDetailsServiceImpl(ProgressManager.getInstance(), requestExecutor, apiRepositoryCoordinates) val stateService = GHPRStateServiceImpl(ProgressManager.getInstance(), securityService, requestExecutor, account.server, apiRepositoryPath) val commentService = GHPRCommentServiceImpl(ProgressManager.getInstance(), requestExecutor, apiRepositoryCoordinates) val changesService = GHPRChangesServiceImpl(ProgressManager.getInstance(), project, requestExecutor, remoteCoordinates, apiRepositoryCoordinates) val reviewService = GHPRReviewServiceImpl(ProgressManager.getInstance(), securityService, requestExecutor, apiRepositoryCoordinates) val searchHolder = GHPRSearchQueryHolderImpl().apply { query = GHPRSearchQuery.DEFAULT } val listLoader = GHGQLPagedListLoader(ProgressManager.getInstance(), SimpleGHGQLPagesLoader(requestExecutor, { p -> GHGQLRequests.PullRequest.search(account.server, buildQuery(apiRepositoryPath, searchHolder.query), p) })) val listUpdatesChecker = GHPRListETagUpdateChecker(ProgressManager.getInstance(), requestExecutor, account.server, apiRepositoryPath) val dataProviderRepository = GHPRDataProviderRepositoryImpl(detailsService, stateService, reviewService, commentService, changesService) { id -> GHGQLPagedListLoader(ProgressManager.getInstance(), SimpleGHGQLPagesLoader(requestExecutor, { p -> GHGQLRequests.PullRequest.Timeline.items(account.server, apiRepositoryPath.owner, apiRepositoryPath.repository, id.number, p) }, true)) } val repoDataService = GHPRRepositoryDataServiceImpl(ProgressManager.getInstance(), requestExecutor, remoteCoordinates, apiRepositoryCoordinates, repoOwner, repositoryInfo.id, repositoryInfo.defaultBranch, repositoryInfo.isFork) val avatarIconsProvider = GHAvatarIconsProvider(CachingGHUserAvatarLoader.getInstance(), requestExecutor) val filesManager = GHPRFilesManagerImpl(project, parsedRepositoryCoordinates) indicator.checkCanceled() val creationService = GHPRCreationServiceImpl(ProgressManager.getInstance(), requestExecutor, repoDataService) return GHPRDataContext(searchHolder, listLoader, listUpdatesChecker, dataProviderRepository, securityService, repoDataService, creationService, detailsService, avatarIconsProvider, filesManager, GHPRDiffRequestModelImpl()) } @RequiresEdt fun findContext(repositoryCoordinates: GHRepositoryCoordinates): GHPRDataContext? = repositories[repositoryCoordinates]?.lastLoadedValue companion object { private val LOG = logger<GHPRDataContextRepository>() fun getInstance(project: Project) = project.service<GHPRDataContextRepository>() private fun buildQuery(repoPath: GHRepositoryPath, searchQuery: GHPRSearchQuery?): String { return GithubApiSearchQueryBuilder.searchQuery { qualifier("type", GithubIssueSearchType.pr.name) qualifier("repo", repoPath.toString()) searchQuery?.buildApiSearchQuery(this) } } } }
191
null
4372
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
9,406
intellij-community
Apache License 2.0
core/src/main/java/com/dtb/core/common/cache/PreferenceCacheImpl.kt
DaoBillTang
109,212,518
false
null
package com.dtb.core.common.cache import android.content.Context import android.content.SharedPreferences import com.dtb.core.common.cache.contract.ICache /** * Project com.daotangbill.exlib.commons.utils * Created by DaoTangBill on 2020/2/23/023. * Email:<EMAIL> * * @author bill * @version 1.0 * @description * */ class PreferenceCacheImpl(context: Context, nameTable: String?) : ICache { private val prefs: SharedPreferences = context.getSharedPreferences(nameTable ?: "config", Context.MODE_PRIVATE) override fun getString(key: String, def: String?): String? = with(prefs) { this.getString(key, def) } override fun getInt(key: String, def: Int): Int = with(prefs) { this.getInt(key, def) } override fun getBool(key: String, def: Boolean): Boolean = with(prefs) { this.getBoolean(key, def) } override fun getFloat(key: String, defValue: Float): Float = with(prefs) { this.getFloat(key, defValue) } override fun getLong(key: String, defValue: Long): Long= with(prefs) { this.getLong(key, defValue) } override fun putLong(key: String, value: Long) = with(prefs.edit()) { putLong(key, value) }.apply() override fun putString(key: String, value: String) = with(prefs.edit()) { this.putString(key, value) }.apply() override fun putInt(key: String, value: Int) = with(prefs.edit()) { this.putInt(key, value) }.apply() override fun putBoolean(key: String, value: Boolean) = with(prefs.edit()) { this.putBoolean(key, value) }.apply() override fun putFloat(key: String, value: Float) = with(prefs.edit()) { this.putFloat(key, value) }.apply() override fun remove(key: String): Boolean? = prefs.edit().remove(key).commit() }
1
null
4
4
2ae19a8c7986cd49fece58475ef0080e1ccc2204
1,816
MLib
Apache License 2.0
src/commonMain/kotlin/KisOpenApi.kt
devngho
565,833,597
false
{"Kotlin": 268528}
package io.github.devngho.kisopenapi import io.github.devngho.kisopenapi.requests.* import io.github.devngho.kisopenapi.requests.response.CorporationRequest import io.github.devngho.kisopenapi.requests.response.LiveResponse import io.github.devngho.kisopenapi.requests.util.createHttpClient import io.github.devngho.kisopenapi.requests.util.json import io.ktor.client.plugins.websocket.* import io.ktor.websocket.* import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.decodeFromString import kotlin.jvm.JvmStatic /** * 한국투자증권 API에 접근하기 위한 객체입니다. * * @property appKey 인증에 사용되는 애플리케이션 키입니다. * @property appSecret 인증에 사용되는 애플리케이션 서크릿입니다. * @property isDemo 데모 환경을 사용하는지 여부를 나타내는 플래그입니다. * @property account 계좌 번호입니다. * @property htsId HTS ID입니다. * @property corp 개인/법인 정보입니다. * @property useHashKey [io.github.devngho.kisopenapi.requests.HashKey]를 사용해 요청을 보낼지 여부를 나타내는 플래그입니다. */ class KisOpenApi internal constructor( val appKey: String, val appSecret: String, val isDemo: Boolean, /** 계좌번호(XXXXXXXX-XX 형식) */ var account: List<String>?, var htsId: String? = null, var corp: CorporationRequest? = CorporationRequest(), var useHashKey: Boolean = false, var autoReconnect: Boolean = true, val rateLimiter: RateLimiter ) { lateinit var oauthToken: String var websocketToken: String? = null /** * 웹소켓 세션입니다. * @see io.github.devngho.kisopenapi.requests.LiveRequest */ var websocket: DefaultClientWebSocketSession? = null /** * 웹소켓으로 들어오는 데이터 Flow입니다. * @see io.github.devngho.kisopenapi.requests.LiveRequest */ var websocketIncoming: MutableSharedFlow<String>? = null /** * tr_key 목록입니다. * 구독을 해제할 때, 다른 곳에서 구독 중인지 확인하기 위해 사용합니다. * @see io.github.devngho.kisopenapi.requests.LiveRequest */ private val websocketSubscribedKey = mutableListOf<String>() private val websocketSubscribedKeyMutex = Mutex() /** * 구독 중인 요청 목록입니다. * 구독 상태를 복원하기 위해 사용합니다. * @see io.github.devngho.kisopenapi.requests.LiveRequest */ private val webSocketSubscribed = mutableListOf<WebSocketSubscribed>() private val webSocketSubscribedMutex = Mutex() internal data class WebSocketSubscribed( val request: LiveRequest<out LiveData, out Response>, val data: LiveData, val initFunc: ((LiveResponse) -> Unit)? = null, val block: (Response) -> Unit ) /** * 요청을 구독 처리합니다. * @param request 구독할 요청 */ internal suspend fun subscribe(request: WebSocketSubscribed) { webSocketSubscribedMutex.withLock { webSocketSubscribed.add(request) } websocketSubscribedKeyMutex.withLock { websocketSubscribedKey.add(request.data.tradeKey(this)) } } /** * 요청을 구독 해제 처리합니다. * @param request 구독 해제할 요청 * @return 구독 해제 요청을 전송해야 하는지 여부 * @see io.github.devngho.kisopenapi.requests.LiveRequest */ internal suspend fun unsubscribe(request: WebSocketSubscribed): Boolean { webSocketSubscribedMutex.withLock { webSocketSubscribed.remove(request) } val trKey = request.data.tradeKey(this) websocketSubscribedKeyMutex.withLock { websocketSubscribedKey.remove(trKey) return websocketSubscribedKey.contains(trKey) } } internal val httpClient = createHttpClient() suspend fun buildWebsocket(): DefaultClientWebSocketSession { httpClient.webSocketSession(if (isDemo) "ws://ops.koreainvestment.com:31000" else "ws://ops.koreainvestment.com:21000").run { websocketIncoming = MutableSharedFlow() websocket = this if (autoReconnect) launch { closeReason.await() reconnectWebsocket() } launch { incoming.consumeEach { if (it is Frame.Text) { val txt = it.readText() websocketIncoming?.emit(txt) // PING-PONG txt .takeIf { v -> v[0] != '0' && v[0] != '1' } ?.let { v -> json.decodeFromString<LiveResponse>(v) } ?.apply { if (this.header?.tradeId == "PINGPONG") send(it) } } } } return this } } /** * 웹소켓을 종료합니다. */ suspend fun closeWebsocket() { websocket?.close() websocket = null websocketIncoming = null } /** * 웹소켓 연결을 다시 시도합니다. */ @Suppress("unchecked_cast") suspend fun reconnectWebsocket() { closeWebsocket() buildWebsocket() // 연결 요청 다시 전송 webSocketSubscribedMutex.withLock { webSocketSubscribed.forEach { (it.request as LiveRequest<LiveData, *>).register(it.data, it.initFunc, it.block) } } } companion object { /** * KisOpenApi 객체를 생성합니다. * @param token 사용할 토큰 * @param appKey 앱 키 * @param appSecret 앱 시크릿 * @param isDemo 모의투자 여부 * @param websocketToken 웹소켓 토큰 * @param account 계좌번호(XXXXXXXX-XX 형식) * @param id HTS ID * @param corp 호출하는 개인/기관 정보 * @param hashKey 해시키 사용 여부 * @param autoReconnect 웹소켓 연결이 끊겼을 때 자동으로 재연결할지 여부 * @param rateLimiter 요청 속도 제한 */ @JvmStatic fun withToken( token: String, appKey: String, appSecret: String, isDemo: Boolean = false, websocketToken: String? = null, /** 계좌번호(XXXXXXXX-XX 형식) */ account: String? = null, id: String? = null, corp: CorporationRequest? = CorporationRequest(), hashKey: Boolean = false, autoReconnect: Boolean = true, rateLimiter: RateLimiter? = null ) = KisOpenApi( appKey, appSecret, isDemo, account?.split("-"), id, corp, hashKey, autoReconnect, rateLimiter ?: RateLimiter.defaultRate(isDemo) ) .apply { oauthToken = token if(websocketToken != null) this.websocketToken = websocketToken } /** * KisOpenApi 객체를 생성합니다. * 토큰 발급 API를 알아서 발급합니다. * @param appKey 앱 키 * @param appSecret 앱 시크릿 * @param isDemo 모의투자 여부 * @param grantWebsocket 웹소켓 토큰 발급 여부 * @param account 계좌번호(XXXXXXXX-XX 형식) * @param id HTS ID * @param corp 호출하는 개인/기관 정보 * @param hashKey 해시키 사용 여부 * @param autoReconnect 웹소켓 연결이 끊겼을 때 자동으로 재연결할지 여부 * @param rateLimiter 요청 속도 제한 */ @JvmStatic suspend fun with( appKey: String, appSecret: String, isDemo: Boolean = false, /** 계좌번호(XXXXXXXX-XX 형식) */ account: String? = null, id: String? = null, corp: CorporationRequest? = CorporationRequest(), grantWebsocket: Boolean = false, hashKey: Boolean = false, autoReconnect: Boolean = true, rateLimiter: RateLimiter? = null ) = KisOpenApi( appKey, appSecret, isDemo, account?.split("-"), id, corp, hashKey, autoReconnect, rateLimiter ?: RateLimiter.defaultRate(isDemo) ) .apply { oauthToken = GrantToken(this).call().accessToken if(grantWebsocket) this.websocketToken = GrantLiveToken(this).call().approvalKey } } }
0
Kotlin
1
2
bba61df1301f0d75f9051e5f423773faadb0a333
8,244
kt_kisopenapi
MIT License
app/src/main/java/com/guhungry/photomanipulator/demo/ImageUtils.kt
guhungry
175,389,166
false
null
package com.guhungry.rnphotomanipulator.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import com.guhungry.photomanipulator.* import java.io.InputStream import java.util.* object ImageUtils { /** * Get Bitmap from Image Uri * * @param context * @param uri Uri of Image file */ @JvmOverloads @JvmStatic fun bitmapFromUri(context: Context, uri: String, options: BitmapFactory.Options? = null): Bitmap { openBitmapInputStream(context, uri).use { image -> val matrix = openBitmapInputStream(context, uri).use { BitmapUtils.getCorrectOrientationMatrix(it) } val bitmap: Bitmap = BitmapFactory.decodeStream(image, null, options)!! return if (matrix != null) Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true).also { bitmap.recycle() } else bitmap } } @JvmStatic fun mutableOptions() = BitmapFactory.Options().apply { inMutable = true } private fun openBitmapInputStream(context: Context, uri: String): InputStream = FileUtils.openBitmapInputStream(context, computeUri(context, uri)) private fun computeUri(context: Context, uri: String): String { return if (Uri.parse(uri).scheme != null) uri else computeDrawableResourceUri(context, uri) } private fun computeDrawableResourceUri(context: Context, name: String) = "android.resource://${context.packageName}/${computeDrawableResourceId(context, name)}" private fun computeDrawableResourceId(context: Context, name: String): Int { if (name.isEmpty()) return 0 // name could be a resource id. try { return name.toInt() } catch (e: NumberFormatException) { // Do nothing. } val resource = name.lowercase(Locale.getDefault()).replace("-", "_") return context.resources.getIdentifier(resource, "drawable", context.packageName) } /** * Get Crop and resize Bitmap from Image Uri * * @param context * @param uri Uri of Image file */ @JvmStatic fun cropBitmapFromUri(context: Context, uri: String, cropRegion: CGRect, targetSize: CGSize?): Bitmap { openBitmapInputStream(context, uri).use { image -> val output = if (targetSize == null) BitmapUtils.crop(image, cropRegion, mutableOptions()) else { val matrix = openBitmapInputStream(context, uri).use { BitmapUtils.getCorrectOrientationMatrix(it) } BitmapUtils.cropAndResize(image, cropRegion, targetSize, mutableOptions(), matrix) } return makeMutable(output) } } private fun makeMutable(output: Bitmap): Bitmap { return when { output.isMutable -> output else -> try { output.copy(output.config, true) } finally { output.recycle() } } } /** * Save image to temp file * * @param context */ @JvmStatic fun saveTempFile(context: Context, image: Bitmap, mimeType: String, prefix: String, quality: Int): String { val file = FileUtils.createTempFile(context, prefix, mimeType) FileUtils.saveImageFile(image, mimeType, quality, file) return Uri.fromFile(file).toString() } }
7
null
38
7
48496059f28a902465b381b33b37923b37c2262b
3,458
android-photo-manipulator
MIT License
richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownUtils.kt
MohamedRejeb
630,584,174
false
{"Kotlin": 550169}
package com.yiyitec.richeditor.parser.markdown import com.yiyitec.richeditor.utils.fastForEach import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.findChildOfType import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.flavours.gfm.GFMElementTypes import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.flavours.gfm.GFMTokenTypes import org.intellij.markdown.parser.MarkdownParser internal fun encodeMarkdownToRichText( markdown: String, onOpenNode: (node: ASTNode) -> Unit, onCloseNode: (node: ASTNode) -> Unit, onText: (text: String) -> Unit, onHtml: (html: String) -> Unit, ) { val parser = MarkdownParser(GFMFlavourDescriptor()) val tree = parser.buildMarkdownTreeFromString(markdown) tree.children.fastForEach { node -> encodeMarkdownNodeToRichText( node = node, markdown = markdown, onOpenNode = onOpenNode, onCloseNode = onCloseNode, onText = onText, onHtml = onHtml, ) } } private fun encodeMarkdownNodeToRichText( node: ASTNode, markdown: String, onOpenNode: (node: ASTNode) -> Unit, onCloseNode: (node: ASTNode) -> Unit, onText: (text: String) -> Unit, onHtml: (html: String) -> Unit, ) { when (node.type) { MarkdownTokenTypes.TEXT -> onText(node.getTextInNode(markdown).toString()) MarkdownTokenTypes.WHITE_SPACE -> onText(" ") MarkdownTokenTypes.SINGLE_QUOTE -> onText("'") MarkdownTokenTypes.DOUBLE_QUOTE -> onText("\"") MarkdownTokenTypes.LPAREN -> onText("(") MarkdownTokenTypes.RPAREN -> onText(")") MarkdownTokenTypes.LBRACKET -> onText("[") MarkdownTokenTypes.RBRACKET -> onText("]") MarkdownTokenTypes.LT -> onText("<") MarkdownTokenTypes.GT -> onText(">") MarkdownTokenTypes.COLON -> onText(":") MarkdownTokenTypes.EXCLAMATION_MARK -> onText("!") MarkdownTokenTypes.EMPH -> onText("*") GFMTokenTypes.TILDE -> onText("~") MarkdownElementTypes.STRONG, GFMElementTypes.STRIKETHROUGH -> { onOpenNode(node) val children = node.children.toMutableList() children.removeFirstOrNull() children.removeFirstOrNull() children.removeLastOrNull() children.removeLastOrNull() children.fastForEach { child -> encodeMarkdownNodeToRichText( node = child, markdown = markdown, onOpenNode = onOpenNode, onCloseNode = onCloseNode, onText = onText, onHtml = onHtml, ) } onCloseNode(node) } MarkdownElementTypes.EMPH -> { onOpenNode(node) val children = node.children.toMutableList() children.removeFirstOrNull() children.removeLastOrNull() children.fastForEach { child -> encodeMarkdownNodeToRichText( node = child, markdown = markdown, onOpenNode = onOpenNode, onCloseNode = onCloseNode, onText = onText, onHtml = onHtml, ) } onCloseNode(node) } MarkdownElementTypes.CODE_SPAN -> { onOpenNode(node) onText(node.getTextInNode(markdown).removeSurrounding("`").toString()) onCloseNode(node) } MarkdownElementTypes.INLINE_LINK -> { onOpenNode(node) val text = node .findChildOfType(MarkdownElementTypes.LINK_TEXT) ?.getTextInNode(markdown) ?.drop(1) ?.dropLast(1) ?.toString() onText(text ?: "") onCloseNode(node) } MarkdownElementTypes.HTML_BLOCK, MarkdownTokenTypes.HTML_TAG -> { onHtml(node.getTextInNode(markdown).toString()) } else -> { onOpenNode(node) node.children.fastForEach { child -> encodeMarkdownNodeToRichText( node = child, markdown = markdown, onOpenNode = onOpenNode, onCloseNode = onCloseNode, onText = onText, onHtml = onHtml, ) } onCloseNode(node) } } }
56
Kotlin
61
995
d07edeb20bbfddc7834618cca630d1326c4c6668
4,727
compose-rich-editor
Apache License 2.0
app/src/main/java/com/nyi/game/tictactoe/TicTacToeViewModel.kt
NyiNyiLin
262,045,830
false
null
package com.nyi.game.tictactoe import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.nyi.game.tictactoe.PlayerState.DRAW import com.nyi.game.tictactoe.PlayerState.O_WIN import com.nyi.game.tictactoe.PlayerState.USER_TURN import com.nyi.game.tictactoe.PlayerState.X_WIN import com.nyi.game.tictactoe.model.Player.PLAYER_EMPTY import com.nyi.game.tictactoe.model.Player.PLAYER_O_MINI import com.nyi.game.tictactoe.model.Player.PLAYER_X_MAXI import com.nyi.game.tictactoe.model.State class TicTacToeViewModel : ViewModel() { val currentState = MutableLiveData<Pair<State, Boolean>>() val playingState = MutableLiveData<PlayerState>() private val emptyComputerStartState = State( lastPlayedPlayer = PLAYER_O_MINI, stateList = arrayOf( PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY ) ) private val emptyUserStartState = State( lastPlayedPlayer = PLAYER_EMPTY, stateList = arrayOf( PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY, PLAYER_EMPTY ) ) init { currentState.postValue(Pair(emptyUserStartState, true)) playingState.postValue(USER_TURN) } fun makeComputerStartFirst(){ val computerClickState = TicTacToe.calculateForX(emptyComputerStartState) //log(computerClickState) var clickable = true if(isFinish(computerClickState)) clickable = false currentState.postValue(Pair(computerClickState, clickable)) } fun onPlayClick(playerClickState : State){ //log(playerClickState) currentState.postValue(Pair(playerClickState, false)) if(isFinish(playerClickState)) return val computerClickState = TicTacToe.calculateForX(playerClickState) //log(computerClickState) var clickable = true if(isFinish(computerClickState)) clickable = false currentState.postValue(Pair(computerClickState, clickable)) } fun onClickRetry(isComputerFirst : Boolean){ if(isComputerFirst){ playingState.postValue(USER_TURN) currentState.postValue(Pair(emptyComputerStartState, true)) makeComputerStartFirst() }else{ playingState.postValue(USER_TURN) currentState.postValue(Pair(emptyUserStartState, true)) } } private fun isFinish(state: State) : Boolean{ if(TicTacToe.terminal(state)){ val result = TicTacToe.utility(state) if(result == TicTacToe.PLAYER_X_WIN) playingState.postValue(X_WIN) else if(result == TicTacToe.PLAYER_O_WIN) playingState.postValue(O_WIN) else playingState.postValue(DRAW) return true } playingState.postValue(USER_TURN) return false } private fun log(state: State){ var finalCodeList = "[" state.stateList.forEach { finalCodeList += "${it.code} , " } finalCodeList += "]" Log.d("Tic Tac Toe", finalCodeList) } }
0
Kotlin
0
0
c7f74fd15c1c5e0a1b81527e325b60ba18e9ad67
2,992
Alpha-Game
Apache License 2.0
Base/src/main/java/xy/xy/base/listener/LoadViewListener.kt
xiuone
291,512,847
false
null
package com.xy.base.listener import android.view.View interface LoadViewListener : LoadEmptyView, LoadErrorView { fun createContentView(): View? fun createLoadView():View? fun createUnNetView(): View? fun createErrorReLoadView(): View? fun createUnNetReLoadView(): View? }
0
Kotlin
1
2
a91666c064e6843511094727503687a1ade12f3f
294
ajinlib
Apache License 2.0
src/main/kotlin/com/joshlong/twitter/api/Entities.kt
this-week-in
251,168,523
false
null
package com.joshlong.twitter.api import java.net.URL data class Entities( val hashtags: List<Hashtag>, val userMentions: List<UserMention>, val urls: List<URL> )
0
Kotlin
0
0
a4bd63e86939c8d7443b62c8807e773b9728dbbd
169
twitter-client
Apache License 2.0
notification-infrastructure/src/main/kotlin/io/github/v1servicenotification/domain/notification/presentation/dto/Group.kt
team-xquare
443,712,278
false
{"Kotlin": 98727, "Dockerfile": 448}
package io.github.v1servicenotification.domain.notification.presentation.dto import com.fasterxml.jackson.annotation.JsonProperty data class Group( val topic: String, val content: String, @JsonProperty("thread_id") val threadId: String, )
2
Kotlin
0
9
cc9c622d781b49607eec0f03386723832a65ac7d
259
v1-service-notification
MIT License
api/src/main/java/com/nspu/riotapi/models/LeagueList.kt
nspu
127,918,560
false
null
package fr.nspu.riot_api.models import android.os.Parcel import android.os.Parcelable data class LeagueList( var leagueId: String? = null, var tier: String? = null, var entries: List<LeagueItem>? = null, var queue: String? = null, var name: String? = null ) : Parcelable { constructor(source: Parcel) : this( source.readString(), source.readString(), source.createTypedArrayList(LeagueItem.CREATOR), source.readString(), source.readString() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(leagueId) writeString(tier) writeTypedList(entries) writeString(queue) writeString(name) } companion object { @JvmField val CREATOR: Parcelable.Creator<LeagueList> = object : Parcelable.Creator<LeagueList> { override fun createFromParcel(source: Parcel): LeagueList = LeagueList(source) override fun newArray(size: Int): Array<LeagueList?> = arrayOfNulls(size) } } }
0
null
0
1
75fa318a2a936438edc9eb45056cd1b27bcc0f3d
1,147
riot-api-android
MIT License
android/SwiftKotlination/features/topstories/src/test/kotlin/fr/jhandguy/topstories/model/mocks/TopStoriesManagerMock.kt
jhandguy
130,410,529
false
null
package fr.jhandguy.topstories.model.mocks import fr.jhandguy.network.model.observer.Disposable import fr.jhandguy.network.model.observer.Observer import fr.jhandguy.network.model.observer.Result import fr.jhandguy.topstories.model.TopStories import fr.jhandguy.topstories.model.TopStoriesManagerInterface class TopStoriesManagerMock(var result: Result<TopStories>, var observer: Observer<TopStories> = {}) : TopStoriesManagerInterface { override suspend fun topStories(observer: Observer<TopStories>): Disposable { this.observer = observer observer(result) return Disposable {} } override suspend fun fetchStories() = observer(result) }
0
Swift
7
24
56c44db2ca9e7c5196f8ce108d73157d417a56cf
678
SwiftKotlination
MIT License
relive-simulator-core/src/jvmMain/kotlin/xyz/qwewqa/relive/simulator/core/gen/valuesGenRemakeSkill.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.gen actual val valuesGenRemakeSkill: Map<Int, GenRemakeSkill> by lazy { loadMasterData<GenRemakeSkill>(dataGenRemakeSkill) }
0
Kotlin
11
7
e32dab696f56ead176e35fca40add33ad1e7f742
169
relight
MIT License
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/visitors/IrElementVisitorVoid.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.ir.visitors import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.* interface IrElementVisitorVoid : IrElementVisitor<Unit, Nothing?> { fun visitElement(element: IrElement) override fun visitElement(element: IrElement, data: Nothing?) = visitElement(element) fun visitModuleFragment(declaration: IrModuleFragment) = visitElement(declaration) override fun visitModuleFragment(declaration: IrModuleFragment, data: Nothing?) = visitModuleFragment(declaration) fun visitPackageFragment(declaration: IrPackageFragment) = visitElement(declaration) override fun visitPackageFragment(declaration: IrPackageFragment, data: Nothing?) = visitPackageFragment(declaration) fun visitExternalPackageFragment(declaration: IrExternalPackageFragment) = visitPackageFragment(declaration) override fun visitExternalPackageFragment(declaration: IrExternalPackageFragment, data: Nothing?) = visitExternalPackageFragment(declaration) fun visitFile(declaration: IrFile) = visitPackageFragment(declaration) override fun visitFile(declaration: IrFile, data: Nothing?) = visitFile(declaration) fun visitDeclaration(declaration: IrDeclarationBase) = visitElement(declaration) override fun visitDeclaration(declaration: IrDeclarationBase, data: Nothing?) = visitDeclaration(declaration) fun visitClass(declaration: IrClass) = visitDeclaration(declaration) override fun visitClass(declaration: IrClass, data: Nothing?) = visitClass(declaration) fun visitScript(declaration: IrScript) = visitDeclaration(declaration) override fun visitScript(declaration: IrScript, data: Nothing?) = visitScript(declaration) fun visitFunction(declaration: IrFunction) = visitDeclaration(declaration) override fun visitFunction(declaration: IrFunction, data: Nothing?) = visitFunction(declaration) fun visitSimpleFunction(declaration: IrSimpleFunction) = visitFunction(declaration) override fun visitSimpleFunction(declaration: IrSimpleFunction, data: Nothing?) = visitSimpleFunction(declaration) fun visitConstructor(declaration: IrConstructor) = visitFunction(declaration) override fun visitConstructor(declaration: IrConstructor, data: Nothing?) = visitConstructor(declaration) fun visitProperty(declaration: IrProperty) = visitDeclaration(declaration) override fun visitProperty(declaration: IrProperty, data: Nothing?) = visitProperty(declaration) fun visitField(declaration: IrField) = visitDeclaration(declaration) override fun visitField(declaration: IrField, data: Nothing?) = visitField(declaration) fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty) = visitDeclaration(declaration) override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty, data: Nothing?) = visitLocalDelegatedProperty(declaration) fun visitVariable(declaration: IrVariable) = visitDeclaration(declaration) override fun visitVariable(declaration: IrVariable, data: Nothing?) = visitVariable(declaration) fun visitEnumEntry(declaration: IrEnumEntry) = visitDeclaration(declaration) override fun visitEnumEntry(declaration: IrEnumEntry, data: Nothing?) = visitEnumEntry(declaration) fun visitAnonymousInitializer(declaration: IrAnonymousInitializer) = visitDeclaration(declaration) override fun visitAnonymousInitializer(declaration: IrAnonymousInitializer, data: Nothing?) = visitAnonymousInitializer(declaration) fun visitTypeParameter(declaration: IrTypeParameter) = visitDeclaration(declaration) override fun visitTypeParameter(declaration: IrTypeParameter, data: Nothing?) = visitTypeParameter(declaration) fun visitValueParameter(declaration: IrValueParameter) = visitDeclaration(declaration) override fun visitValueParameter(declaration: IrValueParameter, data: Nothing?) = visitValueParameter(declaration) fun visitTypeAlias(declaration: IrTypeAlias) = visitDeclaration(declaration) override fun visitTypeAlias(declaration: IrTypeAlias, data: Nothing?) = visitTypeAlias(declaration) fun visitBody(body: IrBody) = visitElement(body) override fun visitBody(body: IrBody, data: Nothing?) = visitBody(body) fun visitExpressionBody(body: IrExpressionBody) = visitBody(body) override fun visitExpressionBody(body: IrExpressionBody, data: Nothing?) = visitExpressionBody(body) fun visitBlockBody(body: IrBlockBody) = visitBody(body) override fun visitBlockBody(body: IrBlockBody, data: Nothing?) = visitBlockBody(body) fun visitSyntheticBody(body: IrSyntheticBody) = visitBody(body) override fun visitSyntheticBody(body: IrSyntheticBody, data: Nothing?) = visitSyntheticBody(body) fun visitSuspendableExpression(expression: IrSuspendableExpression) = visitExpression(expression) override fun visitSuspendableExpression(expression: IrSuspendableExpression, data: Nothing?) = visitSuspendableExpression(expression) fun visitSuspensionPoint(expression: IrSuspensionPoint) = visitExpression(expression) override fun visitSuspensionPoint(expression: IrSuspensionPoint, data: Nothing?) = visitSuspensionPoint(expression) fun visitExpression(expression: IrExpression) = visitElement(expression) override fun visitExpression(expression: IrExpression, data: Nothing?) = visitExpression(expression) fun visitConst(expression: IrConst<*>) = visitExpression(expression) override fun visitConst(expression: IrConst<*>, data: Nothing?) = visitConst(expression) fun visitConstantValue(expression: IrConstantValue) = visitExpression(expression) override fun visitConstantValue(expression: IrConstantValue, data: Nothing?) = visitConstantValue(expression) fun visitConstantObject(expression: IrConstantObject) = visitConstantValue(expression) override fun visitConstantObject(expression: IrConstantObject, data: Nothing?) = visitConstantObject(expression) fun visitConstantPrimitive(expression: IrConstantPrimitive) = visitConstantValue(expression) override fun visitConstantPrimitive(expression: IrConstantPrimitive, data: Nothing?) = visitConstantPrimitive(expression) fun visitConstantArray(expression: IrConstantArray) = visitConstantValue(expression) override fun visitConstantArray(expression: IrConstantArray, data: Nothing?) = visitConstantArray(expression) fun visitVararg(expression: IrVararg) = visitExpression(expression) override fun visitVararg(expression: IrVararg, data: Nothing?) = visitVararg(expression) fun visitSpreadElement(spread: IrSpreadElement) = visitElement(spread) override fun visitSpreadElement(spread: IrSpreadElement, data: Nothing?) = visitSpreadElement(spread) fun visitContainerExpression(expression: IrContainerExpression) = visitExpression(expression) override fun visitContainerExpression(expression: IrContainerExpression, data: Nothing?) = visitContainerExpression(expression) fun visitComposite(expression: IrComposite) = visitContainerExpression(expression) override fun visitComposite(expression: IrComposite, data: Nothing?) = visitComposite(expression) fun visitBlock(expression: IrBlock) = visitContainerExpression(expression) override fun visitBlock(expression: IrBlock, data: Nothing?) = visitBlock(expression) fun visitStringConcatenation(expression: IrStringConcatenation) = visitExpression(expression) override fun visitStringConcatenation(expression: IrStringConcatenation, data: Nothing?) = visitStringConcatenation(expression) fun visitDeclarationReference(expression: IrDeclarationReference) = visitExpression(expression) override fun visitDeclarationReference(expression: IrDeclarationReference, data: Nothing?) = visitDeclarationReference(expression) fun visitSingletonReference(expression: IrGetSingletonValue) = visitDeclarationReference(expression) override fun visitSingletonReference(expression: IrGetSingletonValue, data: Nothing?) = visitSingletonReference(expression) fun visitGetObjectValue(expression: IrGetObjectValue) = visitSingletonReference(expression) override fun visitGetObjectValue(expression: IrGetObjectValue, data: Nothing?) = visitGetObjectValue(expression) fun visitGetEnumValue(expression: IrGetEnumValue) = visitSingletonReference(expression) override fun visitGetEnumValue(expression: IrGetEnumValue, data: Nothing?) = visitGetEnumValue(expression) fun visitValueAccess(expression: IrValueAccessExpression) = visitDeclarationReference(expression) override fun visitValueAccess(expression: IrValueAccessExpression, data: Nothing?) = visitValueAccess(expression) fun visitGetValue(expression: IrGetValue) = visitValueAccess(expression) override fun visitGetValue(expression: IrGetValue, data: Nothing?) = visitGetValue(expression) fun visitSetValue(expression: IrSetValue) = visitValueAccess(expression) override fun visitSetValue(expression: IrSetValue, data: Nothing?) = visitSetValue(expression) fun visitFieldAccess(expression: IrFieldAccessExpression) = visitDeclarationReference(expression) override fun visitFieldAccess(expression: IrFieldAccessExpression, data: Nothing?) = visitFieldAccess(expression) fun visitGetField(expression: IrGetField) = visitFieldAccess(expression) override fun visitGetField(expression: IrGetField, data: Nothing?) = visitGetField(expression) fun visitSetField(expression: IrSetField) = visitFieldAccess(expression) override fun visitSetField(expression: IrSetField, data: Nothing?) = visitSetField(expression) fun visitMemberAccess(expression: IrMemberAccessExpression<*>) = visitDeclarationReference(expression) override fun visitMemberAccess(expression: IrMemberAccessExpression<*>, data: Nothing?) = visitMemberAccess(expression) fun visitFunctionAccess(expression: IrFunctionAccessExpression) = visitMemberAccess(expression) override fun visitFunctionAccess(expression: IrFunctionAccessExpression, data: Nothing?) = visitFunctionAccess(expression) fun visitCall(expression: IrCall) = visitFunctionAccess(expression) override fun visitCall(expression: IrCall, data: Nothing?) = visitCall(expression) fun visitConstructorCall(expression: IrConstructorCall) = visitFunctionAccess(expression) override fun visitConstructorCall(expression: IrConstructorCall, data: Nothing?) = visitConstructorCall(expression) fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall) = visitFunctionAccess(expression) override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall, data: Nothing?) = visitDelegatingConstructorCall(expression) fun visitEnumConstructorCall(expression: IrEnumConstructorCall) = visitFunctionAccess(expression) override fun visitEnumConstructorCall(expression: IrEnumConstructorCall, data: Nothing?) = visitEnumConstructorCall(expression) fun visitGetClass(expression: IrGetClass) = visitExpression(expression) override fun visitGetClass(expression: IrGetClass, data: Nothing?) = visitGetClass(expression) fun visitCallableReference(expression: IrCallableReference<*>) = visitMemberAccess(expression) override fun visitCallableReference(expression: IrCallableReference<*>, data: Nothing?) = visitCallableReference(expression) fun visitFunctionReference(expression: IrFunctionReference) = visitCallableReference(expression) override fun visitFunctionReference(expression: IrFunctionReference, data: Nothing?) = visitFunctionReference(expression) fun visitPropertyReference(expression: IrPropertyReference) = visitCallableReference(expression) override fun visitPropertyReference(expression: IrPropertyReference, data: Nothing?) = visitPropertyReference(expression) fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference) = visitCallableReference(expression) override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference, data: Nothing?) = visitLocalDelegatedPropertyReference(expression) fun visitRawFunctionReference(expression: IrRawFunctionReference) = visitDeclarationReference(expression) override fun visitRawFunctionReference(expression: IrRawFunctionReference, data: Nothing?) = visitRawFunctionReference(expression) fun visitFunctionExpression(expression: IrFunctionExpression) = visitExpression(expression) override fun visitFunctionExpression(expression: IrFunctionExpression, data: Nothing?) = visitFunctionExpression(expression) fun visitClassReference(expression: IrClassReference) = visitDeclarationReference(expression) override fun visitClassReference(expression: IrClassReference, data: Nothing?) = visitClassReference(expression) fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall) = visitExpression(expression) override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall, data: Nothing?) = visitInstanceInitializerCall(expression) fun visitTypeOperator(expression: IrTypeOperatorCall) = visitExpression(expression) override fun visitTypeOperator(expression: IrTypeOperatorCall, data: Nothing?) = visitTypeOperator(expression) fun visitWhen(expression: IrWhen) = visitExpression(expression) override fun visitWhen(expression: IrWhen, data: Nothing?) = visitWhen(expression) fun visitBranch(branch: IrBranch) = visitElement(branch) override fun visitBranch(branch: IrBranch, data: Nothing?) = visitBranch(branch) fun visitElseBranch(branch: IrElseBranch) = visitBranch(branch) override fun visitElseBranch(branch: IrElseBranch, data: Nothing?) = visitElseBranch(branch) fun visitLoop(loop: IrLoop) = visitExpression(loop) override fun visitLoop(loop: IrLoop, data: Nothing?) = visitLoop(loop) fun visitWhileLoop(loop: IrWhileLoop) = visitLoop(loop) override fun visitWhileLoop(loop: IrWhileLoop, data: Nothing?) = visitWhileLoop(loop) fun visitDoWhileLoop(loop: IrDoWhileLoop) = visitLoop(loop) override fun visitDoWhileLoop(loop: IrDoWhileLoop, data: Nothing?) = visitDoWhileLoop(loop) fun visitTry(aTry: IrTry) = visitExpression(aTry) override fun visitTry(aTry: IrTry, data: Nothing?) = visitTry(aTry) fun visitCatch(aCatch: IrCatch) = visitElement(aCatch) override fun visitCatch(aCatch: IrCatch, data: Nothing?) = visitCatch(aCatch) fun visitBreakContinue(jump: IrBreakContinue) = visitExpression(jump) override fun visitBreakContinue(jump: IrBreakContinue, data: Nothing?) = visitBreakContinue(jump) fun visitBreak(jump: IrBreak) = visitBreakContinue(jump) override fun visitBreak(jump: IrBreak, data: Nothing?) = visitBreak(jump) fun visitContinue(jump: IrContinue) = visitBreakContinue(jump) override fun visitContinue(jump: IrContinue, data: Nothing?) = visitContinue(jump) fun visitReturn(expression: IrReturn) = visitExpression(expression) override fun visitReturn(expression: IrReturn, data: Nothing?) = visitReturn(expression) fun visitThrow(expression: IrThrow) = visitExpression(expression) override fun visitThrow(expression: IrThrow, data: Nothing?) = visitThrow(expression) fun visitDynamicExpression(expression: IrDynamicExpression) = visitExpression(expression) override fun visitDynamicExpression(expression: IrDynamicExpression, data: Nothing?) = visitDynamicExpression(expression) fun visitDynamicOperatorExpression(expression: IrDynamicOperatorExpression) = visitDynamicExpression(expression) override fun visitDynamicOperatorExpression(expression: IrDynamicOperatorExpression, data: Nothing?) = visitDynamicOperatorExpression(expression) fun visitDynamicMemberExpression(expression: IrDynamicMemberExpression) = visitDynamicExpression(expression) override fun visitDynamicMemberExpression(expression: IrDynamicMemberExpression, data: Nothing?) = visitDynamicMemberExpression(expression) fun visitErrorDeclaration(declaration: IrErrorDeclaration) = visitDeclaration(declaration) override fun visitErrorDeclaration(declaration: IrErrorDeclaration, data: Nothing?) = visitErrorDeclaration(declaration) fun visitErrorExpression(expression: IrErrorExpression) = visitExpression(expression) override fun visitErrorExpression(expression: IrErrorExpression, data: Nothing?) = visitErrorExpression(expression) fun visitErrorCallExpression(expression: IrErrorCallExpression) = visitErrorExpression(expression) override fun visitErrorCallExpression(expression: IrErrorCallExpression, data: Nothing?) = visitErrorCallExpression(expression) }
183
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
17,322
kotlin
Apache License 2.0
src/main/kotlin/io/kjson/JSONDecimal.kt
pwall567
390,720,614
false
null
/* * @(#) JSONDecimal.kt * * kjson-core JSON Kotlin core functionality * Copyright (c) 2021, 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.kjson import java.math.BigDecimal /** * A JSON decimal value - that is, a JSON number that is not an integer. * * @author <NAME> */ class JSONDecimal(override val value: BigDecimal) : JSONNumberValue(), JSONPrimitive<BigDecimal> { constructor(str: String): this(BigDecimal(str)) constructor(long: Long): this(BigDecimal(long)) constructor(int: Int): this(BigDecimal(int)) override fun toJSON(): String = value.toString() override fun appendTo(a: Appendable) { a.append(value.toString()) } override fun isIntegral(): Boolean = value.scale() <= 0 || value.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0 override fun isLong(): Boolean = isIntegral() && value in MIN_LONG..MAX_LONG override fun isInt(): Boolean = isIntegral() && value in MIN_INT..MAX_INT override fun isShort(): Boolean = isIntegral() && value in MIN_SHORT..MAX_SHORT override fun isByte(): Boolean = isIntegral() && value in MIN_BYTE..MAX_BYTE override fun isULong(): Boolean = isIntegral() && value in BigDecimal.ZERO..MAX_ULONG override fun isUInt(): Boolean = isIntegral() && value in BigDecimal.ZERO..MAX_UINT override fun isUShort(): Boolean = isIntegral() && value in BigDecimal.ZERO..MAX_USHORT override fun isUByte(): Boolean = isIntegral() && value in BigDecimal.ZERO..MAX_UBYTE override fun isZero(): Boolean = value.compareTo(BigDecimal.ZERO) == 0 override fun isNegative(): Boolean = value < BigDecimal.ZERO override fun isPositive(): Boolean = value > BigDecimal.ZERO override fun isNotZero(): Boolean = value.compareTo(BigDecimal.ZERO) != 0 override fun isNotNegative(): Boolean = value >= BigDecimal.ZERO override fun isNotPositive(): Boolean = value <= BigDecimal.ZERO override fun toDouble(): Double = value.toDouble() override fun toFloat(): Float = value.toFloat() override fun toLong(): Long = value.toLong() override fun toInt(): Int = value.toInt() override fun toChar(): Char = value.toChar() override fun toShort(): Short = value.toShort() override fun toByte(): Byte = value.toByte() override fun toDecimal(): BigDecimal = value override fun toULong(): ULong = value.toLong().toULong() override fun toUInt(): UInt = value.toInt().toUInt() override fun toUShort(): UShort = value.toInt().toUShort() override fun toUByte(): UByte = value.toInt().toUByte() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is JSONNumberValue) return false return when (other) { is JSONInt -> value.compareTo(BigDecimal(other.value)) == 0 is JSONLong -> value.compareTo(BigDecimal(other.value)) == 0 is JSONDecimal -> value.compareTo(other.value) == 0 } } override fun hashCode(): Int = value.toInt() override fun toString(): String = toJSON() companion object { val ZERO = JSONDecimal(BigDecimal.ZERO) private val MIN_LONG = BigDecimal(Long.MIN_VALUE) private val MAX_LONG = BigDecimal(Long.MAX_VALUE) private val MIN_INT = BigDecimal(Int.MIN_VALUE) private val MAX_INT = BigDecimal(Int.MAX_VALUE) private val MIN_SHORT = BigDecimal(Short.MIN_VALUE.toInt()) private val MAX_SHORT = BigDecimal(Short.MAX_VALUE.toInt()) private val MIN_BYTE = BigDecimal(Byte.MIN_VALUE.toInt()) private val MAX_BYTE = BigDecimal(Byte.MAX_VALUE.toInt()) private val MAX_ULONG = MAX_LONG * BigDecimal(2) + BigDecimal.ONE private val MAX_UINT = BigDecimal(UInt.MAX_VALUE.toLong()) private val MAX_USHORT = BigDecimal(UShort.MAX_VALUE.toInt()) private val MAX_UBYTE = BigDecimal(UByte.MAX_VALUE.toInt()) fun of(d: BigDecimal): JSONDecimal = if (d == BigDecimal.ZERO) ZERO else JSONDecimal(d) } }
0
null
0
1
61fb20ee49ac5b83667c35b301337e66673f6e8e
5,117
kjson-core
MIT License
src/main/kotlin/com/aemtools/index/search/AemComponentSearch.kt
iannovic
107,144,305
true
{"Kotlin": 574047, "HTML": 14948, "Java": 4019, "Lex": 3652}
package com.aemtools.index.search import com.aemtools.index.AemComponentClassicDialogIndex import com.aemtools.index.AemComponentDeclarationIndex import com.aemtools.index.AemComponentTouchUIDialogIndex import com.aemtools.index.model.AemComponentClassicDialogDefinition import com.aemtools.index.model.AemComponentDefinition import com.aemtools.index.model.AemComponentTouchUIDialogDefinition import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.indexing.FileBasedIndex /** * Search functionality related to aem components. * * @author <NAME> */ object AemComponentSearch { /** * Find all aem component declarations present in the project. * * @param project the project * @return list of aem component declarations */ fun allComponentDeclarations(project: Project): List<AemComponentDefinition> { val fbi = FileBasedIndex.getInstance() val keys = fbi.getAllKeys(AemComponentDeclarationIndex.AEM_COMPONENT_DECLARATION_INDEX_ID, project) return keys.flatMap { fbi.getValues( AemComponentDeclarationIndex.AEM_COMPONENT_DECLARATION_INDEX_ID, it, GlobalSearchScope.projectScope(project)) }.filterNotNull() } /** * Find component by resource type. * Resource type string may be of full path e.g. * * `/app/myapp/components/component` * * or of "not full" path e.g. * * `myapp/components/component` * * or of "project relative" path e.g. * * `components/component` * * @param resourceType the resource type string * @param project the project * @return component definition or *null* if no component was found */ fun findByResourceType(resourceType: String, project: Project): AemComponentDefinition? = allComponentDeclarations(project).find( resourceType.let { typeToFind -> if (typeToFind.startsWith("/apps/")) { { definition: AemComponentDefinition -> definition.resourceType() == typeToFind } } else { { definition: AemComponentDefinition -> definition.resourceType().let { it.substringAfter("/apps/") == typeToFind || it.substringAfter("/apps/") .substringAfter("/") == typeToFind } } } } ) /** * Find classic dialog definition by resource type. * * @param resourceType resource type string * @param project the project * @return classic dialog for given resource type, *null* if no dialog was found */ fun findClassicDialogByResourceType(resourceType: String, project: Project): AemComponentClassicDialogDefinition? = FileBasedIndex.getInstance() .getValues( AemComponentClassicDialogIndex.AEM_COMPONENT_CLASSIC_DIALOG_INDEX_ID, resourceType, GlobalSearchScope.projectScope(project)) .firstOrNull() /** * Find touch ui dialog definition by component's resource type. * * @param resourceType resource type string * @param project the project * @return touch ui dialog for given resource type, *null* if no dialog was found */ fun findTouchUIDialogByResourceType(resourceType: String, project: Project): AemComponentTouchUIDialogDefinition? = FileBasedIndex.getInstance() .getValues( AemComponentTouchUIDialogIndex.AEM_COMPONENT_TOUCH_UI_DIALOG_INDEX, resourceType, GlobalSearchScope.projectScope(project)) .firstOrNull() }
0
Kotlin
0
0
d9c1558872fd5e32f18e0bab0afa8f4495da95b0
3,941
aemtools
MIT License
http4k-server/jetty11/src/main/kotlin/org/http4k/server/jetty11.kt
http4k
86,003,479
false
null
package org.http4k.server import org.eclipse.jetty.server.Server import org.http4k.core.HttpHandler import org.http4k.server.ServerConfig.StopMode import org.http4k.server.ServerConfig.StopMode.Graceful import org.http4k.server.ServerConfig.StopMode.Immediate import org.http4k.server.ServerConfig.UnsupportedStopMode import org.http4k.sse.SseHandler import org.http4k.websocket.WsHandler class Jetty(private val port: Int, override val stopMode: StopMode, private val server: Server) : PolyServerConfig { constructor(port: Int = 8000) : this(port, defaultStopMode) constructor(port: Int = 8000, stopMode: StopMode) : this(port, stopMode, http(port)) constructor(port: Int = 8000, server: Server) : this(port, defaultStopMode, server) constructor(port: Int, vararg inConnectors: ConnectorBuilder) : this(port, defaultStopMode, *inConnectors) constructor(port: Int, stopMode: StopMode, vararg inConnectors: ConnectorBuilder) : this( port, stopMode, Server().apply { inConnectors.forEach { addConnector(it(this)) } }) init { when (stopMode) { is Graceful -> server.apply { stopTimeout = stopMode.timeout.toMillis() } is Immediate -> throw UnsupportedStopMode(stopMode) } } override fun toServer(http: HttpHandler?, ws: WsHandler?, sse: SseHandler?): Http4kServer { http?.let { server.insertHandler(http.toJettyHandler(stopMode is Graceful)) } sse?.let { server.insertHandler(sse.toJettySseHandler()) } ws?.let { server.insertHandler(ws.toJettyWsHandler()) } return object : Http4kServer { override fun start(): Http4kServer = apply { server.start() } override fun stop(): Http4kServer = apply { server.stop() } override fun port(): Int = if (port > 0) port else server.uri.port } } }
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
1,866
http4k
Apache License 2.0
net.akehurst.language/agl-processor/src/commonTest/kotlin/agl/parser/scannerless/leftAndRightRecursive/test_bodmas2_WS.kt
dhakehurst
197,245,665
false
null
/** * Copyright (C) 2018 Dr. <NAME> (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.language.parser.scannerless.choicePriority import net.akehurst.language.agl.runtime.structure.RuntimeRuleChoiceKind import net.akehurst.language.api.parser.ParseFailedException import net.akehurst.language.agl.runtime.structure.RuntimeRuleItem import net.akehurst.language.agl.runtime.structure.RuntimeRuleItemKind import net.akehurst.language.agl.runtime.structure.RuntimeRuleSetBuilder import net.akehurst.language.parser.scannerless.test_ScannerlessParserAbstract import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class test_OperatorPrecedence : test_ScannerlessParserAbstract() { // S = expr ; // expr = var < bool < group < div < mul < add < sub ; // sub = expr '-' expr ; // add = expr '+' expr ; // mul = expr '*' expr ; // div = expr '/' expr ; // group = '(' expr ')' ; // bool = 'true' | 'false' ; // var = "[a-zA-Z]+" ; // WS = "\s+" ; private fun S(): RuntimeRuleSetBuilder { val b = RuntimeRuleSetBuilder() val r_expr = b.rule("expr").build() val r_var = b.rule("var").concatenation(b.pattern("[a-zA-Z]+")) val r_bool = b.rule("bool").choice(RuntimeRuleChoiceKind.LONGEST_PRIORITY, b.literal("true"), b.literal("false")) val r_group = b.rule("group").concatenation(b.literal("("), r_expr, b.literal(")")) val r_div = b.rule("div").concatenation(r_expr, b.literal("/"), r_expr) val r_mul = b.rule("mul").concatenation(r_expr, b.literal("*"), r_expr) val r_add = b.rule("add").concatenation(r_expr, b.literal("+"), r_expr) val r_sub = b.rule("sub").concatenation(r_expr, b.literal("-"), r_expr) b.rule(r_expr).choice(RuntimeRuleChoiceKind.PRIORITY_LONGEST, r_var, r_bool, r_group, r_div, r_mul, r_add, r_sub) b.rule("S").concatenation(r_expr) b.rule("WS").skip(true).concatenation(b.pattern("\\s+")) return b } @Test fun empty_fails() { val rrb = this.S() val goal = "S" val sentence = "" val ex = assertFailsWith(ParseFailedException::class) { super.test(rrb, goal, sentence) } assertEquals(1, ex.location.line) assertEquals(1, ex.location.column) } @Test fun a() { val rrb = this.S() val goal = "S" val sentence = "a" val expected = """ S { expr { var { "[a-zA-Z]+" : 'a' } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun expr_true() { val rrb = this.S() val goal = "expr" val sentence = "true" val expected = """ expr { bool { 'true' } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun S_true() { val rrb = this.S() val goal = "S" val sentence = "true" val expected = """ S { expr { bool { 'true' } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun S_var() { val rrb = this.S() val goal = "S" val sentence = "var" val expected = """ S { expr { var { "[a-zA-Z]+" : 'var' } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun Og_a_Cg() { val rrb = this.S() val goal = "S" val sentence = "(a)" val expected = """ S { expr { group { '(' expr { var { "[a-zA-Z]+" : 'a' } } ')' } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_div_b() { val rrb = this.S() val goal = "S" val sentence = "a / b" val expected = """ S { expr { div { expr { var { "[a-zA-Z]+" : 'a' WS { "\s+" : ' ' } } } '/' WS { "\s+" : ' ' } expr { var { "[a-zA-Z]+" : 'b' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_mul_b() { val rrb = this.S() val goal = "S" val sentence = "a * b" val expected = """ S { expr { mul { expr { var { "[a-zA-Z]+" : 'a' WS { "\s+" : ' ' } } } '*' WS { "\s+" : ' ' } expr { var { "[a-zA-Z]+" : 'b' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_add_b() { val rrb = this.S() val goal = "S" val sentence = "a + b" val expected = """ S { expr { add { expr { var { "[a-zA-Z]+" : 'a' WS { "\s+" : ' ' } } } '+' WS { "\s+" : ' ' } expr { var { "[a-zA-Z]+" : 'b' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_sub_b() { val rrb = this.S() val goal = "S" val sentence = "a - b" val expected = """ S { expr { sub { expr { var { "[a-zA-Z]+" : 'a' WS { "\s+" : ' ' } } } '-' WS { "\s+" : ' ' } expr { var { "[a-zA-Z]+" : 'b' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_add_b_mul_c() { val rrb = this.S() val goal = "S" val sentence = "a+b*c" val expected = """ S { expr { add { expr { var { "[a-zA-Z]+" : 'a' } } '+' expr { mul { expr { var { "[a-zA-Z]+" : 'b' } } '*' expr { var { "[a-zA-Z]+" : 'c' } } } } } } } """.trimIndent() super.testStringResult(rrb, goal, sentence, expected) } @Test fun a_mul_b_add_c() { val rrb = this.S() val goal = "S" val sentence = "a*b+c" val expected = """ S { expr { add { expr { mul { expr { var { "[a-zA-Z]+" : 'a' } } '*' expr { var { "[a-zA-Z]+" : 'b' } } } } '+' expr { var { "[a-zA-Z]+" : 'c' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } @Test fun a_add_b_add_c_add_d() { val rrb = this.S() val goal = "S" val sentence = "a+b+c+c+d" val expected = """ S { expr { add { expr { mul { expr { var { "[a-zA-Z]+" : 'a' } } '*' expr { var { "[a-zA-Z]+" : 'b' } } } } '+' expr { var { "[a-zA-Z]+" : 'c' } } } } } """.trimIndent() super.testStringResult(rrb, goal, sentence, expected) } @Test fun a_add_b_add_c_add_d_add_e_add_f() { val rrb = this.S() val goal = "S" val sentence = "a+b+c+d+e+f" val expected = """ S { expr { add { expr { mul { expr { var { "[a-zA-Z]+" : 'a' } } '*' expr { var { "[a-zA-Z]+" : 'b' } } } } '+' expr { var { "[a-zA-Z]+" : 'c' } } } } } """.trimIndent() super.testStringResult(rrb, goal, sentence, expected) } @Test fun Og_a_add_b_Cg_mul_c() { val rrb = this.S() val goal = "S" val sentence = "(a+b)*c" val expected = """ S { expr { mul { expr { group { '(' expr { add { expr { var { "[a-zA-Z]+" : 'a' } } '+' expr { var { "[a-zA-Z]+" : 'b' } } } } ')' } } '*' expr { var { "[a-zA-Z]+" : 'c' } } } } } """.trimIndent() super.test(rrb, goal, sentence, expected) } }
2
null
5
36
c4a404149d165ea57220f978c5f2bde3ac6f14f3
9,808
net.akehurst.language
Apache License 2.0
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/utils/NameTables.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ir.backend.js.utils import org.jetbrains.kotlin.descriptors.DescriptorVisibilities.INTERNAL import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.backend.js.JsIrBackendContext import org.jetbrains.kotlin.ir.backend.js.JsLoweredDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.symbols.IrReturnableBlockSymbol import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.isUnit import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.js.common.isES5IdentifierPart import org.jetbrains.kotlin.js.common.isES5IdentifierStart import org.jetbrains.kotlin.js.common.isValidES5Identifier import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty import java.util.* import kotlin.collections.set import kotlin.math.abs abstract class NameScope { abstract fun isReserved(name: String): Boolean object EmptyScope : NameScope() { override fun isReserved(name: String): Boolean = false } } class NameTable<T>( val parent: NameScope = EmptyScope, val reserved: MutableSet<String> = mutableSetOf(), ) : NameScope() { val names = mutableMapOf<T, String>() private val suggestedNameLastIdx = mutableMapOf<String, Int>() override fun isReserved(name: String): Boolean { return parent.isReserved(name) || name in reserved } fun declareStableName(declaration: T, name: String) { names[declaration] = name reserved.add(name) } fun declareFreshName(declaration: T, suggestedName: String): String { val freshName = findFreshName(sanitizeName(suggestedName)) declareStableName(declaration, freshName) return freshName } private fun findFreshName(suggestedName: String): String { if (!isReserved(suggestedName)) return suggestedName var i = suggestedNameLastIdx[suggestedName] ?: 0 fun freshName() = suggestedName + "_" + i while (isReserved(freshName())) { i++ } suggestedNameLastIdx[suggestedName] = i return freshName() } } fun NameTable<IrDeclaration>.dump(): String = "Names: \n" + names.toList().joinToString("\n") { (declaration, name) -> val decl: FqName? = (declaration as IrDeclarationWithName).fqNameWhenAvailable val declRef = decl ?: declaration "--- $declRef => $name" } private const val RESERVED_MEMBER_NAME_SUFFIX = "_k$" fun Int.toJsIdentifier(): String { val first = ('a'.code + (this % 26)).toChar().toString() val other = this / 26 return if (other == 0) { first } else { first + other.toString(Character.MAX_RADIX) } } private fun List<IrType>.joinTypes(context: JsIrBackendContext): String { if (isEmpty()) { return "" } return joinToString("$", "$") { superType -> superType.asString(context) } } private fun IrFunction.findOriginallyContainingModule(): IrModuleFragment? { if (JsLoweredDeclarationOrigin.isBridgeDeclarationOrigin(origin)) { val thisSimpleFunction = this as? IrSimpleFunction ?: error("Bridge must be IrSimpleFunction") val bridgeFrom = thisSimpleFunction.overriddenSymbols.firstOrNull() ?: error("Couldn't find the overridden function for the bridge") return bridgeFrom.owner.findOriginallyContainingModule() } return (getPackageFragment() as? IrFile)?.module } fun calculateJsFunctionSignature(declaration: IrFunction, context: JsIrBackendContext): String { val declarationName = declaration.nameIfPropertyAccessor() ?: declaration.getJsNameOrKotlinName().asString() val nameBuilder = StringBuilder() nameBuilder.append(declarationName) if (declaration.visibility === INTERNAL && declaration.parentClassOrNull != null) { val containingModule = declaration.findOriginallyContainingModule() if (containingModule != null) { nameBuilder.append("_\$m_").append(containingModule.name.toString()) } } // TODO should we skip type parameters and use upper bound of type parameter when print type of value parameters? declaration.typeParameters.ifNotEmpty { nameBuilder.append("_\$t") forEach { typeParam -> nameBuilder.append("_").append(typeParam.name.asString()).append(typeParam.superTypes.joinTypes(context)) } } declaration.extensionReceiverParameter?.let { val superTypes = it.type.superTypes().joinTypes(context) nameBuilder.append("_r$${it.type.asString(context)}$superTypes") } declaration.valueParameters.ifNotEmpty { joinTo(nameBuilder, "") { val defaultValueSign = if (it.origin == JsLoweredDeclarationOrigin.JS_SHADOWED_DEFAULT_PARAMETER) "?" else "" val superTypes = it.type.superTypes().joinTypes(context) "_${it.type.asString(context)}$superTypes$defaultValueSign" } } declaration.returnType.let { // Return type is only used in signature for inline class and Unit types because // they are binary incompatible with supertypes. if (context.inlineClassesUtils.isTypeInlined(it) || it.isUnit()) { nameBuilder.append("_ret$${it.asString(context)}") } } val signature = abs(nameBuilder.toString().hashCode()).toString(Character.MAX_RADIX) // TODO: Use better hashCode val sanitizedName = sanitizeName(declarationName, withHash = false) return context.globalIrInterner.string("${sanitizedName}_$signature$RESERVED_MEMBER_NAME_SUFFIX") } fun jsFunctionSignature(declaration: IrFunction, context: JsIrBackendContext): String { require(!declaration.isStaticMethodOfClass) require(declaration.dispatchReceiverParameter != null) if (declaration.hasStableJsName(context)) { val declarationName = declaration.getJsNameOrKotlinName().asString() // TODO: Handle reserved suffix in FE require(!declarationName.endsWith(RESERVED_MEMBER_NAME_SUFFIX)) { "Function ${declaration.fqNameWhenAvailable} uses reserved name suffix \"$RESERVED_MEMBER_NAME_SUFFIX\"" } return declarationName } val declarationSignature = (declaration as? IrSimpleFunction)?.resolveFakeOverride() ?: declaration return calculateJsFunctionSignature(declarationSignature, context) } class LocalNameGenerator(val variableNames: NameTable<IrDeclaration>) : IrElementVisitorVoid { val localLoopNames = NameTable<IrLoop>() val localReturnableBlockNames = NameTable<IrReturnableBlock>() private val jumpableDeque: Deque<IrExpression> = LinkedList() override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitDeclaration(declaration: IrDeclarationBase) { super.visitDeclaration(declaration) if (declaration is IrDeclarationWithName) { variableNames.declareFreshName(declaration, declaration.name.asString()) } } override fun visitBreak(jump: IrBreak) { val loop = jump.loop if (loop.label == null && loop != jumpableDeque.firstOrNull()) { persistLoopName(SYNTHETIC_LOOP_LABEL, loop) } super.visitBreak(jump) } override fun visitContinue(jump: IrContinue) { val loop = jump.loop if (loop.label == null && loop != jumpableDeque.firstOrNull()) { persistLoopName(SYNTHETIC_LOOP_LABEL, loop) } super.visitContinue(jump) } override fun visitReturn(expression: IrReturn) { val targetSymbol = expression.returnTargetSymbol if (targetSymbol is IrReturnableBlockSymbol && !expression.isTheLastReturnStatementIn(targetSymbol)) { persistReturnableBlockName(SYNTHETIC_BLOCK_LABEL, targetSymbol.owner) } super.visitReturn(expression) } override fun visitWhen(expression: IrWhen) { jumpableDeque.push(expression) super.visitWhen(expression) jumpableDeque.pop() } override fun visitLoop(loop: IrLoop) { jumpableDeque.push(loop) super.visitLoop(loop) jumpableDeque.pop() val label = loop.label if (label != null) { persistLoopName(label, loop) } } private fun persistLoopName(label: String, loop: IrLoop) { localLoopNames.declareFreshName(loop, label) } private fun persistReturnableBlockName(label: String, loop: IrReturnableBlock) { localReturnableBlockNames.declareFreshName(loop, label) } } fun sanitizeName(name: String, withHash: Boolean = true): String { if (name.isValidES5Identifier()) return name if (name.isEmpty()) return "_" // 7 = _ + MAX_INT.toString(Character.MAX_RADIX) val builder = StringBuilder(name.length + if (withHash) 7 else 0) val first = name.first() builder.append(first.mangleIfNot(Char::isES5IdentifierStart)) for (idx in 1..name.lastIndex) { val c = name[idx] builder.append(c.mangleIfNot(Char::isES5IdentifierPart)) } return if (withHash) { "${builder}_${abs(name.hashCode()).toString(Character.MAX_RADIX)}" } else { builder.toString() } } fun IrDeclarationWithName.nameIfPropertyAccessor(): String? { if (this is IrSimpleFunction) { return when { this.correspondingPropertySymbol != null -> { val property = this.correspondingPropertySymbol!!.owner val name = property.getJsNameOrKotlinName().asString() val prefix = when (this) { property.getter -> "get_" property.setter -> "set_" else -> error("") } prefix + name } this.origin == JsLoweredDeclarationOrigin.BRIDGE_PROPERTY_ACCESSOR -> { this.getJsNameOrKotlinName().asString() .removePrefix("<") .removeSuffix(">") .replaceFirst("get-", "get_") .replaceFirst("set-", "set_") } else -> null } } return null } private inline fun Char.mangleIfNot(predicate: Char.() -> Boolean) = if (predicate()) this else '_' private const val SYNTHETIC_LOOP_LABEL = "\$l\$loop" private const val SYNTHETIC_BLOCK_LABEL = "\$l\$block"
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
10,825
kotlin
Apache License 2.0
whetstone/compiler/src/main/kotlin/com/freeletics/mad/whetstone/codegen/common/ComposeGenerator.kt
freeletics
375,363,637
false
null
package com.freeletics.mad.whetstone.codegen.common import com.freeletics.mad.whetstone.BaseData import com.freeletics.mad.whetstone.ComposeData import com.freeletics.mad.whetstone.codegen.Generator import com.freeletics.mad.whetstone.codegen.util.asComposeState import com.freeletics.mad.whetstone.codegen.util.composable import com.freeletics.mad.whetstone.codegen.util.compositionLocalProvider import com.freeletics.mad.whetstone.codegen.util.launch import com.freeletics.mad.whetstone.codegen.util.optInAnnotation import com.freeletics.mad.whetstone.codegen.util.propertyName import com.freeletics.mad.whetstone.codegen.util.rememberCoroutineScope import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier.PRIVATE internal val Generator<out BaseData>.composableName get() = "Whetstone${data.baseName}" internal class ComposeGenerator( override val data: ComposeData, ) : Generator<ComposeData>() { internal fun generate(): FunSpec { return FunSpec.builder(composableName) .addAnnotation(composable) .addAnnotation(optInAnnotation()) .addModifiers(PRIVATE) .addParameter("component", retainedComponentClassName) .addStatement("val providedValues = component.%L", providedValueSetPropertyName) .beginControlFlow("%T(*providedValues.toTypedArray()) {", compositionLocalProvider) .addStatement("val stateMachine = component.%L", data.stateMachine.propertyName) .addStatement("val state = stateMachine.%M()", asComposeState) .addStatement("val currentState = state.value") .beginControlFlow("if (currentState != null)") .addStatement("val scope = %M()", rememberCoroutineScope) .beginControlFlow("%L(currentState) { action ->", data.baseName) // dispatch: external method .addStatement("scope.%M { stateMachine.dispatch(action) }", launch) .endControlFlow() .endControlFlow() .endControlFlow() .build() } }
5
Kotlin
5
43
102987a931cebb7d2352a46f7b86c6a32b23982d
2,072
mad
Apache License 2.0
operator/src/main/kotlin/eu/glasskube/operator/apps/gitlab/dependent/GitlabIngress.kt
glasskube
528,301,150
false
null
package eu.glasskube.operator.apps.gitlab.dependent import eu.glasskube.kubernetes.api.model.extensions.ingress import eu.glasskube.kubernetes.api.model.extensions.ingressBackend import eu.glasskube.kubernetes.api.model.extensions.ingressPath import eu.glasskube.kubernetes.api.model.extensions.ingressRule import eu.glasskube.kubernetes.api.model.extensions.ingressRuleValue import eu.glasskube.kubernetes.api.model.extensions.spec import eu.glasskube.kubernetes.api.model.metadata import eu.glasskube.operator.apps.gitlab.Gitlab import eu.glasskube.operator.apps.gitlab.GitlabReconciler import eu.glasskube.operator.apps.gitlab.ingressName import eu.glasskube.operator.apps.gitlab.resourceLabels import eu.glasskube.operator.apps.gitlab.serviceName import eu.glasskube.operator.config.ConfigService import eu.glasskube.operator.generic.dependent.DependentIngress import io.javaoperatorsdk.operator.api.reconciler.Context import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent @KubernetesDependent(labelSelector = GitlabReconciler.SELECTOR) class GitlabIngress(configService: ConfigService) : DependentIngress<Gitlab>(configService) { override fun desired(primary: Gitlab, context: Context<Gitlab>) = ingress { metadata { name = primary.ingressName namespace = primary.metadata.namespace labels = primary.resourceLabels annotations = primary.defaultAnnotations + ("nginx.ingress.kubernetes.io/proxy-body-size" to "256m") } spec { ingressClassName = defaultIngressClassName rules = listOf( ingressRule { host = primary.spec.host http = ingressRuleValue( ingressPath( path = "/", pathType = "Prefix", backend = ingressBackend(primary.serviceName, "http") ) ) } ) } } }
23
Kotlin
4
57
0cb51187275bfc1f17d7386a790645604532c052
2,050
operator
MIT License
module/test/src/test/kotlin/com/github/jameshnsears/chance/data/repository/settings/RepositorySettingsUnitTest.kt
jameshnsears
725,514,594
false
{"Kotlin": 348231, "Shell": 678}
package com.github.jameshnsears.chance.data.repository.settings import com.github.jameshnsears.chance.data.repository.settings.mock.RepositorySettingsTestDouble import com.github.jameshnsears.chance.data.sample.settings.SampleSettingsStartup import com.github.jameshnsears.chance.utility.android.UtilityAndroidHelper import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Test class RepositorySettingsUnitTest : UtilityAndroidHelper() { @Test fun storeAndFetch() = runTest { val repositorySettingsTestDouble = RepositorySettingsTestDouble.getInstance() val settings = SampleSettingsStartup().settings repositorySettingsTestDouble.store(settings) val fetchedSettings = repositorySettingsTestDouble.fetch().first() assertEquals(settings, fetchedSettings) assertEquals(settings.tabRowChance, fetchedSettings.tabRowChance) assertEquals(settings.resize, fetchedSettings.resize) assertEquals(settings.rollIndexTime, fetchedSettings.rollIndexTime) assertEquals(settings.rollScore, fetchedSettings.rollScore) assertEquals(settings.diceTitle, fetchedSettings.diceTitle) assertEquals(settings.sideNumber, fetchedSettings.sideNumber) assertEquals(settings.behaviour, fetchedSettings.behaviour) assertEquals(settings.sideDescription, fetchedSettings.sideDescription) assertEquals(settings.sideSVG, fetchedSettings.sideSVG) assertEquals(settings.rollSound, fetchedSettings.rollSound) } }
1
Kotlin
0
0
a3ceaa3329de9f329ced7b2e02a8177890a8cc73
1,593
Chance
Apache License 2.0
xprl-efactura-model/src/main/kotlin/uk/co/xprl/efactura/IdentificationType.kt
xprl-gjf
534,729,919
false
{"Kotlin": 364167}
package ec.com.xprl.efactura /** * Valores por el campo <tt>tipoIdentificaciónComprador</tt>. * * * Según [SRI Ficha técnica v2.21](https://www.sri.gob.ec/o/sri-portlet-biblioteca-alfresco-internet/descargar/435ca226-b48d-4080-bb12-bf03a54527fd/FICHA%20TE%cc%81CNICA%20COMPROBANTES%20ELECTRO%cc%81NICOS%20ESQUEMA%20OFFLINE%20Versio%cc%81n%202.21.pdf), * Tabla 6. */ enum class IdentificationType(val value: Int) { RUC(4), CEDULA(5), PASAPORTE(6), CONSUMIDOR_FINAL(7), EXTERIOR(8); } /** * Extension property on [IdentityValue] to return the corresponding [IdentificationType] */ val IdentityValue.identificationType: IdentificationType get() = when(this) { is IdentityValue.RUC -> IdentificationType.RUC is IdentityValue.Cedula -> IdentificationType.CEDULA is IdentityValue.Pasaporte -> IdentificationType.PASAPORTE is IdentityValue.ConsumidorFinal -> IdentificationType.CONSUMIDOR_FINAL is IdentityValue.IdentificacionDelExterior -> IdentificationType.EXTERIOR }
0
Kotlin
0
1
58d75bd3bfb96e05ef919aebcec3336c3397c2fb
1,042
xprl-efactura
Apache License 2.0
app/src/main/java/org/covidwatch/android/data/positivediagnosis/PositiveDiagnosisRemoteSource.kt
covidwatchorg
261,834,815
false
{"Gradle": 3, "Java Properties": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "PlantUML": 2, "YAML": 3, "Proguard": 1, "Kotlin": 162, "INI": 1, "XML": 185, "Java": 2, "Protocol Buffer": 1}
package org.covidwatch.android.data.positivediagnosis import androidx.annotation.WorkerThread import com.google.common.io.BaseEncoding import com.google.gson.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody import okio.IOException import org.covidwatch.android.data.model.PositiveDiagnosis import org.covidwatch.android.exposurenotification.ServerException import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.io.OutputStream import java.lang.reflect.Type class PositiveDiagnosisRemoteSource( private val httpClient: OkHttpClient, private val keysDir: String ) { private val keyFilePattern = "/diag_keys/%s/keys_%s.pb" private val jsonType = "application/json; charset=utf-8".toMediaType() private val gson: Gson = GsonBuilder().registerTypeHierarchyAdapter( ByteArray::class.java, ByteArrayToBase64TypeAdapter() ).create() @WorkerThread fun diagnosisKey(dir: String, url: String): File? { val request = Request.Builder().url(url).build() return httpClient.newCall(request).execute().let { response -> if (!response.isSuccessful) throw ServerException(response.body?.string()) toFile(dir, url.split("/").last(), response.body) } } @WorkerThread private fun toFile(dir: String, filename: String, body: ResponseBody?): File? { body ?: return null return try { val name: String = String.format(keyFilePattern, dir, filename) val file = File(File(keysDir), name) val parent = file.parentFile if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory) { throw java.io.IOException("Directory '$parent' could not be created") } } var inputStream: InputStream? = null var outputStream: OutputStream? = null try { val fileReader = ByteArray(4096) var fileSizeDownloaded: Long = 0 inputStream = body.byteStream() outputStream = FileOutputStream(file) while (true) { val read: Int = inputStream.read(fileReader) if (read == -1) { break } outputStream.write(fileReader, 0, read) fileSizeDownloaded += read.toLong() } outputStream.flush() file } catch (e: IOException) { Timber.e(e) null } finally { inputStream?.close() outputStream?.close() } } catch (e: IOException) { Timber.e(e) null } } @WorkerThread fun uploadDiagnosisKeys( uploadUrl: String, diagnosis: PositiveDiagnosis ) { val body: RequestBody = gson.toJson(diagnosis).toRequestBody(jsonType) val request: Request = Request.Builder() .url(uploadUrl) .post(body) .build() httpClient.newCall(request).execute().also { response -> if (!response.isSuccessful) throw ServerException(response.body?.string()) } } private class ByteArrayToBase64TypeAdapter : JsonSerializer<ByteArray?>, JsonDeserializer<ByteArray?> { private val base64 = BaseEncoding.base64() @Throws(JsonParseException::class) override fun deserialize( json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext? ): ByteArray { return base64.decode(json.asString) } override fun serialize( src: ByteArray?, typeOfSrc: Type?, context: JsonSerializationContext? ): JsonElement { return JsonPrimitive(base64.encode(src)) } } }
11
Kotlin
7
11
a9d6fe16427f131fb8e5a5044db34cedb760c56e
4,152
covidwatch-android-en
Apache License 2.0
src/main/kotlin/pl/wendigo/chrome/api/io/Domain.kt
wendigo
83,794,841
false
null
package pl.wendigo.chrome.api.io import kotlinx.serialization.json.Json /** * Input/Output operations for streams produced by DevTools. * * @link Protocol [IO](https://chromedevtools.github.io/devtools-protocol/tot/IO) domain documentation. */ class IODomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain("IO", """Input/Output operations for streams produced by DevTools.""", connection) { /** * Close the stream, discard any temporary backing storage. * * @link Protocol [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) method documentation. */ fun close(input: CloseRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("IO.close", Json.encodeToJsonElement(CloseRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Read a chunk of the stream * * @link Protocol [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. */ fun read(input: ReadRequest): io.reactivex.rxjava3.core.Single<ReadResponse> = connection.request("IO.read", Json.encodeToJsonElement(ReadRequest.serializer(), input), ReadResponse.serializer()) /** * Return UUID of Blob object specified by a remote object id. * * @link Protocol [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. */ fun resolveBlob(input: ResolveBlobRequest): io.reactivex.rxjava3.core.Single<ResolveBlobResponse> = connection.request("IO.resolveBlob", Json.encodeToJsonElement(ResolveBlobRequest.serializer(), input), ResolveBlobResponse.serializer()) } /** * Represents request frame that can be used with [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) operation call. * * Close the stream, discard any temporary backing storage. * @link [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) method documentation. * @see [IODomain.close] */ @kotlinx.serialization.Serializable data class CloseRequest( /** * Handle of the stream to close. */ val handle: StreamHandle ) /** * Represents request frame that can be used with [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) operation call. * * Read a chunk of the stream * @link [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. * @see [IODomain.read] */ @kotlinx.serialization.Serializable data class ReadRequest( /** * Handle of the stream to read. */ val handle: StreamHandle, /** * Seek to the specified offset before reading (if not specificed, proceed with offset following the last read). Some types of streams may only support sequential reads. */ val offset: Int? = null, /** * Maximum number of bytes to read (left upon the agent discretion if not specified). */ val size: Int? = null ) /** * Represents response frame that is returned from [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) operation call. * Read a chunk of the stream * * @link [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. * @see [IODomain.read] */ @kotlinx.serialization.Serializable data class ReadResponse( /** * Set if the data is base64-encoded */ val base64Encoded: Boolean? = null, /** * Data that were read. */ val data: String, /** * Set if the end-of-file condition occured while reading. */ val eof: Boolean ) /** * Represents request frame that can be used with [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) operation call. * * Return UUID of Blob object specified by a remote object id. * @link [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. * @see [IODomain.resolveBlob] */ @kotlinx.serialization.Serializable data class ResolveBlobRequest( /** * Object id of a Blob object wrapper. */ val objectId: pl.wendigo.chrome.api.runtime.RemoteObjectId ) /** * Represents response frame that is returned from [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) operation call. * Return UUID of Blob object specified by a remote object id. * * @link [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. * @see [IODomain.resolveBlob] */ @kotlinx.serialization.Serializable data class ResolveBlobResponse( /** * UUID of the specified Blob. */ val uuid: String )
3
Kotlin
11
76
29b51e37ed509938e986d1ada8cc2b0c8461cb73
4,986
chrome-reactive-kotlin
Apache License 2.0
AUTH_SERVICE/src/main/kotlin/example/com/data/dto/response/ClusterDTO.kt
singhtwenty2
842,083,119
false
{"Kotlin": 95128, "JavaScript": 77547, "Java": 16073, "CSS": 2715, "HTML": 344}
package example.com.data.dto.response import kotlinx.serialization.Serializable @Serializable data class ClusterDTO( val clusterId: String, val clusterName: String, val description: String?, val isActive: String, val createdAt: String, val updatedAt: String )
0
Kotlin
0
1
c4c9ff211a61fe1a6f3d532cf9cd3e25e279a5c5
286
MetricX
MIT License
src/main/kotlin/com/cultureshock/madeleine/auth/client/kakao/KakaoClient.kt
DDD-Community
401,593,410
false
null
package com.cultureshock.madeleine.auth.client.kakao import com.cultureshock.madeleine.auth.client.AbstractClient import com.cultureshock.madeleine.auth.client.kakao.dto.response.KakaoUserLogout import com.cultureshock.madeleine.auth.client.kakao.dto.response.KakaoUserResponse import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import retrofit2.Response import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory @Component class KakaoClient( @Value("\${kakao.url.api}") private val kakaoUrl: String ): AbstractClient() { private val logger = LoggerFactory.getLogger(this::class.java) private lateinit var kakaoClientService: KakaoClientService init { val retrofit = Retrofit.Builder() .baseUrl(kakaoUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() this.kakaoClientService = retrofit.create(KakaoClientService::class.java) logger.info("KakaoClient Init::url=${kakaoUrl}") } fun getUserInfo(token: String): Response<KakaoUserResponse> { val accessToken = "Bearer $token" return isSuccessful(kakaoClientService.getUserInfo(accessToken), "KakaoClient::getUserInfo", logger) } fun signOutKakao(token: String): Response<KakaoUserLogout>{ val accessToken = "Bearer $token" return isSuccessful(kakaoClientService.signOut(accessToken),"KakaoClient::logoutUser", logger ) } }
2
Kotlin
1
4
fc07b03adafd42f7c9c11c8e135c197f24182df8
1,669
CultureShock-Server
MIT License
app/src/main/java/com/z3tecx/catinfo/api/ApiCat.kt
zildrs
185,106,034
false
{"Kotlin": 4342}
package com.z3tecx.catinfo.api import com.google.gson.annotations.SerializedName data class ApiCat ( @SerializedName("name") val name: String, @SerializedName("origin") val origin: String )
0
Kotlin
0
0
2b8e175356a25d00c347191b02386f1cd5639461
200
CatInfo
MIT License
app/src/test/java/hu/mostoha/mobile/android/huki/extensions/DurationExtensionsTest.kt
RolandMostoha
386,949,428
false
{"Kotlin": 1025137, "Java": 38751, "Shell": 308}
package hu.mostoha.mobile.android.huki.extensions import com.google.common.truth.Truth.assertThat import org.junit.Test import kotlin.time.Duration.Companion.milliseconds class DurationExtensionsTest { @Test fun `Given duration, when formatHoursAndMinutes, then formatted string returns`() { val duration = 3299693.milliseconds val formatted = duration.formatHoursAndMinutes() assertThat(formatted).isEqualTo("00:54") } }
0
Kotlin
1
9
92587e6dcc68d89b5ffb2afd8cdd3c0cc47fb7d4
464
HuKi-Android
The Unlicense
app/src/main/java/top/kengtion/dsaudiojetpack/ui/state/Song.kt
kengtion
615,635,048
false
null
package top.kengtion.dsaudiojetpack.ui.state data class Song( val path:String, val name:String, val artist:String, val albumId:Long, val albumName:String, val rate:Int, val type:String?, )
0
Kotlin
0
0
391fbbfb22bd3de2323313ee442540be3b2a2ed2
217
DSAudio-Jetpack
MIT License
adoptopenjdk-api-v3-updater/src/main/kotlin/net/adoptopenjdk/api/v3/mapping/upstream/UpstreamBinaryMapper.kt
johnoliver
196,358,547
true
{"Kotlin": 184956, "CSS": 992, "HTML": 988, "Shell": 734}
package net.adoptopenjdk.api.v3.mapping.upstream import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import net.adoptopenjdk.api.v3.dataSources.github.graphql.models.GHAsset import net.adoptopenjdk.api.v3.mapping.BinaryMapper import net.adoptopenjdk.api.v3.mapping.adopt.AdoptBinaryMapper import net.adoptopenjdk.api.v3.models.* import org.slf4j.LoggerFactory object UpstreamBinaryMapper : BinaryMapper() { @JvmStatic private val LOGGER = LoggerFactory.getLogger(this::class.java) private val EXCLUDES = listOf("sources", "debuginfo") suspend fun toBinaryList(assets: List<GHAsset>): List<Binary> { return assets .filter(this::isArchive) .filter({ !assetIsExcluded(it) }) .map { asset -> assetToBinary(asset) } .map { binaryList -> binaryList.await() } .filterNotNull() } private fun assetIsExcluded(asset: GHAsset) = EXCLUDES.any({ exclude -> asset.name.contains(exclude) }) private fun assetToBinary(asset: GHAsset): Deferred<Binary?> { return GlobalScope.async { try { //TODO add signature to Package val pack = Package(asset.name, asset.downloadUrl, asset.size, null, null) val os = getEnumFromFileName(asset.name, OperatingSystem.values()) val architecture = getEnumFromFileName(asset.name, Architecture.values()) val imageType = getEnumFromFileName(asset.name, ImageType.values(), ImageType.jdk) val updatedAt = getUpdatedTime(asset) Binary( pack, asset.downloadCount, updatedAt, null, null, HeapSize.normal, os, architecture, imageType, JvmImpl.hotspot, Project.jdk ) } catch (e: Exception) { LOGGER.error("Failed to parse binary data", e) return@async null } } } private fun isArchive(asset: GHAsset) = AdoptBinaryMapper.ARCHIVE_WHITELIST.filter { asset.name.endsWith(it) }.isNotEmpty() }
0
Kotlin
0
0
18f573a92cda1587e947cca5d78ed9ce09986974
2,373
openjdk-api-v3
Apache License 2.0
app/src/main/java/com/github/wanderwise_inc/app/MainActivity.kt
WanderWise-Inc
775,382,316
false
{"Kotlin": 366771}
package com.github.wanderwise_inc.app import android.Manifest import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.firebase.ui.auth.AuthUI import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract import com.github.wanderwise_inc.app.data.DirectionsRepository import com.github.wanderwise_inc.app.data.GoogleSignInLauncher import com.github.wanderwise_inc.app.data.ImageRepository import com.github.wanderwise_inc.app.data.ItineraryRepository import com.github.wanderwise_inc.app.data.ProfileRepository import com.github.wanderwise_inc.app.data.SignInRepository import com.github.wanderwise_inc.app.di.AppModule import com.github.wanderwise_inc.app.ui.navigation.graph.RootNavigationGraph import com.github.wanderwise_inc.app.ui.theme.WanderWiseTheme import com.github.wanderwise_inc.app.viewmodel.BottomNavigationViewModel import com.github.wanderwise_inc.app.viewmodel.CreateItineraryViewModel import com.github.wanderwise_inc.app.viewmodel.ItineraryViewModel import com.github.wanderwise_inc.app.viewmodel.ProfileViewModel import com.github.wanderwise_inc.app.viewmodel.UserLocationClient import com.google.android.gms.location.LocationServices import com.google.firebase.auth.FirebaseAuth import com.google.firebase.storage.FirebaseStorage import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { private lateinit var firebaseAuth: FirebaseAuth private lateinit var firebaseStorage: FirebaseStorage private lateinit var imageRepository: ImageRepository private lateinit var itineraryRepository: ItineraryRepository private lateinit var directionsRepository: DirectionsRepository private lateinit var profileRepository: ProfileRepository private lateinit var signInRepository: SignInRepository private lateinit var bottomNavigationViewModel: BottomNavigationViewModel private lateinit var createItineraryViewModel: CreateItineraryViewModel private lateinit var itineraryViewModel: ItineraryViewModel private lateinit var profileViewModel: ProfileViewModel private lateinit var googleSignInLauncher: GoogleSignInLauncher private lateinit var navController: NavHostController private val providers by lazy { listOf(AuthUI.IdpConfig.GoogleBuilder().build()) } private val imageLauncher by lazy { registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res -> if (res.resultCode == RESULT_OK) { res.data?.data?.let { imageRepository.setCurrentFile(it) Log.d("STORE IMAGE", "CURRENT FILE SELECTED") } } } } private val signInLauncher by lazy { registerForActivityResult(FirebaseAuthUIActivityResultContract()) { res -> if (res.resultCode != RESULT_OK) throw Exception("User unsuccessful sign in") lifecycleScope.launch { signInRepository.signIn(navController, profileViewModel, firebaseAuth.currentUser) } } } private val signInIntent by lazy { AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build() } private val locationClient by lazy { UserLocationClient( applicationContext, LocationServices.getFusedLocationProviderClient(applicationContext)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) init() setContent { WanderWiseTheme { Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { navController = rememberNavController() RootNavigationGraph( googleSignInLauncher, profileViewModel, itineraryViewModel, createItineraryViewModel, bottomNavigationViewModel, imageRepository, navController, firebaseAuth) } } } } private fun init() { requestPermissions() AppModule.initialize(imageLauncher, signInLauncher, signInIntent, locationClient) firebaseAuth = AppModule.firebaseAuth firebaseStorage = AppModule.firebaseStorage initializeRepositories() initializeViewModels() googleSignInLauncher = AppModule.googleSignInLauncher } private fun requestPermissions() { ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), 0) } private fun initializeRepositories() { imageRepository = AppModule.imageRepository itineraryRepository = AppModule.itineraryRepository directionsRepository = AppModule.directionsRepository profileRepository = AppModule.profileRepository signInRepository = AppModule.signInRepository } private fun initializeViewModels() { bottomNavigationViewModel = AppModule.bottomNavigationViewModel createItineraryViewModel = AppModule.createItineraryViewModel itineraryViewModel = AppModule.itineraryViewModel profileViewModel = AppModule.profileViewModel } }
8
Kotlin
0
1
418cd2e0015df86246be33742ab85e7f5bb86431
5,508
app
MIT License
app/src/main/java/com/github/wanderwise_inc/app/MainActivity.kt
WanderWise-Inc
775,382,316
false
{"Kotlin": 366771}
package com.github.wanderwise_inc.app import android.Manifest import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.firebase.ui.auth.AuthUI import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract import com.github.wanderwise_inc.app.data.DirectionsRepository import com.github.wanderwise_inc.app.data.GoogleSignInLauncher import com.github.wanderwise_inc.app.data.ImageRepository import com.github.wanderwise_inc.app.data.ItineraryRepository import com.github.wanderwise_inc.app.data.ProfileRepository import com.github.wanderwise_inc.app.data.SignInRepository import com.github.wanderwise_inc.app.di.AppModule import com.github.wanderwise_inc.app.ui.navigation.graph.RootNavigationGraph import com.github.wanderwise_inc.app.ui.theme.WanderWiseTheme import com.github.wanderwise_inc.app.viewmodel.BottomNavigationViewModel import com.github.wanderwise_inc.app.viewmodel.CreateItineraryViewModel import com.github.wanderwise_inc.app.viewmodel.ItineraryViewModel import com.github.wanderwise_inc.app.viewmodel.ProfileViewModel import com.github.wanderwise_inc.app.viewmodel.UserLocationClient import com.google.android.gms.location.LocationServices import com.google.firebase.auth.FirebaseAuth import com.google.firebase.storage.FirebaseStorage import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { private lateinit var firebaseAuth: FirebaseAuth private lateinit var firebaseStorage: FirebaseStorage private lateinit var imageRepository: ImageRepository private lateinit var itineraryRepository: ItineraryRepository private lateinit var directionsRepository: DirectionsRepository private lateinit var profileRepository: ProfileRepository private lateinit var signInRepository: SignInRepository private lateinit var bottomNavigationViewModel: BottomNavigationViewModel private lateinit var createItineraryViewModel: CreateItineraryViewModel private lateinit var itineraryViewModel: ItineraryViewModel private lateinit var profileViewModel: ProfileViewModel private lateinit var googleSignInLauncher: GoogleSignInLauncher private lateinit var navController: NavHostController private val providers by lazy { listOf(AuthUI.IdpConfig.GoogleBuilder().build()) } private val imageLauncher by lazy { registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res -> if (res.resultCode == RESULT_OK) { res.data?.data?.let { imageRepository.setCurrentFile(it) Log.d("STORE IMAGE", "CURRENT FILE SELECTED") } } } } private val signInLauncher by lazy { registerForActivityResult(FirebaseAuthUIActivityResultContract()) { res -> if (res.resultCode != RESULT_OK) throw Exception("User unsuccessful sign in") lifecycleScope.launch { signInRepository.signIn(navController, profileViewModel, firebaseAuth.currentUser) } } } private val signInIntent by lazy { AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build() } private val locationClient by lazy { UserLocationClient( applicationContext, LocationServices.getFusedLocationProviderClient(applicationContext)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) init() setContent { WanderWiseTheme { Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { navController = rememberNavController() RootNavigationGraph( googleSignInLauncher, profileViewModel, itineraryViewModel, createItineraryViewModel, bottomNavigationViewModel, imageRepository, navController, firebaseAuth) } } } } private fun init() { requestPermissions() AppModule.initialize(imageLauncher, signInLauncher, signInIntent, locationClient) firebaseAuth = AppModule.firebaseAuth firebaseStorage = AppModule.firebaseStorage initializeRepositories() initializeViewModels() googleSignInLauncher = AppModule.googleSignInLauncher } private fun requestPermissions() { ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), 0) } private fun initializeRepositories() { imageRepository = AppModule.imageRepository itineraryRepository = AppModule.itineraryRepository directionsRepository = AppModule.directionsRepository profileRepository = AppModule.profileRepository signInRepository = AppModule.signInRepository } private fun initializeViewModels() { bottomNavigationViewModel = AppModule.bottomNavigationViewModel createItineraryViewModel = AppModule.createItineraryViewModel itineraryViewModel = AppModule.itineraryViewModel profileViewModel = AppModule.profileViewModel } }
8
Kotlin
0
1
418cd2e0015df86246be33742ab85e7f5bb86431
5,508
app
MIT License
gto-support-db/src/main/java/org/ccci/gto/android/common/db/Table.kt
CruGlobal
30,609,844
false
null
package org.ccci.gto.android.common.db import android.annotation.SuppressLint import android.os.Parcelable import androidx.annotation.RestrictTo import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize @Parcelize @SuppressLint("SupportAnnotationUsage") data class Table<T : Any> internal constructor( @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val type: Class<T>, private val alias: String? = null, ) : Parcelable { companion object { @JvmStatic fun <T : Any> forClass(type: Class<T>) = Table(type) inline fun <reified T : Any> forClass() = forClass(T::class.java) } @Suppress("ktlint:standard:function-naming") fun `as`(alias: String?) = copy(alias = alias) fun field(field: String) = Expression.Field(this, field) fun <T2 : Any> join(target: Table<T2>) = Join.create<T, T2>(target) inline fun <reified T2 : Any> join() = join(forClass(T2::class.java)) @Transient @IgnoredOnParcel private var sqlPrefix: String? = null @Transient @IgnoredOnParcel private var sqlTable: String? = null internal fun sqlPrefix(dao: AbstractDao) = sqlPrefix ?: "${alias ?: dao.tableName(type)}.".also { sqlPrefix = it } internal fun sqlTable(dao: AbstractDao) = sqlTable ?: buildString { append(dao.tableName(type)) if (alias != null) append(" AS ").append(alias) }.also { sqlTable = it } }
4
null
2
9
e29637677cfa12aa1996c73e87431a2f7d84a026
1,409
android-gto-support
MIT License
compiler/testData/codegen/boxInline/anonymousObject/sam/kt17091.kt
JakeWharton
99,388,807
false
null
// FILE: 1.kt // FULL_JDK package test inline fun foo(value: String, crossinline s: () -> String): String { val x = { value } return java.util.concurrent.Callable(x).call() + { s() }() } // FILE: 2.kt import test.* fun box(): String { return foo("O") { "K" } }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
279
kotlin
Apache License 2.0
ktor-samples/you-kube/src/you/kube/Page.kt
cbeust
64,515,203
false
null
package you.kube import kotlinx.html.* import kotlinx.html.stream.* import org.jetbrains.ktor.application.* import org.jetbrains.ktor.content.* import org.jetbrains.ktor.http.* import org.jetbrains.ktor.locations.* import org.jetbrains.ktor.sessions.* import java.io.* fun ApplicationCall.respondHtml(versions: List<Version>, visibility: CacheControlVisibility, block: HTML.() -> Unit): Nothing { respond(HtmlContent(versions, visibility, block)) } fun ApplicationCall.respondDefaultHtml(versions: List<Version>, visibility: CacheControlVisibility, title: String = "You Kube", block: DIV.() -> Unit): Nothing { respondHtml(versions, visibility) { val session = sessionOrNull<Session>() head { title { +title } styleLink("http://yui.yahooapis.com/pure/0.6.0/pure-min.css") styleLink("http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css") styleLink(url(MainCss())) } body { div("pure-g") { div("sidebar pure-u-1 pure-u-md-1-4") { div("header") { div("brand-title") { +title } div("brand-tagline") { if (session != null) { +session.userId } } nav("nav") { ul("nav-list") { li("nav-item") { if (session == null) { a(classes = "pure-button", href = application.feature(Locations).href(Login())) { +"Login" } } else { a(classes = "pure-button", href = application.feature(Locations).href(Upload())) { +"Upload" } } } li("nav-item") { a(classes = "pure-button", href = application.feature(Locations).href(Index())) { +"Watch" } } } } } } div("content pure-u-1 pure-u-md-3-4") { block() } } } } } class HtmlContent(override val versions: List<Version>, visibility: CacheControlVisibility, val builder: HTML.() -> Unit) : Resource, StreamConsumer() { override val contentType: ContentType get() = ContentType.Text.Html.withCharset(Charsets.UTF_8) override val expires = null override val cacheControl = CacheControl.MaxAge(3600 * 24 * 7, mustRevalidate = true, visibility = visibility, proxyMaxAgeSeconds = null, proxyRevalidate = false) override val contentLength = null override val headers by lazy { super.headers } override fun stream(out: OutputStream) { with(out.bufferedWriter()) { append("<!DOCTYPE html>\n") appendHTML().html(builder) flush() } } }
0
null
0
1
8dc7ac666a336cba0f23a72cc31b8c0b14ad4f09
3,119
ktor
Apache License 2.0
aragog-common/src/main/kotlin/com/gongshw/aragog/common/configuration/AragogConstant.kt
gongshw
50,728,732
false
{"Java": 15467, "Kotlin": 7353, "Groovy": 2796}
/* * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. */ package com.gongshw.aragog.common.configuration; /** * @author gongshiwei */ object AragogConstant { const val LIST_PAGE_URL_DESTINATION_NAME = "ListPageUrl"; const val ARAGOG_BROKER_NAME = "AragogBroker"; }
1
Java
1
1
fe89456fefcd6d40c932b3554fa160fd46e86752
281
aragog
Apache License 2.0
game/ui/src/main/kotlin/de/gleex/pltcmd/game/ui/fragments/ElementUnitsFragment.kt
Baret
227,677,538
false
null
package de.gleex.pltcmd.game.ui.fragments import de.gleex.pltcmd.game.ui.strings.Format import de.gleex.pltcmd.game.ui.strings.FrontendString import de.gleex.pltcmd.game.ui.strings.extensions.toFrontendString import de.gleex.pltcmd.game.ui.strings.extensions.withFrontendString import de.gleex.pltcmd.model.elements.blueprint.CommandingElementBlueprint import de.gleex.pltcmd.model.elements.units.Units import org.hexworks.cobalt.databinding.api.binding.Binding import org.hexworks.cobalt.databinding.api.binding.bindTransform import org.hexworks.cobalt.databinding.api.value.ObservableValue import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.component.AttachedComponent import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.VBox import org.hexworks.zircon.api.data.Size /** * Shows a summary of the units contained in [superOrdinate]. */ class ElementUnitsFragment( private val superOrdinate: ObservableValue<CommandingElementBlueprint>, override val fragmentWidth: Int, val fragmentHeight: Int ) : BaseFragment { private val format: Format = Format.forWidth(fragmentWidth) private val elementName: FrontendString<CommandingElementBlueprint> = superOrdinate.toFrontendString(format) private val totalUnits: FrontendString<String> = superOrdinate.bindTransform { "Total units: ${it.new().totalUnits}" }.toFrontendString(format) private val unitSummary: Binding<Map<Units, Int>> = superOrdinate.bindTransform { superOrdinate -> superOrdinate .new() .allUnits .groupBy { unit -> unit.blueprint } .mapValues { it.value.size } } private val summaryItems: MutableList<AttachedComponent> = mutableListOf() override val root: Component = Components .vbox() .withPreferredSize(fragmentWidth, fragmentHeight) .build() .apply { val elementNameHeader = Components .header() .withPreferredSize(contentSize.withHeight(1)) .build() .apply { withFrontendString(elementName) } val totalUnitsLabel = Components .label() .withPreferredSize(contentSize.withHeight(2)) .build() .apply { withFrontendString(totalUnits) } addComponents( elementNameHeader, totalUnitsLabel, unitSummaryPanel(contentSize.withRelativeHeight(-(elementNameHeader.height + totalUnitsLabel.height))) ) } private fun unitSummaryPanel(size: Size): VBox { val vbox = Components .vbox() .withPreferredSize(size) .build() unitSummary .bindTransform { summaryMap -> with(summaryItems) { forEach { it.detach() } clear() } summaryMap .forEach { (blueprint, count) -> summaryItems.add( vbox.addComponent( Components .label() .withPreferredSize(vbox.contentSize.withHeight(1)) .build() .apply { withFrontendString(format, "${count.toString().padStart(3)}x ", blueprint) } ) ) } } return vbox } }
48
Kotlin
0
4
a76de4af242b5c1dd3b578d1797cbb753c3fc160
3,870
pltcmd
MIT License
ceplin/src/main/java/br/ufpe/cin/jonas/ceplin/ComplexEvent.kt
RxCEP
140,175,602
false
{"Kotlin": 31725}
package br.ufpe.cin.jonas.ceplin import io.reactivex.Observable import java.util.concurrent.TimeUnit class ComplexEvent(val observable: Observable<Pair<Any?, Int>>, val numberOfEvents: Int, val timespan: Long = 5, val timeUnit: TimeUnit = TimeUnit.SECONDS) { fun subscribe(onComplete: () -> Unit) { this.observable.buffer(timespan, timeUnit, numberOfEvents) .subscribe { bundle -> val events = bundle.listIterator() val values = mutableSetOf<Int>() for (item in events) { values.add(item.second) } if (values.count() == this.numberOfEvents) { onComplete() } } } fun <E> merge(eventStream: EventStream<E>): ComplexEvent { val merged = Observable.merge( this.observable, eventStream.observable.map { element -> Pair(element, numberOfEvents + 1) } ) return ComplexEvent(merged, numberOfEvents + 1) } }
0
Kotlin
1
1
404dc3cf3f3a038bb7a1211e516fca71a5bf7ea2
1,095
CEPlin
MIT License
app/src/main/java/ru/hse/miem/miemapp/domain/repositories/IProjectRepository.kt
LostImagin4tion
495,338,532
false
{"Kotlin": 213783}
package ru.hse.miem.miemapp.domain.repositories import ru.hse.miem.miemapp.domain.entities.ProjectExtended interface IProjectRepository { suspend fun getProjectById(id: Long): ProjectExtended suspend fun applyForVacancy(vacancyId: Long, aboutMe: String) }
0
Kotlin
0
1
b5ca63de13926338a99be254f1df4c4adb7a262f
265
MiemApp_android
Apache License 2.0
kPermission/src/iosMain/kotlin/io/github/kpermissions/handler/permissions/requestBlueToothPermission.kt
the-best-is-best
825,391,801
false
{"Kotlin": 45262, "HTML": 715, "Swift": 522}
package io.github.kpermissions.handler.permissions import platform.CoreBluetooth.CBCentralManager import platform.CoreBluetooth.CBCentralManagerDelegateProtocol import platform.CoreBluetooth.CBCentralManagerStatePoweredOn import platform.darwin.NSObject fun requestBlueToothPermission(onPermissionResult: (Boolean) -> Unit) { var centralManager: CBCentralManager? = null centralManager = CBCentralManager(delegate = object : NSObject(), CBCentralManagerDelegateProtocol { override fun centralManagerDidUpdateState(central: CBCentralManager) { when (central.state) { CBCentralManagerStatePoweredOn -> { onPermissionResult(true) // Bluetooth is powered on } else -> { onPermissionResult(false) // Bluetooth is either off or in an unknown state } } println("central state ${central.state.toInt()}") centralManager?.delegate = null // Remove delegate to avoid memory leaks centralManager = null } }, queue = null) }
0
Kotlin
0
0
83ff778f3acdaa9e51d8bca880972a1e9503ca8a
1,175
kPermissions
Apache License 2.0
library/library-common/src/main/java/com/fm/library/common/constants/module/FaceMsg.kt
Luo-DH
425,160,566
false
{"C++": 4599833, "C": 412084, "Java": 132679, "CMake": 95927, "Kotlin": 89758}
package com.fm.library.common.constants.module data class FaceMsg( val name: String, val imgUrl: String )
0
C++
0
2
343f948b68eabffb3ba05bb5b8488ecc5ac09caf
115
HelloFace-Android
Apache License 2.0
src/main/kotlin/mycorda/app/clock/PlatformTimer.kt
mycordaapp
466,482,462
false
null
package mycorda.app.clock /** * Some basic timer primitives that behave appropriately * depending on the OS / hardware */ object PlatformTimer { /** * Should match the granularity of the underlying * clock "tick" on the platform. The idea is to be able to tune * sleeps in tests efficiently. For example on the original PC the * clock ticker 18.2 times a second, so the min time to wait is approx 1000/18. Thank * fully modern computers it normally less than this is */ fun clockTick(): Long { val os = System.getProperty("os.name") val circleCI = "true" == System.getenv("CIRCLECI") // tune as required - it might need some more detailed analysis // of the underlying hardware return when (os) { "Mac OS X" -> 1 // :-) "Linux" -> { if (circleCI) 15 else 5 // currently tuned for CircleCI } else -> 20 } } fun sleepForTicks(ticks: Int) = Thread.sleep(clockTick() * ticks) /** * The wait delay to apply in tests before checking asserts. Current rule * is however many internal ticks are in the test case + a margin * of 2 ticks */ fun testDelayInTicks(ticksTaken: Int): Int = 2 + ticksTaken fun testDelayInMs(ticksTaken: Int): Long = testDelayInTicks(ticksTaken) * clockTick() } data class PlatformTick(private val ticks: Int) { fun ticks(): Int = ticks fun milliseconds(): Long = ticks * PlatformTimer.clockTick() companion object { fun of(ticks: Int): PlatformTick = PlatformTick(ticks) } }
0
Kotlin
0
0
d0a2508060090b6b69a8dbb6bec07d6f5186a44e
1,618
helpers
MIT License
compiler/testData/codegen/box/functions/invoke/invoke.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 invoke fun test1(predicate: (Int) -> Int, i: Int) = predicate(i) fun test2(predicate: (Int) -> Int, i: Int) = predicate.invoke(i) class Method { operator fun invoke(i: Int) = i } fun test3(method: Method, i: Int) = method.invoke(i) fun test4(method: Method, i: Int) = method(i) class Method2 {} operator fun Method2.invoke(s: String) = s fun test5(method2: Method2, s: String) = method2(s) fun box() : String { if (test1({ it }, 1) != 1) return "fail 1" if (test2({ it }, 2) != 2) return "fail 2" if (test3(Method(), 3) != 3) return "fail 3" if (test4(Method(), 4) != 4) return "fail 4" if (test5(Method2(), "s") != "s") return "fail 5" if (test1(Int::dec, 1) != 0) return "fail 6" if (test2(Int::dec, 1) != 0) return "fail 7" if (test1(fun(x: Int) = x - 1, 1) != 0) return "fail 8" return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
854
kotlin
Apache License 2.0
plugin-build/src/main/kotlin/io/sentry/android/gradle/instrumentation/ChainedInstrumentable.kt
getsentry
241,145,606
false
null
@file:Suppress("UnstableApiUsage") package io.sentry.android.gradle.instrumentation import com.android.build.api.instrumentation.ClassContext import java.util.LinkedList import org.objectweb.asm.ClassVisitor class ChainedInstrumentable( private val instrumentables: List<ClassInstrumentable> = emptyList() ) : ClassInstrumentable { override fun getVisitor( instrumentableContext: ClassContext, apiVersion: Int, originalVisitor: ClassVisitor, parameters: SpanAddingClassVisitorFactory.SpanAddingParameters ): ClassVisitor { // build a chain of visitors in order they are provided val queue = LinkedList(instrumentables) var prevVisitor = originalVisitor var visitor: ClassVisitor? = null while (queue.isNotEmpty()) { val instrumentable = queue.poll() visitor = if (instrumentable.isInstrumentable(instrumentableContext)) { instrumentable.getVisitor( instrumentableContext, apiVersion, prevVisitor, parameters ) } else { prevVisitor } prevVisitor = visitor } return visitor ?: originalVisitor } override fun isInstrumentable(data: ClassContext): Boolean = instrumentables.any { it.isInstrumentable(data) } override fun toString(): String { return "ChainedInstrumentable(instrumentables=" + "${instrumentables.joinToString(", ") { it.javaClass.simpleName }})" } }
39
Kotlin
32
99
054a2aa8c8da13553c8fad034b2cebb05e733092
1,600
sentry-android-gradle-plugin
MIT License
include-build/roborazzi-core/src/commonJvmMain/kotlin/com/github/takahirom/roborazzi/CaptureResults.kt
takahirom
594,307,070
false
{"Kotlin": 348437}
package com.github.takahirom.roborazzi import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.google.gson.annotations.SerializedName import java.io.File import java.io.FileReader import java.lang.reflect.Type data class CaptureResults( @SerializedName("summary") val resultSummary: ResultSummary, @SerializedName("results") val captureResults: List<CaptureResult> ) { fun toJson(): String { return gson.toJson(this) } class Tab( val title: String, val id: String, val contents: String ) fun toHtml(reportDirectoryPath: String): String { val resultTab = Tab( title = "Results", id = "results", contents = buildString { val recordedImages = captureResults.filterIsInstance<CaptureResult.Recorded>() val addedImages = captureResults.filterIsInstance<CaptureResult.Added>() val changedImages = captureResults.filterIsInstance<CaptureResult.Changed>() val unchangedImages = captureResults.filterIsInstance<CaptureResult.Unchanged>() append(resultSummary.toHtml()) append(buildTable("Recorded images", "recorded", recordedImages, reportDirectoryPath)) append(buildTable("Added images", "added", addedImages, reportDirectoryPath)) append(buildTable("Changed images", "changed", changedImages, reportDirectoryPath)) append(buildTable("Unchanged images", "unchanged", unchangedImages, reportDirectoryPath)) } ) val contextTabs = captureResults .flatMap { it.contextData.keys } .distinct() .map { key -> Tab( title = RoborazziReportConst.DefaultContextData.keyToTitle(key), id = key, contents = buildString { captureResults.groupBy { it.contextData[key]?.toString() ?: "undefined" } .toSortedMap(Comparator<String> { value1, value2 -> // show "undefined" and "null" at the end if (value1 == "undefined" || value2 == "null") { 1 } else if (value1 == "null" || value2 == "undefined") { -1 } else { value1.compareTo(value2) } }) .forEach { (value, results) -> append(buildTable(value, value, results, reportDirectoryPath)) } } ) } val tabs = listOf(resultTab) + contextTabs return buildString { append( "<div class=\"row\">\n" + "<div class=\"col s12\">\n" + "<ul class=\"tabs\">" ) tabs.forEachIndexed { tabIndex, tab -> // <li class="tab col s3"><a href="#test1">Test 1</a></li> val activeClass = if (tabIndex == 0) """class="active" """ else "" append("""<li class="tab col s3"><a $activeClass href="#${tab.id}">${tab.title}</a></li>""") } append("</ul>\n</div>") tabs.forEach { tab -> append("""<div id="${tab.id}" class="col s12" style="display: none;">${tab.contents}</div>""") } append("</div>") } } private fun buildTable( title: String, anchor: String, images: List<CaptureResult>, reportDirectoryPath: String ): String { fun File.pathFrom(reportDirectoryPath: String): String { val reportDirectory = File(reportDirectoryPath) val relativePath = relativeTo(reportDirectory) return relativePath.path } if (images.isEmpty()) return "" return buildString { append("<h3>$title (${images.size})</h3>") val fileNameClass = "flow-text col s3" val fileNameStyle = "word-wrap: break-word; word-break: break-all;" val imgClass = "col s7" val imgAttributes = "style=\"max-width: 100%; height: 100%; object-fit: cover;\" class=\"modal-trigger\"" append("<table class=\"highlight\" id=\"$anchor\">") append("<thead>") append("<tr class=\"row\">") append("<th class=\"$fileNameClass\" style=\"$fileNameStyle\">File Name</th>") append("<th class=\"$imgClass flow-text \">Image</th>") append("</tr>") append("</thead>") append("<tbody>") images.forEach { image -> append("<tr class=\"row\">") val contextData = if (image.contextData.isNotEmpty() && image.contextData.all { it.value.toString() != "null" && it.value.toString().isNotEmpty() }) { "<br>contextData:${image.contextData}" } else { "" } append("<td class=\"$fileNameClass\" style=\"$fileNameStyle\">${image.reportFile.name}$contextData</td>") append( "<td class=\"$imgClass\"><img $imgAttributes src=\"${ image.reportFile.pathFrom( reportDirectoryPath ) }\" data-alt=\"${image.reportFile.name}\" /></td>" ) append("</tr>") } append("</tbody>") append("</table>") } } companion object { val gson: Gson = GsonBuilder() .registerTypeAdapter(File::class.java, object : JsonSerializer<File>, JsonDeserializer<File> { override fun serialize( src: File?, typeOfSrc: Type?, context: JsonSerializationContext? ): JsonElement { val absolutePath = src?.absolutePath ?: return JsonNull.INSTANCE return JsonPrimitive(absolutePath) } override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): File { val path = json?.asString ?: throw JsonParseException("File path is null") return File(path) } }) .create() fun fromJsonFile(inputPath: String): CaptureResults { val jsonObject = JsonParser.parseString(FileReader(inputPath).readText()).asJsonObject return fromJson(jsonObject) } fun fromJson(jsonObject: JsonObject): CaptureResults { // Auto convert using Gson return gson.fromJson(jsonObject, CaptureResults::class.java) } fun from(results: List<CaptureResult>): CaptureResults { return CaptureResults( resultSummary = ResultSummary( total = results.size, recorded = results.count { it is CaptureResult.Recorded }, added = results.count { it is CaptureResult.Added }, changed = results.count { it is CaptureResult.Changed }, unchanged = results.count { it is CaptureResult.Unchanged } ), captureResults = results ) } } }
38
Kotlin
19
583
96e6bbe3c6265ce7c1da733a8c07ae50f63f3c83
6,918
roborazzi
Apache License 2.0
javascript/js-type-analysis/src/org/jetbrains/dukat/js/type/analysis/expression.kt
Kotlin
159,510,660
false
null
package org.jetbrains.dukat.js.type.analysis import org.jetbrains.dukat.astCommon.IdentifierEntity import org.jetbrains.dukat.js.type.constraint.Constraint import org.jetbrains.dukat.js.type.constraint.reference.ReferenceConstraint import org.jetbrains.dukat.js.type.constraint.composite.CompositeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.CallableConstraint import org.jetbrains.dukat.js.type.propertyOwner.PropertyOwner import org.jetbrains.dukat.js.type.constraint.immutable.resolved.BigIntTypeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.resolved.BooleanTypeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.resolved.NoTypeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.resolved.NumberTypeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.resolved.StringTypeConstraint import org.jetbrains.dukat.js.type.constraint.immutable.resolved.VoidTypeConstraint import org.jetbrains.dukat.js.type.constraint.properties.ClassConstraint import org.jetbrains.dukat.js.type.constraint.properties.FunctionConstraint import org.jetbrains.dukat.js.type.constraint.reference.call.CallArgumentConstraint import org.jetbrains.dukat.js.type.constraint.reference.call.CallResultConstraint import org.jetbrains.dukat.js.type.constraint.properties.ObjectConstraint import org.jetbrains.dukat.js.type.constraint.properties.PropertyOwnerConstraint import org.jetbrains.dukat.js.type.propertyOwner.Scope import org.jetbrains.dukat.panic.raiseConcern import org.jetbrains.dukat.tsmodel.ClassDeclaration import org.jetbrains.dukat.tsmodel.expression.ExpressionDeclaration import org.jetbrains.dukat.tsmodel.FunctionDeclaration import org.jetbrains.dukat.tsmodel.expression.BinaryExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.CallExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.ConditionalExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.NewExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.PropertyAccessExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.TypeOfExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.UnaryExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.BigIntLiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.BooleanLiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.LiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.NumericLiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.ObjectLiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.literal.StringLiteralExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.name.IdentifierExpressionDeclaration import org.jetbrains.dukat.tsmodel.expression.name.QualifierExpressionDeclaration fun FunctionDeclaration.addTo(owner: PropertyOwner) : FunctionConstraint? { return this.body?.let { val pathWalker = PathWalker() val versions = mutableListOf<FunctionConstraint.Overload>() do { val functionScope = Scope(owner) val parameterConstraints = MutableList(parameters.size) { i -> // Store constraints of parameters in scope, // and in parameter list (in case the variable is replaced) val parameterConstraint = CompositeConstraint(owner) functionScope[parameters[i].name] = parameterConstraint parameters[i].name to parameterConstraint } val returnTypeConstraints = it.calculateConstraints(functionScope, pathWalker) ?: VoidTypeConstraint versions.add(FunctionConstraint.Overload( returnConstraints = returnTypeConstraints, parameterConstraints = parameterConstraints )) } while (pathWalker.startNextPath()) val functionConstraint = FunctionConstraint(owner, versions) if (name != "") { owner[name] = functionConstraint } functionConstraint } } fun ClassDeclaration.addTo(owner: PropertyOwner, path: PathWalker) : ClassConstraint? { val className = name // Needed for smart cast return if(className is IdentifierEntity) { val classConstraint = ClassConstraint(owner) members.forEach { it.addToClass(classConstraint, path) } if (className.value != "") { owner[className.value] = classConstraint } classConstraint } else { raiseConcern("Cannot convert class with name of type <${className::class}>.") { null } } } fun BinaryExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { return when (operator) { // Assignments "=" -> { val rightConstraints = right.calculateConstraints(owner, path) owner[left, path] = rightConstraints rightConstraints } "-=", "*=", "/=", "%=", "**=", "&=", "^=", "|=", "<<=", ">>=", ">>>=" -> { right.calculateConstraints(owner, path) owner[left, path] = NumberTypeConstraint NumberTypeConstraint } // Non-assignments "&&", "||" -> { when (path.getNextDirection()) { PathWalker.Direction.Left -> { left.calculateConstraints(owner, path) //right isn't being evaluated } PathWalker.Direction.Right -> { left.calculateConstraints(owner, path) right.calculateConstraints(owner, path) } } } "-", "*", "/", "**", "%", "++", "--" -> { left.calculateConstraints(owner, path) += NumberTypeConstraint right.calculateConstraints(owner, path) += NumberTypeConstraint NumberTypeConstraint } "&", "|", "^", "<<", ">>", ">>>" -> { left.calculateConstraints(owner, path) right.calculateConstraints(owner, path) NumberTypeConstraint } "==", "===", "!=", "!==", "in", "instanceof" -> { left.calculateConstraints(owner, path) right.calculateConstraints(owner, path) BooleanTypeConstraint } ">", "<", ">=", "<=" -> { left.calculateConstraints(owner, path) += NumberTypeConstraint right.calculateConstraints(owner, path) += NumberTypeConstraint BooleanTypeConstraint } else -> { left.calculateConstraints(owner, path) right.calculateConstraints(owner, path) CompositeConstraint(owner, NoTypeConstraint) } } } fun UnaryExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { val operandConstraints = operand.calculateConstraints(owner, path) return when (operator) { "--", "++", "~" -> { operandConstraints += NumberTypeConstraint owner[operand, path] = NumberTypeConstraint NumberTypeConstraint } "-", "+" -> { operandConstraints += NumberTypeConstraint NumberTypeConstraint } "!" -> { BooleanTypeConstraint } else -> { CompositeConstraint(owner, NoTypeConstraint) } } } fun TypeOfExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { expression.calculateConstraints(owner, path) return StringTypeConstraint } fun CallExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { val callTargetConstraints = expression.calculateConstraints(owner, path) var callResultConstraint: Constraint = CallResultConstraint(owner, callTargetConstraints) val argumentConstraints = arguments.map { it.calculateConstraints(owner, path) } argumentConstraints.forEachIndexed { argumentNumber, arg -> arg += CallArgumentConstraint( owner, callTargetConstraints, argumentNumber ) } if (callTargetConstraints is CompositeConstraint) { callResultConstraint = CompositeConstraint(owner) //TODO add arguments to CallableConstraint callTargetConstraints += CallableConstraint(argumentConstraints.size, callResultConstraint) } return callResultConstraint } fun NewExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { val classConstraints = expression.calculateConstraints(owner, path) as PropertyOwnerConstraint //TODO add constraints for constructor call arguments.map { it.calculateConstraints(owner, path) } return ObjectConstraint( owner = owner, instantiatedClass = classConstraints ) } fun ConditionalExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { condition.calculateConstraints(owner, path) return when (path.getNextDirection()) { PathWalker.Direction.Left -> whenTrue.calculateConstraints(owner, path) PathWalker.Direction.Right -> whenFalse.calculateConstraints(owner, path) } } fun ObjectLiteralExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : ObjectConstraint { val obj = ObjectConstraint(owner) members.forEach { it.addTo(obj, path) } return obj } fun LiteralExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { return when (this) { is StringLiteralExpressionDeclaration -> StringTypeConstraint is NumericLiteralExpressionDeclaration -> NumberTypeConstraint is BigIntLiteralExpressionDeclaration -> BigIntTypeConstraint is BooleanLiteralExpressionDeclaration -> BooleanTypeConstraint is ObjectLiteralExpressionDeclaration -> this.calculateConstraints(owner, path) else -> raiseConcern("Unexpected literal expression type <${this::class}>") { CompositeConstraint(owner, NoTypeConstraint) } } } fun ExpressionDeclaration.calculateConstraints(owner: PropertyOwner, path: PathWalker) : Constraint { return when (this) { is FunctionDeclaration -> this.addTo(owner) ?: NoTypeConstraint is ClassDeclaration -> this.addTo(owner, path) ?: NoTypeConstraint is IdentifierExpressionDeclaration -> owner[this] ?: ReferenceConstraint(this.identifier, owner) is QualifierExpressionDeclaration -> owner[this, path] ?: CompositeConstraint(owner) is PropertyAccessExpressionDeclaration -> owner[this, path] ?: CompositeConstraint(owner) is BinaryExpressionDeclaration -> this.calculateConstraints(owner, path) is UnaryExpressionDeclaration -> this.calculateConstraints(owner, path) is TypeOfExpressionDeclaration -> this.calculateConstraints(owner, path) is CallExpressionDeclaration -> this.calculateConstraints(owner, path) is NewExpressionDeclaration -> this.calculateConstraints(owner, path) is ConditionalExpressionDeclaration -> this.calculateConstraints(owner, path) is LiteralExpressionDeclaration -> this.calculateConstraints(owner, path) else -> CompositeConstraint(owner, NoTypeConstraint) } }
244
null
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
11,451
dukat
Apache License 2.0
app/src/main/java/org/metabrainz/android/data/sources/api/entities/Track.kt
metabrainz
166,439,000
false
null
package org.metabrainz.android.model.entities import com.google.gson.annotations.SerializedName import org.metabrainz.android.model.mbentity.Recording class Track { @SerializedName("id") var mbid: String? = null var title: String? = null var position = 0 var recording: Recording? = null var length: Long = 0 val duration: String get() { val builder = StringBuilder() var seconds = length / 1000 val minutes = seconds / 60 seconds %= 60 builder.append(minutes).append(':') if (seconds < 10) builder.append('0') builder.append(seconds) return builder.toString() } }
20
null
32
98
89b89bf6c7df14bc4fd35240f05cfb6b87f91030
706
musicbrainz-android
Apache License 2.0
feature/video-thumbnail-grid-genre/src/main/java/io/filmtime/feature/video/thumbnail/grid/genre/VideoGridGenreNavigation.kt
moallemi
633,160,161
false
{"Kotlin": 522936, "Shell": 3102}
package io.filmtime.feature.video.thumbnail.grid.genre import androidx.lifecycle.SavedStateHandle import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.navArgument import io.filmtime.core.ui.navigation.DestinationRoute import io.filmtime.core.ui.navigation.composable import io.filmtime.data.model.VideoType private const val ROUTE_PATH = "genre-grid" private const val VIDEO_TYPE_ARG = "video_type" private const val GENRE_ID_ARG = "genre_id" private const val GENRE_NAME_ARG = "genre_name" fun NavGraphBuilder.videoThumbnailGridGenreScreen( rootRoute: DestinationRoute, onMovieClick: (DestinationRoute, tmdbId: Int) -> Unit, onShowClick: (DestinationRoute, tmdbId: Int) -> Unit, onBack: () -> Unit, ) { composable( route = "${rootRoute.route}/$ROUTE_PATH/{$VIDEO_TYPE_ARG}/{${GENRE_ID_ARG}}/{$GENRE_NAME_ARG}", arguments = listOf( navArgument(GENRE_ID_ARG) { type = NavType.LongType }, navArgument(VIDEO_TYPE_ARG) { type = NavType.EnumType(VideoType::class.java) }, navArgument(GENRE_NAME_ARG) { type = NavType.StringType }, ), ) { VideoThumbnailGridByGenreScreen( onMovieClick = { onMovieClick(rootRoute, it) }, onShowClick = { onShowClick(rootRoute, it) }, onBack = onBack, ) } } fun NavController.navigateVideoGridByGenre( rootRoute: DestinationRoute, genreId: Long, genreName: String, videoType: VideoType, ) { navigate("${rootRoute.route}/$ROUTE_PATH/$videoType/$genreId/$genreName") } internal class VideoThumbnailGridArgs( val videoType: VideoType, val genreId: Long, val genreName: String, ) { constructor(savedStateHandle: SavedStateHandle) : this( videoType = savedStateHandle[VIDEO_TYPE_ARG] ?: throw IllegalArgumentException("Video type not found"), genreId = savedStateHandle[GENRE_ID_ARG] ?: throw IllegalArgumentException("Genre Id not found"), genreName = savedStateHandle[GENRE_NAME_ARG] ?: throw IllegalArgumentException("Genre Name not found"), ) }
21
Kotlin
14
87
ad3eeed30bed20216a9fa12e34f06e43b70a74cc
2,111
Film-Time
MIT License
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/transformers/LLFirDesignatedExpectActualMatcherTransformer.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.low.level.api.fir.transformers import org.jetbrains.kotlin.analysis.low.level.api.fir.LLFirPhaseRunner import org.jetbrains.kotlin.analysis.low.level.api.fir.api.FirDeclarationDesignationWithFile import org.jetbrains.kotlin.analysis.low.level.api.fir.lazy.resolve.FirLazyBodiesCalculator import org.jetbrains.kotlin.analysis.low.level.api.fir.lazy.resolve.ResolveTreeBuilder import org.jetbrains.kotlin.analysis.low.level.api.fir.transformers.LLFirLazyTransformer.Companion.updatePhaseDeep import org.jetbrains.kotlin.analysis.low.level.api.fir.util.ensurePhase import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.expressions.FirStatement import org.jetbrains.kotlin.fir.resolve.ScopeSession import org.jetbrains.kotlin.fir.resolve.transformers.mpp.FirExpectActualMatcherTransformer internal class LLFirDesignatedExpectActualMatcherTransformer( private val designation: FirDeclarationDesignationWithFile, session: FirSession, scopeSession: ScopeSession, ) : LLFirLazyTransformer, FirExpectActualMatcherTransformer(session, scopeSession) { private val declarationTransformer = LLFirDeclarationTransformer(designation) override fun transformRegularClass(regularClass: FirRegularClass, data: Nothing?): FirStatement { return declarationTransformer.transformDeclarationContent(this, regularClass, data) { super.transformRegularClass(regularClass, data) as FirDeclaration } as FirStatement } override fun transformFile(file: FirFile, data: Nothing?): FirFile { return declarationTransformer.transformDeclarationContent(this, file, data) { super.transformFile(file, data) } as FirFile } override fun transformDeclaration(phaseRunner: LLFirPhaseRunner) { if (designation.declaration.resolvePhase >= FirResolvePhase.EXPECT_ACTUAL_MATCHING) return designation.declaration.ensurePhase(FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE) FirLazyBodiesCalculator.calculateLazyBodiesInside(designation) ResolveTreeBuilder.resolvePhase(designation.declaration, FirResolvePhase.EXPECT_ACTUAL_MATCHING) { phaseRunner.runPhaseWithCustomResolve(FirResolvePhase.EXPECT_ACTUAL_MATCHING) { designation.firFile.transform<FirFile, Nothing?>(this, null) } } declarationTransformer.ensureDesignationPassed() updatePhaseDeep(designation.declaration, FirResolvePhase.EXPECT_ACTUAL_MATCHING) ensureResolved(designation.declaration) ensureResolvedDeep(designation.declaration) } override fun ensureResolved(declaration: FirDeclaration) { when (declaration) { is FirSimpleFunction, is FirConstructor, is FirAnonymousInitializer -> declaration.ensurePhase(FirResolvePhase.EXPECT_ACTUAL_MATCHING) is FirProperty -> { declaration.ensurePhase(FirResolvePhase.EXPECT_ACTUAL_MATCHING) } is FirClass, is FirTypeAlias, is FirEnumEntry, is FirField -> Unit else -> error("Unexpected type: ${declaration::class.simpleName}") } } }
157
Kotlin
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
3,436
kotlin
Apache License 2.0
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/transform/TransformedExternalArtifactSetCodec.kt
blindarcheology
294,432,244
false
null
/* * Copyright 2020 the original author or 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 org.gradle.configurationcache.serialization.codecs.transform import org.gradle.api.Action import org.gradle.api.artifacts.component.ComponentIdentifier import org.gradle.api.file.FileCollection import org.gradle.api.internal.artifacts.PreResolvedResolvableArtifact import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactVisitor import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvableArtifact import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet import org.gradle.api.internal.artifacts.transform.ArtifactTransformDependencies import org.gradle.api.internal.artifacts.transform.ExecutionGraphDependenciesResolver import org.gradle.api.internal.artifacts.transform.ExtraExecutionGraphDependenciesResolverFactory import org.gradle.api.internal.artifacts.transform.Transformation import org.gradle.api.internal.artifacts.transform.TransformationNodeRegistry import org.gradle.api.internal.artifacts.transform.TransformationStep import org.gradle.api.internal.artifacts.transform.TransformedExternalArtifactSet import org.gradle.api.internal.artifacts.transform.Transformer import org.gradle.api.internal.attributes.ImmutableAttributes import org.gradle.api.internal.tasks.TaskDependencyContainer import org.gradle.api.internal.tasks.TaskDependencyResolveContext import org.gradle.configurationcache.serialization.Codec import org.gradle.configurationcache.serialization.ReadContext import org.gradle.configurationcache.serialization.WriteContext import org.gradle.configurationcache.serialization.decodePreservingSharedIdentity import org.gradle.configurationcache.serialization.encodePreservingSharedIdentityOf import org.gradle.configurationcache.serialization.readNonNull import org.gradle.internal.Describables import org.gradle.internal.Try import org.gradle.internal.component.local.model.ComponentFileArtifactIdentifier import org.gradle.internal.component.model.DefaultIvyArtifactName import org.gradle.internal.operations.BuildOperationQueue import org.gradle.internal.operations.RunnableBuildOperation import java.io.File class TransformedExternalArtifactSetCodec( private val transformationNodeRegistry: TransformationNodeRegistry ) : Codec<TransformedExternalArtifactSet> { override suspend fun WriteContext.encode(value: TransformedExternalArtifactSet) { encodePreservingSharedIdentityOf(value) { write(value.ownerId) write(value.targetVariantAttributes) val files = mutableListOf<File>() value.visitArtifacts { files.add(it.file) } write(files) write(value.transformation) val unpacked = unpackTransformation(value.transformation, value.dependenciesResolver) write(unpacked.dependencies) } } override suspend fun ReadContext.decode(): TransformedExternalArtifactSet { return decodePreservingSharedIdentity { val ownerId = readNonNull<ComponentIdentifier>() val targetAttributes = readNonNull<ImmutableAttributes>() val files = readNonNull<List<File>>() val transformation = readNonNull<Transformation>() val dependencies = readNonNull<List<TransformDependencies>>() val dependenciesPerTransformer = mutableMapOf<Transformer, TransformDependencies>() transformation.visitTransformationSteps { dependenciesPerTransformer.put(it.transformer, dependencies[dependenciesPerTransformer.size]) } TransformedExternalArtifactSet(ownerId, FixedFilesArtifactSet(ownerId, files), targetAttributes, transformation, FixedDependenciesResolverFactory(dependenciesPerTransformer), transformationNodeRegistry) } } } private class FixedDependenciesResolverFactory(private val dependencies: Map<Transformer, TransformDependencies>) : ExtraExecutionGraphDependenciesResolverFactory, ExecutionGraphDependenciesResolver { override fun create(componentIdentifier: ComponentIdentifier): ExecutionGraphDependenciesResolver { return this } override fun computeDependencyNodes(transformationStep: TransformationStep): TaskDependencyContainer { throw UnsupportedOperationException("should not be called") } override fun selectedArtifacts(transformer: Transformer): FileCollection { throw UnsupportedOperationException("should not be called") } override fun computeArtifacts(transformer: Transformer): Try<ArtifactTransformDependencies> { return dependencies.getValue(transformer).recreate().computeArtifacts(transformer) } } private class FixedFilesArtifactSet(private val ownerId: ComponentIdentifier, private val files: List<File>) : ResolvedArtifactSet { override fun visitDependencies(context: TaskDependencyResolveContext) { throw UnsupportedOperationException("should not be called") } override fun startVisit(actions: BuildOperationQueue<RunnableBuildOperation>, listener: ResolvedArtifactSet.AsyncArtifactListener): ResolvedArtifactSet.Completion { val artifacts = artifacts for (artifact in artifacts) { listener.artifactAvailable(artifact) } return object : ResolvedArtifactSet.Completion { override fun visit(visitor: ArtifactVisitor) { val displayName = Describables.of(ownerId) for (artifact in artifacts) { visitor.visitArtifact(displayName, ImmutableAttributes.EMPTY, artifact) } } } } override fun visitLocalArtifacts(visitor: ResolvedArtifactSet.LocalArtifactVisitor) { throw UnsupportedOperationException("should not be called") } override fun visitExternalArtifacts(visitor: Action<ResolvableArtifact>) { for (artifact in artifacts) { visitor.execute(artifact) } } private val artifacts: List<ResolvableArtifact> get() = files.map { file -> PreResolvedResolvableArtifact(null, DefaultIvyArtifactName.forFile(file, null), ComponentFileArtifactIdentifier(ownerId, file.name), file, TaskDependencyContainer.EMPTY) } }
0
null
0
1
609634026935ea5d499204469da271b4ef057d43
6,826
gradle
Apache License 2.0
app/src/main/java/com/example/incode/viewmodel/DirectionsViewModel.kt
CharlesMuvaka
641,490,688
false
null
package com.example.incode.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.incode.models.Resource import com.example.incode.models.RouteDirections import com.example.incode.repository.DirectionsRepo import kotlinx.coroutines.launch import retrofit2.Response class DirectionsViewModel(private val origin: String, private val dest: String, private val repo: DirectionsRepo): ViewModel() { val directions: MutableLiveData<Resource<RouteDirections>> = MutableLiveData() init { getRouteDirections(origin, dest) } private fun getRouteDirections(origin: String, dest: String) { viewModelScope.launch{ directions.postValue(Resource.Loading()) val response = repo.getDirections(origin, dest) directions.postValue(getRouteDirectionsState(response)) } } private fun getRouteDirectionsState(response: Response<RouteDirections>): Resource<RouteDirections>? { if (response.isSuccessful){ response.body()?.let {routeDirection -> return Resource.Success(routeDirection) } } return Resource.Failure(error = response.message()) } }
0
Kotlin
0
0
735847f6204830cc2a31ea7fabbdaf29f1615a67
1,270
inDrive
MIT License
suas-lib/src/test/java/zendesk/suas/SuasStoreDispatchTest.kt
tmtron
129,727,450
true
{"Java": 125491, "Kotlin": 89155, "Shell": 2983}
package zendesk.suas import org.junit.Test class SuasStoreDispatchTest : Helper { @Test(expected = RuntimeException::class) fun `dispatch from reducer should crash`() { val store = store(reducer = BadReducer()) store.dispatch(DispatcherAction(store)) } class DispatcherAction(val dispatcher: Dispatcher) : Action<Dispatcher>(":/", dispatcher) class BadReducer : Reducer<String>() { override fun reduce(oldState: String, action: Action<*>): String? { return if(action is DispatcherAction) { action.dispatcher.dispatch(Action<String>("DONT DO THIS EVER")) null } else { "" } } override fun getInitialState(): String = "" } }
0
Java
0
0
e322f5592157be0bbf16f907e949ecd04aa04353
777
Suas-Android
Apache License 2.0
presentation/src/main/java/com/anytypeio/anytype/presentation/sets/filter/CreateFilterView.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.presentation.sets.filter import com.anytypeio.anytype.core_models.DVFilterCondition import com.anytypeio.anytype.core_models.DVFilterQuickOption import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.presentation.objects.ObjectIcon sealed class CreateFilterView { abstract val text: String abstract val isSelected: Boolean data class Tag( val id: Id, val name: String, val color: String, override val isSelected: Boolean ) : CreateFilterView() { override val text: String get() = name } data class Status( val id: Id, val name: String, val color: String, override val isSelected: Boolean ) : CreateFilterView() { override val text: String get() = name } data class Date( val id: Id, val description: String, val type: DVFilterQuickOption, val condition: DVFilterCondition, val value: Long, override val isSelected: Boolean ) : CreateFilterView() { override val text: String get() = description companion object { const val NO_VALUE = 0L } } data class Object( val id: Id, val name: String, val typeName: String?, val icon: ObjectIcon, override val isSelected: Boolean ): CreateFilterView() { override val text: String get() = name } data class Checkbox( val isChecked: Boolean, override val isSelected: Boolean ): CreateFilterView() { override val text: String get() = "" } }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
1,696
anytype-kotlin
RSA Message-Digest License
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/messages/objects/SearchExtendedResponse.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "SpellCheckingInspection") package name.anton3.vkapi.generated.messages.objects import name.anton3.vkapi.generated.groups.objects.GroupFull import name.anton3.vkapi.generated.users.objects.UserFull /** * No description * * @property count Total number * @property items No description * @property profiles No description * @property groups No description */ data class GetByIdExtendedResponse( val count: Long, val items: List<Message>, val profiles: List<UserFull>, val groups: List<GroupFull>? = null )
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
556
kotlin-vk-api
MIT License
app/src/test/kotlin/io/eugenethedev/taigamobile/repositories/UsersRepositoryTest.kt
EugeneTheDev
345,475,827
false
null
package io.eugenethedev.taigamobile.repositories import io.eugenethedev.taigamobile.data.repositories.UsersRepository import io.eugenethedev.taigamobile.domain.repositories.IUsersRepository import io.eugenethedev.taigamobile.testdata.TestData import kotlinx.coroutines.runBlocking import kotlin.test.BeforeTest import org.junit.Test import kotlin.test.assertEquals class UsersRepositoryTest : BaseRepositoryTest() { lateinit var usersRepository: IUsersRepository @BeforeTest fun setupUsersRepositoryTest() { usersRepository = UsersRepository(mockTaigaApi, mockSession) } @Test fun `test getMe`() = runBlocking { val user = usersRepository.getMe() assertEquals( expected = user.username, actual = TestData.activeUser.username ) assertEquals( expected = user.fullName, actual = TestData.activeUser.fullName ) } @Test fun `test getTeam`() = runBlocking { val team = usersRepository.getTeam().sortedBy { it.username } val testTeam = TestData.users.sortedBy { it.username } team.forEachIndexed { index, member -> assertEquals( expected = testTeam[index].username, actual = member.username ) assertEquals( expected = testTeam[index].fullName, actual = member.name ) var count = 0 count += TestData.projects[0].issues.filter { it.creator.username == member.username } .count() count += TestData.projects[0].issues.filter { it.isClosed && it.assignedTo?.username == member.username } .count() TestData.projects[0].sprints.map { sprint -> count += sprint.tasks.filter { it.isClosed && it.assignedTo?.username == member.username }.count() } TestData.projects[0].userstories.map { userStory -> count += userStory.tasks.filter { it.isClosed && it.assignedTo?.username == member.username }.count() } assertEquals( expected = count, actual = member.totalPower ) } } @Test fun `test getUser`() = runBlocking { val testUsers = TestData.users.sortedBy { it.username } usersRepository.getTeam().sortedBy { it.username }.forEachIndexed { index, member -> val user = usersRepository.getUser(member.id) assertEquals( expected = testUsers[index].username, actual = user.username ) assertEquals( expected = testUsers[index].fullName, actual = user.fullName ) } } }
1
null
9
86
410bd4a8efd781280e8038f92b77a2babd120fef
2,867
TaigaMobile
Apache License 2.0
src/main/kotlin/dev/koifysh/randomizer/data/ArchipelagoWorldData.kt
KonoTyran
833,936,250
false
{"Kotlin": 175196, "Java": 12527}
package dev.koifysh.randomizer.data import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableSet import dev.koifysh.randomizer.ArchipelagoRandomizer import dev.koifysh.randomizer.ArchipelagoRandomizer.apClient import dev.koifysh.randomizer.ArchipelagoRandomizer.logger import net.minecraft.core.HolderLookup import net.minecraft.nbt.CompoundTag import net.minecraft.world.level.saveddata.SavedData import java.util.* import java.util.function.Consumer class ArchipelagoWorldData : SavedData { var seedName: String = "" set(value) { field = value; setDirty() } var dragonState: Int = DRAGON_ASLEEP set(value) { field = value; setDirty() } var jailPlayers = true set(value) { field = value; setDirty() } private var completedLocations: MutableSet<Long> = HashSet() var index: Long = 0 set(value) { field = value; this.setDirty() } private var receivedItems: MutableList<Long> = LinkedList() private var playerIndex: MutableMap<String, Int> = HashMap() fun addLocation(location: Long) { completedLocations.add(location) this.setDirty() ArchipelagoRandomizer.goalHandler.advancementGoal?.checkCompletion() } fun addLocations(locations: Collection<Long>) { this.completedLocations.addAll(locations) this.setDirty() val fileName = "${apClient.roomInfo.seedName}_${apClient.slot}.save" } fun addItem(id: Long) { receivedItems.add(id) this.setDirty() } fun addItem(id: Collection<Long>) { receivedItems.addAll(id) this.setDirty() } fun getItems(): ImmutableList<Long> { return ImmutableList.copyOf(receivedItems) } fun getCompletedLocations(): Collection<Long> { return ImmutableSet.copyOf(completedLocations) } fun updatePlayerIndex(playerUUID: String, index: Int) { playerIndex[playerUUID] = index this.setDirty() } fun getPlayerIndex(playerUUID: String): Int { return playerIndex.getOrDefault(playerUUID, 0) } override fun save(tag: CompoundTag, holder: HolderLookup.Provider): CompoundTag { tag.putString("seedName", seedName) tag.putInt("dragonState", dragonState) tag.putBoolean("jailPlayers", jailPlayers) tag.putLongArray("locations", completedLocations.toList()) tag.putLongArray("items", receivedItems) tag.putLong("index", index) val tagIndex = CompoundTag() playerIndex.forEach { (uuid, index) -> tagIndex.putInt(uuid, index) } tag.put("playerIndex", tagIndex) return tag } constructor() private constructor( seedName: String, dragonState: Int, jailPlayers: Boolean, locations: LongArray, items: LongArray, playerIndex: MutableMap<String, Int>, itemIndex: Long, ) { this.seedName = seedName this.dragonState = dragonState this.jailPlayers = jailPlayers this.completedLocations = locations.toSet().toMutableSet() this.receivedItems = items.toMutableList() this.playerIndex = playerIndex this.index = itemIndex } companion object { const val DRAGON_KILLED: Int = 30 const val DRAGON_SPAWNED: Int = 20 const val DRAGON_WAITING: Int = 15 const val DRAGON_ASLEEP: Int = 10 fun factory(): Factory<ArchipelagoWorldData> { return Factory( { ArchipelagoWorldData() }, { tag: CompoundTag, provider: HolderLookup.Provider? -> load(tag, provider) }, null ) } fun load(tag: CompoundTag, provider: HolderLookup.Provider?): ArchipelagoWorldData { val indexTag = tag.getCompound("playerIndex") val indexMap = HashMap<String, Int>() indexTag.allKeys.forEach(Consumer { key: String -> indexMap[key] = indexTag.getInt(key) }) return ArchipelagoWorldData( tag.getString("seedName"), tag.getInt("dragonState"), tag.getBoolean("jailPlayers"), tag.getLongArray("locations"), tag.getLongArray("items"), indexMap, tag.getLong("index") ) } } }
0
Kotlin
0
0
6f6c8a585154d8cce094365b989e995df3357119
4,432
archipelago-randomizer-fabric
Creative Commons Zero v1.0 Universal
build-logic/convention/src/main/kotlin/plugins/AndroidLibComposeConventionPlugin.kt
JohannesPtaszyk
695,929,733
false
{"Kotlin": 511937}
package plugins import com.android.build.gradle.LibraryExtension import configurations.configureAndroidCompose import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType @Suppress("unused") class AndroidLibComposeConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("dev.pott.android.lib") apply("dev.shreyaspatil.compose-compiler-report-generator") } extensions.getByType<LibraryExtension>().apply { configureAndroidCompose(this) } } } }
7
Kotlin
0
2
acf73a7da4e08f105feeca72ea11a1205b3226b1
665
Abonity
Apache License 2.0
src/cds/src/main/kotlin/org/icpclive/api/RunInfo.kt
icpc
447,849,919
false
{"Kotlin": 499270, "JavaScript": 246403, "HTML": 76741, "TypeScript": 31428, "Python": 2450, "SCSS": 1034, "CSS": 466, "Dockerfile": 406, "Shell": 344, "Batchfile": 222}
package org.icpclive.api import kotlinx.serialization.* import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import org.icpclive.util.DurationInMillisecondsSerializer import kotlin.time.Duration @Serializable public data class RunInfo( val id: Int, val result: RunResult?, val percentage: Double, val problemId: Int, val teamId: Int, @Serializable(with = DurationInMillisecondsSerializer::class) val time: Duration, val featuredRunMedia: MediaType? = null, val reactionVideos: List<MediaType> = emptyList(), val isHidden: Boolean = false, ) @Serializable public sealed class RunResult @Serializable(with = VerdictSerializer::class) public sealed class Verdict(public val shortName: String, public val isAddingPenalty: Boolean, public val isAccepted: Boolean) { public data object Accepted: Verdict("AC", false, true) public data object Rejected: Verdict("RJ", true, false) public data object Fail: Verdict("FL", false, true) public data object CompilationError: Verdict("CE", false, false) public data object CompilationErrorWithPenalty: Verdict("CE", true, false) public data object PresentationError: Verdict("PE", true, false) public data object RuntimeError: Verdict("RE", true, false) public data object TimeLimitExceeded: Verdict("TL", true, false) public data object MemoryLimitExceeded: Verdict("ML", true, false) public data object OutputLimitExceeded: Verdict("OL", true, false) public data object IdlenessLimitExceeded: Verdict("IL", true, false) public data object SecurityViolation: Verdict("SV", true, false) public data object Ignored: Verdict("IG", false, false) public data object Challenged: Verdict("CH", true, false) public data object WrongAnswer: Verdict("WA", true, false) public companion object { public val all: List<Verdict> get() = LookupHolder.all public fun lookup(shortName: String, isAddingPenalty: Boolean, isAccepted: Boolean): Verdict = LookupHolder.lookup(shortName, isAddingPenalty, isAccepted) } internal fun toRunResult() = ICPCRunResult(this, false) } internal class VerdictSerializer : KSerializer<Verdict> { @Serializable @SerialName("Verdict") private class VerdictSurrogate(val shortName: String, val isAddingPenalty: Boolean, val isAccepted: Boolean) override val descriptor = VerdictSurrogate.serializer().descriptor override fun deserialize(decoder: Decoder): Verdict { val surrogate = decoder.decodeSerializableValue(VerdictSurrogate.serializer()) return Verdict.lookup(surrogate.shortName, surrogate.isAddingPenalty, surrogate.isAccepted) } override fun serialize(encoder: Encoder, value: Verdict) { val surrogate = VerdictSurrogate(value.shortName, value.isAddingPenalty, value.isAccepted) encoder.encodeSerializableValue(VerdictSurrogate.serializer(), surrogate) } } // We have a separate object here to delay initialization until the function call. // This allows first fully initializing Verdict subclasses, which is required by LookupHolder constructor private object LookupHolder { val all = Verdict::class.sealedSubclasses.map { it.objectInstance!! } private val alternativeNames = listOf( "OK" to Verdict.Accepted, "TLE" to Verdict.TimeLimitExceeded, "RT" to Verdict.RuntimeError, "RTE" to Verdict.RuntimeError, "OLE" to Verdict.OutputLimitExceeded, "MLE" to Verdict.MemoryLimitExceeded, "ILE" to Verdict.IdlenessLimitExceeded, "WTL" to Verdict.IdlenessLimitExceeded, "CTL" to Verdict.CompilationError, ) private val mainNames = all.map { it.shortName to it } private val allNames = (alternativeNames + mainNames).groupBy({ it.first }, { it.second }) fun lookup(shortName: String, isAddingPenalty: Boolean, isAccepted: Boolean) : Verdict { val found = allNames[shortName]?.singleOrNull { it.isAddingPenalty == isAddingPenalty && it.isAccepted == isAccepted } return when { found != null -> found isAccepted -> Verdict.Accepted isAddingPenalty -> Verdict.Rejected else -> Verdict.Ignored } } } @Serializable @SerialName("ICPC") public data class ICPCRunResult( val verdict: Verdict, val isFirstToSolveRun: Boolean, ) : RunResult() @Serializable @SerialName("IOI") public data class IOIRunResult( val score: List<Double>, val wrongVerdict: Verdict? = null, val difference: Double = 0.0, val scoreAfter: Double = 0.0, val isFirstBestRun: Boolean = false, val isFirstBestTeamRun: Boolean = false ) : RunResult()
17
Kotlin
11
36
5668fba15a5db31f51d5c2209c1adedade229f89
4,743
live-v3
MIT License
kotlin/rest-simple/src/main/kotlin/com/example/restsimple/repository/StudentRepository.kt
PatrickKoss
394,726,625
false
null
package com.example.restsimple.repository import com.example.restsimple.model.Student import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param import java.util.* interface StudentRepository : JpaRepository<Student, String> { @Query("SELECT s FROM Student s WHERE s.id = :id") fun findByIdColumn(@Param("id") id: String?): Optional<Student> @Query("DELETE FROM Student s WHERE s.id = :id") @Modifying fun deleteByIdColumn(@Param("id") id: String?) }
1
null
4
3
625532c641ac592ec36344617556e4af79e49b74
641
lecture-ws-development-of-a-db-app
MIT License
app/src/main/java/org/simple/clinic/login/applock/AppLockScreenKey.kt
zhukofff
378,200,443
true
{"Kotlin": 4636507, "Shell": 3719, "Python": 3162, "HTML": 545}
package org.simple.clinic.login.applock import android.os.Parcelable import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.parcelize.Parcelize import org.simple.clinic.navigation.v2.ScreenKey @Parcelize object AppLockScreenKey : ScreenKey(), Parcelable { @IgnoredOnParcel override val analyticsName = "App Lock" override fun instantiateFragment() = AppLockScreen() }
0
null
0
1
7eab5bfef38869c305b5446e4c0da877ecd4c269
384
simple-android
MIT License
web-backend/src/main/java/com/github/aivanovski/testswithme/web/presentation/controller/LoginController.kt
aivanovski
815,197,496
false
{"Kotlin": 800559, "Clojure": 8104, "Shell": 1883, "Dockerfile": 375}
package com.github.aivanovski.testswithme.web.presentation.controller import arrow.core.Either import arrow.core.raise.either import com.github.aivanovski.testswithme.utils.StringUtils.SPACE import com.github.aivanovski.testswithme.web.api.ApiHeaders.X_REQUEST_SET_COOKIE import com.github.aivanovski.testswithme.web.api.request.LoginRequest import com.github.aivanovski.testswithme.web.api.response.LoginResponse import com.github.aivanovski.testswithme.web.domain.service.AuthService import com.github.aivanovski.testswithme.web.domain.service.AuthService.Companion.TOKEN_VALIDITY_PERIOD import com.github.aivanovski.testswithme.web.entity.Credentials import com.github.aivanovski.testswithme.web.entity.Response import com.github.aivanovski.testswithme.web.entity.exception.AppException import com.github.aivanovski.testswithme.web.entity.exception.InvalidCredentialsException import io.ktor.http.Headers import io.ktor.http.HttpHeaders class LoginController( private val authService: AuthService ) { fun login( headers: Headers, request: LoginRequest ): Either<AppException, Response<LoginResponse>> = either { val credentials = request.toCredentials() val isSetCookie = "true".equals(headers[X_REQUEST_SET_COOKIE], ignoreCase = true) if (!authService.isCredentialsValid(credentials)) { raise(InvalidCredentialsException()) } val token = authService.getOrCreateToken(credentials) val responseHeaders = if (isSetCookie) { listOf(HttpHeaders.SetCookie to buildCookieWithToken(token)) } else { emptyList() } Response( response = LoginResponse(token), headers = responseHeaders ) } private fun buildCookieWithToken(token: String): String { return StringBuilder() .apply { append("token=$token;") append(SPACE).append("Path=/;") append(SPACE).append("Max-Age=$TOKEN_VALIDITY_PERIOD;") append(SPACE).append("SameSite=Lax;") append(SPACE).append("HttpOnly") // TODO: 'Secure' should be added to production setup } .toString() } private fun LoginRequest.toCredentials(): Credentials { return Credentials( username = username, password = <PASSWORD> ) } }
0
Kotlin
0
0
a447f89bab54e76467259dba246c015964d1fc14
2,498
tests-with-me
Apache License 2.0
common/src/main/kotlin/org/valkyrienskies/military/MilBlocks.kt
FateOfWar
729,506,610
false
{"Kotlin": 22032, "Java": 13416}
package org.valkyrienskies.military import net.minecraft.core.Registry import net.minecraft.world.item.BlockItem import net.minecraft.world.item.Item import org.valkyrienskies.military.registry.DeferredRegister import org.valkyrienskies.mod.common.hooks.VSGameEvents @Suppress("unused") object MilBlocks { private val BLOCKS = DeferredRegister.create(MilitaryMod.MOD_ID, Registry.BLOCK_REGISTRY) // val ANCHOR = BLOCKS.register("anchor", ::AnchorBlock) fun register() { BLOCKS.applyAll() VSGameEvents.registriesCompleted.on { _, _ -> } } // Blocks should also be registered as items, if you want them to be able to be held // aka all blocks fun registerItems(items: DeferredRegister<Item>) { BLOCKS.forEach { items.register(it.name) { BlockItem(it.get(), Item.Properties().tab(MilItems.TAB)) } } } }
0
Kotlin
0
0
10039942733ef94e62c4611fd40296cf6a4d8ce4
892
MilitaryMod
Apache License 2.0
src/main/kotlin/org/teamvoided/dusk_autumn/init/blocks/DnDWoodBlocks.kt
TeamVoided
737,359,498
false
{"Kotlin": 871908, "Java": 13546}
package org.teamvoided.dusk_autumn.init.blocks import net.fabricmc.fabric.api.registry.StrippableBlockRegistry import net.minecraft.block.* import net.minecraft.block.AbstractBlock.Settings import net.minecraft.block.AbstractBlock.Settings.copy import net.minecraft.block.enums.NoteBlockInstrument import net.minecraft.block.piston.PistonBehavior import net.minecraft.block.sapling.SaplingBlock import net.minecraft.particle.ParticleTypes import net.minecraft.sound.BlockSoundGroup import org.teamvoided.dusk_autumn.block.DnDWoodTypes import org.teamvoided.dusk_autumn.block.FallingLeavesBlock import org.teamvoided.dusk_autumn.block.sapling.SaplingGenerators import org.teamvoided.dusk_autumn.block.sapling.ThreeWideTreeSaplingBlock import org.teamvoided.dusk_autumn.init.DnDBlocks import org.teamvoided.dusk_autumn.init.DnDParticles import org.teamvoided.dusk_autumn.util.* object DnDWoodBlocks { val CASCADE_SAPLING = DnDBlocks.register( "cascade_sapling", ThreeWideTreeSaplingBlock( SaplingGenerators.CASCADE, Settings.create() .mapColor(MapColor.RED).noCollision().ticksRandomly().breakInstantly() .sounds(BlockSoundGroup.CHERRY_SAPLING).pistonBehavior(PistonBehavior.DESTROY) ) ).cutout() val POTTED_CASCADE_SAPLING = DnDBlocks.registerNoItem( "potted_cascade_sapling", Blocks.pottedVariant(CASCADE_SAPLING) ).cutout() val CASCADE_LEAVES = DnDBlocks.register( "cascade_leaves", FallingLeavesBlock( Settings.create().strength(0.2f).ticksRandomly() .nonOpaque().allowsSpawning(Blocks::allowOcelotsAndParrots).suffocates(Blocks::nonSolid) .blockVision(Blocks::nonSolid) .lavaIgnitable().pistonBehavior(PistonBehavior.DESTROY).solidBlock(Blocks::nonSolid) .sounds(BlockSoundGroup.AZALEA_LEAVES) .mapColor(MapColor.RED), DnDParticles.CASCADE_LEAF_PARTICLE ).cutout().flammableLeaves().axe() ) val CASCADE_LEAF_PILE = DnDBlocks.register( "cascade_leaf_pile", fallingLeafPile(DnDParticles.CASCADE_LEAF_PARTICLE, MapColor.RED, BlockSoundGroup.AZALEA_LEAVES).cutout() ) val CASCADE_LOG = DnDBlocks.register( "cascade_log", Blocks.logOf(MapColor.BLUE, MapColor.BROWN, BlockSoundGroup.CHERRY_WOOD) ) val HOLLOW_CASCADE_LOG = DnDBlocks.register("hollow_cascade_log", hollowLog(CASCADE_LOG)) val CASCADE_WOOD = DnDBlocks.register( "cascade_wood", PillarBlock( Settings.create().mapColor(MapColor.BROWN).instrument(NoteBlockInstrument.BASS).strength(2.0f) .sounds(BlockSoundGroup.CHERRY_WOOD).lavaIgnitable() ) ) val CASCADE_WOOD_STAIRS = DnDBlocks.register("cascade_wood_stairs", stairsOf(CASCADE_WOOD)) val CASCADE_WOOD_SLAB = DnDBlocks.register("cascade_wood_slab", slabOf(CASCADE_WOOD)) val CASCADE_WOOD_WALL = DnDBlocks.register("cascade_wood_wall", wallOf(CASCADE_WOOD)) val CASCADE_LOG_PILE = DnDBlocks.register("cascade_log_pile", logPile(CASCADE_WOOD)) val STRIPPED_CASCADE_LOG = DnDBlocks.register( "stripped_cascade_log", Blocks.logOf(MapColor.BLUE, MapColor.BLUE, BlockSoundGroup.CHERRY_WOOD) ) val HOLLOW_STRIPPED_CASCADE_LOG = DnDBlocks.register("hollow_stripped_cascade_log", hollowLog(STRIPPED_CASCADE_LOG)) val STRIPPED_CASCADE_WOOD = DnDBlocks.register( "stripped_cascade_wood", PillarBlock(copy(CASCADE_WOOD).mapColor(MapColor.BLUE)) ) val CASCADE_PLANKS = DnDBlocks.register( "cascade_planks", Block( Settings.create() .mapColor(MapColor.BLUE).instrument(NoteBlockInstrument.BASS).strength(2.0F, 3.0F) .sounds(BlockSoundGroup.CHERRY_WOOD).lavaIgnitable() ) ).flammablePlanks() val CASCADE_STAIRS = DnDBlocks.register("cascade_stairs", stairsOf(CASCADE_PLANKS).axe().flammablePlanks()) val CASCADE_SLAB = DnDBlocks.register("cascade_slab", slabOf(CASCADE_PLANKS).axe().flammablePlanks()) val CASCADE_FENCE = DnDBlocks.register("cascade_fence", fenceOf(CASCADE_PLANKS).axe().flammablePlanks()) val CASCADE_FENCE_GATE = DnDBlocks.register( "cascade_fence_gate", fenceGateOf(DnDWoodTypes.CASCADE_WOOD_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val CASCADE_DOOR = DnDBlocks.registerNoItem( "cascade_door", doorOf(DnDWoodTypes.CASCADE_BLOCK_SET_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val BLUE_DOOR = DnDBlocks.registerNoItem( "blue_door", DoorBlock( BlockSetType.DARK_OAK, Settings.create().mapColor(CASCADE_PLANKS.defaultMapColor) .instrument(NoteBlockInstrument.BASS).strength(3.0f).nonOpaque().lavaIgnitable() .pistonBehavior(PistonBehavior.DESTROY), ).axe().flammablePlanks() ) val CASCADE_TRAPDOOR = DnDBlocks.register( "cascade_trapdoor", trapdoorOf(DnDWoodTypes.CASCADE_BLOCK_SET_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val CASCADE_PRESSURE_PLATE = DnDBlocks.register( "cascade_pressure_plate", pressurePlateOf(DnDWoodTypes.CASCADE_BLOCK_SET_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val CASCADE_BUTTON = DnDBlocks.register( "cascade_button", Blocks.buttonOf(DnDWoodTypes.CASCADE_BLOCK_SET_TYPE).axe().flammablePlanks() ) val CASCADE_SIGN = DnDBlocks.registerNoItem( "cascade_sign", signOf(DnDWoodTypes.CASCADE_WOOD_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val CASCADE_WALL_SIGN = DnDBlocks.registerNoItem( "cascade_wall_sign", wallSignOf(DnDWoodTypes.CASCADE_WOOD_TYPE, CASCADE_PLANKS, CASCADE_SIGN).axe().flammablePlanks() ) val CASCADE_HANGING_SIGN = DnDBlocks.registerNoItem( "cascade_hanging_sign", hangingSignOf(DnDWoodTypes.CASCADE_WOOD_TYPE, CASCADE_PLANKS).axe().flammablePlanks() ) val CASCADE_WALL_HANGING_SIGN = DnDBlocks.registerNoItem( "cascade_wall_hanging_sign", wallHangingSignOf( DnDWoodTypes.CASCADE_WOOD_TYPE, CASCADE_PLANKS, CASCADE_HANGING_SIGN ).axe().flammablePlanks() ) val GOLDEN_BIRCH_SAPLING = DnDBlocks.register( "golden_birch_sapling", SaplingBlock( SaplingGenerators.GOLDEN_BIRCH, copy(Blocks.BIRCH_SAPLING).mapColor(MapColor.YELLOW) ).cutout() ) val POTTED_GOLDEN_BIRCH_SAPLING = DnDBlocks.registerNoItem("potted_golden_birch_sapling", Blocks.pottedVariant(GOLDEN_BIRCH_SAPLING).cutout()) val GOLDEN_BIRCH_LEAVES = DnDBlocks.register( "golden_birch_leaves", LeavesBlock( copy(Blocks.BIRCH_LEAVES).mapColor(MapColor.YELLOW) ).cutout().flammableLeaves() ) val GOLDEN_BIRCH_LEAF_PILE = DnDBlocks.register( "golden_birch_leaf_pile", leafPile(MapColor.YELLOW).cutout() ) // val PINE_PLANKS = register( // "pine_planks", Block( // Settings.create() // .mapColor(MapColor.BLUE).instrument(NoteBlockInstrument.BASS).strength(2.0F, 3.0F) // .sounds(BlockSoundGroup.WOOD).lavaIgnitable() // ).axe() // ) // val PINE_STAIRS = register("pine_stairs", stairsOf(PINE_PLANKS).axe()) // val PINE_SLAB = register("pine_slab", slabOf(PINE_PLANKS).axe()) // val PINE_FENCE = register("pine_fence", fenceOf(PINE_PLANKS)) // val PINE_FENCE_GATE = register( // "pine_fence_gate", // FenceGateBlock( // DnDWoodTypes.PINE_WOOD_TYPE, // Settings.create() // .mapColor(PINE_PLANKS.defaultMapColor).instrument(NoteBlockInstrument.BASS) // .strength(2.0f, 3.0f).solid() // ).axe() // ) val GALLERY_MAPLE_SAPLING = DnDBlocks.register( "gallery_maple_sapling", ThreeWideTreeSaplingBlock( SaplingGenerators.CASCADE, Settings.create() .mapColor(MapColor.RED).noCollision().ticksRandomly().breakInstantly().sounds(BlockSoundGroup.AZALEA) .pistonBehavior(PistonBehavior.DESTROY).luminance(light(1)) ) ).cutout() val POTTED_GALLERY_MAPLE_SAPLING = DnDBlocks.registerNoItem("potted_gallery_maple_sapling", Blocks.pottedVariant(GALLERY_MAPLE_SAPLING)).cutout() val GALLERY_MAPLE_LEAVES = DnDBlocks.register( "gallery_maple_leaves", LeavesBlock( Settings.create().strength(0.2f).ticksRandomly() .nonOpaque().allowsSpawning(Blocks::allowOcelotsAndParrots).suffocates(Blocks::nonSolid) .blockVision(Blocks::nonSolid).pistonBehavior(PistonBehavior.DESTROY).solidBlock(Blocks::nonSolid) .sounds(BlockSoundGroup.GRASS).mapColor(MapColor.RED) ).cutout().axe() ) val GALLERY_MAPLE_LEAF_PILE = DnDBlocks.register( "gallery_maple_leaf_pile", fallingLeafPile(DnDParticles.CASCADE_LEAF_PARTICLE, MapColor.RED).cutout() ) val GALLERY_MAPLE_LOG = DnDBlocks.register( "gallery_maple_log", Blocks.logOf(MapColor.GRAY, MapColor.BROWN, BlockSoundGroup.WOOD) ) val HOLLOW_GALLERY_MAPLE_LOG = DnDBlocks.register("hollow_gallery_maple_log", hollowLog(GALLERY_MAPLE_LOG)) val GALLERY_MAPLE_WOOD = DnDBlocks.register( "gallery_maple_wood", PillarBlock( Settings.create().mapColor(MapColor.BROWN).instrument(NoteBlockInstrument.BASS).strength(2.0f) .sounds(BlockSoundGroup.WOOD) ) ) val GALLERY_MAPLE_WOOD_STAIRS = DnDBlocks.register("gallery_maple_wood_stairs", stairsOf(GALLERY_MAPLE_WOOD)) val GALLERY_MAPLE_WOOD_SLAB = DnDBlocks.register("gallery_maple_wood_slab", slabOf(GALLERY_MAPLE_WOOD)) val GALLERY_MAPLE_WOOD_WALL = DnDBlocks.register("gallery_maple_wood_wall", wallOf(GALLERY_MAPLE_WOOD)) val GALLERY_MAPLE_LOG_PILE = DnDBlocks.register("gallery_maple_log_pile", logPile(GALLERY_MAPLE_WOOD)) val STRIPPED_GALLERY_MAPLE_LOG = DnDBlocks.register( "stripped_gallery_maple_log", Blocks.logOf(MapColor.GRAY, MapColor.GRAY, BlockSoundGroup.WOOD) ) val HOLLOW_STRIPPED_GALLERY_MAPLE_LOG = DnDBlocks.register("hollow_stripped_gallery_maple_log", hollowLog(STRIPPED_GALLERY_MAPLE_LOG)) val STRIPPED_GALLERY_MAPLE_WOOD = DnDBlocks.register( "stripped_gallery_maple_wood", PillarBlock( copy(GALLERY_MAPLE_WOOD).mapColor(MapColor.GRAY) ) ) val GALLERY_MAPLE_PLANKS = DnDBlocks.register( "gallery_maple_planks", Block( Settings.create() .mapColor(MapColor.GRAY).instrument(NoteBlockInstrument.BASS).strength(2.0F, 3.0F) .sounds(BlockSoundGroup.WOOD) ).axe() ) val GALLERY_MAPLE_STAIRS = DnDBlocks.register("gallery_maple_stairs", stairsOf(GALLERY_MAPLE_PLANKS).axe()) val GALLERY_MAPLE_SLAB = DnDBlocks.register("gallery_maple_slab", slabOf(GALLERY_MAPLE_PLANKS).axe()) val GALLERY_MAPLE_FENCE = DnDBlocks.register("gallery_maple_fence", fenceOf(GALLERY_MAPLE_PLANKS).axe()) val GALLERY_MAPLE_FENCE_GATE = DnDBlocks.register( "gallery_maple_fence_gate", fenceGateOf(DnDWoodTypes.GALLERY_MAPLE_WOOD_TYPE, GALLERY_MAPLE_PLANKS).axe() ) val GALLERY_MAPLE_DOOR = DnDBlocks.registerNoItem( "gallery_maple_door", doorOf(DnDWoodTypes.GALLERY_MAPLE_BLOCK_SET_TYPE, GALLERY_MAPLE_PLANKS).cutout().axe() ) val GALLERY_MAPLE_TRAPDOOR = DnDBlocks.register( "gallery_maple_trapdoor", trapdoorOf(DnDWoodTypes.GALLERY_MAPLE_BLOCK_SET_TYPE, GALLERY_MAPLE_DOOR).cutout().axe() ) val GALLERY_MAPLE_PRESSURE_PLATE = DnDBlocks.register( "gallery_maple_pressure_plate", pressurePlateOf(DnDWoodTypes.GALLERY_MAPLE_BLOCK_SET_TYPE, GALLERY_MAPLE_PLANKS).axe() ) val GALLERY_MAPLE_BUTTON = DnDBlocks.register("gallery_maple_button", Blocks.buttonOf(DnDWoodTypes.GALLERY_MAPLE_BLOCK_SET_TYPE).axe()) val GALLERY_MAPLE_SIGN = DnDBlocks.registerNoItem( "gallery_maple_sign", signOf(DnDWoodTypes.GALLERY_MAPLE_WOOD_TYPE, GALLERY_MAPLE_PLANKS).axe() ) val GALLERY_MAPLE_WALL_SIGN = DnDBlocks.registerNoItem( "gallery_maple_wall_sign", wallSignOf(DnDWoodTypes.GALLERY_MAPLE_WOOD_TYPE, GALLERY_MAPLE_PLANKS, GALLERY_MAPLE_SIGN).axe() ) val GALLERY_MAPLE_HANGING_SIGN = DnDBlocks.registerNoItem( "gallery_maple_hanging_sign", hangingSignOf(DnDWoodTypes.GALLERY_MAPLE_WOOD_TYPE, GALLERY_MAPLE_PLANKS).axe() ) val GALLERY_MAPLE_WALL_HANGING_SIGN = DnDBlocks.registerNoItem( "gallery_maple_wall_hanging_sign", wallHangingSignOf(DnDWoodTypes.GALLERY_MAPLE_WOOD_TYPE, GALLERY_MAPLE_PLANKS, GALLERY_MAPLE_HANGING_SIGN).axe() ) val BONEWOOD_PLANKS = DnDBlocks.register( "bonewood_planks", Block( Settings.create() .mapColor(MapColor.SNOW).instrument(NoteBlockInstrument.XYLOPHONE).strength(2.0F, 3.0F) .sounds(bonewoodSound) ).axe() ) val BONEWOOD_STAIRS = DnDBlocks.register("bonewood_stairs", stairsOf(BONEWOOD_PLANKS).axe()) val BONEWOOD_SLAB = DnDBlocks.register("bonewood_slab", slabOf(BONEWOOD_PLANKS).axe()) val BONEWOOD_FENCE = DnDBlocks.register("bonewood_fence", fenceOf(BONEWOOD_PLANKS).axe()) val BONEWOOD_FENCE_GATE = DnDBlocks.register( "bonewood_fence_gate", FenceGateBlock( DnDWoodTypes.BONEWOOD_WOOD_TYPE, copy(BONEWOOD_PLANKS).solid() ).axe() ) val BONEWOOD_DOOR = DnDBlocks.registerNoItem( "bonewood_door", DoorBlock( DnDWoodTypes.BONEWOOD_BLOCK_SET_TYPE, copy(BONEWOOD_PLANKS).strength(3.0f).nonOpaque(), ).cutout().axe() ) val BONEWOOD_TRAPDOOR = DnDBlocks.register( "bonewood_trapdoor", TrapdoorBlock( DnDWoodTypes.BONEWOOD_BLOCK_SET_TYPE, copy(BONEWOOD_DOOR).allowsSpawning(Blocks::nonSpawnable), ).cutout().axe() ) val WITHERING_BONEWOOD_PLANKS = DnDBlocks.register( "withering_bonewood_planks", Block( copy(BONEWOOD_PLANKS).mapColor(MapColor.BLACK).sounds(witheringBonewoodSound) ).axe() ) val WITHERING_BONEWOOD_STAIRS = DnDBlocks.register("withering_bonewood_stairs", stairsOf(WITHERING_BONEWOOD_PLANKS).axe()) val WITHERING_BONEWOOD_SLAB = DnDBlocks.register("withering_bonewood_slab", slabOf(WITHERING_BONEWOOD_PLANKS).axe()) val WITHERING_BONEWOOD_FENCE = DnDBlocks.register("withering_bonewood_fence", fenceOf(WITHERING_BONEWOOD_PLANKS).axe()) val WITHERING_BONEWOOD_FENCE_GATE = DnDBlocks.register( "withering_bonewood_fence_gate", FenceGateBlock( DnDWoodTypes.WITHERING_BONEWOOD_WOOD_TYPE, copy(WITHERING_BONEWOOD_PLANKS).solid() ).axe() ) val WITHERING_BONEWOOD_DOOR = DnDBlocks.registerNoItem( "withering_bonewood_door", DoorBlock( DnDWoodTypes.BONEWOOD_BLOCK_SET_TYPE, copy(WITHERING_BONEWOOD_PLANKS).strength(3.0f).nonOpaque(), ).cutout().axe() ) val WITHERING_BONEWOOD_TRAPDOOR = DnDBlocks.register( "withering_bonewood_trapdoor", TrapdoorBlock( DnDWoodTypes.BONEWOOD_BLOCK_SET_TYPE, copy(WITHERING_BONEWOOD_DOOR).allowsSpawning(Blocks::nonSpawnable), ).cutout().axe() ) val HOLLOW_OAK_LOG = DnDBlocks.register("hollow_oak_log", hollowLog(Blocks.OAK_LOG)) val HOLLOW_STRIPPED_OAK_LOG = DnDBlocks.register("hollow_stripped_oak_log", hollowLog(Blocks.STRIPPED_OAK_LOG)) val HOLLOW_SPRUCE_LOG = DnDBlocks.register("hollow_spruce_log", hollowLog(Blocks.SPRUCE_LOG)) val HOLLOW_STRIPPED_SPRUCE_LOG = DnDBlocks.register("hollow_stripped_spruce_log", hollowLog(Blocks.STRIPPED_SPRUCE_LOG)) val HOLLOW_BIRCH_LOG = DnDBlocks.register("hollow_birch_log", hollowLog(Blocks.BIRCH_LOG)) val HOLLOW_STRIPPED_BIRCH_LOG = DnDBlocks.register("hollow_stripped_birch_log", hollowLog(Blocks.STRIPPED_BIRCH_LOG)) val HOLLOW_JUNGLE_LOG = DnDBlocks.register("hollow_jungle_log", hollowLog(Blocks.JUNGLE_LOG)) val HOLLOW_STRIPPED_JUNGLE_LOG = DnDBlocks.register("hollow_stripped_jungle_log", hollowLog(Blocks.STRIPPED_JUNGLE_LOG)) val HOLLOW_ACACIA_LOG = DnDBlocks.register("hollow_acacia_log", hollowLog(Blocks.ACACIA_LOG)) val HOLLOW_STRIPPED_ACACIA_LOG = DnDBlocks.register("hollow_stripped_acacia_log", hollowLog(Blocks.STRIPPED_ACACIA_LOG)) val HOLLOW_DARK_OAK_LOG = DnDBlocks.register("hollow_dark_oak_log", hollowLog(Blocks.DARK_OAK_LOG)) val HOLLOW_STRIPPED_DARK_OAK_LOG = DnDBlocks.register("hollow_stripped_dark_oak_log", hollowLog(Blocks.STRIPPED_DARK_OAK_LOG)) val HOLLOW_MANGROVE_LOG = DnDBlocks.register("hollow_mangrove_log", hollowLog(Blocks.MANGROVE_LOG)) val HOLLOW_STRIPPED_MANGROVE_LOG = DnDBlocks.register("hollow_stripped_mangrove_log", hollowLog(Blocks.STRIPPED_MANGROVE_LOG)) val HOLLOW_CHERRY_LOG = DnDBlocks.register("hollow_cherry_log", hollowLog(Blocks.CHERRY_LOG)) val HOLLOW_STRIPPED_CHERRY_LOG = DnDBlocks.register("hollow_stripped_cherry_log", hollowLog(Blocks.STRIPPED_CHERRY_LOG)) val HOLLOW_BAMBOO_BLOCK = DnDBlocks.register("hollow_bamboo_block", hollowBambooBlock(Blocks.BAMBOO_BLOCK)) val HOLLOW_STRIPPED_BAMBOO_BLOCK = DnDBlocks.register("hollow_stripped_bamboo_block", hollowBambooBlock(Blocks.STRIPPED_BAMBOO_BLOCK)) val HOLLOW_CRIMSON_STEM = DnDBlocks.register("hollow_crimson_stem", hollowLog(Blocks.CRIMSON_HYPHAE)) val HOLLOW_STRIPPED_CRIMSON_STEM = DnDBlocks.register("hollow_stripped_crimson_stem", hollowLog(Blocks.STRIPPED_CRIMSON_HYPHAE)) val HOLLOW_WARPED_STEM = DnDBlocks.register("hollow_warped_stem", hollowLog(Blocks.WARPED_HYPHAE)) val HOLLOW_STRIPPED_WARPED_STEM = DnDBlocks.register("hollow_stripped_warped_stem", hollowLog(Blocks.STRIPPED_WARPED_HYPHAE)) val OAK_WOOD_STAIRS = DnDBlocks.register("oak_wood_stairs", stairsOf(Blocks.OAK_WOOD)) val OAK_WOOD_SLAB = DnDBlocks.register("oak_wood_slab", slabOf(Blocks.OAK_WOOD)) val OAK_WOOD_WALL = DnDBlocks.register("oak_wood_wall", wallOf(Blocks.OAK_WOOD)) val SPRUCE_WOOD_STAIRS = DnDBlocks.register("spruce_wood_stairs", stairsOf(Blocks.SPRUCE_WOOD)) val SPRUCE_WOOD_SLAB = DnDBlocks.register("spruce_wood_slab", slabOf(Blocks.SPRUCE_WOOD)) val SPRUCE_WOOD_WALL = DnDBlocks.register("spruce_wood_wall", wallOf(Blocks.SPRUCE_WOOD)) val BIRCH_WOOD_STAIRS = DnDBlocks.register("birch_wood_stairs", stairsOf(Blocks.BIRCH_WOOD)) val BIRCH_WOOD_SLAB = DnDBlocks.register("birch_wood_slab", slabOf(Blocks.BIRCH_WOOD)) val BIRCH_WOOD_WALL = DnDBlocks.register("birch_wood_wall", wallOf(Blocks.BIRCH_WOOD)) val JUNGLE_WOOD_STAIRS = DnDBlocks.register("jungle_wood_stairs", stairsOf(Blocks.JUNGLE_WOOD)) val JUNGLE_WOOD_SLAB = DnDBlocks.register("jungle_wood_slab", slabOf(Blocks.JUNGLE_WOOD)) val JUNGLE_WOOD_WALL = DnDBlocks.register("jungle_wood_wall", wallOf(Blocks.JUNGLE_WOOD)) val ACACIA_WOOD_STAIRS = DnDBlocks.register("acacia_wood_stairs", stairsOf(Blocks.ACACIA_WOOD)) val ACACIA_WOOD_SLAB = DnDBlocks.register("acacia_wood_slab", slabOf(Blocks.ACACIA_WOOD)) val ACACIA_WOOD_WALL = DnDBlocks.register("acacia_wood_wall", wallOf(Blocks.ACACIA_WOOD)) val DARK_OAK_WOOD_STAIRS = DnDBlocks.register("dark_oak_wood_stairs", stairsOf(Blocks.DARK_OAK_WOOD)) val DARK_OAK_WOOD_SLAB = DnDBlocks.register("dark_oak_wood_slab", slabOf(Blocks.DARK_OAK_WOOD)) val DARK_OAK_WOOD_WALL = DnDBlocks.register("dark_oak_wood_wall", wallOf(Blocks.DARK_OAK_WOOD)) val MANGROVE_WOOD_STAIRS = DnDBlocks.register("mangrove_wood_stairs", stairsOf(Blocks.MANGROVE_WOOD)) val MANGROVE_WOOD_SLAB = DnDBlocks.register("mangrove_wood_slab", slabOf(Blocks.MANGROVE_WOOD)) val MANGROVE_WOOD_WALL = DnDBlocks.register("mangrove_wood_wall", wallOf(Blocks.MANGROVE_WOOD)) val CHERRY_WOOD_STAIRS = DnDBlocks.register("cherry_wood_stairs", stairsOf(Blocks.CHERRY_WOOD)) val CHERRY_WOOD_SLAB = DnDBlocks.register("cherry_wood_slab", slabOf(Blocks.CHERRY_WOOD)) val CHERRY_WOOD_WALL = DnDBlocks.register("cherry_wood_wall", wallOf(Blocks.CHERRY_WOOD)) val CRIMSON_HYPHAE_STAIRS = DnDBlocks.register("crimson_hyphae_stairs", stairsOf(Blocks.CRIMSON_HYPHAE)) val CRIMSON_HYPHAE_SLAB = DnDBlocks.register("crimson_hyphae_slab", slabOf(Blocks.CRIMSON_HYPHAE)) val CRIMSON_HYPHAE_WALL = DnDBlocks.register("crimson_hyphae_wall", wallOf(Blocks.CRIMSON_HYPHAE)) val WARPED_HYPHAE_STAIRS = DnDBlocks.register("warped_hyphae_stairs", stairsOf(Blocks.WARPED_HYPHAE)) val WARPED_HYPHAE_SLAB = DnDBlocks.register("warped_hyphae_slab", slabOf(Blocks.WARPED_HYPHAE)) val WARPED_HYPHAE_WALL = DnDBlocks.register("warped_hyphae_wall", wallOf(Blocks.WARPED_HYPHAE)) //logs are done differently and crash when varianted, but the woods have the exact same properties, just use them val OAK_LOG_PILE = DnDBlocks.register("oak_log_pile", logPile(Blocks.OAK_WOOD)) val SPRUCE_LOG_PILE = DnDBlocks.register("spruce_log_pile", logPile(Blocks.SPRUCE_WOOD)) val BIRCH_LOG_PILE = DnDBlocks.register("birch_log_pile", logPile(Blocks.BIRCH_WOOD)) val JUNGLE_LOG_PILE = DnDBlocks.register("jungle_log_pile", logPile(Blocks.JUNGLE_WOOD)) val ACACIA_LOG_PILE = DnDBlocks.register("acacia_log_pile", logPile(Blocks.ACACIA_WOOD)) val DARK_OAK_LOG_PILE = DnDBlocks.register("dark_oak_log_pile", logPile(Blocks.DARK_OAK_WOOD)) val MANGROVE_LOG_PILE = DnDBlocks.register("mangrove_log_pile", logPile(Blocks.MANGROVE_WOOD)) val CHERRY_LOG_PILE = DnDBlocks.register("cherry_log_pile", logPile(Blocks.CHERRY_WOOD)) val CRIMSON_STEM_PILE = DnDBlocks.register("crimson_stem_pile", logPile(Blocks.CRIMSON_HYPHAE)) val WARPED_STEM_PILE = DnDBlocks.register("warped_stem_pile", logPile(Blocks.WARPED_HYPHAE)) val BAMBOO_PILE = DnDBlocks.register("bamboo_pile", logPile(Blocks.BAMBOO_PLANKS, MapColor.PLANT)) val STRIPPED_BAMBOO_PILE = DnDBlocks.register("stripped_bamboo_pile", logPile(Blocks.BAMBOO_PLANKS)) val OAK_LEAF_PILE = DnDBlocks.register("oak_leaf_pile", leafPile().cutout()) val SPRUCE_LEAF_PILE = DnDBlocks.register("spruce_leaf_pile", leafPile().cutout()) val BIRCH_LEAF_PILE = DnDBlocks.register("birch_leaf_pile", leafPile().cutout()) val JUNGLE_LEAF_PILE = DnDBlocks.register("jungle_leaf_pile", leafPile().cutout()) val ACACIA_LEAF_PILE = DnDBlocks.register("acacia_leaf_pile", leafPile().cutout()) val DARK_OAK_LEAF_PILE = DnDBlocks.register("dark_oak_leaf_pile", leafPile().cutout()) val MANGROVE_LEAF_PILE = DnDBlocks.register("mangrove_leaf_pile", leafPile().cutout()) val CHERRY_LEAF_PILE = DnDBlocks.register( "cherry_leaf_pile", fallingLeafPile(ParticleTypes.CHERRY_LEAVES, MapColor.PINK, BlockSoundGroup.CHERRY_LEAVES).cutout() ) val AZALEA_LEAF_PILE = DnDBlocks.register( "azalea_leaf_pile", leafPile(BlockSoundGroup.AZALEA_LEAVES).cutout() ) val FLOWERING_AZALEA_LEAF_PILE = DnDBlocks.register( "flowering_azalea_leaf_pile", leafPile(BlockSoundGroup.AZALEA_LEAVES).cutout() ) fun init() { StrippableBlockRegistry.register(CASCADE_LOG, STRIPPED_CASCADE_LOG) StrippableBlockRegistry.register(CASCADE_WOOD, STRIPPED_CASCADE_WOOD) } }
0
Kotlin
0
0
4ab44eed538724732107f1c05bb489279cca731b
23,452
DusksAndDungeons
MIT License