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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
backend/app/src/main/kotlin/io/tolgee/controllers/internal/e2e_data/AvatarsE2eDataController.kt | tolgee | 303,766,501 | false | null | package io.tolgee.controllers.internal.e2e_data
import io.swagger.v3.oas.annotations.Hidden
import io.tolgee.development.testDataBuilder.TestDataService
import io.tolgee.development.testDataBuilder.data.AvatarsTestData
import io.tolgee.security.InternalController
import io.tolgee.service.OrganizationService
import io.tolgee.service.UserAccountService
import io.tolgee.service.project.ProjectService
import org.springframework.http.ResponseEntity
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.FileNotFoundException
@RestController
@CrossOrigin(origins = ["*"])
@Hidden
@RequestMapping(value = ["internal/e2e-data/avatars"])
@Transactional
@InternalController
class AvatarsE2eDataController(
private val testDataService: TestDataService,
private val projectService: ProjectService,
private val userAccountService: UserAccountService,
private val organizationService: OrganizationService,
) {
@GetMapping(value = ["/generate"])
@Transactional
fun generateBasicTestData(): Map<String, *> {
val data = AvatarsTestData()
testDataService.saveTestData(data.root)
return mapOf(
"projectId" to data.projectBuilder.self.id,
"organizationSlug" to data.organization.slug
)
}
@GetMapping(value = ["/clean"])
@Transactional
fun cleanup(): Any? {
try {
val testData = AvatarsTestData()
userAccountService.find(testData.user.username)?.let { user ->
projectService.findAllPermitted(user).forEach {
it.id?.let { id -> projectService.deleteProject(id) }
}
testData.root.data.organizations.forEach { organizationBuilder ->
organizationBuilder.self.name?.let { name -> organizationService.deleteAllByName(name) }
}
userAccountService.delete(user)
}
} catch (e: FileNotFoundException) {
return ResponseEntity.internalServerError().body(e.stackTraceToString())
}
return null
}
}
| 50 | null | 8 | 292 | 9896609f260b1ff073134e672303ff8810afc5a1 | 2,187 | server | Apache License 2.0 |
merge-data-class-ksp/src/main/kotlin/io/github/petertrr/merge/ksp/generators/Generators.kt | petertrr | 458,806,767 | false | null | package io.github.petertrr.merge.ksp.generators
import com.google.devtools.ksp.symbol.KSClassifierReference
import com.google.devtools.ksp.symbol.KSValueParameter
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import io.github.petertrr.merge.ksp.Descriptor
internal fun TypeSpec.Builder.copyParametersAsNullable(
ctorBuilder: FunSpec.Builder,
parameters: List<KSValueParameter>
): TypeSpec.Builder {
parameters.forEach { originalParameter ->
val type = originalParameter.type
val resolvedType = originalParameter.type.resolve()
val className = ClassName(
resolvedType.declaration.packageName.asString(),
resolvedType.declaration.simpleName.asString(),
)
.copy(nullable = true)
val typeName = if (resolvedType.arguments.isNotEmpty()) {
with(ParameterizedTypeName.Companion) {
(className as ClassName).parameterizedBy(
typeArguments = resolvedType.arguments.map {
TypeVariableName.Companion.invoke(it.type.toString())
}
)
}
} else {
className
}
.copy(nullable = true)
val originalParameterName = originalParameter.name!!.asString()
if (type is KSClassifierReference && resolvedType.isMarkedNullable) {
ctorBuilder.addParameter(
name = originalParameterName,
type = typeName,
)
} else {
ctorBuilder.addParameter(
name = originalParameterName,
type = typeName,
)
}
// Parameters need to be duplicated as properties for kotlinpoet to merge them into a primary constructor: https://square.github.io/kotlinpoet/#constructors.
addProperty(
PropertySpec.builder(originalParameterName, typeName)
.initializer(originalParameterName)
.build()
)
}
return this
}
internal fun TypeSpec.Builder.createMergeMethod(
descriptor: Descriptor,
originalClassName: ClassName,
newClassName: ClassName,
): TypeSpec.Builder {
val params = descriptor.properties.joinToString(separator = ",\n", postfix = ",") {
val name = it.name!!.asString()
val isNullable = it.type.resolve().isMarkedNullable
buildString {
append("$name ?: other.$name")
if (!isNullable) {
// Non-breaking spaces because of https://square.github.io/kotlinpoet/#spaces-wrap-by-default
append(
" ?: error(\"Property·$name·is·null·on·both·arguments,·but·is·non-nullable·in·class·${originalClassName.canonicalName}\")"
)
}
}
}
addFunction(
FunSpec.builder("merge")
.addParameter(
ParameterSpec("other", newClassName)
)
.returns(originalClassName)
.addCode(
"""
return ${originalClassName.simpleName}(
$params
)
""".trimIndent()
)
.build()
)
return this
}
| 0 | Kotlin | 0 | 1 | 96a65d3fdaeb195f29b078c59dc2db36ae23ac90 | 3,490 | merge-data-class | MIT License |
app/src/main/java/com/slicksoftcoder/goaltracker/feature/domain/use_case/GoalUseCases.kt | JohnnyRoger | 515,779,656 | false | null | package com.slicksoftcoder.goaltracker.feature.domain.use_case
data class GoalUseCases(
val getGoals: GetGoals,
val deleteGoal: DeleteGoal,
val addGoal: AddGoal
)
| 0 | Kotlin | 0 | 0 | d8543891ef444f6a49e388dbe4da5838b0d5eabf | 176 | goal-tracker | MIT License |
src/main/kotlin/me/bardy/bot/commands/misc/LeaveCommand.kt | BomBardyGamer | 273,072,409 | false | null | package me.bardy.bot.commands.misc
import me.bardy.bot.command.BasicCommand
import me.bardy.bot.command.BotCommandContext
import me.bardy.bot.connection.ConnectionManager
import me.bardy.bot.audio.GuildMusicManagers
import org.springframework.stereotype.Component
@Component
class LeaveCommand(
private val connectionManager: ConnectionManager,
private val musicManagers: GuildMusicManagers
) : BasicCommand("leave", setOf("fuckoff", "pissoff", "goaway")) {
override fun execute(context: BotCommandContext) {
val requester = context.member ?: return
val botVoiceChannel = context.getSelf().voiceState?.channel
if (botVoiceChannel == null) {
context.reply("I can't leave a channel if I'm not in one!")
return
}
if (requester.voiceState?.channel != botVoiceChannel) {
context.reply("You have to be in the same channel as me to make me leave!")
return
}
connectionManager.leave(context.guild)
musicManagers.removeForGuild(context.guild)
context.reply("Alright! Alright! I'll get out of your way!")
}
}
| 0 | Kotlin | 0 | 4 | 194a17e7af4eef93e2f8f41b3f81e21677137b76 | 1,139 | bardybot | MIT License |
app/src/main/kotlin/com/thundermaps/apilib/android/api/requests/SaferMeApiError.kt | SaferMe | 240,105,080 | false | null | package com.thundermaps.apilib.android.api.requests
class SaferMeApiError(
val serverStatus: SaferMeApiStatus?,
val requestHeaders: Map<String, List<String>>,
val responseHeaders: Map<String, List<String>>
) : Exception()
| 2 | Kotlin | 0 | 0 | 08837b7d2d9a7dcc2b0bf8335689ba2a31a29685 | 235 | saferme-api-client-android | MIT License |
Remote/src/main/java/com/revolutan/remote/model/ExchangeRateModel.kt | EslamHussein | 189,711,152 | false | null | package com.revolutan.remote.model
import com.google.gson.annotations.SerializedName
class ExchangeRateModel(
@SerializedName("base") val base: String,
@SerializedName("date") val date: String,
@SerializedName("rates") val rates: Map<String, Double>
) | 0 | Kotlin | 0 | 0 | 31ae7289630eb0d08f10efd5102fa12405b84154 | 265 | Revolut-Exchange | Apache License 2.0 |
goblin-transport-server/src/main/java/org/goblinframework/transport/server/channel/TransportServer.kt | xiaohaiz | 206,246,434 | false | {"Java": 807217, "Kotlin": 650572, "FreeMarker": 27779, "JavaScript": 968} | package org.goblinframework.transport.server.channel
import org.goblinframework.api.core.Lifecycle
import org.goblinframework.core.service.GoblinManagedBean
import org.goblinframework.core.service.GoblinManagedObject
import org.goblinframework.core.service.GoblinManagedStopWatch
import org.goblinframework.transport.server.setting.TransportServerSetting
import java.util.concurrent.atomic.AtomicReference
@GoblinManagedBean("TransportServer")
@GoblinManagedStopWatch
class TransportServer internal constructor(private val setting: TransportServerSetting)
: GoblinManagedObject(), Lifecycle, TransportServerMXBean {
private val serverReference = AtomicReference<TransportServerImpl?>()
@Synchronized
override fun start() {
if (serverReference.get() == null) {
val server = TransportServerImpl(setting)
serverReference.set(server)
logger.debug("Transport server [{}] started at [{}:{}]", setting.name(), server.host, server.port)
}
}
override fun stop() {
serverReference.getAndSet(null)?.dispose()
}
override fun isRunning(): Boolean {
return serverReference.get() != null
}
override fun getUpTime(): String? {
return stopWatch?.toString()
}
override fun getName(): String {
return setting.name()
}
override fun getRunning(): Boolean {
return isRunning()
}
override fun getHost(): String? {
return serverReference.get()?.host
}
override fun getPort(): Int? {
return serverReference.get()?.port
}
override fun getTransportServerChannelManager(): TransportServerChannelManagerMXBean? {
return serverReference.get()?.channelManager
}
override fun disposeBean() {
stop()
logger.debug("Transport server [{}] disposed", setting.name())
}
} | 0 | Java | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 1,758 | goblinframework | Apache License 2.0 |
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/index/hash/UQBTreeIndexConfig.kt | vitrivr | 160,775,368 | false | {"Kotlin": 2317843, "Dockerfile": 548} | package org.vitrivr.cottontail.dbms.index.hash
import jetbrains.exodus.bindings.ComparableBinding
import jetbrains.exodus.util.LightOutputStream
import org.vitrivr.cottontail.dbms.index.IndexConfig
import java.io.ByteArrayInputStream
/**
* The [IndexConfig] for the [UQBTreeIndex].
*
* @author <NAME>
* @version 1.0.0
*/
object UQBTreeIndexConfig: IndexConfig<UQBTreeIndex>, ComparableBinding() {
override fun readObject(stream: ByteArrayInputStream): Comparable<UQBTreeIndexConfig> = UQBTreeIndexConfig
override fun writeObject(output: LightOutputStream, `object`: Comparable<UQBTreeIndexConfig>) {
/* No op. */
}
} | 16 | Kotlin | 18 | 26 | 50cc8526952f637d685da9d18f4b1630b782f1ff | 639 | cottontaildb | MIT License |
src/main/kotlin/io/dkozak/locations/controller/HealthController.kt | d-kozak | 153,925,746 | false | {"HTML": 13232, "Kotlin": 5053} | package io.dkozak.locations.controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class HealthController {
/**
* Ping echo health check
*/
@GetMapping("/health")
fun health() = "ok"
} | 0 | HTML | 0 | 0 | 1a319bcc1404b1fa9769c7ba30f9794635022366 | 301 | locations | MIT License |
app/src/main/java/com/semisonfire/cloudgallery/ui/trash/TrashBinFragment.kt | Semyon100116907 | 132,183,724 | false | null | package com.semisonfire.cloudgallery.ui.trash
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.recyclerview.widget.GridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.semisonfire.cloudgallery.R
import com.semisonfire.cloudgallery.R.dimen
import com.semisonfire.cloudgallery.adapter.holder.Item
import com.semisonfire.cloudgallery.core.ui.ContentFragment
import com.semisonfire.cloudgallery.databinding.FragmentTrashBinding
import com.semisonfire.cloudgallery.di.provider.provideComponent
import com.semisonfire.cloudgallery.ui.detail.PhotoDetailActivity
import com.semisonfire.cloudgallery.ui.trash.adapter.TrashBinAdapter
import com.semisonfire.cloudgallery.ui.trash.di.DaggerTrashBinComponent
import com.semisonfire.cloudgallery.ui.trash.model.TrashBinResult
import com.semisonfire.cloudgallery.utils.dimen
import com.semisonfire.cloudgallery.utils.foreground
import javax.inject.Inject
class TrashBinFragment : ContentFragment() {
@Inject
lateinit var presenter: TrashBinPresenter
@Inject
lateinit var adapter: TrashBinAdapter
private var _viewBinding: FragmentTrashBinding? = null
private val viewBinding: FragmentTrashBinding
get() = _viewBinding!!
private var floatingActionButton: FloatingActionButton? = null
private var swipeRefreshLayout: SwipeRefreshLayout? = null
private lateinit var openDetail: ActivityResultLauncher<Intent>
override fun onAttach(context: Context) {
openDetail = registerForActivityResult(StartActivityForResult()) { result ->
val resultCode = result.resultCode
if (resultCode == Activity.RESULT_OK) {
val isDataChanged =
result.data?.getBooleanExtra(PhotoDetailActivity.EXTRA_CHANGED, false) ?: false
if (isDataChanged) {
presenter.getPhotos(0)
}
}
}
DaggerTrashBinComponent
.factory()
.create(
context.provideComponent()
)
.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.getPhotos(0)
}
override fun layout(): Int {
return R.layout.fragment_trash
}
public override fun bind(view: View) {
super.bind(view)
updateToolbarTitle(getString(R.string.msg_trash))
_viewBinding = FragmentTrashBinding.bind(view)
activity?.let {
floatingActionButton = it.findViewById(R.id.btn_add_new)
swipeRefreshLayout = it.findViewById(R.id.swipe_refresh)
}
floatingActionButton?.hide()
viewBinding.rvTrash.adapter = adapter
val orientation = resources.configuration.orientation
viewBinding.rvTrash.layoutManager = GridLayoutManager(
context,
if (orientation == Configuration.ORIENTATION_LANDSCAPE) 4 else 3
)
val itemDecorator = TrashBinItemDecorator(view.context.dimen(dimen.disk_grid_space))
viewBinding.rvTrash.addItemDecoration(itemDecorator)
swipeRefreshLayout?.setOnRefreshListener {
swipeRefreshLayout?.isRefreshing = true
presenter.getPhotos(0)
}
}
override fun onStart() {
super.onStart()
disposables.add(
presenter
.observeTrashBinResult()
.observeOn(foreground())
.subscribe {
when (it) {
is TrashBinResult.Loaded -> onTrashLoaded(it.photos)
TrashBinResult.Cleared -> onTrashCleared()
}
}
)
}
override fun onStop() {
super.onStop()
disposables.clear()
}
override fun onDestroyView() {
super.onDestroyView()
_viewBinding = null
}
override fun onDestroy() {
super.onDestroy()
presenter.dispose()
}
private fun onTrashLoaded(photos: List<Item>) {
swipeRefreshLayout?.isRefreshing = false
adapter.updateDataSet(photos)
}
private fun onTrashCleared() {
adapter.updateDataSet(emptyList())
}
} | 0 | Kotlin | 0 | 1 | 59f8b94fdeaf8db0557deef84f1b25224ab768e4 | 4,638 | CloudGallery | MIT License |
app/src/main/java/com/kromer/openweather/features/weather/data/datasources/local/WeatherLocalDataSourceImpl.kt | kerolloskromer | 386,706,637 | false | null | package com.kromer.openweather.features.weather.data.datasources.local
import androidx.lifecycle.LiveData
import com.kromer.openweather.features.weather.domain.entities.City
class WeatherLocalDataSourceImpl(private val weatherDao: WeatherDao) :
WeatherLocalDataSource {
override fun getAll(): LiveData<List<City>> = weatherDao.getAll()
override suspend fun getByName(name: String): City? = weatherDao.getByName(name)
override suspend fun getById(id: Long): City? = weatherDao.getById(id)
override suspend fun insert(city: City) = weatherDao.insert(city)
override suspend fun delete(city: City) = weatherDao.delete(city)
} | 0 | Kotlin | 0 | 1 | 245804157b67faca2bc40286416bb10d31f9fd8f | 647 | open-weather | MIT License |
educational-core/src/com/jetbrains/edu/learning/taskDescription/ui/SwingTaskUtil.kt | kirillSenchov | 283,726,841 | true | {"Kotlin": 2674430, "Java": 578303, "HTML": 132288, "CSS": 12844, "Python": 3994, "JavaScript": 315} | @file:JvmName("SwingTaskUtil")
package com.jetbrains.edu.learning.taskDescription.ui
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import com.jetbrains.edu.learning.courseFormat.tasks.choice.ChoiceTask
import java.awt.event.ItemEvent
import java.awt.event.ItemListener
import javax.swing.*
import javax.swing.text.html.HTMLEditorKit
private const val LEFT_INSET = 0
private const val RIGHT_INSET = 10
private const val TOP_INSET = 15
private const val BOTTOM_INSET = 10
fun Task?.createSpecificPanel(): JPanel? {
val choiceTask = this as? ChoiceTask ?: return null
return choiceTask.createSpecificPanel()
}
fun ChoiceTask.createSpecificPanel(): JPanel {
val jPanel = JPanel(VerticalFlowLayout())
jPanel.border = JBUI.Borders.empty(TOP_INSET, LEFT_INSET, BOTTOM_INSET, RIGHT_INSET)
if (this.isMultipleChoice) {
val text = JLabel(MULTIPLE_CHOICE_LABEL, SwingConstants.LEFT)
jPanel.add(text)
for ((index, option) in this.choiceOptions.withIndex()) {
val checkBox = createCheckBox(option.text, index, this)
jPanel.add(checkBox)
}
}
else {
val text = JLabel(SINGLE_CHOICE_LABEL, SwingConstants.LEFT)
jPanel.add(text)
val group = ButtonGroup()
for ((index, option) in this.choiceOptions.withIndex()) {
val checkBox = createRadioButton(option.text, index, group, this)
jPanel.add(checkBox)
}
}
return jPanel
}
fun createCheckBox(variant: String?, index: Int, task: ChoiceTask): JCheckBox {
val checkBox = JCheckBox(variant)
checkBox.isSelected = task.selectedVariants.contains(index)
checkBox.addItemListener(createListener(task, index))
return checkBox
}
fun createRadioButton(variant: String, index: Int, group: ButtonGroup, task: ChoiceTask): JRadioButton {
val button = JRadioButton(variant)
button.isSelected = task.selectedVariants.contains(index)
button.addItemListener(createListener(task, index))
group.add(button)
return button
}
fun createListener(task: ChoiceTask, index: Int): ItemListener? {
return ItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
task.selectedVariants.add(index)
}
else {
task.selectedVariants.remove(index)
}
}
}
fun createTextPane(): JTextPane {
val editorKit = UIUtil.JBWordWrapHtmlEditorKit()
prepareCss(editorKit)
val textPane = object : JTextPane() {
override fun getSelectedText(): String {
// see EDU-3185
return super.getSelectedText().replace(Typography.nbsp, ' ')
}
}
textPane.contentType = editorKit.contentType
textPane.editorKit = editorKit
textPane.isEditable = false
textPane.background = TaskDescriptionView.getTaskDescriptionBackgroundColor()
return textPane
}
private fun prepareCss(editorKit: HTMLEditorKit) {
// ul padding of JBHtmlEditorKit is too small, so copy-pasted the style from
// com.intellij.codeInsight.documentation.DocumentationComponent.prepareCSS
editorKit.styleSheet.addRule("ul { padding: 5px 16px 0 7px; }")
editorKit.styleSheet.addRule("li { padding: 1px 0 2px 0; }")
} | 0 | null | 0 | 0 | ccb9d1072da3d214e0c03914b13af36c14f56bce | 3,166 | educational-plugin | Apache License 2.0 |
exercises/gigasecond/.meta/src/reference/kotlin/Gigasecond.kt | luoken | 151,771,980 | true | {"Kotlin": 253660, "Shell": 11713} | import java.time.LocalDate
import java.time.LocalDateTime
data class Gigasecond(val initialDateTime: LocalDateTime) {
constructor(initialDate: LocalDate): this(initialDate.atTime(0, 0))
val date = initialDateTime.plusSeconds(1000000000)
}
| 0 | Kotlin | 0 | 0 | fc51245f547e83c80fe28a455d0daa1590c9e06a | 250 | kotlin | MIT License |
lib/src/main/java/com/drew/metadata/mov/atoms/SoundInformationMediaHeaderAtom.kt | baelec | 231,688,360 | false | {"Git Config": 1, "Gradle": 4, "Markdown": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "YAML": 1, "Java Properties": 1, "CSS": 1, "SVG": 2, "Java": 60, "Kotlin": 362, "DIGITAL Command Language": 3} | /*
* Copyright 2002-2019 <NAME> and contributors
*
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.metadata.mov.atoms
import com.drew.lang.SequentialReader
import com.drew.metadata.mov.media.QuickTimeSoundDirectory
import kotlin.math.pow
/**
* https://developer.apple.com/library/content/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-25647
*
* @author <NAME>
*/
class SoundInformationMediaHeaderAtom(reader: SequentialReader, atom: Atom) : FullAtom(reader, atom) {
var balance: Int = reader.getInt16().toInt()
fun addMetadata(directory: QuickTimeSoundDirectory) {
val integerPortion = (balance and ((-0x10000).toDouble()).toInt()).toDouble()
val fractionPortion = (balance and 0x0000FFFF) / 2.0.pow(4.0)
directory.setDouble(QuickTimeSoundDirectory.TAG_SOUND_BALANCE, integerPortion + fractionPortion)
}
init {
reader.skip(2) // Reserved
}
}
| 1 | null | 1 | 1 | 2df8efc24efa24aca040bc4f392d9b9285d23369 | 1,629 | metadata-extractor | Apache License 2.0 |
src/main/kotlin/feature/settings/SettingsScreen.kt | JJSwigut | 805,493,547 | false | {"Kotlin": 69924} | package feature.settings
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Arrangement.SpaceBetween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Switch
import androidx.compose.material.SwitchColors
import androidx.compose.material.SwitchDefaults
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.Center
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.awtEventOrNull
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import data.models.KlipSettings
import data.models.SortOrder
import kotlinx.coroutines.flow.distinctUntilChanged
import utils.thenIf
@Composable
fun SettingsScreen(
viewModel: SettingsViewModel,
) {
val viewState by viewModel.state.collectAsState()
Window(
onCloseRequest = { viewModel.handleAction(SettingsAction.HandleExit) },
title = SettingsStrings.WindowTitle,
state = rememberWindowState(
placement = WindowPlacement.Floating,
position = WindowPosition(Alignment.Center),
size = DpSize(width = 600.dp, height = 700.dp)
),
alwaysOnTop = true,
) {
SettingsContent(
viewState,
viewModel::handleAction
)
}
}
@Composable
private fun SettingsContent(
viewState: SettingsViewState,
actionHandler: (SettingsAction) -> Unit,
) {
var settings by remember { mutableStateOf(viewState.settings) }
fun updateSettings(update: KlipSettings.() -> KlipSettings) {
settings = settings.update()
}
Surface(color = MaterialTheme.colors.primary) {
Column(
modifier = Modifier.padding(16.dp).wrapContentSize(),
verticalArrangement = Arrangement.spacedBy(24.dp)
) {
Spacer(Modifier.height(24.dp))
SettingsRow(
title = SettingsStrings.TrackHistory,
subtitle = SettingsStrings.TrackHistorySubtitle,
endContent = {
SettingsSwitch(
checked = settings.shouldTrackHistory,
onCheckedChange = {
updateSettings { copy(shouldTrackHistory = it) }
}
)
}
)
SettingsRow(
title = SettingsStrings.KlipSortOrder,
endContent = {
DropdownMenuSortOrder(
selectedSortOrder = settings.klipSortOrder,
onSelectSortOrder = { updateSettings { copy(klipSortOrder = it) } }
)
}
)
SettingsRow(
title = SettingsStrings.PinSortOrder,
endContent = {
DropdownMenuSortOrder(
selectedSortOrder = settings.pinnedSortOrder,
onSelectSortOrder = { updateSettings { copy(pinnedSortOrder = it) } }
)
}
)
val openHotKeysSubtitle = remember {
SettingsStrings.CurrentKeys + settings.openHotKeys.toHotKeyString()
}
SettingsRow(
title = SettingsStrings.OpenHotKeys,
subtitle = openHotKeysSubtitle,
endContent = {
HotKeyField(
currentHotkeys = remember { settings.openHotKeys },
onHotkeyChange = { updateSettings { copy(openHotKeys = it) } }
)
}
)
val closeHotKeysSubtitle = remember {
SettingsStrings.CurrentKeys + settings.closeHotKeys.toHotKeyString()
}
SettingsRow(
title = SettingsStrings.CloseHotKeys,
subtitle = closeHotKeysSubtitle,
endContent = {
HotKeyField(
currentHotkeys = remember { settings.closeHotKeys },
onHotkeyChange = { updateSettings { copy(closeHotKeys = it) } }
)
}
)
Spacer(Modifier.weight(1f))
Button(
onClick = { actionHandler(SettingsAction.HandleSave(settings)) },
modifier = Modifier.align(CenterHorizontally).padding(16.dp).heightIn(48.dp).border(width = 1.dp, color = MaterialTheme.colors.onPrimary, shape = MaterialTheme.shapes.medium)
) {
Text(SettingsStrings.SaveButton)
}
}
}
}
private fun List<Int>.toHotKeyString(): String {
return this.joinToString(" + ") {
java.awt.event.KeyEvent.getKeyText(it)
}
}
@Composable
private fun SettingsSwitch(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Switch(
checked = checked,
onCheckedChange = onCheckedChange,
colors = SwitchDefaults.colors(
checkedThumbColor = Color.Green,
uncheckedThumbColor = Color.Red,
)
)
}
@Composable
private fun SettingsRow(
title: String,
subtitle: String? = null,
endContent: @Composable () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = SpaceBetween
) {
Column(
modifier = Modifier.weight(2f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.Start
) {
Text(title, style = MaterialTheme.typography.h6, color = MaterialTheme.colors.onPrimary)
subtitle?.let {
Text(
it,
style = MaterialTheme.typography.subtitle2,
color = MaterialTheme.colors.onPrimary
)
}
}
Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.Center) {
endContent()
}
}
}
@Composable
fun DropdownMenuSortOrder(selectedSortOrder: SortOrder, onSelectSortOrder: (SortOrder) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box {
Text(text = selectedSortOrder.name, modifier = Modifier
.clickable { expanded = true }, color = MaterialTheme.colors.onPrimary
)
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
SortOrder.entries.forEach { sortOrder ->
DropdownMenuItem(onClick = {
onSelectSortOrder(sortOrder)
expanded = false
}) {
Text(text = sortOrder.name, color = MaterialTheme.colors.onPrimary)
}
}
}
}
}
@Composable
fun HotKeyField(currentHotkeys: List<Int>, onHotkeyChange: (List<Int>) -> Unit) {
var isFocused by remember { mutableStateOf(false) }
val hotKeys = remember { mutableStateListOf<Int>() }
var hotKeysTextValue by remember(hotKeys) {
mutableStateOf(TextFieldValue(hotKeys.toHotKeyString()))
}
val borderColor = MaterialTheme.colors.onPrimary
val borderShape = MaterialTheme.shapes.medium
val borderModifier = remember(isFocused){
if(isFocused){
Modifier.border(1.dp, borderColor, borderShape)
} else {
Modifier
}
}
TextField(
value = hotKeysTextValue,
onValueChange = {},
readOnly = true,
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
textColor = MaterialTheme.colors.onPrimary,
backgroundColor = MaterialTheme.colors.secondary,
focusedIndicatorColor = MaterialTheme.colors.onPrimary,
unfocusedIndicatorColor = MaterialTheme.colors.onPrimary,
cursorColor = MaterialTheme.colors.onSecondary
),
trailingIcon = {
if (hotKeys.isNotEmpty()) {
TrailingCloseIcon {
hotKeys.clear()
onHotkeyChange(currentHotkeys)
hotKeysTextValue = TextFieldValue("")
}
}
},
modifier = Modifier
.fillMaxWidth().padding(8.dp)
.focusRequester(remember { FocusRequester() })
.onFocusChanged { focusState ->
isFocused = focusState.isFocused
}
.onKeyEvent { event: KeyEvent ->
if (isFocused && event.type == KeyEventType.KeyDown) {
val eventKey = event.awtEventOrNull?.keyCode ?: return@onKeyEvent false
hotKeys.addHotKey(eventKey)
hotKeysTextValue = TextFieldValue(hotKeys.toHotKeyString())
onHotkeyChange(hotKeys)
true
} else {
false
}
}.then(borderModifier)
)
}
private fun MutableList<Int>.addHotKey(key: Int) {
if (key !in this) {
add(key)
}
if (size > 3) {
removeAt(0)
}
}
@Composable
private fun TrailingCloseIcon(onClick: () -> Unit) {
Box(
modifier = Modifier
.background(MaterialTheme.colors.primary, CircleShape)
.clip(CircleShape)
.clickable { onClick() },
contentAlignment = Center
) {
Icon(imageVector = Icons.Filled.Close, contentDescription = null)
}
}
object SettingsStrings {
const val WindowTitle = "Settings"
const val SaveButton = "Save"
const val TrackHistory = "Track History"
const val TrackHistorySubtitle = "when this is checked, any text added to the system clipboard will show up in the history column"
const val KlipSortOrder = "Sort Klips By:"
const val PinSortOrder = "Sort Pinned Klips By:"
const val CloseHotKeys = "Close Hot Keys"
const val OpenHotKeys = "Open Hot Keys"
const val CurrentKeys = "Current Keys: "
}
| 0 | Kotlin | 0 | 1 | 7c427cdb86bdeace9f1a51c4e4dc21922efb05d0 | 12,301 | KlippaKlip | MIT License |
features/auth/firebase/firebase-api/src/main/java/com/odogwudev/example/firebase_api/AuthResult.kt | odogwudev | 592,877,753 | false | null | package com.odogwudev.example.firebase_api
import com.google.android.gms.tasks.Task
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
sealed class AuthResult {
object Success : AuthResult()
data class Failure(val error: String) : AuthResult()
data class Dismissed(val error: String? = null) : AuthResult()
}
fun <T>consumeTask(
task: Task<T>,
sideEffect: () -> Unit = { }
): Flow<AuthResult> = callbackFlow {
task
.addOnSuccessListener {
trySend(element = AuthResult.Success).isSuccess
sideEffect()
}
.addOnFailureListener { error -> trySend(element = AuthResult.Failure(error = error.message.orEmpty())).isFailure }
awaitClose { }
}
sealed class AuthWithResult<T> {
data class Success<T>(val data: T) : AuthWithResult<T>()
data class Failure<T>(val error: String) : AuthWithResult<T>()
data class Dismissed<T>(val message: String? = null) : AuthWithResult<T>()
}
fun <P, T>consumeTaskWithResult(task: Task<T>, taskConverter: (T) -> P): Flow<AuthWithResult<P>> = callbackFlow {
task
.addOnSuccessListener { result -> trySend(element = AuthWithResult.Success(
data = taskConverter(
result
)
)
).isSuccess }
.addOnFailureListener { error -> trySend(element = AuthWithResult.Failure(error = error.message.orEmpty())).isFailure }
awaitClose { }
}
| 0 | Kotlin | 0 | 4 | 82791abdcf1554d2a2cd498a19cd93952f90e53e | 1,499 | CinephilesCompanion | MIT License |
source/sdk/src/main/java/com/stytch/sdk/consumer/crypto/CryptoWalletImpl.kt | stytchauth | 314,556,359 | false | {"Kotlin": 1897715, "Java": 7049, "HTML": 545} | package com.stytch.sdk.consumer.crypto
import com.stytch.sdk.common.StytchDispatchers
import com.stytch.sdk.consumer.AuthResponse
import com.stytch.sdk.consumer.CryptoWalletAuthenticateStartResponse
import com.stytch.sdk.consumer.extensions.launchSessionUpdater
import com.stytch.sdk.consumer.network.StytchApi
import com.stytch.sdk.consumer.sessions.ConsumerSessionStorage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.CompletableFuture
internal class CryptoWalletImpl(
private val externalScope: CoroutineScope,
private val dispatchers: StytchDispatchers,
private val sessionStorage: ConsumerSessionStorage,
private val api: StytchApi.Crypto,
) : CryptoWallet {
override suspend fun authenticateStart(
parameters: CryptoWallet.AuthenticateStartParameters,
): CryptoWalletAuthenticateStartResponse =
withContext(dispatchers.io) {
if (sessionStorage.persistedSessionIdentifiersExist) {
api.authenticateStartSecondary(
cryptoWalletAddress = parameters.cryptoWalletAddress,
cryptoWalletType = parameters.cryptoWalletType,
)
} else {
api.authenticateStartPrimary(
cryptoWalletAddress = parameters.cryptoWalletAddress,
cryptoWalletType = parameters.cryptoWalletType,
)
}
}
override fun authenticateStart(
parameters: CryptoWallet.AuthenticateStartParameters,
callback: (CryptoWalletAuthenticateStartResponse) -> Unit,
) {
externalScope.launch(dispatchers.ui) {
callback(authenticateStart(parameters))
}
}
override fun authenticateStartCompletable(
parameters: CryptoWallet.AuthenticateStartParameters,
): CompletableFuture<CryptoWalletAuthenticateStartResponse> =
externalScope
.async {
authenticateStart(parameters)
}.asCompletableFuture()
override suspend fun authenticate(parameters: CryptoWallet.AuthenticateParameters): AuthResponse =
withContext(dispatchers.io) {
api
.authenticate(
cryptoWalletAddress = parameters.cryptoWalletAddress,
cryptoWalletType = parameters.cryptoWalletType,
signature = parameters.signature,
sessionDurationMinutes = parameters.sessionDurationMinutes,
).apply {
launchSessionUpdater(dispatchers, sessionStorage)
}
}
override fun authenticate(
parameters: CryptoWallet.AuthenticateParameters,
callback: (AuthResponse) -> Unit,
) {
externalScope.launch(dispatchers.ui) {
callback(authenticate(parameters))
}
}
override fun authenticateCompletable(
parameters: CryptoWallet.AuthenticateParameters,
): CompletableFuture<AuthResponse> =
externalScope
.async {
authenticate(parameters)
}.asCompletableFuture()
}
| 2 | Kotlin | 2 | 23 | 4aa3cdf24da81a531f72f6011a07dc80ef082cdb | 3,269 | stytch-android | MIT License |
newsapp-main/newsapp-main/NewsAppStarter/app/src/main/java/daniellopes/io/newsappstarter/ui/fragments/base/ViewModelFactory.kt | juliocarvalho2019 | 650,383,020 | false | null | package daniellopes.io.newsappstarter.ui.fragments.base
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import daniellopes.io.newsappstarter.repository.NewsRepository
import daniellopes.io.newsappstarter.ui.fragments.favorite.FavoriteViewModel
import daniellopes.io.newsappstarter.ui.fragments.home.HomeViewModel
import daniellopes.io.newsappstarter.ui.fragments.search.SearchViewModel
import daniellopes.io.newsappstarter.ui.fragments.webview.WebViewViewModel
// Forma de instanciarmos os viewModels, passando o que eu quero para ele, no caso, o repositorio que recebemos do BaseFragment
@Suppress("UNCHECKED_CAST")
class ViewModelFactory(
private val repository: NewsRepository,
private val application: Application
) : ViewModelProvider.NewInstanceFactory() {
//responsáveis por instanciar ViewModels .
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return when {
modelClass.isAssignableFrom(HomeViewModel::class.java) -> HomeViewModel(repository, application) as T
modelClass.isAssignableFrom(SearchViewModel::class.java) -> SearchViewModel(repository) as T
modelClass.isAssignableFrom(FavoriteViewModel::class.java) -> FavoriteViewModel(repository) as T
modelClass.isAssignableFrom(WebViewViewModel::class.java) -> WebViewViewModel(repository) as T
else -> throw IllegalArgumentException("ViewModel Class not found")
}
}
} | 0 | Kotlin | 0 | 0 | b79d0948394ea5506ab9afde59e86bfdbeea80de | 1,502 | News-App-Starter-MVVM | Apache License 2.0 |
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/logos/BxlYahoo.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.boxicons.boxicons.logos
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.LogosGroup
public val LogosGroup.BxlYahoo: ImageVector
get() {
if (_bxlYahoo != null) {
return _bxlYahoo!!
}
_bxlYahoo = Builder(name = "BxlYahoo", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.131f, 21.0f)
reflectiveCurveToRelative(-0.63f, -0.114f, -1.138f, -0.114f)
curveToRelative(-0.457f, 0.0f, -1.142f, 0.114f, -1.142f, 0.114f)
lineToRelative(0.143f, -7.646f)
curveTo(9.933f, 11.52f, 6.814f, 5.933f, 4.868f, 3.0f)
curveToRelative(0.979f, 0.223f, 1.391f, 0.209f, 2.374f, 0.0f)
lineToRelative(0.015f, 0.025f)
curveToRelative(1.239f, 2.194f, 3.135f, 5.254f, 4.736f, 7.905f)
curveTo(13.575f, 8.325f, 16.064f, 4.258f, 16.74f, 3.0f)
curveToRelative(0.765f, 0.201f, 1.536f, 0.193f, 2.392f, 0.0f)
curveToRelative(-0.9f, 1.213f, -4.175f, 6.88f, -6.153f, 10.354f)
lineTo(13.125f, 21.0f)
horizontalLineToRelative(0.006f)
close()
}
}
.build()
return _bxlYahoo!!
}
private var _bxlYahoo: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,131 | compose-icon-collections | MIT License |
library/src/test/java/com/silverhetch/aura/media/BitmapStreamTest.kt | fossabot | 268,971,220 | false | {"Gradle": 4, "Markdown": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Proguard": 2, "Kotlin": 138, "XML": 41, "Java": 52} | package com.silverhetch.aura.media
import android.graphics.Bitmap
import android.graphics.Color
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
/**
* Test for com.silverhetch.aura.media.BitmapStream
*/
@RunWith(RobolectricTestRunner::class)
class BitmapStreamTest {
/**
* Check if this procedure can be done normally and have some output.
*/
@Test
fun simple() {
assertNotEquals(
0,
BitmapStream(
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888).also {
it.eraseColor(Color.RED)
}
).value().readBytes().size
)
}
} | 9 | Kotlin | 2 | 1 | fb00fe41a2b32dbbd9fcc88d0fcd8d531c9b0638 | 725 | Aura | MIT License |
app/src/main/java/com/zeroami/app/MainPresenter.kt | zerozblin | 94,421,849 | false | {"Java": 158428, "Kotlin": 110631} | package com.zeroami.app
import com.zeroami.commonlib.mvp.LBasePresenter
class MainPresenter(view: MainContract.View) : LBasePresenter<MainContract.View>(view), MainContract.Presenter {
private val mainModel by lazy { MainModel() }
override fun doViewInitialized() {
mainModel.login("123", "456"){
e,result ->
if (e == null){
mvpView.showResult(result!!)
}
}.let { addDisposable(it) }
}
}
| 0 | Java | 0 | 0 | 26726e376064d64f31b810e05195054245dac286 | 472 | CommonLib-Kotlin | Apache License 2.0 |
app/src/main/kotlin/io/github/cianciustyles/BvhNode.kt | CianciuStyles | 544,340,457 | false | {"Kotlin": 92611} | package io.github.cianciustyles
import kotlin.random.Random
class BvhNode: Hittable {
private val left: Hittable
private val right: Hittable
private val box: Aabb
constructor(objects: List<Hittable>, start: Int, end: Int, time0: Double, time1: Double) {
val comparator = BoxComparator(Random.nextInt(2))
when (val objectSpan = end - start) {
1 -> {
left = objects[start]
right = objects[start]
}
2 -> {
if (comparator.compare(objects[start], objects[start + 1]) < 0) {
left = objects[start]
right = objects[start + 1]
} else {
left = objects[start + 1]
right = objects[start]
}
}
else -> {
val sortedObjects = objects.sortedWith(comparator)
val mid = start + objectSpan / 2
left = BvhNode(sortedObjects, start, mid, time0, time1)
right = BvhNode(sortedObjects, mid, end, time0, time1)
}
}
val boxLeft = left.boundingBox(time0, time1)
val boxRight = right.boundingBox(time0, time1)
if (boxLeft == null || boxRight == null)
System.err.println("No bounding box in BvhNode constructor.\n")
box = Aabb.surroundingBox(boxLeft ?: Aabb(), boxRight ?: Aabb())
}
constructor(hittableList: HittableList, time0: Double, time1: Double):
this(hittableList.objects, 0, hittableList.objects.size, time0, time1)
class BoxComparator(private val axis: Int): Comparator<Hittable> {
override fun compare(a: Hittable?, b: Hittable?): Int {
val boxA = a?.boundingBox(0.0, 0.0)
val boxB = b?.boundingBox(0.0, 0.0)
if (boxA == null || boxB == null)
System.err.println("No bounding box in BvhNode constructor.\n")
return ((boxA ?: Aabb()).minimum[axis] compareTo (boxB ?: Aabb()).minimum[axis])
}
}
override fun boundingBox(time0: Double, time1: Double): Aabb = box
override fun hit(ray: Ray, tMin: Double, tMax: Double): HitRecord? {
if (!box.hit(ray, tMin, tMax)) return null
return left.hit(ray, tMin, tMax) ?: right.hit(ray, tMin, tMax)
}
} | 0 | Kotlin | 0 | 0 | d71947f09c9a0ac8611cc9c45999d8f9e1234d67 | 2,345 | ray-tracing-the-next-week | The Unlicense |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/HandFingersCrossed.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.HandFingersCrossed: ImageVector
get() {
if (_handFingersCrossed != null) {
return _handFingersCrossed!!
}
_handFingersCrossed = Builder(name = "HandFingersCrossed", defaultWidth = 512.0.dp,
defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.5f, 8.0f)
curveToRelative(0.828f, 0.0f, 1.5f, 0.672f, 1.5f, 1.5f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
verticalLineToRelative(-4.0f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
close()
moveTo(19.5f, 8.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
verticalLineToRelative(-4.0f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(18.0f, 16.649f)
verticalLineToRelative(4.351f)
lineTo(9.094f, 21.0f)
lineToRelative(-3.506f, -3.288f)
lineToRelative(3.814f, -3.948f)
curveToRelative(0.797f, -0.797f, 0.797f, -2.089f, 0.0f, -2.886f)
curveToRelative(-0.797f, -0.797f, -2.089f, -0.797f, -2.886f, 0.0f)
lineToRelative(-3.512f, 3.618f)
curveToRelative(-0.646f, 0.658f, -1.004f, 1.525f, -1.004f, 2.449f)
curveToRelative(0.0f, 0.935f, 0.364f, 1.814f, 1.06f, 2.508f)
lineToRelative(4.847f, 4.547f)
horizontalLineToRelative(13.094f)
verticalLineToRelative(-7.351f)
curveToRelative(-0.456f, 0.219f, -0.961f, 0.351f, -1.5f, 0.351f)
reflectiveCurveToRelative(-1.044f, -0.133f, -1.5f, -0.351f)
close()
moveTo(7.221f, 6.151f)
lineToRelative(1.651f, -3.261f)
lineTo(7.823f, 0.819f)
curveTo(7.445f, 0.081f, 6.546f, -0.214f, 5.804f, 0.166f)
curveToRelative(-0.737f, 0.377f, -1.029f, 1.281f, -0.652f, 2.019f)
lineToRelative(2.069f, 3.966f)
close()
moveTo(10.817f, 9.464f)
curveToRelative(0.051f, 0.051f, 0.087f, 0.111f, 0.134f, 0.164f)
lineToRelative(3.883f, -7.443f)
curveToRelative(0.377f, -0.737f, 0.085f, -1.641f, -0.652f, -2.019f)
curveToRelative(-0.743f, -0.38f, -1.642f, -0.086f, -2.019f, 0.652f)
lineToRelative(-3.799f, 7.501f)
curveToRelative(0.925f, 0.093f, 1.787f, 0.479f, 2.453f, 1.145f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.5f, 8.0f)
curveToRelative(0.828f, 0.0f, 1.5f, 0.672f, 1.5f, 1.5f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
verticalLineToRelative(-4.0f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
close()
moveTo(19.5f, 8.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
verticalLineToRelative(-4.0f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(18.0f, 16.649f)
verticalLineToRelative(4.351f)
lineTo(9.094f, 21.0f)
lineToRelative(-3.506f, -3.288f)
lineToRelative(3.814f, -3.948f)
curveToRelative(0.797f, -0.797f, 0.797f, -2.089f, 0.0f, -2.886f)
curveToRelative(-0.797f, -0.797f, -2.089f, -0.797f, -2.886f, 0.0f)
lineToRelative(-3.512f, 3.618f)
curveToRelative(-0.646f, 0.658f, -1.004f, 1.525f, -1.004f, 2.449f)
curveToRelative(0.0f, 0.935f, 0.364f, 1.814f, 1.06f, 2.508f)
lineToRelative(4.847f, 4.547f)
horizontalLineToRelative(13.094f)
verticalLineToRelative(-7.351f)
curveToRelative(-0.456f, 0.219f, -0.961f, 0.351f, -1.5f, 0.351f)
reflectiveCurveToRelative(-1.044f, -0.133f, -1.5f, -0.351f)
close()
moveTo(7.221f, 6.151f)
lineToRelative(1.651f, -3.261f)
lineTo(7.823f, 0.819f)
curveTo(7.445f, 0.081f, 6.546f, -0.214f, 5.804f, 0.166f)
curveToRelative(-0.737f, 0.377f, -1.029f, 1.281f, -0.652f, 2.019f)
lineToRelative(2.069f, 3.966f)
close()
moveTo(10.817f, 9.464f)
curveToRelative(0.051f, 0.051f, 0.087f, 0.111f, 0.134f, 0.164f)
lineToRelative(3.883f, -7.443f)
curveToRelative(0.377f, -0.737f, 0.085f, -1.641f, -0.652f, -2.019f)
curveToRelative(-0.743f, -0.38f, -1.642f, -0.086f, -2.019f, 0.652f)
lineToRelative(-3.799f, 7.501f)
curveToRelative(0.925f, 0.093f, 1.787f, 0.479f, 2.453f, 1.145f)
close()
}
}
.build()
return _handFingersCrossed!!
}
private var _handFingersCrossed: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,960 | icons | MIT License |
src/test/kotlin/adventofcode2016/Day03SquaresWithThreeSidesTest.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 490757, "Java": 275} | package adventofcode2016
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import utils.ResourceLoader
import java.io.File
import kotlin.test.assertEquals
class Day03SquaresWithThreeSidesTest {
lateinit var file: File
@BeforeEach
fun setup() {
file = ResourceLoader.getFile("aoc2016/aoc2016_day03_input.txt")
}
@ParameterizedTest
@MethodSource("sampleTestData1")
fun runSamplesPart1(description: String, expectedResult: Boolean) {
val triangle = Triangle.fromString(description)
assertEquals(expectedResult, triangle.isValid())
}
@Test
fun solutionPart1() {
val squareChecker = SquareChecker()
val descriptions = file.readLines().filter { it.length > 1}
val validTrianglesCount = squareChecker.checkTriangles(descriptions)
assertEquals(983, validTrianglesCount)
println("Solution for AoC2016-Day03-Part01: $validTrianglesCount")
}
@Test
fun solutionPart2() {
val squareChecker = SquareChecker()
val descriptions = file.readLines().filter { it.length > 1}
val validTrianglesCount = squareChecker.checkTrianglesVertically(descriptions)
assertEquals(1836, validTrianglesCount)
println("Solution for AoC2016-Day03-Part02: $validTrianglesCount")
}
companion object {
@JvmStatic
fun sampleTestData1() = listOf(
Arguments.of("5 10 25", false),
Arguments.of("10 12 18", true),
Arguments.of("1 2 3", false),
Arguments.of("2 4 5", true),
Arguments.of("4 5 2", true),
Arguments.of("5 4 2", true),
Arguments.of("25 10 5", false),
Arguments.of("10 25 5", false)
)
}
} | 0 | Kotlin | 0 | 0 | 9f12e6a86a14c1cb544e869488d2010df6ae6b42 | 1,929 | kotlin-coding-challenges | MIT License |
plugins/kotlin/idea/tests/testData/quickfix/suppress/inspections/codeStructure/propertySuppressedOnClass.kt | JetBrains | 2,489,216 | false | null | // "Suppress 'CanBePrimaryConstructorProperty' for class PropertySuppressedOnClass" "true"
class PropertySuppressedOnClass(name: String) {
val <caret>name = name
}
// K1_TOOL: org.jetbrains.kotlin.idea.inspections.CanBePrimaryConstructorPropertyInspection
// K2_TOOL: org.jetbrains.kotlin.idea.k2.codeinsight.inspections.CanBePrimaryConstructorPropertyInspection
// FUS_K2_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix
// FUS_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 534 | intellij-community | Apache License 2.0 |
src/no/omb/bigboat/data/ClubEntry.kt | omb | 24,110,528 | false | {"HTML": 35705, "Kotlin": 30411} | package no.omb.bigboat.data
import no.omb.bigboat.BigBoat
import java.text.DecimalFormat
data class ClubEntry(
val club: String,
var score: Double = 0.0,
var numScores: Int = 0
) : Comparable<ClubEntry> {
override fun toString(): String {
val df = DecimalFormat("#0.00")
return club + BigBoat.SEP + df.format(score / BigBoat.CLUB_MAX_SCORES)
}
override fun compareTo(other: ClubEntry): Int {
return (score * 100 - other.score * 100).toInt()
}
}
| 0 | HTML | 0 | 0 | b9009798c32f05f8b0cee449c98af975782eaa84 | 501 | oslo-bigboat | MIT License |
android-checkout-sdk/src/main/java/com/zilla/networking/model/response/BaseResponse.kt | Zilla-tech | 437,619,910 | false | null | package com.zilla.networking.model.response
data class BaseResponse<T>(val message: String?, val data: T?) | 0 | Kotlin | 0 | 0 | 9ca414f084525ad998c9447b974108b19b2bae6f | 107 | android-checkout-sdk | MIT License |
src/main/kotlin/no/nav/familie/ba/sak/integrasjoner/infotrygd/MigreringService.kt | navikt | 224,639,942 | false | null | package no.nav.familie.ba.sak.integrasjoner.infotrygd
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.Metrics
import no.nav.familie.ba.sak.common.EnvService
import no.nav.familie.ba.sak.common.førsteDagIInneværendeMåned
import no.nav.familie.ba.sak.common.førsteDagINesteMåned
import no.nav.familie.ba.sak.common.toYearMonth
import no.nav.familie.ba.sak.config.TaskRepositoryWrapper
import no.nav.familie.ba.sak.integrasjoner.infotrygd.domene.MigreringResponseDto
import no.nav.familie.ba.sak.integrasjoner.pdl.PdlRestClient
import no.nav.familie.ba.sak.kjerne.behandling.BehandlingService
import no.nav.familie.ba.sak.kjerne.behandling.NyBehandling
import no.nav.familie.ba.sak.kjerne.behandling.domene.Behandling
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingRepository
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingStatus
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingType
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingÅrsak
import no.nav.familie.ba.sak.kjerne.beregning.beregnUtbetalingsperioderUtenKlassifisering
import no.nav.familie.ba.sak.kjerne.beregning.domene.AndelTilkjentYtelse
import no.nav.familie.ba.sak.kjerne.beregning.domene.TilkjentYtelseRepository
import no.nav.familie.ba.sak.kjerne.fagsak.Fagsak
import no.nav.familie.ba.sak.kjerne.fagsak.FagsakService
import no.nav.familie.ba.sak.kjerne.fagsak.FagsakStatus
import no.nav.familie.ba.sak.kjerne.personident.Aktør
import no.nav.familie.ba.sak.kjerne.personident.PersonidentService
import no.nav.familie.ba.sak.kjerne.steg.StegService
import no.nav.familie.ba.sak.kjerne.totrinnskontroll.TotrinnskontrollService
import no.nav.familie.ba.sak.kjerne.vedtak.VedtakService
import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.VilkårService
import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.VilkårsvurderingService
import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkårsvurdering
import no.nav.familie.ba.sak.sikkerhet.SikkerhetContext
import no.nav.familie.ba.sak.task.IverksettMotOppdragTask
import no.nav.familie.kontrakter.ba.infotrygd.Sak
import no.nav.familie.kontrakter.ba.infotrygd.Stønad
import no.nav.familie.kontrakter.felles.personopplysning.FORELDERBARNRELASJONROLLE
import no.nav.fpsak.tidsserie.LocalDateSegment
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.Month.APRIL
import java.time.Month.AUGUST
import java.time.Month.DECEMBER
import java.time.Month.FEBRUARY
import java.time.Month.JANUARY
import java.time.Month.JULY
import java.time.Month.JUNE
import java.time.Month.MARCH
import java.time.Month.MAY
import java.time.Month.NOVEMBER
import java.time.Month.OCTOBER
import java.time.Month.SEPTEMBER
import java.time.YearMonth
private const val NULLDATO = "000000"
@Service
class MigreringService(
private val infotrygdBarnetrygdClient: InfotrygdBarnetrygdClient,
private val fagsakService: FagsakService,
private val behandlingService: BehandlingService,
private val personidentService: PersonidentService,
private val stegService: StegService,
private val vedtakService: VedtakService,
private val taskRepository: TaskRepositoryWrapper,
private val vilkårService: VilkårService,
private val vilkårsvurderingService: VilkårsvurderingService,
private val behandlingRepository: BehandlingRepository,
private val tilkjentYtelseRepository: TilkjentYtelseRepository,
private val totrinnskontrollService: TotrinnskontrollService,
private val env: EnvService?,
private val pdlRestClient: PdlRestClient
) {
private val secureLog = LoggerFactory.getLogger("secureLogger")
private val migrertCounter = Metrics.counter("migrering.ok")
@Transactional
fun migrer(personIdent: String): MigreringResponseDto {
try {
val løpendeSak = hentLøpendeSakFraInfotrygd(personIdent)
kastFeilDersomSakIkkeErOrdinær(løpendeSak)
secureLog.info("Migrering: fant løpende sak for $personIdent sak=${løpendeSak.id} stønad=${løpendeSak.stønad?.id}")
val barnasIdenter = finnBarnMedLøpendeStønad(løpendeSak)
val personAktør = personidentService.hentOgLagreAktør(personIdent)
val barnasAktør = personidentService.hentOgLagreAktørIder(barnasIdenter)
validerAtBarnErIRelasjonMedPersonident(personAktør, barnasAktør)
fagsakService.hentEllerOpprettFagsakForPersonIdent(personIdent)
.also { kastFeilDersomAlleredeMigrert(it) }
val behandling = runCatching {
stegService.håndterNyBehandling(
NyBehandling(
søkersIdent = personIdent,
behandlingType = BehandlingType.MIGRERING_FRA_INFOTRYGD,
behandlingÅrsak = BehandlingÅrsak.MIGRERING,
skalBehandlesAutomatisk = true,
barnasIdenter = barnasIdenter
)
)
}.getOrElse { kastOgTellMigreringsFeil(MigreringsfeilType.KAN_IKKE_OPPRETTE_BEHANDLING, it.message, it) }
vilkårService.hentVilkårsvurdering(behandlingId = behandling.id)?.apply {
forsøkSettPerioderFomTilpassetInfotrygdKjøreplan(this)
vilkårsvurderingService.oppdater(this)
} ?: kastOgTellMigreringsFeil(MigreringsfeilType.MANGLER_VILKÅRSVURDERING)
val behandlingEtterVilkårsvurdering = stegService.håndterVilkårsvurdering(behandling)
val førsteUtbetalingsperiode = finnFørsteUtbetalingsperiode(behandling.id)
sammenlignFørsteUtbetalingsbeløpMedBeløpFraInfotrygd(førsteUtbetalingsperiode.value, løpendeSak.stønad!!)
iverksett(behandlingEtterVilkårsvurdering)
migrertCounter.increment()
val migreringResponseDto = MigreringResponseDto(
fagsakId = behandlingEtterVilkårsvurdering.fagsak.id,
behandlingId = behandlingEtterVilkårsvurdering.id,
infotrygdStønadId = løpendeSak.stønad?.id,
infotrygdSakId = løpendeSak.id,
virkningFom = førsteUtbetalingsperiode.fom.toYearMonth(),
infotrygdTkNr = løpendeSak.tkNr,
infotrygdIverksattFom = løpendeSak.stønad?.iverksattFom,
infotrygdVirkningFom = løpendeSak.stønad?.virkningFom,
infotrygdRegion = løpendeSak.region
)
secureLog.info("Ferdig migrert $personIdent. Response til familie-ba-migrering: $migreringResponseDto")
return migreringResponseDto
} catch (e: Exception) {
if (e is KanIkkeMigrereException) throw e
kastOgTellMigreringsFeil(MigreringsfeilType.UKJENT, e.message, e)
}
}
private fun validerAtBarnErIRelasjonMedPersonident(personAktør: Aktør, barnasAktør: List<Aktør>) {
val barnasIdenter = barnasAktør.map { it.aktivFødselsnummer() }
val listeBarnFraPdl = pdlRestClient.hentForelderBarnRelasjon(personAktør)
.filter { it.relatertPersonsRolle == FORELDERBARNRELASJONROLLE.BARN }
.map { it.relatertPersonsIdent }
if (!listeBarnFraPdl.containsAll(barnasIdenter)) {
secureLog.info(
"Kan ikke migrere person ${personAktør.aktivFødselsnummer()} fordi barn fra PDL IKKE inneholder alle løpende barnetrygdbarn fra Infotrygd.\n" +
"Barn fra PDL: ${listeBarnFraPdl}\n Barn fra Infotrygd: $barnasIdenter"
)
kastOgTellMigreringsFeil(MigreringsfeilType.DIFF_BARN_INFOTRYGD_OG_PDL)
}
}
private fun kastFeilDersomAlleredeMigrert(fagsak: Fagsak) {
val aktivBehandling = behandlingRepository.findByFagsakAndAktiv(fagsak.id)
if (aktivBehandling != null) {
val behandlinger = behandlingRepository.finnBehandlinger(fagsak.id).sortedBy { it.opprettetTidspunkt }
behandlinger.findLast { it.erMigrering() && !it.erHenlagt() }?.apply {
when (fagsak.status) {
FagsakStatus.OPPRETTET -> {
kastOgTellMigreringsFeil(MigreringsfeilType.MIGRERING_ALLEREDE_PÅBEGYNT)
}
FagsakStatus.LØPENDE -> {
kastOgTellMigreringsFeil(MigreringsfeilType.ALLEREDE_MIGRERT)
}
FagsakStatus.AVSLUTTET -> {
val behandling = behandlinger.find { it.opprettetTidspunkt.isAfter(this.opprettetTidspunkt) }
if (behandling == null) {
kastOgTellMigreringsFeil(MigreringsfeilType.FAGSAK_AVSLUTTET_UTEN_MIGRERING)
}
}
}
} ?: kastOgTellMigreringsFeil(MigreringsfeilType.AKTIV_BEHANDLING)
}
}
private fun hentLøpendeSakFraInfotrygd(personIdent: String): Sak {
val (ferdigBehandledeSaker, åpneSaker) = infotrygdBarnetrygdClient.hentSaker(listOf(personIdent)).bruker.partition { it.status == "FB" }
if (åpneSaker.isNotEmpty()) {
kastOgTellMigreringsFeil(MigreringsfeilType.ÅPEN_SAK_INFOTRYGD)
}
val ikkeOpphørteSaker = ferdigBehandledeSaker.sortedByDescending { it.iverksattdato }
.filter {
it.stønad != null && (it.stønad!!.opphørsgrunn == "0" || it.stønad!!.opphørsgrunn.isNullOrEmpty())
}
if (ikkeOpphørteSaker.size > 1) {
kastOgTellMigreringsFeil(MigreringsfeilType.FLERE_LØPENDE_SAKER_INFOTRYGD)
}
if (ikkeOpphørteSaker.isEmpty()) {
kastOgTellMigreringsFeil(MigreringsfeilType.INGEN_LØPENDE_SAK_INFOTRYGD)
}
return ikkeOpphørteSaker.first()
}
private fun kastFeilDersomSakIkkeErOrdinær(sak: Sak) {
if (!(sak.valg == "OR" && sak.undervalg == "OS")) {
kastOgTellMigreringsFeil(MigreringsfeilType.IKKE_STØTTET_SAKSTYPE)
}
when (sak.stønad!!.delytelse.size) {
1 -> return
else -> {
kastOgTellMigreringsFeil(MigreringsfeilType.UGYLDIG_ANTALL_DELYTELSER_I_INFOTRYGD)
}
}
}
private fun finnBarnMedLøpendeStønad(løpendeSak: Sak): List<String> {
val barnasIdenter = løpendeSak.stønad!!.barn
.filter { it.barnetrygdTom == NULLDATO }
.map { it.barnFnr!! }
if (barnasIdenter.isEmpty()) {
kastOgTellMigreringsFeil(
MigreringsfeilType.INGEN_BARN_MED_LØPENDE_STØNAD_I_INFOTRYGD,
"Fant ingen barn med løpende stønad på sak ${løpendeSak.saksblokk}${løpendeSak.saksnr} på bruker i Infotrygd."
)
}
return barnasIdenter
}
private fun forsøkSettPerioderFomTilpassetInfotrygdKjøreplan(vilkårsvurdering: Vilkårsvurdering) {
val inneværendeMåned = YearMonth.now()
vilkårsvurdering.personResultater.forEach { personResultat ->
personResultat.vilkårResultater.forEach {
it.periodeFom = it.periodeFom ?: virkningsdatoFra(infotrygdKjøredato(inneværendeMåned))
}
}
}
private fun virkningsdatoFra(kjøredato: LocalDate): LocalDate {
LocalDate.now().run {
return when {
env?.erPreprod() ?: false -> LocalDate.of(2021, 7, 1)
this.isBefore(kjøredato) -> this.førsteDagIInneværendeMåned()
this.isAfter(kjøredato.plusDays(1)) -> this.førsteDagINesteMåned()
env!!.erDev() -> this.førsteDagINesteMåned()
else -> {
kastOgTellMigreringsFeil(
MigreringsfeilType.IKKE_GYLDIG_KJØREDATO,
"Migrering er midlertidig deaktivert frem til ${kjøredato.plusDays(2)} da det kolliderer med Infotrygds kjøredato"
)
}
}.minusMonths(1)
}
}
private fun infotrygdKjøredato(yearMonth: YearMonth): LocalDate {
yearMonth.run {
if (this.year == 2021 || this.year == 2022) {
return when (this.month) {
JANUARY -> 18
FEBRUARY -> 15
MARCH -> 18
APRIL -> 19
MAY -> 16
JUNE -> 17
JULY -> 18
AUGUST -> 18
SEPTEMBER -> 19
OCTOBER -> 18
NOVEMBER -> 17
DECEMBER -> 5
}.run { yearMonth.atDay(this) }
}
}
kastOgTellMigreringsFeil(
MigreringsfeilType.IKKE_GYLDIG_KJØREDATO,
"Kopien av Infotrygds kjøreplan er utdatert."
)
}
private fun finnFørsteUtbetalingsperiode(behandlingId: Long): LocalDateSegment<Int> {
return tilkjentYtelseRepository.findByBehandlingOptional(behandlingId)?.andelerTilkjentYtelse
?.let { andelerTilkjentYtelse: MutableSet<AndelTilkjentYtelse> ->
if (andelerTilkjentYtelse.isEmpty()) {
kastOgTellMigreringsFeil(MigreringsfeilType.MANGLER_ANDEL_TILKJENT_YTELSE)
}
val førsteUtbetalingsperiode = beregnUtbetalingsperioderUtenKlassifisering(andelerTilkjentYtelse)
.sortedWith(compareBy<LocalDateSegment<Int>>({ it.fom }, { it.value }, { it.tom }))
.first()
førsteUtbetalingsperiode
} ?: kastOgTellMigreringsFeil(MigreringsfeilType.MANGLER_FØRSTE_UTBETALINGSPERIODE)
}
private fun sammenlignFørsteUtbetalingsbeløpMedBeløpFraInfotrygd(
førsteUtbetalingsbeløp: Int?,
infotrygdStønad: Stønad,
) {
val beløpFraInfotrygd =
infotrygdStønad.delytelse.singleOrNull()?.beløp?.toInt()
?: kastOgTellMigreringsFeil(MigreringsfeilType.FLERE_DELYTELSER_I_INFOTRYGD)
if (førsteUtbetalingsbeløp != beløpFraInfotrygd) {
kastOgTellMigreringsFeil(
MigreringsfeilType.BEREGNET_BELØP_FOR_UTBETALING_ULIKT_BELØP_FRA_INFOTRYGD,
MigreringsfeilType.BEREGNET_BELØP_FOR_UTBETALING_ULIKT_BELØP_FRA_INFOTRYGD.beskrivelse +
"($førsteUtbetalingsbeløp ≠ $beløpFraInfotrygd)"
)
}
}
private fun iverksett(behandling: Behandling) {
totrinnskontrollService.opprettAutomatiskTotrinnskontroll(behandling)
val vedtak = vedtakService.hentAktivForBehandling(behandlingId = behandling.id) ?: kastOgTellMigreringsFeil(
MigreringsfeilType.IVERKSETT_BEHANDLING_UTEN_VEDTAK,
"${MigreringsfeilType.IVERKSETT_BEHANDLING_UTEN_VEDTAK.beskrivelse} ${behandling.id}"
)
if (env!!.erPreprod()) {
vedtak.vedtaksdato = LocalDate.of(2021, 7, 1).atStartOfDay()
}
vedtakService.oppdater(vedtak)
behandlingService.oppdaterStatusPåBehandling(behandling.id, BehandlingStatus.IVERKSETTER_VEDTAK)
val task = IverksettMotOppdragTask.opprettTask(behandling, vedtak, SikkerhetContext.hentSaksbehandler())
taskRepository.save(task)
}
}
enum class MigreringsfeilType(val beskrivelse: String) {
AKTIV_BEHANDLING("Det finnes allerede en aktiv behandling på personen som ikke er migrering"),
ALLEREDE_MIGRERT("Personen er allerede migrert"),
BEREGNET_BELØP_FOR_UTBETALING_ULIKT_BELØP_FRA_INFOTRYGD("Beregnet beløp var ulikt beløp fra Infotryg"),
DIFF_BARN_INFOTRYGD_OG_PDL("Kan ikke migrere fordi barn fra PDL ikke samsvarer med løpende barnetrygdbarn fra Infotrygd"),
FAGSAK_AVSLUTTET_UTEN_MIGRERING("Personen er allerede migrert"),
FLERE_DELYTELSER_I_INFOTRYGD("Finnes flere delytelser på sak"),
FLERE_LØPENDE_SAKER_INFOTRYGD("Fant mer enn én aktiv sak på bruker i infotrygd"),
IKKE_GYLDIG_KJØREDATO("Ikke gyldig kjøredato"),
IKKE_STØTTET_SAKSTYPE("Kan kun migrere ordinære saker (OR, OS)"),
INGEN_BARN_MED_LØPENDE_STØNAD_I_INFOTRYGD("Fant ingen barn med løpende stønad på sak"),
INGEN_LØPENDE_SAK_INFOTRYGD("Personen har ikke løpende sak i infotrygd"),
IVERKSETT_BEHANDLING_UTEN_VEDTAK("Fant ikke aktivt vedtak på behandling"),
KAN_IKKE_OPPRETTE_BEHANDLING("Kan ikke opprette behandling"),
MANGLER_ANDEL_TILKJENT_YTELSE("Fant ingen andeler tilkjent ytelse på behandlingen"),
MANGLER_FØRSTE_UTBETALINGSPERIODE("Tilkjent ytelse er null"),
MANGLER_VILKÅRSVURDERING("Fant ikke vilkårsvurdering."),
MIGRERING_ALLEREDE_PÅBEGYNT("Migrering allerede påbegynt"),
UGYLDIG_ANTALL_DELYTELSER_I_INFOTRYGD("Kan kun migrere ordinære saker med nøyaktig ett utbetalingsbeløp"),
UKJENT("Ukjent migreringsfeil"),
ÅPEN_SAK_INFOTRYGD("Bruker har åpen behandling i Infotrygd"),
}
open class KanIkkeMigrereException(
open val feiltype: MigreringsfeilType = MigreringsfeilType.UKJENT,
open val melding: String? = null,
open val throwable: Throwable? = null
) : RuntimeException(melding, throwable)
val migreringsFeilCounter = mutableMapOf<String, Counter>()
fun kastOgTellMigreringsFeil(
feiltype: MigreringsfeilType,
melding: String? = null,
throwable: Throwable? = null
): Nothing =
throw KanIkkeMigrereException(feiltype, melding, throwable).also {
if (migreringsFeilCounter[feiltype.name] == null) {
migreringsFeilCounter[feiltype.name] = Metrics.counter("migrering.feil", "type", feiltype.name)
}
migreringsFeilCounter[feiltype.name]?.increment()
}
| 8 | Kotlin | 0 | 7 | d4a7ef6bc7ba6f0dfdbea1e0d7c7413a97891d55 | 17,636 | familie-ba-sak | MIT License |
componentk/src/main/java/com/mozhimen/componentk/netk/app/download/cons/CAppDownloadState.kt | mozhimen | 353,952,154 | false | {"Kotlin": 2509081, "Java": 320961, "AIDL": 1012} | package com.mozhimen.componentk.netk.app.cons
/**
* @ClassName CAppDownloadState
* @Description TODO
* @Author Mozhimen
* @Date 2023/11/7 11:36
* @Version 1.0
*/
object CNetKAppState {
//任务
const val STATE_TASK_CREATE = 0//STATE_NOT_INSTALLED = 0//未安装 处于未下载,
const val STATE_TASK_WAIT = 1//STATE_PENDING = 3//等待中
const val STATE_TASK_WAIT_CANCEL = 2//STATE_PENDING_CANCELED = 4//取消等待中
const val STATE_TASK_CANCEL = 3//取消任务
const val STATE_TASK_SUCCESS = 8//任务成功
const val STATE_TASK_FAIL = 9//任务失败
@JvmStatic
fun isTasking(state: Int): Boolean =
state in STATE_TASK_WAIT until STATE_TASK_SUCCESS
//////////////////////////////////////////////////////////////
//下载
const val STATE_DOWNLOAD_CREATE = 10//STATE_DOWNLOADED = 5//未下载
const val STATE_DOWNLOADING = 11//STATE_DOWNLOAD_IN_PROGRESS = 6//正在下载
const val STATE_DOWNLOAD_PAUSE = 12//STATE_DOWNLOAD_PAUSED = 7//下载暂停
const val STATE_DOWNLOAD_CANCEL = 13//下载取消
const val STATE_DOWNLOAD_SUCCESS = 18//STATE_DOWNLOAD_COMPLETED = 8//下载完成
const val STATE_DOWNLOAD_FAIL = 19//STATE_DOWNLOAD_FAILED = 10//下载失败
@JvmStatic
fun isDownloading(state: Int): Boolean =
state in STATE_DOWNLOADING until STATE_DOWNLOAD_SUCCESS
//////////////////////////////////////////////////////////////
//校验
const val STATE_VERIFY_CREATE = 20 //待校验
const val STATE_VERIFYING = 21//STATE_CHECKING = 14//校验中
const val STATE_VERIFY_SUCCESS = 28//STATE_CHECKING_SUCCESS = 15//校验成功
const val STATE_VERIFY_FAIL = 29//STATE_CHECKING_FAILURE = 16//校验失败
@JvmStatic
fun isVerifying(state: Int): Boolean =
state in STATE_VERIFYING until STATE_VERIFY_SUCCESS
//////////////////////////////////////////////////////////////
//解压
const val STATE_UNZIP_CREATE = 30//待解压
const val STATE_UNZIPING = 31//STATE_UNPACKING = 11//解压中
const val STATE_UNZIP_SUCCESS = 38//STATE_UNPACKING_SUCCESSFUL = 12//解压成功
const val STATE_UNZIP_FAIL = 39//STATE_UNPACKING_FAILED = 13//解压失败
@JvmStatic
fun isUnziping(state: Int): Boolean =
state in STATE_UNZIPING until STATE_UNZIP_SUCCESS
//////////////////////////////////////////////////////////////
//安装
const val STATE_INSTALL_CREATE = 40//待安装
const val STATE_INSTALLING = 41//STATE_INSTALLING = 1//安装中
const val STATE_INSTALL_SUCCESS = 48//STATE_INSTALLED = 2//已安装
const val STATE_INSTALL_FAIL = 49//STATE_INSTALLED = 2//已安装
@JvmStatic
fun isInstalling(state: Int):Boolean =
state in STATE_INSTALLING until STATE_INSTALL_SUCCESS
//////////////////////////////////////////////////////////////
//卸载
const val STATE_UNINSTALL_CREATE = 50
/* //////////////////////////////////////////////////////////////
//更新
const val STATE_UPDATE_CREATE = 50//需要更新
const val STATE_UPDATEING = 51//STATE_NEED_UPDATE = 17//更新中
const val STATE_UPDATE_SUCCESS = 58
const val STATE_UPDATE_FAIL = 59*/
} | 0 | Kotlin | 6 | 114 | d74563aa5722b01ceb0e7d24c9001050b577db5d | 3,008 | SwiftKit | Apache License 2.0 |
http4k-incubator/src/test/kotlin/org/http4k/lens/HasLensTest.kt | http4k | 86,003,479 | false | {"Kotlin": 2855594, "Java": 41165, "HTML": 14220, "Shell": 3200, "Handlebars": 1455, "Pug": 944, "JavaScript": 777, "Dockerfile": 256, "CSS": 248} | package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.format.Jackson
import org.junit.jupiter.api.Test
class HasLensTest {
data class Foo(val bar: String) {
companion object : HasLens<Foo>(Jackson, kClass())
}
@Test
fun `can use companion to provide an automatic lens to a class`() {
val item = Foo("bar")
val injected = Request(GET, "").with(Foo.lens of item)
assertThat(injected.bodyString(), equalTo("""{"bar":"bar"}"""))
assertThat(Foo.lens(injected), equalTo(item)) // returns Foo("bar"
}
}
| 34 | Kotlin | 249 | 2,615 | 7ad276aa9c48552a115a59178839477f34d486b1 | 728 | http4k | Apache License 2.0 |
app/src/main/java/com/example/objectscanner/ActivityMain.kt | thanhdangg | 859,352,756 | false | {"Kotlin": 13605} | package com.example.objectscanner
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.objectscanner.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ActivityMain : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var database: AppDatabase
private lateinit var photoResultAdapter: PhotoResultAdapter
private var photoResults: List<PhotoResult> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
database = AppDatabase.getDatabase(this)
photoResultAdapter = PhotoResultAdapter()
binding.rvResult.layoutManager = LinearLayoutManager(this)
binding.rvResult.adapter = photoResultAdapter
loadPhotoResults()
binding.ivScan.setOnClickListener {
intent = Intent(this, ActivityCamera::class.java)
startActivity(intent)
}
}
private fun loadPhotoResults() {
CoroutineScope(Dispatchers.IO).launch {
photoResults = database.photoResultDao().getAllPhotos()
withContext(Dispatchers.Main) {
photoResultAdapter.submitList(photoResults)
}
Log.d("ActivityMain", "Photo results: $photoResults")
}
}
} | 0 | Kotlin | 0 | 0 | 4ac0a4449769ebc1cd38425a7f78f0e0178cf4d5 | 2,118 | Object-Scanner | Apache License 2.0 |
benchmark/src/main/kotlin/com/github/jcornaz/collekt/benchmark/AddElementBenchmark.kt | jcornaz | 135,052,931 | false | {"Kotlin": 88352} | package com.github.jcornaz.collekt.benchmark
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Fork
import org.openjdk.jmh.annotations.Measurement
import org.openjdk.jmh.annotations.Warmup
import java.util.concurrent.TimeUnit
@Fork(2)
@Warmup(time = 500, timeUnit = TimeUnit.MILLISECONDS, iterations = 3)
@Measurement(time = 500, timeUnit = TimeUnit.MILLISECONDS, iterations = 10)
open class AddElementBenchmark {
@Benchmark
fun appendElementToArrayList(input: ArrayListInput) {
input.list.add(input.size.toInt())
}
@Benchmark
fun appendElement(input: PersistentInput) = input.list + input.size.toInt()
@Benchmark
fun insertElementToArrayList(input: ArrayListInput) {
input.list.add(input.randomIndex, input.size.toInt())
}
@Benchmark
fun insertElement(input: PersistentInput) = input.list.plus(index = input.randomIndex, element = input.size.toInt())
}
| 14 | Kotlin | 0 | 5 | c947530780c2d60f3800e6095b999cef67bce79b | 947 | collekt | MIT License |
domain/src/main/java/org/oppia/domain/classify/rules/textinput/TextInputEqualsRuleClassifierProvider.kt | IronClad1607 | 248,988,006 | true | {"Kotlin": 1921059} | package org.oppia.domain.classify.rules.textinput
import org.oppia.app.model.InteractionObject
import org.oppia.domain.classify.RuleClassifier
import org.oppia.domain.classify.rules.GenericRuleClassifier
import org.oppia.domain.classify.rules.RuleClassifierProvider
import org.oppia.domain.util.normalizeWhitespace
import javax.inject.Inject
/**
* Provider for a classifier that determines whether two strings are equal per the text input interaction.
*
* https://github.com/oppia/oppia/blob/37285a/extensions/interactions/TextInput/directives/text-input-rules.service.ts#L24
*/
internal class TextInputEqualsRuleClassifierProvider @Inject constructor(
private val classifierFactory: GenericRuleClassifier.Factory
): RuleClassifierProvider, GenericRuleClassifier.SingleInputMatcher<String> {
override fun createRuleClassifier(): RuleClassifier {
return classifierFactory.createSingleInputClassifier(InteractionObject.ObjectTypeCase.NORMALIZED_STRING, "x", this)
}
// TODO(#210): Add tests for this classifier.
override fun matches(answer: String, input: String): Boolean {
return answer.normalizeWhitespace().equals(input.normalizeWhitespace(), /* ignoreCase= */ true)
}
}
| 0 | null | 0 | 1 | d6e58b45cc176170afa91d251e6d88b820a44a16 | 1,201 | oppia-android | Apache License 2.0 |
src/test/kotlin/org/rust/ide/inspections/RustInspectionsTest.kt | daschl | 48,996,992 | true | {"Kotlin": 232040, "Rust": 20833, "Lex": 16810, "Java": 7491, "HTML": 169, "RenderScript": 15} | package org.rust.ide.inspections
import com.intellij.codeInspection.LocalInspectionTool
import org.rust.lang.RustTestCaseBase
class RustInspectionsTest : RustTestCaseBase() {
override val dataPath = "org/rust/ide/inspections/fixtures"
private inline fun <reified T: LocalInspectionTool>doTest() {
myFixture.enableInspections(T::class.java)
myFixture.testHighlighting(true, false, true, fileName)
}
fun testApproxConstant() = doTest<ApproxConstantInspection>()
fun testSelfConvention() = doTest<SelfConventionInspection>()
}
| 0 | Kotlin | 0 | 0 | 47d6eb9143038efa2b6042e81de71e5330df0125 | 566 | intellij-rust | MIT License |
src/main/kotlin/no/nav/brukerdialog/metrikk/Metrikker.kt | navikt | 585,578,757 | false | {"Kotlin": 1442489, "Handlebars": 126943, "Dockerfile": 98} | package no.nav.brukerdialog.metrikk
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.MeterRegistry
import no.nav.brukerdialog.ytelse.Ytelse
import org.springframework.stereotype.Service
@Service
class MetrikkService(meterRegistry: MeterRegistry) {
private val antallMottatteSøknaderPerYtelseCounter = Counter.builder("antall_mottatte_soknader_per_ytelse_counter")
.description("Teller antall mottatte søknader per ytelse")
.tag("ytelse", "ytelse")
.register(meterRegistry)
fun registrerMottattSøknad(ytelse: Ytelse) = antallMottatteSøknaderPerYtelseCounter.increment()
}
| 4 | Kotlin | 0 | 0 | 7c29304e39924a70fdbb7270c9dd4669bb70a150 | 640 | k9-brukerdialog-prosessering | MIT License |
Day 6/Data Classes/Code1.kt | arshsaluja | 285,363,555 | false | null |
//data classes are used to store data/hold data i.e its not for processing
//there should be atleast one parameter in data class
//cannot create a open or abstract class
data class Person(var name:String,var age:Int)
fun main(args:Array<String>)
{
var obj=Person("Arsh",20)
println("The name of the data class is ${obj.name}")
println("The age of the data class is ${obj.age}")
}
| 0 | Kotlin | 0 | 0 | 1772c816471612def453d57ab4a3ca4dbaedfd1b | 399 | Kotlin | Apache License 2.0 |
module-framework/src/main/java/xyz/dean/framework/common/util/ReflectUtil.kt | deanssss | 203,539,447 | false | null | package xyz.dean.framework.common.util
object ReflectUtil {
@JvmStatic
fun getDefaultValue(paramClass: Class<*>): Any? {
return when (paramClass) {
Int::class.java -> 0
Byte::class.java -> 0.toByte()
Short::class.java -> 0.toShort()
Long::class.java -> 0L
Float::class.java -> 0.0f
Double::class.java -> 0.0
Char::class.java -> '\u0000'
Boolean::class.java -> false
else -> null
}
}
} | 1 | null | 1 | 1 | 41020b7639c96b7d8d0a84edf63610153f07e2c3 | 521 | AndroidDemos | Apache License 2.0 |
app/src/main/java/com/jleruga/recipes/domain/RecipesRepository.kt | juanmlf | 786,225,735 | false | {"Kotlin": 41829} | package com.jleruga.recipes.domain
import com.jleruga.recipes.domain.model.RecipeDomain
import retrofit2.Response
interface RecipesRepository{
suspend fun getRecipesByName(name: String): Response<List<RecipeDomain>>
} | 0 | Kotlin | 0 | 0 | 29488769196e38fec74ef96fc3562a73a3baeb5e | 223 | recipes | MIT License |
common/src/main/kotlin/net/spaceeye/someperipherals/SomePeripheralsCommands.kt | SuperSpaceEye | 693,105,203 | false | {"Kotlin": 77255, "Java": 1812} | package net.spaceeye.someperipherals
import com.mojang.brigadier.CommandDispatcher
import com.mojang.brigadier.arguments.ArgumentType
import com.mojang.brigadier.arguments.BoolArgumentType
import com.mojang.brigadier.arguments.FloatArgumentType
import com.mojang.brigadier.arguments.StringArgumentType
import com.mojang.brigadier.builder.LiteralArgumentBuilder
import com.mojang.brigadier.builder.RequiredArgumentBuilder
import com.mojang.brigadier.context.CommandContext
import net.minecraft.commands.CommandSourceStack
object SomePeripheralsCommands {
private fun lt(name: String) = LiteralArgumentBuilder.literal<CommandSourceStack>(name)
private fun <T> arg(name: String, type: ArgumentType<T>) = RequiredArgumentBuilder.argument<CommandSourceStack, T>(name, type)
private fun optionDebugLogging(it: CommandContext<CommandSourceStack>):Int {
val state = BoolArgumentType.getBool(it, "enable")
SomePeripherals.slogger.is_enabled = state
return 0
}
// private fun optionSetDebugOffset(it: CommandContext<CommandSourceStack>): Int {
// val offset: Float = FloatArgumentType.getFloat(it, "offset")
//
// SomePeripheralsConfig.SERVER.COMMON.RAYCASTER_SETTINGS.debug_offset = offset.toDouble()
// return 0
// }
fun registerServerCommands(dispatcher: CommandDispatcher<CommandSourceStack>) {
dispatcher.register(
lt("some_peripherals").then(
lt("debug-logging")
.then(arg("enable", BoolArgumentType.bool()).executes{ optionDebugLogging(it) })
)
// .then(
// lt("debug-offset")
// .then(arg("offset", FloatArgumentType.floatArg()).executes{ optionSetDebugOffset(it) })
// )
)
}
} | 0 | Kotlin | 2 | 0 | c527feabe3bb6a5092c39ec890f198410b511948 | 1,799 | Some-Peripherals | MIT License |
src/main/kotlin/net/b0n541/ai/game/tictactoe/TicTacToeBoard.kt | b0n541 | 272,148,725 | false | {"Kotlin": 139843} | package net.b0n541.ai.game.tictactoe
import org.slf4j.LoggerFactory
class TicTacToeBoard(firstPlayer: TicTacToePlayerSymbol) {
companion object {
private val LOG = LoggerFactory.getLogger(TicTacToeBoard::class.java)
}
var nextTicTacToePlayer: TicTacToePlayerSymbol
private set
init {
nextTicTacToePlayer = firstPlayer
}
private var noughts = 0
private var crosses = 0
private val board = listOf(
mutableListOf<TicTacToePlayerSymbol?>(null, null, null),
mutableListOf<TicTacToePlayerSymbol?>(null, null, null),
mutableListOf<TicTacToePlayerSymbol?>(null, null, null)
)
private val moves: MutableList<TicTacToeMove> = mutableListOf()
private var noughtsWon = false
private var crossesWon = false
private var isDraw = false
fun moves() = moves.toList()
operator fun get(row: Int, column: Int): TicTacToePlayerSymbol? {
return board[row][column]
}
fun getMoves(): List<TicTacToeMove> {
return moves.toList()
}
val possibleMoves: List<TicTacToeMove>
get() = if (isFinished) {
emptyList()
} else {
TicTacToeRules.getPossibleMoves(nextTicTacToePlayer, noughts, crosses)
}
fun addMove(move: TicTacToeMove) {
addMoveInternal(move)
switchPlayer()
}
private fun addMoveInternal(move: TicTacToeMove) {
require(board[move.row][move.column] == null) { "Board position already occupied." }
board[move.row][move.column] = move.ticTacToePlayerSymbol
updateNoughtsAndCrosses(move.ticTacToePlayerSymbol, move.row, move.column)
moves.add(move)
if (move.ticTacToePlayerSymbol == TicTacToePlayerSymbol.O) {
noughtsWon = TicTacToeRules.hasWon(noughts)
} else if (move.ticTacToePlayerSymbol == TicTacToePlayerSymbol.X) {
crossesWon = TicTacToeRules.hasWon(crosses)
}
if (TicTacToeRules.isBoardFull(noughts, crosses)) {
isDraw = TicTacToeRules.isDraw(noughts, crosses)
}
}
private fun switchPlayer() {
if (nextTicTacToePlayer == TicTacToePlayerSymbol.O) {
nextTicTacToePlayer = TicTacToePlayerSymbol.X
} else if (nextTicTacToePlayer == TicTacToePlayerSymbol.X) {
nextTicTacToePlayer = TicTacToePlayerSymbol.O
}
}
private fun updateNoughtsAndCrosses(ticTacToePlayerSymbol: TicTacToePlayerSymbol?, row: Int, column: Int) {
val bitPosition = row * 3 + column
if (ticTacToePlayerSymbol == TicTacToePlayerSymbol.O) {
noughts = noughts or (0x1 shl bitPosition)
} else if (ticTacToePlayerSymbol == TicTacToePlayerSymbol.X) {
crosses = crosses or (0x1 shl bitPosition)
}
}
val isFinished: Boolean
get() = noughtsWon || crossesWon || isDraw
val gameResult: TicTacToeGameResult
get() {
if (noughtsWon) {
return TicTacToeGameResult.O_WON
} else if (crossesWon) {
return TicTacToeGameResult.X_WON
}
return TicTacToeGameResult.DRAW
}
fun format(): String {
val builder = StringBuilder()
builder.append("\n\n")
for (row in 0..2) {
for (column in 0..2) {
builder.append(if (board[row][column] == null) " " else " " + board[row][column] + " ")
if (column != 2) {
builder.append("|")
}
}
builder.append('\n')
if (row != 2) {
builder.append("-----------\n")
}
}
return builder.toString()
}
} | 9 | Kotlin | 0 | 0 | 0b01c74a2e5a635bd43bfe3fa7e34d428645c2d5 | 3,722 | monte-carlo-tree-search | Apache License 2.0 |
app/src/main/java/com/myapp/sunnyweather/ui/weather/WeatherActivity.kt | 2991535823 | 269,508,381 | false | null | package com.myapp.sunnyweather.ui.weather
import android.content.Context
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.myapp.sunnyweather.R
import com.myapp.sunnyweather.logic.model.Weather
import com.myapp.sunnyweather.logic.model.getSky
import com.myapp.sunnyweather.ui.place.WeatherViewModel
import com.myapp.sunnyweather.util.Toast.showToast
import com.myapp.sunnyweather.util.log.LogUtil.d
import com.myapp.sunnyweather.util.log.LogUtil.v
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.life_index.*
import kotlinx.android.synthetic.main.now.*
import java.text.SimpleDateFormat
import java.util.*
class WeatherActivity : AppCompatActivity() {
val viewModel by lazy { ViewModelProviders.of(this).get(WeatherViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather)
val decorView=window.decorView
decorView.systemUiVisibility=View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
window.statusBarColor=Color.TRANSPARENT
if (viewModel.locationLng.isEmpty()){
viewModel.locationLng=intent.getStringExtra("location_lng")?:""
}
if (viewModel.locationLat.isEmpty()){
viewModel.locationLat=intent.getStringExtra("location_lat")?:""
}
if (viewModel.placeName.isEmpty()){
viewModel.placeName=intent.getStringExtra("place_name")?:""
}
viewModel.refreshWeather(viewModel.locationLng,viewModel.locationLat)
navBtn.setOnClickListener {
drawerLayout.openDrawer(GravityCompat.START)
}
drawerLayout.addDrawerListener(object :DrawerLayout.DrawerListener{
override fun onDrawerStateChanged(newState: Int) {
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
}
override fun onDrawerClosed(drawerView: View) {
val manager=getSystemService(Context.INPUT_METHOD_SERVICE)as InputMethodManager
manager.hideSoftInputFromWindow(drawerView.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
}
override fun onDrawerOpened(drawerView: View) {
}
})
viewModel.weatherLiveData.observe(this, Observer { result->
val weather=result.getOrNull()
if (weather!=null){
showWeather(weather)
}else{
"无法获取天气QWQ".showToast()
result.exceptionOrNull()?.printStackTrace()
}
swipeRefresh.isRefreshing=false
})
swipeRefresh.setOnRefreshListener {
refreshWeather()
}
}
fun refreshWeather(){
viewModel.refreshWeather(viewModel.locationLng,viewModel.locationLat)
swipeRefresh.isRefreshing=true
}
override fun onResume() {
super.onResume()
}
private fun showWeather(weather: Weather){
placeName.text=viewModel.placeName
val realtime=weather.realtime
val daily=weather.daily
val currentTempText="${realtime.temperature.toInt()}℃"
currentTemp.text=currentTempText
currentSky.text= getSky(realtime.skycon)!!.info
val currentPM25Text="空气指数 ${realtime.airQuality.aqi.chn.toInt()}"
currentAQI.text=currentPM25Text
now_Layout.setBackgroundResource(getSky(realtime.skycon)!!.bg)
forecastLayout.removeAllViews()
val days=daily.skycon.size
for (i in 1 until days){
val skycon=daily.skycon[i]
val temperature=daily.temperature[i]
val view=LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false)
val dateInfo=view.findViewById<TextView>(R.id.dateInfo)
val skyInfo=view.findViewById<TextView>(R.id.skyInfo)
val skyIcon=view.findViewById<ImageView>(R.id.skyIcon)
val temperatureInfo=view.findViewById<TextView>(R.id.temperatureInfo)
dateInfo.text = skycon.date.subSequence(0,10)
val sky= getSky(skycon.value)!!
skyIcon.setImageResource(sky.icon)
skyInfo.text=sky.info
val tempText="${temperature.min.toInt()}~${temperature.max.toInt()}℃"
temperatureInfo.text=tempText
forecastLayout.addView(view)
}
val lifeIndex=daily.lifeIndex
coldRiskText.text=lifeIndex.coldRisk[0].desc
dressingText.text=lifeIndex.dressing[0].desc
ultravioletText.text=lifeIndex.ultraviolet[0].desc
carWashingText.text=lifeIndex.carWashing[0].desc
weatherLayout.visibility= View.VISIBLE
}
}
| 0 | Kotlin | 0 | 0 | 3f0c01b44a5946df1b90c201c9bb55c08060f0e1 | 5,238 | SunnyWeather | Apache License 2.0 |
kin-core/src/androidTest/kotlin/kin/core/KinAccountIntegrationTest.kt | yosriz | 152,132,864 | true | {"Batchfile": 1, "Shell": 1, "Markdown": 3, "Java Properties": 2, "Proguard": 2, "Java": 62, "Kotlin": 3} | package kin.core
import android.support.test.InstrumentationRegistry
import android.support.test.filters.LargeTest
import kin.core.IntegConsts.TEST_NETWORK_ID
import kin.core.IntegConsts.TEST_NETWORK_URL
import kin.core.exception.AccountNotActivatedException
import kin.core.exception.AccountNotFoundException
import kin.core.exception.InsufficientKinException
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.junit.*
import org.junit.rules.ExpectedException
import org.stellar.sdk.Memo
import org.stellar.sdk.MemoText
import org.stellar.sdk.Server
import java.io.IOException
import java.math.BigDecimal
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.test.fail
@Suppress("FunctionName")
class KinAccountIntegrationTest {
private lateinit var kinClient: KinClient
@Rule
@JvmField
val expectedEx: ExpectedException = ExpectedException.none()
private inner class TestServiceProvider internal constructor() : ServiceProvider(TEST_NETWORK_URL, TEST_NETWORK_ID) {
override fun getIssuerAccountId(): String {
return fakeKinIssuer.accountId
}
}
@Before
@Throws(IOException::class)
fun setup() {
val serviceProvider = TestServiceProvider()
kinClient = KinClient(InstrumentationRegistry.getTargetContext(), serviceProvider)
kinClient.clearAllAccounts()
}
@After
fun teardown() {
if (::kinClient.isInitialized) {
kinClient.clearAllAccounts()
}
}
@Test
@LargeTest
fun getBalanceSync_AccountNotCreated_AccountNotFoundException() {
val kinAccount = kinClient.addAccount()
expectedEx.expect(AccountNotFoundException::class.java)
expectedEx.expectMessage(kinAccount.publicAddress.orEmpty())
kinAccount.balanceSync
}
@Test
@LargeTest
fun getStatusSync_AccountNotCreated_StatusNotCreated() {
val kinAccount = kinClient.addAccount()
val status = kinAccount.statusSync
assertThat(status, equalTo(AccountStatus.NOT_CREATED))
}
@Test
@LargeTest
fun getBalanceSync_AccountNotActivated_AccountNotActivatedException() {
val kinAccount = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccount.publicAddress.orEmpty())
expectedEx.expect(AccountNotActivatedException::class.java)
expectedEx.expectMessage(kinAccount.publicAddress.orEmpty())
kinAccount.balanceSync
}
@Test
@LargeTest
@Throws(Exception::class)
fun getStatusSync_AccountNotActivated_StatusNotActivated() {
val kinAccount = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccount.publicAddress.orEmpty())
val status = kinAccount.statusSync
assertThat(status, equalTo(AccountStatus.NOT_ACTIVATED))
}
@Test
@LargeTest
@Throws(Exception::class)
fun getBalanceSync_FundedAccount_GotBalance() {
val kinAccount = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccount.publicAddress.orEmpty())
kinAccount.activateSync()
assertThat(kinAccount.balanceSync.value(), equalTo(BigDecimal("0.0000000")))
fakeKinIssuer.fundWithKin(kinAccount.publicAddress.orEmpty(), "3.1415926")
assertThat(kinAccount.balanceSync.value(), equalTo(BigDecimal("3.1415926")))
}
@Test
@LargeTest
@Throws(Exception::class)
fun getStatusSync_CreateAndActivateAccount_StatusActivated() {
val kinAccount = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccount.publicAddress.orEmpty())
kinAccount.activateSync()
assertThat(kinAccount.balanceSync.value(), equalTo(BigDecimal("0.0000000")))
val status = kinAccount.statusSync
assertThat(status, equalTo(AccountStatus.ACTIVATED))
}
@Test
@LargeTest
@Throws(Exception::class)
fun activateSync_AccountNotCreated_AccountNotFoundException() {
val kinAccount = kinClient.addAccount()
expectedEx.expect(AccountNotFoundException::class.java)
expectedEx.expectMessage(kinAccount.publicAddress.orEmpty())
kinAccount.activateSync()
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_WithMemo() {
val (kinAccountSender, kinAccountReceiver) = onboardAccounts(senderFundAmount = 100)
val expectedMemo = "fake memo"
val latch = CountDownLatch(1)
val listenerRegistration = kinAccountReceiver.blockchainEvents()
.addPaymentListener { _ -> latch.countDown() }
val transactionId = kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"),
expectedMemo)
assertThat(kinAccountSender.balanceSync.value(), equalTo(BigDecimal("78.8770000")))
assertThat(kinAccountReceiver.balanceSync.value(), equalTo(BigDecimal("21.1230000")))
latch.await(10, TimeUnit.SECONDS)
listenerRegistration.remove()
val server = Server(TEST_NETWORK_URL)
val transaction = server.transactions().transaction(transactionId.id())
val actualMemo = transaction.memo
assertThat<Memo>(actualMemo, `is`<Memo>(instanceOf<Memo>(MemoText::class.java)))
assertThat((actualMemo as MemoText).text, equalTo(expectedMemo))
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_ReceiverAccountNotCreated_AccountNotFoundException() {
val kinAccountSender = kinClient.addAccount()
val kinAccountReceiver = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccountSender.publicAddress.orEmpty())
expectedEx.expect(AccountNotFoundException::class.java)
expectedEx.expectMessage(kinAccountReceiver.publicAddress)
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"))
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_SenderAccountNotCreated_AccountNotFoundException() {
val kinAccountSender = kinClient.addAccount()
val kinAccountReceiver = kinClient.addAccount()
fakeKinIssuer.createAccount(kinAccountReceiver.publicAddress.orEmpty())
kinAccountReceiver.activateSync()
expectedEx.expect(AccountNotFoundException::class.java)
expectedEx.expectMessage(kinAccountSender.publicAddress)
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"))
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_ReceiverAccountNotActivated_AccountNotFoundException() {
val (kinAccountSender, kinAccountReceiver) = onboardAccounts(activateSender = true, activateReceiver = false)
expectedEx.expect(AccountNotActivatedException::class.java)
expectedEx.expectMessage(kinAccountReceiver.publicAddress)
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"))
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_SenderAccountNotActivated_AccountNotFoundException() {
val (kinAccountSender, kinAccountReceiver) = onboardAccounts(activateSender = false, activateReceiver = true)
fakeKinIssuer.createAccount(kinAccountSender.publicAddress.orEmpty())
fakeKinIssuer.createAccount(kinAccountReceiver.publicAddress.orEmpty())
kinAccountReceiver.activateSync()
expectedEx.expect(AccountNotActivatedException::class.java)
expectedEx.expectMessage(kinAccountSender.publicAddress)
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"))
}
@Test
@LargeTest
@Throws(Exception::class)
fun createPaymentListener_ListenToReceiver_PaymentEvent() {
listenToPayments(false)
}
@Test
@LargeTest
@Throws(Exception::class)
fun createPaymentListener_ListenToSender_PaymentEvent() {
listenToPayments(true)
}
@Throws(Exception::class)
private fun listenToPayments(sender: Boolean) {
//create and sets 2 accounts (receiver/sender), fund one account, and then
//send transaction from the funded account to the other, observe this transaction using listeners
val fundingAmount = BigDecimal("100")
val transactionAmount = BigDecimal("21.123")
val (kinAccountSender, kinAccountReceiver) = onboardAccounts(true, true, 0, 0)
//register listeners for testing
val actualPaymentsResults = ArrayList<PaymentInfo>()
val actualBalanceResults = ArrayList<Balance>()
val accountToListen = if (sender) kinAccountSender else kinAccountReceiver
val eventsCount = if (sender) 4 else 2 ///in case of observing the sender we'll get 2 events (1 for funding 1 for the
//transaction) in case of receiver - only 1 event. multiply by 2, as we 2 listeners (balance and payment)
val latch = CountDownLatch(eventsCount)
val paymentListener = accountToListen.blockchainEvents().addPaymentListener { data ->
actualPaymentsResults.add(data)
latch.countDown()
}
val balanceListener = accountToListen.blockchainEvents().addBalanceListener { data ->
actualBalanceResults.add(data)
latch.countDown()
}
//send the transaction we want to observe
fakeKinIssuer.fundWithKin(kinAccountSender.publicAddress.orEmpty(), "100")
val expectedMemo = "memo"
val expectedTransactionId = kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), transactionAmount, expectedMemo)
//verify data notified by listeners
val transactionIndex = if (sender) 1 else 0 //in case of observing the sender we'll get 2 events (1 for funding 1 for the
//transaction) in case of receiver - only 1 event
latch.await(10, TimeUnit.SECONDS)
paymentListener.remove()
balanceListener.remove()
val paymentInfo = actualPaymentsResults[transactionIndex]
assertThat(paymentInfo.amount(), equalTo(transactionAmount))
assertThat(paymentInfo.destinationPublicKey(), equalTo(kinAccountReceiver.publicAddress))
assertThat(paymentInfo.sourcePublicKey(), equalTo(kinAccountSender.publicAddress))
assertThat(paymentInfo.memo(), equalTo(expectedMemo))
assertThat(paymentInfo.hash().id(), equalTo(expectedTransactionId.id()))
val balance = actualBalanceResults[transactionIndex]
assertThat(balance.value(),
equalTo(if (sender) fundingAmount.subtract(transactionAmount) else transactionAmount))
}
@Test
@LargeTest
@Throws(Exception::class)
fun createPaymentListener_RemoveListener_NoEvents() {
val (kinAccountSender, kinAccountReceiver) = onboardAccounts(senderFundAmount = 100)
val latch = CountDownLatch(1)
val blockchainEvents = kinAccountReceiver.blockchainEvents()
val listenerRegistration = blockchainEvents
.addPaymentListener {
fail("should not get eny event!")
}
listenerRegistration.remove()
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"), null)
latch.await(15, TimeUnit.SECONDS)
}
@Test
@LargeTest
@Throws(Exception::class)
fun sendTransaction_NotEnoughKin_TransactionFailedException() {
val (kinAccountSender, kinAccountReceiver) = onboardAccounts()
expectedEx.expect(InsufficientKinException::class.java)
kinAccountSender
.sendTransactionSync(kinAccountReceiver.publicAddress.orEmpty(), BigDecimal("21.123"))
}
private fun onboardAccounts(activateSender: Boolean = true, activateReceiver: Boolean = true, senderFundAmount: Int = 0,
receiverFundAmount: Int = 0): Pair<KinAccount, KinAccount> {
val kinAccountSender = kinClient.addAccount()
val kinAccountReceiver = kinClient.addAccount()
onboardSingleAccount(kinAccountSender, activateSender, senderFundAmount)
onboardSingleAccount(kinAccountReceiver, activateReceiver, receiverFundAmount)
return Pair(kinAccountSender, kinAccountReceiver)
}
private fun onboardSingleAccount(account: KinAccount, shouldActivate: Boolean, fundAmount: Int) {
fakeKinIssuer.createAccount(account.publicAddress.orEmpty())
if (shouldActivate) {
account.activateSync()
}
if (fundAmount > 0) {
fakeKinIssuer.fundWithKin(account.publicAddress.orEmpty(), fundAmount.toString())
}
}
companion object {
private lateinit var fakeKinIssuer: FakeKinIssuer
@BeforeClass
@JvmStatic
@Throws(IOException::class)
fun setupKinIssuer() {
fakeKinIssuer = FakeKinIssuer()
}
}
}
| 0 | Java | 0 | 0 | 855a33b2198ac757e0414a0da10b7fe5e5a5a367 | 13,200 | kin-core-android | MIT License |
api/src/main/kotlin/com/wansensoft/api/system/SysMenuController.kt | gitarthakalita | 705,744,172 | true | {"Markdown": 11, "Kotlin": 63, "Java": 217, "Dockerfile": 1, "SQL": 1} | package com.wansensoft.api.system
import com.wansensoft.dto.menu.AddOrUpdateMenuDTO
import com.wansensoft.service.system.SysMenuService
import com.wansensoft.utils.response.Response
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/menu")
class SysMenuController(private val menuService: SysMenuService) {
@PostMapping("addOrUpdate")
fun addOrUpdate(@RequestBody addOrUpdateDeptDTO: AddOrUpdateMenuDTO?): Response<String> {
return menuService.addOrSaveMenu(addOrUpdateDeptDTO)
}
@PostMapping("delete")
fun deleteMenu(@RequestParam(value = "id", required = true) id: Int?): Response<String> {
return menuService.deleteMenu(id)
}
} | 0 | null | 0 | 0 | 617fcc0b9546b37e63394137fb113d7477f800f7 | 707 | eairp | MIT License |
airbyte-config/config-secrets/src/test/kotlin/secrets/persistence/VaultSecretPersistenceTest.kt | lj-michale | 719,837,726 | true | {"Java Properties": 2, "Gradle Kotlin DSL": 49, "Shell": 54, "Markdown": 70, "Batchfile": 1, "Kotlin": 422, "Dockerfile": 25, "Java": 1531, "INI": 7, "JavaScript": 20, "TypeScript": 428, "HTML": 5, "CSS": 3, "Python": 7, "SQL": 14} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.config.secrets.persistence
import io.airbyte.config.secrets.SecretCoordinate
import org.apache.commons.lang3.RandomUtils
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.testcontainers.vault.VaultContainer
internal class VaultSecretPersistenceTest {
private lateinit var persistence: VaultSecretPersistence
private lateinit var vaultClient: VaultClient
private var baseCoordinate: String = ""
private lateinit var vaultContainer: VaultContainer<*>
@BeforeEach
fun setUp() {
vaultContainer = VaultContainer("hashicorp/vault").withVaultToken("vault-dev-token-id")
vaultContainer.start()
val vaultAddress = "http://${vaultContainer.host}:${vaultContainer.firstMappedPort}"
vaultClient = VaultClient(address = vaultAddress, token = "vault-dev-token-id")
persistence = VaultSecretPersistence(vaultClient = vaultClient, pathPrefix = "secret/testing")
baseCoordinate = "VaultSecretPersistenceIntegrationTest_coordinate_${RandomUtils.nextInt() % 20000}"
}
@AfterEach
fun tearDown() {
vaultContainer.stop()
}
@Test
fun testReadWriteUpdate() {
val coordinate1 =
SecretCoordinate(baseCoordinate, 1)
// try reading non-existent value
val firstRead: String = persistence.read(coordinate1)
Assertions.assertThat(firstRead.isBlank()).isTrue()
// write
val firstPayload = "abc"
persistence.write(coordinate1, firstPayload)
val secondRead: String = persistence.read(coordinate1)
Assertions.assertThat(secondRead.isNotBlank()).isTrue()
org.junit.jupiter.api.Assertions.assertEquals(firstPayload, secondRead)
// update
val secondPayload = "def"
val coordinate2 =
SecretCoordinate(baseCoordinate, 2)
persistence.write(coordinate2, secondPayload)
val thirdRead: String = persistence.read(coordinate2)
Assertions.assertThat(thirdRead.isNotBlank()).isTrue()
org.junit.jupiter.api.Assertions.assertEquals(secondPayload, thirdRead)
}
}
| 0 | Java | 0 | 1 | e554884ac0c8a22e423f470213de3d4cfa384938 | 2,152 | airbyte-platform | MIT License |
form/src/main/java/com/chooongg/form/enum/FormGroupTitleOperationMode.kt | Chooongg | 508,242,844 | false | {"Kotlin": 633711, "JavaScript": 7276, "HTML": 1269, "Java": 1181} | package com.chooongg.form.enum
enum class FormGroupTitleOperationMode {
/**
* 无
*/
NONE,
/**
* 新增
*/
ADD,
/**
* 删除
*/
DELETE
} | 0 | Kotlin | 0 | 3 | 4b54bfb5058d3d2ba7f14929ffceb86fb90d3528 | 183 | Learn | Apache License 2.0 |
src/main/kotlin/me/chill/models/RegularError.kt | woojiahao | 152,174,553 | false | null | package me.chill.models
data class RegularError(
val status: Int,
val message: String
) | 1 | Kotlin | 0 | 1 | 6dbb0aecdbba94153455be32b79f60e156641d21 | 92 | java-spotify-wrapper | MIT License |
api/src/main/kotlin/io/github/legion2/tosca_orchestrator/orchestrator/controller/common/Result.kt | Legion2 | 350,881,803 | false | null | package io.github.legion2.tosca_orchestrator.orchestrator.controller.common
import java.time.Duration
data class Result(val requeue: Boolean, val requeueAfter: Duration = Duration.ZERO)
| 6 | Kotlin | 0 | 3 | fb4ef1a7bf3d79d258da2b6779381a87e0c435e9 | 188 | ritam | Apache License 2.0 |
src/main/java/org/klips/engine/rete/mem/MemAlphaNode.kt | vjache | 70,011,286 | false | null | package org.klips.engine.rete.mem
import org.klips.dsl.Fact
import org.klips.engine.Binding
import org.klips.engine.Modification
import org.klips.engine.Modification.Assert
import org.klips.engine.Modification.Retire
import org.klips.engine.rete.AlphaNode
import org.klips.engine.util.Log
import java.util.*
class MemAlphaNode(log: Log, pattern:Fact) : AlphaNode(log, pattern) {
private val set = HashSet<Binding>()
override fun modifyCache(mdf: Modification<out Binding>, hookModify: (Binding) -> Unit): Boolean {
val binding = mdf.arg
when(mdf) {
is Assert -> {
if(binding in set) return false
hookModify(binding)
set.add(binding)
return true
}
is Retire -> {
if(binding !in set) return false
hookModify(binding)
set.remove(binding)
return true
}
}
}
} | 2 | null | 2 | 18 | 1975cf23feeacb204dc5450c0a3142a0e6fbf309 | 968 | klips | Apache License 2.0 |
app/src/main/java/com/example/careerboast/view/navigation/drawer/AppBar.kt | Ev4esem | 771,869,351 | false | {"Kotlin": 251068} | package com.example.careerboast.view.navigation.drawer
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.rounded.Menu
import androidx.compose.material3.DrawerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.careerboast.R
import com.example.careerboast.ui.theme.Blue
import com.example.careerboast.ui.theme.Red
import com.example.careerboast.ui.theme.White
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppBar(
drawerState: DrawerState? = null,
navigationIcon: (@Composable () -> Unit)? = null,
) {
TopAppBar(
title = {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Text(
text = stringResource(id = R.string.career),
style = TextStyle(
fontSize = 20.sp,
color = Blue,
fontWeight = FontWeight.Bold
)
)
Text(
text = stringResource(id = R.string.boast),
style = TextStyle(
fontSize = 20.sp,
color = Red,
fontWeight = FontWeight.Bold
)
)
}
},
modifier = Modifier.background(
color = White
),
navigationIcon = {
if (drawerState != null && navigationIcon == null) {
DrawerIcon(drawerState = drawerState)
} else {
navigationIcon?.invoke()
}
}
)
}
@Composable
private fun DrawerIcon(drawerState: DrawerState) {
val coroutineScope = rememberCoroutineScope()
IconButton(onClick = {
coroutineScope.launch {
drawerState.open()
}
}) {
Icon(
Icons.Rounded.Menu,
tint = MaterialTheme.colorScheme.onBackground,
contentDescription = ""
)
}
} | 0 | Kotlin | 0 | 0 | d6d327784938d67a5e3cc08697b5c62e1b048470 | 2,900 | CareerBoast | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/common/ui/widget/NumberKeyboardButtonView.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252} | package org.p2p.wallet.common.ui.widget
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.RippleDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import org.p2p.wallet.R
import org.p2p.wallet.databinding.WidgetNumberButtonBinding
class NumberKeyboardButtonView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding = WidgetNumberButtonBinding.inflate(LayoutInflater.from(context), this)
init {
attrs?.let {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberKeyboardButtonView)
val text = typedArray.getString(R.styleable.NumberKeyboardButtonView_keyboard_button_text)
if (text != null) {
binding.keyboardButtonTextView.text = text
}
val image = typedArray.getDrawable(R.styleable.NumberKeyboardButtonView_keyboard_button_image)
if (image != null) {
binding.keyboardButtonImageView.setImageDrawable(image)
binding.keyboardButtonImageView.visibility = View.VISIBLE
}
typedArray.recycle()
}
setBackgroundResource(R.drawable.bg_keyboard_selector)
clipToOutline = true
}
fun setIcon(@DrawableRes drawableResId: Int) {
binding.keyboardButtonImageView.setImageResource(drawableResId)
binding.keyboardButtonImageView.visibility = View.VISIBLE
}
fun setPressedColor(color: Int) {
val drawable = ContextCompat.getDrawable(context, R.drawable.bg_keyboard_pressed) as RippleDrawable
drawable.setColor(ColorStateList.valueOf(color))
background = drawable
}
}
| 8 | Kotlin | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 1,970 | key-app-android | MIT License |
ViewPager22/app/src/main/java/com/app/mytaxi/utils/common/TextUtils.kt | ajaypro | 225,294,116 | false | {"Java": 469931, "Kotlin": 294438} | package com.app.mytaxi.utils.common
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.widget.TextView
import java.lang.reflect.Type
/**
* Created by <NAME> on 28-11-2019, 13:17
*/
fun TextView.textDisplay(text: String)
= SpannableString(text)
.setSpan(StyleSpan(Typeface.BOLD), 0, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
| 1 | null | 1 | 1 | 768b70f957cfd6198ad3594c7c50f741542ca674 | 449 | ViewPager2 | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/ui/compose/components/ContentColored.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.ui.compose.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import io.horizontalsystems.bankwallet.modules.transactionInfo.ColorName
import io.horizontalsystems.bankwallet.ui.compose.ComposeAppTheme
@Composable
fun ContentColored(
colorName: ColorName,
content: @Composable() (RowScope.() -> Unit)
) {
val color = when (colorName) {
ColorName.Remus -> ComposeAppTheme.colors.remus
ColorName.Jacob -> ComposeAppTheme.colors.jacob
ColorName.Leah -> ComposeAppTheme.colors.leah
ColorName.Grey -> ComposeAppTheme.colors.grey
}
Surface(
contentColor = color,
color = Color.Transparent
) {
Row {
content.invoke(this)
}
}
}
| 153 | Kotlin | 190 | 348 | fea4c5d96759a865408f92e661a13e10faa66226 | 949 | unstoppable-wallet-android | MIT License |
app/src/main/java/net/mm2d/codereader/LicenseActivity.kt | ohmae | 365,730,517 | false | {"Kotlin": 66995} | /*
* Copyright (c) 2021 大前良介 (<NAME>)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.codereader
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import net.mm2d.codereader.databinding.ActivityLicenseBinding
import net.mm2d.codereader.util.Launcher
class LicenseActivity : AppCompatActivity() {
private lateinit var binding: ActivityLicenseBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityLicenseBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
view.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.webView.settings.let {
it.setSupportZoom(false)
it.displayZoomControls = false
}
binding.webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?,
): Boolean {
val uri = request?.url ?: return true
return Launcher.openCustomTabs(this@LicenseActivity, uri)
}
}
if (savedInstanceState == null) {
binding.webView.loadUrl("file:///android_asset/license.html")
} else {
binding.webView.restoreState(savedInstanceState)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.webView.saveState(outState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
else -> return super.onOptionsItemSelected(item)
}
return true
}
companion object {
fun start(context: Context) {
context.startActivity(Intent(context, LicenseActivity::class.java))
}
}
}
| 0 | Kotlin | 1 | 7 | 6067fb3f8464363fa686e03693702f142e2ad1f3 | 2,652 | code-reader | MIT License |
buildSrc/src/main/kotlin/Versions.kt | anti-social | 166,968,756 | false | null | import org.gradle.api.JavaVersion
object Versions {
val grgit = "4.1.0"
val kotlin = "1.4.32"
val coroutines = "1.4.3-native-mt"
val ktor = "1.5.2"
val serialization = "1.1.0"
val javaVersion = JavaVersion.VERSION_1_8
val jvmTarget = javaVersion.toString()
val targetJvmVersionAttribute = Integer.parseInt(javaVersion.majorVersion)
}
| 0 | Kotlin | 0 | 0 | 1e4378cc76491d5a82a70222a2464c38955c2410 | 369 | kafka-connect-rest-client | Apache License 2.0 |
src/main/kotlin/sh/illumi/labs/jetbrains_crackboard/listeners/MouseEventListener.kt | illumi-engineering | 853,974,750 | false | {"Kotlin": 17587} | package sh.illumi.labs.jetbrains_crackboard.listeners
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import sh.illumi.labs.jetbrains_crackboard.CrackBoard
class MouseEventListener : EditorMouseListener {
private val crackBoard = service<CrackBoard>()
override fun mousePressed(e: EditorMouseEvent) {
if (crackBoard.isAppActive) crackBoard.getVirtualFile(e.editor.document)?.let { crackBoard.sendHeartbeat(it) }
}
} | 1 | Kotlin | 0 | 1 | aa00ce670377d3f7564372fd350a3f11b9e8cb49 | 556 | jetbrains-crackboard | MIT License |
codelab-00/app/src/main/java/com/example/playbilling/trivialdrive/kotlin/billingrepo/BillingWebservice.kt | YogeshUmeshVaity | 245,976,438 | false | null | package com.example.playbilling.trivialdrive.kotlin.billingrepo
import com.android.billingclient.api.Purchase
class BillingWebservice {
fun getPurchases(): Any {
return Any()//TODO("not implemented")
}
fun updateServer(purchases: Set<Purchase>) {
//TODO("not implemented")
}
fun onComsumeResponse(purchaseToken: String?, responseCode: Int) {
//TODO("not implemented")
}
companion object {
fun create(): BillingWebservice {
//TODO("not implemented")
return BillingWebservice()
}
}
}
| 0 | Kotlin | 0 | 0 | 43256e3531410fb0e12ac5e72f7b329b1554822d | 580 | play-billing-scalable-codelab | Apache License 2.0 |
app/src/main/java/com/kromer/openweather/features/weather/domain/usecases/GetWeatherUseCase.kt | kerolloskromer | 386,706,637 | false | null | package com.kromer.openweather.features.weather.domain.usecases
import com.kromer.openweather.core.usecases.UseCase
import com.kromer.openweather.features.weather.domain.entities.City
import com.kromer.openweather.features.weather.domain.entities.WeatherRequest
import com.kromer.openweather.features.weather.domain.repositories.WeatherRepository
class GetWeatherUseCase(private val weatherRepository: WeatherRepository) :
UseCase<City, WeatherRequest> {
override suspend fun call(params: WeatherRequest): City =
weatherRepository.getWeather(params)
} | 0 | Kotlin | 0 | 1 | 245804157b67faca2bc40286416bb10d31f9fd8f | 569 | open-weather | MIT License |
code-generator/src/test/kotlin/executor/DefaultExecutorTest.kt | waveduke | 709,454,938 | false | {"Kotlin": 54407, "TypeScript": 7810} | package executor
import config.DefaultConfigFileGenerator
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import testing.*
import java.io.File
import kotlin.test.assertEquals
class DefaultExecutorTest {
@TempDir
lateinit var tempDir: File
private val logger = FakeLogger()
private val configFileGenerator = DefaultConfigFileGenerator(logger = logger)
private val executor = DefaultExecutor(
logger = logger,
configFileGenerator = configFileGenerator,
processBuilderProvider = { info ->
ProcessBuilder()
.directory(File(info.workingDirectory))
.command("/bin/bash", "-c", info.command)
}
)
@Test
fun `given invalid input directory returns error result`() {
val testPaths = TestPaths.createTestPaths(tempDir)
testPaths.setupDirectories()
val result = executor.generateCode(
inputDirectory = "",
outputDirectory = testPaths.outputDirectory,
workingDirectory = testPaths.workingDirectory
)
assertTrue(result.isFailure)
assertTrue(logger.error.isNotEmpty())
}
@Tag(TestTags.END_TO_END)
@Test
fun `given valid directories generates files`() {
val inputFileContent = getResourceContent("Input.ts")
val testPaths = TestPaths.createTestPaths(tempDir)
testPaths.setupDirectories(inputFileContent = inputFileContent)
val expectedOutputFileContent = getResourceContent("Output.kt")
val result = executor.generateCode(
inputDirectory = testPaths.inputDirectory,
outputDirectory = testPaths.outputDirectory,
workingDirectory = testPaths.workingDirectory
)
result.fold(
onSuccess = {},
onFailure = {
println(it)
}
)
val actualOutputFileContent = getFileContent(filePath = testPaths.outputDirectory)
assertEquals(expectedOutputFileContent, actualOutputFileContent)
assertEquals(Result.success(Unit), result)
assertTrue(logger.info.isNotEmpty())
assertTrue(logger.error.isEmpty())
}
} | 0 | Kotlin | 0 | 0 | e82a163718b01ed78ad937912d3c7a2458e7b08f | 2,291 | ttk | Apache License 2.0 |
core/domain/src/main/java/com/tomaszrykala/recsandfx/core/domain/native/NativeInterface.kt | tomaszrykala | 672,373,610 | false | null | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tomaszrykala.recsandfx.core.domain.native
import android.util.Log
import com.tomaszrykala.recsandfx.core.datatype.EffectDescription
import com.tomaszrykala.recsandfx.core.datatype.NativeEffect
internal object NativeInterface {
// Used to load the 'native-lib' library on application startup.
val effectDescriptionMap: Map<String, EffectDescription>
init {
System.loadLibrary("native-lib")
effectDescriptionMap = getEffects().associateBy { it.name }
Log.d(TAG, effectDescriptionMap.toString())
}
// Functions/Members called by UI code
// Adds effect at end of effect list
fun addEffect(effect: NativeEffect) {
val nativeId = convertEffectToId(effect)
addDefaultEffectNative(nativeId)
}
// Enables effect at index
fun enableEffectAt(turnOn: Boolean, index: Int) {
enableEffectNative(index, turnOn)
}
// Removes effect at index
fun removeEffectAt(index: Int) {
removeEffectNative(index)
}
// Signals params were updated at index
fun updateParamsAt(effect: NativeEffect, index: Int) {
val nativeId = convertEffectToId(effect)
Log.d(TAG, "updateParamsAt $nativeId.")
modifyEffectNative(nativeId, index, effect.paramValues)
}
fun enable(enable: Boolean) {
Log.d(TAG, "Enabling effects: $enable")
enablePassthroughNative(enable)
}
external fun startAudioRecorder()
external fun stopAudioRecorder()
external fun writeFile(pathFile: String)
// State of audio engine
external fun createAudioEngine()
external fun destroyAudioEngine()
// These functions populate effectDescriptionMap
private external fun getEffects(): Array<EffectDescription>
// These functions mutate the function list
// Adds effect at index
private external fun addDefaultEffectNative(id: Int)
private external fun removeEffectNative(index: Int)
private external fun rotateEffectNative(from: Int, to: Int)
private external fun modifyEffectNative(id: Int, index: Int, params: FloatArray)
private external fun enableEffectNative(index: Int, enable: Boolean)
private external fun enablePassthroughNative(enable: Boolean)
// These are utility functions
private fun convertEffectToId(effect: NativeEffect): Int =
effectDescriptionMap[effect.name]?.id ?: -1
}
internal const val TAG = "NativeInterface"
| 2 | Kotlin | 0 | 0 | 45bb9580fcd020006b6f1356bb6c0180d8fc164d | 3,039 | RecsAndFx | Apache License 2.0 |
MVVM-LiveData-Android-app-master/app/src/main/java/com/gojeck/base/Resource.kt | wetwaresystems | 301,784,329 | false | null | package com.gojeck.base
import kotlinx.coroutines.Job
import java.io.IOException
sealed class Resource<out T> {
data class Loading(val job: Job? = null) : Resource<Nothing>()
data class Success<T>(val data: T) : Resource<T>()
data class NetworkError(val retry: () -> Unit = {}) : Resource<Nothing>()
fun get(): T? = when (this) {
is Success -> data
else -> null
}
fun onLoading(onResult: (job: Job?) -> Unit): Resource<T> {
if (this is Loading) {
onResult(job)
}
return this
}
inline fun onSuccess(onResult: (T) -> Unit) {
if (this is Success) {
onResult(data)
}
}
inline fun onNetworkError(onResult: (retry: () -> Unit) -> Unit) {
if (this is NetworkError) {
onResult(retry)
}
}
fun isSuccess() = this is Success
fun isLoading() = this is Loading
fun isResult() = !isLoading()
fun isNetworkError() = this is NetworkError
}
class ResourceException(val resource: Resource<Nothing>) : IOException()
| 0 | Kotlin | 0 | 0 | d3408c454672927c2412892ca5f377581bc50aa8 | 1,074 | MVVM-LiveData-Android-app | Apache License 2.0 |
java_and_kotlin/kotlin/CountryChecker.kt | DongGeon0908 | 579,532,103 | false | {"Kotlin": 6009} | import mu.KotlinLogging
import org.springframework.http.HttpHeaders
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = ["/api/country-checker/v1"])
class CountryCheckRestController(
private val countryCheckService: CountryCheckService
) {
private val logger = KotlinLogging.logger {}
@GetMapping
fun checkCountry(
@RequestHeader headers: HttpHeaders
): ResponseEntity<CountryCheckResponse> {
val country = countryCheckService.checkLanguage(headers)
return ResponseEntity.ok(CountryCheckResponse.from(country))
}
}
@Service
class CountryCheckService {
companion object {
val languageHeadersKey = listOf("accept-language", "Accept-Language")
}
fun checkLanguage(headers: HttpHeaders): CountryCode {
val key = languageHeadersKey.firstOrNull { key -> headers[key] != null }
?: return CountryCode.KOREA
return headers[key]!!.mapNotNull { value -> CountryCode.of(value) }
.ifEmpty { return CountryCode.KOREA }.first()
}
}
enum class CountryCode(val korName: String) {
KOREA("한국") {
override fun check(value: String): Boolean {
listOf("ko", "kr").firstOrNull {
value.contains(it)
} ?: return false
return true
}
},
JAPAN("일본") {
override fun check(value: String): Boolean {
listOf("ja").firstOrNull {
value.contains(it)
} ?: return false
return true
}
};
abstract fun check(value: String): Boolean
companion object {
fun of(value: String): CountryCode? {
return values().firstOrNull { code -> code.check(value) }
}
}
}
data class CountryCheckResponse(
val countryCode: CountryCode,
val korName: String
) {
companion object {
fun from(countryCode: CountryCode): CountryCheckResponse {
return CountryCheckResponse(
countryCode = countryCode,
korName = countryCode.korName
)
}
}
}
| 56 | Kotlin | 0 | 3 | 8cebfae8e8e26fe9ab7eb6522c6c24214c9191c2 | 2,399 | goofy-warehouse | Apache License 2.0 |
Flutter/flutter_belajar/android/app/src/main/kotlin/com/edward/ag/flutter_belajar/MainActivity.kt | sponsbub12 | 345,511,277 | false | {"Dart": 84586, "Swift": 10100, "Kotlin": 3229, "Objective-C": 950} | package com.edward.ag.flutter_belajar
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 82a308aaa7e0488ed76659cb65f8c58bd97c89cd | 134 | learn_flutter | Apache License 2.0 |
app/src/main/java/com/hypertrack/android/ui/screens/visits_management/tabs/summary/SummaryFragment.kt | hypertrack | 241,723,736 | false | null | package com.hypertrack.android.ui.screens.visits_management.tabs.summary
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.hypertrack.android.di.Injector
import com.hypertrack.android.interactors.app.RegisterScreenAction
import com.hypertrack.android.ui.base.ProgressDialogFragment
import com.hypertrack.android.ui.common.util.observeWithErrorHandling
import com.hypertrack.android.ui.common.util.setLinearLayoutManager
import com.hypertrack.logistics.android.github.R
import kotlinx.android.synthetic.main.fragment_tab_summary.*
class SummaryFragment : ProgressDialogFragment(R.layout.fragment_tab_summary) {
private val adapter = SummaryItemsAdapter()
private val vm: SummaryViewModel by viewModels {
Injector.provideUserScopeViewModelFactory()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rvSummary.setLinearLayoutManager(requireContext())
rvSummary.adapter = adapter
vm.viewState.observeWithErrorHandling(viewLifecycleOwner, vm::onError) {
adapter.updateItems(it.summary)
srlSummary.isRefreshing = it.isLoading
}
srlSummary.setOnRefreshListener {
vm.refreshSummary()
}
}
companion object {
fun newInstance() = SummaryFragment()
}
}
| 1 | Kotlin | 17 | 31 | c5dd23621aed11ff188cf98ac037b67f435e9f5b | 1,405 | visits-android | MIT License |
commons/src/main/java/com/vitorpamplona/amethyst/commons/robohash/parts/Body9Huge.kt | retrnull | 827,005,629 | false | null | /**
* Copyright (c) 2024 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.robohash.parts
import androidx.compose.foundation.Image
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.PathData
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.tooling.preview.Preview
import com.vitorpamplona.amethyst.commons.robohash.Black
import com.vitorpamplona.amethyst.commons.robohash.Gray
import com.vitorpamplona.amethyst.commons.robohash.roboBuilder
@Preview
@Composable
fun Body9HugePreview() {
Image(
painter =
rememberVectorPainter(
roboBuilder {
body9Huge(SolidColor(Color.Yellow), this)
},
),
contentDescription = "",
)
}
fun body9Huge(
fgColor: SolidColor,
builder: Builder,
) {
// body
builder.addPath(pathData4, fill = fgColor)
builder.addPath(pathData1, fill = fgColor, stroke = Black, strokeLineWidth = 1.0f)
// base neck
builder.addPath(pathData7, fill = Black, stroke = Black, fillAlpha = 0.6f, strokeLineWidth = 1.0f)
// neck
builder.addPath(pathData11, fill = Gray, stroke = Black, strokeLineWidth = 1.0f)
builder.addPath(pathData10, fill = SolidColor(Color.White), fillAlpha = 0.7f)
// neck base shade
builder.addPath(pathData17, fill = Black, fillAlpha = 0.4f)
// left body shade
builder.addPath(pathData18, fill = SolidColor(Color.White), fillAlpha = 0.7f)
// left arm shades
builder.addPath(pathData20, fill = Black, fillAlpha = 0.4f)
builder.addPath(pathData23, fill = Black, fillAlpha = 0.4f)
builder.addPath(pathData22, fill = Black, fillAlpha = 0.2f, stroke = Black, strokeAlpha = 0.1f, strokeLineWidth = 1f)
// right arm shade
builder.addPath(pathData24, fill = Black, fillAlpha = 0.4f, stroke = Black, strokeLineWidth = 1.0f)
// right body shade
builder.addPath(pathData26, fill = Black, fillAlpha = 0.4f)
// Neck shade
builder.addPath(pathData12, fill = SolidColor(Color(0xFF58595b)))
// Shoulder lines
builder.addPath(pathData21, stroke = Black, strokeLineWidth = 0.75f)
// Joints and body divisions
builder.addPath(pathData13, stroke = Black, strokeLineWidth = 1.0f)
}
private val pathData1 =
PathData {
moveTo(222.5f, 301.5f)
reflectiveCurveToRelative(-10.0f, -35.0f, 11.0f, -53.0f)
reflectiveCurveToRelative(58.0f, -15.0f, 70.0f, 2.0f)
reflectiveCurveToRelative(2.0f, 51.0f, 2.0f, 51.0f)
close()
moveTo(83.5f, 254.5f)
reflectiveCurveToRelative(-6.0f, 28.0f, 67.0f, 26.0f)
reflectiveCurveToRelative(77.0f, -30.0f, 76.0f, -36.0f)
reflectiveCurveToRelative(-12.3f, -10.12f, -26.0f, -13.0f)
curveToRelative(0.0f, 5.0f, 1.0f, 22.0f, 1.0f, 22.0f)
reflectiveCurveToRelative(-8.0f, 13.0f, -46.0f, 17.0f)
curveToRelative(-29.0f, 1.0f, -45.0f, -9.0f, -45.0f, -9.0f)
reflectiveCurveToRelative(-1.5f, -16.0f, -2.5f, -23.13f)
curveTo(96.5f, 241.75f, 85.5f, 247.5f, 83.5f, 254.5f)
close()
moveTo(110.5f, 261.5f)
reflectiveCurveToRelative(20.0f, 11.0f, 44.0f, 9.0f)
reflectiveCurveToRelative(36.0f, -7.0f, 47.0f, -17.0f)
lineToRelative(-1.0f, -24.0f)
arcToRelative(10.53f, 10.53f, 0.0f, false, true, -0.31f, 4.41f)
curveToRelative(-0.69f, 1.59f, -4.63f, 16.78f, -42.16f, 19.68f)
reflectiveCurveToRelative(-47.0f, -4.1f, -50.0f, -16.1f)
close()
moveTo(108.0f, 237.0f)
reflectiveCurveToRelative(-1.0f, 20.0f, 45.0f, 17.0f)
reflectiveCurveToRelative(48.5f, -20.5f, 47.5f, -24.5f)
curveToRelative(-0.91f, -3.63f, -13.68f, -10.56f, -39.0f, -9.56f)
curveToRelative(0.0f, 0.56f, 0.26f, 3.3f, 0.26f, 3.3f)
curveToRelative(1.74f, 9.26f, 0.74f, 15.26f, -9.26f, 16.26f)
curveToRelative(-3.41f, 0.33f, -10.0f, -5.0f, -10.0f, -5.0f)
reflectiveCurveToRelative(-1.0f, -8.0f, -1.0f, -13.0f)
curveTo(120.38f, 224.59f, 108.41f, 230.0f, 108.0f, 237.0f)
close()
moveTo(87.5f, 247.5f)
reflectiveCurveToRelative(-19.0f, -10.0f, -37.0f, -5.0f)
reflectiveCurveToRelative(-29.0f, 20.0f, -32.0f, 37.0f)
curveToRelative(-1.0f, 11.0f, 1.0f, 16.0f, 3.0f, 20.0f)
horizontalLineToRelative(64.0f)
reflectiveCurveToRelative(2.0f, -5.0f, 0.0f, -16.0f)
reflectiveCurveToRelative(-3.0f, -23.0f, -2.0f, -29.0f)
reflectiveCurveTo(87.5f, 247.5f, 87.5f, 247.5f)
close()
}
private val pathData4 =
PathData {
moveTo(83.5f, 250.0f)
horizontalLineToRelative(143.5f)
verticalLineToRelative(58.5f)
horizontalLineToRelative(-143.5f)
close()
}
private val pathData7 =
PathData {
moveTo(108.0f, 237.0f)
reflectiveCurveToRelative(-1.0f, 20.0f, 45.0f, 17.0f)
reflectiveCurveToRelative(48.5f, -20.5f, 47.5f, -24.5f)
curveToRelative(-0.91f, -3.63f, -13.68f, -10.56f, -39.0f, -9.56f)
curveToRelative(0.0f, 0.56f, 0.26f, 3.3f, 0.26f, 3.3f)
curveToRelative(1.74f, 9.26f, 0.74f, 15.26f, -9.26f, 16.26f)
curveToRelative(-3.41f, 0.33f, -10.0f, -5.0f, -10.0f, -5.0f)
reflectiveCurveToRelative(-1.0f, -8.0f, -1.0f, -13.0f)
curveTo(120.38f, 224.59f, 108.41f, 230.0f, 108.0f, 237.0f)
close()
}
private val pathData9 =
PathData {
moveTo(193.37f, 260.15f)
curveToRelative(-6.66f, 3.83f, -18.28f, 8.29f, -37.87f, 10.35f)
curveToRelative(-29.0f, 1.0f, -45.0f, -9.0f, -45.0f, -9.0f)
reflectiveCurveToRelative(-1.5f, -16.0f, -2.5f, -23.13f)
curveToRelative(-11.5f, 3.38f, -22.5f, 9.13f, -24.5f, 16.13f)
curveToRelative(0.0f, 0.0f, -6.0f, 28.0f, 67.0f, 26.0f)
curveToRelative(29.58f, -0.81f, 47.84f, -5.89f, 59.0f, -12.0f)
close()
}
private val pathData10 =
PathData {
moveTo(83.5f, 254.5f)
reflectiveCurveToRelative(-6.0f, 28.0f, 67.0f, 26.0f)
curveToRelative(29.58f, -0.81f, 47.84f, -5.89f, 59.0f, -12.0f)
curveToRelative(-5.5f, -2.5f, -10.5f, -5.5f, -16.13f, -8.35f)
curveToRelative(-6.66f, 3.83f, -18.28f, 8.29f, -37.87f, 10.35f)
curveToRelative(-29.0f, 1.0f, -45.0f, -9.0f, -45.0f, -9.0f)
reflectiveCurveToRelative(-1.5f, -16.0f, -2.5f, -23.13f)
curveTo(96.5f, 241.75f, 85.5f, 247.5f, 83.5f, 254.5f)
close()
}
private val pathData11 =
PathData {
moveTo(141.5f, 190.5f)
verticalLineToRelative(29.0f)
arcToRelative(142.25f, 142.25f, 0.0f, false, false, 1.0f, 15.0f)
arcToRelative(9.78f, 9.78f, 0.0f, false, false, 10.0f, 5.0f)
curveToRelative(7.0f, -1.0f, 11.0f, -4.0f, 10.0f, -11.0f)
curveToRelative(-0.36f, -2.54f, -0.73f, -5.0f, -1.0f, -7.56f)
arcToRelative(138.9f, 138.9f, 0.0f, false, true, -1.0f, -17.44f)
verticalLineToRelative(-14.0f)
arcTo(69.37f, 69.37f, 0.0f, false, false, 141.5f, 190.5f)
close()
}
private val pathData12 =
PathData {
moveTo(152.5f, 190.5f)
reflectiveCurveToRelative(0.0f, 7.0f, 2.0f, 12.0f)
arcToRelative(55.9f, 55.9f, 0.0f, false, true, 3.13f, 17.34f)
curveToRelative(-0.12f, 3.66f, 0.88f, 15.66f, -3.12f, 17.66f)
reflectiveCurveToRelative(-2.0f, 2.0f, -2.0f, 2.0f)
reflectiveCurveToRelative(7.0f, -1.57f, 8.48f, -3.79f)
reflectiveCurveToRelative(1.94f, -3.24f, 1.23f, -9.23f)
arcToRelative(177.33f, 177.33f, 0.0f, false, true, -1.71f, -24.86f)
verticalLineTo(189.5f)
arcToRelative(37.46f, 37.46f, 0.0f, false, false, -6.17f, -0.25f)
lineToRelative(-1.83f, 0.25f)
close()
}
private val pathData13 =
PathData {
moveTo(141.5f, 190.5f)
verticalLineToRelative(29.0f)
arcToRelative(142.25f, 142.25f, 0.0f, false, false, 1.0f, 15.0f)
arcToRelative(9.78f, 9.78f, 0.0f, false, false, 10.0f, 5.0f)
curveToRelative(7.0f, -1.0f, 11.0f, -4.0f, 10.0f, -11.0f)
curveToRelative(-0.36f, -2.54f, -0.73f, -5.0f, -1.0f, -7.56f)
arcToRelative(138.9f, 138.9f, 0.0f, false, true, -1.0f, -17.44f)
verticalLineToRelative(-14.0f)
arcTo(69.37f, 69.37f, 0.0f, false, false, 141.5f, 190.5f)
close()
moveTo(161.25f, 222.25f)
reflectiveCurveToRelative(-2.67f, 3.25f, -9.51f, 3.25f)
reflectiveCurveToRelative(-10.13f, -2.0f, -10.13f, -2.0f)
moveTo(160.0f, 208.5f)
reflectiveCurveToRelative(-3.0f, 3.0f, -9.06f, 3.0f)
reflectiveCurveTo(142.0f, 210.0f, 142.0f, 210.0f)
moveTo(160.0f, 197.5f)
reflectiveCurveToRelative(-2.0f, 2.0f, -8.06f, 2.0f)
arcTo(86.48f, 86.48f, 0.0f, false, true, 142.0f, 199.0f)
// body
moveTo(209.51f, 268.45f)
reflectiveCurveToRelative(18.0f, -9.0f, 17.0f, -24.0f)
lineToRelative(0.74f, 11.0f)
arcToRelative(39.65f, 39.65f, 0.0f, false, false, -7.12f, 24.19f)
curveToRelative(0.38f, 14.81f, 2.38f, 21.81f, 2.38f, 21.81f)
horizontalLineToRelative(-12.0f)
moveTo(83.5f, 254.5f)
reflectiveCurveToRelative(-6.0f, 28.0f, 67.0f, 26.0f)
reflectiveCurveToRelative(77.0f, -30.0f, 76.0f, -36.0f)
reflectiveCurveToRelative(-12.3f, -10.12f, -26.0f, -13.0f)
curveToRelative(0.0f, 5.0f, 1.0f, 22.0f, 1.0f, 22.0f)
reflectiveCurveToRelative(-8.0f, 13.0f, -46.0f, 17.0f)
curveToRelative(-29.0f, 1.0f, -45.0f, -9.0f, -45.0f, -9.0f)
reflectiveCurveToRelative(-1.5f, -16.0f, -2.5f, -23.13f)
curveTo(96.5f, 241.75f, 85.5f, 247.5f, 83.5f, 254.5f)
close()
}
private val pathData17 =
PathData {
moveTo(188.0f, 246.51f)
lineTo(189.52f, 262.0f)
reflectiveCurveToRelative(6.63f, -4.0f, 9.06f, -6.0f)
lineToRelative(2.42f, -2.0f)
reflectiveCurveToRelative(0.72f, 0.24f, 0.36f, -3.88f)
reflectiveCurveToRelative(-0.79f, -17.93f, -0.79f, -17.93f)
reflectiveCurveTo(200.0f, 240.0f, 188.0f, 246.51f)
close()
}
private val pathData18 =
PathData {
moveTo(84.0f, 273.63f)
reflectiveCurveTo(97.0f, 277.0f, 97.0f, 285.0f)
reflectiveCurveToRelative(-1.0f, 9.0f, 0.0f, 14.0f)
reflectiveCurveToRelative(0.0f, 4.0f, 0.0f, 4.0f)
horizontalLineTo(84.0f)
reflectiveCurveToRelative(3.32f, -3.0f, 2.41f, -11.26f)
reflectiveCurveTo(85.0f, 279.5f, 85.0f, 279.5f)
close()
}
private val pathData19 =
PathData {
moveTo(87.5f, 247.5f)
reflectiveCurveToRelative(-19.0f, -10.0f, -37.0f, -5.0f)
reflectiveCurveToRelative(-29.0f, 20.0f, -32.0f, 37.0f)
curveToRelative(-1.0f, 11.0f, 1.0f, 16.0f, 3.0f, 20.0f)
horizontalLineToRelative(64.0f)
reflectiveCurveToRelative(2.0f, -5.0f, 0.0f, -16.0f)
reflectiveCurveToRelative(-3.0f, -23.0f, -2.0f, -29.0f)
reflectiveCurveTo(87.5f, 247.5f, 87.5f, 247.5f)
close()
}
private val pathData20 =
PathData {
moveTo(87.5f, 247.5f)
arcToRelative(63.65f, 63.65f, 0.0f, false, false, -25.06f, -6.39f)
curveToRelative(7.06f, 2.39f, 3.06f, 8.39f, -8.94f, 13.39f)
curveToRelative(-11.0f, 6.0f, -23.0f, 10.0f, -27.5f, 32.5f)
curveToRelative(-0.67f, 7.37f, 0.84f, 13.18f, 1.5f, 14.5f)
lineToRelative(58.0f, -2.0f)
reflectiveCurveToRelative(2.0f, -5.0f, 0.0f, -16.0f)
reflectiveCurveToRelative(-3.0f, -23.0f, -2.0f, -29.0f)
reflectiveCurveTo(87.5f, 247.5f, 87.5f, 247.5f)
close()
}
private val pathData21 =
PathData {
moveTo(33.5f, 299.5f)
reflectiveCurveToRelative(-7.0f, -19.0f, -3.0f, -35.0f)
arcToRelative(28.63f, 28.63f, 0.0f, false, true, 17.0f, -21.06f)
moveTo(292.5f, 241.5f)
reflectiveCurveToRelative(-12.0f, -1.0f, -13.0f, 15.0f)
curveToRelative(-1.0f, 14.0f, 4.0f, 41.0f, 7.0f, 45.0f)
}
private val pathData22 =
PathData {
moveTo(62.44f, 241.12f)
arcToRelative(3.46f, 3.46f, 0.0f, false, true, 3.06f, 3.38f)
curveToRelative(0.0f, 3.0f, 0.0f, 4.0f, -10.0f, 9.0f)
reflectiveCurveToRelative(-21.45f, 10.0f, -26.22f, 21.0f)
reflectiveCurveToRelative(-2.62f, 25.0f, -2.62f, 25.0f)
horizontalLineTo(21.5f)
lineToRelative(-3.0f, -20.0f)
reflectiveCurveTo(27.38f, 241.73f, 62.44f, 241.12f)
close()
}
private val pathData23 =
PathData {
moveTo(84.26f, 275.62f)
arcTo(31.64f, 31.64f, 0.0f, false, true, 80.5f, 290.5f)
arcToRelative(19.71f, 19.71f, 0.0f, false, true, -11.14f, 8.83f)
lineToRelative(16.14f, 0.17f)
reflectiveCurveToRelative(1.42f, -2.62f, 0.71f, -10.81f)
arcTo(90.57f, 90.57f, 0.0f, false, false, 84.26f, 275.62f)
close()
}
private val pathData24 =
PathData {
moveTo(222.5f, 301.5f)
reflectiveCurveToRelative(-10.0f, -35.0f, 11.0f, -53.0f)
reflectiveCurveToRelative(58.0f, -15.0f, 70.0f, 2.0f)
reflectiveCurveToRelative(2.0f, 51.0f, 2.0f, 51.0f)
close()
}
private val pathData26 =
PathData {
moveTo(226.5f, 244.5f)
lineToRelative(0.74f, 11.0f)
arcToRelative(39.65f, 39.65f, 0.0f, false, false, -7.12f, 24.19f)
curveToRelative(0.38f, 14.81f, 2.38f, 21.81f, 2.38f, 21.81f)
horizontalLineToRelative(-12.0f)
reflectiveCurveToRelative(1.0f, -9.0f, 0.5f, -14.5f)
reflectiveCurveToRelative(-1.49f, -18.55f, -1.49f, -18.55f)
reflectiveCurveTo(227.5f, 259.5f, 226.5f, 244.5f)
close()
}
| 5 | null | 3 | 34 | d33428614279300c503770c10a4305ca2a4d5ab6 | 14,917 | garnet | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/service/NostrSearchEventOrUserDataSource.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.service
import com.vitorpamplona.amethyst.model.toHexKey
import com.vitorpamplona.amethyst.service.model.*
import com.vitorpamplona.amethyst.service.nip19.Nip19
import com.vitorpamplona.amethyst.service.relays.COMMON_FEED_TYPES
import com.vitorpamplona.amethyst.service.relays.FeedType
import com.vitorpamplona.amethyst.service.relays.JsonFilter
import com.vitorpamplona.amethyst.service.relays.TypedFilter
import fr.acinq.secp256k1.Hex
object NostrSearchEventOrUserDataSource : NostrDataSource("SingleEventFeed") {
private var searchString: String? = null
private fun createAnythingWithIDFilter(): List<TypedFilter>? {
val mySearchString = searchString
if (mySearchString.isNullOrBlank()) {
return null
}
val hexToWatch = try {
Nip19.uriToRoute(mySearchString)?.hex ?: Hex.decode(mySearchString).toHexKey()
} catch (e: Exception) {
null
}
// downloads all the reactions to a given event.
return listOfNotNull(
hexToWatch?.let {
TypedFilter(
types = COMMON_FEED_TYPES,
filter = JsonFilter(
ids = listOfNotNull(hexToWatch)
)
)
},
hexToWatch?.let {
TypedFilter(
types = COMMON_FEED_TYPES,
filter = JsonFilter(
kinds = listOf(MetadataEvent.kind),
authors = listOfNotNull(hexToWatch)
)
)
},
TypedFilter(
types = setOf(FeedType.SEARCH),
filter = JsonFilter(
kinds = listOf(MetadataEvent.kind),
search = mySearchString,
limit = 100
)
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter = JsonFilter(
search = mySearchString,
limit = 100
)
)
)
}
val searchChannel = requestNewChannel()
override fun updateChannelFilters() {
searchChannel.typedFilters = createAnythingWithIDFilter()
}
fun search(searchString: String) {
this.searchString = searchString
invalidateFilters()
}
fun clear() {
searchString = null
}
}
| 126 | Kotlin | 117 | 818 | 95ac046a095bf00f53d61f28d03bc7fbb6a3b44e | 2,480 | amethyst | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/service/NostrSearchEventOrUserDataSource.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.service
import com.vitorpamplona.amethyst.model.toHexKey
import com.vitorpamplona.amethyst.service.model.*
import com.vitorpamplona.amethyst.service.nip19.Nip19
import com.vitorpamplona.amethyst.service.relays.COMMON_FEED_TYPES
import com.vitorpamplona.amethyst.service.relays.FeedType
import com.vitorpamplona.amethyst.service.relays.JsonFilter
import com.vitorpamplona.amethyst.service.relays.TypedFilter
import fr.acinq.secp256k1.Hex
object NostrSearchEventOrUserDataSource : NostrDataSource("SingleEventFeed") {
private var searchString: String? = null
private fun createAnythingWithIDFilter(): List<TypedFilter>? {
val mySearchString = searchString
if (mySearchString.isNullOrBlank()) {
return null
}
val hexToWatch = try {
Nip19.uriToRoute(mySearchString)?.hex ?: Hex.decode(mySearchString).toHexKey()
} catch (e: Exception) {
null
}
// downloads all the reactions to a given event.
return listOfNotNull(
hexToWatch?.let {
TypedFilter(
types = COMMON_FEED_TYPES,
filter = JsonFilter(
ids = listOfNotNull(hexToWatch)
)
)
},
hexToWatch?.let {
TypedFilter(
types = COMMON_FEED_TYPES,
filter = JsonFilter(
kinds = listOf(MetadataEvent.kind),
authors = listOfNotNull(hexToWatch)
)
)
},
TypedFilter(
types = setOf(FeedType.SEARCH),
filter = JsonFilter(
kinds = listOf(MetadataEvent.kind),
search = mySearchString,
limit = 100
)
),
TypedFilter(
types = setOf(FeedType.SEARCH),
filter = JsonFilter(
search = mySearchString,
limit = 100
)
)
)
}
val searchChannel = requestNewChannel()
override fun updateChannelFilters() {
searchChannel.typedFilters = createAnythingWithIDFilter()
}
fun search(searchString: String) {
this.searchString = searchString
invalidateFilters()
}
fun clear() {
searchString = null
}
}
| 126 | Kotlin | 117 | 818 | 95ac046a095bf00f53d61f28d03bc7fbb6a3b44e | 2,480 | amethyst | MIT License |
src/main/kotlin/org/bonitasoft/example/processes/StartXProcesses.kt | DumitruCorini | 306,242,915 | true | {"Kotlin": 78847} | /*
* Copyright 2020 Bonitasoft S.A.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bonitasoft.example.processes
import org.bonitasoft.engine.api.APIClient
import org.bonitasoft.engine.bpm.bar.BusinessArchiveBuilder
import org.bonitasoft.engine.bpm.bar.actorMapping.Actor
import org.bonitasoft.engine.bpm.bar.actorMapping.ActorMapping
import org.bonitasoft.engine.bpm.contract.Type
import org.bonitasoft.engine.bpm.process.impl.ProcessDefinitionBuilder
import org.bonitasoft.engine.expression.ExpressionBuilder
import org.bonitasoft.engine.expression.ExpressionConstants
import org.bonitasoft.engine.form.FormMappingSearchDescriptor
import org.bonitasoft.engine.form.FormMappingType
import org.bonitasoft.engine.operation.OperationBuilder
import org.bonitasoft.engine.page.PageNotFoundException
import org.bonitasoft.engine.search.SearchOptionsBuilder
import org.bonitasoft.example.safeExec
import org.bonitasoft.example.toExpression
import org.bonitasoft.example.toParameter
import org.bonitasoft.example.toScript
import java.lang.Exception
class StartXProcesses(private val targetProcessName: String, private val targetProcessVersion: String, private val instances: Int) : BonitaProcess() {
override fun process(): ProcessDefinitionBuilder =
ProcessDefinitionBuilder().createNewInstance("StartXProcesses", "1.1")
.apply {
addContract().apply {
addInput("numberOfInstances", Type.INTEGER, "number of processes to start")
}
addIntegerData("instances", ExpressionBuilder().createContractInputExpression("numberOfInstances", "java.lang.Integer"))
addParameter("targetProcessName", "java.lang.String")
addParameter("targetProcessVersion", "java.lang.String")
addActor("theActor", true)
addStartEvent("start")
addShortTextData("someText", null)
addAutomaticTask("task1").apply {
addMultiInstance(false, ExpressionBuilder().createDataExpression("instances", "java.lang.Integer"))
addOperation(OperationBuilder().createSetDataOperation("someText", """
def pId = apiAccessor.processAPI.getProcessDefinitionId(targetProcessName, targetProcessVersion)
apiAccessor.processAPI.startProcess(pId)
return "ok"
""".trimIndent().toScript(ExpressionConstants.API_ACCESSOR.toExpression(), "targetProcessName".toParameter(), "targetProcessVersion".toParameter())))
}
addTransition("start", "task1")
}
override fun withResources(bar: BusinessArchiveBuilder) {
bar.apply {
actorMapping = ActorMapping().apply {
addActor(Actor("theActor").apply {
addUser("walter.bates")
})
}
setParameters(mapOf(
"targetProcessName" to targetProcessName,
"targetProcessVersion" to targetProcessVersion
))
}
}
override fun accept(client: APIClient) {
super.accept(client)
// client.safeExec {
// val formMapping = processAPI.searchFormMappings(SearchOptionsBuilder(0, 10)
// .filter(FormMappingSearchDescriptor.TYPE, FormMappingType.PROCESS_START)
// .filter(FormMappingSearchDescriptor.PROCESS_DEFINITION_ID, processDefinitionId).done()).result[0]
// val processInstantiationForm = customPageAPI.getPageByName("custompage_processAutogeneratedForm")
// processAPI.updateFormMapping(formMapping.id, null, processInstantiationForm.id)
// }
}
} | 0 | null | 0 | 0 | 22460480023a8e6e18cd575d709cafa7e6abd9ee | 4,438 | bonita-test-processes | Apache License 2.0 |
feature/groups/domain/src/main/java/br/com/jwar/sharedbill/groups/domain/usecases/AddMemberUseCase.kt | wellingtonrib | 535,153,218 | false | {"Kotlin": 448034, "JavaScript": 2075} | package br.com.jwar.sharedbill.groups.domain.usecases
interface AddMemberUseCase {
suspend operator fun invoke(userName: String, groupId: String): Result<String>
}
| 17 | Kotlin | 0 | 0 | 5343aac247f77437164505e3b977e4ef8fe764da | 169 | SharedBill | Creative Commons Attribution 4.0 International |
app/src/main/java/jhetzel/mvi/signup/SignUpState.kt | juliushetzel | 102,952,911 | false | null | package jhetzel.mvi.signup
data class SignUpState(
val checkingEmail: Int,
val signingUp: Boolean,
val signedUp: Boolean,
val passwordSafe: Boolean,
val emailAvailable: Boolean,
val errorMessage: Int?
) {
companion object {
val INITIAL = SignUpState(
0,
false,
false,
false,
false,
null
)
}
} | 0 | Kotlin | 0 | 1 | cec98e57906b00b464502d595dd372176ad39c3e | 463 | kotlin-android-mvi | MIT License |
ktor-client/ktor-client-ios/nonWatchos/src/io/ktor/client/engine/ios/ProxySupportFull.kt | skuzmich | 246,382,727 | true | {"Kotlin": 4329257, "JavaScript": 775, "HTML": 165} | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.ios
import io.ktor.http.*
import platform.CFNetwork.*
import platform.CoreFoundation.*
import platform.Foundation.*
internal actual fun NSURLSessionConfiguration.setupProxy(config: IosClientEngineConfig) {
val proxy = config.proxy ?: return
val url = proxy.url
when (url.protocol) {
URLProtocol.HTTP -> setupHttpProxy(url)
URLProtocol.HTTPS -> setupHttpProxy(url)
// URLProtocol.SOCKS -> setupSocksProxy(url)
else -> error("Proxy type ${url.protocol.name} is unsupported by iOS client engine.")
}
}
internal fun NSURLSessionConfiguration.setupHttpProxy(url: Url) {
connectionProxyDictionary = mapOf(
kCFNetworkProxiesHTTPEnable.toNSString() to 1,
kCFNetworkProxiesHTTPProxy.toNSString() to url.host,
kCFNetworkProxiesHTTPPort.toNSString() to url.port
)
}
internal fun NSURLSessionConfiguration.setupHttpsProxy(url: Url) {
// connectionProxyDictionary = mapOf(
// kCFNetworkProxiesHTTPSEnable.toNSString() to 1,
// kCFNetworkProxiesHTTPSProxy.toNSString() to url.host,
// kCFNetworkProxiesHTTPSPort.toNSString() to url.port
// )
}
internal fun NSURLSessionConfiguration.setupSocksProxy(url: Url) {
// connectionProxyDictionary = mapOf(
// kCFNetworkProxiesSOCKSEnable.toNSString() to true,
// kCFNetworkProxiesSOCKSProxy.toNSString() to url.host,
// kCFNetworkProxiesSOCKSPort.toNSString() to url.port
// )
}
internal fun CFStringRef?.toNSString(): NSString = CFBridgingRelease(this) as NSString
| 0 | null | 0 | 0 | f16dc95ffa8c4a99de6ac8f0b7b620aedc4c4f5d | 1,693 | ktor | Apache License 2.0 |
library/src/main/java/com/fanhl/percentagebar/NumberUtil.kt | dyguests | 150,922,192 | false | {"Gradle": 4, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 6, "XML": 25, "INI": 1, "Java": 2} | package com.fanhl.percentagebar
import java.text.DecimalFormat
object NumberUtil {
/**
* 百分比
*
* 0.12341234 -> 12%
*/
fun perc(percentage: Float): String {
return DecimalFormat("##%").format(percentage)
}
} | 0 | Kotlin | 0 | 0 | bdac53a81e814596896a973b5782e382e36aa89e | 248 | PercentageBar | Apache License 2.0 |
src/main/kotlin/com/fappslab/difflinescounter/presentation/DiffStatusWidget.kt | F4bioo | 702,756,758 | false | {"Kotlin": 20776, "Python": 618} | package com.fappslab.difflinescounter.presentation
import com.fappslab.difflinescounter.data.git.GitRepository
import com.fappslab.difflinescounter.domain.model.ActionPlacesType
import com.fappslab.difflinescounter.domain.usecase.GetDiffStatUseCase
import com.fappslab.difflinescounter.domain.usecase.ScheduleUpdatesUseCase
import com.fappslab.difflinescounter.extension.isNull
import com.fappslab.difflinescounter.extension.refreshChangesActions
import com.fappslab.difflinescounter.presentation.action.FileAction
import com.fappslab.difflinescounter.presentation.action.MouseAction
import com.intellij.ide.DataManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.CustomStatusBarWidget
import com.intellij.openapi.wm.StatusBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.swing.JComponent
private const val REFRESH_DELAY = 30L
class DiffStatusWidget(
private val project: Project,
private val component: DiffStatusLabel,
private val getDiffStatUseCase: GetDiffStatUseCase,
private val scheduleUpdatesUseCase: ScheduleUpdatesUseCase
) : CustomStatusBarWidget {
private val job = Job()
private val coroutineScope = CoroutineScope(Dispatchers.Default + job)
private val connection = project.messageBus.connect(this)
private val mouseAction = MouseAction(::refreshChangesAction)
init {
setupFilesChangeTracker()
setupScheduleUpdates()
setupMouseListener()
}
override fun getComponent(): JComponent {
return component
}
override fun ID(): String {
return ID
}
override fun dispose() {
component.removeMouseListener(mouseAction)
connection.disconnect()
job.cancel()
}
override fun install(statusBar: StatusBar) {}
private fun setupMouseListener() {
component.addMouseListener(mouseAction)
}
private fun setupScheduleUpdates() {
coroutineScope.launch {
scheduleUpdatesUseCase(REFRESH_DELAY, ::refreshChangesAction)
}
}
private fun setupFilesChangeTracker() {
connection.subscribe(
VirtualFileManager.VFS_CHANGES,
FileAction {
coroutineScope.launch {
val diffStat = getDiffStatUseCase(project.basePath)
component.showChanges(diffStat)
}
}
)
}
private fun refreshChangesAction() {
if (GitRepository.provider(project.basePath).isNull()) {
component.showChanges(diffStat = null)
} else {
ApplicationManager.getApplication().invokeLater {
val dataContext = DataManager.getInstance().getDataContext(component)
dataContext.refreshChangesActions(ActionPlacesType.StatusBarPlace)
}
}
}
}
| 3 | Kotlin | 1 | 0 | 038df141fba6f147a2f637f86f3dc19ad2bd03af | 3,052 | DiffLinesCounter | MIT License |
shared/src/commonMain/kotlin/me/dinarastepina/features/feature/presentation/ui/screens/home/HomeScreen.kt | dinarastr | 701,858,554 | false | {"Kotlin": 150250, "Swift": 727, "Shell": 227, "Ruby": 101} | package me.dinarastepina.features.feature.presentation.ui.screens.home
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import cafe.adriel.voyager.core.model.rememberScreenModel
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.core.screen.ScreenKey
import cafe.adriel.voyager.navigator.CurrentScreen
import cafe.adriel.voyager.navigator.Navigator
import cafe.adriel.voyager.navigator.tab.LocalTabNavigator
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabNavigator
import me.dinarastepina.features.feature.presentation.data.FeatureStrings
import me.dinarastepina.features.feature.presentation.ui.screens.dictionary.DictionaryTab
import me.dinarastepina.features.feature.presentation.ui.screens.info.InfoTab
import me.dinarastepina.features.feature.presentation.ui.screens.onboarding.OnBoardingScreen
import me.dinarastepina.features.feature.presentation.ui.screens.topics.TopicsTab
object HomeScreen : Screen {
override val key: ScreenKey = FeatureStrings.HOME_SCREEN_TITLE.localize()
@Composable
override fun Content() {
val vm = rememberScreenModel { HomeScreenVM() }
val homeState by vm.startDestination
when (homeState) {
OnBoardingScreen.key -> {
Navigator(
screen = OnBoardingScreen
) {
Scaffold {
CurrentScreen()
}
}
}
TabsScreen.key -> {
TabsContent()
}
}
}
}
object TabsScreen: Screen {
override val key: ScreenKey
get() = FeatureStrings.TAB_SCREEN_TITLE.localize()
@Composable
override fun Content() {
TabsContent()
}
}
@Composable
fun TabsContent() {
TabNavigator(
tab = DictionaryTab
) {
Scaffold(
content = { p ->
CurrentTab(
modifier = Modifier.padding(
bottom = p.calculateBottomPadding()
)
)
},
bottomBar = {
NavigationBar(
containerColor = MaterialTheme.colorScheme.primary
) {
TabNavigationItem(DictionaryTab)
TabNavigationItem(TopicsTab)
TabNavigationItem(InfoTab)
}
}
)
}
}
@Composable
fun CurrentTab(
modifier: Modifier
) {
val tabNavigator = LocalTabNavigator.current
val currentTab = tabNavigator.current
tabNavigator.saveableState("currentTab") {
Box(modifier = modifier) {
currentTab.Content()
}
}
}
@Composable
private fun RowScope.TabNavigationItem(
tab: Tab
) {
val tabNavigator = LocalTabNavigator.current
NavigationBarItem(
colors = NavigationBarItemDefaults.colors(
indicatorColor = MaterialTheme.colorScheme.secondary
),
selected = tabNavigator.current == tab,
onClick = {
tabNavigator.current = tab
},
icon = {
tab.options.icon?.let {
Icon(
painter = it,
contentDescription = tab.options.title
)
}
},
label = {
Text(
text = tab.options.title,
color = MaterialTheme.colorScheme.onPrimary
)
}
)
} | 0 | Kotlin | 0 | 0 | 136b9d0d05d601b71b79f9fcf022a84f7aa75149 | 4,049 | udege | Apache License 2.0 |
feature/auth/src/main/java/com/cmc/curtaincall/feature/auth/login/naver/LoginNaver.kt | CurtainCall-App | 659,971,351 | false | {"Kotlin": 1298142} | package com.cmc.curtaincall.feature.auth.login.naver
import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.cmc.curtaincall.common.designsystem.R
import com.cmc.curtaincall.feature.auth.login.LoginViewModel
import com.navercorp.nid.NaverIdLoginSDK
import timber.log.Timber
private const val LOGIN_NAVER_BUTTON = "LOGIN_NAVER_BUTTON"
private const val NAVER_PROVIDER = "naver"
@Composable
fun LoginNaverButton(
modifier: Modifier = Modifier,
loginViewModel: LoginViewModel = hiltViewModel(),
onNavigateSignUpTerms: () -> Unit = {},
onNavigateHome: () -> Unit = {}
) {
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
when (result.resultCode) {
RESULT_OK -> {
Timber.d("Naver Login Success Token: ${NaverIdLoginSDK.getAccessToken()}")
NaverIdLoginSDK.getAccessToken()?.let { token ->
loginViewModel.fetchLogin(NAVER_PROVIDER, token)
}
}
RESULT_CANCELED -> {
Timber.e("Naver Login Error: ${NaverIdLoginSDK.getLastErrorDescription()}")
}
}
}
Image(
painter = painterResource(R.drawable.ic_naver_login),
contentDescription = LOGIN_NAVER_BUTTON,
modifier = modifier
.size(50.dp)
.clickable {
NaverIdLoginSDK.authenticate(context, launcher)
}
)
}
| 4 | Kotlin | 1 | 5 | c9f51916e3acbb292f364b3a3191991506d76580 | 2,083 | CurtainCall-AOS | Apache License 2.0 |
core/src/test/kotlin/org/cryptobiotic/rlauxe/alpha/TestAlphaMart.kt | JohnLCaron | 847,947,313 | false | {"Kotlin": 611424} | package org.cryptobiotic.rlauxe.alpha
import org.cryptobiotic.rlauxe.SampleFromArray
import org.cryptobiotic.rlauxe.core.AlphaMart
import org.cryptobiotic.rlauxe.core.Bernoulli
import org.cryptobiotic.rlauxe.core.TestH0Result
import org.cryptobiotic.rlauxe.core.TestH0Status
import org.cryptobiotic.rlauxe.core.TruncShrinkage
import org.cryptobiotic.rlauxe.core.eps
import org.cryptobiotic.rlauxe.doublePrecision
import kotlin.math.max
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
// Compare AlphaMart with output from SHANGRLA
class TestAlphaMart {
// def test_alpha_mart(self):
// eps = 0.0001 # Generic small value
//
// # When all the items are 1/2, estimated p for a mean of 1/2 should be 1.
// s = np.ones(5) / 2
// test = NonnegMean(N=int(10 ** 6))
// np.testing.assert_almost_equal(test.alpha_mart(s)[0], 1.0)
// test.t = eps
// np.testing.assert_array_less(test.alpha_mart(s)[1][1:], [eps] * (len(s) - 1))
//
// s = [0.6, 0.8, 1.0, 1.2, 1.4]
// test.u = 2
// np.testing.assert_array_less(test.alpha_mart(s)[1][1:], [eps] * (len(s) - 1))
//
// s1 = [1, 0, 1, 1, 0, 0, 1]
// test.u = 1
// test.N = 7
// test.t = 3 / 7
// alpha_mart1 = test.alpha_mart(s1)[1]
// # p-values should be big until the last, which should be 0
// print(f'{alpha_mart1=}')
// assert (not any(np.isnan(alpha_mart1)))
// assert (alpha_mart1[-1] == 0)
//
// s2 = [1, 0, 1, 1, 0, 0, 0]
// alpha_mart2 = test.alpha_mart(s2)[1]
// # Since s1 and s2 only differ in the last observation,
// # the resulting martingales should be identical up to the next-to-last.
// # Final entry in alpha_mart2 should be 1
// print(f'{alpha_mart2=}')
// assert (all(np.equal(alpha_mart2[0:(len(alpha_mart2) - 1)],
// alpha_mart1[0:(len(alpha_mart1) - 1)])))
//alpha_mart1=array([0.57142857, 1. , 0.61464586, 0.1891218 , 1. ,1. , 0. ])
//alpha_mart2=array([0.57142857, 1. , 0.61464586, 0.1891218 , 1. ,1. , 1. ])
@Test
fun test_alpha_mart_half() {
// # When all the items are 1/2, estimated p for a mean of 1/2 should be 1.
// s = np.ones(5)/2
// test = NonnegMean(N=int(10**6))
// np.testing.assert_almost_equal(test.alpha_mart(s)[0],1.0)
val x = DoubleArray(5) { .5 }
val eta0 = 0.5
val allHalf = testAlphaMartBatch(eta0, x.toList())
println(" allHalf = ${allHalf.pvalues}")
allHalf.pvalues.forEach {
assertEquals(1.0, it)
}
}
@Test
fun test_alpha_mart1() {
// s1 = [1, 0, 1, 1, 0, 0, 1]
val x2 = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0)
val eta0 = .5714285714285714
require(x2.average() == eta0)
val alpha2 = testAlphaMartBatch(x2.average(), x2.toList())
println(" alpha2 = ${alpha2}")
val expected = listOf(0.875, 1.0, 1.0, 0.73981759, 1.0, 1.0, 1.0)
println(" expected = ${expected}")
expected.forEachIndexed { idx, it ->
if (it != 1.0) {
assertEquals(it, alpha2.pvalues[idx], doublePrecision)
}
}
assertTrue(alpha2.status.fail)
assertEquals(alpha2.sampleCount, x2.size)
assertEquals(alpha2.sampleMean, 0.5714285714285714)
}
@Test
fun test_alpha_mart2() {
val x2 = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0)
val alpha2 = testAlphaMartBatch(.51, x2.toList())
println(" alpha2 = ${alpha2}")
val expected = listOf(0.98039216, 1.0 , 1.0 , 0.86706352, 1.0, 1.0 , 1.0)
println(" expected = ${expected}")
expected.forEachIndexed { idx, it ->
if (it != 1.0) {
assertEquals(it, alpha2.pvalues[idx], doublePrecision)
}
}
assertTrue(alpha2.status == TestH0Status.LimitReached)
assertEquals(alpha2.sampleCount, x2.size)
assertEquals(alpha2.sampleMean, 0.42857142857142855)
}
@Test
fun test_shrink_trunk_f1() {
val x = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 )
val eta0 = .51
println("test_shrink_trunk_f1 $eta0 x=$x")
val u = 1.0
val d = 10
val f = 0.5
val minsd = 1.0e-6
val t= 0.5
val c = (eta0 - t) / 2
val N = x.size
val estimFn = TruncShrinkage(N = N, upperBound = u, minsd = minsd, d = d, eta0 = eta0, f = f, c = c)
val alpha = AlphaMart(estimFn = estimFn, N = N, upperBound = u)
val sampler = SampleFromArray(x.toDoubleArray())
val result = alpha.testH0(x.size, false) { sampler.sample() }
println(" test_shrink_trunk_f1 = ${result}")
val expected = listOf(0.74257426, 1.0, 0.96704619, 0.46507099, 1.0, 1.0, 1.0)
println(" expected = ${expected}")
expected.forEachIndexed { idx, it ->
if (it != 1.0) {
assertEquals(it, result.pvalues[idx], doublePrecision)
}
}
assertTrue(result.status.fail)
assertEquals(result.sampleCount, x.size)
assertEquals(result.sampleMean, 0.5714285714285714)
}
@Test
fun test_shrink_trunk_f1_wreplacement() {
val x = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 )
val eta0 = .51
println("test_shrink_trunk_f1 $eta0 x=$x")
val u = 1.0
val d = 10
val f = 0.5
val minsd = 1.0e-6
val t= 0.5
val c = (eta0 - t) / 2
val N = x.size
val estimFn = TruncShrinkage(
N = N,
withoutReplacement = false,
upperBound = u,
minsd = minsd,
d = d,
eta0 = eta0,
f = f,
c = c
)
val alpha = AlphaMart(estimFn = estimFn, N = N, withoutReplacement = false, upperBound = u)
val sampler = SampleFromArray(x.toDoubleArray())
val result = alpha.testH0(x.size, false) { sampler.sample() }
println(" test_shrink_trunk_f1_wreplacement = ${result}")
val expected = listOf(0.74257426, 1.0, 0.82889674, 0.53150971, 1.0, 1.0, 1.0)
println(" expected = ${expected}")
expected.forEachIndexed { idx, it ->
if (it != 1.0) {
assertEquals(it, result.pvalues[idx], doublePrecision)
}
}
assertTrue(result.status.fail)
assertEquals(result.sampleCount, x.size)
assertEquals(result.sampleMean, 0.5714285714285714)
}
@Test
fun compareAlphaWithShrinkTrunc() {
val bernoulliDist = Bernoulli(.5)
val bernoulliList = DoubleArray(20) { bernoulliDist.get() }.toList()
val v = listOf(
listOf(0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0),
listOf(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),
bernoulliList
)
val etas = listOf(.51, .55, .6) // alternative means
for (eta in etas) {
for (x: List<Double> in v) {
compareAlphaWithShrinkTrunc(
eta,
x)
}
println()
}
}
fun compareAlphaWithShrinkTrunc(eta0: Double, x: List<Double>) {
val algoValues: TestH0Result = testAlphaMartWithTermination(
eta0,
x
)
val martValues: TestH0Result = testAlphaMartBatch(
eta0,
x
)
// both failed or both succeeded
val limit1 = algoValues.status == TestH0Status.LimitReached
val limit2 = martValues.status == TestH0Status.LimitReached
assertEquals(limit1, limit2)
algoValues.pvalues.forEachIndexed { idx, it ->
assertEquals(it, martValues.pvalues[idx])
}
}
fun testAlphaMartWithTermination(eta0: Double, x: List<Double>): TestH0Result {
// println("testAlphaMartWithTermination $eta0 x=$x")
val u = 1.0
val d = 10
val f = 0.0
val minsd = 1.0e-6
val t = 0.5
val c = (eta0 - t) / 2
val N = x.size
val estimFn = TruncShrinkage(N = N, upperBound = u, minsd = minsd, d = d, eta0 = eta0, f = f, c = c)
val alpha = AlphaMart(estimFn = estimFn, N = N, upperBound = u)
val sampler = SampleFromArray(x.toDoubleArray())
return alpha.testH0(x.size, true) { sampler.sample() }
}
fun testAlphaMartBatch(eta0: Double, x: List<Double>): TestH0Result {
println("testAlphaMartBatch $eta0 x=$x")
val u = 1.0
val d = 10
val f = 0.0
val minsd = 1.0e-6
val t = 0.5
val c = max(eps, (eta0 - t) / 2)
val N = x.size
val estimFn = TruncShrinkage(N = N, upperBound = u, minsd = minsd, d = d, eta0 = eta0, f = f, c = c)
val alpha = AlphaMart(estimFn = estimFn, N = N, upperBound = u)
val sampler = SampleFromArray(x.toDoubleArray())
return alpha.testH0(x.size, false) { sampler.sample() }
}
@Test
fun testAlphaAlgoWithShrinkTruncProblem() {
val x = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0)
val eta0 = x.average()
val algoValues = testAlphaMartWithTermination(
eta0,
x
)
println("testAlphaAlgoWithShrinkTruncProblem = $algoValues")
}
@Test
fun testAlphaMartWithShrinkTruncProblem() {
val x = listOf(1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0)
val eta0 = x.average()
val martValues = testAlphaMartBatch(eta0, x)
println("testAlphaMartWithShrinkTruncProblem = ${martValues}")
}
} | 0 | Kotlin | 0 | 0 | b977070786f3afbf5dd28e148f4ba9de8fe1201e | 9,897 | rlauxe | Open LDAP Public License v2.1 |
client/src/commonMain/kotlin/com/algolia/client/model/search/QueryType.kt | algolia | 153,273,215 | false | {"Kotlin": 1463733} | /** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */
package com.algolia.client.model.recommend
import kotlinx.serialization.*
/**
* Determines if and how query words are interpreted as prefixes. By default, only the last query word is treated as a prefix (`prefixLast`). To turn off prefix search, use `prefixNone`. Avoid `prefixAll`, which treats all query words as prefixes. This might lead to counterintuitive results and makes your search slower. For more information, see [Prefix searching](https://www.algolia.com/doc/guides/managing-results/optimize-search-results/override-search-engine-defaults/in-depth/prefix-searching/).
*/
@Serializable
public enum class QueryType(public val value: kotlin.String) {
@SerialName(value = "prefixLast")
PrefixLast("prefixLast"),
@SerialName(value = "prefixAll")
PrefixAll("prefixAll"),
@SerialName(value = "prefixNone")
PrefixNone("prefixNone");
override fun toString(): kotlin.String = value
}
| 14 | Kotlin | 23 | 59 | ad21e6ddfbee8df4c40524ff401b5e1058f7b8b7 | 1,095 | algoliasearch-client-kotlin | MIT License |
composeApp/src/commonMain/kotlin/ui/screen/home/HomeScreen.kt | saifi369 | 833,042,897 | false | {"Kotlin": 18399, "Swift": 632} | package ui.screen.home
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
@Composable
fun HomeScreen() {
Column {
//Home Screen Content
}
} | 0 | Kotlin | 0 | 0 | 4e60903342b1793d9198721e5c2dd4c872390cd3 | 198 | KMP-ExpenseTracker | Apache License 2.0 |
feather/src/commonMain/kotlin/compose/icons/feathericons/ArrowLeftCircle.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.feathericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.FeatherIcons
public val FeatherIcons.ArrowLeftCircle: ImageVector
get() {
if (_arrowLeftCircle != null) {
return _arrowLeftCircle!!
}
_arrowLeftCircle = Builder(name = "ArrowLeftCircle", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 12.0f)
moveToRelative(-10.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, 20.0f, 0.0f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, -20.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 8.0f)
lineToRelative(-4.0f, 4.0f)
lineToRelative(4.0f, 4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 12.0f)
lineTo(8.0f, 12.0f)
}
}
.build()
return _arrowLeftCircle!!
}
private var _arrowLeftCircle: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,386 | compose-icons | MIT License |
src/main/kotlin/com/github/varenytsiamykhailo/knml/bignumbers/FFT.kt | VarenytsiaMykhailo | 490,834,301 | false | {"Kotlin": 315543, "Java": 58256} | package com.github.varenytsiamykhailo.knml.bignumbers
import kotlin.math.cos
import kotlin.math.sin
import org.apache.commons.math3.complex.Complex
import kotlin.math.PI
class FFT(var n: Int) {
fun fft(vec: List<Complex>): List<Complex> {
val n = vec.size
var k = 0
while ((1 shl k) < n) k++
val rev = IntArray(n)
rev[0] = 0
var high1 = -1
for (i in 1 until n) {
val flag = i and (i - 1)
if (flag == 0)
high1++
rev[i] = rev[i xor (1 shl high1)]
rev[i] = rev[i] or (1 shl (k - high1 - 1))
}
val roots = List(n) { i ->
val alpha = 2 * PI * i / n
Complex(cos(alpha), sin(alpha))
}
val cur = MutableList(n) { i -> vec[rev[i]] }
var len = 1
while (len < n) {
val ncur = MutableList(n) { Complex(0.0, 0.0) }
val rstep = roots.size / (len * 2)
var pdest = 0
while (pdest < n) {
var p1 = pdest
for (i in 0 until len) {
val val1 = roots[i * rstep].multiply(cur[p1 + len])
ncur[pdest] = cur[p1].add(val1)
ncur[pdest + len] = cur[p1].subtract(val1)
pdest++
p1++
}
pdest += len
}
cur.clear()
cur.addAll(ncur)
len = len shl 1
}
return cur.toList()
}
fun fftRev(vec: List<Complex>): List<Complex> {
var res = fft(vec)
res = res.map { Complex(it.real / vec.size, it.imaginary / vec.size) }
res = res.reversed().toMutableList()
res.add(0, res.removeAt(res.size - 1))
return res
}
}
| 0 | Kotlin | 2 | 6 | a556245de1f4d2529e259a3eee595d735005dcc8 | 1,802 | KNML-Kotlin-Numerical-Methods-Library | MIT License |
packages/library-sync/src/commonMain/kotlin/io/realm/kotlin/mongodb/ext/FunctionsExt.kt | realm | 235,075,339 | false | {"Kotlin": 4564631, "C++": 126122, "SWIG": 26070, "Shell": 23822, "C": 5126, "CMake": 2858, "Ruby": 1586, "Java": 1470} | /*
* Copyright 2023 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.kotlin.mongodb.ext
import io.realm.kotlin.annotations.ExperimentalRealmSerializerApi
import io.realm.kotlin.mongodb.AppConfiguration
import io.realm.kotlin.mongodb.Functions
import io.realm.kotlin.mongodb.exceptions.AppException
import io.realm.kotlin.mongodb.exceptions.FunctionExecutionException
import io.realm.kotlin.mongodb.exceptions.ServiceException
import io.realm.kotlin.mongodb.internal.BsonEncoder
import io.realm.kotlin.mongodb.internal.FunctionsImpl
import io.realm.kotlin.mongodb.internal.serializerOrRealmBuiltInSerializer
import kotlinx.serialization.KSerializer
import org.mongodb.kbson.BsonArray
import org.mongodb.kbson.BsonDocument
import org.mongodb.kbson.BsonValue
import org.mongodb.kbson.ExperimentalKBsonSerializerApi
import org.mongodb.kbson.serialization.Bson
import org.mongodb.kbson.serialization.EJson
/**
* Invokes an Atlas function.
*
* Since the serialization engine [does not support third-party libraries yet](https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md), there are some
* limitations in what types can be used as arguments and return types:
*
* - Primitives, Bson, MutableRealmInt, RealmUUID, ObjectId, RealmInstant, RealmAny, Array, Collection, and Map are valid argument types.
* - Results can only be deserialized to Bson, MutableRealmInt, RealmUUID, ObjectId, RealmInstant, RealmAny and primitive types
*
* The Bson implementations for arrays or maps are [BsonArray] and [BsonDocument], and they can be
* used as valid return types.
*
* @param name name of the function to call.
* @param args arguments to the function.
* @param T the function return value type.
* @return result of the function call.
*
* @throws FunctionExecutionException if the function failed in some way.
* @throws ServiceException for other failures that can happen when communicating with App Services.
* See [AppException] for details.
*/
public suspend inline fun <reified T : Any?> Functions.call(
name: String,
vararg args: Any?
): T = with(this as FunctionsImpl) {
val serializedEjsonArgs = Bson.toJson(BsonEncoder.encodeToBsonValue(args.toList()))
val encodedResult = callInternal(name, serializedEjsonArgs)
BsonEncoder.decodeFromBsonValue(
resultClass = T::class,
bsonValue = Bson(encodedResult)
) as T
}
/**
* Invokes an Atlas function using the EJson encoder defined in [AppConfiguration.ejson].
*
* **Note** This method supports full document serialization. The call arguments are defined with the builder
* [CallBuilder]. This same builder also allows to bind manually any argument or the return type to
* a specific serializer. Arguments and the return value will be encoded and decoded with [AppConfiguration.ejson].
*
* ```
* val dog: Dog = user.functions.call("RetrieveDog") {
* add("a parameter")
* add(1.5, FloatSerializer) // sets the serializer for this particular argument
* returnValueSerializer = DogSerializer // sets the serializer for the return type
* }
* ```
*
* We cannot use a generic because:
* - There is no serializer available for Any.
* - any [KClass<T>.serializer() is marked as Internal](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/serializer.html)
*
* @param name name of the function to call.
* @param callBuilderBlock code block that sets the call arguments and serializers.
* @param T the function return value type.
* @return result of the function call.
*/
@ExperimentalRealmSerializerApi
@OptIn(ExperimentalKBsonSerializerApi::class)
public suspend inline fun <reified T : Any?> Functions.call(
name: String,
callBuilderBlock: CallBuilder<T>.() -> Unit
): T = with(this as FunctionsImpl) {
CallBuilder<T>(app.configuration.ejson)
.apply(callBuilderBlock)
.run {
val serializedEjsonArgs = Bson.toJson(arguments)
val encodedResult = callInternal(name, serializedEjsonArgs)
val returnValueSerializer =
returnValueSerializer
?: ejson.serializersModule.serializerOrRealmBuiltInSerializer()
ejson.decodeFromString(returnValueSerializer, encodedResult)
}
}
/**
* Builder used to construct a call defining serializers for the different arguments and return value.
*/
@ExperimentalRealmSerializerApi
@OptIn(ExperimentalKBsonSerializerApi::class)
public class CallBuilder<T>
@PublishedApi
internal constructor(
@PublishedApi
internal val ejson: EJson,
) {
/**
* Contains all given arguments transformed as [BsonValue]. The encoding is done on each [add] call
* as in that context we have type information from the reified type.
*
* Usually we would store the arguments in a `List<Any>` and would serialize just before invoking
* the call, but that would require to do a runtime look up of the argument serializers an operation
* that unfortunately is internal to kserializer and not stable cross all platforms.
*/
@PublishedApi
internal val arguments: BsonArray = BsonArray()
/**
* Serializer that would be used to deserialize the returned value, null by default.
*
* If null, the return value will be deserialized using the embedded type serializer. Note that
* Realm collection types must be set as they don't have an embedded serializer, for example:
*
* ```kotlin
* CallBuilder<RealmList<String>> {
* returnValueSerializer = RealmListKSerializer(String.serializer())
* }
* ```
*/
public var returnValueSerializer: KSerializer<T>? = null
/**
* Adds an argument with the default serializer for its type to the function call.
*
* @param T argument type.
* @param argument value.
*/
public inline fun <reified T : Any> add(argument: T) {
add(argument, ejson.serializersModule.serializerOrRealmBuiltInSerializer())
}
/**
* Adds an argument with a user defined serializer to the function call.
*
* @param T argument type.
* @param argument value.
* @param serializer argument serializer.
*/
public inline fun <reified T : Any> add(argument: T, serializer: KSerializer<T>) {
arguments.add(ejson.encodeToBsonValue(serializer, argument))
}
}
| 242 | Kotlin | 57 | 942 | df49eefacba8f57653e232203f44003643468463 | 6,922 | realm-kotlin | Apache License 2.0 |
src/main/kotlin/com/buckstabue/stickynotes/idea/stickynotelist/di/PerStickyNoteListDialog.kt | Buckstabue | 225,958,036 | false | null | package com.buckstabue.stickynotes.idea.stickynotelist.di
import javax.inject.Scope
@Scope
annotation class PerStickyNoteListDialog
| 9 | Kotlin | 2 | 9 | ab07743f043a69a6a7c19d8f36bf483e1205fc06 | 134 | sticky_notes_idea | Apache License 2.0 |
app/src/main/java/io/github/edgardobarriam/techkandroidchallenge/ui/adapter/GalleriesRecyclerViewAdapter.kt | edgardobarriam | 148,704,226 | true | {"Kotlin": 34163} | package io.github.edgardobarriam.techkandroidchallenge.ui.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.edgardobarriam.techkandroidchallenge.R
import io.github.edgardobarriam.techkandroidchallenge.server.Gallery
import io.github.edgardobarriam.techkandroidchallenge.ui.util.ImageDisplayHelper
import io.github.edgardobarriam.techkandroidchallenge.ui.util.TimestampFormatter
import kotlinx.android.synthetic.main.gallery_list_item.view.*
class GalleriesRecyclerViewAdapter(val context: Context,
private val listGalleries: List<Gallery>,
private val itemClick: (Gallery) -> Unit)
: RecyclerView.Adapter<GalleriesRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.gallery_list_item, parent, false)
return ViewHolder(view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val gallery = listGalleries[position]
holder.bindGallery(gallery)
}
override fun getItemCount() = listGalleries.size
inner class ViewHolder(view: View, val itemClick: (Gallery) -> Unit) : RecyclerView.ViewHolder(view) {
fun bindGallery(gallery: Gallery) {
with(gallery) {
itemView.textView_title.text = title
itemView.textView_gallery_datetime.text = TimestampFormatter.timestampToDateTimeString(datetime)
itemView.textView_description.text = description
ImageDisplayHelper.displayImage(this, itemView.imageView_image, context)
itemView.setOnClickListener { itemClick(this) }
}
}
}
} | 0 | Kotlin | 0 | 1 | abadcb984c9f2f852a7e29eca1f305403f2daf18 | 1,936 | android-challenge | MIT License |
website/src/main/kotlin/de/westermann/robots/website/component/AdminControllerList.kt | pixix4 | 130,015,411 | false | null | package de.westermann.robots.website.component
import de.westermann.robots.datamodel.Controller
import de.westermann.robots.datamodel.DeviceManager
import de.westermann.robots.datamodel.observe.Library
import de.westermann.robots.website.toolkit.Router
import de.westermann.robots.website.toolkit.widget.CardView
/**
* @author lars
*/
fun Router.adminControllerList() {
view {
CardView<ControllerCard> {
var controllers: Map<Controller, ControllerCard> = emptyMap()
fun addController(controller: Controller) {
val card = ControllerCard(controller)
controllers += controller to card
this += card
}
fun removeController(controller: Controller) {
controllers[controller]?.let { card ->
this -= card
}
}
DeviceManager.controllers.onChange(object : Library.Observer<Controller> {
override fun onAdd(element: Controller) {
addController(element)
}
override fun onRemove(element: Controller) {
removeController(element)
}
})
DeviceManager.controllers.forEach(::addController)
}
}
} | 0 | Kotlin | 0 | 0 | 383475939c2ba1bf95b458edf762e123b10e8509 | 1,307 | Robots | Apache License 2.0 |
presentation/src/main/java/br/pedroso/tweetsentiment/presentation/features/tweetsList/viewStateTransformers/AnalyseTweetsStateTransformer.kt | gustinoco | 148,358,306 | true | {"Kotlin": 98871, "Java": 3580, "Shell": 1706} | package br.pedroso.tweetsentiment.presentation.features.tweetsList.viewStateTransformers
import br.pedroso.tweetsentiment.domain.Sentiment
import br.pedroso.tweetsentiment.domain.entities.ViewState
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
class AnalyseTweetsStateTransformer : ObservableTransformer<Sentiment, ViewState> {
override fun apply(upstream: Observable<Sentiment>): ObservableSource<ViewState> {
return upstream
.map { ViewState.Success() as ViewState }
.onErrorReturn { ViewState.Error(it) }
.startWith(ViewState.Loading())
}
} | 0 | Kotlin | 0 | 0 | e62f478ed977c4f06a925e82238b70e6194127c6 | 674 | tweet-sentiment | MIT License |
Avançado/KotlinRecyclerView_2/app/src/main/java/br/com/kotlinrecyclerview_2/model/Pessoa.kt | Artur-Brasileiro | 800,685,723 | false | {"Kotlin": 74477} | package br.com.kotlinrecyclerview_2.model
data class Pessoa(
val nome: String,
val cpf: String,
val nascimento: String,
val foto: String
)
| 0 | Kotlin | 0 | 0 | fe1cebc2da3cbbdc3c4a37c31fa602fe2b238d85 | 156 | Desenvolvimento-Android | MIT License |
editor/src/main/java/good/damn/editor/actions/VEDataActionSkeletonPoint.kt | GoodDamn | 850,249,504 | false | {"Kotlin": 68918, "Java": 700} | package good.damn.editor.actions
import good.damn.sav.core.skeleton.VESkeleton2D
class VEDataActionSkeletonPoint(
private val mSkeleton: VESkeleton2D
): VEIActionable {
override fun removeAction() {
mSkeleton.removeLast()
}
} | 0 | Kotlin | 0 | 1 | 7889c135f817b773958e4a5fcda1eeaaa9410505 | 249 | VectorEditorAndroid | MIT License |
app/src/main/java/com/xatixatix/clickerpilot/PlayerViewModel.kt | xatixatix | 720,718,816 | false | {"Kotlin": 14298} | package com.xatixatix.clickerpilot
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.xatixatix.clickerpilot.data.Player
import com.xatixatix.clickerpilot.data.PlayerDao
import kotlinx.coroutines.launch
class PlayerViewModel(private val playerDao: PlayerDao) : ViewModel() {
var players: LiveData<List<Player>> = playerDao.getPlayerList().asLiveData()
var currentPlayer: Player = Player(0, "empty", 0, 0)
fun isPlayerExistsByName(name: String): Boolean {
Log.i("Players", players.value.toString())
if (players.value?.isNotEmpty() == true) {
for (player in players.value!!) {
if (player.name == name) {
currentPlayer = player
return true
}
}
}
return false
}
fun createPlayer(player: Player) {
viewModelScope.launch {
playerDao.insert(player)
}
currentPlayer = player
Log.i("Player creation", "New player created.")
}
fun updatePlayer(player: Player) {
viewModelScope.launch {
playerDao.update(player)
}
}
}
class PlayerViewModelFactory(private val playerDao: PlayerDao) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(PlayerViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return PlayerViewModel(playerDao) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} | 0 | Kotlin | 0 | 0 | b8bb3af81a5f64a83b95ff56e2db831ba56478a1 | 1,728 | ClickerPilot | MIT License |
app/src/main/java/ac/uk/hope/osmviewerjetpack/data/external/fanarttv/repository/FanartTvRepositoryImpl.kt | movedaccount-droid | 796,686,976 | false | {"Kotlin": 132239} | package ac.uk.hope.osmviewerjetpack.data.external.fanarttv.repository
import ac.uk.hope.osmviewerjetpack.data.external.fanarttv.model.AlbumImages
import ac.uk.hope.osmviewerjetpack.data.external.fanarttv.model.ArtistImages
import ac.uk.hope.osmviewerjetpack.data.external.util.RateLimiter
import ac.uk.hope.osmviewerjetpack.data.local.fanarttv.dao.AlbumImagesDao
import ac.uk.hope.osmviewerjetpack.data.local.fanarttv.dao.ArtistImagesDao
import ac.uk.hope.osmviewerjetpack.data.local.fanarttv.model.AlbumImagesLocal
import ac.uk.hope.osmviewerjetpack.data.local.fanarttv.model.ArtistImagesLocal
import ac.uk.hope.osmviewerjetpack.data.network.fanarttv.FanartTvService
import ac.uk.hope.osmviewerjetpack.data.network.fanarttv.model.toLocal
import ac.uk.hope.osmviewerjetpack.data.network.fanarttv.responses.toLocal
import ac.uk.hope.osmviewerjetpack.di.DefaultDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import retrofit2.HttpException
class FanartTvRepositoryImpl(
private val albumImagesDao: AlbumImagesDao,
private val artistImagesDao: ArtistImagesDao,
private val service: FanartTvService,
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
): FanartTvRepository {
// implementing a rate limiter is awkward. who should have responsibility of ensuring fair use?
// if we implement a queue, we assume everyone using this repo wants their operations queued
// far in advance, but they might want to prioritize as availability arises.
// if more than two people were using this repo at once, divvying work between them becomes
// even more complicated. the ideal would probably be to submit tasks with some kind of tag,
// and only allow queuing of one type of task at a time. but that's way overboard for us
// instead we just assume users of this repo will avoid queuing too many tasks. not great
private val rateLimiter = RateLimiter(1000)
// get local first, and if not exists get from api
override fun getArtistImages(mbid: String): Flow<ArtistImages> {
return artistImagesDao.observe(mbid)
.mapNotNull { artistImages ->
if (artistImages == null) {
getArtistImagesFromNetwork(mbid)
}
artistImages
}
}
override fun getAlbumImages(mbid: String): Flow<AlbumImages> {
return albumImagesDao.observe(mbid)
.mapNotNull { albumImages ->
if (albumImages == null) {
getAlbumImagesFromNetwork(mbid)
}
albumImages
}
}
override suspend fun prune() {
artistImagesDao.prune()
albumImagesDao.prune()
}
private suspend fun getArtistImagesFromNetwork(mbid: String) {
withContext(dispatcher) {
rateLimiter.startOperation()
try {
val artistImages = service.getArtistImages(mbid).toLocal()
artistImages.albums?.let { albumImagesDao.upsertAll(it) }
artistImagesDao.upsert(artistImages.artist)
} catch (e: HttpException) {
if (e.code() == 404) {
// fanarttv has no data for this artist, insert empty
artistImagesDao.upsert(ArtistImagesLocal(mbid))
} else {
throw e
}
} finally {
rateLimiter.endOperationAndLimit()
}
}
}
private suspend fun getAlbumImagesFromNetwork(mbid: String) {
withContext(dispatcher) {
rateLimiter.startOperation()
var albumImages: AlbumImagesLocal
try {
albumImages = service.getAlbumImages(mbid).toLocal()
} catch (e: HttpException) {
if (e.code() == 404) {
albumImages = AlbumImagesLocal(mbid)
} else {
throw e
}
} finally {
rateLimiter.endOperationAndLimit()
}
albumImagesDao.upsert(albumImages)
}
}
} | 0 | Kotlin | 0 | 0 | 4e20bcf032ababf122f630172be46620fc9abbaf | 4,235 | osmviewerjetpack2 | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/ash/studios/musify/interfaces/IControl.kt | iyashasgowda | 281,011,774 | false | null | package com.ash.studios.musify.interfaces
interface IControl {
fun onPrevClicked()
fun onNextClicked()
fun onPlayClicked()
fun onPauseClicked()
} | 0 | null | 1 | 2 | 6528dbe87c5996937f109dacafac51bdec937595 | 162 | Musify | Apache License 2.0 |
core/src/commonTest/kotlin/dev/androidbroadcast/navstate/TestNavDestinations.kt | androidbroadcast | 805,457,712 | false | {"Kotlin": 37443} | package dev.androidbroadcast.navstate
import kotlinx.serialization.Serializable
sealed interface TestNavDestinations : NavDest {
@Serializable
data object Root : TestNavDestinations
@Serializable
data object DataList : TestNavDestinations
@Serializable
data class Details(val dataId: String) : TestNavDestinations
}
| 8 | Kotlin | 0 | 6 | 1297c0a86bb3abaf6191c0c83ac280595ecfa322 | 344 | NavState | Apache License 2.0 |
waypoints/src/main/kotlin/de/md5lukas/waypoints/config/integrations/BlueMapConfiguration.kt | Sytm | 211,378,928 | false | {"Gradle Kotlin DSL": 11, "Markdown": 16, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Kotlin": 179, "Java": 3, "YAML": 12, "TOML": 1, "INI": 1, "XML": 14} | package de.md5lukas.waypoints.config.integrations
import de.md5lukas.konfig.Configurable
@Configurable
class BlueMapConfiguration {
var enabled: Boolean = false
private set
}
| 2 | Kotlin | 7 | 28 | b31e54acb0cb8e93c9713492b1c1a0759f1045ed | 184 | waypoints | MIT License |
app/src/main/java/br/com/alarmcontroller/DestinationActivity.kt | Lu1sHenrique | 675,865,600 | false | null | package br.com.alarmcontroller
class DestinationActivity {
} | 0 | Kotlin | 0 | 0 | 3b61edc5a8ed963370b4dfd1b1194051eb4ad694 | 61 | alarmController | MIT License |
app/src/main/java/com/bitvolper/yogazzz/presentation/categorydetail/CategoryDetailApp.kt | sheikh-20 | 746,115,322 | false | {"Kotlin": 979402} | package com.bitvolper.yogazzz.presentation.categorydetail
import android.app.Activity
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import com.bitvolper.yogazzz.presentation.viewmodel.HomeViewModel
@Composable
fun CategoryDetailApp(modifier: Modifier = Modifier,
homeViewModel: HomeViewModel = hiltViewModel()) {
val yogaCategoryUIState by homeViewModel.yogaCategoryUIState.collectAsState()
Scaffold(
topBar = {
CategoryTopAppBar()
}
) { paddingValues ->
CategoryDetailScreen(yogaCategoryUIState = yogaCategoryUIState)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CategoryTopAppBar() {
val context = LocalContext.current
CenterAlignedTopAppBar(
title = {
},
navigationIcon = {
IconButton(onClick = { (context as Activity).finish() }) {
Icon(imageVector = Icons.Rounded.ArrowBack, contentDescription = null)
}
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = Color.Transparent)
)
} | 0 | Kotlin | 1 | 0 | 1afb7abb3932d9c4fc1d7b9371221fcc96061b34 | 1,853 | YogaApp | The Unlicense |
src/main/java/net/ccbluex/liquidbounce/features/module/modules/combat/criticals/normal/NoGroundCritical.kt | Rmejia39 | 733,988,804 | false | {"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926} | package net.ccbluex.liquidbounce.features.module.modules.combat.criticals.normal
import net.ccbluex.liquidbounce.event.AttackEvent
import net.ccbluex.liquidbounce.event.PacketEvent
import net.ccbluex.liquidbounce.features.module.modules.combat.criticals.CriticalMode
import net.ccbluex.liquidbounce.features.value.BoolValue
import net.ccbluex.liquidbounce.features.value.IntegerValue
import net.minecraft.network.play.client.C03PacketPlayer
class NoGroundCritical : CriticalMode("NoGround") {
private val autoJumpValue = BoolValue("${valuePrefix}AutoJump", false)
private val smartValue = BoolValue("${valuePrefix}Smart", true)
private val morePacketValue = BoolValue("${valuePrefix}MorePacket", false)
private val packetAmount = IntegerValue("${valuePrefix}PacketAmount", 2, 1, 5).displayable {morePacketValue.get()}
private var shouldEdit = false
override fun onEnable() {
if (autoJumpValue.get()) {
mc.thePlayer.jump()
}
}
override fun onAttack(event: AttackEvent) {
if (morePacketValue.get()) {
repeat(packetAmount.get()) {
shouldEdit = true
critical.sendCriticalPacket(ground = false)
shouldEdit = true //make sure to modify one more C03 after attack.
}
} else {
shouldEdit = true
}
}
override fun onPacket(event: PacketEvent) {
if(event.packet is C03PacketPlayer) {
if (smartValue.get()){
if (shouldEdit) {
event.packet.onGround = false
shouldEdit = false
}
} else {
event.packet.onGround = false
}
}
}
}
| 3 | Kotlin | 0 | 0 | b48c4e83c888568111a6665037db7fd3f7813ed3 | 1,739 | FDPClient | MIT License |
app/src/main/java/com/ayoprez/sobuu/presentation/authentication/login/LoginState.kt | AyoPrez | 542,163,912 | false | {"Kotlin": 531589} | package com.ayoprez.sobuu.presentation.authentication.login
import com.ayoprez.sobuu.shared.features.authentication.remote.AuthenticationError
data class LoginState(
val isLoading: Boolean = false,
val loginUsername: String = "",
val loginPassword: String = "",
val error: AuthenticationError? = null,
)
| 0 | Kotlin | 0 | 0 | d3d9adb6b69abe87c03d94eefcbeaa1c80708f1f | 322 | sobuu | Apache License 2.0 |
src/main/kotlin/com/redgrapefruit/goldenforge/client/GoldenForgeClient.kt | kanpov | 448,509,507 | false | {"Kotlin": 68570} | package com.redgrapefruit.goldenforge.client
import com.redgrapefruit.goldenforge.init.ModMenus
import net.fabricmc.api.ClientModInitializer
object GoldenForgeClient : ClientModInitializer {
override fun onInitializeClient() {
ModMenus.initializeClient()
}
}
| 0 | Kotlin | 0 | 0 | 53a573111334ad4e1f12a23224bf292822d74e02 | 277 | GoldenForge | MIT License |
domain/src/commonMain/kotlin/uk/co/sentinelweb/cuer/domain/SearchRemoteDomain.kt | sentinelweb | 220,796,368 | false | {"Kotlin": 2627352, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170} | package uk.co.sentinelweb.cuer.domain
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
//import java.time.LocalDateTime
@Serializable
data class SearchRemoteDomain(
var text: String? = null,
var platform: PlatformDomain = PlatformDomain.YOUTUBE,
var relatedToMediaPlatformId: String? = null,
var relatedToMediaTitle: String? = null,
var channelPlatformId: String? = null,
var isLive: Boolean = false,
@Contextual var fromDate: LocalDateTime? = null,
@Contextual var toDate: LocalDateTime? = null,
val lang: String = "en",
val order: Order = Order.RATING
) : Domain {
enum class Order { RELEVANCE, RATING, VIEWCOUNT, DATE, TITLE }
} | 94 | Kotlin | 0 | 2 | f74e211570fe3985ba45848b228e91a3a8593788 | 749 | cuer | Apache License 2.0 |
Section 07 - Controle de Fluxo/Projects/ReforcarAprendizadoIfElse/src/Questao2.kt | vilaJJ | 861,494,712 | false | {"Kotlin": 70466, "Java": 1627} | import Utils.*
fun main() {
val leitura1 = realizarLeitura("Insira o primeiro valor:")
val leitura2 = realizarLeitura("Insira o segundo valor:")
val leitura3 = realizarLeitura("Insira o terceiro valor:")
val numero1 = converterParaInteiro(leitura1)
val numero2 = converterParaInteiro(leitura2)
val numero3 = converterParaInteiro(leitura3)
if (numero1 == null || numero2 == null || numero3 == null) {
println("Valores inválidos apresentados.")
return
}
val isEquilatero = isEquilatero(numero1, numero2, numero3)
val resultado = when (isEquilatero) {
true -> "É um triângulo equilátero, os lados são iguais."
false -> "Não é um triângulo equilátero, os lados são diferentes."
}
println("\n$resultado")
}
fun isEquilatero(lado1: Number, lado2: Number, lado3: Number) =
lado1 == lado2 && lado2 == lado3 | 0 | Kotlin | 0 | 0 | 9cd55ab7b1de7a4af802a0eb8212da6b70506998 | 889 | Course_AndroidKotlinDevelopment_GF | The Unlicense |
feature/player/src/commonMain/kotlin/com/andannn/melodify/feature/player/ui/shrinkable/bottom/queue/PlayQueueView.kt | andannn | 583,624,480 | false | {"Kotlin": 364396, "Swift": 621} | package com.andannn.melodify.feature.player.ui.shrinkable.bottom.queue
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.andannn.melodify.feature.common.component.ListTileItemView
import com.andannn.melodify.core.data.model.AudioItemModel
import com.andannn.melodify.feature.common.util.rememberSwapListState
import io.github.aakira.napier.Napier
import kotlinx.collections.immutable.ImmutableList
import sh.calvin.reorderable.ReorderableCollectionItemScope
import sh.calvin.reorderable.ReorderableItem
private const val TAG = "PlayQueueView"
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun PlayQueue(
onItemClick: (AudioItemModel) -> Unit,
onSwapFinished: (from: Int, to: Int) -> Unit,
onDeleteFinished: (Int) -> Unit,
playListQueue: ImmutableList<AudioItemModel>,
activeMediaItem: AudioItemModel,
modifier: Modifier = Modifier
) {
val playQueueState = rememberSwapListState<AudioItemModel>(
onSwapFinished = { from, to, _ ->
Napier.d(tag = TAG) { "PlayQueueView: drag stopped from $from to $to" }
onSwapFinished(from, to)
},
onDeleteFinished = { index, _ ->
Napier.d(tag = TAG) { "onDeleteFinished $index" }
onDeleteFinished(index)
}
)
LaunchedEffect(playListQueue) {
playQueueState.onApplyNewList(playListQueue)
}
LazyColumn(
modifier = modifier
.fillMaxWidth(),
state = playQueueState.lazyListState
) {
items(
items = playQueueState.itemList,
key = { it.hashCode() },
) { item ->
ReorderableItem(
state = playQueueState.reorderableLazyListState,
key = item.hashCode()
) { _ ->
QueueItem(
item = item,
isActive = item.extraUniqueId == activeMediaItem.extraUniqueId,
onClick = {
onItemClick(item)
},
onSwapFinish = {
playQueueState.onStopDrag()
},
onDismissFinish = {
playQueueState.onDeleteItem(item)
}
)
}
}
}
}
@Composable
private fun ReorderableCollectionItemScope.QueueItem(
item: AudioItemModel,
isActive: Boolean,
modifier: Modifier = Modifier,
onSwapFinish: () -> Unit = {},
onClick: () -> Unit = {},
onDismissFinish: () -> Unit = {}
) {
val dismissState = rememberSwipeToDismissBoxState()
var dismissed by remember {
mutableStateOf(false)
}
LaunchedEffect(dismissState.currentValue) {
if (dismissed) return@LaunchedEffect
val state = dismissState.currentValue
if (state == SwipeToDismissBoxValue.EndToStart || state == SwipeToDismissBoxValue.StartToEnd) {
onDismissFinish()
dismissed = true
}
}
SwipeToDismissBox(
state = dismissState,
backgroundContent = {
Spacer(modifier = Modifier)
}
) {
ListTileItemView(
modifier = modifier,
swapIconModifier = Modifier.draggableHandle(
onDragStopped = onSwapFinish
),
isActive = isActive,
defaultColor = MaterialTheme.colorScheme.surfaceContainerHighest,
albumArtUri = item.artWorkUri,
title = item.name,
showTrackNum = false,
subTitle = item.artist,
trackNum = item.cdTrackNumber,
onMusicItemClick = onClick,
)
}
}
| 9 | Kotlin | 0 | 0 | 574de6131bfae87a7c8b7f33a78c47cc0e75693c | 4,402 | Melodify | Apache License 2.0 |
app/src/main/java/com/ptwelvebreeze/app/domain/RuleTemplateEntity.kt | DebashisINT | 652,463,111 | false | {"Kotlin": 14682688, "Java": 1020861} | package com.ptwelvebreeze.app.domain
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.ptwelvebreeze.app.AppConstant
@Entity(tableName = AppConstant.RULE_TEMPLATE)
data class RuleTemplateEntity (
@PrimaryKey(autoGenerate = true) var sl_no: Int = 0,
@ColumnInfo var rule_template_id:Int = 0,
@ColumnInfo var rule_template_name:String = ""
) | 0 | Kotlin | 0 | 0 | 875efe9e6028c9440cc8648183a8f1d2f5e89b0c | 406 | StepUpP12 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.