path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/kursx/chart/ui/screen/PointsContent.kt
KursX
676,468,282
false
null
package com.kursx.chart.ui.screen import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.AppBarDefaults import androidx.compose.material.Button import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.kursx.chart.R import com.kursx.chart.data.dto.PointDto @Composable fun PointsContent( points: List<PointDto>, onClickBack: () -> Unit, onClickSave: (Rect) -> Unit, modifier: Modifier = Modifier, ) { var topBarBounds by remember { mutableStateOf<Rect?>(null) } Scaffold( topBar = { TopBar( onClickBack = onClickBack, modifier = Modifier .onGloballyPositioned { topBarBounds = it.boundsInWindow() }, ) }, modifier = modifier, ) { innerPadding -> Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .verticalScroll(rememberScrollState()) .padding(innerPadding) .padding(16.dp), ) { val density = LocalDensity.current var graphBounds by remember { mutableStateOf<Rect?>(null) } Table( points = points, ) ChartContent( points = points, modifier = Modifier .padding(vertical = 16.dp) .onGloballyPositioned { graphBounds = it.boundsInWindow() }, ) if (graphBounds != null) { Button( onClick = { val elevation = with(density) { AppBarDefaults.TopAppBarElevation.toPx() } val topBarHeight = requireNotNull(topBarBounds).height - elevation val rect = with(requireNotNull(graphBounds)) { copy( top = top - topBarHeight, bottom = bottom - topBarHeight, ) } onClickSave(rect) }, ) { Text(stringResource(R.string.save_graph)) } } } } } @Preview @Composable private fun Preview() { PointsContent(listOf(PointDto(1.1f, 1.1f), PointDto(2.1f, 2.0f), PointDto(3.1f, 3.0f)), {}, {}) }
0
Kotlin
0
0
065d6fb5275ab614ef4ebd70225fa8d75cfc052a
3,221
points_demo
Apache License 2.0
src/main/kotlin/at/wavywalk/simpler/utils/sessions/ISessionHandlerFactory.kt
WavyWalk
165,830,702
false
null
package utils.sessions import utils.sessions.ISessionHandler import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse interface ISessionHandlerFactory { fun create( request: HttpServletRequest, response: HttpServletResponse ): ISessionHandler }
0
Kotlin
0
0
f9667ac9c04e135c075df0ee02f5b742c96d8a44
314
simpler
Do What The F*ck You Want To Public License
net.akehurst.language.editor.demo/application/editor-web-server/src/jvm8Main/kotlin/Main.kt
dhakehurst
252,659,008
false
null
/** * Copyright (C) 2020 Dr. David H. Akehurst (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.language.editor.web.server import io.ktor.application.ApplicationCallPipeline import io.ktor.application.call import io.ktor.application.install import io.ktor.features.* import io.ktor.routing.Routing import io.ktor.server.engine.embeddedServer import io.ktor.server.jetty.Jetty import io.ktor.sessions.Sessions import io.ktor.sessions.cookie import io.ktor.sessions.sessions import io.ktor.sessions.set import io.ktor.util.generateNonce import java.io.File fun main(args: Array<String>) { println("PWD: " + File(".").absolutePath) val application = EditorApplication application.start() } object EditorApplication { val server = Server("0.0.0.0", 9999) fun start() { server.start() } } class Server( val host:String, val port:Int ) { fun start() { val server = embeddedServer(Jetty, port = port, host = host) { install(DefaultHeaders) install(CallLogging) install(Routing) install(Sessions) { cookie<String>("SESSION_ID") } intercept(ApplicationCallPipeline.Features) { call.sessions.set<String>(generateNonce()) } install(SinglePageApplication) { defaultPage = "index.html" folderPath = "/" spaRoute = "" useFiles = false } } server.start(true) } }
2
Kotlin
0
3
4545320435da906da859f2b583bb7ca0281c6482
2,115
net.akehurst.language.editor
Apache License 2.0
presentation/src/main/java/presentation/sections/users/list/UsersFragment.kt
Bhanditz
168,963,623
true
{"Kotlin": 127389, "Java": 1243}
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package presentation.sections.users.list import android.support.v7.widget.GridLayoutManager import data.sections.users.User import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.users_fragment.* import org.base_app_android.R import presentation.foundation.views.BaseFragment import presentation.foundation.views.LayoutResFragment @LayoutResFragment(R.layout.users_fragment) class UsersFragment : BaseFragment<UsersPresenter.View, UsersPresenter>(), UsersPresenter.View { override val paginable by lazy { UserAdapter() } override val onRefreshSignals = PublishSubject.create<Unit>() override fun injectDagger() { getApplicationComponent().inject(this) } override fun initViews() { swipeRefreshUsers.setOnRefreshListener { onRefreshSignals.onNext(Unit) } rvUsers.layoutManager = GridLayoutManager(activity, 2) rvUsers.adapter = paginable } override fun userSelectedClicks(): Observable<User> { val clicks = PublishSubject.create<User>() paginable.setOnItemClickListener { _, _, position -> clicks.onNext(paginable.data[position]) } return clicks } override fun hideLoading() { swipeRefreshUsers.isRefreshing = false } override fun showLoading() { swipeRefreshUsers.isRefreshing = true } }
0
Kotlin
0
0
8384126c9251812205ab5264363b495d9efc52e7
1,986
KDirtyAndroid
Apache License 2.0
src/main/kotlin/org/valkyrienskies/core/networking/IVSPacketToClientSender.kt
ValkyrienSkies
329,044,944
false
null
package org.valkyrienskies.core.networking /** * Sends packets to clients * @param P The player object class */ interface IVSPacketToClientSender<P> { fun sendToClient(vsPacket: IVSPacket, player: P) }
0
Kotlin
1
1
7df4b5a935701e73f70fd2b262c6fb15bf871ca1
210
vs-core
Apache License 2.0
src/main/kotlin/io/github/pleahmacaka/example/kommands/CleanKommand.kt
PleahMaCaka
758,012,881
false
{"Kotlin": 48599, "Python": 5517}
package io.github.pleahmacaka.example.kommands import io.github.monun.kommand.kommand import org.bukkit.plugin.java.JavaPlugin fun cleanKommand(plugin: JavaPlugin) { plugin.kommand { register("clean") { executes { for (i in 0 until 100) { player.sendMessage("") } } } } }
0
Kotlin
0
0
05312f8c1d9d52ad89586dbea2c890a722fa49a9
373
world-border-survival
MIT License
acrarium/src/main/kotlin/com/faendir/acra/ui/component/grid/renderer/RouteButtonRenderer.kt
F43nd1r
91,593,043
false
{"Kotlin": 568918, "TypeScript": 32942, "Groovy": 2382, "JavaScript": 1819, "Dockerfile": 1313, "HTML": 1194, "Shell": 512, "CSS": 131}
/* * (C) Copyright 2021-2023 <NAME> (https://github.com/F43nd1r) * * 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.acra.ui.component.grid.renderer import com.faendir.acra.ui.ext.SizeUnit import com.faendir.acra.ui.ext.setMargin import com.vaadin.flow.component.Component import com.vaadin.flow.component.button.Button import com.vaadin.flow.component.button.ButtonVariant import com.vaadin.flow.component.icon.Icon import com.vaadin.flow.component.icon.VaadinIcon import com.vaadin.flow.data.renderer.ComponentRenderer import com.vaadin.flow.router.RouteParameters import com.vaadin.flow.router.RouterLink class RouteButtonRenderer<T>(icon: VaadinIcon, target: Class<out Component>, getTargetParams: (T) -> Map<String, String>) : ComponentRenderer<RouterLink, T>({ t -> RouterLink("", target, RouteParameters(getTargetParams(t))).apply { element.setAttribute("target", "_blank") element.setAttribute("rel", "noopener noreferrer") add(Button(Icon(icon)).apply { addThemeVariants(ButtonVariant.LUMO_TERTIARY) setMargin(0, SizeUnit.PIXEL) }) } }), InteractiveColumnRenderer
16
Kotlin
51
200
31576a37d2c1eb61bb1d2641d7b214c87ce23fe1
1,710
Acrarium
Apache License 2.0
theodolite/src/test/kotlin/rocks/theodolite/kubernetes/patcher/ImagePatcherTest.kt
cau-se
265,538,393
false
null
package rocks.theodolite.kubernetes.patcher import io.fabric8.kubernetes.api.model.apps.Deployment import io.quarkus.test.junit.QuarkusTest import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* @QuarkusTest internal class ImagePatcherTest: AbstractPatcherTest(){ @BeforeEach fun setUp() { resource = listOf(createDeployment()) patcher = ImagePatcher(container = "container") value = "testValue" } @AfterEach fun tearDown() { } @Test override fun validate() { patch() resource.forEach { assertTrue((it as Deployment).spec.template.spec.containers[0].image == value) } } }
0
Java
6
30
a24089fbef1283575e92d4f655bc5497044560dc
774
theodolite
Apache License 2.0
app/src/main/java/ru/example/studenthubclient/fragments/InformationPredictFragment.kt
urazm
775,666,109
false
{"Kotlin": 17989}
package ru.example.studenthubclient.fragments import android.content.Context import android.content.SharedPreferences import android.os.Bundle import androidx.fragment.app.Fragment import android.view.View import android.widget.TextView import androidx.core.content.ContextCompat import ru.example.studenthubclient.R class InformationPredictFragment : Fragment(R.layout.fragment_information_predict) { private lateinit var predictionTextView: TextView private lateinit var predictionGrantTextView: TextView private lateinit var finalPredictTextView: TextView private lateinit var sharedPreferences: SharedPreferences override fun onAttach(context: Context) { super.onAttach(context) sharedPreferences = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) predictionTextView = view.findViewById(R.id.student_performance_predict) finalPredictTextView = view.findViewById(R.id.final_predict) val savedStudentScorePredoct = sharedPreferences.getFloat("prediction_score", -1f) if (savedStudentScorePredoct != -1f) { predictionTextView.text = savedStudentScorePredoct.toString() } predictionGrantTextView = view.findViewById(R.id.min_grant_predict) val savedGrantPredict = sharedPreferences.getFloat("min_grant_score", -1f) if (savedGrantPredict != -1f) { predictionGrantTextView.text = savedGrantPredict.toString() } if(savedGrantPredict > savedStudentScorePredoct) { finalPredictTextView.text = GRANT_FAIL finalPredictTextView.setTextColor(ContextCompat.getColor(requireContext(), COLOR_FAIL)) } else finalPredictTextView.text = GRANT_SUCCESS } companion object { const val GRANT_SUCCESS = "Вы успешно пройдете на грант" const val GRANT_FAIL = "К сожалению Вы не пройдете на грант" const val COLOR_FAIL = android.R.color.holo_red_dark } }
0
Kotlin
0
0
7e9f3a22397302f67e1fe4616ca114f844ac444e
2,107
student-hub-client
MIT License
src/main/kotlin/io/marelso/shineyard/domain/Device.kt
marelso
867,021,662
false
{"Kotlin": 26263}
package io.marelso.shineyard.domain data class Device( var id: String? = null, val name: String, val sensors: Sensor )
0
Kotlin
0
0
ad98cd2122c5691bfb4d82a9fcd7dfa0f958d216
132
Yard-back
MIT License
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/duplicate/AbstractBlockDuplicate.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.planner.steps.storage.block.duplicate import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.SimpleStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.costs.Cost import com.github.kerubistan.kerub.planner.costs.NetworkCost import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.reservations.VirtualStorageReservation import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.InvertibleStep import com.github.kerubistan.kerub.planner.steps.base.AbstractUnAllocate import io.github.kerubistan.kroki.collections.update import java.math.BigInteger abstract class AbstractBlockDuplicate<T : VirtualStorageBlockDeviceAllocation> : AbstractOperationalStep, InvertibleStep { abstract val virtualStorageDevice: VirtualStorageDevice abstract val source: VirtualStorageBlockDeviceAllocation abstract val sourceHost: Host abstract val target: T abstract val targetHost: Host abstract val targetCapability : StorageCapability override fun isInverseOf(other: AbstractOperationalStep): Boolean = (other is AbstractUnAllocate<*> && other.vstorage == virtualStorageDevice && other.allocation == target && other.host == targetHost) override fun take(state: OperationalState): OperationalState = state.copy( vStorage = state.vStorage.update(virtualStorageDevice.id) { it.copy( dynamic = requireNotNull(it.dynamic) { "can't duplicate storage ${virtualStorageDevice.id}, it is not yet allocated" }.let { it.copy( allocations = it.allocations + target ) } ) }, //update the host storage allocation hosts = state.hosts.update(targetHost.id) { it.copy( dynamic = it.dynamic!!.copy( storageStatus = it.dynamic.storageStatus.map { storageStatus -> if(storageStatus.id == targetCapability.id) { when(storageStatus) { is SimpleStorageDeviceDynamic -> storageStatus.copy( freeCapacity = (storageStatus.freeCapacity - target.actualSize) .coerceAtLeast(BigInteger.ZERO) ) is CompositeStorageDeviceDynamic -> storageStatus.copy( reportedFreeCapacity = (storageStatus.freeCapacity - target.actualSize) .coerceAtLeast(BigInteger.ZERO) ) else -> TODO("Unhandled type: ${storageStatus.javaClass.name}") } } else { storageStatus } } ) ) } ) override fun reservations(): List<Reservation<*>> = listOf( UseHostReservation(targetHost), UseHostReservation(sourceHost), VirtualStorageReservation(virtualStorageDevice) ) override fun getCost(): List<Cost> = listOf( NetworkCost(hosts = listOf(sourceHost, targetHost), bytes = virtualStorageDevice.size.toLong()) ) }
109
Kotlin
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
3,508
kerub
Apache License 2.0
src/main/kotlin/dev/hypestsoftware/hackyeah2020/backend/utils/TokenInfo.kt
Hypest-Software
307,188,078
false
null
package dev.hypestsoftware.hackyeah2020.backend.utils import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails import org.springframework.security.oauth2.provider.token.TokenStore import org.springframework.web.context.annotation.RequestScope import kotlin.reflect.KMutableProperty import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties @Target(AnnotationTarget.PROPERTY) @Retention(AnnotationRetention.RUNTIME) @MustBeDocumented annotation class JwtField(val fieldKey: String) open class TokenInfo( @property:JwtField("user_uuid") open var userUUID: String? = null, @property:JwtField("user_name") open var userName: String? = null, ) { override fun toString(): String { return "TokenInfo(userUUID=$userUUID, userName=$userName)" } } abstract class TokenInfoConfiguration { private val tokenInfoFields = TokenInfo::class.memberProperties .filter { it.findAnnotation<JwtField>() != null } .mapNotNull { it as? KMutableProperty<*> } @Bean @RequestScope abstract fun createTokenInfo(): TokenInfo protected fun fillTokenInfoFromAuthenticationDetails( tokenInfo: TokenInfo, authenticationDetails: OAuth2AuthenticationDetails, tokenStore: TokenStore ) { val oAuth2AccessToken = tokenStore.readAccessToken(authenticationDetails.tokenValue) tokenInfoFields.forEach { // it can not be null because it was checked before.(see field declaration) val key = it.findAnnotation<JwtField>()!!.fieldKey val value = oAuth2AccessToken.additionalInformation[key] it.setter.call(tokenInfo, value) } } } @Configuration class TokenInfoConfigurationImpl : TokenInfoConfiguration() { @Autowired private lateinit var tokenStore: TokenStore override fun createTokenInfo(): TokenInfo { val authentication = SecurityContextHolder.getContext().authentication val authenticationDetails = authentication.details val tokenInfo = TokenInfo() if (authenticationDetails is OAuth2AuthenticationDetails) { fillTokenInfoFromAuthenticationDetails(tokenInfo, authenticationDetails, tokenStore) } return tokenInfo } }
0
Kotlin
0
0
6e05890106bcda0bf9b6a8892cb14c7b6757b442
2,546
alpha-backend
MIT License
app/src/main/java/com/team/nineg/data/db/CalendarRepositoryImpl.kt
cg072
749,293,681
false
{"Kotlin": 134964}
package com.team.nineg.data.db import com.team.nineg.data.db.dto.UserDto import com.team.nineg.data.db.remote.UserRemoteDataSource import retrofit2.Response import javax.inject.Inject class CalendarRepositoryImpl @Inject constructor( private val userRemoteDataSource: UserRemoteDataSource ): CalendarRepository { override suspend fun createUser(deviceId: String) { userRemoteDataSource.createUser(deviceId, "", "", "") } override suspend fun searchUser(deviceId: String): Response<UserDto> { return userRemoteDataSource.searchUser(deviceId) } }
0
Kotlin
0
0
11cf96dc0393754cb84c5dd72bf520e7434eb0d0
583
9G9G_FE
The Unlicense
app/src/main/kotlin/io/orangebuffalo/simpleaccounting/business/incometaxpayments/impl/IncomeTaxPaymentsRepositoryExtImpl.kt
orange-buffalo
154,902,725
false
{"Kotlin": 1129541, "TypeScript": 572465, "Vue": 277186, "SCSS": 30742, "JavaScript": 6817, "HTML": 633, "CSS": 10}
package io.orangebuffalo.simpleaccounting.business.incometaxpayments.impl import io.orangebuffalo.simpleaccounting.infra.jooq.fetchExactlyOne import io.orangebuffalo.simpleaccounting.infra.jooq.mapTo import io.orangebuffalo.simpleaccounting.services.persistence.model.Tables import io.orangebuffalo.simpleaccounting.business.incometaxpayments.IncomeTaxPaymentsRepositoryExt import io.orangebuffalo.simpleaccounting.business.incometaxpayments.IncomeTaxPaymentsStatistics import org.jooq.DSLContext import org.jooq.impl.DSL.coalesce import org.jooq.impl.DSL.sum import org.springframework.stereotype.Repository import java.time.LocalDate @Repository class IncomeTaxPaymentsRepositoryExtImpl( private val dslContext: DSLContext ) : IncomeTaxPaymentsRepositoryExt { private val taxPayment = Tables.INCOME_TAX_PAYMENT override fun getTaxPaymentsStatistics( fromDate: LocalDate, toDate: LocalDate, workspaceId: Long ): IncomeTaxPaymentsStatistics = dslContext .select(coalesce(sum(taxPayment.amount), 0L).mapTo(IncomeTaxPaymentsStatistics::totalTaxPayments)) .from(taxPayment) .where( taxPayment.workspaceId.eq(workspaceId), taxPayment.reportingDate.greaterOrEqual(fromDate), taxPayment.reportingDate.lessOrEqual(toDate) ) .fetchExactlyOne() }
66
Kotlin
0
1
794d455265298451c99eeb1fc1c3091f3b136bd4
1,358
simple-accounting
Creative Commons Attribution 3.0 Unported
card-stack/src/main/java/plznoanr/cardstack/animation/AnimationType.kt
plz-no-anr
697,075,708
false
{"Kotlin": 19452}
package plznoanr.cardstack.animation enum class AnimationType { None, Right, Left } internal fun AnimationType.isRight(): Boolean = this == AnimationType.Right
0
Kotlin
0
0
13633f9be7d967d312c7008e13bca9f645e41929
173
card-stack-for-compose
MIT License
notification-usecase/src/main/java/com/github/kamil1338/recording_app/collecting_use_case/dagger/NotificationProviderModule.kt
kamilpierudzki
217,856,689
false
null
package com.github.kamil1338.recording_app.collecting_use_case.dagger import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import androidx.core.app.NotificationManagerCompat import com.github.kamil1338.recording_app.collecting_use_case.NotificationManagerWrapper import com.github.kamil1338.recording_app.collecting_use_case.NotificationProvider import com.github.kamil1338.recording_app.collecting_use_case.NotificationUseCase import com.github.kamil1338.recording_app.collecting_use_case.NotificationUseCaseImpl import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class NotificationProviderModule { @Provides @Singleton fun provideNotificationManagerCompat(applicationContext: Context): NotificationManagerCompat = NotificationManagerCompat.from(applicationContext) @Provides @Singleton fun provideNotificationManagerWrapper(notificationManagerCompat: NotificationManagerCompat): NotificationManagerWrapper = NotificationManagerWrapper(notificationManagerCompat) @Provides @Singleton fun provideNotificationChannel(channelIds: ChannelIds): NotificationChannels { val summaryNotificationChannel = NotificationChannel( channelIds.summaryChannelId, "Start new collecting", NotificationManager.IMPORTANCE_HIGH ) val savingNotificationChannel = NotificationChannel( channelIds.savingChannelId, "Batch collected", NotificationManager.IMPORTANCE_HIGH ) val workInProgressNotificationChannel = NotificationChannel( channelIds.workInProgressChannelId, "Work in progress", NotificationManager.IMPORTANCE_HIGH ) return NotificationChannels( summaryNotificationChannel, savingNotificationChannel, workInProgressNotificationChannel ) } data class NotificationChannels( val summaryNotificationChannel: NotificationChannel, val savingNotificationChannel: NotificationChannel, val workInProgressNotificationChannel: NotificationChannel ) @Provides @Singleton fun provideChannelIds(): ChannelIds = ChannelIds( "recording_app_starting_collecting_channel", "recording_app_successful_saving_channel", "recording_app_work_in_progress_channel" ) data class ChannelIds( val summaryChannelId: String, val savingChannelId: String, val workInProgressChannelId: String ) @Provides @Singleton fun provideNotificationProvider( applicationContext: Context, channelIds: ChannelIds ): NotificationProvider = NotificationProvider( applicationContext, channelIds.summaryChannelId, channelIds.savingChannelId, channelIds.workInProgressChannelId ) @Provides @Singleton fun provideNotificationUseCase( notificationManagerWrapper: NotificationManagerWrapper, notificationChannels: NotificationChannels, notificationProvider: NotificationProvider ): NotificationUseCase = NotificationUseCaseImpl( notificationManagerWrapper, notificationChannels.summaryNotificationChannel, notificationChannels.savingNotificationChannel, notificationChannels.workInProgressNotificationChannel, notificationProvider ) }
0
Kotlin
0
0
710ad15cd83504ae6383c6121ef76b8f0f83f1e0
3,517
User-Activity-Classification-Android
Apache License 2.0
src/main/kotlin/me/lensvol/blackconnect/actions/ReformatWholeFileAction.kt
lensvol
261,833,378
false
null
package me.lensvol.blackconnect.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import me.lensvol.blackconnect.BlackdResponse import me.lensvol.blackconnect.CodeReformatter import me.lensvol.blackconnect.DocumentUtil import me.lensvol.blackconnect.settings.BlackConnectProjectSettings import me.lensvol.blackconnect.ui.NotificationManager class ReformatWholeFileAction : AnAction(), DumbAware { companion object { private val logger = Logger.getInstance(ReformatWholeFileAction::class.java.name) fun reformatWholeDocument( fileName: String, project: Project, document: Document ) { val configuration = BlackConnectProjectSettings.getInstance(project) val codeReformatter = project.service<CodeReformatter>() val notificationService = project.service<NotificationManager>() val documentUtil = project.service<DocumentUtil>() codeReformatter.process( fileName, document.text, fileName.endsWith(".pyi") ) { response -> when (response) { is BlackdResponse.Blackened -> { documentUtil.updateCodeInDocument(document) { logger.debug("Code is going to be updated in $document") if (!documentUtil.isInUndoRedo()) { document.setText(response.sourceCode) } } } BlackdResponse.NoChangesMade -> { } is BlackdResponse.SyntaxError -> { if (configuration.showSyntaxErrorMsgs) { notificationService.showError("Source code contained syntax errors.") } } is BlackdResponse.InternalError -> { notificationService.showError( "Internal server error, please see blackd output.", viewPromptText = "View response", additionalInfo = response.reason ) } is BlackdResponse.UnknownStatus -> notificationService.showError( "Something unexpected happened:<br>${response.responseText}" ) is BlackdResponse.InvalidRequest -> { /* Sadly, blackd does not reply with easily parseable error codes, so we have to implement crude error detection heuristics here. This one specifically looks for unsupported target versions, as different versions of blackd may have different sets of them. */ if (response.reason.startsWith("Invalid value for X-Python-Variant")) { val startPos = response.reason.indexOf(": ") val endPos = response.reason.indexOf(" is not supported") val unsupportedVersion = response.reason.slice(startPos + 2..endPos) notificationService.showError( "Your version of <b>blackd</b> does not support targeting " + "Python <b>$unsupportedVersion</b>.", ) } else { notificationService.showError( "Server did not understand our request.<br>Maybe you need to connect over SSL?", viewPromptText = "View response", additionalInfo = response.reason ) } } } } } } override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val editor = FileEditorManagerEx.getInstance(project).selectedTextEditor ?: return val vFile: VirtualFile? = FileDocumentManager.getInstance().getFile(editor.document) val fileName = vFile?.name ?: "unknown" reformatWholeDocument(fileName, project, editor.document) } override fun update(event: AnActionEvent) { event.presentation.isEnabled = false val project: Project = event.project ?: return val vFile: VirtualFile = event.getData(PlatformDataKeys.VIRTUAL_FILE) ?: return val codeReformatter = project.service<CodeReformatter>() event.presentation.isEnabled = codeReformatter.isFileSupported(vFile) } }
35
Kotlin
9
74
d5b728dc7f07b97ed4e19c067f9b6ad6a7052b02
5,280
intellij-blackconnect
MIT License
src/jvmMain/kotlin/model/CliContext.kt
hapifhir
285,363,653
false
null
package model actual typealias CliContext = org.hl7.fhir.validation.cli.model.CliContext
18
Kotlin
6
9
6c0eaacfd2afc6d5f95bed143e31b7338cb144f1
90
org.hl7.fhir.validator-wrapper
Apache License 2.0
dm-transport-main-mp/src/commonMain/kotlin/ModelForRequest/cruds/UpdateWorkoutRequest.kt
otuskotlin
382,547,521
false
null
package ModelForRequest.cruds import ModelForRequest.Debug import ModelForRequest.UpdateWorkout import kotlinx.serialization.* /** * Структура для запроса обновления существующей тренеровки * @param messageType * @param requestId * @param debug * @param updateWorkout */ @Serializable data class UpdateWorkoutRequest ( @SerialName(value = "messageType") override val messageType: kotlin.String? = null, @SerialName(value = "requestId") override val requestId: kotlin.String? = null, @SerialName(value = "debug") override val debug: Debug? = null, @SerialName(value = "updateWorkout") val updateWorkout: UpdateWorkout? = null ) : BaseMessage, BaseRequest
1
Kotlin
1
0
ab962d306cab6512c5cffe61b87e810ddc28f193
681
ok-202105-workout-dm
MIT License
src/main/kotlin/com/pambrose/srcref/Api.kt
pambrose
494,865,253
false
null
package com.pambrose.srcref import com.pambrose.srcref.QueryParams.ACCOUNT import com.pambrose.srcref.QueryParams.BEGIN_OCCURRENCE import com.pambrose.srcref.QueryParams.BEGIN_OFFSET import com.pambrose.srcref.QueryParams.BEGIN_REGEX import com.pambrose.srcref.QueryParams.BEGIN_TOPDOWN import com.pambrose.srcref.QueryParams.BRANCH import com.pambrose.srcref.QueryParams.END_OCCURRENCE import com.pambrose.srcref.QueryParams.END_OFFSET import com.pambrose.srcref.QueryParams.END_REGEX import com.pambrose.srcref.QueryParams.END_TOPDOWN import com.pambrose.srcref.QueryParams.PATH import com.pambrose.srcref.QueryParams.REPO import com.pambrose.srcref.Urls.srcrefToGithubUrl @Suppress("unused") object Api { fun srcrefUrl( account: String, repo: String, path: String, beginRegex: String, beginOccurrence: Int = 1, beginOffset: Int = 0, beginTopDown: Boolean = true, endRegex: String = "", endOccurrence: Int = 1, endOffset: Int = 0, endTopDown: Boolean = true, prefix: String = "https://www.srcref.com", branch: String = "master", escapeHtml4: Boolean = false, ): String = srcrefToGithubUrl( mapOf( ACCOUNT.arg to account, REPO.arg to repo, BRANCH.arg to branch, PATH.arg to path, BEGIN_REGEX.arg to beginRegex, BEGIN_OCCURRENCE.arg to beginOccurrence.toString(), BEGIN_OFFSET.arg to beginOffset.toString(), BEGIN_TOPDOWN.arg to beginTopDown.toString(), END_REGEX.arg to endRegex, END_OCCURRENCE.arg to endOccurrence.toString(), END_OFFSET.arg to endOffset.toString(), END_TOPDOWN.arg to endTopDown.toString(), ), escapeHtml4, prefix, ) }
0
Kotlin
0
0
7990b680758ee1a53a3e388f62a95e9fb1ff03a8
1,728
srcref
Apache License 2.0
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/profile/ProfileViewState.kt
denchic45
435,895,363
false
{"Kotlin": 2107790, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.ui.profile import com.denchic45.stuiversity.api.studygroup.model.StudyGroupResponse import com.denchic45.stuiversity.api.user.model.UserResponse data class ProfileViewState( val fullName: String, val avatarUrl: String, val personalDate: PersonalData?, val studyGroups: List<StudyGroupResponse>, val allowEditConfidential: Boolean, val allowEditProfile: Boolean, val allowUpdateAvatar: Boolean, ) { data class PersonalData(val email: String) } fun UserResponse.toProfileViewState(studyGroups:List<StudyGroupResponse>,allowEdit: Boolean, isOwned: Boolean) = ProfileViewState( fullName = fullName, avatarUrl = avatarUrl, personalDate = account.email.let { ProfileViewState.PersonalData(it) }, studyGroups = studyGroups, allowEditConfidential = allowEdit, allowEditProfile = allowEdit, allowUpdateAvatar = isOwned )
0
Kotlin
0
6
58be67e4bb506b69f24012caffc3c035ba79db82
911
Studiversity
Apache License 2.0
database/src/main/java/uk/co/alt236/bluetoothconnectionlog/db/entities/LogEntry.kt
alt236
196,390,058
false
null
package uk.co.alt236.bluetoothconnectionlog.db.entities import androidx.room.ColumnInfo import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey const val TABLE_NAME = "log_entries" @Entity(tableName = TABLE_NAME) data class LogEntry( @ColumnInfo(name = "event") val event: Event, @ColumnInfo(name = "timestamp") val timestamp: Long, @Embedded(prefix = "device_") val device: BtDevice, @Embedded(prefix = "location_") val location: Location ) { @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) var id: Int = 0 fun getDisplayName(): String { return device.getDisplayName() } }
0
Kotlin
2
1
51c7f8cbd70165ba089d469a0901fe472d71f3d4
684
bluetooth-connection-log
Apache License 2.0
basic-example/product/src/test/kotlin/com/pintailconsultingllc/product/controllers/dto/CategoryDTOTest.kt
cebartling
347,271,498
false
null
package com.pintailconsultingllc.product.controllers.dto import com.pintailconsultingllc.product.factories.createCategoryEntity import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.util.* @DisplayName("CategoryDTO unit tests") internal class CategoryDTOTest { private val entity = createCategoryEntity( id = UUID.randomUUID(), name = "Foobar" ) private var categoryDTO: CategoryDTO? = null @Nested @DisplayName("constructor") inner class ContructorTests { @BeforeEach fun doBeforeEachTest() { categoryDTO = CategoryDTO(entity = entity) } @Test fun `should set the data transfer object's ID`() { assertThat(categoryDTO?.id).isEqualTo(entity.id) } @Test fun `should set the data transfer object's name`() { assertThat(categoryDTO?.name).isEqualTo(entity.name) } @Test fun `should set the data transfer object's version`() { assertThat(categoryDTO?.version).isEqualTo(entity.version) } @Test fun `should set the data transfer object's created at timestamp`() { assertThat(categoryDTO?.createdAt).isEqualTo(entity.createdAt) } @Test fun `should set the data transfer object's updated at timestamp`() { assertThat(categoryDTO?.updatedAt).isEqualTo(entity.updatedAt) } @Test fun `should set the data transfer object's created by string`() { assertThat(categoryDTO?.createdBy).isEqualTo(entity.createdBy) } @Test fun `should set the data transfer object's updated by string`() { assertThat(categoryDTO?.updatedBy).isEqualTo(entity.updatedBy) } } }
0
Kotlin
0
0
2687b751e3eb3d2482c9548791dc14df75330a70
1,945
saga-pattern-examples
MIT License
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathWithExprPsiImpl.kt
rhdunn
62,201,764
false
null
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathWithExpr import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmConcatenatingExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression class XPathWithExprPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathWithExpr, XpmSyntaxValidationElement { // region XpmConcatenatingExpression override val expressionElement: PsiElement get() = this override val expressions: Sequence<XpmExpression> get() = when (val expr = children().filterIsInstance<XpmExpression>().firstOrNull()) { null -> emptySequence() is XpmConcatenatingExpression -> expr.expressions else -> sequenceOf(expr) } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = firstChild // endregion }
47
Kotlin
4
25
d363dad28df1eb17c815a821c87b4f15d2b30343
1,830
xquery-intellij-plugin
Apache License 2.0
featureA/src/main/java/dev/kafumi/myapplication/featurea/HomeViewModel.kt
kafumi
180,918,788
false
null
package dev.kafumi.myapplication.featurea import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import dev.kafumi.myapplication.data.UserRepository import dev.kafumi.myapplication.model.User import timber.log.Timber class HomeViewModel : ViewModel() { private val user = MutableLiveData<User>() val loginId = user.map { it.loginId } val displayName = user.map { it.displayName } val mailAddress = user.map { it.mailAddress } fun onButtonClicked() { Timber.d("onButtonClicked") user.value = UserRepository.getLoginUser() } private fun <X, Y> LiveData<X>.map(body: (X) -> Y): LiveData<Y> { return Transformations.map(this, body) } }
0
Kotlin
0
0
de25c2faffced62f1e409cb8fb404f08804ccc33
792
android-kotlin-gradle-sample
The Unlicense
app/src/main/java/com/example/runworkshop/ui/view/recyclerviews/InstitutoAdapter.kt
MrPartner
624,642,559
false
null
package com.example.runworkshop.ui.view.recyclerviews import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.runworkshop.R import com.example.runworkshop.data.model.InstitutoModel class InstitutoAdapter(var institutoList: List<InstitutoModel> = emptyList()) : RecyclerView.Adapter<InstitutoViewHolder>() { fun updateList(institutoList: List<InstitutoModel>){ this.institutoList = institutoList notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InstitutoViewHolder { return InstitutoViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.item_rvinstituto, parent, false) ) } override fun getItemCount(): Int { return institutoList.size } override fun onBindViewHolder(viewholder: InstitutoViewHolder, position: Int) { viewholder.bind(institutoList[position]) } }
0
Kotlin
0
0
01a00751b85448d0d00a9e640108dc9777b02516
996
RunWorkshop
Apache License 2.0
Android/app/src/main/java/com/plantry/presentation/community/FragmentCommunity.kt
GDSC-SWU
736,526,220
false
{"Kotlin": 312709, "Java": 284329, "Python": 1946, "Dockerfile": 370}
package com.plantry.presentation.community import com.plantry.R import com.plantry.coreui.base.BindingFragment import com.plantry.databinding.FragmentCommunityBinding class FragmentCommunity : BindingFragment<FragmentCommunityBinding>(R.layout.fragment_community) { override fun initView() { } }
0
Kotlin
0
3
7a8074ba1a76027fe09077dd490c8c7eb8a87c9f
306
2024-Plantry-SolutionChallenge
MIT License
koleton-sample/src/main/kotlin/koleton/sample/utils/Constants.kt
ericktijerou
267,768,682
false
null
package koleton.sample.utils const val DEFAULT_DELAY: Long = 3000 const val DEFAULT_PAGE_SIZE: Int = 10 const val ITEM_COUNT: Int = 3
6
null
12
87
58b7a54674ee3bf0c2351f21101181ca203a3d06
134
koleton
Apache License 2.0
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/flows/flowbuilders/1_flow_builders_basics.kt
regxl2
775,843,577
false
{"Kotlin": 283103}
package com.lukaslechner.coroutineusecasesonandroid.flows.flowbuilders import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* suspend fun main(){ val firstFlow = flowOf<Int>(1).collect{emittedValue -> println("First flow: $emittedValue") } val secondFlow = flowOf<Int>(1, 2, 3) secondFlow.collect{emittedValue -> println("Second flow: $emittedValue") } // we can also convert the list into flow using asFlow() function listOf<Int>(1, 2, 3).asFlow().collect{ emittedValue -> println("Third flow: $emittedValue") } // this below flow builder is flexible because we can put arbitrary code // inside the flow builder. flow{ delay(2000) emit("The value is emitted after 2000ms") }.collect{ emittedValue -> println("Fourth flow: $emittedValue") } // Inside flow builder we can also emit the values from other flow flow{ delay(2000) emit("The value is emitted after 2000ms") // secondFlow.collect{emittedValue -> // emit(emittedValue) // } // shorthand of the above code:- emitAll(secondFlow) }.collect{ emittedValue -> println("Fifth flow: $emittedValue") } }
0
Kotlin
0
0
3c88fd943d408ffae7ae429b9f05607d21da2f38
1,249
coroutine-and-flows
Apache License 2.0
core-starter/src/main/kotlin/com/labijie/application/exception/DataOwnerMissMatchedException.kt
hongque-pro
309,874,586
false
{"Kotlin": 1219832, "Java": 72766}
package com.labijie.application.exception import com.labijie.application.ApplicationErrors import com.labijie.application.ErrorCodedException /** * Created with IntelliJ IDEA. * @author Anders Xiao * @date 2019-09-28 */ class DataOwnerMissMatchedException(message:String? = null) : ErrorCodedException(ApplicationErrors.DataOwnerMissMatched, message)
0
Kotlin
0
7
3ed6fc2a981e798e9ffc250180185280abb2d989
360
application-framework
Apache License 2.0
app/src/main/java/chiarajm/android/base/sample/domain/usecases/task/CreateTask.kt
chiara-jm
161,471,167
false
null
package chiarajm.android.base.sample.domain.usecases.task import chiarajm.android.base.sample.data.TaskDataSource import chiarajm.android.base.sample.data.model.Task import chiarajm.android.base.sample.domain.usecases.UseCase import javax.inject.Inject class CreateTask @Inject constructor( private val what: String, private val time: Long, private val dataSource: TaskDataSource ) : UseCase<Task> { override operator fun invoke() = dataSource.save(Task(what, time)) }
0
Kotlin
0
0
3df3f75eba30bc147187923dab81e538f8ab7292
501
task-scheduler-sample
Apache License 2.0
src/main/kotlin/br/com/zupacademy/nicolecatarina/client/bcb/CreatePixKeyRequest.kt
NicoleCatarina
399,212,119
true
{"Kotlin": 49503}
package br.com.zupacademy.nicolecatarina.client.bcb import br.com.zupacademy.nicolecatarina.client.itau.AccountResponse import br.com.zupacademy.nicolecatarina.pixkey.KeyType import br.com.zupacademy.nicolecatarina.pixkey.registry.NewPixKey data class CreatePixKeyRequest( val NewPixKey: NewPixKey, val accountResponse: AccountResponse ){ val keyType: KeyType = NewPixKey.keyType val key: String = NewPixKey.key val bankAccount: BankAccountRequest = BankAccountRequest( participant = accountResponse.institution.ispb, branch = accountResponse.agency, accountNumber = accountResponse.accountNumber, accountType = BCBAccountType.getType(accountResponse.accountType) ) val owner: OwnerRequest = OwnerRequest( PersonType.NATURAL_PERSON, accountResponse.accountHolder.nome, accountResponse.accountHolder.cpf ) }
0
Kotlin
0
0
42b17c2d35839ba086971691e72e10f44e4c12a5
935
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
domain/src/main/kotlin/de/dhbw/ka/domain/aggregates/RentalInstrument.kt
liza-kl
429,557,945
false
{"Kotlin": 73998, "JavaScript": 29965, "HTML": 1990, "Dockerfile": 706, "CSS": 606, "Shell": 337}
package de.dhbw.ka.domain.aggregates import de.dhbw.ka.domain.valueobjects.InstrumentIdentification data class RentalInstrument( val instrumentIdentification: InstrumentIdentification, val quantity: Int )
0
Kotlin
0
2
f6eefb986e4bfc3c229f7a7d3a948d6fb9770626
214
ase-project
MIT License
src/main/kotlin/dev/sublab/substrate/modules/DefaultModuleProvider.kt
sublabdev
540,213,973
false
{"Kotlin": 157012}
/** * * Copyright 2023 SUBSTRATE LABORATORY LLC <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package dev.sublab.substrate.modules import com.sun.net.httpserver.Filter.Chain import dev.sublab.substrate.ScaleCodecProvider import dev.sublab.substrate.SubstrateClient import dev.sublab.substrate.hashers.HashersProvider import dev.sublab.substrate.modules.chain.ChainModule import dev.sublab.substrate.modules.chain.ChainModuleClient import dev.sublab.substrate.modules.payment.PaymentModule import dev.sublab.substrate.modules.payment.PaymentModuleClient import dev.sublab.substrate.modules.state.StateModule import dev.sublab.substrate.modules.state.StateModuleClient import dev.sublab.substrate.modules.system.SystemModule import dev.sublab.substrate.modules.system.SystemModuleClient import dev.sublab.substrate.rpcClient.Rpc /** * Default module rpc provider */ class DefaultModuleProvider( private val codecProvider: ScaleCodecProvider, private val rpc: Rpc, private val hashersProvider: HashersProvider ): InternalModuleProvider { lateinit var client: SubstrateClient override val chain: ChainModule get() = ChainModuleClient(rpc) override val state: StateModule get() = StateModuleClient(codecProvider.hex, rpc, hashersProvider) override val system: SystemModule get() = SystemModuleClient(client.constants, client.storage) override val payment: PaymentModule get() = PaymentModuleClient(codecProvider.hex, rpc) // Supply dependencies /** * Sets substrate client to be used */ override fun workingWithClient(client: SubstrateClient) { this.client = client } }
3
Kotlin
3
6
8a5469b2820c74f4a5a85576db4fdd681cfefa94
2,166
substrate-client-kotlin
Apache License 2.0
taxi-cli/src/main/java/lang/taxi/cli/plugins/internal/PublishPluginPlugin.kt
taxilang
601,101,781
false
null
package lang.taxi.cli.plugins.internal import com.beust.jcommander.IStringConverter import lang.taxi.cli.plugins.InternalPlugin import lang.taxi.cli.utils.log import lang.taxi.plugins.Artifact import lang.taxi.plugins.ArtifactId import lang.taxi.plugins.PluginWithConfig import org.springframework.core.io.UrlResource import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.util.LinkedMultiValueMap import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.RestTemplate import java.io.File /** * Plugin which publishes other plugins */ @Component class PublishPluginPlugin( private val restTemplate: RestTemplate = RestTemplate() ) : InternalPlugin, PluginWithConfig<PublishPluginConfig> { override val artifact = Artifact.parse("publish") private lateinit var config: PublishPluginConfig override fun setConfig(config: PublishPluginConfig) { this.config = config } fun publish() { // val zip = createZip() val fileToRelease = File(config.file) require(fileToRelease.exists()) { "File ${fileToRelease.canonicalPath} doesn't exist" } log().info("Publishing plugin ${config.id} from ${fileToRelease.canonicalPath} to ${config.taxiHub}") val releaseType = ReleaseType.parse(config.version) val releaseUrlParam = if (releaseType != null) "?releaseType=$releaseType" else "/${config.version}" val url = "${config.taxiHub}/projects/${config.id.group}/${config.id.name}/releases$releaseUrlParam" upload(fileToRelease, url) } private fun upload(fileToRelease: File, url: String) { val map: LinkedMultiValueMap<String, Any> = LinkedMultiValueMap() map.put("file", listOf(UrlResource(fileToRelease.toURI()))) val headers = HttpHeaders() headers.contentType = MediaType.MULTIPART_FORM_DATA val requestEntity = HttpEntity(map, headers) try { val result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Release::class.java) val release = result.body log().info("Released version ${release.version} with id of ${release.identifier}") } catch (error: HttpClientErrorException) { log().error("Failed to upload", error.message) } } // private fun createZip(): File { // val zipFilePath = File.createTempFile(config.id.fileSafeIdentifier, ".zip") // val zipFile = ZipFile(zipFilePath) // val matcher = FileSystems.getDefault().getPathMatcher("glob:${config.include}") // File(config.artifactDir) // .walkTopDown() // .filter { matcher.matches(it.toPath().fileName) } // .forEach { // if (it.isFile) { // log().info("Adding file ${it.canonicalPath}") // val zipParameters = ZipParameters() // zipParameters.compressionMethod = Zip4jConstants.COMP_DEFLATE // zipParameters.compressionLevel = Zip4jConstants.DEFLATE_LEVEL_NORMAL // zipFile.addFile(it, zipParameters) // } // } // return zipFilePath // } } data class Release( val identifier: String, val version: String) data class PublishPluginConfig(val taxiHub: String, val file: String, val id: ArtifactId, // Note : Can be a number or a ReleaseType val version: String ) enum class ReleaseType { MAJOR, MINOR, PATCH; companion object { fun parse(value: String): ReleaseType? { return if (ReleaseType.values().map { it.name }.contains(value.toUpperCase())) { valueOf(value.toUpperCase()); } else { null } } } }
8
null
5
75
b94c71c7c8751c05c4f466c58c4483dac3f2e421
4,100
taxilang
Apache License 2.0
app/src/main/java/com/skydoves/androidveildemo/SecondActivity.kt
Fukienren
195,665,619
true
{"Kotlin": 40144}
package com.skydoves.androidveildemo import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager import com.skydoves.androidveil.VeiledItemOnClickListener import com.skydoves.androidveildemo.profile.ListItemUtils import com.skydoves.androidveildemo.profile.Profile import com.skydoves.androidveildemo.profile.ProfileAdapter import com.skydoves.androidveildemo.profile.ProfileViewHolder import kotlinx.android.synthetic.main.activity_second.* class SecondActivity : AppCompatActivity(), VeiledItemOnClickListener, ProfileViewHolder.Delegate { private val adapter by lazy { ProfileAdapter(this) } @SuppressLint("CheckResult") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) // sets VeilRecyclerView's properties veilFrameView.setVeilLayout(R.layout.item_preview, this) veilFrameView.setAdapter(adapter) veilFrameView.setLayoutManager(GridLayoutManager(this, 2)) veilFrameView.addVeiledItems(12) // add profile times to adapter adapter.addProfiles(ListItemUtils.getProfiles(this)) } /** OnItemClickListener by Veiled Item */ override fun onItemClicked(pos: Int) { Toast.makeText(this, getString(R.string.msg_loading), Toast.LENGTH_SHORT).show() } /** OnItemClickListener by User Item */ override fun onItemClickListener(profile: Profile) { startActivity(Intent(this, DetailActivity::class.java)) } }
0
Kotlin
0
0
508f32fe1d6394587476ebbdf6992b602bcf8250
1,616
AndroidVeil
Apache License 2.0
src/day17/Day17.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day17 import println import readInputAsText import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt data class Target(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int) private fun String.parseTarget() = "target area: x=([-\\d]+)..([-\\d]+), y=([-\\d]+)..([-\\d]+)" .toRegex().matchEntire(this)!! .groupValues .drop(1) .map { it.toInt() } .let { Target(it[0], it[1], it[2], it[3]) } /* If we look only at the y trajectory then it has to pass through 0 as it comes down since it is symmetrical. The same increments going up happen in reverse going down. The downward path is a series of triangular numbers and the problem consists in maximizing these. The largest possible jump is from 0 to the min y value in the target. The upward path is the same series of triangular numbers without this last jump. */ private fun Target.maxHeightPossible(): Int { val initialY = -minY - 1 return initialY * (initialY + 1) / 2 } /* minX = n(n-1)/2 where n is the initial X velocity */ private fun Target.minXVelocity() = ceil((-1 + sqrt(1.0 + 8 * minX)) / 2).toInt() private fun Target.trajectoryHits(initialXV: Int, initialYV: Int): Boolean { var xV = initialXV var yV = initialYV var x = xV var y = yV while (y > minY && !isHit(x, y)) { yV-- xV = (xV - 1).coerceAtLeast(0) x += xV y += yV } return isHit(x, y) } private fun Target.isHit(x: Int, y: Int) = x in minX..maxX && y in minY..maxY private fun Target.maxYVelocity() = floor((-1 + sqrt(1 + 8 * maxHeightPossible().toFloat())) / 2).toInt() fun part1(input: String): Int { return input.parseTarget().maxHeightPossible() } fun part2(input: String): Int { val target = input.parseTarget() return (target.minXVelocity()..target.maxX) .flatMap { xV -> (target.minY..target.maxYVelocity()).map { yV -> Pair(xV, yV) } } .count { (xV, yV) -> target.trajectoryHits(xV, yV) } } fun main() { check(part1(readInputAsText("day17/input_test")) == 45) check(part2(readInputAsText("day17/input_test")) == 112) val input = readInputAsText("day17/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
2,244
advent-of-code-2021
Apache License 2.0
features/image_viewer/src/main/java/es/littledavity/features/image/viewer/ImageViewerUiState.kt
Benderinos
260,322,264
false
null
/* * Copyright 2021 dalodev */ package es.littledavity.features.image.viewer sealed class ImageViewerUiState { object Loading : ImageViewerUiState() data class Error(val error: Throwable) : ImageViewerUiState() data class Result(val urls: List<String>, val selectedPosition: Int) : ImageViewerUiState() }
0
Kotlin
0
1
91d5d355e4d83b1cc97b6ec360edab39f0baaf12
320
ChorboAgenda
The Unlicense
todo/src/main/java/dev/sanson/donezo/todo/storage/LocalStorageInitialiser.kt
jamiesanson
338,439,053
false
null
package dev.sanson.donezo.todo.storage import dev.sanson.donezo.arch.di.inject import dev.sanson.donezo.arch.redux.asyncAction import dev.sanson.donezo.model.TodoList import dev.sanson.donezo.todo.Action import dev.sanson.donezo.todo.AppState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.reduxkotlin.Store /** * Thunk function for loading initial state from local storage asynchronously */ private fun LoadFromStorage(initialState: List<TodoList>) = asyncAction<AppState> { dispatch, _ -> val storage by inject<LocalStorage>() dispatch(Action.ListsLoaded(storage.load().ifEmpty { initialState })) } fun Store<AppState>.initialiseLocalStorage(initialState: List<TodoList>) { // Load lists from storage immediately dispatch(LoadFromStorage(initialState)) // Publish changes back to local storage subscribe { val state = getState() val scope by inject<CoroutineScope>() scope.launch { val storage by inject<LocalStorage>() if (storage.load() == state.lists) return@launch storage.save(state.lists) } } }
3
Kotlin
0
9
17642ee8d4aee9ed099b7abcd28f1b05cbb4b4c0
1,146
donezo
Apache License 2.0
apk_explorer/src/main/java/com/domker/doctor/explorer/main/PlaceholderFragment.kt
MaisonWan
330,649,879
false
{"Kotlin": 411869, "Java": 274094}
package com.domker.app.doctor.explorer.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.domker.app.doctor.explorer.R /** * A placeholder fragment containing a simple view. */ class PlaceholderFragment : Fragment() { private lateinit var pageViewModel: PageViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) pageViewModel = ViewModelProvider(this)[PageViewModel::class.java].apply { setIndex(arguments?.getInt("section_number") ?: 1) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_apk_explorer, container, false) val textView: TextView = root.findViewById(R.id.section_label) pageViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } }
0
Kotlin
0
0
df13773545f278b8e2946a93bd0b30477e176120
1,190
AppDoctor
Apache License 2.0
app/src/main/java/com/aws/amazonlocation/ui/main/signin/CustomSpinnerAdapter.kt
aws-geospatial
625,008,140
false
{"Kotlin": 1631818, "Java": 77291, "JavaScript": 5632, "Ruby": 1352, "Shell": 797}
package com.aws.amazonlocation.ui.main.signin import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import androidx.core.content.ContextCompat import com.aws.amazonlocation.R class CustomSpinnerAdapter(context: Context, private val items: ArrayList<String>) : ArrayAdapter<String>(context, 0, items) { private var mSelectedIndex = -1 fun setSelection(position: Int) { mSelectedIndex = position notifyDataSetChanged() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: LayoutInflater.from(context) .inflate(R.layout.spinner_item, parent, false) val textView = view.findViewById<TextView>(R.id.spinner_item_text) textView.text = items[position] return view } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: LayoutInflater.from(context) .inflate(R.layout.spinner_dropdown_item, parent, false) val textView = view.findViewById<TextView>(R.id.spinner_item_text) textView.text = items[position] if (position == mSelectedIndex) { view.setBackgroundColor(ContextCompat.getColor(context, R.color.color_selected_spinner_bg)) } else { view.setBackgroundColor(Color.TRANSPARENT) } return view } }
4
Kotlin
3
0
7a16c17c0ca4410674ad5f12e4104f58d791bd02
1,568
amazon-location-features-demo-android
MIT No Attribution
dagger/testSrc/com/android/tools/idea/dagger/index/psiwrappers/ImportHelperTest.kt
JetBrains
60,701,247
false
{"Kotlin": 47327090, "Java": 36711107, "HTML": 1217549, "Starlark": 856686, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28699, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7828, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.dagger.index.psiwrappers import com.android.tools.idea.testing.AndroidProjectRule import com.android.tools.idea.testing.onEdt import com.google.common.truth.Truth.assertThat import com.intellij.ide.highlighter.JavaFileType import com.intellij.psi.PsiJavaFile import com.intellij.testFramework.RunsInEdt import com.intellij.testFramework.fixtures.CodeInsightTestFixture import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.psi.KtFile import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @RunsInEdt class ImportHelperTest { @get:Rule val projectRule = AndroidProjectRule.inMemory().onEdt() private lateinit var myFixture: CodeInsightTestFixture @Before fun setup() { myFixture = projectRule.fixture } @Test fun kotlin_getPossibleAnnotationText_noImports() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun kotlin_getPossibleAnnotationText_starImports() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.inject.* """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun kotlin_getPossibleAnnotationText_directImport() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.inject.Inject """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun kotlin_getPossibleAnnotationText_importWithAlias() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.inject.Inject as OtherInject """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "OtherInject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun `kotlin_getPossibleAnnotationText_allTheImports!!!`() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.inject.* import javax.inject.Inject import javax.inject.Inject as OtherInject """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject", "OtherInject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun kotlin_getPossibleAnnotationText_nestedClasses() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import com.other.Foo1 import com.other.Foo2.Inner import com.other.Foo3 as MyFoo3 import com.other.Foo4 import com.other.Foo4.Inner4 """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("com.example.Foo0.Inner")) .containsExactly("com.example.Foo0.Inner", "Foo0.Inner") assertThat(importHelper.getPossibleAnnotationText("com.example.Foo0.Inner.NestedAgain")) .containsExactly("com.example.Foo0.Inner.NestedAgain", "Foo0.Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo1.Inner")) .containsExactly("com.other.Foo1.Inner", "Foo1.Inner") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo1.Inner.NestedAgain")) .containsExactly("com.other.Foo1.Inner.NestedAgain", "Foo1.Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo2.Inner")) .containsExactly("com.other.Foo2.Inner", "Inner") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo2.Inner.NestedAgain")) .containsExactly("com.other.Foo2.Inner.NestedAgain", "Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo3.Inner")) .containsExactly("com.other.Foo3.Inner", "MyFoo3.Inner") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo3.Inner.NestedAgain")) .containsExactly("com.other.Foo3.Inner.NestedAgain", "MyFoo3.Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo4.Inner4")) .containsExactly("com.other.Foo4.Inner4", "Foo4.Inner4", "Inner4") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo4.Inner4.NestedAgain")) .containsExactly( "com.other.Foo4.Inner4.NestedAgain", "Foo4.Inner4.NestedAgain", "Inner4.NestedAgain" ) } @Test fun kotlin_aliasMap_noImports() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.aliasMap).isEmpty() } @Test fun kotlin_aliasMap_noAliases() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.import.* import com.other.Foo import java.util.List """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.aliasMap).isEmpty() } @Test fun kotlin_aliasMap_aliases() { val psiFile = myFixture.configureByText( KotlinFileType.INSTANCE, // language=kotlin """ package com.example import javax.import.* import com.other.Foo as Bar import java.util.List as MyList """ .trimIndent() ) as KtFile val importHelper = KotlinImportHelper(psiFile) assertThat(importHelper.aliasMap).containsExactly("Bar", "Foo", "MyList", "List") } @Test fun java_getPossibleAnnotationText_noImports() { val psiFile = myFixture.configureByText( JavaFileType.INSTANCE, // language=java """ package com.example; """ .trimIndent() ) as PsiJavaFile val importHelper = JavaImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun java_getPossibleAnnotationText_starImports() { val psiFile = myFixture.configureByText( JavaFileType.INSTANCE, // language=java """ package com.example; import javax.inject.*; """ .trimIndent() ) as PsiJavaFile val importHelper = JavaImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun java_getPossibleAnnotationText_directImport() { val psiFile = myFixture.configureByText( JavaFileType.INSTANCE, // language=java """ package com.example; import javax.inject.Inject; """ .trimIndent() ) as PsiJavaFile val importHelper = JavaImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun java_getPossibleAnnotationText_importedBothWays() { val psiFile = myFixture.configureByText( JavaFileType.INSTANCE, // language=java """ package com.example; import javax.inject.*; import javax.inject.Inject; """ .trimIndent() ) as PsiJavaFile val importHelper = JavaImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("javax.inject.Inject")) .containsExactly("javax.inject.Inject", "Inject") assertThat(importHelper.getPossibleAnnotationText("com.example.Inject")) .containsExactly("com.example.Inject", "Inject") } @Test fun java_getPossibleAnnotationText_nestedClasses() { val psiFile = myFixture.configureByText( JavaFileType.INSTANCE, // language=java """ package com.example; import com.other.Foo1; import com.other.Foo2.Inner; import com.other.Foo3; import com.other.Foo3.Inner3; """ .trimIndent() ) as PsiJavaFile val importHelper = JavaImportHelper(psiFile) assertThat(importHelper.getPossibleAnnotationText("com.example.Foo0.Inner")) .containsExactly("com.example.Foo0.Inner", "Foo0.Inner") assertThat(importHelper.getPossibleAnnotationText("com.example.Foo0.Inner.NestedAgain")) .containsExactly("com.example.Foo0.Inner.NestedAgain", "Foo0.Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo1.Inner")) .containsExactly("com.other.Foo1.Inner", "Foo1.Inner") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo1.Inner.NestedAgain")) .containsExactly("com.other.Foo1.Inner.NestedAgain", "Foo1.Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo2.Inner")) .containsExactly("com.other.Foo2.Inner", "Inner") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo2.Inner.NestedAgain")) .containsExactly("com.other.Foo2.Inner.NestedAgain", "Inner.NestedAgain") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo3.Inner3")) .containsExactly("com.other.Foo3.Inner3", "Foo3.Inner3", "Inner3") assertThat(importHelper.getPossibleAnnotationText("com.other.Foo3.Inner3.NestedAgain")) .containsExactly( "com.other.Foo3.Inner3.NestedAgain", "Foo3.Inner3.NestedAgain", "Inner3.NestedAgain" ) } }
3
Kotlin
220
912
d88742a5542b0852e7cb2dd6571e01576cb52841
12,450
android
Apache License 2.0
androidDesignSystem/src/test/java/by/game/binumbers/design/system/components/button/SettingsButtonTest.kt
alexander-kulikovskii
565,271,232
false
{"Kotlin": 454229, "Swift": 3274, "Ruby": 2480, "Shell": 622}
package by.game.binumbers.design.system.components.button import androidx.compose.runtime.Composable import by.game.binumbers.screenshot.test.tool.BaseComponentTest class SettingsButtonTest : BaseComponentTest() { override val content: @Composable () -> Unit = { SettingsButton() } }
0
Kotlin
0
10
66b1678b47a96a52ebef467111d1d4854a37486a
290
2048-kmm
Apache License 2.0
app/src/main/java/com/example/plateform/data/remote/RemoteDataSource.kt
saad7aeed
650,043,227
false
null
package com.example.plateform.data.remote import javax.inject.Inject class RemoteDataSource @Inject constructor( private val apiService: ApiService, ) : BaseDataSource() { suspend fun getSpecificSearchDetails(searchReference: String) = getResult { apiService.getSpecificSearchDetails(searchReference) } }
0
Kotlin
0
0
2b314539de02caa3d629d8f9815b70b9b4275085
343
AndroidAssessment
Apache License 2.0
korge/src@jvm/korlibs/korge/awt/ViewsDebugger.kt
korlibs
80,095,683
false
null
package korlibs.korge.awt import korlibs.datastructure.* import korlibs.event.Event import korlibs.io.async.* import korlibs.korge.internal.* import korlibs.korge.view.* import korlibs.korge.view.Container import korlibs.math.geom.Point import java.awt.* import java.awt.event.* import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.util.* import javax.swing.* import javax.swing.tree.* import kotlin.collections.AbstractList import kotlin.coroutines.* val View.treeNode: ViewNode by Extra.PropertyThis { ViewNode(this) } class ViewNode(val view: View?) : TreeNode { val container = view as? Container? override fun toString(): String { if (view == null) return "null" val nodeName = if (view.name != null) view.name else "#${view.index}" return "$nodeName (${view::class.simpleName})" } override fun isLeaf(): Boolean = (container == null) || (view is ViewLeaf) fun childrenList(): List<View> { if (view is ViewLeaf) return listOf() //return container?.children?.filter { it !is DummyView } ?: EmptyList() // TOO SLOW return container?.children ?: emptyList() } override fun getChildAt(childIndex: Int): TreeNode? = childrenList().getOrNull(childIndex)?.treeNode override fun getChildCount(): Int = childrenList().size override fun getParent(): TreeNode? = view?.parent?.treeNode override fun getIndex(node: TreeNode?): Int = childrenList().indexOf((node as? ViewNode?)?.view) override fun getAllowsChildren(): Boolean = container != null @OptIn(KorgeInternal::class) override fun children() = Vector<Any>(childrenList()).elements() as Enumeration<out TreeNode> } class ViewDebuggerChanged(val view: View?) : Event() fun TreePath.withTree(tree: JTree): TreePathWithTree = TreePathWithTree(this, tree) class TreePathWithTree(val path: TreePath, val tree: JTree) : AbstractList<TreePathWithTree>() { val model: TreeModel get() = tree.model val node: Any? get() = path.lastPathComponent val parent: TreePathWithTree? by lazy { if (path.path.size >= 2) { path.parentPath.withTree(tree) } else { null } } val expanded: Boolean get() = tree.isExpanded(path) val index: Int get() = model.getIndexOfChild(parent!!.node, node) override val size: Int get() = model.getChildCount(node) override fun get(index: Int): TreePathWithTree { if (index !in indices) throw IndexOutOfBoundsException() val newNode = model.getChild(node, index) return TreePath(arrayOf(*path.path, newNode)).withTree(tree) } fun siblingOffset(offset: Int): TreePathWithTree? { val parent = this.parent ?: return null val nextIndex = index + offset return if (nextIndex in 0 until parent.size) parent[nextIndex] else null } val prevSibling: TreePathWithTree? get() = siblingOffset(-1) val nextSibling: TreePathWithTree? get() = siblingOffset(+1) val firstChild: TreePathWithTree? get() = if (isNotEmpty()) this[0] else null val nextSiblingOrNext: TreePathWithTree? get() = nextSibling ?: parent?.nextSiblingOrNext val next: TreePathWithTree? get() = firstChild ?: nextSiblingOrNext fun scroll(top: Boolean = false) { val bounds = tree.getPathBounds(path) ?: return if (top) bounds.height = tree.visibleRect.height tree.scrollRectToVisible(bounds) } fun select() { tree.selectionPath = path } fun selectAndScroll() { select() scroll() } } internal class ViewsDebuggerComponent constructor( val views: Views, val app: UiApplication, rootView: View? = views.stage, val coroutineContext: CoroutineContext = views.coroutineContext, val actions: ViewsDebuggerActions = ViewsDebuggerActions(views), val displayTree: Boolean = true ) : JPanel(GridLayout(if (displayTree) 2 else 1, 1)) { init { actions.component = this } val uiProperties = UiEditProperties(app, rootView, views) val uiPropertiesPanel = JPanel() .also { val panel = app.wrapContainer(it) //panel.layout = VerticalUiLayout panel.layout = UiFillLayout //panel.button("Hello") panel.addChild(uiProperties) //it.add(JButton()) panel.relayout() } val uiPropertiesPanelScroll = scrollPane(uiPropertiesPanel).also { add(it) } init { views.debugHighlighters.add { view -> SwingUtilities.invokeLater { //EventQueue.invokeLater { //println("HIGHLIGHTING: $view") println("ViewsDebuggerActions.highlight: $views") update() val treeNode = view?.treeNode if (treeNode != null) { val path = TreePath((tree.model as DefaultTreeModel).getPathToRoot(treeNode)) val rpath = path.withTree(tree) //tree.selectionPath?.withTree(tree) println(" - $path : ${rpath.expanded}") rpath.selectAndScroll() //tree.expandPath(path) //tree.clearSelection() //tree.selectionPath = path //tree.scrollPathToVisible(path) //tree.repaint() } else { tree.clearSelection() selectView(null) } update() } } } private fun selectView(view: View?) { uiProperties.setView(view) views.renderContext.debugAnnotateView = view uiProperties.relayout() } val tree: JTree = JTree(rootView!!.treeNode).apply { val tree = this addTreeSelectionListener { println("addTreeSelectionListener: ${it.paths.toList()}") if (it.paths.isNotEmpty()) { selectView((it.path.lastPathComponent as ViewNode).view) } else { selectView(null) } } addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent) { if (e.keyCode == KeyEvent.VK_RIGHT) { val selectionPath = tree.selectionPath?.withTree(tree) if (selectionPath != null && (selectionPath.expanded || selectionPath.isEmpty())) { selectionPath.next?.selectAndScroll() } } if (e.keyCode == KeyEvent.VK_DELETE) { actions.removeCurrentNode() } } }) addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (SwingUtilities.isRightMouseButton(e)) { val row = tree.getClosestRowForLocation(e.x, e.y) tree.setSelectionRow(row) val view = selectedView val isContainer = view is Container if (view != null) { val popupMenu = createPopupMenu() val subMenuAdd = JMenu("Add") for (factory in getViewFactories(views)) { subMenuAdd.add(createMenuItem(factory.name).also { it.isEnabled = isContainer it.addActionListener { actions.attachNewView(factory.build().also { it.globalPos = Point(views.virtualWidthDouble * 0.5, views.virtualHeightDouble * 0.5) }) } }) } popupMenu.add(subMenuAdd) popupMenu.add(createSeparator()) popupMenu.add(createMenuItem("Cut").also { it.addActionListener { actions.requestCut() } }) popupMenu.add(createMenuItem("Copy").also { it.addActionListener { actions.requestCopy() } }) popupMenu.add(createMenuItem("Paste").also { it.addActionListener { actions.requestPaste() } }) popupMenu.add(createSeparator()) popupMenu.add(createMenuItem("Duplicate", KeyEvent.CTRL_DOWN_MASK or KeyEvent.VK_D).also { it.addActionListener { launchImmediately(coroutineContext) { actions.duplicate() } } }) popupMenu.add(createSeparator()) popupMenu.add(createMenuItem("Remove view", KeyEvent.VK_DELETE).also { it.addActionListener { actions.removeCurrentNode() } }) popupMenu.add(createSeparator()) popupMenu.add(createMenuItem("Send to back").also { it.addActionListener { actions.sendToBack() } }) popupMenu.add(createMenuItem("Bring to front").also { it.addActionListener { actions.sendToFront() } }) popupMenu.show(e.component, e.x, e.y) } } } }) } val selectedView: View? get() = actions.selectedView val treeScroll = JScrollPane(tree).also { if (displayTree) { add(it) } } fun setRootView(root: View) { //this.coroutineContext = coroutineContext //if (views != null) this.views = views //properties.views = views?.views tree.model = DefaultTreeModel(root.treeNode) update() } fun updateTimer() { EventQueue.invokeLater { if (uiProperties.currentView != null && uiProperties.currentView?.stage == null) { uiProperties.setView(null) views.renderContext.debugAnnotateView = null } else { update() } } } fun update() { //tree.model.tree //tree.treeDidChange() tree.updateUI() uiProperties.update() } private fun scrollPane(view: Component): JScrollPane = JScrollPane(view, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) private fun getViewFactories(views: Views): List<ViewFactory> = views.viewFactories.toList() /* ArrayList<ViewFactory>().also { list -> for (factory in views.viewFactories) ´ for (factories in ServiceLoader.load(ViewsFactory::class.java).toList()) { list.addAll(factories.create()) } //list.add(ViewFactory("TreeViewRef") { TreeViewRef() }) //for (registration in views.ktreeSerializer.registrationsExt) { // list.add(ViewFactory(registration.name) { registration.factory() }) //} } */ private fun createPopupMenu(): JPopupMenu = JPopupMenu() private fun createSeparator(): JSeparator = JSeparator() private fun createMenuItem(text: String, mnemonic: Int? = null, icon: Icon? = null): JMenuItem = when { mnemonic != null -> JMenuItem(text, mnemonic) icon != null -> JMenuItem(text, icon) else -> JMenuItem(text) } }
464
null
123
2,497
1a565007ab748e00a4d602fcd78f7d4032afaf0b
12,040
korge
Apache License 2.0
src/main/kotlin/io/github/aleris/plugins/tscfg/ConfigFile.kt
aleris
752,362,581
false
{"Kotlin": 36192}
package io.github.aleris.plugins.tscfg import groovy.json.StringEscapeUtils import org.gradle.api.Project import org.gradle.api.file.RegularFileProperty import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import javax.inject.Inject /** * Represents a configuration file for the tscfg plugin. */ open class ConfigFile /** * Constructs a new [ConfigFile] instance. * * @param name the name acting as a label of the configuration file * @param tscfgExtension the tscfg extension used for some of the default values * @param project the Gradle project */ @Inject constructor(val name: String, tscfgExtension: TscfgExtension, project: Project) { private val objects: ObjectFactory = project.objects /** * The specification or template file used to generate both the configuration file and the config class. * The default value is `src/tscfg/<name>.spec.conf` if not specified. */ @get:Input val specFile: RegularFileProperty = objects.fileProperty().convention(project.layout.projectDirectory.file("src/tscfg/${name}.spec.conf")) /** * The configuration file that will be generated from the specification file. * The default value is `src/main/resources/<name>.conf` if not specified. */ @get:Input val configFile: RegularFileProperty = objects.fileProperty() .convention(specFile.map { project.layout.projectDirectory.file(configFilePath(it.asFile.path)) }) /** * The package name of the generated config class. * Can be used to override the global package name in the upper tscfg block of the configuration. */ @get:Input val packageName: Property<String> = objects.property(String::class.java).convention(tscfgExtension.packageName.getOrElse("")) /** * The class name of the generated config class. * The default value is derived from the configuration file path. * Default is `ApplicationConfig` if not specified. * * Examples: * - `src/tscfg/application.spec.conf` -> `ApplicationConfig` * - `src/tscfg/another.spec.conf` -> `AnotherConfig` * - `src/tscfg/another.spec.conf` -> `AnotherConfig` */ @get:Input val className: Property<String> = objects.property(String::class.java).convention(configFile.map { classNameFromConfigFilePath(it.asFile.path) }) companion object { /** * Returns the configuration file path from the specification file path * by stripping `.spec` or `.template` from the name. * Used as default value for the `configFile` property if not specified. * * @param specFilePath the specification file path * @return the configuration file path */ private fun configFilePath(specFilePath: String) = specFilePath.replace(".spec.conf", ".conf").replace(".template.conf", ".conf") /** * Returns a java class name from the configuration file path. * Used as default value for the `className` property if not specified. * Uses the name of the file without the extension and the first letter capitalized and appends `Config`. */ private fun classNameFromConfigFilePath(path: String) = StringEscapeUtils.escapeJava(path .substringAfterLast("/") .substringBefore(".") .replaceFirstChar { it.uppercase() } + "Config" ) } }
0
Kotlin
0
0
93243c59df458750bca41f867e67ea1474c6093b
3,311
tscfg-plugin-gradle
MIT License
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/FinalNewline.kt
hungyanbin
132,751,396
true
{"Kotlin": 832601, "Java": 9706, "Groovy": 3514, "HTML": 698, "Shell": 688}
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.github.shyiko.ktlint.ruleset.standard.FinalNewlineRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.formatting.FormattingRule /** * See https://ktlint.github.io for documentation. * * @active since v1.0.0 * @autoCorrect since v1.0.0 * @author Artur Bosch */ class FinalNewline(config: Config) : FormattingRule(config) { override val wrapping = FinalNewlineRule() override val issue = issueFor("Detects missing final newlines") }
0
Kotlin
0
0
f0a41abe94b39b483f815bd3b92dcf835fa5be12
543
detekt
Apache License 2.0
app/src/main/java/com/comunidadedevspace/taskbeats/MyCountRepository.kt
al1neferreira
764,016,540
false
{"Kotlin": 29482}
package com.comunidadedevspace.taskbeats import kotlin.random.Random interface MyCountRepository { fun sum(): Int fun sub(num1: Int, num2: Int): Int } class MyCountRepositoryImpl( private val numbersProvider: MyNumbersProvider ) : MyCountRepository { override fun sum(): Int { val num1 = numbersProvider.getNumber() val num2 = numbersProvider.getNumber() return num1 + num2 } override fun sub(num1: Int, num2: Int): Int { return num1 - num2 } } interface MyNumbersProvider{ fun getNumber():Int } class MyNumbersProviderImpl(): MyNumbersProvider{ override fun getNumber(): Int { return Random.nextInt(from = 0, until = 100) } }
0
Kotlin
0
2
598978da404fc59056ddb97f8fc8d508896a4ec3
723
TaskBeats
MIT License
common/src/main/java/io/github/lekaha/common/presentation/NetworkHandler.kt
lekaha
264,767,689
false
null
package io.github.lekaha.common.presentation import android.content.Context import io.github.lekaha.common.core.ext.networkInfo /** * Injectable class which returns information about the network connection state. */ class NetworkHandler constructor(private val context: Context) { val isConnected get() = context.networkInfo?.isConnectedOrConnecting ?: false }
0
Kotlin
0
1
907d926f42f1240eb870751d61e45a055832a06f
368
currency
MIT License
src/main/kotlin/uk/co/ben_gibson/git/link/url/template/UrlTemplates.kt
cdambo
419,691,103
true
{"Kotlin": 89867}
package uk.co.ben_gibson.git.link.url.template data class UrlTemplates(val fileAtBranch: String, val fileAtCommit : String, val commit : String)
0
Kotlin
0
0
2a82df9f0c0d3c83fc599c89745357af8e648dbd
146
GitLink
MIT License
app/src/main/java/io/github/wulkanowy/data/enums/MessageFolder.kt
wulkanowy
87,721,285
false
{"Kotlin": 1660551, "HTML": 1949, "Shell": 220}
package io.github.wulkanowy.data.enums enum class MessageFolder(val id: Int = 1) { RECEIVED(1), SENT(2), TRASHED(3) }
98
Kotlin
32
247
c781159e757c7cefa21aa51e4e52331601f75f07
131
wulkanowy
Apache License 2.0
src/main/kotlin/com/willoutwest/kalahari/scene/Group.kt
wbknez
217,644,047
false
null
package com.willoutwest.kalahari.scene import com.willoutwest.kalahari.math.ComputeUtils import com.willoutwest.kalahari.math.EpsilonTable import com.willoutwest.kalahari.math.Quaternion import com.willoutwest.kalahari.math.Ray3 import com.willoutwest.kalahari.math.Vector3 import com.willoutwest.kalahari.math.intersect.Intersection import com.willoutwest.kalahari.util.FloatContainer import com.willoutwest.kalahari.util.ObjectContainer /** * Represents an implementation of [Actor] that contains a collection of * other actors as an arbitrary logical or spatial grouping. * * @property children * A collection of actors. */ class Group(name: String) : AbstractActor(name), Actor, Cloneable { private val children = mutableListOf<Actor>() /** * Constructor. * * @param group * The group to copy from. */ constructor(group: Group?) : this(group!!.name) { this.children.addAll(group.children) } /** * Adds the specified child to this group's collection of children. * * @param child * The child to add. */ fun addChild(child: Actor) { child.parent = this this.children.add(child) } override fun clone(): Group = Group(this) override fun intersects(ray: Ray3, tMin: FloatContainer, record: Intersection, eps: EpsilonTable): Boolean { if(!this.enabled || this.children.isEmpty()) { return false } if(this.bounds?.intersects(ray) == false) { return false } val cache = ComputeUtils.localCache val hRay = cache.rays.borrow() val hRecord = cache.records.borrow() var hit = false var minTime = Float.MAX_VALUE hRay.set(ray).transformSelf(this.invTransform) this.children.forEach { if(it.intersects(hRay, tMin, record, eps) && tMin.value <= minTime) { hit = true minTime = tMin.value hRecord.set(record) } } if(hit) { ray.projectAlong(tMin.value, record.worldPosition) record.set(hRecord) record.normal.transformSelf(this.invTransform) .normalizeSelf() tMin.value = minTime } cache.rays.reuse(hRay) cache.records.reuse(hRecord) return hit } override fun move(x: Float, y: Float, z: Float): Group = super.move(x, y, z) as Group override fun move(vec: Vector3): Group = super.move(vec) as Group override fun rotate(angle: Float, axis: Vector3): Group = super.rotate(angle, axis) as Group override fun rotate(roll: Float, pitch: Float, yaw: Float): Group = super.rotate(roll, pitch, yaw) as Group override fun rotate(quat: Quaternion): Group = super.rotate(quat) as Group override fun scale(x: Float, y: Float, z: Float): Group = super.scale(x, y, z) as Group override fun scale(vec: Vector3): Group = super.scale(vec) as Group override fun shadows(ray: Ray3, tMin: FloatContainer, obj: ObjectContainer, eps: EpsilonTable, tMax: Float): Boolean { if(!this.isCastingShadows()) { return false } if(this.bounds?.intersects(ray) == false) { return false } val cache = ComputeUtils.localCache val sRay = cache.rays.borrow() sRay.set(ray).transformSelf(this.invTransform) val hit = this.children.any { it.shadows(sRay, tMin, obj, eps, tMax) } cache.rays.reuse(sRay) return hit } override fun visit(visitor: (Actor) -> Unit) { super.visit(visitor) this.children.forEach(visitor) } }
0
Kotlin
0
0
46b1b3de9474dda22291a33b93a9b40b634c29c0
3,835
kalahari
Apache License 2.0
domain/src/main/java/com/maximeroussy/fizzhub/domain/GithubDataRepository.kt
maximeroussy
152,085,225
false
null
package com.maximeroussy.fizzhub.domain import com.maximeroussy.fizzhub.domain.models.GithubIssue import com.maximeroussy.fizzhub.domain.models.GithubRepository import io.reactivex.Completable import io.reactivex.Single interface GithubDataRepository { fun searchRepositories(query: String): Single<List<GithubRepository>> fun loadMoreSearchRepositories(query: String): Single<List<GithubRepository>> fun getAllSavedRepositories(): Single<List<GithubRepository>> fun saveRepository(githubRepository: GithubRepository): Completable fun deleteRepository(githubRepository: GithubRepository): Completable fun getIssues(githubRepository: GithubRepository): Single<List<GithubIssue>> fun getMoreIssues(githubRepository: GithubRepository): Single<List<GithubIssue>> fun searchIssues(query: String, githubRepository: GithubRepository): Single<List<GithubIssue>> fun loadMoreSearchIssues(query: String, githubRepository: GithubRepository): Single<List<GithubIssue>> }
0
Kotlin
0
0
374c41941df0265f24ee099c742e66f0748c461d
987
fizzhub
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/FileFingerprintOptionsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.FileFingerprintOptions import software.amazon.awscdk.IgnoreMode import software.amazon.awscdk.SymlinkFollowMode /** * Options related to calculating source hash. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.*; * FileFingerprintOptions fileFingerprintOptions = FileFingerprintOptions.builder() * .exclude(List.of("exclude")) * .extraHash("extraHash") * .followSymlinks(SymlinkFollowMode.NEVER) * .ignoreMode(IgnoreMode.GLOB) * .build(); * ``` */ @CdkDslMarker public class FileFingerprintOptionsDsl { private val cdkBuilder: FileFingerprintOptions.Builder = FileFingerprintOptions.builder() private val _exclude: MutableList<String> = mutableListOf() /** * @param exclude File paths matching the patterns will be excluded. See `ignoreMode` to set the * matching behavior. Has no effect on Assets bundled using the `bundling` property. */ public fun exclude(vararg exclude: String) { _exclude.addAll(listOf(*exclude)) } /** * @param exclude File paths matching the patterns will be excluded. See `ignoreMode` to set the * matching behavior. Has no effect on Assets bundled using the `bundling` property. */ public fun exclude(exclude: Collection<String>) { _exclude.addAll(exclude) } /** * @param extraHash Extra information to encode into the fingerprint (e.g. build instructions * and other inputs). */ public fun extraHash(extraHash: String) { cdkBuilder.extraHash(extraHash) } /** @param followSymlinks A strategy for how to handle symlinks. */ public fun followSymlinks(followSymlinks: SymlinkFollowMode) { cdkBuilder.followSymlinks(followSymlinks) } /** @param ignoreMode The ignore behavior to use for `exclude` patterns. */ public fun ignoreMode(ignoreMode: IgnoreMode) { cdkBuilder.ignoreMode(ignoreMode) } public fun build(): FileFingerprintOptions { if (_exclude.isNotEmpty()) cdkBuilder.exclude(_exclude) return cdkBuilder.build() } }
3
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
2,613
awscdk-dsl-kotlin
Apache License 2.0
template/composeApp/src/commonMain/kotlin/kotli/app/di/state/ProvidesAppState.kt
kotlitecture
790,159,970
false
{"Kotlin": 296989, "Swift": 587, "HTML": 234}
package kotli.app.di.state import kotli.app.AppNavigationRouter import kotli.app.AppState import org.koin.dsl.module val ProvidesAppState = module { single { AppState() } single { AppNavigationRouter() } }
2
Kotlin
1
29
b692cfd1895fdcd37ce5f6b654bfed834b7e7cec
215
template-multiplatform-compose
MIT License
shared/src/commonMain/kotlin/Date.kt
kropp
132,184,431
false
null
fun validate(day: Day, month: Month, year: Year): Boolean { return Date(day, month, year).isValid() } expect class Date(day: Day, month: Month, year: Year) { fun isValid(): Boolean } inline class Day(val value: Int) inline class Month(val value: Int) inline class Year(val value: Int)
0
Kotlin
0
1
973d20ca464c75f3948684ca04d42917b9b1724e
290
kotlin-multiplatform-sample
MIT License
Client/app/src/main/java/com/t3ddyss/clother/presentation/auth/PasswordRecoveryViewModel.kt
t3ddyss
337,083,750
false
null
package com.t3ddyss.clother.presentation.auth import androidx.lifecycle.* import com.t3ddyss.clother.domain.auth.AuthInteractor import com.t3ddyss.clother.domain.common.common.models.Response import com.t3ddyss.clother.util.Event import com.t3ddyss.core.domain.models.Loading import com.t3ddyss.core.domain.models.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class PasswordRecoveryViewModel @Inject constructor( private val authInteractor: AuthInteractor, private val savedStateHandle: SavedStateHandle ) : ViewModel() { private val _email = savedStateHandle.getLiveData(SavedStateHandleKeys.EMAIL, "") val email: LiveData<String> = _email private val _passwordRecoveryResult = MutableLiveData<Event<Resource<Response>>>() val passwordRecoveryResult: LiveData<Event<Resource<Response>>> = _passwordRecoveryResult fun resetPassword(email: String) { _passwordRecoveryResult.value = Event(Loading()) viewModelScope.launch { val response = authInteractor.resetPassword(email = email) _passwordRecoveryResult.postValue(Event(response)) } } fun saveEmail(email: String) { savedStateHandle[SavedStateHandleKeys.EMAIL] = email } }
0
Kotlin
1
23
a2439707002e0086de09bf37c3d10e7c8cf9f060
1,321
Clother
MIT License
src/commonMain/kotlin/com/rtarita/metadata/delegate/NullableMetadataDelegateImpl.kt
RaphaelTarita
611,979,857
false
null
package com.rtarita.metadata.delegate import com.rtarita.metadata.NullableMetadata import com.rtarita.metadata.NullableTypedMetadata import com.rtarita.metadata.exc.UnknownIdentifierException import kotlin.reflect.KProperty internal class NullableMetadataDelegateImpl( private val metadata: NullableMetadata, private val identifier: String ) : MetadataDelegate<Any?> { private var submapCache: NullableTypedMetadata<*> = refreshCache() private fun refreshCache(): NullableTypedMetadata<*> { return metadata.locate(identifier) ?: metadata } override fun getValue(thisRef: Any?, property: KProperty<*>): Any? { return try { submapCache[identifier] } catch (_: UnknownIdentifierException) { refreshCache() metadata[identifier] } } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Any?) { metadata[identifier] = value } }
0
Kotlin
0
1
af3fef48cca022593c835051a26496f251f115f0
953
multiplaform-metadata
MIT License
korge-sandbox/src/samples/MainCompression.kt
korlibs
80,095,683
false
{"Kotlin": 3929805, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "Batchfile": 41, "CSS": 33}
package samples import korlibs.time.measureTime import korlibs.korge.scene.Scene import korlibs.korge.view.SContainer import korlibs.io.file.std.MemoryVfsMix import korlibs.io.file.std.localVfs import korlibs.io.file.std.openAsZip import korlibs.io.stream.DummyAsyncOutputStream import korlibs.io.stream.openAsync import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class MainCompression : Scene() { override suspend fun SContainer.sceneMain() { //run { withContext(Dispatchers.Unconfined) { val mem = MemoryVfsMix() val zipFile = localVfs("c:/temp", async = true)["1.zip"] val zipBytes = zipFile.readAll() println("ELAPSED TIME [NATIVE]: " + measureTime { //localVfs("c:/temp")["1.zip"].openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(mem["test.img"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].readAll().openAsync().openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["1.zip"].readAll().openAsync().openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) //localVfs("c:/temp")["1.zip"].openAsZip(useNativeDecompression = true)["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) zipBytes.openAsync().openAsZip(useNativeDecompression = true)["2012-07-15-wheezy-raspbian.img"].copyTo( DummyAsyncOutputStream ) }) println("ELAPSED TIME [PORTABLE]: " + measureTime { //localVfs("c:/temp")["1.zip"].openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(mem["test.img"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].readAll().openAsync().openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["1.zip"].readAll().openAsync().openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) //localVfs("c:/temp")["1.zip"].openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp2.img")) //localVfs("c:/temp", async = true)["1.zip"].openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo(DummyAsyncOutputStream) zipBytes.openAsync().openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo( DummyAsyncOutputStream ) }) } } }
461
Kotlin
120
2,394
0ca8644eb43c2ea8148dcd94d5c2a063466b0079
2,992
korge
Apache License 2.0
collect_app/src/androidTest/java/org/odk/collect/android/feature/instancemanagement/SendFinalizedFormTest.kt
getodk
40,213,809
false
{"Java": 3378614, "Kotlin": 2749754, "JavaScript": 2830, "Shell": 2689}
package org.odk.collect.android.feature.instancemanagement import androidx.test.ext.junit.runners.AndroidJUnit4 import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.javarosa.xform.parse.XFormParser import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import org.kxml2.kdom.Element import org.odk.collect.android.support.TestDependencies import org.odk.collect.android.support.pages.FormEntryPage.QuestionAndAnswer import org.odk.collect.android.support.pages.MainMenuPage import org.odk.collect.android.support.pages.OkDialog import org.odk.collect.android.support.pages.ProjectSettingsPage import org.odk.collect.android.support.pages.SendFinalizedFormPage import org.odk.collect.android.support.rules.CollectTestRule import org.odk.collect.android.support.rules.TestRuleChain.chain import org.odk.collect.androidtest.RecordedIntentsRule @RunWith(AndroidJUnit4::class) class SendFinalizedFormTest { private val testDependencies = TestDependencies() private val rule = CollectTestRule(useDemoProject = false) @get:Rule val chain: RuleChain = chain(testDependencies) .around(RecordedIntentsRule()) .around(rule) @Test fun canViewFormsBeforeSending() { rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "52")) .clickSendFinalizedForm(1) .clickOnForm("One Question") .assertText("52") } @Test fun whenThereIsAnAuthenticationError_allowsUserToReenterCredentials() { testDependencies.server.setCredentials("Draymond", "Green") rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .answerQuestion("what is your age", "123") .swipeToEndScreen() .clickFinalize() .clickSendFinalizedForm(1) .clickSelectAll() .clickSendSelectedWithAuthenticationError() .fillUsername("Draymond") .fillPassword("Green") .clickOK(OkDialog()) .assertText("One Question - Success") } @Test fun canViewSentForms() { rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .answerQuestion("what is your age", "123") .swipeToEndScreen() .clickFinalize() .clickSendFinalizedForm(1) .clickSelectAll() .clickSendSelected() .clickOK(SendFinalizedFormPage()) .pressBack(MainMenuPage()) .clickViewSentForm(1) .clickOnForm("One Question") .assertText("123") .assertText(org.odk.collect.strings.R.string.exit) } @Test fun canSendIndividualForms() { rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "123")) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "124")) .clickSendFinalizedForm(2) .selectForm(0) .clickSendSelected() .clickOK(SendFinalizedFormPage()) .pressBack(MainMenuPage()) .assertNumberOfFinalizedForms(1) .clickViewSentForm(1) .clickOnForm("One Question") .assertText("123") } @Test fun whenDeleteAfterSendIsEnabled_deletesFilledForm() { rule.withProject(testDependencies.server.url) .openProjectSettingsDialog() .clickSettings() .clickFormManagement() .scrollToRecyclerViewItemAndClickText(org.odk.collect.strings.R.string.delete_after_send) .pressBack(ProjectSettingsPage()) .pressBack(MainMenuPage()) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .answerQuestion("what is your age", "123") .swipeToEndScreen() .clickFinalize() .clickSendFinalizedForm(1) .clickSelectAll() .clickSendSelected() .clickOK(SendFinalizedFormPage()) .pressBack(MainMenuPage()) .clickViewSentForm(1) .clickOnText("One Question") .assertOnPage() } @Test fun whenThereAreSentAndReadyToSendForms_displayTheBanner() { rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "123")) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "124")) .clickSendFinalizedForm(2) .selectForm(0) .clickSendSelected() .clickOK(SendFinalizedFormPage()) .assertQuantityText(org.odk.collect.strings.R.plurals.forms_ready_to_send, 1, 1) } @Test fun formsAreSentInOldestFirstOrder() { rule.withProject(testDependencies.server.url) .copyForm("one-question.xml", testDependencies.server.hostName) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "123")) .startBlankForm("One Question") .fillOutAndFinalize(QuestionAndAnswer("what is your age", "124")) .clickSendFinalizedForm(2) .sortByDateNewestFirst() .clickSelectAll() .clickSendSelected() .clickOK(SendFinalizedFormPage()) val firstFormRootElement = XFormParser.getXMLDocument(testDependencies.server.submissions[0].inputStream().reader()).rootElement val secondFormRootElement = XFormParser.getXMLDocument(testDependencies.server.submissions[1].inputStream().reader()).rootElement assertThat((firstFormRootElement.getChild(0) as Element).getChild(0), equalTo("123")) assertThat((secondFormRootElement.getChild(0) as Element).getChild(0), equalTo("124")) } }
283
Java
1372
717
63050fdd265c42f3c340f0ada5cdff3c52a883bc
6,577
collect
Apache License 2.0
src/day05/Day05.kt
cmargonis
573,161,233
false
null
package day05 import readInput private const val DIRECTORY = "./day05" fun main() { fun getStack(input: List<String>): Pair<Int, Map<Int, ArrayDeque<String>>> { var stackIndex = 0 val stackRows: List<List<String>> = input.takeWhile { it.isNotBlank() }.mapIndexed { runningIndex, row -> stackIndex = runningIndex row.windowed(size = 3, step = 4, partialWindows = true) } val stack: MutableMap<Int, MutableList<String>> = mutableMapOf<Int, MutableList<String>>() val stackKeys: List<Int> = stackRows[stackIndex].map { it.trim(' ', '\"').toInt() } stackRows.dropLast(1).forEach { row: List<String> -> row.forEachIndexed { index, item -> val itemsAtStack: MutableList<String> = stack[stackKeys[index]] ?: mutableListOf() itemsAtStack.add(item) stack[stackKeys[index]] = itemsAtStack } } stack.forEach { entry -> entry.value.removeIf { it.isBlank() } } return Pair(stackIndex, stack.toSortedMap(compareByDescending { it }).mapValues { entry -> val trimmed = entry.value.map { it.trim('[', ']', ' ') } ArrayDeque(trimmed) }) } fun getInstructions(rawInstructions: List<String>): List<Instruction> = rawInstructions.map { val instruction = it.split(" ") Instruction( quantity = instruction[1].toInt(), origin = instruction[3].toInt(), destination = instruction[5].toInt() ) } fun Map<Int, ArrayDeque<String>>.move(from: Int, to: Int) { if (isEmpty()) return val removed = this[from]?.removeFirst() this[to]?.addFirst(removed!!) } fun Map<Int, ArrayDeque<String>>.moveMany(times: Int, from: Int, to: Int) { if (isEmpty()) return val tempQueue: ArrayDeque<String> = ArrayDeque(initialCapacity = times) repeat(times) { tempQueue.addFirst(this[from]!!.removeFirst()) } repeat(times) { this[to]?.addFirst(tempQueue.removeFirst()) } } fun Map<Int, ArrayDeque<String>>.topOfTheStack(): String = asIterable() .runningFold("") { _, entry -> entry.value.first() } .filterNot { it.isEmpty() } .joinToString(separator = "") fun part1(input: List<String>): String { val (indexOfInstructions, stack) = getStack(input) val instructions = getInstructions(input.subList(fromIndex = indexOfInstructions + 2, toIndex = input.size)) instructions.forEach { instruction -> repeat(instruction.quantity) { stack.move(from = instruction.origin, to = instruction.destination) } } return stack.topOfTheStack().reversed() } fun part2(input: List<String>): String { val (indexOfInstructions, stack) = getStack(input) val instructions = getInstructions(input.subList(fromIndex = indexOfInstructions + 2, toIndex = input.size)) instructions.forEach { instruction -> stack.moveMany(times = instruction.quantity, from = instruction.origin, to = instruction.destination) } return stack.topOfTheStack().reversed() } val input = readInput("${DIRECTORY}/Day05") println(part1(input)) println(part2(input)) } data class Instruction(val quantity: Int, val origin: Int, val destination: Int)
0
Kotlin
0
0
bd243c61bf8aae81daf9e50b2117450c4f39e18c
3,434
kotlin-advent-2022
Apache License 2.0
apps/etterlatte-migrering/src/main/kotlin/migrering/ApplicationContext.kt
navikt
417,041,535
false
null
package no.nav.etterlatte.migrering import no.nav.etterlatte.libs.database.DataSourceBuilder class ApplicationContext { private val properties: ApplicationProperties = ApplicationProperties.fromEnv(System.getenv()) val dataSource = DataSourceBuilder.createDataSource( jdbcUrl = properties.jdbcUrl, username = properties.dbUsername, password = <PASSWORD> ) }
14
Kotlin
0
3
3f003be38db3c064b9a9d7b2af44f9668582bd4a
395
pensjon-etterlatte-saksbehandling
MIT License
src/main/kotlin/com/example/ddd/order/domain/models/entities/Product.kt
cesar-lp
485,152,561
false
null
package com.example.ddd.order.domain.models.entities import com.example.ddd.common.domain.models.ID import com.example.ddd.common.domain.models.Money import com.example.ddd.order.domain.errors.product.InvalidProductPriceException import com.example.ddd.order.domain.errors.product.InvalidProductStatusException import com.example.ddd.order.domain.errors.product.InvalidProductStockException import java.time.Instant import java.util.* class Product( val id: String = ID.generate("prd"), var name: String, var description: String, private var status: ProductStatus = ProductStatus.ENABLED, private var stock: Int = 0, private var price: Money, val createdAt: Instant = Instant.now(), var updatedAt: Instant = Instant.now() ) { fun updateStatus(newStatus: String) { val productStatus = ProductStatus.of(newStatus) ?: throw InvalidProductStatusException(id, newStatus) status = productStatus updatedAt = Instant.now() } fun updatePrice(newPrice: Money) { if (newPrice.isZeroOrNegative()) { throw InvalidProductPriceException(id, newPrice) } price = newPrice } // TODO: separate into function to decrement/increment stock fun updateStock(units: Int) { if ((stock + units) < 0) { throw InvalidProductStockException(id, units) } stock += units } fun getStatus() = status.description fun getStock() = stock fun getPrice() = price override fun hashCode() = Objects.hash(id, name) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Product) return false return (other.id == id && other.name == name) } override fun toString(): String { return "Product(id: ${id}, name: ${name}, description: ${description}, status: ${status}, stock: ${stock}, price: ${price})" } }
0
Kotlin
0
0
094ea43a68cc6a50a5a42c1dfbb26726faaaa0b8
1,825
kotlin-ddd-example
MIT License
node-api/src/main/kotlin/net/corda/nodeapi/internal/cordapp/CordappLoader.kt
corda
70,137,417
false
{"Kotlin": 10568684, "Java": 270270, "C++": 239894, "Python": 37811, "Shell": 28320, "CSS": 23544, "Groovy": 14473, "CMake": 5393, "Dockerfile": 2575, "Batchfile": 1777, "PowerShell": 660, "C": 454}
package net.corda.nodeapi.internal.cordapp import net.corda.core.cordapp.Cordapp import net.corda.core.internal.cordapp.CordappImpl import net.corda.core.internal.flatMapToSet import net.corda.core.schemas.MappedSchema /** * Handles loading [Cordapp]s. */ interface CordappLoader : AutoCloseable { /** * Returns all [Cordapp]s found. */ val cordapps: List<CordappImpl> /** * Returns a [ClassLoader] containing all types from all [Cordapp]s. */ val appClassLoader: ClassLoader } /** * Returns all [MappedSchema] found inside the [Cordapp]s. */ val CordappLoader.cordappSchemas: Set<MappedSchema> get() = cordapps.flatMapToSet { it.customSchemas }
59
Kotlin
1089
3,966
c2742ba6a582c8d46347a14f58041a29eecac120
694
corda
Apache License 2.0
app/src/main/java/com/pcm/gallery/utils/Rx2Helper.kt
piyush-malaviya
126,628,682
false
null
package com.pcm.gallery.utils import android.content.Context import android.provider.MediaStore import com.pcm.gallery.constant.Constant import com.pcm.gallery.model.ModelAlbum import com.pcm.gallery.model.ModelMedia import io.reactivex.Flowable import java.util.concurrent.Callable class Rx2Helper { companion object { val SORT_ORDER_ASC = "ASC" val SORT_ORDER_DESC = "DESC" /** * get image album list */ fun getImageAlbum(context: Context): Flowable<ArrayList<ModelAlbum>> { return Flowable.fromCallable(object : Callable<ArrayList<ModelAlbum>> { override fun call(): ArrayList<ModelAlbum> { val albumList = ArrayList<ModelAlbum>() val projection = arrayOf(MediaStore.Images.Media.BUCKET_ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, "COUNT(*) as count", MediaStore.Images.Media.DATA) val sortBy = MediaStore.Images.Media.BUCKET_DISPLAY_NAME val selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " != ?) " + "GROUP BY (" + MediaStore.Images.Media.BUCKET_DISPLAY_NAME val cursor = context.getContentResolver() .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, arrayOf(""), sortBy) if (cursor != null) { while (cursor.moveToNext()) { val album = ModelAlbum( CursorUtils.getString(cursor, MediaStore.Images.Media.BUCKET_ID), CursorUtils.getString(cursor, MediaStore.Images.Media.BUCKET_DISPLAY_NAME), CursorUtils.getInt(cursor, "count"), Constant.TYPE_IMAGE, CursorUtils.getString(cursor, MediaStore.Images.Media.DATA)) albumList.add(album) } cursor.close() } return albumList } }) } /** * get video album list */ fun getVideoAlbum(context: Context): Flowable<ArrayList<ModelAlbum>> { return Flowable.fromCallable(object : Callable<ArrayList<ModelAlbum>> { override fun call(): ArrayList<ModelAlbum> { val albumList = ArrayList<ModelAlbum>() val projection = arrayOf(MediaStore.Video.Media.BUCKET_ID, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, "COUNT(*) as count", MediaStore.Video.Media.DATA) val sortBy = MediaStore.Video.Media.BUCKET_DISPLAY_NAME val selection = MediaStore.Video.Media.BUCKET_DISPLAY_NAME + " != ?) " + "GROUP BY (" + MediaStore.Video.Media.BUCKET_DISPLAY_NAME val cursor = context.getContentResolver() .query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, arrayOf(""), sortBy) if (cursor != null) { while (cursor.moveToNext()) { val album = ModelAlbum( CursorUtils.getString(cursor, MediaStore.Video.Media.BUCKET_ID), CursorUtils.getString(cursor, MediaStore.Video.Media.BUCKET_DISPLAY_NAME), CursorUtils.getInt(cursor, "count"), Constant.TYPE_VIDEO, CursorUtils.getString(cursor, MediaStore.Video.Media.DATA)) albumList.add(album) } cursor.close() } return albumList } }) } /** * get image list */ fun getImageList(context: Context, albumId: String, type: String, order: String): Flowable<ArrayList<ModelMedia>> { return Flowable.fromCallable(object : Callable<ArrayList<ModelMedia>> { override fun call(): ArrayList<ModelMedia> { val albumList = ArrayList<ModelMedia>() val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.DATA, MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT, MediaStore.Images.Media.ORIENTATION) val sortBy = type + " " + order val selection = MediaStore.Images.Media.BUCKET_ID + " = ? " val cursor = context.getContentResolver() .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, arrayOf(albumId), sortBy) if (cursor != null) { while (cursor.moveToNext()) { val media = ModelMedia( CursorUtils.getString(cursor, MediaStore.Images.Media._ID), albumId, CursorUtils.getString(cursor, MediaStore.Images.Media.DISPLAY_NAME), Constant.TYPE_IMAGE, CursorUtils.getString(cursor, MediaStore.Images.Media.DATA), CursorUtils.getLong(cursor, MediaStore.Images.Media.DATE_TAKEN), CursorUtils.getLong(cursor, MediaStore.Images.Media.SIZE), CursorUtils.getInt(cursor, MediaStore.Images.Media.WIDTH), CursorUtils.getInt(cursor, MediaStore.Images.Media.HEIGHT), CursorUtils.getInt(cursor, MediaStore.Images.Media.ORIENTATION) ) albumList.add(media) } cursor.close() } return albumList } }) } fun getImageList(context: Context, albumId: String): Flowable<ArrayList<ModelMedia>> { return getImageList(context, albumId, MediaStore.Images.Media.DATE_TAKEN, SORT_ORDER_DESC) } /** * get video list */ fun getVideoList(context: Context, albumId: String, type: String, order: String): Flowable<ArrayList<ModelMedia>> { return Flowable.fromCallable(object : Callable<ArrayList<ModelMedia>> { override fun call(): ArrayList<ModelMedia> { val albumList = ArrayList<ModelMedia>() val projection = arrayOf( MediaStore.Video.Media._ID, MediaStore.Video.Media.BUCKET_ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATE_TAKEN, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DATA, MediaStore.Video.Media.WIDTH, MediaStore.Video.Media.HEIGHT, MediaStore.Video.Media.DURATION) val sortBy = type + " " + order val selection = MediaStore.Video.Media.BUCKET_ID + " = ? " val cursor = context.getContentResolver() .query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, arrayOf(albumId), sortBy) if (cursor != null) { while (cursor.moveToNext()) { val media = ModelMedia( CursorUtils.getString(cursor, MediaStore.Video.Media._ID), albumId, CursorUtils.getString(cursor, MediaStore.Video.Media.DISPLAY_NAME), Constant.TYPE_VIDEO, CursorUtils.getString(cursor, MediaStore.Video.Media.DATA), CursorUtils.getLong(cursor, MediaStore.Video.Media.DATE_TAKEN), CursorUtils.getLong(cursor, MediaStore.Video.Media.SIZE), CursorUtils.getInt(cursor, MediaStore.Video.Media.WIDTH), CursorUtils.getInt(cursor, MediaStore.Video.Media.HEIGHT), CursorUtils.getLong(cursor, MediaStore.Video.Media.DURATION) ) albumList.add(media) } cursor.close() } return albumList } }) } fun getVideoList(context: Context, albumId: String): Flowable<ArrayList<ModelMedia>> { return getVideoList(context, albumId, MediaStore.Video.Media.DATE_TAKEN, SORT_ORDER_DESC) } } }
0
Kotlin
0
2
eca315de491c31e5825a5753c21b78b32bb06747
10,244
Gallery
Apache License 2.0
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/config/spring/TaskConfig.kt
navikt
593,529,397
false
{"Kotlin": 907524, "HTML": 12173, "Shell": 806, "Dockerfile": 614}
package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.config.spring import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.model.BrevProcessingTask import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.godskriv.model.GodskrivOpptjeningProcessingTask import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.kontrollbehandling.KontrollbehandlingProcessingTask import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.oppgave.model.OppgaveProcessingTask import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.persongrunnlag.model.PersongrunnlagMeldingProcessingTask import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @Configuration class TaskConfig { @Bean @Profile("dev-gcp", "prod-gcp", "kafkaIntegrationTest") fun taskExecutorService( oppgaveProcessingTask: OppgaveProcessingTask, brevProcessingTask: BrevProcessingTask, persongrunnlagMeldingProcessingTask: PersongrunnlagMeldingProcessingTask, kontrollbehandlingProcessingTask: KontrollbehandlingProcessingTask, godskrivOpptjeningProcessingTask: GodskrivOpptjeningProcessingTask ): ExecutorService { return Executors.newVirtualThreadPerTaskExecutor().also { executor -> repeat(1) { executor.submit(oppgaveProcessingTask) } repeat(1) { executor.submit(brevProcessingTask) } repeat(4) { executor.submit(persongrunnlagMeldingProcessingTask) } repeat(4) { executor.submit(kontrollbehandlingProcessingTask) } repeat(1) { executor.submit(godskrivOpptjeningProcessingTask) } } } }
1
Kotlin
0
0
189e166b848c75b57ca10409a8890fcd3d4630c1
1,896
omsorgsopptjening-bestem-pensjonsopptjening
MIT License
src/main/kotlin/com/deflatedpickle/undulation/functions/ColourButton.kt
DeflatedPickle
286,105,109
false
null
package com.deflatedpickle.undulation.functions import com.deflatedpickle.undulation.widget.ColourButton import java.awt.Color import java.awt.event.ActionEvent fun ColourButton(colour: Color, tooltip: String? = null, function: (ActionEvent) -> Unit) = ColourButton(colour).apply { toolTipText = tooltip addActionListener { function(it) } }
0
Kotlin
0
0
db954124cd20bc6f6fc31357a86239df84bc98bd
386
undulation
MIT License
core/src/main/kotlin/com/bartlomiejpluta/smnp/dsl/ast/model/node/FunctionDefinitionNode.kt
bartlomiej-pluta
247,806,164
false
null
package com.bartlomiejpluta.smnp.dsl.ast.model.node import com.bartlomiejpluta.smnp.dsl.token.model.entity.TokenPosition class FunctionDefinitionNode(identifier: Node, arguments: Node, body: Node, position: TokenPosition) : Node(3, position) { operator fun component1() = children[0] operator fun component2() = children[1] operator fun component3() = children[2] val identifier: Node get() = children[0] val arguments: Node get() = children[1] val body: Node get() = children[2] init { children[0] = identifier children[1] = arguments children[2] = body } }
0
Kotlin
0
0
88f2089310b2a23b2ce63fb6be23a96db156ea4a
632
smnp-kt
MIT License
android/http-coroutine/src/main/java/com/caldremch/http/execute/PostExecuteImpl.kt
android-module
522,390,095
false
{"Kotlin": 149203, "Java": 23434, "Shell": 433}
package com.caldremch.http.execute import com.caldremch.android.log.debugLog import com.caldremch.http.Api import com.caldremch.http.CoroutineHandler import com.caldremch.http.core.HttpInitializer import com.caldremch.http.core.abs.AbsCallback import com.caldremch.http.core.framework.PostRequest import com.caldremch.http.core.framework.TransferStation import com.caldremch.http.core.framework.base.IBaseResp import com.caldremch.http.core.framework.base.IPostExecute import com.caldremch.http.core.model.ResponseBodyWrapper import com.caldremch.http.core.params.HttpParams import com.google.gson.Gson import kotlinx.coroutines.CancellationException import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody import java.lang.reflect.Type class PostExecuteImpl : BaseExecute(), IPostExecute { private val gson by lazy { Gson() } private inline fun <T> exception(handler: CoroutineHandler<T>, dsl: () -> Unit) { try { dsl.invoke() } catch (e: CancellationException) { debugLog { "ignore CancellationException" } } catch (e: Exception) { handler.onError(e) } } override suspend fun <T> execute( request: PostRequest, ts: TransferStation, url: String, callback: AbsCallback<IBaseResp<T>>?, clazz: Class<T> ): IBaseResp<T> { return executeType(request, ts, url, callback, clazz) } override suspend fun <T> executeType( postRequest: PostRequest, ts: TransferStation, url: String, callback: AbsCallback<IBaseResp<T>>?, clazz: Type ): IBaseResp<T> { val pathUrl = if (ts.httpPath.isEmpty) url else ts.httpPath.getPathUrl(url) val api = getApi(ts.noCustomerHeader, ts.channel) val handler = go(callback, ts) var convertResult: IBaseResp<T> try { val resp = getResponse(ts, api, pathUrl) convertResult = convert.convert(ResponseBodyWrapper(resp), clazz) handler.onSuccess(convertResult) } catch (e: Exception) { convertResult = HttpInitializer.getBaseRespFactory().create(null, e.findCode(),e.message, null,e.findCode()?.toString()) handleException(e, ts, handler) } return convertResult } private suspend fun getResponse( ts: TransferStation, api: Api, pathUrl: String ): ResponseBody { val resp = if (ts.requestBody != null) { val requestBody: RequestBody if (ts.requestBody is RequestBody) { requestBody = ts.requestBody as RequestBody } else { requestBody = gson.toJson(ts.requestBody).toRequestBody(MEDIA_TYPE_JSON) } api.post(pathUrl, requestBody) } else if (ts.httpParams.isEmpty) { api.post(pathUrl, getHttpParamsBody(ts.httpParams)) } else if (ts.formUrlEncoded) { api.post(pathUrl, ts.httpParams.urlParams) } else { api.post(pathUrl, getHttpParamsBody(ts.httpParams)) } return resp } private fun getHttpParamsBody(httpParams: HttpParams): RequestBody { if (httpParams.isEmpty) { return "{}".toRequestBody(MEDIA_TYPE_JSON) } return toJsonString(httpParams).toRequestBody(MEDIA_TYPE_JSON) } companion object { private val gson = Gson() val MEDIA_TYPE_PLAIN: MediaType = "text/plain;charset=utf-8".toMediaType() val MEDIA_TYPE_JSON: MediaType = "application/json;charset=utf-8".toMediaType() val MEDIA_TYPE_STREAM: MediaType = "application/octet-stream".toMediaType() } fun toJsonString(httpParams: HttpParams): String { return if (!httpParams.isEmpty) { gson.toJson(httpParams.getUrlParamsMap()) } else "{}" } }
0
Kotlin
0
1
52b640f9e1e65b15417a4cc61b64845aca837d74
3,995
android-http
Apache License 2.0
avro-kotlin-serialization/src/main/kotlin/cache/AvroCache.kt
toolisticon
493,962,736
false
{"Kotlin": 474632, "Java": 1511}
package io.toolisticon.kotlin.avro.serialization.cache import io.toolisticon.kotlin.avro.model.wrapper.AvroSchema import kotlinx.serialization.KSerializer import kotlin.reflect.KClass object AvroCache { interface SchemaByClassCache { operator fun get(klass: KClass<*>): AvroSchema } interface ClassBySchemaCache { operator fun <T : Any> get(schema: AvroSchema): KClass<T> } interface SerializerByClassCache { operator fun <T : Any> get(klass: KClass<out T>): KSerializer<T> } }
12
Kotlin
0
4
d45b8fc3300205d4bf278a53ebfa53d3c46d0a48
507
avro-kotlin
Apache License 2.0
app/src/main/java/com/Alkemy/alkemybankbase/ui/fragments/MovementFragment.kt
MicaMathieu
566,627,293
false
null
package com.Alkemy.alkemybankbase.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import com.Alkemy.alkemybankbase.data.local.SessionManager import com.Alkemy.alkemybankbase.databinding.FragmentMovementBinding import com.Alkemy.alkemybankbase.presentation.MovementViewModel import com.Alkemy.alkemybankbase.ui.adapters.TransactionAdapter import com.Alkemy.alkemybankbase.utils.LogBundle import com.google.firebase.analytics.FirebaseAnalytics import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MovementFragment : Fragment() { private var _binding: FragmentMovementBinding? = null private val binding get() = _binding!! private val viewModel: MovementViewModel by viewModels() private lateinit var auth: String private lateinit var firebaseAnalytics: FirebaseAnalytics override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) _binding = FragmentMovementBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) auth = "${SessionManager.getToken(requireContext())}" firebaseAnalytics = FirebaseAnalytics.getInstance(requireContext()) LogBundle.logBundleAnalytics( firebaseAnalytics, "Ingreso a la vista de movimientos", "ingreso_a_ultimos_movimientos") viewModel.getAllAccounts(auth) initRecyclerView() setupObservers() } private fun setupObservers() { viewModel.isLoadingLiveData.observe(viewLifecycleOwner) { binding.progressBar.isVisible = it binding.rvTransactions.isVisible = !it if(it){ binding.tvErrorTransaction.isVisible = !it } } viewModel.allTransactionLiveData.observe(viewLifecycleOwner) { transactionList -> binding.rvTransactions.adapter = TransactionAdapter(transactionList) {} } viewModel.errorLiveData.observe(viewLifecycleOwner) { resId -> //show error message binding.tvErrorTransaction.isVisible = true binding.rvTransactions.isVisible = false } } private fun initRecyclerView() { binding.rvTransactions.layoutManager = LinearLayoutManager(requireContext()) } private fun showAlert(title:String,message:String) { val builder = AlertDialog.Builder(requireContext()) builder.setTitle(title) builder.setMessage(message) builder.setPositiveButton("Aceptar",null) val dialog: AlertDialog = builder.create() dialog.show() } }
0
Kotlin
0
0
30b3919f294626a2687d612fa2866d1e3e49c92e
3,118
AlkeBankBase
MIT License
app/src/main/java/vn/loitp/a/cv/fancyShowcase/SecondActivityFancyShowcase.kt
tplloi
126,578,283
false
null
package vn.loitp.a.cv.fancyShowcase import android.os.Bundle import com.loitp.annotation.IsAutoAnimation import com.loitp.annotation.IsFullScreen import com.loitp.annotation.LogTag import com.loitp.core.base.BaseActivityFancyShowcase import kotlinx.android.synthetic.main.a_fancy_showcase_second.* import me.toptas.fancyshowcase.FancyShowCaseView import vn.loitp.R @LogTag("SecondActivityFancyShowcaseFont") @IsFullScreen(false) @IsAutoAnimation(false) class SecondActivityFancyShowcase : BaseActivityFancyShowcase() { override fun setLayoutResourceId(): Int { return R.layout.a_fancy_showcase_second } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) focusOnButton() button1.setOnClickListener { focusOnButton() } } private fun focusOnButton() { FancyShowCaseView.Builder(this@SecondActivityFancyShowcase) .focusOn(button1) .title("Focus a view") .fitSystemWindows(true) .build() .show() } }
0
Kotlin
0
10
333bebaf3287b1633f35d29b8adaf25b19c1859f
1,082
base
Apache License 2.0
app/src/main/java/com/putrova/turnir4gk/data/Tournament.kt
vputrov
231,395,161
false
null
package com.putrova.turnir4gk.data import androidx.room.* import java.util.* @Entity data class Tournament( @PrimaryKey val uid: Int, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "date") val date: Long, @ColumnInfo(name = "question_count") val questionCount: Int ) @Dao interface TournamentDao { @Query("SELECT * FROM tournament") fun getAll(): List<Tournament> @Query("SELECT * FROM tournament WHERE uid IN (:ids)") fun loadAllByIds(ids: IntArray): List<Tournament> @Query("SELECT * FROM tournament WHERE name LIKE :name LIMIT 1") fun findByName(name: String): Tournament @Insert fun insertAll(vararg tournaments: Tournament) @Delete fun delete(tournament: Tournament) }
0
Kotlin
0
0
314fcfce2b3c995e140845ea65a06dec76e130c5
754
Turnir4GK
MIT License
williamchart/src/test/java/com/db/williamchart/renderer/LineChartRendererTest.kt
diogobernardino
22,572,203
false
null
package com.db.williamchart.renderer import com.db.williamchart.ChartContract import com.db.williamchart.Painter import com.db.williamchart.animation.ChartAnimation import com.db.williamchart.data.AxisType import com.db.williamchart.data.DataPoint import com.db.williamchart.data.configuration.LineChartConfiguration import com.db.williamchart.data.Paddings import com.db.williamchart.data.Scale import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.atMost import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.junit.Assert import org.junit.Test class LineChartRendererTest { private val view: ChartContract.LineView = mock() private val painter: Painter = mock() private val animation: ChartAnimation<DataPoint> = mock() private val lineChartRenderer by lazy { LineChartRenderer( view = view, painter = painter, animation = animation ) } @Test fun `draw line background`() { // Arrange val data = linkedMapOf( "this" to 999f, "that" to 111f ) val chartConfiguration = LineChartConfiguration( width = 0, height = 0, paddings = Paddings(0f, 0f, 0f, 0f), axis = AxisType.NONE, labelsSize = 0f, lineThickness = 0f, pointsDrawableWidth = 0, pointsDrawableHeight = 0, fillColor = 20705, gradientFillColors = intArrayOf(), scale = Scale(0f, 0f), clickableRadius = 0 ) // Act lineChartRenderer.render(data) lineChartRenderer.preDraw(chartConfiguration) lineChartRenderer.draw() // Assert verify(view).drawLineBackground(any(), any()) } @Test fun `draw x labels`() { // Arrange val data = linkedMapOf( "this" to 999f, "that" to 111f ) val chartConfiguration = LineChartConfiguration( width = 0, height = 0, paddings = Paddings(0f, 0f, 0f, 0f), axis = AxisType.X, labelsSize = 0f, lineThickness = 0f, pointsDrawableWidth = 0, pointsDrawableHeight = 0, fillColor = 20705, gradientFillColors = intArrayOf(), scale = Scale(0f, 0f), clickableRadius = 0 ) // Act lineChartRenderer.render(data) lineChartRenderer.preDraw(chartConfiguration) lineChartRenderer.draw() // Assert verify(view, atMost(1)).drawLabels(any()) } @Test fun `do not execute click check if no data available`() { // Act val got = lineChartRenderer.processClick(1f, 2f) // Assert Assert.assertEquals(-1, got.first) Assert.assertEquals(-1f, got.second) Assert.assertEquals(-1f, got.third) } }
30
null
800
4,993
f0defc0ad2d509aaf32fcbb40fe353470cca35c8
3,114
williamchart
Apache License 2.0
task1/src/main/java/com/hellofresh/task1/presentation/view/states/MenuUIState.kt
sairam1592
792,622,128
false
{"Kotlin": 46937}
package com.hellofresh.task1.presentation.view.states import com.hellofresh.task1.data.model.Menu /** * This is a UI state that provides access to the menu. * @param menu The menu. * @param selectedRecipeIds The selected recipe IDs. * @param error The error message. */ data class MenuUIState( val menu: Menu? = null, val selectedRecipeIds: Set<Int> = emptySet(), val error: String? = null )
0
Kotlin
0
0
92f571f4ea0bdcad2f5c6eae7f38452524f0126b
410
HelloFresh-Android-Challenge
MIT License
src/commonMain/kotlin/com/adyen/model/payment/SubMerchant.kt
tjerkw
733,432,442
false
{"Kotlin": 5043126, "Makefile": 6356}
/** * Adyen Payment API * * A set of API endpoints that allow you to initiate, settle, and modify payments on the Adyen payments platform. You can use the API to accept card payments (including One-Click and 3D Secure), bank transfers, ewallets, and many other payment methods. To learn more about the API, visit [Classic integration](https://docs.adyen.com/classic-integration). ## Authentication You need an [API credential](https://docs.adyen.com/development-resources/api-credentials) to authenticate to the API. If using an API key, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication, for example: ``` curl -U \"[email protected]_COMPANY_ACCOUNT\":\"YOUR_BASIC_AUTHENTICATION_PASSWORD\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning Payments API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://pal-test.adyen.com/pal/servlet/Payment/v68/authorise ``` ## Going live To authenticate to the live endpoints, you need an [API credential](https://docs.adyen.com/development-resources/api-credentials) from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account: ``` https://{PREFIX}-pal-live.adyenpayments.com/pal/servlet/Payment/v68/authorise ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. * * The version of the OpenAPI document: 68 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.adyen.model.payment import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * * * @param city The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters * @param country The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters * @param mcc The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits * @param name The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters * @param taxId The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ */ @Serializable data class SubMerchant ( /* The city of the sub-merchant's address. * Format: Alphanumeric * Maximum length: 13 characters */ @SerialName(value = "city") val city: kotlin.String? = null, /* The three-letter country code of the sub-merchant's address. For example, **BRA** for Brazil. * Format: [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) * Fixed length: 3 characters */ @SerialName(value = "country") val country: kotlin.String? = null, /* The sub-merchant's 4-digit Merchant Category Code (MCC). * Format: Numeric * Fixed length: 4 digits */ @SerialName(value = "mcc") val mcc: kotlin.String? = null, /* The name of the sub-merchant. Based on scheme specifications, this value will overwrite the shopper statement that will appear in the card statement. * Format: Alphanumeric * Maximum length: 22 characters */ @SerialName(value = "name") val name: kotlin.String? = null, /* The tax ID of the sub-merchant. * Format: Numeric * Fixed length: 11 digits for the CPF or 14 digits for the CNPJ */ @SerialName(value = "taxId") val taxId: kotlin.String? = null )
0
Kotlin
0
0
2da5aea5519b2dfa84454fe1665e9699edc87507
4,150
adyen-kotlin-multiplatform-api-library
MIT License
src/commonMain/kotlin/com/github/adriantodt/lin/bytecode/insn/PushIntegerInsn.kt
adriantodt
280,314,655
false
null
package com.github.adriantodt.lin.bytecode.insn import com.github.adriantodt.lin.bytecode.utils.requireI24 import com.github.adriantodt.lin.bytecode.utils.writeU24 import okio.Buffer public data class PushIntegerInsn(val immediateValue: Int) : Insn() { override fun serializeTo(buffer: Buffer) { buffer.writeByte(Opcode.PUSH_INTEGER.ordinal) .writeU24(immediateValue.requireI24("PushIntegerInsn#immediateValue")) } }
16
Kotlin
0
7
b3b10f34e85bc7dec2d3b94d0d6fb2e51dcf1fbf
449
Lin
MIT License
src/test/kotlin/leetcode/problem0063/UniquePaths2Test.kt
ayukatawago
456,312,186
false
null
package leetcode.problem0063 import kotlin.test.Test import kotlin.test.assertEquals internal class UniquePaths2Test { private val target = UniquePaths2() @Test fun test1() { val obstacleGrid = arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, 0, 0) ) assertEquals(2, target.uniquePathsWithObstacles(obstacleGrid)) } @Test fun test2() { val obstacleGrid = arrayOf( intArrayOf(0, 1), intArrayOf(0, 0) ) assertEquals(1, target.uniquePathsWithObstacles(obstacleGrid)) } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
624
leetcode-kotlin
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/core/adapters/TonAdapter.kt
horizontalsystems
142,825,178
false
{"Kotlin": 4800349, "Shell": 6112, "Ruby": 1350}
package io.horizontalsystems.bankwallet.core.adapters import io.horizontalsystems.bankwallet.core.AdapterState import io.horizontalsystems.bankwallet.core.App import io.horizontalsystems.bankwallet.core.BalanceData import io.horizontalsystems.bankwallet.core.IAdapter import io.horizontalsystems.bankwallet.core.IBalanceAdapter import io.horizontalsystems.bankwallet.core.IReceiveAdapter import io.horizontalsystems.bankwallet.core.ISendTonAdapter import io.horizontalsystems.bankwallet.core.ITransactionsAdapter import io.horizontalsystems.bankwallet.core.UnsupportedAccountException import io.horizontalsystems.bankwallet.entities.AccountType import io.horizontalsystems.bankwallet.entities.LastBlockInfo import io.horizontalsystems.bankwallet.entities.TransactionValue import io.horizontalsystems.bankwallet.entities.Wallet import io.horizontalsystems.bankwallet.entities.transactionrecords.TransactionRecord import io.horizontalsystems.bankwallet.modules.transactions.FilterTransactionType import io.horizontalsystems.bankwallet.modules.transactions.TransactionSource import io.horizontalsystems.bankwallet.modules.transactions.TransactionStatus import io.horizontalsystems.hdwalletkit.Curve import io.horizontalsystems.hdwalletkit.HDWallet import io.horizontalsystems.marketkit.models.Token import io.horizontalsystems.tonkit.ConnectionManager import io.horizontalsystems.tonkit.DriverFactory import io.horizontalsystems.tonkit.SyncState import io.horizontalsystems.tonkit.TonKit import io.horizontalsystems.tonkit.TonKitFactory import io.horizontalsystems.tonkit.TonTransaction import io.horizontalsystems.tonkit.TransactionType import io.horizontalsystems.tonkit.Transfer import io.horizontalsystems.tonkit.transfers import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.subjects.PublishSubject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.rx2.asFlowable import kotlinx.coroutines.rx2.rxSingle import java.math.BigDecimal class TonAdapter( private val wallet: Wallet, ) : IAdapter, IBalanceAdapter, IReceiveAdapter, ITransactionsAdapter, ISendTonAdapter { private val decimals = 9 private val balanceUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() private val balanceStateUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() private val transactionsStateUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() private val tonKit: TonKit private val coroutineScope = CoroutineScope(Dispatchers.Default) private var balance = BigDecimal.ZERO init { val accountType = wallet.account.type val tonKitFactory = TonKitFactory(DriverFactory(App.instance), ConnectionManager(App.instance)) tonKit = when (accountType) { is AccountType.Mnemonic -> { val hdWallet = HDWallet(accountType.seed, 607, HDWallet.Purpose.BIP44, Curve.Ed25519) val privateKey = hdWallet.privateKey(0) tonKitFactory.create(privateKey.privKeyBytes, wallet.account.id) } is AccountType.TonAddress -> { tonKitFactory.createWatch(accountType.address, wallet.account.id) } else -> { throw UnsupportedAccountException() } } } override fun start() { coroutineScope.launch { tonKit.balanceFlow.collect { balance = it.toBigDecimal().movePointLeft(decimals) balanceUpdatedSubject.onNext(Unit) } } coroutineScope.launch { tonKit.balanceSyncStateFlow.collect { balanceState = convertToAdapterState(it) balanceStateUpdatedSubject.onNext(Unit) } } coroutineScope.launch { tonKit.transactionsSyncStateFlow.collect { transactionsState = convertToAdapterState(it) transactionsStateUpdatedSubject.onNext(Unit) } } tonKit.start() } override fun stop() { tonKit.stop() coroutineScope.cancel() } override fun refresh() { // tonKit.refresh() } override val debugInfo: String get() = "" override var balanceState: AdapterState = AdapterState.Syncing() override val balanceStateUpdatedFlowable: Flowable<Unit> get() = balanceStateUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val balanceData: BalanceData get() = BalanceData(balance) override val balanceUpdatedFlowable: Flowable<Unit> get() = balanceUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val receiveAddress = tonKit.receiveAddress override val isMainNet = true override val explorerTitle = "tonscan.org" override var transactionsState: AdapterState = AdapterState.Syncing() override val transactionsStateUpdatedFlowable: Flowable<Unit> get() = transactionsStateUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val lastBlockInfo: LastBlockInfo? get() = null override val lastBlockUpdatedFlowable: Flowable<Unit> get() = Flowable.empty() override fun getTransactionsAsync( from: TransactionRecord?, token: Token?, limit: Int, transactionType: FilterTransactionType, ) = rxSingle { val tonTransactionType = when (transactionType) { FilterTransactionType.All -> null FilterTransactionType.Incoming -> TransactionType.Incoming FilterTransactionType.Outgoing -> TransactionType.Outgoing FilterTransactionType.Swap -> return@rxSingle listOf() FilterTransactionType.Approve -> return@rxSingle listOf() } tonKit .transactions(from?.transactionHash, tonTransactionType, limit.toLong()) .map { createTransactionRecord(it) } } private fun createTransactionRecord(transaction: TonTransaction): TransactionRecord { val amount = transaction.amount?.toBigDecimal()?.movePointLeft(decimals) val value = if (transaction.type == TransactionType.Outgoing) { amount?.negate() } else { amount } ?: BigDecimal.ZERO val fee = transaction.fee?.toBigDecimal()?.movePointLeft(decimals) val type = when (transaction.type) { TransactionType.Incoming -> TonTransactionRecord.Type.Incoming TransactionType.Outgoing -> TonTransactionRecord.Type.Outgoing TransactionType.Unknown -> TonTransactionRecord.Type.Unknown } return TonTransactionRecord( uid = transaction.hash, transactionHash = transaction.hash, logicalTime = transaction.lt, blockHeight = null, confirmationsThreshold = null, timestamp = transaction.timestamp, source = wallet.transactionSource, mainValue = TransactionValue.CoinValue(wallet.token, value), fee = fee?.let { TransactionValue.CoinValue(wallet.token, it) }, type = type, transfers = transaction.transfers.map { createTransferRecprd(it) } ) } private fun createTransferRecprd(transfer: Transfer): TonTransfer { val amount = transfer.amount.toBigDecimal().movePointLeft(decimals) return TonTransfer( src = transfer.src, dest = transfer.dest, amount = TransactionValue.CoinValue(wallet.token, amount), ) } override fun getTransactionRecordsFlowable( token: Token?, transactionType: FilterTransactionType, ): Flowable<List<TransactionRecord>> { val tonTransactionType = when (transactionType) { FilterTransactionType.All -> null FilterTransactionType.Incoming -> TransactionType.Incoming FilterTransactionType.Outgoing -> TransactionType.Outgoing FilterTransactionType.Swap -> return Flowable.empty() FilterTransactionType.Approve -> return Flowable.empty() } return tonKit.newTransactionsFlow .map { if (tonTransactionType != null) { it.filter { it.type == tonTransactionType } } else { it } } .filter { it.isNotEmpty() } .map { it.map { createTransactionRecord(it) } } .asFlowable() } override fun getTransactionUrl(transactionHash: String): String { return "https://tonscan.org/tx/$transactionHash" } private fun convertToAdapterState(syncState: SyncState) = when (syncState) { is SyncState.NotSynced -> AdapterState.NotSynced(syncState.error) is SyncState.Synced -> AdapterState.Synced is SyncState.Syncing -> AdapterState.Syncing() } override val availableBalance: BigDecimal get() = balance override suspend fun send(amount: BigDecimal, address: String) { tonKit.send(address, amount.movePointRight(decimals).toBigInteger().toString()) } override suspend fun estimateFee(): BigDecimal { return tonKit.estimateFee().toBigDecimal().movePointLeft(decimals) } } class TonTransactionRecord( uid: String, transactionHash: String, val logicalTime: Long, blockHeight: Int?, confirmationsThreshold: Int?, timestamp: Long, failed: Boolean = false, spam: Boolean = false, source: TransactionSource, override val mainValue: TransactionValue, val fee: TransactionValue?, val type: Type, val transfers: List<TonTransfer> ) : TransactionRecord( uid, transactionHash, 0, blockHeight, confirmationsThreshold, timestamp, failed, spam, source, ) { enum class Type { Incoming, Outgoing, Unknown } override fun status(lastBlockHeight: Int?) = TransactionStatus.Completed } data class TonTransfer(val src: String, val dest: String, val amount: TransactionValue.CoinValue)
54
Kotlin
355
778
454cb88a3f4687d77ffc3d2d878462f23b4b9dab
10,347
unstoppable-wallet-android
MIT License
src/main/kotlin/com/mark/netrune/endpoint/login/outgoing/LoginResponse.kt
Mark7625
641,050,293
false
null
package com.mark.netrune.endpoint.login.outgoing import com.mark.netrune.endpoint.OutgoingMessage sealed interface LoginResponse : OutgoingMessage { data class SolveProofOfWork( val difficulty: Int, val text: String ) : LoginResponse }
1
Kotlin
1
1
8cff984c258cf12b440e30626b60dd3f36aa9824
263
Osrs-Data-packer
MIT License
app/src/main/java/com/theberdakh/from2/util/ViewEx.kt
theberdakh
710,148,447
false
{"Kotlin": 26465}
package com.theberdakh.from2.util import android.annotation.SuppressLint import android.content.Context import android.graphics.drawable.InsetDrawable import android.util.Log import android.util.TypedValue import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.MenuRes import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.widget.PopupMenu import androidx.compose.material.SnackbarDuration import com.google.android.material.snackbar.Snackbar import com.theberdakh.from2.R import com.theberdakh.from2.data.Language fun Context.showUpMenu( anchorView: View, listOfLanguage: List<Language>, onMenuItemClick: (Int, CharSequence?) -> Boolean ) { val popupMenu = android.widget.PopupMenu(this, anchorView) val menu = popupMenu.menu for (language in listOfLanguage) { menu.add(Menu.NONE, language.ordinal, Menu.NONE, language.name) } popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { } onMenuItemClick.invoke(item.itemId, item.title) } popupMenu.show() } @SuppressLint("RestrictedApi") fun Context.showPopUpMenuWithIcons( view: View, @MenuRes menuRes: Int, onMenuItemClick: (MenuItem) -> Boolean ) { val popUpMenu = PopupMenu(this, view, Gravity.END) popUpMenu.menuInflater.inflate(menuRes, popUpMenu.menu) if (popUpMenu.menu is MenuBuilder) { val menuBuilder = popUpMenu.menu as MenuBuilder menuBuilder.setOptionalIconsVisible(true) for (item in menuBuilder.visibleItems) { val iconMarginPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8f, resources.displayMetrics) .toInt() if (item.icon != null) { item.icon = InsetDrawable(item.icon, iconMarginPx, 0, iconMarginPx, 0) } } } popUpMenu.setOnMenuItemClickListener { menuItem: MenuItem -> onMenuItemClick.invoke(menuItem) } popUpMenu.show() } fun Context.showToast(text: String, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, text, duration).show() } fun View.showSnackbar(text: String, @DrawableRes startIcon : Int = 0, duration: Int = Snackbar.LENGTH_SHORT) { val snackbar = Snackbar.make(this, text, duration) val snackbarLayout = snackbar.view val textView = snackbarLayout.findViewById<TextView>(com.google.android.material.R.id.snackbar_text) textView.setCompoundDrawablesWithIntrinsicBounds(startIcon, 0, 0, 0) textView.compoundDrawablePadding = resources.getDimensionPixelOffset(R.dimen.snackbar_icon_padding) snackbar.show() }
0
Kotlin
0
0
687b137de70a78cf10173820fa5576591d3ab97c
2,821
From2
Apache License 2.0
news-view/core/src/main/java/pe/richard/news/view/core/view/ClicksKt.kt
flight95
814,927,497
false
{"Kotlin": 47427}
package pe.richard.news.view.core.view import android.os.Looper import android.view.View import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.isActive import kotlinx.coroutines.launch fun View.clicks( owner: LifecycleOwner? = null, callback: (View) -> Unit ) { when (owner) { null -> context as? LifecycleOwner else -> owner }?.let { lifecycle -> callbackFlow { if (Looper.myLooper() == Looper.getMainLooper()) { setOnClickListener { if (isActive) { runCatching { trySend(Unit).isSuccess } .getOrDefault(false) } } awaitClose { setOnClickListener(null) } } }.throttleFirst() .onEach { callback(this) } .launchIn(lifecycle.lifecycleScope) } } private fun <T> Flow<T>.throttleFirst(windowDuration: Long = 1000): Flow<T> { var job: Job = Job().apply { complete() } return onCompletion { job.cancel() }.run { flow { coroutineScope { collect { value -> if (!job.isActive) { emit(value) job = launch { delay(windowDuration) } } } } } } }
0
Kotlin
0
2
1a6c9e3b8a8d5e120ee75cbc9457cf4682f42379
1,789
news
MIT License
lib-client/src/main/java/com/baptistecarlier/kotlin/datagouvfr/client/api/AvatarsApi.kt
BapNesS
393,147,318
false
null
package com.baptistecarlier.kotlin.datagouvfr.client.api import com.baptistecarlier.kotlin.datagouvfr.client.DgfrCallState import kotlinx.coroutines.flow.Flow /** * Get a deterministic avatar given an identifier at a given size */ interface AvatarsApi { /** * @param identifier * @param size */ fun getAvatar( identifier: String, size: Int ): Flow<DgfrCallState<ByteArray>> }
3
Kotlin
0
2
f4b849f1b4377c781423bc0b4afbe37fd69ed3e7
424
kotlin-datagouvfr-client
Apache License 2.0
app/src/main/java/com/komeyama/shader_study_android/ui/study16/Study16Renderer.kt
Komeyama
376,831,724
false
null
package com.komeyama.shader_study_android.ui.study16 import android.opengl.Matrix import com.komeyama.shader_study_android.ui.base.GLRendererBase import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 class Study16Renderer : GLRendererBase() { private var gradation: Gradation? = null private val rotationMatrix = FloatArray(16) var angle: Float = 0f private lateinit var currentType: Gradation.GradationShaderType override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig?) { super.onSurfaceCreated(p0, p1) currentType = Gradation.GradationShaderType.Vertical() gradation = Gradation() } override fun onDrawFrame(p0: GL10?) { super.onDrawFrame(p0) drawAndRotate() } override fun onSurfaceChanged(unused: GL10, width: Int, height: Int) { super.onSurfaceChanged(unused, width, height) gradation?.resolution = floatArrayOf(width.toFloat(), height.toFloat()) } fun changeFragmentShader() { currentType = when (currentType) { is Gradation.GradationShaderType.Vertical -> { Gradation.GradationShaderType.Circle() } is Gradation.GradationShaderType.Circle -> { Gradation.GradationShaderType.Bilinear() } is Gradation.GradationShaderType.Bilinear -> { Gradation.GradationShaderType.Vertical() } } } private fun drawAndRotate() { val scratch = FloatArray(16) Matrix.setRotateM(rotationMatrix, 0, angle, 0f, 0f, -1.0f) Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0) gradation?.draw(scratch) gradation?.setProgram(currentType) } }
0
Kotlin
0
0
dd3e76f2538b54fd71c28a9c7667f4f7cc2fd275
1,771
shader-study-android
MIT License
src/main/kotlin/online/bingiz/bilibili/video/internal/helper/LangHelper.kt
BingZi-233
706,595,133
false
{"Kotlin": 38710}
package online.bingiz.bilibili.video.internal.util import org.bukkit.command.CommandSender import org.bukkit.entity.Player import taboolib.common.platform.function.console import taboolib.module.lang.sendInfo import taboolib.module.lang.sendWarn import taboolib.platform.util.sendInfo import taboolib.platform.util.sendWarn internal fun infoMessageAsLang(node: String) { console().sendInfo(node) } internal fun infoMessageAsLang(node: String, vararg args: Any) { console().sendInfo(node, *args) } internal fun warningMessageAsLang(node: String) { console().sendWarn(node) } internal fun warningMessageAsLang(node: String, vararg args: Any) { console().sendWarn(node, *args) } internal fun CommandSender.infoAsLang(node: String) { if (this is Player) { this.sendInfo(node) } else { infoMessageAsLang(node) } } internal fun CommandSender.infoAsLang(node: String, vararg args: Any) { if (this is Player) { this.sendInfo(node, *args) } else { infoMessageAsLang(node, *args) } } internal fun CommandSender.warningAsLang(node: String) { if (this is Player) { this.sendWarn(node) } else { warningMessageAsLang(node) } } internal fun CommandSender.warningAsLang(node: String, vararg args: Any) { if (this is Player) { this.sendWarn(node, *args) } else { warningMessageAsLang(node, *args) } }
0
Kotlin
0
2
407da0351eda1500e42dccbdedfb3448228600f9
1,420
BilibiliVideo
Creative Commons Zero v1.0 Universal
src/main/kotlin/io/github/jonaskahn/services/PagingService.kt
jonaskahn
830,457,632
false
{"Kotlin": 50286, "Dockerfile": 288, "HTML": 228}
package io.github.jonaskahn.services import io.github.jonaskahn.assistant.PageData import io.github.jonaskahn.constants.Defaults.Pageable.DEFAULT_PAGE_SIZE import io.github.jonaskahn.entities.enums.Status import kotlin.math.ceil abstract class PagingService { fun <T> search( statuses: Collection<Status> = listOf(), pageNo: Long, count: (statuses: Collection<Int>) -> Long, lookup: (statuses: Collection<Int>, offset: Long) -> Collection<T> ): PageData<T> { val statusValues = statuses.ifEmpty { Status.entries }.map { it.id } val totalItems = count(statusValues) val totalPages = (ceil(totalItems * 1F / DEFAULT_PAGE_SIZE)).toLong() val calculatedPageNumber = calculatePageNumber(pageNo, totalPages) val offset = (calculatedPageNumber - 1) * DEFAULT_PAGE_SIZE val records = if (totalItems > 0) lookup(statusValues, offset) else listOf() return PageData( data = records, currentPage = if (totalPages == 0L) 0L else calculatedPageNumber, totalPages = totalPages, totalItems = totalItems ) } private fun calculatePageNumber(pageNumber: Long, totalPages: Long): Long { return if (totalPages < 1) { 1L } else if (pageNumber <= 1) { 1L } else if (pageNumber >= totalPages) { totalPages } else { pageNumber } } }
0
Kotlin
1
0
9cbb9369604865089cae4c471ea37741b67d3132
1,463
kooby-api-template
Apache License 2.0
compottie/src/commonTest/kotlin/expressions/global/BooleanExpressionsTest.kt
alexzhirkevich
730,724,501
false
{"Kotlin": 891763, "Swift": 601, "HTML": 211}
package expressions.global import expressions.assertSimpleExprEquals import kotlin.test.Test class BooleanExpressionsTest { @Test fun and() { "true && true".assertSimpleExprEquals(true) "true && true && true".assertSimpleExprEquals(true) "false && false".assertSimpleExprEquals(false) "true && false".assertSimpleExprEquals(false) "false && true".assertSimpleExprEquals(false) "true && true && false".assertSimpleExprEquals(false) "false && true && true".assertSimpleExprEquals(false) } @Test fun or() { "true || true".assertSimpleExprEquals(true) "true || true || true".assertSimpleExprEquals(true) "true || false".assertSimpleExprEquals(true) "false || true".assertSimpleExprEquals(true) "false || false".assertSimpleExprEquals(false) "true || true || false".assertSimpleExprEquals(true) "false || true || true".assertSimpleExprEquals(true) "false || false || true".assertSimpleExprEquals(true) "false || false || false".assertSimpleExprEquals(false) } @Test fun and_or_order() { "true && true || false".assertSimpleExprEquals(true) "false || true && true".assertSimpleExprEquals(true) "(false && true) || (true && true)".assertSimpleExprEquals(true) "false && true || true && true".assertSimpleExprEquals(true) "(false && true || true) && true".assertSimpleExprEquals(true) // "true || false && false".assertSimpleExprEquals(true) "(true || false) && false".assertSimpleExprEquals(false) } @Test fun with_different_source() { "false || 1 == 1".assertSimpleExprEquals(true) "true && 1 == 2".assertSimpleExprEquals(false) "(1 == 2) || false || (1+1) == 2".assertSimpleExprEquals(true) "1 == 2 || false || (1+1) == 2".assertSimpleExprEquals(true) "1 == 1 && 2 == 2".assertSimpleExprEquals(true) "1 == 2 && 2 == 1 || 2 * 2 == 4".assertSimpleExprEquals(true) } }
5
Kotlin
7
232
46b008cd7cf40a84261b20c5888359f08368016a
2,053
compottie
MIT License
app/src/main/java/com/example/moviesapp/data/local/MoviesDatabase.kt
adolfo1295
743,683,867
false
{"Kotlin": 50423}
package com.example.moviesapp.data.local import androidx.room.Database import androidx.room.RoomDatabase import com.example.moviesapp.data.local.dao.MovieDao import com.example.moviesapp.data.local.entities.MovieEntity @Database(entities = [MovieEntity::class], version = 1, exportSchema = false) abstract class MoviesDatabase: RoomDatabase() { abstract fun movieDao(): MovieDao }
24
Kotlin
0
0
c7f8a40c757381ef5254b72bbcfdb336a84e91c4
384
android-basic-course
Apache License 2.0
app/src/main/java/com/example/tracking_app/utils/BindingUtils.kt
yassine-zouhri
373,333,286
false
null
package com.example.tracking_app.utils import android.graphics.Bitmap import android.graphics.BitmapFactory import android.widget.ImageView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import java.io.ByteArrayOutputStream @BindingAdapter("image") fun loadImage(view: ImageView, url: String) { val imageUrl = url.replace("localhost", "192.168.56.1") Glide.with(view) .load(imageUrl) .into(view) } fun ByteArray.toBitmap():Bitmap{ return BitmapFactory.decodeByteArray(this,0,size) } // extension function to convert bitmap to byte array fun Bitmap.toByteArray():ByteArray{ ByteArrayOutputStream().apply { compress(Bitmap.CompressFormat.JPEG,10,this) return toByteArray() } }
0
Kotlin
0
0
88d1c899814e9e3b6df86833dab19b5853963d8f
758
AppMobilePFE
MIT License
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNode.kt
ShalokShalom
343,354,086
true
{"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName") package godot import godot.annotation.GodotBaseType import godot.core.TransferContext import godot.core.VariantArray import godot.core.VariantType.ANY import godot.core.VariantType.ARRAY import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.signals.Signal0 import godot.signals.signal import godot.util.VoidPtr import kotlin.Any import kotlin.Long import kotlin.Suppress @GodotBaseType open class VisualShaderNode : Resource() { val editorRefreshRequest: Signal0 by signal() open var defaultInputValues: VariantArray<Any?> get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_GET_DEFAULT_INPUT_VALUES, ARRAY) return TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?> } set(value) { TransferContext.writeArguments(ARRAY to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_SET_DEFAULT_INPUT_VALUES, NIL) } open var outputPortForPreview: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_GET_OUTPUT_PORT_FOR_PREVIEW, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_SET_OUTPUT_PORT_FOR_PREVIEW, NIL) } override fun __new(): VoidPtr = TransferContext.invokeConstructor(ENGINECLASS_VISUALSHADERNODE) open fun getInputPortDefaultValue(port: Long): Any? { TransferContext.writeArguments(LONG to port) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_GET_INPUT_PORT_DEFAULT_VALUE, ANY) return TransferContext.readReturnValue(ANY, true) as Any? } open fun setInputPortDefaultValue(port: Long, value: Any) { TransferContext.writeArguments(LONG to port, ANY to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODE_SET_INPUT_PORT_DEFAULT_VALUE, NIL) } enum class PortType( id: Long ) { PORT_TYPE_SCALAR(0), PORT_TYPE_VECTOR(1), PORT_TYPE_BOOLEAN(2), PORT_TYPE_TRANSFORM(3), PORT_TYPE_SAMPLER(4), PORT_TYPE_MAX(5); val id: Long init { this.id = id } companion object { fun from(value: Long) = values().single { it.id == value } } } companion object { final const val PORT_TYPE_BOOLEAN: Long = 2 final const val PORT_TYPE_MAX: Long = 5 final const val PORT_TYPE_SAMPLER: Long = 4 final const val PORT_TYPE_SCALAR: Long = 0 final const val PORT_TYPE_TRANSFORM: Long = 3 final const val PORT_TYPE_VECTOR: Long = 1 } }
0
null
0
1
7b9b195de5be4a0b88b9831c3a02f9ca06aa399c
3,090
godot-jvm
MIT License
app/src/main/java/com/example/gifter_single_module/util/TextError.kt
chrming
490,583,267
false
null
package com.example.gifter_single_module.util data class TextError(val isError: Boolean = false, val errorMessage: String? = null)
0
Kotlin
0
0
1937d14a8eb35df1e750ed9fee128879dfd80781
131
GifterSingleModule
BSD Source Code Attribution
datastores/datastores-jvm/src/main/kotlin/info/kinterest/datastores/jvm/manager.kt
svd27
125,085,657
false
null
package info.kinterest.datastores.jvm import info.kinterest.DataStoreEvent import info.kinterest.EntityEvent import info.kinterest.MetaProvider import info.kinterest.datastores.DataStoreFacade import info.kinterest.datastores.IEntityTrace import info.kinterest.functional.Try import info.kinterest.jvm.datastores.DataStoreConfig import info.kinterest.jvm.datastores.IDataStoreFactoryProvider import info.kinterest.jvm.events.Dispatcher import info.kinterest.jvm.tx.TransactionManager import info.kinterest.jvm.tx.TransactionManagerJvm import info.kinterest.query.QueryManager import kotlinx.coroutines.experimental.channels.Channel import mu.KLogging import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.erased.bind import org.kodein.di.erased.instance import org.kodein.di.erased.singleton import java.io.Serializable import java.util.* interface DataStoreFactory : KodeinAware { val events: Channel<DataStoreEvent> fun create(cfg: DataStoreConfig): DataStoreJvm } class DataStoreFactoryProvider(override val kodein: Kodein) : KodeinAware, IDataStoreFactoryProvider { val factories: Map<String, DataStoreFactory> init { logger.debug { "loading factories" } factories = this.javaClass.classLoader.getResources("datastore-factory.properties").toList().flatMap { val props = Properties() it.openStream().use { props.load(it) } props.map { (n, v) -> logger.debug { "loading $n = $v" } //factories[n.toString()] = (Class.forName(v.toString()).newInstance() as DataStoreFactory) n.toString() to Class.forName(v.toString()).kotlin.constructors.first { logger.debug { "$it pars: ${it.parameters}" } it.parameters.size == 1 && it.parameters.any { logger.debug { "par: $it type: ${it.type} ${it.type.classifier == Kodein::class}" } it.type.classifier == Kodein::class } }.call(kodein) as DataStoreFactory } }.toMap() } override fun create(cfg: DataStoreConfig): Try<DataStoreFacade> = Try { factories[cfg.type]!!.create(cfg) } companion object : KLogging() } abstract class DataStoreJvm(name: String, override val kodein: Kodein) : KodeinAware, DataStoreFacade(name) { protected val events: Dispatcher<EntityEvent<*, *>> by instance("entities") override val metaProvider by instance<MetaProvider>() override val qm by instance<QueryManager>() protected val tm: TransactionManager by lazy { val t by kodein.instance<TransactionManager>() t } } data class EntityTrace(override val type: String, override val id: Any, override val ds: String) : Serializable, IEntityTrace { override fun equals(other: Any?): Boolean = _equals(other) } val datasourceKodein = Kodein.Module { bind<IDataStoreFactoryProvider>() with singleton { DataStoreFactoryProvider(kodein) } bind<TransactionManager>() with singleton { TransactionManagerJvm(kodein) } }
0
Kotlin
0
0
19f6d1f1a4c4221dc169e705e95b8ce169f0dc6c
3,142
ki
Apache License 2.0
kotlin-node/src/jsMain/generated/node/v8/cachedDataVersionTag.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! @file:JsModule("node:v8") package node.v8 /** * Returns an integer representing a version tag derived from the V8 version, * command-line flags, and detected CPU features. This is useful for determining * whether a `vm.Script` `cachedData` buffer is compatible with this instance * of V8. * * ```js * console.log(v8.cachedDataVersionTag()); // 3947234607 * // The value returned by v8.cachedDataVersionTag() is derived from the V8 * // version, command-line flags, and detected CPU features. Test that the value * // does indeed update when flags are toggled. * v8.setFlagsFromString('--allow_natives_syntax'); * console.log(v8.cachedDataVersionTag()); // 183726201 * ``` * @since v8.0.0 */ external fun cachedDataVersionTag(): Double
40
Kotlin
165
1,347
997ed3902482883db4a9657585426f6ca167d556
807
kotlin-wrappers
Apache License 2.0
src/main/kotlin/com/wandera/affectedmodulesdetector/graph/GraphFinder.kt
wandera
858,170,746
false
{"Kotlin": 12248}
package com.wandera.affectedmodulesdetector.graph /** * Class searching through graph. * * @property graph Graph to search through. */ class GraphFinder( private val graph: Graph, ) { /** * Finds all nodes that are dependent on given nodes. It doesn't support graph with cycles. * * @param nodes Nodes to find dependent nodes for. * @return Input nodes and nodes dependent on them. */ fun findDependentNodes(nodes: Set<Node>): Set<Node> = if (nodes.isEmpty()) { emptySet() } else { val sourceNodes = nodes.flatMap { node: Node-> getSourceNodes(node) }.toSet() nodes + findDependentNodes(sourceNodes) } private fun getSourceNodes(node: Node): Set<Node> { return graph.edges.filter { it.target == node }.map { it.source }.toSet() } }
0
Kotlin
0
0
079e05e819c6d96316b37cb918262913cc7e0c0b
824
gradle-affected-modules-detector
Apache License 2.0
app/src/main/java/com/example/myapplication/eventcalender/interfaces/MonthlyCalendar.kt
abwarlock
170,000,278
false
null
package com.example.myapplication.eventcalender.interfaces import android.content.Context import com.example.myapplication.eventcalender.models.DayMonthly import org.joda.time.DateTime interface MonthlyCalendar { fun updateMonthlyCalendar(context: Context, month: String, days: ArrayList<DayMonthly>, checkedEvents: Boolean, currTargetDate: DateTime) }
0
Kotlin
0
0
e9e6a7eebeed144971da58450b1f71015af70386
358
calendertest
Apache License 2.0
app/src/main/java/com/isanz/spafy/common/retrofit/home/PlayListResponse.kt
Zenin0
751,889,990
false
{"Kotlin": 88434}
package com.isanz.spafy.common.retrofit.home import com.google.gson.annotations.SerializedName import com.isanz.spafy.common.entities.Cancion import com.isanz.spafy.common.entities.PlayList import com.isanz.spafy.common.retrofit.SuccessResponse data class PlayListResponse( @SerializedName("playlist") val playlists: List<PlayList> ) : SuccessResponse(playlists)
0
Kotlin
0
1
d17f0fe6e3da8336e798eacaebd0cc1fe4ae8fad
368
Spafy
Creative Commons Zero v1.0 Universal
kotlin-electron/src/jsMain/generated/electron/core/DidNavigateEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron.core external interface DidNavigateEvent : Event { var url: String }
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
92
kotlin-wrappers
Apache License 2.0
src/test/kotlin/no/nav/syfo/narmesteleder/NarmesteLederServiceTest.kt
navikt
349,456,925
false
null
package no.nav.syfo.narmesteleder import io.mockk.clearMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import kotlinx.coroutines.runBlocking import no.nav.syfo.application.db.DatabaseInterface import no.nav.syfo.db.getAnsatte import no.nav.syfo.narmesteleder.arbeidsforhold.model.Arbeidsgiverinfo import no.nav.syfo.narmesteleder.arbeidsforhold.service.ArbeidsgiverService import no.nav.syfo.pdl.model.Navn import no.nav.syfo.pdl.model.PdlPerson import no.nav.syfo.pdl.service.PdlPersonService import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.LocalDate import java.time.OffsetDateTime import java.util.UUID class NarmesteLederServiceTest : Spek({ val database = mockk<DatabaseInterface>(relaxed = true) val pdlPersonService = mockk<PdlPersonService>() val arbeidsgiverService = mockk<ArbeidsgiverService>() val service = NarmesteLederService(database, pdlPersonService) mockkStatic("no.nav.syfo.db.NarmesteLederQueriesKt") beforeEachTest { clearMocks(pdlPersonService, arbeidsgiverService) } describe("Get ansatte") { it("should get one ansatt") { runBlocking { coEvery { pdlPersonService.getPersoner(any(), any()) } returns mapOf( "1" to PdlPerson(Navn("ansatt", null, "etternavn"), "1", "aktorId"), "2" to PdlPerson(Navn("leder", null, "etternavn"), "2", "aktorIdLeder") ) every { database.getAnsatte("2") } returns listOf( getNarmestelederRelasjon() ) coEvery { arbeidsgiverService.getArbeidsgivere("2", "token", true) } returns listOf( Arbeidsgiverinfo( orgnummer = "123456789", juridiskOrgnummer = "123456780", aktivtArbeidsforhold = true ) ) val ansatte = service.getAnsatte("2", "callId") ansatte.size shouldBeEqualTo 1 } } it("Skal ikke kalle pdl eller andre tjenester når man ikke finner narmesteleder relasjoner i databasen") { every { database.getAnsatte(any()) } returns emptyList() runBlocking { val ansatte = service.getAnsatte("2", "callid") ansatte.size shouldBeEqualTo 0 coVerify(exactly = 0) { pdlPersonService.getPersoner(any(), any()) } coVerify(exactly = 0) { arbeidsgiverService.getArbeidsgivere(any(), any(), any()) } coVerify(exactly = 0) { pdlPersonService.getPersoner(any(), any()) } } } } }) private fun getNarmestelederRelasjon() = NarmesteLederRelasjon( narmesteLederId = UUID.randomUUID(), fnr = "1", orgnummer = "123456789", narmesteLederFnr = "2", narmesteLederTelefonnummer = "", narmesteLederEpost = "", aktivFom = LocalDate.now(), aktivTom = null, arbeidsgiverForskutterer = true, skrivetilgang = false, tilganger = emptyList(), timestamp = OffsetDateTime.now(), null )
0
Kotlin
2
0
e0cfb8cfacb2aaadaab2b801a670203f51a11006
3,268
narmesteleder
MIT License
app/src/androidTest/java/com/duckduckgo/app/trackerdetection/TdsTest.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.trackerdetection import androidx.test.platform.app.InstrumentationRegistry import com.duckduckgo.app.browser.R import org.junit.Assert.assertEquals import org.junit.Test class TdsTest { /** * If this test fails is because you updated the internal tds json file without changing the default etag value in TrackerDataLoader. * Change the DEFAULT_ETAG value with the latest etag header from tds and then change the value of DEFAULT_TDS_HASH_VALUE below with the new one * to make the test pass. **/ @Test fun whenInternalTdsFileChangesThenEtagValueChanges() { val tdsContent = InstrumentationRegistry.getInstrumentation().targetContext.resources.openRawResource(R.raw.tds) .bufferedReader().use { it.readText() } assertEquals(DEFAULT_TDS_HASH_VALUE, tdsContent.hashCode()) } companion object { private const val DEFAULT_TDS_HASH_VALUE = -160289387 } }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
964
DuckDuckGo
Apache License 2.0
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/models/house/HousesSection.kt
Galarzaa90
285,669,589
false
{"Kotlin": 539836, "Dockerfile": 1451}
/* * Copyright © 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.galarzaa.tibiakt.core.models.house import com.galarzaa.tibiakt.core.enums.HouseOrder import com.galarzaa.tibiakt.core.enums.HouseStatus import com.galarzaa.tibiakt.core.enums.HouseType import com.galarzaa.tibiakt.core.utils.getHousesSectionUrl import kotlinx.serialization.Serializable /** * The Houses Section in Tibia.com. * * @property world The world of the houses. * @property town The town of the houses. * @property status The status filter used for the search, if null, houses of any status will be shown. * @property type The type of houses to display. * @property order The ordering to use. * @property entries The list of houses matching the provided filters. */ @Serializable public data class HousesSection( val world: String, val town: String, val status: HouseStatus?, val type: HouseType, val order: HouseOrder, val entries: List<HouseEntry>, ) { val url: String get() = getHousesSectionUrl(world, town, type, status, order) }
0
Kotlin
2
1
a36cb41c5eef7b9ed54a8bf35c499e32d9bc4fc3
1,596
TibiaKt
Apache License 2.0