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/ru/scisolutions/scicmscore/engine/persistence/service/PermissionService.kt
borisblack
737,700,232
false
null
package ru.scisolutions.scicmscore.engine.persistence.service import jakarta.persistence.EntityManager import org.hibernate.Session import org.hibernate.stat.Statistics import org.springframework.security.access.AccessDeniedException import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Repository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import ru.scisolutions.scicmscore.engine.persistence.entity.Access import ru.scisolutions.scicmscore.engine.persistence.entity.Permission import ru.scisolutions.scicmscore.engine.persistence.repository.AccessRepository import ru.scisolutions.scicmscore.engine.persistence.repository.PermissionRepository import ru.scisolutions.scicmscore.engine.util.Acl @Service @Repository @Transactional class PermissionService( private val accessRepository: AccessRepository, private val permissionRepository: PermissionRepository, private val cacheService: CacheService, private val entityManager: EntityManager ) { @Transactional(readOnly = true) fun findById(id: String): Permission? = permissionRepository.findById(id).orElse(null) @Transactional(readOnly = true) fun getDefault(): Permission = findById(Permission.DEFAULT_PERMISSION_ID) ?: throw IllegalArgumentException("Default permission not found") // @Cacheable("nativeQueryCache") @Transactional(readOnly = true) fun idsForRead(): Set<String> = idsByAccessMask(Acl.Mask.READ) // @Cacheable("nativeQueryCache") @Transactional(readOnly = true) fun idsByAccessMask(accessMask: Acl.Mask): Set<String> = idsByMask(accessMask.mask) @Transactional(readOnly = true) fun idsByMask(mask: Set<Int>): Set<String> { val authentication = SecurityContextHolder.getContext().authentication ?: throw AccessDeniedException("User is not authenticated") val accessList = accessRepository.findAllByMask( mask, authentication.name, AuthorityUtils.authorityListToSet(authentication.authorities) ).sortedWith(Access.AccessComparator()) val permissionAccessMap = accessList.groupBy { it.sourceId } val session: Session = entityManager.delegate as Session val stats: Statistics = session.sessionFactory.statistics // val testAccessQueryString = "select a from Access a where a.label = :label"; // val testAccessQuery = entityManager.createQuery(testAccessQueryString, Access::class.java) // .setParameter("label", "Default ROLE_ADMIN Access") // .setHint(org.hibernate.jpa.HibernateHints.HINT_CACHEABLE, true) // val testAccList: List<Access> = testAccessQuery.resultList // val accessQuery = entityManager.createQuery(Acl.ACCESS_JPQL_SNIPPET, Access::class.java) // .setParameter("mask", mask) // .setParameter("username", authentication.name) // .setParameter("roles", AuthorityUtils.authorityListToSet(authentication.authorities)) // .setHint(org.hibernate.jpa.HibernateHints.HINT_CACHEABLE, true) // val accList: List<Access> = accessQuery.resultList // val itemStats = stats.getNaturalIdStatistics(Item::class.qualifiedName as String) // val testAccessQueryStats = stats.getQueryStatistics(testAccessQueryString) // val accessStats = stats.getQueryStatistics(Acl.ACCESS_JPQL_SNIPPET) // // cacheService.printStatistics() return permissionAccessMap.filterValues { it[0].granting }.keys.toSet() } }
0
null
0
4
586b6bbe338cc3ea678b1116f9d095a276d20d99
3,714
scicms-core
Apache License 2.0
app/src/main/java/com/example/lockScreen/battery/charging/animation/view/LockScreenChargingAnimationView.kt
HammadAhmed-AndroidDeveloper
720,210,090
false
{"Kotlin": 55545}
package com.example.lockScreen.battery.charging.animation.view import android.content.Context import android.util.AttributeSet import android.widget.VideoView class LockScreenChargingAnimationView : VideoView { constructor(context: Context?) : super(context) {} constructor(context: Context?, attributeSet: AttributeSet?) : super(context, attributeSet) {} constructor(context: Context?, attributeSet: AttributeSet?, i: Int) : super( context, attributeSet, i ) { } public override fun onMeasure(i: Int, i2: Int) { super.onMeasure(i, i2) setMeasuredDimension(i, i2) } }
0
Kotlin
0
0
1a3e69aa713881ca11850e2d7d0026b468712de8
638
LockScreenBatteryChargingAnimation
Apache License 2.0
app/src/main/java/io/aayush/relabs/ui/screens/alerts/AlertsScreen.kt
theimpulson
679,298,392
false
null
package io.aayush.relabs.ui.screens.alerts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import io.aayush.relabs.R import io.aayush.relabs.network.data.alert.UserAlert import io.aayush.relabs.ui.components.AlertItem @Composable @OptIn(ExperimentalMaterial3Api::class) fun AlertsScreen( navHostController: NavHostController, viewModel: AlertsViewModel = hiltViewModel() ) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.alerts)) }) } ) { val alerts: List<UserAlert> by viewModel.alerts.collectAsStateWithLifecycle() LazyColumn(modifier = Modifier.padding(it)) { items(alerts) { userAlert -> AlertItem( modifier = Modifier.padding(10.dp), avatarURL = userAlert.User.avatar_urls.values.first() ?: "", title = userAlert.alert_text, date = userAlert.event_date ) } } } }
0
Kotlin
0
1
c8969074d2ded50c37b2d4ca9c04f6195f1d5e6c
1,738
ReLabs
Apache License 2.0
app/src/main/java/com/amazing/eye/bean/HomeBean.kt
amazingokc
225,336,483
false
null
package com.amazing.eye.bean import java.io.Serializable data class HomeBean( var nextPageUrl: String?, var nextPublishTime: Long, var newestIssueType: String?, var dialog: Any?, var issueList: List<IssueListBean>? ) : BaseBean() { data class IssueListBean( var releaseTime: Long, var type: String?, var date: Long, var publishTime: Long, var count: Int, var itemList: List<ItemListBean>? ) { data class ItemListBean(var type: String?, var data: DataBean?, var tag: Any?) : Serializable { data class DataBean( var dataType: String?, var id: Int, var title: String?, var description: String?, var image: String?, var actionUrl: String?, var adTrack: Any?, var isShade: Boolean, var label: Any?, var labelList: Any?, var header: Any?, var category: String?, var duration: Long?, var playUrl: String, var cover: CoverBean?, var author: AuthorBean?, var releaseTime: Long?, var consumption: ConsumptionBean?, var playInfo: List<PlayInfoBean> ) :Serializable{ data class CoverBean( var feed: String?, var detail: String?, var blurred: String?, var sharing: String?, var homepage: String? ) : Serializable {} data class ConsumptionBean( var collectionCount: String, var shareCount: String, var replyCount: String ) : Serializable { } data class AuthorBean(var icon: String) : Serializable {} } } } }
0
Kotlin
1
4
feac6870a45ac08aba85fab8ebd4e438b737d460
1,916
Eye-kotlin
Apache License 2.0
butterfly/src/main/java/com/morpho/butterfly/lexicons/com/atproto/admin/resolveModerationReports.kt
morpho-app
752,463,268
false
{"Kotlin": 811512}
package com.atproto.admin import kotlin.Long import kotlinx.serialization.Serializable import com.morpho.butterfly.Did import com.morpho.butterfly.model.ReadOnlyList @Serializable public data class ResolveModerationReportsRequest( public val actionId: Long, public val reportIds: ReadOnlyList<Long>, public val createdBy: Did, ) public typealias ResolveModerationReportsResponse = ActionView
20
Kotlin
0
8
525b2f18e9cef6d973c66cf2b3684a06d38332ab
401
Morpho
Apache License 2.0
app/src/main/java/org/stepik/android/domain/course_payments/exception/CoursePurchaseVerificationException.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.domain.course_payments.exception class CoursePurchaseVerificationException : Exception()
13
null
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
116
stepik-android
Apache License 2.0
feature/camera/src/main/java/com/ahmetocak/camera/CameraViewModel.kt
AhmetOcak
793,949,918
false
{"Kotlin": 406065}
package com.ahmetocak.camera import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ahmetocak.camera.capture_img.CameraController import com.ahmetocak.camera.navigation.MESSAGE_BOX_ID import com.ahmetocak.camera.navigation.SENDER_EMAIL import com.ahmetocak.camera.navigation.SENDER_IMG_URL import com.ahmetocak.camera.navigation.SENDER_USERNAME import com.ahmetocak.common.SnackbarManager import com.ahmetocak.common.UiText import com.ahmetocak.domain.usecase.chat.SendMessageUseCase import com.ahmetocak.domain.usecase.firebase.storage.UploadImageFileUseCase import com.ahmetocak.model.Message import com.ahmetocak.model.MessageType import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.time.LocalDateTime import javax.inject.Inject @HiltViewModel class CameraViewModel @Inject constructor( private val ioDispatcher: CoroutineDispatcher, private val sendMessageUseCase: SendMessageUseCase, private val uploadImageFileUseCase: UploadImageFileUseCase, savedStateHandle: SavedStateHandle ) : ViewModel() { private val _uiState = MutableStateFlow(CameraUiState()) val uiState: StateFlow<CameraUiState> = _uiState.asStateFlow() private var messageBoxId: Int? = null private var senderEmail: String? = null private var senderImgUrl: String? = null private var senderUsername: String? = null init { messageBoxId = savedStateHandle.get<String>(MESSAGE_BOX_ID)?.toInt() senderEmail = savedStateHandle.get<String>(SENDER_EMAIL) senderImgUrl = savedStateHandle.get<String>(SENDER_IMG_URL) senderUsername = savedStateHandle.get<String>(SENDER_USERNAME) } fun onEvent(event: CameraUiEvent) { when (event) { is CameraUiEvent.OnCaptureImageClick -> { viewModelScope.launch(ioDispatcher) { CameraController.takePhoto( event.imageCapture, event.context ) { capturedImageUri -> _uiState.update { it.copy( capturedImageUri = capturedImageUri, screenState = if (capturedImageUri == null) ScreenState.CAMERA else ScreenState.CAPTURED_IMAGE ) } } } } is CameraUiEvent.OnSendImageClick -> { if (senderEmail.isNullOrBlank() || senderUsername.isNullOrBlank()) { SnackbarManager.showMessage( UiText.DynamicString("Something went wrong! Please try again later.") ) } else { _uiState.update { it.copy(isMessageSending = true) } uploadImageFileUseCase( imageFileName = "$senderEmail${LocalDateTime.now()}", imageFileUri = event.imageUri, onSuccess = { viewModelScope.launch(ioDispatcher) { sendMessageUseCase( message = Message( senderEmail = senderEmail!!, messageContent = it.toString(), senderImgUrl = senderImgUrl, senderUsername = senderUsername!!, messageType = MessageType.IMAGE, messageBoxId = messageBoxId!! ), onFailure = SnackbarManager::showMessage ) _uiState.update { it.copy( navigateBack = true, isMessageSending = false ) } } }, onFailure = { errorMessage -> SnackbarManager.showMessage(errorMessage) _uiState.update { it.copy(isMessageSending = false) } } ) } } } } override fun onCleared() { super.onCleared() CameraController.resetCapturedPhotoUri() } }
0
Kotlin
0
0
61d1fad8809e1420fd767c33806f994443062b6b
4,826
ChatApp
MIT License
src/test/kotlin/benchmark/suites/edit/RecursifyFunctionSuite.kt
voqal
716,228,492
false
{"Kotlin": 1209055, "Java": 493485, "JavaScript": 13007, "Go": 10765, "Python": 9638, "TypeScript": 828, "Groovy": 568, "PHP": 315, "Rust": 308}
package benchmark.suites.edit import benchmark.model.BenchmarkPromise import benchmark.model.BenchmarkSuite import benchmark.model.context.PromptSettingsContext import benchmark.model.context.VirtualFileContext import com.intellij.psi.PsiFile import dev.voqal.assistant.context.VoqalContext import dev.voqal.assistant.context.code.ViewingCode import dev.voqal.config.settings.PromptSettings import dev.voqal.services.getClasses import dev.voqal.services.getCodeBlock import dev.voqal.services.getFunctions /** * A suite to test the recursifying and de-recursifying of functions. */ class RecursifyFunctionSuite : BenchmarkSuite { fun `rewrite factorial recursive as factorial iterative and find max iterative as find max recursive using no helper functions`( command: BenchmarkPromise ): List<VoqalContext> { val className = "RFunctions" val lang = getCurrentLang() val virtualFile = getVirtualFile(className) val psiFile = getPsiFile(command.project, virtualFile) val code = psiFile.text command.verifyRecursion(className, psiFile) return listOf( VirtualFileContext(virtualFile), ViewingCode(code, language = lang.id), PromptSettingsContext(PromptSettings(promptName = "Edit Mode")) ) } private fun BenchmarkPromise.verifyRecursion(className: String, psiFile: PsiFile) { this.promise.future().onSuccess { checkPsiFileErrors(psiFile, it) val psiClasses = psiFile.getClasses() if (psiClasses.size != 1) { it.fail("Classes found: " + psiClasses.size) } else if (psiClasses.firstOrNull()?.name != className) { it.fail("Class name: " + psiClasses.firstOrNull()?.name) } else { it.success("Found class: $className") } val psiFunctions = psiFile.getFunctions() if (psiFunctions.size != 2) { it.fail("Expected 2 functions, found ${psiFunctions.size}") } else { it.success("Found 2 functions") } val factorialIterative = psiFunctions.find { it.name == "factorialIterative" } if (factorialIterative == null) { it.fail("Factorial iterative function not found") } else { val functionBody = factorialIterative.getCodeBlock() if (functionBody != null) { checkNotTextContains("factorialIterative(", functionBody, it) } else { it.fail("Missing factorialIterative function body") } } val findMaxRecursive = psiFunctions.find { it.name == "findMaxRecursive" } if (findMaxRecursive == null) { it.fail("Find max recursive function not found") } else { val functionBody = findMaxRecursive.getCodeBlock() if (functionBody != null) { checkTextContains("findMaxRecursive(", functionBody, it) } else { it.fail("Missing findMaxRecursive function body") } } it.testFinished() } } }
1
Kotlin
8
90
1a4eac0c4907c44a88288d6af6a686b97b003583
3,259
coder
Apache License 2.0
converter/src/main/java/com/epicadk/hapiprotoconverter/converter/SupplyDeliveryConverter.kt
epicadk
402,074,793
false
{"Kotlin": 2405480}
package com.epicadk.hapiprotoconverter.converter import com.epicadk.hapiprotoconverter.converter.CodeableConceptConverter.toHapi import com.epicadk.hapiprotoconverter.converter.CodeableConceptConverter.toProto import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toHapi import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toProto import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toHapi import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toProto import com.epicadk.hapiprotoconverter.converter.IdentifierConverter.toHapi import com.epicadk.hapiprotoconverter.converter.IdentifierConverter.toProto import com.epicadk.hapiprotoconverter.converter.MetaConverter.toHapi import com.epicadk.hapiprotoconverter.converter.MetaConverter.toProto import com.epicadk.hapiprotoconverter.converter.NarrativeConverter.toHapi import com.epicadk.hapiprotoconverter.converter.NarrativeConverter.toProto import com.epicadk.hapiprotoconverter.converter.PeriodConverter.toHapi import com.epicadk.hapiprotoconverter.converter.PeriodConverter.toProto import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toHapi import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toProto import com.epicadk.hapiprotoconverter.converter.SimpleQuantityConverter.toHapi import com.epicadk.hapiprotoconverter.converter.SimpleQuantityConverter.toProto import com.epicadk.hapiprotoconverter.converter.TimingConverter.toHapi import com.epicadk.hapiprotoconverter.converter.TimingConverter.toProto import com.epicadk.hapiprotoconverter.converter.UriConverter.toHapi import com.epicadk.hapiprotoconverter.converter.UriConverter.toProto import com.google.fhir.r4.core.Id import com.google.fhir.r4.core.String import com.google.fhir.r4.core.SupplyDelivery import com.google.fhir.r4.core.SupplyDelivery.SuppliedItem import com.google.fhir.r4.core.SupplyDeliveryStatusCode import java.lang.IllegalArgumentException import org.hl7.fhir.r4.model.CodeableConcept import org.hl7.fhir.r4.model.DateTimeType import org.hl7.fhir.r4.model.Period import org.hl7.fhir.r4.model.Reference import org.hl7.fhir.r4.model.SimpleQuantity import org.hl7.fhir.r4.model.Timing import org.hl7.fhir.r4.model.Type public object SupplyDeliveryConverter { private fun SupplyDelivery.SuppliedItem.ItemX.supplyDeliverySuppliedItemItemToHapi(): Type { if (hasCodeableConcept()) { return (this.getCodeableConcept()).toHapi() } if (hasReference()) { return (this.getReference()).toHapi() } throw IllegalArgumentException("Invalid Type for SupplyDelivery.suppliedItem.item[x]") } private fun Type.supplyDeliverySuppliedItemItemToProto(): SupplyDelivery.SuppliedItem.ItemX { val protoValue = SupplyDelivery.SuppliedItem.ItemX.newBuilder() if (this is CodeableConcept) { protoValue.setCodeableConcept(this.toProto()) } if (this is Reference) { protoValue.setReference(this.toProto()) } return protoValue.build() } private fun SupplyDelivery.OccurrenceX.supplyDeliveryOccurrenceToHapi(): Type { if (hasDateTime()) { return (this.getDateTime()).toHapi() } if (hasPeriod()) { return (this.getPeriod()).toHapi() } if (hasTiming()) { return (this.getTiming()).toHapi() } throw IllegalArgumentException("Invalid Type for SupplyDelivery.occurrence[x]") } private fun Type.supplyDeliveryOccurrenceToProto(): SupplyDelivery.OccurrenceX { val protoValue = SupplyDelivery.OccurrenceX.newBuilder() if (this is DateTimeType) { protoValue.setDateTime(this.toProto()) } if (this is Period) { protoValue.setPeriod(this.toProto()) } if (this is Timing) { protoValue.setTiming(this.toProto()) } return protoValue.build() } public fun SupplyDelivery.toHapi(): org.hl7.fhir.r4.model.SupplyDelivery { val hapiValue = org.hl7.fhir.r4.model.SupplyDelivery() if (hasId()) { hapiValue.id = id.value } if (hasMeta()) { hapiValue.setMeta(meta.toHapi()) } if (hasImplicitRules()) { hapiValue.setImplicitRulesElement(implicitRules.toHapi()) } if (hasText()) { hapiValue.setText(text.toHapi()) } if (extensionCount > 0) { hapiValue.setExtension(extensionList.map { it.toHapi() }) } if (modifierExtensionCount > 0) { hapiValue.setModifierExtension(modifierExtensionList.map { it.toHapi() }) } if (identifierCount > 0) { hapiValue.setIdentifier(identifierList.map { it.toHapi() }) } if (basedOnCount > 0) { hapiValue.setBasedOn(basedOnList.map { it.toHapi() }) } if (partOfCount > 0) { hapiValue.setPartOf(partOfList.map { it.toHapi() }) } if (hasStatus()) { hapiValue.setStatus(org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliveryStatus.valueOf(status.value.name.hapiCodeCheck().replace("_", ""))) } if (hasPatient()) { hapiValue.setPatient(patient.toHapi()) } if (hasType()) { hapiValue.setType(type.toHapi()) } if (hasSuppliedItem()) { hapiValue.setSuppliedItem(suppliedItem.toHapi()) } if (hasOccurrence()) { hapiValue.setOccurrence(occurrence.supplyDeliveryOccurrenceToHapi()) } if (hasSupplier()) { hapiValue.setSupplier(supplier.toHapi()) } if (hasDestination()) { hapiValue.setDestination(destination.toHapi()) } if (receiverCount > 0) { hapiValue.setReceiver(receiverList.map { it.toHapi() }) } return hapiValue } public fun org.hl7.fhir.r4.model.SupplyDelivery.toProto(): SupplyDelivery { val protoValue = SupplyDelivery.newBuilder() if (hasId()) { protoValue.setId(Id.newBuilder().setValue(id)) } if (hasMeta()) { protoValue.setMeta(meta.toProto()) } if (hasImplicitRules()) { protoValue.setImplicitRules(implicitRulesElement.toProto()) } if (hasText()) { protoValue.setText(text.toProto()) } if (hasExtension()) { protoValue.addAllExtension(extension.map { it.toProto() }) } if (hasModifierExtension()) { protoValue.addAllModifierExtension(modifierExtension.map { it.toProto() }) } if (hasIdentifier()) { protoValue.addAllIdentifier(identifier.map { it.toProto() }) } if (hasBasedOn()) { protoValue.addAllBasedOn(basedOn.map { it.toProto() }) } if (hasPartOf()) { protoValue.addAllPartOf(partOf.map { it.toProto() }) } if (hasStatus()) { protoValue.setStatus(SupplyDelivery.StatusCode.newBuilder().setValue(SupplyDeliveryStatusCode.Value.valueOf(status.toCode().protoCodeCheck().replace("-", "_").toUpperCase())).build()) } if (hasPatient()) { protoValue.setPatient(patient.toProto()) } if (hasType()) { protoValue.setType(type.toProto()) } if (hasSuppliedItem()) { protoValue.setSuppliedItem(suppliedItem.toProto()) } if (hasOccurrence()) { protoValue.setOccurrence(occurrence.supplyDeliveryOccurrenceToProto()) } if (hasSupplier()) { protoValue.setSupplier(supplier.toProto()) } if (hasDestination()) { protoValue.setDestination(destination.toProto()) } if (hasReceiver()) { protoValue.addAllReceiver(receiver.map { it.toProto() }) } return protoValue.build() } private fun org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliverySuppliedItemComponent.toProto(): SupplyDelivery.SuppliedItem { val protoValue = SupplyDelivery.SuppliedItem.newBuilder() if (hasId()) { protoValue.setId(String.newBuilder().setValue(id)) } if (hasExtension()) { protoValue.addAllExtension(extension.map { it.toProto() }) } if (hasModifierExtension()) { protoValue.addAllModifierExtension(modifierExtension.map { it.toProto() }) } if (hasQuantity()) { protoValue.setQuantity((quantity as SimpleQuantity).toProto()) } if (hasItem()) { protoValue.setItem(item.supplyDeliverySuppliedItemItemToProto()) } return protoValue.build() } private fun SupplyDelivery.SuppliedItem.toHapi(): org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliverySuppliedItemComponent { val hapiValue = org.hl7.fhir.r4.model.SupplyDelivery.SupplyDeliverySuppliedItemComponent() if (hasId()) { hapiValue.id = id.value } if (extensionCount > 0) { hapiValue.setExtension(extensionList.map { it.toHapi() }) } if (modifierExtensionCount > 0) { hapiValue.setModifierExtension(modifierExtensionList.map { it.toHapi() }) } if (hasQuantity()) { hapiValue.setQuantity(quantity.toHapi()) } if (hasItem()) { hapiValue.setItem(item.supplyDeliverySuppliedItemItemToHapi()) } return hapiValue } }
1
Kotlin
0
3
2abe5967a905f6a29ed5736c75e8ffb2cf6d3e78
8,781
hapi-proto-converter
Apache License 2.0
common/src/main/java/android/recycler/OnFastScroller.kt
eastar-dev
188,695,253
false
null
package android.recycler import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ObjectAnimator import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.IdRes import androidx.annotation.LayoutRes import androidx.core.view.ViewCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlin.math.max import kotlin.math.min class OnFastScroller @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) { private lateinit var bubble: TextView private lateinit var handle: View private var recyclerView: RecyclerView? = null private var currentAnimator: ObjectAnimator? = null private val onScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { updateBubbleAndHandlePosition() } } interface BubbleTextGetter { fun getTextToShowInBubble(position: Int): String } init { orientation = HORIZONTAL clipChildren = false } fun setViewsToUse(@LayoutRes layoutresId: Int, @IdRes bubbleresId: Int, @IdRes handleresId: Int) { val inflater = LayoutInflater.from(context) inflater.inflate(layoutresId, this, true) bubble = findViewById(bubbleresId) bubble.visibility = View.INVISIBLE handle = findViewById(handleresId) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // height = h updateBubbleAndHandlePosition() } override fun onTouchEvent(event: MotionEvent?): Boolean { event ?: return super.onTouchEvent(event) val action = event.action when (action) { MotionEvent.ACTION_DOWN -> { if (event.x < handle.x - ViewCompat.getPaddingStart(handle)) return false currentAnimator?.cancel() if (bubble.visibility == View.INVISIBLE) showBubble() handle.isSelected = true val y = event.y setBubbleAndHandlePosition(y) setRecyclerViewPosition(y) return true } MotionEvent.ACTION_MOVE -> { val y = event.y setBubbleAndHandlePosition(y) setRecyclerViewPosition(y) return true } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { handle.isSelected = false hideBubble() return true } } return super.onTouchEvent(event) } fun setRecyclerView(recyclerView: RecyclerView?) { if (this.recyclerView !== recyclerView) { this.recyclerView?.removeOnScrollListener(onScrollListener) this.recyclerView = recyclerView this.recyclerView?.addOnScrollListener(onScrollListener) } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() recyclerView?.removeOnScrollListener(onScrollListener) recyclerView = null } private fun setRecyclerViewPosition(y: Float) { recyclerView?.run { val itemCount = adapter!!.itemCount val proportion: Float = when { handle.y == 0f -> 0f handle.y + handle.height >= height - TRACK_SNAP_RANGE -> 1f else -> y / height.toFloat() } val targetPos = getValueInRange(0, itemCount - 1, (proportion * itemCount.toFloat()).toInt()) (layoutManager as LinearLayoutManager).scrollToPositionWithOffset(targetPos, 0) val bubbleText = (recyclerView!!.adapter as BubbleTextGetter).getTextToShowInBubble(targetPos) bubble.text = bubbleText } } private fun getValueInRange(min: Int, max: Int, value: Int): Int { val minimum = max(min, value) return min(minimum, max) } private fun updateBubbleAndHandlePosition() { if (handle.isSelected) return recyclerView?.run { val verticalScrollOffset = computeVerticalScrollOffset() val verticalScrollRange = computeVerticalScrollRange() val proportion = verticalScrollOffset.toFloat() / (verticalScrollRange.toFloat() - height) setBubbleAndHandlePosition(height * proportion) } } private fun setBubbleAndHandlePosition(y: Float) { val handleHeight = handle.height handle.y = getValueInRange(0, height - handleHeight, (y - handleHeight / 2).toInt()).toFloat() val bubbleHeight = bubble.height bubble.y = getValueInRange(0, height - bubbleHeight - handleHeight / 2, (y - bubbleHeight).toInt()).toFloat() } private fun showBubble() { bubble.visibility = View.VISIBLE currentAnimator?.cancel() currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 0F, 1F).setDuration(BUBBLE_ANIMATION_DURATION.toLong()) currentAnimator!!.start() } private fun hideBubble() { currentAnimator?.cancel() currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 1F, 0F).setDuration(BUBBLE_ANIMATION_DURATION.toLong()) currentAnimator!!.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) bubble.visibility = View.INVISIBLE currentAnimator = null } override fun onAnimationCancel(animation: Animator) { super.onAnimationCancel(animation) bubble.visibility = View.INVISIBLE currentAnimator = null } }) currentAnimator!!.start() } companion object { private val BUBBLE_ANIMATION_DURATION = 100 private val TRACK_SNAP_RANGE = 5 } }
0
Kotlin
0
1
100cf219787346561cc9af83db555f3f363cd0c7
6,294
_EastarStudyLogForAndroid
Apache License 2.0
src/main/kotlin/me/steven/indrev/packets/common/SelectModuleOnWorkbenchPacket.kt
GabrielOlvH
265,247,813
false
null
package me.steven.indrev.packets.common import me.steven.indrev.blockentities.modularworkbench.ModularWorkbenchBlockEntity import me.steven.indrev.gui.screenhandlers.machines.ModularWorkbenchScreenHandler import me.steven.indrev.recipes.machines.ModuleRecipe import me.steven.indrev.utils.getRecipes import me.steven.indrev.utils.identifier import me.steven.indrev.utils.isLoaded import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking object SelectModuleOnWorkbenchPacket { val MODULE_SELECT_PACKET = identifier("module_select_packet") fun register() { ServerPlayNetworking.registerGlobalReceiver(MODULE_SELECT_PACKET) { server, player, _, buf, _ -> val syncId = buf.readInt() val recipeId = buf.readIdentifier() val pos = buf.readBlockPos() val screenHandler = player.currentScreenHandler as? ModularWorkbenchScreenHandler ?: return@registerGlobalReceiver if (syncId != screenHandler.syncId) return@registerGlobalReceiver server.execute { val world = player.world if (world.isLoaded(pos)) { val recipe = server.recipeManager.getRecipes(ModuleRecipe.TYPE)[recipeId]!! screenHandler.layoutSlots(recipe) val blockEntity = world.getBlockEntity(pos) as? ModularWorkbenchBlockEntity ?: return@execute blockEntity.selectedRecipe = recipeId blockEntity.markDirty() blockEntity.sync() } } } } }
51
null
56
192
012a1b83f39ab50a10d03ef3c1a8e2651e517053
1,601
Industrial-Revolution
Apache License 2.0
src/main/kotlin/com/nazonazo_app/shit_forces/account/AccountService.kt
GunseiKPaseri
367,370,225
true
{"Kotlin": 82566, "TypeScript": 73151, "HTML": 1675, "CSS": 1467, "JavaScript": 401, "Dockerfile": 41, "Shell": 10}
package com.nazonazo_app.shit_forces.account import com.nazonazo_app.shit_forces.session.SharedSessionService import com.nazonazo_app.shit_forces.submission.SharedSubmissionService import java.util.Base64 import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import org.springframework.http.HttpStatus import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.springframework.web.server.ResponseStatusException @Transactional @Service class AccountService( val accountInfoRepository: AccountInfoRepository, val sharedSubmissionService: SharedSubmissionService, val sharedAccountService: SharedAccountService, val sharedSessionService: SharedSessionService ) { private fun createConnectedPassword(accountName: String, password: String): String { return Base64.getEncoder().encodeToString("$accountName:$password".toByteArray()) } private fun createHashPassword(accountName: String, password: String): String { val bcrypt = BCryptPasswordEncoder() return bcrypt.encode(createConnectedPassword(accountName, password)) } private fun isSamePassword(name: String, password: String): Boolean { val savedPasswordHash = accountInfoRepository.findByAccountName(name)?.passwordHash return BCryptPasswordEncoder().matches(createConnectedPassword(name, password), savedPasswordHash) } fun createAccount(requestAccount: RequestAccount): AccountInfo? = try { if (requestAccount.name.length < 4) { throw Error("名前が短すぎます") } if (accountInfoRepository.findByAccountName(requestAccount.name) != null) { throw Error("名前が重複しています") } val account = accountInfoRepository.createAccount( requestAccount.name, createHashPassword(requestAccount.name, requestAccount.password)) ?: throw Error("アカウント作成に失敗しました") account } catch (e: Error) { print(e) null } fun loginAccount(requestAccount: RequestAccount, servletResponse: HttpServletResponse): Boolean = if (!isSamePassword(requestAccount.name, requestAccount.password)) { false } else { sharedSessionService.createNewSession(requestAccount.name, servletResponse) != null } fun changeAccountName( prevAccountName: String, requestAccount: RequestAccount, httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse ) { if (!isSamePassword(prevAccountName, requestAccount.password)) { throw ResponseStatusException(HttpStatus.UNAUTHORIZED) } accountInfoRepository.changeAccountName(prevAccountName, requestAccount.name, createHashPassword(requestAccount.name, requestAccount.password)) sharedSessionService.deleteSession(prevAccountName) sharedSessionService.createNewSession(requestAccount.name, httpServletResponse) sharedSubmissionService.changeSubmissionAccountName(prevAccountName, requestAccount.name) accountInfoRepository.changeAccountRatingChangeHistoryName(prevAccountName, requestAccount.name) } fun getAccountRanking(page: Int): ResponseAccountRanking { val accounts = accountInfoRepository.findAllAccount() .filter { it.partNum != 0 } val responseAccounts = accounts .map { ResponseAccount(it.name, sharedAccountService.calcCorrectionRate(it), it.partNum, it.authority.name) } .sortedBy { -it.rating } .filterIndexed { idx, _ -> page * ACCOUNT_RANKING_ONE_PAGE <= idx && idx < (page + 1) * ACCOUNT_RANKING_ONE_PAGE } return ResponseAccountRanking(responseAccounts, accounts.size) } }
0
null
0
0
3bc4351d8884a15b9b40cf2a4c3baa68176d96dc
3,974
Shitforces
MIT License
app/src/main/java/victorteka/github/io/koin_tutorial/utils/Constants.kt
Victorteka
292,320,460
false
null
package victorteka.github.io.koin_tutorial.utils class Constants { companion object{ const val BASE_URL = "https://5e510330f2c0d300147c034c.mockapi.io/" } }
0
Kotlin
0
0
c6d6b76d83402e66a57c69731d35e8f2f4d26c84
173
Android_DI_With_Koin
MIT License
arrow-libs/fx/arrow-fx-coroutines/src/test/kotlin/arrow/fx/coroutines/CancelBoundary.kt
clojj
343,913,289
true
{"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83}
package arrow.fx.coroutines import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.types.shouldBeInstanceOf import kotlinx.coroutines.delay import kotlin.time.ExperimentalTime import kotlin.time.seconds @ExperimentalTime class CancelBoundary : StringSpec({ suspend fun forever(): Unit { while (true) { cancelBoundary() // cancellable computation loop } } "endless loop can be cancelled if it includes a boundary" { val latch = Promise<Unit>() val exit = Promise<ExitCase>() val f = ForkConnected { guaranteeCase( { latch.complete(Unit) forever() }, { ec -> exit.complete(ec) } ) } latch.get() f.cancel() exit.get().shouldBeInstanceOf<ExitCase.Cancelled>() delay(1.seconds) } })
0
null
0
0
5eae605bbaeb2b911f69a5bccf3fa45c42578416
807
arrow
Apache License 2.0
domain/src/test/java/com/gentalhacode/domain/features/search/interactor/GetRepositoriesUseCaseTest.kt
thgMatajs
239,887,486
false
null
package com.gentalhacode.domain.features.search.interactor import com.gentalhacode.domain.features.factory.RepositoryFactory import com.gentalhacode.github.base.rx.PostExecutionThread import com.gentalhacode.github.domain.features.search.interactor.GetRepositoriesUseCase import com.gentalhacode.github.domain.features.search.model.DomainParamsToSearch import com.gentalhacode.github.domain.features.search.repository.SearchRepository import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Flowable import org.junit.Before import org.junit.Test /** * .:.:.:. Created by @thgMatajs on 12/02/20 .:.:.:. */ class GetRepositoriesUseCaseTest { private lateinit var useCase: GetRepositoriesUseCase private val repository = mock<SearchRepository>() private var postExecutionThread = mock<PostExecutionThread>() private val dummyRepositories = RepositoryFactory.dummyDomainRepositories() private val paramsToSearch = RepositoryFactory.dummyDomainParamsToSearch() @Before fun init() { useCase = GetRepositoriesUseCase(repository, postExecutionThread) whenever(repository.getRepositoriesBy(paramsToSearch)) .thenReturn(Flowable.just(dummyRepositories)) } @Test fun `Check if Repositories is loaded`() { val call = useCase.buildUseCaseFlowable(paramsToSearch).test() call.assertValue { it.size == dummyRepositories.size } .assertNoErrors() .assertComplete() } @Test fun `Check exception when pass null param`() { val call = useCase.buildUseCaseFlowable().test() call.assertFailure(IllegalArgumentException::class.java) } @Test fun `Check exception when pass blank param`() { val params = DomainParamsToSearch("") whenever(repository.getRepositoriesBy(params)) .thenReturn(Flowable.just(dummyRepositories)) val call = useCase.buildUseCaseFlowable(params).test() call.assertFailure(IllegalArgumentException::class.java) } }
0
Kotlin
0
5
f3e8465cdbc92c9375f32c20085afdeac69dd04d
2,085
GitHubSearch
The Unlicense
src/main/kotlin/dev/voitenko/services/trainings/TrainingsController.kt
voitenkodev
611,669,266
false
null
package dev.voitenko.services.trainings import dev.voitenko.database.* import dev.voitenko.services.trainings.dto.Training import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import org.jetbrains.exposed.sql.SqlExpressionBuilder.like import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.select import java.util.* class TrainingsController(private val call: ApplicationCall) { suspend fun getTraining() { val token = call.request.headers["Authorization"]?.replace("Bearer ", "") val user = Users.getByToken(token = UUID.fromString(token)) if (user == null) { call.respond(HttpStatusCode.Unauthorized, "User Not Found") return } val id = call.parameters["id"]?.toLongOrNull() val training = Trainings.getTrainings { select { Trainings.id eq id } }.firstOrNull() if (training == null) { call.respond(HttpStatusCode.NotFound, "Training Not Found") return } call.respond(HttpStatusCode.OK, training) } suspend fun getTrainings() { val token = call.request.headers["Authorization"]?.replace("Bearer ", "") val user = Users.getByToken(token = UUID.fromString(token)) if (user == null) { call.respond(HttpStatusCode.Unauthorized, "User Not Found") return } val trainings = Trainings.getTrainings { select { Trainings.user_id eq user.token } } call.respond(HttpStatusCode.OK, trainings) } suspend fun setTraining() { val token = call.request.headers["Authorization"]?.replace("Bearer ", "") val user = Users.getByToken(token = UUID.fromString(token)) if (user == null) { call.respond(HttpStatusCode.Unauthorized, "User Not Found") return } val body = call.receive<Training>() val trainingId = Trainings.insert(user.token, body).value.toString() call.respond(HttpStatusCode.OK, trainingId) } suspend fun removeTraining() { val token = call.request.headers["Authorization"]?.replace("Bearer ", "") val user = Users.getByToken(token = UUID.fromString(token)) if (user == null) { call.respond(HttpStatusCode.Unauthorized, "User Not Found") return } val id = call.request.queryParameters["id"]?.toLongOrNull() if (id == null) { call.respond(HttpStatusCode.BadRequest, "Invalid ID") return } Trainings.remove(trainingId = id) call.respond(HttpStatusCode.OK) } suspend fun getExercises() { val token = call.request.headers["Authorization"]?.replace("Bearer ", "") val user = Users.getByToken(token = UUID.fromString(token)) if (user == null) { call.respond(HttpStatusCode.Unauthorized, "User Not Found") return } val name = call.request.queryParameters["name"] ?: "" val response = Trainings.getExercises { select { (Trainings.user_id eq user.token) and (Exercises.name like "$name%") } } call.respond(HttpStatusCode.OK, response) } }
0
Kotlin
0
1
cee86b020bad2b4425ac28c0c6534fed7b5fb4e3
3,307
useful-training-backend
MIT License
backend.native/tests/external/stdlib/properties/delegation/lazy/LazyValuesTest/NullableLazyValTest.kt
pedromassango
109,945,056
true
{"Kotlin": 3706234, "C++": 727837, "C": 135283, "Groovy": 47410, "JavaScript": 7780, "Shell": 6563, "Batchfile": 6379, "Objective-C++": 5203, "Objective-C": 1891, "Python": 1844, "Pascal": 1698, "Makefile": 1341, "Java": 782, "HTML": 185}
import kotlin.test.* import kotlin.properties.* class NullableLazyValTest { var resultA = 0 var resultB = 0 val a: Int? by lazy { resultA++; null } val b by lazy { foo() } fun doTest() { a b assertTrue(a == null, "fail: a should be null") assertTrue(b == null, "fail: b should be null") assertTrue(resultA == 1, "fail: initializer for a should be invoked only once") assertTrue(resultB == 1, "fail: initializer for b should be invoked only once") } fun foo(): String? { resultB++ return null } } fun box() { NullableLazyValTest().doTest() }
0
Kotlin
0
1
5d514e3ede6c70ad144ceaf3a5aac065c74e09eb
646
kotlin-native
Apache License 2.0
src/main/kotlin/rs/dusk/network/codec/download/decode/message/DownloadLogout.kt
FailZombie
324,388,128
true
{"Kotlin": 85527, "Java": 4112}
package rs.dusk.network.codec.download.decode.message import rs.dusk.network.codec.download.DownloadServiceMessage /** * @author Tyluur <[email protected]> * @since December 17, 2020 */ data class DownloadLogout(val value : Int) : DownloadServiceMessage
0
null
0
0
5f9e53a1575f3c547314ef0f8da86fb2556fc7b3
260
dusk
Creative Commons Attribution 3.0 Unported
cropper/src/main/kotlin/com/canhub/cropper/BitmapCroppingWorkerJob.kt
CanHub
314,844,143
false
null
package com.canhub.cropper import android.content.Context import android.graphics.Bitmap import android.net.Uri import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.lang.ref.WeakReference import kotlin.coroutines.CoroutineContext internal class BitmapCroppingWorkerJob( private val context: Context, private val cropImageViewReference: WeakReference<CropImageView>, private val uri: Uri?, private val bitmap: Bitmap?, private val cropPoints: FloatArray, private val degreesRotated: Int, private val orgWidth: Int, private val orgHeight: Int, private val fixAspectRatio: Boolean, private val aspectRatioX: Int, private val aspectRatioY: Int, private val reqWidth: Int, private val reqHeight: Int, private val flipHorizontally: Boolean, private val flipVertically: Boolean, private val options: CropImageView.RequestSizeOptions, private val saveCompressFormat: Bitmap.CompressFormat, private val saveCompressQuality: Int, private val customOutputUri: Uri?, ) : CoroutineScope { private var job: Job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job fun start() { job = launch(Dispatchers.Default) { try { if (isActive) { val bitmapSampled: BitmapUtils.BitmapSampled when { uri != null -> { bitmapSampled = BitmapUtils.cropBitmap( context = context, loadedImageUri = uri, cropPoints = cropPoints, degreesRotated = degreesRotated, orgWidth = orgWidth, orgHeight = orgHeight, fixAspectRatio = fixAspectRatio, aspectRatioX = aspectRatioX, aspectRatioY = aspectRatioY, reqWidth = reqWidth, reqHeight = reqHeight, flipHorizontally = flipHorizontally, flipVertically = flipVertically, ) } bitmap != null -> { bitmapSampled = BitmapUtils.cropBitmapObjectHandleOOM( bitmap = bitmap, cropPoints = cropPoints, degreesRotated = degreesRotated, fixAspectRatio = fixAspectRatio, aspectRatioX = aspectRatioX, aspectRatioY = aspectRatioY, flipHorizontally = flipHorizontally, flipVertically = flipVertically, ) } else -> { onPostExecute( Result( bitmap = null, uri = null, error = null, sampleSize = 1, ), ) return@launch } } val resizedBitmap = BitmapUtils.resizeBitmap( bitmap = bitmapSampled.bitmap, reqWidth = reqWidth, reqHeight = reqHeight, options = options, ) launch(Dispatchers.IO) { val newUri = BitmapUtils.writeBitmapToUri( context = context, bitmap = resizedBitmap, compressFormat = saveCompressFormat, compressQuality = saveCompressQuality, customOutputUri = customOutputUri, ) onPostExecute( Result( bitmap = resizedBitmap, uri = newUri, sampleSize = bitmapSampled.sampleSize, error = null, ), ) } } } catch (throwable: Exception) { onPostExecute( Result( bitmap = null, uri = null, error = throwable, sampleSize = 1, ), ) } } } private suspend fun onPostExecute(result: Result) { withContext(Dispatchers.Main) { var completeCalled = false if (isActive) { cropImageViewReference.get()?.let { completeCalled = true it.onImageCroppingAsyncComplete(result) } } if (!completeCalled && result.bitmap != null) { // Fast release of unused bitmap. result.bitmap.recycle() } } } fun cancel() = job.cancel() internal data class Result( val bitmap: Bitmap?, val uri: Uri?, val error: Exception?, val sampleSize: Int, ) }
11
null
47
968
d382c97e0447b5ea55f52c9067997f1ae62b9e54
4,555
Android-Image-Cropper
Apache License 2.0
app/src/main/java/com/team7/pregnancytracker/models/daos/ContactDao.kt
Explore-In-HMS
402,767,707
false
{"Kotlin": 231923, "Java": 90247}
/* * * * *Copyright 2020. Explore in HMS. 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.team7.pregnancytracker.models.daos import androidx.room.* import com.team7.pregnancytracker.models.entities.Contact import com.team7.pregnancytracker.utils.Constants @Dao interface ContactDao { @Insert fun insert(contact: Contact): Long @Delete fun delete(contact: Contact) @Update fun update(contact: Contact) @Query("SELECT * FROM " + Constants.DB_TABLE_NAME_CONTACT) fun getAllContacts(): List<Contact> }
1
Kotlin
1
1
1c0cf421e09e61c0d094bfd79f564443cbb2fa93
1,089
Pregnancy-Tracker
Apache License 2.0
wudaozi/src/main/java/com/josephuszhou/wudaozi/config/Config.kt
JosephusZhou
214,570,971
false
null
package com.josephuszhou.wudaozi.config import com.josephuszhou.wudaozi.R import com.josephuszhou.wudaozi.callback.ActivityCallback import com.josephuszhou.wudaozi.filter.Filter import com.josephuszhou.wudaozi.imageloader.ImageLoader import com.josephuszhou.wudaozi.imageloader.impl.GlideLoader class Config private constructor() { companion object { fun getInstance() = InstanceHolder.INSTANCE fun getInitialInstance(): Config { val instance = getInstance() instance.reset() return instance } } private object InstanceHolder { val INSTANCE = Config() } var mThemeId: Int = R.style.WuDaozi_Theme var mImageLoader: ImageLoader = GlideLoader() var mColumnsCount: Int = 4 var mMaxSelectableCount: Int = 1 var mFilter: Filter? = null var mCallback: ActivityCallback? = null fun reset() { mThemeId = R.style.WuDaozi_Theme mImageLoader = GlideLoader() mColumnsCount = 4 mMaxSelectableCount = 1 mFilter = null } }
1
null
1
6
074d81c973f65a3751a876d5f5fe42d5d9c4c07a
1,075
WuDaozi
Apache License 2.0
api/src/main/kotlin/eu/codeloop/thehub/jobs/model/CompanyEntity.kt
codeloopeu
140,247,675
false
{"Dotenv": 3, "Text": 3, "Ignore List": 1, "YAML": 5, "Markdown": 2, "JSON": 3, "EditorConfig": 2, "JSON with Comments": 1, "HTML": 2, "JavaScript": 36, "SVG": 3, "SCSS": 2, "Gradle Kotlin DSL": 2, "Procfile": 1, "INI": 3, "Gradle": 1, "Shell": 1, "Batchfile": 1, "Kotlin": 49, "Java": 28, "SQL": 6, "Dockerfile": 1}
package eu.codeloop.thehub.jobs.model import java.util.ArrayList import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.OneToMany import javax.persistence.Table @Entity @Table(name = "companies") class CompanyEntity { @Id @Column(name = "company_id", nullable = false) lateinit var companyId: String @Column(name = "name", nullable = false) lateinit var name: String @Column(name = "logo", nullable = false) lateinit var logo: String @OneToMany(cascade = [CascadeType.MERGE]) @JoinColumn( name = "company_id", referencedColumnName = "company_id", insertable = true, updatable = true ) val jobs: MutableList<JobEntity> = ArrayList() @ManyToOne(cascade = [CascadeType.MERGE]) @JoinColumn( name = "domain", referencedColumnName = "domain", insertable = true, updatable = true, nullable = false ) lateinit var domain: DomainEntity @ManyToOne(cascade = [CascadeType.MERGE]) @JoinColumn( name = "location", referencedColumnName = "location", insertable = true, updatable = true, nullable = false ) lateinit var location: LocationEntity }
18
Kotlin
0
0
056b501f6262d59d239ab270cee4bf77c0496c0d
1,398
thehub
ISC License
app/src/main/java/id/co/jst/siar/Helpers/sqlite/DBHandlerLocations.kt
indi90
146,280,497
false
{"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 2, "XML": 10, "Kotlin": 24}
package id.co.jst.siar.Helpers.sqlite import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import java.util.ArrayList import id.co.jst.siar.Models.sqlite.LocationModel /** * Created by endro.ngujiharto on 4/6/2017. */ class DBHandlerLocations(context: Context) : DBHandlerSQLite(context) { // Getting locations Count // return count val locationCount: Int get() { val countQuery = "SELECT * FROM " + DBHandlerSQLite.TABLE_LOCATION val db = this.readableDatabase val cursor = db.rawQuery(countQuery, null) return cursor.count } // Getting All Locations // Select All Query // looping through all rows and adding to list // Adding to list // return contact list val allLocations: List<LocationModel> get() { val locationList = ArrayList<LocationModel>() val selectQuery = "SELECT * FROM " + DBHandlerSQLite.TABLE_LOCATION val db = this.writableDatabase val cursor = db.rawQuery(selectQuery, null) if (cursor.moveToFirst()) { do { val location = LocationModel() location.pl_code = Integer.parseInt(cursor.getString(0)) location.pl_building = cursor.getString(1) location.pl_floor = cursor.getString(2) location.pl_place = cursor.getString(3) location.pl_description = cursor.getString(4) locationList.add(location) } while (cursor.moveToNext()) } return locationList } // Adding new location fun addLocation(location: LocationModel) { val db = this.writableDatabase val values = ContentValues() values.put(DBHandlerSQLite.KEY_ID, location.pl_code) values.put(DBHandlerSQLite.KEY_BUILDING, location.pl_building) values.put(DBHandlerSQLite.KEY_FLOOR, location.pl_floor) values.put(DBHandlerSQLite.KEY_PLACE, location.pl_place) values.put(DBHandlerSQLite.KEY_DESCRIPTION, location.pl_description) values.put(DBHandlerSQLite.KEY_DATE, location.pl_date!!.toString()) // Inserting Row db.insert(DBHandlerSQLite.TABLE_LOCATION, null, values) db.close() // Closing database connection } // Deleting a shop fun deleteLocation(location: LocationModel) { val db = this.writableDatabase db.delete(DBHandlerSQLite.TABLE_LOCATION, DBHandlerSQLite.KEY_ID + " = ?", arrayOf(location.pl_code.toString())) db.close() } // Getting location fun getLocation(pl_code: String): LocationModel { val query = "SELECT * FROM " + DBHandlerSQLite.TABLE_LOCATION + " WHERE pl_code = " + pl_code val db = this.readableDatabase val cursor = db.rawQuery(query, null) cursor?.moveToFirst() // return count return LocationModel(cursor!!.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)) } // Truncate Location fun truncateLocation() { val success: Boolean? val truncateQuery = "DELETE FROM " + DBHandlerSQLite.TABLE_LOCATION val db = this.readableDatabase db.execSQL(truncateQuery) } }
1
null
1
1
c9a0beb415502d780618494ca574551b2fd4d62a
3,490
SIAR
MIT License
android/src/com/android/tools/idea/res/AndroidLightPackage.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.res import com.android.tools.idea.projectsystem.getProjectSystem import com.android.utils.concurrency.getAndUnwrap import com.google.common.base.MoreObjects import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementFinder import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.PsiPackage import com.intellij.psi.impl.file.PsiPackageImpl import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.android.augment.AndroidLightClassBase /** * [PsiPackage] for packages that contain classes generated by aapt. * * @see AndroidLightClassBase * @see ProjectSystemPsiElementFinder * @see com.android.tools.idea.projectsystem.LightResourceClassService */ class AndroidLightPackage private constructor(manager: PsiManager, qualifiedName: String) : PsiPackageImpl(manager, qualifiedName) { companion object { @JvmStatic fun withName(packageName: String, project: Project): PsiPackage { return project.getService(InstanceCache::class.java).get(packageName) } } /** * Overrides [PsiPackageImpl.isValid] to ignore what files exist on disk. [AndroidLightPackage] * instances are only used if the right [PsiElementFinder] decided there are light R classes with * this package name, so the package is valid even if there are no physical files in corresponding * directories. */ override fun isValid(): Boolean { return project.isDisposed.not() } /** Returns true if there are corresponding physical directories to navigate to. */ override fun canNavigate(): Boolean { return super.isValid() } override fun toString(): String { return MoreObjects.toStringHelper(this).addValue(qualifiedName).toString() } override fun getFiles(scope: GlobalSearchScope): Array<PsiFile> { // Return any light `R` classes defined in modules within the search scope. // // When an `R` class is defined in a package that contains no other Java/Kotlin classes, the // system ends up checking with this package to determine whether the class is accessible in a // given scope; see b/292491619. To enable that check to pass, this function must return the // `R` class. // // It's possible that other light classes also reside in this package (or other real classes, // for that matter), but there's no need to return them at this time. If we run into a similar // situation with other synthetic classes that are defined in unique packages, they can be // added here. // Find all modules with the required package name that are in the search scope. val projectSystem = project.getProjectSystem() val modulesInScope = projectSystem .getAndroidFacetsWithPackageName(project, qualifiedName) .map { it.module } .filter { scope.isSearchInModuleContent(it) } // Return the containing files for `R` classes defined by those modules. val lightResourceClassService = projectSystem.getLightResourceClassService() return modulesInScope .flatMap { lightResourceClassService.getLightRClassesDefinedByModule(it) } .mapNotNull { it.containingFile } .toTypedArray() } /** * Project service responsible for interning instances of [AndroidLightPackage] with a given name. */ @Service(Service.Level.PROJECT) class InstanceCache(val project: Project) { /** Cache of [PsiPackage] instances for a given package name. */ private val packageCache: Cache<String, PsiPackage> = CacheBuilder.newBuilder().softValues().build() fun get(name: String): PsiPackage = packageCache.getAndUnwrap(name) { AndroidLightPackage(PsiManager.getInstance(project), name) } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
4,481
android
Apache License 2.0
compiler/testData/ir/irText/firProblems/noErrorTypeAfterCaptureApproximation.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL class Inv1<X> class Inv2<Y> internal fun <F> useSelectOptions( options: Inv1<out F>, ): Inv1<out Inv2<F>> = myRun { getSelectOptions(options) } private fun <G> getSelectOptions( options: Inv1<out G>, ): Inv1<out Inv2<G>> = TODO() fun <T> myRun( callback: () -> T, ): T = TODO()
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
325
kotlin
Apache License 2.0
compiler/testData/codegen/boxWithJava/collections/platformValueContains/platformValueContains.kt
msdgwzhy6
51,743,245
true
{"Java": 15875830, "Kotlin": 12695228, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 29983, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 6859, "Shell": 4704, "IDL": 4669, "Batchfile": 3703}
class MySet : Set<String> { override val size: Int get() = throw UnsupportedOperationException() override fun isEmpty(): Boolean { throw UnsupportedOperationException() } override fun contains(o: String): Boolean { throw UnsupportedOperationException() } override fun iterator(): Iterator<String> { throw UnsupportedOperationException() } override fun containsAll(c: Collection<String>): Boolean { throw UnsupportedOperationException() } } fun box(): String { val mySet = MySet() // no UnsupportedOperationException thrown mySet.contains(J.nullValue()) J.nullValue() in mySet val set: Set<String> = mySet set.contains(J.nullValue()) J.nullValue() in set val anySet: Set<Any?> = mySet as Set<Any?> anySet.contains(J.nullValue()) anySet.contains(null) J.nullValue() in anySet null in anySet return "OK" }
0
Java
0
1
f713adc96e9adeacb1373fc170a5ece1bf2fc1a2
939
kotlin
Apache License 2.0
app/src/main/java/com/qyh/keepalivekotlin/receiver/ScreenReceiverUtils.kt
qiu-yongheng
123,305,863
false
null
package com.qyh.keepalivekotlin.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log /** * @author 邱永恒 * * @time 2018/3/1 10:38 * * @desc 静态监听锁屏、解锁、开屏广播 * a) 当用户锁屏时,将SportsActivity置于前台,同时开启1像素悬浮窗; * b) 当用户解锁时,关闭1像素悬浮窗; */ class ScreenReceiverUtils(private val context: Context) { companion object { val TAG = "ScreenReceiverUtils" var listener: ScreenStatusListener? = null } private val screenReceiver: ScreenReceiver by lazy { ScreenReceiver() } fun setScreenStatusListener(screenListener: ScreenStatusListener) { listener = screenListener // 动态启动广播接收器 val filter = IntentFilter() filter.addAction(Intent.ACTION_SCREEN_ON) filter.addAction(Intent.ACTION_SCREEN_OFF) filter.addAction(Intent.ACTION_USER_PRESENT) context.registerReceiver(screenReceiver, filter) } fun stopScreenStatusListener() { context.unregisterReceiver(screenReceiver) } /** * 广播接收 */ class ScreenReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action Log.d(TAG, "ScreenReceiver --> 监听到系统广播: " + action) when (action) { Intent.ACTION_SCREEN_ON -> listener?.onScreenOn() // 开屏 Intent.ACTION_SCREEN_OFF -> listener?.onScreenOff() // 锁屏 Intent.ACTION_USER_PRESENT -> listener?.onUserPresent() // 解锁 } } } /** * 屏幕状态改变监听 */ interface ScreenStatusListener { fun onScreenOn() fun onScreenOff() fun onUserPresent() } }
1
null
4
8
89562859f1627c0955304f45f1ed09a6dd82e8d5
1,796
KeepAlive-kotlin
Apache License 2.0
app/src/main/java/com/wan/android/adapter/ImageHolder.kt
qinghuaAndroid
252,683,218
false
null
package com.wan.android.adapter import android.view.View import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView class ImageHolder(view: View) : RecyclerView.ViewHolder(view) { @JvmField var imageView: ImageView = view as ImageView }
1
Kotlin
3
3
00e30dcac6593e57d677092eb10ab47b270248a1
269
WanAndroid-MVVM
Apache License 2.0
interactors/src/test/java/com/thefuntasty/interactors/sample/User.kt
okalman
193,893,166
true
{"Gradle Kotlin DSL": 10, "YAML": 1, "INI": 2, "Ruby": 2, "Shell": 1, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "Markdown": 1, "Java": 2, "XML": 26, "FreeMarker": 4, "Fluent": 16, "Kotlin": 116, "Proguard": 1, "Java Properties": 1}
package com.thefuntasty.interactors.sample data class User(val name: String)
0
Kotlin
1
0
7564acba0e67ec86bd141904c774b8fcf8cced58
78
mvvm-android
MIT License
Kotlin/App.SQLite.ArtGallery/app/src/main/java/com/sercan/artgallery/ArtAdapter.kt
sebetci
499,716,185
false
{"Java": 294457, "Kotlin": 194532}
package com.sercan.artgallery import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.sercan.artgallery.databinding.RecyclerRowBinding class ArtAdapter(val artList : ArrayList<Art>) : RecyclerView.Adapter<ArtAdapter.ArtHolder>() { class ArtHolder(val binding : RecyclerRowBinding) : RecyclerView.ViewHolder(binding.root) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArtHolder { val binding = RecyclerRowBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ArtHolder(binding) } override fun onBindViewHolder(holder: ArtHolder, position: Int) { holder.binding.recyclerViewTextView.text = artList.get(position).name holder.itemView.setOnClickListener { val intent = Intent(holder.itemView.context, ArtActivity::class.java) intent.putExtra("info", "old") intent.putExtra("id", artList.get(position).id) holder.itemView.context.startActivity(intent) } } override fun getItemCount(): Int { return artList.size } }
1
null
1
1
5d75faf7f4ca8ee74398280a49e6ed7d9881ee17
1,192
Android-Apps
MIT License
app/src/main/java/com/mapswithme/maps/bookmarks/OnItemLongClickListener.kt
dnemov
245,413,600
false
{"Gradle": 3, "Java Properties": 3, "Shell": 1, "Text": 16, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "XML": 624, "Kotlin": 708, "Java": 9, "HTML": 3, "JSON": 95}
package com.mapswithme.maps.bookmarks import android.view.View interface OnItemLongClickListener<T> { fun onItemLongClick(v: View, item: T) }
0
Kotlin
0
1
8b75114193e141aee14fcbc207a208c4a39de1db
147
omim.kt
Apache License 2.0
app/src/test/java/com/raiden/learningunittest/chapter7/MailClientTest.kt
Raiden18
175,925,941
false
null
package com.raiden.learningunittest.chapter7 import org.junit.Test import org.junit.runner.RunWith import org.mockito.internal.verification.VerificationModeFactory.times import org.powermock.api.mockito.PowerMockito import org.powermock.api.mockito.PowerMockito.mockStatic import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(EmailServer::class, MailClient::class) class MailClientTest() { @Throws(Exception::class) @Test fun `Should create email`() { val legacyMailClient = MailClient() val email = Email("123", "123", "123") mockStatic(EmailServer::class.java) val address = "<EMAIL>" val title = "Пиьсмо бабушке" val body = "Где пенсия?" PowerMockito.whenNew(Email::class.java).withArguments(address, title, body).thenReturn(email) legacyMailClient.sendEmail(address, title, body) PowerMockito.verifyStatic(times(1)) EmailServer.sendEmail(email) }}
0
Kotlin
0
1
2b775ae8266489c4639702427616c26da0da6633
1,067
Practical-Unit-Testing-With-Junit-And-Mockito
MIT License
subprojects/xcfa/xcfa/src/main/java/hu/bme/mit/theta/xcfa/passes/AtomicReadsOneWritePass.kt
ftsrg
39,392,321
false
null
/* * Copyright 2024 Budapest University of Technology and Economics * * 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 hu.bme.mit.theta.xcfa.passes import hu.bme.mit.theta.core.decl.Decl import hu.bme.mit.theta.core.decl.Decls import hu.bme.mit.theta.core.decl.VarDecl import hu.bme.mit.theta.core.stmt.AssignStmt import hu.bme.mit.theta.core.stmt.AssumeStmt import hu.bme.mit.theta.core.stmt.HavocStmt import hu.bme.mit.theta.core.type.Expr import hu.bme.mit.theta.core.type.Type import hu.bme.mit.theta.core.type.anytype.RefExpr import hu.bme.mit.theta.core.utils.TypeUtils.cast import hu.bme.mit.theta.core.utils.indexings.VarIndexing import hu.bme.mit.theta.core.utils.indexings.VarIndexingFactory import hu.bme.mit.theta.xcfa.* import hu.bme.mit.theta.xcfa.model.* /** * One atomic unit (atomic block or edge) can have at most one write operation on a global variable and no read can * happen after writing a global variable. Therefore, each atomic unit that violates this rule is transformed so that * each global variable is replaced with a local variable that is assigned the value of the global variable at the * beginning of the atomic unit and the global variable is assigned the value of the local variable at the end of the * atomic unit. */ class AtomicReadsOneWritePass : ProcedurePass { private lateinit var builder: XcfaProcedureBuilder override fun run(builder: XcfaProcedureBuilder): XcfaProcedureBuilder { var indexing: VarIndexing = VarIndexingFactory.indexing(0) this.builder = builder builder.getEdges().toSet().forEach { edge -> if (edge.getFlatLabels().any { it.isAtomicBegin }) { val toReplace = edge.countAtomicBlockAccesses() .mapNotNull { (v, ao) -> if (ao.wrongWrite) v else null } if (toReplace.isNotEmpty()) { val localVersions = toReplace.associateWith { v -> indexing = indexing.inc(v) v.localVersion(indexing) } val newStartEdge = edge.replaceAccesses(localVersions) val initialAssigns = SequenceLabel(localVersions.map { (v, local) -> StmtLabel(AssignStmt.of(cast(local, local.type), cast(v.ref, local.type))) }) val atomicBeginIndex = newStartEdge.getFlatLabels().indexOfFirst { it.isAtomicBegin } val newLabels = newStartEdge.getFlatLabels().toMutableList().apply { add(atomicBeginIndex + 1, initialAssigns) } builder.removeEdge(newStartEdge) builder.addEdge(newStartEdge.withLabel(SequenceLabel(newLabels))) } } } builder.getEdges().toSet().forEach { edge -> val toReplace = edge.countEdgeAccesses() .mapNotNull { (v, ao) -> if (ao.wrongWrite) v else null } if (toReplace.isNotEmpty()) { val localVersions = toReplace.associateWith { v -> indexing = indexing.inc(v) v.localVersion(indexing) } val initialAssigns = localVersions.map { (v, local) -> StmtLabel(AssignStmt.of(cast(local, local.type), cast(v.ref, local.type))) } val newLabels = edge.getFlatLabels().map { it.replaceAccesses(localVersions) } val finalAssigns = localVersions.map { (v, local) -> StmtLabel(AssignStmt.of(cast(v, local.type), cast(local.ref, v.type))) } builder.removeEdge(edge) builder.addEdge(edge.withLabel(SequenceLabel(initialAssigns + newLabels + finalAssigns))) } } return builder } private fun <T : Type> VarDecl<T>.localVersion(indexing: VarIndexing): VarDecl<T> = Decls.Var("${name}_l${indexing.get(this)}", type) private data class AccessOrder(var write: Boolean = false, var wrongWrite: Boolean = false) private fun XcfaEdge.countAtomicBlockAccesses(): Map<VarDecl<*>, AccessOrder> { val accesses = mutableMapOf<VarDecl<*>, AccessOrder>() // over-approximation of writePrecedesRead val toVisit = mutableListOf(this) while (toVisit.isNotEmpty()) { val current = toVisit.removeAt(0) var atomicEnd = false current.getFlatLabels().forEach { it.countAccesses(accesses) atomicEnd = atomicEnd || it.isAtomicEnd } if (!atomicEnd) toVisit.addAll(current.target.outgoingEdges) } return accesses } private fun XcfaEdge.countEdgeAccesses(): Map<VarDecl<*>, AccessOrder> { val accesses = mutableMapOf<VarDecl<*>, AccessOrder>() getFlatLabels().forEach { it.countAccesses(accesses) } return accesses } private fun XcfaLabel.countAccesses(accesses: MutableMap<VarDecl<*>, AccessOrder>) { collectVarsWithAccessType().filter { (v, _) -> v !in builder.getVars() }.forEach { (v, at) -> val t = accesses.getOrDefault(v, AccessOrder()) if (t.write) t.wrongWrite = true if (at.isWritten) t.write = true accesses[v] = t } } private fun XcfaEdge.replaceAccesses(localVersions: Map<VarDecl<*>, VarDecl<*>>): XcfaEdge { val toVisit = mutableListOf(this) var first: XcfaEdge? = null while (toVisit.isNotEmpty()) { val current = toVisit.removeAt(0) var atomicEnd = false val newLabels = current.getFlatLabels().map { atomicEnd = atomicEnd || it.isAtomicEnd if (atomicEnd) it else it.replaceAccesses(localVersions) }.toMutableList() builder.removeEdge(current) if (!atomicEnd) { toVisit.addAll(current.target.outgoingEdges) } else { val atomicEndIndex = newLabels.indexOfFirst { it.isAtomicEnd } val finalAssigns = SequenceLabel(localVersions.map { (v, local) -> StmtLabel(AssignStmt.of(cast(v, local.type), cast(local.ref, v.type))) }) newLabels.add(atomicEndIndex, finalAssigns) } val newEdge = current.withLabel(SequenceLabel(newLabels)) builder.addEdge(newEdge) first = first ?: newEdge } return first!! } private fun XcfaLabel.replaceAccesses(localVersions: Map<VarDecl<*>, VarDecl<*>>): XcfaLabel { return when (this) { is StmtLabel -> when (val stmt = stmt) { is AssignStmt<*> -> StmtLabel(AssignStmt.of( cast(localVersions[stmt.varDecl] ?: stmt.varDecl, stmt.varDecl.type), cast(stmt.expr.replace(localVersions), stmt.varDecl.type))) is AssumeStmt -> StmtLabel(AssumeStmt.of(stmt.cond.replace(localVersions))) is HavocStmt<*> -> StmtLabel(HavocStmt.of(localVersions[stmt.varDecl] ?: stmt.varDecl)) else -> this } is SequenceLabel -> SequenceLabel(labels.map { it.replaceAccesses(localVersions) }, metadata) is FenceLabel -> this is NopLabel -> this else -> error("Unsupported label type at global var atomic localization: $this") } } private fun <T : Type> Expr<T>.replace(localVersions: Map<out Decl<*>, VarDecl<*>>): Expr<T> = if (this is RefExpr<T>) localVersions[decl]?.ref?.let { cast(it, decl.type) } ?: this ?: this else map { it.replace(localVersions) } }
50
null
42
49
cb77d7e6bb0e51ea00d2a1dc483fdf510dd8e8b4
8,251
theta
Apache License 2.0
sketch-core/src/main/kotlin/com/github/panpf/sketch/cache/internal/KeyMapperCache.kt
panpf
14,798,941
false
{"Kotlin": 3225805, "Shell": 724}
/* * Copyright (C) 2022 panpf <[email protected]> * * 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.github.panpf.sketch.cache.internal import com.github.panpf.sketch.util.LruCache class KeyMapperCache(val maxSize: Int = 100, val mapper: (key: String) -> String) { private val cache = LruCache<String, String>(maxSize) fun mapKey(key: String): String = cache.get(key) ?: mapper(key).apply { cache.put(key, this) } }
1
Kotlin
308
1,978
82ffde1ff148311bb5b36eb70a4c82224d1f3af4
982
sketch
Apache License 2.0
native/src/main/kotlin/com/faendir/zachtronics/bot/om/OmSimMetric.kt
F43nd1r
290,065,466
false
{"Git Config": 1, "Gradle Kotlin DSL": 3, "YAML": 6, "Ignore List": 3, "JSON": 3, "Dockerfile": 1, "Java Properties": 1, "Shell": 1, "Text": 19, "Batchfile": 1, "Markdown": 14, "TOML": 1, "INI": 1, "Java": 219, "XML": 3, "Kotlin": 123, "JSON with Comments": 1, "HTML": 1, "robots.txt": 1, "CSS": 1, "TSX": 58, "JavaScript": 1, "C": 1}
/* * Copyright (c) 2024 * * 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.faendir.zachtronics.bot.om /** see http://events.critelli.technology/static/metrics.html */ @Suppress("ClassName", "Unused") sealed class OmSimMetric(val id: String) { object PARSED_CYCLES : OmSimMetric("parsed cycles") object PARSED_COST : OmSimMetric("parsed cost") object PARSED_AREA : OmSimMetric("parsed area") object PARSED_INSTRUCTIONS : OmSimMetric("parsed instructions") object CYCLES : OmSimMetric("cycles") object COST : OmSimMetric("cost") object AREA : OmSimMetric("area") object INSTRUCTIONS : OmSimMetric("instructions") class INSTRUCTIONS_WITH_HOTKEY(hotkeys: String) : OmSimMetric("instructions with hotkey $hotkeys") object EXECUTED_INSTRUCTIONS : OmSimMetric("executed instructions") object INSTRUCTION_EXECUTION : OmSimMetric("instruction executions") class INSTRUCTION_EXECUTIONS_WITH_HOTKEY(hotkeys: String) : OmSimMetric("instruction executions with hotkey $hotkeys") object INSTRUCTION_TAPE_PERIOD : OmSimMetric("instruction tape period") object HEIGHT : OmSimMetric("height") object WIDTH_TIMES_TWO : OmSimMetric("width*2") object OMNI_HEIGHT : OmSimMetric("omniheight") object OMNI_WIDTH_TIMES_TWO : OmSimMetric("omniwidth*2") object HEIGHT_AT_0_DEGREES : OmSimMetric("height at 0 degrees") object HEIGHT_AT_60_DEGREES : OmSimMetric("height at 60 degrees") object HEIGHT_AT_120_DEGREES : OmSimMetric("height at 120 degrees") object WIDTH_TIMES_TWO_AT_0_DEGREES : OmSimMetric("width*2 at 0 degrees") object WIDTH_TIMES_TWO_AT_60_DEGREES : OmSimMetric("width*2 at 60 degrees") object WIDTH_TIMES_TWO_AT_120_DEGREES : OmSimMetric("width*2 at 120 degrees") object MINIMUM_HEXAGON : OmSimMetric("minimum hexagon") // object THROUGHPUT_CYCLES : OmSimMetric("throughput cycles") object PER_REPETITION_CYCLES : OmSimMetric("per repetition cycles") // object THROUGHPUT_OUTPUTS : OmSimMetric("throughput outputs") object PER_REPETITION_OUTPUTS : OmSimMetric("per repetition outputs") object PER_REPETITION_AREA : OmSimMetric("per repetition area") object PER_REPETITION_SQUARED_AREA : OmSimMetric("per repetition^2 area") object THROUGHPUT_WASTE : OmSimMetric("throughput waste") class PRODUCT_N_METRIC(n: Int, metric: OmSimMetric) : OmSimMetric("product $n ${metric.id}") class CYCLE_N_METRIC(n: Int, metric: OmSimMetric) : OmSimMetric("cycle $n ${metric.id}") object REACHES_STEADY_STATE : OmSimMetric("reaches steady state") class STEADY_STATE(metric: OmSimMetric) : OmSimMetric("steady state ${metric.id}") class PARTS_OF_TYPE(partType: PartType) : OmSimMetric("parts of type ${partType.id}") object ATOMS_GRABBED : OmSimMetric("atoms grabbed") class ATOMS_GRABBED_OF_TYPE(atomType: AtomType) : OmSimMetric("atoms grabbed of type ${atomType.id}") object NUMBER_OF_TRACK_SEGMENTS : OmSimMetric("number of track segments") object NUMBER_OF_ARMS : OmSimMetric("number of arms") object MAXIMUM_ABSOLUTE_ARM_ROTATION : OmSimMetric("maximum absolute arm rotation") object OVERLAP : OmSimMetric("overlap") object DUPLICATE_REAGENTS : OmSimMetric("duplicate reagents") object DUPLICATE_PRODUCTS : OmSimMetric("duplicate products") object MAXIMUM_TRACK_GAP_POW_2 : OmSimMetric("maximum track gap^2") object VISUAL_LOOP_START_CYCLE : OmSimMetric("visual loop start cycle") object VISUAL_LOOP_END_CYCLE : OmSimMetric("visual loop end cycle") } @Suppress("Unused") enum class PartType(val id: String) { ARM1("arm1"), ARM2("arm2"), ARM3("arm3"), ARM6("arm6"), PISTON("piston"), VAN_BERLOS_WHEEL("baron"), BONDER("bonder"), MULTI_BONDER("bonder-speed"), TRIPLEX_BONDER("bonder-prisma"), UNBONDER("unbonder"), CALCIFICATION("glyph-calcification"), DUPLICATION("glyph-duplication"), PROJECTION("glyph-projection"), PURIFICATION("glyph-purification"), ANIMISMUS("glyph-life-and-death"), DISPOSAL("glyph-disposal"), UNIFICATION("glyph-unification"), DISPERSION("glyph-dispersion"), EQUILIBRIUM("glyph-marker"), INPUT("input"), OUTPUT("out-std"), POLYMER("out-rep"), TRACK("track"), CONDUIT("pipe") } @Suppress("Unused") enum class AtomType(val id: String) { SALT("salt"), AIR("air"), EARTH("earth"), FIRE("fire"), WATER("water"), QUICKSILVER("quicksilver"), GOLD("gold"), SILVER("silver"), COPPER("copper"), IRON("iron"), TIN("tin"), LEAD("lead"), VITAE("vitae"), MORS("mors"), QUINTESSENCE("quintessence"), }
5
Java
6
3
39b8ff6e6b26e7b12f4ab66e44368a954ad99ef2
5,157
zachtronics-leaderboard-bot
Apache License 2.0
koin-projects/koin-core/src/main/kotlin/org/koin/ext/InjectProperty.kt
akram09
187,230,273
true
{"AsciiDoc": 5, "Markdown": 53, "Text": 3, "Ignore List": 6, "Gradle": 27, "Shell": 9, "Java Properties": 2, "Batchfile": 1, "INI": 9, "XML": 54, "Kotlin": 267, "Java": 6, "HTML": 2, "CSS": 1, "JavaScript": 2, "Proguard": 1, "YAML": 1}
package org.koin.ext import org.koin.core.Koin import org.koin.core.context.KoinContextHandler import org.koin.core.scope.Scope import kotlin.reflect.KMutableProperty0 inline fun <reified T> KMutableProperty0<T>.inject() { set(KoinContextHandler.get().get()) } inline fun <reified T> KMutableProperty0<T>.inject(koin: Koin) { set(koin.get()) } inline fun <reified T> KMutableProperty0<T>.inject(scope: Scope) { set(scope.get()) }
0
Kotlin
0
1
654068b498ad5d47f8aa4cef016265263f6d32b8
445
koin
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/module/Stateful.kt
WHHSFTC
298,673,129
false
null
package org.firstinspires.ftc.teamcode.module import com.qualcomm.robotcore.hardware.CRServo class Stateful<B, W: Stateful.Wrap<B>>(val module: Module<B>, initial: W): Module<W> { override var state: W = initial set(value) { module(value.v) field = value } interface Wrap<B> { val v: B } }
1
null
1
5
e2297d983c7267ce6e5c30f330393ba2d47288bf
352
20-21_season
MIT License
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRStateDataProvider.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.provider import com.intellij.openapi.Disposable import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.CalledInAny import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityState import java.util.concurrent.CompletableFuture interface GHPRStateDataProvider { @RequiresEdt fun loadMergeabilityState(): CompletableFuture<GHPRMergeabilityState> @RequiresEdt fun reloadMergeabilityState() @RequiresEdt fun addMergeabilityStateListener(disposable: Disposable, listener: () -> Unit) @RequiresEdt fun loadMergeabilityState(disposable: Disposable, consumer: (CompletableFuture<GHPRMergeabilityState>) -> Unit) { addMergeabilityStateListener(disposable) { consumer(loadMergeabilityState()) } consumer(loadMergeabilityState()) } @CalledInAny fun close(progressIndicator: ProgressIndicator): CompletableFuture<Unit> @CalledInAny fun reopen(progressIndicator: ProgressIndicator): CompletableFuture<Unit> @RequiresEdt fun markReadyForReview(progressIndicator: ProgressIndicator): CompletableFuture<Unit> @CalledInAny fun merge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String): CompletableFuture<Unit> @CalledInAny fun rebaseMerge(progressIndicator: ProgressIndicator, currentHeadRef: String): CompletableFuture<Unit> @CalledInAny fun squashMerge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String): CompletableFuture<Unit> }
233
null
4912
15,461
9fdd68f908db0b6bb6e08dc33fafb26e2e4712af
1,817
intellij-community
Apache License 2.0
compiler/testData/codegen/boxInline/smap/kt23369.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FILE: 1+a.kt package test inline fun inlineFun(lambda: () -> String): String { return lambda() } // FILE: 2.kt import test.* fun box(): String { return inlineFun { "OK" } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
188
kotlin
Apache License 2.0
api/src/test/kotlin/com/openlattice/linking/EntityLinkingFeaturesSerializationTest.kt
openlattice
101,697,464
false
{"Git Config": 1, "Gradle Kotlin DSL": 4, "XML": 6, "JSON": 3, "HTML": 4, "INI": 11, "Shell": 23, "Text": 248, "Ignore List": 8, "Batchfile": 10, "Markdown": 13, "Gradle": 21, "YAML": 68, "Kotlin": 752, "Java": 556, "Java Properties": 8, "CODEOWNERS": 5, "Mustache": 8, "PLpgSQL": 7, "SQL": 14, "OASv3-yaml": 1}
package com.openlattice.linking import com.openlattice.data.EntityDataKey import com.openlattice.mapstores.TestDataFactory import com.geekbeast.serializer.serializer.AbstractJacksonSerializationTest import java.util.* import kotlin.random.Random class EntityLinkingFeaturesSerializationTest : AbstractJacksonSerializationTest<EntityLinkingFeatures>() { override fun getSampleData(): EntityLinkingFeatures { return EntityLinkingFeatures( EntityLinkingFeedback( EntityKeyPair( EntityDataKey(UUID.randomUUID(), UUID.randomUUID()), EntityDataKey(UUID.randomUUID(), UUID.randomUUID())), Random.nextBoolean()), mapOf( TestDataFactory.randomAlphabetic(5) to Random.nextDouble(), TestDataFactory.randomAlphabetic(5) to Random.nextDouble()) ) } override fun getClazz(): Class<EntityLinkingFeatures> { return EntityLinkingFeatures::class.java } }
1
Kotlin
3
4
b836eea0a17128089e0dbe6719495413b023b2fb
1,071
openlattice
Apache License 2.0
app/src/main/java/com/perol/asdpl/pixivez/ui/home/trend/RankingMAdapter.kt
ultranity
258,955,010
false
null
/* * MIT License * * Copyright (c) 2020 ultranity * Copyright (c) 2019 Perol_Notsfsssf * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE */ package com.perol.asdpl.pixivez.ui.home.trend import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.perol.asdpl.pixivez.core.PicListFragment import com.perol.asdpl.pixivez.core.TAG_TYPE import com.perol.asdpl.pixivez.objects.WeakValueHashMap class RankingMAdapter(fragment: Fragment, private var isR18on: Boolean) : FragmentStateAdapter(fragment) { private val modeList = arrayOf( "day", "day_male", "day_female", "day_ai", "week_original", "week_rookie", "week", "month", "day_manga", "day_r18", "day_male_r18", "day_female_r18", "week_r18", "week_r18g" ) override fun getItemCount() = if (isR18on) modeList.size else modeList.size - 5 //TODO: LRU cache val fragments = WeakValueHashMap<Int, PicListFragment>(3) override fun createFragment(position: Int): Fragment { if (fragments[position] == null) { fragments[position] = PicListFragment.newInstance( TAG_TYPE.Rank.name, position, mutableMapOf( "mode" to modeList[position] ) ) } return fragments[position]!! } /* override fun getItemCount() = modelist.size override fun createFragment(position: Int) = RankingMFragment.newInstance(modelist[position])*/ }
6
null
33
692
d5caf81746e4f16a1af64d45490a358fd19aec1a
2,498
Pix-EzViewer
MIT License
app/src/main/kotlin/li/ruoshi/nextday/models/HttpGzipInterceptor.kt
iceboundrock
15,003,541
false
null
package li.ruoshi.nextday.models import android.text.TextUtils import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import okhttp3.internal.http.RealResponseBody import okio.GzipSource import okio.Okio /** * Created by ruoshili on 1/10/16. */ class HttpGzipInterceptor : Interceptor { companion object { const val ContentEncoding = "Content-Encoding" const val AcceptEncoding = "Accept-Encoding" } override fun intercept(chain: Interceptor.Chain?): Response? { if (chain == null) { return null } val request = chain.request() var newReq: Request = request; if (TextUtils.isEmpty(request.header(AcceptEncoding))) { newReq = request .newBuilder() .addHeader(AcceptEncoding, "gzip, deflate") .build() } val resp = chain.proceed(newReq) return unzipRespBody(resp) } private fun unzipRespBody(response: Response): Response { val ce = response.header(ContentEncoding, "") if (!"gzip".equals(ce, ignoreCase = true)) { return response; } val body = response.body() ?: return response val responseBody = GzipSource(body.source()); val strippedHeaders = response.headers().newBuilder() .removeAll(ContentEncoding) .removeAll("Content-Length") .build(); return response.newBuilder() .headers(strippedHeaders) .body(RealResponseBody(strippedHeaders, Okio.buffer(responseBody))) .build(); } }
2
Kotlin
0
0
217c7db7d3bbf7675680d3455d6c6ef35d75266e
1,667
nextday-for-android
Apache License 2.0
app/src/main/java/br/com/levez/challenge/delivery/model/Delivery.kt
levezf
599,782,558
false
null
package br.com.levez.challenge.delivery.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "deliveries", indices = [Index(value = ["id", "external_id"], unique = true)] ) data class Delivery( @ColumnInfo("external_id") val externalId: String, @ColumnInfo("number_of_packages") val numberOfPackages: String, @ColumnInfo("deadline") val deadline: String, @ColumnInfo("customer_name") val customerName: String, @ColumnInfo("customer_cpf") val customerCpf: String, @ColumnInfo("address_zip_code") val addressZipCode: String, @ColumnInfo("address_state") val addressState: String, @ColumnInfo("address_city") val addressCity: String, @ColumnInfo("address_neighborhood") val addressNeighborhood: String, @ColumnInfo("address_street") val addressStreet: String, @ColumnInfo("address_number") val addressNumber: String, @ColumnInfo("address_complement") val addressComplement: String, @PrimaryKey(autoGenerate = true) val id: Long? = null, ) { fun isNewUser() = id == null }
0
Kotlin
0
0
7aa737484d7557a8dd6fa39ee1b09fc0f3bf6853
1,181
delivery-challenge
MIT License
src/main/java/assembly/DependencyProcessor.kt
ihsmarkitoss
230,111,712
false
null
package assembly import assembly.models.AssemblyDependencies import assembly.models.JarDependency import assembly.models.LocalResource import assembly.models.MavenDependency import javassist.bytecode.ClassFile import javassist.bytecode.ConstPool import persisted.HandlerInformation import java.io.DataInputStream import java.io.File import java.io.InputStream import java.util.HashSet import java.util.jar.JarFile import java.util.jar.JarOutputStream class DependencyProcessor( private val mavenDependencies: Map<String, MavenDependency>, private val localResources: Map<String, String>, private val targetDirectory: String, private val addEntireJars: Boolean ) { private val alreadyProcessed: MutableMap<String, MutableSet<String>> = mutableMapOf() fun determineDependencies(handlers: Iterable<Pair<HandlerInformation, JarOutputStream>>): AssemblyDependencies { val assemblyDependencies = AssemblyDependencies() handlers.forEach { pair -> val handler = pair.first val targetJar = pair.second val handlerStream = getClassFile(classPathToJarPath(handler.handlerClassPath))!! val dependencies = getDependenciesOfClassFile(handlerStream) dependencies.addAll( handler.usesClients.flatMap { it.toClassPaths() }.map { classPathToJarPath(it) } ) val jarPathExtraDependencies = handler.extraDependencies.map { classPathToJarPath(it) }.toSet() dependencies.addAll(jarPathExtraDependencies) val stringDependencies = getRecursiveDependencies(dependencies, handler.usesClients) dependencies.addAll(stringDependencies) addToAssemblyDependencies(dependencies, jarPathExtraDependencies, assemblyDependencies, targetJar) } return assemblyDependencies } private fun addToAssemblyDependencies(dependencies: Set<String>, forceEntireJar: Set<String>, assemblyDependencies: AssemblyDependencies, targetJar: JarOutputStream) { //: Pair<Map<String, EntireJarDependency>, Set<String>> { val alreadyProcessedMavenDependency: MutableSet<MavenDependency> = mutableSetOf() for (dependency in dependencies) { val mavenDependency = mavenDependencies[dependency] if (mavenDependency != null) { val jarFilePath = mavenDependency.filePath val externalDependency = assemblyDependencies.externalDependencies.getOrPut(jarFilePath) { JarDependency() } if (forceEntireJar.contains(dependency) || addEntireJars) { externalDependency.allClasses.add(targetJar) } else if (!externalDependency.allClasses.contains(targetJar)) { externalDependency.specificClasses.getOrPut(dependency) { mutableListOf() }.add(targetJar) if (!alreadyProcessedMavenDependency.contains(mavenDependency)) { mavenDependency.requiredClasses.forEach { val specificTargets = externalDependency.specificClasses.getOrPut(it) { mutableListOf() } specificTargets.add(targetJar) } } } alreadyProcessedMavenDependency.add(mavenDependency) } else { if (localResources.contains(dependency)) { assemblyDependencies.localResources.getOrPut(dependency) { LocalResource(localResources[dependency]!!) }.targets.add(targetJar) } else { assemblyDependencies.localDependencies.getOrPut(dependency) { mutableListOf() }.add(targetJar) } } } } //Expects JAR path private fun getClassFile(path: String): InputStream? { if (path.startsWith("java") || !path.endsWith(".class")) return null val operatingSystemPath = path.replace('/', File.separatorChar) val projectFilePath = targetDirectory + File.separator + operatingSystemPath val projectFile = File(projectFilePath) if (projectFile.exists()) return projectFile.inputStream() val jarFilePath = mavenDependencies[path]?.filePath ?: return null val jarFile = JarFile(jarFilePath) val jarEntry = jarFile.getJarEntry(path) if (jarEntry.isDirectory) return null return jarFile.getInputStream(jarEntry) } private fun getOtherFile(path: String): InputStream? { val jarFilePath = mavenDependencies[path]?.filePath ?: return null val jarFile = JarFile(jarFilePath) val jarEntry = jarFile.getJarEntry(path) if (jarEntry.isDirectory) return null return jarFile.getInputStream(jarEntry) } //Return JAR path of files private fun getRecursiveDependencies(jarPaths: Set<String>, clients: Set<ClientType>): Set<String> { val dependencies: MutableSet<String> = mutableSetOf() for (jarPath in jarPaths) { if (alreadyProcessed.contains(jarPath)) { dependencies.addAll(alreadyProcessed[jarPath]!!) continue } val results = mutableSetOf<String>() alreadyProcessed[jarPath] = results //This is required if clients are declared in fields they do not throw class not found errors if the client is not used val classInputStream = getClassFile(jarPath) val directDependencies = if (classInputStream != null) { getDependenciesOfClassFile(classInputStream) } else { val handlerInputStream = getOtherFile(jarPath) ?: continue getDependenciesOfHandlerFile(handlerInputStream) } val recursiveDependencies = getRecursiveDependencies(directDependencies, clients) results.addAll(directDependencies) results.addAll(recursiveDependencies) dependencies.addAll(results) } return dependencies } // Returns a set of possible dependencies // Dependencies of form 'path.path.path.ClassName' (if class) // Or path/path/path/file.extension (if other type of file) private fun getDependenciesOfClassFile(inputStream: InputStream): MutableSet<String> { val cf = ClassFile(DataInputStream(inputStream)) val constPool = cf.constPool val dependencies = HashSet<String>() for (ix in 1 until constPool.size) { val constTag = constPool.getTag(ix) if (constTag == ConstPool.CONST_Class) { //Always a class val constClass = classPathToJarPath(constPool.getClassInfo(ix)) dependencies.add(constClass) } else if (constTag == ConstPool.CONST_String) { //Could be any kind of file val possibleDependency = constPool.getStringInfo(ix) if (possibleDependency != null) { addAnyFileToDependencySet(possibleDependency, dependencies) } } else if (constTag == ConstPool.CONST_Utf8) { //Could be any kind of file val desc = constPool.getUtf8Info(ix) addAnyFileToDependencySet(desc, dependencies) addAnyClassToDependencySet(desc, dependencies) } else { val descriptorIndex = when (constTag) { ConstPool.CONST_NameAndType -> constPool.getNameAndTypeDescriptor(ix) ConstPool.CONST_MethodType -> constPool.getMethodTypeInfo(ix) else -> -1 } if (descriptorIndex != -1) { //Guaranteed to be class val desc = constPool.getUtf8Info(descriptorIndex) addAnyClassToDependencySet(desc, dependencies) } } } inputStream.close() return dependencies } private fun getDependenciesOfHandlerFile(inputStream: InputStream): Set<String> { val dependencies = HashSet<String>() inputStream.bufferedReader().useLines { lines -> lines.forEach { addAnyFileToDependencySet(it, dependencies) } } return dependencies } private fun addAnyClassToDependencySet(desc: String, dependencies: MutableSet<String>) { var p = 0 while (p < desc.length) { //Will always be a class (path/path/path/class) if (desc[p] == 'L') { val semiColonIndex = desc.indexOf(';', p) if (semiColonIndex < 0) break val typeIndex = desc.indexOf('<', p) val endIndex = if (typeIndex in (p + 1) until semiColonIndex) { typeIndex } else { semiColonIndex } val toAdd = desc.substring(p + 1, endIndex) + ".class" dependencies.add(toAdd) p = endIndex } p++ } } private fun addAnyFileToDependencySet(possibleDependency: String, dependencies: MutableSet<String>) { val noLeadingSeparator = removeLeadingSeparator(possibleDependency) if (mavenDependencies.containsKey(noLeadingSeparator) || localResources.containsKey(noLeadingSeparator)) { dependencies.add(noLeadingSeparator) } val transformedClassPath = classPathToJarPath(noLeadingSeparator) if (mavenDependencies.containsKey(transformedClassPath)) { dependencies.add(transformedClassPath) } } private fun removeLeadingSeparator(path: String): String { return if (path.startsWith('/')) { path.substring(1, path.length) } else { path } } private fun classPathToJarPath(classPath: String): String { return classPath.replace('.', '/') + ".class" } }
2
null
1
1
2fcb6d418f78618ccd15a8d9296797d85d26224f
9,987
nimbus-deployment
Apache License 2.0
Navigation/Filter.kt
Fernando922
366,197,277
false
null
fun main() { val words = listOf("about", "acute", "awesome", "balloon", "best", "brief", "class", "coffee", "creative") val filteredWords = words.filter { it.startsWith("c", ignoreCase = true)} .shuffled() .take(2) .sorted() println(filteredWords) }
0
Kotlin
0
0
75292ebb0d4ce99037441da000f3f53b3a18d270
272
learn-kotlin
Open Market License
auth-foundation/src/test/java/com/okta/authfoundation/client/OAuth2ClientResultTest.kt
okta
445,628,677
false
{"Kotlin": 846264, "Shell": 884}
/* * Copyright 2022-Present Okta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.okta.authfoundation.client import com.google.common.truth.Truth.assertThat import org.junit.Test import kotlin.test.assertFailsWith internal class OidcClientResultTest { @Test fun testGetOrThrowReturnsEncapsulatedValue() { val result = OidcClientResult.Success("Hi") assertThat(result.getOrThrow()).isEqualTo("Hi") } @Test fun testGetOrThrowThrowsEncapsulatedException() { val result = OidcClientResult.Error<String>(IllegalStateException("Expected Error")) val exception = assertFailsWith<IllegalStateException> { result.getOrThrow() } assertThat(exception).hasMessageThat().isEqualTo("Expected Error") } }
15
Kotlin
11
33
72776583e6e4066d576f36b4d73ed83216e61584
1,301
okta-mobile-kotlin
Apache License 2.0
app/src/main/java/com/breezefsmp12/features/addshop/api/typeList/TypeListRepoProvider.kt
DebashisINT
652,463,111
false
{"Kotlin": 14144630, "Java": 1003051}
package com.breezefsmp12.features.addshop.api.typeList /** * Created by Saikat on 22-Jun-20. */ object TypeListRepoProvider { fun provideTypeListRepository(): TypeListRepo { return TypeListRepo(TypeListApi.create()) } }
0
Kotlin
0
0
073c66529db58399402a646905c147cbc9b5ecd6
239
StepUpP12
Apache License 2.0
app/src/main/java/uk/nhs/nhsx/covid19/android/app/state/CalculateExpirationNotificationTime.kt
coderus-ltd
369,240,870
true
{"Kotlin": 3133494, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.state import java.time.Instant import java.time.LocalDate import java.time.ZoneId import javax.inject.Inject class CalculateExpirationNotificationTime @Inject constructor() { operator fun invoke( expiryDate: LocalDate, zoneId: ZoneId ): Instant = expiryDate .atStartOfDay() .atZone(zoneId) .minusHours(3) .toInstant() }
0
null
0
0
b74358684b9dbc0174890db896b93b0f7c6660a4
443
covid-19-app-android-ag-public
MIT License
src/main/kotlin/dev/t7e/routes/v1/TagRouter.kt
Sports-day
589,245,462
false
{"Kotlin": 215307, "Dockerfile": 330}
package dev.t7e.routes.v1 import dev.t7e.models.OmittedTag import dev.t7e.plugins.Role import dev.t7e.plugins.withRole import dev.t7e.services.TagService import dev.t7e.utils.DataMessageResponse import dev.t7e.utils.DataResponse import dev.t7e.utils.respondOrInternalError import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* /** * Created by testusuke on 2023/10/02 * @author testusuke */ fun Route.tagRouter() { route("/tags") { withRole(Role.USER) { /** * Get all tags */ get { val tags = TagService.getAll() call.respond(HttpStatusCode.OK, DataResponse(tags.getOrDefault(listOf()))) } withRole(Role.ADMIN) { /** * Create new tag */ post { val requestBody = call.receive<OmittedTag>() TagService .create(requestBody) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "created tag", it, ), ) } } } route("/{id?}") { /** * Get tag by id */ get { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") TagService .getById(id) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataResponse(it), ) } } withRole(Role.ADMIN) { /** * Update tag */ put { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") val requestBody = call.receive<OmittedTag>() TagService .update(id, requestBody) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "update tag", it, ), ) } } /** * Delete tag */ delete { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") TagService .deleteById(id) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "deleted tag", it, ), ) } } } } } } }
10
Kotlin
0
0
a25bb31c807b8ffb939fb869a25ab11f2db3f8cd
3,823
SportsDayAPI
Apache License 2.0
graphene-writer/src/main/kotlin/com/graphene/writer/config/StatsProperty.kt
graphene-monitoring
208,468,543
false
null
package com.graphene.writer.config import java.net.InetAddress import java.net.UnknownHostException import javax.annotation.PostConstruct import org.slf4j.LoggerFactory import org.springframework.boot.context.properties.ConfigurationProperties /** * @author <NAME> */ @ConfigurationProperties(prefix = "graphene.writer.stats") class StatsProperty { var interval: Int = 0 var tenant: String? = null var hostname: String? = null var isLog: Boolean = false @PostConstruct fun init() { logger.info("Load Graphene stats configuration : {}", toString()) } init { try { hostname = InetAddress.getLocalHost().hostName } catch (e: UnknownHostException) { hostname = "unknown" } } override fun toString(): String { return "StatsProperty{" + "interval=" + interval + ", tenant='" + tenant + '\''.toString() + ", hostname='" + hostname + '\''.toString() + ", log=" + isLog + '}'.toString() } companion object { private val logger = LoggerFactory.getLogger(StatsProperty::class.java) } }
8
null
4
34
6bba2e000a744411322dfa19769ad8608463f6cc
1,076
graphene
MIT License
app/src/main/java/com/koma/video/search/SearchPresenter.kt
komamj
135,701,576
false
{"Kotlin": 177378}
/* * Copyright 2018 koma_mj * * 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.koma.video import com.koma.video.data.source.VideoRepository import com.koma.video.util.LogUtils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject class VideosPresenter @Inject constructor( private val view: VideosContract.View, private val repository: VideoRepository ) : VideosContract.Presenter { private val disposables by lazy { CompositeDisposable() } init { view.presenter = this } override fun subscribe() { LogUtils.d(TAG, "subscribe") loadVideoEntries() } override fun unSubscribe() { LogUtils.d(TAG, "unSubscribe") disposables.clear() } override fun loadVideoEntries() { if (view.isActive) { view.setLoadingIndicator(true) } val disposable: Disposable = repository.getVideoEntries() .delay(1000, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy(onNext = { if (view.isActive) { view.showVideoEntries(it) view.setEmptyIndicator(it.isEmpty()) } }, onError = { LogUtils.e(TAG, "loadVideoEntries error : " + it.message) if (view.isActive) { view.setLoadingIndicator(false) } }, onComplete = { if (view.isActive) { view.setLoadingIndicator(false) } }) disposables.add(disposable) } companion object { private const val TAG = "VideosPresenter" } }
0
Kotlin
1
1
be4142c9126b0e74cd1d8d1dcaae5285505294d8
2,508
Video
Apache License 2.0
util/src/main/kotlin/org/rsmod/util/runelite/PluginHubConstants.kt
dodian-community
457,389,140
false
{"Kotlin": 532088}
package io.nozemi.runescape.tools.runelite object PluginHubConstants { const val PLUGIN_HUB_BASE_PATH = "./plugin-hub" const val PLUGIN_HUB_KEY_PATH = "keys" const val PLUGIN_HUB_PRIVATE_KEY = "private.pem" const val PLUGIN_HUB_PUBLIC_KEY = "externalplugins.crt" const val PLUGIN_HUB_DUMMY_TEXT_FILE = "dummy-text.txt" const val PLUGIN_HUB_OUTPUT_DIRECTORY = "output" }
6
Kotlin
3
3
f3b341a724016c699e620dd75db121b364261e41
394
osrs-ub3r-monorepo
ISC License
app/src/test/java/com/example/tempconverter/business/TemperatureCelciusBusinessTest.kt
rabsouza
211,225,020
false
null
package com.example.tempconverter.business import com.example.tempconverter.model.Temperature import com.example.tempconverter.model.Type import com.example.tempconverter.model.format import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertThat import org.junit.Test class TemperatureCelciusBusinessTest { @Test fun `calcule - converter de 0 ºC para 32 ºF`() { val temperature = Temperature(0.0, Type.CELCIUS) val result = TemperatureCelciusBusiness().calcule(temperature) val expected = 32.0 assertThat(result.format(2), equalTo(expected.format(2))) } }
0
Kotlin
0
0
53752da910155945341e6560f2155cec1f27ea5f
650
TempConverter
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/codecs/VideoFrameOutputCallback.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.codecs typealias VideoFrameOutputCallback = ( output: VideoFrame, ) -> Unit
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
138
types-kotlin
Apache License 2.0
src/unixLikeTest/kotlin/process/CommandTest.kt
kgit2
553,675,958
false
null
package process import com.kgit2.process.Command import com.kgit2.process.Stdio import kotlin.test.Test import kotlin.test.assertTrue class CommandTest { fun outputWithExitCodeTest() { @Test fun tempTest() { val executor = Command("ping") .arg("-c") .args("5", "localhost") .stdout(Stdio.Pipe) .spawn() val stdoutReader = executor.getChildStdout()!! val sb = StringBuilder() stdoutReader.lines().forEach { // do something sb.appendLine(it) } val exitStatus = runCatching { executor.wait() } assertTrue(exitStatus.isSuccess) } } @Test fun pipeTest() { val child1 = Command("zsh") .args("-c", "unset count; count=0; while ((count < 10)) do ((count += 1));echo from child1:${"$"}count;done") .stdout(Stdio.Pipe) .spawn() val child2 = Command("zsh") .args("-c", "while read line; do echo from child2:${"$"}line; done") .stdin(Stdio.Pipe) .stdout(Stdio.Inherit) .spawn() val child1StdoutReader = child1.getChildStdout()!! val child2StdinWriter = child2.getChildStdin()!! child1StdoutReader.lines().forEach { child2StdinWriter.appendLine(it) } child2StdinWriter.close() } }
2
Kotlin
0
23
842dbc8bfccfb04baedcbff6d77cc33e468d6bbe
1,474
kommand
Apache License 2.0
app/src/main/java/com/amrdeveloper/currencyexchange/data/HistoryResponse.kt
AmrDeveloper
336,627,139
false
null
package com.amrdeveloper.currencyexchange.data import com.google.gson.annotations.SerializedName data class HistoryResponse( @SerializedName("rates") val rates: Map<String, Map<String, Double>>, @SerializedName("base") val base: String )
0
Kotlin
0
1
61a9d2c33b486c10514c55200b969ced40cd0d8b
258
CurrencyExchange
MIT License
buildSrc/src/main/kotlin/Modules.kt
vitorhugods
327,687,713
false
null
object Modules { object Android { const val APP = ":app" const val BASE = ":base" const val BASE_TEST = ":base-test" const val TICKER = ":ticker" } object JVM { const val BLOCKCHAIN_CLIENT = ":blockchain-api-client" } }
0
Kotlin
0
1
53f3a26e8d7b9b49e809e5b1d5969b71f5d120b7
277
android-crypto-tracker
Apache License 2.0
game/src/main/kotlin/gg/rsmod/game/message/handler/ResumePNameDialogHandler.kt
2011Scape
578,880,245
false
null
package gg.rsmod.game.message.handler import gg.rsmod.game.message.MessageHandler import gg.rsmod.game.message.impl.ResumePNameDialogMessage import gg.rsmod.game.model.World import gg.rsmod.game.model.entity.Client import gg.rsmod.game.model.queue.QueueTask /** * @author Tom <[email protected]> */ class ResumePNameDialogHandler : MessageHandler<ResumePNameDialogMessage> { override fun handle(client: Client, world: World, message: ResumePNameDialogMessage) { val name = message.name val target = world.getPlayerForName(name) log(client, "Player username input dialog: username=%s", name) client.queues.submitReturnValue(target ?: QueueTask.EMPTY_RETURN_VALUE) } }
36
null
138
32
da66bb6d68ebae531ee325b909a6536e798b1144
714
game
Apache License 2.0
app/src/main/java/com/commit451/gitlab/extension/TextInputLayout.kt
Commit451
39,787,724
false
null
package com.commit451.gitlab.extension import com.google.android.material.textfield.TextInputLayout import com.commit451.gitlab.R fun TextInputLayout.checkValid(): Boolean { if (editText!!.text.isNullOrEmpty()) { error = resources.getString(R.string.required_field) return false } else { error = null return true } } fun TextInputLayout.text(): String { return editText!!.text.toString() }
6
Kotlin
27
248
504b5311c00ac2b87ba728d74925c6f46e6c5781
441
LabCoat
Apache License 2.0
domain/src/main/java/antuere/domain/dto/mental_tips/MentalTipsCategory.kt
antuere
526,507,044
false
null
package antuere.domain.dto.mental_tips class MentalTipsCategory( val categoryName: TipsCategoryName, val iconRes: Int, val textRes: Int )
1
Kotlin
1
1
dccddea7bf36f0910b87c09becd0de2d74ac26b2
151
HowAreYou
Apache License 2.0
app/src/main/java/br/com/fiap/hubappworld/screens/hub/HubScreen.kt
guilhermefsilv4
847,478,184
false
{"Kotlin": 24532}
package br.com.fiap.hubappworld.screens.hub import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import br.com.fiap.hubappworld.R import br.com.fiap.hubappworld.components.CardHub import br.com.fiap.hubappworld.functions.navigate @Composable fun HubScreen(navController: NavController) { Box( modifier = Modifier .fillMaxSize() .background(Color(0xFFD4DCFF)), contentAlignment = Alignment.Center ) { Column(verticalArrangement = Arrangement.spacedBy((-35).dp)) { CardHub( painterResource(id = R.drawable.clima), "Icone do clima", handleClick = { navigate(navController, "clima") } ) // CardHub(painterResource(id = R.drawable.monetization_on_24), "Icone de dinheiro") } } }
0
Kotlin
0
0
dac9cf6bf4d954cea00f8857e89282edaf232b81
1,303
hub-app-world
MIT License
app/src/main/java/br/com/fiap/hubappworld/screens/hub/HubScreen.kt
guilhermefsilv4
847,478,184
false
{"Kotlin": 24532}
package br.com.fiap.hubappworld.screens.hub import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import br.com.fiap.hubappworld.R import br.com.fiap.hubappworld.components.CardHub import br.com.fiap.hubappworld.functions.navigate @Composable fun HubScreen(navController: NavController) { Box( modifier = Modifier .fillMaxSize() .background(Color(0xFFD4DCFF)), contentAlignment = Alignment.Center ) { Column(verticalArrangement = Arrangement.spacedBy((-35).dp)) { CardHub( painterResource(id = R.drawable.clima), "Icone do clima", handleClick = { navigate(navController, "clima") } ) // CardHub(painterResource(id = R.drawable.monetization_on_24), "Icone de dinheiro") } } }
0
Kotlin
0
0
dac9cf6bf4d954cea00f8857e89282edaf232b81
1,303
hub-app-world
MIT License
android/src/main/java/org/ergoplatform/android/Preferences.kt
ergoplatform
376,102,125
false
null
package org.ergoplatform.android import android.content.Context import android.content.SharedPreferences import androidx.appcompat.app.AppCompatDelegate import org.ergoplatform.persistance.* const val KEY_DAYNIGHTMODE = "dayNightMode" const val KEY_APPLOCK = "appLock" class Preferences(context: Context) : PreferencesProvider() { private val prefs: SharedPreferences = context.getSharedPreferences(NAME_SHAREDPREFS, Context.MODE_PRIVATE) override fun getString(key: String, default: String): String { return prefs.getString(key, default) ?: default } override fun saveString(key: String, value: String) { prefs.edit().putString(key, value).apply() } override fun getLong(key: String, default: Long): Long { return prefs.getLong(key, default) } override fun saveLong(key: String, value: Long) { prefs.edit().putLong(key, value).apply() } override fun getFloat(key: String, default: Float): Float { return prefs.getFloat(key, default) } override fun saveFloat(key: String, value: Float) { prefs.edit().putFloat(key, value).apply() } var dayNightMode: Int get() { return prefs.getInt( KEY_DAYNIGHTMODE, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM ) } set(mode) { prefs.edit().putInt(KEY_DAYNIGHTMODE, mode).apply() AppCompatDelegate.setDefaultNightMode(mode) } var enableAppLock: Boolean get() = getBoolean(KEY_APPLOCK, false) set(value) = saveBoolean(KEY_APPLOCK, value) }
16
Kotlin
35
94
b5f6e5176cf780a7437eb3c8447820bd9409c8ac
1,625
ergo-wallet-app
Apache License 2.0
glance/glance-wear-tiles-preview/src/main/java/androidx/glance/wear/tiles/preview/GlanceTileServiceViewAdapter.kt
androidx
256,589,781
false
null
/* * Copyright 2022 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.glance.wear.tiles.preview import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.FrameLayout import androidx.compose.runtime.Composable import androidx.compose.runtime.currentComposer import androidx.compose.ui.unit.DpSize import androidx.core.content.ContextCompat import androidx.glance.wear.tiles.ExperimentalGlanceWearTilesApi import androidx.glance.wear.tiles.compose import androidx.glance.wear.tiles.preview.ComposableInvoker.invokeComposable import androidx.wear.tiles.LayoutElementBuilders import androidx.wear.tiles.TileBuilders import androidx.wear.tiles.TimelineBuilders import kotlinx.coroutines.runBlocking import androidx.wear.tiles.renderer.TileRenderer private const val TOOLS_NS_URI = "http://schemas.android.com/tools" /** * View adapter that renders a glance `@Composable`. The `@Composable` is found by reading the * `tools:composableName` attribute that contains the FQN of the function. */ internal class GlanceTileServiceViewAdapter : FrameLayout { constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(attrs) } @OptIn(ExperimentalGlanceWearTilesApi::class) internal fun init( className: String, methodName: String, ) { val content = @Composable { val composer = currentComposer invokeComposable( className, methodName, composer) } val wearTilesComposition = runBlocking { compose( context = context, size = DpSize.Unspecified, content = content) } // As far as GlanceWearTiles.compose accepts no timeleine argument, assume we only support // [TimelineMode.SingleEntry] val timelineBuilders = TimelineBuilders.Timeline.Builder() timelineBuilders.addTimelineEntry( TimelineBuilders.TimelineEntry.Builder() .setLayout( LayoutElementBuilders.Layout.Builder() .setRoot(wearTilesComposition.layout) .build() ).build() ) val tile = TileBuilders.Tile.Builder() .setTimeline(timelineBuilders.build()) .build() val layout = tile.timeline?.timelineEntries?.get(0)?.layout @Suppress("DEPRECATION") if (layout != null) { val renderer = TileRenderer( context, layout, wearTilesComposition.resources, ContextCompat.getMainExecutor(context) ) { } renderer.inflate(this)?.apply { (layoutParams as LayoutParams).gravity = Gravity.CENTER } } } private fun init(attrs: AttributeSet) { val composableName = attrs.getAttributeValue(TOOLS_NS_URI, "composableName") ?: return val className = composableName.substringBeforeLast('.') val methodName = composableName.substringAfterLast('.') init(className, methodName) } }
26
null
901
4,964
155b4777a51e77095ca1609b1c514d37933d8828
3,919
androidx
Apache License 2.0
src/main/kotlin/org/veupathdb/vdi/lib/common/fs/files.kt
VEuPathDB
619,968,031
false
{"Kotlin": 33308}
package vdi.components.common.util import java.nio.file.Path import kotlin.io.path.ExperimentalPathApi import kotlin.io.path.deleteIfExists import kotlin.io.path.deleteRecursively import kotlin.io.path.isDirectory @OptIn(ExperimentalPathApi::class) inline fun Path.useThenDelete(fn: (path: Path) -> Unit) { try { fn(this) } finally { if (this.isDirectory()) this.deleteRecursively() else this.deleteIfExists() } }
1
Kotlin
0
0
a1dff94719670e71cb0c30a57fb326024e7de1ae
445
vdi-service
Apache License 2.0
projects/src/main/java/com/kingsland/projects/data/repository/ProjectRepository.kt
data-programmer
599,861,493
false
null
package com.kingsland.projects.data.repository import com.kingsland.projects.convertProjectDtoToDomain import com.kingsland.projects.convertToDomain import com.kingsland.projects.data.source.ProjectDataSource import com.kingsland.projects.domain.model.ProjectDomain import com.kingsland.projects.domain.repository.IProjectRepository import javax.inject.Inject class ProjectRepository @Inject constructor( private val projectDataSource: ProjectDataSource ) : IProjectRepository { override fun getAllProjects(): List<ProjectDomain> = projectDataSource.getAllProjects().convertProjectDtoToDomain() override fun getProjectById(projectId: Int): ProjectDomain = projectDataSource.getProjectById(projectId).convertToDomain() override fun insertProject(project: ProjectDomain) { projectDataSource.insertProject(project.convertToDomain()) } override fun updateProject(project: ProjectDomain) { projectDataSource.updateProject(project.convertToDomain()) } override fun deleteProject(project: ProjectDomain) { projectDataSource.deleteProject(project.convertToDomain()) } }
0
Kotlin
0
0
bcd53b9784689e5b60d893248ccc2910b17391e0
1,088
ProjectTrakAndroid
MIT License
studio-idea-plugin/src/main/kotlin/com/evolveum/midpoint/studio/ui/configuration/Utils.kt
Evolveum
208,789,988
false
{"Java": 1203618, "Kotlin": 32896, "XSLT": 30131, "ANTLR": 926, "HTML": 300}
package com.evolveum.midpoint.studio.ui.configuration import com.evolveum.midpoint.schema.constants.ObjectTypes import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.layout.ValidationInfoBuilder import javax.swing.JTextField fun <E> validateNotNull(builder: ValidationInfoBuilder, comp: ComboBox<E>): ValidationInfo? { return builder.run { val value = comp.selectedItem when { value == null -> error("Please fill in value") else -> null } } } fun validateNotBlank(builder: ValidationInfoBuilder, textField: JTextField): ValidationInfo? { return builder.run { val value = textField.text when { value.isNullOrBlank() -> error("Please fill in value") else -> null } } } fun convertObjectTypesListToString(list: List<ObjectTypes>): String { if (list.isEmpty()) { return "" } return list.joinToString { it.value } } fun convertStringToObjectTypesList(value: String): List<ObjectTypes> { if (value.isEmpty()) { return emptyList() } return value .split(",") .filter { it.isNotBlank() } .map(String::trim) .mapNotNull { convertToObjectTypes(it) } .toList() } fun validateTypes(builder: ValidationInfoBuilder, textField: JTextField): ValidationInfo? { return builder.run { val value = textField.text val array = value?.split(",") ?: emptyList() val result = array.stream() .map { it.trim() } .filter { convertToObjectTypes(it) == null } .toList() if (result.isEmpty()) { return null } error("Unknown types: " + result.joinToString { it }) } } fun convertToObjectTypes(item: String): ObjectTypes? { if (item.isBlank()) { return null } for (type in ObjectTypes.values()) { if (type.value.equals(item)) { return type } } return null }
0
Java
3
3
bd5cfc0f2ad37e07c573d4349b6156d107a680d2
2,043
midpoint-studio
Apache License 2.0
app/src/main/java/com/example/easyload/ui/RecyclerViewAdapter.kt
xushanning
279,640,389
false
null
package com.example.easyload.ui import android.content.Context import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.example.easyload.R import com.xu.easyload.EasyLoad /** * @author 言吾許 */ class RecyclerViewAdapter(private val data: List<String>) : RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>() { private var context: Context? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { this.context = parent.context val view = LayoutInflater.from(context).inflate(R.layout.item_recyclerview, parent, false) return MyViewHolder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.showImage(data[position], context!!, position) } class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) { private var img: ImageView = view.findViewById(R.id.img_item) fun showImage(url: String, context: Context, position: Int) { val iLoadService = EasyLoad.initLocal().inject(img) Glide.with(context) .load(url) .addListener(object : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean { return false } override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { iLoadService.showSuccess() println("加载成功$position") return false } }) .into(img) } } }
1
Kotlin
1
6
eb2624d24eb2a59064c85b64728692e0a016e416
2,273
EasyLoad
Apache License 2.0
app/src/main/java/com/alerdoci/marvelsuperheroes/app/components/ShimmerListItem.kt
AlvaroErd
645,667,383
false
{"Kotlin": 807067, "Shell": 2165}
package com.alerdoci.marvelsuperheroes.app.components import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay @Composable fun ShimmerListItem( isLoading: Boolean, contentAfterLoading: @Composable () -> Unit, modifier: Modifier = Modifier ) { if (isLoading) { Row( modifier = modifier ) { Box( modifier = Modifier .size(100.dp) .shimmerEffect() ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.weight(1f) ) { Box( modifier = Modifier .fillMaxWidth() .height(20.dp) .shimmerEffect() ) Spacer(modifier = Modifier.height(16.dp)) Box( modifier = Modifier .fillMaxWidth(0.7f) .height(20.dp) .shimmerEffect() ) } } } else { contentAfterLoading() } } fun Modifier.shimmerEffect(): Modifier = composed { var size by remember { mutableStateOf(IntSize.Zero) } val transition = rememberInfiniteTransition(label = "") val startOffsetX by transition.animateFloat( initialValue = -2 * size.width.toFloat(), targetValue = 2 * size.width.toFloat(), animationSpec = infiniteRepeatable( animation = tween(1000) ), label = "" ) background( brush = Brush.linearGradient( colors = listOf( Color(0xFFB8B5B5), Color(0xFF8F8B8B), Color(0xFFB8B5B5), ), start = Offset(startOffsetX, 0f), end = Offset(startOffsetX + size.width.toFloat(), size.height.toFloat()) ) ) .onGloballyPositioned { size = it.size } } @Preview @Composable fun ShimmerListPreview() { var isLoading by remember { mutableStateOf(true) } LaunchedEffect(key1 = true) { delay(2000) isLoading = false } LazyColumn( modifier = Modifier.fillMaxSize() ) { items(20) { ShimmerListItem( isLoading = isLoading, contentAfterLoading = { Box(modifier = Modifier .size(200.dp) .background(Color.LightGray)) }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) } } }
0
Kotlin
0
4
ca08baa30ab3e5452ecff6243caaa4d4ad89b4bb
3,423
MarvelSuperHeroes
Apache License 2.0
msg-sentiment/src/test/kotlin/dev/number6/sentiment/dagger/TestChannelMessageSentimentComprehensionComponent.kt
Number6App
251,323,476
false
null
package dev.number6.sentiment.dagger import dagger.Component import dev.number6.comprehend.results.PresentableSentimentResults import dev.number6.message.ChannelMessagesToComprehensionResultsFunction import dev.number6.message.ComprehensionResultsConsumer import javax.inject.Singleton @Component(modules = [FakeComprehendModule::class, ChannelMessagesHandlerModule::class, FakeComprehensionResultsModule::class]) @Singleton interface TestChannelMessageSentimentComprehensionComponent : ChannelMessagesSentimentComprehensionComponent { @Singleton fun getResultsFunction(): ChannelMessagesToComprehensionResultsFunction<PresentableSentimentResults> @Singleton fun getConsumer(): ComprehensionResultsConsumer<PresentableSentimentResults> }
9
Kotlin
1
2
f065b79211f6d96f154cb9b2434b13532feb380e
756
Number6
MIT License
buildSrc/src/main/kotlin/versioning/Platforms.kt
soberich
194,400,851
false
null
package versioning /** * To use versions in `plugin {}` block it needs to be in Kotlin not Java */ object Platforms { object Versions { //@formatter:off const val ARROW = "0.11.0-SNAPSHOT" const val BLAZE_JPA = "1.6.0-Alpha2" const val COROUTINES = "1.4.3" const val GUAVA = "30.+" const val IMMUTABLES = "2.8.9-SNAPSHOT" const val JACKSON = "2.11.2"//"2.10.3" const val JAXB = "3.0.0-M4" const val KTOR = "1.4.0" const val MICRONAUT = "1.3.7" const val MICRONAUT_DATA = "+" const val QUARKUS = "1.7.1.Final" const val RESTEASY = "4.1.1.Final" const val JUNIT5 = "5.7.0-M1" const val SPOCK = "2.0-M2-groovy-3.0" //@formatter:on } }
0
Kotlin
0
4
cba5771b0c55b206fd356a3b26ab14bc24bb2788
865
marvel
MIT License
eithernet/test-fixtures/src/jvmMain/java/com/slack/eithernet/test/EitherNetController.jvm.kt
slackhq
297,518,695
false
{"Kotlin": 149282, "Shell": 2526, "Java": 839}
/* * Copyright (C) 2021 Slack Technologies, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.slack.eithernet.test import com.slack.eithernet.ApiResult import com.slack.eithernet.InternalEitherNetApi import kotlin.reflect.KFunction import kotlin.reflect.jvm.javaMethod /** Enqueues a suspended [resultBody]. */ public inline fun <reified T : Any, reified S : Any, reified E : Any> EitherNetController<T> .enqueue( ref: KFunction<ApiResult<S, E>>, noinline resultBody: suspend (args: Array<Any>) -> ApiResult<S, E>, ) { ref.validateTypes() val apiClass = T::class.java check(ref.javaMethod?.declaringClass?.isAssignableFrom(apiClass) == true) { "Given function ${ref.javaMethod?.declaringClass}.${ref.name} is not a member of target API $apiClass." } val key = EndpointKey.create(ref.javaMethod!!) @OptIn(InternalEitherNetApi::class) unsafeEnqueue(key, resultBody) } /** Enqueues a scalar [result] instance. */ public inline fun <reified T : Any, reified S : Any, reified E : Any> EitherNetController<T> .enqueue(ref: KFunction<ApiResult<S, E>>, result: ApiResult<S, E>): Unit = enqueue(ref) { result }
4
Kotlin
26
734
290aae1da9f8ab2b64e035f9b99840d97bc910f4
1,658
EitherNet
Apache License 2.0
app/src/main/java/com/snelling_alaska/kotlin/liquidplanner_android_client/data/daos/ChecklistItemDao.kt
jsnelling
108,856,104
false
null
package com.snelling_alaska.kotlin.liquidplanner_android_client.data.daos import com.snelling_alaska.kotlin.liquidplanner_android_client.data.Api import com.snelling_alaska.kotlin.liquidplanner_android_client.data.dtos.ChecklistItem import com.snelling_alaska.kotlin.liquidplanner_android_client.data.dtos.Treeitem import com.snelling_alaska.kotlin.liquidplanner_android_client.data.dtos.Workspace import com.snelling_alaska.kotlin.liquidplanner_android_client.util.toRequestBody object ChecklistItemDao { fun loadChecklistItems( workspace: Workspace, treeitem: Treeitem, then: (List<ChecklistItem>?) -> Unit ) { Api.shared .get<ChecklistItem>(checklistItemUrl(workspace, treeitem.id)) .fetchA(then) } fun createChecklistItem( workspace: Workspace, treeitem: Treeitem, title: String, then: (ChecklistItem?) -> Unit ) { Api.shared .post<ChecklistItem>(checklistItemUrl(workspace, treeitem.id), mapOf( "checklist_item" to mapOf( ChecklistItem.NAME to title )).toRequestBody(true)) .fetch(then) } fun updateChecklistItem( workspace: Workspace, checklistItem: ChecklistItem, update: Map<String, Any?>, then: (ChecklistItem?) -> Unit ) { Api.shared .put<ChecklistItem>(checklistItemUrl(workspace, checklistItem.item_id, checklistItem.id), mapOf( "checklist_item" to update).toRequestBody(true)) .fetch(then) } fun deleteChecklistItem(workspace: Workspace, checklistItem: ChecklistItem, then: () -> Unit) { Api.shared .delete<ChecklistItem>(checklistItemUrl(workspace, checklistItem.item_id, checklistItem.id)) .fetch { then() } } fun checklistItemUrl(workspace: Workspace, tiId: Int, clId: Int? = null) = "workspaces/${ workspace.id }/treeitems/${ tiId }/checklist_items${ clId?.let { "/$it" } ?: "" }" }
0
Kotlin
0
0
3f7626f83bc6b2e8764f8b3a60be4c3c1239a2bf
1,884
kotlin_android_liquidplanner_client_example
Apache License 2.0
common-client/src/main/kotlin/org/kotlinacademy/presentation/notifications/RegisterNotificationTokenView.kt
MarcinMoskala
111,068,526
false
null
package org.kotlinacademy.presentation.notifications interface RegisterNotificationTokenView { fun setTokenRegistered(token: String) fun logError(error: Throwable) }
9
CSS
58
446
e7ad620f5a2fb2e3a0330928ed560adf1925d797
174
KtAcademyPortal
Apache License 2.0
android/app/src/main/java/de/bkm/kulturpass/custom/KPCustomPackage.kt
kulturpass-de
621,855,863
false
{"TypeScript": 2379271, "JavaScript": 26191, "Java": 17901, "C++": 7301, "Kotlin": 5352, "Ruby": 2661, "Objective-C": 2293, "Objective-C++": 2143, "Starlark": 602, "CMake": 274, "Shell": 86}
package de.bkm.kulturpass.custom import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager class KPCustomPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf(KPCustomModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } }
3
TypeScript
7
54
c9e1e64ccb8587797d17d8950d7e9414c5767d70
558
kulturpass-app
Apache License 2.0
Barlom-Foundation-JVM/src/main/kotlin/o/barlom/infrastructure/graphs/ConnectionTypeId.kt
martin-nordberg
82,682,055
false
null
// // (C) Copyright 2019 <NAME> // Apache 2.0 License // package o.barlom.infrastructure.graphs //--------------------------------------------------------------------------------------------------------------------- /** * The type of a connection. */ @Suppress("unused") data class ConnectionTypeId<Connection : IConnection<Connection>>( /** The name of this connection type. */ val typeName: String ) //---------------------------------------------------------------------------------------------------------------------
0
Kotlin
0
0
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
538
ZZ-Barlom
Apache License 2.0
app/src/main/java/com/andrii_a/walleria/domain/models/user/User.kt
andrew-andrushchenko
525,795,850
false
{"Kotlin": 656065}
package com.andrii_a.walleria.domain.models.user import com.andrii_a.walleria.domain.models.photo.Photo data class User( val id: String, val username: String, val firstName: String, val lastName: String, val bio: String?, val location: String?, val totalLikes: Long, val totalPhotos: Long, val totalCollections: Long, val followersCount: Long, val followingCount: Long, val downloads: Long, val profileImage: UserProfileImage?, val social: UserSocialMediaLinks?, val tags: UserTags?, val photos: List<Photo>? )
0
Kotlin
2
3
c25661c610d3197390ac86b7c63295a10095e622
576
Walleria
MIT License
app/src/main/java/com/example/avjindersinghsekhon/minimaltodo/data/model/Card.kt
felipetozato
214,848,997
true
{"Java": 117971, "Kotlin": 18404}
package com.example.avjindersinghsekhon.minimaltodo.data.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Card { @SerializedName("last_4_digits") @Expose var last4Digits: String? = null @SerializedName("type") @Expose var type: String? = null @SerializedName("cardholder_name") @Expose var cardholderName: String? = null @SerializedName("expiry_month") @Expose var expiryMonth: String? = null @SerializedName("expiry_year") @Expose var expiryYear: String? = null @SerializedName("token") @Expose var token: String? = null }
0
Java
0
0
df6e04cc5c60958afd1bc5d2359c2427f9fb7bcc
655
Minimal-Todo
MIT License
screenrecorder/src/main/kotlin/io/github/japskiddin/screenrecorder/utils/RecordUtils.kt
Japskiddin
643,089,658
false
{"Kotlin": 23408}
package io.github.japskiddin.screenrecorder.utils import android.content.Context import android.content.res.Configuration import android.media.CamcorderProfile import android.os.Build import android.os.Bundle import android.util.DisplayMetrics import android.view.WindowManager import androidx.core.os.bundleOf import io.github.japskiddin.screenrecorder.model.CameraInfo import io.github.japskiddin.screenrecorder.model.DisplayInfo import io.github.japskiddin.screenrecorder.model.RecordingInfo import java.text.SimpleDateFormat import java.util.Date import java.util.Locale internal val curSysDate: String get() = SimpleDateFormat("MM-dd_HH-mm", Locale.getDefault()).format(Date()) internal fun getRecordingInfo(context: Context): RecordingInfo { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val display: DisplayInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { windowManager.currentWindowMetrics.run { DisplayInfo( width = bounds.width(), height = bounds.height(), density = context.resources.configuration.densityDpi ) } } else { DisplayMetrics().run { @Suppress("DEPRECATION") windowManager.defaultDisplay.getRealMetrics(this) DisplayInfo( width = widthPixels, height = heightPixels, density = densityDpi ) } } val configuration = context.resources.configuration val isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE val camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH) val camera: CameraInfo = if (camcorderProfile != null) { CameraInfo( width = camcorderProfile.videoFrameWidth, height = camcorderProfile.videoFrameHeight, frameRate = camcorderProfile.videoFrameRate ) } else { CameraInfo(width = -1, height = -1, frameRate = 30) } return calculateRecordingInfo( display, isLandscape, camera ) } private fun calculateRecordingInfo( display: DisplayInfo, isLandscapeDevice: Boolean, camera: CameraInfo, sizePercentage: Int = 100, ): RecordingInfo { // Scale the display size before any maximum size calculations. val width = display.width * sizePercentage / 100 val height = display.height * sizePercentage / 100 if (camera.width == -1 && camera.height == -1) { // No cameras. Fall back to the display size. return RecordingInfo(width, height, camera.frameRate, display.density) } var frameWidth: Int var frameHeight: Int if (isLandscapeDevice) { frameWidth = camera.width frameHeight = camera.height } else { frameWidth = camera.height frameHeight = camera.width } if (frameWidth >= width && frameHeight >= height) { // Frame can hold the entire display. Use exact values. return RecordingInfo(width, height, camera.frameRate, display.density) } // Calculate new width or height to preserve aspect ratio. if (isLandscapeDevice) { frameWidth = width * frameHeight / height } else { frameHeight = height * frameWidth / width } return RecordingInfo(frameWidth, frameHeight, camera.frameRate, display.density) } internal fun Map<String, Any?>.toBundle(): Bundle = bundleOf(*this.toList().toTypedArray())
0
Kotlin
0
0
3a58097a743b72b219aa1d8fad65801783f49093
3,266
ScreenRecorder
Apache License 2.0
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/database/usecases/CopyDatabaseUseCaseTest.kt
infinum
17,116,181
false
null
package com.infinum.dbinspector.domain.database.usecases import com.infinum.dbinspector.domain.Repositories import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get import org.mockito.kotlin.any @DisplayName("CopyDatabaseUseCase tests") internal class CopyDatabaseUseCaseTest : BaseTest() { override fun modules(): List<Module> = listOf( module { factory { mockk<Repositories.Database>() } } ) @Test fun `Invoking use case clears history per database`() { val repository: Repositories.Database = get() val useCase = CopyDatabaseUseCase(repository) coEvery { repository.copy(any()) } returns mockk() launch { useCase.invoke(any()) } coVerify(exactly = 1) { repository.copy(any()) } } }
0
Kotlin
93
936
10b9ac5013ca01e602976a615e754dff7001f11d
1,023
android_dbinspector
Apache License 2.0
app/src/main/java/com/abanoub/newsify/data/local/NewsDatabase.kt
iAbanoubSamir
660,753,154
false
null
package com.abanoub.newsify.data.local import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database( entities = [ArticleEntity::class], version = 1 ) @TypeConverters(Converters::class) abstract class NewsDatabase : RoomDatabase() { abstract fun articleDao(): ArticleDao }
0
Kotlin
0
1
c623932c1591baff9a7cc634c84f1daf6291c5e5
335
Newsify
Apache License 2.0
app/src/main/java/com/cl/abby/ui/CustomSplashActivity.kt
aaaaaaaazmx
528,318,389
false
{"Kotlin": 3131721, "Java": 1486476}
package com.cl.abby.ui import android.animation.ValueAnimator import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.drawable.AnimationDrawable import android.os.Build import androidx.annotation.RestrictTo import com.alibaba.android.arouter.launcher.ARouter import com.cl.abby.R import com.cl.abby.databinding.CustomSplashActivityBinding import com.cl.common_base.base.BaseActivity import com.cl.common_base.bean.AutomaticLoginReq import com.cl.common_base.bean.TuYaInfo import com.cl.common_base.bean.UserinfoBean import com.cl.common_base.constants.Constants import com.cl.common_base.constants.RouterPath import com.cl.common_base.ext.logI import com.cl.common_base.ext.resourceObserver import com.cl.common_base.help.PlantCheckHelp import com.cl.common_base.init.InitSdk import com.cl.common_base.listener.BluetoothMonitorReceiver import com.cl.common_base.listener.TuYaDeviceUpdateReceiver import com.cl.common_base.salt.AESCipher import com.cl.common_base.util.Prefs import com.cl.common_base.util.json.GSON import com.cl.common_base.widget.toast.ToastUtil import com.cl.modules_login.viewmodel.LoginViewModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class CustomSplashActivity : BaseActivity<CustomSplashActivityBinding>() { private val tuYaInfo by lazy { val bean = Prefs.getString(Constants.Login.KEY_TU_YA_INFO) GSON.parseObject(bean, TuYaInfo::class.java) } private val borad by lazy { BluetoothMonitorReceiver() } // 账号 val account by lazy { Prefs.getString(Constants.Login.KEY_LOGIN_ACCOUNT) } // 密码 val psd by lazy { Prefs.getString(Constants.Login.KEY_LOGIN_PSD) } @Inject lateinit var mViewModel: LoginViewModel private val images = intArrayOf( R.mipmap.plant_one, R.mipmap.plant_two, R.mipmap.plant_three, R.mipmap.plant_four, R.mipmap.plant_five, R.mipmap.plant_six, R.mipmap.plant_seven, R.mipmap.plant_eight, R.mipmap.plant_nine, R.mipmap.plant_ten, R.mipmap.plant_eleven, R.mipmap.plant_twelve ) // 初始化动画 private lateinit var animator: ValueAnimator override fun initView() { InitSdk.init() binding.ivAnimation.apply { animator = ValueAnimator.ofInt(0, images.size - 1) animator.duration = (images.size * 100).toLong() animator.repeatCount = ValueAnimator.INFINITE animator.addUpdateListener { animation -> val index = (animation.animatedValue as Int) setImageResource(images[index]) } animator.start() } restrictTo() } private fun restrictTo() { val data = Prefs.getString(Constants.Login.KEY_LOGIN_DATA_TOKEN) if (data.isEmpty()) { // 直接跳转登录界面 ARouter.getInstance().build(RouterPath.LoginRegister.PAGE_LOGIN).navigation() finish() } else { // 主要是针对老用户,因为新增了一个key用于保存涂鸦的信息,老用户是没有的,所以会一直登录不上,如果是老用户,那么就直接跳转到登录页面,让其登录一遍。 val tuyaCountryCode = tuYaInfo?.tuyaCountryCode val tuyaPassword = tuYaInfo?.tuyaPassword if (null == tuYaInfo || (tuyaCountryCode?.isEmpty() == true && tuyaPassword?.isEmpty() == true)) { // 直接跳转登录界面 ARouter.getInstance().build(RouterPath.LoginRegister.PAGE_LOGIN).navigation() finish() } else { mViewModel.refreshToken( AutomaticLoginReq( userName = account, password = psd, token = data ) ) } } } override fun observe() { mViewModel.refreshToken.observe(this@CustomSplashActivity, resourceObserver { error { errorMsg, code -> // 从设备列表当中获取当前选中设备 mViewModel.userDetail() } success { // 保存涂鸦信息 val tuYaInfo = TuYaInfo( tuyaCountryCode = data?.tuyaCountryCode, tuyaPassword = <PASSWORD>?.tuyaPassword, tuyaUserId = data?.tuyaUserId, tuyaUserType = data?.tuyaUserType ) GSON.toJson(tuYaInfo)?.let { tuyainfos -> logI("tuYaInfoL: $tuyainfos") Prefs.putStringAsync(Constants.Login.KEY_TU_YA_INFO, tuyainfos) } // 从设备列表当中获取当前选中设备 mViewModel.userDetail() } }) mViewModel.userDetail.observe(this@CustomSplashActivity, resourceObserver { error { errorMsg, code -> if (code == -1) { ARouter.getInstance().build(RouterPath.LoginRegister.PAGE_LOGIN).navigation() finish() } } success { // 缓存信息 GSON.toJson(data)?.let { it1 -> Prefs.putStringAsync( Constants.Login.KEY_LOGIN_DATA, it1 ) } // 获取InterCome信息 mViewModel.getInterComeData() } }) mViewModel.getInterComeData.observe(this@CustomSplashActivity, resourceObserver { error { errorMsg, code -> val email = mViewModel.userDetail.value?.data?.email val tuyaCountryCode = tuYaInfo?.tuyaCountryCode val tuyaPassword = <PASSWORD> mViewModel.tuYaLogin( map = mapOf(), mViewModel.userDetail.value?.data?.externalId, mViewModel.userDetail.value?.data, mViewModel.userDetail.value?.data?.deviceId, tuyaCountryCode, email, AESCipher.aesDecryptString(tuyaPassword, AESCipher.KEY), onRegisterReceiver = { devId -> val intent = Intent( this@CustomSplashActivity, TuYaDeviceUpdateReceiver::class.java ) startService(intent) }, onError = { code, error -> hideProgressLoading() error?.let { ToastUtil.shortShow(it) } } ) } success { val email = mViewModel.userDetail.value?.data?.email val tuyaCountryCode = tuYaInfo?.tuyaCountryCode val tuyaPassword = <PASSWORD> mViewModel.tuYaLogin( map = mapOf(), mViewModel.userDetail.value?.data?.externalId, mViewModel.userDetail.value?.data, mViewModel.userDetail.value?.data?.deviceId, tuyaCountryCode, email, AESCipher.aesDecryptString(tuyaPassword, AESCipher.KEY), onRegisterReceiver = { devId -> val intent = Intent( this@CustomSplashActivity, TuYaDeviceUpdateReceiver::class.java ) startService(intent) }, onError = { code, error -> hideProgressLoading() error?.let { ToastUtil.shortShow(it) } } ) } }) /** * 检查是否种植过 */ mViewModel.checkPlant.observe(this@CustomSplashActivity, resourceObserver { loading { } error { errorMsg, code -> errorMsg?.let { msg -> ToastUtil.shortShow(msg) } // 如果接口抛出异常,那么直接跳转登录页面。不能卡在这 if (code == -1) { ARouter.getInstance().build(RouterPath.LoginRegister.PAGE_LOGIN).navigation() } } success { data?.let { PlantCheckHelp().plantStatusCheck(this@CustomSplashActivity, it) } // when (userinfoBean?.deviceStatus) { // // 设备状态(1-绑定,2-已解绑) // "1" -> { // // 是否种植过 // } // "2" -> { // // 跳转绑定界面 // ARouter.getInstance() // .build(RouterPath.PairConnect.PAGE_PLANT_CHECK) // .navigation() // } // } finish() } }) } override fun initData() { // 开启蓝牙广播 val intentFilter = IntentFilter() intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF") intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON") registerReceiver(borad, intentFilter) } override fun onPause() { super.onPause() animator.cancel() } override fun onDestroy() { super.onDestroy() } }
0
Kotlin
0
0
ef616ab37c42ad8a6b98d887e2e8deae58cedc29
9,634
abby
Apache License 2.0
features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/edit/RoomDetailsEditStateProvider.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.roomdetails.impl.edit import android.net.Uri import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.ui.media.AvatarAction import io.element.android.libraries.permissions.api.PermissionsState import io.element.android.libraries.permissions.api.aPermissionsState import kotlinx.collections.immutable.toImmutableList open class RoomDetailsEditStateProvider : PreviewParameterProvider<RoomDetailsEditState> { override val values: Sequence<RoomDetailsEditState> get() = sequenceOf( aRoomDetailsEditState(), aRoomDetailsEditState(roomTopic = ""), aRoomDetailsEditState(roomRawName = ""), aRoomDetailsEditState(roomAvatarUrl = Uri.parse("example://uri")), aRoomDetailsEditState(canChangeName = true, canChangeTopic = false, canChangeAvatar = true, saveButtonEnabled = false), aRoomDetailsEditState(canChangeName = false, canChangeTopic = true, canChangeAvatar = false, saveButtonEnabled = false), aRoomDetailsEditState(saveAction = AsyncAction.Loading), aRoomDetailsEditState(saveAction = AsyncAction.Failure(Throwable("Whelp"))), ) } fun aRoomDetailsEditState( roomId: RoomId = RoomId("!aRoomId:aDomain"), roomRawName: String = "Marketing", canChangeName: Boolean = true, roomTopic: String = "a room topic that is quite long so should wrap onto multiple lines", canChangeTopic: Boolean = true, roomAvatarUrl: Uri? = null, canChangeAvatar: Boolean = true, avatarActions: List<AvatarAction> = emptyList(), saveButtonEnabled: Boolean = true, saveAction: AsyncAction<Unit> = AsyncAction.Uninitialized, cameraPermissionState: PermissionsState = aPermissionsState(showDialog = false), eventSink: (RoomDetailsEditEvents) -> Unit = {}, ) = RoomDetailsEditState( roomId = roomId, roomRawName = roomRawName, canChangeName = canChangeName, roomTopic = roomTopic, canChangeTopic = canChangeTopic, roomAvatarUrl = roomAvatarUrl, canChangeAvatar = canChangeAvatar, avatarActions = avatarActions.toImmutableList(), saveButtonEnabled = saveButtonEnabled, saveAction = saveAction, cameraPermissionState = cameraPermissionState, eventSink = eventSink, )
263
null
129
955
31d0621fa15fe153bfd36104e560c9703eabe917
3,060
element-x-android
Apache License 2.0
compiler/fir/analysis-tests/testData/resolveWithStdlib/delegates/delegateWithAnonymousObject.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// !DUMP_CFG import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty abstract class DelegateProvider<in Type> fun <Type : Base, Base : DelegateProvider<Base>, Target : Any> Type.delegate( factory: () -> ReadWriteProperty<Type, Target> ): ReadWriteProperty<Type, Target> = null!! class IssueListView : DelegateProvider<IssueListView>() { fun updateFrom(any: Any) {} } class IssuesListUserProfile : DelegateProvider<IssuesListUserProfile>() { var issueListView by delegate { object : ReadWriteProperty<IssuesListUserProfile, IssueListView> { override fun getValue(thisRef: IssuesListUserProfile, property: KProperty<*>): IssueListView { return IssueListView() } override fun setValue(thisRef: IssuesListUserProfile, property: KProperty<*>, value: IssueListView) { return IssueListView().updateFrom(value) } } } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
947
kotlin
Apache License 2.0
ktor-client/ktor-client-core/test/io/ktor/client/tests/engine/mock/MockEngine.kt
sillerud
137,465,837
true
{"Kotlin": 1751604, "Java": 62081, "Lua": 280, "HTML": 35}
package io.ktor.client.tests.engine.mock import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.request.* import io.ktor.http.* import kotlinx.coroutines.experimental.* typealias MockHttpResponseBuilder = (HttpClientCall, HttpRequest) -> HttpEngineCall internal class MockEngine(override val config: MockEngineConfig) : HttpClientEngine { override val dispatcher: CoroutineDispatcher = Unconfined override suspend fun execute(call: HttpClientCall, data: HttpRequestData): HttpEngineCall { config.checks.forEach { it(data) } return config.response(call, data.toRequest(call)) } override fun close() {} companion object : HttpClientEngineFactory<MockEngineConfig> { override fun create(block: MockEngineConfig.() -> Unit): HttpClientEngine = MockEngine(MockEngineConfig().apply(block)) fun check(check: HttpRequestData.() -> Unit) = object : HttpClientEngineFactory<MockEngineConfig> { override fun create(block: MockEngineConfig.() -> Unit): HttpClientEngine = [email protected] { block() checks += check } } fun setResponse(newResponse: MockHttpResponseBuilder) = object : HttpClientEngineFactory<MockEngineConfig> { override fun create(block: MockEngineConfig.() -> Unit): HttpClientEngine = [email protected] { block() response = newResponse } } val EMPTY_SUCCESS_RESPONSE: (HttpClientCall, HttpRequest) -> HttpEngineCall = { call, request -> HttpEngineCall(request, MockHttpResponse(call, HttpStatusCode.OK)) } } }
0
Kotlin
0
0
f51c77cbc9298b600968ca7c28b355242d764e52
1,725
ktor
Apache License 2.0
app/src/test/java/cz/budikpet/bachelorwork/screens/main/mainViewModel/MainViewModelTest_ShareCalendars.kt
budikpet
173,619,887
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 2, "Java": 1, "Kotlin": 57, "XML": 72}
package cz.budikpet.bachelorwork.screens.main.mainViewModel import android.arch.lifecycle.Observer import com.google.api.services.calendar.model.AclRule import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.reset import com.nhaarman.mockitokotlin2.whenever import cz.budikpet.bachelorwork.MyApplication import cz.budikpet.bachelorwork.screens.main.util.mock import cz.budikpet.bachelorwork.util.NoInternetConnectionException import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import org.junit.After import org.junit.Before import org.junit.Test internal class MainViewModelTest_ShareCalendars : BaseMainViewModelTest() { private val testObserver = mock<Observer<ArrayList<String>>>() private val calendarName = MyApplication.calendarNameFromId(username) private val emails = arrayListOf("<EMAIL>", "<EMAIL>") @Before override fun initTest() { super.initTest() reset(testObserver) } @After override fun clear() { assert(viewModel.compositeDisposable.size() > 0) super.clear() } @Test fun shareCalendars_update() { // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.fromIterable(emails)) viewModel.emails.observeForever(testObserver) viewModel.updateSharedEmails(username) // Asserts assert(viewModel.emails.value != null) assert(viewModel.emails.value!! == emails) assert(viewModel.thrownException.value == null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } @Test fun shareCalendars_updateError() { // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.error(NoInternetConnectionException())) viewModel.emails.observeForever(testObserver) viewModel.updateSharedEmails(username) // Asserts assert(viewModel.thrownException.value != null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } @Test fun shareCalendars_share() { // Data val newEmail = "<EMAIL>" emails.add(newEmail) // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.fromIterable(emails)) whenever(repository.sharePersonalCalendar(any())) .thenReturn(Single.just(AclRule())) viewModel.emails.observeForever(testObserver) viewModel.shareTimetable(newEmail, username) // Asserts assert(viewModel.emails.value != null) assert(viewModel.emails.value!! == emails) assert(viewModel.thrownException.value == null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } @Test fun shareCalendars_shareError() { // Data val newEmail = "<EMAIL>" emails.add(newEmail) // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.fromIterable(emails)) whenever(repository.sharePersonalCalendar(any())) .thenReturn(Single.error(NoInternetConnectionException())) viewModel.emails.observeForever(testObserver) viewModel.shareTimetable(newEmail, username) // Asserts assert(viewModel.emails.value == null) assert(viewModel.thrownException.value != null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } @Test fun shareCalendars_unshare() { // Data val removedEmail = emails.last() emails.remove(removedEmail) // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.fromIterable(emails)) whenever(repository.unsharePersonalCalendar(any())) .thenReturn(Completable.complete()) viewModel.emails.observeForever(testObserver) viewModel.unshareTimetable(removedEmail, username) // Asserts assert(viewModel.emails.value != null) assert(viewModel.emails.value!! == emails) assert(viewModel.thrownException.value == null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } @Test fun shareCalendars_unshareError() { // Data val removedEmail = emails.last() // Stubs whenever(repository.getEmails(calendarName)) .thenReturn(Observable.fromIterable(emails)) whenever(repository.unsharePersonalCalendar(any())) .thenReturn(Completable.error(NoInternetConnectionException())) viewModel.emails.observeForever(testObserver) viewModel.unshareTimetable(removedEmail, username) // Asserts assert(viewModel.emails.value != null) assert(viewModel.emails.value!! == emails) assert(viewModel.thrownException.value != null) assert(viewModel.operationsRunning.value != null) assert(viewModel.operationsRunning.value!!.number == 0) } }
0
Kotlin
0
0
df5c3d4720f7afe2d9217e03428ca0681d753f57
5,286
BachelorWork
MIT License
components/core/ui/flippermockup/src/main/java/com/flipperdevices/core/ui/flippermockup/ComposableFlipperMockup.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.core.ui.flippermockup import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.flipperdevices.core.preference.pb.HardwareColor import com.flipperdevices.core.ui.theme.FlipperThemeInternal @Composable fun ComposableFlipperMockup( flipperColor: HardwareColor, isActive: Boolean, mockupImage: ComposableFlipperMockupImage, modifier: Modifier = Modifier ) { val templatePicId = when (flipperColor) { HardwareColor.UNRECOGNIZED, HardwareColor.WHITE -> when (isActive) { true -> R.drawable.template_white_flipper_active false -> R.drawable.template_white_flipper_disabled } HardwareColor.BLACK -> when (isActive) { true -> R.drawable.template_black_flipper_active false -> R.drawable.template_black_flipper_disabled } HardwareColor.TRANSPARENT -> when (isActive) { true -> R.drawable.template_transparent_flipper_active false -> R.drawable.template_transparent_flipper_disabled } } ComposableFlipperMockupInternal( templatePicId = templatePicId, picId = mockupImage.imageId, modifier = modifier ) } @Preview( showBackground = true, heightDp = 1500 ) @Composable private fun PreviewComposableFlipperMockup() { FlipperThemeInternal { Column { HardwareColor.values().forEach { color -> listOf(true, false).forEach { isActive -> ComposableFlipperMockup( flipperColor = color, isActive = isActive, mockupImage = ComposableFlipperMockupImage.DEFAULT, modifier = Modifier.fillMaxWidth() .padding(top = 16.dp) ) } } } } }
20
null
173
999
ef27b6b6a78a59b603ac858de2c88f75b743f432
2,150
Flipper-Android-App
MIT License
testing/lab1/src/main/kotlin/tpo1/tests/BarTests.kt
Azmalent
179,684,678
false
null
package tpo1.tests import org.openqa.selenium.WebElement import org.openqa.selenium.support.FindBy import tpo1.PresentationPage class BarTests(page: PresentationPage) : AbstractTestSet("Bar", page) { @FindBy(id = "insertImageMenuButton") lateinit var insertImageMenuButton: WebElement @FindBy(id = "lineMenuButton") lateinit var lineMenuButton: WebElement @FindBy(id = "zoomButtonDropdown") lateinit var zoomButtonDropdown: WebElement @FindBy(id = "shapeButton") lateinit var shapeButton: WebElement @FindBy(id = "slideThemeButton") lateinit var slideThemeButton: WebElement @FindBy(id = "slideTransitionButton") lateinit var slideTransitionButton: WebElement override fun initializeTest() { } @Test("Insert image") fun insertImagesest() { basicEscapeTest(insertImageMenuButton, "//span[text()='Загрузить с компьютера']") } @Test("Line") fun lineTest() { basicEscapeTest(lineMenuButton, "//span[text()='Линия']") } @Test("Zoom dropdown") fun zoomButtonDropdownTest() { basicEscapeTest(zoomButtonDropdown, "//span[@aria-label='50% 5']") } @Test("Shape") fun shapeTest() { basicEscapeTest(shapeButton, "//span[text()='Фигуры']") } @Test("Theme") fun themeTest() { basicWindowTest(slideThemeButton, "//div[@class='punch-theme-sidebar-header']//div[@title='Закрыть']/div") } @Test("Transition") fun transotionTest() { basicWindowTest(slideTransitionButton, "//div[@class='punch-animation-sidebar-header']//div[@title='Закрыть']/div") } }
0
Kotlin
0
0
3f5103bfc26ab988818b2a80d1e0df5ef787bbbd
1,597
itmo6
Do What The F*ck You Want To Public License
petsearch-android/common/compose/src/main/kotlin/com/msa/petsearch/android/common/compose/NavRoute.kt
msa1422
534,594,528
false
null
package com.msa.petsearch.android.common.compose import androidx.compose.animation.AnimatedContentScope import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.navigation.NamedNavArgument import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDeepLink import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import com.google.accompanist.navigation.animation.composable import com.msa.petsearch.android.common.compose.util.OnDestroy import com.msa.petsearch.shared.core.util.sharedviewmodel.BaseViewModel import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.NavigationEvent import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.NavigationEvent.NavigateAndPopUpToRoute import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.NavigationEvent.NavigateToRoute import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.NavigationEvent.NavigateUp import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.NavigationEvent.PopToRoute import com.msa.petsearch.shared.core.util.sharedviewmodel.navigation.RouteNavigator import kotlinx.coroutines.delay typealias AnimatedBackStack = AnimatedContentScope<NavBackStackEntry> /** * Heavily modified implementation of ViewModelNavigationCompose by Frank * [Source](https://github.com/Frank1234/ViewModelNavigationCompose) */ interface NavRoute<T : RouteNavigator> { val route: String val enableLifecycleObserver: Boolean get() = true @Composable fun Content(viewModel: T) @Composable fun viewModel(entry: NavBackStackEntry): T fun getArguments(): List<NamedNavArgument> = emptyList() fun getDeepLinks(): List<NavDeepLink> = emptyList() fun getEnterTransition(): (AnimatedBackStack.() -> EnterTransition?)? = null fun getExitTransition(): (AnimatedBackStack.() -> ExitTransition?)? = null fun getPopEnterTransition(): (AnimatedBackStack.() -> EnterTransition?)? = getEnterTransition() fun getPopExitTransition(): (AnimatedBackStack.() -> ExitTransition?)? = getExitTransition() fun asComposable(builder: NavGraphBuilder, navController: NavHostController) = builder.composable( route = route, arguments = getArguments(), deepLinks = getDeepLinks(), enterTransition = getEnterTransition(), exitTransition = getExitTransition(), popEnterTransition = getPopEnterTransition(), popExitTransition = getPopExitTransition() ) { backStackEntry -> val viewModel = viewModel(backStackEntry) (viewModel as? BaseViewModel<*, *, *, *, *, *>)?.let { if (enableLifecycleObserver) { backStackEntry.OnDestroy(it::onCleared) } LaunchedEffect(it) { if (getArguments().isNotEmpty()) { // Update Args in ViewModel val argsMap = hashMapOf<String, String>().also { hashMap -> getArguments().forEach { namedArg -> backStackEntry.arguments?.getString(namedArg.name)?.let { arg -> hashMap[namedArg.name] = arg } } } it.updateArgsInState(argsMap) } it.navigationEvent.collect { state -> onNavEvent(navController, state) } } Content(viewModel) } } private suspend fun onNavEvent(controller: NavHostController, event: NavigationEvent) = when (event) { is NavigateToRoute -> handleNavigateToRoute(controller, event) is NavigateAndPopUpToRoute -> handleNavigateAndPopUpToRoute(controller, event) is PopToRoute -> handlePopToRoute(controller, event) is NavigateUp -> handleNavigateUp(controller, event) } } fun Iterable<NavRoute<*>>.provide(builder: NavGraphBuilder, navController: NavHostController) = forEach { it.asComposable(builder, navController) } private suspend fun handleNavigateToRoute(controller: NavHostController, event: NavigateToRoute) { if (controller.currentDestination?.route == event.route) { return } delay(event.delay) var currentRoute = event.route event.args?.forEach { entry -> currentRoute = currentRoute .replace( oldValue = "{${entry.key}}", newValue = entry.value.takeIf { it.isNotBlank() } ?: "null" ) } controller.navigate(currentRoute) { launchSingleTop = true restoreState = true popUpTo(controller.graph.findStartDestination().id) { saveState = true } } } private suspend fun handleNavigateAndPopUpToRoute( controller: NavHostController, event: NavigateAndPopUpToRoute ) { if (controller.currentDestination?.route == event.route) { return } delay(event.delay) var currentRoute = event.route event.args?.forEach { args -> currentRoute = currentRoute .replace( oldValue = "{${args.key}}", newValue = args.value.takeIf { it.isNotBlank() } ?: "null" ) } controller.navigate(currentRoute) { launchSingleTop = true restoreState = true popUpTo(event.popUpTo) { inclusive = true saveState = true } } } private suspend fun handlePopToRoute(controller: NavHostController, event: PopToRoute) { if (controller.currentDestination?.route == event.staticRoute) { return } delay(event.delay) controller .getBackStackEntry(event.staticRoute) .arguments?.let { bundle -> event.args?.forEach { args -> bundle.putString(args.key, args.value) } } controller.popBackStack(event.staticRoute, false) } private suspend fun handleNavigateUp(controller: NavHostController, event: NavigateUp) { delay(event.delay) controller.currentDestination?.route?.let { controller.popBackStack(route = it, inclusive = true) } }
0
Kotlin
0
10
e659a4252af8b0e48dad51839ac62eed2e321fb7
6,552
KMM-Arch-PetSearch
MIT License
legacy/src/main/java/com/onevn/browser/legacy/webkit/handler/WebSrcImageWhiteListHandler.kt
1-vn
186,006,245
true
{"Kotlin": 2104535, "Java": 697833, "HTML": 44658, "CSS": 4743, "JavaScript": 3209}
/* * Copyright (C) 2017-2019 DiepDT * * 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.onevn.browser.legacy.webkit.handler import androidx.appcompat.app.AppCompatActivity import com.onevn.browser.adblock.ui.original.AddAdBlockDialog import java.lang.ref.WeakReference class WebSrcImageBlackListHandler(activity: AppCompatActivity) : WebSrcImageHandler() { private val mReference: WeakReference<AppCompatActivity> = WeakReference(activity) override fun handleUrl(url: String) { mReference.get()?.run { AddAdBlockDialog.addBackListInstance(url) .show(supportFragmentManager, "add black") } } }
0
Kotlin
0
0
50d5221a959da6b35c492db02ec4d46d3dd6850a
1,180
OneVNBrowser
Apache License 2.0
strikt-core/src/test/kotlin/strikt/Throws.kt
tadfisher
226,414,327
true
{"Kotlin": 335728, "CSS": 53016, "Java": 1221, "JavaScript": 766, "Shell": 241}
package strikt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import strikt.api.expectThrows import strikt.assertions.isA @DisplayName("throws assertion") internal class Throws { @Test fun `throws passes if the action throws the expected exception`() { expectThrows<IllegalStateException> { error("o noes") } } @Test fun `throws passes if the action throws a sub-class of the expected exception`() { expectThrows<RuntimeException> { error("o noes") } } @Test fun `throws fails if the action does not throw any exception`() { assertThrows<AssertionError> { expectThrows<IllegalStateException> { } }.let { e -> val expected = """▼ Expect that Success(kotlin.Unit): | ✗ failed with an exception : ran successfully""" .trimMargin() assertEquals(expected, e.message) } } @Test fun `throws fails if the action throws the wrong type of exception`() { assertThrows<AssertionError> { expectThrows<NullPointerException> { error("o noes") } }.let { e -> val expected = """▼ Expect that Failure(IllegalStateException: o noes): | ✓ failed with an exception | ▼ caught exception: | ✗ is an instance of java.lang.NullPointerException : found java.lang.IllegalStateException""" .trimMargin() assertEquals(expected, e.message) } } @Test fun `throws returns an assertion whose subject is the exception that was caught`() { expectThrows<IllegalStateException> { error("o noes") } .isA<IllegalStateException>() } @Test fun `expectThrows accepts a suspending lambda`() { expectThrows<IllegalStateException> { delayedException(IllegalStateException()) } .isA<IllegalStateException>() } } private suspend fun <T : Throwable> delayedException(input: T): Nothing = withContext(Dispatchers.Default) { throw input }
0
null
0
0
f0dba2dd82294e5fd9f4d2598bc3b7b74093a09d
2,110
strikt
Apache License 2.0
backend/src/test/kotlin/de/mcella/spring/learntool/card/CardImportServiceTest.kt
sitMCella
251,022,990
false
null
package de.mcella.spring.learntool.card import de.mcella.spring.learntool.UnitTest import de.mcella.spring.learntool.card.dto.CardContent import de.mcella.spring.learntool.card.dto.CardId import de.mcella.spring.learntool.card.exceptions.CardAlreadyExistsException import de.mcella.spring.learntool.workspace.dto.Workspace import de.mcella.spring.learntool.workspace.exceptions.WorkspaceNotExistsException import java.io.ByteArrayInputStream import org.junit.Test import org.junit.experimental.categories.Category import org.mockito.Mockito @Category(UnitTest::class) class CardImportServiceTest { private val cardService = Mockito.mock(CardService::class.java) private val cardImportService = CardImportService(cardService) @Test(expected = WorkspaceNotExistsException::class) fun `given a non existent Workspace name and a Cards stream content, when creating the Cards, then throw WorkspaceNotExistsException`() { val workspaceName = "workspaceTest" val workspace = Workspace(workspaceName) val streamContent = "question,response\nquestionTest1,responseTest1\nquestionTest2,responseTest2" val cardContent1 = CardContent("questionTest1", "responseTest1") Mockito.`when`(cardService.create(workspace, cardContent1)).thenThrow(WorkspaceNotExistsException(workspace)) cardImportService.createMany(workspace, ByteArrayInputStream(streamContent.toByteArray())) } @Test(expected = CardAlreadyExistsException::class) fun `given a Workspace name and a Cards stream content, when creating the Cards and the Card already exists, then throw CardAlreadyExistsException`() { val workspaceName = "workspaceTest" val workspace = Workspace(workspaceName) val streamContent = "question,response\nquestionTest1,responseTest1\nquestionTest2,responseTest2" val cardContent1 = CardContent("questionTest1", "responseTest1") Mockito.`when`(cardService.create(workspace, cardContent1)).thenThrow(CardAlreadyExistsException(CardId("9e493dc0-ef75-403f-b5d6-ed510634f8a6"))) cardImportService.createMany(workspace, ByteArrayInputStream(streamContent.toByteArray())) } @Test fun `given a Workspace name and a Cards stream content, when creating the Cards, then call the method create of CardService`() { val workspaceName = "workspaceTest" val workspace = Workspace(workspaceName) val streamContent = "question,response\nquestionTest1,responseTest1\nquestionTest2,responseTest2" cardImportService.createMany(workspace, ByteArrayInputStream(streamContent.toByteArray())) val cardContent1 = CardContent("questionTest1", "responseTest1") Mockito.verify(cardService).create(workspace, cardContent1) val cardContent2 = CardContent("questionTest2", "responseTest2") Mockito.verify(cardService).create(workspace, cardContent2) } }
0
Kotlin
0
0
32b3b651e9365c9518a2eeae6bc4720670239a14
2,912
learn-tool
MIT License
domain/src/main/java/com/rowland/adventcalendly/domain/usecase/SingleUseCase.kt
RowlandOti
236,055,285
false
null
package com.rowland.adventcalendly.domain.usecase import com.rowland.adventcalendly.domain.executor.IPostExecutionThread import com.rowland.adventcalendly.domain.executor.IThreadExecutor import io.reactivex.Single import io.reactivex.disposables.Disposables import io.reactivex.schedulers.Schedulers /** * Created by Rowland on 1/26/2020. * * Abstract class for a UseCase that returns an instance of a [Single]. * */ abstract class SingleUseCase<T, in Params> constructor( private val threadExecutor: IThreadExecutor, private val postExecutionThread: IPostExecutionThread ) { private val subscription = Disposables.empty() /** * Builds a [Single] which will be used when the current [SingleUseCase] is executed. */ protected abstract fun buildUseCaseObservable(params: Params? = null): Single<T> /** * Executes the current use case. */ open fun execute(params: Params? = null): Single<T> { return this.buildUseCaseObservable(params) .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.scheduler) } /** * Unsubscribes from current [Disposable]. */ fun unsubscribe() { if (!subscription.isDisposed) { subscription.dispose() } } }
0
Kotlin
0
0
ebc109636cea730f3e1041bf30617548da50fc05
1,298
AdventCalendly
The Unlicense
app/src/main/java/com/steleot/jetpackcompose/playground/compose/ui/ModifierLocalScreen.kt
Vivecstel
338,792,534
false
null
package com.steleot.jetpackcompose.playground.compose.ui import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.modifier.modifierLocalConsumer import androidx.compose.ui.modifier.modifierLocalOf import androidx.compose.ui.modifier.modifierLocalProvider import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.steleot.jetpackcompose.playground.compose.reusable.DefaultScaffold import com.steleot.jetpackcompose.playground.navigation.UiNavRoutes private const val Url = "ui/ModifierLocalScreen.kt" @Composable fun ModifierLocalScreen() { DefaultScaffold( title = UiNavRoutes.ModifierLocal, link = Url, ) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { ModifierLocalExample() } } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun ModifierLocalExample() { val localMessage = modifierLocalOf { "Unknown" } val context = LocalContext.current Box( Modifier .modifierLocalProvider(localMessage) { "Jetpack Compose" } .size(150.dp) .background(MaterialTheme.colors.primary) .composed { var message by remember { mutableStateOf("") } Modifier .modifierLocalConsumer { message = localMessage.current } .clickable { Toast .makeText(context, "Hello $message", Toast.LENGTH_SHORT) .show() } } ) }
1
Kotlin
10
117
e4f4c45b4376dac907cae4ef07db1f188c86d01c
2,086
Jetpack-Compose-Playground
Apache License 2.0
src/test/kotlin/org/incava/rando/RandCalcVsGenTest.kt
jpace
483,382,354
false
{"Kotlin": 243664, "Ruby": 674}
package org.incava.rando import org.incava.ikdk.io.Console import org.incava.mmonkeys.testutil.assertWithin import org.junit.jupiter.api.Test import kotlin.math.abs import kotlin.math.roundToInt import kotlin.test.assertNotNull internal class RandCalcVsGenTest { @Test fun slots() { // at 10M or so, we get out of heap space errors val numTrials = 1_000_000 val numSlots = 100 val gen = object : RandGen(27, numSlots, numTrials) { override fun nextInt(): Int { TODO("Not yet implemented") } } val genResult = gen.slots val maxDistance = 1.1 Console.info("genResult", genResult) val calc = object : RandCalc(27, numSlots, numTrials) { override fun nextInt(): Int { TODO("Not yet implemented") } } val calcResult = calc.slots val keys = genResult.keys + calcResult.keys keys.forEach { key -> val g = gen.slots[key] val c = calc.slots[key] //showComparison(key, c, g) assertNotNull(g, "key: $key") assertNotNull(c, "key: $key") assertWithin(c.toDouble(), g.toDouble(), maxDistance, "key: $key") } } private fun findGap(list: List<Int>): Int? { val unique = list.sorted().distinct() return (0 until unique.size - 1).find { unique[it] + 1 != unique[it + 1] } } @Test fun findGap() { // calculated and generated should have the same gap (slot N without N + 1) val numTrials = 1_000_000 val numSlots = 100 val gen = object : RandGen(27, numSlots, numTrials) { override fun nextInt(): Int { TODO("Not yet implemented") } } val calc = object : RandCalc(27, numSlots, numTrials) { override fun nextInt(): Int { TODO("Not yet implemented") } } println("gen.slots : ${gen.slots}") println("calc.slots: ${calc.slots}") val genNums = gen.slots.values.toSortedSet().toList() val calcNums = calc.slots.values.toSortedSet().toList() println("genNums : $genNums") println("calcNums: $calcNums") val firstGenGap = findGap(genNums) ?: -1 val firstCalcGap = findGap(calcNums) ?: -1 println("firstGenGap : ${genNums[firstGenGap]}") println("firstCalcGap : ${calcNums[firstCalcGap]}") assertWithin(firstGenGap.toDouble(), firstCalcGap.toDouble(), 1.1, "gap") } fun showComparison(num: Int, calculated: Double?, generated: Double?) { if (calculated == null) { System.out.printf("%5d | %8s | %.1f\n", num, "", generated) } else if (generated == null) { System.out.printf("%5d | %.1f | %s\n", num, calculated, "") } else { val diff = abs(calculated - generated) System.out.printf("%5d | %.1f | %.1f | %.1f\n", num, calculated, generated, diff) } } }
0
Kotlin
0
0
e62885d84945819043d1a789132d65fb5a65eff3
3,061
mmonkeys
MIT License
app/src/main/java/com/example/gourmetsearcher/view/RestaurantDetailFragment.kt
0v0d
759,826,460
false
{"Kotlin": 53344}
package com.example.gourmetsearcher.view import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.net.toUri import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.example.gourmetsearcher.databinding.FragmentRestaurantDetailBinding import com.example.gourmetsearcher.viewmodel.RestaurantDetailViewModel class RestaurantDetailFragment : Fragment() { private var _binding: FragmentRestaurantDetailBinding? = null private val binding get() = _binding!! private val args: RestaurantDetailFragmentArgs by navArgs() private val viewModel: RestaurantDetailViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRestaurantDetailBinding.inflate(inflater, container, false) binding.restaurant = args.restaurantData binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner viewModel.url.observe(viewLifecycleOwner) { startActivity(Intent(Intent.ACTION_VIEW, it.toUri())) } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
692b974c47aa0e7715e1e008b7e9577597c2d794
1,413
GourmetSearcher
MIT License
projects/workforce-allocations-to-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/entity/IapsEvent.kt
ministryofjustice
500,855,647
false
{"Kotlin": 3560571, "HTML": 57595, "D2": 27334, "Ruby": 25392, "Shell": 12351, "SCSS": 6240, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1344, "Python": 268}
package uk.gov.justice.digital.hmpps.data.entity import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.Table import org.hibernate.annotations.Immutable @Immutable @Entity @Table(name = "iaps_event") class IapsEvent( @Id val eventId: Long, val iapsFlag: Long )
3
Kotlin
0
2
0fb759df4c12502697879af48c6bfe2fb8c0da31
312
hmpps-probation-integration-services
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/pp/Localizer.kt
gitRaiku
696,241,983
false
{"Kotlin": 215738, "Java": 59489}
package org.firstinspires.ftc.teamcode.pp import org.firstinspires.ftc.teamcode.utils.Pose import org.firstinspires.ftc.teamcode.utils.Util.angNorm import org.firstinspires.ftc.teamcode.utils.Util.epsEq import org.firstinspires.ftc.teamcode.utils.Vec2d import kotlin.math.cos import kotlin.math.sin interface Localizer { var pose: Pose var poseVel: Pose fun init(startPos: Pose) fun update() //fun start() //fun close() fun relativeOdometryUpdate(fieldPose: Pose, robotPoseDelta: Pose): Pose { val dtheta = robotPoseDelta.h val (sineTerm, cosTerm) = if (epsEq(dtheta, 0.0)) { 1.0 - dtheta * dtheta / 6.0 to dtheta / 2.0 } else { sin(dtheta) / dtheta to (1 - cos(dtheta)) / dtheta } val fieldPositionDelta = Vec2d( sineTerm * robotPoseDelta.x - cosTerm * robotPoseDelta.y, cosTerm * robotPoseDelta.x + sineTerm * robotPoseDelta.y ) val fieldPoseDelta = Pose(fieldPositionDelta.rotated(fieldPose.h), robotPoseDelta.h) return Pose( fieldPose.x + fieldPoseDelta.x, fieldPose.y + fieldPoseDelta.y, angNorm(fieldPose.h + fieldPoseDelta.h) ) } }
0
Kotlin
0
3
53f1069de6832d2bc2ca214109de08b3b2b8df9f
1,253
CenterStage
BSD 3-Clause Clear License
app/src/main/kotlin/org/mifos/mobile/cn/ui/mifos/customerProfile/CustomerProfileContract.kt
openMF
133,982,000
false
null
package org.mifos.mobile.cn.ui.mifos.customerProfile import org.mifos.mobile.cn.ui.base.MvpView interface CustomerProfileContract { interface View: MvpView{ fun checkWriteExternalStoragePermission(); fun requestPermission(); fun loadCustomerPortrait(); } }
65
null
64
38
24a93032be5eb3ac55d79fe08b0409ba47f482e7
294
mifos-mobile-cn
Apache License 2.0
sample/src/main/kotlin/com/example/App.kt
hendraanggrian
78,655,968
false
null
package com.example import androidx.appcompat.app.AppCompatDelegate import androidx.multidex.MultiDexApplication import androidx.preference.PreferenceManager class App : MultiDexApplication() { override fun onCreate() { super.onCreate() val preferences = PreferenceManager.getDefaultSharedPreferences(this) AppCompatDelegate.setDefaultNightMode( preferences.getInt("theme", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) ) } }
4
null
53
287
32fea147ff3b11b679cb30723ca5ad133570e533
478
collapsingtoolbarlayout-subtitle
Apache License 2.0