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/app/domain/datasources/remote/authentication/RemoteAuthenticationDatasource.kt | bed72 | 664,335,364 | false | null | package app.domain.datasources.remote.authentication
import app.domain.alias.SignUpType
import app.domain.parameters.authentication.SignUpParameter
import app.domain.parameters.authentication.SignInParameter
interface RemoteAuthenticationDatasource {
suspend fun signUp(parameters: SignUpParameter): SignUpType
suspend fun signIn(parameters: SignInParameter): SignUpType
}
| 0 | Kotlin | 0 | 0 | d247a689128721751ded77bb2e0d60f45fe3d403 | 384 | KingsCross | Apache License 2.0 |
app/src/main/kotlin/eu/ezytarget/processingtemplate/realms/tesseract/TesseractRealmBuilder.kt | easytarget2000 | 266,631,921 | false | {"Kotlin": 125275} | package eu.ezytarget.processingtemplate.realms.tesseract
import eu.ezytarget.processingtemplate.realms.Realm
import eu.ezytarget.processingtemplate.realms.RealmBuilder
object TesseractRealmBuilder : RealmBuilder {
override fun build(): Realm = TesseractRealm()
} | 0 | Kotlin | 0 | 0 | 78f5aa56882a8cb16017781bd0060ba36ba1793b | 268 | kotlin-processing-template | ANTLR Software Rights Notice |
android/khajit/app/src/main/java/com/project/khajit_app/activity/ui/other_profile/OtherUserProfile.kt | bounswe | 170,124,936 | false | null | package com.project.khajit_app.activity.ui.other_profile
import android.graphics.Color
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentManager
import com.mikhaellopez.circularimageview.CircularImageView
import com.project.khajit_app.R
import com.project.khajit_app.activity.ListViewAdapter
import com.project.khajit_app.activity.OtherListViewAdapter
import com.project.khajit_app.activity.ui.article.ListArticleFragment
import com.project.khajit_app.activity.ui.followlist.FollowListFragment
import com.project.khajit_app.activity.ui.notificationdetails.notificationDetailFragment
import com.project.khajit_app.activity.ui.otherportfolio.OtherPortfolioFragment
import com.project.khajit_app.api.RetrofitClient
import com.project.khajit_app.data.models.*
import com.project.khajit_app.global.User
import com.squareup.picasso.Picasso
import interfaces.fragmentOperationsInterface
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class OtherUserProfile : Fragment(), fragmentOperationsInterface{
var containerId : ViewGroup? = null
private lateinit var viewModel: OtherUserProfileViewModel
private lateinit var other_nameBox: TextView
private lateinit var other_titleBox: TextView
private lateinit var other_aboutBox: TextView
private lateinit var other_followingBox: TextView
private lateinit var other_followerBox: TextView
private lateinit var other_traderImage: ImageView
private lateinit var other_followerButton: Button
private lateinit var other_followingButton: Button
private lateinit var follow_user: Button
private lateinit var private_part_layout: ConstraintLayout
private lateinit var public_private_ind: TextView
private lateinit var other_user_article_button :Button
private lateinit var other_portfolioButton: Button
private var public = false
private var isFollowing = 0 // 0 --> Not following, 1 --> Following, 2 --> Pending
private lateinit var other_id: String
private var other_id_for_article = 0
private lateinit var other_name: String
private lateinit var profile_pic: CircularImageView
var profile_pic_url: String? = ""
var other_user_public = true
/*override fun onClick(v: View?) {
if isFollowing
// Add stack fragment
val parentActivityManager: FragmentManager =
activity?.supportFragmentManager as FragmentManager
val fragment = ListArticleFragment.Companion.newInstance(0, 1, 0, 0, -1)
fragmentTransaction(
parentActivityManager,
fragment,
containerId!!.id,
true,
true,
false
)
}*/
var equipments = arrayOf<String>()
var rates = arrayOf<String>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
viewModel =
ViewModelProviders.of(this).get(OtherUserProfileViewModel::class.java)
val root = inflater.inflate(R.layout.other_user_profile_fragment, container, false)
containerId = container
other_id = arguments?.getInt("id").toString()
other_id_for_article = arguments?.getInt("id") as Int
other_nameBox = root.findViewById(R.id.other_user_real_name) as TextView
other_titleBox = root.findViewById(R.id.other_user_title) as TextView
other_aboutBox = root.findViewById(R.id.other_text_bio) as TextView
other_followingBox = root.findViewById(R.id.other_following_number) as TextView
other_followerBox = root.findViewById(R.id.other_follower_number) as TextView
other_traderImage = root.findViewById(R.id.other_trader_image) as ImageView
other_followerButton = root.findViewById(R.id.other_follower_button) as Button
other_followingButton = root.findViewById(R.id.other_following_button) as Button
follow_user = root.findViewById(R.id.other_follow_button) as Button
private_part_layout = root.findViewById(R.id.private_part) as ConstraintLayout
public_private_ind = root.findViewById(R.id.other_public_private_text) as TextView
other_user_article_button = root.findViewById(R.id.other_button_article_page) as Button
other_portfolioButton = root.findViewById(R.id.other_button_portfolio_page) as Button
profile_pic = root.findViewById(R.id.other_profile_pic) as CircularImageView
other_user_article_button.setOnClickListener(articleListListener)
// This will be used for further methods in order to set prediction rates
var lview = root.findViewById(R.id.other_list_prediction_name) as ListView
var ladapter = OtherListViewAdapter(this, equipments, rates)
lview.adapter = ladapter
//other_user_article_button.setOnClickListener(this)
RetrofitClient.instance.isFollowing(other_id).enqueue(object :
Callback<isFollowingResponseModel> {
override fun onResponse(
call: Call<isFollowingResponseModel>,
response: Response<isFollowingResponseModel>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
println("PROBLEM")
}else{
if(response.body()?.result == "Found") {
isFollowing = 1
follow_user.text = "UNFOLLOW"
follow_user.setBackgroundColor(Color.parseColor("#AAB80707"))
other_followerButton.isEnabled = true
other_followerButton.isClickable = true
other_followingButton.isEnabled = true
other_followingButton.isClickable = true
private_part_layout.visibility = View.VISIBLE
} else {
RetrofitClient.instance.getFollowingPending().enqueue(object :
Callback<FollowingPendingResponseModel> {
override fun onResponse(
call: Call<FollowingPendingResponseModel>,
response: Response<FollowingPendingResponseModel>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
println("NOT CHANGED")
}else{
var count = response.body()?.list!!.count()
var found_bff = false
for (a in 1..count!!) {
if(response.body()?.list!!.get(a-1).following.id.toString() == other_id) {
found_bff = true
break
}
}
if(found_bff == false) {
isFollowing = 0
follow_user.text = "FOLLOW"
follow_user.setBackgroundColor(Color.parseColor("#AA4AE608"))
}else {
isFollowing = 2
follow_user.text = "PENDING"
follow_user.setBackgroundColor(Color.parseColor("#AA976419"))
}
}
}else{
}
}
override fun onFailure(call: Call<FollowingPendingResponseModel>, t: Throwable) {
}
})
}
}
}else{
}
}
override fun onFailure(call: Call<isFollowingResponseModel>, t: Throwable) {
}
})
RetrofitClient.instance.getInfo(other_id).enqueue(object :
Callback<GenericUserModel> {
override fun onResponse(
call: Call<GenericUserModel>,
response: Response<GenericUserModel>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
println("PROBLEM")
}else{
other_nameBox.text = response.body()?.first_name + " " + response.body()?.last_name
other_name = other_nameBox.text.toString()
other_titleBox.text = response.body()?.title
other_aboutBox.text = response.body()?.biography
public = response.body()?.is_public!!
other_user_public = public
var isTrader = response.body()?.groups?.get(0).equals("trader")
profile_pic_url = response.body()?.photo
if(profile_pic_url != null) {
Picasso.get().load(profile_pic_url).into(profile_pic)
}
if(isTrader == true) {
other_traderImage.alpha = 1F
}
if(public == true) {
private_part_layout.visibility = View.VISIBLE
}
}
}else{
}
}
override fun onFailure(call: Call<GenericUserModel>, t: Throwable) {
}
})
RetrofitClient.instance.followerListID(other_id).enqueue(object :
Callback<GeneralFollowModel2> {
override fun onResponse(
call: Call<GeneralFollowModel2>,
response: Response<GeneralFollowModel2>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
println("NOT CHANGED")
}else{
var count = response.body()?.list?.count()!!.toString()
other_followerBox.text = count
}
}else{
}
}
override fun onFailure(call: Call<GeneralFollowModel2>, t: Throwable) {
}
})
RetrofitClient.instance.followingListID(other_id).enqueue(object :
Callback<GeneralFollowModel> {
override fun onResponse(
call: Call<GeneralFollowModel>,
response: Response<GeneralFollowModel>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
println("NOT CHANGED")
}else{
var count = response.body()?.list?.count()!!.toString()
other_followingBox.text = count
}
}else{
}
}
override fun onFailure(call: Call<GeneralFollowModel>, t: Throwable) {
}
})
other_followerButton.setOnClickListener { root ->
followList(root, "follower", other_id.toInt())
}
other_followingButton.setOnClickListener { root ->
followList(root, "following", other_id.toInt())
}
follow_user.setOnClickListener { root ->
follow_unfollow_user(root, other_id.toInt())
}
other_portfolioButton.setOnClickListener { root ->
myPortfolio(root)
}
return root
}
fun myPortfolio(view: View) {
val parentActivityManager : FragmentManager = activity?.supportFragmentManager as FragmentManager
fragmentTransaction(
parentActivityManager,
OtherPortfolioFragment.newInstance(other_name, other_id),
(containerId!!.id),
true,
true,
false
)
}
fun follow_unfollow_user(view: View, other_id : Int) {
if((isFollowing == 1) or (isFollowing == 2)) {
val follow_type = FollowIDModel(other_id)
RetrofitClient.instance.unfollowUser(follow_type).enqueue(object :
Callback<FollowIDModelResponse> {
override fun onResponse(
call: Call<FollowIDModelResponse>,
response: Response<FollowIDModelResponse>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
}else{
isFollowing = 0
follow_user.text = "FOLLOW"
follow_user.setBackgroundColor(Color.parseColor("#AA4AE608"))
reloadFragment(other_id)
}
}else{
}
}
override fun onFailure(call: Call<FollowIDModelResponse>, t: Throwable) {
}
})
} else{
val follow_type = FollowIDModel(other_id)
RetrofitClient.instance.followUser(follow_type).enqueue(object :
Callback<FollowIDModelResponse> {
override fun onResponse(
call: Call<FollowIDModelResponse>,
response: Response<FollowIDModelResponse>
) {
println(response.toString())
if(response.code() == 200 ){
if(response.body()?.detail != null){
}else{
if(other_user_public) {
isFollowing = 1
follow_user.text = "UNFOLLOW"
follow_user.setBackgroundColor(Color.parseColor("#AAB80707"))
reloadFragment(other_id)
}else {
isFollowing = 2
follow_user.text = "PENDING"
follow_user.setBackgroundColor(Color.parseColor("#AA976419"))
reloadFragment(other_id)
}
}
}else{
}
}
override fun onFailure(call: Call<FollowIDModelResponse>, t: Throwable) {
}
})
}
}
fun followList(view: View, request: String, other_id: Int) {
val parentActivityManager : FragmentManager = activity?.supportFragmentManager as FragmentManager
fragmentTransaction(
parentActivityManager,
FollowListFragment.newInstance(request, other_id),
(containerId!!.id),
true,
true,
false
)
}
fun reloadFragment(other_id: Int) {
var parentActivityManager: FragmentManager = activity?.supportFragmentManager as FragmentManager
removeFragment(parentActivityManager)
fragmentTransaction(
parentActivityManager,
OtherUserProfile.newInstance(other_id),
(containerId!!.id),
true,
true,
false
)
}
private val articleListListener = View.OnClickListener { view ->
val parentActivityManager : FragmentManager = activity?.supportFragmentManager as FragmentManager
fragmentTransaction(
parentActivityManager,
ListArticleFragment.newInstance(0,0,0,0,other_id_for_article),
(containerId!!.id),
true,
true,
false
)
}
companion object {
fun newInstance(id: Int): OtherUserProfile {
val fragmentUser = OtherUserProfile()
val args = Bundle()
args.putSerializable("id",id)
fragmentUser.arguments = args
return fragmentUser
}
}
}
| 32 | Kotlin | 2 | 9 | 9572fd307345b3f842c2c2ff4426857086484ed5 | 17,235 | bounswe2019group1 | MIT License |
yelp-fusion-android/src/main/java/com/jieheng/yelpfusion/model/Open.kt | JieHeng | 193,074,711 | false | null | package com.jieheng.yelpfusion.model
import com.google.gson.annotations.SerializedName
data class Open (
@SerializedName("is_overnight") val isOvernight : Boolean,
@SerializedName("start") val start : Int,
@SerializedName("end") val end : Int,
@SerializedName("day") val day : Int
) | 0 | Kotlin | 0 | 0 | 6094bf6a3d5214a61abd25e283af3a43e274047d | 300 | yelp-fusion-android | The Unlicense |
projects/manage-supervision-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/api/model/personalDetails/Document.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 3955601, "HTML": 68645, "D2": 30565, "Ruby": 25392, "Shell": 15576, "SCSS": 6240, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1344, "Python": 268} | package uk.gov.justice.digital.hmpps.api.model.personalDetails
import java.time.ZonedDateTime
data class Document(
val id: String,
val name: String,
val lastUpdated: ZonedDateTime?
)
| 9 | Kotlin | 0 | 2 | 47407ee1233a7a3dcee0aff33f328f100ba17ba5 | 197 | hmpps-probation-integration-services | MIT License |
biometric/src/main/java/dev/skomlach/biometric/compat/engine/internal/face/miui/impl/Miui3DFaceManagerImpl.kt | sergeykomlach | 317,847,167 | false | null | /*
* Copyright (c) 2023 <NAME> aka Salat-Cx65; Original project https://github.com/Salat-Cx65/AdvancedBiometricPromptCompat
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.skomlach.biometric.compat.engine.internal.face.miui.impl
import android.annotation.SuppressLint
import android.content.Context
import android.database.ContentObserver
import android.database.sqlite.SQLiteDatabase
import android.graphics.Point
import android.graphics.Rect
import android.graphics.RectF
import android.os.*
import android.provider.Settings
import android.view.Surface
import dev.skomlach.biometric.compat.engine.internal.face.miui.impl.BiometricClient.ServiceCallback
import dev.skomlach.biometric.compat.engine.internal.face.miui.impl.wrapper.*
import dev.skomlach.biometric.compat.utils.logging.BiometricLoggerImpl.d
import dev.skomlach.biometric.compat.utils.logging.BiometricLoggerImpl.e
import dev.skomlach.common.contextprovider.AndroidContext
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantLock
class Miui3DFaceManagerImpl : IMiuiFaceManager,
ServiceCallback {
companion object {
const val COMMAND_ENROLL_RESUME_ENROLL_LOGIC = 0
const val MSG_AUTHENTICATION_HELP_ALL_BLOCKED = 28
const val MSG_AUTHENTICATION_HELP_BAD_AMBIENT_LIGHT = 32
const val MSG_AUTHENTICATION_HELP_BOTH_EYE_BLOCKED = 25
const val MSG_AUTHENTICATION_HELP_BOTH_EYE_CLOSE = 31
const val MSG_AUTHENTICATION_HELP_FACE_AUTH_FAILD = 70
const val MSG_AUTHENTICATION_HELP_FACE_DETECT_FAIL = 20
const val MSG_AUTHENTICATION_HELP_FACE_DETECT_OK = 10
const val MSG_AUTHENTICATION_HELP_FACE_TOO_NEER = 33
const val MSG_AUTHENTICATION_HELP_LEFTEYE_MOUSE_BLOCKED = 26
const val MSG_AUTHENTICATION_HELP_LEFT_EYE_BLOCKED = 22
const val MSG_AUTHENTICATION_HELP_LEFT_EYE_CLOSE = 29
const val MSG_AUTHENTICATION_HELP_LIVING_BODY_DETECTION_FAILED = 63
const val MSG_AUTHENTICATION_HELP_MOUSE_BLOCKED = 24
const val MSG_AUTHENTICATION_HELP_RIGHTEYE_MOUSE_BLOCKED = 27
const val MSG_AUTHENTICATION_HELP_RIGHT_EYE_BLOCKED = 23
const val MSG_AUTHENTICATION_HELP_RIGHT_EYE_CLOSE = 30
const val MSG_AUTHENTICATION_STOP = 34
const val MSG_ENROLL_ENROLL_TIMEOUT = 66
const val MSG_ENROLL_ERROR_CREATE_FOLDER_FAILED = 52
const val MSG_ENROLL_ERROR_DISABLE_FAIL = 57
const val MSG_ENROLL_ERROR_ENABLE_FAIL = 50
const val MSG_ENROLL_ERROR_FACE_LOST = 62
const val MSG_ENROLL_ERROR_FLOOD_ITO_ERR = 41
const val MSG_ENROLL_ERROR_IR_CAM_CLOSED = 6
const val MSG_ENROLL_ERROR_LASER_ITO_ERR = 40
const val MSG_ENROLL_ERROR_LIVING_BODY_DETECTION_FAILED = 63
const val MSG_ENROLL_ERROR_NOT_SAME_PERSON = 58
const val MSG_ENROLL_ERROR_PREVIEW_CAM_ERROR = 5
const val MSG_ENROLL_ERROR_RTMV_IC_ERR = 53
const val MSG_ENROLL_ERROR_SAVE_TEMPLATE_FAILED = 51
const val MSG_ENROLL_ERROR_SDK_ERROR = 59
const val MSG_ENROLL_ERROR_SYSTEM_EXCEPTION = 54
const val MSG_ENROLL_ERROR_TEMLATE_FILE_NOT_EXIST = 56
const val MSG_ENROLL_ERROR_TOF_BE_COVERED = 64
const val MSG_ENROLL_ERROR_TOF_NOT_MOUNT = 65
const val MSG_ENROLL_ERROR_UNLOCK_FAIL = 55
const val MSG_ENROLL_FACE_IR_FOUND = 2
const val MSG_ENROLL_FACE_IR_NOT_FOUND = 4
const val MSG_ENROLL_FACE_RGB_FOUND = 1
const val MSG_ENROLL_FACE_RGB_NOT_FOUND = 3
const val MSG_ENROLL_HELP_ALL_BLOCKED = 28
const val MSG_ENROLL_HELP_BAD_AMBIENT_LIGHT = 32
const val MSG_ENROLL_HELP_BOTH_EYE_BLOCKED = 25
const val MSG_ENROLL_HELP_BOTH_EYE_CLOSE = 31
const val MSG_ENROLL_HELP_DIRECTION_DOWN = 13
const val MSG_ENROLL_HELP_DIRECTION_LEFT = 14
const val MSG_ENROLL_HELP_DIRECTION_RIGHT = 15
const val MSG_ENROLL_HELP_DIRECTION_UP = 12
const val MSG_ENROLL_HELP_FACE_DETECT_FAIL_NOT_IN_ROI = 21
const val MSG_ENROLL_HELP_FACE_DETECT_OK = 10
const val MSG_ENROLL_HELP_FACE_TOO_NEER = 33
const val MSG_ENROLL_HELP_IR_CAM_OPEND = 2
const val MSG_ENROLL_HELP_LEFTEYE_MOUSE_BLOCKED = 26
const val MSG_ENROLL_HELP_LEFT_EYE_BLOCKED = 22
const val MSG_ENROLL_HELP_LEFT_EYE_CLOSE = 29
const val MSG_ENROLL_HELP_MOUSE_BLOCKED = 24
const val MSG_ENROLL_HELP_PREVIEW_CAM_OPEND = 1
const val MSG_ENROLL_HELP_RIGHTEYE_MOUSE_BLOCKED = 27
const val MSG_ENROLL_HELP_RIGHT_EYE_BLOCKED = 23
const val MSG_ENROLL_HELP_RIGHT_EYE_CLOSE = 30
const val MSG_ENROLL_PROGRESS_SUCCESS = 0
const val TABLE_TEMPLATE_COLUMN_DATA = "data"
const val TABLE_TEMPLATE_COLUMN_GROUP_ID = "group_id"
const val TABLE_TEMPLATE_COLUMN_ID = "_id"
const val TABLE_TEMPLATE_COLUMN_NAME = "template_name"
const val TABLE_TEMPLATE_COLUMN_VALID = "valid"
const val TABLE_TEMPLATE_NAME = "_template"
private const val CANCEL_STATUS_DONE = 1
private const val CANCEL_STATUS_NONE = 0
private const val DB_STATUS_NONE = 0
private const val DB_STATUS_PREPARED = 2
private const val DB_STATUS_PREPARING = 1
private const val FACEUNLOCK_SUPPORT_SUPERPOWER = "faceunlock_support_superpower"
private const val FACE_UNLOCK_HAS_FEATURE = "face_unlock_has_feature_sl"
private const val FACE_UNLOCK_HAS_FEATURE_URI =
"content://settings/secure/face_unlock_has_feature_sl"
private const val POWERMODE_SUPERSAVE_OPEN = "power_supersave_mode_open"
private const val POWERMODE_SUPERSAVE_OPEN_URI =
"content://settings/secure/power_supersave_mode_open"
private const val RECEIVER_ON_AUTHENTICATION_TIMEOUT = 1
private const val RECEIVER_ON_ENROLL_TIMEOUT = 0
private const val TEMPLATE_PATH = "/data/user/0/com.xiaomi.biometric/files/"
private const val VERSION_1 = 1
private const val height = 4
private const val width = 3
private const val DEBUG = true
private const val LOG_TAG = "3DFaceManagerImpl"
private val lock = ReentrantLock()
private var INSTANCE = AtomicReference<IMiuiFaceManager?>(null)
fun getInstance(): IMiuiFaceManager? {
if (INSTANCE.get() != null && INSTANCE.get()?.isReleased == true) {
INSTANCE.set(null)
}
if (INSTANCE.get() == null) {
try {
lock.runCatching { this.lock() }
if (INSTANCE.get() == null) {
INSTANCE.set(Miui3DFaceManagerImpl())
}
} finally {
lock.runCatching {
this.unlock()
}
}
}
return INSTANCE.get()
}
}
private val hasEnrollFace = 0
private val mBinderLock = Any()
private val mEnrollParam = EnrollParam()
private lateinit var mSuperPowerOpenObserver: ContentObserver
private lateinit var mHasFaceDataObserver: ContentObserver
private val mMiuifaceList: List<Miuiface>? = null
private var boostFramework: Any? = null
private var mAuthenticationCallback: IMiuiFaceManager.AuthenticationCallback?
private var mBiometricClient: BiometricClient? = null
private var mDatabaseChanged = false
private var mDatabaseStatus = 0
private var mDisonnected = false
private var mEnrollmentCallback: IMiuiFaceManager.EnrollmentCallback?
private var mFaceInfo: FaceInfo? = null
private var mGroupIdMax = 0
private var mGroupItemList: MutableList<GroupItem?>? = null
private var mHandler: Handler
private var mHasFaceData = false
private var mIsSuperPower = false
override var isReleased = false
private set
private var mRemovalCallback: IMiuiFaceManager.RemovalCallback?
private var mRemovalMiuiface: Miuiface? = null
private var mTemplateIdMax = 0
private var mTemplateItemList: MutableList<TemplateItem?>? = null
private var mcancelStatus = 0
private var myDB: SQLiteDatabase? = null
private var myTemplateItemList: MutableList<TemplateItem?>? = null
private var sAcquireFunc: Method? = null
private var sPerfClass: Class<*>? = null
private var sReleaseFunc: Method? = null
private val context = AndroidContext.appContext
init {
mDisonnected = true
isReleased = false
mRemovalCallback = null
mAuthenticationCallback = null
mEnrollmentCallback = null
mHandler = ClientHandler(
context
)
mSuperPowerOpenObserver = object : ContentObserver(mHandler) {
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
mIsSuperPower = SettingsSystem.getIntForUser(
context.contentResolver,
POWERMODE_SUPERSAVE_OPEN,
0,
0
) != 0
}
}
mHasFaceDataObserver = object : ContentObserver(mHandler) {
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
mHasFaceData = SettingsSecure.getIntForUser(
context.contentResolver,
FACE_UNLOCK_HAS_FEATURE, 0, 0
) != 0
}
}
try {
// Secure.putIntForUser(this.context.getContentResolver(), FACEUNLOCK_SUPPORT_SUPERPOWER, 1, -2);
ContentResolverHelper.registerContentObserver(
context.contentResolver,
Settings.Secure.getUriFor(FACE_UNLOCK_HAS_FEATURE),
false,
mHasFaceDataObserver,
0
)
mHasFaceDataObserver.onChange(false)
ContentResolverHelper.registerContentObserver(
context.contentResolver,
Settings.System.getUriFor(POWERMODE_SUPERSAVE_OPEN),
false,
mSuperPowerOpenObserver,
0
)
mSuperPowerOpenObserver.onChange(false)
} catch (e: Throwable) {
e(e)
}
mBiometricClient = BiometricClient()
preloadBoostFramework()
tryConnectService()
}
private fun preloadBoostFramework() {
try {
sPerfClass = Class.forName("android.util.BoostFramework")
val constuctor = sPerfClass?.getConstructor()
boostFramework = constuctor?.newInstance()
sAcquireFunc =
sPerfClass?.getMethod("perfLockAcquire", Integer.TYPE, IntArray::class.java)
sReleaseFunc = sPerfClass?.getMethod("perfLockRelease")
d(LOG_TAG, "preload BoostFramework succeed.")
} catch (e: Exception) {
e(LOG_TAG, "preload class android.util.BoostFramework failed")
}
}
override fun onBiometricServiceConnected() {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("onBiometricServiceConnected ")
stringBuilder.append(this)
d(str, stringBuilder.toString())
mDisonnected = false
prepareDatabase()
}
override fun onBiometricServiceDisconnected() {
var str = LOG_TAG
var stringBuilder = StringBuilder()
stringBuilder.append("onBiometricServiceDisconnected ")
stringBuilder.append(this)
d(str, stringBuilder.toString())
if (!mDisonnected) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("xiaomi--> set mDisonnected true ")
stringBuilder.append(this)
d(str, stringBuilder.toString())
mDisonnected = true
release()
}
}
override fun onBiometricEventClassLoader(bundle: Bundle) {
if (BiometricConnect.DEBUG_LOG) {
d(LOG_TAG, "onBiometricEventClassLoader")
}
bundle.classLoader = BiometricConnect::class.java.classLoader
}
override fun release() {
val str: String
val stringBuilder: StringBuilder
if (isReleased) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("release ignore ")
stringBuilder.append(this)
e(str, stringBuilder.toString())
return
}
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("release ctx:")
stringBuilder.append(context)
stringBuilder.append(", this:")
stringBuilder.append(this)
d(str, stringBuilder.toString())
isReleased = true
}
override fun onBiometricEventCallback(module_id: Int, event: Int, arg1: Int, arg2: Int) {
val str: String
val stringBuilder: StringBuilder
if (module_id != 1) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricEventCallback ignore - module_id:+")
stringBuilder.append(module_id)
stringBuilder.append(" event: ")
stringBuilder.append(event)
stringBuilder.append(", arg1:")
stringBuilder.append(arg1)
stringBuilder.append(", arg2:")
stringBuilder.append(arg2)
e(str, stringBuilder.toString())
} else if (mDisonnected) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricEventCallback mDisonnected:")
stringBuilder.append(mDisonnected)
stringBuilder.append(" ignore event: ")
stringBuilder.append(event)
stringBuilder.append(", arg1:")
stringBuilder.append(arg1)
stringBuilder.append(", arg2:")
stringBuilder.append(arg2)
e(str, stringBuilder.toString())
} else {
var str2: String
var stringBuilder2: StringBuilder
if (BiometricConnect.DEBUG_LOG) {
str2 = LOG_TAG
stringBuilder2 = StringBuilder()
stringBuilder2.append("onBiometricEventCallback - event: ")
stringBuilder2.append(event)
stringBuilder2.append(", arg1:")
stringBuilder2.append(arg1)
stringBuilder2.append(", arg2:")
stringBuilder2.append(arg2)
d(str2, stringBuilder2.toString())
}
if (event == 0) {
val enrollmentCallback = mEnrollmentCallback
enrollmentCallback?.onEnrollmentHelp(1, null)
} else if (event != 1) {
if (!(event == 2 || event == 3)) {
var enrollmentCallback2: IMiuiFaceManager.EnrollmentCallback?
if (event != 4) {
when (event) {
20 -> {
enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
enrollmentCallback2.onEnrollmentHelp(2, null)
}
}
21 -> if (BiometricConnect.DEBUG_LOG) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricEventCallback MSG_CB_EVENT_IR_CAM_PREVIEW_SIZE arg1:")
stringBuilder.append(arg1)
stringBuilder.append(",arg2:")
stringBuilder.append(arg2)
d(str, stringBuilder.toString())
}
22 -> {
}
23 -> d(LOG_TAG, "MSG_CB_EVENT_IR_CAM_CLOSED")
24 -> {
enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
enrollmentCallback2.onEnrollmentError(6, null)
cancelEnrollment()
}
}
else -> when (event) {
30 -> {
str2 = LOG_TAG
stringBuilder2 = StringBuilder()
stringBuilder2.append("onBiometricEventCallback MSG_CB_EVENT_ENROLL_SUCCESS mEnrollmentCallback:")
stringBuilder2.append(mEnrollmentCallback)
d(str2, stringBuilder2.toString())
val enrollmentCallback3 = mEnrollmentCallback
if (enrollmentCallback3 != null) {
enrollmentCallback3.onEnrollmentProgress(0, arg1)
//Secure.putIntForUser(this.context.getContentResolver(), FACE_UNLOCK_HAS_FEATURE, 1, -2);
try {
lock.runCatching { this.lock() }
mDatabaseStatus = 0
prepareDatabase()
} finally {
lock.runCatching {
this.unlock()
}
}
}
}
31 -> {
enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
enrollmentCallback2.onEnrollmentHelp(arg1, null)
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("MSG_CB_EVENT_ENROLL_ERROR arg1 = ")
stringBuilder.append(arg1)
d(str, stringBuilder.toString())
}
}
32 -> {
str = LOG_TAG
stringBuilder2 = StringBuilder()
stringBuilder2.append("MSG_CB_EVENT_ENROLL_INFO arg1 = ")
stringBuilder2.append(arg1)
d(str, stringBuilder2.toString())
enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
enrollmentCallback2.onEnrollmentHelp(arg1, null)
}
}
else -> {
val authenticationCallback: IMiuiFaceManager.AuthenticationCallback?
when (event) {
40 -> {
str = LOG_TAG
stringBuilder2 = StringBuilder()
stringBuilder2.append("onBiometricEventCallback MSG_CB_EVENT_VERIFY_SUCCESS mAuthenticationCallback:")
stringBuilder2.append(mAuthenticationCallback)
d(str, stringBuilder2.toString())
authenticationCallback = mAuthenticationCallback
if (authenticationCallback != null) {
authenticationCallback.onAuthenticationSucceeded(
null
)
cancelAuthentication()
}
}
41 -> {
authenticationCallback = mAuthenticationCallback
if (authenticationCallback != null) {
authenticationCallback.onAuthenticationHelp(
70,
null
)
}
}
42 -> {
authenticationCallback = mAuthenticationCallback
if (authenticationCallback != null) {
authenticationCallback.onAuthenticationHelp(
arg1,
null
)
}
}
43 -> {
val removalCallback = mRemovalCallback
if (removalCallback != null) {
removalCallback.onRemovalSucceeded(
mRemovalMiuiface,
mMiuifaceList?.size ?: 0
)
mRemovalCallback = null
mRemovalMiuiface = null
}
}
}
}
}
}
}
enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
enrollmentCallback2.onEnrollmentError(5, null)
cancelEnrollment()
}
}
} else if (BiometricConnect.DEBUG_LOG) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricEventCallback MSG_CB_EVENT_RGB_CAM_PREVIEW_SIZE mEnrollmentCallback:")
stringBuilder.append(mEnrollmentCallback)
stringBuilder.append(" arg1:")
stringBuilder.append(arg1)
stringBuilder.append(",arg2:")
stringBuilder.append(arg2)
d(str, stringBuilder.toString())
}
}
}
override fun onBiometricBundleCallback(module_id: Int, key: Int, bundle: Bundle) {
val str: String
val stringBuilder: StringBuilder
if (module_id != 1) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricBundleCallback ignore module_id:")
stringBuilder.append(module_id)
stringBuilder.append(", key:")
stringBuilder.append(key)
e(str, stringBuilder.toString())
} else if (mDisonnected) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricBundleCallback mDisonnected:")
stringBuilder.append(mDisonnected)
stringBuilder.append(" ignore key:")
stringBuilder.append(key)
e(str, stringBuilder.toString())
} else {
if (BiometricConnect.DEBUG_LOG) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("onBiometricBundleCallback key:")
stringBuilder.append(key)
d(str, stringBuilder.toString())
}
if (key == 2) {
handlerFace(bundle)
} else if (key == 3) {
handlerDatabase(bundle)
} else if (key != 5) {
}
}
}
override val isFaceFeatureSupport: Boolean
get() = if (mIsSuperPower) {
d(
LOG_TAG,
"enter super power mode, isFaceFeatureSupport:false"
)
false
} else if (MiuiBuild.IS_INTERNATIONAL_BUILD) {
false
} else {
"ursa" == MiuiBuild.DEVICE
}
override val isSupportScreenOnDelayed: Boolean
get() = false
override val isFaceUnlockInited: Boolean
get() = false
override val managerVersion: Int
get() = 1
override val vendorInfo: String
get() = "3D Structure Light"
private fun handlerDatabase(bundle: Bundle) {
if (mDatabaseStatus != 1) {
e(LOG_TAG, "handlerDatabase mDatabaseStatus ignore")
return
}
if (BiometricConnect.DEBUG_LOG) {
d(LOG_TAG, "handlerDatabase ")
}
mTemplateIdMax = bundle.getInt(BiometricConnect.MSG_CB_BUNDLE_DB_TEMPLATE_ID_MAX)
mGroupIdMax = bundle.getInt(BiometricConnect.MSG_CB_BUNDLE_DB_GROUP_ID_MAX)
val listGroup = bundle.getParcelableArrayList<Parcelable>("group")
if (BiometricConnect.DEBUG_LOG) {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("handlerDatabase listGroup:")
stringBuilder.append(listGroup?.size)
d(str, stringBuilder.toString())
}
val listTemplate =
bundle.getParcelableArrayList<Parcelable>(BiometricConnect.MSG_CB_BUNDLE_DB_TEMPLATE)
if (BiometricConnect.DEBUG_LOG) {
val str2 = LOG_TAG
val stringBuilder2 = StringBuilder()
stringBuilder2.append("handlerDatabase list:")
stringBuilder2.append(listTemplate?.size)
d(str2, stringBuilder2.toString())
}
initClientDB(listGroup, listTemplate)
}
private fun initClientDB(listGroup: ArrayList<Parcelable>?, list: ArrayList<Parcelable>?) {
if (mDatabaseStatus != 2 || mDatabaseChanged) {
d(LOG_TAG, "initClientDB begin")
mTemplateItemList = ArrayList<TemplateItem?>()
var it: Iterator<*> = list?.iterator() ?: listOf<TemplateItem?>().iterator()
var clazz: Class<*>? = null
while (it.hasNext()) {
val i = it.next()
try {
if (clazz == null) {
clazz = i?.javaClass
}
clazz?.let {
val item = TemplateItem()
item.id = it.getField("mId").getInt(i)
item.name = it.getField("mName").get(i) as String
item.group_id = it.getField("mGroupId").getInt(i)
item.data = it.getField("mData").get(i) as String
mTemplateItemList?.add(item)
}
} catch (e: Throwable) {
e(e)
}
}
mGroupItemList = ArrayList<GroupItem?>()
it = listGroup?.iterator() ?: listOf<TemplateItem?>().iterator()
clazz = null
while (it.hasNext()) {
val group: Any? = it.next()
try {
if (clazz == null) {
clazz = group?.javaClass
}
clazz?.let {
val groupItem = GroupItem()
groupItem.id = it.getField("mId").getInt(group)
groupItem.name = it.getField("mName").get(group) as String
mGroupItemList?.add(groupItem)
}
} catch (e: Throwable) {
e(e)
}
}
clazz = null
mDatabaseStatus = 2
mDatabaseChanged = false
d(LOG_TAG, "initClientDB ok")
}
}
private fun prepareDatabase() {
if (mDatabaseStatus != 0) {
e(LOG_TAG, "prepareDatabase ignore!")
return
}
d(LOG_TAG, "prepareDatabase")
mDatabaseStatus = 1
mBiometricClient?.sendCommand(9)
}
private fun resetDatabase() {
if (mDatabaseStatus != 2) {
e(LOG_TAG, "resetDatabase ignore!")
return
}
d(LOG_TAG, "resetDatabase")
mDatabaseStatus = 1
mBiometricClient?.sendCommand(10)
}
private fun commitDatabase() {
if (isReleased) {
e(LOG_TAG, "commitDatabase ignore!")
} else if (mDatabaseChanged) {
d(LOG_TAG, "commitDatabase")
val out_bundle = Bundle()
out_bundle.classLoader = BiometricConnect::class.java.classLoader
val listGroup: ArrayList<Parcelable?> = ArrayList<Parcelable?>()
mGroupItemList?.let {
for (g in it) {
if (g != null)
listGroup.add(BiometricConnect.getDBGroup(g.id, g.name))
}
}
out_bundle.putParcelableArrayList("group", listGroup)
val listTemplate: ArrayList<Parcelable?> = ArrayList<Parcelable?>()
mTemplateItemList?.let {
for (i in it) {
if (i != null)
listTemplate.add(
BiometricConnect.getDBTemplate(
i.id,
i.name,
i.data,
i.group_id
)
)
}
}
out_bundle.putParcelableArrayList(
BiometricConnect.MSG_CB_BUNDLE_DB_TEMPLATE,
listTemplate
)
mBiometricClient?.sendBundle(4, out_bundle)
}
}
private fun handlerFace(bundle: Bundle) {
if (mEnrollmentCallback != null) {
if (BiometricConnect.DEBUG_LOG) {
d(LOG_TAG, "handlerFace ")
}
val is_ir_detect = bundle.getBoolean(BiometricConnect.MSG_CB_BUNDLE_FACE_IS_IR)
if (bundle.getBoolean(BiometricConnect.MSG_CB_BUNDLE_FACE_HAS_FACE)) {
if (mFaceInfo == null) {
mFaceInfo = FaceInfo()
}
val parcelable =
bundle.getParcelable<Parcelable>(BiometricConnect.MSG_CB_BUNDLE_FACE_RECT_BOUND)
if (parcelable is Rect) {
mFaceInfo?.bounds = parcelable
if (BiometricConnect.DEBUG_LOG) {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("handlerFace detect face:")
stringBuilder.append(mFaceInfo?.bounds.toString())
d(str, stringBuilder.toString())
}
}
mFaceInfo?.yaw = bundle.getFloat(BiometricConnect.MSG_CB_BUNDLE_FACE_FLOAT_YAW)
mFaceInfo?.pitch = bundle.getFloat("pitch")
mFaceInfo?.roll = bundle.getFloat(BiometricConnect.MSG_CB_BUNDLE_FACE_FLOAT_ROLL)
mFaceInfo?.eye_dist =
bundle.getFloat(BiometricConnect.MSG_CB_BUNDLE_FACE_FLOAT_EYE_DIST)
try {
val parcelables =
bundle.getParcelableArray(BiometricConnect.MSG_CB_BUNDLE_FACE_POINTS_ARRAY)
mFaceInfo?.points_array = parcelables as Array<Point?>
} catch (cc: Exception) {
}
if (!is_ir_detect) {
val enrollmentCallback = mEnrollmentCallback
if (enrollmentCallback != null) {
enrollmentCallback.onEnrollmentHelp(1, null)
return
}
}
if (is_ir_detect && mEnrollmentCallback != null) {
val z = mEnrollParam.enableDistanceDetect
mEnrollmentCallback?.onEnrollmentHelp(2, null)
}
return
}
val enrollmentCallback2 = mEnrollmentCallback
if (enrollmentCallback2 != null) {
val i: Int = if (is_ir_detect) {
4
} else {
3
}
enrollmentCallback2.onEnrollmentHelp(i, null)
}
}
}
override fun hasEnrolledFaces(): Int {
tryConnectService()
return if (mHasFaceData) {
1
} else 0
}
override fun remove(face: Miuiface, callback: IMiuiFaceManager.RemovalCallback) {
if (isReleased) {
e(LOG_TAG, "removeTemplate ignore!")
} else if (mDatabaseStatus != 2) {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("removeTemplate error mDatabaseStatus :")
stringBuilder.append(mDatabaseStatus)
d(str, stringBuilder.toString())
} else {
val templateItem = findTemplate(face.miuifaceId)
if (templateItem == null) {
val str2 = LOG_TAG
val stringBuilder2 = StringBuilder()
stringBuilder2.append("removeTemplate findTemplate ")
stringBuilder2.append(face.miuifaceId)
stringBuilder2.append(" is null")
d(str2, stringBuilder2.toString())
return
}
d(LOG_TAG, "removeTemplate")
mTemplateItemList?.remove(templateItem)
// Secure.putIntForUser(this.context.getContentResolver(), FACE_UNLOCK_HAS_FEATURE, 0, -2);
mDatabaseChanged = true
mRemovalCallback = callback
mRemovalMiuiface = face
commitDatabase()
}
}
private fun findTemplate(id: Int): TemplateItem? {
mTemplateItemList?.let {
for (i in it) {
if (i?.id == id) {
return i
}
}
}
return null
}
val templatepath: Int
@SuppressLint("Range")
get() {
val dbFile = File(TEMPLATE_PATH, "biometric.db")
if (dbFile.exists()) {
d(LOG_TAG, "getTemplatepath")
myDB = SQLiteDatabase.openDatabase(dbFile.path, null, 0)
myTemplateItemList = ArrayList<TemplateItem?>()
d(LOG_TAG, "selectTemplate")
val cursor = myDB?.rawQuery(
"select _id,data,template_name,group_id from _template where valid=1",
null
)
if (cursor?.moveToFirst() == true) {
e(LOG_TAG, "xiaomi -->4.3 test")
val t = TemplateItem()
t.id = cursor.getInt(cursor.getColumnIndex("_id"))
t.name = cursor.getString(cursor.getColumnIndex(TABLE_TEMPLATE_COLUMN_NAME))
t.group_id = cursor.getInt(cursor.getColumnIndex("group_id"))
t.data = cursor.getString(cursor.getColumnIndex("data"))
myTemplateItemList?.add(t)
}
cursor?.close()
return myTemplateItemList?.size ?: 0
}
d(LOG_TAG, "getTemplatepath faild")
return 0
}
private fun getMessageInfo(msgId: Int): String {
val msg = "define by 3dclient"
if (msgId == 34) {
return "Be cancel"
}
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("default msgId: ")
stringBuilder.append(msgId)
d(str, stringBuilder.toString())
return msg
}
private fun tryConnectService() {
if (mDisonnected) {
e(LOG_TAG, "mDisonnected is true ")
mDatabaseStatus = 0
mBiometricClient?.startService(this)
}
}
override fun rename(faceId: Int, name: String) {
if (isReleased) {
e(LOG_TAG, "setTemplateName ignore!")
} else if (mDatabaseStatus != 2) {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("setTemplateName error mPrepareDbStatus:")
stringBuilder.append(mDatabaseStatus)
d(str, stringBuilder.toString())
} else {
val templateItem = findTemplate(faceId)
if (templateItem == null) {
val str2 = LOG_TAG
val stringBuilder2 = StringBuilder()
stringBuilder2.append("setTemplateName findTemplate ")
stringBuilder2.append(faceId)
stringBuilder2.append(" is null")
d(str2, stringBuilder2.toString())
return
}
d(LOG_TAG, "setTemplateName")
templateItem.name = name
mDatabaseChanged = true
commitDatabase()
}
}
override val enrolledFaces: List<Miuiface?>
get() {
val res: MutableList<Miuiface?> = ArrayList<Miuiface?>()
e(LOG_TAG, " xiaomi getEnrolledFaces!")
mTemplateItemList?.let {
for (i in it) {
if (i != null) {
res.add(Miuiface(i.name, i.group_id, i.id, 0))
}
}
}
return res
}
override fun preInitAuthen() {
tryConnectService()
}
private fun cancelAuthentication() {
val str: String
val stringBuilder: StringBuilder
if (isReleased) {
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("stopVerify ctx:")
stringBuilder.append(context)
stringBuilder.append(" ignore!")
e(str, stringBuilder.toString())
return
}
if (mcancelStatus != 0) {
mAuthenticationCallback?.onAuthenticationError(34, getMessageInfo(34))
mcancelStatus = 0
}
try {
if (sReleaseFunc != null) {
sReleaseFunc?.invoke(boostFramework)
}
} catch (e: IllegalAccessException) {
e(e)
} catch (e2: InvocationTargetException) {
e(e2)
}
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("cancelAuthentication ctx:")
stringBuilder.append(context)
d(str, stringBuilder.toString())
mAuthenticationCallback = null
mBiometricClient?.sendCommand(6)
mHandler.removeMessages(1)
}
override fun authenticate(
cancel: CancellationSignal?,
flags: Int,
callback: IMiuiFaceManager.AuthenticationCallback?,
handler: Handler?,
timeout: Int
) {
var str = " ignore!"
val str2 = "start authenticate ctx:"
val str3: String
val stringBuilder: StringBuilder
if (isReleased) {
str3 = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append(str2)
stringBuilder.append(context)
stringBuilder.append(str)
e(str3, stringBuilder.toString())
} else if (hasEnrolledFaces() == 0) {
str3 = LOG_TAG
val stringBuilder2 = StringBuilder()
stringBuilder2.append("has no enrolled face ctx:")
stringBuilder2.append(context)
stringBuilder2.append(str)
e(str3, stringBuilder2.toString())
} else if (callback != null) {
if (cancel != null) {
if (cancel.isCanceled) {
d(LOG_TAG, "authentication already canceled")
return
}
cancel.setOnCancelListener(OnAuthenticationCancelListener())
}
try {
if (sAcquireFunc != null) {
val method = sAcquireFunc
val obj = boostFramework
val objArr = arrayOfNulls<Any>(2)
objArr[0] = 2000
objArr[1] = intArrayOf(1082130432, 4095, 1086324736, 1)
method?.invoke(obj, *objArr)
}
} catch (e: IllegalAccessException) {
e(e)
} catch (e2: InvocationTargetException) {
e(e2)
}
str = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append(str2)
stringBuilder.append(context)
d(str, stringBuilder.toString())
useHandler(handler)
mAuthenticationCallback = callback
tryConnectService()
mBiometricClient?.sendCommand(5)
val handler2 = mHandler
handler2.sendMessageDelayed(handler2.obtainMessage(1), timeout.toLong())
} else {
throw IllegalArgumentException("Must supply an authentication callback")
}
}
private fun cancelEnrollment() {
if (isReleased) {
e(LOG_TAG, "stopEnroll ignore!")
return
}
d(LOG_TAG, "stopEnroll")
mBiometricClient?.sendCommand(8)
mBiometricClient?.sendCommand(4)
mHandler.removeMessages(0)
}
private fun adjustDetectZone(detect_zone: FloatArray?) {
if (detect_zone != null && detect_zone.size >= 4) {
for (i in detect_zone.indices) {
val temp = detect_zone[i]
if (i % 2 == 1) {
if (i < 4) {
detect_zone[i] = IrToRgbScale(detect_zone[i], 1.18f)
} else {
detect_zone[i] = IrToRgbScale(detect_zone[i], 1.06f)
}
detect_zone[i] = IrToRgbMove(detect_zone[i], -0.067f)
detect_zone[i] = IrToRgbRadio(detect_zone[i])
} else {
if (i < 4) {
detect_zone[i] = IrToRgbScale(detect_zone[i], 1.16f)
} else {
detect_zone[i] = IrToRgbScale(detect_zone[i], 1.05f)
}
detect_zone[i] = IrToRgbMove(detect_zone[i], -0.044f)
}
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("adjustDetectZone ")
stringBuilder.append(i)
stringBuilder.append(": ")
stringBuilder.append(temp)
stringBuilder.append(" to ")
stringBuilder.append(detect_zone[i])
d(str, stringBuilder.toString())
}
}
}
private fun IrToRgbRadio(x: Float): Float {
return (12.0f * x - 1.0f) / 10.0f
}
private fun IrToRgbMove(x: Float, offset: Float): Float {
return x + offset
}
private fun IrToRgbScale(x: Float, zoom: Float): Float {
return if (x > 0.5f) x * zoom else 0.5f - (0.5f - x) * zoom
}
override fun enroll(
cryptoToken: ByteArray?,
cancel: CancellationSignal,
flags: Int,
enrollCallback: IMiuiFaceManager.EnrollmentCallback?,
surface: Surface?,
detectArea: Rect?,
timeout: Int
) {
}
override fun enroll(
cryptoToken: ByteArray?,
cancel: CancellationSignal,
flags: Int,
enrollCallback: IMiuiFaceManager.EnrollmentCallback?,
surface: Surface?,
detectArea: RectF?,
enrollArea: RectF,
timeout: Int
) {
var str: String?
val i: Int
if (isReleased) {
e(LOG_TAG, "enroll ignore!")
}
val timeout2: Int = if (timeout == 0) {
180000
} else {
timeout
}
if (surface == null || timeout2 < 2000) {
e(LOG_TAG, "enroll error!")
}
val str2 = "]"
val str3 = ","
if (BiometricConnect.DEBUG_LOG) {
var str4 = LOG_TAG
var stringBuilder = StringBuilder()
stringBuilder.append("xiaomi detectArea data:[")
stringBuilder.append(detectArea)
stringBuilder.append(str3)
stringBuilder.append(detectArea?.left)
stringBuilder.append(str3)
stringBuilder.append(detectArea?.right)
stringBuilder.append(str3)
stringBuilder.append(detectArea?.top)
stringBuilder.append(str3)
stringBuilder.append(detectArea?.bottom)
stringBuilder.append(str2)
e(str4, stringBuilder.toString())
str4 = LOG_TAG
stringBuilder = StringBuilder()
stringBuilder.append("xiaomi enrollArea data:[")
stringBuilder.append(enrollArea)
stringBuilder.append(str3)
stringBuilder.append(enrollArea.left)
stringBuilder.append(str3)
stringBuilder.append(enrollArea.right)
stringBuilder.append(str3)
stringBuilder.append(enrollArea.top)
stringBuilder.append(str3)
stringBuilder.append(enrollArea.bottom)
stringBuilder.append(str2)
e(str4, stringBuilder.toString())
}
if (cancel.isCanceled) {
d(
LOG_TAG,
"enrollment already canceled"
)
return
}
cancel.setOnCancelListener(OnEnrollCancelListener())
val bundle_preview = Bundle()
mEnrollmentCallback = enrollCallback
bundle_preview.putParcelable("surface", surface)
bundle_preview.putInt("width", 3)
bundle_preview.putInt("height", 4)
tryConnectService()
mBiometricClient?.sendBundle(1, bundle_preview)
mBiometricClient?.sendCommand(3, 0)
detectArea?.let {
mEnrollParam.rectDetectZones = FRect(
it.left,
it.top, it.right, it.bottom
)
}
mEnrollParam.rectEnrollZones = FRect(
enrollArea.left,
enrollArea.top,
enrollArea.right,
enrollArea.bottom
)
val enrollParam = mEnrollParam
enrollParam.enableDistanceDetect = false
enrollParam.enableIrFaceDetect = true
enrollParam.enableDepthmap = false
enrollParam.enrollWaitUi = true
var detect_zone = floatArrayOf()
enrollParam.rectDetectZones?.let {
detect_zone = floatArrayOf(
it.top,
1.0f - it.right,
it.bottom,
1.0f - it.left,
it.top,
1.0f - it.right,
it.bottom,
1.0f - it.left
)
}
adjustDetectZone(detect_zone)
if (BiometricConnect.DEBUG_LOG) {
val str5 = LOG_TAG
val stringBuilder2 = StringBuilder()
stringBuilder2.append("startEnroll rectDetectZones:[")
stringBuilder2.append(mEnrollParam.rectDetectZones?.left)
stringBuilder2.append(str3)
stringBuilder2.append(mEnrollParam.rectDetectZones?.top)
stringBuilder2.append(str3)
stringBuilder2.append(mEnrollParam.rectDetectZones?.right)
stringBuilder2.append(str3)
stringBuilder2.append(mEnrollParam.rectDetectZones?.bottom)
val str6 = "] adjustDetectZone -> ["
stringBuilder2.append(str6)
stringBuilder2.append(detect_zone[0])
stringBuilder2.append(str3)
stringBuilder2.append(detect_zone[1])
stringBuilder2.append(str3)
stringBuilder2.append(detect_zone[2])
stringBuilder2.append(str3)
stringBuilder2.append(detect_zone[3])
stringBuilder2.append(str2)
d(str5, stringBuilder2.toString())
str = LOG_TAG
val stringBuilder3 = StringBuilder()
stringBuilder3.append("startEnroll rectEnrollZones:[")
stringBuilder3.append(mEnrollParam.rectEnrollZones?.left)
stringBuilder3.append(str3)
stringBuilder3.append(mEnrollParam.rectEnrollZones?.top)
stringBuilder3.append(str3)
stringBuilder3.append(mEnrollParam.rectEnrollZones?.right)
stringBuilder3.append(str3)
stringBuilder3.append(mEnrollParam.rectEnrollZones?.bottom)
stringBuilder3.append(str6)
stringBuilder3.append(detect_zone[4])
stringBuilder3.append(str3)
stringBuilder3.append(detect_zone[5])
stringBuilder3.append(str3)
stringBuilder3.append(detect_zone[6])
stringBuilder3.append(str3)
stringBuilder3.append(detect_zone[7])
stringBuilder3.append(str2)
d(str, stringBuilder3.toString())
}
val bundle_enroll = Bundle()
bundle_enroll.putFloatArray(
BiometricConnect.MSG_CB_BUNDLE_ENROLL_PARAM_DETECT_ZONE,
detect_zone
)
bundle_enroll.putBoolean(
BiometricConnect.MSG_CB_BUNDLE_ENROLL_PARAM_DETECT_FACE,
mEnrollParam.enableIrFaceDetect
)
bundle_enroll.putBoolean(
BiometricConnect.MSG_CB_BUNDLE_ENROLL_PARAM_DETECT_DISTANCE,
mEnrollParam.enableDistanceDetect
)
bundle_enroll.putBoolean(
BiometricConnect.MSG_CB_BUNDLE_ENROLL_PARAM_WAITING_UI,
mEnrollParam.enrollWaitUi
)
val z = mEnrollParam.enableDepthmap
str = BiometricConnect.MSG_CB_BUNDLE_ENROLL_PARAM_DETECT_DEPTHMAP
if (z) {
bundle_enroll.putInt(str, mEnrollParam.DepthmpaType)
i = 0
} else {
i = 0
bundle_enroll.putInt(str, 0)
}
mBiometricClient?.sendBundle(6, bundle_enroll)
mBiometricClient?.sendCommand(7)
val handler = mHandler
handler.sendMessageDelayed(handler.obtainMessage(i), timeout2.toLong())
}
private fun useHandler(handler: Handler?) {
if (handler != null) {
mHandler = ClientHandler(handler.looper)
} else if (mHandler.looper != context.mainLooper) {
mHandler = ClientHandler(
context.mainLooper
)
}
}
override fun extCmd(cmd: Int, param: Int): Int {
if (cmd != 0) {
return -1
}
mBiometricClient?.sendCommand(14, param)
return 0
}
override fun addLockoutResetCallback(callback: IMiuiFaceManager.LockoutResetCallback?) {
if (DEBUG) {
val str = LOG_TAG
val stringBuilder = StringBuilder()
stringBuilder.append("addLockoutResetCallback callback:")
stringBuilder.append(callback)
d(str, stringBuilder.toString())
}
}
override fun resetTimeout(token: ByteArray) {
if (DEBUG) {
d(LOG_TAG, "resetTimeout")
}
}
class EnrollParam {
var DepthmpaType = 0
var enableDepthmap = false
var enableDistanceDetect = false
var enableIrFaceDetect = false
var enrollWaitUi = false
var rectDetectZones: FRect? = null
var rectEnrollZones: FRect? = null
}
class FRect(var left: Float, var top: Float, var right: Float, var bottom: Float)
class FaceInfo {
var bounds: Rect? = null
var eye_dist = 0f
var pitch = 0f
var points_array: Array<Point?> = arrayOf()
var roll = 0f
var yaw = 0f
}
class GroupItem {
var id = 0
var name: String? = null
}
class TemplateItem {
var data: String? = null
var group_id = 0
var id = 0
var name: String? = null
}
private inner class ClientHandler : Handler {
constructor(context: Context) : super(context.mainLooper)
constructor(looper: Looper) : super(looper)
override fun handleMessage(msg: Message) {
if (DEBUG) {
val stringBuilder = StringBuilder()
stringBuilder.append(" handleMessage callback what:")
stringBuilder.append(msg.what)
d(LOG_TAG, stringBuilder.toString())
}
val i = msg.what
if (i != 0) {
if (i == 1 && mAuthenticationCallback != null) {
d(LOG_TAG, "xiaomi ---> RECEIVER_ON_AUTHENTICATION_TIMEOUT")
mAuthenticationCallback?.onAuthenticationFailed()
cancelAuthentication()
}
} else if (mEnrollmentCallback != null) {
mEnrollmentCallback?.onEnrollmentError(66, null)
d(LOG_TAG, "RECEIVER_ON_ENROLL_TIMEOUT")
cancelEnrollment()
}
}
}
private inner class OnAuthenticationCancelListener :
CancellationSignal.OnCancelListener {
override fun onCancel() {
mcancelStatus = 1
cancelAuthentication()
}
}
private inner class OnEnrollCancelListener :
CancellationSignal.OnCancelListener {
override fun onCancel() {
cancelEnrollment()
}
}
} | 9 | null | 5 | 94 | 9555725a28227e28079a6dbc5da7c91d8b9634bb | 55,009 | AdvancedBiometricPromptCompat | Apache License 2.0 |
react-table-kotlin/src/jsMain/kotlin/tanstack/table/core/isSubRowSelected.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("@tanstack/table-core")
@file:JsNonModule
package tanstack.table.core
import kotlinx.js.ReadonlyRecord
external fun <TData : RowData> isSubRowSelected(
row: Row<TData>,
selection: ReadonlyRecord<String, Boolean>,
table: Table<TData>,
): Any /* Boolean | 'some' | 'all' */
| 0 | null | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 347 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/quixom/apps/deviceinfo/views/CPUView.kt | code4lifevn | 116,898,728 | true | {"Java": 481337, "Kotlin": 113550} | package com.quixom.apps.deviceinfo.views
import android.view.Gravity
import android.widget.LinearLayout
import com.quixom.apps.deviceinfo.fragments.CPUFragment
import org.jetbrains.anko.*
/**
* Created by akif on 9/25/17.
*/
class CPUView : AnkoComponent<CPUFragment> {
private lateinit var ankoContext: AnkoContext<CPUFragment>
override fun createView(ui: AnkoContext<CPUFragment>) = with(ui) {
ankoContext = ui
verticalLayout {
this.gravity = Gravity.CENTER
lparams(width = matchParent, height = matchParent)
linearLayout {
orientation = LinearLayout.HORIZONTAL
}
}
}
} | 0 | Java | 1 | 0 | ae60e9bdfd01e1c6a7541f2526845535e9f5848f | 682 | DeviceInfo | Apache License 2.0 |
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TestOwner.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.semantics.getAllSemanticsNodes
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
/**
* Provides necessary services to facilitate testing.
*
* This is typically implemented by entities like test rule.
*/
@InternalTestApi
interface TestOwner {
/**
* Clock that drives frames and recompositions in compose tests.
*/
val mainClock: MainTestClock
/**
* Sends the given list of text commands to the given semantics node.
*/
fun sendTextInputCommand(node: SemanticsNode, command: List<EditCommand>)
/**
* Sends the given IME action to the given semantics node.
*/
fun sendImeAction(node: SemanticsNode, actionSpecified: ImeAction)
/**
* Runs the given [action] on the ui thread.
*
* This is a blocking call.
*/
// TODO: Does ui-test really need it? Can it use coroutine context on Owner?
fun <T> runOnUiThread(action: () -> T): T
/**
* Collects all [RootForTest]s from all compose hierarchies.
*
* This is a blocking call. Returns only after compose is idle.
*
* Can crash in case it hits time out. This is not supposed to be handled as it
* surfaces only in incorrect tests.
*
* @param atLeastOneRootExpected Whether the caller expects that at least one compose root is
* present in the tested app. This affects synchronization efforts / timeouts of this API.
*/
fun getRoots(atLeastOneRootExpected: Boolean): Set<RootForTest>
}
@InternalTestApi
fun createTestContext(owner: TestOwner): TestContext {
return TestContext(owner)
}
@OptIn(InternalTestApi::class)
class TestContext internal constructor(internal val testOwner: TestOwner) {
/**
* Stores the [InputDispatcherState] of each [RootForTest]. The state will be restored in an
* [InputDispatcher] when it is created for an owner that has a state stored. To avoid leaking
* the [RootForTest], the [identityHashCode] of the root is used as the key instead of the
* actual object.
*/
internal val states = mutableMapOf<Int, InputDispatcherState>()
/**
* Collects all [SemanticsNode]s from all compose hierarchies.
*
* This is a blocking call. Returns only after compose is idle.
*
* Can crash in case it hits time out. This is not supposed to be handled as it
* surfaces only in incorrect tests.
*/
internal fun getAllSemanticsNodes(
atLeastOneRootRequired: Boolean,
useUnmergedTree: Boolean
): Iterable<SemanticsNode> {
val roots = testOwner.getRoots(atLeastOneRootRequired).also {
check(!atLeastOneRootRequired || it.isNotEmpty()) {
"No compose hierarchies found in the app. Possible reasons include: " +
"(1) the Activity that calls setContent did not launch; " +
"(2) setContent was not called; " +
"(3) setContent was called before the ComposeTestRule ran. " +
"If setContent is called by the Activity, make sure the Activity is " +
"launched after the ComposeTestRule runs"
}
}
return roots.flatMap {
it.semanticsOwner.getAllSemanticsNodes(mergingEnabled = !useUnmergedTree)
}
}
}
| 30 | null | 974 | 5,229 | ff4bb04d5ec21e510422eba7ee2240d6e71576be | 4,100 | androidx | Apache License 2.0 |
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/KissWinkHeart.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.fontawesomeicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.SolidGroup
public val SolidGroup.KissWinkHeart: ImageVector
get() {
if (_kissWinkHeart != null) {
return _kissWinkHeart!!
}
_kissWinkHeart = Builder(name = "KissWinkHeart", defaultWidth = 504.0.dp, defaultHeight =
512.0.dp, viewportWidth = 504.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(501.1f, 402.5f)
curveToRelative(-8.0f, -20.8f, -31.5f, -31.5f, -53.1f, -25.9f)
lineToRelative(-8.4f, 2.2f)
lineToRelative(-2.3f, -8.4f)
curveToRelative(-5.9f, -21.4f, -27.0f, -36.5f, -49.0f, -33.0f)
curveToRelative(-25.2f, 4.0f, -40.6f, 28.6f, -34.0f, 52.6f)
lineToRelative(22.9f, 82.6f)
curveToRelative(1.5f, 5.3f, 7.0f, 8.5f, 12.4f, 7.1f)
lineToRelative(83.0f, -21.5f)
curveToRelative(24.1f, -6.3f, 37.7f, -31.8f, 28.5f, -55.7f)
close()
moveTo(323.5f, 398.5f)
curveToRelative(-5.6f, -20.3f, -2.3f, -42.0f, 9.0f, -59.7f)
curveToRelative(29.7f, -46.3f, 98.7f, -45.5f, 127.8f, 4.3f)
curveToRelative(6.4f, 0.1f, 12.6f, 1.4f, 18.6f, 2.9f)
curveToRelative(10.9f, -27.9f, 17.1f, -58.2f, 17.1f, -90.0f)
curveTo(496.0f, 119.0f, 385.0f, 8.0f, 248.0f, 8.0f)
reflectiveCurveTo(0.0f, 119.0f, 0.0f, 256.0f)
reflectiveCurveToRelative(111.0f, 248.0f, 248.0f, 248.0f)
curveToRelative(35.4f, 0.0f, 68.9f, -7.5f, 99.4f, -20.9f)
curveToRelative(-0.3f, -0.7f, -23.9f, -84.6f, -23.9f, -84.6f)
close()
moveTo(168.0f, 240.0f)
curveToRelative(-17.7f, 0.0f, -32.0f, -14.3f, -32.0f, -32.0f)
reflectiveCurveToRelative(14.3f, -32.0f, 32.0f, -32.0f)
reflectiveCurveToRelative(32.0f, 14.3f, 32.0f, 32.0f)
reflectiveCurveToRelative(-14.3f, 32.0f, -32.0f, 32.0f)
close()
moveTo(288.0f, 396.0f)
curveToRelative(0.0f, 19.2f, -28.7f, 41.5f, -71.5f, 44.0f)
curveToRelative(-8.5f, 0.8f, -12.1f, -11.8f, -3.6f, -15.4f)
lineToRelative(17.0f, -7.2f)
curveToRelative(13.0f, -5.5f, 20.8f, -13.5f, 20.8f, -21.5f)
reflectiveCurveToRelative(-7.8f, -16.0f, -20.8f, -21.5f)
lineToRelative(-17.0f, -7.2f)
curveToRelative(-6.0f, -2.5f, -5.7f, -12.3f, 0.0f, -14.8f)
lineToRelative(17.0f, -7.2f)
curveToRelative(13.0f, -5.5f, 20.8f, -13.5f, 20.8f, -21.5f)
reflectiveCurveToRelative(-7.8f, -16.0f, -20.8f, -21.5f)
lineToRelative(-17.0f, -7.2f)
curveToRelative(-8.8f, -3.7f, -4.6f, -16.6f, 3.6f, -15.4f)
curveToRelative(42.8f, 2.5f, 71.5f, 24.8f, 71.5f, 44.0f)
curveToRelative(0.0f, 13.0f, -13.4f, 27.3f, -35.2f, 36.0f)
curveTo(274.6f, 368.7f, 288.0f, 383.0f, 288.0f, 396.0f)
close()
moveTo(304.0f, 217.0f)
curveToRelative(-8.3f, 7.4f, -21.6f, 0.4f, -19.8f, -10.8f)
curveToRelative(4.0f, -25.2f, 34.2f, -42.1f, 59.9f, -42.1f)
reflectiveCurveTo(400.0f, 181.0f, 404.0f, 206.2f)
curveToRelative(1.7f, 11.1f, -11.3f, 18.3f, -19.8f, 10.8f)
lineToRelative(-9.5f, -8.5f)
curveToRelative(-14.8f, -13.2f, -46.2f, -13.2f, -61.0f, 0.0f)
lineTo(304.0f, 217.0f)
close()
}
}
.build()
return _kissWinkHeart!!
}
private var _kissWinkHeart: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 4,507 | compose-icons | MIT License |
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/KissWinkHeart.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.fontawesomeicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.SolidGroup
public val SolidGroup.KissWinkHeart: ImageVector
get() {
if (_kissWinkHeart != null) {
return _kissWinkHeart!!
}
_kissWinkHeart = Builder(name = "KissWinkHeart", defaultWidth = 504.0.dp, defaultHeight =
512.0.dp, viewportWidth = 504.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(501.1f, 402.5f)
curveToRelative(-8.0f, -20.8f, -31.5f, -31.5f, -53.1f, -25.9f)
lineToRelative(-8.4f, 2.2f)
lineToRelative(-2.3f, -8.4f)
curveToRelative(-5.9f, -21.4f, -27.0f, -36.5f, -49.0f, -33.0f)
curveToRelative(-25.2f, 4.0f, -40.6f, 28.6f, -34.0f, 52.6f)
lineToRelative(22.9f, 82.6f)
curveToRelative(1.5f, 5.3f, 7.0f, 8.5f, 12.4f, 7.1f)
lineToRelative(83.0f, -21.5f)
curveToRelative(24.1f, -6.3f, 37.7f, -31.8f, 28.5f, -55.7f)
close()
moveTo(323.5f, 398.5f)
curveToRelative(-5.6f, -20.3f, -2.3f, -42.0f, 9.0f, -59.7f)
curveToRelative(29.7f, -46.3f, 98.7f, -45.5f, 127.8f, 4.3f)
curveToRelative(6.4f, 0.1f, 12.6f, 1.4f, 18.6f, 2.9f)
curveToRelative(10.9f, -27.9f, 17.1f, -58.2f, 17.1f, -90.0f)
curveTo(496.0f, 119.0f, 385.0f, 8.0f, 248.0f, 8.0f)
reflectiveCurveTo(0.0f, 119.0f, 0.0f, 256.0f)
reflectiveCurveToRelative(111.0f, 248.0f, 248.0f, 248.0f)
curveToRelative(35.4f, 0.0f, 68.9f, -7.5f, 99.4f, -20.9f)
curveToRelative(-0.3f, -0.7f, -23.9f, -84.6f, -23.9f, -84.6f)
close()
moveTo(168.0f, 240.0f)
curveToRelative(-17.7f, 0.0f, -32.0f, -14.3f, -32.0f, -32.0f)
reflectiveCurveToRelative(14.3f, -32.0f, 32.0f, -32.0f)
reflectiveCurveToRelative(32.0f, 14.3f, 32.0f, 32.0f)
reflectiveCurveToRelative(-14.3f, 32.0f, -32.0f, 32.0f)
close()
moveTo(288.0f, 396.0f)
curveToRelative(0.0f, 19.2f, -28.7f, 41.5f, -71.5f, 44.0f)
curveToRelative(-8.5f, 0.8f, -12.1f, -11.8f, -3.6f, -15.4f)
lineToRelative(17.0f, -7.2f)
curveToRelative(13.0f, -5.5f, 20.8f, -13.5f, 20.8f, -21.5f)
reflectiveCurveToRelative(-7.8f, -16.0f, -20.8f, -21.5f)
lineToRelative(-17.0f, -7.2f)
curveToRelative(-6.0f, -2.5f, -5.7f, -12.3f, 0.0f, -14.8f)
lineToRelative(17.0f, -7.2f)
curveToRelative(13.0f, -5.5f, 20.8f, -13.5f, 20.8f, -21.5f)
reflectiveCurveToRelative(-7.8f, -16.0f, -20.8f, -21.5f)
lineToRelative(-17.0f, -7.2f)
curveToRelative(-8.8f, -3.7f, -4.6f, -16.6f, 3.6f, -15.4f)
curveToRelative(42.8f, 2.5f, 71.5f, 24.8f, 71.5f, 44.0f)
curveToRelative(0.0f, 13.0f, -13.4f, 27.3f, -35.2f, 36.0f)
curveTo(274.6f, 368.7f, 288.0f, 383.0f, 288.0f, 396.0f)
close()
moveTo(304.0f, 217.0f)
curveToRelative(-8.3f, 7.4f, -21.6f, 0.4f, -19.8f, -10.8f)
curveToRelative(4.0f, -25.2f, 34.2f, -42.1f, 59.9f, -42.1f)
reflectiveCurveTo(400.0f, 181.0f, 404.0f, 206.2f)
curveToRelative(1.7f, 11.1f, -11.3f, 18.3f, -19.8f, 10.8f)
lineToRelative(-9.5f, -8.5f)
curveToRelative(-14.8f, -13.2f, -46.2f, -13.2f, -61.0f, 0.0f)
lineTo(304.0f, 217.0f)
close()
}
}
.build()
return _kissWinkHeart!!
}
private var _kissWinkHeart: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 4,507 | compose-icons | MIT License |
app/src/main/java/com/guru/composecookbook/ui/learnwidgets/AppBars.kt | Gurupreet | 293,227,683 | false | null | package com.guru.composecookbook.ui.learnwidgets
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.outlined.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.guru.composecookbook.R
import com.guru.composecookbook.spotify.ui.home.SpotifyNavType
import com.guru.composecookbook.theme.twitterColor
import com.guru.composecookbook.theme.typography
import com.guru.composecookbook.ui.utils.SubtitleText
import com.guru.composecookbook.ui.utils.TitleText
@Composable
fun AppBars() {
Text(text = "App Bars", style = typography.h5, modifier = Modifier.padding(8.dp))
TopAppBarsDemo()
BottomAppBarDemo()
NavigationBarDemo()
}
@Composable
fun TopAppBarsDemo() {
SubtitleText(subtitle = "Top App bar")
TopAppBar(
title = { Text(text = "Home") },
elevation = 8.dp,
navigationIcon = {
IconButton(onClick = {}) {
Icon(imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(id = R.string.cd_back)
)
}
}
)
Spacer(modifier = Modifier.height(8.dp))
TopAppBar(
title = { Text(text = "Instagram") },
backgroundColor = MaterialTheme.colors.surface,
contentColor = MaterialTheme.colors.onSurface,
elevation = 8.dp,
navigationIcon = {
IconButton(onClick = {}) {
Icon(
painter = painterResource(id = R.drawable.ic_instagram),
contentDescription = null
)
}
},
actions = {
IconButton(onClick = {}) {
Icon(painter = painterResource(id = R.drawable.ic_send), contentDescription = null)
}
}
)
Spacer(modifier = Modifier.height(8.dp))
TopAppBar(
title = {
Icon(
painter = painterResource(id = R.drawable.ic_twitter),
contentDescription = null,
tint = twitterColor,
modifier = Modifier.fillMaxWidth()
)
},
backgroundColor = MaterialTheme.colors.surface,
contentColor = MaterialTheme.colors.onSurface,
elevation = 8.dp,
navigationIcon = {
Image(
painter = painterResource(id = R.drawable.p6),
contentDescription = null,
modifier = Modifier
.padding(vertical = 4.dp, horizontal = 8.dp)
.size(32.dp)
.clip(CircleShape)
)
},
actions = {
Icon(
imageVector = Icons.Default.StarBorder,
contentDescription = null,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
)
Spacer(modifier = Modifier.height(8.dp))
}
@Composable
fun BottomAppBarDemo() {
Spacer(modifier = Modifier.height(16.dp))
SubtitleText("Bottom app bars: Note bottom app bar support FAB cutouts when used with scafolds see demoUI crypto app")
BottomAppBar(
cutoutShape = CircleShape
) {
IconButton(onClick = {}) {
Icon(imageVector = Icons.Default.MoreHoriz, contentDescription = null)
}
TitleText(title = "Bottom App Bar")
}
}
@Composable
fun NavigationBarDemo() {
Spacer(modifier = Modifier.height(16.dp))
SubtitleText(subtitle = "Bottom Navigation Bars")
val spotifyNavItemState = remember { mutableStateOf(SpotifyNavType.HOME) }
BottomNavigation(backgroundColor = MaterialTheme.colors.surface) {
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.Home, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.HOME,
onClick = { spotifyNavItemState.value = SpotifyNavType.HOME },
label = { Text(text = stringResource(id = R.string.spotify_nav_home)) },
)
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.Search, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.SEARCH,
onClick = { spotifyNavItemState.value = SpotifyNavType.SEARCH },
label = { Text(text = stringResource(id = R.string.spotify_nav_search)) }
)
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.LibraryMusic, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.LIBRARY,
onClick = { spotifyNavItemState.value = SpotifyNavType.LIBRARY },
label = { Text(text = stringResource(id = R.string.spotify_nav_library)) }
)
}
Spacer(modifier = Modifier.height(16.dp))
BottomNavigation {
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.ReadMore, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.HOME,
onClick = { spotifyNavItemState.value = SpotifyNavType.HOME },
)
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.Search, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.SEARCH,
onClick = { spotifyNavItemState.value = SpotifyNavType.SEARCH },
)
BottomNavigationItem(
icon = { Icon(imageVector = Icons.Outlined.CleanHands, contentDescription = null) },
selected = spotifyNavItemState.value == SpotifyNavType.LIBRARY,
onClick = { spotifyNavItemState.value = SpotifyNavType.LIBRARY },
)
}
}
@Preview
@Composable
fun PreviewAppBars() {
Column {
AppBars()
}
}
| 10 | Kotlin | 8 | 3,360 | d02d2cc827b8cab804ef75821d2755d50ce448c9 | 6,431 | ComposeCookBook | MIT License |
app/src/main/java/com/example/dashboard_cba/utils/Constants.kt | JuanseVidales | 671,575,527 | false | null | /**
* Objeto [Constants] que contiene constantes utilizadas en la aplicación.
*/
object Constants {
/**
* ID del canal de notificaciones utilizado para mostrar las notificaciones de la aplicación.
* Este valor se utiliza para identificar el canal de notificaciones al crearlo.
*/
const val channelId = "CanalTienda"
}
| 0 | Kotlin | 0 | 1 | 23a773e0842d2166c6291b378b26d40ac58ad2a9 | 343 | Proyecto_Kotlin | MIT License |
EarthGardener/app/src/main/java/team/gdsc/earthgardener/domain/nickname/CheckNicknameData.kt | EarthGardener | 454,439,830 | false | {"Kotlin": 10400} | package team.gdsc.earthgardener.domain.nickname
data class CheckNicknameData(
val message: String,
val status: Int
)
| 20 | Kotlin | 0 | 1 | a06cbf7c45ea2181475a0fccd8c77f04cee58970 | 126 | EarthGardener-Android | MIT License |
sample/src/main/kotlin/br/com/zup/beagle/sample/BeagleUiSampleApplication.kt | ZupIT | 391,144,851 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.automatedTests
import android.app.Application
class AppApplication: Application() {
override fun onCreate() {
super.onCreate()
BeagleSetup().init(this)
}
}
| 4 | null | 3 | 9 | 812a330777edd79a123495e9f678dc8f25a019f7 | 837 | beagle-android | Apache License 2.0 |
mvvm/src/main/java/com/taonce/mvvm/util/LogUtils.kt | Taonce | 200,171,135 | false | null | package com.moyoi.library_base.utils
import android.util.Log
/**
* 常用的日志打印类
*/
const val COMMON_TAG = "WanAndroid"
private const val IS_SHOW_LOG: Boolean = true
fun showDebug(
msg: String,
tag: String = COMMON_TAG
) {
if (IS_SHOW_LOG) {
Log.d(tag, zipLogMsg(msg))
}
}
fun showError(
msg: String,
error: Exception? = null,
tag: String = COMMON_TAG
) {
if (IS_SHOW_LOG) {
error?.let {
Log.e(tag, msg, error)
} ?: Log.e(tag, zipLogMsg(msg))
}
}
fun showThrowable(
msg: String,
throwable: Throwable? = null,
tag: String = COMMON_TAG
) {
if (IS_SHOW_LOG) {
throwable?.let {
Log.e(tag, msg, throwable)
} ?: Log.e(tag, zipLogMsg(msg))
}
}
fun showInfo(
msg: String,
tag: String = COMMON_TAG
) {
if (IS_SHOW_LOG) {
Log.i(tag, zipLogMsg(msg))
}
}
fun showWarning(
msg: String,
tag: String = COMMON_TAG
) {
if (IS_SHOW_LOG) {
Log.w(tag, zipLogMsg(msg))
}
}
private fun zipLogMsg(msg: String): String {
val stackTrace = Thread.currentThread().stackTrace
val buffer = StringBuffer()
stackTrace.takeIf { it.size > 5 }?.let {
val element = stackTrace[5]
buffer.apply {
append(getShortClassName(element.className))
append(".")
append(element.methodName)
append("(")
append(element.fileName)
append(":")
append(element.lineNumber)
append(")")
append(":")
}
}
return with(buffer) {
append(msg).toString()
}
}
private fun getShortClassName(className: String): String {
if (className.isEmpty()) {
return ""
}
return className.substring(className.lastIndexOf(".") + 1)
}
| 1 | null | 6 | 25 | 3f01a173447f7d4d1628115021c48e2224e71a3b | 1,818 | MVVM-T | MIT License |
examples/androidx-samples/src/main/java/org/koin/sample/sandbox/navigation/NavFragmentA.kt | InsertKoinIO | 93,515,203 | false | null | package org.koin.sample.androidx.navigation
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.navigation.fragment.findNavController
import org.koin.androidx.navigation.koinNavGraphViewModel
import org.koin.sample.android.R
class NavFragmentA : Fragment() {
val mainViewModel: NavViewModel by koinNavGraphViewModel(R.id.main)
lateinit var button: Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.nav_fragment_a, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button = requireView().findViewById(R.id.a_button)
button.setOnClickListener {
findNavController().navigate(R.id.action_fragmentA_to_fragmentB)
}
ID = mainViewModel.id
}
companion object {
var ID = ""
}
} | 78 | null | 711 | 8,934 | f870a02fd32a2cf1ff8b69406ebf555c26ffe39f | 1,134 | koin | Apache License 2.0 |
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/AutoImportTest.kt | hieuprogrammer | 284,920,751 | true | null | // Copyright 2000-2019 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 com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.FAILURE
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS
import com.intellij.openapi.externalSystem.autoimport.MockProjectAware.RefreshCollisionPassType
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.Parallel.Companion.parallel
import org.junit.Test
import java.io.File
class AutoImportTest : AutoImportTestCase() {
@Test
fun `test simple modification tracking`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, notified = true, event = "modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert changes")
settingsFile.appendString("\n ")
assertState(refresh = 2, notified = false, event = "empty modification")
settingsFile.replaceString("println", "print ln")
assertState(refresh = 2, notified = true, event = "split token by space")
settingsFile.replaceString("print ln", "println")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.appendString(" ")
assertState(refresh = 2, notified = false, event = "empty modification")
settingsFile.appendString("//It is comment")
assertState(refresh = 2, notified = false, event = "append comment")
settingsFile.insertStringAfter("println", "/*It is comment*/")
assertState(refresh = 2, notified = false, event = "append comment")
settingsFile.insertString(0, "//")
assertState(refresh = 2, notified = true, event = "comment code")
refreshProject()
assertState(refresh = 3, notified = false, event = "project refresh")
refreshProject()
assertState(refresh = 3, notified = false, event = "empty project refresh")
}
}
@Test
fun `test simple modification tracking in xml`() {
simpleTest("settings.xml") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContent("""
<element>
<name description="This is a my super name">my-name</name>
</element>
""".trimIndent())
assertState(refresh = 1, notified = true, event = "modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "refresh project")
settingsFile.replaceString("my-name", "my name")
assertState(refresh = 2, notified = true, event = "replace by space")
settingsFile.replaceString("my name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", "my - name")
assertState(refresh = 2, notified = true, event = "split token by spaces")
settingsFile.replaceString("my - name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", " my-name ")
assertState(refresh = 2, notified = false, event = "expand text token by spaces")
settingsFile.insertStringAfter("</name>", " ")
assertState(refresh = 2, notified = false, event = "append space after tag")
settingsFile.insertStringAfter("</name>", "\n ")
assertState(refresh = 2, notified = false, event = "append empty line in file")
settingsFile.replaceString("</name>", "</n am e>")
assertState(refresh = 2, notified = true, event = "split tag by spaces")
settingsFile.replaceString("</n am e>", "</name>")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("</name>", "</ name >")
assertState(refresh = 2, notified = false, event = "expand tag brackets by spaces")
settingsFile.replaceString("=", " = ")
assertState(refresh = 2, notified = false, event = "expand attribute definition")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = true, event = "expand space inside attribute value")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.insertStringAfter("my super name", " ")
assertState(refresh = 2, notified = true, event = "insert space in end of attribute")
settingsFile.replaceString("my super name \"", "my super name\"")
assertState(refresh = 2, notified = false, event = "revert modification")
}
}
@Test
fun `test unrecognized settings file`() {
simpleTest("settings.elvish") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.appendString("q71Gpj5 .9jR°`N.")
assertState(refresh = 1, notified = true, event = "modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("9jR°`N", "9`B")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("9`B", "9jR°`N")
assertState(refresh = 2, notified = false, event = "revert changes")
settingsFile.appendString(" ")
assertState(refresh = 2, notified = true, event = "unrecognized empty modification")
refreshProject()
assertState(refresh = 3, notified = false, event = "project refresh")
settingsFile.appendString("//1G iT zt^P1Fp")
assertState(refresh = 3, notified = true, event = "unrecognized comment modification")
refreshProject()
assertState(refresh = 4, notified = false, event = "project refresh")
}
}
@Test
fun `test deletion tracking`() {
simpleTest("settings.groovy", "println 'hello'") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.delete()
assertState(refresh = 1, notified = true, event = "delete registered settings")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
var newSettingsFile = createVirtualFile("settings.groovy")
assertState(refresh = 2, notified = true, event = "create registered settings")
newSettingsFile.replaceContent("println 'hello'")
assertState(refresh = 2, notified = true, event = "modify registered settings")
refreshProject()
assertState(refresh = 3, notified = false, event = "project refresh")
newSettingsFile.delete()
assertState(refresh = 3, notified = true, event = "delete registered settings")
newSettingsFile = createVirtualFile("settings.groovy")
assertState(refresh = 3, notified = true, event = "create registered settings immediately after deleting")
newSettingsFile.replaceContent("println 'hello'")
assertState(refresh = 3, notified = false, event = "modify registered settings immediately after deleting")
}
}
@Test
fun `test modification tracking with several settings files`() {
simpleTest("settings.groovy", "println 'hello'") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
val scriptFile = createVirtualFile("script.groovy")
assertState(refresh = 1, notified = false, event = "create unregistered settings")
scriptFile.replaceContent("println('hello')")
assertState(refresh = 1, notified = false, event = "modify unregistered settings")
registerSettingsFile(scriptFile)
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 1, notified = true, event = "try to revert changes if has other modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
scriptFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = true, event = "try to revert changes if has other modification")
scriptFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert changes")
}
}
@Test
fun `test modification tracking with several sub projects`() {
val systemId1 = ProjectSystemId("External System 1")
val systemId2 = ProjectSystemId("External System 2")
val projectId1 = ExternalSystemProjectId(systemId1, projectPath)
val projectId2 = ExternalSystemProjectId(systemId2, projectPath)
val projectAware1 = MockProjectAware(projectId1)
val projectAware2 = MockProjectAware(projectId2)
initialize()
val scriptFile1 = createVirtualFile("script1.groovy")
val scriptFile2 = createVirtualFile("script2.groovy")
projectAware1.settingsFiles.add(scriptFile1.path)
projectAware2.settingsFiles.add(scriptFile2.path)
register(projectAware1)
register(projectAware2)
assertProjectAware(projectAware1, refresh = 1, event = "register project without cache")
assertProjectAware(projectAware2, refresh = 1, event = "register project without cache")
assertNotificationAware(event = "register project without cache")
scriptFile1.appendString("println 1")
assertProjectAware(projectAware1, refresh = 1, event = "modification of first settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of first settings")
assertNotificationAware(projectId1, event = "modification of first settings")
scriptFile2.appendString("println 2")
assertProjectAware(projectAware1, refresh = 1, event = "modification of second settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of second settings")
assertNotificationAware(projectId1, projectId2, event = "modification of second settings")
scriptFile1.removeContent()
assertProjectAware(projectAware1, refresh = 1, event = "revert changes at second settings")
assertProjectAware(projectAware2, refresh = 1, event = "revert changes at second settings")
assertNotificationAware(projectId2, event = "revert changes at second settings")
refreshProject()
assertProjectAware(projectAware1, refresh = 1, event = "project refresh")
assertProjectAware(projectAware2, refresh = 2, event = "project refresh")
assertNotificationAware(event = "project refresh")
scriptFile1.replaceContent("println 'script 1'")
scriptFile2.replaceContent("println 'script 2'")
assertProjectAware(projectAware1, refresh = 1, event = "modification of both settings")
assertProjectAware(projectAware2, refresh = 2, event = "modification of both settings")
assertNotificationAware(projectId1, projectId2, event = "modification of both settings")
refreshProject()
assertProjectAware(projectAware1, refresh = 2, event = "project refresh")
assertProjectAware(projectAware2, refresh = 3, event = "project refresh")
assertNotificationAware(event = "project refresh")
}
@Test
fun `test project link-unlink`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, subscribe = 2, unsubscribe = 0, notified = false, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, subscribe = 2, unsubscribe = 0, notified = true, event = "modification")
removeProjectAware()
assertState(refresh = 1, subscribe = 2, unsubscribe = 2, notified = false, event = "remove project")
registerProjectAware()
assertState(refresh = 2, subscribe = 4, unsubscribe = 2, notified = false, event = "register project without cache")
}
}
@Test
fun `test external modification tracking`() {
simpleTest("settings.groovy") {
var settingsFile = it
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 2, notified = false, event = "untracked external modification")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "internal modification")
settingsFile.replaceStringInIoFile("hi", "settings")
assertState(refresh = 2, notified = true, event = "untracked external modification during internal modification")
refreshProject()
assertState(refresh = 3, notified = false, event = "refresh project")
modification {
assertState(refresh = 3, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("settings", "modified settings")
assertState(refresh = 3, notified = false, event = "external modification")
}
assertState(refresh = 4, notified = false, event = "complete external modification")
modification {
assertState(refresh = 4, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("modified settings", "simple settings")
assertState(refresh = 4, notified = false, event = "external modification")
settingsFile.replaceStringInIoFile("simple settings", "modified settings")
assertState(refresh = 4, notified = false, event = "revert external modification")
}
assertState(refresh = 4, notified = false, event = "complete external modification")
modification {
assertState(refresh = 4, notified = false, event = "start external modification")
settingsFile.deleteIoFile()
assertState(refresh = 4, notified = false, event = "external deletion")
}
assertState(refresh = 5, notified = false, event = "complete external modification")
modification {
assertState(refresh = 5, notified = false, event = "start external modification")
settingsFile = createIoFile("settings.groovy")
assertState(refresh = 5, notified = false, event = "external creation")
settingsFile.replaceContentInIoFile("println 'settings'")
assertState(refresh = 5, notified = false, event = "external modification")
}
assertState(refresh = 6, notified = false, event = "complete external modification")
modification {
assertState(refresh = 6, notified = false, event = "start first external modification")
settingsFile.replaceStringInIoFile("settings", "hello")
assertState(refresh = 6, notified = false, event = "first external modification")
modification {
assertState(refresh = 6, notified = false, event = "start second external modification")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 6, notified = false, event = "second external modification")
}
assertState(refresh = 6, notified = false, event = "complete second external modification")
}
assertState(refresh = 7, notified = false, event = "complete first external modification")
modification {
assertState(refresh = 7, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("println", "print")
assertState(refresh = 7, notified = false, event = "external modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 7, notified = true, event = "internal modification during external modification")
settingsFile.replaceStringInIoFile("hello", "settings")
assertState(refresh = 7, notified = true, event = "external modification")
}
assertState(refresh = 7, notified = true, event = "complete external modification")
refreshProject()
assertState(refresh = 8, notified = false, event = "refresh project")
}
}
@Test
fun `test tracker store and restore`() {
var state = simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContent("println 'hello'")
assertState(refresh = 1, notified = true, event = "modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 0, notified = true, event = "modification")
refreshProject()
assertState(refresh = 1, notified = false, event = "project refresh")
}
with(File(projectPath, "settings.groovy")) {
writeText(readText().replace("hi", "hello"))
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project with external modifications")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 0, notified = true, event = "modification")
}
simpleTest("settings.groovy", state = state) {
assertState(refresh = 1, notified = false, event = "register project with previous modifications")
}
}
fun `test move and rename settings files`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
registerSettingsFile("script.groovy")
registerSettingsFile("dir/script.groovy")
registerSettingsFile("dir1/script.groovy")
registerSettingsFile("dir/dir1/script.groovy")
var scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 1, notified = true, event = "copy to registered settings")
refreshProject()
assertState(refresh = 2, notified = false, event = "project refresh")
scriptFile.delete()
assertState(refresh = 2, notified = true, event = "delete file")
scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 2, notified = false, event = "revert delete by copy")
val configurationFile = settingsFile.copy("configuration.groovy")
assertState(refresh = 2, notified = false, event = "copy to registered settings")
configurationFile.delete()
assertState(refresh = 2, notified = false, event = "delete file")
val dir = findOrCreateDirectory("dir")
val dir1 = findOrCreateDirectory("dir1")
assertState(refresh = 2, notified = false, event = "create directory")
scriptFile.move(dir)
assertState(refresh = 2, notified = true, event = "move settings to directory")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
scriptFile.move(dir1)
assertState(refresh = 2, notified = true, event = "move settings to directory")
dir1.move(dir)
assertState(refresh = 2, notified = true, event = "move directory with settings to other directory")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
scriptFile.move(dir)
assertState(refresh = 2, notified = true, event = "move settings to directory")
dir.rename("dir1")
assertState(refresh = 2, notified = true, event = "rename directory with settings")
scriptFile.move(myProjectRoot)
assertState(refresh = 2, notified = false, event = "revert move settings")
settingsFile.rename("configuration.groovy")
assertState(refresh = 2, notified = true, event = "rename")
settingsFile.rename("settings.groovy")
assertState(refresh = 2, notified = false, event = "revert rename")
}
}
fun `test document changes between save`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
val settingsDocument = settingsFile.asDocument()
settingsDocument.replaceContent("println 'hello'")
assertState(refresh = 1, notified = true, event = "change")
refreshProject()
assertState(refresh = 2, notified = false, event = "refresh project")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "change")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert change")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "change")
settingsDocument.save()
assertState(refresh = 2, notified = true, event = "save")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert change after save")
settingsDocument.save()
assertState(refresh = 2, notified = false, event = "save reverted changes")
}
}
fun `test processing of failure refresh`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 2, notified = false, event = "external change")
setRefreshStatus(FAILURE)
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 3, notified = true, event = "external change with failure refresh")
refreshProject()
assertState(refresh = 4, notified = true, event = "failure project refresh")
setRefreshStatus(SUCCESS)
refreshProject()
assertState(refresh = 5, notified = false, event = "project refresh")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 5, notified = true, event = "modify")
setRefreshStatus(FAILURE)
refreshProject()
assertState(refresh = 6, notified = true, event = "failure project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 6, notified = true, event = "try to revert changes after failure refresh")
setRefreshStatus(SUCCESS)
refreshProject()
assertState(refresh = 7, notified = false, event = "project refresh")
}
}
fun `test files generation during refresh`() {
val systemId = ProjectSystemId("External System")
val projectId = ExternalSystemProjectId(systemId, projectPath)
val projectAware = MockProjectAware(projectId)
initialize()
register(projectAware)
assertProjectAware(projectAware, refresh = 1, event = "register project")
assertNotificationAware(event = "register project")
val settingsFile = createIoFile("project.groovy")
projectAware.onceDuringRefresh {
projectAware.settingsFiles.add(settingsFile.path)
settingsFile.replaceContentInIoFile("println 'generated project'")
}
forceRefreshProject(projectId)
assertProjectAware(projectAware, refresh = 2, event = "registration of settings file during project refresh")
assertNotificationAware(event = "registration of settings file during project refresh")
// modification during refresh
projectAware.onceDuringRefresh {
settingsFile.appendString("println 'hello'")
}
forceRefreshProject(projectId)
assertProjectAware(projectAware, refresh = 3, event = "modification during project refresh")
assertNotificationAware(projectId, event = "modification during project refresh")
}
fun `test disabling of auto-import`() {
var state = simpleTest("settings.groovy") { settingsFile ->
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "register project without cache")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
state = simpleTest("settings.groovy", state = state) { settingsFile ->
// Open modified project with disabled auto-import for external changes
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register modified project")
refreshProject()
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "refresh project")
// Checkout git branch, that has additional linked project
withLinkedProject("module/settings.groovy") { moduleSettingsFile ->
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register project without cache with disabled auto-import")
moduleSettingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "remove modified linked project")
setAutoReloadType(SELECTIVE)
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for project without modifications")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
setAutoReloadType(SELECTIVE)
assertState(refresh = 2, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for modified project")
}
simpleTest("settings.groovy", state = state) {
assertState(refresh = 0, autoReloadType = SELECTIVE, notified = false, event = "register project with correct cache")
}
}
@Test
fun `test activation of auto-import`() {
val systemId = ProjectSystemId("External System")
val projectId1 = ExternalSystemProjectId(systemId, projectPath)
val projectId2 = ExternalSystemProjectId(systemId, "$projectPath/sub-project")
val projectAware1 = MockProjectAware(projectId1)
val projectAware2 = MockProjectAware(projectId2)
initialize()
register(projectAware1, activate = false)
assertProjectAware(projectAware1, refresh = 0, event = "register project")
assertNotificationAware(projectId1, event = "register project")
assertActivationStatus(event = "register project")
activate(projectId1)
assertProjectAware(projectAware1, refresh = 1, event = "activate project")
assertNotificationAware(event = "activate project")
assertActivationStatus(projectId1, event = "activate project")
register(projectAware2, activate = false)
assertProjectAware(projectAware1, refresh = 1, event = "register project 2")
assertProjectAware(projectAware2, refresh = 0, event = "register project 2")
assertNotificationAware(projectId2, event = "register project 2")
assertActivationStatus(projectId1, event = "register project 2")
val settingsFile1 = createIoFile("settings.groovy")
val settingsFile2 = createIoFile("sub-project/settings.groovy")
projectAware1.settingsFiles.add(settingsFile1.path)
projectAware2.settingsFiles.add(settingsFile2.path)
settingsFile1.replaceContentInIoFile("println 'hello'")
settingsFile2.replaceContentInIoFile("println 'hello'")
assertProjectAware(projectAware1, refresh = 2, event = "externally modified both settings files, but project 2 is inactive")
assertProjectAware(projectAware2, refresh = 0, event = "externally modified both settings files, but project 2 is inactive")
assertNotificationAware(projectId2, event = "externally modified both settings files, but project 2 is inactive")
assertActivationStatus(projectId1, event = "externally modified both settings files, but project 2 is inactive")
settingsFile1.replaceString("hello", "Hello world!")
settingsFile2.replaceString("hello", "Hello world!")
assertProjectAware(projectAware1, refresh = 2, event = "internally modify settings")
assertProjectAware(projectAware2, refresh = 0, event = "internally modify settings")
assertNotificationAware(projectId1, projectId2, event = "internally modify settings")
assertActivationStatus(projectId1, event = "internally modify settings")
refreshProject()
assertProjectAware(projectAware1, refresh = 3, event = "refresh project")
assertProjectAware(projectAware2, refresh = 1, event = "refresh project")
assertNotificationAware(event = "refresh project")
assertActivationStatus(projectId1, projectId2, event = "refresh project")
}
@Test
fun `test merging of refreshes with different nature`() {
simpleTest("settings.groovy") { settingsFile ->
assertState(1, notified = false, event = "register project without cache")
enableAsyncExecution()
waitForProjectRefresh {
parallel {
thread {
settingsFile.replaceContentInIoFile("println 'hello'")
}
thread {
forceRefreshProject()
}
}
}
assertState(refresh = 2, notified = false, event = "modification")
}
}
@Test
fun `test enabling-disabling internal-external changes importing`() {
simpleModificationTest {
modifySettingsFile(INTERNAL)
assertState(refresh = 0, notified = true, autoReloadType = SELECTIVE, event = "internal modification")
refreshProject()
assertState(refresh = 1, notified = false, autoReloadType = SELECTIVE, event = "refresh project")
modifySettingsFile(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "external modification")
setAutoReloadType(ALL)
modifySettingsFile(INTERNAL)
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "internal modification with enabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "external modification with enabled auto-reload")
setAutoReloadType(NONE)
modifySettingsFile(INTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(SELECTIVE)
assertState(refresh = 4, notified = true, autoReloadType = SELECTIVE,
event = "enable auto-reload external changes with internal and external modifications")
setAutoReloadType(ALL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
setAutoReloadType(NONE)
modifySettingsFile(INTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
modifySettingsFile(EXTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(ALL)
assertState(refresh = 6, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
}
}
@Test
fun `test failure auto-reload with enabled auto-reload of any changes`() {
simpleModificationTest {
setAutoReloadType(ALL)
setRefreshStatus(FAILURE)
modifySettingsFile(INTERNAL)
assertState(refresh = 1, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
modifySettingsFile(INTERNAL)
assertState(refresh = 2, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
setRefreshStatus(SUCCESS)
refreshProject()
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "refresh project")
setRefreshStatus(FAILURE)
onceDuringRefresh {
setRefreshStatus(SUCCESS)
modifySettingsFile(INTERNAL)
}
modifySettingsFile(INTERNAL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "success modification after failure")
}
}
@Test
fun `test up-to-date promise after modifications with enabled auto-import`() {
simpleModificationTest {
for (collisionPassType in RefreshCollisionPassType.values()) {
resetAssertionCounters()
setRefreshCollisionPassType(collisionPassType)
setAutoReloadType(SELECTIVE)
onceDuringRefresh {
modifySettingsFile(EXTERNAL)
}
modifySettingsFile(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "auto-reload inside reload ($collisionPassType)")
setAutoReloadType(ALL)
onceDuringRefresh {
modifySettingsFile(INTERNAL)
}
modifySettingsFile(INTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "auto-reload inside reload ($collisionPassType)")
}
}
}
} | 1 | null | 2 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 34,595 | intellij-community | Apache License 2.0 |
src/test/kotlin/ru/yoomoney/tech/grafana/dsl/metrics/prometheus/functions/FloorTest.kt | yoomoney | 158,901,967 | false | {"Kotlin": 378524, "Shell": 644} | package ru.yoomoney.tech.grafana.dsl.metrics.prometheus.functions
import org.amshove.kluent.shouldBeEqualTo
import org.testng.annotations.Test
import ru.yoomoney.tech.grafana.dsl.metrics.prometheus.asInstantVector
class FloorTest {
@Test
fun `should apply floor function to prometheusMetric`() {
// given
val metric = "metric_name".asInstantVector().floor()
// then
metric.asString() shouldBeEqualTo "floor(metric_name)"
}
} | 2 | Kotlin | 8 | 53 | 58ab4e2e70e544c4160b97b4dc64e73235a4bd00 | 472 | grafana-dashboard-dsl | MIT License |
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/mocks/oppgave/gask/behandleoppgave/v1/BehandleOppgaveServiceMockImpl.kt | navikt | 254,055,233 | false | null | package no.nav.pensjon.vtp.mocks.oppgave.gask.behandleoppgave.v1
import no.nav.pensjon.vtp.annotations.SoapService
import no.nav.pensjon.vtp.mocks.oppgave.gask.sak.v1.GsakRepo
import no.nav.pensjon.vtp.testmodell.exceptions.NotImplementedException
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.BehandleOppgaveV1
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.meldinger.WSFerdigstillOppgaveRequest
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.meldinger.WSFerdigstillOppgaveResponse
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.meldinger.WSLagreOppgaveRequest
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.meldinger.WSOpprettOppgaveRequest
import no.nav.tjeneste.virksomhet.behandleoppgave.v1.meldinger.WSOpprettOppgaveResponse
import javax.jws.HandlerChain
import javax.jws.WebMethod
import javax.jws.WebParam
import javax.jws.WebResult
import javax.jws.WebService
import javax.xml.ws.RequestWrapper
import javax.xml.ws.ResponseWrapper
import javax.xml.ws.soap.Addressing
@SoapService(path = ["/nav-gsak-ws/BehandleOppgaveV1"])
@Addressing
@WebService(targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1", name = "BehandleOppgaveV1")
@HandlerChain(file = "/Handler-chain.xml")
class BehandleOppgaveServiceMockImpl(private val repo: GsakRepo) : BehandleOppgaveV1 {
@RequestWrapper(
localName = "ping",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.Ping"
)
@WebMethod(action = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1/BehandleOppgave_v1/pingRequest")
@ResponseWrapper(
localName = "pingResponse",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.PingResponse"
)
override fun ping() = Unit
@WebResult(name = "response")
@RequestWrapper(
localName = "ferdigstillOppgave",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.FerdigstillOppgave"
)
@WebMethod(action = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1/BehandleOppgave_v1/ferdigstillOppgaveRequest")
@ResponseWrapper(
localName = "ferdigstillOppgaveResponse",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.FerdigstillOppgaveResponse"
)
override fun ferdigstillOppgave(
@WebParam(name = "request") request: WSFerdigstillOppgaveRequest
) = WSFerdigstillOppgaveResponse()
@RequestWrapper(
localName = "lagreOppgave",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.LagreOppgave"
)
@WebMethod(action = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1/BehandleOppgave_v1/lagreOppgaveRequest")
@ResponseWrapper(
localName = "lagreOppgaveResponse",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.LagreOppgaveResponse"
)
override fun lagreOppgave(
@WebParam(name = "request") request: WSLagreOppgaveRequest
) = throw NotImplementedException()
@WebResult(name = "response")
@RequestWrapper(
localName = "opprettOppgave",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.OpprettOppgave"
)
@WebMethod(action = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1/BehandleOppgave_v1/opprettOppgaveRequest")
@ResponseWrapper(
localName = "opprettOppgaveResponse",
targetNamespace = "http://nav.no/tjeneste/virksomhet/behandleoppgave/v1",
className = "no.nav.tjeneste.virksomhet.behandleoppgave.v1.OpprettOppgaveResponse"
)
override fun opprettOppgave(
@WebParam(name = "request") request: WSOpprettOppgaveRequest
) = WSOpprettOppgaveResponse().apply {
oppgaveId = repo.opprettOppgave(request.wsOppgave.saksnummer)
}
}
| 14 | Kotlin | 0 | 2 | cd270b5f698c78c1eee978cd24bd788163c06a0c | 4,285 | vtp-pensjon | MIT License |
components/bridge/impl/src/main/java/com/flipperdevices/bridge/impl/manager/service/FlipperVersionApiImpl.kt | flipperdevices | 288,258,832 | false | null | package com.flipperdevices.bridge.impl.manager.service
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import androidx.datastore.core.DataStore
import com.flipperdevices.bridge.api.manager.ktx.state.FlipperSupportedState
import com.flipperdevices.bridge.api.manager.service.FlipperVersionApi
import com.flipperdevices.bridge.api.utils.Constants
import com.flipperdevices.bridge.impl.manager.UnsafeBleManager
import com.flipperdevices.core.data.SemVer
import com.flipperdevices.core.log.LogTagProvider
import com.flipperdevices.core.log.error
import com.flipperdevices.core.log.info
import com.flipperdevices.core.preference.pb.Settings
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
class FlipperVersionApiImpl(
private val settingsStore: DataStore<Settings>
) : BluetoothGattServiceWrapper, FlipperVersionApi, LogTagProvider {
override val TAG = "FlipperVersionApi"
private val semVerStateFlow = MutableStateFlow<SemVer?>(null)
private var apiVersionCharacteristics: BluetoothGattCharacteristic? = null
override fun getVersionInformationFlow(): StateFlow<SemVer?> = semVerStateFlow
override fun onServiceReceived(gatt: BluetoothGatt): Boolean {
getServiceOrLog(gatt, Constants.BLEInformationService.SERVICE_UUID)?.let { service ->
apiVersionCharacteristics = service.getCharacteristic(
Constants.BLEInformationService.API_VERSION
)
}
val serviceFounded = apiVersionCharacteristics != null
if (!serviceFounded) {
error { "Support version not founded" }
}
return serviceFounded
}
override suspend fun initialize(bleManager: UnsafeBleManager) {
val ignoreUnsupported = settingsStore.data.first().ignoreUnsupportedVersion
if (ignoreUnsupported) {
bleManager.setDeviceSupportedStatus(FlipperSupportedState.READY)
return
}
bleManager.readCharacteristicUnsafe(apiVersionCharacteristics)
.with { _, data ->
info { "Found information about version $data" }
val content = data.value ?: return@with
try {
val apiVersion = String(content)
onSupportedVersionReceived(bleManager, apiVersion)
} catch (e: Exception) {
error(e) { "Failed parse api version $content" }
bleManager.setDeviceSupportedStatus(
FlipperSupportedState.DEPRECATED_FLIPPER
)
}
}.enqueue()
}
override suspend fun reset(bleManager: UnsafeBleManager) {
// Do nothing
}
private fun onSupportedVersionReceived(bleManager: UnsafeBleManager, apiVersion: String) {
info { "Api version is $apiVersion" }
val filteredApiVersion = apiVersion.replace("[^0-9.]", "")
info { "Filtered api version is $filteredApiVersion" }
val parts = apiVersion.trim().split(".")
val majorPart = parts.firstOrNull()
val minorPart = if (parts.size >= 2) parts[1] else null
info { "Founded ${parts.size} parts. Major part is $majorPart, minor is $minorPart" }
val versionInformation = SemVer(
majorVersion = majorPart?.toIntOrNull() ?: 0,
minorVersion = minorPart?.toIntOrNull() ?: 0
)
semVerStateFlow.update { versionInformation }
bleManager.setDeviceSupportedStatus(versionInformation.toSupportedState())
}
}
private fun SemVer.toSupportedState() = when {
this < Constants.API_SUPPORTED_VERSION -> FlipperSupportedState.DEPRECATED_FLIPPER
this >= Constants.API_MAX_SUPPORTED_VERSION -> FlipperSupportedState.DEPRECATED_APPLICATION
else -> FlipperSupportedState.READY
}
| 9 | null | 78 | 999 | ef27b6b6a78a59b603ac858de2c88f75b743f432 | 3,938 | Flipper-Android-App | MIT License |
packaging-gradle-plugin/src/com/hendraanggrian/packaging/WindowsPackSpec.kt | hendraanggrian | 120,912,663 | false | null | package com.hendraanggrian.packaging
import org.gradle.api.provider.Property
/** Platform-specific options than can be configured using `windows { ... }` within [PackSpec]. */
@PackSpecMarker
interface WindowsPackSpec : PackSpec {
//region Platform dependent option for creating the application launcher
/** Creates a console launcher for the application, should be specified for application which requires console interactions. */
val console: Property<Boolean>
//endregion
//region Platform dependent options for creating the application package
/** Adds a dialog to enable the user to choose a directory in which the product is installed. */
val directoryChooser: Property<Boolean>
/** Adds the application to the system menu. */
val menu: Property<Boolean>
/** Start Menu group this application is placed in. */
val menuGroup: Property<String>
/** Request to perform an install on a per-user basis. */
val perUserInstall: Property<Boolean>
/** Creates a desktop shortcut for the application. */
val shortcut: Property<Boolean>
/** UUID associated with upgrades for this package. */
val upgradeUUID: Property<String>
//endregion
}
| 3 | Kotlin | 1 | 18 | d8d82578ae76da81c92c05cc5963976af48afa1f | 1,215 | packaging-gradle-plugin | Apache License 2.0 |
serialk_gson/src/main/java/com/mozhimen/serialk/gson/UtilKStrJson.kt | mozhimen | 812,481,724 | false | {"Kotlin": 16695} | package com.mozhimen.serialk.gson
import org.json.JSONArray
/**
* @ClassName UtilKStrJson
* @Description TODO
* @Author Mozhimen / <NAME>
* @Date 2024/6/10 0:33
* @Version 1.0
*/
fun <T> String.strJson2tList(clazz: Class<T>): ArrayList<T?>? =
UtilKStrJson.strJson2tList(this, clazz)
///////////////////////////////////////////////////////////////////////////////
object UtilKStrJson {
@JvmStatic
fun <T> strJson2tList(strJson: String, clazz: Class<T>): ArrayList<T?>? =
UtilKJSONArrayFormat.jSONArray2tList(JSONArray(strJson.trim { strJson <= " " }), clazz)
} | 0 | Kotlin | 1 | 1 | 3b4bb6c34fa6029e63e2a02a396ad08ea1b5ae21 | 590 | ASerialKit | Apache License 2.0 |
samples/kaspresso-sample/src/androidTest/kotlin/com/kaspersky/kaspressample/docloc_tests/advanced/AdvancedScreenshotSampleTestLegacy.kt | eakurnikov | 255,060,909 | true | {"Kotlin": 700193, "Java": 10748, "Makefile": 387} | package com.kaspersky.kaspressample.docloc_tests.advanced
import android.graphics.Color
import androidx.fragment.app.testing.launchFragmentInContainer
import com.kaspersky.kaspressample.docloc.ScreenshotSampleFragment
import com.kaspersky.kaspressample.docloc.ScreenshotSampleView
import com.kaspersky.kaspresso.annotations.ScreenShooterTest
import com.kaspersky.kaspresso.testcases.api.testcase.DocLocScreenshotTestCase
import org.junit.Test
import java.io.File
/**
* An example of advanced [DocLocScreenshotTestCase] usage.
* For more information see DocLoc wiki page.
*/
class AdvancedScreenshotSampleTestLegacy : DocLocScreenshotTestCase(
screenshotsDirectory = File("screenshots"),
locales = "en,ru"
) {
private lateinit var view: ScreenshotSampleView
@ScreenShooterTest
@Test
fun test() = before {
val scenario = launchFragmentInContainer<ScreenshotSampleFragment>()
scenario.onFragment {
view = getUiSafeProxy(it as ScreenshotSampleView)
}
}.after {
}.run {
step("1. Launch feature screen") {
view.setCounterValue(0)
view.setBackgroundColor(Color.WHITE)
captureScreenshot("1. Startup")
}
step("2. Increase counter by 5") {
view.setCounterValue(5)
captureScreenshot("2. Value has been increased by 5")
}
step("3. Set red background color") {
view.setBackgroundColor(Color.RED)
captureScreenshot("3. Background has been set to red")
}
}
}
| 5 | Kotlin | 0 | 0 | 57f4fa7b9aa99d350fa4433cef6ecce58a2e58a7 | 1,556 | Kaspresso | Apache License 2.0 |
plugins/kotlin/j2k/new/tests/testData/newJ2k/settings/publicByDefault.kt | JetBrains | 2,489,216 | false | null | // !PUBLIC_BY_DEFAULT: true
class J {
fun foo() {}
var bar = 42
}
| 214 | null | 4829 | 15,129 | 5578c1c17d75ca03071cc95049ce260b3a43d50d | 74 | intellij-community | Apache License 2.0 |
plugins/hh-garcon/src/main/kotlin/ru/hh/plugins/garcon/actions/collect_kakao_views/CollectWidgetsIntoPageObjectDialog.kt | hhru | 159,637,875 | false | null | package ru.hh.plugins.garcon.actions.collect_kakao_views
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlFile
import com.intellij.ui.RecentsManager
import com.intellij.ui.layout.CCFlags
import com.intellij.ui.layout.panel
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import org.jetbrains.kotlin.psi.KtClass
import ru.hh.plugins.garcon.GarconConstants
import ru.hh.plugins.garcon.extensions.showErrorDialog
import ru.hh.plugins.garcon.services.ClassFiltersFactory
import ru.hh.plugins.extensions.EMPTY
import ru.hh.plugins.extensions.layout.createKotlinClassChooserComboBox
import ru.hh.plugins.layout.KotlinFileComboBoxWrapper
import javax.swing.JCheckBox
import javax.swing.JComponent
class CollectWidgetsIntoPageObjectDialog(
private val xmlFile: XmlFile
) : DialogWrapper(xmlFile.project) {
private val project: Project get() = xmlFile.project
private lateinit var openInEditorCheckBox: JCheckBox
private lateinit var targetClassChooser: KotlinFileComboBoxWrapper
private var targetClass: PsiElement? = null
init {
init()
title = "Collect widgets into Page Object"
}
override fun createCenterPanel(): JComponent? {
return panel {
titledRow("Choose target <Screen> Page Object class") {
row {
targetClassChooser = createKotlinClassChooserComboBox(
project = project,
chooserDialogTitle = "Choose target <Screen> Page Object class",
recentKey = GarconConstants.RecentsKeys.TARGET_SCREEN_CLASS,
initialText = null,
classFilter = ClassFiltersFactory.getInstance(project).createKakaoScreensClassFilter(),
onSelectTargetClassAction = { aClass, needChangeText ->
if (aClass is KtLightClassForSourceDeclaration) {
targetClass = aClass.kotlinOrigin
if (needChangeText) {
targetClassChooser.text = aClass.qualifiedName ?: String.EMPTY
}
} else {
targetClass = aClass
}
}
)
targetClassChooser()
}
}
row {
openInEditorCheckBox = checkBox(
text = "Open in editor",
isSelected = PropertiesComponent.getInstance()
.getBoolean(GarconConstants.RecentsKeys.OPEN_IN_EDITOR_FLAG, true)
).component
openInEditorCheckBox(CCFlags.pushX)
}
}
}
override fun doOKAction() {
if (isFormValid()) {
targetClass?.let { aClass ->
RecentsManager.getInstance(project).registerRecentEntry(
GarconConstants.RecentsKeys.TARGET_SCREEN_CLASS, aClass.getKotlinFqName().toString()
)
}
PropertiesComponent.getInstance()
.setValue(GarconConstants.RecentsKeys.OPEN_IN_EDITOR_FLAG, getOpenInEditor().toString())
super.doOKAction()
}
}
fun getDialogResult(): CollectWidgetsIntoPageObjectDialogResult {
return CollectWidgetsIntoPageObjectDialogResult(
xmlFile = xmlFile,
targetClass = getTargetPsiElement() as KtClass,
openInEditor = getOpenInEditor()
)
}
private fun getOpenInEditor(): Boolean {
return openInEditorCheckBox.isSelected
}
private fun getTargetPsiElement(): PsiElement? {
return targetClass
}
private fun isFormValid(): Boolean {
return isTargetClassValid()
}
private fun isTargetClassValid(): Boolean {
return if (targetClass == null) {
project.showErrorDialog("No target class specified")
false
} else {
true
}
}
} | 24 | null | 18 | 97 | 2d6c02fc814eff3934c17de77ef7ade91d3116f5 | 4,313 | android-multimodule-plugin | MIT License |
zowe-cli/src/jsMain/kotlin/zowe/cli/zosjobs/download/download_output/Output.definition.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | @file:JsModule("@zowe/cli")
package zowe.cli.zosjobs.download.download_output
import zowe.imperative.cmd.doc.ICommandDefinition
external val OutputDefinition: ICommandDefinition
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 181 | kotlin-externals | MIT License |
app/src/main/java/xyz/teamgravity/todo/data/local/converter/TodoConverter.kt | raheemadamboev | 330,992,280 | false | null | package xyz.teamgravity.todo.data.local.converter
import androidx.room.TypeConverter
import java.util.*
class TodoConverter {
@TypeConverter
fun dateToLong(value: Date): Long {
return value.time
}
@TypeConverter
fun longToDate(value: Long): Date {
return Date(value)
}
} | 1 | null | 1 | 6 | 4a5538781b0312183861058638f6a0fbeb65347a | 314 | todo-app | Apache License 2.0 |
android/app/src/main/java/com/thedevgang/liga/presentation/ui/players/PlayersViewModel.kt | RZEROSTERN | 272,800,715 | false | null | package com.thedevgang.liga.presentation.ui.players
import androidx.lifecycle.ViewModel
class PlayersViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
| 0 | Kotlin | 0 | 0 | 930eb79fdd81130ead2c5d1f1dc01dc3f400e142 | 168 | thedevgang_liga | MIT License |
android/Library/Owner/app/src/main/java/com/pradyotprakash/libraryowner/app/utils/Assets.kt | pradyotprksh | 385,586,594 | false | {"Kotlin": 1895342, "Dart": 1052279, "Python": 311069, "Swift": 145439, "C++": 90451, "CMake": 74709, "Go": 45704, "HTML": 19243, "Ruby": 12424, "C": 5700, "Shell": 817, "JavaScript": 781, "CSS": 588, "Objective-C": 342, "Makefile": 318, "Dockerfile": 32} | package com.pradyotprakash.libraryowner.app.utils
import com.pradyotprakash.libraryowner.R
import com.pradyotprakash.libraryowner.app.utils.Constants.defaultLanguage
sealed class Assets(
val resourceId: Int = -1,
val path: String = "",
val imageDescription: String = ""
) {
object AppIcon :
Assets(resourceId = R.drawable.app_icon, imageDescription = "Main application icon")
data class Localization(val lanKey: String = defaultLanguage) :
Assets(path = "localization_${lanKey}.json")
} | 0 | Kotlin | 9 | 15 | f2bef232d7b45c68f94985a0ac2542f3bb2d8f19 | 525 | development_learning | MIT License |
vector/src/main/java/vmodev/clearkeep/viewmodels/FeedBackFragmentViewModel.kt | telred-llc | 194,596,139 | false | {"Java": 5914133, "Kotlin": 3855534, "JavaScript": 179733, "HTML": 22037, "Shell": 17049} | package vmodev.clearkeep.viewmodels
import androidx.lifecycle.LiveData
import vmodev.clearkeep.repositories.FeedbackRepository
import vmodev.clearkeep.rests.models.responses.FeedbackResponse
import vmodev.clearkeep.viewmodelobjects.Resource
import vmodev.clearkeep.viewmodels.interfaces.AbstractFeedBackFragmentViewModel
import javax.inject.Inject
class FeedBackFragmentViewModel @Inject constructor(private val feedbackRepository: FeedbackRepository) : AbstractFeedBackFragmentViewModel() {
override fun submitFeedback(content: String, stars: Int): LiveData<Resource<FeedbackResponse>> {
return feedbackRepository.feedBackApp(content, stars)
}
} | 5 | Java | 1 | 3 | 2d20e94e9711b51aee89fa569efd61449cc7e9c3 | 666 | clearkeep-android | Apache License 2.0 |
cesium-kotlin/src/jsMain/kotlin/cesium/engine/ConstantSpline.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
@file:JsModule("@cesium/engine")
@file:Suppress(
"EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER",
)
package cesium.engine
/**
* A spline that evaluates to a constant value. Although this follows the [Spline] interface,
* it does not maintain an internal array of times since its value never changes.
* ```
* const position = new Cartesian3(1.0, 2.0, 3.0);
* const spline = new ConstantSpline(position);
*
* const p0 = spline.evaluate(0.0);
* ```
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html">Online Documentation</a>
*
* @constructor
* @property [value] The constant value that the spline evaluates to.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html">Online Documentation</a>
*/
external class ConstantSpline(val value: Any /* number | Cartesian3 | Quaternion */) {
/**
* Finds an index `i` in `times` such that the parameter
* `time` is in the interval `[times[i], times[i + 1]]`.
*
* Since a constant spline has no internal times array, this will throw an error.
* @param [time] The time.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html#findTimeInterval">Online Documentation</a>
*/
fun findTimeInterval(time: Double)
/**
* Wraps the given time to the period covered by the spline.
* @param [time] The time.
* @return The time, wrapped around to the updated animation.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html#wrapTime">Online Documentation</a>
*/
fun wrapTime(time: Double): Double
/**
* Clamps the given time to the period covered by the spline.
* @param [time] The time.
* @return The time, clamped to the animation period.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html#clampTime">Online Documentation</a>
*/
fun clampTime(time: Double): Double
/**
* Evaluates the curve at a given time.
* @param [time] The time at which to evaluate the curve.
* @param [result] The object onto which to store the result.
* @return The modified result parameter or the value that the constant spline represents.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ConstantSpline.html#evaluate">Online Documentation</a>
*/
fun evaluate(
time: Double,
result: Any /* Cartesian3 | Quaternion */? = definedExternally,
): Any /* number | Cartesian3 | Quaternion */
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 2,550 | types-kotlin | Apache License 2.0 |
src/main/kotlin/org/intellij/plugin/mdx/lang/psi/MdxTemplateDataElementType.kt | valentinnodan | 279,243,243 | false | null | package org.intellij.plugin.mdx.lang.psi
import com.intellij.lang.javascript.types.JEEmbeddedBlockElementType
import com.intellij.lang.javascript.types.JSEmbeddedContentElementType
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.TextRange
import com.intellij.psi.templateLanguages.TemplateDataElementType
import com.intellij.psi.templateLanguages.TemplateDataModifications
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import org.intellij.plugin.mdx.lang.MdxLanguage
import org.intellij.plugin.mdx.lang.parse.JsxBlockProvider
import org.intellij.plugin.mdx.lang.parse.MdxTokenTypes
import org.intellij.plugins.markdown.lang.MarkdownElementType
import java.util.*
import kotlin.math.min
object MdxTemplateDataElementType : MdxTemplateDataElementTypeBase(),
JEEmbeddedBlockElementType {
override fun isModule(): Boolean = true
override fun getTemplateDataInsertionTokens(): TokenSet {
return TokenSet.forAllMatching(IElementType.TRUE)
}
}
open class MdxTemplateDataElementTypeBase : TemplateDataElementType("MDX_TEMPLATE_JSX",
MdxLanguage,
MarkdownElementType.platformType(MdxTokenTypes.JSX_BLOCK_CONTENT),
MdxTokenTypes.OUTER_ELEMENT_TYPE) {
var lastImportExportBlock = 0
override fun collectTemplateModifications(sourceCode: CharSequence, baseLexer: Lexer): TemplateDataModifications {
val modifications = TemplateDataModifications()
baseLexer.start(sourceCode)
while (baseLexer.tokenType != null) {
if (baseLexer.tokenType === MarkdownElementType.platformType(MdxTokenTypes.JSX_BLOCK_CONTENT)) {
val trim = baseLexer.tokenText.trim()
var hadEnter = false
if (trim.startsWith("import") || trim.startsWith("export")) {
while (baseLexer.tokenType == MarkdownElementType.platformType(MdxTokenTypes.JSX_BLOCK_CONTENT)) {
if (baseLexer.tokenText.trim() == "" && hadEnter) {
break
}
lastImportExportBlock = baseLexer.tokenEnd
if (baseLexer.tokenText.endsWith('\n')){
hadEnter = true
}
baseLexer.advance()
}
lastImportExportBlock = baseLexer.tokenEnd
if (baseLexer.tokenType == null) {
return modifications
}
val sequence = baseLexer.bufferSequence
val trim1 = sequence.subSequence(0, lastImportExportBlock).trim()
if (!trim1.endsWith(';')) {
modifications.addRangeToRemove(min(trim1.length, sequence.length - 1), ";")
}
}
} else {
val range = TextRange.create(baseLexer.tokenStart, baseLexer.tokenEnd)
modifications.addOuterRange(range, true)
}
baseLexer.advance()
}
return modifications
}
}
| 13 | Kotlin | 2 | 8 | 52a51db1e1b6158d52e27f12277f56ca20c228f0 | 3,120 | mdx-intellij-plugin | MIT License |
app/src/main/java/com/anangkur/movieku/consumer/feature/detail/DetailActionListener.kt | anangkur | 198,078,584 | false | {"Kotlin": 52406} | package com.anangkur.movieku.consumer.feature.detail
import com.anangkur.movieku.consumer.data.model.Result
interface DetailActionListener {
fun onAddFavourite(data: Result)
fun onRemoveFavourite(data: Result)
} | 0 | Kotlin | 0 | 0 | 6a66a0c48b9e1d95ec1f29c42e2d28d2d894c656 | 221 | movie-ku-consumer | MIT License |
core-legacy/src/main/java/com/dipien/core/gson/GsonBuilderFactory.kt | dipien | 83,250,302 | false | {"Java": 154407, "Kotlin": 153960, "Shell": 2559, "HTML": 1750} | package com.dipien.core.gson
import com.dipien.core.date.DateConfiguration
import com.google.gson.GsonBuilder
object GsonBuilderFactory {
fun createGsonBuilder(): GsonBuilder {
val gsonBuilder = GsonBuilder()
gsonBuilder.setDateFormat(DateConfiguration.getDefaultDateTimeFormat())
gsonBuilder.disableHtmlEscaping()
gsonBuilder.setExclusionStrategies(HiddenAnnotationExclusionStrategy())
return gsonBuilder
}
}
| 3 | Java | 1 | 3 | 755109b4b63969287b64f42973bdb287ab06c13f | 461 | kotlin-libraries | Apache License 2.0 |
src/main/kotlin/me/senseiwells/replay/recorder/ChunkSender.kt | senseiwells | 643,690,788 | false | {"Kotlin": 226706, "Java": 62719} | package me.senseiwells.replay.recorder
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import me.senseiwells.replay.ServerReplay
import me.senseiwells.replay.chunk.ChunkRecorder
import me.senseiwells.replay.mixin.rejoin.ChunkMapAccessor
import me.senseiwells.replay.mixin.rejoin.TrackedEntityAccessor
import me.senseiwells.replay.player.PlayerRecorder
import net.minecraft.network.protocol.Packet
import net.minecraft.network.protocol.game.*
import net.minecraft.server.level.ChunkMap
import net.minecraft.server.level.ChunkMap.TrackedEntity
import net.minecraft.server.level.ServerEntity
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.Mob
import net.minecraft.world.level.ChunkPos
import net.minecraft.world.level.chunk.LevelChunk
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.ApiStatus.NonExtendable
import org.jetbrains.annotations.ApiStatus.OverrideOnly
import java.util.function.Consumer
import kotlin.math.min
/**
* This interface provides a way to resend any given chunks
* and any entities within those chunks.
*
* @see PlayerRecorder
* @see ChunkRecorder
*/
interface ChunkSender {
/**
* The level of which the chunks are in.
*/
val level: ServerLevel
/**
* The center chunk position of all the chunks being sent.
*
* @return The center most chunk position.
*/
fun getCenterChunk(): ChunkPos
/**
* This will iterate over every chunk position that is going
* to be sent, each chunk position will be accepted into the
* [consumer].
*
* @param consumer The consumer that will accept the given chunks positions.
*/
fun forEachChunk(consumer: Consumer<ChunkPos>)
/**
* This determines whether a given [entity] should be sent.
*
* @param entity The entity to check.
* @param range The entity's tracking range.
* @return Whether the entity should be tracked.
*/
fun shouldTrackEntity(entity: Entity, range: Double): Boolean
/**
* This method should consume a packet.
* This is used to send the chunk and entity packets.
*
* @param packet The packet to send.
*/
fun sendPacket(packet: Packet<*>)
/**
* This is called when [shouldTrackEntity] returns `true`,
* this should be used to send any additional packets for this entity.
*
* @param tracked The [WrappedTrackedEntity].
*/
fun addTrackedEntity(tracked: WrappedTrackedEntity)
/**
* This gets the view distance of the server.
*
* @return The view distance of the server.
*/
fun getViewDistance(): Int {
return this.level.server.playerList.viewDistance
}
/**
* This is called when a chunk is successfully sent to the client.
*
* @param chunk The chunk that was sent.
*/
@OverrideOnly
fun onChunkSent(chunk: LevelChunk) {
}
/**
* This sends all chunk and entity packets.
*/
@NonExtendable
fun sendChunksAndEntities() {
val seen = IntOpenHashSet()
this.sendChunkViewDistance()
this.sendChunks(seen)
this.sendChunkEntities(seen)
}
/**
* This sends all the chunk view distance and simulation distance packets.
*/
@Internal
fun sendChunkViewDistance() {
val center = this.getCenterChunk()
this.sendPacket(ClientboundSetChunkCacheCenterPacket(center.x, center.z))
this.sendPacket(ClientboundSetChunkCacheRadiusPacket(this.getViewDistance()))
this.sendPacket(ClientboundSetSimulationDistancePacket(this.getViewDistance()))
}
/**
* This sends all chunk packets.
*
* @param seen The [IntSet] of entity ids that have already been seen.
*/
@Internal
fun sendChunks(seen: IntSet) {
val source = this.level.chunkSource
val chunks = source.chunkMap
this.forEachChunk { pos ->
val chunk = source.getChunk(pos.x, pos.z, true)
if (chunk != null) {
this.sendChunk(chunks, chunk, seen)
} else {
ServerReplay.logger.warn("Failed to get chunk at $pos, didn't send")
}
}
}
/**
* This sends a specific chunk packet.
*
* @param chunks The [ChunkMap] containing all chunks.
* @param chunk The current chunk that is being sent.
* @param seen The [IntSet] of entity ids that have already been seen.
*/
@Internal
fun sendChunk(
chunks: ChunkMap,
chunk: LevelChunk,
seen: IntSet,
) {
chunks as ChunkMapAccessor
// We don't need to use the chunkSender
// We are only writing the packets to disk...
this.sendPacket(ClientboundLevelChunkWithLightPacket(
chunk,
chunk.level.lightEngine,
null,
null
))
val leashed = ArrayList<Mob>()
val ridden = ArrayList<Entity>()
val viewDistance = this.level.server.playerList.viewDistance
for (tracked in chunks.entityMap.values) {
val entity = (tracked as TrackedEntityAccessor).entity
if (entity.chunkPosition() == chunk.pos) {
if (!seen.contains(entity.id)) {
val range = min(tracked.getRange(), viewDistance * 16).toDouble()
if (this.shouldTrackEntity(entity, range)) {
this.addTrackedEntity(WrappedTrackedEntity(tracked))
seen.add(entity.id)
}
}
if (entity is Mob && entity.leashHolder != null) {
leashed.add(entity)
}
if (entity.passengers.isNotEmpty()) {
ridden.add(entity)
}
}
}
for (entity in leashed) {
this.sendPacket(ClientboundSetEntityLinkPacket(entity, entity.leashHolder))
}
for (entity in ridden) {
this.sendPacket(ClientboundSetPassengersPacket(entity))
}
this.onChunkSent(chunk)
}
/**
* This sends all the entities.
*
* @param seen The [IntSet] of entity ids that have already been seen.
*/
@Internal
fun sendChunkEntities(seen: IntSet) {
val chunks = this.level.chunkSource.chunkMap
val entities = (chunks as ChunkMapAccessor).entityMap
val viewDistance = this.level.server.playerList.viewDistance
for (tracked in entities.values) {
val entity = (tracked as TrackedEntityAccessor).entity
val range = min(tracked.getRange(), viewDistance * 16).toDouble()
if (this.shouldTrackEntity(entity, range)) {
this.addTrackedEntity(WrappedTrackedEntity(tracked))
}
}
}
/**
* We wrap the tracked entity into a new class because
* [TrackedEntity] by default is a package-private class.
*
* We don't want to force mods that need to implement [ChunkSender]
* to have an access-widener for this class.
*/
class WrappedTrackedEntity(val tracked: TrackedEntity) {
/**
* Gets the [Entity] being tracked.
*
* @return The tracked entity.
*/
@Suppress("unused")
fun getEntity(): Entity {
return (this.tracked as TrackedEntityAccessor).entity
}
/**
* Gets the [ServerEntity] being tracked.
*
* @return The server entity.
*/
fun getServerEntity(): ServerEntity {
return (this.tracked as TrackedEntityAccessor).serverEntity
}
}
} | 1 | Kotlin | 8 | 91 | 04aad600db3705026759d91eba96554493d7dfbd | 7,773 | ServerReplay | MIT License |
feature/profile/src/main/java/com/niyaj/profile/components/AccountInfoBox.kt | skniyajali | 644,752,474 | false | {"Kotlin": 4922890, "Shell": 4104, "Batchfile": 1397, "Java": 232} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.niyaj.profile.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import com.niyaj.designsystem.theme.SpaceSmall
@Composable
fun AccountInfoBox(
title: String,
icon: ImageVector,
value: String,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.fillMaxWidth()
.padding(SpaceSmall),
) {
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Row(
modifier = Modifier
.weight(1.5f),
horizontalArrangement = Arrangement.spacedBy(SpaceSmall, Alignment.Start),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = icon,
contentDescription = title,
tint = MaterialTheme.colorScheme.secondary,
)
Text(
text = title,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.SemiBold,
)
}
Box(
modifier = Modifier
.weight(1.5f),
contentAlignment = Alignment.CenterEnd,
) {
Text(
text = value,
style = MaterialTheme.typography.bodyMedium,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.SemiBold,
)
}
}
}
}
| 42 | Kotlin | 0 | 1 | 49485fe344b9345cd0cce0e0961742226dbd8ea1 | 2,928 | PoposRoom | Apache License 2.0 |
videoplayerapp/src/main/java/com/example/android/videoplayersample/MediaCatalog.kt | googlearchive | 127,076,887 | false | null | /*
* Copyright 2018 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.videoplayersample
import android.net.Uri
import android.support.v4.media.MediaDescriptionCompat
/**
* Manages a set of media metadata that is used to create a playlist for [VideoActivity].
*/
open class MediaCatalog(
private val list: MutableList<MediaDescriptionCompat>) : List<MediaDescriptionCompat> by list {
companion object : MediaCatalog(mutableListOf())
init {
// More creative commons, creative commons videos - https://www.blender.org/about/projects/
list.add(
with(MediaDescriptionCompat.Builder()) {
setDescription("MP4 loaded over HTTP")
setMediaId("1")
// License - https://peach.blender.org/download/
setMediaUri(Uri.parse("http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4"))
setTitle("Short film Big Buck Bunny")
setSubtitle("Streaming video")
build()
})
list.add(
with(MediaDescriptionCompat.Builder()) {
setDescription("MP4 loaded over HTTP")
setMediaId("2")
// License - https://archive.org/details/ElephantsDream
setMediaUri(Uri.parse("https://archive.org/download/ElephantsDream/ed_hd.mp4"))
setTitle("Short film Elephants Dream")
setSubtitle("Streaming video")
build()
})
list.add(
with(MediaDescriptionCompat.Builder()) {
setDescription("MOV loaded over HTTP")
setMediaId("3")
// License - https://mango.blender.org/sharing/
setMediaUri(Uri.parse("http://ftp.nluug.nl/pub/graphics/blender/demo/movies/ToS/ToS-4k-1920.mov"))
setTitle("Short film Tears of Steel")
setSubtitle("Streaming audio")
build()
})
}
} | 1 | null | 50 | 146 | 14898c2271bfb53be8d9ab250f2107a28ec20ac5 | 2,680 | android-VideoPlayer | Apache License 2.0 |
plugins/client/graphql-kotlin-client-generator/src/main/kotlin/com/expediagroup/graphql/plugin/client/generator/types/generatePropertySpecs.kt | ssullivan | 344,931,918 | false | null | /*
* Copyright 2020 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.plugin.generator.types
import com.expediagroup.graphql.plugin.generator.GraphQLClientGeneratorContext
import com.expediagroup.graphql.plugin.generator.exceptions.DeprecatedFieldsSelectedException
import com.expediagroup.graphql.plugin.generator.exceptions.InvalidSelectionSetException
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.PropertySpec
import graphql.Directives.DeprecatedDirective
import graphql.language.Field
import graphql.language.FieldDefinition
import graphql.language.NonNullType
import graphql.language.SelectionSet
import graphql.language.StringValue
/**
* Generate [PropertySpec]s from the field definitions and selection set.
*/
internal fun generatePropertySpecs(
context: GraphQLClientGeneratorContext,
objectName: String,
selectionSet: SelectionSet,
fieldDefinitions: List<FieldDefinition>,
abstract: Boolean = false
): List<PropertySpec> = selectionSet.getSelectionsOfType(Field::class.java)
.filterNot {
val typeNameSelected = it.name == "__typename"
if (typeNameSelected) {
context.objectsWithTypeNameSelection.add(objectName)
}
typeNameSelected
}
.map { selectedField ->
val fieldDefinition = fieldDefinitions.find { it.name == selectedField.name }
?: throw InvalidSelectionSetException(selectedField.name, objectName)
val nullable = fieldDefinition.type !is NonNullType
val kotlinFieldType = generateTypeName(context, fieldDefinition.type, selectedField.selectionSet)
val fieldName = selectedField.alias ?: fieldDefinition.name
val propertySpecBuilder = PropertySpec.builder(fieldName, kotlinFieldType.copy(nullable = nullable))
if (!abstract) {
propertySpecBuilder.initializer(fieldName)
}
fieldDefinition.getDirective(DeprecatedDirective.name)?.let { deprecatedDirective ->
if (!context.allowDeprecated) {
throw DeprecatedFieldsSelectedException(selectedField.name, objectName)
} else {
val deprecatedReason = deprecatedDirective.getArgument("reason")?.value as? StringValue
val reason = deprecatedReason?.value ?: "no longer supported"
propertySpecBuilder.addAnnotation(
AnnotationSpec.builder(Deprecated::class)
.addMember("message = %S", reason)
.build()
)
}
}
fieldDefinition.description?.content?.let { kdoc ->
propertySpecBuilder.addKdoc(kdoc)
}
propertySpecBuilder.build()
}
| 0 | null | 0 | 1 | 4a89a8b183defa6a1f25494f2f9f90753f2723b2 | 3,276 | graphql-kotlin | Apache License 2.0 |
analysis/kt-references/src/org/jetbrains/kotlin/idea/references/KtForLoopInReference.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 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.idea.references
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.util.OperatorNameConventions
abstract class KtForLoopInReference(element: KtForExpression) : KtMultiReference<KtForExpression>(element) {
override fun getRangeInElement(): TextRange {
val inKeyword = expression.inKeyword ?: return TextRange.EMPTY_RANGE
val offset = inKeyword.startOffsetInParent
return TextRange(offset, offset + inKeyword.textLength)
}
override val resolvesByNames: Collection<Name>
get() = NAMES
companion object {
private val NAMES = listOf(
OperatorNameConventions.ITERATOR,
OperatorNameConventions.NEXT,
OperatorNameConventions.HAS_NEXT
)
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,086 | kotlin | Apache License 2.0 |
src/main/kotlin/Main.kt | aurelioklv | 737,580,684 | false | {"Kotlin": 83511} | package com.aurelioklv
import com.aurelioklv.enigma.component.ReflectorType
import com.aurelioklv.enigma.component.RotorType
import com.aurelioklv.enigma.util.Factory
fun main() {
val enigmaI = Factory.createEnigma(
Factory.createPlugboard(wiringString = "vbnmhjklasdfqwertyui"),
rotorTypes = listOf(RotorType.ROTOR_V, RotorType.ROTOR_I, RotorType.ROTOR_V),
reflectorType = ReflectorType.REFLECTOR_UKW_B_ENIGMA_I
)
val enigmaM3 = Factory.createEnigma(
Factory.createPlugboard(wiringString = "qawsedrftgyhujikolpz"),
rotorTypes = listOf(RotorType.ROTOR_VIII, RotorType.ROTOR_VII, RotorType.ROTOR_IV),
reflectorType = ReflectorType.REFLECTOR_UKW_C_ENIGMA_M3
)
val enigmaNorenigma = Factory.createEnigma(
Factory.createPlugboard(wiringString = "plokijuhygtfrdeswa"),
rotorTypes = listOf(RotorType.ROTOR_V_NORENIGMA, RotorType.ROTOR_II_NORENIGMA, RotorType.ROTOR_III_NORENIGMA),
reflectorType = ReflectorType.REFLECTOR_UKW_NORENIGMA
)
val enigmaM4 = Factory.createEnigma(
Factory.createPlugboard(wiringString = "KRYPTOSX"),
rotorTypes = listOf(RotorType.ROTOR_GAMMA, RotorType.ROTOR_VI, RotorType.ROTOR_II, RotorType.ROTOR_III),
reflectorType = ReflectorType.REFLECTOR_UKW_C_THIN
)
val enigmaSonder = Factory.createEnigma(
Factory.createPlugboard(wiringString = "SECRXTINFO"),
rotorTypes = listOf(RotorType.ROTOR_III_SONDER, RotorType.ROTOR_I_SONDER, RotorType.ROTOR_II_SONDER),
reflectorType = ReflectorType.REFLECTOR_UKW_SONDER
)
val message = "P.Sherman, 42 Wallaby Way, Sydney"
enigmaI.config(rotorInitialLetter = listOf('D', 'I', 'S'))
println(enigmaI.process(message, split = 5, removeSymbol = true))
// NFNDP YJW42 OYCQF ZZUXA KVKUY G
enigmaI.config(rotorInitialLetter = listOf('D', 'I', 'S'))
println(enigmaI.process("NFNDP YJW42 OYCQF ZZUXA KVKUY G", removeWhiteSpace = true))
// PSHERMAN42WALLABYWAYSYDNEY
enigmaM4.config(rotorInitialLetter = listOf('C', 'V', 'R', 'Y'))
println(enigmaM4.process("ikhijfnezi4cmwt3i", preserveCase = true))
// ??🗿
} | 0 | Kotlin | 0 | 0 | 2110e20ab9e5d2160b0e32bda137b0f63a93ecc3 | 2,157 | enigma | MIT License |
src/main/kotlin/no/nav/helse/spurte_du/Api.kt | navikt | 728,230,541 | false | {"Kotlin": 40967, "Dockerfile": 168} | package no.nav.helse.spurte_du
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import no.nav.helse.spurte_du.SpurteDuPrinsipal.Companion.logg
import java.util.*
fun Route.api(logg: Logg, maskeringer: Maskeringtjeneste) {
route("/vis_meg") {
get("{maskertId?}") {
val (uuid, principal) = call.håndterVisMeg(logg) ?: return@get
try {
maskeringer.visMaskertVerdi(logg, call, uuid, principal?.claims)
} catch (err: Exception) {
logg.error("Ukjent feil oppstod: {}", err.message, err)
return@get call.respondText("Nå røyk vi på en smell her. Vi får håpe det er forbigående!", status = HttpStatusCode.InternalServerError)
}
}
get("{maskertId}/metadata") {
val (uuid, principal) = call.håndterVisMeg(logg) ?: return@get
try {
maskeringer.visMetadata(logg, call, uuid, principal?.claims)
} catch (err: Exception) {
logg.error("Ukjent feil oppstod: {}", err.message, err)
return@get call.respondText("Nå røyk vi på en smell her. Vi får håpe det er forbigående!", status = HttpStatusCode.InternalServerError)
}
}
}
get("/skjul_meg") {
call.respondText("""<!doctype html>
<head>
<meta charset="utf-8" />
<title>Skjul meg!</title>
</head>
<body>
<h1>Skjul meg</h1>
<form action="/skjul_meg" method="post">
<fieldset>
<legend>Url</legend>
<input type="text" name="url" />
</fieldset>
<fieldset>
<legend>Tekst</legend>
<input type="text" name="tekst" />
</fieldset>
<fieldset>
<legend>Påkrevd tilgang</legend>
<input type="text" name="påkrevdTilgang" />
<p>
Kan enten være en Azure AD-gruppeID eller en Nav-epost.
</p>
</fieldset>
<fieldset>
<button type="submit">Send inn rakker'n</button>
</fieldset>
</form>
<h2>API-bruk</h2>
<p>Om <code>påkrevdTilgang</code> utelates vil verdien være åpen for alle</p>
<p><code>påkrevdTilgang</code> kan være en Azure AD-gruppe ID eller en NAV epost-adresse (f.eks. om du vil sende til én mottaker)</p>
<h3>Skjule url</h3>
<pre>curl -X POST -d '{ "url": "http://min-app.intern.nav.no/hemmelig", "påkrevdTilgang": "en gruppe" }' -H 'Content-type: application/json' /skjul_meg</pre>
<pre>curl -X POST -d '{ "url": "http://min-app.intern.nav.no/hemmelig", "påkrevdTilgang": "[email protected]" }' -H 'Content-type: application/json' /skjul_meg</pre>
<h3>Skjule tekst</h3>
<pre>curl -X POST -d '{ "tekst": "Superhemmelig melding", "påkrevdTilgang": "en gruppe" }' -H 'Content-type: application/json' /skjul_meg</pre>
<h3>Respons</h3>
<p>Responsen inneholder felt for ID-en til den skjulte verdien, en absolutt-URL til visning, og path til visning</p>
<pre>
{
"id": "<en uuid>",
"url": "https://spurte-du.intern.nav.no/vis_meg/<uuid-en>",
"path": "/vis_meg/<uuid-en>"
}
</pre>
</body>
</html>
""", ContentType.Text.Html)
}
post("/skjul_meg") {
val request = call.receiveNullable<SkjulMegRequest>()
val maskertVerdi = request?.tilMaskertVerdi() ?: return@post call.respond(HttpStatusCode.BadRequest, ApiFeilmelding(
"""Du må angi en gyldig json-kropp. Eksempel: { "url": "en-url", "påkrevdTilgang": "<en azure gruppe-ID eller NAV-epost>" } eller { "tekst": "en tekst" } """
))
val id = maskeringer.lagre(maskertVerdi)
val path = "/vis_meg/$id"
call.respond(SkjulMegRespons(
id = id,
url = call.url {
set("https", port = 443)
path(path)
},
path = path
))
}
}
private suspend fun ApplicationCall.håndterVisMeg(logg: Logg): Pair<UUID, SpurteDuPrinsipal?>? {
val id = parameters["maskertId"]
if (id == null) {
respondText("Maksert id mangler fra url", status = HttpStatusCode.BadRequest)
return null
}
val uuid = try {
UUID.fromString(id)
} catch (err: IllegalArgumentException) {
respondText("Maksert id er jo ikke gyldig uuid", status = HttpStatusCode.BadRequest)
return null
}
val principal = principal<SpurteDuPrinsipal>()
principal.logg(logg)
return uuid to principal
}
data class ApiFeilmelding(
val feilbeskrivelse: String
)
data class SkjulMegRespons(
val id: UUID,
val url: String,
val path: String
)
data class SkjulMegRequest(
val url: String?,
val tekst: String?,
val påkrevdTilgang: String?
) {
fun tilMaskertVerdi(): MaskertVerdi? {
val tilganger = påkrevdTilgang?.split(',')?.map(String::trim) ?: emptyList()
return when {
url?.takeUnless { it.isBlank() } != null -> MaskertVerdi.Url(UUID.randomUUID(), url, tilganger)
tekst?.takeUnless { it.isBlank() } != null -> MaskertVerdi.Tekst(UUID.randomUUID(), tekst, tilganger)
else -> null
}
}
}
suspend fun ApplicationCall.`404`(logg: Logg, hjelpetekst: String) {
logg.info(hjelpetekst)
respondText("Finner ikke noe spesielt til deg", status = HttpStatusCode.NotFound)
}
| 3 | Kotlin | 0 | 0 | 88e7dd0cc4d11c794012b41d86f4f682cb3eb210 | 5,880 | spurtedu | MIT License |
src/main/kotlin/no/nav/helse/spurte_du/Api.kt | navikt | 728,230,541 | false | {"Kotlin": 40967, "Dockerfile": 168} | package no.nav.helse.spurte_du
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import no.nav.helse.spurte_du.SpurteDuPrinsipal.Companion.logg
import java.util.*
fun Route.api(logg: Logg, maskeringer: Maskeringtjeneste) {
route("/vis_meg") {
get("{maskertId?}") {
val (uuid, principal) = call.håndterVisMeg(logg) ?: return@get
try {
maskeringer.visMaskertVerdi(logg, call, uuid, principal?.claims)
} catch (err: Exception) {
logg.error("Ukjent feil oppstod: {}", err.message, err)
return@get call.respondText("Nå røyk vi på en smell her. Vi får håpe det er forbigående!", status = HttpStatusCode.InternalServerError)
}
}
get("{maskertId}/metadata") {
val (uuid, principal) = call.håndterVisMeg(logg) ?: return@get
try {
maskeringer.visMetadata(logg, call, uuid, principal?.claims)
} catch (err: Exception) {
logg.error("Ukjent feil oppstod: {}", err.message, err)
return@get call.respondText("Nå røyk vi på en smell her. Vi får håpe det er forbigående!", status = HttpStatusCode.InternalServerError)
}
}
}
get("/skjul_meg") {
call.respondText("""<!doctype html>
<head>
<meta charset="utf-8" />
<title>Skjul meg!</title>
</head>
<body>
<h1>Skjul meg</h1>
<form action="/skjul_meg" method="post">
<fieldset>
<legend>Url</legend>
<input type="text" name="url" />
</fieldset>
<fieldset>
<legend>Tekst</legend>
<input type="text" name="tekst" />
</fieldset>
<fieldset>
<legend>Påkrevd tilgang</legend>
<input type="text" name="påkrevdTilgang" />
<p>
Kan enten være en Azure AD-gruppeID eller en Nav-epost.
</p>
</fieldset>
<fieldset>
<button type="submit">Send inn rakker'n</button>
</fieldset>
</form>
<h2>API-bruk</h2>
<p>Om <code>påkrevdTilgang</code> utelates vil verdien være åpen for alle</p>
<p><code>påkrevdTilgang</code> kan være en Azure AD-gruppe ID eller en NAV epost-adresse (f.eks. om du vil sende til én mottaker)</p>
<h3>Skjule url</h3>
<pre>curl -X POST -d '{ "url": "http://min-app.intern.nav.no/hemmelig", "påkrevdTilgang": "en gruppe" }' -H 'Content-type: application/json' /skjul_meg</pre>
<pre>curl -X POST -d '{ "url": "http://min-app.intern.nav.no/hemmelig", "påkrevdTilgang": "[email protected]" }' -H 'Content-type: application/json' /skjul_meg</pre>
<h3>Skjule tekst</h3>
<pre>curl -X POST -d '{ "tekst": "Superhemmelig melding", "påkrevdTilgang": "en gruppe" }' -H 'Content-type: application/json' /skjul_meg</pre>
<h3>Respons</h3>
<p>Responsen inneholder felt for ID-en til den skjulte verdien, en absolutt-URL til visning, og path til visning</p>
<pre>
{
"id": "<en uuid>",
"url": "https://spurte-du.intern.nav.no/vis_meg/<uuid-en>",
"path": "/vis_meg/<uuid-en>"
}
</pre>
</body>
</html>
""", ContentType.Text.Html)
}
post("/skjul_meg") {
val request = call.receiveNullable<SkjulMegRequest>()
val maskertVerdi = request?.tilMaskertVerdi() ?: return@post call.respond(HttpStatusCode.BadRequest, ApiFeilmelding(
"""Du må angi en gyldig json-kropp. Eksempel: { "url": "en-url", "påkrevdTilgang": "<en azure gruppe-ID eller NAV-epost>" } eller { "tekst": "en tekst" } """
))
val id = maskeringer.lagre(maskertVerdi)
val path = "/vis_meg/$id"
call.respond(SkjulMegRespons(
id = id,
url = call.url {
set("https", port = 443)
path(path)
},
path = path
))
}
}
private suspend fun ApplicationCall.håndterVisMeg(logg: Logg): Pair<UUID, SpurteDuPrinsipal?>? {
val id = parameters["maskertId"]
if (id == null) {
respondText("Maksert id mangler fra url", status = HttpStatusCode.BadRequest)
return null
}
val uuid = try {
UUID.fromString(id)
} catch (err: IllegalArgumentException) {
respondText("Maksert id er jo ikke gyldig uuid", status = HttpStatusCode.BadRequest)
return null
}
val principal = principal<SpurteDuPrinsipal>()
principal.logg(logg)
return uuid to principal
}
data class ApiFeilmelding(
val feilbeskrivelse: String
)
data class SkjulMegRespons(
val id: UUID,
val url: String,
val path: String
)
data class SkjulMegRequest(
val url: String?,
val tekst: String?,
val påkrevdTilgang: String?
) {
fun tilMaskertVerdi(): MaskertVerdi? {
val tilganger = påkrevdTilgang?.split(',')?.map(String::trim) ?: emptyList()
return when {
url?.takeUnless { it.isBlank() } != null -> MaskertVerdi.Url(UUID.randomUUID(), url, tilganger)
tekst?.takeUnless { it.isBlank() } != null -> MaskertVerdi.Tekst(UUID.randomUUID(), tekst, tilganger)
else -> null
}
}
}
suspend fun ApplicationCall.`404`(logg: Logg, hjelpetekst: String) {
logg.info(hjelpetekst)
respondText("Finner ikke noe spesielt til deg", status = HttpStatusCode.NotFound)
}
| 3 | Kotlin | 0 | 0 | 88e7dd0cc4d11c794012b41d86f4f682cb3eb210 | 5,880 | spurtedu | MIT License |
objects/src/commonMain/kotlin/ru/krindra/vkkt/objects/callback/CallbackVideoCommentDelete.kt | krindra | 780,080,411 | false | {"Kotlin": 1336107} | package ru.krindra.vkkt.objects.callback
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
*
* @param id
* @param ownerId
* @param userId
* @param videoId
*/
@Serializable
data class CallbackVideoCommentDelete (
@SerialName("id") val id: Int,
@SerialName("user_id") val userId: Int,
@SerialName("owner_id") val ownerId: Int,
@SerialName("video_id") val videoId: Int,
)
| 0 | Kotlin | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 433 | VKKT | MIT License |
ion-schema/src/main/kotlin/com/amazon/ionschema/util/CloseableIterator.kt | amazon-ion | 148,685,964 | false | {"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631} | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.ionschema.util
import java.io.Closeable
/**
* An Iterator that has the opportunity to free up any resources
* when [close()] is called, after it is no longer needed.
*/
interface CloseableIterator<T> : Iterator<T>, Closeable
| 40 | Kotlin | 14 | 27 | 7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b | 844 | ion-schema-kotlin | Apache License 2.0 |
src/main/kotlin/com/jetbrains/sorrel/plugin/packagesearch/api/model/StandardV2Version.kt | JetBrains-Research | 300,825,939 | false | {"Kotlin": 588227, "Java": 4072} | package com.jetbrains.sorrel.plugin.packagesearch.api.model
import com.google.gson.annotations.SerializedName
data class StandardV2Version(
@SerializedName("version")
val version: String,
@SerializedName("last_changed")
val lastChanged: Long?,
@SerializedName("stable")
val stable: Boolean?,
@SerializedName("repository_ids")
val repositoryIds: List<String>?,
@SerializedName("artifacts")
val artifacts: List<StandardV2Artifact>?
)
data class StandardV2Artifact(
@SerializedName("sha1")
val sha1: String?,
@SerializedName("sha256")
val sha256: String?,
@SerializedName("md5")
val md5: String?,
@SerializedName("packaging")
val packaging: String?,
@SerializedName("classifier")
val classifier: String?
)
| 1 | Kotlin | 4 | 21 | 5f020a313dd2395a9ebe748eb0e0980d6fe08e63 | 876 | sorrel | Apache License 2.0 |
build/icons/compose/vitaminicons/fill/Barcode.kt | Decathlon | 511,157,831 | false | {"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33103, "Handlebars": 771} | package com.decathlon.vitamin.compose.vitaminicons.fill
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.decathlon.vitamin.compose.vitaminicons.FillGroup
public val FillGroup.Barcode: ImageVector
get() {
if (_barcode != null) {
return _barcode!!
}
_barcode = Builder(name = "Barcode", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(22.0f, 2.0f)
horizontalLineTo(2.0f)
verticalLineTo(22.0f)
horizontalLineTo(22.0f)
verticalLineTo(2.0f)
close()
moveTo(15.0f, 3.0f)
horizontalLineTo(21.0f)
verticalLineTo(8.0f)
horizontalLineTo(19.0f)
verticalLineTo(5.0f)
horizontalLineTo(15.0f)
verticalLineTo(3.0f)
close()
moveTo(9.0f, 3.0f)
verticalLineTo(5.0f)
horizontalLineTo(5.0f)
verticalLineTo(8.0f)
horizontalLineTo(3.0f)
verticalLineTo(3.0f)
horizontalLineTo(9.0f)
close()
moveTo(15.0f, 21.0f)
verticalLineTo(19.0f)
horizontalLineTo(19.0f)
verticalLineTo(16.0f)
horizontalLineTo(21.0f)
verticalLineTo(21.0f)
horizontalLineTo(15.0f)
close()
moveTo(9.0f, 21.0f)
horizontalLineTo(3.0f)
verticalLineTo(16.0f)
horizontalLineTo(5.0f)
verticalLineTo(19.0f)
horizontalLineTo(9.0f)
verticalLineTo(21.0f)
close()
moveTo(9.0f, 7.0f)
horizontalLineTo(6.0f)
verticalLineTo(17.0f)
horizontalLineTo(9.0f)
verticalLineTo(7.0f)
close()
moveTo(10.0f, 7.0f)
horizontalLineTo(12.0f)
verticalLineTo(17.0f)
horizontalLineTo(10.0f)
verticalLineTo(7.0f)
close()
moveTo(14.0f, 7.0f)
horizontalLineTo(13.0f)
verticalLineTo(17.0f)
horizontalLineTo(14.0f)
verticalLineTo(7.0f)
close()
moveTo(15.0f, 7.0f)
horizontalLineTo(18.0f)
verticalLineTo(17.0f)
horizontalLineTo(15.0f)
verticalLineTo(7.0f)
close()
}
}
.build()
return _barcode!!
}
private var _barcode: ImageVector? = null
| 1 | Kotlin | 5 | 33 | c2c9cfa43128d412b7b2841cabd76952a13db2e1 | 3,471 | vitamin-design | Apache License 2.0 |
src/main/kotlin/by/dev/madhead/doktor/confluence/ConfluenceException.kt | jenkinsci | 102,877,358 | true | null | package by.dev.madhead.doktor.confluence
class ConfluenceException(override val message: String, cause: Throwable?) : Throwable(message, cause) {
constructor(message: String) : this(message, null)
}
| 0 | Kotlin | 3 | 20 | 25b51884853d8be0d524673a40eaccc87a7b91d8 | 201 | doktor-plugin | Apache License 2.0 |
app/src/main/java/com/example/hotpopcorn/view/main/MainActivity.kt | kamil-matula | 359,783,715 | false | null | package com.example.hotpopcorn.view.main
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import com.example.hotpopcorn.R
import com.example.hotpopcorn.databinding.ActivityMainBinding
import com.example.hotpopcorn.viewmodel.MovieViewModel
import com.example.hotpopcorn.viewmodel.PersonViewModel
import com.example.hotpopcorn.viewmodel.TVShowViewModel
class MainActivity : AbstractFirebaseActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var movieVM : MovieViewModel
private lateinit var personVM : PersonViewModel
private lateinit var showVM : TVShowViewModel
private var searchbarContent : String = ""
private var justLaunched : Boolean = true
override fun onCreate(savedInstanceState: Bundle?) {
// Binding with layout:
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setUpNavigation()
// Initializing ViewModels:
movieVM = ViewModelProvider(this).get(MovieViewModel::class.java)
personVM = ViewModelProvider(this).get(PersonViewModel::class.java)
showVM = ViewModelProvider(this).get(TVShowViewModel::class.java)
// Adding connection listener and initializing the lists:
makeIfNotConnected { justLaunched = false }
addConnectionListener(
actionForReconnecting = {
downloadData(searchbarContent)
if (!justLaunched) showToast(getString(R.string.connected))
justLaunched = false
}, actionForDisconnecting = {
showToast(getString(R.string.disconnected))
}
)
// Displaying subtitle and Home Icon only in Details:
val bar = (this as AppCompatActivity?)?.supportActionBar
bar?.setHomeAsUpIndicator(R.drawable.ic_home_24)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_main) as NavHostFragment
navHostFragment.navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.id == R.id.exploreFragment || destination.id == R.id.libraryFragment) {
bar?.subtitle = null
bar?.setDisplayHomeAsUpEnabled(false)
} else bar?.setDisplayHomeAsUpEnabled(true)
}
}
// Managing the menu - Search Icon:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
// Search Icon with searching process:
val searchView = menu?.findItem(R.id.search)?.actionView as SearchView
searchView.inputType = 33 // eliminates "SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length" error
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(givenText : String) : Boolean { return false }
override fun onQueryTextChange(givenText : String): Boolean {
makeIfConnected {
searchbarContent = givenText
downloadData(searchbarContent)
}
return false
}
})
return true
}
// Managing the Home Button:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
startActivity(Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK })
}
return super.onOptionsItemSelected(item)
}
// Setting up navigation that can be seen at the bottom of the screen:
private fun setUpNavigation() {
// Functionality:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_main) as NavHostFragment
NavigationUI.setupWithNavController(binding.btmNav, navHostFragment.navController)
// Hiding in Details:
navHostFragment.navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.id == R.id.exploreFragment || destination.id == R.id.libraryFragment)
binding.btmNav.visibility = View.VISIBLE
else binding.btmNav.visibility = View.GONE
}
}
// Downloading matching data for all lists:
private fun downloadData(givenText : String) {
movieVM.setMoviesWithMatchingTitle(givenText)
personVM.setPeopleWithMatchingName(givenText)
showVM.setTVShowsWithMatchingTitle(givenText)
firebaseVM.setMatchingSavedObjects(givenText)
}
} | 0 | Kotlin | 0 | 0 | b08066819a92d7228f2a0a1a40f69564298418b0 | 4,932 | HotPopcorn | MIT License |
mobile_app1/module994/src/main/java/module994packageKt0/Foo150.kt | uber-common | 294,831,672 | false | null | package module692packageKt0;
annotation class Foo150Fancy
@Foo150Fancy
class Foo150 {
fun foo0(){
module692packageKt0.Foo149().foo4()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 267 | android-build-eval | Apache License 2.0 |
koin-projects/examples/hello-ktor/src/test/kotlin/org/koin/sample/ApplicationJobRoutesTest.kt | ermolnik | 212,771,350 | false | null | package org.koin.sample
import io.ktor.application.Application
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.handleRequest
import io.ktor.server.testing.withTestApplication
import org.junit.Test
import org.koin.test.AutoCloseKoinTest
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class ApplicationJobRoutesTest : AutoCloseKoinTest() {
@Test
fun testHelloRequest() = withTestApplication(Application::main) {
with(handleRequest(HttpMethod.Get, "/hello")) {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("Hello Ktor & Koin !", response.content)
}
with(handleRequest(HttpMethod.Get, "/index.html")) {
assertFalse(requestHandled)
}
}
@Test
fun testV1HelloRequest() = withTestApplication(Application::main) {
with(handleRequest(HttpMethod.Get, "/v1/hello")) {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("[/v1/hello] Hello Ktor & Koin !", response.content)
}
with(handleRequest(HttpMethod.Get, "/index.html")) {
assertFalse(requestHandled)
}
}
@Test
fun testV1ByeRequest() = withTestApplication(Application::main) {
with(handleRequest(HttpMethod.Get, "/v1/bye")) {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("[/v1/bye] Hello Ktor & Koin !", response.content)
}
with(handleRequest(HttpMethod.Get, "/index.html")) {
assertFalse(requestHandled)
}
}
}
| 0 | null | 1 | 4 | 86c0398775463ac6be1301a4de0d2282e690462e | 1,617 | koin | Apache License 2.0 |
modules/effects/arrow-effects/src/main/kotlin/arrow/effects/MonadSuspend.kt | scame | 120,785,791 | true | {"Kotlin": 1404949, "CSS": 118096, "HTML": 9871, "JavaScript": 7457, "Java": 4423, "Shell": 3057} | package arrow.effects
import arrow.HK
import arrow.TC
import arrow.core.Either
import arrow.core.Tuple2
import arrow.core.toT
import arrow.effects.data.internal.BindingCancellationException
import arrow.typeclass
import arrow.typeclasses.MonadError
import kotlin.coroutines.experimental.startCoroutine
/** The context required to defer evaluating a safe computation. **/
@typeclass
interface MonadSuspend<F> : MonadError<F, Throwable>, TC {
fun <A> suspend(fa: () -> HK<F, A>): HK<F, A>
operator fun <A> invoke(fa: () -> A): HK<F, A> =
suspend {
try {
pure(fa())
} catch (t: Throwable) {
raiseError<A>(t)
}
}
fun lazy(): HK<F, Unit> = invoke { }
fun <A> deferUnsafe(f: () -> Either<Throwable, A>): HK<F, A> =
suspend { f().fold({ raiseError<A>(it) }, { pure(it) }) }
}
inline fun <reified F, A> (() -> A).defer(SC: MonadSuspend<F> = monadSuspend()): HK<F, A> = SC(this)
inline fun <reified F, A> (() -> Either<Throwable, A>).deferUnsafe(SC: MonadSuspend<F> = monadSuspend()): HK<F, A> =
SC.deferUnsafe(this)
/**
* Entry point for monad bindings which enables for comprehensions. The underlying impl is based on coroutines.
* A coroutines is initiated and inside [MonadSuspendCancellableContinuation] suspended yielding to [Monad.flatMap]. Once all the flatMap binds are completed
* the underlying monad is returned from the act of executing the coroutine
*
* This one operates over [MonadError] instances that can support [Throwable] in their error type automatically lifting
* errors as failed computations in their monadic context and not letting exceptions thrown as the regular monad binding does.
*
* This operation is cancellable by calling invoke on the [Disposable] return.
* If [Disposable.invoke] is called the binding result will become a lifted [BindingCancellationException].
*/
fun <F, B> MonadSuspend<F>.bindingCancellable(c: suspend MonadSuspendCancellableContinuation<F, *>.() -> HK<F, B>): Tuple2<HK<F, B>, Disposable> {
val continuation = MonadSuspendCancellableContinuation<F, B>(this)
c.startCoroutine(continuation, continuation)
return continuation.returnedMonad() toT continuation.disposable()
} | 0 | Kotlin | 0 | 0 | 4208bc074cc0bb7e952e60501261808b93b6b797 | 2,296 | arrow | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/activities/ActivitiesApiServiceTest.kt | ministryofjustice | 445,140,246 | false | {"Kotlin": 1195589, "Mustache": 1803, "Dockerfile": 1118} | @file:OptIn(ExperimentalCoroutinesApi::class)
package uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities
import com.github.tomakehurst.wiremock.client.WireMock.equalTo
import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Import
import org.springframework.web.reactive.function.client.WebClientResponseException.NotFound
import org.springframework.web.reactive.function.client.WebClientResponseException.ServiceUnavailable
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityLite
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.Allocation.Status.ACTIVE
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.helpers.SpringAPIServiceTest
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.wiremock.ActivitiesApiExtension.Companion.activitiesApi
import java.time.LocalDate
import java.time.LocalDateTime
@SpringAPIServiceTest
@Import(ActivitiesApiService::class, ActivitiesConfiguration::class)
internal class ActivitiesApiServiceTest {
@Autowired
private lateinit var activitiesApiService: ActivitiesApiService
@Nested
inner class GetSchedule {
@BeforeEach
internal fun setUp() {
activitiesApi.stubGetSchedule(
1234,
"""
{
"id": 1234,
"instances": [
{
"id": 123456,
"date": "2022-12-30",
"startTime": "9:00",
"endTime": "10:00",
"cancelled": false,
"cancelledTime": "2022-12-30T14:03:06.365Z",
"cancelledBy": "Adam Smith",
"attendances": [
{
"id": 123456,
"prisonerNumber": "A1234AA",
"attendanceReason": {
"id": 123456,
"code": "ABS",
"description": "Unacceptable absence",
"attended": true,
"capturePay": true,
"captureMoreDetail": true,
"captureCaseNote": true,
"captureIncentiveLevelWarning": false,
"captureOtherText": false,
"displayInAbsence": false,
"displaySequence": 1,
"notes": "Maps to ACCAB in NOMIS"
},
"comment": "Prisoner was too unwell to attend the activity.",
"recordedTime": "2022-12-30T14:03:06.365Z",
"recordedBy": "10/09/2023",
"status": "SCHEDULED",
"payAmount": 100,
"bonusAmount": 50,
"pieces": 0,
"attendanceHistory": []
}
]
}
],
"allocations": [
{
"id": 123456,
"prisonerNumber": "A1234AA",
"bookingId": 10001,
"activitySummary": "string",
"scheduleDescription": "string",
"prisonPayBand": {
"id": 987,
"displaySequence": 1,
"alias": "Low",
"description": "Pay band 1",
"nomisPayBand": 1,
"prisonCode": "PVI"
},
"startDate": "2022-12-30",
"endDate": "2022-12-30",
"allocatedTime": "2022-12-30T14:03:06",
"allocatedBy": "Mr Blogs",
"deallocatedTime": "2022-12-30T14:03:06",
"deallocatedBy": "Mrs Blogs",
"deallocatedReason": {
"code": "RELEASED",
"description": "Released from prison"
},
"status": "ACTIVE",
"exclusions": []
}
],
"description": "Monday AM Houseblock 3",
"suspensions": [
{
"suspendedFrom": "2022-12-30",
"suspendedUntil": "2022-12-30"
}
],
"internalLocation": {
"id": 98877667,
"code": "EDU-ROOM-1",
"description": "Education - R1"
},
"capacity": 10,
"activity": {
"id": 123456,
"prisonCode": "PVI",
"attendanceRequired": false,
"inCell": false,
"pieceWork": false,
"outsideWork": false,
"payPerSession": "F",
"summary": "Maths level 1",
"description": "A basic maths course suitable for introduction to the subject",
"category": {
"id": 1,
"code": "LEISURE_SOCIAL",
"name": "Leisure and social",
"description": "Such as association, library time and social clubs, like music or art"
},
"riskLevel": "High",
"minimumIncentiveLevel": "Basic",
"minimumIncentiveNomisCode": "BAS",
"minimumEducationLevel": [
{
"id": 123456,
"educationLevelCode": "Basic",
"educationLevelDescription": "Basic",
"studyAreaCode": "ENGLA",
"studyAreaDescription": "English language"
}
],
"createdTime": "2023-06-01T09:17:30.425Z",
"activityState": "LIVE",
"capacity": 10,
"allocated": 5
},
"slots": [
{
"id": 123456,
"startTime": "9:00",
"endTime": "11:30",
"daysOfWeek": ["Mon","Tue","Wed"],
"mondayFlag": true,
"tuesdayFlag": true,
"wednesdayFlag": true,
"thursdayFlag": false,
"fridayFlag": false,
"saturdayFlag": false,
"sundayFlag": false
}
],
"startDate" : "2023-01-20",
"endDate" : "2023-12-24",
"runsOnBankHoliday": true
}
""".trimIndent(),
)
}
@Test
fun `should call api with OAuth2 token`() = runTest {
activitiesApiService.getActivitySchedule(1234)
activitiesApi.verify(
getRequestedFor(urlEqualTo("/schedules/1234"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `get parse core data`() = runTest {
val schedule = activitiesApiService.getActivitySchedule(1234)
assertThat(schedule.id).isEqualTo(1234)
assertThat(schedule.startDate).isEqualTo("2023-01-20")
assertThat(schedule.endDate).isEqualTo("2023-12-24")
assertThat(schedule.description).isEqualTo("Monday AM Houseblock 3")
assertThat(schedule.internalLocation?.id).isEqualTo(98877667)
assertThat(schedule.internalLocation?.code).isEqualTo("EDU-ROOM-1")
assertThat(schedule.capacity).isEqualTo(10)
assertThat(schedule.activity.payPerSession).isEqualTo(ActivityLite.PayPerSession.F)
with(schedule.instances.first()) {
assertThat(date).isEqualTo("2022-12-30")
assertThat(startTime).isEqualTo("9:00")
assertThat(endTime).isEqualTo("10:00")
}
with(schedule.slots.first()) {
assertThat(startTime).isEqualTo("9:00")
assertThat(endTime).isEqualTo("11:30")
assertThat(mondayFlag).isTrue()
assertThat(tuesdayFlag).isTrue()
assertThat(wednesdayFlag).isTrue()
assertThat(thursdayFlag).isFalse()
assertThat(fridayFlag).isFalse()
assertThat(saturdayFlag).isFalse()
assertThat(sundayFlag).isFalse()
}
assertThat(schedule.runsOnBankHoliday).isTrue()
assertThat(schedule.activity.category.code).isEqualTo("LEISURE_SOCIAL")
}
@Test
fun `when schedule is not found an exception is thrown`() = runTest {
activitiesApi.stubGetScheduleWithError(1234, status = 404)
assertThrows<NotFound> {
activitiesApiService.getActivitySchedule(1234)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubGetScheduleWithError(1234, status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getActivitySchedule(1234)
}
}
}
@Nested
inner class GetActivity {
@BeforeEach
internal fun setUp() {
activitiesApi.stubGetActivity(
1234,
"""
{
"id": 1234,
"prisonCode": "PVI",
"attendanceRequired": false,
"inCell": false,
"pieceWork": false,
"outsideWork": false,
"payPerSession": "F",
"summary": "Maths level 1",
"description": "A basic maths course suitable for introduction to the subject",
"category": {
"id": 1,
"code": "LEISURE_SOCIAL",
"name": "Leisure and social",
"description": "Such as association, library time and social clubs, like music or art"
},
"eligibilityRules": [],
"schedules": [
{
"id": 123456,
"instances": [
{
"id": 123456,
"date": "2022-12-30",
"startTime": "9:00",
"endTime": "10:00",
"cancelled": false,
"cancelledTime": "2022-12-30T16:09:11.127Z",
"cancelledBy": "Adam Smith",
"attendances": [
{
"id": 123456,
"scheduleInstanceId": 123456,
"prisonerNumber": "A1234AA",
"attendanceReason": {
"id": 123456,
"code": "SICK",
"description": "Sick",
"attended": true,
"capturePay": true,
"captureMoreDetail": true,
"captureCaseNote": true,
"captureIncentiveLevelWarning": false,
"captureOtherText": false,
"displayInAbsence": false,
"displaySequence": 1,
"notes": "Maps to ACCAB in NOMIS"
},
"comment": "Prisoner was too unwell to attend the activity.",
"recordedTime": "2022-12-30T16:09:11.127Z",
"recordedBy": "10/09/2023",
"status": "SCHEDULED",
"payAmount": 100,
"bonusAmount": 50,
"pieces": 0,
"attendanceHistory": []
}
]
}
],
"allocations": [
{
"id": 123456,
"prisonerNumber": "A1234AA",
"bookingId": 10001,
"activitySummary": "string",
"scheduleDescription": "string",
"prisonPayBand": {
"id": 987,
"displaySequence": 1,
"alias": "Low",
"description": "Pay band 1",
"nomisPayBand": 1,
"prisonCode": "PVI"
},
"startDate": "2022-12-30",
"endDate": "2022-12-30",
"allocatedTime": "2022-12-30T16:09:11.127Z",
"allocatedBy": "Mr Blogs",
"deallocatedTime": "2022-12-30T16:09:11.127Z",
"deallocatedBy": "Mrs Blogs",
"deallocatedReason": {
"code": "RELEASED",
"description": "Released from prison"
},
"status": "ACTIVE",
"exclusions": []
}
],
"description": "Monday AM Houseblock 3",
"suspensions": [
{
"suspendedFrom": "2022-12-30",
"suspendedUntil": "2022-12-30"
}
],
"internalLocation": {
"id": 98877667,
"code": "EDU-ROOM-1",
"description": "Education - R1"
},
"capacity": 10,
"activity": {
"id": 123456,
"prisonCode": "PVI",
"attendanceRequired": false,
"inCell": false,
"pieceWork": false,
"outsideWork": false,
"payPerSession": "F",
"summary": "Maths level 1",
"description": "A basic maths course suitable for introduction to the subject",
"category": {
"id": 1,
"code": "LEISURE_SOCIAL",
"name": "Leisure and social",
"description": "Such as association, library time and social clubs, like music or art"
},
"riskLevel": "High",
"minimumIncentiveLevel": "Basic",
"minimumIncentiveNomisCode": "BAS",
"minimumEducationLevel": [
{
"id": 123456,
"educationLevelCode": "Basic",
"educationLevelDescription": "Basic",
"studyAreaCode": "ENGLA",
"studyAreaDescription": "English language"
}
],
"createdTime": "2023-06-01T09:17:30.425Z",
"activityState": "LIVE",
"capacity": 10,
"allocated": 5
},
"slots": [
{
"id": 123456,
"startTime": "9:00",
"endTime": "11:30",
"daysOfWeek": ["Mon","Tue","Wed"],
"mondayFlag": true,
"tuesdayFlag": true,
"wednesdayFlag": true,
"thursdayFlag": false,
"fridayFlag": false,
"saturdayFlag": false,
"sundayFlag": false
}
],
"startDate" : "2023-01-20",
"runsOnBankHoliday": true
}
],
"waitingList": [
{
"id": 123456,
"prisonerNumber": "A1234AA",
"priority": 1,
"createdTime": "2022-12-30T16:09:11.127Z",
"createdBy": "Adam Smith"
}
],
"pay": [
{
"id": 3456,
"incentiveLevel": "Basic",
"incentiveNomisCode": "BAS",
"prisonPayBand": {
"id": 987,
"displaySequence": 1,
"alias": "Low",
"description": "Pay band 1",
"nomisPayBand": 1,
"prisonCode": "PVI"
},
"rate": 150,
"pieceRate": 150,
"pieceRateItems": 10
}
],
"startDate": "2022-12-30",
"endDate": "2022-12-31",
"riskLevel": "High",
"minimumIncentiveLevel": "Basic",
"minimumIncentiveNomisCode": "BAS",
"createdTime": "2022-12-30T16:09:11.127Z",
"createdBy": "Adam Smith",
"minimumEducationLevel": [
{
"id": 123456,
"educationLevelCode": "Basic",
"educationLevelDescription": "Basic",
"studyAreaCode": "ENGLA",
"studyAreaDescription": "English language"
}
]
}
""".trimIndent(),
)
}
@Test
fun `should call api with OAuth2 token`() = runTest {
activitiesApiService.getActivity(1234)
activitiesApi.verify(
getRequestedFor(urlEqualTo("/activities/1234/filtered?earliestSessionDate=${LocalDate.now()}"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `get parse core data`() = runTest {
val activity = activitiesApiService.getActivity(1234)
assertThat(activity.id).isEqualTo(1234)
assertThat(activity.prisonCode).isEqualTo("PVI")
assertThat(activity.description).isEqualTo("A basic maths course suitable for introduction to the subject")
assertThat(activity.category.code).isEqualTo("LEISURE_SOCIAL")
assertThat(activity.startDate).isEqualTo("2022-12-30")
assertThat(activity.endDate).isEqualTo("2022-12-31")
assertThat(activity.summary).isEqualTo("Maths level 1")
val pay = activity.pay[0]
assertThat(pay.incentiveNomisCode).isEqualTo("BAS")
assertThat(pay.prisonPayBand.nomisPayBand).isEqualTo(1)
assertThat(pay.rate).isEqualTo(150)
assertThat(pay.pieceRate).isEqualTo(150)
assertThat(pay.pieceRateItems).isEqualTo(10)
}
@Test
fun `when schedule is not found an exception is thrown`() = runTest {
activitiesApi.stubGetActivityWithError(1234, status = 404)
assertThrows<NotFound> {
activitiesApiService.getActivity(1234)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubGetActivityWithError(1234, status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getActivity(1234)
}
}
}
@Nested
inner class GetAllocation {
@BeforeEach
internal fun setUp() {
activitiesApi.stubGetAllocation(
1234,
"""
{
"id": 1234,
"prisonerNumber": "A1234AA",
"bookingId": 10001,
"activitySummary": "Some activity summary",
"scheduleId": 2345,
"scheduleDescription": "Some schedule description",
"isUnemployment": true,
"prisonPayBand": {
"id": 3456,
"displaySequence": 1,
"alias": "Low",
"description": "Pay band 1",
"nomisPayBand": 1,
"prisonCode": "MDI"
},
"startDate": "2022-09-10",
"endDate": "2023-09-10",
"allocatedTime": "2023-03-17T10:35:19.136Z",
"allocatedBy": "Mr Blogs",
"deallocatedTime": "2023-03-17T10:35:19.136Z",
"deallocatedBy": "Mrs Blogs",
"deallocatedReason": {
"code": "RELEASED",
"description": "Released from prison"
},
"suspendedTime": "2023-03-17T10:35:19.136Z",
"suspendedBy": "Mrs Blogs",
"suspendedReason": "TRANSFERRED",
"status": "ACTIVE",
"exclusions": []
}
""".trimIndent(),
)
}
@Test
fun `should call api with OAuth2 token`() = runTest {
activitiesApiService.getAllocation(1234)
activitiesApi.verify(
getRequestedFor(urlEqualTo("/allocations/id/1234"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `get parse core data`() = runTest {
val allocation = activitiesApiService.getAllocation(1234)
assertThat(allocation.id).isEqualTo(1234)
assertThat(allocation.prisonerNumber).isEqualTo("A1234AA")
assertThat(allocation.bookingId).isEqualTo(10001)
assertThat(allocation.activitySummary).isEqualTo("Some activity summary")
assertThat(allocation.scheduleId).isEqualTo(2345)
assertThat(allocation.scheduleDescription).isEqualTo("Some schedule description")
assertThat(allocation.isUnemployment).isEqualTo(true)
assertThat(allocation.prisonPayBand?.id).isEqualTo(3456)
assertThat(allocation.prisonPayBand?.nomisPayBand).isEqualTo(1)
assertThat(allocation.prisonPayBand?.prisonCode).isEqualTo("MDI")
assertThat(allocation.startDate).isEqualTo(LocalDate.of(2022, 9, 10))
assertThat(allocation.endDate).isEqualTo(LocalDate.of(2023, 9, 10))
assertThat(allocation.allocatedTime).isEqualTo(LocalDateTime.of(2023, 3, 17, 10, 35, 19, 136000000))
assertThat(allocation.allocatedBy).isEqualTo("Mr Blogs")
assertThat(allocation.deallocatedTime).isEqualTo(LocalDateTime.of(2023, 3, 17, 10, 35, 19, 136000000))
assertThat(allocation.deallocatedBy).isEqualTo("Mrs Blogs")
assertThat(allocation.deallocatedReason?.code).isEqualTo("RELEASED")
assertThat(allocation.suspendedTime).isEqualTo(LocalDateTime.of(2023, 3, 17, 10, 35, 19, 136000000))
assertThat(allocation.suspendedBy).isEqualTo("Mrs Blogs")
assertThat(allocation.suspendedReason).isEqualTo("TRANSFERRED")
assertThat(allocation.status).isEqualTo(ACTIVE)
}
@Test
fun `when allocation is not found an exception is thrown`() = runTest {
activitiesApi.stubGetAllocationWithError(1234, status = 404)
assertThrows<NotFound> {
activitiesApiService.getAllocation(1234)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubGetAllocationWithError(1234, status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getAllocation(1234)
}
}
}
@Nested
inner class GetAttendanceSync {
@BeforeEach
internal fun setUp() {
activitiesApi.stubGetAttendanceSync(
1234,
"""
{
"attendanceId": 1234,
"scheduledInstanceId": 2345,
"activityScheduleId": 3456,
"sessionDate": "2023-03-23",
"sessionStartTime": "10:00",
"sessionEndTime": "11:00",
"prisonerNumber": "A1234AA",
"bookingId": 4567,
"attendanceReasonCode": "SICK",
"comment": "Prisoner was too unwell to attend the activity.",
"status": "WAITING",
"payAmount": 100,
"bonusAmount": 50,
"issuePayment": true
}
""".trimIndent(),
)
}
@Test
fun `should call api with OAuth2 token`() = runTest {
activitiesApiService.getAttendanceSync(1234)
activitiesApi.verify(
getRequestedFor(urlEqualTo("/synchronisation/attendance/1234"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `get parse core data`() = runTest {
val attendance = activitiesApiService.getAttendanceSync(1234)
with(attendance) {
assertThat(attendanceId).isEqualTo(1234)
assertThat(scheduledInstanceId).isEqualTo(2345)
assertThat(activityScheduleId).isEqualTo(3456)
assertThat(sessionDate).isEqualTo("2023-03-23")
assertThat(sessionStartTime).isEqualTo("10:00")
assertThat(sessionEndTime).isEqualTo("11:00")
assertThat(prisonerNumber).isEqualTo("A1234AA")
assertThat(bookingId).isEqualTo(4567)
assertThat(attendanceReasonCode).isEqualTo("SICK")
assertThat(comment).isEqualTo("Prisoner was too unwell to attend the activity.")
assertThat(status).isEqualTo("WAITING")
assertThat(payAmount).isEqualTo(100)
assertThat(bonusAmount).isEqualTo(50)
assertThat(issuePayment).isEqualTo(true)
}
}
@Test
fun `when attendance is not found an exception is thrown`() = runTest {
activitiesApi.stubGetAttendanceSyncWithError(1234, status = 404)
assertThrows<NotFound> {
activitiesApiService.getAttendanceSync(1234)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubGetAttendanceSyncWithError(1234, status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getAttendanceSync(1234)
}
}
}
@Nested
inner class GetScheduledInstance {
@BeforeEach
internal fun setUp() {
activitiesApi.stubGetScheduledInstance(
1234,
"""
{
"id": 1234,
"date": "2023-05-02",
"startTime": "09:00",
"endTime": "12:00",
"cancelled": true,
"cancelledTime": "2023-04-21T13:13:28.192Z",
"cancelledBy": "Adam Smith",
"cancelledReason": "Staff unavailable",
"previousScheduledInstanceId": 58,
"previousScheduledInstanceDate": "2023-05-01",
"nextScheduledInstanceId": 60,
"nextScheduledInstanceDate": "2023-05-02",
"attendances": [],
"activitySchedule": {
"id": 4,
"description": "Pen testing again",
"internalLocation": {
"id": 197684,
"code": "ASSO",
"description": "ASSOCIATION"
},
"capacity": 10,
"activity": {
"id": 4,
"prisonCode": "MDI",
"attendanceRequired": true,
"inCell": false,
"pieceWork": false,
"outsideWork": false,
"payPerSession": "H",
"summary": "Pen testing again",
"description": "Pen testing again",
"category": {
"id": 3,
"code": "SAA_PRISON_JOBS",
"name": "Prison jobs",
"description": "Such as kitchen, cleaning, gardens or other maintenance and services to keep the prison running"
},
"riskLevel": "high",
"minimumIncentiveNomisCode": "STD",
"minimumIncentiveLevel": "Standard",
"minimumEducationLevel": [],
"createdTime": "2023-06-01T09:17:30.425Z",
"activityState": "LIVE",
"capacity": 10,
"allocated": 5
},
"slots": [
{
"id": 5,
"startTime": "09:00",
"endTime": "12:00",
"daysOfWeek": [
"Mon",
"Tue",
"Wed",
"Thu",
"Fri"
],
"mondayFlag": true,
"tuesdayFlag": true,
"wednesdayFlag": true,
"thursdayFlag": true,
"fridayFlag": true,
"saturdayFlag": false,
"sundayFlag": false
},
{
"id": 6,
"startTime": "13:00",
"endTime": "16:30",
"daysOfWeek": [
"Mon",
"Tue",
"Wed",
"Thu",
"Fri"
],
"mondayFlag": true,
"tuesdayFlag": true,
"wednesdayFlag": true,
"thursdayFlag": true,
"fridayFlag": true,
"saturdayFlag": false,
"sundayFlag": false
}
],
"startDate": "2023-04-20",
"endDate": null
}
}
""".trimIndent(),
)
}
@Test
fun `should call api with OAuth2 token`() = runTest {
activitiesApiService.getScheduledInstance(1234)
activitiesApi.verify(
getRequestedFor(urlEqualTo("/scheduled-instances/1234"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `get parse core data`() = runTest {
val attendance = activitiesApiService.getScheduledInstance(1234)
with(attendance) {
assertThat(id).isEqualTo(1234)
assertThat(cancelled).isEqualTo(true)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubGetScheduledInstanceWithError(1234, status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getScheduledInstance(1234)
}
}
}
@Nested
inner class AllocationReconciliation {
@BeforeEach
fun `stub allocation reconciliation`() {
activitiesApi.stubAllocationReconciliation(
"BXI",
"""
{
"prisonCode": "BXI",
"bookings": [
{
"bookingId": 1234,
"count": 2
},
{
"bookingId": 1235,
"count": 1
}
]
}
""".trimIndent(),
)
}
@Test
fun `should call API with auth token`() = runTest {
activitiesApiService.getAllocationReconciliation("BXI")
activitiesApi.verify(
getRequestedFor(urlEqualTo("/synchronisation/reconciliation/allocations/BXI"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `should parse return data`() = runTest {
val response = activitiesApiService.getAllocationReconciliation("BXI")
with(response) {
assertThat(prisonCode).isEqualTo("BXI")
assertThat(bookings[0].bookingId).isEqualTo(1234)
assertThat(bookings[0].count).isEqualTo(2)
assertThat(bookings[1].bookingId).isEqualTo(1235)
assertThat(bookings[1].count).isEqualTo(1)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubAllocationReconciliationWithError("BXI", status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getAllocationReconciliation("BXI")
}
}
}
@Nested
inner class AttendanceReconciliation {
@BeforeEach
fun `stub attendance reconciliation`() {
activitiesApi.stubAttendanceReconciliation(
"BXI",
LocalDate.now(),
"""
{
"prisonCode": "BXI",
"date": "${LocalDate.now()}",
"bookings": [
{
"bookingId": 1234,
"count": 2
},
{
"bookingId": 1235,
"count": 1
}
]
}
""".trimIndent(),
)
}
@Test
fun `should call API with auth token`() = runTest {
activitiesApiService.getAttendanceReconciliation("BXI", LocalDate.now())
activitiesApi.verify(
getRequestedFor(urlEqualTo("/synchronisation/reconciliation/attendances/BXI?date=${LocalDate.now()}"))
.withHeader("Authorization", equalTo("Bearer ABCDE")),
)
}
@Test
fun `should parse return data`() = runTest {
val response = activitiesApiService.getAttendanceReconciliation("BXI", LocalDate.now())
with(response) {
assertThat(prisonCode).isEqualTo("BXI")
assertThat(date).isEqualTo("${LocalDate.now()}")
assertThat(bookings[0].bookingId).isEqualTo(1234)
assertThat(bookings[0].count).isEqualTo(2)
assertThat(bookings[1].bookingId).isEqualTo(1235)
assertThat(bookings[1].count).isEqualTo(1)
}
}
@Test
fun `when any bad response is received an exception is thrown`() = runTest {
activitiesApi.stubAttendanceReconciliationWithError("BXI", LocalDate.now(), status = 503)
assertThrows<ServiceUnavailable> {
activitiesApiService.getAttendanceReconciliation("BXI", LocalDate.now())
}
}
}
}
| 1 | Kotlin | 0 | 2 | e45536fb628694160e9ce7ac052b2e9053da65b2 | 29,947 | hmpps-prisoner-to-nomis-update | MIT License |
library/src/main/java/com/wahidabd/library/utils/rx/operators/ApiErrorOperators.kt | wahidabd | 609,474,062 | false | null | package com.wahidabd.library.utils.rx.operators
import com.wahidabd.library.data.libs.UnsuccessfulResponseHandler
import com.wahidabd.library.data.model.ApiError
import com.wahidabd.library.utils.exception.ApiException
import retrofit2.Response
/**
* Created by Wahid on 3/13/2023.
* Github wahidabd.
*/
fun <T : Any> getObservableApiError(): ObservableApiErrorOperator<T, ApiError> =
ObservableApiErrorOperator(
errorClazz = ApiError::class.java,
mapObject = {it.toApiError()}
)
fun <T: Any> getSingleApiError(): SingleApiErrorOperator<T, ApiError> =
SingleApiErrorOperator(
errorClazz = ApiError::class.java,
mapObject = {it.toApiError()}
)
fun <T: Any> getFlowableApiError(): FlowableApiErrorOperator<T, ApiError> =
FlowableApiErrorOperator(
errorClazz = ApiError::class.java,
mapObject = {it.toApiError()}
)
fun ApiError.toApiError(): ApiError =
ApiError(statusCode, message, errorCode)
fun <T, R> handleErrorResponseToApiException(
response: Response<T>,
errorClazz: Class<R>?,
mabObject: ((R) -> ApiError)?,
) : ApiException {
val errorBody = response.errorBody()
val errorResponse = errorBody?.toString()
val apiException: ApiException = if (errorClazz == null && mabObject == null){
UnsuccessfulResponseHandler.INSTANCE.getApiError(errorResponse.toString(), response)
}else{
if (errorClazz == null){
throw IllegalArgumentException("errorClazz can not be null")
}
if (mabObject == null){
throw IllegalArgumentException("mapObject can not be null")
}
val parsing = UnsuccessfulResponseHandler.INSTANCE.parseCustomApiErrorResponse(errorResponse.toString(), errorClazz)
ApiException(mabObject.invoke(parsing), response)
}
return apiException
} | 1 | Kotlin | 0 | 0 | 9f1a38df839fa2705bea5682552d293c77dd0d4a | 1,856 | one-library | MIT License |
api/shops/src/main/kotlin/org/rsmod/api/shops/restock/ShopRestockProcess.kt | rsmod | 293,875,986 | false | {"Kotlin": 1969385} | package org.rsmod.api.shops.restock
import com.github.michaelbull.logging.InlineLogger
import jakarta.inject.Inject
import org.rsmod.api.utils.format.formatAmount
import org.rsmod.game.MapClock
import org.rsmod.game.inv.Inventory
public class ShopRestockProcess @Inject constructor(private val mapClock: MapClock) {
public val modifiedShops: MutableSet<Inventory> = hashSetOf()
private val restockedShops: MutableSet<Inventory> = hashSetOf()
private val logger = InlineLogger()
public operator fun plusAssign(inventory: Inventory) {
modifiedShops += inventory
}
public fun process() {
processModifiedShops()
removeRestockedShops()
}
private fun processModifiedShops() {
for (shop in modifiedShops) {
val fullyRestocked = shop.restoreInitialStock()
if (fullyRestocked) {
restockedShops += shop
}
}
}
private fun Inventory.restoreInitialStock(): Boolean {
var fullyRestocked = true
val stock = type.stock
for (i in indices) {
val obj = this[i] ?: continue
val stockObj = stock?.getOrNull(i)
val initialStock = stockObj?.count ?: 0
if (obj.count == initialStock) {
continue
}
val restockRate = stockObj?.restockCycles ?: NON_STOCK_NORMALIZE_CYCLES
if (mapClock % restockRate != 0) {
fullyRestocked = false
continue
}
val newCount = if (obj.count > initialStock) obj.count - 1 else obj.count + 1
val deleteObj = newCount == 0 && stockObj == null
if (deleteObj) {
this[i] = null
} else {
this[i] = obj.copy(count = newCount)
}
if (newCount != initialStock) {
fullyRestocked = false
}
}
return fullyRestocked
}
private fun removeRestockedShops() {
if (restockedShops.isNotEmpty()) {
val neutralizeCount = restockedShops.size
modifiedShops.removeAll(restockedShops)
restockedShops.clear()
logClearedRestockedShops(modifiedShops.size, neutralizeCount)
}
}
private fun logClearedRestockedShops(modifiedCount: Int, neutralizeCount: Int) {
if (!logger.isDebugEnabled) {
return
}
val message =
if (modifiedCount == 0) {
"Cleared ${neutralizeCount.formatAmount} modified " +
"shop${if (neutralizeCount == 1) "" else "s"}."
} else {
"Cleared ${neutralizeCount.formatAmount} modified shops. $modifiedCount " +
"active modified shop${if (modifiedCount == 1) "" else "s"} left."
}
logger.debug { message }
}
private companion object {
private const val NON_STOCK_NORMALIZE_CYCLES: Int = 100
}
}
| 0 | Kotlin | 64 | 93 | da10560f220f4a9ff2f034e0879dc69b103465cc | 2,993 | rsmod | ISC License |
fashion-tryon-compose/src/main/kotlin/com/aiuta/fashionsdk/tryon/compose/ui/internal/navigation/NavigationAppBarState.kt | aiuta-com | 759,918,511 | false | {"Kotlin": 467654, "Shell": 562} | package com.aiuta.fashionsdk.tryon.compose.ui.internal.navigation
internal enum class NavigationAppBarState {
EMPTY,
GENERAL,
HISTORY,
}
internal enum class NavigationAppBarActionState {
EMPTY,
SELECT_PHOTOS,
HISTORY,
}
| 0 | Kotlin | 0 | 2 | df7e33c5e2814fb1693d0f3a078a48d3deef4ebd | 250 | android-sdk | Apache License 2.0 |
modules/logging/src/test/kotlin/org/springframework/fu/module/logging/LogbackDslTest.kt | jnizet | 136,587,970 | false | null | /*
* Copyright 2002-2018 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.springframework.fu.module.logging
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.Appender
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.springframework.context.support.GenericApplicationContext
import org.springframework.fu.application
import java.io.File
/**
* @author <NAME>
*/
internal class LogbackDslTest {
private val tmp = System.getProperty("java.io.tmpdir").let(::File)
@Test
fun `Default Logback Configuration`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
application {
logging {
logback = logback { }
}
}.run(context)
assertEquals(false, logback.debug)
assertEquals(Level.INFO, logback.rootLogger.level)
assertEquals(listOf<Appender<ILoggingEvent>>(), logback.appenders)
}
@Test
fun `Debug Logback Configuration`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
application {
logging {
logback = logback {
debug(true)
}
}
}.run(context)
assertEquals(true, logback.debug)
}
@Test
fun `LogbackDsl rootLogger consoleAppender`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
application {
logging {
logback = logback {
consoleAppender()
}
}
}.run(context)
val console = logback.rootLogger.getAppender("STDOUT")
assertEquals(ConsoleAppender::class.java, console::class.java)
assertEquals("STDOUT", console.name)
}
@Test
fun `Logback consoleAppender custom`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
application {
logging {
logback = logback {
consoleAppender(name = "MY_STDOUT")
}
}
}.run(context)
val console = logback.rootLogger.getAppender("MY_STDOUT")
assertEquals(ConsoleAppender::class.java, console::class.java)
assertEquals("MY_STDOUT", console.name)
assertNull(logback.rootLogger.getAppender("STDOUT"))
}
@Test
fun `Logback rollingFileAppender`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
val logFile = File(tmp, "log.txt")
application {
logging {
logback = logback {
rollingFileAppender(logFile)
}
}
}.run(context)
val rolling = logback.rootLogger.getAppender("ROLLING")
assertEquals(RollingFileAppender::class.java, rolling::class.java)
assertEquals("ROLLING", rolling.name)
(rolling as RollingFileAppender).let {
assertTrue(it.isAppend)
(it.rollingPolicy as SizeAndTimeBasedRollingPolicy<*>).let {
assertEquals(logFile.path, it.activeFileName)
assertEquals("log.%d{yyyy-MM-dd}.%i.gz", it.fileNamePattern)
assertEquals(30, it.maxHistory)
}
}
}
@Test
fun `Logback rollingFileAppender custom`() {
lateinit var logback: LogbackDsl
val context = GenericApplicationContext()
val logFile = File(tmp, "mylog.txt")
application {
logging {
logback = logback {
rollingFileAppender(
file = logFile,
name = "MY_ROLLING",
pattern = "%d{yyyy-MM}",
fileNamePattern = "%i.gz",
maxFileSize = "2GB",
maxHistory = 11,
totalSizeCap = "1MB",
append = false
)
}
}
}.run(context)
val rolling = logback.rootLogger.getAppender("MY_ROLLING")
assertEquals(RollingFileAppender::class.java, rolling::class.java)
assertEquals("MY_ROLLING", rolling.name)
assertNull(logback.rootLogger.getAppender("ROLLING"))
(rolling as RollingFileAppender).let {
assertFalse(it.isAppend)
(it.rollingPolicy as SizeAndTimeBasedRollingPolicy<*>).let {
assertEquals(logFile.path, it.activeFileName)
assertEquals("%i.gz", it.fileNamePattern)
assertEquals(11, it.maxHistory)
}
}
}
}
| 0 | null | 0 | 3 | a5e28c413d4e30578d59d235c890fa06ad1f1d30 | 4,556 | spring-fu | Apache License 2.0 |
src/day12/Day12.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 38701} | package day12
import java.io.File
fun main() {
val data = parse("src/day12/Day12.txt")
println("🎄 Day 12 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Row(
val springs: String,
val numbers: List<Int>,
)
private fun String.toRow(): Row {
val (springs, numbers) = this.split(" ")
return Row(springs, numbers.split(",").map(String::toInt))
}
private fun parse(path: String): List<Row> =
File(path)
.readLines()
.map(String::toRow)
private typealias Cache = MutableMap<Pair<String, List<Int>>, Long>
private fun solve(springs: String, numbers: List<Int>, cache: Cache = mutableMapOf()): Long {
if (cache.containsKey(springs to numbers)) {
return cache.getValue(springs to numbers)
}
if (springs.isEmpty()) {
return if (numbers.isEmpty()) 1L else 0L
}
if (numbers.isEmpty()) {
return if (springs.contains('#')) 0L else 1L
}
var count = 0L
if (springs.first() in ".?") {
count += solve(springs.substring(1), numbers, cache)
}
if (springs.first() in "#?") {
val n = numbers.first()
if (springs.length > n) {
val group = springs.substring(0, n)
if (!group.contains('.') && springs[n] != '#') {
count += solve(springs.substring(n + 1), numbers.drop(1), cache)
}
}
if (springs.length == n) {
if (!springs.contains('.')) {
count += solve("", numbers.drop(1), cache)
}
}
}
cache[springs to numbers] = count
return count
}
private fun part1(data: List<Row>): Long =
data.sumOf { (springs, numbers) -> solve(springs, numbers) }
private fun part2(data: List<Row>): Long =
data.sumOf { (springs, numbers) -> solve(
generateSequence { springs }.take(5).toList().joinToString("?"),
generateSequence { numbers }.take(5).toList().flatten())
}
| 0 | Kotlin | 0 | 0 | 74c9854a3e5f9534c05dabbbf4af96d38984c511 | 2,060 | advent-of-code-2023 | MIT License |
Android/App_qixiashan/App/src/main/java/com/zktony/android/ui/upgradeMode.kt | OriginalLight | 556,213,614 | false | {"Kotlin": 6123849, "C#": 376657, "Vue": 164353, "Rust": 101266, "C++": 63250, "TypeScript": 62359, "Python": 28781, "CMake": 18271, "C": 16214, "Less": 2885, "Dockerfile": 1898, "HTML": 648, "JavaScript": 450} | package com.zktony.android.ui
import android.content.Context
import android.graphics.Color.rgb
import android.os.Build
import android.os.storage.StorageManager
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.paging.compose.LazyPagingItems
import com.zktony.android.R
import com.zktony.android.data.entities.SportsLog
import com.zktony.android.ui.brogressbar.HorizontalProgressBar
import com.zktony.android.ui.components.TableTextBody
import com.zktony.android.ui.components.TableTextHead
import com.zktony.android.ui.navigation.Route
import com.zktony.android.ui.utils.PageType
import com.zktony.android.ui.utils.getStoragePath
import com.zktony.android.ui.utils.itemsIndexed
import com.zktony.android.ui.utils.line
import com.zktony.android.utils.extra.UpgradeState
import com.zktony.android.utils.extra.dateFormat
import com.zktony.android.utils.extra.embeddedUpgrade
import com.zktony.android.utils.extra.embeddedVersion
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.lang.reflect.Method
import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.math.ceil
/**
* 上下位机升级
*/
@OptIn(
ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class,
ExperimentalLayoutApi::class
)
@Composable
fun upgradeMode(
uiEvent: (SettingIntent) -> Unit,
uiEventHome: (HomeIntent) -> Unit,
updateMsg: String
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
/**
* 主控板升级弹窗
*/
val masterDialog = remember { mutableStateOf(false) }
val stateDialog = remember { mutableStateOf(false) }
val apkDialog = remember { mutableStateOf(false) }
var text by remember { mutableStateOf("") }
var showButton by remember { mutableStateOf(true) }
/**
* bin文件列表
*/
var masterList by remember { mutableStateOf(emptyList<File>()) }
var stateList by remember { mutableStateOf(emptyList<File>()) }
var apkList by remember { mutableStateOf(emptyList<File>()) }
LaunchedEffect(text) {
if (text.contains("成功")) {
uiEventHome(HomeIntent.WaitTimeRinse)
uiEventHome(HomeIntent.Heartbeat)
text = ""
masterDialog.value = false
showButton = true
} else if (text.contains("失败") || text.contains("超时") || text.contains("未知")) {
showButton = true
text = ""
}
}
Column(
modifier = Modifier
.padding(start = 26.dp, top = 13.75.dp)
.clip(RoundedCornerShape(10.dp))
.background(Color.White)
.height(1000.dp)
.width(540.dp)
) {
Row(
modifier = Modifier
.padding(top = 20.dp)
) {
Icon(
modifier = Modifier
.padding(start = 25.dp)
.size(30.dp)
.clickable {
uiEvent(SettingIntent.NavTo(PageType.SETTINGS))
},
painter = painterResource(id = R.mipmap.greenarrow),
contentDescription = null
)
Text(
modifier = Modifier.padding(start = 150.dp),
text = "系统更新",
fontSize = 20.sp,
color = Color(rgb(112, 112, 112))
)
}
Row(
modifier = Modifier
.padding(top = 100.dp, start = 150.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.mipmap.android_update),
contentDescription = null,
modifier = Modifier
.size(200.dp)
.clickable {
scope.launch {
var path = getStoragePath(context, true)
if (!"".equals(path)) {
path += "/zktony/apk"
apkList =
File(path)
.listFiles { _, name -> name.endsWith(".apk") }
?.toList() ?: emptyList()
if (apkList.isNotEmpty()) {
apkDialog.value = true
} else {
Toast
.makeText(
context,
"没有更新文件!",
Toast.LENGTH_SHORT
)
.show()
}
} else {
Toast
.makeText(
context,
"U盘不存在!",
Toast.LENGTH_SHORT
)
.show()
}
}
}
)
}
}
Row(
modifier = Modifier
.padding(top = 100.dp)
.fillMaxWidth()
) {
line(Color(0, 105, 5), 5f, 530f)
}
Row {
Column(
modifier = Modifier
.padding(top = 100.dp, start = 50.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.mipmap.master_update),
contentDescription = null,
modifier = Modifier
.size(200.dp)
.clickable {
scope.launch {
var path = getStoragePath(context, true)
if (!"".equals(path)) {
path += "/zktony/apk/master"
masterList =
File(path)
.listFiles { _, name -> name.endsWith(".bin") }
?.toList() ?: emptyList()
if (masterList.isNotEmpty()) {
masterDialog.value = true
} else {
Toast
.makeText(
context,
"没有更新文件!",
Toast.LENGTH_SHORT
)
.show()
}
} else {
Toast
.makeText(
context,
"U盘不存在!",
Toast.LENGTH_SHORT
)
.show()
}
}
}
)
}
Column(
modifier = Modifier
.padding(top = 100.dp, start = 80.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.mipmap.state_update),
contentDescription = null,
modifier = Modifier
.size(200.dp)
.clickable {
scope.launch {
var path = getStoragePath(context, true)
if (!"".equals(path)) {
path += "/zktony/apk/state"
stateList =
File(path)
.listFiles { _, name -> name.endsWith(".bin") }
?.toList() ?: emptyList()
if (stateList.isNotEmpty()) {
stateDialog.value = true
} else {
Toast
.makeText(
context,
"没有更新文件!",
Toast.LENGTH_SHORT
)
.show()
}
} else {
Toast
.makeText(
context,
"U盘不存在!",
Toast.LENGTH_SHORT
)
.show()
}
}
}
)
}
}
// Text(text = ver, style = MaterialTheme.typography.displaySmall)
// Button(onClick = {
// scope.launch {
// ver = embeddedVersion()
// }
// }) {
// Text(text = "查询版本")
// }
}
if (masterDialog.value) {
Dialog(onDismissRequest = {
}) {
ElevatedCard {
var selectedFile by remember { mutableStateOf<File?>(null) }
Column(
modifier = Modifier
.padding(30.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(masterList) { file ->
FileItem(file, selectedFile) {
selectedFile = it
}
}
item {
if (showButton) {
Column {
Row {
Button(
modifier = Modifier
.width(100.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color(rgb(0, 105, 52))
),
onClick = {
scope.launch {
if (selectedFile != null) {
showButton = false
uiEventHome(HomeIntent.StopWaitTimeRinse)
uiEventHome(HomeIntent.StopHeartbeat)
delay(200)
embeddedUpgrade(
selectedFile!!,
"master",
"zkty"
).collect {
text = when (it) {
is UpgradeState.Message -> it.message
is UpgradeState.Success -> "升级成功"
is UpgradeState.Err -> "${it.t.message}"
is UpgradeState.Progress -> "升级中 ${
String.format(
"%.2f",
it.progress * 100
)
} %"
}
}
} else {
Toast.makeText(
context,
"未选择更新程序!",
Toast.LENGTH_SHORT
).show()
}
}
}) {
Text(fontSize = 18.sp, text = "确 认")
}
Button(
modifier = Modifier
.padding(start = 250.dp)
.width(100.dp),
border = BorderStroke(1.dp, Color.Gray),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent
),
onClick = {
masterDialog.value = false
}) {
Text(fontSize = 18.sp, text = "取 消", color = Color.Black)
}
}
Row(modifier = Modifier.padding(top = 10.dp, start = 180.dp)) {
Text(text = "升级中请勿关机!", fontSize = 18.sp)
}
}
} else {
Row {
Text(text = text, style = MaterialTheme.typography.displaySmall)
}
}
}
}
}
}
}
}
if (stateDialog.value) {
Dialog(onDismissRequest = {
}) {
ElevatedCard {
var selectedFile by remember { mutableStateOf<File?>(null) }
Column(
modifier = Modifier
.padding(30.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(stateList) { file ->
FileItem(file, selectedFile) {
selectedFile = it
}
}
item {
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
Button(
modifier = Modifier
.width(100.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color(rgb(0, 105, 52))
),
onClick = {
scope.launch {
if (selectedFile != null) {
embeddedUpgrade(
selectedFile!!,
"state",
"led"
).collect {
text = when (it) {
is UpgradeState.Message -> it.message
is UpgradeState.Success -> "升级成功"
is UpgradeState.Err -> "${it.t.message}"
is UpgradeState.Progress -> "升级中 ${
String.format(
"%.2f",
it.progress * 100
)
} %"
}
Toast.makeText(
context,
text,
Toast.LENGTH_SHORT
).show()
if (text == "升级成功") {
stateDialog.value = false
}
}
} else {
Toast.makeText(
context,
"未选择更新程序!",
Toast.LENGTH_SHORT
).show()
}
}
}) {
Text(fontSize = 18.sp, text = "确 认")
}
Button(
modifier = Modifier
.padding(start = 250.dp)
.width(100.dp),
border = BorderStroke(1.dp, Color.Gray),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent
),
onClick = {
stateDialog.value = false
}) {
Text(fontSize = 18.sp, text = "取 消", color = Color.Black)
}
}
}
}
}
}
}
}
if (apkDialog.value) {
Dialog(onDismissRequest = {
}) {
ElevatedCard {
var selectedFile by remember { mutableStateOf<File?>(null) }
Column(
modifier = Modifier
.padding(30.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(apkList) { file ->
FileItem(file, selectedFile) {
selectedFile = it
}
}
item {
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
Button(
modifier = Modifier
.width(100.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color(rgb(0, 105, 52))
),
onClick = {
scope.launch {
if (selectedFile != null) {
uiEvent(
SettingIntent.UpdateApkU(
context,
selectedFile!!.path
)
)
if (updateMsg.isNotEmpty()) {
Toast.makeText(
context,
updateMsg,
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(
context,
"未选择更新程序!",
Toast.LENGTH_SHORT
).show()
}
}
}) {
Text(fontSize = 18.sp, text = "确 认")
}
Button(
modifier = Modifier
.padding(start = 250.dp)
.width(100.dp),
border = BorderStroke(1.dp, Color.Gray),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent
),
onClick = {
apkDialog.value = false
}) {
Text(fontSize = 18.sp, text = "取 消", color = Color.Black)
}
}
}
}
}
}
}
}
}
@Composable
fun FileItem(
file: File,
selectedFile: File?,
onFileClick: (File) -> Unit
) {
val isSelected = file == selectedFile
Card(
modifier = Modifier
.fillMaxWidth()
.clickable { onFileClick(file) }
.padding(vertical = 4.dp),
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
text = "Name: ${file.name}",
color = if (isSelected) Color.Red else Color.Black
)
}
}
} | 0 | Kotlin | 0 | 1 | bcf0671b9e4ad199e579764f29683c1c575369d2 | 28,120 | ZkTony | Apache License 2.0 |
app/src/main/java/com/harshalv/jetpackcompose/model/MockData.kt | harshalkvibhandik | 737,453,397 | false | {"Kotlin": 55814} | package com.harshalv.jetpackcompose.model
import android.icu.text.SimpleDateFormat
import android.util.Log
import com.harshalv.jetpackcompose.R
import java.util.Calendar
import java.util.Date
import java.util.Locale
object MockData {
val topNewsList = listOf<NewsData>(
NewsData(
1,
author = "Raja Razek, CNN",
title = "'Tiger King' Joe Exotic says he has been diagnosed with aggressive form of prostate cancer - CNN",
description = "Joseph Maldonado, known as Joe Exotic on the 2020 Netflix docuseries \\\"Tiger King: Murder, Mayhem and Madness,\\\" has been diagnosed with an aggressive form of prostate cancer, according to a letter written by Maldonado.",
publishedAt = "2021-11-04T05:35:21Z"
),
NewsData(
2,
R.drawable.namita,
author = "Namita Singh",
title = "Cleo Smith news — live: Kidnap suspect 'in hospital again' as 'hard police grind' credited for breakthrough - The Independent",
description = "The suspected kidnapper of four-year-old Cleo Smith has been treated in hospital for a second time amid reports he was “attacked” while in custody.",
publishedAt = "2021-11-07T04:42:40Z"
),
NewsData(
3,
R.drawable.reuters,
author = "Not available",
title = "'You are not alone': EU Parliament delegation tells Taiwan on first official visit - Reuters",
description =
"The European Parliament's first official delegation to Taiwan said on Thursday the diplomatically isolated island is not alone and called for bolder actions to strengthen EU-Taiwan ties as Taipei faces rising pressure from Beijing.",
publishedAt = "2021-11-04T03:37:00Z"
),
NewsData(
4,
R.drawable.michael,
author = "Mike Florio",
title = "Aaron Rodgers violated COVID protocol by doing maskless indoor press conferences - NBC Sports",
description = "Packers quarterback Aaron Rodgers has been conducting in-person press conferences in the Green Bay facility without wearing a mask. Because he was secretly unvaccinated, Rodgers violated the rules.",
publishedAt = "2021-11-04T03:21:00Z"
),
NewsData(
5,
R.drawable.grant,
author = "Grant Brisbee",
title = "Buster Posey's career was like no other in Giants history - The Athletic",
description = "There was a franchise without Buster Posey, and there was one with him, and those two franchises were radically, impossibly different.",
publishedAt = "2021-11-04T02:12:54Z"
),
NewsData(
6,
author = "Michael Schneider",
title = "‘The Masked Singer’ Reveals Identity of the Beach Ball: Here Are the Stars Under the Mask - Variety",
description = "SPOILER ALERT: Do not read ahead if you have not watched “The Masked Singer” Season 6, Episode 8, “Giving Thanks,” which aired November 3 on Fox. Honey Boo Boo, we hardly knew you. Reality TV mother and daughter stars June Edith “Mama June” Shannon and Alana …",
publishedAt = "2021-11-04T02:00:00Z"
),
NewsData(
7,
R.drawable.thomas,
author = "Thomas Barrabi",
title = "Sen. Murkowski slams Dems over 'show votes' on federal election bills - Fox News",
description = "Sen. Lisa Murkowski, R-Alaska, slammed Senate Democrats for pursuing “show votes” on federal election bills on Wednesday as Republicans used the filibuster to block consideration the John Lewis Voting Rights Advancement Act.",
publishedAt = "2021-11-04T01:57:36Z"
),
NewsData(
8,
author = "CBSBoston.com Staff",
title = "Principal Beaten Unconscious At Dorchester School; Classes Canceled Thursday - CBS Boston",
description = "Principal Patricia Lampron and another employee were assaulted at Henderson Upper Campus during dismissal on Wednesday.",
publishedAt = "2021-11-04T01:55:00Z"
)
)
fun Date.getTimeAgo(): String {
val calendar = Calendar.getInstance()
calendar.time = this
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val currentCalendar = Calendar.getInstance()
val currentYear = currentCalendar.get(Calendar.YEAR)
val currentMonth = currentCalendar.get(Calendar.MONTH)
val currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH)
val currentHour = currentCalendar.get(Calendar.HOUR_OF_DAY)
val currentMinute = currentCalendar.get(Calendar.MINUTE)
return if (year < currentYear) {
val interval = currentYear - year
if (interval == 1) "$interval year ago" else "$interval years ago"
} else if (month < currentMonth) {
val interval = currentMonth - month
if (interval == 1) "$interval month ago" else "$interval months ago"
} else if (day < currentDay) {
val interval = currentDay - day
if (interval == 1) "$interval day ago" else "$interval days ago"
} else if (hour < currentHour) {
val interval = currentHour - hour
if (interval == 1) "$interval hour ago" else "$interval hours ago"
} else if (minute < currentMinute) {
val interval = currentMinute - minute
if (interval == 1) "$interval minute ago" else "$interval minutes ago"
} else {
"a moment ago"
}
}
fun stringToDate(publishedAt: String): Date {
val date = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssxx", Locale.ENGLISH).parse(publishedAt)
Log.d("published", "$date")
return date
}
} | 0 | Kotlin | 0 | 0 | 27118a34fc5fccf6672a7ade14b389c58ab683bf | 6,083 | Android_Jetpack_Compose_Learning | MIT License |
app/src/main/java/com/example/mrakopediareader/api/Queue.kt | pokatomnik | 280,012,339 | false | {"Kotlin": 96333, "Java": 1116} | package com.example.mrakopediareader.api
import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.RetryPolicy
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import io.reactivex.rxjava3.core.Observable
import org.json.JSONArray
import org.json.JSONObject
class Queue(context: Context) {
private val requestQueue: RequestQueue = Volley.newRequestQueue(context)
private val retryPolicy: RetryPolicy = MRRetryPolicy()
private fun queueRequest(request: JsonArrayRequest) {
request.retryPolicy = retryPolicy
requestQueue.add(request)
}
private fun queueRequest(request: JsonObjectRequest) {
request.retryPolicy = retryPolicy
requestQueue.add(request)
}
fun jsonObjectRequestGET(url: String): Observable<JSONObject> {
return Observable.create { resolver ->
val request = JsonObjectRequest(
Request.Method.GET,
url,
null,
{ resolver.onNext(it); resolver.onComplete() },
{ resolver.onError(it); resolver.onComplete() }
)
queueRequest(request)
}
}
fun jsonArrayRequestGET(
url: String
): Observable<JSONArray> {
return Observable.create {
resolver ->
val request = JsonArrayRequest(
Request.Method.GET,
url,
null,
{ resolver.onNext(it); resolver.onComplete() },
{ resolver.onError(it); resolver.onComplete() }
)
queueRequest(request)
}
}
} | 2 | Kotlin | 1 | 1 | c805ac4e25a6e1b4945918286d3faf292245ef7e | 1,799 | mrakopedia-reader | MIT License |
loader/src/main/java/com/pyamsoft/pydroid/loader/glide/GlideLoader.kt | pyamsoft | 48,562,480 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.loader.glide
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.CheckResult
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.pyamsoft.pydroid.loader.GenericLoader
import com.pyamsoft.pydroid.loader.ImageTarget
import com.pyamsoft.pydroid.loader.Loaded
@Deprecated("Use Coil-Compose in Jetpack Compose UI")
internal abstract class GlideLoader<T : Any> protected constructor(protected val context: Context) :
GenericLoader<T>() {
@CheckResult protected abstract fun createRequest(request: RequestManager): RequestBuilder<T>
final override fun into(imageView: ImageView): Loaded {
return glideLoad(
object : CustomViewTarget<ImageView, T>(imageView) {
override fun onResourceCleared(placeholder: Drawable?) {
imageView.setImageDrawable(null)
}
override fun onLoadFailed(errorDrawable: Drawable?) {
imageView.setImageDrawable(null)
notifyError()
}
override fun onResourceLoading(placeholder: Drawable?) {
notifyLoading()
}
override fun onResourceReady(resource: T, transition: Transition<in T>?) {
val mutated: T = executeMutator(mutateImage(resource))
setImage(imageView, mutated)
notifySuccess(mutated)
}
})
}
final override fun into(target: ImageTarget<T>): Loaded {
return glideLoad(
object : CustomTarget<T>() {
override fun onLoadCleared(placeholder: Drawable?) {
target.clear()
}
override fun onLoadFailed(errorDrawable: Drawable?) {
target.clear()
notifyError()
}
override fun onLoadStarted(placeholder: Drawable?) {
notifyLoading()
}
override fun onResourceReady(resource: T, transition: Transition<in T>?) {
val mutated: T = executeMutator(mutateImage(resource))
target.setImage(mutated)
notifySuccess(mutated)
}
})
}
@CheckResult
private fun glideLoad(target: Target<T>): Loaded {
val manager = Glide.with(context.applicationContext)
createRequest(manager).into(target)
return GlideLoaded(manager, target)
}
}
| 0 | null | 3 | 6 | 969fa1c129149f7f2bba06b3d072f3368faa8ba7 | 3,224 | pydroid | Apache License 2.0 |
sudoklify-tokenizer/src/commonTest/kotlin/dev/teogor/sudoklify/tokenizer/JEncodedCellTest.kt | teogor | 656,370,747 | false | {"Kotlin": 298485, "Shell": 404} | /*
* Copyright 2024 Teogor (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.teogor.sudoklify.tokenizer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class JEncodedCellTest {
@Test
fun testToInt_whenSingleDigit_thenCorrectInteger() {
val encodedCell = JEncodedCell("E")
val intValue = encodedCell.toInt()
assertEquals(5, intValue, "Expected 5 but got $intValue")
}
@Test
fun testToInt_whenMultiDigit_thenCorrectInteger() {
val encodedCell = JEncodedCell("Aj")
val intValue = encodedCell.toInt()
assertEquals(10, intValue, "Expected 10 but got $intValue")
}
@Test
fun testToInt_whenZero_thenCorrectInteger() {
val encodedCell = JEncodedCell("-")
val intValue = encodedCell.toInt()
assertEquals(0, intValue, "Expected 0 but got $intValue")
}
@Test
fun testToJEncodedCell_whenSingleDigit_thenCorrectEncodedCell() {
val intValue = 5
val encodedCell = intValue.toJEncodedCell()
assertEquals(JEncodedCell("E"), encodedCell, "Expected 'E' but got ${encodedCell.value}")
}
@Test
fun testToJEncodedCell_whenMultiDigit_thenCorrectEncodedCell() {
val intValue = 10
val encodedCell = intValue.toJEncodedCell()
assertEquals(JEncodedCell("Aj"), encodedCell, "Expected 'Aj' but got ${encodedCell.value}")
}
@Test
fun testToJEncodedCell_whenZero_thenCorrectEncodedCell() {
val intValue = 0
val encodedCell = intValue.toJEncodedCell()
assertEquals(JEncodedCell("-"), encodedCell, "Expected '-' but got ${encodedCell.value}")
}
@Test
fun testJEncodedCell_whenEqualValues_thenEqual() {
val encodedCell1 = JEncodedCell("E")
val encodedCell2 = JEncodedCell("E")
val encodedCell3 = JEncodedCell("Aj")
assertEquals(encodedCell1, encodedCell2, "Expected $encodedCell1 to equal $encodedCell2")
assertNotEquals(encodedCell1, encodedCell3, "Expected $encodedCell1 to not equal $encodedCell3")
}
@Test
fun testJEncodedCell_whenDifferentValues_thenNotEqual() {
val encodedCell = JEncodedCell("E")
assertEquals("E", encodedCell.toString(), "Expected 'E' but got $encodedCell")
}
}
| 0 | Kotlin | 3 | 13 | 7b7dc5ab246a93bb09f10c9aa167abbae1cfd5bd | 2,689 | sudoklify | Apache License 2.0 |
node/src/integration-test/kotlin/net/corda/node/NodeKeystoreCheckTest.kt | tomtau | 262,343,298 | false | null | package net.corda.node
import net.corda.core.crypto.Crypto
import net.corda.core.internal.div
import net.corda.core.utilities.getOrThrow
import net.corda.node.services.config.configureDevKeyAndTrustStores
import net.corda.nodeapi.internal.crypto.CertificateType
import net.corda.nodeapi.internal.crypto.X509Utilities
import net.corda.testing.core.ALICE_NAME
import net.corda.testing.driver.DriverParameters
import net.corda.testing.driver.driver
import net.corda.testing.internal.stubs.CertificateStoreStubs
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
import javax.security.auth.x500.X500Principal
class NodeKeystoreCheckTest {
@Test
fun `starting node in non-dev mode with no key store`() {
driver(DriverParameters(startNodesInProcess = true, notarySpecs = emptyList())) {
assertThatThrownBy {
startNode(customOverrides = mapOf("devMode" to false)).getOrThrow()
}.hasMessageContaining("One or more keyStores (identity or TLS) or trustStore not found.")
}
}
@Test
fun `node should throw exception if cert path doesn't chain to the trust root`() {
driver(DriverParameters(startNodesInProcess = true, notarySpecs = emptyList())) {
// Create keystores.
val keystorePassword = "<PASSWORD>"
val certificatesDirectory = baseDirectory(ALICE_NAME) / "certificates"
val signingCertStore = CertificateStoreStubs.Signing.withCertificatesDirectory(certificatesDirectory, keystorePassword)
val p2pSslConfig = CertificateStoreStubs.P2P.withCertificatesDirectory(certificatesDirectory, keyStorePassword = keystorePassword, trustStorePassword = keystorePassword)
p2pSslConfig.configureDevKeyAndTrustStores(ALICE_NAME, signingCertStore, certificatesDirectory)
// This should pass with correct keystore.
val node = startNode(
providedName = ALICE_NAME,
customOverrides = mapOf("devMode" to false,
"keyStorePassword" to keystorePassword,
"trustStorePassword" to keystorePassword)
).getOrThrow()
node.stop()
// Fiddle with node keystore.
signingCertStore.get().update {
// Self signed root.
val badRootKeyPair = Crypto.generateKeyPair()
val badRoot = X509Utilities.createSelfSignedCACertificate(X500Principal("O=Bad Root,L=Lodnon,C=GB"), badRootKeyPair)
val nodeCA = getCertificateAndKeyPair(X509Utilities.CORDA_CLIENT_CA)
val badNodeCACert = X509Utilities.createCertificate(CertificateType.NODE_CA, badRoot, badRootKeyPair, ALICE_NAME.x500Principal, nodeCA.keyPair.public)
setPrivateKey(X509Utilities.CORDA_CLIENT_CA, nodeCA.keyPair.private, listOf(badNodeCACert, badRoot))
}
assertThatThrownBy {
startNode(providedName = ALICE_NAME, customOverrides = mapOf("devMode" to false)).getOrThrow()
}.hasMessage("Client CA certificate must chain to the trusted root.")
}
}
}
| 61 | null | 1 | 1 | f524ed9af7027004abfa91c0bd3a31d645ef0b3b | 3,176 | corda | Apache License 2.0 |
modules/core/arrow-core-extensions/src/main/kotlin/arrow/core/extensions/function0.kt | tdelev | 175,006,167 | true | {"Kotlin": 2235102, "CSS": 148033, "JavaScript": 66118, "HTML": 18206, "Java": 4465, "Shell": 3043, "Ruby": 1606} | package arrow.core.extensions
import arrow.core.*
import arrow.core.extensions.eval.monad.monad
import arrow.core.extensions.function0.monad.monad
import arrow.extension
import arrow.typeclasses.*
import arrow.typeclasses.suspended.monad.Fx
@extension
interface Function0Semigroup<A> : Semigroup<Function0<A>> {
fun SA(): Semigroup<A>
override fun Function0<A>.combine(b: Function0<A>): Function0<A> =
{ SA().run { invoke().combine(b.invoke()) } }.k()
}
@extension
interface Function0Monoid<A> : Monoid<Function0<A>>, Function0Semigroup<A> {
fun MA(): Monoid<A>
override fun SA() = MA()
override fun empty(): Function0<A> =
{ MA().run { empty() } }.k()
}
@extension
interface Function0Functor : Functor<ForFunction0> {
override fun <A, B> Function0Of<A>.map(f: (A) -> B): Function0<B> =
fix().map(f)
}
@extension
interface Function0Applicative : Applicative<ForFunction0> {
override fun <A, B> Function0Of<A>.ap(ff: Function0Of<(A) -> B>): Function0<B> =
fix().ap(ff)
override fun <A, B> Function0Of<A>.map(f: (A) -> B): Function0<B> =
fix().map(f)
override fun <A> just(a: A): Function0<A> =
Function0.just(a)
}
@extension
interface Function0Monad : Monad<ForFunction0> {
override fun <A, B> Function0Of<A>.ap(ff: Function0Of<(A) -> B>): Function0<B> =
fix().ap(ff)
override fun <A, B> Function0Of<A>.flatMap(f: (A) -> Function0Of<B>): Function0<B> =
fix().flatMap(f)
override fun <A, B> tailRecM(a: A, f: kotlin.Function1<A, Function0Of<Either<A, B>>>): Function0<B> =
Function0.tailRecM(a, f)
override fun <A, B> Function0Of<A>.map(f: (A) -> B): Function0<B> =
fix().map(f)
override fun <A> just(a: A): Function0<A> =
Function0.just(a)
}
@extension
interface Function0Comonad : Comonad<ForFunction0> {
override fun <A, B> Function0Of<A>.coflatMap(f: (Function0Of<A>) -> B): Function0<B> =
fix().coflatMap(f)
override fun <A> Function0Of<A>.extract(): A =
fix().extract()
override fun <A, B> Function0Of<A>.map(f: (A) -> B): Function0<B> =
fix().map(f)
}
@extension
interface Function0Bimonad : Bimonad<ForFunction0> {
override fun <A, B> Function0Of<A>.ap(ff: Function0Of<(A) -> B>): Function0<B> =
fix().ap(ff)
override fun <A, B> Function0Of<A>.flatMap(f: (A) -> Function0Of<B>): Function0<B> =
fix().flatMap(f)
override fun <A, B> tailRecM(a: A, f: kotlin.Function1<A, Function0Of<Either<A, B>>>): Function0<B> =
Function0.tailRecM(a, f)
override fun <A, B> Function0Of<A>.map(f: (A) -> B): Function0<B> =
fix().map(f)
override fun <A> just(a: A): Function0<A> =
Function0.just(a)
override fun <A, B> Function0Of<A>.coflatMap(f: (Function0Of<A>) -> B): Function0<B> =
fix().coflatMap(f)
override fun <A> Function0Of<A>.extract(): A =
fix().extract()
}
@extension
interface Function0Fx<A> : Fx<ForFunction0> {
override fun monad(): Monad<ForFunction0> = Function0.monad()
} | 0 | Kotlin | 0 | 0 | ce8099d05215a7ead8789b32af3ea9de67c1496f | 2,938 | arrow | Apache License 2.0 |
app/src/main/java/com/github/unborn2016/mykotlindemo/BaseApplication.kt | unborn2016 | 383,642,227 | false | null | package com.github.unborn2016.mykotlindemo
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
/**
* Created by Unborn on 2021/7/7.
*/
class BaseApplication : Application() {
companion object {
const val TOKEN = "123"
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
} | 0 | Kotlin | 0 | 0 | f5b92692740fb2cd7f2f2195ff012bd788867019 | 470 | MyKotlinDemo | Apache License 2.0 |
olm/src/commonMain/kotlin/io/github/matrixkt/olm/Account.kt | Dominaezzz | 205,671,029 | false | null | package io.github.matrixkt.olm
import kotlin.random.Random
/**
* Account class used to create Olm sessions in conjunction with [Session] class.
*
* [Account] provides APIs to retrieve the Olm keys.
*
* Detailed implementation guide is available at [Implementing End-to-End Encryption in Matrix clients](http://matrix.org/docs/guides/e2e_implementation.html).
*/
public expect class Account(random: Random = Random.Default) {
public fun clear()
/**
* Return the identity keys (identity and fingerprint keys) in a dictionary.
* @sample
* {
* "curve25519":"<KEY>",
* "ed25519":"<KEY>"
* }
* @return identity keys dictionary if operation succeeds, null otherwise
*/
public val identityKeys: IdentityKeys
/**
* Return the largest number of "one time keys" this account can store.
* @return the max number of "one time keys", -1 otherwise
*/
public val maxNumberOfOneTimeKeys: Long
/**
* Generate a number of new one time keys.
* If total number of keys stored by this account exceeds [maxNumberOfOneTimeKeys],
* the old keys are discarded.
* The corresponding keys are retrieved by [oneTimeKeys].
* @param numberOfKeys number of keys to generate
*/
public fun generateOneTimeKeys(numberOfKeys: Long, random: Random = Random.Default)
/**
* Return the "one time keys" in a dictionary.
* The number of "one time keys", is specified by [generateOneTimeKeys]
* @sample
* { "curve25519":
* {
* "AAAABQ":"<KEY>",
* "AAAABA":"/<KEY>",
* "AAAAAw":"<KEY>",
* }
* }
* Note: these keys are to be published on the server.
* @return one time keys in string dictionary.
*/
public val oneTimeKeys: OneTimeKeys
/**
* Remove the "one time keys" that the session used from the account.
* @param session session instance
*/
public fun removeOneTimeKeys(session: Session)
/**
* Marks the current set of "one time keys" as being published.
*/
public fun markOneTimeKeysAsPublished()
/**
* Generates a new fallback key. Only one previous fallback key is stored.
*/
public fun generateFallbackKey(random: Random = Random.Default)
/**
* Get fallback key.
*/
public val fallbackKey: OneTimeKeys
/**
* Sign a message with the ed25519 fingerprint key for this account.
*
* The signed message is returned by the method.
* @param message message to sign
* @return the signed message
*/
public fun sign(message: String): String
/**
* Return an account as a bytes buffer.
*
* The account is serialized and encrypted with [key].
*
* @param[key] encryption key
* @return the account as bytes buffer
*/
public fun pickle(key: ByteArray): String
public companion object {
/**
* Loads an account from a pickle.
*
* @see[pickle]
* @param[key] key used to encrypt
* @param[pickle] Base64 pickle
* @exception Exception the exception
*/
public fun unpickle(key: ByteArray, pickle: String): Account
}
}
| 3 | Kotlin | 8 | 28 | 522e067eec51883f4859753c5ad9240a9535544f | 3,226 | matrix-kt | Apache License 2.0 |
legacy/core/src/commonMain/kotlin/atom/Buttons.kt | CLOVIS-AI | 582,955,979 | false | {"Kotlin": 313130, "JavaScript": 1822, "Dockerfile": 1464, "Shell": 556, "HTML": 372, "CSS": 280} | package opensavvy.decouple.core.atom
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import kotlinx.coroutines.CoroutineScope
import opensavvy.decouple.core.UI
import opensavvy.decouple.core.progression.launch
import opensavvy.decouple.core.progression.rememberProgress
import opensavvy.progress.Progress
interface ButtonAttrs {
val onClick: () -> Unit
val role: Buttons.Role
val enabled: Boolean
val loading: Progress
val contrasted: Boolean
val icon: (@Composable () -> Unit)?
val content: (@Composable Buttons.ButtonScope.() -> Unit)
}
interface Buttons {
enum class Role {
Primary,
Secondary,
Action,
Normal,
@Suppress("unused")
@Deprecated("We reserve the right to add more elements in the future.", level = DeprecationLevel.ERROR)
Reserved,
}
/**
* The most common kind of button.
*
* This should be used for low priority actions, especially when there are multiple of them.
*/
@Composable
fun ButtonSpec(attrs: ButtonAttrs)
interface ButtonScope
}
private data class ButtonAttrsImpl(
override val onClick: () -> Unit,
override val role: Buttons.Role,
override val enabled: Boolean,
override val loading: Progress,
override val icon: (@Composable () -> Unit)?,
override val content: @Composable Buttons.ButtonScope.() -> Unit,
override val contrasted: Boolean,
) : ButtonAttrs
@Composable
fun AbstractButton(
onClick: suspend () -> Unit,
enabled: Boolean = true,
scope: CoroutineScope,
icon: (@Composable () -> Unit)? = null,
content: @Composable Buttons.ButtonScope.() -> Unit,
role: Buttons.Role = Buttons.Role.Normal,
contrasted: Boolean = false,
) {
var loading by rememberProgress()
UI.current.ButtonSpec(
ButtonAttrsImpl(
onClick = {
scope.launch(
onProgress = { loading = it },
block = onClick,
)
},
enabled = enabled,
loading = loading,
icon = icon,
content = content,
role = role,
contrasted = contrasted,
)
)
}
/**
* The most common kind of button.
*
* For more information, see [Buttons.ButtonSpec].
*/
@Composable
fun Button(
onClick: suspend () -> Unit,
enabled: Boolean = true,
scope: CoroutineScope = rememberCoroutineScope(),
icon: (@Composable () -> Unit)? = null,
content: @Composable Buttons.ButtonScope.() -> Unit,
) = AbstractButton(
onClick = onClick,
enabled = enabled,
scope = scope,
icon = icon,
content = content,
)
/**
* Important buttons.
*/
@Composable
fun PrimaryButton(
onClick: suspend () -> Unit,
enabled: Boolean = true,
scope: CoroutineScope = rememberCoroutineScope(),
icon: (@Composable () -> Unit)? = null,
content: @Composable Buttons.ButtonScope.() -> Unit,
) = AbstractButton(
onClick = onClick,
enabled = enabled,
scope = scope,
icon = icon,
content = content,
role = Buttons.Role.Primary,
)
@Composable
fun SecondaryButton(
onClick: suspend () -> Unit,
enabled: Boolean = true,
scope: CoroutineScope = rememberCoroutineScope(),
icon: (@Composable () -> Unit)? = null,
content: @Composable Buttons.ButtonScope.() -> Unit,
) = AbstractButton(
onClick = onClick,
enabled = enabled,
scope = scope,
icon = icon,
content = content,
role = Buttons.Role.Secondary,
)
/**
* Medium-emphasis button.
*/
@Composable
fun ActionButton(
onClick: suspend () -> Unit,
enabled: Boolean = true,
icon: (@Composable () -> Unit)? = null,
scope: CoroutineScope = rememberCoroutineScope(),
content: @Composable Buttons.ButtonScope.() -> Unit,
) = AbstractButton(
onClick = onClick,
enabled = enabled,
scope = scope,
icon = icon,
content = content,
role = Buttons.Role.Action,
)
/**
* Button variant used where high contrast is necessary.
*/
@Composable
fun ContrastButton(
onClick: suspend () -> Unit,
enabled: Boolean = true,
scope: CoroutineScope = rememberCoroutineScope(),
icon: (@Composable () -> Unit)? = null,
content: @Composable Buttons.ButtonScope.() -> Unit,
) = AbstractButton(
onClick = onClick,
enabled = enabled,
scope = scope,
icon = icon,
content = content,
contrasted = true,
)
| 0 | Kotlin | 0 | 2 | b97efa62f6c0d5800722001234cf8dd6c2dd6511 | 4,132 | Decouple | Apache License 2.0 |
klock/src/commonMain/kotlin/com/soywiz/klock/wrapped/WDate.kt | korlibs | 108,193,127 | false | null | package com.soywiz.klock.wrapped
import com.soywiz.klock.*
import com.soywiz.klock.annotations.*
import com.soywiz.klock.internal.Serializable
@KlockExperimental
val Date.wrapped get() = WDate(this)
/**
* Wrapped Version, that is not inline. You can use [value] to get the wrapped inline class.
*
* Represents a triple of [year], [month] and [day].
*
* It is packed in an inline class wrapping an Int to prevent allocations.
*/
@KlockExperimental
class WDate(val value: Date) : Comparable<WDate>, Serializable {
companion object {
@Suppress("MayBeConstant", "unused")
private const val serialVersionUID = 1L
/** Constructs a new [WDate] from the [year], [month] and [day] components. */
operator fun invoke(year: Int, month: Int, day: Int) = Date(year, month, day).wrapped
/** Constructs a new [WDate] from the [year], [month] and [day] components. */
operator fun invoke(year: Int, month: WMonth, day: Int) = Date(year, month, day).wrapped
/** Constructs a new [WDate] from the [year], [month] and [day] components. */
operator fun invoke(year: WYear, month: WMonth, day: Int) = Date(year.value, month, day).wrapped
/** Constructs a new [WDate] from the [yearMonth] and [day] components. */
operator fun invoke(yearMonth: WYearMonth, day: Int) = Date(yearMonth.value, day).wrapped
}
/** The [year] part as [Int]. */
val year: Int get() = value.year
/** The [month] part as [Int] where [Month.January] is 1. */
val month1: Int get() = value.month1
/** The [month] part. */
val month: WMonth get() = value.month
/** The [day] part. */
val day: Int get() = value.day
/** The [year] part as [Year]. */
val yearYear: WYear get() = value.yearYear.wrapped
/** A [WDateTime] instance representing this date and time from the beginning of the [day]. */
val dateTimeDayStart get() = value.dateTimeDayStart.wrapped
/** The [dayOfYear] part. */
val dayOfYear get() = value.dayOfYear
/** The [dayOfWeek] part. */
val dayOfWeek get() = value.dayOfWeek
/** The [dayOfWeek] part as [Int]. */
val dayOfWeekInt get() = value.dayOfWeekInt
/** Converts this date to String using [format] for representing it. */
fun format(format: String) = value.format(format)
/** Converts this date to String using [format] for representing it. */
fun format(format: DateFormat) = value.format(format)
override fun compareTo(other: WDate): Int = this.value.compareTo(other.value)
operator fun plus(time: WTimeSpan) = (this.value + time.value).wrapped
operator fun plus(time: WMonthSpan) = (this.value + time.value).wrapped
operator fun plus(time: WDateTimeSpan) = (this.value + time.value).wrapped
operator fun plus(time: WTime) = (this.value + time.value).wrapped
override fun equals(other: Any?): Boolean = (other is WDate) && this.value == other.value
override fun hashCode(): Int = value.hashCode()
/** Converts this date to String formatting it like "2020-01-01", "2020-12-31" or "-2020-12-31" if the [year] is negative */
override fun toString(): String = value.toString()
}
| 19 | Kotlin | 52 | 679 | 9bbef7aca8018d7b64d971a777d03b9bac07686e | 3,177 | klock | Creative Commons Zero v1.0 Universal |
src/rocks/danielw/udemy/chapter3/Equality.kt | DanielW1987 | 193,260,876 | false | null | package rocks.danielw.chapter3
import rocks.danielw.model.Employee
fun main() {
val employee1 = Employee(1, "John", "Doe")
val employee2 = Employee(2, "Jane", "Johnson")
val employee3 = Employee(2, "Jane", "Johnson")
val employee4 = employee1
println(employee1 == employee2) // false => as expected
println(employee2 == employee3) // true => == works like equals in Java
println(employee1 === employee4) // true => use === to check for referential equality
}
| 1 | null | 1 | 1 | 7388d301565de075b4377d3d3ff0d43d9f18fb4b | 481 | kotlin-udemy-course | Apache License 2.0 |
app/src/main/java/alektas/telecomapp/domain/entities/signals/Signal.kt | Alektas | 214,780,544 | false | null | package alektas.telecomapp.domain.entities.signals
interface Signal {
/**
* Возвращает словарь со всеми значения сигнала на всем измеренном временном участке.
* Ключ - время измерения, значение - величина (напряжение/ток/мощность) сигнала в момент времени.
*/
fun getPoints(): Map<Double, Double>
/**
* Возвращает словарь со всеми значения сигнала от <code>from</code> до <code>to</code> на временной шкале.
* Ключ - время измерения, значение - величина (напряжение/ток/мощность) сигнала в момент времени.
*
* @param from от какого момента времени брать значения (включительно), в секундах
* @param to до какого момента времени брать значения (не включительно), в секундах
*/
fun getPoints(from: Double, to: Double): Map<Double, Double>
/**
* Возвращает все моменты времени, на которых измерялись значения сигнала.
*/
fun getTimes(): DoubleArray
/**
* Возвращает моменты времени от <code>from</code> до <code>to</code> на временной шкале,
* на которых измерялись значения сигнала.
*
* @param from от какого момента времени брать значения (включительно), в секундах
* @param to до какого момента времени брать значения (не включительно), в секундах
*/
fun getTimes(from: Double, to: Double): DoubleArray
/**
* Возвращает все значения сигнала на всем измеренном временном участке.
* Значение - величина (напряжение/ток/мощность) сигнала в момент времени.
*/
fun getValues(): DoubleArray
/**
* Возвращает значения сигнала от <code>from</code> до <code>to</code> на временной шкале.
* Значение - величина (напряжение/ток/мощность) сигнала в момент времени.
*
* @param from от какого момента времени брать значения (включительно), в секундах
* @param to до какого момента времени брать значения (не включительно), в секундах
*/
fun getValues(from: Double, to: Double): DoubleArray
/**
* Возвращает значение сигнала во время <code>time</code>.
*
* @param time момент времени, в котором берется значение, в секундах
*/
fun getValueAt(time: Double): Double
/**
* Возвращает отрезок сигнала.
*
* @param from от какого момента времени брать сигнал (включительно), в секундах
* @param to до какого момента времени брать сигнал (не включительно), в секундах
*/
fun getPart(from: Double, to: Double): Signal
/**
* Проверяет, есть ли сигнал
*/
fun isEmpty(): Boolean
operator fun plus(other: Signal): Signal
operator fun minus(other: Signal): Signal
operator fun times(other: Signal): Signal
} | 0 | Kotlin | 0 | 0 | 1e83fbe6daa496f4c4f47d41f404d3e66fb200ff | 2,661 | Telecom-System | Apache License 2.0 |
compiler/testData/codegen/box/hashPMap/manyNumbers.kt | JakeWharton | 99,388,807 | false | null | // TARGET_BACKEND: JVM
// WITH_REFLECT
import java.util.*
import kotlin.reflect.jvm.internal.pcollections.HashPMap
import kotlin.test.*
fun digitSum(number: Int): Int {
var x = number
var ans = 0
while (x != 0) {
ans += x % 10
x /= 10
}
return ans
}
val N = 1000000
fun box(): String {
var map = HashPMap.empty<Int, Any>()!!
for (x in 1..N) {
map = map.plus(x, digitSum(x))!!
}
assertEquals(N, map.size())
// Check in reverse order just in case
for (x in N downTo 1) {
assertTrue(map.containsKey(x), "Not found: $x")
assertEquals(digitSum(x), map[x], "Incorrect value for $x")
}
// Delete in random order
val list = (1..N).toCollection(ArrayList<Int>())
Collections.shuffle(list, Random(42))
for (x in list) {
map = map.minus(x)!!
}
assertEquals(0, map.size())
for (x in 1..N) {
assertFalse(map.containsKey(x), "Incorrectly found: $x")
assertEquals(null, map[x], "Incorrectly found value for $x")
}
return "OK"
}
| 157 | null | 5209 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,077 | kotlin | Apache License 2.0 |
src/main/kotlin/com/github/bjansen/intellij/pebble/editor/PebbleEditorHighlighterProvider.kt | bjansen | 78,885,057 | false | {"Kotlin": 170841, "Java": 36124, "ANTLR": 7881, "HTML": 343} | package com.github.bjansen.intellij.pebble.editor
import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens
import com.github.bjansen.pebble.parser.PebbleLexer
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.util.LayerDescriptor
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter
import com.intellij.openapi.editor.highlighter.EditorHighlighter
import com.intellij.openapi.fileTypes.EditorHighlighterProvider
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
/**
* Allows using Pebble templates inside other file types.
*/
class PebbleEditorHighlighterProvider : EditorHighlighterProvider {
override fun getEditorHighlighter(project: Project?, fileType: FileType,
virtualFile: VirtualFile?, colors: EditorColorsScheme): EditorHighlighter {
return PebbleTemplateHighlighter(project, virtualFile, colors)
}
}
internal class PebbleTemplateHighlighter(project: Project?, virtualFile: VirtualFile?, colors: EditorColorsScheme)
: LayeredLexerEditorHighlighter(PebbleHighlighter(project), colors) {
init {
// highlighter for outer lang
var type: FileType? = null
if (project == null || virtualFile == null) {
type = StdFileTypes.PLAIN_TEXT
} else {
val language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile)
if (language != null) {
type = language.associatedFileType
}
if (type == null) {
type = StdFileTypes.PLAIN_TEXT
}
}
if (type != null) {
val outerHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(type, project, virtualFile)
if (outerHighlighter != null) {
registerLayer(tokens[PebbleLexer.CONTENT], LayerDescriptor(outerHighlighter, ""))
}
}
}
}
| 24 | Kotlin | 8 | 89 | 9c1ce60e93546e186984b8f29bf5ca7c96570627 | 2,247 | pebble-intellij | MIT License |
app/src/main/java/com/padcmyanmar/myapplication/utils/HealthCareConstants.kt | YaminThwe | 140,179,244 | false | {"Kotlin": 15693} | package com.padcmyanmar.myapplication.utils
class HealthCareConstants
{
//static
companion object {
const val ACCESS_TOKEN = "<KEY>"
const val API_BASE="http://padcmyanmar.com/padc-5/mm-healthcare/"
const val GET_NEWS="GetHealthcareInfo.php"
}
} | 0 | Kotlin | 0 | 0 | 723c6c85bc88f0521cfe4872ad4369d4cbe70e23 | 282 | MIUI_FORUM_YMT | MIT License |
test-utils/src/main/kotlin/dev/restate/e2e/utils/ContainerLogger.kt | restatedev | 489,007,488 | false | {"Kotlin": 71921, "TypeScript": 71722, "Java": 63785, "Shell": 2387, "Dockerfile": 413} | // Copyright (c) 2023 - Restate Software, Inc., Restate GmbH
//
// This file is part of the Restate SDK Test suite tool,
// which is released under the MIT license.
//
// You can find a copy of the license in file LICENSE in the root
// directory of this repository or package, or at
// https://github.com/restatedev/sdk-test-suite/blob/main/LICENSE
package dev.restate.sdktesting.infra
import java.io.BufferedWriter
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.function.Consumer
import org.testcontainers.containers.output.OutputFrame
/** Logger to dump to specific files the stdout and stderr of the containers */
internal class ContainerLogger(
private val testReportDirectory: String,
private val loggerName: String
) : Consumer<OutputFrame> {
private var startCount = 0
private var stdoutStream: BufferedWriter? = null
private var stderrStream: BufferedWriter? = null
override fun accept(frame: OutputFrame) {
when (frame.type) {
OutputFrame.OutputType.STDOUT -> {
resolveStdoutStream().write(frame.utf8String)
}
OutputFrame.OutputType.STDERR -> {
resolveStderrStream().write(frame.utf8String)
}
else -> {
stdoutStream?.close()
stderrStream?.close()
stdoutStream = null
stderrStream = null
startCount++
}
}
}
private fun resolveStdoutStream(): BufferedWriter {
if (stdoutStream == null) {
stdoutStream = newStream(testReportDirectory, loggerName, "stdout")
}
return stdoutStream!!
}
private fun resolveStderrStream(): BufferedWriter {
if (stderrStream == null) {
stderrStream = newStream(testReportDirectory, loggerName, "stderr")
}
return stderrStream!!
}
private fun newStream(
testReportDirectory: String,
loggerName: String,
type: String
): BufferedWriter {
val path = Path.of(testReportDirectory, "${loggerName}_${startCount}_${type}.log")
val fileExists = Files.exists(path)
val writer =
Files.newBufferedWriter(
path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)
if (fileExists) {
writer.newLine()
writer.newLine()
}
writer.write("========================= START LOG =========================\n")
return writer
}
}
| 4 | Kotlin | 3 | 3 | 6da138c6afc25b70ce5be7cbb444b178a7f325c9 | 2,384 | e2e | MIT License |
app/src/main/java/org/lineageos/aperture/models/GestureActions.kt | LineageOS | 544,998,745 | false | null | /*
* SPDX-FileCopyrightText: 2023 The LineageOS Project
* SPDX-License-Identifier: Apache-2.0
*/
package com.statix.flash.utils
/**
* Available gesture actions.
*/
enum class GestureActions {
SHUTTER,
ZOOM,
VOLUME,
NOTHING;
}
| 5 | null | 52 | 88 | db5101d1b0f50b92ba557bce6c88e6ce009697a9 | 249 | android_packages_apps_Aperture | Apache License 2.0 |
src/DayXX.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun input(): List<String> {
return readInput("DayXX")
}
private fun part1(input: List<String>): Int {
return input.size
}
private fun part2(input: List<String>): Int {
return input.size
}
fun main() {
measure { part1(input()) }
measure { part2(input()) }
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 288 | advent-of-code-2022 | Apache License 2.0 |
data/src/main/java/com/hackertronix/model/countries/Latest.kt | hackertronix | 249,216,550 | false | null | package com.hackertronix.model.countries
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
@Entity
data class Latest(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@Json(name = "confirmed")
val confirmed: Int = 0,
@Json(name = "deaths")
val deaths: Int = 0,
@Json(name = "recovered")
val recovered: Int = 0
) | 3 | Kotlin | 4 | 3 | 74fc478600a30a2edb5eec3909756d7584a3bafc | 458 | 91-DIVOC | Apache License 2.0 |
app/src/main/java/com/example/petstore/data/network/model/mapper/PetStoreMappers.kt | zillow | 216,824,627 | false | null | package com.example.petstore.data.network.model.mapper
import com.example.petstore.data.network.model.PetNetworkModel
import com.example.petstore.data.network.model.StoreInfoNetworkModel
import com.example.petstore.data.network.model.StorePetNetworkModel
import com.example.petstore.domain.model.PetDomainModel
import com.example.petstore.domain.model.PetStoreDomainModel
fun PetNetworkModel.toDomain() = PetDomainModel(
id = id,
name = name,
age = age,
type = type
)
fun StorePetNetworkModel.toDomain() = PetDomainModel(
id = id,
name = name,
age = age,
type = type
)
fun StoreInfoNetworkModel.toDomain() = PetStoreDomainModel(
phoneNumber = phoneNumber,
address = address,
recentPets = pets.map { it.toDomain() }
) | 0 | Kotlin | 0 | 1 | 723706fe12988de16bfcb9c7a8f3e8e1376c63ce | 764 | openapi-tutorial-android | Apache License 2.0 |
app/src/main/java/com/oguzdogdu/wallieshd/presentation/detail/DetailViewModel.kt | oguzsout | 616,912,430 | false | null | package com.oguzdogdu.wallieshd.presentation.detail
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.oguzdogdu.domain.model.favorites.FavoriteImages
import com.oguzdogdu.domain.repository.DataStore
import com.oguzdogdu.domain.usecase.auth.GetCheckUserAuthStateUseCase
import com.oguzdogdu.domain.usecase.auth.GetCurrentUserInfoUseCase
import com.oguzdogdu.domain.usecase.auth.GetDeleteFavoriteFromFirebaseUseCase
import com.oguzdogdu.domain.usecase.auth.GetFavoritesToFirebaseUseCase
import com.oguzdogdu.domain.usecase.favorites.GetAddFavoritesUseCase
import com.oguzdogdu.domain.usecase.favorites.GetDeleteFromFavoritesUseCase
import com.oguzdogdu.domain.usecase.favorites.GetImageFromFavoritesUseCase
import com.oguzdogdu.domain.usecase.singlephoto.GetPhotoDetailUseCase
import com.oguzdogdu.domain.wrapper.Resource
import com.oguzdogdu.domain.wrapper.onFailure
import com.oguzdogdu.domain.wrapper.onLoading
import com.oguzdogdu.domain.wrapper.onSuccess
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@HiltViewModel
class DetailViewModel @Inject constructor(
private val dataStore: DataStore,
private val getPhotoDetailUseCase: GetPhotoDetailUseCase,
private val getAddFavoritesUseCase: GetAddFavoritesUseCase,
private val getImageFromFavoritesUseCase: GetImageFromFavoritesUseCase,
private val getDeleteFromFavoritesUseCase: GetDeleteFromFavoritesUseCase,
private val getFavoritesToFirebaseUseCase: GetFavoritesToFirebaseUseCase,
private val getDeleteFavoriteFromFirebaseUseCase: GetDeleteFavoriteFromFirebaseUseCase,
private val getCheckUserAuthStateUseCase: GetCheckUserAuthStateUseCase,
private val getCurrentUserInfoUseCase: GetCurrentUserInfoUseCase
) : ViewModel() {
private val _getPhoto = MutableStateFlow<DetailState?>(null)
val photo = _getPhoto.asStateFlow()
private val _toogleState = MutableStateFlow(false)
val toggleState = _toogleState.asStateFlow()
fun handleUIEvent(event: DetailScreenEvent) {
when (event) {
is DetailScreenEvent.GetPhotoDetails -> {
getSinglePhoto(id = event.id)
}
is DetailScreenEvent.AddFavorites -> {
addOrDeleteFavoritesToAnyDatabase(
FavoriteImages(
id = event.photo?.id.orEmpty(),
url = event.photo?.urls.orEmpty(),
profileImage = event.photo?.profileimage.orEmpty(),
portfolioUrl = event.photo?.portfolio.orEmpty(),
name = event.photo?.username.orEmpty(),
isChecked = true
),
DatabaseProcess.ADD.name
)
}
is DetailScreenEvent.DeleteFavorites -> {
addOrDeleteFavoritesToAnyDatabase(
FavoriteImages(
id = event.photo?.id.orEmpty(),
url = event.photo?.urls.orEmpty(),
profileImage = event.photo?.profileimage.orEmpty(),
portfolioUrl = event.photo?.portfolio.orEmpty(),
name = event.photo?.username.orEmpty(),
isChecked = false
),
DatabaseProcess.DELETE.name
)
}
is DetailScreenEvent.GetPhotoFromWhere -> {
checkAuthStatusForShowFavorites(id = event.id)
}
is DetailScreenEvent.SetLoginDialogState -> setUserAuthDialogPresent(event.isShown)
DetailScreenEvent.CheckUserAuth -> checkUserAuthStatus()
}
}
private fun getSinglePhoto(id: String?) {
viewModelScope.launch {
getPhotoDetailUseCase.invoke(id = id).collectLatest { result ->
result.onLoading {
_getPhoto.update { DetailState.Loading }
}
result.onSuccess { photo ->
_getPhoto.update { DetailState.DetailOfPhoto(detail = photo) }
}
result.onFailure { error ->
_getPhoto.update {
DetailState.DetailError(
errorMessage = error
)
}
}
}
}
}
private fun checkUserAuthStatus() {
viewModelScope.launch {
getCheckUserAuthStateUseCase.invoke().collectLatest { status ->
_getPhoto.update { DetailState.UserAuthenticated(status) }
}
}
}
private fun setUserAuthDialogPresent(value: Boolean) = runBlocking {
dataStore.setShowLoginWarningPresent(key = "isShow", value = value)
getUserAuthDialogShown()
}
private fun getUserAuthDialogShown() {
viewModelScope.launch {
dataStore.getLoginWarningPresent("isShow").collect { result ->
_getPhoto.update { DetailState.StateOfLoginDialog(isShown = result) }
}
}
}
private fun checkAuthStatusForShowFavorites(id: String?) {
viewModelScope.launch {
getCheckUserAuthStateUseCase.invoke().collectLatest { status ->
when (status) {
true -> getFavoritesFromFirebase(id)
false -> getFavoritesFromRoom(id)
}
}
}
}
private fun addOrDeleteFavoritesToAnyDatabase(favoriteImage: FavoriteImages, process: String?) {
viewModelScope.launch {
getCheckUserAuthStateUseCase.invoke().collectLatest { status ->
when (status) {
true -> {
when (process) {
DatabaseProcess.ADD.name -> addImagesToFavorites(
favoriteImage,
whichDb = ChooseDB.FIREBASE.name
)
DatabaseProcess.DELETE.name -> deleteImagesToFavorites(
favoriteImage,
whichDb = ChooseDB.FIREBASE.name
)
}
}
false -> {
when (process) {
DatabaseProcess.ADD.name -> {
addImagesToFavorites(
favoriteImage,
whichDb = ChooseDB.ROOM.name
)
}
DatabaseProcess.DELETE.name -> deleteImagesToFavorites(
favoriteImage,
whichDb = ChooseDB.ROOM.name
)
}
}
}
}
}
}
private fun addImagesToFavorites(
favoriteImage: FavoriteImages,
whichDb: String?
) {
viewModelScope.launch(Dispatchers.IO) {
when (whichDb) {
ChooseDB.FIREBASE.name -> getFavoritesToFirebaseUseCase.invoke(
id = favoriteImage.id,
favorite = favoriteImage.url
)
ChooseDB.ROOM.name -> getAddFavoritesUseCase.invoke(favoriteImage)
}
}
}
private fun deleteImagesToFavorites(
favoriteImage: FavoriteImages,
whichDb: String?
) {
viewModelScope.launch(Dispatchers.IO) {
when (whichDb) {
ChooseDB.FIREBASE.name -> {
getDeleteFavoriteFromFirebaseUseCase.invoke(
id = favoriteImage.id,
favorite = favoriteImage.url
)
}
ChooseDB.ROOM.name -> getDeleteFromFavoritesUseCase.invoke(favoriteImage)
}
}
}
private fun getFavoritesFromFirebase(id: String?) {
viewModelScope.launch {
getCurrentUserInfoUseCase.invoke().collectLatest { userDatas ->
when (userDatas) {
is Resource.Success -> {
val containsUrl = userDatas.data?.favorites?.any { favorite ->
favorite?.containsValue(id) == true
}
containsUrl?.let { _toogleState.emit(it) }
_getPhoto.update {
DetailState.FavoriteStateOfPhoto(
favorite = containsUrl == true
)
}
}
is Resource.Error -> {}
is Resource.Loading -> {}
}
}
}
}
private fun getFavoritesFromRoom(id: String?) {
viewModelScope.launch {
getImageFromFavoritesUseCase.invoke().collectLatest { result ->
when (result) {
is Resource.Loading -> {}
is Resource.Error -> {}
is Resource.Success -> {
val matchingFavorite = result.data?.find { it.id == id }
_getPhoto.update {
matchingFavorite?.isChecked?.let { it1 ->
DetailState.FavoriteStateOfPhoto(
favorite = it1
)
}
}
matchingFavorite?.isChecked?.let { _toogleState.emit(it) }
}
}
}
}
}
enum class ChooseDB(name: String) {
FIREBASE("firebase"),
ROOM("room")
}
enum class DatabaseProcess(name: String) {
ADD("add"),
DELETE("delete")
}
}
| 0 | null | 6 | 8 | e6f899f32c4e914fc9e585c28f7d54bfd05398fd | 10,269 | Wallies | MIT License |
app/src/main/java/com/example/sunnyweather/ui/place/PlaceAdapter.kt | qwer2236112382 | 458,119,552 | false | {"Kotlin": 25454} | package com.example.sunnyweather.ui.place
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.example.sunnyweather.logic.model.Place
import com.example.sunnyweather.ui.weather.WeatherActivity
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.coroutines.internal.artificialFrame
class PlaceAdapter(private val fragment: PlaceFragment, private val placeList: List<Place>):
RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
val placeName: TextView = view.findViewById(com.example.sunnyweather.R.id.placeName)
val placeAddress: TextView = view.findViewById(com.example.sunnyweather.R.id.placeAddress)
val placeLng :TextView = view.findViewById(com.example.sunnyweather.R.id.placeLng)
val placeLat : TextView =view.findViewById(com.example.sunnyweather.R.id.placeLat)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(com.example.sunnyweather.R.layout.place_item,parent, false)
val holder = ViewHolder(view)
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
val place = placeList[position]
val activity = fragment.activity
if (activity is WeatherActivity) {
activity.drawerLayout.closeDrawers()
activity.viewModel.locationLng = place.location.lng
activity.viewModel.locationLat = place.location.lat
activity.viewModel.placeName = place.name
activity.refreshWeather()
} else {
val intent = Intent(parent.context, WeatherActivity::class.java).apply {
putExtra("location_lng", place.location.lng)
putExtra("location_lat", place.location.lat)
putExtra("place_name", place.name)
}
fragment.startActivity(intent)
fragment.activity?.finish()
}
fragment.viewModel.savePlace(place)
Log.d("Activity","${fragment.viewModel.getSavedPlace()} is saved")
}
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val place = placeList[position]
holder.placeName.text = place.name
holder.placeAddress.text = place.address
holder.placeLng.text = "lon: " + place.location.lng
holder.placeLat.text = "lat: " + place.location.lat
}
override fun getItemCount() = placeList.size
}
| 0 | Kotlin | 0 | 0 | 24dede2d8b590bae63b063c995fca547e820ead5 | 2,881 | SunnyWeather | Apache License 2.0 |
library/process/src/nativeMain/kotlin/io/matthewnelson/kmp/process/internal/ReadStream.kt | 05nelsonm | 750,560,085 | false | {"Kotlin": 301826, "Java": 262} | /*
* Copyright (c) 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package io.matthewnelson.kmp.process.internal
import io.matthewnelson.kmp.file.IOException
import io.matthewnelson.kmp.process.internal.stdio.StdioDescriptor
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.convert
import kotlinx.cinterop.usePinned
internal actual abstract class ReadStream private constructor(
private val descriptor: StdioDescriptor,
) {
@Throws(IllegalArgumentException::class, IndexOutOfBoundsException::class, IOException::class)
internal actual open fun read(buf: ByteArray, offset: Int, len: Int): Int {
buf.checkBounds(offset, len)
if (descriptor.isClosed) throw IOException("ReadStream is closed")
if (len == 0) return 0
@OptIn(ExperimentalForeignApi::class)
return buf.usePinned { pinned ->
descriptor.withFd(retries = 10, action = { fd ->
platform.posix.read(
fd,
pinned.addressOf(offset),
len.convert(),
).toInt()
}).check()
}
}
@Throws(IOException::class)
internal actual fun read(buf: ByteArray): Int = read(buf, 0, buf.size)
internal companion object {
internal fun of(
pipe: StdioDescriptor.Pipe,
): ReadStream = of(pipe.read)
@Throws(IllegalArgumentException::class)
internal fun of(
descriptor: StdioDescriptor,
): ReadStream {
require(descriptor.canRead) { "StdioDescriptor must be readable" }
return object : ReadStream(descriptor) {}
}
}
}
| 2 | Kotlin | 1 | 25 | ec5e3262c27aa9098eb2c52a9a7275cd2697318b | 2,295 | kmp-process | Apache License 2.0 |
src/main/kotlin/org/cdb/homunculus/components/PasswordEncoder.kt | CodeDrillBrigade | 714,769,385 | false | {"Kotlin": 122651, "Dockerfile": 336} | package org.cdb.homunculus.components
/**
* Functional interface that defines the method to hash a password and verify the hash.
*/
interface PasswordEncoder {
/**
* Hashes a password with a random salt.
*
* @param password the password to hash.
* @return the generated hash.
*/
fun hashAndSaltPassword(password: String): String
/**
* Verifies a plain-text password against a hash.
*
* @param password the plain-text password to verify.
* @param hash the hash to verify against.
* @return true if the hash corresponds to the password, false otherwise
*/
fun checkHash(
password: String,
hash: String,
): Boolean
/**
* @param maybeHashed a [String].
* @return true if [maybeHashed] is a hash string created with this encoder, false otherwise.
*/
fun isHashed(maybeHashed: String): Boolean
}
| 0 | Kotlin | 0 | 0 | 64aa91cd4513b17ace0e3fe833a11f9a715e4712 | 834 | Homunculus | MIT License |
app/src/main/java/com/theone/music/viewmodel/MusicInfoViewModel.kt | Theoneee | 490,112,111 | false | null | package com.theone.music.viewmodel
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.theone.music.data.model.CollectionEvent
import com.theone.music.data.model.Music
import com.theone.music.data.repository.DataRepository
import com.theone.common.callback.databind.BooleanObservableField
import com.theone.common.callback.databind.IntObservableField
import com.theone.common.callback.databind.StringObservableField
import com.theone.music.app.util.CacheUtil
import com.theone.music.data.repository.LrcRepository
import com.theone.mvvm.base.viewmodel.BaseViewModel
import com.theone.mvvm.core.base.viewmodel.BaseRequestViewModel
import kotlinx.coroutines.launch
// ┏┓ ┏┓
//┏┛┻━━━┛┻┓
//┃ ┃
//┃ ━ ┃
//┃ ┳┛ ┗┳ ┃
//┃ ┃
//┃ ┻ ┃
//┃ ┃
//┗━┓ ┏━┛
// ┃ ┃ 神兽保佑
// ┃ ┃ 永无BUG!
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
/**
* @author The one
* @date 2022-01-04 15:26
* @describe TODO
* @email <EMAIL>
* @remark
*/
class MusicInfoViewModel : BaseViewModel() {
/**
* 数据是否成功
* 用于控制界面是否显示
*/
val isSuccess = BooleanObservableField()
/**
* 音乐数据是否设置成功
* 用于控制是否显示回调的音乐播放信息
*/
val isSetSuccess = BooleanObservableField()
val max = IntObservableField()
val progress = IntObservableField()
val name = StringObservableField()
val author = StringObservableField()
val nowTime = StringObservableField("00:00")
val allTime = StringObservableField("00:00")
val isCollection = BooleanObservableField()
val isCollectionEnable = BooleanObservableField()
val isPlaying = BooleanObservableField()
var cover: StringObservableField = StringObservableField()
var link: String = ""
init {
isCollectionEnable.set(CacheUtil.isLogin())
}
fun requestCollection(username: String, url: String) {
isCollection.set(DataRepository.MUSIC_DAO.findCollectionMusics(username, url).isNotEmpty())
}
fun toggleCollection(username: String, collectionEvent: CollectionEvent) {
with(collectionEvent) {
viewModelScope.launch {
DataRepository.MUSIC_DAO.updateCollectionMusic(
username,
music.shareUrl,
if (collection) 1 else 0,
System.currentTimeMillis()
)
}
}
}
fun reset() {
isSuccess.set(false)
isSetSuccess.set(false)
isCollection.set(false)
isCollectionEnable.set(false)
isPlaying.set(false)
max.set(0)
progress.set(0)
nowTime.set("00:00")
allTime.set("00:00")
}
} | 2 | Kotlin | 1 | 17 | f8773f948b20f0a90930ceb6d6c68ad16833f65c | 2,744 | HifiNi | Apache License 2.0 |
test/libs/src/main/java/id/apwdevs/app/libs/util/RecyclerTestAdapter.kt | AlexzPurewoko | 354,045,461 | false | null | package id.apwdevs.app.libs.util
import android.annotation.SuppressLint
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import id.apwdevs.app.data.source.remote.response.MovieItemResponse
import id.apwdevs.app.data.source.remote.response.TvShowItemResponse
class RecyclerTestAdapter<T : Any> : PagingDataAdapter<T, VH<T>>(DiffRecyclerTest()) {
override fun onBindViewHolder(holder: VH<T>, position: Int) {
holder.bind(getItem(position)!!)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH<T> {
return VH(View(parent.context))
}
fun forcePrefetch(position: Int) {
val item = getItem(position)
if (item is TvShowItemResponse) {
Log.d("RESULT", "id: ${item.id}, name: ${item.name}")
}
}
}
class DiffRecyclerTest<T> : DiffUtil.ItemCallback<T>() {
override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
return when (oldItem) {
is MovieItemResponse -> oldItem.id == (newItem as MovieItemResponse).id
is TvShowItemResponse -> oldItem.id == (newItem as TvShowItemResponse).id
else -> false
}
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
return oldItem == newItem
}
}
class VH<T>(view: View) : RecyclerView.ViewHolder(view) {
fun bind(data: T) {}
} | 5 | Kotlin | 0 | 0 | e80db0e7f11c7d24e86e410eae052ce6e10f9d1f | 1,560 | movie_catalogue | MIT License |
imagekit/src/test/java/com/imagekit/android/preprocess/ImageUploadPreprocessorTest.kt | imagekit-developer | 191,357,009 | false | null | package com.imagekit.android.preprocess
import android.app.Application
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import com.imagekit.android.ImageKit
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.io.File
import java.io.FileInputStream
import java.lang.Math.abs
import java.lang.Math.cos
import java.lang.Math.sin
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.PI
@RunWith(RobolectricTestRunner::class)
class ImageUploadPreprocessorTest {
private val urlEndpoint = "https://ik.imagekit.io/demo"
private val testFilePath = "src/test/java/com/imagekit/android/sample-image.jpg"
private lateinit var testBitmap: Bitmap
lateinit var context: Application
@Before
fun setUp() {
context = RuntimeEnvironment.getApplication()
testBitmap = BitmapFactory.decodeFile(testFilePath)
ImageKit.init(
context = context,
urlEndpoint = urlEndpoint
)
}
@After
fun tearDown() {
}
@Test
fun imageDimensionsLimiterTest() {
val limiter = ImageDimensionsLimiter(
maxWidth = 300,
maxHeight = 200
)
val outputBitmap = limiter.process(testBitmap)
kotlin.test.assertEquals(300, outputBitmap.width)
kotlin.test.assertEquals(200, outputBitmap.height)
}
@Test
fun imageCropTest() {
val cropper = ImageCrop(
topLeft = Point(10, 20),
bottomRight = Point(110, 120),
)
val outputBitmap = cropper.process(testBitmap)
for (x in 10..110) {
for (y in 20..120) {
kotlin.test.assertEquals(
expected = testBitmap.getPixel(x, y),
actual = outputBitmap.getPixel(x - 10, y - 20),
message = "Pixel mismatch at Point ($x, $y)"
)
}
}
}
@Test
fun imageRotationTest() {
val rotator = ImageRotation(angle = 60f)
val angleRadians = 60f * PI / 180f
val rotatedWidth = abs((testBitmap.width / 2.0 * cos(angleRadians)) - (testBitmap.height / 2.0 * sin(angleRadians))).toInt() * 2
val rotatedHeight = abs((testBitmap.width / 2.0 * sin(angleRadians)) + (testBitmap.height / 2.0 * cos(angleRadians))).toInt() * 2
val outputBitmap = rotator.process(testBitmap)
assertEquals(rotatedWidth, outputBitmap.width)
assertEquals(rotatedHeight, outputBitmap.height)
}
@Test
fun imageFilePreprocessOutputFormatTest() {
val magicNumbers = mapOf(
0x89.toByte() to "image/png",
0xff.toByte() to "image/jpeg",
)
val preprocessor = ImageUploadPreprocessor.Builder()
.format(Bitmap.CompressFormat.PNG)
.build<File>()
val outputFile = preprocessor.outputFile(File(testFilePath), "output", context)
FileInputStream(outputFile.path).use { inputStream ->
val buffer = ByteArray(1024)
inputStream.read(buffer, 0, buffer.size)
val magicNumber = ByteBuffer.wrap(buffer).order(ByteOrder.BIG_ENDIAN).get(0).toInt() and 0xff
val mimeType = magicNumbers[magicNumber.toByte()]
kotlin.test.assertEquals("image/png", mimeType)
}
}
} | 3 | Kotlin | 3 | 15 | ec89f96c18775670486f10c9ee911a47b7bdf2a6 | 3,516 | imagekit-android | MIT License |
app/src/main/java/me/bytebeats/compose/bitcoin/util/ktx/NetworkStates.kt | bytebeats | 431,009,469 | false | null | package me.bytebeats.compose.bitcoin.util.ktx
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.transform
import me.bytebeats.compose.bitcoin.network.NetworkState
/**
* Created by bytebeats on 2021/11/23 : 17:06
* E-mail: <EMAIL>
* Quote: Peasant. Educated. Worker
*/
fun <T, R> NetworkState<T>.map(transform: (T) -> R): NetworkState<R> {
return when (this) {
is NetworkState.Success -> NetworkState.Success(transform.invoke(data))
is NetworkState.Error -> NetworkState.Error(error)//immutable state, so we create new UiState
is NetworkState.Loading -> NetworkState.Loading
}
}
fun <T> Flow<NetworkState<T>>.doOnSuccess(action: suspend (T) -> Unit): Flow<NetworkState<T>> =
transform { state ->
if (state is NetworkState.Success) {
action.invoke(state.data)
}
return@transform emit(state)
}
fun <T> Flow<NetworkState<T>>.doOnError(action: suspend (Throwable) -> Unit): Flow<NetworkState<T>> =
transform { state ->
if (state is NetworkState.Error) {
action.invoke(state.error)
}
return@transform emit(state)
}
fun <T> Flow<NetworkState<T>>.doOnLoading(action: suspend () -> Unit): Flow<NetworkState<T>> =
transform { state ->
if (state is NetworkState.Loading) {
action.invoke()
}
return@transform emit(state)
}
| 0 | Kotlin | 2 | 3 | 9f10a8c79b4b67785b76a43f9fd54a41773bee73 | 1,402 | compose-bitcoin | MIT License |
src/com/wuyr/google_library_query/NetworkRequstter.kt | GB1025049030 | 264,075,266 | true | {"Kotlin": 8199, "Java": 1812} | @file:Suppress("UNCHECKED_CAST")
package com.wuyr.google_library_query
import com.google.gson.Gson
import java.net.URL
import java.nio.charset.Charset
import javax.net.ssl.HttpsURLConnection
import javax.swing.DefaultListModel
/**
* @author wuyr
* @github https://github.com/wuyr/GoogleLibraryVersionQuerier
* @since 2020-05-05 15:02
*/
const val BASE_URL = "https://wanandroid.com/maven_pom/"
@Throws(java.lang.Exception::class)
fun getAvailableVersions(libraryGroup: String, libraryName: String) = search("$libraryGroup:$libraryName") { dataList ->
dataList.find { it["groupName"] == libraryGroup }?.run {
(this["artifactMap"] as? Map<String, Any>)?.run {
(this[libraryName] as? List<Map<String, Any>>)?.map {
it["version"].toString()
}
}
}
}
fun matchingLibraries(keyword: String) = ArrayList<Pair<String, String>>().apply {
runSafely {
search(keyword) { dataList ->
dataList.map {
(it["artifactMap"] as? Map<String, List<Map<String, Any>>>)?.values?.map { e ->
e.last().run {
this["content"].toString() to this["group"].toString()
}
}
}.forEach { it?.let { addAll(it) } }
}
}
}
@Throws(java.lang.Exception::class)
inline fun <O> search(keyword: String, block: (List<Map<String, Any>>) -> O): O? = (URL(BASE_URL + "search/json?k=$keyword").openConnection() as HttpsURLConnection).run {
if (responseCode == 200) {
val json = inputStream.readBytes().toString(Charset.forName("utf-8"))
((Gson().fromJson(json, Map::class.java)["data"]) as? List<Map<String, Any>>)?.run {
block(this)
}
} else null
}
inline fun <T, R> T.runSafely(block: (T) -> R) = try {
block(this)
} catch (e: Exception) {
e.printStackTrace()
null
}
fun main() {
val libraryGroup = "androidx.recyclerview"
val libraryName = "recyclerview"
println("json: " + getAvailableVersions(libraryGroup, libraryName))
println("matchingLibraries: " + matchingLibraries("recy"))
VersionSelectorDialog.show(DefaultListModel<String>().apply {
getAvailableVersions(libraryGroup, libraryName)?.forEach {
addElement(it)
}
}) {
println(it)
}
} | 0 | null | 0 | 0 | 9194b6280d1e2ba29e858d810b00274d8cded608 | 2,333 | GoogleLibraryVersionQuerier | Apache License 2.0 |
SliderInTableCell/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.*
import javax.swing.*
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
fun makeUI(): Component {
val columnNames = arrayOf("Integer", "Integer", "Boolean")
val data = arrayOf(
arrayOf(50, 50, false),
arrayOf(13, 13, true),
arrayOf(0, 0, false),
arrayOf(20, 20, true),
arrayOf(99, 99, false),
)
val model = object : DefaultTableModel(data, columnNames) {
override fun getColumnClass(column: Int) = getValueAt(0, column).javaClass
override fun isCellEditable(row: Int, column: Int) = column != 0
}
val table = object : JTable(model) {
override fun updateUI() {
super.updateUI()
putClientProperty("terminateEditOnFocusLost", true)
autoCreateRowSorter = true
setRowHeight(26)
getColumnModel().getColumn(1).also {
it.cellRenderer = SliderRenderer()
it.cellEditor = SliderEditor()
}
}
override fun getSelectionBackground() = super.getSelectionBackground()?.brighter()
}
return JPanel(BorderLayout()).also {
it.add(JScrollPane(table))
it.preferredSize = Dimension(320, 240)
}
}
private class SliderRenderer : TableCellRenderer {
private val renderer = JSlider()
override fun getTableCellRendererComponent(
table: JTable,
value: Any?,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int,
): Component {
renderer.background = if (isSelected) table.selectionBackground else table.background
if (value is Int) {
renderer.value = value
}
return renderer
}
}
private class SliderEditor : AbstractCellEditor(), TableCellEditor {
private val renderer = JSlider()
private var prev = 0
init {
renderer.isOpaque = true
renderer.addChangeListener {
(SwingUtilities.getAncestorOfClass(JTable::class.java, renderer) as? JTable)?.also {
val value = renderer.value
if (it.isEditing && value != prev) {
val row = it.convertRowIndexToModel(it.editingRow)
it.model.setValueAt(value, row, 0)
it.model.setValueAt(value, row, 1)
prev = value
}
}
}
}
override fun getTableCellEditorComponent(
table: JTable,
value: Any?,
isSelected: Boolean,
row: Int,
column: Int,
): Component {
if (value is Int) {
renderer.value = value
}
renderer.background = table.selectionBackground
return renderer
}
override fun getCellEditorValue() = renderer.value
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 5 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 2,984 | kotlin-swing-tips | MIT License |
src/main/kotlin/Config.kt | sambady | 213,947,783 | false | null | package DuckyLuckTgBot
import com.natpryce.konfig.*
import java.io.File
object Config : Configuration {
override fun <T> getOrNull(key: Key<T>): T? = config.getOrNull(key)
override fun list(): List<Pair<Location, Map<String, String>>> = config.list()
override fun locationOf(key: Key<*>): PropertyLocation? = config.locationOf(key)
override fun searchPath(key: Key<*>): List<PropertyLocation> = config.searchPath(key)
lateinit var config : Configuration
val bot_key = Key("bot.key", stringType)
val db_url = Key("db.url", stringType)
val db_driver = Key("db.driver", stringType)
val db_username = Key("db.username", stringType)
val db_password = Key("db.password", stringType)
val log_limit = Key("log_limit", intType)
fun Init(fileName : String) {
config = ConfigurationProperties.fromFile(File(fileName))
}
fun print() {
config.list().map{ it.second.map { println(it) }}
}
} | 0 | Kotlin | 0 | 0 | 5216e99ed37b3f798bc4f1005f6e986a8ed26def | 958 | duckylucktgbot | MIT License |
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/internal/navigation/NavigationLifecycleMonitor.kt | luugiathuy | 227,537,256 | true | {"Java": 1432132, "Kotlin": 647817, "Python": 4645, "Makefile": 3213, "JavaScript": 3107, "Shell": 1903, "Prolog": 611} | package com.mapbox.services.android.navigation.v5.internal.navigation
import android.app.Activity
import android.app.Application
import android.content.res.Configuration
import android.os.Bundle
import java.util.ArrayList
internal class NavigationLifecycleMonitor(
application: Application
) : Application.ActivityLifecycleCallbacks {
companion object {
private const val ONE_HUNDRED_PERCENT = 100
}
private val startSessionTime: Long = System.currentTimeMillis()
private val resumes = arrayListOf<Long>()
private val pauses = arrayListOf<Long>()
private var currentOrientation: Int = Configuration.ORIENTATION_UNDEFINED
private var portraitStartTime = 0L
private var portraitTimeInMillis = 0.0
init {
application.registerActivityLifecycleCallbacks(this)
initCurrentOrientation(application)
}
override fun onActivityStarted(activity: Activity?) {
activity?.let {
val newOrientation = it.resources.configuration.orientation
// If a new orientation is found, set it to the current
if (currentOrientation != newOrientation) {
currentOrientation = newOrientation
val currentTimeMillis = System.currentTimeMillis()
// If the current orientation is now landscape, add the time the phone was just in portrait
when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
portraitTimeInMillis += currentTimeMillis - portraitStartTime
}
Configuration.ORIENTATION_PORTRAIT -> {
portraitStartTime = currentTimeMillis
}
}
}
}
}
override fun onActivityResumed(activity: Activity?) {
resumes.add(System.currentTimeMillis())
}
override fun onActivityPaused(activity: Activity?) {
pauses.add(System.currentTimeMillis())
}
override fun onActivityDestroyed(activity: Activity?) {
activity?.let {
if (it.isFinishing) {
it.application.unregisterActivityLifecycleCallbacks(this)
}
}
}
//region Unused Lifecycle Methods
override fun onActivityCreated(activity: Activity?, bundle: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivitySaveInstanceState(activity: Activity?, bundle: Bundle?) {
}
//endregion
fun obtainPortraitPercentage(): Int {
// If no changes to landscape
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT && portraitTimeInMillis == 0.0) {
return ONE_HUNDRED_PERCENT
}
// Calculate given the time spent in portrait
val portraitFraction = portraitTimeInMillis / (System.currentTimeMillis() - startSessionTime)
return (ONE_HUNDRED_PERCENT * portraitFraction).toInt()
}
fun obtainForegroundPercentage(): Int {
val currentTime = System.currentTimeMillis()
val foregroundTime = calculateForegroundTime(currentTime)
return (ONE_HUNDRED_PERCENT * (foregroundTime / (currentTime - startSessionTime))).toInt()
}
private fun initCurrentOrientation(application: Application) {
currentOrientation = application.resources.configuration.orientation
// If starting in portrait, set the portrait start time
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
portraitStartTime = System.currentTimeMillis()
}
}
private fun calculateForegroundTime(currentTime: Long): Double {
val tempResumes = ArrayList(resumes)
// If the activity was destroyed while in the background
if (tempResumes.size < pauses.size) {
tempResumes.add(currentTime)
}
var resumePauseDiff = 0L
for (i in tempResumes.indices) {
if (i < pauses.size) {
resumePauseDiff += tempResumes[i] - pauses[i]
}
}
return (currentTime - resumePauseDiff - startSessionTime).toDouble()
}
}
| 0 | null | 0 | 1 | f1e5d047665617c4ef32a3b4b5c9ab29d0ecaa93 | 4,160 | mapbox-navigation-android | Apache License 2.0 |
libs/commons-database/src/main/kotlin/gov/cdc/ocio/database/dynamo/AnyAttributeConverter.kt | CDCgov | 679,761,337 | false | {"Kotlin": 606270, "Python": 14605, "TypeScript": 7647, "Java": 4266, "JavaScript": 2382} | package gov.cdc.ocio.database.dynamo
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.JsonItemAttributeConverter
import software.amazon.awssdk.protocols.jsoncore.JsonNode
import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode
import software.amazon.awssdk.services.dynamodb.model.AttributeValue
/**
* Attribute converter for the Any type, which for dynamodb this can only be interpreted as a JsonNode.
*/
class AnyAttributeConverter : AttributeConverter<Any> {
/**
* Attempt to map to the JsonItemAttributeConverter if the input is a JsonNode.
*
* @param input Any
* @return AttributeValue
*/
override fun transformFrom(input: Any): AttributeValue {
if (input is JsonNode) {
return JsonItemAttributeConverter.create().transformFrom(input)
}
throw Exception("Unable to transform from Any object input type to a JsonNode")
}
/**
* Attempt to transform the input to a JsonNode.
*
* @param input AttributeValue
* @return Any
*/
override fun transformTo(input: AttributeValue?): Any {
if (AttributeValue.fromNul(true) == input) {
return NullJsonNode.instance()
}
return JsonItemAttributeConverter.create().transformTo(input)
}
/**
* The enhanced type is Any.
*
* @return EnhancedType<Any>
*/
override fun type(): EnhancedType<Any> {
return EnhancedType.of(Any::class.java)
}
/**
* The attribute type value is M for map.
*
* @return AttributeValueType
*/
override fun attributeValueType(): AttributeValueType {
return AttributeValueType.M
}
} | 4 | Kotlin | 0 | 2 | c8b369ba84918cd90d29a25d581d42c4d2cc346e | 1,911 | data-exchange-processing-status | Apache License 2.0 |
api/src/main/kotlin/me/filizes/prison/api/data/world/Position.kt | FILIZES | 845,464,403 | false | {"Kotlin": 38620} | package me.filizes.prison.api.data.world
data class Position(
val world: String,
val x: Int,
val y: Int,
val z: Int
) | 0 | Kotlin | 0 | 0 | 916203e1dd071a171ec2b963b41b5005931620fc | 134 | PrisonGame | MIT License |
e2e-tests/src/jvmTest/kotlin/dev/aoddon/connector/BasicServiceValidation.kt | AlessandroOddone | 277,954,349 | false | null | package dev.aoddon.connector
import com.tschuchort.compiletesting.SourceFile.Companion.kotlin
import dev.aoddon.connector.http.EXPECTED_RETURN_TYPES_MESSAGE_PART
import dev.aoddon.connector.util.runTestCompilation
import org.junit.Test
class BasicServiceValidationTest {
@Test fun `@Service abstract class target is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service abstract class TestApi {
@GET("get") abstract suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("@Service target must be a top-level interface." atLine 6)
}
}
@Test fun `@Service target must be top-level`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
object TopLevel {
@Service interface TestApi {
@GET("get") suspend fun get(): String
}
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("@Service target must be a top-level interface." atLine 7)
}
}
@Test fun `Supertypes are not allowed for @Service interfaces`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
interface SuperType
@Service interface TestApi : SuperType {
@GET("get") suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("@Service interfaces cannot have supertypes." atLine 8)
}
}
@Test fun `Type parameters are not allowed for @Service interfaces`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi<T> {
@GET("get") suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("@Service interfaces cannot have type parameters." atLine 6)
}
}
@Test fun `Abstract property is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
val s: String
@GET("get") suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("Properties are not allowed in @Service interfaces." atLine 7)
}
}
@Test fun `Property with getter is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
val s: String get() = ""
@GET("get") suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("Properties are not allowed in @Service interfaces." atLine 7)
}
}
@Test fun `Function missing HTTP method is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
suspend fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors(
"All functions in @Service interfaces must be annotated with an HTTP method." atLine 7
)
}
}
@Test fun `Non-suspension function is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
@GET("get") fun get(): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors(
"All functions in @Service interfaces must be suspension functions." atLine 7
)
}
}
@Test fun `Function with a default implementation is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
@GET("get") suspend fun get(): String = ""
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors("Functions with a body are not allowed in @Service interfaces." atLine 7)
}
}
@Test fun `Function with type parameters is not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
@GET("get") suspend fun <T> get(): T
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors(
"Functions with type parameters are not allowed in @Service interfaces." atLine 7,
"Invalid return type: 'test.TestApi.get.T'. $EXPECTED_RETURN_TYPES_MESSAGE_PART" atLine 7,
)
}
}
@Test fun `Function parameters must be annotated`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
@GET("get") suspend fun get(notAnnotated: String): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors(
"All parameters in a @Service function must have an appropriate Connector annotation." atLine 7
)
}
}
@Test fun `Multiple annotations on the same function parameter are not allowed`() {
val sourceFile = kotlin(
"Test.kt",
"""
package test
import dev.aoddon.connector.*
import dev.aoddon.connector.http.*
@Service interface TestApi {
@GET("get/{id}") suspend fun get(@Path("id") @Query("id") id: String): String
}
"""
)
sourceFile.runTestCompilation {
assertKspErrors(
"Multiple Connector annotations are not allowed on the same parameter." atLine 7
)
}
}
}
| 1 | Kotlin | 0 | 0 | 91d8581d65e3e65b5ec0c5f19d0ab902de3afea1 | 6,297 | connector | Apache License 2.0 |
stretchez/src/main/java/me/shangdelu/stretchez/ui/main/ui/dashboard/StretchPlanListFragment.kt | ShangDeLu | 554,451,333 | false | null | package me.shangdelu.stretchez.ui.main.ui.dashboard
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.snackbar.Snackbar
import me.shangdelu.stretchez.R
import me.shangdelu.stretchez.StretchPlanFragment
import me.shangdelu.stretchez.StretchPlanListViewModel
import me.shangdelu.stretchez.SwipeToDeleteCallBack
import me.shangdelu.stretchez.database.StretchPlan
import java.util.*
/**
* Required interface for hosting activities
*/
//Use a StretchPlanCallback interface to delegate on-click events from fragments back to its hosting activity.
interface StretchPlanCallbacks {
//called when click on StretchPlan
fun onStretchPlanSelected(stretchPlanId: UUID, option: Int)
}
class StretchPlanListFragment : Fragment(), StretchPlanCallbacks {
private lateinit var stretchPlanRecyclerView: RecyclerView
private lateinit var stretchPlanCoordinatorLayout: CoordinatorLayout
private lateinit var bottomNavView: BottomNavigationView
private var adapter: StretchPlanAdapter? = StretchPlanAdapter(emptyList())
private val stretchPlanListViewModel: StretchPlanListViewModel by lazy {
ViewModelProvider(this)[StretchPlanListViewModel::class.java]
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_stretch_plan_list, container, false)
//use requireActivity to find the bottom navigation view that is bind to Activity
bottomNavView = requireActivity().findViewById(R.id.nav_view)
stretchPlanCoordinatorLayout = view.findViewById(R.id.stretch_plan_coordinator_layout)
stretchPlanRecyclerView = view.findViewById(R.id.stretch_plan_recycler_view) as RecyclerView
stretchPlanRecyclerView.layoutManager = LinearLayoutManager(context)
stretchPlanRecyclerView.adapter = adapter
//Swipe to delete existing stretch plans
val swipeToDeleteCallBack = object : SwipeToDeleteCallBack(context) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.bindingAdapterPosition
val currentId = adapter?.stretchPlans?.get(position)
currentId?.let { currentPlan ->
//get current timestamp of the stretch plan
//it.timestamp = System.currentTimeMillis();
//delete the stretchExercise contain in current stretchPlan
stretchPlanListViewModel.getExercisesOfPlan(currentPlan.id).observe(viewLifecycleOwner) { exerciseList ->
exerciseList.forEach {
stretchPlanListViewModel.deleteStretchExercise(it)
}
}
//delete the current stretch plan
stretchPlanListViewModel.deleteStretchPlan(currentPlan)
}
//notify the user that delete is complete
val deleteMessage = Snackbar.make(stretchPlanCoordinatorLayout,
R.string.delete_plan_snackbar, Snackbar.LENGTH_LONG)
//use bottomNavView to setAnchorView for the snack bar to prevent snack bar got blocked by bottom navigation bar.
deleteMessage.setActionTextColor(Color.WHITE).setAnchorView(bottomNavView).show()
// deleteMessage.setAction(R.string.undo_delete_snackbar) {
// currentId?.let {
// it.timestamp = null
// stretchPlanListViewModel.updateStretchPlan(it)
// }
// }
}
}
val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallBack)
itemTouchHelper.attachToRecyclerView(stretchPlanRecyclerView)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupMenu()
stretchPlanListViewModel.stretchPlanListLiveData.observe(viewLifecycleOwner)
{ stretchPlans ->
stretchPlans?.let {
//Log.i(TAG, "GOT ${stretchPlans.size} stretchPlans")
updateUI(stretchPlans)
}
}
}
private fun setupMenu() {
(requireActivity() as MenuHost).addMenuProvider(object: MenuProvider {
//Populates the Menu instance with the items defined in file.
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.fragment_stretch_plan_list, menu)
}
//Respond to MenuItem selection by creating a new stretchPlan, saving it to database,
//and then notifying the parent activity that the new stretchPlan has been selected.
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.new_stretchPlan -> {
val stretchPlan = StretchPlan()
stretchPlanListViewModel.addStretchPlan(stretchPlan)
//argumentOption is 1 as we are creating new stretchPlan
onStretchPlanSelected(stretchPlan.id, 1)
//return true once the MenuItem is handled, indicating no further processing is necessary.
true
}
//return false when the MenuItem cannot be handled by the MenuProvider.
else -> return false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
override fun onStretchPlanSelected(stretchPlanId: UUID, option: Int) {
val arguments = StretchPlanFragment.newInstance(stretchPlanId, option)
findNavController().navigate(R.id.action_navigation_stretch_plan_list_to_navigation_stretch_plan, arguments)
}
private fun updateUI(stretchPlans: List<StretchPlan>) {
adapter = StretchPlanAdapter(stretchPlans)
stretchPlanRecyclerView.adapter = adapter
}
private inner class StretchPlanHolder(view: View)
: RecyclerView.ViewHolder(view), View.OnClickListener {
private lateinit var stretchPlan: StretchPlan
private val titleTextView: TextView = itemView.findViewById(R.id.stretch_plan_title)
init {
itemView.setOnClickListener(this)
}
fun bind (stretchPlan: StretchPlan) {
this.stretchPlan = stretchPlan
titleTextView.text = this.stretchPlan.title
if (stretchPlan.title.isEmpty()) {
stretchPlanListViewModel.deleteStretchPlan(stretchPlan)
}
// if user deleted a stretch plan last more than 30 days, then delete it completely
if (stretchPlan.timestamp != null && stretchPlan.timestamp!! >= 2592000000) {
stretchPlanListViewModel.deleteStretchPlan(stretchPlan)
}
}
override fun onClick(v: View?) {
onStretchPlanSelected(stretchPlan.id, 0)
}
}
private inner class StretchPlanAdapter(var stretchPlans: List<StretchPlan>)
: RecyclerView.Adapter<StretchPlanHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StretchPlanHolder {
val view = layoutInflater.inflate(R.layout.list_item_stretch_plan, parent, false)
return StretchPlanHolder(view)
}
override fun onBindViewHolder(holder: StretchPlanHolder, position: Int) {
val stretchPlan = stretchPlans[position]
holder.bind(stretchPlan)
}
override fun getItemCount() = stretchPlans.size
}
companion object {
fun newInstance(): StretchPlanListFragment {
return StretchPlanListFragment()
}
}
} | 0 | Kotlin | 0 | 0 | f4c536f0cf9425fdccc462434ee4d32fc7ffbc7c | 8,561 | StretchEz | Apache License 2.0 |
compiler/testData/diagnostics/tests/multiplatform/java/implicitJavaActualization_multipleActuals.ll.kt | JetBrains | 3,432,266 | false | null | // MODULE: m1-common
// FILE: common.kt
expect class Foo(i: Int) {
fun foo()
}
// MODULE: m2-jvm()()(m1-common)
// FILE: Foo.java
public class Foo {
public Foo(int i) {}
public void foo() {}
}
// FILE: jvm.kt
class <!PACKAGE_OR_CLASSIFIER_REDECLARATION!>Foo<!><T>(t: T) {
fun foo() {}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 308 | kotlin | Apache License 2.0 |
src/main/com/intellij/lang/jsgraphql/ide/project/schemastatus/GraphQLTreeNodeNavigationUtil.kt | JetBrains | 47,924,453 | false | null | /*
* Copyright (c) 2018-present, <NAME>
* All rights reserved.
* <p>
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.intellij.lang.jsgraphql.ide.project.schemastatus
import com.intellij.json.JsonFileType
import com.intellij.lang.jsgraphql.ide.introspection.source.GraphQLGeneratedSourcesManager
import com.intellij.lang.jsgraphql.types.language.SourceLocation
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.psi.NavigatablePsiElement
object GraphQLTreeNodeNavigationUtil {
@JvmStatic
fun openSourceLocation(myProject: Project, location: SourceLocation, followGeneratedFile: Boolean) {
if (location.isPsiBased) {
val element = location.element
if (element is NavigatablePsiElement && element.isValid()) {
element.navigate(true)
return
}
}
var sourceFile = StandardFileSystems.local().findFileByPath(location.sourceName) ?: return
if (sourceFile.fileType == JsonFileType.INSTANCE && followGeneratedFile) {
val generatedSource = GraphQLGeneratedSourcesManager.getInstance(myProject).requestGeneratedFile(sourceFile)
if (generatedSource != null) {
// open the SDL file and not the JSON introspection file it was based on
sourceFile = generatedSource
}
}
OpenFileDescriptor(myProject, sourceFile, location.line - 1, location.column - 1).navigate(true)
}
}
| 138 | null | 97 | 880 | fcd80eea779e595bc5e5b7aa2f1dc3c69b179d97 | 1,673 | js-graphql-intellij-plugin | MIT License |
privacy-config/privacy-config-impl/src/main/java/com/duckduckgo/privacy/config/impl/features/unprotectedtemporary/RealUnprotectedTemporary.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2021 DuckDuckGo
*
* 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.duckduckgo.privacy.config.impl.features.unprotectedtemporary
import com.duckduckgo.app.global.UriString
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.privacy.config.api.UnprotectedTemporary
import com.duckduckgo.privacy.config.api.UnprotectedTemporaryException
import com.duckduckgo.privacy.config.store.features.unprotectedtemporary.UnprotectedTemporaryRepository
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
import dagger.SingleInstanceIn
@ContributesBinding(AppScope::class)
@SingleInstanceIn(AppScope::class)
class RealUnprotectedTemporary @Inject constructor(private val repository: UnprotectedTemporaryRepository) : UnprotectedTemporary {
override fun isAnException(url: String): Boolean {
return matches(url)
}
override val unprotectedTemporaryExceptions: List<UnprotectedTemporaryException>
get() = repository.exceptions
private fun matches(url: String): Boolean {
return repository.exceptions.any { UriString.sameOrSubdomain(url, it.domain) }
}
}
| 68 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,672 | Android | Apache License 2.0 |
RxKit/src/main/java/com/tamsiree/rxkit/RxSPTool.kt | Tamsiree | 69,093,112 | false | null | package com.tamsiree.rxkit
import android.content.Context
/**
* SharedPreferences工具类
*
* @author tamsiree
* @date 2016/1/24
*/
object RxSPTool {
private const val JSON_CACHE = "JSON_CACHE"
/**
* 存入自定义的标识的数据 可以近似的看作网络下载数据的缓存
* 单条方式存入
*
* @param context 使用的上下文
* @param tag 存入内容的标记,约定俗成的tag用当前的类名命名来区分不同的sp
* @param content 存入的内
*/
@JvmStatic
fun putContent(context: Context, tag: String?, content: String?) {
putString(context, tag, content)
}
/**
* 获取以tag命名的存储内
*
* @param context 当前调用的上下文
* @param tag 命名的tag
* @return 返回以tag区分的内容,默认为空
*/
@JvmStatic
fun getContent(context: Context, tag: String?): String {
return getString(context, tag)
}
/**
* SP中写入String类型value
*
* @param key 键
* @param value 值
*/
@JvmStatic
fun putString(context: Context, key: String?, value: String?) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putString(key, value)
editor.apply()
}
/**
* SP中读取String
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值`defaultValue`
*/
@JvmStatic
fun getString(context: Context, key: String?): String {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val value: String
value = sp.getString(key, "")!!
return value
}
/**
* SP中写入int类型value
*
* @param key 键
* @param value 值
*/
@JvmStatic
fun putInt(context: Context, key: String?, value: Int) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putInt(key, value)
editor.apply()
}
/**
* SP中读取int
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
@JvmStatic
fun getInt(context: Context, key: String?): Int {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val value: Int
value = sp.getInt(key, -1)
return value
}
/**
* SP中写入long类型value
*
* @param key 键
* @param value 值
*/
@JvmStatic
fun putLong(context: Context, key: String?, value: Long) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putLong(key, value)
editor.apply()
}
/**
* SP中读取long
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
@JvmStatic
fun getLong(context: Context, key: String?): Long {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val value: Long
value = sp.getLong(key, -1L)
return value
}
/**
* SP中写入float类型value
*
* @param key 键
* @param value 值
*/
@JvmStatic
fun putFloat(context: Context, key: String?, value: Float) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putFloat(key, value)
editor.apply()
}
/**
* SP中读取float
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
@JvmStatic
fun getFloat(context: Context, key: String?): Float {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val value: Float
value = sp.getFloat(key, -1f)
return value
}
/**
* SP中写入boolean类型value
*
* @param key 键
* @param value 值
*/
@JvmStatic
fun putBoolean(context: Context, key: String?, value: Boolean) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putBoolean(key, value)
editor.apply()
}
/**
* SP中读取boolean
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值`defaultValue`
*/
@JvmStatic
fun getBoolean(context: Context, key: String?): Boolean {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
val value: Boolean
value = sp.getBoolean(key, false)
return value
}
/**
* SP中移除该key
*
* @param key 键
*/
@JvmStatic
fun remove(context: Context, key: String?) {
val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
sp.edit().remove(key).apply()
}
/**
* 存放JSON缓存数据
*
* @param context 上下文
* @param key 键名
* @param content 内容
* @return
*/
@JvmStatic
fun putJSONCache(context: Context, key: String?, content: String?) {
val sp = context.getSharedPreferences(JSON_CACHE, Context.MODE_PRIVATE)
val editor = sp.edit()
editor.putString(key, content)
editor.apply()
}
/**
* 读取JSON缓存数据
*
* @param context 上下文
* @param key 键名
* @return
*/
@JvmStatic
fun readJSONCache(context: Context, key: String?): String? {
val sp = context.getSharedPreferences(JSON_CACHE, Context.MODE_PRIVATE)
return sp.getString(key, null)
}
/**
* 清除指定的信息
*
* @param context 上下文
* @param name 键名
* @param key 若为null 则删除name下所有的键值
*/
@JvmStatic
fun clearPreference(context: Context, name: String?, key: String?) {
val sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
if (key != null) {
editor.remove(key)
} else {
editor.clear()
}
editor.apply()
}
} | 70 | null | 2855 | 12,025 | fa5f88c24594a562c2a9047c40ceeb94de297428 | 5,614 | RxTool | Apache License 2.0 |
core/kotlinx-coroutines-core/test/test/TestCoroutineContextTest.kt | objcode | 159,731,828 | false | null | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import kotlin.coroutines.*
import kotlin.test.*
class TestCoroutineContextTest {
private val injectedContext = TestCoroutineContext()
@After
fun tearDown() {
injectedContext.cancelAllActions()
}
@Test
fun testDelayWithLaunch() = withTestContext(injectedContext) {
val delay = 1000L
var executed = false
launch {
suspendedDelayedAction(delay) {
executed = true
}
}
advanceTimeBy(delay / 2)
assertFalse(executed)
advanceTimeBy(delay / 2)
assertTrue(executed)
}
@Test
fun testTimeJumpWithLaunch() = withTestContext(injectedContext) {
val delay = 1000L
var executed = false
launch {
suspendedDelayedAction(delay) {
executed = true
}
}
advanceTimeTo(delay / 2)
assertFalse(executed)
advanceTimeTo(delay)
assertTrue(executed)
}
@Test
fun testDelayWithAsync() = withTestContext(injectedContext) {
val delay = 1000L
var executed = false
async {
suspendedDelayedAction(delay) {
executed = true
}
}
advanceTimeBy(delay / 2)
assertFalse(executed)
advanceTimeBy(delay / 2)
assertTrue(executed)
}
@Test
fun testDelayWithRunBlocking() = withTestContext(injectedContext) {
val delay = 1000L
var executed = false
runBlocking {
suspendedDelayedAction(delay) {
executed = true
}
}
assertTrue(executed)
assertEquals(delay, now())
}
private suspend fun suspendedDelayedAction(delay: Long, action: () -> Unit) {
delay(delay)
action()
}
@Test
fun testDelayedFunctionWithRunBlocking() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 16
val result = runBlocking {
suspendedDelayedFunction(delay) {
expectedValue
}
}
assertEquals(expectedValue, result)
assertEquals(delay, now())
}
@Test
fun testDelayedFunctionWithAsync() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 16
val deferred = async {
suspendedDelayedFunction(delay) {
expectedValue
}
}
advanceTimeBy(delay / 2)
try {
deferred.getCompleted()
fail("The Job should not have been completed yet.")
} catch (e: Exception) {
// Success.
}
advanceTimeBy(delay / 2)
assertEquals(expectedValue, deferred.getCompleted())
}
private suspend fun <T> TestCoroutineContext.suspendedDelayedFunction(delay: Long, function: () -> T): T {
delay(delay / 4)
return async {
delay((delay / 4) * 3)
function()
}.await()
}
@Test
fun testBlockingFunctionWithRunBlocking() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 16
val result = runBlocking {
suspendedBlockingFunction(delay) {
expectedValue
}
}
assertEquals(expectedValue, result)
assertEquals(delay, now())
}
@Test
fun testBlockingFunctionWithAsync() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 16
var now = 0L
val deferred = async {
suspendedBlockingFunction(delay) {
expectedValue
}
}
now += advanceTimeBy((delay / 4) - 1)
assertEquals((delay / 4) - 1, now)
assertEquals(now, now())
try {
deferred.getCompleted()
fail("The Job should not have been completed yet.")
} catch (e: Exception) {
// Success.
}
now += advanceTimeBy(1)
assertEquals(delay, now())
assertEquals(now, now())
assertEquals(expectedValue, deferred.getCompleted())
}
private suspend fun <T> TestCoroutineContext.suspendedBlockingFunction(delay: Long, function: () -> T): T {
delay(delay / 4)
return runBlocking {
delay((delay / 4) * 3)
function()
}
}
@Test
fun testTimingOutFunctionWithAsyncAndNoTimeout() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 67
val result = async {
suspendedTimingOutFunction(delay, delay + 1) {
expectedValue
}
}
triggerActions()
assertEquals(expectedValue, result.getCompleted())
}
@Test
fun testTimingOutFunctionWithAsyncAndTimeout() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 67
val result = async {
suspendedTimingOutFunction(delay, delay) {
expectedValue
}
}
triggerActions()
assertTrue(result.getCompletionExceptionOrNull() is TimeoutCancellationException)
}
@Test
fun testTimingOutFunctionWithRunBlockingAndTimeout() = withTestContext(injectedContext) {
val delay = 1000L
val expectedValue = 67
try {
runBlocking {
suspendedTimingOutFunction(delay, delay) {
expectedValue
}
}
fail("Expected TimeoutCancellationException to be thrown.")
} catch (e: TimeoutCancellationException) {
// Success
} catch (e: Throwable) {
fail("Expected TimeoutCancellationException to be thrown: $e")
}
}
private suspend fun <T> TestCoroutineContext.suspendedTimingOutFunction(delay: Long, timeOut: Long, function: () -> T): T {
return runBlocking {
withTimeout(timeOut) {
delay(delay / 2)
val ret = function()
delay(delay / 2)
ret
}
}
}
@Test(expected = AssertionError::class)
fun testWithTestContextThrowingAnAssertionError() = withTestContext(injectedContext) {
val expectedError = IllegalAccessError("hello")
launch {
throw expectedError
}
triggerActions()
}
@Test
fun testExceptionHandlingWithLaunch() = withTestContext(injectedContext) {
val expectedError = IllegalAccessError("hello")
launch {
throw expectedError
}
triggerActions()
assertUnhandledException { it === expectedError}
}
@Test
fun testExceptionHandlingWithLaunchingChildCoroutines() = withTestContext(injectedContext) {
val delay = 1000L
val expectedError = TestException("hello")
val expectedValue = 12
launch {
suspendedAsyncWithExceptionAfterDelay(delay, expectedError, expectedValue, true)
}
advanceTimeBy(delay)
assertUnhandledException { it === expectedError}
}
@Test
fun testExceptionHandlingWithAsyncAndDontWaitForException() = withTestContext(injectedContext) {
val delay = 1000L
val expectedError = IllegalAccessError("hello")
val expectedValue = 12
val result = async {
suspendedAsyncWithExceptionAfterDelay(delay, expectedError, expectedValue, false)
}
advanceTimeBy(delay)
assertNull(result.getCompletionExceptionOrNull())
assertEquals(expectedValue, result.getCompleted())
}
@Test
fun testExceptionHandlingWithAsyncAndWaitForException() = withTestContext(injectedContext) {
val delay = 1000L
val expectedError = TestException("hello")
val expectedValue = 12
val result = async {
suspendedAsyncWithExceptionAfterDelay(delay, expectedError, expectedValue, true)
}
advanceTimeBy(delay)
val e = result.getCompletionExceptionOrNull()
assertTrue(expectedError === e, "Expected to be thrown: '$expectedError' but was '$e'")
}
@Test
fun testExceptionHandlingWithRunBlockingAndDontWaitForException() = withTestContext(injectedContext) {
val delay = 1000L
val expectedError = IllegalAccessError("hello")
val expectedValue = 12
val result = runBlocking {
suspendedAsyncWithExceptionAfterDelay(delay, expectedError, expectedValue, false)
}
advanceTimeBy(delay)
assertEquals(expectedValue, result)
}
@Test
fun testExceptionHandlingWithRunBlockingAndWaitForException() = withTestContext(injectedContext) {
val delay = 1000L
val expectedError = TestException("hello")
val expectedValue = 12
try {
runBlocking {
suspendedAsyncWithExceptionAfterDelay(delay, expectedError, expectedValue, true)
}
fail("Expected to be thrown: '$expectedError'")
} catch (e: AssertionError) {
throw e
} catch (e: Throwable) {
assertTrue(expectedError === e, "Expected to be thrown: '$expectedError' but was '$e'")
}
}
private suspend fun <T> TestCoroutineContext.suspendedAsyncWithExceptionAfterDelay(delay: Long, exception: Throwable, value: T, await: Boolean): T {
val deferred = async {
delay(delay - 1)
throw exception
}
if (await) {
deferred.await()
}
return value
}
@Test
fun testCancellationException() = withTestContext {
val job = launch {
delay(1000)
}
advanceTimeBy(500)
job.cancel()
assertAllUnhandledExceptions { it is CancellationException }
}
@Test
fun testCancellationExceptionNotThrownByWithTestContext() = withTestContext {
val job = launch {
delay(1000)
}
advanceTimeBy(500)
job.cancel()
}
}
/* Some helper functions */
// todo: deprecate, replace, see https://github.com/Kotlin/kotlinx.coroutines/issues/541
private fun TestCoroutineContext.launch(
start: CoroutineStart = CoroutineStart.DEFAULT,
parent: Job? = null,
block: suspend CoroutineScope.() -> Unit
) =
GlobalScope.launch(this + (parent ?: EmptyCoroutineContext), start, block)
// todo: deprecate, replace, see https://github.com/Kotlin/kotlinx.coroutines/issues/541
private fun <T> TestCoroutineContext.async(
start: CoroutineStart = CoroutineStart.DEFAULT,
parent: Job? = null,
block: suspend CoroutineScope.() -> T
) =
GlobalScope.async(this + (parent ?: EmptyCoroutineContext), start, block)
private fun <T> TestCoroutineContext.runBlocking(
block: suspend CoroutineScope.() -> T
) = runBlocking(this, block)
| 1 | null | 99 | 5 | 46741db4b0c2863475d5cc6fc75eafadd8e6199d | 11,188 | kotlinx.coroutines | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.