path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/chatsupport/activity/SpecificThread.kt
|
prathmesh444
| 716,429,070
| false
|
{"Kotlin": 21873}
|
package com.example.chatsupport.activity
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.chatsupport.R
import com.example.chatsupport.adaptor.SpecificThreadAdapter
import com.example.chatsupport.dao.ChatDao
import com.example.chatsupport.dao.OutgoingMessageDao
import com.example.chatsupport.utilis.Constants
import com.example.chatsupport.utilis.Resource
import com.example.chatsupport.utilis.SharedPreferences
import com.example.chatsupport.viewModel.NetworkViewModel
import java.sql.Timestamp
import java.time.Instant
import java.util.Date
class SpecificThread : AppCompatActivity(){
private lateinit var _recyclerView: RecyclerView
private lateinit var _inputMessage: EditText
private lateinit var _sendButton: Button
private lateinit var _mAdapter: SpecificThreadAdapter
private lateinit var _header:Map<String,String>
private val _dataList: MutableList<ChatDao> = mutableListOf<ChatDao>()
private val viewmodel = NetworkViewModel()
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.specific_messages_layout)
_recyclerView = findViewById(R.id.specificRecyclerView)
_inputMessage = findViewById(R.id.InputMessageText)
_sendButton = findViewById(R.id.buttonSend)
_header = mapOf(Constants.HEADER to SharedPreferences.get(Constants.LOGIN_AUTH,this))
val data = Constants.MSGLIST
val threadID = intent.extras?.getString("thread_id")
val position = intent.extras?.getInt("position")
print(data[threadID])
data[threadID]?.forEach {
val userTimestamp = Timestamp.from(Instant.parse(it.timestamp))
if(it.agent_id == null) {
_dataList.add(ChatDao(it.thread_id, it.user_id, true, it.body, userTimestamp))
}
else {
_dataList.add(ChatDao(it.thread_id, it.agent_id, false, it.body, userTimestamp))
}
}
_recyclerView.layoutManager = LinearLayoutManager(this)
_mAdapter = SpecificThreadAdapter(_dataList)
_recyclerView.adapter = _mAdapter
_sendButton.setOnClickListener {
val message = _inputMessage.text.toString().trim()
if (message.isNotEmpty()) {
viewmodel.sendMessages(_header, OutgoingMessageDao(threadID!!, message))
setObservers()
}
_inputMessage.text.clear()
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun setObservers() {
viewmodel.sendData.observe(this){ resource ->
when(resource){
is Resource.Error -> Toast.makeText(this, "Error Sending the Messages", Toast.LENGTH_SHORT).show()
is Resource.Loading -> Toast.makeText(this, "Loading", Toast.LENGTH_SHORT).show()
is Resource.Success -> {
resource.data?.let { it ->
val agenttimestamp: Date? = Timestamp.from(Instant.parse(it.timestamp))
_dataList.add(ChatDao(it.thread_id, it.agent_id, false, it.body, agenttimestamp))
_dataList.sortBy { it.time }
_mAdapter.notifyDataSetChanged()
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a8e9e9dae99287b958fcf7c31744c010ab6afffc
| 3,662
|
Customer-Support-Chat-App
|
MIT License
|
app/src/main/java/com/project/resqfood/presentation/itemdetailscreen/SuccessScreen.kt
|
sourabhkumar47
| 796,387,014
| false
|
{"Kotlin": 250041}
|
package com.project.resqfood.presentation.itemdetailscreen
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.TextStyle
import com.project.resqfood.R
@Composable
fun SuccessScreen(
buttonText: String,
onClick: () -> Unit,
animationJsonResId: Int,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Lottie Animation
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.RawRes(animationJsonResId)
)
val progress by animateLottieCompositionAsState(
composition = composition,
iterations = Int.MAX_VALUE
)
LottieAnimation(
composition = composition,
progress = progress,
modifier = Modifier
.padding(16.dp)
.size(200.dp)
)
Spacer(modifier = Modifier.height(32.dp))
Text(text = "Success!", style = MaterialTheme.typography.headlineMedium)
Spacer(modifier = Modifier.height(32.dp))
// Button
Button(
onClick = onClick,
modifier = Modifier.padding(16.dp)
.fillMaxWidth(0.8f),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
) {
Text(text = buttonText, color = Color.White)
}
}
}
@Preview
@Composable
fun PreviewSuccessScreen() {
SuccessScreen(
buttonText = "Continue",
onClick = {},
animationJsonResId = R.raw.successanimation
)
}
| 29
|
Kotlin
|
37
| 19
|
f9123342a39e2e3eeed88fd61bf2a9a2d68da951
| 2,413
|
ResQFood
|
MIT License
|
app/src/main/java/com/task/noteapp/features/notes/domain/NotesRepository.kt
|
faranjit
| 441,673,624
| false
|
{"Kotlin": 51756}
|
package com.task.noteapp.features.notes.domain
import com.task.noteapp.features.notes.domain.model.CreateNoteModel
import com.task.noteapp.features.notes.domain.model.NoteModel
import kotlinx.coroutines.flow.Flow
/**
* Created by <NAME> on 29.09.2021.
*/
interface NotesRepository {
/**
* Returns all notes with edit history
*/
fun getNotes(): Flow<List<NoteModel>>
/**
* Creates a new note entity in db
*/
suspend fun createNote(noteModel: CreateNoteModel)
/**
* Updates the note entity in db
*/
suspend fun editNote(noteModel: CreateNoteModel)
suspend fun deleteNote(noteId: Long)
}
| 0
|
Kotlin
|
0
| 2
|
572eea5c62ad077a89e4ad664b6535ae86f7e534
| 650
|
note-flow
|
MIT License
|
app/src/main/java/com/comunidadedevspace/imc/MainActivity.kt
|
denismorello
| 808,745,245
| false
|
{"Kotlin": 4741}
|
package com.comunidadedevspace.imc
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Recuperar os componenetes EditText
//Criar uma variável e associar o componente de UI<TextInputEditText>
//Recuperar botao da tela
//Colocar a acao no botao SetOnClickListener
//Recuperar o texto digitado no edt_peso
val edtPeso = findViewById<TextInputEditText>(R.id.edt_peso)
val edtAltura = findViewById<TextInputEditText>(R.id.edt_altura)
val btnCalcular = findViewById<Button>(R.id.btn_calcular)
btnCalcular.setOnClickListener {
val pesoStr: String = edtPeso.text.toString()
val alturaStr: String = edtAltura.text.toString()
if(pesoStr == "" || alturaStr == ""){
//Mostrar mensagem para usuario
Snackbar.make(
edtPeso,
"Preencha todos os campos",
Snackbar.LENGTH_LONG
)
.show()
}else{
val peso = pesoStr.toFloat()
val altura = alturaStr.toFloat()
val alturaQ2 = altura * altura
val resultado = peso / alturaQ2
//Navegar para proxima tela
//Criar o layout da proxima tela
//Passar dados (resultado) para proxima tela
//Intent - Classe do proprio Android
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra(KEY_RESULT_IMC, resultado)
startActivity(intent)
//Cores
//Edit Text background
//Gradiente + icone + titulo
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d0635046a5be9dc670b62931df78730fef7f8d24
| 2,130
|
calculadoraimc
|
MIT License
|
src/main/kotlin/herbaccara/jusokr/model/PageableCommon.kt
|
herbaccara
| 608,484,828
| false
| null |
package herbaccara.jusokr.model
class PageableCommon(
/**
* 에러코드. 0 이면 정상, -999 면 시스템 에러
*/
errorCode: String,
errorMessage: String,
val currentPage: Int,
val countPerPage: Int,
totalCount: Int
) : Common(errorCode, errorMessage, totalCount)
| 0
|
Kotlin
|
0
| 0
|
1c3250a0ddff944f3e3ec9b5f0a3abd8026636ee
| 277
|
spring-boot-starter-jusokr
|
MIT License
|
app/src/main/java/io/flaterlab/kyrgyzdaamy/ui/food/FoodAddToBasket.kt
|
chorobaev
| 355,274,946
| false
|
{"Kotlin": 168085}
|
package io.flaterlab.kyrgyzdaamy.ui.food
import io.flaterlab.kyrgyzdaamy.service.response.MenuItem
interface FoodAddToBasket {
fun addToBasket(item: MenuItem, position: Int)
}
| 0
|
Kotlin
|
0
| 1
|
a1c17e42cefdf0536f4e1b9c235e0f434b9a1e58
| 181
|
kyrgyz-daamy
|
MIT License
|
src/main/kotlin/dev/himirai/kiyomi/annotation/PostConstruct.kt
|
Himirai
| 804,927,408
| false
|
{"Kotlin": 10780}
|
package dev.himirai.kiyomi.annotation
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class PostConstruct
| 0
|
Kotlin
|
0
| 2
|
87a09740884ae0f696ffffef47be593b3f05593c
| 145
|
kiyomi
|
Apache License 2.0
|
redwood-layout-uiview/src/commonTest/kotlin/app/cash/redwood/layout/uiview/UIViewBoxTest.kt
|
cashapp
| 305,409,146
| false
|
{"Kotlin": 2084287, "Swift": 20654, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129}
|
/*
* Copyright (C) 2024 Square, 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 app.cash.redwood.layout.uiview
import app.cash.redwood.layout.AbstractBoxTest
import app.cash.redwood.layout.widget.Box
import app.cash.redwood.snapshot.testing.UIViewSnapshotCallback
import app.cash.redwood.snapshot.testing.UIViewSnapshotter
import app.cash.redwood.snapshot.testing.UIViewTestWidgetFactory
import app.cash.redwood.snapshot.testing.isEqualTo
import assertk.assertThat
import kotlin.test.Test
import platform.CoreGraphics.CGSizeMake
import platform.UIKit.UIColor
import platform.UIKit.UIView
class UIViewBoxTest(
private val callback: UIViewSnapshotCallback,
) : AbstractBoxTest<UIView>() {
override val widgetFactory = UIViewTestWidgetFactory
override fun box(): Box<UIView> {
return UIViewBox().apply {
value.backgroundColor = UIColor(red = 0.0, green = 0.0, blue = 0.0, alpha = 0.5)
}
}
override fun snapshotter(widget: UIView) = UIViewSnapshotter.framed(callback, widget)
@Test
fun maxEachDimension() {
assertThat(
maxEachDimension(
CGSizeMake(5.0, 10.0),
CGSizeMake(8.0, 4.0),
),
).isEqualTo(8.0, 10.0)
assertThat(
maxEachDimension(
CGSizeMake(8.0, 4.0),
CGSizeMake(5.0, 10.0),
),
).isEqualTo(8.0, 10.0)
assertThat(
maxEachDimension(
CGSizeMake(8.0, 10.0),
CGSizeMake(5.0, 4.0),
),
).isEqualTo(8.0, 10.0)
assertThat(
maxEachDimension(
CGSizeMake(5.0, 4.0),
CGSizeMake(8.0, 10.0),
),
).isEqualTo(8.0, 10.0)
}
}
| 111
|
Kotlin
|
72
| 1,641
|
edeabb17a1b69d5255cf0bbeb442893d65667f2b
| 2,123
|
redwood
|
Apache License 2.0
|
app/src/main/java/foxapple/android/finacial/utilities/Constants.kt
|
foxapple
| 210,019,108
| false
| null |
package foxapple.android.finacial.utilities
const val DATABASE_NAME = "finacial-watch-db"
| 0
|
Kotlin
|
0
| 0
|
8543a644ed86acc5cdb2f7ba313cf9aa487efd67
| 90
|
finacialWatch
|
MIT License
|
modules/vfs/src/main/kotlin/com/lhwdev/vfs/impl/common/VfsCommon.kt
|
lhwdev
| 412,778,971
| false
|
{"Kotlin": 64983}
|
package com.lhwdev.vfs.impl.common
public object VfsCommon
| 0
|
Kotlin
|
0
| 0
|
0f3c0ae152d4bb10e7883cb0fa6dc35fe08edcfb
| 61
|
lhwdev-bot
|
MIT License
|
projects/simulation/src/main/kotlin/simulation/abilities/ShadowSpirit.kt
|
silentorb
| 188,621,122
| false
|
{"Kotlin": 862571, "Python": 32172, "SuperCollider": 5214, "Faust": 528}
|
package simulation.abilities
import com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld
import silentorb.mythic.characters.rigs.disableFreedomsBuff
import silentorb.mythic.characters.rigs.defaultCharacterHeight
import silentorb.mythic.characters.rigs.defaultCharacterRadius
import silentorb.mythic.ent.Id
import silentorb.mythic.happenings.DeleteEntityEvent
import silentorb.mythic.happenings.Events
import silentorb.mythic.performing.ActionDefinition
import silentorb.mythic.physics.*
import silentorb.mythic.scenery.Capsule
import silentorb.mythic.spatial.Matrix
import silentorb.mythic.spatial.Vector3
import silentorb.mythic.timing.FloatTimer
import simulation.accessorize.Accessory
import simulation.characters.characterDynamicBody
import simulation.characters.commonCharacterElements
import simulation.characters.newAccessory
import simulation.entities.PlayerRigEvent
import simulation.main.Deck
import simulation.main.NewHand
import simulation.main.World
import simulation.physics.CollisionGroups
const val shadowSpiritBuff = "shadowSpiritBuff"
fun shadowSpiritPlacementOffset(dynamicsWorld: btDiscreteDynamicsWorld, collisionObject: CollisionObject, transform: Matrix): Vector3 {
val shape = createCollisionShape(collisionObject.shape, Vector3.unit)
val bulletBody = createBulletDynamicObject(transform, characterDynamicBody, shape, false)
dynamicsWorld.addRigidBody(bulletBody, collisionObject.groups, collisionObject.mask)
// dynamicsWorld.applySpeculativeContactRestitution = false
// dynamicsWorld.stepSimulation(1f / 60f, 10)
val newLocation = toVector3(bulletBody.worldTransform.getTranslation(com.badlogic.gdx.math.Vector3()))
dynamicsWorld.removeRigidBody(bulletBody)
bulletBody.release()
return newLocation - transform.translation()
}
fun onShadowSpirit(world: World, actionDefinition: ActionDefinition, actor: Id): Events {
val nextId = world.nextId.source()
val shadowSpirit = nextId()
val deck = world.deck
val realBody = deck.bodies[actor]!!
val realRig = deck.characterRigs[actor]!!
val position = realBody.position + Vector3(0.4f, 0f, 0f)
.transform(Matrix.identity.rotateZ(realRig.facingRotation.x))
val angle = realRig.facingRotation.x
val collisionObject = CollisionObject(
shape = Capsule(defaultCharacterRadius, defaultCharacterHeight),
groups = CollisionGroups.spirit,
mask = CollisionGroups.spiritMask
)
return listOf(
NewHand(
id = shadowSpirit,
components = commonCharacterElements(position, angle, 10f) + listOf(
collisionObject,
)
),
NewHand(
components = listOf(
Accessory(
type = shadowSpiritBuff,
owner = actor,
),
FloatTimer(10f)
),
),
newAccessory(world.definitions, Actions.cancelShadowSpirit, shadowSpirit),
PlayerRigEvent(
player = actor,
rig = shadowSpirit,
)
)
}
fun removeShadowSpirit(actor: Id, spiritActor: Id?): Events =
listOfNotNull(
if (spiritActor != null && spiritActor != actor)
DeleteEntityEvent(spiritActor)
else
null,
PlayerRigEvent(
player = actor,
rig = actor,
)
)
fun onCancelShadowSpirit(deck: Deck, spiritActor: Id): Events {
val player = deck.players.entries.firstOrNull { it.value.rig == spiritActor }?.key
return if (player == null)
listOf()
else
deck.accessories
.filter { it.value.owner == player && it.value.type == shadowSpiritBuff }
.map { (key) -> DeleteEntityEvent(key) } +
NewHand(
components = listOf(
Accessory(
type = disableFreedomsBuff,
owner = player,
),
FloatTimer(0.2f)
),
)
}
fun eventsFromShadowSpiritRemoval(previousDeck: Deck, world: World): Events {
val removedBuffs = previousDeck.accessories.filter { (id, accessory) ->
!world.deck.accessories.containsKey(id) && accessory.type == shadowSpiritBuff
}
return removedBuffs.flatMap { (id, accessory) ->
val actor = accessory.owner!!
val spiritRig = previousDeck.players[actor]?.rig
removeShadowSpirit(actor, spiritRig)
}
}
| 0
|
Kotlin
|
0
| 0
|
03a1e2c082343ee3d64c8d1ffadad156fca6f9e1
| 4,312
|
marloth-kotlin
|
MIT License
|
src/main/kotlin/org/wfanet/measurement/common/grpc/DeferredForwardingListener.kt
|
world-federation-of-advertisers
| 375,798,604
| false
| null |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.grpc
import io.grpc.ServerCall
/**
* gRPC [ServerCall.Listener] that defers forwarding events to a delegate until [setDelegate] is
* called.
*/
class DeferredForwardingListener<ReqT> : ServerCall.Listener<ReqT>() {
private lateinit var delegate: ServerCall.Listener<ReqT>
private val events = arrayListOf<Runnable>()
@Synchronized
override fun onMessage(message: ReqT) {
if (!this::delegate.isInitialized) {
events.add { delegate.onMessage(message) }
} else {
delegate.onMessage(message)
}
}
@Synchronized
override fun onHalfClose() {
if (!this::delegate.isInitialized) {
events.add { delegate.onHalfClose() }
} else {
delegate.onHalfClose()
}
}
@Synchronized
override fun onCancel() {
if (!this::delegate.isInitialized) {
events.add { delegate.onCancel() }
} else {
delegate.onCancel()
}
}
@Synchronized
override fun onComplete() {
if (!this::delegate.isInitialized) {
events.add { delegate.onComplete() }
} else {
delegate.onComplete()
}
}
@Synchronized
override fun onReady() {
if (!this::delegate.isInitialized) {
events.add { delegate.onReady() }
} else {
delegate.onReady()
}
}
@Synchronized
fun setDelegate(delegate: ServerCall.Listener<ReqT>) {
this.delegate = delegate
events.forEach { it.run() }
events.clear()
}
}
| 3
|
Kotlin
|
0
| 1
|
91b8802bb7f6a1db6cedcc3d623771c12dc136bf
| 2,060
|
common-jvm
|
Apache License 2.0
|
linea/src/commonMain/kotlin/compose/icons/lineaicons/basic/BatteryCharge.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.lineaicons.basic
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 compose.icons.lineaicons.BasicGroup
public val BasicGroup.BatteryCharge: ImageVector
get() {
if (_batteryCharge != null) {
return _batteryCharge!!
}
_batteryCharge = Builder(name = "BatteryCharge", defaultWidth = 64.0.dp, defaultHeight =
64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(1.0f, 21.0f)
horizontalLineToRelative(58.0f)
verticalLineToRelative(24.0f)
horizontalLineToRelative(-58.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(59.0f, 27.0f)
lineToRelative(4.0f, 0.0f)
lineToRelative(0.0f, 12.0f)
lineToRelative(-4.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 25.0f)
horizontalLineToRelative(50.0f)
verticalLineToRelative(16.0f)
horizontalLineToRelative(-50.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(22.0f, 33.0f)
lineToRelative(7.0f, -3.0f)
lineToRelative(0.0f, 6.0f)
lineToRelative(7.0f, -3.0f)
}
}
.build()
return _batteryCharge!!
}
private var _batteryCharge: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,961
|
compose-icons
|
MIT License
|
common/src/commonMain/kotlin/com/nordeck/app/worldle/common/model/Guess.kt
|
ameriod
| 494,662,375
| false
|
{"Kotlin": 50860, "Swift": 17503, "Shell": 89}
|
package com.nordeck.app.worldle.common.model
import com.nordeck.app.worldle.common.ConversionMath
import com.nordeck.app.worldle.common.isLocaleMetric
data class Guess(
val country: Country,
val distanceFromMeters: Int,
val proximityPercent: Int,
val direction: Direction
) {
fun getDistanceFrom(): String {
return if (isLocaleMetric()) {
"${(ConversionMath.metersToKilometers(distanceFromMeters))} km"
} else {
"${(ConversionMath.metersToMiles(distanceFromMeters))} mi"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c9b99d045a1910e8d00e559af536b4714c4b3e02
| 551
|
Worldle-Mobile
|
MIT License
|
gateway/src/test/kotlin/com/qingzhu/gateway/TestCoroutine.kt
|
nedphae
| 322,789,778
| false
|
{"Kotlin": 744301, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375}
|
package com.qingzhu.gateway
import com.qingzhu.gateway.config.SecurityConfiguration
import kotlinx.coroutines.*
import org.junit.jupiter.api.Test
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class TestCoroutine {
@Test
fun testCoroutine() {
val launch = GlobalScope.launch {
// 在后台启动一个新的协程并继续
delay(1000L) // 非阻塞的等待 1 秒钟(默认时间单位是毫秒)
println("World!") // 在延迟后打印输出
}
println("Hello,") // 协程已在等待时主线程还在继续
Thread.sleep(1000L) // 阻塞主线程 1 秒钟来保证 JVM 存活
runBlocking {
// 但是这个表达式阻塞了主线程
launch.join() // 等待 launch 结束
delay(1000L) // ……我们延迟 1 秒来保证 JVM 的存活
}
val (_, b) = getPair()
println(b)
}
@Test
fun testFlux() {
val reactiveJwtDecoder = SecurityConfiguration().reactiveJwtDecoder()
val decode =
reactiveJwtDecoder.decode("<KEY>")
decode.map { it.claims["organizationId"] as Long }
.subscribe {
println(it)
}
}
@Test
fun testFluxWithoutSubscribe() {
val reactiveJwtDecoder = SecurityConfiguration().reactiveJwtDecoder()
val decode =
reactiveJwtDecoder.decode("<KEY>")
decode.map { it.claims["organizationId"] as Long }
.map {
println(it)
}
.subscribe()
}
@InternalCoroutinesApi
@Test
fun testCoroutineWithFlux() {
val reactiveJwtDecoder = SecurityConfiguration().reactiveJwtDecoder()
runBlocking {
setParams(reactiveJwtDecoder)
}
}
@InternalCoroutinesApi
private suspend fun setParams(reactiveJwtDecoder: ReactiveJwtDecoder) =
suspendCancellableCoroutine { cont: CancellableContinuation<Unit> ->
// val decode = reactiveJwtDecoder.decode("<KEY>")
// decode.map { it.claims["organizationId"] as Long }
// .subscribe {
// println(it)
// }
Thread({
println("新线程睡眠")
cont.tryResumeWithException(TimeoutException("消息超时"))?.let { cont.completeResume(it) }
cont.tryResumeWithException(TimeoutException("消息超时"))?.let { cont.completeResume(it) }
if (cont.isActive) cont.resumeWithException(TimeoutException("消息超时"))
if (cont.isActive) cont.resumeWithException(TimeoutException("消息超时"))
Thread.sleep(10000L)
println("睡眠结束")
if (cont.isActive) cont.resume(Unit)
}).start()
}
@Test
fun testAsync() {
runBlocking {
val result = async {
Thread({
println("新线程睡眠")
Thread.sleep(10000L)
println("睡眠结束")
}).start()
}
result.await()
}
}
private fun getPair(): Pair<String, String> {
return Pair("Hello", "World!")
}
}
| 1
|
Kotlin
|
18
| 42
|
217b4658508763133e1a5b6a96763a14e9f6f4ad
| 3,168
|
contact-center
|
Apache License 2.0
|
data/src/main/java/com/pp/moviefy/data/di/DataModule.kt
|
pauloaapereira
| 356,418,263
| false
| null |
/*
* Copyright 2021 Paulo Pereira
*
* 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.pp.moviefy.data.di
import com.pp.moviefy.data.remote.account.api.AccountDao
import com.pp.moviefy.data.remote.auth.api.AuthDao
import com.pp.moviefy.data.remote.certifications.api.CertificationsDao
import com.pp.moviefy.data.remote.collections.api.CollectionsDao
import com.pp.moviefy.data.remote.lists.api.ListsDao
import com.pp.moviefy.data.remote.movies.api.MoviesDao
import com.pp.moviefy.data.remote.persons.api.PersonsDao
import com.pp.moviefy.data.remote.tv.api.TvDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
@Module
@InstallIn(SingletonComponent::class)
object DataModule {
@Provides
fun provideCertificationsDao(@V3Api retrofit: Retrofit): CertificationsDao {
return retrofit.create(CertificationsDao::class.java)
}
@Provides
fun provideCollectionsDao(@V3Api retrofit: Retrofit): CollectionsDao {
return retrofit.create(CollectionsDao::class.java)
}
@Provides
fun provideMoviesDao(@V3Api retrofit: Retrofit): MoviesDao {
return retrofit.create(MoviesDao::class.java)
}
@Provides
fun provideTvDao(@V3Api retrofit: Retrofit): TvDao {
return retrofit.create(TvDao::class.java)
}
@Provides
fun providePersonsDao(@V3Api retrofit: Retrofit): PersonsDao {
return retrofit.create(PersonsDao::class.java)
}
@Provides
fun provideAuthDao(@V4Api retrofit: Retrofit): AuthDao {
return retrofit.create(AuthDao::class.java)
}
@Provides
fun provideAccountDao(@V4Api retrofit: Retrofit): AccountDao {
return retrofit.create(AccountDao::class.java)
}
@Provides
fun provideListsDao(@V4Api retrofit: Retrofit): ListsDao {
return retrofit.create(ListsDao::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
e174b88ab2397720c47f81c06603794e142bd91f
| 2,447
|
Moviefy
|
Apache License 2.0
|
src/test/kotlin/complex-3D/src/Complex3D.kt
|
exerro
| 160,990,895
| false
| null |
import lwaf_3D.*
import lwaf_3D.poly.VAOObject3D
import lwaf_3D.poly.loadOBJModel
import lwaf_3D.poly.toUVVAOObject3D
import lwaf_3D.poly.toVAOObject3D
import lwaf_3D.property.*
import lwaf_core.*
import lwaf_util.noise
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL11.*
private lateinit var texture2D: GLTexture
private lateinit var context3D: DrawContext3D
private var textureToDraw = 0
private lateinit var view: GLView
private lateinit var context2D: DrawContext2D
private val objects = ArrayList<Object3D>()
private var t = 0f
fun loadModels() {
val noTextureLight = loadResource("No texture light") { ->
loadTextureFromInputStream(GLTexture::class.java.getResourceAsStream("/res/img/no-texture-light.png"), "no-texture-light.png")
}
for (i in 0..4) {
objects.add(Sphere().toVAOObject3D(i + 1)
.translateTo(i * 2.5f, -3f, -2f))
}
for (i in 0..9) {
for (j in 0..9) {
objects.add(Sphere(0.8f).toUVVAOObject3D(i + 3, j + 1, Material()
.setTexture(loadResource("example/complex-3D/res/img/2k_earth_daymap.png", ::loadTexture))
.setSpecularLightingIntensity(0f))
.translateTo(18 - i * 2f, 18 - j * 2f, -5f))
}
}
objects.add(Sphere(1f).toVAOObject3D(1, Material()
.setColour(0f, 1f, 1f))
.translateTo(0f, 0f, 0f))
objects.add(Box().toVAOObject3D(Material()
.setTexture(noTextureLight))
.translateBy(vec3(2f, 0f, 0f)))
// .setTranslation(2f, 0f, 0f)
objects.add(Sphere().toUVVAOObject3D(60, 40, Material()
.setTexture(loadResource("example/complex-3D/res/img/2k_earth_daymap.png", ::loadTexture)))
.translateTo(4f, 0f, 0f))
objects.add(Sphere().toVAOObject3D(7, Material()
.setColour(1f, 1f, 0f))
.translateTo(6f, 0f, 0f))
objects.add(VAOObject3D(LegacyConeVAO(360))
.translateTo(-2f, 0f, 0f))
objects.add(VAOObject3D(LegacyCylinderVAO(100))
.translateTo(-2f, 2f, 0f))
objects.add(VAOObject3D(LegacyPyramidVAO(4))
.translateTo(-2f, 4f, 0f))
objects.add(Box().toVAOObject3D().translateTo(0f, -10f, 11f))
objects.add(Box().toVAOObject3D().translateTo(10f, -10f, 11f))
val graph = Graph3D { v ->
// (float) 1 / (0.1f + v.length())
Math.sin((1 / (1 + v.length2() / 2) * 25 + 10 * v.y / 2).toDouble()).toFloat()
}
.setColouring { (x, y, z) -> vec3(0.5f + y * 0.5f, vec2(x, z).length(), 1f - y * 0.5f) }
val scale = vec3(5f, 1f, 5f)
val res = 50
objects.add(VAOObject3D(graph.getTriangulatedVAO(false, Graph3D.UniformGridStrategy(res)))
.translateTo(scale.x + 1, -10f, scale.x + 1).scaleTo(scale))
objects.add(VAOObject3D(graph.getTriangulatedVAO(false, Graph3D.GradientPullStrategy(res)))
.translateTo(scale.x + 1, -10f, -scale.x - 1).scaleTo(scale))
objects.add(VAOObject3D(graph.getTriangulatedVAO(true, Graph3D.UniformGridStrategy(res)))
.translateTo(-scale.x - 1, -10f, scale.x + 1).scaleTo(scale))
objects.add(VAOObject3D(graph.getTriangulatedVAO(true, Graph3D.GradientPullStrategy(res)))
.translateTo(-scale.x - 1, -10f, -scale.x - 1).scaleTo(scale))
// loadResourceAsync("bugatti", { ident ->
// ResourceWrapper(OBJModelLoader.safePreloadModel("lwaf_demo/models/bugatti/bugatti.obj"), ident)
// }) {
// addModel(OBJModelLoader.loadModel(it.value).setMaterial(Material()
// .setSpecularLightingIntensity(0.1f))
// .translateTo(20f, 0f, 10f))
// }
//
// loadResourceAsync("cottage_obj", { ident ->
// ResourceWrapper(OBJModelLoader.safePreloadModel("lwaf_demo/models/cottage/cottage_obj.obj"), ident)
// }) {
// addModel(OBJModelLoader.loadModel(it.value)).setMaterial(Material()
// .setSpecularLightingIntensity(0.1f)
// .setTexture(loadResource("lwaf_demo/models/cottage/cottage_diffuse.png", ::loadTexture)))
// .translateTo(30f, 0f, -50f)
// }
//
// loadResourceAsync("buildings", { ident ->
// ResourceWrapper(OBJModelLoader.safePreloadModel("lwaf_demo/models/buildings/low poly buildings.obj"), ident)
// }) {
// addModel(OBJModelLoader.loadModel(it.value)).setMaterial(Material()
// .setSpecularLightingIntensity(0.1f))
// .translateTo(40f, 0f, 10f)
// .scaleTo(0.005f)
// }
//
// loadResourceAsync("Tree1", { ident ->
// ResourceWrapper(OBJModelLoader.safePreloadModel("lwaf_demo/models/trees/Tree1.obj"), ident)
// }) {
// addModel(OBJModelLoader.loadModel(it.value)).removeObject("Plane")
// .setMaterial(Material()
// .setSpecularLightingIntensity(0.1f))
// .translateTo(50f, -1f, 10f)
// }
//
// loadResourceAsync("stall", { ident ->
// ResourceWrapper(OBJModelLoader.safePreloadModel("lwaf_demo/models/stall/stall.obj"), ident)
// }) {
// addModel(OBJModelLoader.loadModel(it.value)).setMaterial(Material()
// .setTexture(loadResource("lwaf_demo/models/stall/stall_texture.png", ::loadTexture))
// .setSpecularLightingIntensity(0f))
// .translateTo(0f, 0f, 10f)
// }
val stall = loadResource("example/complex-3D/res/models/stall/stall.obj", ::loadOBJModel)
stall.translateBy(vec3(0f, 0f, -30f))
stall.objects["Cube[0]"] = stall.objects["Cube[0]"]!!.copy(second = Material().setTexture(loadResource("example/complex-3D/res/models/stall/stall_texture.png", ::loadTexture)))
objects.add(stall)
val deer = loadResource("example/complex-3D/res/models/deer/deer.obj", ::loadOBJModel)
deer.translateTo(vec3(10f, 0f, 9f))
deer.scaleBy(0.002f)
objects.add(deer)
}
object Demo3D {
@JvmStatic
fun main(args: Array<String>) {
Logging.enable("resource")
val display = Display()
var text = "Hello world"
display.attachLoadCallback {
view = GLView(vec2(0f, 0f), display.getWindowSize())
context2D = DrawContext2D(view)
context3D = DrawContext3D(view)
texture2D = loadResource("No texture dark") { ->
loadTextureFromInputStream(GLTexture::class.java.getResourceAsStream("/res/img/no-texture-dark.png"), "no-texture-dark.png")
}
context3D.camera.setPerspectiveProjection(context3D.aspectRatio)
loadModels()
}
display.attachUnloadCallback {
context3D.destroy()
freeResources()
}
display.attachDrawCallback {
val sea = Graph3D { (x, y) ->
(2.00 * noise(x * 0.5 + t * 0.05, y * 0.5, t * 0.05)
+ 0.50 * noise(x + t * 0.1, y.toDouble(), t * 0.1)
+ 0.50 * noise(x * 3 + t * 0.3, (y * 3).toDouble(), t * 0.3)).toFloat()
}
sea.setColouring { (_, y) -> (vec3(0.3f, 0.6f, 0.9f) + vec3(1f, 1f, 1f) * y * 0.1f) }
context3D.begin()
// glPolygonMode( GL_FRONT_AND_BACK, GL_LINE )
context3D.drawToGBuffer(context3D.DEFAULT_SHADER, objects)
context3D.drawToGBuffer(context3D.DEFAULT_SHADER, VAOObject3D(sea.getTriangulatedVAO(true, Graph3D.UniformGridStrategy(50)))
.translateTo(50f, -10f, 0f)
.scaleTo(40f, 1f, 40f))
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL )
context3D.ambientLight(0.2f)
context3D.directionalLight(vec3(-1f, -1f, -1f), 0.4f, vec3(0f, 1f, 0f))
context3D.directionalLight(vec3(0f, 1f, 0f), 0.4f, vec3(1f, 0f, 0f))
context3D.directionalLight(vec3(0f, -1f, 0f), 0.4f)
context3D.pointLight(vec3(0f, 4f, 10f), 4.8f, getLightingAttenuation(25f), vec3(1f, 1f, 0f))
context3D.spotLight(
vec3(-6f, -7f, -1f),
vec3(-3f, -1f, 2f).normalise(),
10f,
vec2(0.4f, 0.5f),
vec3(1f, 0.09f, 0.032f),
vec3(0f, 1f, 1f)
)
context3D.spotLight(
vec3(0f, -5f, 11f),
vec3(0f, -1f, 0f),
5f,
vec2(0.5f, 0.8f),
vec3(1f, 0.09f, 0.032f)
)
val scale = vec2(1f, 1f)
val texture = when (textureToDraw) {
0 -> context3D.texture
1 -> context3D.buffer.colourTexture
2 -> context3D.buffer.normalTexture
3 -> context3D.buffer.positionTexture
4 -> context3D.buffer.lightingTexture
else -> error("oh")
}
context2D.setColour(1f, 1f, 1f)
context2D.drawTexture(texture, vec2(0f, 0f), scale)
context2D.write(text, Font.DEFAULT_FONT, vec2(0f, 0f))
if (::texture2D.isInitialized) context2D.drawImage(texture2D, vec2(100f), vec2(0.1f))
}
display.attachUpdateCallback { dt ->
var translation = context3D.camera.translation
val forward = context3D.camera.flatForward
val right = context3D.camera.flatRight
val speed = dt * 5
finaliseQueuedResources()
t += dt * 1.2f
if (display.isKeyDown(GLFW_KEY_A)) {
translation -= right * speed
}
if (display.isKeyDown(GLFW_KEY_D)) {
translation += right * speed
}
if (display.isKeyDown(GLFW_KEY_W)) {
translation += forward * speed
}
if (display.isKeyDown(GLFW_KEY_S)) {
translation -= forward * speed
}
if (display.isKeyDown(GLFW_KEY_SPACE)) {
translation += vec3(0f, speed, 0f)
}
if (display.isKeyDown(GLFW_KEY_LEFT_SHIFT)) {
translation -= vec3(0f, speed, 0f)
}
text = display.fps.toString()
context3D.camera.moveTo(translation)
}
display.attachMouseDownCallback { _, _ ->
display.setMouseLocked(true)
}
display.attachMouseUpCallback { _, _ ->
if (!display.isMouseDown()) display.setMouseLocked(false)
}
display.attachMouseDragCallback { pos, last, _, _ ->
val dx = pos.x - last.x
val dy = pos.y - last.y
context3D.camera.rotateBy(vec3(0f, -dx / display.getWindowSize().x * 0.5f, 0f))
context3D.camera.rotateBy(vec3(-dy / display.getWindowSize().y * 0.5f, 0f, 0f))
}
display.attachKeyPressedCallback { key, modifier ->
if (key == GLFW_KEY_TAB) {
textureToDraw = if (modifier and GLFW_MOD_CONTROL != 0) {
(textureToDraw - 1) % 5
} else {
(textureToDraw + 1) % 5
}
}
if (textureToDraw < 0) textureToDraw += 5
}
display.attachResizedCallback { w, h ->
view = GLView(view.offset, vec2(w.toFloat(), h.toFloat()))
context2D = DrawContext2D(view)
context3D = DrawContext3D(view, context3D.camera)
context3D.camera.setPerspectiveProjection(context3D.aspectRatio)
}
display.run()
}
}
| 1
|
Kotlin
|
0
| 0
|
732f76f981fcb00ba486708965be2944a9d82b4d
| 11,569
|
LWAF
|
MIT License
|
core/networkApi/crm/impl/src/main/kotlin/odoo/miem/android/core/networkApi/crm/impl/di/CrmRepositoryComponent.kt
|
19111OdooApp
| 546,191,502
| false
|
{"Kotlin": 889625}
|
package odoo.miem.android.core.networkApi.crm.impl.di
import dagger.Component
import odoo.miem.android.core.networkApi.crm.api.di.ICrmRepositoryApi
import odoo.miem.android.core.networkApi.crm.impl.CrmRepository
/**
* [CrmRepositoryComponent] - **Dagger** component, which implements interface [ICrmRepositoryApi]
* Providing in general **DI graph** with a help of [CrmRepositoryApiProvider].
*
* Included modules:
* - [CrmRepositoryModule] - provide [CrmRepository] in *DI graph*
*
* @author <NAME>
*/
@Component(
modules = [
CrmRepositoryModule::class
]
)
interface CrmRepositoryComponent : ICrmRepositoryApi {
companion object {
fun create(): ICrmRepositoryApi = DaggerCrmRepositoryComponent.builder()
.build()
}
}
| 0
|
Kotlin
|
1
| 5
|
e107fcbb8db2d179d40b5c1747051d2cb75e58c6
| 773
|
OdooApp-Android
|
Apache License 2.0
|
app/src/main/java/si/hub/android/dialog/MessageDialogActivity.kt
|
dv5
| 289,117,603
| false
| null |
package si.hub.android.dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.viewbinding.ViewBinding
import si.hub.android.base.BaseDialogActivity
import si.hub.android.databinding.ActivityMessageDialogBinding
class MessageDialogActivity : BaseDialogActivity() {
private val binding: ActivityMessageDialogBinding by lazy {
ActivityMessageDialogBinding.inflate(
layoutInflater
)
}
override val contentViewBinding: ViewBinding
get() = binding
override fun onCreateEx(savedInstanceState: Bundle?) {
intent.extras?.let {
binding.title.text = it.getString(ARG_TITLE)
binding.subtitle.text = it.getString(ARG_SUBTITLE)
}
binding.btnYes.setOnClickListener {
setResult(RESULT_OK)
finish()
}
binding.btnCancel.setOnClickListener {
setResult(RESULT_CANCELED)
finish()
}
}
companion object {
private const val ARG_TITLE = "title"
private const val ARG_SUBTITLE = "subtitle"
fun createIntent(context: Context, title: String, subtitle: String): Intent {
return Intent(context, MessageDialogActivity::class.java).apply {
putExtra(ARG_TITLE, title)
putExtra(ARG_SUBTITLE, subtitle)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b5514ba0cd20bd20bea69142afaf59f60e2347c6
| 1,406
|
android-components
|
Apache License 2.0
|
sykepenger-model/src/test/kotlin/no/nav/helse/person/refusjon/RefusjonsservitørTest.kt
|
navikt
| 193,907,367
| false
|
{"Kotlin": 6610000, "PLpgSQL": 2738, "Dockerfile": 168}
|
package no.nav.helse.person.refusjon
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
import no.nav.helse.hendelser.Avsender
import no.nav.helse.hendelser.til
import no.nav.helse.januar
import no.nav.helse.person.beløp.Beløpstidslinje
import no.nav.helse.person.beløp.Kilde
import no.nav.helse.økonomi.Inntekt.Companion.daglig
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class RefusjonsservitørTest {
@Test
fun `rester etter servering`() {
val refusjonstidslinje = Beløpstidslinje.fra(januar, 100.daglig, kilde)
val servitør = Refusjonsservitør.fra(refusjonstidslinje)!!
val suppekjøkken = TestSuppekjøkken()
servitør.servér(1.januar, 10.januar til 15.januar)
servitør.donérRester(suppekjøkken)
assertEquals(setOf(1.januar), suppekjøkken.rester.keys)
assertEquals(listOf(1.januar til 9.januar, 16.januar til 31.januar), suppekjøkken.rester.getValue(1.januar).perioderMedBeløp)
}
@Test
fun `rester etter servering med fler startdatoer`() {
val refusjonstidslinje = Beløpstidslinje.fra(januar, 100.daglig, kilde)
val servitør = Refusjonsservitør.fra(refusjonstidslinje, setOf(5.januar, 16.januar))!!
val suppekjøkken = TestSuppekjøkken()
servitør.servér(2.januar, 10.januar til 12.januar)
servitør.servér(16.januar, 23.januar til 25.januar)
servitør.donérRester(suppekjøkken)
assertEquals(setOf(5.januar, 16.januar), suppekjøkken.rester.keys)
assertEquals(listOf(5.januar til 9.januar, 13.januar til 15.januar), suppekjøkken.rester.getValue(5.januar).perioderMedBeløp)
assertEquals(listOf(16.januar til 22.januar, 26.januar til 31.januar), suppekjøkken.rester.getValue(16.januar).perioderMedBeløp)
}
private companion object {
private val kilde = Kilde(UUID.randomUUID(), Avsender.ARBEIDSGIVER, LocalDateTime.now())
private class TestSuppekjøkken: Suppekjøkken {
val rester = mutableMapOf<LocalDate, Beløpstidslinje>()
override fun motta(startdato: LocalDate, refusjonstidslinje: Beløpstidslinje) {
rester[startdato] = (rester[startdato] ?: Beløpstidslinje()) + refusjonstidslinje
}
}
}
}
| 2
|
Kotlin
|
7
| 3
|
d8b9192fbce73e0f27f60de4e68360a06480235b
| 2,312
|
helse-spleis
|
MIT License
|
social-network/src/main/kotlin/ru/amai/highload/social/repository/impl/UserPersonalDetailsJdbcRepository.kt
|
slobanov
| 256,960,829
| false
|
{"Jupyter Notebook": 256899, "Kotlin": 81512, "HTML": 11765, "JavaScript": 7926, "Shell": 2913, "CSS": 1704, "Lua": 807}
|
package ru.amai.highload.social.repository.impl
import org.springframework.jdbc.core.RowMapper
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations
import org.springframework.jdbc.support.GeneratedKeyHolder
import org.springframework.stereotype.Repository
import ru.amai.highload.social.domain.City
import ru.amai.highload.social.domain.Gender
import ru.amai.highload.social.domain.UserPersonalDetails
import ru.amai.highload.social.repository.UserPersonalDetailsRepository
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.BIRTH_DATE
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.CITY_ID
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.CITY_NAME
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.FIRST_NAME
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.GENDER_ID
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.GENDER_NAME
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.ID
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.LAST_NAME
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.NAME
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Column.USER_ID
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Table.CITY
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Table.GENDER
import ru.amai.highload.social.repository.impl.UserPersonalDetailsJdbcRepository.Companion.Table.USER_PERSONAL_DETAILS
@Repository
class UserPersonalDetailsJdbcRepository(
private val jdbcOperations: NamedParameterJdbcOperations
) : UserPersonalDetailsRepository {
override fun findByUserId(userId: Long): UserPersonalDetails? =
jdbcOperations.query("""
$userPersonalDetailsSQL
WHERE $USER_PERSONAL_DETAILS.$USER_ID IN (:$USER_ID)
""".trimIndent(),
mapOf(USER_ID.name to userId),
userPersonalDetailsExtractor
).asSingle()
override fun save(
userPersonalDetails: UserPersonalDetails
): UserPersonalDetails = with(userPersonalDetails) {
val keyHolder = GeneratedKeyHolder()
jdbcOperations.update(
insertUserPersonalDetailsSql,
MapSqlParameterSource(mapOf(
USER_ID.name to userId,
FIRST_NAME.name to firstName,
LAST_NAME.name to lastName,
BIRTH_DATE.name to birthDate,
GENDER_ID.name to gender.id,
CITY_ID.name to city.id
)),
keyHolder,
arrayOf(ID.name)
)
val key = keyHolder.key
requireNotNull(key)
return userPersonalDetails.copy(id = key.toLong())
}
override fun findAllOrderById(limit: Int, offset: Long): List<UserPersonalDetails> =
jdbcOperations.query("""
$userPersonalDetailsSQL
ORDER BY $ID DESC
LIMIT :OFFSET, :LIMIT
""".trimIndent(),
mapOf(
"LIMIT" to limit,
"OFFSET" to offset
),
userPersonalDetailsExtractor
)
override fun findByFirstNamePrefixAndLastNamePrefixOrderById(
firstNamePrefix: String,
lastNamePrefix: String,
limit: Int,
offset: Long
): List<UserPersonalDetails> = jdbcOperations.query("""
$userPersonalDetailsSQL
WHERE LAST_NAME LIKE :LAST_NAME_PREFIX
AND FIRST_NAME LIKE :FIRST_NAME_PREFIX
ORDER BY $ID DESC
LIMIT :OFFSET, :LIMIT
""".trimIndent(),
mapOf(
"FIRST_NAME_PREFIX" to "$firstNamePrefix%",
"LAST_NAME_PREFIX" to "$lastNamePrefix%",
"LIMIT" to limit,
"OFFSET" to offset
),
userPersonalDetailsExtractor
)
private companion object {
enum class Table {
USER_PERSONAL_DETAILS,
GENDER,
CITY
}
enum class Column {
ID,
NAME,
USER_ID,
FIRST_NAME,
LAST_NAME,
BIRTH_DATE,
GENDER_ID,
GENDER_NAME,
CITY_ID,
CITY_NAME,
}
val userPersonalDetailsSQL = """
SELECT $USER_PERSONAL_DETAILS.$ID,
$USER_PERSONAL_DETAILS.$USER_ID,
$USER_PERSONAL_DETAILS.$FIRST_NAME,
$USER_PERSONAL_DETAILS.$LAST_NAME,
$USER_PERSONAL_DETAILS.$BIRTH_DATE,
$GENDER.$ID AS $GENDER_ID,
$GENDER.$NAME AS $GENDER_NAME,
$CITY.$ID AS $CITY_ID,
$CITY.$NAME AS $CITY_NAME
FROM $USER_PERSONAL_DETAILS
JOIN $GENDER
ON $USER_PERSONAL_DETAILS.$GENDER_ID = $GENDER.$ID
JOIN $CITY
ON $USER_PERSONAL_DETAILS.$CITY_ID = $CITY.$ID
""".trimIndent()
val insertUserPersonalDetailsSql = """
INSERT INTO $USER_PERSONAL_DETAILS (
$USER_ID, $FIRST_NAME, $LAST_NAME, $BIRTH_DATE, $GENDER_ID, $CITY_ID
) VALUES (
:$USER_ID, :$FIRST_NAME, :$LAST_NAME, :$BIRTH_DATE, :$GENDER_ID, :$CITY_ID
)
""".trimIndent()
val userPersonalDetailsExtractor = RowMapper { resultSet, _ -> with(resultSet) {
UserPersonalDetails(
id = getLong(ID.name),
userId = getLong(USER_ID.name),
firstName = getString(FIRST_NAME.name),
lastName = getString(LAST_NAME.name),
birthDate = getDate(BIRTH_DATE.name).toLocalDate(),
gender = Gender(
id = getLong(GENDER_ID.name),
name = getString(GENDER_NAME.name)
),
city = City(
id = getLong(CITY_ID.name),
name = getString(CITY_NAME.name)
)
)
} }
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
941bbb5c3e3118306343fc10671c2e26edc22fa3
| 6,486
|
otus-highload-2020-03-slobanov
|
MIT License
|
src/test/kotlin/com/hypto/iam/server/apis/KeyApiTest.kt
|
hwslabs
| 455,187,437
| false
|
{"Kotlin": 862507, "Shell": 1449, "Dockerfile": 648}
|
package com.hypto.iam.server.apis
import com.hypto.iam.server.helpers.BaseSingleAppTest
import com.hypto.iam.server.helpers.DataSetupHelperV3.createOrganization
import com.hypto.iam.server.helpers.DataSetupHelperV3.deleteOrganization
import com.hypto.iam.server.models.KeyResponse
import com.hypto.iam.server.models.TokenResponse
import com.hypto.iam.server.service.TokenServiceImpl
import io.jsonwebtoken.Jwts
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType.Application.Json
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.test.dispatcher.testSuspend
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.Base64
class KeyApiTest : BaseSingleAppTest() {
@Test
fun `validate token using public key`() {
testSuspend {
val (organizationResponse, _) = testApp.createOrganization()
val createTokenCall =
testApp.client.post("/organizations/${organizationResponse.organization.id}/token") {
header(HttpHeaders.ContentType, Json.toString())
header(HttpHeaders.Authorization, "Bearer ${organizationResponse.rootUserToken}")
}
val token =
gson
.fromJson(createTokenCall.bodyAsText(), TokenResponse::class.java).token
println(token)
val splitToken: Array<String> = token.split(".").toTypedArray()
val unsignedToken = splitToken[0] + "." + splitToken[1] + "."
val jwt = Jwts.parserBuilder().build().parseClaimsJwt(unsignedToken)
val kid = jwt.header.getValue(TokenServiceImpl.KEY_ID) as String
val response =
testApp.client.get(
"/keys/$kid?format=der",
) {
header(HttpHeaders.Authorization, "Bearer ${organizationResponse.rootUserToken}")
}
assertEquals(HttpStatusCode.OK, response.status)
assertEquals(
Json,
response.contentType(),
)
val publicKeyResponse = gson.fromJson(response.bodyAsText(), KeyResponse::class.java)
assertEquals(KeyResponse.Format.der, publicKeyResponse.format)
val encodedPublicKey = Base64.getDecoder().decode(publicKeyResponse.key)
val keyFactory = KeyFactory.getInstance("EC")
val keySpec = X509EncodedKeySpec(encodedPublicKey)
val publicKey = keyFactory.generatePublic(keySpec) as PublicKey
assertEquals(kid, publicKeyResponse.kid)
assertDoesNotThrow {
Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token)
}
testApp.deleteOrganization(organizationResponse.organization.id)
}
}
}
| 17
|
Kotlin
|
3
| 15
|
0feca2fbb29db932b855e391d3816dd6d7aa5bd0
| 3,172
|
iam
|
MIT License
|
app/src/main/java/com/example/arvoice/domain/AugmentedRoom.kt
|
catalinghita8
| 277,578,519
| false
| null |
package com.example.arvoice.domain
class AugmentedRoom(var id: Int, var userAssets: List<UserAsset>)
| 0
|
Kotlin
|
0
| 1
|
2a0f821c4b2c7171ab3118f54526a143e761fc42
| 102
|
ARCore-NLP-persistent-augmentation
|
Apache License 2.0
|
src/main/kotlin/com/sauleiros/albumexplorer/application/service/AlbumServiceImpl.kt
|
SaulEiros
| 833,679,357
| false
|
{"Kotlin": 24735, "Dockerfile": 270}
|
package com.sauleiros.albumexplorer.application.service
import com.sauleiros.albumexplorer.application.ports.input.AlbumService
import com.sauleiros.albumexplorer.application.ports.output.AlbumRepository
import com.sauleiros.albumexplorer.domain.exception.AlbumNotFoundException
import com.sauleiros.albumexplorer.domain.model.Album
import org.springframework.stereotype.Service
@Service
class AlbumServiceImpl(private val repository: AlbumRepository) : AlbumService {
override fun findById(id: Long): Album {
return repository.findById(id) ?: throw AlbumNotFoundException(id)
}
override fun findAll(): List<Album> {
return repository.findAll()
}
}
| 0
|
Kotlin
|
0
| 0
|
3647b87e66c72709f1352e0c958979b022189608
| 684
|
album-explorer
|
Apache License 2.0
|
Extensions/Music/src/main/kotlin/net/sourcebot/module/music/audio/AudioSubsystem.kt
|
TheSourceCodeLLC
| 271,902,483
| false
| null |
package net.sourcebot.module.music.audio
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.track.AudioItem
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.VoiceChannel
import net.sourcebot.api.audio.AudioSender
import net.sourcebot.api.response.Response
import net.sourcebot.api.response.error.ExceptionResponse
import net.sourcebot.module.music.Music
import java.util.concurrent.CompletableFuture
class AudioSubsystem(
val player: AudioPlayer
) {
private val audioSender = AudioSender(player)
val scheduler = TrackScheduler(player)
private lateinit var guild: Guild
var connected = false
@JvmOverloads
fun load(
identifier: String,
postLoad: (AudioItem) -> Response,
noMatch: () -> Response,
onFailed: (FriendlyException) -> Response = { ExceptionResponse(it) }
): Response = CompletableFuture<Response>().apply {
Music.PLAYER_MANAGER.loadItem(identifier, object : AudioLoadResultHandler {
override fun trackLoaded(track: AudioTrack) {
scheduler.offer(track)
complete(postLoad(track))
}
override fun playlistLoaded(playlist: AudioPlaylist) {
playlist.tracks.forEach(scheduler::offer)
complete(postLoad(playlist))
}
override fun noMatches() {
complete(noMatch())
}
override fun loadFailed(exception: FriendlyException) {
complete(onFailed(exception))
}
})
}.get()
fun applyTo(guild: Guild) {
if (this::guild.isInitialized) return
this.guild = guild
guild.audioManager.sendingHandler = audioSender
}
fun connect(channel: VoiceChannel): Boolean {
if (connected) return false
guild.audioManager.openAudioConnection(channel)
return true
}
fun stop() {
player.stopTrack()
scheduler.clear()
}
fun pause() = if (player.isPaused) false else {
player.isPaused = true; true
}
fun resume() = if (!player.isPaused) false else {
player.isPaused = false; true
}
}
| 5
|
Kotlin
|
8
| 9
|
ff4a07c69a009d118b10bc4d57f6e567334ed768
| 2,488
|
Source
|
MIT License
|
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/skin/detail/GatheringToolSkinDetails.kt
|
Woody230
| 388,820,096
| false
|
{"Kotlin": 750899}
|
package com.bselzer.gw2.v2.model.skin.detail
import com.bselzer.gw2.v2.model.enumeration.wrapper.GatheringToolDetailType
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GatheringToolSkinDetails(
@SerialName("type")
val type: GatheringToolDetailType = GatheringToolDetailType()
)
| 2
|
Kotlin
|
0
| 2
|
7bd43646f94d1e8de9c20dffcc2753707f6e455b
| 347
|
GW2Wrapper
|
Apache License 2.0
|
pact-jvm-mockk-spring/src/test/kotlin/io/github/ludorival/pactjvm/mockk/spring/test/ShoppingListAppDeterministicTest.kt
|
ludorival
| 600,899,235
| false
|
{"Kotlin": 39620}
|
package io.github.ludorival.pactjvm.mockk.spring.test
import io.github.ludorival.pactjvm.mockk.spring.DeterministicPact
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(DeterministicPact::class)
open class ShoppingListAppDeterministicTest : ShoppingListAppTest()
| 6
|
Kotlin
|
0
| 1
|
b2a6d1f6cb6cd7231450d637757803730ee8a5a3
| 278
|
pact-jvm-mock
|
MIT License
|
app/src/main/java/com/aos/app/net/mk/MRetrofit.kt
|
ltqi
| 279,073,843
| false
| null |
package com.aos.app.net.mk
import com.aos.app.App
import com.aos.app.BuildConfig
import com.aos.app.ut.saveAccessToken
import com.aos.app.ut.saveRefreshToken
import com.aos.app.ut.saveSessionInfo
import com.q.net.BaseRetrofitClient
import com.q.net.InjectCommonParamsInterceptor
import com.q.net.injectParams
import com.q.net.newBuilder
import com.q.util.GsonHelper
import com.q.util.body2String
import com.q.util.formatJson
import com.q.util.i
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okio.Buffer
import retrofit2.Retrofit
/**
* Created by: qiliantao on 2020.06.22 11:52
* email : qiliantao@mockuai.com
* Describe : Retrofit okHttpClient封装
*/
object MRetrofit : BaseRetrofitClient() {
val refreshTokenLock = Any()
private val buffer = Buffer()
override fun builderOkHttpClient(builder: OkHttpClient.Builder) {
builder.addInterceptor(
InjectCommonParamsInterceptor(
CommonRequestParams.commonParams
)
)
if (BuildConfig.DEBUG) {
builder.addInterceptor {
val request = it.request()
val t1 = System.nanoTime()
buffer.clear()
request.body?.writeTo(buffer)
i(" =============================Request=======================" +
String.format(" \n %s to %s%n%s Body = %s", request.url, it.connection(), request.headers, formatJson(buffer.readUtf8())))
val response = it.proceed(request)
val t2 = System.nanoTime()
i(" =============================Response======================= " +
String.format(" \n from %s spend %.1fms%n%s Body = %s", response.request.url, (t2 - t1) / 1e6, response.headers, response.body?.body2String()))
response
}
}
builder.addInterceptor(AccessTokenRefreshInterceptor())
}
override fun builderRetrofit(builder: Retrofit.Builder) {}
}
class AccessTokenRefreshInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originRequest = chain.request()
val response = chain.proceed(originRequest)
if (response.isSuccessful) {
val result = GsonHelper.fromJson<MKResult<String?>>(
response.body?.body2String(), GsonHelper.findType(
MKResult::class.java, String::class.java
)
)
when (result?.code) {
ServerCode.SESSION_TOKEN_INVALID -> {
synchronized(MRetrofit.refreshTokenLock) {
val sessionTokenResult =
MRetrofit.getApiService<ApiMKService>().refreshSessionToken()
val sessionToken = sessionTokenResult.data?.sessionToken
return if (sessionTokenResult.isSuccess && sessionToken != null) {
App.sp.saveSessionInfo(sessionToken)
val requestBuilder = originRequest.newBuilder()
.injectParams(originRequest, CommonRequestParams.commonParams)
chain.proceed(requestBuilder.build())
} else {
Response.Builder().newBuilder(response).message("获取sessionToken失败")
.build()
}
}
}
ServerCode.ACCESS_TOKEN_INVALID -> {
synchronized(MRetrofit.refreshTokenLock) {
val accessTokenResult =
MRetrofit.getApiService<ApiMKService>().refreshAccessToken()
val accessToken = accessTokenResult.accessToken
val refreshToken = accessTokenResult.refreshToken
return if (accessTokenResult.isSuccess && accessToken != null && refreshToken != null) {
App.sp.saveAccessToken(accessToken)
App.sp.saveRefreshToken(refreshToken)
val requestBuilder = originRequest.newBuilder()
.injectParams(originRequest, CommonRequestParams.commonParams)
chain.proceed(requestBuilder.build())
} else {
Response.Builder().newBuilder(response).message("获取accessToken失败")
.build()
}
}
}
ServerCode.REFRESH_TOKEN_INVALID -> {
return Response.Builder().newBuilder(response).message("token已失效,请重新登录").build()
}
ServerCode.REQUEST_TIME_OUT -> {
return Response.Builder().newBuilder(response).message("请求超时").build()
}
}
}
return response
}
}
| 0
|
Kotlin
|
0
| 1
|
723c297f97b42868febed4eaa906af57adbfe14a
| 5,020
|
aos
|
MIT License
|
js/js.translator/testData/incremental/invalidation/inlineFunctionAsParam/lib1/l1.3.kt
|
JetBrains
| 3,432,266
| false
|
{"Markdown": 192, "Gradle": 401, "Gradle Kotlin DSL": 1182, "Java Properties": 29, "Shell": 45, "Ignore List": 20, "Batchfile": 21, "Git Attributes": 8, "JSON": 203, "XML": 833, "Kotlin": 56096, "INI": 200, "Java": 3899, "Text": 25219, "JavaScript": 316, "JAR Manifest": 2, "Roff": 256, "Roff Manpage": 56, "Protocol Buffer": 16, "Proguard": 15, "TOML": 1, "AsciiDoc": 1, "YAML": 8, "EditorConfig": 2, "OpenStep Property List": 24, "C": 216, "C++": 368, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 19, "Objective-C": 237, "Groovy": 10, "Dockerfile": 5, "Diff": 4, "EJS": 1, "CSS": 6, "HTML": 11, "Swift": 161, "LLVM": 1, "Reason": 1, "JSON with Comments": 62, "TypeScript": 8, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 102, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 77, "FreeMarker": 1, "Fluent": 2, "Ruby": 19, "Scala": 1}
|
inline fun foo1() = 77
inline fun foo2() = "foo2 update"
inline fun foo3() = "foo3"
| 179
|
Kotlin
|
5640
| 48,055
|
e3542ec7d0ffb0a27b189cadc323e88e4cb8ba4f
| 84
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/github/tcpgnl/thoughtworkscodereviewtools/services/MyApplicationService.kt
|
xiaoquisme
| 432,933,512
| false
|
{"Java Properties": 1, "Gradle Kotlin DSL": 2, "Markdown": 3, "Shell": 1, "Batchfile": 1, "Java": 24, "Kotlin": 4, "INI": 2}
|
package com.github.tcpgnl.thoughtworkscodereviewtools.services
import com.github.tcpgnl.thoughtworkscodereviewtools.MyBundle
class MyApplicationService {
init {
println(MyBundle.message("applicationService"))
}
}
| 1
| null |
1
| 1
|
f06832fb166500894394e3e63a714cb8d357d66a
| 232
|
thoughtworks-code-review-tools
|
MIT License
|
src/main/kotlin/no/nav/syfo/dodshendelser/kafka/PersonhendelserConsumer.kt
|
navikt
| 273,248,067
| false
|
{"Kotlin": 261314, "Dockerfile": 277}
|
package no.nav.syfo.dodshendelser.kafka
import java.time.Duration
import org.apache.avro.generic.GenericRecord
import org.apache.kafka.clients.consumer.KafkaConsumer
class PersonhendelserConsumer(
private val kafkaPersonhendelserConsumer: KafkaConsumer<String, GenericRecord>
) {
fun poll(): List<GenericRecord> {
return kafkaPersonhendelserConsumer.poll(Duration.ofMillis(0)).map { it.value() }
}
}
| 0
|
Kotlin
|
0
| 0
|
bd0a3474d6517bcf7bd761646854a621127c170d
| 422
|
sparenaproxy
|
MIT License
|
image-loader/src/commonMain/kotlin/com/seiko/imageloader/util/LruCache.kt
|
qdsfdhvh
| 502,954,331
| false
|
{"Kotlin": 824269, "Swift": 717, "HTML": 496}
|
package com.seiko.imageloader.util
expect open class LruCache<K : Any, V : Any>(maxSize: Int) {
protected open fun sizeOf(key: K, value: V): Int
protected open fun entryRemoved(evicted: Boolean, key: K, oldValue: V, newValue: V?)
protected open fun create(key: K): V?
fun size(): Int
fun maxSize(): Int
fun snapshot(): MutableMap<K, V>
operator fun get(key: K): V?
fun put(key: K, value: V): V?
fun remove(key: K): V?
fun evictAll()
}
| 32
|
Kotlin
|
15
| 432
|
bdf4a1e89113552abe98d250f192ea55bd8a2c24
| 476
|
compose-imageloader
|
MIT License
|
engine/src/main/kotlin/rs/dusk/engine/client/ui/detail/InterfaceData.kt
|
Palmfeldt
| 673,267,966
| true
|
{"Kotlin": 1529507}
|
package rs.dusk.engine.client.ui.detail
/**
* Location of an interface in relation to it's parents and screen mode
*/
data class InterfaceData(
val fixedParent: Int? = null,
val resizableParent: Int? = null,
val fixedIndex: Int? = null,
val resizableIndex: Int? = null
) {
fun getIndex(resize: Boolean) = if(resize) resizableIndex else fixedIndex
fun getParent(resize: Boolean) = if(resize) resizableParent else fixedParent
}
| 0
|
Kotlin
|
0
| 0
|
0b3a4fe8eb9f2e2e29f8834d028fd3edf038cd2f
| 455
|
NostalgiaScape
|
Creative Commons Attribution 3.0 Unported
|
app/src/main/java/com/duckduckgo/app/tabs/store/TabSwitcherDataStore.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.app.tabs.store
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.duckduckgo.app.tabs.model.TabSwitcherData
import com.duckduckgo.app.tabs.model.TabSwitcherData.LayoutType
import com.duckduckgo.app.tabs.model.TabSwitcherData.UserState
import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
interface TabSwitcherDataStore {
val data: Flow<TabSwitcherData>
suspend fun setUserState(userState: UserState)
suspend fun setWasAnnouncementDismissed(wasDismissed: Boolean)
suspend fun setAnnouncementDisplayCount(displayCount: Int)
suspend fun setTabLayoutType(layoutType: LayoutType)
}
@ContributesBinding(AppScope::class)
class TabSwitcherPrefsDataStore @Inject constructor(
@TabSwitcher private val store: DataStore<Preferences>,
) : TabSwitcherDataStore {
companion object {
const val KEY_USER_STATE = "KEY_USER_STATE"
const val KEY_WAS_ANNOUNCEMENT_DISMISSED = "KEY_WAS_ANNOUNCEMENT_DISMISSED"
const val KEY_ANNOUNCEMENT_DISPLAY_COUNT = "KEY_ANNOUNCEMENT_DISPLAY_COUNT"
const val KEY_LAYOUT_TYPE = "KEY_LAYOUT_TYPE"
}
override val data: Flow<TabSwitcherData> = store.data.map { preferences ->
TabSwitcherData(
userState = UserState.valueOf(
preferences[stringPreferencesKey(KEY_USER_STATE)] ?: UserState.UNKNOWN.name
),
wasAnnouncementDismissed = preferences[booleanPreferencesKey(
KEY_WAS_ANNOUNCEMENT_DISMISSED
)] ?: false,
announcementDisplayCount = preferences[intPreferencesKey(KEY_ANNOUNCEMENT_DISPLAY_COUNT)]
?: 0,
layoutType = LayoutType.valueOf(
preferences[stringPreferencesKey(KEY_LAYOUT_TYPE)] ?: LayoutType.GRID.name
),
)
}
override suspend fun setUserState(userState: UserState) {
store.edit { preferences ->
preferences[stringPreferencesKey(KEY_USER_STATE)] = userState.name
}
}
override suspend fun setWasAnnouncementDismissed(wasDismissed: Boolean) {
store.edit { preferences ->
preferences[booleanPreferencesKey(KEY_WAS_ANNOUNCEMENT_DISMISSED)] = wasDismissed
}
}
override suspend fun setAnnouncementDisplayCount(displayCount: Int) {
store.edit { preferences ->
preferences[intPreferencesKey(KEY_ANNOUNCEMENT_DISPLAY_COUNT)] = displayCount
}
}
override suspend fun setTabLayoutType(layoutType: LayoutType) {
store.edit { preferences ->
preferences[stringPreferencesKey(KEY_LAYOUT_TYPE)] = layoutType.name
}
}
}
| 0
|
Kotlin
|
0
| 0
|
54351d039b85138a85cbfc7fc3bd5bc53637559f
| 3,073
|
DuckDuckGo
|
Apache License 2.0
|
walletlibrary/src/test/java/com/microsoft/walletlibrary/requests/RequestResolverFactoryTest.kt
|
microsoft
| 567,422,889
| false
| null |
package com.microsoft.walletlibrary.requests
import com.microsoft.walletlibrary.requests.input.VerifiedIdRequestInput
import com.microsoft.walletlibrary.requests.resolvers.RequestResolver
import com.microsoft.walletlibrary.util.ResolverMissingException
import com.microsoft.walletlibrary.util.UnSupportedInputException
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions
import org.junit.Test
class RequestResolverFactoryTest {
private val mockRequestResolver: RequestResolver = mockk()
private val requestResolverFactory = RequestResolverFactory()
private val mockVerifiedIdRequestInput: VerifiedIdRequestInput = mockk()
private fun hasCompatibleResolver() {
every { mockRequestResolver.canResolve(mockVerifiedIdRequestInput) } returns true
}
private fun doesNotHaveCompatibleResolver(mockRequestResolver: RequestResolver) {
every { mockRequestResolver.canResolve(mockVerifiedIdRequestInput) } returns false
}
@Test
fun resolver_RegisterOneHandler_Succeeds() {
// Arrange
requestResolverFactory.requestResolvers.add(mockRequestResolver)
hasCompatibleResolver()
// Act
val actualResult = requestResolverFactory.getResolver(mockVerifiedIdRequestInput)
// Assert
Assertions.assertThat(actualResult).isEqualTo(mockRequestResolver)
}
@Test
fun resolver_NoResolverRegistration_Throws() {
// Act and Assert
Assertions.assertThatThrownBy { requestResolverFactory.getResolver(mockVerifiedIdRequestInput) }
.isInstanceOf(
ResolverMissingException::class.java
)
}
@Test
fun resolver_NoCompatibleResolver_Throws() {
// Arrange
requestResolverFactory.requestResolvers.add(mockRequestResolver)
doesNotHaveCompatibleResolver(mockRequestResolver)
// Act and Assert
Assertions.assertThatThrownBy { requestResolverFactory.getResolver(mockVerifiedIdRequestInput) }
.isInstanceOf(
UnSupportedInputException::class.java
)
}
@Test
fun resolver_RegisterMultipleResolver_Succeeds() {
// Arrange
val secondMockRequestResolver: RequestResolver = mockk()
requestResolverFactory.requestResolvers.add(mockRequestResolver)
requestResolverFactory.requestResolvers.add(secondMockRequestResolver)
hasCompatibleResolver()
doesNotHaveCompatibleResolver(secondMockRequestResolver)
// Act
val actualResult = requestResolverFactory.getResolver(mockVerifiedIdRequestInput)
// Assert
Assertions.assertThat(actualResult).isEqualTo(mockRequestResolver)
}
}
| 1
|
Kotlin
|
2
| 9
|
d7c28891eaa6f6d4bd373be324cd61ba32776622
| 2,724
|
entra-verifiedid-wallet-library-android
|
MIT License
|
app/src/main/java/com/buchi/fullentry/movie/data/cache/MovieDao.kt
|
SunnyBe
| 370,745,596
| false
| null |
package com.buchi.fullentry.movie.data.cache
import androidx.room.*
import com.buchi.core.base.BaseDao
import kotlinx.coroutines.flow.Flow
@Dao
interface MovieDao: BaseDao {
@Query("SELECT * FROM movie")
fun getAll(): List<MovieData>
@Query("SELECT * FROM movie WHERE id IN (:movieIds)")
fun loadAllByIds(movieIds: IntArray): List<MovieData>
@Query("SELECT * FROM movie WHERE title LIKE :title LIMIT 1")
fun findByTitle(title: String): MovieData
@Query("SELECT * FROM movie WHERE title LIKE '%' || :title || '%'")
fun selectByTitle(title: String): Flow<List<MovieData>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(vararg movies: MovieData)
@Delete
fun delete(movie: MovieData)
}
| 0
|
Kotlin
|
1
| 0
|
f4c1d6c8067c4149d357a4ded6e6455b60b15156
| 753
|
MovieApp
|
The Unlicense
|
src/main/kotlin/no/nav/k9/los/domene/repository/BehandlingProsessEventTilbakeRepository.kt
|
navikt
| 238,874,021
| false
|
{"Kotlin": 1605106, "JavaScript": 741, "Shell": 659, "Dockerfile": 343, "PLpgSQL": 167}
|
package no.nav.k9.los.domene.repository
import kotliquery.queryOf
import kotliquery.sessionOf
import kotliquery.using
import no.nav.k9.los.domene.modell.K9TilbakeModell
import no.nav.k9.los.integrasjon.kafka.dto.BehandlingProsessEventTilbakeDto
import no.nav.k9.los.tjenester.innsikt.Databasekall
import no.nav.k9.los.utils.LosObjectMapper
import java.util.*
import java.util.concurrent.atomic.LongAdder
import javax.sql.DataSource
class BehandlingProsessEventTilbakeRepository(private val dataSource: DataSource) {
fun hent(uuid: UUID): K9TilbakeModell {
val json: String? = using(sessionOf(dataSource)) {
it.run(
queryOf(
"select data from behandling_prosess_events_tilbake where id = :id",
mapOf("id" to uuid.toString())
)
.map { row ->
row.string("data")
}.asSingle
)
}
Databasekall.map.computeIfAbsent(object {}.javaClass.name + object {}.javaClass.enclosingMethod.name) { LongAdder() }
.increment()
if (json.isNullOrEmpty()) {
return K9TilbakeModell(mutableListOf())
}
val modell = LosObjectMapper.instance.readValue(json, K9TilbakeModell::class.java)
return K9TilbakeModell(modell.eventer.sortedBy { it.eventTid }.toMutableList())
}
fun lagre(
event: BehandlingProsessEventTilbakeDto
): K9TilbakeModell {
val json = LosObjectMapper.instance.writeValueAsString(event)
val id = event.eksternId.toString()
val out = using(sessionOf(dataSource)) {
it.transaction { tx ->
tx.run(
queryOf(
"""
insert into behandling_prosess_events_tilbake as k (id, data)
values (:id, :dataInitial :: jsonb)
on conflict (id) do update
set data = jsonb_set(k.data, '{eventer,999999}', :data :: jsonb, true)
""", mapOf("id" to id, "dataInitial" to "{\"eventer\": [$json]}", "data" to json)
).asUpdate
)
tx.run(
queryOf(
"select data from behandling_prosess_events_tilbake where id = :id",
mapOf("id" to id)
)
.map { row ->
row.string("data")
}.asSingle
)
}
}
Databasekall.map.computeIfAbsent(object {}.javaClass.name + object {}.javaClass.enclosingMethod.name) { LongAdder() }
.increment()
val modell = LosObjectMapper.instance.readValue(out!!, K9TilbakeModell::class.java)
return modell.copy(eventer = modell.eventer.sortedBy { it.eventTid })
}
}
| 9
|
Kotlin
|
0
| 0
|
8436f18b676df5c772d178a3b1ff1747657c8169
| 2,888
|
k9-los-api
|
MIT License
|
app/src/main/java/com/example/mywaycompose/domain/usecase/product_task/UseObserveProductTasksFirebase.kt
|
larkes-cyber
| 739,078,285
| false
|
{"Kotlin": 575045}
|
package com.example.mywaycompose.domain.usecase.product_task
import android.util.Log
import com.example.mywaycompose.data.remote.firebase_model.FirebaseProductTask
import com.example.mywaycompose.domain.mapper.toProductTask
import com.example.mywaycompose.domain.model.ProductTask
import com.example.mywaycompose.domain.repository.UserRepository
import com.example.mywaycompose.utils.Constants
import com.example.mywaycompose.utils.Resource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class UseObserveProductTasksFirebase(
private val userRepository: UserRepository,
private val coroutineScope: CoroutineScope
) {
operator fun invoke(): Flow<Resource<List<ProductTask>>> = callbackFlow {
trySend(Resource.Loading())
try {
val tasks = userRepository.getAppData<FirebaseProductTask>(Constants.PRODUCT_TASKS_KIND)
var open_flow: ProducerScope<Resource<List<ProductTask>>>? = null
tasks.onEach {
open_flow = this
Log.d("sfsdfsdf"," e.toString()")
trySend(Resource.Success(it.map { it.toProductTask()}))
}.launchIn(coroutineScope)
awaitClose{open_flow!!.close()}
}catch (e:Exception){
Log.d("sfsdfsdf", e.toString())
trySend(Resource.Error(e.toString()))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
81ff3952a4aa8d83269a349ff52f8afb6a1156ff
| 1,599
|
PlannerApp
|
Apache License 2.0
|
android/src/newarch/AnalyticsampleSpec.kt
|
prakharbangar
| 878,313,523
| false
|
{"Kotlin": 4948, "Ruby": 3264, "Objective-C": 2551, "TypeScript": 2277, "JavaScript": 1613, "Objective-C++": 1535, "C": 103, "Swift": 66}
|
package com.analyticsample
import com.facebook.react.bridge.ReactApplicationContext
abstract class AnalyticsampleSpec internal constructor(context: ReactApplicationContext) :
NativeAnalyticsampleSpec(context) {
}
| 0
|
Kotlin
|
0
| 0
|
83a50929dfb77c324bcbe583bda71174d2cc4d4d
| 217
|
sampleapp
|
MIT License
|
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/java/JavaSamDebugSupport.kt
|
MaciejFed
| 325,069,298
| true
|
{"Kotlin": 3150911, "C#": 96494, "Java": 15092, "Dockerfile": 637}
|
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.lambda.java
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.DefaultDebugEnvironment
import com.intellij.debugger.engine.JavaDebugProcess
import com.intellij.execution.DefaultExecutionResult
import com.intellij.execution.configurations.RemoteConnection
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugProcessStarter
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.impl.XDebugSessionImpl
import software.amazon.awssdk.services.lambda.model.PackageType
import software.amazon.awssdk.services.lambda.model.Runtime
import software.aws.toolkits.jetbrains.services.lambda.execution.sam.SamDebugSupport
import software.aws.toolkits.jetbrains.services.lambda.execution.sam.SamRunningState
class JavaSamDebugSupport : SamDebugSupport {
override fun containerEnvVars(runtime: Runtime, packageType: PackageType, debugPorts: List<Int>): Map<String, String> {
if (packageType != PackageType.IMAGE) {
return mapOf()
}
return when (runtime) {
Runtime.JAVA8, Runtime.JAVA8_AL2 -> mapOf(
"_JAVA_OPTIONS" to "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=${debugPorts.first()} " +
"-XX:MaxHeapSize=2834432k -XX:MaxMetaspaceSize=163840k -XX:ReservedCodeCacheSize=81920k -XX:+UseSerialGC " +
"-XX:-TieredCompilation -Djava.net.preferIPv4Stack=true -Xshare:off"
)
else -> mapOf(
"_JAVA_OPTIONS" to "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=*:${debugPorts.first()} " +
"-XX:MaxHeapSize=2834432k -XX:MaxMetaspaceSize=163840k -XX:ReservedCodeCacheSize=81920k -XX:+UseSerialGC " +
"-XX:-TieredCompilation -Djava.net.preferIPv4Stack=true"
)
}
}
override fun createDebugProcess(
environment: ExecutionEnvironment,
state: SamRunningState,
debugHost: String,
debugPorts: List<Int>
): XDebugProcessStarter? {
val connection = RemoteConnection(true, debugHost, debugPorts.first().toString(), false)
val debugEnvironment = DefaultDebugEnvironment(environment, state, connection, true)
val debuggerManager = DebuggerManagerEx.getInstanceEx(environment.project)
val debuggerSession = debuggerManager.attachVirtualMachine(debugEnvironment) ?: return null
return object : XDebugProcessStarter() {
override fun start(session: XDebugSession): XDebugProcess {
if (session is XDebugSessionImpl) {
val debugProcess = debuggerSession.process
val executionResult = debugProcess.executionResult
session.addExtraActions(*executionResult.actions)
if (executionResult is DefaultExecutionResult) {
session.addRestartActions(*executionResult.restartActions)
}
}
return JavaDebugProcess.create(session, debuggerSession)
}
}
}
}
| 0
| null |
0
| 0
|
c464ff20657e9091ac2ac9f22b91c2753d81ab26
| 3,344
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
model/src/test/kotlin/MergedAnalyzerResultTest.kt
|
enterstudio
| 128,504,116
| true
|
{"Kotlin": 489933, "Shell": 1064}
|
/*
* Copyright (c) 2017-2018 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.ort.model
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.WordSpec
import java.io.File
class MergedAnalyzerResultTest : WordSpec() {
val repositoryPath = File("/absolute/path")
val directoryDetails = Repository(repositoryPath.name, repositoryPath.absolutePath.replace(File.separatorChar, '/'),
VcsInfo.EMPTY)
val package1 = Package.EMPTY.copy(id = Identifier("provider-1", "namespace-1", "package-1", "version-1"))
val package2 = Package.EMPTY.copy(id = Identifier("provider-2", "namespace-2", "package-2", "version-2"))
val package3 = Package.EMPTY.copy(id = Identifier("provider-3", "namespace-3", "package-3", "version-3"))
val pkgRef1 = package1.toReference()
val pkgRef2 = package2.toReference(sortedSetOf(package3.toReference()))
val scope1 = Scope("scope-1", true, sortedSetOf(pkgRef1))
val scope2 = Scope("scope-2", true, sortedSetOf(pkgRef2))
val project1 = Project.EMPTY.copy(
id = Identifier("provider-1", "namespace-1", "project-1", "version-1"),
scopes = sortedSetOf(scope1)
)
val project2 = Project.EMPTY.copy(
id = Identifier("provider-2", "namespace-2", "project-2", "version-2"),
scopes = sortedSetOf(scope1, scope2)
)
val analyzerResult1 = AnalyzerResult(true, project1, sortedSetOf(package1), listOf("error-1", "error-2"))
val analyzerResult2 = AnalyzerResult(true, project2, sortedSetOf(package1, package2, package3), listOf("error-2"))
init {
"MergedAnalyzerResult" should {
"create the correct AnalyzerResults" {
val builder = MergedResultsBuilder(true, repositoryPath, VcsInfo.EMPTY)
builder.addResult("/analyzer-result-1.yml", analyzerResult1)
builder.addResult("/analyzer-result-2.yml", analyzerResult2)
val mergedResults = builder.build()
mergedResults.createAnalyzerResults() shouldBe listOf(analyzerResult1, analyzerResult2)
}
}
"MergedResultsBuilder" should {
"merge results from all files" {
val builder = MergedResultsBuilder(true, repositoryPath, VcsInfo.EMPTY)
builder.addResult("/analyzer-result-1.yml", analyzerResult1)
builder.addResult("/analyzer-result-2.yml", analyzerResult2)
val mergedResults = builder.build()
mergedResults.allowDynamicVersions shouldBe true
mergedResults.repository shouldBe directoryDetails
mergedResults.projects shouldBe sortedSetOf(project1, project2)
mergedResults.projectResultsFiles shouldBe
sortedMapOf(project1.id to "/analyzer-result-1.yml", project2.id to "/analyzer-result-2.yml")
mergedResults.packages shouldBe sortedSetOf(package1, package2, package3)
mergedResults.errors shouldBe
sortedMapOf(project1.id to analyzerResult1.errors, project2.id to analyzerResult2.errors)
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
5b0ea0c292d1abfcef00b02250ae109cdebc6389
| 3,784
|
oss-review-toolkit
|
Apache License 2.0
|
app/src/main/java/net/tnose/app/trisquel/ImportWorker.kt
|
plus7
| 117,273,066
| false
|
{"Kotlin": 627932, "Java": 1153}
|
package net.tnose.app.trisquel
import android.R
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import org.apache.commons.compress.archivers.zip.ZipFile
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Calendar
import kotlin.coroutines.cancellation.CancellationException
class VersionUnmatchException : Exception()
sealed class WrappedZipFile {
data class JavaZipFile(val zf: java.util.zip.ZipFile): WrappedZipFile()
data class ApacheCCZipFile(val zf: ZipFile): WrappedZipFile()
}
class CustomImportException : Exception ("Internal backup before import failed!")
class ImportWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
private val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
companion object{
val PARAM_ZIPFILE = "zipfile"
val PARAM_URI = "uri"
val PARAM_MODE = "mode"
val PARAM_PERCENTAGE = "percentage"
val PARAM_STATUS = "status"
const val notificationId = 1
const val channelId = "trisquel_ch"
fun createImportRequest(zipFile : String, mode : Int): WorkRequest {
return OneTimeWorkRequestBuilder<ImportWorker>()
.setInputData(
workDataOf(
Pair(PARAM_ZIPFILE, zipFile),
Pair(PARAM_MODE, mode)
)
)
.addTag(Util.WORKER_TAG_IMPORT)
.build()
}
const val SUCCESS = 0
const val VERSION_UNMATCH = -1
const val CANCELED = -2
const val UNKNOWN = -999
}
val cameraIdOld2NewMap: HashMap<Int, Int> = HashMap()
val lensIdOld2NewMap: HashMap<Int, Int> = HashMap()
val accessoryIdOld2NewMap: HashMap<Int, Int> = HashMap()
val filmrollIdOld2NewMap: HashMap<Int, Int> = HashMap()
val filmrollNameByOldIdMap: HashMap<Int, String> = HashMap()
val photoIdOld2NewMap: HashMap<Int, Int> = HashMap()
override suspend fun doWork(): Result {
val uri = inputData.getString(PARAM_ZIPFILE)
val mode = inputData.getInt(PARAM_MODE, 0)
var success = false
setForeground(createForegroundInfo())
val retval = try {
backupDBBeforeImport()
val result = importFromZip(Uri.parse(uri), (mode == 0))
if(result != SUCCESS){
val errstr = when(result){
VERSION_UNMATCH -> "Database version is too new"
CANCELED -> "User canceled import operation"
UNKNOWN -> "Unknown error %d".format(result)
else -> "Impossible error %d".format(result)
}
Result.failure(
workDataOf(
Pair(PARAM_PERCENTAGE, 100.0),
Pair(PARAM_STATUS, errstr)))
}else {
success = true
Result.success(
workDataOf(
Pair(PARAM_PERCENTAGE, 100.0),
Pair(PARAM_STATUS, "Import from $uri completed")))
}
} catch (error: CancellationException) {
Result.failure(
workDataOf(
Pair(PARAM_PERCENTAGE, 100.0),
Pair(PARAM_STATUS, "Backup canceled.")))
} catch (e: Exception){
Result.failure(
workDataOf(
Pair(PARAM_PERCENTAGE, 100.0),
Pair(PARAM_STATUS, e.toString())))
}
notifyCompletion(success)
return retval
}
// https://developer.android.com/develop/background-work/background-tasks/persistent/how-to/long-running?hl=ja
private fun createForegroundInfo(): ForegroundInfo {
val title = "Importing"
val contentText = "Trisquel"
val cancel = "Cancel"
// This PendingIntent can be used to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(id)
createChannel()
val notification = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle(title)
.setTicker(title)
.setContentText(contentText)
.setSmallIcon(R.mipmap.sym_def_app_icon)
.setOngoing(true)
// Add the cancel action to the notification which can
// be used to cancel the worker
.addAction(R.drawable.ic_delete, cancel, intent)
.build()
//ステータスバーの通知を消せないようにする
notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
return ForegroundInfo(
notificationId,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
)
} else {
return ForegroundInfo(
notificationId,
notification
)
}
}
private fun createChannel() {
val g = NotificationChannelGroup("trisquel_ch_grp", "trisquel_ch_grp")
nm.createNotificationChannelGroups(arrayListOf(g))
val ch = NotificationChannel("trisquel_ch", "trisquel_ch", NotificationManager.IMPORTANCE_DEFAULT)
ch.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
nm.createNotificationChannel(ch)
}
private fun notifyCompletion(success: Boolean){
val i = Intent(applicationContext, MainActivity::class.java)
val pi = PendingIntent.getActivity(applicationContext, 0, i, PendingIntent.FLAG_IMMUTABLE)
val builder = NotificationCompat.Builder(applicationContext, channelId)
val msg = if (success) "Import completed." else "Import failed."
//Foreground Service
val n = builder.setContentIntent(pi)
.setGroup("trisquel_ch_grp")
.setSmallIcon(R.mipmap.sym_def_app_icon).setTicker("")
.setAutoCancel(true).setContentTitle(msg)
.setContentText("Trisquel").build()
//val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.notify(1, n)
}
private suspend fun bcastProgress(percentage: Double, status: String){
setProgress(workDataOf(Pair(PARAM_PERCENTAGE, percentage), Pair(PARAM_STATUS, status)))
}
fun getStringFromEntry(wzf: WrappedZipFile, entryName: String): String{
val stream: InputStream = when(wzf) {
is WrappedZipFile.JavaZipFile -> wzf.zf.getInputStream(wzf.zf.getEntry(entryName))
is WrappedZipFile.ApacheCCZipFile -> wzf.zf.getInputStream(wzf.zf.getEntry(entryName))
}
val baos = ByteArrayOutputStream()
val bos = BufferedOutputStream(baos)
val data = ByteArray(8*1024)
while (true) {
val count = stream.read(data, 0, 8*1024)
if (count < 0) break
bos.write(data, 0, count)
}
bos.flush()
val result = baos.toString()
bos.close()
stream.close()
return result
}
private fun getJSONObjectFromEntry(wzf: WrappedZipFile, entryName: String): JSONObject {
val str = getStringFromEntry(wzf, entryName)
return JSONObject(str)
}
private fun getJSONArrayFromEntry(wzf: WrappedZipFile, entryName: String): JSONArray {
val str = getStringFromEntry(wzf, entryName)
return JSONArray(str)
}
fun appendSuffix(fileName: String, suffixNumber: Int):String{
val lastDot = fileName.lastIndexOf('.')
if(lastDot < 0){
return fileName + "(%d)".format(suffixNumber)
}else{
return fileName.replaceRange(lastDot, lastDot, "(%d)".format(suffixNumber))
}
}
private fun getSafeFileNameP(relPath: String, displayName: String): String {
var currentCandidate = displayName
var suffixNumber = 1
while(true) {
val filePath = Environment.getExternalStorageDirectory().absolutePath + "/" + relPath + "/" + currentCandidate
val f = File(filePath)
if(!f.exists()) break
currentCandidate = appendSuffix(displayName, suffixNumber)
suffixNumber++
}
return currentCandidate
}
@RequiresApi(Build.VERSION_CODES.Q)
fun getSafeFileNameQ(relPath: String, displayName: String): String{
var currentCandidate = displayName
var suffixNumber = 1
while(true) {
/*val values = ContentValues().apply {
put(MediaStore.Images.Media.RELATIVE_PATH, relPath)
put(MediaStore.Images.Media.DISPLAY_NAME, currentCandidate)
}*/
val projection = arrayOf(
MediaStore.Images.Media.RELATIVE_PATH,
MediaStore.Images.Media.DISPLAY_NAME)
val selection = "${MediaStore.Images.Media.RELATIVE_PATH} = ? AND ${MediaStore.Images.Media.DISPLAY_NAME} = ?"
val selectionArgs = arrayOf(relPath, currentCandidate)
val cursor: Cursor? = applicationContext.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectionArgs, null)
if(cursor == null){
break
}else{
if(!cursor.moveToNext()) break
currentCandidate = appendSuffix(displayName, suffixNumber)
cursor.close()
}
suffixNumber++
}
return currentCandidate
}
private fun writeInMediaStoreP(relPath: String, displayName: String, ist: InputStream): String{
val dirPath = Environment.getExternalStorageDirectory().absolutePath + "/" + relPath
val dir = File(dirPath)
if(!dir.exists()){
dir.mkdirs()
}
val filePath = dirPath + "/" + displayName
val ost = FileOutputStream(filePath)
val bost = BufferedOutputStream(ost)
val data = ByteArray(8*1024)
while (true) {
val count = ist.read(data, 0, 8*1024)
if (count < 0) break
bost.write(data, 0, count)
}
bost.flush()
bost.close()
val values= ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
put(MediaStore.Images.Media.DATA, filePath)
}
val item = applicationContext.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
return item.toString()
}
@RequiresApi(Build.VERSION_CODES.Q)
fun writeInMediaStoreQ(relPath: String, displayName: String, ist: InputStream): String{
val values = ContentValues().apply {
put(MediaStore.Images.Media.RELATIVE_PATH, relPath)
put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val collection = MediaStore.Images.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val item = applicationContext.contentResolver.insert(collection, values)!!
val pfd = applicationContext.contentResolver.openFileDescriptor(item, "w", null)
if(pfd != null){
val ost = FileOutputStream(pfd.fileDescriptor)
val bost = BufferedOutputStream(ost)
val data = ByteArray(8*1024)
while (true) {
val count = ist.read(data, 0, 8*1024)
if (count < 0) break
bost.write(data, 0, count)
}
bost.flush()
bost.close()
pfd.close()
}
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
applicationContext.contentResolver.update(item, values, null, null)
return item.toString()
}
private fun newPathsFullRestore(wzf: WrappedZipFile, photo: JSONObject, dao: TrisquelDao, filmrollIdOld2NewMap: HashMap<Int, Int>): Pair<ArrayList<String>, String>{
val result = ArrayList<String>()
//val importErrors = ArrayList<String>()
if(photo.getString("suppimgs").isEmpty()) return Pair(result, "")
val filmRollOldId = photo.getInt("filmroll")
val filmRollNewId = filmrollIdOld2NewMap[filmRollOldId]!! // TODO: 手抜きなのであとでなおす
// もともとこうだったが、トランザクションを導入した結果、DBに格納された途中経過は
// 使えなくなったので、自前でフィルムのIDと名前のペアを持つことにする
// val folderName = dao.getFilmRoll(filmRollNewId)!!.name.replace('/', '_')
val folderName = filmrollNameByOldIdMap[filmRollOldId]!!.replace('/', '_')
val fileNames = photo.getJSONArray("suppimgs_file_name")
val md5sums = photo.getJSONArray("suppimgs_md5sum")
for(i in 0 until fileNames.length()){
val fileName = fileNames.getString(i)
if(fileName.isEmpty()) continue // こういうケースが本当にあってよいものか… 要確認な気がする
val md5sum = md5sums.getString(i)
val relPath = "Pictures/Trisquel/" + folderName
val safeFileName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
getSafeFileNameQ(relPath, fileName)
}else{
getSafeFileNameP(relPath, fileName)
}
/*val ze = zf.getEntry("imgs/" + md5sum)
if(ze == null){
Log.d("ZipFile", "zip entry for imgs/%s is null".format(md5sum))
}
val istream = zf.getInputStream(ze)
if(istream == null){
Log.d("ZipFile", "istream is null")
}*/
val entryName = "imgs/" + md5sum
val istream: InputStream = when(wzf) {
is WrappedZipFile.JavaZipFile -> wzf.zf.getInputStream(wzf.zf.getEntry(entryName))
is WrappedZipFile.ApacheCCZipFile -> wzf.zf.getInputStream(wzf.zf.getEntry(entryName))
}
val newpath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
writeInMediaStoreQ(relPath, safeFileName, istream)
}else{
writeInMediaStoreP(relPath, safeFileName, istream)
}
result.add(newpath)
istream.close()
}
return Pair(result, "")
}
private fun isContentUriExists(uri: Uri): Boolean{
var result = true
try{
val pfd = applicationContext.contentResolver.openFileDescriptor(uri, "r")
if(pfd==null){ result = false }
pfd?.close()
}catch(e: FileNotFoundException){
result = false
}
return result
}
private fun isMd5sumMatch(uri: Uri, md5sum: String): Boolean{
val ist = applicationContext.contentResolver.openInputStream(uri)
if(ist != null)
return MD5Util.digestAsStr(ist) == md5sum
else
return false
}
private fun getRealPathFromURI(contentUri: Uri): String {
var cursor: Cursor? = null
val result: String
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = applicationContext.contentResolver.query(contentUri, proj, null, null, null)
cursor!!.moveToFirst()
val column_index = cursor.getColumnIndex(proj[0])
result = cursor.getString(column_index)
} finally {
cursor?.close()
}
return result
}
private fun queryCandidateUris(fileName: String): ArrayList<String> {
val cr = applicationContext.contentResolver
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME)
val selection = "${MediaStore.Images.Media.DISPLAY_NAME} = ?"
val selectionArgs = arrayOf(fileName)
val cursor: Cursor? = cr.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectionArgs, null)
val paths = ArrayList<String>()
while (cursor?.moveToNext() == true) {
val idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID)
//val displayNameColumn = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
val id = cursor.getLong(idColumn)
val contentUri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id.toString()
)
paths.add(contentUri.toString())
}
cursor?.close()
return paths
}
private fun assumedPaths(photo: JSONObject): Pair<ArrayList<String>, String> {
val result = ArrayList<String>()
val importErrors = ArrayList<String>()
//Log.d("AssumePath", "suppimgs=" + photo.getString("suppimgs"))
val suppimgs: String = photo.getString("suppimgs")
val paths = if(suppimgs.isEmpty()) JSONArray() else JSONArray(suppimgs)
val fileNames = if(photo.isNull("suppimgs_file_name")) JSONArray() else photo.getJSONArray("suppimgs_file_name")
//val dateTakens = photo.getJSONArray("suppimgs_date_taken")
val md5sums = if(photo.isNull("suppimgs_md5sum")) JSONArray() else photo.getJSONArray("suppimgs_md5sum")
for (i in 0 until paths.length()) {
val path = paths.getString(i)
if(path.isEmpty()) continue
val fileName = fileNames.getString(i)
val md5sum = md5sums.getString(i)
// if(pathが存在してファイル名もmd5sumも一致) -> pathを採用(同じスマートフォンからのインポートを想定)
val contentUri = Uri.parse(path)
if(isContentUriExists(contentUri) && isMd5sumMatch(contentUri, md5sum)){
result.add(path)
}else{
val candidates = queryCandidateUris(fileName)
when(candidates.size){
//fileNameが存在して1個しかない -> これを採用(普通はこれになるはず)
//1 -> result.add(candidates.first()) //やめた。ファイルがないのにcontent://のURIがみつかることがある。中身もチェックしないとだめ
//fileNameが存在しない -> インポートエラーに追加
0 -> importErrors.add("Not found: " + fileName)
//md5sumが一致するものを全部追加(取りこぼすよりはええじゃろ)
else -> {
var foundSome = false
for(c in candidates){
Log.d("ImportDebug",
"fileName:" + fileName
+ " Candidate URI:" + c
+ " Path:" +getRealPathFromURI(Uri.parse(c)))
val ist = CompatibilityUtil.pathToInputStream(applicationContext.contentResolver, c, true)
if(ist!=null) {
val md5sumToCompare = MD5Util.digestAsStr(ist)
if(md5sum == md5sumToCompare){
result.add(c)
foundSome = true
}
}
}
if(!foundSome){
importErrors.add("Not found: " + fileName)
}
}
}
}
}
return Pair(result, importErrors.joinToString("\n"))
}
// インポート前に現在のDBを念の為アプリ内ローカルの領域にコピーしておく
@SuppressLint("SimpleDateFormat")
private fun backupDBBeforeImport(){
val dbpath = applicationContext.getDatabasePath("trisquel.db")
val calendar = Calendar.getInstance()
val sdf = SimpleDateFormat("yyyyMMddHHmmss")
val backupPath = dbpath.absolutePath + "." + sdf.format(calendar.time) + ".bak"
val fos = FileOutputStream(backupPath)
val fis = FileInputStream(dbpath)
val src = fis.channel
val dst = fos.channel
dst.transferFrom(src, 0, src.size())
src.close()
dst.close()
}
private fun CloseWrappedZipFile(wzf: WrappedZipFile){
when(wzf) {
is WrappedZipFile.JavaZipFile -> wzf.zf.close()
is WrappedZipFile.ApacheCCZipFile -> wzf.zf.close()
}
}
private suspend fun importFromZip(uri: Uri, merge: Boolean): Int{
var result = UNKNOWN
var pfd: ParcelFileDescriptor? = null
//どうもここでval pfdとするとファイルディスクリプタがGCされてしまう???
pfd = applicationContext.contentResolver.openFileDescriptor(uri, "r")
if (pfd == null) throw FileNotFoundException(uri.toString())
val fis = FileInputStream(pfd.fileDescriptor)
val zipfile: WrappedZipFile = WrappedZipFile.ApacheCCZipFile(ZipFile(fis.channel))
val dao = TrisquelDao(applicationContext)
dao.connection()
//try {
try {
val metadataJSON = getJSONObjectFromEntry(zipfile, "metadata.json")
val dbver = metadataJSON.getInt("DB_VERSION")
val mode = metadataJSON.getInt("EXPORT_MODE")
Log.d("importFromZip",
"DB_VERSION=" + dbver.toString() + ", " +
"EXPORT_MODE=" + mode.toString())
if (dbver > DatabaseHelper.DATABASE_VERSION) {
throw VersionUnmatchException()
}
dao.beginTransaction()
if (!merge) dao.deleteAll()
val cameraJSON = getJSONArrayFromEntry(zipfile, "camera.json")
for (i in 0 until cameraJSON.length()) {
val id_pair = dao.mergeCameraJSON(cameraJSON.getJSONObject(i))
cameraIdOld2NewMap[id_pair.first] = id_pair.second
}
val lensJSON = getJSONArrayFromEntry(zipfile, "lens.json")
for (i in 0 until lensJSON.length()) {
val id_pair = dao.mergeLensJSON(lensJSON.getJSONObject(i), cameraIdOld2NewMap)
lensIdOld2NewMap[id_pair.first] = id_pair.second
}
val accessoryJSON = getJSONArrayFromEntry(zipfile, "accessory.json")
for (i in 0 until accessoryJSON.length()) {
val id_pair = dao.mergeAccessoryJSON(accessoryJSON.getJSONObject(i))
accessoryIdOld2NewMap[id_pair.first] = id_pair.second
}
val filmrollJSON = getJSONArrayFromEntry(zipfile, "filmroll.json")
for (i in 0 until filmrollJSON.length()) {
val id_pair = dao.mergeFilmRollJSON(filmrollJSON.getJSONObject(i), cameraIdOld2NewMap)
filmrollIdOld2NewMap[id_pair.first] = id_pair.second
filmrollNameByOldIdMap[id_pair.first] = filmrollJSON.getJSONObject(i).getString("name")
}
val photoJSON = getJSONArrayFromEntry(zipfile, "photo.json")
for (i in 0 until photoJSON.length()) {
val pjo = photoJSON.getJSONObject(i)
val tmp: Pair<ArrayList<String>, String> =
if (mode == 0) assumedPaths(pjo)
else newPathsFullRestore(zipfile, pjo, dao, filmrollIdOld2NewMap)
val newpaths = tmp.first
val importErrorStr = tmp.second
// val (newpaths, importErrorStr) = tmp なぜかこれができない
val id_pair = dao.mergePhotoJSON(pjo, newpaths, importErrorStr,
cameraIdOld2NewMap, lensIdOld2NewMap, filmrollIdOld2NewMap, accessoryIdOld2NewMap)
photoIdOld2NewMap[id_pair.first] = id_pair.second
val msg = if(mode == 0) "Searching photo files..." else "Copying photo files..."
bcastProgress(i.toDouble() / photoJSON.length().toDouble() * 99.99, msg)
}
val tagJSON = getJSONArrayFromEntry(zipfile, "tag.json")
val tagmapJSON = getJSONArrayFromEntry(zipfile, "tagmap.json")
dao.mergeTagMapJSON(tagmapJSON, tagJSON, filmrollIdOld2NewMap, photoIdOld2NewMap)
//} catch( e: Exception ) {
// Log.d("ZipFile", e.toString())
dao.setTransactionSuccessful()
result = SUCCESS
} catch (e: VersionUnmatchException) {
result = VERSION_UNMATCH
} catch (e: Exception){
Log.d("Import", e.toString())
result = UNKNOWN
} finally {
CloseWrappedZipFile(zipfile)
dao.endTransaction()
dao.close()
//zipfile.close()
//tmpFile.delete()
}
//} catch( e: Exception ) {
//Log.d("ZipFile", e.toString())
//} finally {
//}
pfd.close() //念のため最後にpfdを触るコードを入れてGCさせない(いいのかこれで?) ついでにクローズもしてみる
return result
}
}
| 16
|
Kotlin
|
0
| 2
|
6c43ac8b89216421f9720e6d23d114f21a478ff3
| 25,661
|
Trisquel
|
Apache License 2.0
|
showcase/src/main/kotlin/com/kevlar/showcase/ui/activities/antipiracy/APActivityViewModel.kt
|
kevlar-kt
| 468,138,363
| false
|
{"Kotlin": 213285, "Shell": 3108}
|
/*
* Designed and developed by Kevlar 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.
*/
package com.kevlar.showcase.ui.activities.antipiracy
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kevlar.antipiracy.dsl.attestation.AntipiracyAttestation
import com.kevlar.antipiracy.KevlarAntipiracy
import com.kevlar.showcase.data.repo.AntipiracyRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class APActivityViewModel @Inject constructor(
private val securityRepository: AntipiracyRepository
) : ViewModel() {
private val _attestationState = MutableStateFlow(KevlarAntipiracy.blankAttestation())
val attestation: SharedFlow<AntipiracyAttestation> = _attestationState.stateIn(
viewModelScope,
SharingStarted.Eagerly,
initialValue = KevlarAntipiracy.blankAttestation()
)
fun requestAttestation() {
viewModelScope.launch {
_attestationState.value = securityRepository.attestate()
}
}
}
| 0
|
Kotlin
|
2
| 70
|
893012a184562ce0220e4c023acddb088e8854fb
| 1,648
|
kevlar
|
Apache License 2.0
|
core-ui/src/main/java/fr/nihilus/music/core/ui/actions/ExcludeTrackAction.kt
|
thibseisel
| 80,150,620
| false
| null |
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.nihilus.music.core.ui.actions
import fr.nihilus.music.core.database.exclusion.TrackExclusion
import fr.nihilus.music.core.database.exclusion.TrackExclusionDao
import fr.nihilus.music.core.media.MediaId
import fr.nihilus.music.core.os.Clock
import javax.inject.Inject
/**
* An action to exclude tracks from the music library.
* A track mark as excluded is no longer part of media collections.
*/
class ExcludeTrackAction @Inject constructor(
private val excludeList: TrackExclusionDao,
private val clock: Clock
) {
suspend fun exclude(trackMediaId: MediaId) {
val trackId = requireNotNull(trackMediaId.track)
excludeList.exclude(TrackExclusion(trackId, clock.currentEpochTime))
}
}
| 14
|
Kotlin
|
7
| 48
|
7d1f78301ae1dd0801cee48c98e8729e0a8248d1
| 1,320
|
android-odeon
|
Apache License 2.0
|
kotlin/workflows/serverless-generator/src/main/kotlin/com/github/frtu/workflow/serverlessworkflow/state/AbstractStateBuilder.kt
|
frtu
| 338,595,537
| false
|
{"Kotlin": 396231, "Java": 157399, "Shell": 10826, "Dockerfile": 248}
|
package com.github.frtu.workflow.serverlessworkflow.state
import com.github.frtu.workflow.serverlessworkflow.DslBuilder
import io.serverlessworkflow.api.end.End
import io.serverlessworkflow.api.states.DefaultState
import io.serverlessworkflow.api.transitions.Transition
/**
* Base class for Builder state
*
* @author frtu
* @since 1.2.5
*/
@DslBuilder
abstract class AbstractStateBuilder<STATE : DefaultState>(
state: STATE,
type: DefaultState.Type,
name: String? = null,
terminate: Boolean = false,
) : AbstractBuilder<STATE>(state, name) {
init {
model.withType(type)
assignTerminate(terminate)
}
@DslBuilder
override var name: String
get() = model.name
set(value) { assignName(value) }
override fun assignName(value: String?) {
value?.let { model.withName(it) }
}
@DslBuilder
override var transition: String?
get() = model.transition?.nextState
set(value) { assignTransition(value) }
override fun assignTransition(value: String?) {
value?.let { model.withTransition(Transition(it)) }
}
@DslBuilder
open var terminate: Boolean
get() = model.end?.isTerminate ?: false
set(value) {
assignTerminate(value)
}
private fun assignTerminate(value: Boolean) {
if (value) {
model.withEnd(End().withTerminate(true))
}
}
}
| 0
|
Kotlin
|
0
| 1
|
d641ca6826d57d91985da34492eff8a92ad9261e
| 1,425
|
lib-toolbox
|
Apache License 2.0
|
platform/backend/api/src/main/kotlin/io/hamal/api/http/endpoint/exec/ExecListController.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 1678862, "C": 1398401, "TypeScript": 47224, "Lua": 41508, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 449, "CSS": 118}
|
package io.hamal.api.http.endpoint.exec
import io.hamal.core.adapter.ListExecsPort
import io.hamal.lib.common.domain.Limit
import io.hamal.lib.domain.vo.ExecId
import io.hamal.lib.domain.vo.FuncId
import io.hamal.lib.domain.vo.GroupId
import io.hamal.lib.sdk.api.ApiExecList
import io.hamal.repository.api.ExecQueryRepository
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
internal class ExecListController(private val listExec: ListExecsPort) {
@GetMapping("/v1/execs")
fun list(
@RequestParam(required = false, name = "after_id", defaultValue = "7FFFFFFFFFFFFFFF") afterId: ExecId,
@RequestParam(required = false, name = "limit", defaultValue = "100") limit: Limit,
@RequestParam(required = false, name = "group_ids", defaultValue = "") groupIds: List<GroupId>,
@RequestParam(required = false, name = "func_ids", defaultValue = "") funcIds: List<FuncId>
): ResponseEntity<ApiExecList> {
return listExec(
ExecQueryRepository.ExecQuery(
afterId = afterId,
limit = limit,
groupIds = groupIds,
funcIds = funcIds
)
) { execs ->
ResponseEntity.ok(
ApiExecList(
execs = execs.map {
ApiExecList.Exec(
id = it.id,
status = it.status,
correlation = it.correlation,
)
}
)
)
}
}
}
| 6
|
Kotlin
|
0
| 0
|
fd06bf799f18db2d425b7084abf15b741fa9878e
| 1,758
|
hamal
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/io/kotlintest/specs/BehaviorSpec.kt
|
terachanple
| 92,839,408
| true
|
{"Kotlin": 148733}
|
package io.kotlintest.specs
import io.kotlintest.*
import org.junit.runner.RunWith
@RunWith(KTestJUnitRunner::class) // required to let IntelliJ discover tests
abstract class BehaviorSpec(body: BehaviorSpec.() -> Unit = {}) : Spec() {
init {
body()
}
fun Given(description: String, init: Given.() -> Unit): Unit = given(description, init)
fun given(description: String, init: Given.() -> Unit): Unit {
val suite = TestSuite("Given ${sanitizeSpecName(description)}")
rootTestSuite.addNestedSuite(suite)
val given = Given(suite)
given.init()
}
inner class Given(val nestedSuite: TestSuite) {
fun `When`(description: String, init: When.() -> Unit): Unit = `when`(description, init)
fun `when`(description: String, init: When.() -> Unit): Unit {
val suite = TestSuite("When ${sanitizeSpecName(description)}")
nestedSuite.addNestedSuite(suite)
val `when` = When(suite)
`when`.init()
}
}
inner class When(val nestedSuite: TestSuite) {
fun Then(description: String, check: () -> Unit): TestCase = then(description, check)
fun then(description: String, check: () -> Unit): TestCase {
val testCase =
TestCase(
nestedSuite,
"Then ${sanitizeSpecName(description)}",
check,
defaultTestCaseConfig)
nestedSuite.addTestCase(testCase)
return testCase
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6620bef3add4c0c199a4d636a77a9513c19a49c6
| 1,417
|
kotlintest
|
Apache License 2.0
|
src/main/kotlin/org/crystal/intellij/lang/psi/CrCUnion.kt
|
asedunov
| 353,165,557
| false
|
{"Kotlin": 1661507, "Java": 554445, "Crystal": 245131, "Lex": 192822, "HTML": 445}
|
package org.crystal.intellij.lang.psi
import com.intellij.lang.ASTNode
import org.crystal.intellij.lang.parser.CR_C_UNION_DEFINITION
import org.crystal.intellij.lang.stubs.api.CrCUnionStub
class CrCUnion : CrCStructLikeDefinition<CrCUnion, CrCUnionStub> {
constructor(stub: CrCUnionStub) : super(stub, CR_C_UNION_DEFINITION)
constructor(node: ASTNode) : super(node)
override fun accept(visitor: CrVisitor) = visitor.visitCUnion(this)
}
| 11
|
Kotlin
|
4
| 33
|
2e255da6c56a33109b8c58a0aa1a692abf977da2
| 451
|
intellij-crystal-lang
|
Apache License 2.0
|
app/src/main/java/com/mobilescanner/main/feature_community/ui/ContentViewModel.kt
|
EricMoin
| 706,004,415
| false
|
{"Kotlin": 165276}
|
package com.mobilescanner.main.feature_community.ui
import androidx.lifecycle.ViewModel
import com.mobilescanner.main.feature_community.data.item.ContentItem
class ContentViewModel : ViewModel() {
val contentList = mutableListOf<ContentItem>(
ContentItem(
"https://lmg.jj20.com/up/allimg/1115/101021110256/211010110256-8-1200.jpg",
"这是如今的香港,城市风景美如画"
),
ContentItem(
"https://c-ssl.dtstatic.com/uploads/item/201703/23/20170323142829_JfFYy.thumb.1000_0.jpeg",
"故宫博物院上新啦!这是本期的好物推荐"
),
ContentItem(
"https://img.book118.com/sr1/M00/18/24/wKh2Al7acSGIAHASAABiqUt3w3QAAjQ-wGr3AoAAGLB557.png",
"家人们最近开了一个小蛋糕店这是我们的项目企划书大家看看有什么地方还需要改进吗"
),
ContentItem(
"https://lmg.jj20.com/up/allimg/1115/101021110256/211010110256-8-1200.jpg",
"这是如今的香港,城市风景美如画"
),
ContentItem(
"https://c-ssl.dtstatic.com/uploads/item/201703/23/20170323142829_JfFYy.thumb.1000_0.jpeg",
"故宫博物院上新啦!这是本期的好物推荐"
),
ContentItem(
"https://img.book118.com/sr1/M00/18/24/wKh2Al7acSGIAHASAABiqUt3w3QAAjQ-wGr3AoAAGLB557.png",
"家人们最近开了一个小蛋糕店这是我们的项目企划书大家看看有什么地方还需要改进吗"
),
ContentItem(
"https://lmg.jj20.com/up/allimg/1115/101021110256/211010110256-8-1200.jpg",
"这是如今的香港,城市风景美如画"
),
ContentItem(
"https://c-ssl.dtstatic.com/uploads/item/201703/23/20170323142829_JfFYy.thumb.1000_0.jpeg",
"故宫博物院上新啦!这是本期的好物推荐"
),
ContentItem(
"https://img.book118.com/sr1/M00/18/24/wKh2Al7acSGIAHASAABiqUt3w3QAAjQ-wGr3AoAAGLB557.png",
"家人们最近开了一个小蛋糕店这是我们的项目企划书大家看看有什么地方还需要改进吗"
),
ContentItem(
"https://lmg.jj20.com/up/allimg/1115/101021110256/211010110256-8-1200.jpg",
"这是如今的香港,城市风景美如画"
),
ContentItem(
"https://c-ssl.dtstatic.com/uploads/item/201703/23/20170323142829_JfFYy.thumb.1000_0.jpeg",
"故宫博物院上新啦!这是本期的好物推荐"
),
ContentItem(
"https://img.book118.com/sr1/M00/18/24/wKh2Al7acSGIAHASAABiqUt3w3QAAjQ-wGr3AoAAGLB557.png",
"家人们最近开了一个小蛋糕店这是我们的项目企划书大家看看有什么地方还需要改进吗"
)
)
}
| 0
|
Kotlin
|
0
| 0
|
64bd7ce7d204aed42c8575059bcf768930017990
| 2,287
|
Open-MobileScanner
|
Apache License 2.0
|
android/airship-framework-proxy/src/main/java/com/urbanairship/android/framework/proxy/events/DisplayMessageCenterEvent.kt
|
urbanairship
| 587,525,727
| false
| null |
/* Copyright Urban Airship and Contributors */
package com.urbanairship.android.framework.proxy.events
import com.urbanairship.android.framework.proxy.Event
import com.urbanairship.android.framework.proxy.EventType
import com.urbanairship.json.JsonMap
import com.urbanairship.json.jsonMapOf
/**
* Show inbox event.
*
* @param messageId The optional message ID.
*/
internal class DisplayMessageCenterEvent(messageId: String?) : Event {
override val type = EventType.DISPLAY_MESSAGE_CENTER
override val body: JsonMap = jsonMapOf("messageId" to messageId)
}
| 0
|
Kotlin
|
2
| 1
|
6bbb3a61cd9b5b0b2531263a9a9b2940d2f89bf3
| 572
|
airship-mobile-framework-proxy
|
Apache License 2.0
|
src/main/kotlin/days/day2/Day2.kt
|
Stenz123
| 725,707,248
| false
|
{"Kotlin": 6120, "Shell": 862}
|
package days.day2
import days.Day
class Day2: Day(false) {
override fun partOne(): Any {
val games = readInput().map{
val id = it.substringBefore(":").substringAfter(" ").toInt()
val values = it.substringAfter(": ").replace(";",",").split(", ").map{ it ->
val color = it.substringAfter(" ").toLowerCase()
val value = it.substringBefore(" ").toInt()
ColorValue(color, value)
}
Game(id, values)
}
val validGames = games.filter { game ->
game.value.all { color ->
(color.color != "red" || color.value <= 12) &&
(color.color != "green" || color.value <= 13) &&
(color.color != "blue" || color.value <= 14)
}
}
return validGames.sumOf { it.id }
}
override fun partTwo(): Any {
val games = readInput().map{
val id = it.substringBefore(":").substringAfter(" ").toInt()
val values = it.substringAfter(": ").replace(";",",").split(", ").map{ it ->
val color = it.substringAfter(" ").toLowerCase()
val value = it.substringBefore(" ").toInt()
ColorValue(color, value)
}
Game(id, values)
}
val map: MutableMap<Game, ArrayList<ColorValue>> = mutableMapOf()
for (game in games) {
map[game] = arrayListOf()
map[game]?.add(ColorValue("red",game.value.filter { it.color == "red" }.map { it.value }.max()))
map[game]?.add(ColorValue("green",game.value.filter { it.color == "green" }.map { it.value }.max()))
map[game]?.add(ColorValue("blue",game.value.filter { it.color == "blue" }.map { it.value }.max()))
}
return map.map { it.value.map { it.value }.reduce{ acc, i -> acc * i } }.sum()
}
}
class Game(val id:Int, val value:List<ColorValue>){
override fun toString(): String {
return "Game(id=$id, value=$value)"
}
}
class ColorValue(val color:String, val value:Int){
override fun toString(): String {
return "ColorValue(color='$color', value=$value)"
}
}
| 0
|
Kotlin
|
1
| 0
|
ae81fd2976e4fb58c701ff6400a8e7d173d6e09c
| 2,202
|
advent-of-code_2023
|
The Unlicense
|
feature/calendar/calendar/src/main/kotlin/com/ngapps/phototime/feature/calendar/calendar/color/CalendarColor.kt
|
ngapp-dev
| 752,386,763
| false
|
{"Kotlin": 1833486, "Shell": 10136}
|
/*
* Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ngapps.phototime.feature.calendar.calendar.color
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.Color
/**
* The `color` package provides color-related classes and utilities for the Calendar library.
*
* It includes predefined color schemes for backgrounds, day backgrounds, and header text colors.
*
* @see CalendarColor
* @see CalendarColors
*/
@Stable
@SuppressWarnings("MagicNumber")
private val headerBackgroundColor = Color(0xFFFCEFFE)
@Stable
@SuppressWarnings("MagicNumber")
private val calendarBackgroundColor = Color(0xFFFCEFFE)
@Stable
@SuppressWarnings("MagicNumber")
private val headerTextColor = Color(0xFF000000)
@Stable
@SuppressWarnings("MagicNumber")
private val calendarTextColor = Color(0xFF000000)
@Stable
@SuppressWarnings("MagicNumber")
private val dayBackgroundColor = Color(0xffF1F4C8)
/**
* A stable representation of a specific color scheme for Calendar.
*
* @property headerBackgroundColor The background color.
* @property calendarBackgroundColor The background color.
* @property headerIconColor The color for header text.
* @property calendarTextColor The color for header text.
* @property dayBackgroundColor The color for day backgrounds.
*/
data class CalendarColor(
val headerBackgroundColor: Color,
val calendarBackgroundColor: Color,
val headerIconColor: Color,
val calendarTextColor: Color,
val dayBackgroundColor: Color,
) {
companion object {
internal fun previewDefault() = CalendarColor(
headerBackgroundColor,
calendarBackgroundColor,
headerTextColor,
calendarTextColor,
dayBackgroundColor,
)
}
}
/**
* A collection of predefined color schemes for Сalendar.
*
* @property color A list of [CalendarColor] instances.
*/
data class CalendarColors(
val color: CalendarColor
) {
companion object {
/**
* Returns the default set of colors.
*
* @return The default [CalendarColors] instance.
*/
fun default(): CalendarColors {
val colors =
CalendarColor(
headerBackgroundColor,
calendarBackgroundColor,
headerTextColor,
calendarTextColor,
dayBackgroundColor,
)
return CalendarColors(colors)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
bc1990bccd9674c6ac210fa72a56ef5318bf7241
| 3,080
|
phototime
|
Apache License 2.0
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinBitFlips.kt
|
ashtanko
| 203,993,092
| false
|
{"Kotlin": 7520849, "Shell": 1168, "Makefile": 1144}
|
/*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 2220. Minimum Bit Flips to Convert Number
* @see <a href="https://leetcode.com/problems/minimum-bit-flips-to-convert-number/">Source</a>
*/
fun interface MinBitFlips {
operator fun invoke(start: Int, goal: Int): Int
}
class MinBitFlipsKernighansAlgorithm : MinBitFlips {
override fun invoke(start: Int, goal: Int): Int {
var flips = 0
var xor = start xor goal
while (xor != 0) {
xor = xor and (xor - 1)
flips++
}
return flips
}
}
| 6
|
Kotlin
|
0
| 19
|
b8d05d3b10a8b16d156234775c655038cbbfac3c
| 1,149
|
Kotlin-Lab
|
Apache License 2.0
|
app/src/test/java/io/astronout/dicodingstoryapp/ui/auth/register/RegisterViewModelTest.kt
|
ariastro
| 678,904,369
| false
| null |
package io.astronout.dicodingstoryapp.ui.auth.register
import io.astronout.dicodingstoryapp.domain.AuthUsecase
import io.astronout.dicodingstoryapp.utils.Dummies
import io.astronout.dicodingstoryapp.vo.Resource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
internal class RegisterViewModelTest {
@Mock
private lateinit var authUsecase: AuthUsecase
private lateinit var registerViewModel: RegisterViewModel
private val dummyRegisterResponse = Dummies.generateDummyRegister()
private val dummyName = "<NAME>"
private val dummyEmail = "<EMAIL>"
private val dummyPassword = "<PASSWORD>"
@Before
fun setUp() {
registerViewModel = RegisterViewModel(authUsecase)
}
@Test
fun `Registration success - result success`(): Unit = runTest {
val expectedResponse = flowOf(Resource.Success(dummyRegisterResponse))
`when`(authUsecase.register(dummyName, dummyEmail, dummyPassword)).thenReturn(
expectedResponse
)
registerViewModel.register(dummyName, dummyEmail, dummyPassword).collect {
Assert.assertTrue(it is Resource.Success)
Assert.assertFalse(it is Resource.Error)
if (it is Resource.Success) {
Assert.assertNotNull(it.data)
Assert.assertSame(dummyRegisterResponse, it.data)
} else {
Assert.fail()
}
}
verify(authUsecase).register(dummyName, dummyEmail, dummyPassword)
}
@Test
fun `Registration failed - result error with message`(): Unit = runTest {
val expectedResponse = flow {
emit(Resource.Error("Register failed"))
}
`when`(authUsecase.register(dummyName, dummyEmail, dummyPassword)).thenReturn(
expectedResponse
)
registerViewModel.register(dummyName, dummyEmail, dummyPassword).collect {
Assert.assertFalse(it is Resource.Success)
Assert.assertTrue(it is Resource.Error)
if (it is Resource.Error) {
Assert.assertNotNull(it.message)
} else {
Assert.fail()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7c85e2af777e4fa98aa9e9990d4800853b38ece9
| 2,599
|
DicodingStoryApp
|
MIT License
|
app/src/main/java/dev/mayank/cowinvaccinebook/view/adapter/BeneficiaryRvAdapter.kt
|
hackelite01
| 370,006,949
| false
| null |
package dev.mayank.cowinvaccinebook.view.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import dev.mayank.cowinvaccinebook.R
import dev.mayank.cowinvaccinebook.data.model.BeneficiarySummary
import dev.mayank.cowinvaccinebook.databinding.ItemBeneficiaryBinding
class BeneficiaryRvAdapter: RecyclerView.Adapter<BeneficiaryRvAdapter.BeneficiaryViewHolder>() {
private val beneficiaries = mutableListOf<BeneficiarySummary>()
private var enableCheckBoxes = true
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BeneficiaryViewHolder {
val binding = DataBindingUtil.inflate<ItemBeneficiaryBinding>(LayoutInflater.from(parent.context),
R.layout.item_beneficiary, parent, false)
return BeneficiaryViewHolder(binding)
}
override fun onBindViewHolder(holder: BeneficiaryViewHolder, position: Int) {
holder.bind(beneficiaries[position])
}
override fun getItemCount(): Int = beneficiaries.size
fun setBeneficiaries(beneficiaries: List<BeneficiarySummary>) {
val diffUtilCallback = BeneficiaryDiffCallBack(this.beneficiaries, beneficiaries)
val diffResult = DiffUtil.calculateDiff(diffUtilCallback)
this.beneficiaries.clear()
this.beneficiaries.addAll(beneficiaries)
diffResult.dispatchUpdatesTo(this)
}
fun enableChecking(enable: Boolean) {
this.enableCheckBoxes = enable
notifyDataSetChanged()
}
inner class BeneficiaryViewHolder(
private val binding: ItemBeneficiaryBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(beneficiarySummary: BeneficiarySummary) {
binding.cbBeneficiary.setOnCheckedChangeListener { _, isChecked ->
beneficiarySummary.isChecked = isChecked
}
binding.viewmodel = beneficiarySummary
binding.executePendingBindings()
binding.cbBeneficiary.isEnabled = enableCheckBoxes
}
}
}
class BeneficiaryDiffCallBack(
private val oldList: List<BeneficiarySummary>,
private val newList: List<BeneficiarySummary>
): DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].brId == newList[newItemPosition].brId
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
return oldItem.brId == newItem.brId &&
oldItem.isChecked == newItem.isChecked &&
oldItem.name == newItem.name &&
oldItem.vaccinationStatus == newItem.vaccinationStatus &&
oldItem.vaccine == newItem.vaccine
}
}
| 0
|
Kotlin
|
0
| 3
|
36cdad2997c2f62a7ddf1ffa20ec2b35c65b0e73
| 3,050
|
cowin-vaccine-booking
|
MIT License
|
miniapp/src/main/java/com/rakuten/tech/mobile/miniapp/errors/MiniAppBridgeErrorModel.kt
|
rakutentech
| 225,744,634
| false
|
{"Kotlin": 1372714}
|
package com.rakuten.tech.mobile.miniapp.errors
import androidx.annotation.Keep
/**
* A data class to prepare the json object of custom error to be sent from this to miniapp.
*/
@Keep
internal data class MiniAppBridgeErrorModel(
val type: String? = null,
val message: String? = null
)
| 9
|
Kotlin
|
35
| 73
|
466c9551161b1240cc4963d7108a342355b983de
| 296
|
android-miniapp
|
MIT License
|
src/test/kotlin/guru/drako/eventer/alexa/ApplicationTest.kt
|
ChemnitzHackt
| 108,638,262
| false
| null |
package guru.drako.eventer.alexa
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment
import org.springframework.context.ApplicationContext
import org.springframework.test.context.junit.jupiter.SpringExtension
import kotlin.test.assertTrue
@ExtendWith(SpringExtension::class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
class ApplicationTest {
@field:Autowired
private lateinit var ctx: ApplicationContext
@Test
@DisplayName("DI container contains required beans")
fun checkRequiredBeans() {
assertTrue(ctx.containsBean("application"))
}
}
| 1
|
Kotlin
|
0
| 0
|
055d2e79c578987ae345057fbcbc12a25e947960
| 838
|
eventer-alexa-skill
|
Apache License 2.0
|
VectorLib/src/test/kotlin/api/ConstructorTests.kt
|
cout970
| 68,244,385
| false
| null |
package api
import com.cout970.vector.extensions.*
import com.cout970.vector.impl.*
import org.junit.Assert
import org.junit.Test
class ConstructorTests {
@Test
fun `Tests basic constructors`() {
val a1 = vec2Of(1, 2)
val a2 = mutableVec2Of(3, 4)
val a3 = vec3Of(5, 6, 7)
val a4 = mutableVec3Of(8, 9, 10)
val a5 = vec4Of(11, 12, 13, 14)
val a6 = mutableVec4Of(15, 16, 17, 18)
val a7 = quatOf(19, 20, 21, 22)
val a8 = mutableQuatOf(23, 24, 25, 26)
Assert.assertTrue(a1 is Vector2d)
Assert.assertTrue(a2 is MutableVector2d)
Assert.assertTrue(a3 is Vector3d)
Assert.assertTrue(a4 is MutableVector3d)
Assert.assertTrue(a5 is Vector4d)
Assert.assertTrue(a6 is MutableVector4d)
Assert.assertTrue(a7 is Quaterniond)
Assert.assertTrue(a8 is MutableQuaterniond)
Assert.assertEquals(1.0, a1.x)
Assert.assertEquals(2.0, a1.y)
Assert.assertEquals(3.0, a2.x)
Assert.assertEquals(4.0, a2.y)
Assert.assertEquals(5.0, a3.x)
Assert.assertEquals(6.0, a3.y)
Assert.assertEquals(7.0, a3.z)
Assert.assertEquals(8.0, a4.x)
Assert.assertEquals(9.0, a4.y)
Assert.assertEquals(10.0, a4.z)
Assert.assertEquals(11.0, a5.x)
Assert.assertEquals(12.0, a5.y)
Assert.assertEquals(13.0, a5.z)
Assert.assertEquals(14.0, a5.w)
Assert.assertEquals(15.0, a6.x)
Assert.assertEquals(16.0, a6.y)
Assert.assertEquals(17.0, a6.z)
Assert.assertEquals(18.0, a6.w)
Assert.assertEquals(19.0, a7.x)
Assert.assertEquals(20.0, a7.y)
Assert.assertEquals(21.0, a7.z)
Assert.assertEquals(22.0, a7.w)
Assert.assertEquals(23.0, a8.x)
Assert.assertEquals(24.0, a8.y)
Assert.assertEquals(25.0, a8.z)
Assert.assertEquals(26.0, a8.w)
}
@Test
fun `Test quatOfAxisAngled`(){
val a1 = quatOfAxisAngledDeg(90, 1, 0,0)
val a2 = quatOfAxisAngledDeg(90, 0, 1,0)
val a3 = quatOfAxisAngledDeg(90, 0, 0,1)
val a4 = quatOfAxisAngledDeg(90, 0, 0,0)
val a5 = quatOfAxisAngledDeg(-90, 1, 0,0)
val a6 = quatOfAxisAngledDeg(-90, 0, 1,0)
val a7 = quatOfAxisAngledDeg(-90, 0, 0,1)
val a8 = quatOfAxisAngledDeg(180, 1, 0,0)
val a9 = quatOfAxisAngledDeg(-180, 1, 0,0)
assertQuatEquals(Quaterniond(xd=0.7071067811865475, yd=0.0, zd=0.0, wd=0.7071067811865476), a1)
assertQuatEquals(Quaterniond(xd=0.0, yd=0.7071067811865475, zd=0.0, wd=0.7071067811865476), a2)
assertQuatEquals(Quaterniond(xd=0.0, yd=0.0, zd=0.7071067811865475, wd=0.7071067811865476), a3)
assertQuatEquals(Quaterniond(xd=0.0, yd=0.0, zd=0.0, wd=0.7071067811865476), a4)
assertQuatEquals(Quaterniond(xd=-0.7071067811865475, yd=-0.0, zd=-0.0, wd=0.7071067811865476), a5)
assertQuatEquals(Quaterniond(xd=-0.0, yd=-0.7071067811865475, zd=-0.0, wd=0.7071067811865476), a6)
assertQuatEquals(Quaterniond(xd=-0.0, yd=-0.0, zd=-0.7071067811865475, wd=0.7071067811865476), a7)
assertQuatEquals(Quaterniond(xd=1.0, yd=0.0, zd=0.0, wd=-0.0), a8)
assertQuatEquals(Quaterniond(xd=-1.0, yd=-0.0, zd=-0.0, wd=0.0), a9)
}
@Test
fun `Test mutableQuatOfAxisAngled`(){
val a1 = mutableQuatOfAxisAngled(90, 1, 0,0)
val a2 = mutableQuatOfAxisAngled(90, 0, 1,0)
val a3 = mutableQuatOfAxisAngled(90, 0, 0,1)
val a4 = mutableQuatOfAxisAngled(90, 0, 0,0)
val a5 = mutableQuatOfAxisAngled(-90, 1, 0,0)
val a6 = mutableQuatOfAxisAngled(-90, 0, 1,0)
val a7 = mutableQuatOfAxisAngled(-90, 0, 0,1)
val a8 = mutableQuatOfAxisAngled(180, 1, 0,0)
val a9 = mutableQuatOfAxisAngled(-180, 1, 0,0)
assertQuatEquals(MutableQuaterniond(xd=0.7071067811865475, yd=0.0, zd=0.0, wd=0.7071067811865476), a1)
assertQuatEquals(MutableQuaterniond(xd=0.0, yd=0.7071067811865475, zd=0.0, wd=0.7071067811865476), a2)
assertQuatEquals(MutableQuaterniond(xd=0.0, yd=0.0, zd=0.7071067811865475, wd=0.7071067811865476), a3)
assertQuatEquals(MutableQuaterniond(xd=0.0, yd=0.0, zd=0.0, wd=0.7071067811865476), a4)
assertQuatEquals(MutableQuaterniond(xd=-0.7071067811865475, yd=-0.0, zd=-0.0, wd=0.7071067811865476), a5)
assertQuatEquals(MutableQuaterniond(xd=-0.0, yd=-0.7071067811865475, zd=-0.0, wd=0.7071067811865476), a6)
assertQuatEquals(MutableQuaterniond(xd=-0.0, yd=-0.0, zd=-0.7071067811865475, wd=0.7071067811865476), a7)
assertQuatEquals(MutableQuaterniond(xd=1.0, yd=0.0, zd=0.0, wd=-0.0), a8)
assertQuatEquals(MutableQuaterniond(xd=-1.0, yd=-0.0, zd=-0.0, wd=0.0), a9)
}
}
| 0
|
Kotlin
|
0
| 0
|
069683154d3f516e04af8a7088662a68ce4d8fc4
| 4,794
|
Libraries
|
MIT License
|
src/main/kotlin/algorithms/NumUtils.kt
|
xmmmmmovo
| 280,634,710
| false
| null |
/*
* Copyright (c) 2020. xmmmmmovo
*/
package algorithms
import ds.LinkedList
import edu.princeton.cs.algs4.StdRandom
import ext.compareTo
/**
* 蛮力法求三数之和
* @author xmmmmmovo
* @date 2020/7/28 16:09
* @param list 数字列表
* @param num 所求的数字
* @return 满足条件的个数
* @since version-1.0
*/
fun threeSumForce(list: List<Int>, num: Int): List<List<Int>> {
val res = LinkedList<List<Int>>()
val sl = list.sorted().run {
if (containsDuplicatesInSorted(this))
distinct()
else
this
}
for (a in sl.indices)
for (b in a + 1 until sl.size)
for (c in b + 1 until sl.size)
if (sl[a] + sl[b] + sl[c] == num) {
res.add(listOf(sl[a], sl[b], sl[c]))
}
return res
}
/**
* 二分法[binarySearch]求三数之和
* @author xmmmmmovo
* @date 2020/7/28 16:09
* @param list 数字列表
* @return 满足和为0的所有组合的列表
* @throws IllegalArgumentException 数组元素小于3个时抛出异常
* @since version-1.0
*/
fun threeSumBinaryFast(list: List<Int>, num: Int): List<List<Int>> {
val res = LinkedList<List<Int>>()
val sl = list.sorted().run {
if (containsDuplicatesInSorted(this))
distinct()
else
this
}
if (list.size < 3) throw IllegalArgumentException("数组非重复元素小于3个!")
for (i in sl.indices) {
for (j in i + 1 until sl.size) {
val k = binarySearch(sl, num - (sl[i] + sl[j]), j + 1)
if (k != -1) {
res.add(listOf(sl[i], sl[j], sl[k]))
}
}
}
return res
}
/**
* 矩阵局部最小元素
* @author xmmmmmovo
* @date 2020/7/30 19:36
* @param matrix 矩阵
* @return 最小元素数字
* @throws IllegalArgumentException 矩阵为空的时候抛出异常
* @since version-1.0
*/
fun <T : Comparable<T>> matrixPartialMinElem(matrix: List<List<T>>): Pair<Int, Int> {
if (matrix.isEmpty()) throw IllegalArgumentException("矩阵不能为空!")
var lor = 0
var hir = matrix.size - 1
while (lor <= hir) {
val mr = lor + (hir - lor) / 2
val kc = partialMinElem(matrix[mr])
when {
kc == -1 -> {
lor++
}
mr == 0 ->
if (matrix[mr + 1][kc] > matrix[mr][kc])
return Pair(mr, kc)
else
lor = mr + 1
mr == matrix.size - 1 ->
if (matrix[mr][kc] < matrix[mr - 1][kc])
return Pair(mr, kc)
else
hir = mr - 1
matrix[mr - 1][kc] > matrix[mr][kc] && matrix[mr][kc] < matrix[mr + 1][kc] ->
return Pair(mr, kc)
matrix[mr - 1][kc] < matrix[mr][kc] && matrix[mr][kc] < matrix[mr + 1][kc] ->
hir = mr - 1
matrix[mr - 1][kc] < matrix[mr][kc] && matrix[mr][kc] > matrix[mr + 1][kc] ->
if (matrix[mr - 1][kc] >= matrix[mr + 1][kc]) lor = mr + 1 else hir = mr - 1
else -> lor = mr + 1
}
}
return Pair(-1, -1)
}
/**
* 生日问题
* 验证第一个重复随机数之前生成的整数数量为(ΠN/2)^(1/2)
* 具体测试查看Test文件
* @author xmmmmmovo
* @date 2020/7/30 12:24
* @param N 生成的数量
* @return 返回第一个重复的随机数时生成的数字数量
* @since version-1.0
*/
fun firstRandomDuplicate(N: Int): Int {
val m = mutableSetOf<Int>()
var i = 0
while (true) {
val rn = StdRandom.uniform(N)
if (m.contains(rn))
return i
m.add(rn)
i++
}
}
| 0
|
Kotlin
|
0
| 0
|
94da0519cf2b8d8a9b42b4aea09caf50d9732599
| 3,403
|
Algorithms4thEditionKotlinSolutions
|
Apache License 2.0
|
library/src/main/java/dev/luckybet100/android/dragging/rotation/MatrixGestureDetector.kt
|
luckybet100
| 312,357,415
| false
|
{"Kotlin": 25141}
|
package dev.luckybet100.android.dragging.rotation
import android.graphics.Matrix
import android.util.Log
import android.view.MotionEvent
import dev.luckybet100.android.dragging.utils.getPointerPosition
class MatrixGestureDetector(private val listener: OnRotationGestureListener) {
interface OnRotationGestureListener {
fun onRotationBegin(detector: MatrixGestureDetector)
fun onRotation(detector: MatrixGestureDetector)
}
private var fx = 0f
private var fy = 0f
private var sx = 0f
private var sy = 0f
private var pointerIndex1: Int = INVALID_POINTER_ID
private var pointerIndex2: Int = INVALID_POINTER_ID
private val originalMatrixInverted = Matrix()
var originalMatrix = Matrix()
set(value) {
field = value
value.invert(originalMatrixInverted)
}
var localMatrix = Matrix()
val matrix = Matrix()
private val originalPointsArray = FloatArray(4)
private val newPointsArray = FloatArray(4)
private val originalPoints = FloatArray(4)
private val newPoints = FloatArray(4)
fun onTouchEvent(event: MotionEvent) {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> pointerIndex1 = event.getPointerId(event.actionIndex)
MotionEvent.ACTION_POINTER_DOWN -> {
pointerIndex2 = event.getPointerId(event.actionIndex)
getPointerPosition(event, pointerIndex1).let {
fx = it.first
fy = it.second
}
getPointerPosition(event, pointerIndex2).let {
sx = it.first
sy = it.second
}
listener.onRotationBegin(this)
}
MotionEvent.ACTION_MOVE -> if (pointerIndex1 != INVALID_POINTER_ID && pointerIndex2 != INVALID_POINTER_ID) {
val (nfx, nfy) = getPointerPosition(event, pointerIndex1)
val (nsx, nsy) = getPointerPosition(event, pointerIndex2)
originalPointsArray[0] = fx
originalPointsArray[1] = fy
originalPointsArray[2] = sx
originalPointsArray[3] = sy
newPointsArray[0] = nfx
newPointsArray[1] = nfy
newPointsArray[2] = nsx
newPointsArray[3] = nsy
originalMatrixInverted.mapPoints(originalPoints, originalPointsArray)
originalMatrixInverted.mapPoints(newPoints, newPointsArray)
matrix.setPolyToPoly(originalPoints, 0, newPoints, 0, 2)
listener.onRotation(this)
}
MotionEvent.ACTION_UP -> pointerIndex1 = INVALID_POINTER_ID
MotionEvent.ACTION_POINTER_UP -> pointerIndex2 = INVALID_POINTER_ID
MotionEvent.ACTION_CANCEL -> {
pointerIndex1 = INVALID_POINTER_ID
pointerIndex2 = INVALID_POINTER_ID
}
}
}
companion object {
private const val INVALID_POINTER_ID = -1
}
init {
pointerIndex1 = INVALID_POINTER_ID
pointerIndex2 = INVALID_POINTER_ID
}
}
| 0
|
Kotlin
|
0
| 0
|
d735cbc4c59c04fd5dad42d16f7a38ba5418cb85
| 3,159
|
android-custom-elements
|
Apache License 2.0
|
smash-ranks-android/app/src/main/java/com/garpr/android/features/favoritePlayers/AddOrRemovePlayerFromFavoritesDialogFragment.kt
|
charlesmadere
| 41,832,700
| true
| null |
package com.garpr.android.features.favoritePlayers
import android.os.Bundle
import android.view.HapticFeedbackConstants
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.garpr.android.R
import com.garpr.android.data.models.FavoritePlayer
import com.garpr.android.extensions.requireParcelable
import com.garpr.android.features.common.fragments.dialogs.BaseBottomSheetDialogFragment
import kotlinx.android.synthetic.main.dialog_add_or_remove_player_from_favorites.*
import org.koin.androidx.viewmodel.ext.android.viewModel
class AddOrRemovePlayerFromFavoritesDialogFragment : BaseBottomSheetDialogFragment() {
private val player by lazy { arguments.requireParcelable<FavoritePlayer>(KEY_PLAYER) }
private val viewModel: AddOrRemovePlayerFromFavoritesViewModel by viewModel()
private val addOrRemovePlayerClickListener = View.OnClickListener { view ->
viewModel.addOrRemoveFromFavorites()
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
dismissAllowingStateLoss()
}
companion object {
const val TAG = "AddOrRemovePlayerFromFavoritesDialogFragment"
private const val KEY_PLAYER = "Player"
fun create(player: FavoritePlayer): AddOrRemovePlayerFromFavoritesDialogFragment {
val args = Bundle()
args.putParcelable(KEY_PLAYER, player)
val fragment = AddOrRemovePlayerFromFavoritesDialogFragment()
fragment.arguments = args
return fragment
}
}
private fun initListeners() {
viewModel.stateLiveData.observe(viewLifecycleOwner, Observer {
refreshState(it)
})
}
private fun initViews() {
dialogPositiveText.setOnClickListener(addOrRemovePlayerClickListener)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.initialize(player)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.dialog_add_or_remove_player_from_favorites, container,
false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initListeners()
initViews()
}
private fun refreshState(state: AddOrRemovePlayerFromFavoritesViewModel.State) {
if (state.isFetching) {
dialogMessage.visibility = View.INVISIBLE
dialogPositiveText.visibility = View.INVISIBLE
dialogProgressGroup.visibility = View.VISIBLE
} else {
if (state.isFavorited) {
dialogMessage.text = getString(R.string.remove_x_from_favorites, player.name)
dialogPositiveText.setText(R.string.yes_remove)
dialogPositiveText.setStartCompoundDrawableRelativeWithIntrinsicBounds(
R.drawable.ic_delete_white_24dp)
} else {
dialogMessage.text = getString(R.string.add_x_to_favorites, player.name)
dialogPositiveText.setText(R.string.yes_add)
dialogPositiveText.setStartCompoundDrawableRelativeWithIntrinsicBounds(
R.drawable.ic_add_circle_white_24dp)
}
dialogMessage.visibility = View.VISIBLE
dialogPositiveText.visibility = View.VISIBLE
dialogProgressGroup.visibility = View.GONE
}
}
}
| 0
|
Kotlin
|
0
| 9
|
151b2a0f9b4d38be60c3f73344ca444f17810bfd
| 3,662
|
smash-ranks-android
|
The Unlicense
|
buildSrc/src/main/kotlin/lwjgl.kt
|
wgpu4k
| 773,068,055
| false
|
{"Kotlin": 1190676, "HTML": 1638, "Dockerfile": 1039, "Shell": 308}
|
val lwjglVersion = "3.3.3"
| 7
|
Kotlin
|
6
| 41
|
822c304afaa72411ae42e86f20c7b5c62b5f9815
| 26
|
wgpu4k
|
MIT License
|
app/src/main/java/com/fredprojects/helloworld/ui/theme/Theme.kt
|
FredNekrasov
| 832,214,231
| false
|
{"Kotlin": 296555}
|
package com.fredprojects.helloworld.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.*
import androidx.compose.runtime.Composable
private val DarkColorScheme = darkColors(
primary = Purple80, secondary = PurpleGrey80, primaryVariant = Pink80
)
private val LightColorScheme = lightColors(
primary = Purple40, secondary = PurpleGrey40, primaryVariant = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun HelloWorldTheme(
darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit
) {
val colorScheme = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colors = colorScheme, typography = Typography, content = content
)
}
| 0
|
Kotlin
|
0
| 1
|
591c08f769e2d56f50c1480d7e81061e82fa6f11
| 1,021
|
jetpack-compose-projects
|
MIT License
|
MyEcMall-K/OrderCenter/src/main/java/cn/nieking/ordercenter/presenter/view/OrderDetailView.kt
|
NieQing
| 132,399,328
| false
|
{"Kotlin": 241813, "Java": 7791}
|
package cn.nieking.ordercenter.presenter.view
import cn.nieking.baselibrary.presenter.view.BaseView
import cn.nieking.ordercenter.data.protocol.Order
interface OrderDetailView : BaseView {
fun onGetOrderByIdResult(result: Order)
}
| 0
|
Kotlin
|
0
| 0
|
07b22622f98c8bfd8b26ea1303d48f6d66cc4b4b
| 238
|
MyEcMall-K
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/delegatedProperty/incompleteTypeInference.fir.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// DIAGNOSTICS: -UNUSED_PARAMETER
import kotlin.reflect.KProperty
class A
class D {
val c: Int <!DELEGATE_SPECIAL_FUNCTION_MISSING!>by<!> IncorrectThis<A>()
}
val cTopLevel: Int <!DELEGATE_SPECIAL_FUNCTION_MISSING!>by<!> IncorrectThis<A>()
class IncorrectThis<T> {
fun <R> get(t: Any?, p: KProperty<*>): Int {
return 1
}
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 348
|
kotlin
|
Apache License 2.0
|
features/media/src/main/kotlin/app/ss/media/playback/service/MusicService.kt
|
Adventech
| 65,243,816
| false
| null |
/*
* Copyright (c) 2023. Adventech <<EMAIL>>
*
* 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 app.ss.media.playback.service
import android.content.Intent
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import androidx.media.MediaBrowserServiceCompat
import androidx.media.session.MediaButtonReceiver
import app.ss.media.playback.BACKWARD
import app.ss.media.playback.FORWARD
import app.ss.media.playback.MediaNotifications
import app.ss.media.playback.NOTIFICATION_ID
import app.ss.media.playback.PLAY_PAUSE
import app.ss.media.playback.STOP_PLAYBACK
import app.ss.media.playback.extensions.isIdle
import app.ss.media.playback.extensions.playPause
import app.ss.media.playback.model.MediaId
import app.ss.media.playback.model.MediaId.Companion.CALLER_OTHER
import app.ss.media.playback.model.MediaId.Companion.CALLER_SELF
import app.ss.media.playback.players.SSAudioPlayer
import app.ss.media.playback.receivers.BecomingNoisyReceiver
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class MusicService : MediaBrowserServiceCompat() {
@Inject
lateinit var musicPlayer: SSAudioPlayer
@Inject
lateinit var mediaNotifications: MediaNotifications
private var becomingNoisyReceiver: BecomingNoisyReceiver? = null
override fun onCreate() {
super.onCreate()
sessionToken = musicPlayer.getSession().sessionToken
sessionToken?.let { token ->
becomingNoisyReceiver = BecomingNoisyReceiver(this, token)
}
musicPlayer.onPlayingState { isPlaying, byUi ->
val isIdle = musicPlayer.getSession().controller.playbackState.isIdle
if (!isPlaying && isIdle) {
pauseForeground(byUi)
mediaNotifications.clearNotifications()
} else {
startForeground()
}
mediaNotifications.updateNotification(getSession())
}
musicPlayer.onMetaDataChanged {
mediaNotifications.updateNotification(getSession())
}
}
private fun startForeground() {
if (IS_FOREGROUND) {
Timber.i("Tried to start foreground, but was already in foreground")
return
}
Timber.i("Starting foreground service")
startForeground(NOTIFICATION_ID, mediaNotifications.buildNotification(musicPlayer.getSession()))
becomingNoisyReceiver?.register()
IS_FOREGROUND = true
}
private fun pauseForeground(removeNotification: Boolean) {
if (!IS_FOREGROUND) {
Timber.w("Tried to stop foreground, but was already NOT in foreground")
return
}
Timber.d("Stopping foreground service")
becomingNoisyReceiver?.unregister()
@Suppress("DEPRECATION")
stopForeground(removeNotification)
IS_FOREGROUND = false
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) {
return START_STICKY
}
val mediaSession = musicPlayer.getSession()
val controller = mediaSession.controller
when (intent.action) {
PLAY_PAUSE -> controller.playPause()
FORWARD -> controller.transportControls.fastForward()
BACKWARD -> controller.transportControls.rewind()
STOP_PLAYBACK -> controller.transportControls.stop()
}
MediaButtonReceiver.handleIntent(mediaSession, intent)
return START_STICKY
}
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot {
val caller = if (clientPackageName == applicationContext.packageName) CALLER_SELF else CALLER_OTHER
return BrowserRoot(MediaId(caller = caller).toString(), null)
}
override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
result.detach()
}
override fun onTaskRemoved(rootIntent: Intent) {
musicPlayer.pause()
musicPlayer.stop(false)
super.onTaskRemoved(rootIntent)
}
override fun onDestroy() {
musicPlayer.release()
}
companion object {
var IS_FOREGROUND = false
}
}
| 11
|
Kotlin
|
43
| 147
|
9a8fd1a712c83814f37b75c1549b297e7f90bbd1
| 5,323
|
sabbath-school-android
|
MIT License
|
app/src/main/java/com/dvird/enterprise_iot_architecture/app/App.kt
|
dvird
| 164,823,805
| false
| null |
package com.dvird.enterprise_iot_architecture.app
import android.app.Application
class App : Application() {
}
| 0
|
Kotlin
|
0
| 0
|
4847afe2b844f165c8ca3ba8293c9123d809cda6
| 113
|
enterprise-iot-architecture
|
Apache License 2.0
|
docker/spring/code/src/main/kotlin/ch/derlin/bbdata/output/api/user_groups/UserGroupRepository.kt
|
bukibarak
| 412,392,282
| true
|
{"Kotlin": 337287, "JavaScript": 110303, "HTML": 55821, "Jupyter Notebook": 39748, "Shell": 15337, "CSS": 8790, "Dockerfile": 1544, "Python": 1320, "Batchfile": 17}
|
package ch.derlin.bbdata.output.api.user_groups
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.util.*
/**
* date: 06.12.19
* @author <NAME> <<EMAIL>>
*/
@Repository
interface UserGroupRepository : JpaRepository<UserGroup, Int?> {
@Query("SELECT g FROM UserGroup g INNER JOIN g.userMappings u " +
"WHERE u.userId = :userId AND (:admin = false OR u.isAdmin = :admin)")
fun findMines(userId: Int, admin: Boolean = false): List<UserGroup>
@Query("SELECT g FROM UserGroup g INNER JOIN g.userMappings u " +
"WHERE g.id = :id AND u.userId = :userId AND (:admin = false OR u.isAdmin = :admin)")
fun findMine(userId: Int, id: Int, admin: Boolean = false): Optional<UserGroup>
}
| 0
|
Kotlin
|
1
| 0
|
638eef5e2d63882328cfcaf31ea8a3bdf11b98c9
| 844
|
bbdata-api
|
MIT License
|
src/backendMain/kotlin/io/joaofig/vedmap/databases/ClusterPointTable.kt
|
joaofig
| 437,581,924
| false
| null |
package io.joaofig.vedmap.databases
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Column
object ClusterPointTable : IntIdTable(name = "cluster_point", columnName = "pt_id") {
val clusterId: Column<Int> = integer("cluster_id")
val latitude: Column<Double> = double("latitude")
val longitude: Column<Double> = double("longitude")
val h3: Column<String> = text("h3")
}
class ClusterPointRow(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<ClusterPointRow>(ClusterPointTable)
var clusterId by ClusterPointTable.clusterId
var latitude by ClusterPointTable.latitude
var longitude by ClusterPointTable.longitude
var h3 by ClusterPointTable.h3
}
| 0
|
Kotlin
|
0
| 1
|
6b11d1183cc48526612a33967c516a5bfcbc6e07
| 881
|
ved-map
|
MIT License
|
app/src/main/kotlin/com/reach/modernandroid/ui/App.kt
|
Reach2027
| 741,563,053
| false
|
{"Kotlin": 56430}
|
/*
* Copyright 2024 Reach Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.reach.modernandroid.ui
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.reach.modernandroid.navigation.AppNavHost
import com.reach.modernandroid.navigation.TopDest
import com.reach.modernandroid.navigation.navToTopDest
import com.reach.modernandroid.ui.core.common.LocalAppUiState
@Composable
fun App(
navController: NavHostController = rememberNavController(),
) {
CompositionLocalProvider(
LocalAppUiState provides DefaultAppUiState(navController),
) {
AppScreen(navController = navController)
}
}
@Composable
private fun AppScreen(
navController: NavHostController = LocalAppUiState.current.navController,
) {
val snackbarHostState = remember { SnackbarHostState() }
val currentDest = navController.currentBackStackEntryAsState().value?.destination
Scaffold(
bottomBar = {
AppNavBar(
destList = TopDest.entries,
onNavToTopDest = { navController.navToTopDest(it) },
currentDest = currentDest,
)
},
snackbarHost = { SnackbarHost(snackbarHostState) },
) { padding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
AppNavHost(navController)
}
}
}
@Composable
private fun AppNavBar(
destList: List<TopDest>,
onNavToTopDest: (TopDest) -> Unit,
currentDest: NavDestination?,
) {
NavigationBar {
destList.forEach { topDest ->
val selected = currentDest.isTopDestInHierarchy(topDest)
NavigationBarItem(
selected = selected,
onClick = { onNavToTopDest(topDest) },
icon = {
Icon(
imageVector = if (selected) topDest.selectedIcon else topDest.unselectedIcon,
contentDescription = "",
)
},
)
}
}
}
private fun NavDestination?.isTopDestInHierarchy(topDest: TopDest) =
this?.hierarchy?.any {
it.route?.contains(topDest.name, true) ?: false
} ?: false
| 0
|
Kotlin
|
0
| 1
|
44cc1cacdd2e5362d0c7b4d159e31a9ab55d3232
| 3,585
|
ModernAndroid
|
Apache License 2.0
|
sms-core/src/main/kotlin/team/msg/sms/domain/student/service/impl/CommandStudentServiceImpl.kt
|
GSM-MSG
| 625,717,097
| false
|
{"Kotlin": 458135, "Shell": 1480, "Dockerfile": 288}
|
package team.msg.sms.domain.student.service.impl
import team.msg.sms.common.annotation.Service
import team.msg.sms.domain.student.model.Student
import team.msg.sms.domain.student.service.CommandStudentService
import team.msg.sms.domain.student.spi.StudentPort
import team.msg.sms.domain.user.model.User
import java.util.*
@Service
class CommandStudentServiceImpl(
private val studentPort: StudentPort
) : CommandStudentService {
override fun saveStudent(student: Student, user: User): Student =
studentPort.saveStudent(student, user)
override fun deleteByUuid(studentId: UUID) =
studentPort.deleteById(studentId)
}
| 7
|
Kotlin
|
0
| 9
|
4c6c206cdd7cdaf8d28e0ab6d53de504298cb60b
| 645
|
SMS-BackEnd
|
MIT License
|
walletconnectv2/src/main/kotlin/com/walletconnect/walletconnectv2/storage/KeyStore.kt
|
securewalletrevalidate
| 442,118,839
| false
|
{"Kotlin": 215502}
|
package com.walletconnect.walletconnectv2.storage
import com.walletconnect.walletconnectv2.crypto.data.Key
interface KeyStore {
fun setKey(tag: String, key1: Key, key2: Key)
fun getKeys(tag: String): Pair<String, String>
fun deleteKeys(tag: String)
}
| 0
|
Kotlin
|
0
| 0
|
c774b674cc9bb8b8709999f85500f59f25e508d0
| 264
|
WallectConnectKotlinV22
|
Apache License 2.0
|
src/main/kotlin/com/brand4impact/client/apis/SectorApi.kt
|
brand4impact
| 476,640,560
| false
| null |
/**
* Total API Reference
*
* Este contrato se usara para generar los clientes con todos los servicios necesarios. `!Uso exclusivo interno!` ---
*
* The version of the OpenAPI document: 0.0.1
* Contact: support@brand4impact.com
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.brand4impact.client.apis
import com.brand4impact.client.models.PlatformSector
import com.brand4impact.client.models.PlatformSectorItemWrapper
import com.brand4impact.client.models.RestError
import com.brand4impact.client.infrastructure.ApiClient
import com.brand4impact.client.infrastructure.ClientException
import com.brand4impact.client.infrastructure.ClientError
import com.brand4impact.client.infrastructure.ServerException
import com.brand4impact.client.infrastructure.ServerError
import com.brand4impact.client.infrastructure.MultiValueMap
import com.brand4impact.client.infrastructure.RequestConfig
import com.brand4impact.client.infrastructure.RequestMethod
import com.brand4impact.client.infrastructure.ResponseType
import com.brand4impact.client.infrastructure.Success
import com.brand4impact.client.infrastructure.toMultiValue
class SectorApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("com.brand4impact.client.baseUrl", "http://localhost:8080/backend")
}
}
/**
* Get a single sector
* This method returns a specific sector and represents principals industries
* @param token The unique token for the sector.
* @return PlatformSector
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getSector(token: kotlin.String) : PlatformSector {
val localVariableConfig = getSectorRequestConfig(token = token)
val localVarResponse = request<Unit, PlatformSector>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as PlatformSector
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* To obtain the request config of the operation getSector
*
* @param token The unique token for the sector.
* @return RequestConfig
*/
fun getSectorRequestConfig(token: kotlin.String) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
return RequestConfig(
method = RequestMethod.GET,
path = "/rest/platform/sector/{token}".replace("{"+"token"+"}", "$token"),
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Get a set of sectors
* This method returns all the sectors according the filters and represents principals industries [](http://localhost:8080/backend/blog/home#pagination)
* @param page The number of the page. Possible values: 0 to unlimited (optional)
* @param size The number of items inside a page. Possible values: 1 to 100 (optional)
* @param sort The order direction for sorted results. Possible values: ASC or DESC (optional)
* @return PlatformSectorItemWrapper
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getSectors(page: kotlin.Int?, size: kotlin.Int?, sort: kotlin.String?) : PlatformSectorItemWrapper {
val localVariableConfig = getSectorsRequestConfig(page = page, size = size, sort = sort)
val localVarResponse = request<Unit, PlatformSectorItemWrapper>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as PlatformSectorItemWrapper
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* To obtain the request config of the operation getSectors
*
* @param page The number of the page. Possible values: 0 to unlimited (optional)
* @param size The number of items inside a page. Possible values: 1 to 100 (optional)
* @param sort The order direction for sorted results. Possible values: ASC or DESC (optional)
* @return RequestConfig
*/
fun getSectorsRequestConfig(page: kotlin.Int?, size: kotlin.Int?, sort: kotlin.String?) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
if (page != null) {
put("page", listOf(page.toString()))
}
if (size != null) {
put("size", listOf(size.toString()))
}
if (sort != null) {
put("sort", listOf(sort.toString()))
}
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
return RequestConfig(
method = RequestMethod.GET,
path = "/rest/platform/sector",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
}
| 0
|
Kotlin
|
0
| 0
|
8d087bc04ef596e581c9b14665bc0264dd859d82
| 7,877
|
brand4impact-kotlin-sdk
|
MIT License
|
travelmaker_android/app/src/main/java/com/gumibom/travelmaker/data/api/google/GoogleLocationSearchService.kt
|
serotonins
| 808,489,421
| false
|
{"Kotlin": 481004, "Java": 174550, "HTML": 4622, "Dockerfile": 516}
|
package com.gumibom.travelmaker.data.api.google
import com.gumibom.travelmaker.data.dto.google.GoogleLocationDTO
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface GoogleLocationSearchService {
@GET("/maps/api/geocode/json")
suspend fun findGoogleLocationSearch(
@Query("address") location: String,
@Query("key") apiKey: String
) : Response<GoogleLocationDTO>
}
| 0
|
Kotlin
|
0
| 0
|
eb8dee9dd6979722026a6d20fab96b56c4a63b1b
| 436
|
TravelMaker
|
MIT License
|
core/common/src/main/kotlin/cn/wj/android/cashbook/core/common/tools/Time.kt
|
WangJie0822
| 365,932,300
| false
|
{"Kotlin": 1323186, "Java": 1271087}
|
@file:Suppress("unused")
@file:JvmName("TimeTools")
package cn.wj.android.cashbook.core.common.tools
import cn.wj.android.cashbook.core.common.ext.logger
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.Date
import java.util.Locale
/* ----------------------------------------------------------------------------------------- */
/* | 时间相关 | */
/* ----------------------------------------------------------------------------------------- */
/** 默认时间格式化 */
const val DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss"
/** 备份名称时间格式化 */
const val DATE_FORMAT_BACKUP = "yyyyMMddHHmmss"
/** 日期时间格式化 */
const val DATE_FORMAT_DATE = "yyyy-MM-dd"
/** 日期时间格式化 */
const val DATE_FORMAT_MONTH_DAY = "MM.dd"
/** 日期时间格式化 */
const val DATE_FORMAT_YEAR_MONTH = "yyyy-MM"
/** 时间格式化 */
const val DATE_FORMAT_TIME = "HH:mm"
/** 没有秒的时间格式化 */
const val DATE_FORMAT_NO_SECONDS = "yyyy-MM-dd HH:mm"
/** 时间格式化 - 年 */
const val DATE_FORMAT_YEAR = "yyyy"
/** 时间格式化 - 月 */
const val DATE_FORMAT_MONTH = "MM"
/** 时间格式化 - 日 */
const val DATE_FORMAT_DAY = "dd"
/** 根据[format]格式化时间,[format]默认[DATE_FORMAT_DEFAULT] */
@JvmOverloads
fun <N : Number> N.dateFormat(format: String = DATE_FORMAT_DEFAULT): String {
return try {
SimpleDateFormat(format, Locale.getDefault()).format(this)
} catch (e: ParseException) {
logger().e(e, "dateFormat")
""
}
}
fun String.parseDate(format: String = DATE_FORMAT_DEFAULT): Date? {
return try {
SimpleDateFormat(format, Locale.getDefault()).parse(this)
} catch (throwable: Throwable) {
logger().e(throwable, "parseDate")
null
}
}
fun String.parseDateLong(format: String = DATE_FORMAT_DEFAULT): Long {
return try {
parseDate(format)?.time ?: System.currentTimeMillis()
} catch (throwable: Throwable) {
logger().e(throwable, "parseDate")
System.currentTimeMillis()
}
}
/** 根据[format]格式化时间,[format]默认[DATE_FORMAT_DEFAULT] */
@JvmOverloads
fun Date.dateFormat(format: String = DATE_FORMAT_DEFAULT): String {
return try {
SimpleDateFormat(format, Locale.getDefault()).format(this)
} catch (e: ParseException) {
logger().e(e, "dateFormat")
""
}
}
/** 根据[format]格式化时间,[format]默认[DATE_FORMAT_DEFAULT] */
@JvmOverloads
fun String.paresDate(format: String = DATE_FORMAT_DEFAULT): Date? {
return try {
SimpleDateFormat(format, Locale.getDefault()).parse(this)
} catch (e: ParseException) {
logger().e(e, "paresDate")
null
}
}
/** 将字符串时间转换为 [Long] 类型时间 */
@JvmOverloads
fun String?.toLongTime(format: String = DATE_FORMAT_DEFAULT): Long? {
return this?.paresDate(format)?.time
}
fun Long.toLocalDate(): LocalDate {
return Instant.ofEpochMilli(this).atZone(ZoneId.systemDefault()).toLocalDate()
}
fun LocalDate.toMs(): Long {
return atStartOfDay(ZoneOffset.systemDefault()).toInstant().toEpochMilli()
}
| 0
|
Kotlin
|
7
| 23
|
004fb1d6e81ff60fd9e8cb46dc131107a720bbe5
| 3,111
|
Cashbook
|
Apache License 2.0
|
domain/api/src/nativeMain/kotlin/mehiz/abdallah/progres/api/ApiModule.native.kt
|
abdallahmehiz
| 830,308,163
| false
|
{"Kotlin": 449026, "Swift": 621}
|
package mehiz.abdallah.progres.api
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.darwin.Darwin
actual val engine: HttpClientEngine = Darwin.create()
| 1
|
Kotlin
|
0
| 8
|
331d3c6c8caa126fdc7df033f2574cd3aa8f8e80
| 180
|
progres
|
MIT License
|
core/src/main/java/io/github/thisdk/core/cookie/AppCookie.kt
|
thisdk
| 518,834,164
| false
|
{"Kotlin": 21141}
|
package io.github.thisdk.core.cookie
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Serializable
@Parcelize
@Serializable
data class AppCookie(
val name: String,
val value: String,
val expiresAt: Long,
val domain: String,
val path: String,
val secure: Boolean,
val httpOnly: Boolean,
val persistent: Boolean,
val hostOnly: Boolean
) : Parcelable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppCookie
if (name != other.name) return false
if (value != other.value) return false
if (expiresAt != other.expiresAt) return false
if (domain != other.domain) return false
if (path != other.path) return false
if (secure != other.secure) return false
if (httpOnly != other.httpOnly) return false
if (persistent != other.persistent) return false
if (hostOnly != other.hostOnly) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + value.hashCode()
result = 31 * result + expiresAt.hashCode()
result = 31 * result + domain.hashCode()
result = 31 * result + path.hashCode()
result = 31 * result + secure.hashCode()
result = 31 * result + httpOnly.hashCode()
result = 31 * result + persistent.hashCode()
result = 31 * result + hostOnly.hashCode()
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
f9226751072c7687f915ef842c153d022bae767f
| 1,589
|
core
|
Apache License 2.0
|
core/src/main/java/io/github/thisdk/core/cookie/AppCookie.kt
|
thisdk
| 518,834,164
| false
|
{"Kotlin": 21141}
|
package io.github.thisdk.core.cookie
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Serializable
@Parcelize
@Serializable
data class AppCookie(
val name: String,
val value: String,
val expiresAt: Long,
val domain: String,
val path: String,
val secure: Boolean,
val httpOnly: Boolean,
val persistent: Boolean,
val hostOnly: Boolean
) : Parcelable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppCookie
if (name != other.name) return false
if (value != other.value) return false
if (expiresAt != other.expiresAt) return false
if (domain != other.domain) return false
if (path != other.path) return false
if (secure != other.secure) return false
if (httpOnly != other.httpOnly) return false
if (persistent != other.persistent) return false
if (hostOnly != other.hostOnly) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + value.hashCode()
result = 31 * result + expiresAt.hashCode()
result = 31 * result + domain.hashCode()
result = 31 * result + path.hashCode()
result = 31 * result + secure.hashCode()
result = 31 * result + httpOnly.hashCode()
result = 31 * result + persistent.hashCode()
result = 31 * result + hostOnly.hashCode()
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
f9226751072c7687f915ef842c153d022bae767f
| 1,589
|
core
|
Apache License 2.0
|
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/tormaystarkastelu/TormaystarkasteluTulos.kt
|
City-of-Helsinki
| 300,534,352
| false
| null |
package fi.hel.haitaton.hanke.tormaystarkastelu
import javax.persistence.Column
import javax.persistence.Embeddable
import javax.persistence.EnumType
import javax.persistence.Enumerated
// TODO: Only hankeTunnus to be used as part of equals(), hashCode() and copy() auto-implementations?
// For now we only have one result per hanke, so it is ok, but in future there can be multiple results
// for each hanke, and at least geometryId or something like that should be considered.
data class TormaystarkasteluTulos(val hankeTunnus: String) {
var hankeId: Int = 0
var hankeGeometriatId: Int = 0
var liikennehaittaIndeksi: LiikennehaittaIndeksiType? = null
var perusIndeksi: Float? = null
var pyorailyIndeksi: Float? = null
var joukkoliikenneIndeksi: Float? = null
var tila: TormaystarkasteluTulosTila? = null
override fun toString(): String {
return "TormaystarkasteluTulos(" +
"hankeTunnus='$hankeTunnus', " +
"hankeId=$hankeId, " +
"hankeGeometriatId=$hankeGeometriatId, " +
"liikennehaittaIndeksi=$liikennehaittaIndeksi, " +
"perusIndeksi=$perusIndeksi, " +
"pyorailyIndeksi=$pyorailyIndeksi, " +
"joukkoliikenneIndeksi=$joukkoliikenneIndeksi)"
}
/**
* Selects maximum of three indeksi and sets that to be LiikennehaittaIndeksi.
*/
fun calculateLiikennehaittaIndeksi() {
val maxIndex = setOf(perusIndeksi!!, pyorailyIndeksi!!, joukkoliikenneIndeksi!!).maxOrNull()
?: throw IllegalStateException("perusIndeksi, pyorailyIndeksi and joukkoliikenneIndeksi cannot be null")
liikennehaittaIndeksi = when (maxIndex) {
joukkoliikenneIndeksi -> LiikennehaittaIndeksiType(
joukkoliikenneIndeksi!!,
IndeksiType.JOUKKOLIIKENNEINDEKSI
)
perusIndeksi -> LiikennehaittaIndeksiType(perusIndeksi!!, IndeksiType.PERUSINDEKSI)
else -> LiikennehaittaIndeksiType(pyorailyIndeksi!!, IndeksiType.PYORAILYINDEKSI)
}
}
}
// This class is also used as part of entity-classes TormaystarkasteluTulosEntity and Hanke.
// HankeEntity overrides the column names.
@Embeddable
data class LiikennehaittaIndeksiType(
@Column(name = "liikennehaitta")
var indeksi: Float,
@Column(name = "liikennehaittatyyppi")
@Enumerated(EnumType.STRING)
var tyyppi: IndeksiType
)
enum class IndeksiType {
PERUSINDEKSI,
PYORAILYINDEKSI,
JOUKKOLIIKENNEINDEKSI
// TODO: will likely need a new option "MONTA" or "USEITA".
}
enum class TormaystarkasteluTulosTila {
VOIMASSA,
EI_VOIMASSA
}
| 1
|
Kotlin
|
4
| 1
|
89ac42586cfb1355f79b09062ba54736a4a6adfd
| 2,681
|
haitaton-backend
|
MIT License
|
app/src/main/java/me/blog/korn123/easydiary/fragments/CalendarFragment.kt
|
TimMagee
| 208,467,729
| true
|
{"Kotlin": 583300}
|
package me.blog.korn123.easydiary.fragments
import com.roomorama.caldroid.CaldroidFragment
import com.roomorama.caldroid.CaldroidGridAdapter
import me.blog.korn123.easydiary.adapters.CaldroidItemAdapter
import me.blog.korn123.easydiary.adapters.WeekdayArrayAdapter
class CalendarFragment : CaldroidFragment() {
override fun getNewDatesGridAdapter(month: Int, year: Int): CaldroidGridAdapter {
return CaldroidItemAdapter(activity!!, month, year,
getCaldroidData(), extraData)
}
override fun getNewWeekdayAdapter(themeResource: Int): WeekdayArrayAdapter {
return WeekdayArrayAdapter(
activity!!, com.caldroid.R.layout.weekday_textview,
daysOfWeek, themeResource)
}
}
| 0
| null |
0
| 0
|
2e83fc637cae8096c46c3d55e9675fb59aaf046b
| 749
|
aaf-easydiary
|
Apache License 2.0
|
WeatherApp/app/src/main/java/com/azhar/weatherapp/adapter/MainAdapter.kt
|
AzharRivaldi
| 302,811,123
| false
| null |
package com.azhar.weatherapp.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.amulyakhare.textdrawable.util.ColorGenerator
import com.azhar.weatherapp.R
import com.azhar.weatherapp.model.ModelMain
import kotlinx.android.synthetic.main.list_item_main.view.*
import java.util.*
/**
* Created by Azhar Rivaldi on 03-10-2020
*/
class MainAdapter(private val items: List<ModelMain>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_main, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = items[position]
val generator = ColorGenerator.MATERIAL
// generate random color
val color = generator.randomColor
holder.cvListWeather.setCardBackgroundColor(color)
holder.tvNameDay.text = data.timeNow
holder.tvTemp.text = String.format(Locale.getDefault(), "%.0f°C", data.currentTemp)
holder.tvTempMin.text = String.format(Locale.getDefault(), "%.0f°C", data.tempMin)
holder.tvTempMax.text = String.format(Locale.getDefault(), "%.0f°C", data.tempMax)
if (data.descWeather == "broken clouds") {
holder.iconTemp.setAnimation(R.raw.broken_clouds)
} else if (data.descWeather == "light rain") {
holder.iconTemp.setAnimation(R.raw.light_rain)
} else if (data.descWeather == "overcast clouds") {
holder.iconTemp.setAnimation(R.raw.overcast_clouds)
} else if (data.descWeather == "moderate rain") {
holder.iconTemp.setAnimation(R.raw.moderate_rain)
} else if (data.descWeather == "few clouds") {
holder.iconTemp.setAnimation(R.raw.few_clouds)
} else if (data.descWeather == "heavy intensity rain") {
holder.iconTemp.setAnimation(R.raw.heavy_intentsity)
} else if (data.descWeather == "clear sky") {
holder.iconTemp.setAnimation(R.raw.clear_sky)
} else if (data.descWeather == "scattered clouds") {
holder.iconTemp.setAnimation(R.raw.scattered_clouds)
} else {
holder.iconTemp.setAnimation(R.raw.unknown)
}
}
override fun getItemCount(): Int {
return items.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var cvListWeather: CardView
var tvNameDay: TextView
var tvTemp: TextView
var tvTempMin: TextView
var tvTempMax: TextView
var iconTemp: LottieAnimationView
init {
cvListWeather = itemView.cvListWeather
tvNameDay = itemView.tvNameDay
tvTemp = itemView.tvTemp
tvTempMin = itemView.tvTempMin
tvTempMax = itemView.tvTempMax
iconTemp = itemView.iconTemp
}
}
}
| 0
|
Kotlin
|
6
| 20
|
8420a359e2b45e0ceed2c982a075ce1b3a727b98
| 3,187
|
Weather
|
Apache License 2.0
|
app/src/main/java/com/crjacinro/composepathfinding/State.kt
|
crjacinro
| 381,725,166
| false
| null |
package com.crjacinro.composepathfinding
import com.crjacinro.composepathfinding.algorithms.startDijkstra
import com.crjacinro.composepathfinding.data.CellData
import com.crjacinro.composepathfinding.data.Position
import com.crjacinro.composepathfinding.ui.composables.CellType
import kotlinx.coroutines.delay
class State {
private var gridState: MutableList<MutableList<CellData>> = mutableListOf()
private val startPosition = Position((NUMBER_OF_ROWS / 2), (NUMBER_OF_COLUMNS / 4))
private val finishPosition = Position((NUMBER_OF_ROWS / 2), (NUMBER_OF_COLUMNS / 4) * 3)
var isVisualizing = false
private set
init {
clear()
}
fun clear() {
gridState = getInitGridState()
isVisualizing = false
addStartAndFinishGrids()
}
suspend fun randomizeWalls() {
clear()
for (i in 0 until gridState.size) {
for (j in 0 until gridState[i].size) {
val position = gridState[i][j].position
if (isPositionNotAtStartOrFinish(position)) {
updateCellTypeAtPosition(position, weightedRandomWall())
}
delay(5.toLong())
}
}
}
fun drawCurrentGridState(): List<List<CellData>> {
val updatedGrid = getInitGridState()
for (i in 0 until updatedGrid.size) {
for (j in 0 until updatedGrid[i].size) {
updatedGrid[i][j] = gridState[i][j]
}
}
return updatedGrid
}
fun getFinishPosition() = finishPosition
fun getCurrentGrid(): List<List<CellData>> = gridState
fun toggleCellTypeToWall(p: Position) {
if (getCellAtPosition(p).type == CellType.WALL) {
updateCellTypeAtPosition(p, CellType.BACKGROUND)
} else {
updateCellTypeAtPosition(p, CellType.WALL)
}
}
fun isPositionNotAtStartOrFinish(p: Position) =
getCellAtPosition(p).type != CellType.START &&
getCellAtPosition(p).type != CellType.FINISH
private fun updateCellTypeAtPosition(p: Position, cellType: CellType) {
gridState[p.row][p.column] = getCellAtPosition(p).copy(type = cellType)
}
fun setCellVisitedAtPosition(p: Position) {
gridState[p.row][p.column] = getCellAtPosition(p).copy(isVisited = true)
}
suspend fun animatedShortestPath() {
isVisualizing = true
val shortestPath = startDijkstra(this)
shortestPath.forEach {
val p = it.position
gridState[p.row][p.column] = getCellAtPosition(p).copy(isShortestPath = true)
delay(GAME_DELAY_IN_MS)
}
}
fun getFinishCell() = getCellAtPosition(finishPosition)
fun getCellAtPosition(p: Position) = gridState[p.row][p.column]
private fun addStartAndFinishGrids() {
gridState[startPosition.row][startPosition.column] =
CellData(CellType.START, startPosition, distance = 0)
gridState[finishPosition.row][finishPosition.column] =
CellData(CellType.FINISH, finishPosition)
}
private fun getInitGridState() = getGridWithClearBackground()
}
| 0
|
Kotlin
|
2
| 34
|
bd709e815694105f4b4bbcb56f7d7f9d662daccd
| 3,182
|
compose-path-finding
|
MIT License
|
app/src/main/java/com/technocreatives/example/bond/PermissionsService.kt
|
technocreatives
| 364,517,134
| false
| null |
package com.technocreatives.example.bond
import android.content.Intent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.technocreatives.example.bond.domain.LocationPermissionState
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
class PermissionsService(
private val fragment: AppCompatActivity,
private val permissions: List<String>,
private val rationale: String,
private val requestCode: Int,
private val callbacks: PermissionsServiceCallbacks
) : PermissionsServiceCallbacks by callbacks{
fun hasPermission(): Boolean {
return EasyPermissions.hasPermissions(fragment!!, *permissions.toTypedArray())
}
fun requestPermissions() {
EasyPermissions.requestPermissions(
fragment, rationale,
requestCode, *permissions.toTypedArray()
)
}
}
interface PermissionsServiceCallbacks : EasyPermissions.PermissionCallbacks {
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
fun onResume(isHasPermissions: Boolean)
}
interface CustomEasyPermission: EasyPermissions.PermissionCallbacks{
fun initCallback(fragment: Fragment){
}
}
class MagicCallbacks : CustomEasyPermission{
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
throw UnsupportedOperationException("not implemented")
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
throw UnsupportedOperationException("not implemented")
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
throw UnsupportedOperationException("not implemented")
}
}
class LocationPermissionsCallbacks(private val fragment: AppCompatActivity, private val permissions: List<String>, private val appStore: AppStore) : PermissionsServiceCallbacks {
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
if (EasyPermissions.somePermissionPermanentlyDenied(fragment, perms)) {
Toast.makeText(fragment!!, "Show dialog", Toast.LENGTH_SHORT).show()
updateLocationPermissionState(LocationPermissionState.DONT_ASK_AGAIN)
val dialog = AppSettingsDialog.Builder(fragment).build()
dialog.show()
} else {
updateLocationPermissionState(LocationPermissionState.DENIED)
}
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
// todo I think it doesn't work correctly if we request multiple permissions
updateLocationPermissionState(LocationPermissionState.ON)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
// Do something after user returned from app settings screen, like showing a Toast.
if (EasyPermissions.hasPermissions(fragment!!, *permissions.toTypedArray())) {
Toast.makeText(fragment!!, "Received permissions via settings", Toast.LENGTH_SHORT)
.show()
updateLocationPermissionState(LocationPermissionState.ON)
}
}
}
override fun onResume(isHasPermissions: Boolean) {
val state = if (isHasPermissions) {
LocationPermissionState.ON
} else {
LocationPermissionState.UNKNOWN
}
updateLocationPermissionState(state)
}
private fun updateLocationPermissionState(state: LocationPermissionState) {
appStore.dispatch(BondAction.UpdateLocationPermissionState(state))
}
}
| 1
|
Kotlin
|
1
| 8
|
2e252df19c02104821c393225ee8d5abefa07b74
| 4,004
|
beckon-android
|
Apache License 2.0
|
src/main/java/miyucomics/hexical/casting/patterns/getters/types/OpGetFoodTypeData.kt
|
miyucomics
| 757,094,041
| false
|
{"Kotlin": 310151, "Java": 29667, "GLSL": 1353}
|
package miyucomics.hexical.casting.patterns.getters.types
import at.petrak.hexcasting.api.spell.ConstMediaAction
import at.petrak.hexcasting.api.spell.asActionResult
import at.petrak.hexcasting.api.spell.casting.CastingContext
import at.petrak.hexcasting.api.spell.iota.Iota
import at.petrak.hexcasting.api.spell.mishaps.MishapInvalidIota
import miyucomics.hexical.casting.iota.getIdentifier
import net.minecraft.util.registry.Registry
class OpGetFoodTypeData(private val mode: Int) : ConstMediaAction {
override val argc = 1
override fun execute(args: List<Iota>, ctx: CastingContext): List<Iota> {
val id = args.getIdentifier(0, argc)
if (!Registry.ITEM.containsId(id))
throw MishapInvalidIota.of(args[0], 0, "food_id")
val food = Registry.ITEM.get(id).foodComponent ?: throw MishapInvalidIota.of(args[0], 0, "food_id")
return when (mode) {
0 -> food.hunger.asActionResult
1 -> food.saturationModifier.asActionResult
2 -> food.isMeat.asActionResult
3 -> food.isSnack.asActionResult
else -> throw IllegalStateException()
}
}
}
| 0
|
Kotlin
|
1
| 1
|
ed8abb4c4339166f2d21872999d1379615e82e36
| 1,060
|
hexical
|
MIT License
|
app/src/main/java/com/githubly/wanandroid/presenter/LogoutPresenter.kt
|
leiyun1993
| 153,766,139
| false
| null |
package com.githubly.wanandroid.presenter
import com.githubly.wanandroid.contract.ILogoutContract
import com.githubly.wanandroid.net.ApiCallBack
import com.githubly.wanandroid.net.ApiHelper
import com.githubly.wanandroid.presenter.base.BasePresenter
/**
* 类名:LogoutPresenter
* 作者:Yun.Lei
* 功能:
* 创建日期:2018-10-22 16:40
* 修改人:
* 修改时间:
* 修改备注:
*/
class LogoutPresenter(view: ILogoutContract.View) :
BasePresenter<ILogoutContract.View>(view),ILogoutContract.Presenter {
override fun logout() {
ApiHelper.api.logout().enqueue(ApiCallBack{
if (isSuccess){
mView?.onLogoutSuccess()
}else{
mView?.onLogoutFailed(errorMsg)
}
})
}
}
| 0
|
Kotlin
|
0
| 45
|
abd7c07203f9e03e40ce436f23c4086913a0b0ec
| 732
|
WanAndroid
|
Apache License 2.0
|
web/src/main/kotlin/fr/arsenelapostolet/fsa_banking_system/app/templates/CreateAccountPage.kt
|
Ombrelin
| 664,083,827
| false
| null |
package fr.arsenelapostolet.fsa_banking_system.app.templates
import fr.arsenelapostolet.fsa_banking_system.bank.entities.Operation
import fr.arsenelapostolet.fsa_banking_system.bank.entities.Rank
import kotlinx.html.*
internal fun FlowContent.createAccountPage(ranks: Collection<Rank>) {
div(classes = "center") {
form(action = "/accounts/create", method = FormMethod.post, classes = "box") {
h1(classes = "title") {
+"Create new Account"
}
div(classes = "select") {
select {
attributes["name"] = "rank"
attributes["required"] = "true"
ranks.map {
option { +it.name }
}
}
}
div(classes = "field") {
label(classes = "label") {
+"Holder Account Name :"
}
div(classes = "control") {
textInput(name = "holderName", classes = "input"){
attributes["required"] = "true"
}
}
}
div(classes = "control") {
submitInput(classes = "button is-primary") { value = "Create Account" }
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9561658b519e95afbc9f810c52b2ac4361f11019
| 1,317
|
fsa-banking-system
|
MIT License
|
app/src/main/java/com/alexandre/myquotes/model/UserData.kt
|
alexandre7777
| 131,637,016
| false
| null |
package com.alexandre.myquotes.model
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.ColumnInfo
@Entity(tableName = "userData")
data class UserData(@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "login") var login: String,
@ColumnInfo(name = "password") var password: String,
@ColumnInfo(name = "urlPicto") var urlPicto: String,
@ColumnInfo(name = "favCount") var favCount: Int) {
}
| 0
|
Kotlin
|
0
| 0
|
b03804ea875178fd37d51f8c69d429ceb89d0894
| 566
|
my-quotes
|
MIT License
|
ocpp-2-0-core/src/main/kotlin/com/izivia/ocpp/core20/model/changeavailability/enumeration/OperationalStatusEnumType.kt
|
IZIVIA
| 501,708,979
| false
|
{"Kotlin": 1934096}
|
package com.izivia.ocpp.core20.model.changeavailability.enumeration
enum class OperationalStatusEnumType(val value: String) {
Inoperative("Inoperative"),
Operative("Operative");
}
| 6
|
Kotlin
|
10
| 32
|
bd8e7334ae05ea75d02d96a508269acbe076bcd8
| 189
|
ocpp-toolkit
|
MIT License
|
app/shared/feature-flag/public/src/commonMain/kotlin/build/wallet/feature/FeatureFlagInitializer.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.feature
/**
* A common place for flag initialization that should be used at app launch to
* initialize all flags from the persistent store.
*/
interface FeatureFlagInitializer {
/**
* Initializes all flags managed by this component from the persistent store
* (calls [initializeFromDao] on each)
*/
suspend fun initializeAllFlags()
}
| 0
|
C
|
10
| 98
|
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
| 372
|
bitkey
|
MIT License
|
src/main/kotlin/io/github/ay012/aysignvariable/command/AySignCommand.kt
|
AyOl2
| 854,650,661
| false
|
{"Kotlin": 8696}
|
package io.github.ay012.aysignvariable.command
import io.github.ay012.aysignvariable.AySignVariable.config
import io.github.ay012.aysignvariable.api.AySignAPI
import io.github.ay012.aysignvariable.util.KetherUtil
import io.github.ay012.aysignvariable.util.TimeUtil.isOver24Hours
import io.github.ay012.aysignvariable.util.TimeUtil.storeCurrentTime
import io.github.ay012.aysignvariable.util.TimeUtil.timeRemainingUntil24Hours
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import taboolib.common.platform.command.CommandBody
import taboolib.common.platform.command.CommandHeader
import taboolib.common.platform.command.subCommand
import taboolib.common.platform.function.submitAsync
import taboolib.expansion.getDataContainer
import taboolib.platform.util.sendLang
@CommandHeader("AySignVariable", ["asv"], permission = "AySignVariable.command")
object AySignCommand {
@CommandBody(permission = "AySignVariable.admin.reload")
val reload = subCommand {
execute<CommandSender> { sender, _, _ ->
config.reload()
sender.sendMessage("配置文件重载成功")
}
}
@CommandBody
val sign = subCommand {
execute<CommandSender> { sender, _, _ ->
if (sender !is Player) {
sender.sendLang("sign-console")
return@execute
}
// 获取玩家数据库
val container = sender.getDataContainer()
// 获取玩家数据
val data = container[sender.name].let {
AySignAPI.getPlayer(it ?: AySignAPI.setPlayer())
}
submitAsync {
// 获取时间与天数
val day = data.day
val time = data.time
if(day > config.getInt("Reward-day")) {
sender.sendLang("sign-day")
return@submitAsync
}
if (!isOver24Hours(time)) {
sender.sendLang("sign-true", timeRemainingUntil24Hours(time), day)
return@submitAsync
}
sender.sendLang("sign-false")
container[sender.name] = AySignAPI.setPlayer(storeCurrentTime(), day + 1)
KetherUtil.runKether(config.getStringList("Reward-kether.$day"), sender)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
35fa020522503f8a645c60560af98d3090732ecd
| 1,958
|
AySignVariable
|
Creative Commons Zero v1.0 Universal
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Hours24.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 20416825}
|
package com.woowla.compose.icon.collections.tabler.tabler.outline
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.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.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.Hours24: ImageVector
get() {
if (_hours24 != null) {
return _hours24!!
}
_hours24 = Builder(name = "Hours24", 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 = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 13.0f)
curveToRelative(0.325f, 2.532f, 1.881f, 4.781f, 4.0f, 6.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 11.0f)
arcToRelative(8.1f, 8.1f, 0.0f, false, false, -15.5f, -2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 5.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 15.0f)
horizontalLineToRelative(2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
horizontalLineToRelative(-1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, 1.0f)
verticalLineToRelative(1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f)
horizontalLineToRelative(2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 15.0f)
verticalLineToRelative(2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f)
horizontalLineToRelative(1.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.0f, 15.0f)
verticalLineToRelative(6.0f)
}
}
.build()
return _hours24!!
}
private var _hours24: ImageVector? = null
| 0
|
Kotlin
|
0
| 1
|
b037895588c2f62d069c724abe624b67c0889bf9
| 3,990
|
compose-icon-collections
|
MIT License
|
domains/domain_common/src/main/java/com/bael/dads/domain/common/ext/ListExt.kt
|
virendersran01
| 356,644,618
| true
|
{"Kotlin": 200059}
|
package com.bael.dads.domain.common.ext
import com.bael.dads.domain.common.response.Response
import com.bael.dads.domain.common.response.Response.Success
/**
* Created by ErickSumargo on 01/01/21.
*/
fun <T> List<Response<T>>.findSuccess(): Success<T>? {
return firstOrNull { it is Success } as? Success
}
| 0
| null |
0
| 1
|
0dab6bcc5d7a6f726140e80fc21f503ab8b07c07
| 315
|
Dads
|
MIT License
|
keel-core/src/test/kotlin/com/netflix/spinnaker/keel/actuation/CheckSchedulerTests.kt
|
evansb
| 242,371,391
| true
|
{"Kotlin": 1371208, "Java": 9170, "Shell": 2086}
|
package com.netflix.spinnaker.keel.actuation
import com.netflix.spinnaker.keel.SPINNAKER_API_V1
import com.netflix.spinnaker.keel.persistence.AgentLockRepository
import com.netflix.spinnaker.keel.persistence.DeliveryConfigRepository
import com.netflix.spinnaker.keel.persistence.ResourceRepository
import com.netflix.spinnaker.keel.scheduled.ScheduledAgent
import com.netflix.spinnaker.keel.test.resource
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.Called
import io.mockk.clearAllMocks
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.time.Duration
import org.springframework.context.ApplicationEventPublisher
internal object CheckSchedulerTests : JUnit5Minutests {
private val resourceRepository = mockk<ResourceRepository>()
private val deliveryConfigRepository = mockk<DeliveryConfigRepository>()
private val resourceActuator = mockk<ResourceActuator>(relaxUnitFun = true)
private val environmentPromotionChecker = mockk<EnvironmentPromotionChecker>()
private val publisher = mockk<ApplicationEventPublisher>(relaxUnitFun = true)
class DummyScheduledAgent(override val lockTimeoutSeconds: Long) : ScheduledAgent {
override suspend fun invokeAgent() {
}
}
private val dummyAgent = mockk<DummyScheduledAgent>(relaxUnitFun = true) {
every {
lockTimeoutSeconds
} returns 5
}
private var agentLockRepository = mockk<AgentLockRepository>(relaxUnitFun = true) {
every { agents } returns listOf(dummyAgent)
}
private val resources = listOf(
resource(
apiVersion = "ec2.$SPINNAKER_API_V1",
kind = "security-group",
id = "ec2:security-group:prod:ap-south-1:keel-sg",
application = "keel"
),
resource(
apiVersion = "ec2.$SPINNAKER_API_V1",
kind = "cluster",
id = "ec2:cluster:prod:keel",
application = "keel"
)
)
fun tests() = rootContext<CheckScheduler> {
fixture {
CheckScheduler(
resourceRepository = resourceRepository,
deliveryConfigRepository = deliveryConfigRepository,
resourceActuator = resourceActuator,
environmentPromotionChecker = environmentPromotionChecker,
resourceCheckMinAgeDuration = Duration.ofMinutes(5),
resourceCheckBatchSize = 2,
publisher = publisher,
agentLockRepository = agentLockRepository
)
}
context("scheduler is disabled") {
test("nothing happens") {
checkResources()
verify { resourceActuator wasNot Called }
}
}
context("scheduler is enabled") {
before {
onApplicationUp()
every {
resourceRepository.itemsDueForCheck(any(), any())
} returns resources
}
after {
onApplicationDown()
}
test("all resources are checked") {
checkResources()
resources.forEach { resource ->
coVerify(timeout = 500) {
resourceActuator.checkResource(resource)
}
}
}
}
context("test invoke agents") {
before {
onApplicationUp()
}
test("invoke a single agent") {
every {
agentLockRepository.tryAcquireLock(any(), any())
} returns true
invokeAgent()
coVerify {
dummyAgent.invokeAgent()
}
}
after {
onApplicationDown()
clearAllMocks()
}
}
}
}
| 0
| null |
0
| 0
|
738c3f2998264c090e645dcf71ef252ad8349b9a
| 3,471
|
keel
|
Apache License 2.0
|
android/src/newarch/RnScheduleClearCacheSpec.kt
|
scantarbian
| 854,623,482
| false
|
{"Kotlin": 8724, "TypeScript": 4307, "Ruby": 2018, "JavaScript": 1722, "Objective-C++": 740, "Objective-C": 260, "C": 103, "Swift": 72}
|
package com.rnscheduleclearcache
import com.facebook.react.bridge.ReactApplicationContext
abstract class RnScheduleClearCacheSpec internal constructor(context: ReactApplicationContext) :
NativeRnScheduleClearCacheSpec(context) {}
| 0
|
Kotlin
|
0
| 0
|
2ab722290a54d763e446cdaf22f53631a653934b
| 240
|
rn-schedule-clear-cache
|
MIT License
|
android/src/newarch/RnScheduleClearCacheSpec.kt
|
scantarbian
| 854,623,482
| false
|
{"Kotlin": 8724, "TypeScript": 4307, "Ruby": 2018, "JavaScript": 1722, "Objective-C++": 740, "Objective-C": 260, "C": 103, "Swift": 72}
|
package com.rnscheduleclearcache
import com.facebook.react.bridge.ReactApplicationContext
abstract class RnScheduleClearCacheSpec internal constructor(context: ReactApplicationContext) :
NativeRnScheduleClearCacheSpec(context) {}
| 0
|
Kotlin
|
0
| 0
|
2ab722290a54d763e446cdaf22f53631a653934b
| 240
|
rn-schedule-clear-cache
|
MIT License
|
app/src/main/java/com/steleot/jetpackcompose/playground/compose/constraintlayout/BarrierScreen.kt
|
Vivecstel
| 338,792,534
| false
|
{"Kotlin": 1538487}
|
package com.steleot.jetpackcompose.playground.compose.constraintlayout
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.Button
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.steleot.jetpackcompose.playground.resources.R
import com.steleot.jetpackcompose.playground.navigation.graph.ConstraintLayoutNavRoutes
import com.steleot.jetpackcompose.playground.ui.base.material.DefaultScaffold
import timber.log.Timber
private const val URL = "constraintlayout/BarrierScreen.kt"
@Composable
fun BarrierScreen() {
DefaultScaffold(
title = ConstraintLayoutNavRoutes.Barrier,
link = URL,
) {
Column(
modifier = Modifier.fillMaxSize().padding(paddingValues = it),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
BarrierExample()
}
}
}
@Composable
private fun BarrierExample() {
ConstraintLayout {
val (button1, button2, text1) = createRefs()
Button(
onClick = { Timber.d("Button 1 pressed") },
modifier = Modifier.constrainAs(button1) {
top.linkTo(parent.top, margin = 16.dp)
}
) {
Text(stringResource(id = R.string.button_args, 1))
}
Text(stringResource(id = R.string.text_args, 1), Modifier.constrainAs(text1) {
top.linkTo(button1.bottom, margin = 16.dp)
centerAround(button1.end)
})
val barrier = createEndBarrier(button1, text1)
Button(
onClick = { Timber.d("Button 2 pressed") },
modifier = Modifier.constrainAs(button2) {
top.linkTo(parent.top, margin = 16.dp)
start.linkTo(barrier)
}
) {
Text(stringResource(id = R.string.button_args, 2))
}
}
}
| 1
|
Kotlin
|
46
| 346
|
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
| 2,405
|
Jetpack-Compose-Playground
|
Apache License 2.0
|
shared/domain/src/commonMain/kotlin/ly/david/musicsearch/shared/domain/place/PlaceDetailsModel.kt
|
lydavid
| 458,021,427
| false
|
{"Kotlin": 1934721, "HTML": 1854067, "Swift": 4205, "Python": 3527, "Shell": 1594, "Ruby": 955}
|
package ly.david.musicsearch.shared.domain.place
import ly.david.musicsearch.shared.domain.LifeSpanUiModel
import ly.david.musicsearch.shared.domain.listitem.AreaListItemModel
import ly.david.musicsearch.shared.domain.listitem.RelationListItemModel
data class PlaceDetailsModel(
override val id: String,
override val name: String,
override val disambiguation: String? = null,
override val address: String,
override val type: String? = null,
override val coordinates: CoordinatesUiModel? = null,
override val lifeSpan: LifeSpanUiModel? = null,
val area: AreaListItemModel? = null,
val urls: List<RelationListItemModel> = listOf(),
) : Place
| 115
|
Kotlin
|
0
| 45
|
3ab7303fca3a33f1a64e88ef3b411198fb25477c
| 678
|
MusicSearch
|
Apache License 2.0
|
androidApp/src/main/java/com/somabits/spanish/android/SpanishApp.kt
|
chiljamgossow
| 581,781,635
| false
| null |
package com.somabits.spanish.android
import android.app.Application
import com.somabits.spanish.android.di.androidModule
import com.somabits.spanish.android.di.viewModelModule
import com.somabits.spanish.di.appModule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.GlobalContext
import timber.log.Timber
class SpanishApp : Application() {
override fun onCreate() {
GlobalContext.startKoin {
androidContext(this@SpanishApp)
modules(appModule, viewModelModule, androidModule)
}
Timber.plant(Timber.DebugTree())
super.onCreate()
}
}
| 0
|
Kotlin
|
0
| 0
|
d7e8581b081ba3e3a27701e9d6fce038ec747716
| 625
|
Spanish
|
MIT License
|
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/presentation/account/details/mixin/WalletDetailsMixin.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 9662409, "Java": 16389, "Rust": 15215, "JavaScript": 425}
|
package io.novafoundation.nova.feature_account_impl.presentation.account.details.mixin
import io.novafoundation.nova.common.list.GroupedList
import io.novafoundation.nova.common.list.headers.TextHeader
import io.novafoundation.nova.common.list.toListWithHeaders
import io.novafoundation.nova.feature_account_api.domain.model.MetaAccount
import io.novafoundation.nova.feature_account_api.presenatation.account.details.ChainAccountActionsSheet.AccountAction
import io.novafoundation.nova.feature_account_impl.domain.account.details.AccountInChain
import io.novafoundation.nova.feature_account_impl.presentation.account.details.model.AccountTypeAlert
import io.novafoundation.nova.feature_account_impl.presentation.common.chainAccounts.AccountInChainUi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
abstract class WalletDetailsMixin(
val metaAccount: MetaAccount
) {
abstract val availableAccountActions: Flow<Set<AccountAction>>
abstract val typeAlert: Flow<AccountTypeAlert?>
val chainAccountProjections: Flow<List<Any>> = accountProjectionsFlow()
.map { groupedList ->
groupedList.toListWithHeaders(
keyMapper = { type, _ -> mapAccountHeader(type) },
valueMapper = { mapAccount(it) }
)
}
abstract fun accountProjectionsFlow(): Flow<GroupedList<AccountInChain.From, AccountInChain>>
abstract suspend fun mapAccountHeader(from: AccountInChain.From): TextHeader?
abstract suspend fun mapAccount(accountInChain: AccountInChain): AccountInChainUi
}
| 18
|
Kotlin
|
26
| 32
|
26d530400c30d00b08b23f9d69411f1719566930
| 1,577
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/afra/cheforia/model/Recipe.kt
|
afradigm
| 853,749,359
| false
|
{"Kotlin": 50350}
|
package com.afra.cheforia.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Recipe(
val id: Int,
val title: String,
val rate: String,
val ingredients: List<String>,
val instructions: List<String>,
@SerialName(value = "cooking_time") val cookingTime: Int,
@SerialName(value = "img_url") val imageUrl: String,
)
| 1
|
Kotlin
|
0
| 1
|
0e583ca99c9df4af703c8ddb27ca28e34cc03057
| 402
|
cheforia-android-app
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.