path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/dehnes/accounting/utils/kmymoney/booking_creators/TransferOutsideRealm.kt | sebdehne | 694,658,939 | false | {"Kotlin": 162290, "TypeScript": 138837, "CSS": 7370, "HTML": 1660, "SCSS": 1015, "JavaScript": 372} | package com.dehnes.accounting.utils.kmymoney.booking_creators
import com.dehnes.accounting.database.*
import com.dehnes.accounting.domain.StandardAccount
import com.dehnes.accounting.kmymoney.KMyMoneyUtils
import com.dehnes.accounting.utils.kmymoney.AccountImporter
import com.dehnes.accounting.utils.kmymoney.AccountWrapper
import com.dehnes.accounting.utils.kmymoney.BookingCreator
import java.sql.Connection
import java.time.Instant
object TransferOutsideRealm : BookingCreator {
override fun createBooking(
realmId: String,
transactionId: String,
datetime: Instant,
mainSplit: KMyMoneyUtils.KTransactionSplit,
otherSplits: Map<KMyMoneyUtils.KTransactionSplit, AccountWrapper>,
bankAccount: BankAccount,
bankAccountDto: AccountDto,
accountImporter: AccountImporter,
bookingRepository: BookingRepository,
connection: Connection
): List<AddBooking> {
val intermediateAccount = if (mainSplit.amountInCents > 0) {
accountImporter.getImportedAccountReceivable(connection, mainSplit.payeeId)
} else {
accountImporter.getImportedAccountPayable(connection, mainSplit.payeeId)
}
return listOf(
AddBooking(
realmId,
mainSplit.memo,
datetime,
listOf(
AddBookingEntry(
null,
bankAccountDto.id,
mainSplit.amountInCents
),
AddBookingEntry(
null,
intermediateAccount.accountDto.id,
mainSplit.amountInCents * -1
)
)
),
AddBooking(
realmId,
mainSplit.memo,
datetime,
listOf(
AddBookingEntry(
null,
intermediateAccount.accountDto.id,
mainSplit.amountInCents
),
AddBookingEntry(
null,
StandardAccount.OtherBankTransfers.toAccountId(realmId),
mainSplit.amountInCents * -1
)
)
),
)
}
} | 0 | Kotlin | 0 | 0 | d02d3c992630c90d86d0da8513be70d146f39443 | 2,383 | dehne-accounting | MIT License |
persian/src/main/java/io/github/madmaximuus/persian/chips/suggestion/PersianSuggestionChip.kt | MADMAXIMUUS | 689,789,834 | false | {"Kotlin": 845470} | package io.github.madmaximuus.persian.chips.assist
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import io.github.madmaximuus.persian.chips.founfation.BaseChip
import io.github.madmaximuus.persian.chips.founfation.ChipColors
import io.github.madmaximuus.persian.chips.founfation.ChipElevation
import io.github.madmaximuus.persian.chips.founfation.ChipSizes
@Composable
fun PersianAssistChip(
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
leadingIcon: Painter? = null,
colors: ChipColors = PersianAssistChipDefaults.chipColors(),
sizes: ChipSizes = PersianAssistChipDefaults.chipSizes(),
elevation: ChipElevation = PersianAssistChipDefaults.chipElevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) = BaseChip(
modifier = modifier,
onClick = onClick,
enabled = enabled,
label = label,
leadingIcon = leadingIcon,
trailingIcon = null,
colors = colors,
sizes = sizes,
minHeight = 32.dp,
paddingValues = PaddingValues(8.dp, 6.dp),
elevation = elevation,
interactionSource = interactionSource
)
| 0 | Kotlin | 1 | 1 | 1ccf0c0860a5ea07b9819792d52c02c241b65643 | 1,457 | Persian | MIT License |
persian/src/main/java/io/github/madmaximuus/persian/chips/suggestion/PersianSuggestionChip.kt | MADMAXIMUUS | 689,789,834 | false | {"Kotlin": 845470} | package io.github.madmaximuus.persian.chips.assist
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import io.github.madmaximuus.persian.chips.founfation.BaseChip
import io.github.madmaximuus.persian.chips.founfation.ChipColors
import io.github.madmaximuus.persian.chips.founfation.ChipElevation
import io.github.madmaximuus.persian.chips.founfation.ChipSizes
@Composable
fun PersianAssistChip(
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
leadingIcon: Painter? = null,
colors: ChipColors = PersianAssistChipDefaults.chipColors(),
sizes: ChipSizes = PersianAssistChipDefaults.chipSizes(),
elevation: ChipElevation = PersianAssistChipDefaults.chipElevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) = BaseChip(
modifier = modifier,
onClick = onClick,
enabled = enabled,
label = label,
leadingIcon = leadingIcon,
trailingIcon = null,
colors = colors,
sizes = sizes,
minHeight = 32.dp,
paddingValues = PaddingValues(8.dp, 6.dp),
elevation = elevation,
interactionSource = interactionSource
)
| 0 | Kotlin | 1 | 1 | 1ccf0c0860a5ea07b9819792d52c02c241b65643 | 1,457 | Persian | MIT License |
src/main/kotlin/com/gcrj/web/dao/UtilDao.kt | Gcrj | 149,216,707 | false | null | package com.gcrj.web.dao
import com.gcrj.web.bean.*
import com.gcrj.web.util.Constant
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.text.SimpleDateFormat
import java.util.*
object UtilDao {
init {
Class.forName("org.sqlite.JDBC")
}
/**
* 更新子项目、界面和界面相关进度
*/
fun updateProgress(subProjectId: Int): Boolean {
var conn: Connection? = null
try {
conn = DriverManager.getConnection(Constant.WEB_DB_PATH, null, null)
var stmt = conn.createStatement()
var rs = stmt.executeQuery("select activity._id, avg(activity_related.progress) from activity, activity_related where activity.sub_project_id = '$subProjectId' and activity_related.activity_id = activity._id group by activity._id")
while (rs.next()) {
val ps = conn.prepareStatement("update activity set progress = ? WHERE _id = ?")
ps.setInt(1, rs.getFloat(2).toInt())
ps.setInt(2, rs.getInt(1))
ps.executeUpdate()
ps.close()
}
stmt = conn.createStatement()
rs = stmt.executeQuery("select avg(progress) from activity where activity.sub_project_id = '$subProjectId'")
if (rs.next()) {
val progress = rs.getFloat(1).toInt()
val ps = conn.prepareStatement("update sub_project set progress = $progress WHERE _id = $subProjectId")
ps.executeUpdate()
ps.close()
}
return true
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
conn?.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
return false
}
fun queryAllInfo(userId: Int): List<ProjectBean> {
val list = mutableListOf<ProjectBean>()
var conn: Connection? = null
try {
conn = DriverManager.getConnection(Constant.WEB_DB_PATH, null, null)
val stmt = conn.createStatement()
// val calendar = Calendar.getInstance()
// calendar.set(Calendar.DAY_OF_WEEK, 2)
// val monday = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
// calendar.timeInMillis += 7 * 24 * 60 * 60 * 1000
// val nextMonday = SimpleDateFormat("yyyy-MM-dd").format(calendar.time)
val rs = stmt.executeQuery("select project._id, project.name, sub_project._id, sub_project.name, sub_project.progress, sub_project.deadline, sub_project.completion_time, sub_project.version_name, activity._id, activity.name, activity.progress, activity_related._id, activity_related.name, activity_related.progress " +
"from project, project_user, sub_project, activity, activity_related " +
"where project_user.user_id = '$userId' and project_user.project_id = sub_project.project_id and project._id = sub_project.project_id and activity.sub_project_id = sub_project._id " +
"and activity_related.activity_id = activity._id " +
// " and activity_related.time between '$monday' and '$nextMonday'" +
"order by project._id asc, sub_project._id asc, activity._id asc, activity_related._id asc")
var lastProjectId = 0
var lastSubProjectId = 0
var lastActivityId = 0
while (rs.next()) {
val projectId = rs.getInt(1)
val subProjectId = rs.getInt(3)
val activityId = rs.getInt(9)
if (projectId != lastProjectId) {
val project = ProjectBean()
project.id = projectId
project.name = rs.getString(2)
project.subProject = mutableListOf()
list.add(project)
val subProject = SubProjectBean()
subProject.id = subProjectId
subProject.name = rs.getString(4)
subProject.progress = rs.getInt(5)
subProject.deadline = rs.getString(6)
subProject.completionTime = rs.getString(7)
subProject.versionName = rs.getString(8)
subProject.activity = mutableListOf()
(project.subProject as MutableList).add(subProject)
val activity = ActivityBean()
activity.id = activityId
activity.name = rs.getString(10)
activity.progress = rs.getInt(11)
activity.activityRelated = mutableListOf()
(subProject.activity as MutableList).add(activity)
val activityRelated = ActivityRelatedBean()
activityRelated.id = rs.getInt(12)
activityRelated.name = rs.getString(13)
activityRelated.progress = rs.getInt(14)
(activity.activityRelated as MutableList).add(activityRelated)
} else {
if (subProjectId != lastSubProjectId) {
val subProject = SubProjectBean()
subProject.id = subProjectId
subProject.name = rs.getString(4)
subProject.progress = rs.getInt(5)
subProject.deadline = rs.getString(6)
subProject.completionTime = rs.getString(7)
subProject.versionName = rs.getString(8)
subProject.activity = mutableListOf()
(list.last().subProject as MutableList).add(subProject)
val activity = ActivityBean()
activity.id = activityId
activity.name = rs.getString(10)
activity.progress = rs.getInt(11)
activity.activityRelated = mutableListOf()
(subProject.activity as MutableList).add(activity)
val activityRelated = ActivityRelatedBean()
activityRelated.id = rs.getInt(12)
activityRelated.name = rs.getString(13)
activityRelated.progress = rs.getInt(14)
(activity.activityRelated as MutableList).add(activityRelated)
} else {
if (activityId != lastActivityId) {
val activity = ActivityBean()
activity.id = activityId
activity.name = rs.getString(10)
activity.progress = rs.getInt(11)
activity.activityRelated = mutableListOf()
(list.last().subProject!!.last().activity as MutableList).add(activity)
val activityRelated = ActivityRelatedBean()
activityRelated.id = rs.getInt(12)
activityRelated.name = rs.getString(13)
activityRelated.progress = rs.getInt(14)
(activity.activityRelated as MutableList).add(activityRelated)
} else {
val activityRelated = ActivityRelatedBean()
activityRelated.id = rs.getInt(12)
activityRelated.name = rs.getString(13)
activityRelated.progress = rs.getInt(14)
(list.last().subProject!!.last().activity!!.last().activityRelated as MutableList).add(activityRelated)
}
}
}
lastProjectId = projectId
lastSubProjectId = subProjectId
lastActivityId = activityId
}
stmt.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
conn?.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
return list
}
} | 0 | Kotlin | 0 | 0 | 14883e2e4e38b656a3248ca7062a9890453eaba7 | 8,269 | ProjectControlWeb | MIT License |
app/src/main/java/com/kire/audio/di/TrackUseCasesModule.kt | KiREHwYE | 674,992,893 | false | {"Kotlin": 276219} | package com.kire.audio.di
import com.kire.audio.domain.use_case.util.ITrackUseCases
import com.kire.audio.domain.use_case.util.TrackUseCases
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class TrackUseCasesModule {
@Binds
abstract fun provideTrackUseCases(trackUseCases: TrackUseCases): ITrackUseCases
} | 0 | Kotlin | 0 | 0 | faea19fe52e18fcad60a4fb01f65c77f461da288 | 442 | RE13 | Apache License 2.0 |
api/src/main/kotlin/io/rsbox/api/event/login/PlayerLoginEvent.kt | TheProdigy94 | 199,138,033 | false | null | package io.rsbox.api.event.login
import io.rsbox.api.World
import io.rsbox.api.event.Event
import io.rsbox.api.entity.Player
/**
* @author <NAME>
*/
class PlayerLoginEvent(val player: Player, val world: World) : Event() | 0 | Kotlin | 0 | 0 | b83537fb4cb39be1a9fb22354477b9063d518d0d | 224 | rsbox | Apache License 2.0 |
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/plugin/PluginFilterStep.kt | rhdunn | 62,201,764 | false | null | /*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.ast.plugin
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathAxisStep
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
/**
* An XPath 3.0 and XQuery 3.0 `AxisStep` node in the XPath and XQuery AST
* that is associated with a `Predicate` node.
*/
interface PluginFilterStep : XPathAxisStep, XpmExpression
| 47 | Kotlin | 4 | 25 | d363dad28df1eb17c815a821c87b4f15d2b30343 | 981 | xquery-intellij-plugin | Apache License 2.0 |
backend/repo/inmemory/src/test/kotlin/ru/otus/opinion/repo/inmemory/CreateTest.kt | otuskotlin | 378,047,392 | false | null | package ru.otus.opinion.repo.inmemory
import ru.otus.opinion.repo.api.test.CreateTestBase
class CreateTest : CreateTestBase() {
override val repo = CacheBasedRepo()
} | 0 | Kotlin | 0 | 0 | ccde46da64355724add000dd88eb9e8b6fc3de7c | 172 | ok-202105-qa-mz | MIT License |
app/src/main/java/com/jthou/wanandroidkotlin/viewmodel/ProjectViewModelFactory.kt | jthou20121212 | 210,117,827 | false | null | package com.jthou.wanandroidkotlin.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.jthou.wanandroidkotlin.repository.ProjectRepository
/**
*
*
* @author jthou
* @version 1.0.0
* @date 07-09-2019
*/
class ProjectViewModelFactory(private val repository : ProjectRepository) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return ProjectViewModel(repository) as T
}
} | 0 | Kotlin | 0 | 0 | 7518eccff844b4c9191f69b7d9c6b72b13373f49 | 502 | WanAndroidKotlin | Apache License 2.0 |
app/src/main/kotlin/na/komi/kodesh/ui/widget/LayoutedTextView.kt | inshiro | 174,658,194 | false | null | package na.komi.kodesh.ui.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.text.Layout
import android.text.Spannable
import android.text.StaticLayout
import android.text.TextPaint
import android.text.style.ForegroundColorSpan
import android.text.style.LeadingMarginSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import na.komi.kodesh.Prefs
import na.komi.kodesh.util.log
import na.komi.kodesh.util.page.Fonts
import na.komi.kodesh.util.sp
import kotlin.math.absoluteValue
class LayoutedTextView : AppCompatTextView {
private var mOnLayoutListener: OnLayoutListener? = null
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}
var showDropCap = false
var dropCapText = ""
var showDropCapMargin = false
interface OnLayoutListener {
fun onLayouted(view: AppCompatTextView)
}
fun setOnLayoutListener(listener: OnLayoutListener) {
mOnLayoutListener = listener
}
fun removeOnLayoutListener(listener: OnLayoutListener) {
mOnLayoutListener = listener
mOnLayoutListener = null
}
override fun onLayout(
changed: Boolean, left: Int, top: Int, right: Int,
bottom: Int
) {
super.onLayout(changed, left, top, right, bottom)
if (mOnLayoutListener != null) {
mOnLayoutListener!!.onLayouted(this)
}
}
val tp by lazy {
TextPaint().apply {
isAntiAlias = true
color = Color.WHITE
style = Paint.Style.FILL
typeface = Fonts.GentiumPlus_R
textSize = sp(Prefs.mainFontSize * 4)
}
}
var sLayout: StaticLayout? = null
private var PADDING_BOUNDS = 20
private val leadingMarginSpan by lazy { LeadingMarginSpan3() }
fun getStaticLayout(str: CharSequence, textSize: Float, width: Int): StaticLayout {
if (tp.textSize == textSize && sLayout != null) return sLayout!!
if (tp.textSize != textSize || sLayout == null) {
tp.textSize = textSize
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
log d "Create StaticLayout"
val builder = StaticLayout.Builder.obtain(str, 0, str.length, tp, width)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setLineSpacing(0f, 1f)
.setIncludePad(false)
.setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NONE)
return builder.build()
} else {
@Suppress("DEPRECATION")
return StaticLayout(
str,
tp,
width,
Layout.Alignment.ALIGN_NORMAL,
1f,
0f,
false
)
}
}
return sLayout!!
}
/*
override fun onDrawForeground(canvas: Canvas?) {
if (!showDropCap) {super.onDrawForeground(canvas); return}
if (canvas!=null) {
//super.onDrawForeground(canvas)
log d "Called onDrawForeground"
val dLayout = getStaticLayout(text.take(1).toString(), width)
dLayout.draw(canvas)
}
}
*/
var drawn = false
var drawCount = 0
var hasPeriscope = false
val MARGIN_PADDING = 20
override fun onDraw(canvas: Canvas?) {
if (!showDropCap) {
//log d "onDraw"
super.onDraw(canvas)
} else {
if (canvas != null) {
// if (drawn) return
//var moveY = y+height-(top+Math.abs(paint.descent()))
//drawCount++
//log w "onDraw $drawCount"
var moveY = y + height - (top + Math.abs(paint.descent()))
//log w "linecount: ${lineCount}"
for (i in leadingMarginSpan.lineCount + 1..lineCount) {
moveY -= Math.abs(paint.fontMetrics.top) + Math.abs(paint.fontMetrics.bottom)
}
moveY += paint.fontMetrics.descent / 3
//log w "movey: $moveY"
if (hasPeriscope) {
// Getting n amount of line heights and multiplying that to the abs value of ascent (Bottom of first line text)
val line = layout.getLineForOffset(text.lastIndexOf("\n") + 3) + 1
val v = paint.fontMetrics.ascent.absoluteValue + (lineHeight.toFloat() * line)
//canvas.drawLine(0f, v, width.toFloat(), v + 5f, paint)
//log i "line for offset $line"
moveY = v
}
tp.textSize = paint.textSize * 4
tp.color = paint.color
// TOP of first line text
// canvas.drawLine(0f, paint.fontMetrics.descent, width.toFloat(), paint.fontMetrics.descent + 5f, paint)
// canvas.drawLine(0f, paint.fontMetrics.bottom, width.toFloat(), paint.fontMetrics.bottom + 5f, paint)
// canvas.drawLine(0f, paint.fontMetrics.leading, width.toFloat(), paint.fontMetrics.leading + 5f, paint)
// Bottom of first line text
// canvas.drawLine(0f, moveY, width.toFloat(), moveY + 5f, paint)
// Getting line height if TextView.getLineHeight() is not accessible. https://stackoverflow.com/a/16050019
// val lh = paint.fontMetrics.top - paint.fontMetrics.bottom
// log i "fm.top - fm.bottom: ${lh} line height: ${lineHeight}"
val ss = text as Spannable
val redSpans = ss.getSpans(0, 1, ForegroundColorSpan::class.java)
for (redSpan in redSpans) {
tp.color = redSpan.foregroundColor
}
canvas.drawText(dropCapText, x + paddingLeft.toFloat(), moveY, tp)
val spans = ss.getSpans(0, ss.length, LeadingMarginSpan3::class.java)
for (span in spans) {
span.setMargin(tp.measureText(dropCapText).toInt() + MARGIN_PADDING)
}
super.onDraw(canvas)
}
}
}
}
class LeadingMarginSpan3(private var margin: Int = 0, var lineCount: Int = 2) :
LeadingMarginSpan.LeadingMarginSpan2 {
override fun getLeadingMargin(first: Boolean): Int {
return if (first) margin else 0
}
override fun getLeadingMarginLineCount(): Int {
return lineCount
}
fun setMargin(size: Int) {
margin = size
}
override fun drawLeadingMargin(
c: Canvas?,
p: Paint?,
x: Int,
dir: Int,
top: Int,
baseline: Int,
bottom: Int,
text: CharSequence?,
start: Int,
end: Int,
first: Boolean,
layout: Layout?
) {
}
} | 0 | Kotlin | 3 | 8 | 311fe579feb9948086e0523226c11a69dac26133 | 7,216 | kodesh | Apache License 2.0 |
src/main/kotlin/trik/testsys/webclient/entity/impl/Task.kt | Pupsen-Vupsen | 627,349,038 | false | {"Kotlin": 218154, "HTML": 153787, "CSS": 12506, "JavaScript": 3471, "Dockerfile": 953} | package trik.testsys.webclient.entity.impl
import trik.testsys.core.entity.Entity.Companion.TABLE_PREFIX
import trik.testsys.webclient.entity.AbstractNotedEntity
import trik.testsys.webclient.entity.user.impl.Developer
import javax.persistence.*
@Entity
@Table(name = "${TABLE_PREFIX}_TASK")
class Task(
name: String
) : AbstractNotedEntity(name) {
/**
* @author <NAME>
* @since 1.1.0
*/
@ManyToOne
@JoinColumn(
nullable = false, unique = false, updatable = false,
name = "developer_id", referencedColumnName = "id"
)
lateinit var developer: Developer
@ManyToMany(mappedBy = "tasks")
val taskFiles: MutableSet<TaskFile> = mutableSetOf()
@get:Transient
val polygons: Set<TaskFile>
get() = taskFiles.filter { it.type == TaskFile.TaskFileType.POLYGON }.toSet()
@get:Transient
val exercise: TaskFile?
get() = taskFiles.firstOrNull { it.type == TaskFile.TaskFileType.EXERCISE }
@get:Transient
val solution: TaskFile?
get() = taskFiles.firstOrNull { it.type == TaskFile.TaskFileType.SOLUTION }
} | 5 | Kotlin | 1 | 0 | 5d599e96dfbed6578e84ddb93af3b0a12ae2cc1d | 1,107 | trik-testsys-web-client | Apache License 2.0 |
app/src/main/java/com/julive/adapter_demo/ext/ViewExt.kt | bagutree | 378,672,502 | false | null | package com.julive.adapter_demo.ext
import android.content.Context
import android.util.AttributeSet
import android.view.ViewManager
import android.widget.FrameLayout
import androidx.cardview.widget.CardView
import com.julive.adapter_demo.R
import kotlinx.android.synthetic.main.include_card_button.view.*
import org.jetbrains.anko.custom.ankoView
import org.jetbrains.anko.include
/**
* 自定义Card样式的Button
*/
class CardButtonView : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
)
init {
include<CardView>(R.layout.include_card_button)
}
fun setText(text: String): CardButtonView {
card_text.text = text
return this
}
}
inline fun Context.cardView(): CardView = cardView() {}
inline fun Context.cardView(init: CardView.() -> Unit = {}): CardView {
return ankoView({ CardView(it) }, theme = 0, init = init)
}
inline fun ViewManager.cardView(): CardView = cardView() {}
inline fun ViewManager.cardView(init: CardView.() -> Unit = {}): CardView {
return ankoView({ CardView(it) }, theme = 0, init = init)
} | 0 | Kotlin | 0 | 4 | 5c6f6952ac2475616a7b12020c42d830b1ccb5b2 | 1,290 | RecyclerViewAdapter | Apache License 2.0 |
rt-common/src/main/kotlin/xyz/redtorch/common/trade/client/service/TradeClientSyncService.kt | sun0x00 | 130,566,707 | false | null | package xyz.redtorch.common.trade.client.service
import xyz.redtorch.common.sync.dto.CancelOrder
import xyz.redtorch.common.sync.dto.InsertOrder
import xyz.redtorch.common.trade.dto.Contract
interface TradeClientSyncService {
fun setCallBack(callBack: TradeClientSyncServiceCallBack)
fun auth(userId: String, authToken: String): Boolean
fun subscribeContract(contract: Contract)
fun unsubscribeContract(contract: Contract)
fun subscribeContractList(contractList: List<Contract>)
fun unsubscribeContractList(contractList: List<Contract>)
fun cancelOrder(cancelOrder: CancelOrder)
fun submitOrder(insertOrder: InsertOrder)
fun getDelay(): Long
fun isConnected(): Boolean
fun isAutoReconnect(): Boolean
} | 0 | null | 346 | 714 | c6a036adc262829e28d8e6cd2ea4bc3b7089b863 | 753 | redtorch | MIT License |
code-generators/src/main/kotlin/com/danrusu/pods4k/ModulePath.kt | daniel-rusu | 774,714,857 | false | {"Kotlin": 38006} | package com.danrusu.pods4k
private const val SUFFIX = "src/main/kotlin"
internal object ModulePath {
internal const val IMMUTABLE_ARRAYS = "immutable-arrays/$SUFFIX"
}
| 0 | Kotlin | 0 | 0 | 4d56f85e478e749593ef9b6aaa1663cc53aee9bc | 174 | pods4k | Apache License 2.0 |
src/main/kotlin/org/vitrivr/cottontail/database/queries/planning/rules/physical/implementation/EntityScanImplementationRule.kt | pombredanne | 341,129,834 | true | {"Kotlin": 1056564, "Dockerfile": 472, "Shell": 164} | package org.vitrivr.cottontail.database.queries.planning.rules.physical.implementation
import org.vitrivr.cottontail.database.queries.planning.nodes.interfaces.NodeExpression
import org.vitrivr.cottontail.database.queries.planning.nodes.interfaces.RewriteRule
import org.vitrivr.cottontail.database.queries.planning.nodes.logical.sources.EntityScanLogicalNodeExpression
import org.vitrivr.cottontail.database.queries.planning.nodes.physical.sources.EntityScanPhysicalNodeExpression
/**
* A [RewriteRule] that replaces a [EntityScanLogicalNodeExpression] by a [EntityScanPhysicalNodeExpression].
*
* @author <NAME>
* @version 1.0
*/
object EntityScanImplementationRule : RewriteRule {
override fun canBeApplied(node: NodeExpression): Boolean = node is EntityScanLogicalNodeExpression
override fun apply(node: NodeExpression): NodeExpression? {
if (node is EntityScanLogicalNodeExpression) {
val children = node.copyOutput()
val p = EntityScanPhysicalNodeExpression(node.entity, node.columns)
children?.addInput(p)
return p
}
return null
}
} | 0 | null | 0 | 0 | 6a5c4d7dc84eb7877acb0729c1267e1d3ab8b8f0 | 1,130 | cottontaildb | MIT License |
presentation/src/main/java/com/bayarsahintekin/matchscores/ui/components/games/GameDetailScreen.kt | bayarsahintekin0 | 651,000,613 | false | {"Kotlin": 182502} | package com.bayarsahintekin.matchscores.ui.components.games
import android.annotation.SuppressLint
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.bayarsahintekin.domain.entity.teams.TeamEntity
import com.bayarsahintekin.matchscores.ui.viewmodel.GamesViewModel
import com.bayarsahintekin.matchscores.util.TeamLogosObject
import kotlinx.coroutines.launch
@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
fun GameDetailScreen(
gameDetailViewModel: GamesViewModel = hiltViewModel(),
gameId: Int
) {
//TeamList(items = items)
}
| 0 | Kotlin | 0 | 2 | c69585cc9adceca58ed1dcc33833bae66a9ddc0c | 2,446 | MatchScores | Open LDAP Public License v2.2.1 |
core/src/commonMain/kotlin/com/maxkeppeker/sheets/core/icons/rounded/Star.kt | maxkeppeler | 523,345,776 | false | {"Kotlin": 1337179, "Python": 4978, "Shell": 645} | package com.maxkeppeker.sheets.core.icons.rounded
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
public val Star: ImageVector
get() {
if (_star != null) {
return _star!!
}
_star = materialIcon(name = "Rounded.Star") {
materialPath {
moveTo(12.0f, 17.27f)
lineToRelative(4.15f, 2.51f)
curveToRelative(0.76f, 0.46f, 1.69f, -0.22f, 1.49f, -1.08f)
lineToRelative(-1.1f, -4.72f)
lineToRelative(3.67f, -3.18f)
curveToRelative(0.67f, -0.58f, 0.31f, -1.68f, -0.57f, -1.75f)
lineToRelative(-4.83f, -0.41f)
lineToRelative(-1.89f, -4.46f)
curveToRelative(-0.34f, -0.81f, -1.5f, -0.81f, -1.84f, 0.0f)
lineTo(9.19f, 8.63f)
lineTo(4.36f, 9.04f)
curveToRelative(-0.88f, 0.07f, -1.24f, 1.17f, -0.57f, 1.75f)
lineToRelative(3.67f, 3.18f)
lineToRelative(-1.1f, 4.72f)
curveToRelative(-0.2f, 0.86f, 0.73f, 1.54f, 1.49f, 1.08f)
lineTo(12.0f, 17.27f)
close()
}
}
return _star!!
}
private var _star: ImageVector? = null
| 14 | Kotlin | 38 | 816 | 2af41f317228e982e261522717b6ef5838cd8b58 | 1,369 | sheets-compose-dialogs | Apache License 2.0 |
app/src/main/java/com/frogobox/wallpaper/di/DelegateModule.kt | amirisback | 247,242,834 | false | null | package com.frogobox.wallpaper.di
import com.frogobox.sdk.delegate.preference.PreferenceDelegatesImpl
import com.frogobox.wallpaper.ext.APP_PREF_NAME
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
/**
* Created by Faisal Amir on 08/01/23
* Copyright (C) Frogobox
*/
val delegateModule = module {
single {
PreferenceDelegatesImpl(androidContext(), APP_PREF_NAME)
}
}
| 1 | null | 3 | 8 | 0ca8e554f2064fcb4e882fac458214a08efd2507 | 418 | wallpaper | Apache License 2.0 |
data/src/main/java/com/lefarmico/data/repository/manager/ThemeManagerImpl.kt | LeFarmico | 382,809,671 | false | null | package com.lefarmico.data.repository.manager
import android.util.Log
import com.lefarmico.domain.preferences.ThemeSettingsPreferenceHelper
import com.lefarmico.domain.repository.manager.ThemeManager
import io.reactivex.rxjava3.core.Single
import javax.inject.Inject
class ThemeManagerImpl @Inject constructor(
private val helper: ThemeSettingsPreferenceHelper
) : ThemeManager {
override fun getCurrentTheme(): Single<Int> {
return Single.create {
val themeId = helper.getCurrentThemeRes()
it.onSuccess(themeId)
}
}
override fun setCurrentTheme(themeId: Int) {
helper.setCurrentThemeRes(themeId)
}
}
| 0 | Kotlin | 0 | 3 | e1fa8a81aefcb6131b704f787b1fa9b5518a6735 | 673 | GymSupporter | Apache License 2.0 |
ui-common/src/main/java/com/facebook/fresco/ui/common/LegacyOnFadeListener.kt | facebook | 31,533,997 | false | {"Java": 2895425, "Kotlin": 1024596, "C++": 183862, "C": 53836, "Makefile": 10411, "Python": 10096, "Shell": 840} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.ui.common
@Deprecated(
"Please use the OnFadeListener directly",
replaceWith =
ReplaceWith(
"OnFadeListener",
"import com.facebook.fresco.ui.common.OnFadeListener",
),
)
interface LegacyOnFadeListener {
fun onFadeStarted(id: String)
fun onFadeFinished(id: String)
}
| 233 | Java | 3751 | 17,073 | dbb46cebfffeeabf289db5f4a8d64950ba1e020d | 539 | fresco | MIT License |
app/src/main/java/com/example/mrokey/besttrip/entities/Company.kt | youknowbaron | 139,706,638 | false | {"Kotlin": 109066} | package com.example.mrokey.besttrip.entities
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
data class Company(
val name: String,
val address: String,
val phone: String,
val vehicles: ArrayList<Vehicle>,
val wait_time: Long,
val logo: String
)
@Parcelize
data class Vehicle(
val name: String = "",
val number_seat: Long = 0,
val _1km: Long = 0,
val over_1km: Double = 0.0,
val over_30km: Double = 0.0
): Parcelable | 0 | Kotlin | 0 | 0 | 7677b547e6ef21729c6212bff39e62a6c7da8d86 | 527 | week45-TogetherWeGo | Apache License 2.0 |
simple-stack-example-scoping/src/main/java/com/zhuinden/simplestackexamplescoping/core/scoping/ScopeConfiguration.kt | yongaru | 193,541,339 | true | {"Java": 855179, "Kotlin": 248936, "IDL": 410} | package com.zhuinden.simplestackexamplescoping.core.scoping
import com.zhuinden.simplestack.ScopedServices
import com.zhuinden.simplestack.ServiceBinder
class ScopeConfiguration : ScopedServices {
override fun bindServices(serviceBinder: ServiceBinder) {
val key = serviceBinder.getKey<Any>()
if (key is HasServices) {
key.bindServices(serviceBinder)
}
}
} | 0 | Java | 0 | 0 | ac5ec424f44c12d91dd6f7bbaa749387a47d85b6 | 402 | simple-stack | Apache License 2.0 |
androidApp/src/main/java/gcu/production/stavlenta/android/repository/modules/RestModule.kt | Ilyandr | 576,032,482 | false | null | package gcu.production.stavlenta.android.repository.modules
import android.content.Context
import coil.request.CachePolicy
import coil.request.ImageRequest
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import gcu.production.stavlenta.repository.di.CommonSDK
import gcu.production.stavlenta.repository.feature.other.LOGIN_KEY
import gcu.production.stavlenta.repository.feature.other.PASSWORD_KEY
import gcu.production.stavlenta.repository.feature.other.convertToBase64
@Module
@InstallIn(ViewModelComponent::class)
internal class RestModule {
@Provides
fun requireAuthImageRequest(@ApplicationContext context: Context) =
ImageRequest.Builder(context)
.addHeader("Authorization", CommonSDK.storageSource.run {
convertToBase64(getString(LOGIN_KEY), getString(PASSWORD_KEY))
})
.crossfade(true)
.memoryCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.DISABLED)
} | 0 | Kotlin | 0 | 1 | 4e797410e7482cffebdc5b988fa7819b3ebd4a77 | 1,108 | StavLenta-multiplatform | MIT License |
idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesClassRootsIndex.kt | shadrina | 171,863,726 | true | {"Kotlin": 52180060, "Java": 7665872, "JavaScript": 185101, "HTML": 78949, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "Swift": 10768, "CSS": 9270, "Shell": 7220, "Batchfile": 5727, "Ruby": 2655, "Objective-C": 626, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.script
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.*
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_PATH
import java.io.DataInput
import java.io.DataOutput
import java.util.*
class ScriptTemplatesClassRootsIndex :
ScalarIndexExtension<String>(),
FileBasedIndex.InputFilter, KeyDescriptor<String>,
DataIndexer<String, Void, FileContent> {
companion object {
val KEY = ID.create<String, Void>(ScriptTemplatesClassRootsIndex::class.java.canonicalName)
const val VALUE = "MY_VALUE"
private val suffix = SCRIPT_DEFINITION_MARKERS_PATH.removeSuffix("/")
}
override fun getName(): ID<String, Void> = KEY
override fun getIndexer(): DataIndexer<String, Void, FileContent> = this
override fun getKeyDescriptor(): KeyDescriptor<String> = this
override fun getInputFilter(): FileBasedIndex.InputFilter = this
override fun dependsOnFileContent() = false
override fun getVersion(): Int = 2
override fun indexDirectories(): Boolean = false
override fun acceptInput(file: VirtualFile): Boolean {
val parent = file.parent ?: return false
return parent.isDirectory
&& parent.path.endsWith(suffix)
&& file.path.endsWith(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT)
}
override fun save(out: DataOutput, value: String) = IOUtil.writeUTF(out, value)
override fun read(input: DataInput): String? = IOUtil.readUTF(input)
override fun getHashCode(value: String): Int = value.hashCode()
override fun isEqual(val1: String?, val2: String?): Boolean {
return val1 == val2
}
override fun map(inputData: FileContent): Map<String?, Void?> {
return Collections.singletonMap(VALUE, null)
}
} | 1 | Kotlin | 1 | 1 | 3c8a1270722bce3bfef8205d265786fa0c1bb9c6 | 2,226 | kotlin | Apache License 2.0 |
app/src/main/java/com/jsw/tweetmap/ui/splash/SplashActivity.kt | joselusw | 268,129,616 | false | null | package com.jsw.tweetmap.ui.splash
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.jsw.tweetmap.R
import android.content.Intent
import android.os.Handler
import com.jsw.tweetmap.MainActivity
class SplashActivity : AppCompatActivity() {
/* -- VARS --*/
private lateinit var myHandler : Handler
private val splashTime = 2000L // 2 seconds
/* -- FUNCTIONS --*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
myHandler = Handler()
myHandler.postDelayed({
goToMainActivity()
},splashTime)
}
/**
* Display the main activity and finish the current one
*/
private fun goToMainActivity(){
val mainActivityIntent = Intent(applicationContext, MainActivity::class.java)
startActivity(mainActivityIntent)
finish()
}
} | 0 | Kotlin | 0 | 0 | 8c760b899164ace91ab6c6c8d712b515090af393 | 950 | TweetMap-public | MIT License |
torque-core/src/main/kotlin/com/workday/torque/ProcessRunner.kt | Workday | 170,632,912 | false | null | package com.workday.torque
import com.gojuno.commander.android.adb
import com.gojuno.commander.os.Notification
import com.gojuno.commander.os.process
import io.reactivex.Observable
import java.io.File
import java.util.concurrent.TimeUnit
class ProcessRunner {
fun run(commandAndArgs: List<String>,
timeout: Timeout? = Timeout(DEFAULT_PER_CHUNK_TIMEOUT_SECONDS.toInt(), TimeUnit.SECONDS),
redirectOutputTo: File? = null,
keepOutputOnExit: Boolean = false,
unbufferedOutput: Boolean = false,
print: Boolean = false,
destroyOnUnsubscribe: Boolean = false): Observable<Notification> {
return process(commandAndArgs, timeout?.toPair(), redirectOutputTo, keepOutputOnExit, unbufferedOutput, print, destroyOnUnsubscribe)
.toV2Observable()
}
fun runAdb(commandAndArgs: List<String>,
timeout: Timeout? = Timeout(DEFAULT_PER_CHUNK_TIMEOUT_SECONDS.toInt(), TimeUnit.SECONDS),
redirectOutputTo: File? = null,
keepOutputOnExit: Boolean = false,
unbufferedOutput: Boolean = false,
print: Boolean = false,
destroyOnUnsubscribe: Boolean = false
): Observable<Notification> {
return run(listOf(adb) + commandAndArgs,
timeout,
redirectOutputTo,
keepOutputOnExit,
unbufferedOutput,
print,
destroyOnUnsubscribe)
}
}
| 0 | Kotlin | 5 | 7 | 088a18f03c60d44727381cf4163074a389128837 | 1,527 | torque | Apache License 2.0 |
src/main/kotlin/me/senseiwells/players/network/FakeConnection.kt | senseiwells | 867,818,868 | false | {"Kotlin": 60935, "Java": 8876} | package me.senseiwells.players.network
import io.netty.channel.embedded.EmbeddedChannel
import me.senseiwells.players.mixins.ConnectionAccessor
import net.minecraft.network.Connection
import net.minecraft.network.PacketListener
import net.minecraft.network.ProtocolInfo
import net.minecraft.network.protocol.PacketFlow
@Suppress("CAST_NEVER_SUCCEEDS")
class FakeConnection: Connection(PacketFlow.SERVERBOUND) {
init {
(this as ConnectionAccessor).setChannel(EmbeddedChannel())
}
override fun <T: PacketListener?> setupInboundProtocol(protocolInfo: ProtocolInfo<T>, listener: T) {
(this as ConnectionAccessor).setPacketListener(listener)
}
} | 0 | Kotlin | 0 | 0 | 9f97c535feee95d3868afe415562cd7d787f5bb4 | 675 | FakePlayers | MIT License |
buildSrc/src/main/kotlin/RepositoryHandler.kt | zmwas | 284,056,937 | true | {"Kotlin": 32280} | import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import org.gradle.kotlin.dsl.maven
private const val DATA_STORE_SNAPSHOT =
"https://androidx.dev/snapshots/builds/6639139/artifacts/repository"
private const val JITPACK =
"https://jitpack.io"
private const val KOTLIN_EAP =
"https://dl.bintray.com/kotlin/kotlin-eap"
fun RepositoryHandler.android(): MavenArtifactRepository = google {
content {
includeGroupByRegex("androidx.*")
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeModule("org.jetbrains.kotlin", "kotlin-compiler-embeddable")
}
}
fun RepositoryHandler.jitpack(): MavenArtifactRepository = maven(JITPACK) {
content {
includeGroupByRegex("com\\.github\\.ashdavies.*")
}
}
fun RepositoryHandler.kotlin(): MavenArtifactRepository = maven(KOTLIN_EAP) {
content {
includeGroup("org.jetbrains.kotlin")
}
}
fun RepositoryHandler.tensorflow(): MavenArtifactRepository = jcenter {
content {
includeModule("org.tensorflow", "tensorflow-lite-support")
}
}
fun RepositoryHandler.trove4j(): MavenArtifactRepository = jcenter {
content {
includeModule("org.jetbrains.trove4j", "trove4j")
}
}
fun RepositoryHandler.dataStore(): MavenArtifactRepository = maven(DATA_STORE_SNAPSHOT) {
content {
includeGroup("androidx.datastore")
}
}
| 0 | null | 0 | 0 | f002b54317c625ea4c97c518f4289704f30f590a | 1,479 | playground | Apache License 2.0 |
src/main/kotlin/systems/ajax/malov/stockanalyzer/service/StockClientApi.kt | ajax-malov-n | 841,964,113 | false | {"Kotlin": 26008, "Dockerfile": 246} | package systems.ajax.malov.stockanalyzer.service
import systems.ajax.malov.stockanalyzer.entity.Stock
interface StockClientApi {
fun getAllStocksData(): List<Stock>
}
| 1 | Kotlin | 0 | 0 | 2156a9dab427de7bd3d786db565634fb7796f38f | 173 | stockanalyzer | MIT License |
frogocovid19api/src/main/java/com/frogobox/frogocovid19api/data/model/Country.kt | amirisback | 247,946,214 | false | null | package com.frogobox.frogocovid19api.data.model
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME>
* FrogoBox Inc License
* =========================================
* Covid19Api
* Copyright (C) 18/03/2020.
* All rights reserved
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.frogocovid19api.data.model
*
*/
data class Country(
@SerializedName("Country")
var country : String? = null,
@SerializedName("Slug")
var slug : String? = null,
@SerializedName("Provinces")
var provinces : List<String>? = null
) | 0 | Kotlin | 1 | 9 | 60c03d42a517ba3d1cd5630aa47c12bb4a629cf6 | 778 | consumable-code-covid-19-api | Apache License 2.0 |
mobile-kotox-task/src/androidTest/kotlin/cz/kotox/task/list/TaskDetailScreenSmokeTest.kt | kotoMJ | 575,403,398 | false | null | package cz.kotox.task.list
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import cz.kotox.core.ui.theme.KotoxBasicTheme
import cz.kotox.domain.task.api.factory.toTask
import cz.kotox.domain.task.impl.remote.dto.TaskDTO
import cz.kotox.task.detail.ui.TaskDetailActivity
import cz.kotox.task.detail.ui.TaskDetailScreen
import cz.kotox.task.detail.ui.TaskDetailScreenInput
import cz.kotox.task.detail.ui.UI_TEST_DOWNLOAD_BUTTON_TAG
import cz.kotox.task.detail.ui.component.TaskSummaryItem
import org.junit.Rule
import org.junit.Test
class TaskDetailScreenSmokeTest {
@get:Rule(order = 1)
val detailTaskActivityTestRule = createAndroidComposeRule<TaskDetailActivity>()
@Test
fun detailScreenSmokeTest() {
detailTaskActivityTestRule.setContent {
KotoxBasicTheme {
TaskDetailScreen(input = TaskDetailScreenInput(
TaskSummaryItem.from(
TaskDTO(
creationDate = "2016-04-23T18:25:43.511Z",
dueDate = "2017-01-23T18:00:00.511Z",
encryptedDescription = "<KEY>
encryptedTitle = "SW4gcHJvZ3Jlc3MgYW5kIHRoZSByZXN1bHQKCg==",
id = "1",
encryptedImage = "<KEY>"
).toTask()
),
), onEventHandler = {
})
}
}
detailTaskActivityTestRule.onNodeWithTag(UI_TEST_DOWNLOAD_BUTTON_TAG).assertExists()
}
} | 0 | Kotlin | 0 | 0 | 7784a52ae5d9ee8bacb51ca7f32e1d7ebda582fa | 1,621 | kotox-android | MIT License |
data/src/main/kotlin/io/mateam/playground2/data/utils/TimeUtils.kt | AndZp | 198,453,114 | false | null | package mobi.mateam.core.utils
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.max
private val timeConverter = TimeConverter()
/***** Long Extensions *****/
fun Long.toEventListDate(): String {
return timeConverter.toDate(this)
}
fun Long.toTopMomentListDate(): String {
return timeConverter.toDateWithYear(this)
}
fun Long.toEventListTime(): String {
return timeConverter.toTime(this)
}
fun Long.toHumanReadableTime(withDate: Boolean = false): String {
return timeConverter.toHumanDate(this, withDate)
}
fun Long.toMinutesSecondsForm(leadingZero: Boolean = true): String {
val minutes = max(TimeUnit.SECONDS.toMinutes(this).toInt(), 0)
val seconds = max((this - TimeUnit.MINUTES.toSeconds(minutes.toLong())).toInt(), 0)
val stringFormat = if (leadingZero) "%02d:%02d" else "%d:%02d"
return String.format(Locale.getDefault(), stringFormat, minutes, seconds)
}
fun Long.toHoursMinutesSecondsForm(): String {
val hours = TimeUnit.SECONDS.toHours(this)
val minutes = TimeUnit.SECONDS.toMinutes(this - TimeUnit.HOURS.toSeconds(hours))
val seconds = this - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minutes)
return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds)
}
object TimeUtils {
private val msSimpleDateFormat: SimpleDateFormat = SimpleDateFormat.getDateTimeInstance() as SimpleDateFormat
fun currentTrueTimeInMilliseconds(): Long {
return System.currentTimeMillis()
}
fun periodTimeLeft(timeLeft: Long): String {
msSimpleDateFormat.applyPattern(TimePattern.M_SS.timeFormat)
return msSimpleDateFormat.format(Date(timeLeft))
}
fun getTimeUntil(time: Long): Long {
return time - currentTrueTimeInMilliseconds()
}
fun eventTimeLog(time: Long): String {
val simpleDateFormat = SimpleDateFormat("HH:mm:ss:SSS dd/MM/yyyy", Locale.getDefault())
return try {
simpleDateFormat.format(Date(time))
} catch (e: Exception) {
Date(time).toString()
}
}
fun momentMatchDate(time: Long): String {
val simpleDateFormat = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
return try {
simpleDateFormat.format(Date(time))
} catch (e: Exception) {
Date(time).toString()
}
}
enum class TimePattern(val timeFormat: String) {
/**
* Tue, 18:07, Jul 11
*/
EEE_HH_MM_MMM_DD("EEE, HH:mm, MMM dd"),
/**
* Tue, 6:07 pm, Jul 11
*/
EEE_HH_MM_A_MMM_DD("EEE, h:mm a, MMM dd"),
/**
* 11 Jul 2017 18:07
*/
DD_MMM_YYYY_HH_MM("dd MMM yyyy HH:mm"),
/**
* 11 Jul 2017 6:07 pm
*/
DD_MMM_YYYY_HH_MM_A("dd MMM yyyy h:mm a"),
/**
* 11 Jul, 18:07
*/
DD_MMM_HH_MM("dd MMM, HH:mm"),
/**
* 11 Jul, 6:07 pm
*/
DD_MMM_HH_MM_A("dd MMM, h:mm a"),
/**
* 18:07
*/
HH_MM_24_HOURS_FORMAT("HH:mm"),
/**
* 18:07:100
*/
HH_MM_SS_SSS("HH:mm:ss:SSS"),
/**
* 6:07AM
*/
HH_MM_12_HOURS_FORMAT("h:mmaa"),
/**
* Jul 11
*/
MMM_DD("MMM dd"),
/**
* Tue, Jul 11
*/
EEE_MMM_DD("EEE, MMM dd"),
/**
* 11/07
*/
DD_MM("dd/MM"),
/**
* Tue
*/
EEE("EEE"),
/**
* Jul
*/
MMM("MMM"),
/**
* 11/07/2017
*/
HH_MM_SS("dd/MM/yyyy"),
/**
* 04:08:59
*/
DD_MM_YYYY("hh:mm:ss"),
/**
* 08:59
*/
MM_SS("mm:ss"),
/**
* 8:59
*/
M_SS("m:ss")
}
}
class TimeConverter
{
fun toDate(time: Long): String
{
val sdf = SimpleDateFormat("dd MMM", Locale.getDefault())
return sdf.format(time)
}
fun toDateWithYear(time: Long): String
{
val sdf = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
return sdf.format(time)
}
fun toTime(time: Long): String
{
val sdf = SimpleDateFormat("h:mm a", Locale.getDefault())
return sdf.format(time)
}
fun toHumanDate(time: Long, withDate: Boolean = false): String
{
val dateFormat = "dd/MM/yyyy - "
val timeFormat = "HH:mm:ss:SSS"
val format: String = if (withDate) dateFormat + timeFormat else timeFormat
val sdf = SimpleDateFormat(format, Locale.getDefault())
return sdf.format(time)
}
} | 0 | Kotlin | 2 | 1 | e369ce8d2c65e1ba3915ebfea060bf6efdc1e9b9 | 4,774 | Clean-MVVM-Coroutines | Do What The F*ck You Want To Public License |
app/src/main/java/io/codetail/airplanes/ext/DataBindingExt.kt | ozodrukh | 92,581,070 | false | null | package io.codetail.airplanes.ext
/**
* created at 5/21/17
* @author Ozodrukh
* *
* @version 1.0
*/
| 0 | Kotlin | 0 | 4 | 04efe58ca4cc7225ddec9d1c38e113e08d5b2a71 | 107 | Tours-App | MIT License |
app/src/main/java/ch/ralena/natibo/data/room/PackRepository.kt | chickendude | 125,679,771 | false | null | package ch.ralena.natibo.data.room
import ch.ralena.natibo.data.room.`object`.PackRoom
import ch.ralena.natibo.data.room.dao.PackDao
import javax.inject.Inject
class PackRepository @Inject constructor(
private val packDao: PackDao
) {
suspend fun createPack(pack: PackRoom) = packDao.insert(pack)
suspend fun fetchPack(id: Long) = packDao.getById(id)
suspend fun fetchPackByName(name: String) =
packDao.getByName(name)
suspend fun fetchPackWithSentences(id: Long) = packDao.getWithSentencesById(id)
suspend fun fetchPacks(): List<PackRoom> =
packDao.getAll()
} | 18 | Kotlin | 3 | 24 | a409b4642e32a52921da77641899fb5ffdf8e6fb | 576 | Natibo | The Unlicense |
compose-desktop-toolbox/src/main/kotlin/com/alexfacciorusso/composedesktoptoolbox/BindWindowMinimumSizeModifier.kt | alexfacciorusso | 696,162,634 | false | {"Kotlin": 2275} | package com.alexfacciorusso.composedesktoptoolbox
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.WindowScope
import java.awt.Dimension
@ExperimentalComposeDesktopToolboxApi
fun Modifier.bindWindowMinimumSize(windowScope: WindowScope) = composed {
with(windowScope) {
val localDensity = LocalDensity.current
var updated by remember { mutableIntStateOf(0) }
DisposableEffect(updated, localDensity) {
window.preferredSize = null
val calculatedPreferredSize = window.preferredSize
with(localDensity) {
window.minimumSize =
Dimension(
calculatedPreferredSize.width.dp.roundToPx(),
calculatedPreferredSize.height.dp.roundToPx()
)
}
onDispose {
window.minimumSize = Dimension()
}
}
onSizeChanged {
if (updated == Int.MAX_VALUE) {
updated = 0
return@onSizeChanged
}
updated++
}
}
} | 0 | Kotlin | 0 | 0 | bb2f4ca8fa071a046795e564e3d7b61d4c2cbc86 | 1,321 | compose-desktop-toolbox | MIT License |
src/main/kotlin/dev/crashteam/uzumanalytics/client/uzum/model/proxy/ProxyRequestBody.kt | crashteamdev | 647,366,680 | false | {"Kotlin": 76909} | package dev.crashteam.kazanexpressfetcher.client.model
data class ProxyRequestBody(
val url: String,
val httpMethod: String,
val context: List<ProxyRequestContext>? = null,
)
data class ProxyRequestContext(
val key: String,
val value: Any
)
| 3 | Kotlin | 0 | 0 | 9553df4fd2bed15c5c86b2ed80da05862a958756 | 263 | uzum-analytics | Apache License 2.0 |
account-repo/src/main/java/com/skullper/account_repo/AccountRepository.kt | Skullper | 507,640,394 | false | null | package com.skullper.account_repo
import com.skullper.account_repo.data.AccountInfo
import com.skullper.account_repo.data.LegendInfo
import com.skullper.account_repo.data.PlatformType
import com.skullper.account_repo.data.mapTo
import com.skullper.account_repo.db.AccountDao
import com.skullper.account_repo.db.AccountStorage
import com.skullper.mozambique_api.MozambiqueApiHelper
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
class AccountRepository internal constructor(
private val api: MozambiqueApiHelper,
private val accountDao: AccountDao,
private val accountStorage: AccountStorage,
private val dispatcher: CoroutineDispatcher,
) {
/**
* @param playerName of the request player. If [PlatformType.PC] selected must be an Origin ID
* @param platform where player was created
*
* @return all available information about player
*/
suspend fun getAccountInfo(
playerName: String,
platform: PlatformType = PlatformType.PC
): AccountInfo = withContext(dispatcher) {
val account = api.getAccount(playerName, platform.mapTo())
accountStorage.storeAccount(account)
accountDao.getAccount(account.global.uid)
}
/**
* @return only the last cached account information
*/
suspend fun getCachedAccountInfo(): AccountInfo = accountDao.getLastCachedAccount()
/**
* @return all cached legends
*/
suspend fun getLegendsInfo(): List<LegendInfo> = withContext(dispatcher) {
accountDao.getLegends()
}
}
| 0 | Kotlin | 0 | 0 | 4ca2d5277fbc953994044da753d6b51a590d40bd | 1,576 | ApexLegendsMateApp | Apache License 2.0 |
app/src/main/java/com/kotlin/mvvm/boilerplate/ui/main/home/TrackModule.kt | kanwalNayyer | 520,274,229 | false | {"Kotlin": 36488} | package com.kotlin.mvvm.boilerplate.ui.main.home
import com.kotlin.mvvm.boilerplate.di.FragmentScoped
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* Created by cuongpm on 11/29/18.
*/
@Module
abstract class TrackModule {
@FragmentScoped
@ContributesAndroidInjector
abstract fun bindTrackFragment(): TrackFragment
} | 0 | Kotlin | 0 | 0 | a72bfdbf6f427c94c3084d8e5c023e6ce8bcd932 | 361 | skoovin | MIT License |
next/kmp/helper/src/androidMain/kotlin/org/dweb_browser/helper/SharePreferenceUtil.kt | BioforestChain | 594,577,896 | false | {"Kotlin": 3364898, "TypeScript": 796189, "Swift": 368692, "Vue": 155144, "SCSS": 39016, "Objective-C": 17350, "HTML": 16888, "Shell": 13534, "JavaScript": 4687, "Svelte": 3504, "CSS": 818} | package org.dweb_browser.helper
import android.content.Context
import androidx.core.content.edit
private const val SHARED_PREFERENCES_NAME = "DwebBrowser"
/// TODO 这里统一使用 NativeMicroModule 替代 Context
fun Context.saveString(key: String, value: String) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { putString(key, value) }
}
fun Context.getString(key: String, default: String = ""): String {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
return sp.getString(key, default) ?: ""
}
fun Context.saveInteger(key: String, value: Int) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { putInt(key, value) }
}
fun Context.getInteger(key: String, default: Int = 0): Int {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
return sp.getInt(key, default)
}
fun Context.saveBoolean(key: String, value: Boolean) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { putBoolean(key, value) }
}
fun Context.getBoolean(key: String, default: Boolean = false): Boolean {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
return sp.getBoolean(key, default)
}
fun Context.saveStringSet(key: String, value: Set<String>) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { putStringSet(key, value) }
}
fun Context.saveList(key: String, value: List<String>) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { putStringSet(key, value.toSet()) }
}
fun Context.getList(key: String): MutableList<String>? {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
return getStringSet(key)?.toMutableList()
}
fun Context.getStringSet(key: String, default: Set<String>? = null): Set<String>? {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
return sp.getStringSet(key, default)
}
fun Context.removeKey(key: String) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit { remove(key) }
}
fun Context.removeKeys(keys: List<String>) {
val sp = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
sp.edit {
keys.forEach {
remove(it)
}
}
}
| 59 | Kotlin | 4 | 13 | 57738069a4fbf3fc11ff64b527934698c32fecd9 | 2,359 | dweb_browser | MIT License |
api/src/main/kotlin/io/github/wulkanowy/api/messages/SentMessage.kt | wulkanowy | 145,134,008 | false | null | package io.github.wulkanowy.sdk.scrapper.messages
import com.google.gson.annotations.SerializedName
data class SentMessage(
@SerializedName("Adresaci")
val recipients: List<Recipient>,
@SerializedName("Temat")
val subject: String,
@SerializedName("Tresc")
val content: String,
@SerializedName("Nadawca")
val sender: Sender,
@SerializedName("WiadomoscPowitalna")
val isWelcomeMessage: Boolean,
@SerializedName("Id")
val id: Int
)
| 0 | null | 1 | 12 | 3e8cdb8a27cdfcd734000d54c946f4b4e2002794 | 485 | api | Apache License 2.0 |
app/src/main/java/org/oppia/android/app/testing/NavigationDrawerTestActivity.kt | oppia | 148,093,817 | false | {"Kotlin": 13302271, "Starlark": 693163, "Java": 34760, "Shell": 18872} | package org.oppia.android.app.testing
import android.content.Context
import android.content.Intent
import android.os.Bundle
import org.oppia.android.R
import org.oppia.android.app.activity.ActivityComponentImpl
import org.oppia.android.app.activity.InjectableAutoLocalizedAppCompatActivity
import org.oppia.android.app.activity.route.ActivityRouter
import org.oppia.android.app.home.HomeActivityPresenter
import org.oppia.android.app.home.RouteToRecentlyPlayedListener
import org.oppia.android.app.home.RouteToTopicListener
import org.oppia.android.app.home.RouteToTopicPlayStoryListener
import org.oppia.android.app.model.DestinationScreen
import org.oppia.android.app.model.ProfileId
import org.oppia.android.app.model.RecentlyPlayedActivityParams
import org.oppia.android.app.model.RecentlyPlayedActivityTitle
import org.oppia.android.app.topic.TopicActivity
import org.oppia.android.app.translation.AppLanguageResourceHandler
import org.oppia.android.util.profile.CurrentUserProfileIdIntentDecorator.decorateWithUserProfileId
import org.oppia.android.util.profile.CurrentUserProfileIdIntentDecorator.extractCurrentUserProfileId
import javax.inject.Inject
class NavigationDrawerTestActivity :
InjectableAutoLocalizedAppCompatActivity(),
RouteToTopicListener,
RouteToTopicPlayStoryListener,
RouteToRecentlyPlayedListener {
@Inject
lateinit var homeActivityPresenter: HomeActivityPresenter
@Inject
lateinit var resourceHandler: AppLanguageResourceHandler
@Inject
lateinit var activityRouter: ActivityRouter
private var internalProfileId: Int = -1
companion object {
fun createNavigationDrawerTestActivity(context: Context, internalProfileId: Int?): Intent {
val intent = Intent(context, NavigationDrawerTestActivity::class.java)
val profileId = internalProfileId?.let { ProfileId.newBuilder().setInternalId(it).build() }
if (profileId != null) {
intent.decorateWithUserProfileId(profileId)
}
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activityComponent as ActivityComponentImpl).inject(this)
internalProfileId = intent?.extractCurrentUserProfileId()?.internalId ?: -1
homeActivityPresenter.handleOnCreate(internalProfileId)
title = resourceHandler.getStringInLocale(R.string.home_activity_title)
}
override fun onRestart() {
super.onRestart()
homeActivityPresenter.handleOnRestart()
}
override fun routeToTopic(internalProfileId: Int, classroomId: String, topicId: String) {
startActivity(
TopicActivity.createTopicActivityIntent(this, internalProfileId, classroomId, topicId)
)
}
override fun routeToTopicPlayStory(
internalProfileId: Int,
classroomId: String,
topicId: String,
storyId: String
) {
startActivity(
TopicActivity.createTopicPlayStoryActivityIntent(
this,
internalProfileId,
classroomId,
topicId,
storyId
)
)
}
override fun routeToRecentlyPlayed(recentlyPlayedActivityTitle: RecentlyPlayedActivityTitle) {
val recentlyPlayedActivityParams =
RecentlyPlayedActivityParams
.newBuilder()
.setProfileId(ProfileId.newBuilder().setInternalId(internalProfileId).build())
.setActivityTitle(recentlyPlayedActivityTitle)
.build()
activityRouter.routeToScreen(
DestinationScreen
.newBuilder()
.setRecentlyPlayedActivityParams(recentlyPlayedActivityParams)
.build()
)
}
}
| 487 | Kotlin | 517 | 315 | 95699f922321f49a3503783187a14ad1cef0d5d3 | 3,542 | oppia-android | Apache License 2.0 |
shared/src/commonMain/kotlin/App.kt | dima-avdeev-jb | 708,933,038 | false | {"Kotlin": 2228, "Swift": 580, "Shell": 228} | import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
@Composable
fun App() {
var text by remember { mutableStateOf("Focus to TextField and press backspace") }
var backSpaceCounter by remember { mutableStateOf(0) }
Column {
TextField(
modifier = Modifier
.fillMaxWidth()
.onPreviewKeyEvent { event ->
if (event.key == Key.Backspace) {
backSpaceCounter++
true
} else {
false
}
},
value = text,
onValueChange = {
text = it
}
)
Text("Backspace pressed $backSpaceCounter times")
}
}
| 0 | Kotlin | 0 | 0 | b0403708e7f8b14162aeb87f2432e0de850f181e | 1,283 | ios-simulator-preview-key-event-backspace | Apache License 2.0 |
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/history/HistoryRecordingDemoDescriptor.kt | Neckar-IT | 599,079,962 | false | null | /**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.demo.descriptors.history
import com.meistercharts.algorithms.TimeRange
import com.meistercharts.algorithms.ValueRange
import com.meistercharts.algorithms.impl.FittingWithMargin
import com.meistercharts.algorithms.layers.HistoryBucketsRangeDebugLayer
import com.meistercharts.algorithms.layers.HistoryUpdatesVisualizationLayer
import com.meistercharts.algorithms.layers.TilesLayer
import com.meistercharts.algorithms.layers.ValueAxisLayer
import com.meistercharts.algorithms.layers.addClearBackground
import com.meistercharts.algorithms.layers.addTimeAxis
import com.meistercharts.algorithms.layers.debug.CleanupServiceDebugLayer
import com.meistercharts.algorithms.layers.debug.DirtyRangesDebugLayer
import com.meistercharts.algorithms.layers.debug.ShowTimeRangeLayer
import com.meistercharts.algorithms.layers.linechart.LineStyle
import com.meistercharts.algorithms.painter.Color
import com.meistercharts.algorithms.painter.DirectLineLivePainter
import com.meistercharts.algorithms.painter.DirectLinePainter
import com.meistercharts.algorithms.tile.AverageHistoryCanvasTilePainter
import com.meistercharts.algorithms.tile.CanvasTileProvider
import com.meistercharts.algorithms.tile.CountingTileProvider
import com.meistercharts.algorithms.tile.DefaultHistoryTileInvalidator
import com.meistercharts.algorithms.tile.HistoryGapCalculator
import com.meistercharts.algorithms.tile.HistoryRenderPropertiesCalculatorLayer
import com.meistercharts.algorithms.tile.HistoryTileInvalidator
import com.meistercharts.algorithms.tile.MaxDistanceSamplingPeriodCalculator
import com.meistercharts.algorithms.tile.SamplingPeriodCalculator
import com.meistercharts.algorithms.tile.cached
import com.meistercharts.algorithms.tile.canvasTiles
import com.meistercharts.algorithms.tile.withMinimum
import com.meistercharts.annotations.PhysicalPixel
import com.meistercharts.canvas.translateOverTime
import com.meistercharts.demo.ChartingDemo
import com.meistercharts.demo.ChartingDemoDescriptor
import com.meistercharts.demo.DemoCategory
import com.meistercharts.demo.PredefinedConfiguration
import com.meistercharts.demo.configurableBoolean
import com.meistercharts.demo.configurableDouble
import com.meistercharts.demo.configurableInt
import com.meistercharts.demo.section
import com.meistercharts.history.DecimalDataSeriesIndexProvider
import com.meistercharts.history.InMemoryHistoryStorage
import com.meistercharts.history.SamplingPeriod
import com.meistercharts.history.cleanup.MaxHistorySizeConfiguration
import com.meistercharts.history.downsampling.DownSamplingDirtyRangesCollector
import com.meistercharts.history.downsampling.DownSamplingService
import com.meistercharts.history.downsampling.observe
import com.meistercharts.history.generator.DecimalValueGenerator
import com.meistercharts.history.generator.HistoryChunkGenerator
import com.meistercharts.history.generator.offset
import com.meistercharts.model.Insets
import com.meistercharts.model.Size
import it.neckar.open.kotlin.lang.fastMap
import it.neckar.open.provider.MultiProvider
import it.neckar.open.observable.ObservableBoolean
import kotlin.time.Duration.Companion.milliseconds
import it.neckar.open.time.repeat
data class HistoryRecordingDemoConfig(
val recordingSamplingPeriod: SamplingPeriod = SamplingPeriod.EveryHundredMillis,
val dataSeriesCount: Int = 3,
) {
override fun toString(): String {
return "${recordingSamplingPeriod.label} - $dataSeriesCount"
}
}
/**
*
*/
class HistoryRecordingDemoDescriptor : ChartingDemoDescriptor<HistoryRecordingDemoConfig> {
override val name: String = "History Recording"
override val category: DemoCategory
get() = DemoCategory.Calculations
override val predefinedConfigurations: List<PredefinedConfiguration<HistoryRecordingDemoConfig>> = listOf(
PredefinedConfiguration(HistoryRecordingDemoConfig(SamplingPeriod.EveryHundredMillis, 3)),
PredefinedConfiguration(HistoryRecordingDemoConfig(SamplingPeriod.EveryHundredMillis, 100)),
PredefinedConfiguration(HistoryRecordingDemoConfig(SamplingPeriod.EveryMillisecond, 3)),
)
override fun createDemo(configuration: PredefinedConfiguration<HistoryRecordingDemoConfig>?): ChartingDemo {
require(configuration != null)
val recordingSamplingPeriod: SamplingPeriod = configuration.payload.recordingSamplingPeriod
val dataSeriesCount = configuration.payload.dataSeriesCount
return ChartingDemo {
meistercharts {
configureAsTimeChart()
configureAsTiledTimeChart()
zoomAndTranslationDefaults {
FittingWithMargin(Insets.of(50.0))
}
val historyStorage = InMemoryHistoryStorage().also {
it.naturalSamplingPeriod = recordingSamplingPeriod
it.maxSizeConfiguration = MaxHistorySizeConfiguration(7)
it.scheduleCleanupService()
onDispose(it)
}
val visibleDataSeriesIndices = DecimalDataSeriesIndexProvider.indices { dataSeriesCount }
val valueRangeStart = 0.0
val valueRangeEnd = 100.0
val valueRange = ValueRange.linear(valueRangeStart, valueRangeEnd)
val valueRanges = dataSeriesCount.fastMap { valueRange }
val distance = valueRange.delta * 0.8 / dataSeriesCount
val offset = valueRange.center() - dataSeriesCount * 0.5 * distance
val decimalValueGenerators = dataSeriesCount.fastMap {
DecimalValueGenerator.normality(valueRanges[it], valueRanges[it].delta * 0.05)
.offset(offset + it * distance)
}
val historyChunkGenerator = HistoryChunkGenerator(historyStorage = historyStorage, samplingPeriod = recordingSamplingPeriod, decimalValueGenerators = decimalValueGenerators, enumValueGenerators = emptyList(), referenceEntryGenerators = emptyList())
val contentAreaTimeRange = TimeRange.oneMinuteUntilNow()
//Collects the time ranges that will be down sampled
val downSamplingDirtyRangesCollector = DownSamplingDirtyRangesCollector()
downSamplingDirtyRangesCollector.observe(historyStorage)
val downSamplingService = DownSamplingService(historyStorage)
.also { onDispose(it) }
downSamplingService.scheduleDownSampling(downSamplingDirtyRangesCollector)
//Provides the manually configured sampling period
val samplingPeriodCalculator: SamplingPeriodCalculator = MaxDistanceSamplingPeriodCalculator().withMinimum(recordingSamplingPeriod)
val historyGapCalculator = object : HistoryGapCalculator {
var factor: Double = 3.0
override fun calculateMinGapDistance(renderedSamplingPeriod: SamplingPeriod): Double {
return renderedSamplingPeriod.distance * factor
}
}
val tilePainter = AverageHistoryCanvasTilePainter(
AverageHistoryCanvasTilePainter.Configuration(
historyStorage,
{ contentAreaTimeRange },
MultiProvider { valueRange },
{ visibleDataSeriesIndices },
MultiProvider.always(LineStyle(Color.red, 1.0, null)),
MultiProvider.always(DirectLinePainter(snapXValues = false, snapYValues = false))
)
)
@PhysicalPixel val physicalTileSize = Size.of(400.0, 400.0)
val canvasTileProvider = CanvasTileProvider(physicalTileSize, tilePainter)
val countingTileProvider = CountingTileProvider(canvasTileProvider)
val cachedTileProvider = countingTileProvider.cached(chartId)
configure {
chartSupport.rootChartState.contentAreaSizeProperty.consume {
cachedTileProvider.clear()
}
chartSupport.rootChartState.axisOrientationXProperty.consume {
cachedTileProvider.clear()
}
chartSupport.rootChartState.axisOrientationYProperty.consume {
cachedTileProvider.clear()
}
layers.addClearBackground()
val tilesCountOverlayVisible = ObservableBoolean(true)
layers.addLayer(HistoryRenderPropertiesCalculatorLayer(samplingPeriodCalculator, historyGapCalculator) { contentAreaTimeRange })
layers.addLayer(TilesLayer(cachedTileProvider))
layers.addLayer(ShowTimeRangeLayer(contentAreaTimeRange))
layers.addLayer(HistoryBucketsRangeDebugLayer(contentAreaTimeRange, samplingPeriodCalculator))
layers.addLayer(DirtyRangesDebugLayer(downSamplingDirtyRangesCollector, contentAreaTimeRange))
layers.addLayer(CleanupServiceDebugLayer(historyStorage, contentAreaTimeRange))
layers.addLayer(ValueAxisLayer("Sin", valueRange))
layers.addTimeAxis(contentAreaTimeRange)
val historyUpdateVisualizationLayer = HistoryUpdatesVisualizationLayer(contentAreaTimeRange)
layers.addLayer(historyUpdateVisualizationLayer)
val tileInvalidator: HistoryTileInvalidator = DefaultHistoryTileInvalidator()
historyStorage.observe { _, updateInfo ->
historyUpdateVisualizationLayer.lastUpdateInfo = updateInfo
tileInvalidator.historyHasBeenUpdated(updateInfo, cachedTileProvider.canvasTiles(), chartSupport)
[email protected]()
}
section("Visualization")
chartSupport.translateOverTime.contentAreaTimeRangeX = contentAreaTimeRange
configurableBoolean("Play", chartSupport.translateOverTime.animatedProperty)
configurableBoolean("Tiles Age", tilesCountOverlayVisible)
configurableDouble("Gap Factor", historyGapCalculator::factor) {
max = 100.0
}
section("Data")
declare {
button("Clear cache") {
cachedTileProvider.clear()
[email protected]()
}
button("Add 1 data point now") {
historyChunkGenerator.forNow()?.let {
historyStorage.storeWithoutCache(it, recordingSamplingPeriod)
}
}
val recordingActive = ObservableBoolean(true)
checkBox("Recording", recordingActive)
repeat(recordingSamplingPeriod.distance.milliseconds) {
if (recordingActive.value) {
historyChunkGenerator.next()?.let {
historyStorage.storeWithoutCache(it, recordingSamplingPeriod)
}
}
}.also {
chartSupport.onDispose(it)
}
}
configurableInt("History length (keptBucketsCount)") {
max = 200
min = 1
value = historyStorage.maxSizeConfiguration.keptBucketsCount
onChange {
historyStorage.maxSizeConfiguration = MaxHistorySizeConfiguration(it)
markAsDirty()
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 4 | af73f0e09e3e7ac9437240e19974d0b1ebc2f93c | 11,447 | meistercharts | Apache License 2.0 |
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/EffectInlayPresentation.kt | rmfish | 194,981,579 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.paint.EffectPainter
import java.awt.Font
import java.awt.Graphics2D
/**
* Adds effects to the underlying text
*/
class EffectInlayPresentation(
presentation: InlayPresentation,
var font: Font?, // null means current
var lineHeight: Int,
var ascent: Int,
var descent: Int
) : StaticDelegatePresentation(presentation) {
override fun paint(g: Graphics2D, attributes: TextAttributes) {
presentation.paint(g, attributes)
val effectColor = attributes.effectColor
if (effectColor != null) {
g.color = effectColor
when (attributes.effectType) {
EffectType.LINE_UNDERSCORE -> EffectPainter.LINE_UNDERSCORE.paint(g, 0, ascent, width, descent, font)
EffectType.BOLD_LINE_UNDERSCORE -> EffectPainter.BOLD_LINE_UNDERSCORE.paint(g, 0, ascent, width, descent, font)
EffectType.STRIKEOUT -> EffectPainter.STRIKE_THROUGH.paint(g, 0, ascent, width, height, font)
EffectType.WAVE_UNDERSCORE -> EffectPainter.WAVE_UNDERSCORE.paint(g, 0, ascent, width, descent, font)
EffectType.BOLD_DOTTED_LINE -> EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(g, 0, ascent, width, descent, font)
else -> {}
}
}
}
} | 1 | null | 1 | 1 | f8c2935227c5fa77e6dbd301ffa84d9278929eaf | 1,501 | intellij-community | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/ui/presencetracing/organizer/details/QrCodeDetailFragment.kt | agigleux-limited | 368,849,842 | true | {"Kotlin": 4353686, "HTML": 305965, "Java": 11137, "Shell": 1232} | package de.rki.coronawarnapp.ui.presencetracing.organizer.details
import android.os.Bundle
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.widget.LinearLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.transition.MaterialContainerTransform
import com.google.android.material.transition.MaterialSharedAxis
import de.rki.coronawarnapp.R
import de.rki.coronawarnapp.databinding.TraceLocationOrganizerQrCodeDetailFragmentBinding
import de.rki.coronawarnapp.util.ContextExtensions.getDrawableCompat
import de.rki.coronawarnapp.util.di.AutoInject
import de.rki.coronawarnapp.util.ui.doNavigate
import de.rki.coronawarnapp.util.ui.observe2
import de.rki.coronawarnapp.util.ui.popBackStack
import de.rki.coronawarnapp.util.ui.viewBindingLazy
import de.rki.coronawarnapp.util.viewmodel.CWAViewModelFactoryProvider
import de.rki.coronawarnapp.util.viewmodel.cwaViewModelsAssisted
import javax.inject.Inject
import kotlin.math.abs
class QrCodeDetailFragment : Fragment(R.layout.trace_location_organizer_qr_code_detail_fragment), AutoInject {
@Inject lateinit var viewModelFactory: CWAViewModelFactoryProvider.Factory
private val navArgs by navArgs<QrCodeDetailFragmentArgs>()
private val viewModel: QrCodeDetailViewModel by cwaViewModelsAssisted(
factoryProducer = { viewModelFactory },
constructorCall = { factory, _ ->
factory as QrCodeDetailViewModel.Factory
factory.create(navArgs.traceLocationId)
}
)
private val binding: TraceLocationOrganizerQrCodeDetailFragmentBinding by viewBindingLazy()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedElementEnterTransition = MaterialContainerTransform()
sharedElementReturnTransition = MaterialContainerTransform()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setToolbarOverlay()
binding.apply {
appBarLayout.addOnOffsetChangedListener(
OnOffsetChangedListener { appBarLayout, verticalOffset ->
title.alpha = (
1.0f - abs(verticalOffset / (appBarLayout.totalScrollRange.toFloat() * 0.5f))
)
subtitle.alpha = (
1.0f - abs(verticalOffset / (appBarLayout.totalScrollRange.toFloat() * 0.7f))
)
}
)
toolbar.apply {
navigationIcon = context.getDrawableCompat(R.drawable.ic_close_white)
navigationContentDescription = getString(R.string.accessibility_close)
setNavigationOnClickListener { viewModel.onBackButtonPress() }
}
qrCodePrintButton.setOnClickListener {
exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true)
reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false)
viewModel.onPrintQrCode()
}
qrCodeCloneButton.setOnClickListener {
viewModel.duplicateTraceLocation()
}
root.transitionName = navArgs.traceLocationId.toString()
}
viewModel.routeToScreen.observe2(this) {
when (it) {
QrCodeDetailNavigationEvents.NavigateBack -> popBackStack()
is QrCodeDetailNavigationEvents.NavigateToDuplicateFragment -> doNavigate(
QrCodeDetailFragmentDirections.actionQrCodeDetailFragmentToTraceLocationCreateFragment(
it.category,
it.traceLocation
)
)
is QrCodeDetailNavigationEvents.NavigateToQrCodePosterFragment -> doNavigate(
QrCodeDetailFragmentDirections.actionQrCodeDetailFragmentToQrCodePosterFragment(it.locationId)
)
}
}
viewModel.uiState.observe2(this) { uiState ->
with(binding) {
title.text = uiState.description
subtitle.text = uiState.address
if (uiState.startDateTime != null && uiState.endDateTime != null) {
val startTime = uiState.startDateTime!!.toDateTime()
val endTime = uiState.endDateTime!!.toDateTime()
eventDate.isGone = false
eventDate.text = if (startTime.toLocalDate() == endTime.toLocalDate()) {
requireContext().getString(
R.string.trace_location_organizer_detail_item_duration,
startTime.toLocalDate().toString("dd.MM.yyyy"),
startTime.toLocalTime().toString("HH:mm"),
endTime.toLocalTime().toString("HH:mm")
)
} else {
requireContext().getString(
R.string.trace_location_organizer_detail_item_duration_multiple_days,
startTime.toLocalDate().toString("dd.MM.yyyy"),
startTime.toLocalTime().toString("HH:mm"),
endTime.toLocalDate().toString("dd.MM.yyyy"),
endTime.toLocalTime().toString("HH:mm")
)
}
} else {
eventDate.isGone = true
}
uiState.bitmap?.let {
binding.progressBar.hide()
binding.qrCodeImage.apply {
val resourceId = RoundedBitmapDrawableFactory.create(resources, it)
resourceId.cornerRadius = 15f
setImageDrawable(resourceId)
}
}
}
}
}
private fun setToolbarOverlay() {
val width = requireContext().resources.displayMetrics.widthPixels
val params: CoordinatorLayout.LayoutParams = binding.nestedScrollView.layoutParams
as (CoordinatorLayout.LayoutParams)
val textParams = binding.subtitle.layoutParams as (LinearLayout.LayoutParams)
textParams.bottomMargin = ((width) / 2) - 24 /* 24 is space between screen border and QrCode */
binding.subtitle.requestLayout() /* 24 is space between screen border and QrCode */
val behavior: AppBarLayout.ScrollingViewBehavior = params.behavior as ((AppBarLayout.ScrollingViewBehavior))
behavior.overlayTop = ((width) / 2) - 24
}
override fun onResume() {
super.onResume()
binding.contentContainer.sendAccessibilityEvent(AccessibilityEvent.TYPE_ANNOUNCEMENT)
}
}
| 0 | Kotlin | 1 | 0 | ee69ea77f5a010e21c94c14b230581cbd88dfb7e | 7,174 | cwa-app-android | Apache License 2.0 |
lib/src/main/java/com/vander/scaffold/annotations/ServiceScope.kt | vudangnt | 165,397,865 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "XML": 20, "Kotlin": 65, "Java": 1, "Proguard": 1} | package com.vander.scaffold.annotations
import javax.inject.Scope
/**
* @author marian on 20.9.2017.
*/
@Scope
annotation class ServiceScope | 1 | null | 3 | 1 | 7ecd4cabdc87f7b01928b4950298b73f85e91834 | 144 | scaffold | MIT License |
game-api/src/main/java/org/runestar/client/game/api/live/Widgets.kt | forsco | 135,697,131 | true | {"Kotlin": 1058154, "Java": 4007} | package org.runestar.client.game.api.live
import org.runestar.client.game.api.Widget
import org.runestar.client.game.api.WidgetParentId
import org.runestar.client.game.raw.Client
object Widgets {
val flat: Iterable<Widget> get() {
return WidgetGroups.asSequence().filterNotNull().flatMap { it.flat.asSequence() }.asIterable()
}
operator fun get(id: WidgetParentId): Widget.Parent? =
Client.accessor.widgets.getOrNull(id.group)?.getOrNull(id.parent)?.let { Widget.Parent(it) }
val roots: Iterable<Widget.Parent> get() = WidgetGroups.root?.roots ?: emptyList()
} | 0 | Kotlin | 0 | 0 | b15c07570af82377bcd2be48b00a5e9708be08ab | 601 | client | MIT License |
lawnchair/src/app/lawnchair/SearchBarInsetsHandler.kt | LawnchairLauncher | 83,799,439 | false | null | package app.lawnchair
import android.graphics.Insets
import android.os.Build
import android.view.WindowInsetsAnimationControlListener
import android.view.WindowInsetsAnimationController
import androidx.annotation.RequiresApi
import com.android.launcher3.anim.AnimatedFloat
@RequiresApi(Build.VERSION_CODES.R)
class SearchBarInsetsHandler(private val shiftRange: Float) : WindowInsetsAnimationControlListener {
val progress = AnimatedFloat(this::updateInsets)
private var animationController: WindowInsetsAnimationController? = null
override fun onReady(controller: WindowInsetsAnimationController, types: Int) {
animationController = controller
}
override fun onFinished(controller: WindowInsetsAnimationController) {
animationController = null
}
override fun onCancelled(controller: WindowInsetsAnimationController?) {
animationController = null
}
private fun updateInsets() {
val controller = animationController ?: return
val shownBottomInset = controller.shownStateInsets.bottom
val hiddenBottomInset = controller.hiddenStateInsets.bottom
val targetBottomInset = (shownBottomInset - progress.value * shiftRange).toInt()
val bottomInset = targetBottomInset.coerceIn(hiddenBottomInset, shownBottomInset)
controller.setInsetsAndAlpha(
Insets.of(0, 0, 0, bottomInset),
1f,
progress.value,
)
}
fun onAnimationEnd() {
animationController?.finish(progress.value < 0.5f)
}
}
| 388 | null | 1200 | 9,200 | d91399d2e4c6acbeef9c0704043f269115bb688b | 1,551 | lawnchair | Apache License 2.0 |
src/commonMain/kotlin/app/thelema/ui/Actor.kt | zeganstyl | 275,550,896 | false | null | /*
* Copyright 2020-2021 Anton Trushkov
*
* 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.thelema.ui
import app.thelema.math.*
import app.thelema.utils.Pool
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
/** 2D scene graph node. An actor has a position, rectangular size, origin, scale, rotation, Z index, and color. The position
* corresponds to the unrotated, unscaled bottom left corner of the actor. The position is relative to the actor's parent. The
* origin is relative to the position and is used for scale and rotation.
*
* An actor has two kinds of listeners associated with it: "capture" and regular. The listeners are notified of events the actor
* or its children receive. The regular listeners are designed to allow an actor to respond to events that have been delivered.
* The capture listeners are designed to allow a parent or container actor to handle events before child actors. See [fire]
* for more details.
*
*
* An [InputListener] can receive all the basic input events. More complex listeners (like [ClickListener] and
* [ActorGestureListener]) can listen for and combine primitive events and recognize complex interactions like multi-touch
* or pinch.
* @author mzechner, Nathan Sweet, zeganstyl
*/
open class Actor: IActor {
override var hud: HeadUpDisplay? = null
override var parent: Group? = null
val listeners: ArrayList<EventListener> = ArrayList(0)
val captureListeners: ArrayList<EventListener> = ArrayList(0)
/** Set the actor's name, which is used for identification convenience and by [toString].
* @see Group.findActor
*/
var name: String? = null
/** Determines how touch events are distributed to this actor. Default is [Touchable.Enabled]. */
var touchable = Touchable.Enabled
/** If false, the actor will not be drawn and will not receive touch events. Default is true. */
open var isVisible = true
/** Returns the X position of the actor's left edge. */
override var x = 0f
set(value) {
if (field != value) {
field = value
positionChanged()
}
}
/** Returns the Y position of the actor's bottom edge. */
override var y = 0f
set(value) {
if (field != value) {
field = value
positionChanged()
}
}
override val globalPosition: IVec2 = Vec2()
override var width = 0f
set(value) {
if (field != value) {
field = value
sizeChanged()
}
}
override var height = 0f
set(value) {
if (field != value) {
field = value
sizeChanged()
}
}
var originX = 0f
var originY = 0f
var scaleX = 1f
var scaleY = 1f
var rotation = 0f
set(value) {
if (field != value) {
field = value
rotationChanged()
}
}
open var color: Int = -1
/** Returns an application specific object for convenience, or null. */
/** Sets an application specific object for convenience. */
var userObject: Any? = null
val isTouchable
get() = touchable == Touchable.Enabled
/** Updates the actor based on time. Typically this is called each frame by [HeadUpDisplay.update]. */
open fun act(delta: Float) {}
/** Sets this actor as the event [target][Event.setTarget] and propagates the event to this actor and ancestor
* actors as necessary. If this actor is not in the stage, the stage must be set before calling this method.
*
*
* Events are fired in 2 phases:
*
* 1. The first phase (the "capture" phase) notifies listeners on each actor starting at the root and propagating downward to
* (and including) this actor.
* 1. The second phase notifies listeners on each actor starting at this actor and, if [Event.getBubbles] is true,
* propagating upward to the root.
*
* If the event is [stopped][Event.stop] at any time, it will not propagate to the next actor.
* @return true if the event was [cancelled][Event.cancel].
*/
fun fire(event: Event): Boolean {
if (event.headUpDisplay == null) event.headUpDisplay = hud
event.target = this
// Collect ancestors so event propagation is unaffected by hierarchy changes.
val ancestors: ArrayList<Group> = groupsArrayPool.get()
var parent = parent
while (parent != null) {
ancestors.add(parent)
parent = parent.parent
}
return try { // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it.
for (i in ancestors.size - 1 downTo 0) {
val currentTarget = ancestors[i]
currentTarget.notify(event, true)
if (event.isStopped) return event.isCancelled
}
// Notify the target capture listeners.
notify(event, true)
if (event.isStopped) return event.isCancelled
// Notify the target listeners.
notify(event, false)
if (!event.bubbles) return event.isCancelled
if (event.isStopped) return event.isCancelled
// Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it.
var i = 0
val n = ancestors.size
while (i < n) {
(ancestors[i]).notify(event, false)
if (event.isStopped) return event.isCancelled
i++
}
event.isCancelled
} finally {
ancestors.clear()
groupsArrayPool.free(ancestors)
}
}
/** Notifies this actor's listeners of the event. The event is not propagated to any parents. Before notifying the listeners,
* this actor is set as the [listener actor][Event.getListenerActor]. The event [target][Event.setTarget]
* must be set before calling this method. If this actor is not in the stage, the stage must be set before calling this method.
* @param capture If true, the capture listeners will be notified instead of the regular listeners.
* @return true of the event was [cancelled][Event.cancel].
*/
fun notify(event: Event, capture: Boolean): Boolean {
requireNotNull(event.target) { "The event target cannot be null." }
val listeners = if (capture) captureListeners else listeners
if (listeners.size == 0) return event.isCancelled
event.listenerActor = this
event.isCapture = capture
if (event.headUpDisplay == null) event.headUpDisplay = hud
try {
var i = 0
while (i < listeners.size) {
val listener = listeners[i]
if (listener.handle(event)) {
event.handle()
if (event.eventType == EventType.Input) {
event as InputEvent
if (event.type == InputEventType.touchDown) {
event.headUpDisplay?.addTouchFocus(listener, this, event.target, event.pointer, event.button)
}
}
}
i++
}
} catch (ex: RuntimeException) {
val context = toString()
throw RuntimeException("Actor: " + context.substring(0, min(context.length, 128)), ex)
}
return event.isCancelled
}
/** Returns the deepest [visible][isVisible] (and optionally, [touchable][getTouchable]) actor that contains
* the specified point, or null if no actor was hit. The point is specified in the actor's local coordinate system (0,0 is the
* bottom left of the actor and width,height is the upper right).
*
*
* This method is used to delegate touchDown, mouse, and enter/exit events. If this method returns null, those events will not
* occur on this Actor.
*
*
* The default implementation returns this actor if the point is within this actor's bounds and this actor is visible.
* @param touchable If true, hit detection will respect the [touchability][setTouchable].
* @see Touchable
*/
open fun hit(x: Float, y: Float, touchable: Boolean): Actor? {
if (touchable && this.touchable != Touchable.Enabled) return null
if (!isVisible) return null
//println("${this.javaClass.name}: ($x, $y) in (0 - $width, 0 - $height)")
return if (x >= 0 && x < width && y >= 0 && y < height) this else null
}
/** Removes this actor from its parent, if it has a parent.
* @see Group.removeActor
*/
open fun remove(): Boolean {
return if (parent != null) parent!!.removeActor(this, true) else false
}
/** Add a listener to receive events that [hit][hit] this actor. See [fire].
* @see InputListener
*
* @see ClickListener
*/
fun addListener(listener: EventListener): Boolean {
if (!listeners.contains(listener)) {
listeners.add(listener)
return true
}
return false
}
fun removeListener(listener: EventListener): Boolean {
return listeners.remove(listener)
}
/** Adds a listener that is only notified during the capture phase.
* @see .fire
*/
fun addCaptureListener(listener: EventListener): Boolean {
if (!captureListeners.contains(listener)) captureListeners.add(listener)
return true
}
fun removeCaptureListener(listener: EventListener): Boolean {
return captureListeners.remove(listener)
}
/** Removes all listeners on this actor. */
fun clearListeners() {
listeners.clear()
captureListeners.clear()
}
/** Removes all actions and listeners on this actor. */
open fun clear() {
clearListeners()
}
/** Returns true if this actor is the same as or is the descendant of the specified actor. */
fun isDescendantOf(actor: Actor): Boolean {
var parent: Actor? = this
do {
if (parent === actor) return true
parent = parent!!.parent
} while (parent != null)
return false
}
/** Returns true if this actor is the same as or is the ascendant of the specified actor. */
fun isAscendantOf(actor: Actor): Boolean {
var actor: Actor? = actor
do {
if (actor === this) return true
actor = actor?.parent
} while (actor != null)
return false
}
/** Returns true if this actor and all ancestors are visible. */
fun ancestorsVisible(): Boolean {
var actor: Actor? = this
do {
if (!actor!!.isVisible) return false
actor = actor.parent
} while (actor != null)
return true
}
/** Returns true if this actor is the [keyboard focus][HeadUpDisplay.getKeyboardFocus] actor. */
fun hasKeyboardFocus(): Boolean {
val stage = hud
return stage != null && stage.keyboardFocus === this
}
/** Returns true if this actor is the [scroll focus][HeadUpDisplay.getScrollFocus] actor. */
fun hasScrollFocus(): Boolean {
val stage = hud
return stage != null && stage.scrollFocus === this
}
/** Returns true if this actor is a target actor for touch focus.
* @see HeadUpDisplay.addTouchFocus
*/
val isTouchFocusTarget: Boolean
get() {
val stage = hud ?: return false
var i = 0
val n = stage.touchFocuses.size
while (i < n) {
if (stage.touchFocuses[i].target === this) return true
i++
}
return false
}
/** Returns true if this actor is a listener actor for touch focus.
* @see HeadUpDisplay.addTouchFocus
*/
val isTouchFocusListener: Boolean
get() {
val stage = hud ?: return false
var i = 0
val n = stage.touchFocuses.size
while (i < n) {
if (stage.touchFocuses[i].listenerActor === this) return true
i++
}
return false
}
open fun containsDeep(actor: Actor?): Boolean = false
/** Returns the X position of the specified [alignment][Align]. */
fun getX(alignment: Int): Float {
var x = x
if (alignment and Align.right != 0) x += width else if (alignment and Align.left == 0) //
x += width / 2
return x
}
/** Sets the x position using the specified [alignment][Align]. Note this may set the position to non-integer
* coordinates. */
fun setX(x: Float, alignment: Int) {
var x = x
if (alignment and Align.right != 0) x -= width else if (alignment and Align.left == 0) //
x -= width / 2
if (this.x != x) {
this.x = x
positionChanged()
}
}
/** Sets the y position using the specified [alignment][Align]. Note this may set the position to non-integer
* coordinates. */
fun setY(y: Float, alignment: Int) {
var y = y
if (alignment and Align.top != 0) y -= height else if (alignment and Align.bottom == 0) //
y -= height / 2
if (this.y != y) {
this.y = y
positionChanged()
}
}
/** Returns the Y position of the specified [alignment][Align]. */
fun getY(alignment: Int): Float {
var y = y
if (alignment and Align.top != 0) y += height else if (alignment and Align.bottom == 0) //
y += height / 2
return y
}
/** Sets the position of the actor's bottom left corner. */
fun setPosition(x: Float, y: Float): IActor {
if (this.x != x || this.y != y) {
this.x = x
this.y = y
positionChanged()
}
return this
}
/** Sets the position using the specified [alignment][Align]. Note this may set the position to non-integer
* coordinates. */
fun setPosition(x: Float, y: Float, alignment: Int) {
var x = x
var y = y
if (alignment and Align.right != 0) x -= width else if (alignment and Align.left == 0) //
x -= width * 0.5f
if (alignment and Align.top != 0) y -= height else if (alignment and Align.bottom == 0) //
y -= height * 0.5f
if (this.x != x || this.y != y) {
this.x = x
this.y = y
positionChanged()
}
}
/** Add x and y to current position */
fun moveBy(x: Float, y: Float) {
if (x != 0f || y != 0f) {
this.x += x
this.y += y
positionChanged()
}
}
/** Returns y plus height. */
val top: Float
get() = y + height
/** Returns x plus width. */
val right: Float
get() = x + width
/** Called when the actor's position has been changed. */
protected open fun positionChanged() {}
/** Called when the actor's size has been changed. */
protected open fun sizeChanged() {}
/** Called when the actor's rotation has been changed. */
protected fun rotationChanged() {}
/** Sets the width and height. */
fun setSize(width: Float, height: Float): IActor {
if (this.width != width || this.height != height) {
this.width = width
this.height = height
sizeChanged()
}
return this
}
/** Adds the specified size to the current size. */
fun sizeBy(size: Float) {
if (size != 0f) {
width += size
height += size
sizeChanged()
}
}
/** Adds the specified size to the current size. */
fun sizeBy(width: Float, height: Float) {
if (width != 0f || height != 0f) {
this.width += width
this.height += height
sizeChanged()
}
}
/** Set bounds the x, y, width, and height. */
open fun setBounds(x: Float, y: Float, width: Float, height: Float) {
if (this.x != x || this.y != y) {
this.x = x
this.y = y
positionChanged()
}
if (this.width != width || this.height != height) {
this.width = width
this.height = height
sizeChanged()
}
}
/** Sets the origin position which is relative to the actor's bottom left corner. */
fun setOrigin(originX: Float, originY: Float) {
this.originX = originX
this.originY = originY
}
/** Sets the origin position to the specified [alignment][Align]. */
fun setOrigin(alignment: Int) {
originX = if (alignment and Align.left != 0) 0f else if (alignment and Align.right != 0) width else width * 0.5f
originY = if (alignment and Align.bottom != 0) 0f else if (alignment and Align.top != 0) height else height * 0.5f
}
/** Sets the scale for both X and Y */
fun setScale(scaleXY: Float) {
scaleX = scaleXY
scaleY = scaleXY
}
/** Sets the scale X and scale Y. */
fun setScale(scaleX: Float, scaleY: Float) {
this.scaleX = scaleX
this.scaleY = scaleY
}
/** Adds the specified scale to the current scale. */
fun scaleBy(scale: Float) {
scaleX += scale
scaleY += scale
}
/** Adds the specified scale to the current scale. */
fun scaleBy(scaleX: Float, scaleY: Float) {
this.scaleX += scaleX
this.scaleY += scaleY
}
/** Adds the specified rotation to the current rotation. */
fun rotateBy(amountInDegrees: Float) {
if (amountInDegrees != 0f) {
rotation = (rotation + amountInDegrees) % 360
rotationChanged()
}
}
/** Changes the z-order for this actor so it is in front of all siblings. */
fun toFront() {
setZIndex(Int.MAX_VALUE)
}
/** Changes the z-order for this actor so it is in back of all siblings. */
fun toBack() {
setZIndex(0)
}
/** Sets the z-index of this actor. The z-index is the index into the parent's [children][Group.getChildren], where a
* lower index is below a higher index. Setting a z-index higher than the number of children will move the child to the front.
* Setting a z-index less than zero is invalid.
* @return true if the z-index changed.
*/
fun setZIndex(index: Int): Boolean {
var index = index
require(index >= 0) { "ZIndex cannot be < 0." }
val parent = parent ?: return false
val children = parent.children
if (children.size == 1) return false
index = min(index, children.size - 1)
if (children[index] === this) return false
if (!children.remove(this)) return false
children.add(index, this)
return true
}
/** Returns the z-index of this actor, or -1 if the actor is not in a group.
* @see .setZIndex
*/
val zIndex: Int
get() {
val parent = parent ?: return -1
return parent.children.indexOf(this)
}
/** Clips the specified screen aligned rectangle, specified relative to the transform matrix of the stage's Batch. The
* transform matrix and the stage's camera must not have rotational components.
* @see ScissorStack
*/
inline fun clipArea(x: Float, y: Float, width: Float, height: Float, block: () -> Unit) {
if (width <= 0 || height <= 0) return
val stage = hud ?: return
val scissorBounds = rectanglePool.get()
stage.calculateScissors(x, y, width, height, scissorBounds)
if (ScissorStack.pushScissors(scissorBounds)) {
block()
rectanglePool.free(ScissorStack.popScissors())
} else {
rectanglePool.free(scissorBounds)
}
}
/** Transforms the specified point in screen coordinates to the actor's local coordinate system.
* @see HeadUpDisplay.screenToStageCoordinates
*/
fun screenToLocalCoordinates(screenCoords: IVec2): IVec2 {
val stage = hud ?: return screenCoords
return stageToLocalCoordinates(stage.screenToStageCoordinates(screenCoords))
}
/** Transforms the specified point in the stage's coordinates to the actor's local coordinate system. */
fun stageToLocalCoordinates(stageCoords: IVec2): IVec2 {
if (parent != null) parent!!.stageToLocalCoordinates(stageCoords)
parentToLocalCoordinates(stageCoords)
return stageCoords
}
/** Converts the coordinates given in the parent's coordinate system to this actor's coordinate system. */
fun parentToLocalCoordinates(parentCoords: IVec2): IVec2 {
val rotation = rotation
val scaleX = scaleX
val scaleY = scaleY
val childX = x
val childY = y
if (rotation == 0f) {
if (scaleX == 1f && scaleY == 1f) {
parentCoords.x -= childX
parentCoords.y -= childY
} else {
val originX = originX
val originY = originY
parentCoords.x = (parentCoords.x - childX - originX) / scaleX + originX
parentCoords.y = (parentCoords.y - childY - originY) / scaleY + originY
}
} else {
val cos = MATH.cos(rotation * MATH.degRad)
val sin = MATH.sin(rotation * MATH.degRad)
val originX = originX
val originY = originY
val tox = parentCoords.x - childX - originX
val toy = parentCoords.y - childY - originY
parentCoords.x = (tox * cos + toy * sin) / scaleX + originX
parentCoords.y = (tox * -sin + toy * cos) / scaleY + originY
}
return parentCoords
}
/** Transforms the specified point in the actor's coordinates to be in screen coordinates.
* @see HeadUpDisplay.stageToScreenCoordinates
*/
fun localToScreenCoordinates(localCoords: IVec2): IVec2 {
val stage = hud ?: return localCoords
return stage.stageToScreenCoordinates(localToAscendantCoordinates(null, localCoords))
}
/** Transforms the specified point in the actor's coordinates to be in the stage's coordinates. */
fun localToStageCoordinates(localCoords: IVec2): IVec2 {
return localToAscendantCoordinates(null, localCoords)
}
/** Transforms the specified point in the actor's coordinates to be in the parent's coordinates. */
fun localToParentCoordinates(localCoords: IVec2): IVec2 {
val rotation = -rotation
val scaleX = scaleX
val scaleY = scaleY
val x = x
val y = y
if (rotation == 0f) {
if (scaleX == 1f && scaleY == 1f) {
localCoords.x += x
localCoords.y += y
} else {
val originX = originX
val originY = originY
localCoords.x = (localCoords.x - originX) * scaleX + originX + x
localCoords.y = (localCoords.y - originY) * scaleY + originY + y
}
} else {
val cos = cos(rotation * MATH.degRad)
val sin = sin(rotation * MATH.degRad)
val originX = originX
val originY = originY
val tox = (localCoords.x - originX) * scaleX
val toy = (localCoords.y - originY) * scaleY
localCoords.x = tox * cos + toy * sin + originX + x
localCoords.y = tox * -sin + toy * cos + originY + y
}
return localCoords
}
/** Converts coordinates for this actor to those of a parent actor. The ascendant does not need to be a direct parent. */
fun localToAscendantCoordinates(ascendant: Actor?, localCoords: IVec2): IVec2 {
var actor: Actor? = this
do {
actor!!.localToParentCoordinates(localCoords)
actor = actor.parent
if (actor === ascendant) break
} while (actor != null)
return localCoords
}
/** Converts coordinates for this actor to those of another actor, which can be anywhere in the stage. */
fun localToActorCoordinates(actor: Actor, localCoords: IVec2): IVec2 {
localToStageCoordinates(localCoords)
return actor.stageToLocalCoordinates(localCoords)
}
override fun toString(): String = name ?: super.toString()
companion object {
val groupsArrayPool = Pool({ ArrayList<Group>() }, { it.clear() })
val rectanglePool: Pool<IRectangle> = Pool({ Rectangle() }, {})
}
}
| 3 | Kotlin | 5 | 61 | 8e2943b6d2de3376ce338025b58ff31c14097caf | 25,331 | thelema-engine | Apache License 2.0 |
flank-scripts/src/main/kotlin/flank/scripts/data/github/objects/GitHubUpdateIssue.kt | Flank | 84,221,974 | false | null | package flank.scripts.data.github.objects
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GitHubUpdateIssueRequest(
val title: String = "",
val body: String = "",
val state: IssueState = IssueState.OPEN,
val milestone: Int? = null,
val labels: List<String> = emptyList(),
val assignees: List<String> = emptyList()
)
@Serializable
enum class IssueState {
@SerialName("open") OPEN,
@SerialName("closed") CLOSED
}
| 64 | null | 115 | 676 | b40904b4e74a670cf72ee53dc666fc3a801e7a95 | 505 | flank | Apache License 2.0 |
src/main/kotlin/com/supa/spring/supaspring/controller/dto/BucketDto.kt | hieuwu | 804,142,942 | false | {"Kotlin": 17210} | package com.supa.spring.supaspring.controller.dto
import com.fasterxml.jackson.annotation.JsonProperty
import kotlinx.datetime.Instant
data class BucketDto(
@JsonProperty("created_at")
val createdAt: Instant,
@JsonProperty("id")
val id: String,
@JsonProperty("name")
val name: String,
@JsonProperty("owner")
val owner: String,
@JsonProperty("updated_at")
val updatedAt: Instant,
val public: Boolean,
@JsonProperty("allowed_mime_types")
val allowedMimeTypes: List<String>? = null,
@JsonProperty("file_size_limit")
val fileSizeLimit: Long? = null
) | 2 | Kotlin | 0 | 2 | 428d95e563d116faa94c25a29ff5455cfb29c414 | 608 | supa-spring-kt | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/transfer/CfnWorkflowDecryptStepDetailsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.transfer
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.transfer.CfnWorkflow
/**
* Details for a step that decrypts an encrypted file.
*
* Consists of the following values:
* * A descriptive name
* * An Amazon S3 or Amazon Elastic File System (Amazon EFS) location for the source file to
* decrypt.
* * An S3 or Amazon EFS location for the destination of the file decryption.
* * A flag that indicates whether to overwrite an existing file of the same name. The default is
* `FALSE` .
* * The type of encryption that's used. Currently, only PGP encryption is supported.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.transfer.*;
* DecryptStepDetailsProperty decryptStepDetailsProperty = DecryptStepDetailsProperty.builder()
* .destinationFileLocation(InputFileLocationProperty.builder()
* .efsFileLocation(EfsInputFileLocationProperty.builder()
* .fileSystemId("fileSystemId")
* .path("path")
* .build())
* .s3FileLocation(S3InputFileLocationProperty.builder()
* .bucket("bucket")
* .key("key")
* .build())
* .build())
* .name("name")
* .overwriteExisting("overwriteExisting")
* .sourceFileLocation("sourceFileLocation")
* .type("type")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-transfer-workflow-decryptstepdetails.html)
*/
@CdkDslMarker
public class CfnWorkflowDecryptStepDetailsPropertyDsl {
private val cdkBuilder: CfnWorkflow.DecryptStepDetailsProperty.Builder =
CfnWorkflow.DecryptStepDetailsProperty.builder()
/**
* @param destinationFileLocation Specifies the location for the file being decrypted. Use
* `${Transfer:UserName}` or `${Transfer:UploadDate}` in this field to parametrize the
* destination prefix by username or uploaded date.
* * Set the value of `DestinationFileLocation` to `${Transfer:UserName}` to decrypt uploaded
* files to an Amazon S3 bucket that is prefixed with the name of the Transfer Family user
* that uploaded the file.
* * Set the value of `DestinationFileLocation` to `${Transfer:UploadDate}` to decrypt uploaded
* files to an Amazon S3 bucket that is prefixed with the date of the upload.
*
* The system resolves `UploadDate` to a date format of *YYYY-MM-DD* , based on the date the
* file is uploaded in UTC.
*/
public fun destinationFileLocation(destinationFileLocation: IResolvable) {
cdkBuilder.destinationFileLocation(destinationFileLocation)
}
/**
* @param destinationFileLocation Specifies the location for the file being decrypted. Use
* `${Transfer:UserName}` or `${Transfer:UploadDate}` in this field to parametrize the
* destination prefix by username or uploaded date.
* * Set the value of `DestinationFileLocation` to `${Transfer:UserName}` to decrypt uploaded
* files to an Amazon S3 bucket that is prefixed with the name of the Transfer Family user
* that uploaded the file.
* * Set the value of `DestinationFileLocation` to `${Transfer:UploadDate}` to decrypt uploaded
* files to an Amazon S3 bucket that is prefixed with the date of the upload.
*
* The system resolves `UploadDate` to a date format of *YYYY-MM-DD* , based on the date the
* file is uploaded in UTC.
*/
public fun destinationFileLocation(
destinationFileLocation: CfnWorkflow.InputFileLocationProperty
) {
cdkBuilder.destinationFileLocation(destinationFileLocation)
}
/** @param name The name of the step, used as an identifier. */
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param overwriteExisting A flag that indicates whether to overwrite an existing file of the
* same name. The default is `FALSE` . If the workflow is processing a file that has the same
* name as an existing file, the behavior is as follows:
* * If `OverwriteExisting` is `TRUE` , the existing file is replaced with the file being
* processed.
* * If `OverwriteExisting` is `FALSE` , nothing happens, and the workflow processing stops.
*/
public fun overwriteExisting(overwriteExisting: String) {
cdkBuilder.overwriteExisting(overwriteExisting)
}
/**
* @param sourceFileLocation Specifies which file to use as input to the workflow step: either
* the output from the previous step, or the originally uploaded file for the workflow.
* * To use the previous file as the input, enter `${previous.file}` . In this case, this
* workflow step uses the output file from the previous workflow step as input. This is the
* default value.
* * To use the originally uploaded file location as input for this step, enter
* `${original.file}` .
*/
public fun sourceFileLocation(sourceFileLocation: String) {
cdkBuilder.sourceFileLocation(sourceFileLocation)
}
/** @param type The type of encryption used. Currently, this value must be `PGP` . */
public fun type(type: String) {
cdkBuilder.type(type)
}
public fun build(): CfnWorkflow.DecryptStepDetailsProperty = cdkBuilder.build()
}
| 3 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 5,677 | awscdk-dsl-kotlin | Apache License 2.0 |
idea/testData/quickfix/when/addRemainingBranchesBoolean.kt | JakeWharton | 99,388,807 | true | null | // "Add remaining branches" "true"
// ERROR: Unresolved reference: TODO
fun test(b: Boolean) = wh<caret>en(b) {
false -> 0
}
| 1 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 129 | kotlin | Apache License 2.0 |
app/src/main/java/com/babylon/wallet/android/presentation/account/settings/specificassets/composables/LabeledRadioButton.kt | radixdlt | 513,047,280 | false | {"Kotlin": 4784987, "HTML": 215350, "Ruby": 2757, "Shell": 1963} | package com.babylon.wallet.android.presentation.account.settings.specificassets.composables
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.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.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.babylon.wallet.android.R
import com.babylon.wallet.android.designsystem.theme.RadixTheme
import com.babylon.wallet.android.presentation.ui.RadixWalletPreviewTheme
@Composable
fun LabeledRadioButton(
modifier: Modifier = Modifier,
label: String,
selected: Boolean,
onSelected: () -> Unit
) {
Box(
modifier = modifier.clickable {
onSelected()
},
contentAlignment = Alignment.CenterStart
) {
RadioButton(
selected = selected,
colors = RadioButtonDefaults.colors(
selectedColor = RadixTheme.colors.gray1,
unselectedColor = RadixTheme.colors.gray3,
disabledSelectedColor = RadixTheme.colors.white
),
onClick = onSelected,
)
Text(
modifier = Modifier.padding(start = 40.dp),
text = label,
style = RadixTheme.typography.body1HighImportance,
color = RadixTheme.colors.gray1,
textAlign = TextAlign.Center
)
}
}
@Composable
@Preview
private fun LabeledRadioButtonPreview() {
RadixWalletPreviewTheme {
LabeledRadioButton(
modifier = Modifier,
label = stringResource(id = R.string.accountSettings_specificAssetsDeposits_addAnAssetAllow),
selected = true,
onSelected = {}
)
}
}
| 8 | Kotlin | 6 | 8 | 5bf97355e9df691ca56e3fa608b95167f3adb5b3 | 2,071 | babylon-wallet-android | Apache License 2.0 |
app/src/main/kotlin/me/echeung/moemoekyun/ui/theme/Theme.kt | LISTEN-moe | 86,269,685 | false | {"Kotlin": 205904} | package me.echeung.moemoekyun.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val ThemePalette = darkColorScheme(
primary = Color(0xFFFF015B),
onPrimary = Color(0xFFFFFFFF),
secondary = Color(0xFFB4B8C2),
primaryContainer = Color(0xFFFF015B),
background = Color(0xFF1C1D1C),
)
@Composable
fun AppTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = ThemePalette,
content = content,
)
}
| 8 | Kotlin | 25 | 252 | c48818a69952a83e57e574776b402b5b3620d94a | 602 | android-app | MIT License |
app/src/main/java/com/cdhiraj40/leetdroid/api/GithubApi.kt | cdhiraj40 | 448,634,081 | false | {"Kotlin": 377758} | package com.cdhiraj40.leetdroid.api
import com.cdhiraj40.leetdroid.model.ContributorListModel
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
interface GithubApi {
@GET("repos/{owner}/{repo}/stats/contributors")
fun getContributors(
@Path("owner") owner: String?,
@Path("repo") repositoryName: String
): Call<ContributorListModel>
companion object {
fun create(): GithubApi {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(URL.githubApi)
.build()
return retrofit.create(GithubApi::class.java)
}
}
} | 2 | Kotlin | 15 | 54 | a4a42158297c9cb48600259febd7b1d4916a4bb6 | 779 | LeetDroid | MIT License |
src/test/kotlin/csperandio/dependencies/tests/integration/VersionCheckerIntegrationTest.kt | lolo101 | 366,496,744 | true | {"Kotlin": 20826} | package csperandio.dependencies.tests.integration
import csperandio.dependencies.VersionChecker
import csperandio.dependencies.dependencies.Dependency
import csperandio.dependencies.repo.ExternalMavenRepo
import org.junit.jupiter.api.Test
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import java.util.Collections.singleton
import kotlin.test.assertEquals
class VersionCheckerIntegrationTest {
@Test
internal fun dependencyDatesFromPom() {
val simplePom =
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>example.project.maven</groupId>\n" +
" <artifactId>MavenEclipseExample</artifactId>\n" +
" <version>0.0.1-SNAPSHOT</version>\n" +
" <packaging>jar</packaging>\n" +
" <description>Maven pom example</description>\n" +
" <name>MavenEclipseExample</name>\n" +
" <url>http://maven.apache.org</url>\n" +
"\n" +
" <properties>\n" +
" <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n" +
" </properties>\n" +
"\n" +
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>junit</groupId>\n" +
" <artifactId>junit</artifactId>\n" +
" <version>3.8.1</version>\n" +
" <scope>test</scope>\n" +
" </dependency>\n" +
" <dependency>\n" +
" <groupId>log4j</groupId>\n" +
" <artifactId>log4j</artifactId>\n" +
" <version>1.2.17</version>\n" +
" </dependency>\n" +
" </dependencies>\n" +
"</project>"
val checker = VersionChecker(ExternalMavenRepo("https://repo1.maven.org/maven2"))
val dates = checker.dates(singleton(simplePom.reader()))
val expected = mapOf(
Pair(Dependency("junit", "junit", "3.8.1"), "2005-09-20"),
Pair(Dependency("log4j", "log4j", "1.2.17"), "2012-05-26")
)
assertEquals(expected, dates)
}
@Test
internal fun searchDuplicatedDependencyOnlyOnce() {
val firstPom =
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>example.project.maven</groupId>\n" +
" <artifactId>main</artifactId>\n" +
" <version>0.0.1-SNAPSHOT</version>\n" +
"\n" +
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>log4j</groupId>\n" +
" <artifactId>log4j</artifactId>\n" +
" <version>1.2.17</version>\n" +
" </dependency>\n" +
" </dependencies>\n" +
"</project>"
val secondPom =
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>example.project.maven</groupId>\n" +
" <artifactId>module</artifactId>\n" +
" <version>0.0.1-SNAPSHOT</version>\n" +
"\n" +
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>log4j</groupId>\n" +
" <artifactId>log4j</artifactId>\n" +
" <version>1.2.17</version>\n" +
" </dependency>\n" +
" </dependencies>\n" +
"</project>"
val checker = spy(VersionChecker(ExternalMavenRepo("https://repo1.maven.org/maven2")))
checker.dates(listOf(firstPom.reader(), secondPom.reader()))
verify(checker).date(Dependency("log4j", "log4j", "1.2.17"))
}
}
| 0 | Kotlin | 0 | 0 | c20f9df48bbe5e37172704f05b6be0bace2914d0 | 4,972 | check-dependencies | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/sagemaker/CfnDataQualityJobDefinitionDataQualityAppSpecificationPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.sagemaker
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.sagemaker.CfnDataQualityJobDefinition
/**
* Information about the container that a data quality monitoring job runs.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.sagemaker.*;
* DataQualityAppSpecificationProperty dataQualityAppSpecificationProperty =
* DataQualityAppSpecificationProperty.builder()
* .imageUri("imageUri")
* // the properties below are optional
* .containerArguments(List.of("containerArguments"))
* .containerEntrypoint(List.of("containerEntrypoint"))
* .environment(Map.of(
* "environmentKey", "environment"))
* .postAnalyticsProcessorSourceUri("postAnalyticsProcessorSourceUri")
* .recordPreprocessorSourceUri("recordPreprocessorSourceUri")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sagemaker-dataqualityjobdefinition-dataqualityappspecification.html)
*/
@CdkDslMarker
public class CfnDataQualityJobDefinitionDataQualityAppSpecificationPropertyDsl {
private val cdkBuilder:
CfnDataQualityJobDefinition.DataQualityAppSpecificationProperty.Builder =
CfnDataQualityJobDefinition.DataQualityAppSpecificationProperty.builder()
private val _containerArguments: MutableList<String> = mutableListOf()
private val _containerEntrypoint: MutableList<String> = mutableListOf()
/**
* @param containerArguments The arguments to send to the container that the monitoring job
* runs.
*/
public fun containerArguments(vararg containerArguments: String) {
_containerArguments.addAll(listOf(*containerArguments))
}
/**
* @param containerArguments The arguments to send to the container that the monitoring job
* runs.
*/
public fun containerArguments(containerArguments: Collection<String>) {
_containerArguments.addAll(containerArguments)
}
/** @param containerEntrypoint The entrypoint for a container used to run a monitoring job. */
public fun containerEntrypoint(vararg containerEntrypoint: String) {
_containerEntrypoint.addAll(listOf(*containerEntrypoint))
}
/** @param containerEntrypoint The entrypoint for a container used to run a monitoring job. */
public fun containerEntrypoint(containerEntrypoint: Collection<String>) {
_containerEntrypoint.addAll(containerEntrypoint)
}
/**
* @param environment Sets the environment variables in the container that the monitoring job
* runs.
*/
public fun environment(environment: Map<String, String>) {
cdkBuilder.environment(environment)
}
/**
* @param environment Sets the environment variables in the container that the monitoring job
* runs.
*/
public fun environment(environment: IResolvable) {
cdkBuilder.environment(environment)
}
/** @param imageUri The container image that the data quality monitoring job runs. */
public fun imageUri(imageUri: String) {
cdkBuilder.imageUri(imageUri)
}
/**
* @param postAnalyticsProcessorSourceUri An Amazon S3 URI to a script that is called after
* analysis has been performed. Applicable only for the built-in (first party) containers.
*/
public fun postAnalyticsProcessorSourceUri(postAnalyticsProcessorSourceUri: String) {
cdkBuilder.postAnalyticsProcessorSourceUri(postAnalyticsProcessorSourceUri)
}
/**
* @param recordPreprocessorSourceUri An Amazon S3 URI to a script that is called per row prior
* to running analysis. It can base64 decode the payload and convert it into a flattened JSON
* so that the built-in container can use the converted data. Applicable only for the built-in
* (first party) containers.
*/
public fun recordPreprocessorSourceUri(recordPreprocessorSourceUri: String) {
cdkBuilder.recordPreprocessorSourceUri(recordPreprocessorSourceUri)
}
public fun build(): CfnDataQualityJobDefinition.DataQualityAppSpecificationProperty {
if (_containerArguments.isNotEmpty()) cdkBuilder.containerArguments(_containerArguments)
if (_containerEntrypoint.isNotEmpty()) cdkBuilder.containerEntrypoint(_containerEntrypoint)
return cdkBuilder.build()
}
}
| 3 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 4,896 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/kotlin/dev/wellcoded/sunshine/domain/weather/WeatherApi.kt | dtokarzewski | 195,118,053 | false | null | package dev.wellcoded.sunshine.domain.weather
import dev.wellcoded.sunshine.domain.weather.data.WeatherDto
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface WeatherApi {
@GET("weather")
fun getWeatherForCity(@Query("id") cityId: Int): Single<WeatherDto>
} | 0 | Kotlin | 0 | 0 | d28f12c7e5a7320775d77c4fed621957f04779f6 | 307 | Sunshine | MIT License |
src/main/kotlin/org/microjservice/lark/api/ChatApi.kt | MicroJService | 358,535,254 | false | null | package org.microjservice.lark.api
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
import io.reactivex.Single
import org.microjservice.lark.api.models.GroupPage
import org.microjservice.lark.api.models.BaseResponse
import org.microjservice.lark.api.models.Group
/**
* Chat Api
*
* @author <NAME>
* @since 0.1.0
*/
@Client(value = "\${lark.endpoint}/chat/v4")
interface ChatApi {
@Get("/list")
fun list(): Single<BaseResponse<GroupPage>>
companion object {
@JvmStatic
fun getChatIds(response: BaseResponse<GroupPage>): List<String> {
return response.data.groups.map(Group::chatId)
}
}
} | 1 | Kotlin | 1 | 2 | 6f4d4befc3373b486616c19a632e2c9bbb8997c6 | 688 | lark-api | Apache License 2.0 |
espresso-runner/src/main/kotlin/org/mint/espressoRunner/state/EspressoStateToXML.kt | ing-bank | 620,378,707 | false | {"Kotlin": 375172, "XSLT": 61849} | package com.ing.mint.espressoRunner.state
import android.content.res.Resources
import android.view.View
import android.view.ViewGroup
import com.ing.mint.android.AndroidStateUtils
import com.ing.mint.espressoRunner.state.attributes.ViewAttributes
import com.ing.mint.espressoRunner.state.attributes.ViewGroupAttributes
import com.ing.mint.espressoRunner.state.attributes.WindowAttributes
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
object EspressoStateToXML {
/** Create an empty document representing the SUT */
fun emptySUT(): Pair<Document, Element> {
val doc = AndroidStateUtils.newDocument()
val root = doc.createElement("SystemUnderTest")
doc.adoptNode(root)
return Pair(doc, root)
}
fun toXML(roots: List<View>): Element {
val (doc, root) = emptySUT()
root.appendChild(DeviceInfo.toNode(doc))
root.appendChild(Screenshot.toNode(doc))
val applicationNode = doc.createElement("Application")
root.appendChild(applicationNode)
AppInfo.toNode(doc)?.let { applicationNode.appendChild(it) }
applicationNode.appendChild(AppComponents.toNode(doc))
roots.forEach { view ->
val windowNode = doc.createElement("Window")
WindowAttributes.apply((windowNode as Element), view)
val viewHierarchy = toXML(doc, view, "root")
windowNode.appendChild(viewHierarchy)
applicationNode.appendChild(windowNode)
}
return root
}
fun toString(n: Node): String = AndroidStateUtils.toXdm(n).toString()
private fun toXML(doc: Document, view: View, positionInViewHierarchy: String): Node {
val viewElement = doc.createElement("View")
// Apply Attributes
applyResourceAttributes(viewElement, view, positionInViewHierarchy)
applyDetailedViewAttributes(viewElement, view)
applyWindowAttributes(viewElement, view)
// Add Accessibility Check Findings
AccessibilityViewCheck.apply(viewElement, view)
// Recursion - for each child in the ViewGroup
if (view is ViewGroup) {
ViewGroupAttributes.apply(viewElement, view)
for (i in 0 until view.childCount) {
viewElement.appendChild(
toXML(
doc,
view.getChildAt(i),
positionInViewHierarchy.plus(".$i"),
),
)
}
}
return viewElement
}
/**
* Apply attributes from the view resources (if applicable)
*/
private fun applyResourceAttributes(
viewElement: Element,
view: View,
positionInViewHierarchy: String,
) {
viewElement.setUserData("origin", view, null)
viewElement.setAttribute("positionInViewHierarchy", positionInViewHierarchy)
viewElement.setAttribute("class", view.javaClass.canonicalName)
val viewResources = view.resources
val viewId = view.id
if (viewResources != null && viewId != View.NO_ID) {
viewElement.setAttribute("id", "" + viewId)
try {
viewElement.setAttribute(
"resourceName",
viewResources.getResourceEntryName(viewId),
)
viewElement.setAttribute(
"package",
viewResources.getResourcePackageName(viewId),
)
} catch (e: Resources.NotFoundException) {
println("Resource with id=$viewId not found")
}
}
}
/**
* Apply View Attributes for all views even without an ID or resources. This is to ensure
* that all views are being included in the view hierarchy for MINT to interact with.
*/
private fun applyDetailedViewAttributes(
viewElement: Element,
view: View,
) {
ViewAttributes.apply(viewElement, view)
}
private fun applyWindowAttributes(
viewElement: Element,
view: View,
) {
viewElement.setAttribute("hasWindowFocus", view.hasWindowFocus().toString())
}
}
| 0 | Kotlin | 2 | 4 | abf96d311b3ebb1bba2a331a353126c653225be9 | 4,218 | mint | MIT License |
domain/src/main/java/klodian/kambo/domain/usecases/GetWeatherByLocationUseCase.kt | KlodianKambo | 350,786,745 | false | {"Kotlin": 58683} | package klodian.kambo.domain.usecases
import arrow.core.Either
import com.kambo.klodian.entities.model.ForecastWeather
import com.kambo.klodian.entities.model.TemperatureUnit
import klodian.kambo.domain.model.HttpRequestError
import klodian.kambo.domain.repositories.WeatherRemoteDataStore
import java.time.ZoneId
import java.util.*
import javax.inject.Inject
class GetWeatherByLocationUseCase @Inject constructor(private val weatherRemoteDataStore: WeatherRemoteDataStore) {
suspend operator fun invoke(
latitude: Double,
longitude: Double,
locale: Locale,
measurementUnit: TemperatureUnit,
zoneId: ZoneId
): Either<HttpRequestError, ForecastWeather> {
return weatherRemoteDataStore.getWeatherByLocation(
latitude,
longitude,
locale,
measurementUnit,
zoneId
)
}
}
| 0 | Kotlin | 1 | 0 | a79c15a972be484136a7fc8fc5ae7b9da249e724 | 898 | WeatherAndroid | The Unlicense |
speakers/src/main/java/com/droidcon/speakers/presentation/speakerlist/fragment/SpeakersFragment.kt | rockndroid | 219,824,667 | false | null | package com.droidcon.speakers.presentation.speakerlist.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.droidcon.commons.presentation.Navigator
import com.droidcon.commons.recyclerview.setDivider
import com.droidcon.speakers.R
import com.droidcon.speakers.presentation.speakerlist.model.SpeakersEffect
import com.droidcon.speakers.presentation.speakerlist.model.SpeakersState
import com.droidcon.speakers.presentation.speakerlist.recyclerview.SpeakersAdapter
import com.droidcon.speakers.presentation.speakerlist.viewmodel.SpeakersViewModel
import com.droidcon.speakers.presentation.speakerlist.viewmodel.SpeakersViewModelFactory
import dagger.android.support.DaggerFragment
import javax.inject.Inject
class SpeakersFragment : DaggerFragment() {
@Inject
lateinit var navigator: Navigator
@Inject
lateinit var speakersAdapter: SpeakersAdapter
@Inject
lateinit var speakersViewModelFactory: SpeakersViewModelFactory
private lateinit var speakersViewModel: SpeakersViewModel
private lateinit var speakers: RecyclerView
private lateinit var errorView: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.fragment_speakers, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpViewModel()
setUpView(view)
setUpMenu(view)
bindViewModel()
}
private fun setUpView(rootView: View) {
speakers = rootView.findViewById<RecyclerView>(R.id.speakers).apply {
layoutManager = LinearLayoutManager(context)
adapter = speakersAdapter
itemAnimator = null
setDivider(R.drawable.row_divider)
}
errorView = rootView.findViewById(R.id.fatalError)
}
private fun setUpMenu(rootView: View) {
val toolbar = rootView.findViewById<Toolbar>(R.id.toolbar)
toolbar.run {
inflateMenu(R.menu.speakers_menu)
setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.search -> {
speakersViewModel.onSearchTapped()
true
}
else -> false
}
}
}
}
private fun setUpViewModel() {
speakersViewModel = speakersViewModelFactory.get(this)
speakersViewModel.onSpeakersScreenVisible()
}
private fun bindViewModel() {
speakersViewModel.speakersState.observe(::getLifecycle, ::onSpeakersUpdated)
speakersViewModel.speakersEffects.observe(::getLifecycle, ::onSpeakersEffect)
}
private fun onSpeakersUpdated(speakersState: SpeakersState) {
when (speakersState) {
is SpeakersState.Content -> {
speakers.visibility = View.VISIBLE
errorView.visibility = View.GONE
speakersAdapter.submitList(speakersState.speakers)
}
SpeakersState.Error -> {
speakers.visibility = View.GONE
errorView.visibility = View.VISIBLE
}
}
}
private fun onSpeakersEffect(speakersEffect: SpeakersEffect) {
when (speakersEffect) {
is SpeakersEffect.NavigateToDetail -> navigateToSpeakerDetail(speakersEffect.speakerId)
is SpeakersEffect.NavigateToSearch -> navigateToSearch()
}
}
private fun navigateToSpeakerDetail(speakerId: String) {
context?.let { navigator.toSpeakerDetail(it, speakerId) }
}
private fun navigateToSearch() {
findNavController().navigate(
SpeakersFragmentDirections.actionSpeakersFragmentToSearchSpeakersFragment()
)
}
} | 2 | Kotlin | 0 | 0 | 01e1bbb55b65ee57f186eb0fd98cbc84ea92b3f9 | 4,190 | android-droidcon-madrid-19 | Apache License 2.0 |
library/src/main/java/com/alexstyl/contactstore/AndroidContactStore.kt | alexstyl | 408,189,357 | false | {"Kotlin": 292914} | package com.alexstyl.contactstore
import android.content.ContentResolver
import android.provider.ContactsContract
import com.alexstyl.contactstore.ContactOperation.Delete
import com.alexstyl.contactstore.ContactOperation.DeleteGroup
import com.alexstyl.contactstore.ContactOperation.Insert
import com.alexstyl.contactstore.ContactOperation.InsertGroup
import com.alexstyl.contactstore.ContactOperation.Update
import com.alexstyl.contactstore.ContactOperation.UpdateGroup
import kotlinx.coroutines.runBlocking
internal class AndroidContactStore(
private val fetchRequestFactory: FetchRequestFactory,
private val contentResolver: ContentResolver,
private val newContactOperationsFactory: NewContactOperationsFactory,
private val contactGroupOperations: GroupOperationsFactory,
private val existingContactOperationsFactory: ExistingContactOperationsFactory,
) : ContactStore {
override fun execute(builder: SaveRequest.() -> Unit) {
val apply = SaveRequest().apply(builder)
apply.requests.map { operation ->
when (operation) {
is Update -> runBlocking {
existingContactOperationsFactory.updateOperation(operation.contact)
}
is Insert -> newContactOperationsFactory
.addContactsOperation(operation.account, operation.contact)
is Delete -> existingContactOperationsFactory
.deleteContactOperation(operation.contactId)
is InsertGroup -> contactGroupOperations.addGroupOperation(operation.group)
is UpdateGroup -> contactGroupOperations.updateGroupOperation(operation.group)
is DeleteGroup -> contactGroupOperations.deleteGroupOperation(operation.groupId)
}
}.forEach { ops ->
contentResolver.applyBatch(ContactsContract.AUTHORITY, ArrayList(ops))
}
}
override fun fetchContacts(
predicate: ContactPredicate?,
columnsToFetch: List<ContactColumn>,
displayNameStyle: DisplayNameStyle
): FetchRequest<List<Contact>> {
return fetchRequestFactory.fetchContactsRequest(predicate, columnsToFetch, displayNameStyle)
}
override fun fetchContactGroups(predicate: GroupsPredicate?): FetchRequest<List<ContactGroup>> {
return fetchRequestFactory.fetchGroupsRequest(predicate)
}
}
| 3 | Kotlin | 15 | 429 | ee2c5b0bc014b8191783e44e610315c1cc51d896 | 2,394 | contactstore | Apache License 2.0 |
app/src/main/java/com/ku_stacks/ku_ring/navigator/KuringNavigatorImpl.kt | ku-ring | 412,458,697 | false | {"Kotlin": 403379} | package com.ku_stacks.ku_ring.navigator
import android.app.Activity
import android.content.Context
import android.content.Intent
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.ku_stacks.ku_ring.R
import com.ku_stacks.ku_ring.data.model.Notice
import com.ku_stacks.ku_ring.data.model.WebViewNotice
import com.ku_stacks.ku_ring.ui.chat.ChatActivity
import com.ku_stacks.ku_ring.ui.edit_subscription.EditSubscriptionActivity
import com.ku_stacks.ku_ring.ui.feedback.FeedbackActivity
import com.ku_stacks.ku_ring.ui.main.MainActivity
import com.ku_stacks.ku_ring.ui.my_notification.NotificationActivity
import com.ku_stacks.ku_ring.ui.notice_storage.NoticeStorageActivity
import com.ku_stacks.ku_ring.ui.notice_webview.NoticeWebActivity
import com.ku_stacks.ku_ring.ui.notion.NotionViewActivity
import com.ku_stacks.ku_ring.ui.onboarding.OnboardingActivity
import com.ku_stacks.ku_ring.ui.splash.SplashActivity
import javax.inject.Inject
class KuringNavigatorImpl @Inject constructor(): KuringNavigator {
override fun navigateToChat(activity: Activity) {
ChatActivity.start(activity)
}
override fun createEditSubscriptionIntent(context: Context, isFirstRun: Boolean): Intent {
return Intent(context, EditSubscriptionActivity::class.java).apply {
putExtra(EditSubscriptionActivity.FIRST_RUN_FLAG, isFirstRun)
}
}
override fun navigateToEditSubscription(activity: Activity, isFirstRun: Boolean) {
EditSubscriptionActivity.start(activity, isFirstRun)
}
override fun navigateToFeedback(activity: Activity) {
FeedbackActivity.start(activity)
}
override fun createMainIntent(context: Context): Intent {
return MainActivity.createIntent(context)
}
override fun navigateToMain(activity: Activity) {
MainActivity.start(activity)
}
override fun navigateToMain(
activity: Activity,
url: String,
articleId: String,
category: String
) {
MainActivity.start(activity, url, articleId, category)
}
override fun navigateToNotification(activity: Activity) {
NotificationActivity.start(activity)
}
override fun navigateToNoticeStorage(activity: Activity) {
NoticeStorageActivity.start(activity)
}
override fun createNoticeWebIntent(
context: Context,
url: String?,
articleId: String?,
category: String?
): Intent {
return NoticeWebActivity.createIntent(context, url, articleId, category)
}
override fun navigateToNoticeWeb(activity: Activity, notice: Notice) {
NoticeWebActivity.start(activity, notice)
}
override fun navigateToNoticeWeb(activity: Activity, webViewNotice: WebViewNotice) {
NoticeWebActivity.start(activity, webViewNotice)
}
override fun navigateToNoticeWeb(
activity: Activity,
url: String?,
articleId: String?,
category: String?
) {
NoticeWebActivity.start(activity, url, articleId, category)
}
override fun navigateToNotionView(activity: Activity, notionUrl: String) {
NotionViewActivity.start(activity, notionUrl)
}
override fun navigateToOnboarding(activity: Activity) {
OnboardingActivity.start(activity)
}
override fun navigateToSplash(activity: Activity) {
SplashActivity.start(activity)
}
override fun navigateToOssLicensesMenu(activity: Activity) {
val intent = Intent(activity, OssLicensesMenuActivity::class.java)
activity.startActivity(intent)
OssLicensesMenuActivity.setActivityTitle(activity.getString(R.string.open_source_license))
}
} | 2 | Kotlin | 0 | 16 | 16b0bec12fa934c80f41560067f6b0ba93de4665 | 3,708 | KU-Ring-Android | Apache License 2.0 |
meteor-core/src/commonTest/kotlin/fake/CountDslViewModel.kt | getspherelabs | 646,328,849 | false | {"Kotlin": 68656} | package fake
import io.spherelabs.meteor.dsl.meteor
import io.spherelabs.meteor.store.Store
import io.spherelabs.meteor.viewmodel.CommonViewModel
class CountDslViewModel : CommonViewModel<FakeCountState, FakeCountWish, FakeCountEffect>() {
override val store: Store<FakeCountState, FakeCountWish, FakeCountEffect> = meteor {
config {
initialState = FakeCountState()
}
reducer {
on<FakeCountWish.Decrease> {
transition(
action = {
copy(count = count - 1)
}
)
}
on<FakeCountWish.Increase> {
transition(
action = {
copy(count = count + 1)
}
)
}
}
middleware {
on { _, _, _ -> }
}
}
}
| 13 | Kotlin | 3 | 41 | c2406b12c08ab20485130d00b82ef181ebd0a890 | 906 | meteor-kmp | Apache License 2.0 |
src/main/kotlin/org/rust/cargo/runconfig/test/CargoTestRunLineMarkerContributor.kt | beriny | 87,803,437 | false | null | package org.rust.cargo.runconfig.test
import com.intellij.execution.lineMarker.ExecutorAction
import com.intellij.execution.lineMarker.RunLineMarkerContributor
import com.intellij.icons.AllIcons
import com.intellij.psi.PsiElement
import com.intellij.util.Function
import org.rust.cargo.runconfig.getExecutorActions
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.isTest
import org.rust.lang.core.psi.ext.elementType
class CargoTestRunLineMarkerContributor : RunLineMarkerContributor() {
override fun getInfo(element: PsiElement): Info? {
if (element.elementType != IDENTIFIER) return null
val fn = element.parent as? RsFunction ?: return null
return when {
fn.isTest -> Info(
AllIcons.RunConfigurations.TestState.Green2,
Function<PsiElement, String> { "Run Test" },
// `1` here will prefer test configuration over application configuration,
// when both a applicable. Usually configurations are ordered by their target
// PSI elements (smaller element means more specific), but this is not the case here.
*getExecutorActions(1)
)
else -> null
}
}
}
| 0 | null | 0 | 1 | 1205d2ec61fa7ee0b058c3a95bd25a28d94b2abc | 1,307 | intellij-rust | MIT License |
source-code/starter-project/app/src/main/java/com/droidcon/freshpassword/MainScreen.kt | droidcon-academy | 649,553,484 | false | null | package com.droidcon.freshpassword
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import com.droidcon.freshpassword.ui.PasswordFetch
@Composable
fun MainScreen(
modifier: Modifier = Modifier,
viewModel: MainViewModel,
shareText: (String) -> Unit
) {
val password by viewModel.password.observeAsState()
val previousPasswords by viewModel.previousPasswords.observeAsState()
val loading by viewModel.loading.observeAsState()
PasswordFetch(
modifier = modifier,
password = password ?: "",
previousPasswords = previousPasswords ?: emptyList(),
loading = loading ?: false,
shareText = shareText,
onClick = viewModel::fetchPassword
)
}
| 0 | Kotlin | 0 | 2 | ffa7a3e308b6ccf2bced960a07ccf9aa6485f5b5 | 840 | android-cbc-livedata-to-kotlin-flow | Apache License 2.0 |
marketpricelibrary/src/androidTest/java/com/cincinnatiai/marketpricelibrary/MarketPriceAndroidTest.kt | nicholaspark09 | 218,684,304 | false | null | package com.cincinnatiai.marketpricelibrary
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
import junit.framework.Assert.assertNotNull
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import java.lang.Thread.sleep
class MarketPriceAndroidTest {
private lateinit var marketPrice: MarketPrice
@Before
fun setup() {
marketPrice = MarketPrice.intialize(
InstrumentationRegistry.getInstrumentation().targetContext,
apiToken = BuildConfig.API_TOKEN,
isDebug = true
)
}
@Test
fun fetchPrice_testPriceIsReturned() {
// When
marketPrice.fetchStockPrice("EWY") { stock, error ->
assertNotNull(stock)
Log.d("MarketPrice", "the result was " + stock.toString())
}
sleep(600)
}
@Test
fun fetchHistoricalData_testDataReturnedProperly() {
marketPrice.fetchHistoricalMarketData("TSLA", "2019-10-28", "2019-10-30") { data, error ->
Log.d("AndroidTest", "Data is: ${data.toString()}")
assertNotNull(data)
}
sleep(600)
}
@Test
fun fetchPriceContinuously_testPriceIsReturned() {
runBlocking {
marketPrice.fetchRealTimeStockPrice("TSLA").collect { it ->
assertNotNull(it)
}
}
}
@Test
fun fetchPriceContinuouslyInCallback_testCallback() {
marketPrice.fetchContinuousStockPrice(
"MSFT",
intervalInMilliseconds = 300
) { stock, error ->
assertNotNull(stock)
}
sleep(600)
}
} | 0 | Kotlin | 0 | 1 | 62dc6c634593ed36e95ecdd05679e536a8ba8a2e | 1,710 | stockprice | Apache License 2.0 |
codestream-runtime/src/test/kotlin/io/codestream/runtime/TestModule.kt | jexenberger | 131,731,461 | false | {"Maven POM": 9, "Ignore List": 1, "Markdown": 2, "YAML": 6, "Text": 2, "Kotlin": 322, "Java": 8, "Gradle": 3, "JAR Manifest": 5, "XML": 2, "Batchfile": 1, "Shell": 1, "Groovy": 1} | /*
* Copyright 2018 <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`](http://www.apache.org/licenses/LICENSE-2.0)
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.codestream.runtime
import de.skuzzle.semantic.Version
import io.codestream.api.KotlinModule
class TestModule : KotlinModule("test","A test module", Version.create(1, 0, 0)) {
init {
create {
add(SampleSimpleTask::class)
add(ReallySimpleTask::class)
add(SimpleGroupTask::class)
}
}
} | 1 | null | 1 | 1 | 65bd6bb08e25b1af776f4c6d2dc4ca27e1bb6e78 | 1,007 | codestreamparent | Apache License 2.0 |
app/src/main/java/dev/techpolis/studservice/repositories/user/UserRepo.kt | StudServices | 353,117,513 | false | null | package dev.techpolis.studservice.repositories.user
interface UserRepo {
} | 0 | Kotlin | 0 | 0 | a844a9ac31fa02245237a7af68a66b2451dac7cd | 75 | StudServices-Android | MIT License |
platform/src/commonMain/kotlin/it/nicolasfarabegoli/pulverization/runtime/componentsref/CommunicationRef.kt | nicolasfara | 540,771,410 | false | null | package it.nicolasfarabegoli.pulverization.runtime.componentsref
import it.nicolasfarabegoli.pulverization.core.BehaviourComponent
import it.nicolasfarabegoli.pulverization.core.CommunicationComponent
import it.nicolasfarabegoli.pulverization.runtime.communication.Communicator
import kotlinx.serialization.KSerializer
import kotlinx.serialization.serializer
/**
* Represent a reference to the _communication_ component in a pulverized system.
*/
interface CommunicationRef<S : Any> : ComponentRef<S> {
companion object {
/**
* Create a [CommunicationRef] specifying the [serializer] and the [communicator] to be used.
*/
fun <S : Any> create(serializer: KSerializer<S>, communicator: Communicator):
CommunicationRef<S> = CommunicationRefImpl(serializer, communicator)
/**
* Create a [CommunicationRef] specifying the [communicator] to be used.
*/
inline fun <reified S : Any> create(communicator: Communicator): CommunicationRef<S> =
create(serializer(), communicator)
/**
* Create a fake component reference.
* All the methods implementation with this instance do nothing.
*/
fun <S : Any> createDummy(): CommunicationRef<S> = NoOpCommunicationRef()
}
}
internal class CommunicationRefImpl<S : Any>(
private val serializer: KSerializer<S>,
private val communicator: Communicator,
) : ComponentRef<S> by ComponentRefImpl(serializer, BehaviourComponent to CommunicationComponent, communicator),
CommunicationRef<S>
internal class NoOpCommunicationRef<S : Any> :
ComponentRef<S> by NoOpComponentRef(),
CommunicationRef<S>
| 3 | Kotlin | 0 | 1 | 521a45fcfc4db558dacf401ad35872a28934021a | 1,692 | pulverization-framework | MIT License |
clvr-back/platform/src/main/kotlin/com/clvr/platform/api/Template.kt | spbu-math-cs | 698,591,633 | false | {"Kotlin": 94320, "TypeScript": 49419, "JavaScript": 8395, "Python": 8353, "CSS": 738} | package com.clvr.platform.api
import kotlinx.serialization.Serializable
@Serializable
data class TemplateHeader(val name: String, val id: String, val comment: String)
@Serializable
data class TemplateId(val activityName: String, val id: String)
interface Template {
val id: TemplateId
val header: TemplateHeader
} | 16 | Kotlin | 0 | 0 | d5b1b910047bf60d22f628c20ebda1d329d743f5 | 325 | ig-platform | Apache License 2.0 |
availability_core/src/main/java/com/github/availability/ad/debug/AdDebug.kt | 7449 | 652,961,505 | false | null | package com.github.availability.ad.debug
object AdDebug {
@JvmField
var debug = false
} | 0 | Kotlin | 0 | 0 | 2b882f6b9b54d5eaaa0fb1d9cb75d2520dd56e75 | 98 | AvailabilityAd | Apache License 2.0 |
app/src/main/java/com/luiz/thenews/presentation/di/UseCaseModule.kt | Felipeecp | 641,915,241 | false | null | package com.luiz.thenews.presentation.di
import com.luiz.thenews.domain.respository.NewsRepository
import com.luiz.thenews.domain.usecase.DeleteSavedNewsUseCase
import com.luiz.thenews.domain.usecase.GetNewsHeadlinesUseCase
import com.luiz.thenews.domain.usecase.GetSavedNewsUseCase
import com.luiz.thenews.domain.usecase.GetSearchedNewsUseCase
import com.luiz.thenews.domain.usecase.SaveNewsUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class UseCaseModule {
@Provides
@Singleton
fun provideNewsHeadLinesUseCase(
newsRepository: NewsRepository
):GetNewsHeadlinesUseCase{
return GetNewsHeadlinesUseCase(newsRepository)
}
@Provides
@Singleton
fun provideSearchedNewsUseCase(
newsRepository: NewsRepository
):GetSearchedNewsUseCase{
return GetSearchedNewsUseCase(newsRepository)
}
@Provides
@Singleton
fun provideSaveNewsUseCase(
newsRepository: NewsRepository
):SaveNewsUseCase{
return SaveNewsUseCase(newsRepository)
}
@Provides
@Singleton
fun provideGetSavedNewsUseCase(
newsRepository: NewsRepository
):GetSavedNewsUseCase{
return GetSavedNewsUseCase(newsRepository)
}
@Provides
@Singleton
fun provideDeleteSavedNewsUseCase(
newsRepository: NewsRepository
):DeleteSavedNewsUseCase{
return DeleteSavedNewsUseCase(newsRepository)
}
} | 0 | Kotlin | 0 | 0 | e78de1fb46118ac3a9a950b653ca9ef2902b6844 | 1,580 | TheNewsApp | MIT License |
app/src/main/java/com/mob/lee/fastair/localhost/ImageHandler.kt | hongui | 123,892,735 | false | {"Kotlin": 223529, "HTML": 16935, "Svelte": 11650, "Java": 1951, "CSS": 1572, "JavaScript": 552} | package com.mob.lee.fastair.localhost
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.ThumbnailUtils
import android.os.Build
import android.provider.MediaStore
import android.util.Size
import com.mob.lee.fastair.io.http.*
import com.mob.lee.fastair.io.socket.Writer
import kotlinx.coroutines.channels.Channel
import java.io.*
import java.lang.Exception
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
class ImageHandler(val context: Context) : Handler {
companion object {
const val PREV = "/images"
}
override fun canHandleIt(request: Request) = request.url.startsWith(PREV)
override suspend fun handle(request: Request, channel: SocketChannel): Writer {
val path = request.url.substring(PREV.length)
if (request.urlParams.containsKey("width")) {
val width = request.urlParam("width")!!.toInt()
val height = request.urlParam("height")!!.toInt()
val id = request.urlParam("id")!!.toLong()
try {
val bitmap = fetchThumb(id, path, Size(width, height))
ByteArrayOutputStream().use {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
val bytes=it.toByteArray()
return ByteResponse({bytes},PNG)
}
}catch (e:Exception){
return JsonResponse.json(null, NOTFOUNT)
}
}
return ResourceResponse({ FileInputStream(path) }, PNG)
}
fun fetchThumb(id: Long, path: String, size: Size): Bitmap {
return if (Build.VERSION.SDK_INT >= 29) {
ThumbnailUtils.createImageThumbnail(File(path), size, null)
} else {
MediaStore.Images.Thumbnails.getThumbnail(context.contentResolver, id, MediaStore.Images.Thumbnails.MICRO_KIND, null)
}
}
} | 3 | Kotlin | 15 | 82 | ed357bc88292f77f0629cef8e969a5bc06a583a6 | 1,922 | FastAir | Apache License 2.0 |
app/src/main/java/com/example/prodlist/app/ProdListActivity.kt | bsscco | 482,714,624 | false | null | package com.example.prodlist.app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.unit.IntOffset
import androidx.navigation.navDeepLink
import com.example.prodlist.aosutil.navigation.LocalNavController
import com.example.prodlist.designsys.theme.ProdListTheme
import com.example.prodlist.home.HomeScreen
import com.example.prodlist.navigation.Uris
import com.example.prodlist.proddetail.ProductDetailScreen
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.google.accompanist.navigation.animation.composable
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
internal class ProdListActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ProdListApp()
}
}
}
@Composable
private fun ProdListApp() {
ProdListTheme {
@OptIn(ExperimentalAnimationApi::class)
CompositionLocalProvider(LocalNavController provides rememberAnimatedNavController()) {
// 참고 : https://google.github.io/accompanist/navigation-animation
AnimatedNavHost(navController = LocalNavController.current, startDestination = "home") {
composable(
route = "home",
exitTransition = { fadeOut() },
popEnterTransition = { fadeIn() },
) {
HomeScreen()
}
composable(
route = "product?key={key}",
deepLinks = listOf(navDeepLink { uriPattern = "${Uris.ProdList.PRODUCT_DETAIL}?key={key}" }),
enterTransition = { slideIn { fullSize -> IntOffset(fullSize.width, 0) } },
popExitTransition = { slideOut { fullSize -> IntOffset(fullSize.width, 0) } },
) { entry ->
val productKey = entry.arguments!!.getString("key")!!
ProductDetailScreen(productKey)
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | eacb6427f12f953bce62e4a72c31e2300918bd20 | 2,352 | prodlist | Apache License 2.0 |
app/src/main/java/ru/maxim/barybians/data/repository/user/UserRepositoryImpl.kt | maximborodkin | 286,116,912 | false | null | package ru.maxim.barybians.data.repository.user
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import ru.maxim.barybians.data.database.dao.UserDao
import ru.maxim.barybians.data.database.model.mapper.UserEntityMapper
import ru.maxim.barybians.data.network.model.mapper.UserDtoMapper
import ru.maxim.barybians.data.network.service.UserService
import ru.maxim.barybians.data.repository.RepositoryBound
import ru.maxim.barybians.domain.model.User
import javax.inject.Inject
class UserRepositoryImpl @Inject constructor(
private val userService: UserService,
private val userDao: UserDao,
private val repositoryBound: RepositoryBound,
private val userDtoMapper: UserDtoMapper,
private val userEntityMapper: UserEntityMapper
) : UserRepository {
override fun getUserById(userId: Int) = userDao.getById(userId)
.map { entity -> userEntityMapper.toDomainModel(entity ?: return@map null) }
override suspend fun refreshUser(userId: Int) = withContext(IO) {
val userDto = repositoryBound.wrapRequest { userService.getUser(userId) }
if (userDto != null) {
val user = userDtoMapper.toDomainModel(userDto)
userDao.save(userEntityMapper.fromDomainModel(user))
}
}
override suspend fun editStatus(status: String): String =
repositoryBound.wrapRequest { userService.editStatus(status) }
override suspend fun getAllUsers(): List<User> {
val userDto = repositoryBound.wrapRequest { userService.getAll() }
return userDtoMapper.toDomainModelList(userDto)
}
} | 0 | Kotlin | 1 | 5 | 033704d0e141bce002800c6bc00fd19983acc99f | 1,635 | Barybians-Android-App | MIT License |
uranium-arkade-htmlcanvas/src/commonMain/kotlin/pl/karol202/uranium/arkade/htmlcanvas/values/Circle.kt | karol-202 | 269,330,616 | false | null | package pl.karol202.uranium.arkade.htmlcanvas.values
data class Circle(val center: Vector = Vector.ZERO,
val radius: Double)
{
val diameter by lazy { 2 * radius }
val boundingBox by lazy { Bounds(center.x - radius, center.y - radius, diameter, diameter) }
operator fun plus(offset: Vector) = Circle(center + offset, radius)
operator fun minus(offset: Vector) = Circle(center - offset, radius)
// TODO Add ellipse to make multiplying by vector possible
operator fun times(factor: Double) = Circle(center * factor, radius * factor)
operator fun div(factor: Double) =
if(factor != 0.0) Circle(center * factor, radius * factor) else null
}
| 1 | Kotlin | 1 | 3 | ed458611e89b2bdb85d0a23c30c9dd6c0611d30f | 670 | uranium-arkade | MIT License |
permission/src/main/java/halo/android/permission/processor/PermissionProcessor.kt | SupLuo | 128,705,034 | false | null | /*
* Copyright (C) 2019 Lucio
*
* 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 halo.android.permission.processor
import android.content.Intent
import halo.android.permission.caller.PermissionCaller
import halo.android.permission.checker.PermissionChecker
import halo.android.permission.common.PLog
import halo.android.permission.request.PermissionRequest
import halo.android.permission.request.RationaleRender
import halo.android.permission.setting.PermissionSetting
import halo.android.permission.setting.SettingRender
import halo.android.permission.setting.SettingResponder
/**
* Created by Lucio on 2019/6/22.
*/
class PermissionProcessor(val request: PermissionRequest,
val caller: PermissionCaller,
val checker: PermissionChecker) : PermissionResponder, SettingResponder {
//被拒绝的权限集合
private var permissionStates: List<PermissionState> = listOf()
/**
* 控制SettingRender只显示一次
*/
private var isSettingRenderDone = false
/**
* 控制在设置界面关闭之后,是否自动重新检查权限
*/
private var autoCheckWhenSettingResult: Boolean = true
/**
* 校验请求
*/
fun invoke() {
val permissions = request.permissions
PLog.d("[invoke]:即将请求以下权限:${permissions.joinToString(",")}")
//过滤被拒绝的权限
val denyPermissions = permissions.filter {
!checker.isPermissionGranted(caller.ctx, it)
}
if (denyPermissions.isNotEmpty()) {
PLog.d("[invoke]:以下权限未授权,进行请求${denyPermissions.joinToString(",")}")
requestPermissionsReal()
// if (Build.VERSION.SDK_INT >= Util.M) {//有未授权权限
// //过滤Rationale权限
// val rationalePermissions = permissionStates.filter {
// checker.shouldShowRequestPermissionRationale(invokecaller.ctx, it)
// }
// if (!rationalePermissions.isNullOrEmpty()) {
// //有Rationale权限,执行RatinaleRender流程,判断是否需要向用户解释获取权限的原因
// invokeRationaleRenderProcess(rationalePermissions)
// } else {
// //没有Rationale权限,直接请求权限得到结果
// requestPermissionsReal()
// }
// } else {
// //23以下,直接处理SettingRender
// invokeSettingRenderProcess()
// }
} else {
PLog.d("[invoke]:所有权限已授权,直接通知成功回调")
//所有权限已通过,直接触发回调
notifyPermissionSucceed()
}
}
/**
* 权限请求成功
*/
protected fun notifyPermissionSucceed() {
request.getGrandAction()?.onPermissionGrand(request.permissions.toList())
}
private fun getDeniedPermissions():List<String>{
return permissionStates.filter{
!it.isGrand
}.map {
it.value
}
}
/**
* 权限请求失败
*/
protected fun notifyPermissionFailed() {
request.getDenyAction()?.onPermissionDenied(getDeniedPermissions())
}
/**
* 请求权限
*/
private fun requestPermissionsReal() {
caller.requestPermission(this, *request.permissions)
}
/**
* [PermissionResponder]回调 处理请求的权限结果返回
*/
override fun onPermissionResponderResult(permissions: Array<out String>, grantResults: IntArray) {
PLog.d("[onPermissionResponderResult]")
var containsNever: Boolean = false
var exitsDenyPermission: Boolean = false
val ctx = caller.ctx
permissionStates = permissions.map { permission ->
val isGrand = checker.isPermissionGranted(ctx, permission)
val shouldRationale = checker.shouldShowRequestPermissionRationale(ctx, permission)
if (!isGrand) {
exitsDenyPermission = true
}
if (!isGrand && !shouldRationale) {
//如果权限被拒绝,并不允许show rationale,则说明权限被拒绝并且被设置为不再询问等,
// 也就是说即便二次请求也无法获得权限
containsNever = true
}
PermissionState(permission, isGrand, shouldRationale)
}
if (exitsDenyPermission) {//存在未授权权限
PLog.d("[onPermissionResponderResult]:存在未授权权限")
if (containsNever) {//存在无法二次请求获取授权的权限
PLog.d("[onPermissionResponderResult]:存在无法二次请求获取授权的权限,执行SettingRender")
invokeSettingRenderProcess()
} else {
PLog.d("[onPermissionResponderResult]:执行RatinalRender")
invokeRationaleRenderProcess(permissionStates.filter {
it.shouldRationale
}.map {
it.value
})
}
} else {
PLog.d("[onPermissionResponderResult]:所有权限已授权,进行成功回调")
notifyPermissionSucceed()
}
// permissionStates.clear()
// //过滤被拒绝的权限
// permissions.filterTo(permissionStates) {
// !checker.isPermissionGranted(invokecaller.ctx, it)
// }
//
// if (permissionStates.isNullOrEmpty()) {
// notifyPermissionSucceed()
// } else {
// invokeSettingRenderProcess()
// }
}
/**
* 执行RationaleRender流程
*/
private fun invokeRationaleRenderProcess(permissions: List<String>) {
PLog.d("[invokeRationaleRenderProcess]")
val rationaleRender = request.getRationaleRender()
if (rationaleRender != null) {
PLog.d("[invokeRationaleRenderProcess]:执行RationaleRender展示")
//执行RationaleRender显示
rationaleRender.show(caller.ctx, permissions, mRationaleRenderProcess)
} else {
PLog.d("[invokeRationaleRenderProcess]:未设置RationaleRender,执行invokeSettingRenderProcess")
invokeSettingRenderProcess()
// //没有设置RationaleRender,则直接请求权限
// requestPermissionsReal()
}
}
/**
* RationaleRender回调
*/
private val mRationaleRenderProcess: RationaleRender.Process by lazy {
object : RationaleRender.Process {
/**
* 执行权限请求
*/
override fun onNext() {
PLog.d("[RationaleRender.Process]:onNext")
requestPermissionsReal()
}
/**
* 取消则执行权限设置流程
*/
override fun onCancel() {
PLog.d("[RationaleRender.Process]:onCancel")
invokeSettingRenderProcess()
}
}
}
/**
* 处理权限设置SettingRende
*/
private fun invokeSettingRenderProcess() {
PLog.d("[invokeSettingRenderProcess]")
val settingRender = request.getSettingRender()
if (settingRender != null && !isSettingRenderDone) {
PLog.d("[invokeSettingRenderProcess]:已设置SettingRender,并且未显示过权限设置界面,显示")
isSettingRenderDone = true
settingRender.show(caller.ctx, getDeniedPermissions(), mSettingRenderProcess)
} else {
PLog.d("[invokeSettingRenderProcess]:未设置SettingRender,通知权限请求失败")
notifyPermissionFailed()
}
}
/**
* RationaleView回调
*/
private val mSettingRenderProcess: SettingRender.Process by lazy {
object : SettingRender.Process {
/**
* RationaleView回调 下一步
*/
override fun onNext(autoCheckWhenSettingResult: Boolean) {
PLog.d("[SettingRender.Process]:onNext(autoCheckWhenSettingResult=$autoCheckWhenSettingResult)")
[email protected] = autoCheckWhenSettingResult
requestPermissionSettingReal()
}
/**
* RationaleView回调 取消
*/
override fun onCancel() {
PLog.d("[SettingRender.Process]:onCancel")
notifyPermissionFailed()
}
}
}
/**
* 请求权限设置界面
*/
private fun requestPermissionSettingReal() {
val settingIntent = PermissionSetting.getCanResolvedSettingIntent(caller.ctx, request.getSettingRender()?.getCustomSettingIntent(caller.ctx))
if (settingIntent != null) {
caller.requestPermissionSetting(this, settingIntent)
} else {
notifySettingResult()
}
}
/**
* [SettingResponder]回调
*/
override fun onSettingResponderResult(resultCode: Int, data: Intent?) {
notifySettingResult()
}
private fun notifySettingResult() {
if (autoCheckWhenSettingResult) {
//过滤被拒绝的权限
val deniedPermissions = request.permissions.filter{
!checker.isPermissionGranted(caller.ctx, it)
}
if (deniedPermissions.isEmpty()) {
notifyPermissionSucceed()
} else {
notifyPermissionFailed()
}
}
}
} | 0 | Kotlin | 7 | 69 | 45f3f0eac01bef8b3e0bbaaa149ac8fe01754020 | 9,334 | HaloPermission | Apache License 2.0 |
compiler/testData/codegen/box/callableReference/property/localClassVar.kt | JetBrains | 3,432,266 | false | null | class X(val ok: String) {
fun y(): String = ok
}
fun box(): String {
val x = X("OK")
val y = x::y
return y()
}
//fun y(): String = "OK"
//
//fun box(): String {
// val y = ::y
// return y.invoke()
//}
//val x = "OK"
//
//fun box(): String {
// val x = ::x
// return x.get()
//} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 308 | kotlin | Apache License 2.0 |
ref_code/leetcode-main/kotlin/2050-parallel-courses-iii.kt | yennanliu | 66,194,791 | false | null | class Solution {
fun minimumTime(n: Int, relations: Array<IntArray>, time: IntArray): Int {
val adj = HashMap<Int, MutableList<Int>>().apply {
for ((src, dst) in relations) {
this[src] = getOrDefault(src, mutableListOf<Int>()).apply {
add(dst)
}
}
}
val maxTime = IntArray (n + 1) { -1 }
fun dfs(src: Int): Int {
if (maxTime[src] != -1) return maxTime[src]
var res = time[src - 1]
adj[src]?.forEach { nei ->
res = maxOf(res, time[src - 1] + dfs(nei))
}
maxTime[src] = res
return res
}
for (i in 1..n)
dfs(i)
return maxTime.max()!!
}
}
| 0 | null | 42 | 98 | 209db7daa15718f54f32316831ae269326865f40 | 791 | CS_basics | The Unlicense |
domain/src/main/kotlin/pl/angulski/salarytracker/domain/salary/Salary.kt | matiangul | 130,270,750 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 23, "Kotlin": 45, "JSON": 2} | package pl.angulski.salarytracker.domain.salary
/**
* @param money money that user earned
* @param day day when user received her money
*/
data class Salary(val money: Money, val day: Day)
| 2 | null | 1 | 1 | 9d7848923a0dc97364964b0722ab4c7a84be081a | 193 | SalaryTracker | MIT License |
platform/ml-impl/src/com/intellij/platform/ml/impl/logs/common.kt | sprigogin | 93,194,179 | false | {"Text": 9376, "INI": 516, "YAML": 419, "Ant Build System": 11, "Batchfile": 33, "Dockerfile": 10, "Shell": 633, "Markdown": 744, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7826, "SVG": 4416, "Kotlin": 58363, "Java": 83686, "HTML": 3782, "Java Properties": 220, "Gradle": 447, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1419, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 713, "Groovy": 3131, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17005, "C": 111, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 17, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.ml.impl.logs
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.openapi.util.Version
import com.intellij.platform.ml.Feature
import com.intellij.platform.ml.FeatureDeclaration
import com.intellij.platform.ml.FeatureValueType
import com.intellij.platform.ml.impl.session.DescriptionPartition
internal data class StringField(override val name: String, private val possibleValues: Set<String>) : PrimitiveEventField<String>() {
override fun addData(fuData: FeatureUsageData, value: String) {
fuData.addData(name, value)
}
override val validationRule = listOf(
"{enum:${possibleValues.joinToString("|")}}"
)
}
internal data class VersionField(override val name: String) : PrimitiveEventField<Version?>() {
override val validationRule: List<String>
get() = listOf("{regexp#version}")
override fun addData(fuData: FeatureUsageData, value: Version?) {
fuData.addVersion(value)
}
}
internal fun FeatureDeclaration<*>.toEventField(): EventField<*> {
return when (val valueType = type) {
is FeatureValueType.Enum<*> -> EnumEventField(name, valueType.enumClass, Enum<*>::name)
is FeatureValueType.Int -> IntEventField(name)
is FeatureValueType.Long -> LongEventField(name)
is FeatureValueType.Class -> ClassEventField(name)
is FeatureValueType.Boolean -> BooleanEventField(name)
is FeatureValueType.Double -> DoubleEventField(name)
is FeatureValueType.Float -> FloatEventField(name)
is FeatureValueType.Nullable -> FeatureDeclaration(name, valueType.baseType).toEventField()
is FeatureValueType.Categorical -> StringField(name, valueType.possibleValues)
is FeatureValueType.Version -> VersionField(name)
FeatureValueType.Language -> EventFields.Language(name)
}
}
internal fun <T : Enum<*>> Feature.Enum<T>.toEventPair(): EventPair<*> {
return EnumEventField(declaration.name, valueType.enumClass, Enum<*>::name) with value
}
internal fun <T> Feature.Nullable<T>.toEventPair(): EventPair<*>? {
return value?.let {
baseType.instantiate(this.declaration.name, it).toEventPair()
}
}
internal fun Feature.toEventPair(): EventPair<*>? {
return when (this) {
is Feature.TypedFeature<*> -> typedToEventPair()
}
}
internal fun <T> Feature.TypedFeature<T>.typedToEventPair(): EventPair<*>? {
return when (this) {
is Feature.Boolean -> BooleanEventField(declaration.name) with this.value
is Feature.Categorical -> StringField(declaration.name, this.valueType.possibleValues) with this.value
is Feature.Class -> ClassEventField(declaration.name) with this.value
is Feature.Double -> DoubleEventField(declaration.name) with this.value
is Feature.Enum<*> -> toEventPair()
is Feature.Float -> FloatEventField(declaration.name) with this.value
is Feature.Int -> IntEventField(declaration.name) with this.value
is Feature.Long -> LongEventField(declaration.name) with this.value
is Feature.Nullable<*> -> toEventPair()
is Feature.Version -> VersionField(declaration.name) with this.value
is Feature.Language -> EventFields.Language(name) with this.value
}
}
internal class FeatureSet(featureDeclarations: Set<FeatureDeclaration<*>>) : ObjectDescription() {
init {
for (featureDeclaration in featureDeclarations) {
field(featureDeclaration.toEventField())
}
}
fun toObjectEventData(features: Set<Feature>) = ObjectEventData(features.mapNotNull { it.toEventPair() })
}
internal fun Set<Feature>.toObjectEventData() = FeatureSet(this.map { it.declaration }.toSet()).toObjectEventData(this)
internal data class TierDescriptionFields(
val used: FeatureSet,
val notUsed: FeatureSet,
) : ObjectDescription() {
private val fieldUsed = ObjectEventField("used", used)
private val fieldNotUsed = ObjectEventField("not_used", notUsed)
private val fieldAmountUsedNonDeclaredFeatures = IntEventField("n_used_non_declared")
private val fieldAmountNotUsedNonDeclaredFeatures = IntEventField("n_not_used_non_declared")
constructor(descriptionFeatures: Set<FeatureDeclaration<*>>)
: this(used = FeatureSet(descriptionFeatures), notUsed = FeatureSet(descriptionFeatures))
init {
field(fieldUsed)
field(fieldNotUsed)
field(fieldAmountUsedNonDeclaredFeatures)
field(fieldAmountNotUsedNonDeclaredFeatures)
}
fun buildEventPairs(descriptionPartition: DescriptionPartition): List<EventPair<*>> {
val result = mutableListOf<EventPair<*>>(
fieldUsed with descriptionPartition.declared.used.toObjectEventData(),
fieldNotUsed with descriptionPartition.declared.notUsed.toObjectEventData(),
)
descriptionPartition.nonDeclared.used.let {
if (it.isNotEmpty()) result += fieldAmountUsedNonDeclaredFeatures with it.size
}
descriptionPartition.nonDeclared.notUsed.let {
if (it.isNotEmpty()) result += fieldAmountUsedNonDeclaredFeatures with it.size
}
return result
}
fun buildObjectEventData(descriptionPartition: DescriptionPartition) = ObjectEventData(
buildEventPairs(descriptionPartition)
)
}
| 1 | null | 1 | 1 | f1b733c79fd134e6646f28d1dc99af144c942785 | 5,264 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/zhpan/circleviewpager/viewholder/PhotoViewHolder.kt | denghub | 272,428,993 | true | {"Java Properties": 2, "Markdown": 2, "Gradle": 5, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 4, "Proguard": 3, "Java": 88, "XML": 77, "YAML": 1, "Kotlin": 14} | package com.example.zhpan.circleviewpager.viewholder
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.example.zhpan.circleviewpager.R
import com.github.chrisbanes.photoview.PhotoView
import com.zhpan.bannerview.BaseViewHolder
/**
* Created by zhpan on 2017/10/30.
* Description:
*/
class PhotoViewHolder(itemView: View) : BaseViewHolder<Int>(itemView) {
override fun bindData(data: Int?, position: Int, size: Int) {
setImageResource(R.id.banner_image, data!!)
setOnClickListener(R.id.banner_image) {
Toast.makeText(itemView.context, "$adapterPosition 页面数$size", Toast.LENGTH_SHORT).show()
}
}
}
| 0 | null | 0 | 0 | 92b68177152ae4ea62f4994890907a3d2ebee2f8 | 695 | BannerViewPager | Apache License 2.0 |
src/services/schema-export/tests/models/all/kotlin/ChildEmbeddedType.kt | realm | 99,191,277 | false | {"TypeScript": 605898, "SCSS": 49723, "JavaScript": 19917, "Java": 15450, "C#": 7647, "Kotlin": 5427, "Objective-C": 4327, "Swift": 3370, "HTML": 1434, "Dockerfile": 505, "Shell": 31} | // Please note : @LinkingObjects and default values are not represented in the schema and thus will not be part of the generated models
package your.package.name.here
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class ChildEmbeddedType : RealmObject() {
var id: Long = 0
}
| 292 | TypeScript | 38 | 300 | b501e044ad59010d45cd8b773f1b96149aa302e2 | 337 | realm-studio | Apache License 2.0 |
domain/teamplay-database-domain/src/main/kotlin/com/teamplay/domain/database/match/entity/MatchStatus.kt | YAPP-16th | 235,351,938 | false | {"Kotlin": 79474, "Java": 5820, "Shell": 224} | package com.teamplay.domain.database.match.entity
enum class MatchStatus {
WAITING, CLOSE, END
}
| 2 | Kotlin | 0 | 1 | a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2 | 102 | Team_Android_2_Backend | MIT License |
src/main/kotlin/nl/mvdr/adventofcode/adventofcode2021/day22/ReactorRebootPart1.kt | TinusTinus | 189,766,134 | false | {"Maven POM": 1, "Ignore List": 1, "Text": 666, "Markdown": 1, "XML": 2, "Java": 1066, "Kotlin": 309, "INI": 1, "YAML": 1} | package nl.mvdr.adventofcode.adventofcode2021.day22
import io.github.oshai.kotlinlogging.KotlinLogging
import nl.mvdr.adventofcode.FunctionSolver
private val logger = KotlinLogging.logger{}
fun solvePart1(lines: Sequence<String>) = solve(lines, true)
fun main() {
val result = FunctionSolver(::solvePart1).solve("input-day22-2021.txt")
logger.info { result }
}
| 0 | Java | 0 | 0 | 18b66bbb239590f3399afbedb7fde1d1180bde3b | 373 | adventofcode | MIT License |
HelloApp3/app/src/main/java/com/noso/hello/OldFragment.kt | soyeon-noh | 389,844,259 | false | null | package com.noso.hello
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class OldFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater
.inflate(R.layout.fragment_old, container, false)
}
} | 1 | null | 1 | 1 | 19e5ad5541dbcd755451441b5d3f3cfb87208130 | 602 | Biz_2021_07_Android | Apache License 2.0 |
usage/src/main/kotlin/dev/android/playground/nova/usage/SimpleAppCompat.kt | kirill-grouchnikov | 286,843,815 | false | {"Gradle": 7, "Java Properties": 1, "Markdown": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 53, "INI": 1, "Java": 9} | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.playground.nova.usage
import dev.android.playground.nova.appcompat.manual.appCompatThemeManual
import dev.android.playground.nova.core.base.color
import dev.android.playground.nova.core.base.postInit
import dev.android.playground.nova.core.framework.generated.android
import dev.android.playground.nova.core.framework.generated.background_light
import dev.android.playground.nova.core.framework.generated.colorAccent
fun simpleAppCompat() {
appCompatThemeManual(name = "MyMainTheme", parent = "Theme.AppCompat.Light") {
// Simple boolean attributes. The first two will be from the android:
// namespace, while the third will be in the app: (implicit) namespace.
windowDrawsSystemBarBackgrounds = true
windowLightStatusBar = true
windowActionModeOverlay = true
focusable = true
// Attributes that point to color resources. The first will be from the android:
// namespace, while the second will be in the app: (implicit) namespace.
statusBarColor = android.attr.colorAccent
actionMenuTextColor = android.color.background_light
// Inline widget style. The output will create a separate <style> entry with an
// autogenerated name and correct parent name based on what is defined in the base
// theme for this widget style
actionModeStyle {
background = color.action_mode_background
}
}
}
fun main() {
simpleAppCompat()
for (entry in postInit()) {
println("*** " + entry.key + " ***")
println(entry.value)
println()
}
}
| 0 | Kotlin | 0 | 29 | a866b14b14291e99f82f76b4a1dacc416413c6b1 | 2,216 | nova | Apache License 2.0 |
debop4k-core/src/main/kotlin/debop4k/core/Guardx.kt | debop | 60,844,667 | false | null | /*
* Copyright (c) 2016. <NAME> <<EMAIL>>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("Guardx")
package debop4k.core
import java.lang.IllegalArgumentException
fun <T> firstNotNull(first: T, second: T): T {
if (!areEquals(first, null)) return first
else if (!areEquals(second, null)) return second
else throw IllegalArgumentException("all parameter is null.")
}
fun shouldBe(cond: Boolean): Unit = assert(cond)
inline fun shouldBe(cond: Boolean, msg: () -> Any): Unit = assert(cond, msg)
fun shouldBe(cond: Boolean, fmt: String, vararg args: Any): Unit {
assert(cond) { fmt.format(*args) }
}
fun Any.shouldBeEquals(expected: Any, actualName: String): Unit {
shouldBe(areEquals(this, expected), ShouldBeEquals, actualName, this, expected)
}
fun Any?.shouldBeNull(argName: String): Any? {
shouldBe(this == null, ShouldBeNull, argName)
return this
}
fun Any?.shouldNotBeNull(argName: String): Any? {
shouldBe(this != null, ShouldNotBeNull, argName)
return this
}
fun String?.shouldBeEmpty(argName: String): String? {
shouldBe(this.isNullOrEmpty(), ShouldBeEmptyString, argName)
return this
}
fun String?.shouldNotBeEmpty(argName: String): String? {
shouldBe(!this.isNullOrEmpty(), ShouldBeEmptyString, argName)
return this
}
fun String?.shouldBeWhitespace(argName: String): String? {
shouldBe(this.isNullOrBlank(), ShouldBeWhiteSpace, argName)
return this
}
fun String?.shouldNotBeWhitespace(argName: String): String? {
shouldBe(!this.isNullOrBlank(), ShouldNotBeWhiteSpace, argName)
return this
}
fun <T : Number> T.shouldBePositiveNumber(argName: String): T {
shouldBe(this.toDouble() > 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBePositiveOrZeroNumber(argName: String): T {
shouldBe(this.toDouble() >= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNotPositiveNumber(argName: String): T {
shouldBe(this.toDouble() <= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNegativeNumber(argName: String): T {
shouldBe(this.toDouble() < 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldBeNegativeOrZeroNumber(argName: String): T {
shouldBe(this.toDouble() <= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> T.shouldNotBeNegativeNumber(argName: String): T {
shouldBe(this.toDouble() >= 0.0, ShouldBePositiveNumber, argName)
return this
}
fun <T : Number> shouldBeInRange(value: T, fromInclude: T, toExclude: T, argName: String): Unit {
val v = value.toDouble()
shouldBe(v >= fromInclude.toDouble() && v < toExclude.toDouble(),
ShouldBeInRangeInt, argName, value, fromInclude, toExclude)
}
fun Int.shouldBeInRange(range: IntProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun Long.shouldBeInRange(range: LongProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun <T : Number> T.shouldBeBetween(fromInclude: T, toInclude: T, argName: String): Unit {
val v = this.toDouble()
shouldBe(v >= fromInclude.toDouble() && v <= toInclude.toDouble(),
ShouldBeInRangeDouble, argName, this, fromInclude, toInclude)
}
fun Int.shouldBeBetween(range: IntProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
}
fun Long.shouldBeBetween(range: LongProgression, argName: String): Unit {
shouldBe(range.contains(this),
ShouldBeInRangeInt, argName, this, range.first, range.last)
} | 1 | null | 10 | 40 | 5a621998b88b4d416f510971536abf3bf82fb2f0 | 4,236 | debop4k | Apache License 2.0 |
jicofo/src/test/kotlin/org/jitsi/jicofo/conference/source/SourceSignalingTest.kt | jitsi | 26,950,457 | false | {"Kotlin": 890841, "Java": 222879, "Python": 5315, "Shell": 5215, "Batchfile": 455, "D": 134} | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.jicofo.conference.source
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.shouldBe
import org.jitsi.jicofo.conference.AddOrRemove.Add
import org.jitsi.jicofo.conference.AddOrRemove.Remove
import org.jitsi.jicofo.conference.SourceSignaling
import org.jitsi.utils.MediaType
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
class SourceSignalingTest : ShouldSpec() {
override fun isolationMode() = IsolationMode.InstancePerLeaf
init {
val e1 = "endpoint1"
val e1a = Source(1, MediaType.AUDIO)
val e1v = Source(11, MediaType.VIDEO)
val s1 = ConferenceSourceMap(e1 to EndpointSourceSet(setOf(e1a, e1v))).unmodifiable
val e2 = "endpoint2"
val e2a = Source(2, MediaType.AUDIO)
val e2v = Source(22, MediaType.VIDEO)
val s2 = ConferenceSourceMap(e2 to EndpointSourceSet(setOf(e2a, e2v))).unmodifiable
val e2a2 = Source(222, MediaType.AUDIO)
val e2v2 = Source(2222, MediaType.VIDEO)
val s2new = ConferenceSourceMap(e2 to EndpointSourceSet(setOf(e2a2, e2v2))).unmodifiable
val e3 = "endpoint3"
val e3a = Source(3, MediaType.AUDIO)
val s3 = ConferenceSourceMap(e3 to EndpointSourceSet(e3a)).unmodifiable
context("Queueing remote sources") {
val sourceSignaling = SourceSignaling()
sourceSignaling.update().shouldBeEmpty()
context("Resetting") {
sourceSignaling.addSources(s1)
sourceSignaling.reset(ConferenceSourceMap())
sourceSignaling.update().shouldBeEmpty()
sourceSignaling.addSources(s1)
sourceSignaling.reset(s2)
sourceSignaling.update().shouldBeEmpty()
}
context("Adding a single source") {
sourceSignaling.addSources(s1)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe s1.toMap()
}
}
context("Adding multiple sources") {
// Consecutive source-adds should be merged.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2).toMap()
}
}
context("Adding multiple sources in multiple API calls") {
// Consecutive source-adds should be merged.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2 + s2new).toMap()
}
}
context("Adding and removing sources") {
// A source-remove after a series of source-adds should be a new entry.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.removeSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2).toMap()
}
}
context("Adding, removing, then adding again") {
// A source-add following source-remove should be a new entry.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.removeSources(s2new)
sourceSignaling.addSources(s3)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2 + s3).toMap()
}
}
context("Adding and removing the same source") {
sourceSignaling.addSources(s1)
sourceSignaling.removeSources(s1)
sourceSignaling.update().shouldBeEmpty()
}
sourceSignaling.debugState.shouldBeValidJson()
}
context("Filtering") {
val sourceSignaling = SourceSignaling(audio = true, video = false, stripSimulcast = true)
sourceSignaling.reset(s1 + s2).shouldBe(
ConferenceSourceMap(
e1 to EndpointSourceSet(e1a),
e2 to EndpointSourceSet(e2a)
)
)
sourceSignaling.addSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources shouldBe ConferenceSourceMap(e2 to EndpointSourceSet(e2a2))
}
sourceSignaling.removeSources(s1)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Remove
it[0].sources shouldBe ConferenceSourceMap(e1 to EndpointSourceSet(e1a))
}
sourceSignaling.addSources(s1)
sourceSignaling.removeSources(s1)
sourceSignaling.update().shouldBeEmpty()
sourceSignaling.removeSources(s2)
sourceSignaling.addSources(s2)
sourceSignaling.update().shouldBeEmpty()
}
}
}
fun JSONObject.shouldBeValidJson() = JSONParser().parse(this.toJSONString())
| 20 | Kotlin | 347 | 319 | 743151147d709d637dc93c3e9a9bb05563ad3442 | 6,548 | jicofo | Apache License 2.0 |
app/src/main/java/com/relieve/android/network/data/relieve/UserToken.kt | luxinfity | 159,038,146 | false | {"Kotlin": 106981, "Java": 1126} | package com.relieve.android.network.data.relieve
import com.google.gson.annotations.SerializedName
data class UserToken(
@field:SerializedName("refresh_token")
val refreshToken: String? = null,
@field:SerializedName("expires_in")
val expiresIn: Int? = null,
@field:SerializedName("token")
val token: String? = null,
@field:SerializedName("fcm_token")
val fcmToken: String? = null,
@field:SerializedName("new_token")
val newToken: String? = null
) | 0 | Kotlin | 0 | 0 | 7e0de304db66d60ad4f25846723fe048f7aefbb9 | 464 | relieve_android | MIT License |
app/src/main/java/com/hankkin/reading/ui/person/PersonContract.kt | Hankkin | 143,494,873 | false | null | package com.hankkin.reading.ui.person
import com.hankkin.library.mvp.contract.IBaseViewContract
import com.hankkin.library.mvp.contract.IPresenterContract
/**
* Created by huanghaijie on 2018/5/16.
*/
interface PersonContract {
interface IView : IBaseViewContract {
}
interface IPresenter : IPresenterContract {
}
} | 4 | null | 47 | 407 | 6d61ded0e9e15b473007ae5577c9520b17b454b1 | 338 | Reading | Apache License 2.0 |
mpp-library/src/commonTest/kotlin/org/example/library/createSharedFactory.kt | icerockdev | 210,767,979 | false | null | /*
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package org.example.library
import com.russhwolf.settings.MockSettings
import com.russhwolf.settings.Settings
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.MockRequestHandler
internal fun createSharedFactory(
settings: Settings = MockSettings(),
mock: MockRequestHandler
): SharedFactory {
return SharedFactory(
settings = settings,
antilog = TestAntilog(),
baseUrl = "https://localhost",
httpClientEngine = MockEngine(mock)
)
}
| 8 | Kotlin | 43 | 413 | 1e202b699153a337944ca4b00353ecf3a685884d | 618 | moko-template | Apache License 2.0 |
tabulate-test/src/main/kotlin/io/github/voytech/tabulate/test/TestExportOperationsFactory.kt | voytech | 262,033,710 | false | null | package io.github.voytech.tabulate.test
import io.github.voytech.tabulate.template.TabulationFormat
import io.github.voytech.tabulate.template.context.RenderingContext
import io.github.voytech.tabulate.template.operations.*
import io.github.voytech.tabulate.template.result.ResultProvider
import io.github.voytech.tabulate.template.spi.ExportOperationsProvider
import java.io.OutputStream
import java.util.logging.Logger
class TestRenderingContext: RenderingContext
fun interface AttributedCellTest {
fun test(context: AttributedCell)
}
interface AttributedRowTest {
fun <T> test(context: AttributedRowWithCells<T>) { }
}
fun interface AttributedColumnTest {
fun test(context: AttributedColumn)
}
class TestResultProvider: ResultProvider<TestRenderingContext, Unit> {
override fun outputClass() = Unit.javaClass
override fun flush() {
logger.info("This is fake implementation of ResultProvider flushing results into ether")
}
override fun setOutput(renderingContext: TestRenderingContext, output: Unit) {
logger.info("This is fake implementation of ResultProvider flushing results into ether")
}
companion object {
val logger: Logger = Logger.getLogger(TestResultProvider::class.java.name)
}
}
class OutputStreamTestResultProvider: ResultProvider<TestRenderingContext, OutputStream> {
override fun outputClass() = OutputStream::class.java
override fun setOutput(renderingContext: TestRenderingContext, output: OutputStream) {
logger.info("This is fake implementation of ResultProvider flushing results into OutputStream")
}
override fun flush() {
logger.info("This is fake implementation of ResultProvider flushing results into OutputStream")
}
companion object {
val logger: Logger = Logger.getLogger(OutputStreamTestResultProvider::class.java.name)
}
}
class TestExportOperationsFactory:
ExportOperationsProvider<TestRenderingContext> {
override fun supportsFormat() = TabulationFormat.format("test")
override fun createExportOperations(): AttributedContextExportOperations<TestRenderingContext> = object:
AttributedContextExportOperations<TestRenderingContext> {
override fun renderColumn(renderingContext: TestRenderingContext, context: AttributedColumn) {
columnTest?.test(context)
}
override fun renderRowCell(renderingContext: TestRenderingContext, context: AttributedCell) {
cellTest?.test(context)
}
override fun <T> beginRow(renderingContext: TestRenderingContext, context: AttributedRow<T>) {
println("begin row: $context")
}
override fun <T> endRow(renderingContext: TestRenderingContext, context: AttributedRowWithCells<T>) {
rowTest?.test(context)
}
override fun createTable(renderingContext: TestRenderingContext, context: AttributedTable) {
println("table context: $context")
}
}
override fun createResultProviders(): List<ResultProvider<TestRenderingContext, *>> = listOf(
TestResultProvider(), OutputStreamTestResultProvider()
)
companion object {
@JvmStatic
var cellTest: AttributedCellTest? = null
@JvmStatic
var rowTest: AttributedRowTest? = null
@JvmStatic
var columnTest: AttributedColumnTest? = null
fun clear() {
cellTest = null
rowTest = null
columnTest = null
}
}
override fun getContextClass(): Class<TestRenderingContext> = TestRenderingContext::class.java
override fun createRenderingContext(): TestRenderingContext =
TestRenderingContext()
} | 17 | Kotlin | 0 | 1 | 1ccf2b0f289f23919492fb30d3a5df05490780a1 | 3,720 | tabulate | Apache License 2.0 |
app/src/main/java/com/example/sunnyweather/android/ui/weather/WeatherViewModel.kt | zeroxzp111 | 785,563,668 | false | {"Kotlin": 27946} | package com.example.sunnyweather.android.ui.weather
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.sunnyweather.android.logic.Repository.NetworkRepository
import com.example.sunnyweather.android.logic.Repository.PlaceRepository
import com.example.sunnyweather.android.logic.model.Location
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class WeatherViewModel :ViewModel(){
private val locationLiveData=MutableLiveData<Location>()
var locationLng=""
var locationLat=""
var placeName=""
val weatherLiveData=Transformations.switchMap(locationLiveData){location->
NetworkRepository.refreshWeather(location.lng,location.lat)
}
fun refreshWeather(lng:String,lat:String){
locationLiveData.value=Location(lng,lat)
}
} | 0 | Kotlin | 0 | 0 | 30593376bf7c740ac1f84c7e7ffefcae3dfe7705 | 953 | SunnyWeather | Apache License 2.0 |
ui/src/main/java/com/semicolon/shakeit/feature/editprofile/EditProfileViewModel.kt | shake-it-shake | 473,043,498 | false | {"Kotlin": 158886} | package com.semicolon.shakeit.feature.editprofile
import com.semicolon.domain.entity.user.EditProfileEntity
import com.semicolon.domain.exception.BadRequestException
import com.semicolon.domain.exception.ConflictException
import com.semicolon.domain.usecase.user.EditProfileUseCase
import com.semicolon.domain.usecase.user.FetchMyProfileUseCase
import com.semicolon.shakeit.base.BaseViewModel
import com.semicolon.shakeit.util.UrlConverter
import dagger.hilt.android.lifecycle.HiltViewModel
import java.io.File
import javax.inject.Inject
@HiltViewModel
class EditProfileViewModel @Inject constructor(
private val fetchMyProfileUseCase: FetchMyProfileUseCase,
private val editProfileUseCase: EditProfileUseCase,
private val urlConverter: UrlConverter
) : BaseViewModel<EditProfileViewModel.Event>() {
fun fetchMyProfile() = execute(
job = {
val profile = fetchMyProfileUseCase.execute()
Event.FetchProfileEvent.Success(
urlConverter.convert(profile.imagePath),
profile.nickname
)
},
onSuccess = { emitEvent(it) },
onFailure = { emitEvent(Event.FetchProfileEvent.Failure) }
)
fun editProfile(image: File, nickname: String) = execute(
job = { editProfileUseCase.execute(EditProfileEntity(image, nickname)) },
onSuccess = { emitEvent(Event.EditProfileEvent.Success) },
onFailure = {
when (it) {
is BadRequestException -> emitEvent(Event.EditProfileEvent.WrongProfile)
is ConflictException -> emitEvent(Event.EditProfileEvent.ConflictNickname)
else -> emitEvent(Event.EditProfileEvent.UnknownError)
}
}
)
sealed class Event {
sealed class FetchProfileEvent : Event() {
data class Success(val image: File, val nickname: String) : FetchProfileEvent()
object Failure : FetchProfileEvent()
}
sealed class EditProfileEvent : Event() {
object Success : EditProfileEvent()
object WrongProfile : EditProfileEvent()
object ConflictNickname : EditProfileEvent()
object UnknownError : EditProfileEvent()
}
}
} | 0 | Kotlin | 0 | 4 | 6c8c7278bc7839514f414086eef7509c4fca8b8c | 2,243 | shake-it-android | MIT License |
src/main/kotlin/org/rust/lang/core/macros/MappedText.kt | intellij-rust | 42,619,487 | false | {"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.util.SmartList
data class MappedText(val text: String, val ranges: RangeMap) {
companion object {
val EMPTY: MappedText = MappedText("", RangeMap.EMPTY)
fun single(text: String, srcOffset: Int): MappedText {
return if (text.isNotEmpty()) {
MappedText(
text,
RangeMap.from(SmartList(MappedTextRange(srcOffset, 0, text.length)))
)
} else {
EMPTY
}
}
}
}
class MutableMappedText private constructor(
private val sb: StringBuilder,
private val ranges: MutableList<MappedTextRange> = mutableListOf()
) {
constructor(capacity: Int) : this(StringBuilder(capacity))
val length: Int get() = sb.length
val text: CharSequence get() = sb
fun appendUnmapped(text: CharSequence) {
sb.append(text)
}
fun appendMapped(text: CharSequence, srcOffset: Int) {
if (text.isNotEmpty()) {
ranges.mergeAdd(MappedTextRange(srcOffset, sb.length, text.length))
sb.append(text)
}
}
fun toMappedText(): MappedText = MappedText(sb.toString(), RangeMap.from(SmartList(ranges)))
override fun toString(): String {
return sb.toString()
}
}
| 1,841 | Kotlin | 380 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 1,436 | intellij-rust | MIT License |
firebase-installations/src/androidMain/kotlin/dev/gitlive/firebase/installations/installations.kt | GitLiveApp | 213,915,094 | false | {"Kotlin": 660226, "Ruby": 18024, "JavaScript": 469} | package dev.gitlive.firebase.installations
import dev.gitlive.firebase.Firebase
import dev.gitlive.firebase.FirebaseApp
import kotlinx.coroutines.tasks.await
actual val Firebase.installations
get() = FirebaseInstallations(com.google.firebase.installations.FirebaseInstallations.getInstance())
actual fun Firebase.installations(app: FirebaseApp)
= FirebaseInstallations(com.google.firebase.installations.FirebaseInstallations.getInstance(app.android))
actual class FirebaseInstallations internal constructor(val android: com.google.firebase.installations.FirebaseInstallations) {
actual suspend fun delete() = android.delete().await().let { }
actual suspend fun getId(): String = android.id.await()
actual suspend fun getToken(forceRefresh: Boolean): String =
android.getToken(forceRefresh).await().token
}
actual typealias FirebaseInstallationsException = com.google.firebase.installations.FirebaseInstallationsException
| 83 | Kotlin | 147 | 969 | e54c12e5f0b62c6b1878fdba966d6bb4b94cb676 | 962 | firebase-kotlin-sdk | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.