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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tmp/arrays/youTrackTests/1526.kt | DaniilStepanov | 228,623,440 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | // Original bug: KT-11825
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
open class TypeLiteral<T> {
val type: Type
get() = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
}
// normal type argument works fine
inline fun <reified T> typeLiteral(): TypeLiteral<T> = object : TypeLiteral<T>() {}
// composing T into List<T> loses reification
inline fun <reified T> listTypeLiteral() = typeLiteral<List<T>>()
fun main(args: Array<String>) {
// prints "java.lang.String" as expected
println(typeLiteral<String>().type)
// prints "java.util.List<? extends T>" instead of "java.util.List<? extends java.lang.String>"
println(listTypeLiteral<String>().type)
}
| 1 | null | 11 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 737 | bbfgradle | Apache License 2.0 |
Slices/Inspector/app/src/main/java/com/commonsware/android/slice/inspector/TabAdapter.kt | commonsguy | 3,695,744 | false | null | /*
Copyright (c) 2018 CommonsWare, 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.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.slice.inspector
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.slice.widget.SliceView
class TabAdapter(fm: FragmentManager, private val titles: Array<String>) : FragmentPagerAdapter(fm) {
override fun getCount() = 4
override fun getPageTitle(position: Int) = titles[position]
override fun getItem(position: Int): Fragment =
when (position) {
0 -> SliceFragment.newInstance(SliceView.MODE_SHORTCUT)
1 -> SliceFragment.newInstance(SliceView.MODE_SMALL)
2 -> SliceFragment.newInstance(SliceView.MODE_LARGE)
else -> InspectorFragment()
}
} | 0 | null | 3855 | 5,314 | f2ffeb687d002f4a41b52a6ef5bb2580eb6a4ed6 | 1,397 | cw-omnibus | Apache License 2.0 |
app/src/main/java/com/dan/perspective/EditPerspectiveImageView.kt | ETS-Android2 | 497,347,729 | false | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "INI": 1, "Markdown": 1, "Batchfile": 1, "Text": 2, "Ignore List": 3, "XML": 23, "AIDL": 2, "Java": 108, "Kotlin": 11, "Proguard": 1, "Python": 1} | package com.dan.perspective
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class PerspectivePoints(
val leftTop: PointF = PointF(),
val leftBottom: PointF = PointF(),
val rightTop: PointF = PointF(),
val rightBottom: PointF = PointF()
) {
fun set( points: PerspectivePoints ) {
leftTop.set(points.leftTop)
leftBottom.set(points.leftBottom)
rightTop.set(points.rightTop)
rightBottom.set(points.rightBottom)
}
}
private class ViewTransform(bitmapWidth: Int = 1, bitmapHeight: Int = 1, viewRect: RectF = RectF()) {
private val scale = PointF(1f, 1f)
private val delta = PointF( 0f, 0f)
init {
set( bitmapWidth, bitmapHeight, viewRect )
}
fun set( bitmapWidth: Int, bitmapHeight: Int, viewRect: RectF ) {
if (bitmapWidth <= 0 || bitmapHeight <= 0) {
delta.set( 0f, 0f )
scale.set( 1f, 1f )
} else {
delta.set( viewRect.left, viewRect.top )
scale.set( viewRect.width() / bitmapWidth, viewRect.height() / bitmapHeight )
}
}
fun mapToView( point: PointF ): PointF {
return PointF(
delta.x + point.x * scale.x,
delta.y + point.y * scale.y
)
}
fun mapToView( points: PerspectivePoints ): PerspectivePoints {
return PerspectivePoints(
mapToView( points.leftTop ),
mapToView( points.leftBottom ),
mapToView( points.rightTop ),
mapToView( points.rightBottom )
)
}
fun mapToBitmap( point: PointF ): PointF {
return PointF(
(point.x - delta.x) / scale.x,
(point.y - delta.y) / scale.y,
)
}
fun mapToBitmap( points: PerspectivePoints ): PerspectivePoints {
return PerspectivePoints(
mapToBitmap( points.leftTop ),
mapToBitmap( points.leftBottom ),
mapToBitmap( points.rightTop ),
mapToBitmap( points.rightBottom )
)
}
}
class EditPerspectiveImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TouchImageView(context, attrs, defStyleAttr) {
companion object {
const val BORDER = 5 //percent
const val POINT_RADIUS = 15 // dp
const val TRACKED_POINT_RADIUS = 20 // dp
const val LINE_WIDTH = 5 //dp
const val MIN_POINT_DISTANCE_TO_TRACK = 20 //dp
const val LOCK_NONE = 0
const val LOCK_HORIZONTAL = 1
const val LOCK_VERTICAL = 2
fun dpToPixels( value: Int ): Float {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value.toFloat(),
Resources.getSystem().displayMetrics)
}
}
private val transform = ViewTransform()
private val _perspectivePoints = PerspectivePoints()
private var trackedPoint: PointF? = null
private var trackedViewPoint = PointF()
private var trackedAllowedRect = RectF()
private val trackedOldPosition = PointF()
private val paint = Paint()
private var onPerspectiveChanged: (()->Unit)? = null
private var onEditStart: (()->Unit)? = null
private var onEditEnd: (()->Unit)? = null
var lock = LOCK_NONE
var perspectivePoints: PerspectivePoints
get() = _perspectivePoints
set(points) {
_perspectivePoints.set(points)
invalidate()
}
fun setOnPerspectiveChanged( listener: (()->Unit)? ) {
onPerspectiveChanged = listener
}
fun setOnEditStart( listener: (()->Unit)? ) {
onEditStart = listener
}
fun setOnEditEnd( listener: (()->Unit)? ) {
onEditEnd = listener
}
override fun setBitmap(bitmap: Bitmap? ) {
super.setBitmap(bitmap)
resetPoints()
}
fun resetPoints() {
val bitmap = super.getBitmap() ?: return
val left = bitmap.width * BORDER.toFloat() / 100
val right = bitmap.width - left
val top = bitmap.height * BORDER.toFloat() / 100
val bottom = bitmap.height - top
_perspectivePoints.leftTop.set(left, top)
_perspectivePoints.leftBottom.set(left, bottom)
_perspectivePoints.rightTop.set(right, top)
_perspectivePoints.rightBottom.set(right, bottom)
invalidate()
onPerspectiveChanged?.invoke()
}
private fun drawPoint( point: PointF, radius: Float, canvas: Canvas, paint: Paint ) {
canvas.drawCircle( point.x, point.y, radius, paint )
}
private fun calculateCy( Ax: Float, Ay: Float, Bx: Float, By: Float, Cx:Float ): Float =
Ay + (By - Ay) * (Cx - Ax) / (Bx - Ax)
private fun drawLine( pointA: PointF, pointB: PointF, canvas: Canvas, paint: Paint, viewRect: RectF ) {
val pointFrom: PointF
val pointTo: PointF
val isHorizontal = abs(pointA.x - pointB.x) > abs(pointA.y - pointB.y)
if (isHorizontal) {
pointFrom = PointF(
viewRect.left,
calculateCy( pointA.x, pointA.y, pointB.x, pointB.y, viewRect.left )
)
pointTo = PointF(
viewRect.right,
calculateCy( pointA.x, pointA.y, pointB.x, pointB.y, viewRect.right )
)
} else {
pointFrom = PointF(
calculateCy( pointA.y, pointA.x, pointB.y, pointB.x, viewRect.top ),
viewRect.top
)
pointTo = PointF(
calculateCy( pointA.y, pointA.x, pointB.y, pointB.x, viewRect.bottom ),
viewRect.bottom
)
}
canvas.drawLine( pointFrom.x, pointFrom.y, pointTo.x, pointTo.y, paint )
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (null == canvas) return
val bitmap = super.getBitmap() ?: return
val viewRect = super.viewRect
transform.set( bitmap.width, bitmap.height, viewRect )
val viewPoints = transform.mapToView( _perspectivePoints )
paint.strokeCap = Paint.Cap.ROUND
paint.style = Paint.Style.FILL_AND_STROKE
paint.strokeWidth = dpToPixels(LINE_WIDTH)
paint.color = Color.argb( 128, 255, 0, 0 )
drawLine( viewPoints.leftTop, viewPoints.leftBottom, canvas, paint, viewRect )
drawLine( viewPoints.leftTop, viewPoints.rightTop, canvas, paint, viewRect )
drawLine( viewPoints.rightTop, viewPoints.rightBottom, canvas, paint, viewRect )
drawLine( viewPoints.leftBottom, viewPoints.rightBottom, canvas, paint, viewRect )
val radius = dpToPixels(POINT_RADIUS)
paint.style = Paint.Style.FILL
paint.color = Color.argb( 128, 0, 0, 255 )
val trackedPoint = this.trackedPoint
if (_perspectivePoints.leftTop != trackedPoint) drawPoint( viewPoints.leftTop, radius, canvas, paint )
if (_perspectivePoints.leftBottom != trackedPoint) drawPoint( viewPoints.leftBottom, radius, canvas, paint )
if (_perspectivePoints.rightTop != trackedPoint) drawPoint( viewPoints.rightTop, radius, canvas, paint )
if (_perspectivePoints.rightBottom != trackedPoint) drawPoint( viewPoints.rightBottom, radius, canvas, paint )
if (null != trackedPoint) {
val trackedViewPoint = transform.mapToView(trackedPoint)
val radiusTracked = dpToPixels(TRACKED_POINT_RADIUS)
paint.style = Paint.Style.STROKE
drawPoint( trackedViewPoint, radiusTracked, canvas, paint )
}
}
private fun distance( pointA: PointF, pointB: PointF ): Float =
PointF.length( pointA.x - pointB.x, pointA.y - pointB.y )
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (null == event) return true
val bitmap = super.getBitmap() ?: return true
when( event.action ) {
MotionEvent.ACTION_DOWN -> {
if (null == trackedPoint) {
transform.set(bitmap.width, bitmap.height, viewRect)
val screenPoint = PointF(event.x, event.y)
val viewPoints = transform.mapToView(_perspectivePoints)
val minDistance = dpToPixels(MIN_POINT_DISTANCE_TO_TRACK)
trackedOldPosition.set(event.x, event.y)
when {
distance(viewPoints.leftTop, screenPoint) < minDistance -> {
trackedPoint = _perspectivePoints.leftTop
trackedViewPoint.set(viewPoints.leftTop)
trackedAllowedRect.set(
viewRect.left,
viewRect.top,
min(viewPoints.rightTop.x, viewPoints.rightBottom.x) - minDistance,
min(viewPoints.leftBottom.y, viewPoints.rightBottom.y) - minDistance
)
}
distance(viewPoints.leftBottom, screenPoint) < minDistance -> {
trackedPoint = _perspectivePoints.leftBottom
trackedViewPoint.set(viewPoints.leftBottom)
trackedAllowedRect.set(
viewRect.left,
max(viewPoints.leftTop.y, viewPoints.rightTop.y) + minDistance,
min(viewPoints.rightTop.x, viewPoints.rightBottom.x) - minDistance,
viewRect.bottom
)
}
distance(viewPoints.rightTop, screenPoint) < minDistance -> {
trackedPoint = _perspectivePoints.rightTop
trackedViewPoint.set(viewPoints.rightTop)
trackedAllowedRect.set(
max(viewPoints.leftTop.x, viewPoints.leftBottom.x) + minDistance,
viewRect.top,
viewRect.right,
min(viewPoints.leftBottom.y, viewPoints.rightBottom.y) - minDistance
)
}
distance(viewPoints.rightBottom, screenPoint) < minDistance -> {
trackedPoint = _perspectivePoints.rightBottom
trackedViewPoint.set(viewPoints.rightBottom)
trackedAllowedRect.set(
max(viewPoints.leftTop.x, viewPoints.leftBottom.x) + minDistance,
max(viewPoints.leftTop.y, viewPoints.rightTop.y) + minDistance,
viewRect.right,
viewRect.bottom
)
}
}
if (null != trackedPoint) onEditStart?.invoke()
}
}
MotionEvent.ACTION_MOVE -> {
val trackedPoint = this.trackedPoint
if (null != trackedPoint) {
transform.set(bitmap.width, bitmap.height, viewRect)
val dx = if (LOCK_HORIZONTAL == lock) 0f else event.x - trackedOldPosition.x
val dy = if (LOCK_VERTICAL == lock) 0f else event.y - trackedOldPosition.y
trackedViewPoint.offset( dx, dy )
if (trackedViewPoint.x < trackedAllowedRect.left) trackedViewPoint.x = trackedAllowedRect.left
if (trackedViewPoint.x > trackedAllowedRect.right) trackedViewPoint.x = trackedAllowedRect.right
if (trackedViewPoint.y < trackedAllowedRect.top) trackedViewPoint.y = trackedAllowedRect.top
if (trackedViewPoint.y > trackedAllowedRect.bottom) trackedViewPoint.y = trackedAllowedRect.bottom
trackedPoint.set( transform.mapToBitmap(trackedViewPoint) )
trackedOldPosition.set(event.x, event.y)
invalidate()
onPerspectiveChanged?.invoke()
return true
}
}
MotionEvent.ACTION_UP -> {
if (null != trackedPoint) {
trackedPoint = null
onEditEnd?.invoke()
return true
}
}
}
if (null != trackedPoint) {
Log.i("EDIT", "Track is ON")
return true
}
return super.onTouchEvent(event)
}
} | 1 | null | 1 | 1 | f7bce91c5e9d31fc959873eed319b69b0f8f2294 | 13,035 | Perspective | MIT License |
src/main/kotlin/org/neo4j/graphql/GraphQLContext.kt | glevine | 104,232,440 | false | null | package org.neo4j.graphql
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.logging.Log
class GraphQLContext(val db : GraphDatabaseService, private val log : Log? = null, val parameters: Map<String,Any> = emptyMap(), val backLog : MutableMap<String,Any> = mutableMapOf()) {
fun store(key : String, value : Any) {
backLog[key]=value
}
}
| 1 | null | 1 | 1 | d006a734dca4328346c895a21e5fdc4c6c688ca3 | 367 | neo4j-graphql | Apache License 2.0 |
hencoder/src/main/java/com/pwj/hencoder/MainHenCoderActivity.kt | a-pwj | 255,207,003 | false | {"Gradle": 20, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 20, "Batchfile": 1, "Markdown": 5, "Proguard": 14, "XML": 252, "Java": 74, "INI": 13, "Kotlin": 133, "JSON": 2, "C++": 1, "CMake": 1, "C": 42, "Gradle Kotlin DSL": 1, "Groovy": 1} | package com.pwj.hencoder
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainHenCoderActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_hen_coder)
}
} | 0 | C | 0 | 0 | 6d6411916d1528b300c6c6ddf9932a10b41aa3fb | 318 | Record | Apache License 2.0 |
core-android/src/main/java/com/clipfinder/core/android/util/ext/BottomNavigationViewExt.kt | tosoba | 133,674,301 | false | {"Gradle": 33, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 31, "Batchfile": 1, "Kotlin": 409, "Proguard": 24, "XML": 176, "Java": 2, "INI": 4} | package com.clipfinder.core.android.util.ext
import com.google.android.material.bottomnavigation.BottomNavigationView
fun BottomNavigationView.checkItem(id: Int) {
menu.findItem(id)?.isChecked = true
}
fun BottomNavigationView.setHeight(height: Int) {
val params = this.layoutParams
params.height = height
this.layoutParams = params
}
| 1 | null | 1 | 1 | 84ae309c8c059308c16902ee43b0cdfd2740794c | 354 | ClipFinder | MIT License |
src/main/kotlin/de/mcc/simra/services/osm/coloring/runner/Runner.kt | simra-project | 388,140,915 | false | null | package de.mcc.simra.services.osm.coloring.runner
import de.mcc.simra.services.osm.coloring.config.OsmColoringConfig
import de.mcc.simra.services.osm.coloring.services.ElasticIndexService
import de.mcc.simra.services.osm.coloring.services.ReaderService
import de.mcc.simra.services.osm.coloring.services.TransformerService
import kotlinx.coroutines.*
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component
private val LOG: Logger = LogManager.getLogger()
@ExperimentalCoroutinesApi
@Profile("!test") // do not run during tests
@Component
class Runner(
val osmColoringConfig: OsmColoringConfig,
val readerService: ReaderService,
val transformerService: TransformerService,
val elasticIndexService: ElasticIndexService
) : ApplicationRunner {
override fun run(args: ApplicationArguments) {
LOG.info("Reading files from ${osmColoringConfig.geoJsonDir.absolutePath}")
// to have multiple threads available
runBlocking(Dispatchers.Default + CoroutineName("Runner")) {
// start in reverse order to prevent backlog
launch { elasticIndexService.indexIncomingElasticSegmentsBlocking() }
launch { transformerService.transformIncomingGeoFeaturesBlocking() }
launch { readerService.processExistingFiles() }
LOG.info("Started all coroutines")
}
}
} | 0 | Kotlin | 0 | 1 | a47852654fd31a1796910d08fbda3f82d7f27c1a | 1,587 | osm-coloring-service | Apache License 2.0 |
mobile_app1/module994/src/main/java/module994packageKt0/Foo457.kt | uber-common | 294,831,672 | false | null | package module994packageKt0;
annotation class Foo457Fancy
@Foo457Fancy
class Foo457 {
fun foo0(){
module994packageKt0.Foo456().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 237 | android-build-eval | Apache License 2.0 |
mobile_app1/module994/src/main/java/module994packageKt0/Foo457.kt | uber-common | 294,831,672 | false | null | package module994packageKt0;
annotation class Foo457Fancy
@Foo457Fancy
class Foo457 {
fun foo0(){
module994packageKt0.Foo456().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 237 | android-build-eval | Apache License 2.0 |
gremlin-kore/src/main/kotlin/org/apache/tinkerpop4/gremlin/process/computer/ComputerResult.kt | phreed | 449,920,526 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.tinkerpop4.gremlin.process.computer
import org.apache.tinkerpop4.gremlin.structure.Graph
/**
* The result of the [GraphComputer]'s computation. This is returned in a `Future` by
* [GraphComputer.submit]. A GraphComputer computation yields two things: an updated view of the computed on
* [Graph] and any computational sideEffects called [Memory].
*
* @author <NAME> (http://markorodriguez.com)
*/
interface ComputerResult : AutoCloseable {
/**
* Get the [Graph] computed as determined by [GraphComputer.Persist] and [GraphComputer.ResultGraph].
*
* @return The computed graph
*/
fun graph(): Graph?
/**
* Get the GraphComputer's computational sideEffects known as [Memory].
*
* @return the computed memory
*/
fun memory(): Memory?
/**
* Close the computed [GraphComputer] result. The semantics of "close" differ depending on the underlying implementation.
* In general, when a [ComputerResult] is closed, the computed values are no longer available to the user.
*
* @throws Exception
*/
@Override
@Throws(Exception::class)
fun close()
} | 4 | null | 1 | 1 | cb6805d686e9a27caa8e597b0728a50a63dc9092 | 1,968 | tinkerpop4 | Apache License 2.0 |
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRDiffVirtualFile.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.collaboration.file.codereview.CodeReviewDiffVirtualFile
import com.intellij.collaboration.ui.codereview.CodeReviewAdvancedSettings
import com.intellij.diff.impl.DiffEditorViewer
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.vcs.editor.ComplexPathVirtualFileSystem
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContextRepository
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.ui.diff.GHPRDiffService
internal data class GHPRDiffVirtualFile(private val fileManagerId: String,
private val project: Project,
private val repository: GHRepositoryCoordinates,
private val pullRequest: GHPRIdentifier)
: CodeReviewDiffVirtualFile(getFileName(pullRequest)) {
override fun getFileSystem(): ComplexPathVirtualFileSystem<*> = GHPRVirtualFileSystem.getInstance()
override fun getPath(): String = (fileSystem as GHPRVirtualFileSystem)
.getPath(fileManagerId, project, repository, pullRequest, true)
override fun getPresentablePath(): String = getPresentablePath(repository, pullRequest)
override fun getPresentableName(): String = GithubBundle.message("pull.request.diff.editor.title", pullRequest.number)
override fun isValid(): Boolean = isFileValid(fileManagerId, project, repository)
override fun createViewer(project: Project): DiffEditorViewer {
val processor = if (CodeReviewAdvancedSettings.isCombinedDiffEnabled()) {
project.service<GHPRDiffService>().createCombinedDiffProcessor(repository, pullRequest)
}
else {
project.service<GHPRDiffService>().createDiffRequestProcessor(repository, pullRequest)
}
processor.context.putUserData(DiffUserDataKeysEx.COMBINED_DIFF_TOGGLE, CodeReviewAdvancedSettings.CodeReviewCombinedDiffToggle)
return processor
}
}
private fun isFileValid(fileManagerId: String, project: Project, repository: GHRepositoryCoordinates): Boolean {
val dataContext = GHPRDataContextRepository.getInstance(project).findContext(repository) ?: return false
return dataContext.filesManager.id == fileManagerId
}
private fun getPresentablePath(repository: GHRepositoryCoordinates, pullRequest: GHPRIdentifier) =
"${repository.toUrl()}/pulls/${pullRequest.number}.diff"
private fun getFileName(pullRequest: GHPRIdentifier): String = "#${pullRequest.number}.diff"
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 2,903 | intellij-community | Apache License 2.0 |
app/src/main/java/com/belatrix/authentication/ui/MainActivity.kt | Luistlvr1989 | 92,952,232 | false | null | package com.belatrix.authentication.ui
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.belatrix.authentication.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 0 | Kotlin | 0 | 0 | 2aaff3ea43e6c0fb7f9bd644dced2016ddd26658 | 351 | authentication | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/ui/lists/BaseAdapter.kt | covid-be-app | 281,650,940 | false | null | package de.rki.coronawarnapp.ui.lists
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T : BaseAdapter.VH> : RecyclerView.Adapter<T>() {
@CallSuper
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): T {
return onCreateBaseVH(parent, viewType)
}
abstract fun onCreateBaseVH(parent: ViewGroup, viewType: Int): T
@CallSuper
final override fun onBindViewHolder(holder: T, position: Int) {
onBindBaseVH(holder, position)
}
abstract fun onBindBaseVH(holder: T, position: Int)
abstract class VH(@LayoutRes layoutRes: Int, parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(layoutRes, parent, false)
) {
val context: Context = parent.context
}
}
| 13 | null | 10 | 55 | d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b | 980 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/vitorpamplona/amethyst/ui/dal/UserProfileZapsFeedFilter.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.dal
import com.vitorpamplona.amethyst.model.User
import com.vitorpamplona.amethyst.service.model.zaps.UserZaps
import com.vitorpamplona.amethyst.ui.screen.ZapReqResponse
class UserProfileZapsFeedFilter(val user: User) : FeedFilter<ZapReqResponse>() {
override fun feedKey(): String {
return user.pubkeyHex
}
override fun feed(): List<ZapReqResponse> {
return UserZaps.forProfileFeed(user.zaps)
}
}
| 131 | null | 123 | 857 | c7a3a74d5a4adf2cea315a345dadaf9abc63f416 | 472 | amethyst | MIT License |
collect_app/src/main/java/org/odk/collect/android/projects/ProjectCreator.kt | nchenari | 375,854,035 | true | {"Java Properties": 2, "Gradle": 18, "Shell": 3, "YAML": 2, "INI": 14, "Markdown": 15, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 14, "Text": 1, "JSON": 3, "Java": 987, "Kotlin": 145, "XML": 456, "HTML": 1, "JavaScript": 1, "Proguard": 2, "XSLT": 6} | package org.odk.collect.android.projects
import org.json.JSONException
import org.json.JSONObject
import org.odk.collect.android.configure.SettingsImporter
import org.odk.collect.android.preferences.keys.GeneralKeys
import org.odk.collect.projects.Project
import org.odk.collect.projects.ProjectsRepository
import java.net.URL
class ProjectCreator(
private val projectImporter: ProjectImporter,
private val projectsRepository: ProjectsRepository,
private val currentProjectProvider: CurrentProjectProvider,
private val settingsImporter: SettingsImporter,
) {
fun createNewProject(settingsJson: String): Boolean {
val newProject = getNewProject(settingsJson)
val savedProject = projectImporter.importNewProject(newProject)
val settingsImportedSuccessfully = settingsImporter.fromJSON(settingsJson, savedProject.uuid)
return if (settingsImportedSuccessfully) {
if (projectsRepository.getAll().size == 1) {
currentProjectProvider.setCurrentProject(savedProject.uuid)
}
true
} else {
projectsRepository.delete(savedProject.uuid)
false
}
}
private fun getNewProject(settingsJson: String): Project.New {
val urlString = try {
JSONObject(settingsJson)
.getJSONObject("general")
.getString(GeneralKeys.KEY_SERVER_URL)
} catch (e: JSONException) {
""
}
var projectName = ""
var projectIcon = ""
try {
val url = URL(urlString)
projectName = url.host
projectIcon = projectName.first().toUpperCase().toString()
} catch (e: Exception) {
}
return Project.New(projectName, projectIcon, "#3e9fcc")
}
}
| 0 | Java | 0 | 0 | 3b5f08e205392ce38bf1abe1a18804d4a59b2e86 | 1,813 | collect | Apache License 2.0 |
src/main/kotlin/edu/csh/chase/jschema/models/ConstraintWrapper.kt | chaseberry | 111,830,495 | false | null | package edu.csh.chase.jschema.models
import edu.csh.chase.jschema.models.constraints.Constraint
import edu.csh.chase.jschema.parser.ConstraintParser
import edu.csh.chase.jschema.parser.ConstraintSerializer
class ConstraintWrapper<T : Constraint<*>>(val name: String, val clazz: Class<T>, parser: ConstraintParser<T>, serializer: ConstraintSerializer<T>) {
} | 0 | Kotlin | 0 | 0 | cbd208adae5ec8e6bf20e1d9b0eaaef771216e6b | 359 | jschema | MIT License |
samples/messenger/playground/src/main/java/com/revolut/kompot/sample/playground/flows/demo/DemoFlowContract.kt | revolut-mobile | 488,970,565 | false | null | package com.revolut.kompot.sample.playground.flows.demo
import com.revolut.kompot.common.IOData
import com.revolut.kompot.navigable.flow.FlowModel
import com.revolut.kompot.navigable.flow.FlowState
import com.revolut.kompot.navigable.flow.FlowStep
import kotlinx.parcelize.Parcelize
interface DemoFlowContract {
interface FlowModelApi : FlowModel<Step, IOData.EmptyOutput>
@Parcelize
class State : FlowState
sealed class Step : FlowStep {
@Parcelize
object Step1 : Step()
@Parcelize
object Step2: Step()
}
} | 0 | Kotlin | 5 | 91 | 1ea49978cd64b74aeac41d1d0bcce68bbcce9d6c | 566 | kompot | Apache License 2.0 |
src/main/kotlin/co/edu/uniquindio/compiladores/lexico/Token.kt | jenunezb | 542,360,188 | false | {"Kotlin": 503857, "Java": 255} | package co.edu.uniquindio.compiladores.lexico
class Token(var lexema:String, var categoria: Categoria, var fila:Int, var columna:Int) {
override fun toString(): String {
return "Token(lexema='$lexema', categoria=$categoria, fila=$fila, columna=$columna)"
}
fun getJavaCode(): String {
if (categoria == Categoria.IDENTIFICADOR_TIPO_DECIMAL) {
return "double"
}
if (categoria == Categoria.IDENTIFICADOR_TIPO_CADENA) {
return "String"
}
if (categoria == Categoria.IDENTIFICADOR_TIPO_ENTERO) {
return "int"
}
if (categoria == Categoria.IDENTIFICADOR_TIPO_CARACTER) {
return "char"
}
if (categoria == Categoria.IDENTIFICADOR_TIPO_BOOLEANO) {
return "boolean"
}
if (categoria == Categoria.PALABRA_RESERVADA_VACIO) {
return " "
}
if (categoria == Categoria.IDENTIFICADOR_VARIABLE) {
var retorno = ""
for (s in lexema) {
if (s != '#' && s != '>') {
retorno += s
}
}
return retorno
}
if (categoria == Categoria.IDENTIFICADOR_DE_METODOS) {
var minu = lexema.toLowerCase()
var retorno = ""
for (s in minu) {
if (s.isLetter()) {
retorno += s
}
}
return retorno
}
if (categoria == Categoria.OPERADOR_RELACIONAL) {
if (lexema == "|∞") {
return "!="
}
if (lexema == "∞") {
return "="
}
if (lexema == "∞∞") {
return "=="
}
if (lexema == "+") {
return ">"
}
if (lexema == "-") {
return "<"
}
if (lexema == "+∞") {
return ">="
}
if (lexema == "-∞") {
return "<="
}
}
if (categoria == Categoria.CADENA) {
return lexema.replace("%", "\"")
}
if (categoria == Categoria.CARACTER) {
return lexema.replace("/", "\'")
}
if (categoria == Categoria.PALABRA_RESERVADA_DECISIONES) {
if (lexema == "Yes") {
return "if"
} else {
if (lexema == "Not") {
return "else"
}
}
}
if (categoria == Categoria.OPERADOR_ARITMETICO) {
if (lexema == "S++") {
return "+"
}
if (lexema == "R--") {
return "-"
}
if (lexema == "mod%") {
return "%"
}
if (lexema == "m#") {
return "*"
}
if (lexema == "d//") {
return "/"
}
}
if (categoria == Categoria.OPERADOR_ASIGNACION) {
if (lexema == "S++∞") {
return "+="
}
if (lexema == "R--∞") {
return "-="
}
if (lexema == "m#∞") {
return "*="
}
if (lexema == "mod%∞") {
return "%="
}
if (lexema == "d//∞") {
return "/="
}
if (lexema == "∞") {
return "="
}
}
if (categoria == Categoria.OPERADOR_LOGICO) {
if (lexema == "YY") {
return "&&"
}
if (lexema == "O") {
return "||"
}
}
if (categoria == Categoria.ENTERO) {
var cod = lexema
var cod1 = ""
for (s in cod) {
if (s.isDigit()) {
cod1 += s
}
}
return cod1
}
if (categoria == Categoria.DECIMAL) {
var cod = lexema
var cod1 = cod.replace(",", ".")
var cod2 = ""
for (s in cod1) {
if (s.isDigit() || s == '.') {
cod2 += s
}
}
return cod2
}
if (categoria == Categoria.IDENTIFICADOR_TIPO_BOOLEANO) {
if (lexema == "On") {
return "true"
}
if (lexema == "Off") {
return "false"
}
}
if (categoria == Categoria.PALABRA_RESERVADA_CONTINUAR) {
return "continue"
}
if (categoria == Categoria.PALABRA_RESERVADA_ROMPER) {
return "breack"
}
if (categoria == Categoria.IDENTIFICADOR_ARREGLO) {
var retorno = ""
for (s in lexema) {
if (s != '#' && s != '>') {
retorno += s
}
}
return retorno
}
return lexema
}
}
| 0 | Kotlin | 0 | 0 | 4f9571e6c8679cf395e33cc4ff057e3c142382d5 | 5,087 | compiladores | Creative Commons Attribution 2.0 Generic |
src/main/kotlin/tech/egglink/bot/internal/BotLoginSolver.kt | EggPixel | 511,362,374 | false | null | package tech.egglink.bot.internal
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.mamoe.mirai.Bot
import net.mamoe.mirai.network.CustomLoginFailedException
import net.mamoe.mirai.utils.LoginSolver
import tech.egglink.bot.untils.Untils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class BotLoginSolver : LoginSolver() {
private var threads: Thread? = null
private val loginCancelException: CustomLoginFailedException =
object : CustomLoginFailedException(true, "用户终止登录") {}
private val loginErrorException: CustomLoginFailedException =
object : CustomLoginFailedException(true, "登录时出现严重错误") {}
/**
* @param bot 机器人实例
* @param data 图片内容
* @return 验证码结果
*/
override suspend fun onSolvePicCaptcha(bot: Bot, data: ByteArray): String? {
deviceVerifyCanceled[bot] = false
// 建立机器人账号文件夹
val imageDir = File(Untils.plugin.dataFolder, "verifyimage")
if (!imageDir.exists() && !imageDir.mkdirs()) {
throw RuntimeException("Failed to create folder " + imageDir.path)
}
// 验证码保存到本地
val imageFile = File(imageDir, bot.id.toString() + "-verify.png")
try {
withContext(Dispatchers.IO) {
FileOutputStream(imageFile).use { fos ->
fos.write(data)
fos.flush()
}
}
} catch (e: IOException) {
bot.logger.warning("保存验证码图片文件时出现异常,原因: $e")
}
threads = Thread {
deviceVerifyContinue[bot] = false
bot.logger.warning("当前登录的QQ(" + bot.id + ")需要文字验证码验证")
bot.logger.warning("请找到下面的文件并识别文字验证码")
bot.logger.warning(imageFile.path)
bot.logger.warning("识别完成后,请输入指令 /bot pic <Code>")
bot.logger.warning("如需取消登录,请输入指令 /bot pic cancel")
while (true) {
try {
if (!deviceVerifyContinue.containsKey(bot) || deviceVerifyContinue[bot]!!) {
break
}
} catch (e: NullPointerException) {
break
}
}
}
threads!!.start()
try {
withContext(Dispatchers.IO) {
threads!!.join()
}
} catch (e: InterruptedException) {
bot.logger.warning("启动验证线程时出现异常,原因: $e")
throw loginErrorException
}
return if (!deviceVerifyCanceled.containsKey(bot) || deviceVerifyCanceled[bot]!!) {
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
throw loginCancelException
} else {
val result = deviceVerifyCode[bot]
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
result
}
}
/**
* @param bot 机器人实例
* @param url 滑动验证码验证链接
* @return 验证码解决成功后获得的 ticket
*/
override suspend fun onSolveSliderCaptcha(bot: Bot, url: String): String? {
deviceVerifyCanceled[bot] = false
threads = Thread {
deviceVerifyContinue[bot] = false
bot.logger.warning("当前登录的QQ(" + bot.id + ")需要滑动验证码验证")
bot.logger.warning("请使用手机QQ打开以下链接进行验证")
bot.logger.warning(url)
bot.logger.warning("验证完成后,请输入指令 /bot slider <ticket>")
bot.logger.warning("如需取消登录,请输入指令 /bot slider cancel")
while (true) {
try {
if (!deviceVerifyContinue.containsKey(bot) || deviceVerifyContinue[bot]!!
) {
break
}
} catch (e: NullPointerException) {
break
}
}
}
threads!!.start()
try {
withContext(Dispatchers.IO) {
threads!!.join()
}
} catch (e: InterruptedException) {
bot.logger.warning("启动验证线程时出现异常,原因: $e")
throw loginErrorException
}
return if (!deviceVerifyCanceled.containsKey(bot) || deviceVerifyCanceled[bot]!!) {
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
throw loginCancelException
} else {
val result = deviceVerifyCode[bot]
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
result
}
}
/**
* @param bot 机器人实例
* @param url 设备锁验证链接
* @return 任意值
*/
override suspend fun onSolveUnsafeDeviceLoginVerify(bot: Bot, url: String): String? {
deviceVerifyCanceled[bot] = false
threads = Thread {
deviceVerifyContinue[bot] = false
bot.logger.warning("当前登录的QQ(" + bot.id + ")需要设备锁验证")
bot.logger.warning("请使用手机QQ打开以下链接进行验证")
bot.logger.warning(url)
bot.logger.warning("验证完成后,请输入指令 /bot unsafe verify")
bot.logger.warning("如需取消登录,请输入指令 /bot unsafe cancel")
while (true) {
try {
if (!deviceVerifyContinue.containsKey(bot) || deviceVerifyContinue[bot]!!
) {
break
}
} catch (e: NullPointerException) {
break
}
}
}
threads!!.start()
try {
withContext(Dispatchers.IO) {
threads!!.join()
}
} catch (e: InterruptedException) {
bot.logger.warning("启动验证线程时出现异常,原因: $e")
throw loginErrorException
}
return if (!deviceVerifyCanceled.containsKey(bot) || deviceVerifyCanceled[bot]!!) {
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
throw loginCancelException
} else {
deviceVerifyCanceled.remove(bot)
deviceVerifyContinue.remove(bot)
deviceVerifyCode.remove(bot)
null
}
}
companion object {
/**
* 是否继续线程(用于判断用户侧是否完成验证)
*/
private val deviceVerifyContinue = HashMap<Bot, Boolean>()
/**
* 是否取消线程(用于判断用户是否决定终止验证)
*/
private val deviceVerifyCanceled = HashMap<Bot, Boolean>()
/**
* 验证码(用户提供的验证码或ticket)
*/
private val deviceVerifyCode = HashMap<Bot, String>()
fun solveUnsafeDeviceLoginVerify(BotAccount: Long, Canceled: Boolean) {
deviceVerifyContinue[Bot.getInstance(BotAccount)] = true
deviceVerifyCanceled[Bot.getInstance(BotAccount)] = Canceled
}
fun solveSliderCaptcha(BotAccount: Long, Canceled: Boolean) {
deviceVerifyContinue[Bot.getInstance(BotAccount)] = true
deviceVerifyCanceled[Bot.getInstance(BotAccount)] = Canceled
}
fun solveSliderCaptcha(BotAccount: Long, ticket: String) {
deviceVerifyContinue[Bot.getInstance(BotAccount)] = true
deviceVerifyCanceled[Bot.getInstance(BotAccount)] = false
deviceVerifyCode[Bot.getInstance(BotAccount)] = ticket
}
fun solvePicCaptcha(BotAccount: Long, Canceled: Boolean) {
deviceVerifyContinue[Bot.getInstance(BotAccount)] = true
deviceVerifyCanceled[Bot.getInstance(BotAccount)] = Canceled
}
fun solvePicCaptcha(BotAccount: Long, Captcha: String) {
deviceVerifyContinue[Bot.getInstance(BotAccount)] = true
deviceVerifyCanceled[Bot.getInstance(BotAccount)] = false
deviceVerifyCode[Bot.getInstance(BotAccount)] = Captcha
}
fun closeAllVerifyThreads() {
deviceVerifyContinue.clear()
deviceVerifyCanceled.clear()
deviceVerifyCode.clear()
}
}
} | 0 | Kotlin | 0 | 1 | ebab554b5328db0b4d408799e37e87ae235da540 | 8,131 | BotCommand | Apache License 2.0 |
komposecountrycodepicker/src/test/java/com/joelkanyi/jcomposecountrycodepicker/fake/FakeCountryCodePicker.kt | joelkanyi | 668,574,920 | false | {"Kotlin": 184208} | package com.joelkanyi.jcomposecountrycodepicker.fake
import com.joelkanyi.jcomposecountrycodepicker.annotation.RestrictedApi
import com.joelkanyi.jcomposecountrycodepicker.component.CountryCodePicker
import com.joelkanyi.jcomposecountrycodepicker.data.Country
class FakeCountryCodePicker(
phone: String,
code: String,
countries: List<Country>,
) : CountryCodePicker {
override var phoneNumber: String = phone
override var countryCode: String = code
override var countryList: List<Country> = countries
override val showCountryCode: Boolean
get() {
TODO()
}
override val showCountryFlag: Boolean
get() {
TODO()
}
override fun getCountryName(): String {
return countryList.first().name
}
override fun getCountryPhoneCode(): String {
return countryList.first().phoneNoCode
}
override fun getCountryPhoneCodeWithoutPrefix(): String {
return countryList.first().phoneNoCode.substring(1)
}
override fun getPhoneNumberWithoutPrefix(): String {
return phoneNumber
}
override fun getFullPhoneNumberWithoutPrefix(): String {
val phoneCode = getCountryPhoneCodeWithoutPrefix()
return "$phoneCode$phoneNumber"
}
override fun getFullPhoneNumber(): String {
return "${getCountryPhoneCode()}$phoneNumber"
}
override fun isPhoneNumberValid(phoneNumber: String): Boolean {
return true
}
override fun getFullyFormattedPhoneNumber(): String {
return getFullPhoneNumber()
}
@RestrictedApi
override fun setPhoneNo(phoneNumber: String) {
TODO("Not yet implemented")
}
@RestrictedApi
override fun setCode(countryCode: String) {
TODO("Not yet implemented")
}
}
| 5 | Kotlin | 13 | 152 | 27c9b0206fc7ade5d1e1b93daffae5c063060254 | 1,812 | kompose-country-code-picker | Apache License 2.0 |
komposecountrycodepicker/src/test/java/com/joelkanyi/jcomposecountrycodepicker/fake/FakeCountryCodePicker.kt | joelkanyi | 668,574,920 | false | {"Kotlin": 184208} | package com.joelkanyi.jcomposecountrycodepicker.fake
import com.joelkanyi.jcomposecountrycodepicker.annotation.RestrictedApi
import com.joelkanyi.jcomposecountrycodepicker.component.CountryCodePicker
import com.joelkanyi.jcomposecountrycodepicker.data.Country
class FakeCountryCodePicker(
phone: String,
code: String,
countries: List<Country>,
) : CountryCodePicker {
override var phoneNumber: String = phone
override var countryCode: String = code
override var countryList: List<Country> = countries
override val showCountryCode: Boolean
get() {
TODO()
}
override val showCountryFlag: Boolean
get() {
TODO()
}
override fun getCountryName(): String {
return countryList.first().name
}
override fun getCountryPhoneCode(): String {
return countryList.first().phoneNoCode
}
override fun getCountryPhoneCodeWithoutPrefix(): String {
return countryList.first().phoneNoCode.substring(1)
}
override fun getPhoneNumberWithoutPrefix(): String {
return phoneNumber
}
override fun getFullPhoneNumberWithoutPrefix(): String {
val phoneCode = getCountryPhoneCodeWithoutPrefix()
return "$phoneCode$phoneNumber"
}
override fun getFullPhoneNumber(): String {
return "${getCountryPhoneCode()}$phoneNumber"
}
override fun isPhoneNumberValid(phoneNumber: String): Boolean {
return true
}
override fun getFullyFormattedPhoneNumber(): String {
return getFullPhoneNumber()
}
@RestrictedApi
override fun setPhoneNo(phoneNumber: String) {
TODO("Not yet implemented")
}
@RestrictedApi
override fun setCode(countryCode: String) {
TODO("Not yet implemented")
}
}
| 5 | Kotlin | 13 | 152 | 27c9b0206fc7ade5d1e1b93daffae5c063060254 | 1,812 | kompose-country-code-picker | Apache License 2.0 |
src/test/kotlin/no/nav/helse/flex/e2e/IntegrasjonsTest.kt | navikt | 451,810,928 | false | {"Kotlin": 346362, "Dockerfile": 267} | package no.nav.helse.flex.e2e
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.readValue
import no.nav.helse.flex.*
import no.nav.helse.flex.domain.DokumentTypeDTO
import no.nav.helse.flex.domain.OppdateringstypeDTO
import no.nav.helse.flex.domain.OppgaveDTO
import no.nav.helse.flex.mockdispatcher.SykepengesoknadMockDispatcher
import no.nav.helse.flex.service.*
import no.nav.helse.flex.sykepengesoknad.kafka.ArbeidssituasjonDTO
import no.nav.helse.flex.sykepengesoknad.kafka.FiskerBladDTO
import no.nav.helse.flex.sykepengesoknad.kafka.SoknadstypeDTO
import org.amshove.kluent.`should be null`
import org.amshove.kluent.shouldBeEqualTo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.test.annotation.DirtiesContext
import søknad
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.UUID
import java.util.concurrent.TimeUnit
@DirtiesContext
class IntegrasjonsTest : FellesTestOppsett() {
@Test
fun `En arbeidsledigsøknad får behandlingstema ab0426 og takler at bømlo sier opprett`() {
val soknadId = UUID.randomUUID()
val søknad = søknad(soknadId).copy(type = SoknadstypeDTO.ARBEIDSLEDIG, arbeidssituasjon = ArbeidssituasjonDTO.ARBEIDSLEDIG)
SykepengesoknadMockDispatcher.enque(søknad)
leggSøknadPåKafka(søknad)
oppgaveOpprettelse.behandleOppgaver(Instant.now().plus(249, ChronoUnit.HOURS))
val oppgaveRequest = oppgaveMockWebserver.takeRequest(2, TimeUnit.SECONDS)!!
assertThat(oppgaveRequest.requestLine).isEqualTo("POST /api/v1/oppgaver HTTP/1.1")
val oppgaveRequestBody = objectMapper.readValue<OppgaveRequest>(oppgaveRequest.body.readUtf8())
assertThat(oppgaveRequestBody.behandlingstema).isEqualTo("ab0426")
leggOppgavePåAivenKafka(OppgaveDTO(DokumentTypeDTO.Søknad, OppdateringstypeDTO.Opprett, soknadId))
oppgaveOpprettelse.behandleOppgaver()
oppgaveMockWebserver.takeRequest(1, TimeUnit.SECONDS).`should be null`()
val pdfRequest = pdfMockWebserver.takeRequest(10, TimeUnit.SECONDS)!!
val pdfRequestBody = objectMapper.readValue<JsonNode>(pdfRequest.body.readUtf8())
pdfRequestBody.get("arbeidssituasjonTekst").textValue() shouldBeEqualTo "arbeidsledig"
}
@Test
fun `En fiskersøknad med fiskerblad i oppgavebeskrivelsen`() {
val soknadId = UUID.randomUUID()
val søknad =
søknad(soknadId).copy(
type = SoknadstypeDTO.SELVSTENDIGE_OG_FRILANSERE,
arbeidssituasjon = ArbeidssituasjonDTO.FISKER,
fiskerBlad = FiskerBladDTO.A,
)
SykepengesoknadMockDispatcher.enque(søknad)
leggSøknadPåKafka(søknad)
oppgaveOpprettelse.behandleOppgaver(Instant.now().plus(249, ChronoUnit.HOURS))
val oppgaveRequest = oppgaveMockWebserver.takeRequest(2, TimeUnit.SECONDS)!!
assertThat(oppgaveRequest.requestLine).isEqualTo("POST /api/v1/oppgaver HTTP/1.1")
val oppgaveRequestBody = objectMapper.readValue<OppgaveRequest>(oppgaveRequest.body.readUtf8())
assertThat(oppgaveRequestBody.behandlingstema).isEqualTo("ab0061")
assertThat(oppgaveRequestBody.beskrivelse).isEqualTo(
"""
Søknad om sykepenger for fisker på blad A for perioden 04.05.2019 til 08.05.2019
Har systemet gode integrasjonstester?
Ja
""".trimIndent(),
)
val pdfRequest = pdfMockWebserver.takeRequest(10, TimeUnit.SECONDS)!!
val pdfRequestBody = objectMapper.readValue<JsonNode>(pdfRequest.body.readUtf8())
pdfRequestBody.get("arbeidssituasjonTekst").textValue() shouldBeEqualTo "fisker"
}
}
| 3 | Kotlin | 0 | 0 | be9da0c85c38d8e4238a4ca66174e4f267b36180 | 3,786 | sykepengesoknad-arkivering-oppgave | MIT License |
app/src/main/java/com/example/calculadoraimcv2/MainActivity.kt | maumauriciog | 778,565,484 | false | {"Kotlin": 5209} | package com.example.calculadoraimcv2
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.android.material.textfield.TextInputEditText
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val btnButton = findViewById<Button>(R.id.btnIMC)
val impPeso = findViewById<TextInputEditText>(R.id.impPeso)
val impAltura = findViewById<TextInputEditText>(R.id.impAltura)
btnButton.setOnClickListener {
if (impPeso.text.toString() == "" || impAltura.text.toString() == "") {
Toast.makeText(this, "Todos os campos precisam estar preenchidos!", Toast.LENGTH_SHORT).show()
} else {
val peso: Float = impPeso.text.toString().toFloat()
val altura: Float = impAltura.text.toString().toFloat()
val respAltura = altura * altura
val respIMC = peso / respAltura
val intent = Intent(this, ResultActivity::class.java)
.putExtra("dateIMCp", peso)
.putExtra("dateIMCa", altura)
.putExtra("dateIMC", respIMC)
startActivity(intent)
}
}
}
} | 0 | Kotlin | 0 | 1 | 919ee269dbf85dbdc19af7110d3284741c69f363 | 1,586 | calculadoraIMCv2 | MIT License |
modules/modules_my/src/main/java/com/cl/modules_my/adapter/MyTroubleAdapter.kt | alizhijun | 528,318,389 | false | null | package com.cl.modules_my.adapter
import androidx.databinding.DataBindingUtil
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cl.common_base.util.calendar.Calendar
import com.cl.modules_my.R
import com.cl.modules_my.databinding.MyCalendarItemBinding
import com.cl.modules_my.databinding.MyTroubleItemBinding
import com.cl.modules_my.repository.MyTroubleData
class MyTroubleAdapter(data: MutableList<MyTroubleData.Bean>?) :
BaseQuickAdapter<MyTroubleData.Bean, BaseViewHolder>(R.layout.my_trouble_item, data) {
override fun onItemViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
DataBindingUtil.bind<MyTroubleItemBinding>(viewHolder.itemView)
}
override fun convert(holder: BaseViewHolder, item: MyTroubleData.Bean) {
// 获取 Binding
val binding: MyTroubleItemBinding? = holder.getBinding()
binding?.apply {
data = item
executePendingBindings()
}
}
} | 0 | Kotlin | 0 | 0 | 9ae50ccc521fda4d30ea47491b793694ac41dd0c | 1,100 | abby | Apache License 2.0 |
app/src/main/java/com/exner/tools/activitytimerfortv/ui/CustomComponents.kt | janexner | 749,859,621 | false | {"Kotlin": 162534} | package com.exner.tools.activitytimerfortv.ui
import androidx.compose.foundation.layout.Column
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.text.KeyboardOptions
import androidx.compose.material3.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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.tv.material3.LocalContentColor
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
import com.exner.tools.activitytimerfortv.ui.tools.AutoSizeText
import java.util.Locale
import kotlin.math.roundToInt
import kotlin.time.Duration
@Composable
fun durationToAnnotatedString(
duration: Duration,
withHours: Boolean,
postText: String? = null
): AnnotatedString {
// convert seconds to "00:00" style string
val output = duration.toComponents { hours, minutes, seconds, _ ->
String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds)
}
val tmp = output.split(":")
val styledOutput = buildAnnotatedString {
var myStyle = SpanStyle()
if (withHours) {
if ("00" == tmp[0]) {
myStyle = SpanStyle(color = LocalContentColor.current.copy(alpha = 0.2f))
}
withStyle(style = myStyle) {
append(tmp[0])
}
append(":")
}
myStyle = if ("00" == tmp[1]) {
SpanStyle(color = LocalContentColor.current.copy(alpha = 0.2f))
} else {
SpanStyle(color = LocalContentColor.current.copy(alpha = 1f))
}
withStyle(style = myStyle) {
append(tmp[1])
}
append(":")
append(tmp[2])
if (postText !== null) {
append(postText)
}
}
return styledOutput
}
@Composable
fun BigTimerText(duration: Duration, withHours: Boolean, modifier: Modifier = Modifier) {
AutoSizeText(
text = durationToAnnotatedString(duration, withHours),
modifier = modifier,
maxLines = 1,
color = MaterialTheme.colorScheme.onSurface,
)
}
@Composable
fun MediumTimerAndIntervalText(
duration: Duration,
withHours: Boolean,
intervalText: String,
modifier: Modifier = Modifier
) {
Row(modifier = modifier) {
AutoSizeText(
text = durationToAnnotatedString(duration, withHours, " | Round $intervalText"),
maxLines = 1,
color = MaterialTheme.colorScheme.onSurface,
)
}
}
@Composable
fun InfoText(
infoText: String,
modifier: Modifier = Modifier
) {
Row(modifier = modifier) {
AutoSizeText(
text = infoText,
alignment = Alignment.BottomStart,
color = MaterialTheme.colorScheme.onSurface,
lineSpacingRatio = 1.75f,
)
}
}
@Composable
fun TimerDisplay(
processTime: Duration,
intervalTime: Duration,
info: String?,
forceWithHours: Boolean = false
) {
Column(modifier = Modifier.fillMaxSize()) {
BigTimerText(
duration = processTime,
withHours = forceWithHours,
modifier = Modifier
.fillMaxWidth(0.66f)
.align(Alignment.End)
)
Row(
modifier = Modifier
.fillMaxWidth(0.66f)
.align(Alignment.End)
) {
AutoSizeText(
text = durationToAnnotatedString(
duration = intervalTime,
withHours = forceWithHours,
postText = " | ${(processTime / intervalTime).roundToInt().toString()} round(s)"
),
maxLines = 1,
color = MaterialTheme.colorScheme.onSurface,
)
}
if (null != info) {
Spacer(modifier = Modifier.height(16.dp))
InfoText(infoText = info)
}
}
}
@Composable
fun TextFieldForTimes(
value: Int,
label: @Composable (() -> Unit)?,
onValueChange: (Int) -> Unit,
placeholder: @Composable (() -> Unit)? = null,
) {
var text by remember(value) { mutableStateOf(value.toString()) }
TextField(
value = text,
label = label,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
onValueChange = { raw ->
text = raw
val parsed = text.toIntOrNull() ?: 0
onValueChange(parsed)
},
placeholder = placeholder,
textStyle = MaterialTheme.typography.bodyLarge
)
}
@Composable
fun HeaderText(text: String, modifier: Modifier = Modifier) {
Text(
text = text,
style = MaterialTheme.typography.headlineSmall,
modifier = modifier
.fillMaxWidth()
.padding(8.dp),
)
}
@Composable
fun BodyText(text: String, modifier: Modifier = Modifier) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
modifier = modifier,
)
} | 0 | Kotlin | 0 | 0 | 555b68ad52bc976d36d4e55258d449e27ffbb954 | 5,766 | ActivityTimerForTV | Apache License 2.0 |
app/src/main/java/com/anubhav_auth/bento/database/entities/placesData/Geometry.kt | anubhav-auth | 850,108,148 | false | {"Kotlin": 82163} | package com.anubhav_auth.bento.database.entities.placesData
data class Geometry(
val location: Location,
val viewport: Viewport
) | 0 | Kotlin | 0 | 0 | 36c1d117d3f50064e8664fa4f31893ba61f74e69 | 138 | Bento | MIT License |
backend/src/main/kotlin/com/mobilispect/backend/schedule/gtfs/GTFSRoute.kt | alandovskis | 502,662,711 | false | {"Kotlin": 360480, "Shell": 472, "Swift": 345} | package com.mobilispect.backend.schedule.gtfs
import com.mobilispect.backend.schedule.agency.FeedLocalAgencyID
import com.mobilispect.backend.schedule.agency.FeedLocalAgencyIDSerializer
import com.mobilispect.backend.schedule.route.FeedLocalRouteID
import com.mobilispect.backend.schedule.route.FeedLocalRouteIDSerializer
import kotlinx.serialization.Serializable
@Serializable
class GTFSRoute(
@Serializable(with = FeedLocalRouteIDSerializer::class)
val route_id: FeedLocalRouteID,
val route_short_name: String,
val route_long_name: String,
@Serializable(with = FeedLocalAgencyIDSerializer::class)
val agency_id: FeedLocalAgencyID? = null,
)
| 4 | Kotlin | 0 | 1 | 432b2425a9ab841f73525aa8cf3075b2f7e49d7b | 670 | mobilispect | Apache License 2.0 |
model/src/main/kotlin/de/fraunhofer/iem/kpiCalculator/model/kpi/KpiId.kt | janniclas | 845,527,947 | false | {"Kotlin": 66083} | package de.fraunhofer.iem.kpiCalculator.model.kpi
enum class KpiId {
// Raw Value KPIs
CHECKED_IN_BINARIES,
NUMBER_OF_COMMITS,
VULNERABILITY_SCORE,
NUMBER_OF_SIGNED_COMMITS,
IS_DEFAULT_BRANCH_PROTECTED,
SECRETS,
SAST_USAGE,
COMMENTS_IN_CODE,
DOCUMENTATION_INFRASTRUCTURE,
// Calculated KPIs
SIGNED_COMMITS_RATIO,
INTERNAL_QUALITY,
EXTERNAL_QUALITY,
PROCESS_COMPLIANCE,
PROCESS_TRANSPARENCY,
SECURITY,
MAXIMAL_VULNERABILITY,
DOCUMENTATION,
// ROOT
ROOT
}
| 0 | Kotlin | 0 | 0 | 2c6297b961eee9c7c3df7d79e208613ab70dd5a3 | 542 | AutoDeploymentTest | MIT License |
app/src/androidTest/kotlin/com/nagopy/android/aplin/ApplicationMockComponent.kt | 75py | 43,955,994 | false | null | /*
* Copyright 2015 75py
*
* 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.nagopy.android.aplin
import com.nagopy.android.aplin.model.AplinDevicePolicyManagerTest
import com.nagopy.android.aplin.model.converter.AppConverterTest
import com.nagopy.android.aplin.presenter.MainScreenPresenterTest
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(ApplicationMockModule::class))
interface ApplicationMockComponent : ApplicationComponent {
fun inject(appParametersTest: AppConverterTest)
fun inject(mainScreenPresenterTest: MainScreenPresenterTest)
fun inject(aplinDevicePolicyManagerTest: AplinDevicePolicyManagerTest)
} | 4 | Kotlin | 2 | 12 | fa6519679c5f6ee910dd25d0715f04e1bc39e7b2 | 1,200 | Aplin | Apache License 2.0 |
core/src/commonMain/kotlin/org/kobjects/kowa/core/module/Extension.kt | kobjects | 340,712,554 | false | {"Kotlin": 165863} | package org.kobjects.kowa.core.module
enum class Extension {
BULK_MEMORY_OPERATIONS,
EXTENDED_CONSTANT_EXPRESSIONS,
GARBAGE_COLLECTION,
MULTIPLE_MEMORIES,
MULTIVALUE,
REFERENCE_TYPES,
RELAXED_SIMD,
NON_TRAPPING_FLOAT_TO_INT_CONVERSIONS,
SIGN_EXTENSION_OPERATIONS,
FIXED_WIDTH_SIMD,
TAIL_CALLS,
THREADS,
EXCEPTION_HANDLING,
MEMORY_64,
TYPE_REFLECTION,
GC_DEVELOPMENT,
} | 0 | Kotlin | 0 | 3 | 5b9254491f695ca557329d0eb339ed8272957478 | 434 | kowa | Apache License 2.0 |
app/src/main/java/com/simplepeople/watcha/domain/core/SearchLogItem.kt | hbjosemaria | 786,895,118 | false | {"Kotlin": 425852} | package com.simplepeople.watcha.domain.core
import com.simplepeople.watcha.data.model.local.SearchLogItemEntity
data class SearchLogItem(
val id: Int = 0,
val searchedText: String = "",
) {
fun toEntity(): SearchLogItemEntity =
SearchLogItemEntity(
id = this.id,
searchedText = this.searchedText
)
} | 0 | Kotlin | 0 | 3 | 05cd1a2abc9fd5b19c5d4273d99dc4b7bd2c97e3 | 353 | Watcha | Apache License 2.0 |
src/test/kotlin/no/gjensidige/bsf/example/BuyInsuranceTest.kt | gjensidige | 839,253,007 | false | {"Kotlin": 17723} | package no.gjensidige.bsf.example
import kotlinx.coroutines.runBlocking
import no.gjensidige.bsf.example.mapping.mapToBoligsalgopplysningerWithKjopsdetaljer
import no.gjensidige.bsf.example.security.*
import no.gjensidige.bsf.example.service.getInformationFromYourSystem
import org.junit.jupiter.api.Test
import kotlin.test.assertTrue
/**
* This is an example of how to buy a boligselgerforsikring using Gjensidiges bsf api.
*/
class BuyInsuranceTest {
@Test
fun `use boligselgerforsikring api`() = runBlocking {
// init
val tokenStorage = tokenStorage(tokenMockClientEngine())
val egenerklaeringApi = egenerklaeringApi(tokenStorage, mockEgenerklaeringClientEngine())
val boligselgerforsikringApi = boligselgerforsikringApi(tokenStorage, mockBoligselgerforsikringClientEngine())
// Step 1 - Read egenerklæring status
// Fetch status on sellers progress with the egenerklæring
val yourDto = getInformationFromYourSystem()
val egenerklaeringStatus = egenerklaeringApi.getEgenerklaeringStatus(
id = yourDto.oppdragsid,
orgnr = setOf(yourDto.meglerkontor.organisasjonsnummer)
).body()
// Step 2:
// Gather info required to buy the insurance
val boligsalgopplysningerForKjop = yourDto.mapToBoligsalgopplysningerWithKjopsdetaljer()
// Step 3:
// Buy the insurance, receive payment info if successful
assertTrue(egenerklaeringStatus.signed, "The egenerklaering should be signed before buying")
assertTrue(egenerklaeringStatus.boligselgerforsikringAccepted, "The insurance should be accepted before buying")
val betalingsinformasjon = boligselgerforsikringApi.buyBoligselgerforsikring(boligsalgopplysningerForKjop)
}
} | 4 | Kotlin | 0 | 0 | bd4af5ad56f590d755e9fab169ccd3e2e9309502 | 1,790 | bsf-client-example | MIT License |
src/main/kotlin/com/github/shatteredsuite/scrolls/ext/PluginDescriptionFileExt.kt | ShatteredSoftware | 263,253,802 | false | null | package com.github.shatteredsuite.scrolls.ext
import org.bukkit.plugin.PluginDescriptionFile
val PluginDescriptionFile.placeholders: Map<out String, String>
get() {
val map = mutableMapOf("version" to this.version, "name" to this.name, "authors" to this.authors.joinToString())
if(apiVersion != null)
map["api-version"] = apiVersion!!
if(description != null)
map["description"] = description!!
return map
} | 1 | null | 1 | 1 | b4d65a8d18a3842032f302a871e7a64f7dfe1d88 | 473 | ShatteredScrolls2 | MIT License |
core/src/main/kotlin/org/jetbrains/kotlinx/dataframe/jupyter/JupyterHtmlRenderer.kt | Kotlin | 259,256,617 | false | {"Kotlin": 7630374, "JavaScript": 11483, "Java": 4185, "CSS": 3083, "Shell": 229, "HTML": 137} | package org.jetbrains.kotlinx.dataframe.jupyter
import com.beust.klaxon.json
import org.jetbrains.kotlinx.dataframe.api.take
import org.jetbrains.kotlinx.dataframe.impl.io.encodeFrame
import org.jetbrains.kotlinx.dataframe.io.Base64ImageEncodingOptions
import org.jetbrains.kotlinx.dataframe.io.DataFrameHtmlData
import org.jetbrains.kotlinx.dataframe.io.DisplayConfiguration
import org.jetbrains.kotlinx.dataframe.io.toHTML
import org.jetbrains.kotlinx.dataframe.io.toJsonWithMetadata
import org.jetbrains.kotlinx.dataframe.io.toStaticHtml
import org.jetbrains.kotlinx.dataframe.jupyter.KotlinNotebookPluginUtils.convertToDataFrame
import org.jetbrains.kotlinx.dataframe.nrow
import org.jetbrains.kotlinx.dataframe.size
import org.jetbrains.kotlinx.jupyter.api.HtmlData
import org.jetbrains.kotlinx.jupyter.api.JupyterClientType
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion
import org.jetbrains.kotlinx.jupyter.api.MimeTypedResult
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.libraries.JupyterIntegration
import org.jetbrains.kotlinx.jupyter.api.mimeResult
import org.jetbrains.kotlinx.jupyter.api.renderHtmlAsIFrameIfNeeded
/** Starting from this version, dataframe integration will respond with additional data for rendering in Kotlin Notebooks plugin. */
private const val MIN_KERNEL_VERSION_FOR_NEW_TABLES_UI = "0.11.0.311"
private const val MIN_IDE_VERSION_SUPPORT_JSON_WITH_METADATA = 241
private const val MIN_IDE_VERSION_SUPPORT_IMAGE_VIEWER = 242
internal class JupyterHtmlRenderer(
val display: DisplayConfiguration,
val builder: JupyterIntegration.Builder,
)
internal inline fun <reified T : Any> JupyterHtmlRenderer.render(
noinline getFooter: (T) -> String,
crossinline modifyConfig: T.(DisplayConfiguration) -> DisplayConfiguration = { it },
applyRowsLimit: Boolean = true,
) = builder.renderWithHost<T> { host, value ->
val contextRenderer = JupyterCellRenderer(this.notebook, host)
val reifiedDisplayConfiguration = value.modifyConfig(display)
val footer = getFooter(value)
val df = convertToDataFrame(value)
val limit = if (applyRowsLimit) {
reifiedDisplayConfiguration.rowsLimit ?: df.nrow
} else {
df.nrow
}
val html = DataFrameHtmlData.tableDefinitions(
includeJs = reifiedDisplayConfiguration.isolatedOutputs,
includeCss = true,
).plus(
df.toHTML(
// is added later to make sure it's put outside of potential iFrames
configuration = reifiedDisplayConfiguration.copy(enableFallbackStaticTables = false),
cellRenderer = contextRenderer,
) { footer }
).toJupyterHtmlData()
// Generates a static version of the table which can be displayed in GitHub previews etc.
val staticHtml = df.toStaticHtml(reifiedDisplayConfiguration, DefaultCellRenderer).toJupyterHtmlData()
if (notebook.kernelVersion >= KotlinKernelVersion.from(MIN_KERNEL_VERSION_FOR_NEW_TABLES_UI)!!) {
val ideBuildNumber = KotlinNotebookPluginUtils.getKotlinNotebookIDEBuildNumber()
val jsonEncodedDf = when {
!ideBuildNumber.supportsDynamicNestedTables() -> {
json {
obj(
"nrow" to df.size.nrow,
"ncol" to df.size.ncol,
"columns" to df.columnNames(),
"kotlin_dataframe" to encodeFrame(df.take(limit)),
)
}.toJsonString()
}
else -> {
val imageEncodingOptions =
if (ideBuildNumber.supportsImageViewer()) Base64ImageEncodingOptions() else null
df.toJsonWithMetadata(
limit,
reifiedDisplayConfiguration.rowsLimit,
imageEncodingOptions = imageEncodingOptions
)
}
}
notebook.renderAsIFrameAsNeeded(html, staticHtml, jsonEncodedDf)
} else {
notebook.renderHtmlAsIFrameIfNeeded(html)
}
}
private fun KotlinNotebookPluginUtils.IdeBuildNumber?.supportsDynamicNestedTables() =
this != null && majorVersion >= MIN_IDE_VERSION_SUPPORT_JSON_WITH_METADATA
private fun KotlinNotebookPluginUtils.IdeBuildNumber?.supportsImageViewer() =
this != null && majorVersion >= MIN_IDE_VERSION_SUPPORT_IMAGE_VIEWER
internal fun Notebook.renderAsIFrameAsNeeded(
data: HtmlData,
staticData: HtmlData,
jsonEncodedDf: String
): MimeTypedResult {
val textHtml = if (jupyterClientType == JupyterClientType.KOTLIN_NOTEBOOK) {
data.generateIframePlaneText(currentColorScheme) +
staticData.toString(currentColorScheme)
} else {
(data + staticData).toString(currentColorScheme)
}
return mimeResult(
"text/html" to textHtml,
"application/kotlindataframe+json" to jsonEncodedDf
).also { it.isolatedHtml = false }
}
internal fun DataFrameHtmlData.toJupyterHtmlData() = HtmlData(style, body, script)
| 183 | Kotlin | 48 | 731 | 5088ce81231117608f17285d699c6dc3648ed48c | 5,053 | dataframe | Apache License 2.0 |
application/second/src/main/kotlin/com/example/demo/SecondDemoApplication.kt | yokrh | 630,272,864 | false | null | package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class SecondDemoApplication
fun main(args: Array<String>) {
runApplication<SecondDemoApplication>(*args)
}
| 0 | Kotlin | 0 | 0 | aa03d3bb87e7a087d370554880f0d69e5f81eedd | 274 | spring-boot-multiproject-training | Apache License 2.0 |
ide-former-plugin/ide-core/src/main/kotlin/org/jetbrains/research/ideFormerPlugin/api/models/fileSystemRelated/ProjectModules.kt | JetBrains-Research | 676,069,470 | false | {"Kotlin": 48565, "Jupyter Notebook": 41524, "Python": 18567, "Shell": 1382, "Dockerfile": 960, "Java": 113} | package org.jetbrains.research.ideFormerPlugin.api.models.fileSystemRelated
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import org.jetbrains.research.ideFormerPlugin.api.models.IdeApiMethod
class ProjectModules(private val project: Project) : IdeApiMethod {
private var projectModules: List<Module>? = null
private fun Project.modules(): List<Module> = ModuleManager.getInstance(this).modules.toList()
override fun execute() {
projectModules = project.modules()
}
fun getProjectModulesNames(): List<String>? = projectModules?.map { it.name }?.toList()
}
| 1 | Kotlin | 0 | 0 | fcf76878f08c128ccf904c0f1f496f060b6202c6 | 677 | ideformer-plugin | MIT License |
android/src/main/kotlin/co/quis/flutter_contacts/properties/Name.kt | QuisApp | 315,608,148 | false | {"Dart": 196066, "Kotlin": 85866, "Swift": 57514, "Ruby": 3625, "Objective-C": 782, "Shell": 81} | package co.quis.flutter_contacts.properties
data class Name(
var first: String = "",
var last: String = "",
var middle: String = "",
var prefix: String = "",
var suffix: String = "",
var nickname: String = "",
var firstPhonetic: String = "",
var lastPhonetic: String = "",
var middlePhonetic: String = ""
) {
companion object {
fun fromMap(m: Map<String, Any>): Name = Name(
m["first"] as String,
m["last"] as String,
m["middle"] as String,
m["prefix"] as String,
m["suffix"] as String,
m["nickname"] as String,
m["firstPhonetic"] as String,
m["lastPhonetic"] as String,
m["middlePhonetic"] as String
)
}
fun toMap(): Map<String, Any> = mapOf(
"first" to first,
"last" to last,
"middle" to middle,
"prefix" to prefix,
"suffix" to suffix,
"nickname" to nickname,
"firstPhonetic" to firstPhonetic,
"lastPhonetic" to lastPhonetic,
"middlePhonetic" to middlePhonetic
)
}
| 48 | Dart | 135 | 81 | 6d4b7cebd84059af04923cd206fbb58affab7f57 | 1,117 | flutter_contacts | MIT License |
repository/src/main/java/com/telen/easylineup/repository/dao/PlayerFieldPositionsDao.kt | kaygenzo | 177,859,247 | false | null | package com.telen.easylineup.repository.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import com.telen.easylineup.repository.model.RoomPlayerFieldPosition
import com.telen.easylineup.repository.model.RoomPlayerGamesCount
import com.telen.easylineup.repository.model.RoomPlayerWithPosition
import com.telen.easylineup.repository.model.RoomPositionWithLineup
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
@Dao
internal interface PlayerFieldPositionsDao {
@Query("DELETE FROM playerFieldPosition")
fun deleteAll(): Completable
@Insert
fun insertPlayerFieldPositions(fieldPositions: List<RoomPlayerFieldPosition>): Completable
@Update
fun updatePlayerFieldPositions(fieldPositions: List<RoomPlayerFieldPosition>): Completable
@Update
fun updatePlayerFieldPositionsWithRowCount(fieldPositions: List<RoomPlayerFieldPosition>): Single<Int>
@Delete
fun deletePosition(position: RoomPlayerFieldPosition): Completable
@Delete
fun deletePositions(position: List<RoomPlayerFieldPosition>): Completable
@Update
fun updatePlayerFieldPosition(fieldPosition: RoomPlayerFieldPosition): Completable
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPlayerFieldPosition(fieldPositions: RoomPlayerFieldPosition): Single<Long>
@Query("SELECT * from playerFieldPosition")
fun getAllPlayerFieldPositions(): LiveData<List<RoomPlayerFieldPosition>>
@Query("SELECT * from playerFieldPosition where hash = :hash")
fun getPlayerFieldPositionByHash(hash: String): Single<RoomPlayerFieldPosition>
@Query("SELECT * from playerFieldPosition")
fun getPlayerFieldPositions(): Single<List<RoomPlayerFieldPosition>>
@Query("SELECT * FROM playerFieldPosition WHERE id = :positionID")
fun getPlayerFieldPosition(positionID: Long): Single<RoomPlayerFieldPosition>
@Query("""
SELECT * FROM playerFieldPosition
WHERE playerFieldPosition.lineupID = :lineupId
""")
fun getAllPlayerFieldPositionsForLineup(lineupId: Long): Single<List<RoomPlayerFieldPosition>>
@Query("""
SELECT players.name as playerName,
players.shirtNumber, players.licenseNumber,
playerFieldPosition.position,
playerFieldPosition.x, playerFieldPosition.y,
playerFieldPosition.`order`, playerFieldPosition.id as fieldPositionID,
playerFieldPosition.lineupID,
playerFieldPosition.flags,
players.id as playerID,
players.teamID, players.image,
players.positions as playerPositions
FROM playerFieldPosition
INNER JOIN players ON playerFieldPosition.playerID = players.id
INNER JOIN lineups ON playerFieldPosition.lineupID = lineups.id
WHERE playerFieldPosition.lineupID = :lineupId
ORDER BY playerFieldPosition.`order` ASC
""")
fun getAllPlayersWithPositionsForLineup(lineupId: Long): LiveData<List<RoomPlayerWithPosition>>
@Query("""
SELECT players.name as playerName,
players.shirtNumber, players.licenseNumber,
playerFieldPosition.position,
playerFieldPosition.x, playerFieldPosition.y,
playerFieldPosition.`order`, playerFieldPosition.id as fieldPositionID,
playerFieldPosition.lineupID,
playerFieldPosition.flags,
players.id as playerID,
players.teamID, players.image,
players.positions as playerPositions
FROM playerFieldPosition
INNER JOIN players ON playerFieldPosition.playerID = players.id
INNER JOIN lineups ON playerFieldPosition.lineupID = lineups.id
WHERE playerFieldPosition.lineupID = :lineupId
ORDER BY playerFieldPosition.`order` ASC
""")
fun getAllPlayersWithPositionsForLineupRx(lineupId: Long): Single<List<RoomPlayerWithPosition>>
@Query("""
SELECT playerFieldPosition.* FROM playerFieldPosition
INNER JOIN players ON playerFieldPosition.playerID = players.id
INNER JOIN lineups ON playerFieldPosition.lineupID = lineups.id
WHERE playerFieldPosition.lineupID = :lineupID AND playerFieldPosition.playerID = :playerID
""")
fun getPlayerPositionFor(lineupID: Long, playerID: Long): Maybe<RoomPlayerFieldPosition>
@Query("""
SELECT lineups.name as lineupName, tournaments.name as tournamentName, playerFieldPosition.position, playerFieldPosition.x, playerFieldPosition.y, playerFieldPosition.`order`
FROM playerFieldPosition
INNER JOIN lineups ON playerFieldPosition.lineupID = lineups.id
INNER JOIN tournaments ON lineups.tournamentID = tournaments.id
WHERE playerFieldPosition.playerID = :playerID
ORDER BY lineups.editedAt DESC
""")
fun getAllPositionsForPlayer(playerID: Long): Single<List<RoomPositionWithLineup>>
@Query("""
SELECT playerID, COUNT(*) as size FROM playerFieldPosition
INNER JOIN lineups ON lineups.id = playerFieldPosition.lineupID
INNER JOIN teams ON teams.id = lineups.teamID
WHERE teams.id = :teamID
GROUP BY playerID ORDER BY 2 DESC
""")
fun getMostUsedPlayers(teamID: Long): Single<List<RoomPlayerGamesCount>>
} | 0 | Kotlin | 0 | 0 | 67bc24d99346cb1812857bafe4e4979d3a1ca1f5 | 5,207 | EasyLineUp | Apache License 2.0 |
src/main/kotlin/br/com/zup/edu/shared/grpc/KeymanagerGrpcFactory.kt | gabrielBrandaoZp | 410,882,647 | true | {"Kotlin": 21676, "Dockerfile": 163} | package br.com.zup.edu.shared.grpc
import br.com.zup.edu.KeyManagerListUserPixServiceGrpc
import br.com.zup.edu.KeyManagerRegisterServiceGrpc
import br.com.zup.edu.KeyManagerRemoveServiceGrpc
import br.com.zup.edu.KeyManagerSearchPixServiceGrpc
import io.grpc.ManagedChannel
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import jakarta.inject.Singleton
@Factory
class KeymanagerGrpcFactory(@GrpcChannel("keymanager") val channel: ManagedChannel) {
@Singleton
fun registerKey() = KeyManagerRegisterServiceGrpc.newBlockingStub(channel)
@Singleton
fun removeKey() = KeyManagerRemoveServiceGrpc.newBlockingStub(channel)
@Singleton
fun findKey() = KeyManagerSearchPixServiceGrpc.newBlockingStub(channel)
@Singleton
fun listUserKeys() = KeyManagerListUserPixServiceGrpc.newBlockingStub(channel)
} | 0 | Kotlin | 0 | 0 | eb28fbe1274e934bb4bff8eff2653c0967b44df3 | 877 | orange-talents-07-template-pix-keymanager-rest | Apache License 2.0 |
sample/src/main/java/fr/bipi/sample/pickup/app/extensions/IntExtension.kt | bastienpaulfr | 508,698,382 | false | {"Kotlin": 2053, "Java": 841, "HTML": 80} | package fr.bipi.sample.pickup.app.extensions
import android.content.Context
import android.content.res.Resources
fun Int.dpToPx() = (this * Resources.getSystem().displayMetrics.density).toInt()
fun Int.toResString(context: Context): String {
return context.getString(this)
}
fun Int.toResString(context: Context, vararg arguments: Any): String {
return context.getString(this, *arguments)
}
| 0 | Kotlin | 0 | 0 | d2aa643f926b2e21fb1adf7303827a981b85e307 | 403 | android-pick-up | Apache License 2.0 |
events/src/main/kotlin/br/com/guiabolso/connector/proxy/ProxyingEventHandlerDiscovery.kt | GuiaBolso | 269,366,943 | false | null | package br.com.guiabolso.connector.proxy
import br.com.guiabolso.connector.auth.AuthenticationService
import br.com.guiabolso.connector.configuration.ConfigService
import br.com.guiabolso.connector.event.EventDispatcher
import br.com.guiabolso.connector.wrapper.LoggingEventHandlerWrapper
import br.com.guiabolso.events.server.handler.EventHandler
import br.com.guiabolso.events.server.handler.EventHandlerDiscovery
class ProxyingEventHandlerDiscovery(
configService: ConfigService,
private val eventDispatcher: EventDispatcher,
private val eventAuthenticationService: AuthenticationService
) : EventHandlerDiscovery {
private val logEnabled = configService.getBoolean("event.log.startAndFinish", true)
override fun eventHandlerFor(eventName: String, eventVersion: Int): EventHandler? {
val proxyingEventHandler = ProxyingEventHandler(
eventName = eventName,
eventVersion = eventVersion,
dispatcher = eventDispatcher,
eventAuthenticationService = eventAuthenticationService
)
return if (logEnabled) {
LoggingEventHandlerWrapper(proxyingEventHandler)
} else proxyingEventHandler
}
}
| 0 | null | 3 | 1 | b11ed7435b79073f0dfd4e7be6fbace3ba9a067f | 1,202 | guiabolso-connector | Apache License 2.0 |
ui/utils/src/main/kotlin/me/gegenbauer/catspy/utils/persistence/UserPreferences.kt | Gegenbauer | 609,809,576 | false | {"Kotlin": 1056932} | package me.gegenbauer.catspy.utils.persistence
import me.gegenbauer.catspy.context.ServiceManager
import me.gegenbauer.catspy.java.ext.EMPTY_STRING
import me.gegenbauer.catspy.utils.file.JsonFileManager
import me.gegenbauer.catspy.utils.file.KeyValuesFileManager
import me.gegenbauer.catspy.utils.file.XMLFileManager
interface UserPreferences {
suspend fun loadFromDisk()
fun <T> get(key: String, defaultValue: T): T
fun <T> put(key: String, value: T?)
fun getString(key: String, defaultValue: String): String
fun getString(key: String): String {
return getString(key, EMPTY_STRING)
}
fun putString(key: String, value: String)
fun getBoolean(key: String, defaultValue: Boolean): Boolean
fun getBoolean(key: String): Boolean {
return getBoolean(key, false)
}
fun putBoolean(key: String, value: Boolean)
fun getInt(key: String, defaultValue: Int): Int
fun getInt(key: String): Int {
return getInt(key, 0)
}
fun putInt(key: String, value: Int)
fun getLong(key: String, defaultValue: Long): Long
fun getLong(key: String): Long {
return getLong(key, 0)
}
fun putLong(key: String, value: Long)
fun getFloat(key: String, defaultValue: Float): Float
fun getFloat(key: String): Float {
return getFloat(key, 0f)
}
fun putFloat(key: String, value: Float)
fun getStringList(key: String, defaultValue: List<String>): List<String>
fun getStringList(key: String): List<String> {
return getStringList(key, emptyList())
}
fun putStringList(key: String, value: List<String>)
fun putStringList(key: String, value: List<String>, maxSize: Int)
/**
* Do not pass in an instance of an anonymous inner class created in a method,
* it will be recycled after the method is completed.
*/
fun addChangeListener(listener: PreferencesChangeListener)
fun remove(key: String)
fun clear()
fun contains(key: String): Boolean
interface PreferencesChangeListener {
val key: String
fun onPreferencesChanged()
}
}
class XmlUserPreferences : BaseUserPreferences() {
override val keyValuesFileManager: KeyValuesFileManager =
ServiceManager.getContextService(XMLFileManager::class.java)
}
class JsonUserPreferences : BaseUserPreferences() {
override val keyValuesFileManager: KeyValuesFileManager =
ServiceManager.getContextService(JsonFileManager::class.java)
}
object Preferences : UserPreferences by JsonUserPreferences() | 3 | Kotlin | 4 | 23 | a868d118c42a9ab0984bfd51ea845d3dcfd16449 | 2,559 | CatSpy | Apache License 2.0 |
androidApp/src/main/java/com/rld/justlisten/android/ui/playlistdetailscreen/PlaylistDetailScreen.kt | RLD-JL | 495,044,961 | false | {"Kotlin": 317519, "Swift": 344} | package com.rld.justlisten.android.ui.playlistdetailscreen
import android.graphics.drawable.ColorDrawable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.rld.justlisten.android.exoplayer.MusicServiceConnection
import com.rld.justlisten.android.ui.loadingscreen.LoadingScreen
import com.rld.justlisten.android.ui.playlistdetailscreen.components.AnimatedToolBar
import com.rld.justlisten.android.ui.playlistdetailscreen.components.BottomScrollableContent
import com.rld.justlisten.android.ui.utils.playMusic
import com.rld.justlisten.datalayer.models.SongIconList
import com.rld.justlisten.datalayer.models.UserModel
import com.rld.justlisten.viewmodel.screens.playlistdetail.PlaylistDetailState
@Composable
fun PlaylistDetailScreen(
playlistDetailState: PlaylistDetailState, onBackButtonPressed: (Boolean) -> Unit,
musicServiceConnection: MusicServiceConnection,
onSongPressed: (String) -> Unit,
onFavoritePressed: (String, String, UserModel, SongIconList, Boolean) -> Unit,
) {
if (playlistDetailState.isLoading) {
LoadingScreen()
} else {
val isPlayerReady: MutableState<Boolean> = remember {
mutableStateOf(false)
}
val painter = rememberAsyncImagePainter(
model = ImageRequest.Builder(context = LocalContext.current)
.placeholder(ColorDrawable(MaterialTheme.colors.secondaryVariant.toArgb()))
.data(playlistDetailState.playlistIcon).build()
)
val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// try to consume before LazyColumn to collapse toolbar if needed, hence pre-scroll
val delta = available.y
val newOffset = toolbarOffsetHeightPx.value + delta
if (newOffset < 0 && playlistDetailState.songPlaylist.size >= 5) {
toolbarOffsetHeightPx.value = newOffset
}
// here's the catch: let's pretend we consumed 0 in any case, since we want
// LazyColumn to scroll anyway for good UX
// We're basically watching scroll without taking it
return Offset.Zero
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
BottomScrollableContent(
playlistDetailState = playlistDetailState,
scrollState = toolbarOffsetHeightPx,
playlist = playlistDetailState.songPlaylist,
onShuffleClicked = {
playMusic(
musicServiceConnection,
playlistDetailState.songPlaylist,
isPlayerReady.value
)
isPlayerReady.value = true
},
onSongClicked = onSongPressed,
onFavoritePressed = onFavoritePressed,
painter = painter
)
AnimatedToolBar(playlistDetailState, toolbarOffsetHeightPx, onBackButtonPressed)
}
}
}
| 3 | Kotlin | 3 | 82 | f1d4281c534563d4660c40cb0b9e83435146a4d4 | 4,088 | Just-Listen | Apache License 2.0 |
app/src/main/java/com/ambient/simpleui/theme/Colors.kt | sidhu18 | 314,758,228 | false | null | package com.ambient.simpleui.theme
import androidx.compose.ui.graphics.Color
val Green300 = Color(0xff1abc9c)
val Green500 = Color(0xff16a085)
val Red200 = Color(0xfff297a2)
val Red800 = Color(0xffd00036)
// for bg
val dayBG = Color(0xfff3f7f9)
val nightBG = Color(0xff121212)
// for card colors
val day = Color(0xffffffff)
val night = Color(0xff1A191E)
// for text colors
val black = Color(0xff000000)
val white = Color(0xffffffff) | 0 | Kotlin | 0 | 0 | bb9c43259a39698d4cb62eeaafc0b1b24243785a | 438 | SimpleUI | Apache License 2.0 |
app/src/sharedTest/java/com/paradigma/rickandmorty/mockwebserver/NoDataDispatcher.kt | txoksue | 442,830,441 | false | {"Kotlin": 114844} | package com.paradigma.rickandmorty.mockwebserver
import com.paradigma.rickandmorty.mockwebserver.LoaderData.load
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.RecordedRequest
class NoDataDispatcher : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
val responseBody = load("characters_no_data.json")
return MockResponse().setResponseCode(200).setBody(responseBody)
}
} | 0 | Kotlin | 0 | 0 | ee5c777edb28d9bbde6df0159e0794df2e7d5648 | 490 | rickandmorty-app | MIT License |
app/src/main/java/com/rodrigolmti/lunch/money/companion/features/home/ui/HomeViewModel.kt | Rodrigolmti | 737,641,287 | false | {"Kotlin": 166709} | package com.rodrigolmti.lunch.money.companion.features.home.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rodrigolmti.lunch.money.companion.core.Outcome
import com.rodrigolmti.lunch.money.companion.core.LunchError
import com.rodrigolmti.lunch.money.companion.core.onFailure
import com.rodrigolmti.lunch.money.companion.core.onSuccess
import com.rodrigolmti.lunch.money.companion.features.home.model.AssetOverviewView
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
internal abstract class IHomeViewModel : ViewModel(), IHomeUIModel
private typealias GetAccountOverview = suspend () -> Outcome<List<AssetOverviewView>, LunchError>
private typealias RefreshUserData = suspend () -> Outcome<Unit, LunchError>
internal class HomeViewModel(
private val getUserAccountOverview: GetAccountOverview,
private val refreshUserData: RefreshUserData,
) : IHomeViewModel() {
private val _viewState = MutableStateFlow<HomeUiState>(HomeUiState.Loading)
override val viewState: StateFlow<HomeUiState> = _viewState
init {
getAccountOverview()
}
override fun getAccountOverview() {
viewModelScope.launch {
_viewState.value = HomeUiState.Loading
getUserAccountOverview().onSuccess {
_viewState.value = HomeUiState.Success(it)
}.onFailure {
_viewState.value = HomeUiState.Error
}
}
}
override fun onRefresh() {
viewModelScope.launch {
_viewState.value = HomeUiState.Loading
refreshUserData().onSuccess {
getAccountOverview()
}.onFailure {
_viewState.value = HomeUiState.Error
}
}
}
} | 0 | Kotlin | 0 | 4 | 5e1e120b1e9542dc1026be08962795bf192d58d4 | 1,829 | lunch_money_companion | Apache License 2.0 |
Driver Mobile App/app/src/main/java/in/techware/lataxidriverapp/model/RegistrationBean.kt | BlondelSeumo | 272,554,453 | false | {"TSQL": 61756373, "PHP": 2277395, "Java": 2067539, "JavaScript": 103903, "Kotlin": 40327, "CSS": 25122, "HTML": 6107, "Hack": 3473} | package `in`.techware.lataxidriverapp.model
/**
* Created by <NAME> on 21 April, 2017.
* Package in.techware.lataxidriver.model
* Project LaTaxiDriver
*/
class RegistrationBean : BaseBean() {
var name: String= ""
var phone: String= ""
var email: String= ""
var password: String= ""
var location: String= ""
}
| 0 | TSQL | 4 | 1 | ba28a9ba6129a502a3f5081d9a999d4b2c2da165 | 339 | On-Demand-Taxi-Booking-Application | MIT License |
shared/src/commonMain/kotlin/ch/dreipol/multiplatform/reduxsample/shared/ui/HeaderViewState.kt | terrakok | 334,467,384 | true | {"Kotlin": 145354, "Swift": 99066, "Ruby": 16325, "Shell": 483} | package ch.dreipol.multiplatform.reduxsample.shared.ui
data class HeaderViewState(val title: String, val iconLeft: String = "ic_36_chevron_left") | 0 | Kotlin | 0 | 1 | d35f0034f3fa870c00dd783d692dc586c8785614 | 146 | multiplatform-redux-sample | MIT License |
buildSrc/src/main/kotlin/ModPlugin.kt | MrBean355 | 302,406,828 | false | null | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.gradle.api.Plugin
import org.gradle.api.Project
class ModPlugin : Plugin<Project> {
override fun apply(target: Project) {
val extension = target.extensions.create("mod", ModExtension::class.java)
target.tasks.register("buildMod", BuildModTask::class.java) {
it.replacements = extension.allReplacements
it.fileRenames = extension.allFileRenames
it.emoticons = extension.allEmoticons
}
target.tasks.register("publishMod", PublishModTask::class.java)
}
}
fun Project.dotaMod(configure: ModExtension.() -> Unit) =
extensions.getByType(ModExtension::class.java).let(configure) | 0 | Kotlin | 0 | 3 | 46622790d080990a80ef59eb111cbdfafbdcaf42 | 1,257 | admiralbulldog-mod-split | Apache License 2.0 |
app/src/main/java/com/dluvian/voyage/ui/views/main/DrawerView.kt | dluvian | 766,355,809 | false | {"Kotlin": 1049080} | package com.dluvian.voyage.ui.views.main
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import com.dluvian.voyage.R
import com.dluvian.voyage.core.ClickBookmarks
import com.dluvian.voyage.core.ClickCreateList
import com.dluvian.voyage.core.ClickFollowLists
import com.dluvian.voyage.core.ClickMuteList
import com.dluvian.voyage.core.ClickRelayEditor
import com.dluvian.voyage.core.ClickSettings
import com.dluvian.voyage.core.CloseDrawer
import com.dluvian.voyage.core.ComposableContent
import com.dluvian.voyage.core.DeleteList
import com.dluvian.voyage.core.DrawerViewSubscribeSets
import com.dluvian.voyage.core.EditList
import com.dluvian.voyage.core.Fn
import com.dluvian.voyage.core.OnUpdate
import com.dluvian.voyage.core.OpenList
import com.dluvian.voyage.core.OpenProfile
import com.dluvian.voyage.core.viewModel.DrawerViewModel
import com.dluvian.voyage.data.model.ItemSetMeta
import com.dluvian.voyage.data.nostr.createNprofile
import com.dluvian.voyage.ui.theme.AccountIcon
import com.dluvian.voyage.ui.theme.AddIcon
import com.dluvian.voyage.ui.theme.BookmarksIcon
import com.dluvian.voyage.ui.theme.ListIcon
import com.dluvian.voyage.ui.theme.MuteIcon
import com.dluvian.voyage.ui.theme.RelayIcon
import com.dluvian.voyage.ui.theme.SettingsIcon
import com.dluvian.voyage.ui.theme.ViewListIcon
import com.dluvian.voyage.ui.theme.light
import com.dluvian.voyage.ui.theme.spacing
import kotlinx.coroutines.CoroutineScope
@Composable
fun MainDrawer(
vm: DrawerViewModel,
scope: CoroutineScope,
onUpdate: OnUpdate,
content: ComposableContent
) {
val personalProfile by vm.personalProfile.collectAsState()
val itemSets by vm.itemSetMetas.collectAsState()
ModalNavigationDrawer(drawerState = vm.drawerState, drawerContent = {
ModalDrawerSheet {
LaunchedEffect(key1 = vm.drawerState.isOpen) {
if (vm.drawerState.isOpen) onUpdate(DrawerViewSubscribeSets)
}
LazyColumn {
item { Spacer(modifier = Modifier.height(spacing.screenEdge)) }
item {
DrawerRow(
label = personalProfile.name,
icon = AccountIcon,
onClick = {
onUpdate(
OpenProfile(nprofile = createNprofile(hex = personalProfile.pubkey))
)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
DrawerRow(
label = stringResource(id = R.string.follow_lists),
icon = ListIcon,
onClick = {
onUpdate(ClickFollowLists)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
DrawerRow(
label = stringResource(id = R.string.bookmarks),
icon = BookmarksIcon,
onClick = {
onUpdate(ClickBookmarks)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
DrawerRow(
label = stringResource(id = R.string.relays),
icon = RelayIcon,
onClick = {
onUpdate(ClickRelayEditor)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
DrawerRow(
label = stringResource(id = R.string.mute_list),
icon = MuteIcon,
onClick = {
onUpdate(ClickMuteList)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
DrawerRow(
label = stringResource(id = R.string.settings),
icon = SettingsIcon,
onClick = {
onUpdate(ClickSettings)
onUpdate(CloseDrawer(scope = scope))
})
}
item {
HorizontalDivider(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = spacing.medium)
)
}
items(itemSets) {
DrawerListItem(meta = it, scope = scope, onUpdate = onUpdate)
}
item {
DrawerRow(
modifier = Modifier.padding(bottom = spacing.bottomPadding),
label = stringResource(id = R.string.create_a_list),
icon = AddIcon,
onClick = {
onUpdate(ClickCreateList)
onUpdate(CloseDrawer(scope = scope))
})
}
}
}
}) {
content()
}
}
@Composable
private fun DrawerListItem(meta: ItemSetMeta, scope: CoroutineScope, onUpdate: OnUpdate) {
val showMenu = remember { mutableStateOf(false) }
Box {
ItemSetOptionsMenu(
isExpanded = showMenu.value,
identifier = meta.identifier,
scope = scope,
onDismiss = { showMenu.value = false },
onUpdate = onUpdate
)
DrawerRow(
label = meta.title,
modifier = Modifier.fillMaxWidth(),
icon = ViewListIcon,
onClick = {
onUpdate(OpenList(identifier = meta.identifier))
onUpdate(CloseDrawer(scope = scope))
},
onLongClick = { showMenu.value = true }
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun DrawerRow(
icon: ImageVector,
label: String,
modifier: Modifier = Modifier,
onClick: Fn,
onLongClick: Fn = {}
) {
Row(
modifier = modifier
.fillMaxWidth()
.combinedClickable(
onClick = onClick,
onLongClick = onLongClick,
)
.padding(horizontal = spacing.bigScreenEdge, vertical = spacing.xl)
.padding(start = spacing.small),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = icon,
tint = LocalContentColor.current.light(0.85f),
contentDescription = label
)
Spacer(modifier = Modifier.width(spacing.xl))
Text(text = label, color = LocalContentColor.current.light(0.85f))
}
}
@Composable
private fun ItemSetOptionsMenu(
isExpanded: Boolean,
identifier: String,
scope: CoroutineScope,
modifier: Modifier = Modifier,
onDismiss: Fn,
onUpdate: OnUpdate,
) {
val onCloseDrawer = { onUpdate(CloseDrawer(scope = scope)) }
DropdownMenu(
modifier = modifier,
expanded = isExpanded,
onDismissRequest = onDismiss
) {
DropdownMenuItem(
text = { Text(text = stringResource(R.string.edit_list)) },
onClick = {
onUpdate(EditList(identifier = identifier))
onCloseDrawer()
onDismiss()
}
)
DropdownMenuItem(
text = { Text(text = stringResource(R.string.delete_list)) },
onClick = {
onUpdate(DeleteList(identifier = identifier, onCloseDrawer = onCloseDrawer))
onDismiss()
}
)
}
}
| 36 | Kotlin | 4 | 40 | e117d2d00f1e92bc0d5117055169b03906feb479 | 9,157 | voyage | MIT License |
arrow-libs/optics/arrow-match/src/wasmJsMain/kotlin/arrow/match/Matcher.kt | arrow-kt | 86,057,409 | false | {"Kotlin": 2010028, "Java": 434} | package arrow.match
public actual fun <S, A> Matcher(
name: String,
get: (S) -> A
): Matcher<S, A> = object : Matcher<S, A> {
override val name: String = name
override fun get(receiver: S): A = get(receiver)
override fun invoke(receiver: S): A = get(receiver)
}
| 43 | Kotlin | 448 | 6,168 | cb363449e925ebae1dd3eca5c3292d492a639791 | 273 | arrow | Apache License 2.0 |
payments-core/src/main/java/com/stripe/android/analytics/PaymentSessionEvent.kt | stripe | 6,926,049 | false | null | package com.stripe.android.analytics
import com.stripe.android.core.exception.safeAnalyticsMessage
import com.stripe.android.core.networking.AnalyticsEvent
import kotlin.time.Duration
import kotlin.time.DurationUnit
internal sealed class PaymentSessionEvent : AnalyticsEvent {
abstract val additionalParams: Map<String, Any?>
class LoadStarted : PaymentSessionEvent() {
override val eventName: String = "bi_load_started"
override val additionalParams: Map<String, Any?> = emptyMap()
}
class LoadSucceeded(
code: String?,
duration: Duration?,
) : PaymentSessionEvent() {
override val eventName: String = "bi_load_succeeded"
override val additionalParams: Map<String, Any?> = mapOf(
FIELD_DURATION to duration?.asSeconds,
FIELD_SELECTED_LPM to code,
)
}
class LoadFailed(
duration: Duration?,
error: Throwable,
) : PaymentSessionEvent() {
override val eventName: String = "bi_load_failed"
override val additionalParams: Map<String, Any?> = mapOf(
FIELD_DURATION to duration?.asSeconds,
FIELD_ERROR_MESSAGE to error.safeAnalyticsMessage,
)
}
class ShowPaymentOptions : PaymentSessionEvent() {
override val eventName: String = "bi_options_shown"
override val additionalParams: Map<String, Any?> = mapOf()
}
class ShowPaymentOptionForm(
code: String,
) : PaymentSessionEvent() {
override val eventName: String = "bi_form_shown"
override val additionalParams: Map<String, Any?> = mapOf(
FIELD_SELECTED_LPM to code,
)
}
class PaymentOptionFormInteraction(
code: String,
) : PaymentSessionEvent() {
override val eventName: String = "bi_form_interacted"
override val additionalParams: Map<String, Any?> = mapOf(
FIELD_SELECTED_LPM to code,
)
}
class CardNumberCompleted : PaymentSessionEvent() {
override val eventName: String = "bi_card_number_completed"
override val additionalParams: Map<String, Any?> = mapOf()
}
class TapDoneButton(
code: String,
duration: Duration?,
) : PaymentSessionEvent() {
override val eventName: String = "bi_done_button_tapped"
override val additionalParams: Map<String, Any?> = mapOf(
FIELD_SELECTED_LPM to code,
FIELD_DURATION to duration?.asSeconds,
)
}
internal companion object {
private val Duration.asSeconds: Float
get() = toDouble(DurationUnit.SECONDS).toFloat()
const val FIELD_DURATION = "duration"
const val FIELD_ERROR_MESSAGE = "error_message"
const val FIELD_SELECTED_LPM = "selected_lpm"
}
}
| 104 | null | 644 | 1,275 | 4fa2a1a9ca21edad1b687e30861e23e07907264d | 2,817 | stripe-android | MIT License |
frontend/src/jsMain/kotlin/com/monkopedia/konstructor/frontend/utils/ReactKoin.kt | Monkopedia | 418,215,448 | false | null | /*
* Copyright 2022 Jason Monk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.monkopedia.konstructor.frontend.utils
import io.ktor.utils.io.core.Closeable
import kotlinx.coroutines.flow.Flow
import org.koin.core.component.KoinComponent
import org.koin.core.component.KoinScopeComponent
import org.koin.core.component.get
import react.useMemo
import react.useRef
import react.useState
inline fun <reified T : KoinScopeComponent> KoinComponent.useSubScope(
crossinline getter: KoinComponent.() -> T = { get() }
): T {
val createdScope = useMemo(this) {
getter()
}
val first = useRef(true)
val (scope, setScope) = useState(createdScope)
react.useEffect(this@useSubScope) {
if (first.current == true) {
first.current = false
} else {
setScope(createdScope)
}
cleanup {
createdScope.scope.close()
}
}
return scope
}
inline fun <reified T : Closeable> KoinComponent.useCloseable(
crossinline getter: KoinComponent.() -> T = { get() }
): T {
val createdScope = useMemo(this) {
getter()
}
val first = useRef(true)
val (scope, setScope) = useState(createdScope)
react.useEffect(this@useCloseable) {
if (first.current == true) {
first.current = false
} else {
setScope(createdScope)
}
cleanup {
createdScope.close()
}
}
return scope
}
inline fun <reified T> KoinComponent.useCollected(
crossinline flow: KoinComponent.() -> Flow<T>,
): T? = useCollected(null, flow)
inline fun <reified T> KoinComponent.useCollected(
initial: T,
crossinline flow: KoinComponent.() -> Flow<T>
): T {
val flow = useMemo(this@useCollected) {
flow()
}
return flow.useCollected(initial)
}
| 0 | Kotlin | 0 | 0 | 597c1c7b193734451ad9846e9010d98e1de3f1d5 | 2,358 | Konstructor | Apache License 2.0 |
src/main/kotlin/org/kalasim/monitors/MetricMonitor.kt | holgerbrandl | 299,282,108 | false | null | package org.kalasim.monitors
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
import org.kalasim.analysis.snapshot.StatisticalSummarySnapshot
import org.kalasim.misc.*
import org.koin.core.Koin
import kotlin.math.roundToInt
class NumericStatisticMonitor(name: String? = null, koin: Koin = DependencyContext.get()) :
Monitor<Number>(name, koin), ValueMonitor<Number> {
private val sumStats = ifEnabled { DescriptiveStatistics() }
val values: DoubleArray
get() = sumStats.values
override fun addValue(value: Number) {
if (!enabled) return
sumStats.addValue(value.toDouble())
}
/** Increment the current value by 1 and add it as value. Autostart with 0 if there is no prior value. */
operator fun inc(): NumericStatisticMonitor {
val roundToInt = (values.lastOrNull() ?: 0.0).roundToInt()
addValue((roundToInt + 1).toDouble())
return this
}
operator fun dec(): NumericStatisticMonitor {
val roundToInt = values.last()
addValue((roundToInt - 1))
return this
}
override fun reset() = sumStats.clear()
// open fun mean(): Double? = sumStats.mean
// open fun standardDeviation(): Double? = sumStats.mean
// fun statistics(): DescriptiveStatistics = DescriptiveStatistics(sumStats.values)
fun printHistogram(binCount: Int = NUM_HIST_BINS) {
// val histJson = JSONArray(GSON.toJson(histogramScaled))
// json {
// "name" to name
// "type" to <EMAIL> //"queue statistics"
// "entries" to n
// "mean" to mean
// "minimum" to min
// "maximum" to max
// }.toString(2).println()
// val histogram = sumStats.buildHistogram()
// val colWidth = 40.0
//
// val histogramScaled = histogram.map { (range, value) -> range to colWidth * value / sumStats.n }
println("Summary of: '${name}'")
statistics().printThis()
if (values.size > 2) {
println("Histogram of: '${name}'")
sumStats.buildHistogram(binCount).printHistogram()
} else {
println("Skipping histogram of '$name' because of to few data")
}
}
fun statistics(excludeZeros: Boolean = false, rollingStats: Boolean = false): StatisticalSummarySnapshot {
require(!rollingStats) { TODO() }
// val stats: StatisticalSummary = if(rollingStats) SummaryStatistics() else DescriptiveStatistics()
val stats = DescriptiveStatistics()
if (excludeZeros) {
values.filter { it > 0 }.forEach {
stats.addValue(it)
}
// SummaryStatistics().apply { values.filter { it > 0 }.forEach { addValue(it) } }
} else {
values.forEach { stats.addValue(it) }
}
return StatisticalSummarySnapshot(stats)
}
override val snapshot
get() = statistics(false)
}
| 7 | null | 7 | 71 | 550f7dde2db737ad6d4186a3f439894d1e0455f2 | 3,007 | kalasim | MIT License |
buildSrc/src/main/java/com.rickandmorty.buildsrc/Dependencies.kt | AlvaroQ | 679,809,906 | false | {"Kotlin": 74212} | package com.rickandmorty.buildsrc
object Config {
const val applicationId = "com.rickandmorty"
const val minSdk = 26
const val targetSdk = 34
const val compileSdk = 34
const val name = "0.0.1"
const val code = 1
}
object Gradle {
private const val gradleVersion = "8.1.1"
private const val kotlinVersion = "1.7.21"
const val androidPlugin = "com.android.tools.build:gradle:${gradleVersion}"
const val versionsPlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}"
}
object Libs {
object Retrofit {
private const val version = "2.9.0"
const val retrofit = "com.squareup.retrofit2:retrofit:$version"
const val converterGson = "com.squareup.retrofit2:converter-gson:$version"
}
object OkHttp3 {
private const val version = "4.11.0"
const val loginInterceptor = "com.squareup.okhttp3:logging-interceptor:$version"
const val mockWebServer = "com.squareup.okhttp3:mockwebserver:$version"
}
object Arrow {
private const val version = "1.1.5"
const val core = "io.arrow-kt:arrow-core:$version"
const val coredata = "io.arrow-kt:arrow-core-data:0.10.3"
}
object Glide {
private const val version = "4.16.0"
const val glide = "com.github.bumptech.glide:glide:$version"
const val compiler = "com.github.bumptech.glide:compiler:$version"
}
object Coil {
private const val version = "2.2.0"
const val compose = "io.coil-kt:coil-compose:$version"
const val gif = "io.coil-kt:coil-gif:$version"
}
object JavaX {
const val inject = "javax.inject:javax.inject:1"
}
object Hilt {
const val version = "2.47"
const val android = "com.google.dagger:hilt-android:$version"
const val compiler = "com.google.dagger:hilt-compiler:$version"
const val gradlePlugin = "com.google.dagger:hilt-android-gradle-plugin:$version"
const val test = "com.google.dagger:hilt-android-testing:$version"
const val navigationCompose = "androidx.hilt:hilt-navigation-compose:1.0.0"
}
object Kotlin {
const val version = "1.8.10"
const val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version"
object Coroutines {
private const val version = "1.7.1"
// const val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1"
const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$version"
const val test = "org.jetbrains.kotlinx:kotlinx-coroutines-test:$version"
}
}
object AndroidX {
const val coreKtx = "androidx.core:core-ktx:1.10.1"
const val appCompat = "androidx.appcompat:appcompat:1.6.1"
const val recyclerView = "androidx.recyclerview:recyclerview:1.3.0"
const val material = "com.google.android.material:material:1.9.0"
const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.1.4"
object Activity {
private const val version = "1.7.2"
const val ktx = "androidx.activity:activity-ktx:$version"
const val compose = "androidx.activity:activity-compose:$version"
}
object Lifecycle {
private const val version = "2.6.1"
const val viewmodelKtx = "androidx.lifecycle:lifecycle-viewmodel-ktx:$version"
const val runtimeKtx = "androidx.lifecycle:lifecycle-runtime-ktx:$version"
const val viewmodelCompose = "androidx.lifecycle:lifecycle-viewmodel-compose:$version"
}
object Navigation {
const val version = "2.7.3"
const val fragmentKtx = "androidx.navigation:navigation-fragment-ktx:$version"
const val uiKtx = "androidx.navigation:navigation-ui-ktx:$version"
// const val gradlePlugin =
// "androidx.navigation:navigation-safe-args-gradle-plugin:$version"
const val compose = "androidx.navigation:navigation-compose:$version"
}
object Room {
private const val version = "2.5.2"
const val runtime = "androidx.room:room-runtime:$version"
const val ktx = "androidx.room:room-ktx:$version"
const val compiler = "androidx.room:room-compiler:$version"
}
object Test {
private const val version = "1.5.0"
const val runner = "androidx.test:runner:$version"
const val rules = "androidx.test:rules:$version"
object Ext {
private const val version = "1.1.5"
const val junit = "androidx.test.ext:junit-ktx:$version"
}
object Espresso {
private const val version = "3.5.1"
const val contrib = "androidx.test.espresso:espresso-contrib:$version"
}
}
object Compose {
object UI {
private const val version = "1.5.0"
const val ui = "androidx.compose.ui:ui:$version"
const val tooling = "androidx.compose.ui:ui-tooling:$version"
const val toolingPreview = "androidx.compose.ui:ui-tooling-preview:$version"
}
object Material3 {
const val material3 = "androidx.compose.material3:material3:1.2.0-alpha05"
const val materialIconsExtended =
"androidx.compose.material:material-icons-extended-android:1.5.0"
}
}
}
object JUnit {
private const val version = "4.13.2"
const val junit = "junit:junit:$version"
}
object Mockito {
const val kotlin = "org.mockito.kotlin:mockito-kotlin:5.0.0"
const val inline = "org.mockito:mockito-inline:5.2.0"
}
} | 0 | Kotlin | 0 | 0 | 4ddcc6e983ee5b50c27069da7855276b72879a21 | 5,861 | RickAndMorty | Apache License 2.0 |
app/src/main/java/org/simple/clinic/introvideoscreen/IntroVideoEffectHandler.kt | KelvnPere | 310,601,209 | true | {"Kotlin": 4452962, "Shell": 3616, "Python": 3162} | package org.simple.clinic.introvideoscreen
import com.spotify.mobius.rx2.RxMobius
import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject
import io.reactivex.ObservableTransformer
import org.simple.clinic.util.scheduler.SchedulersProvider
class IntroVideoEffectHandler @AssistedInject constructor(
@Assisted val uiActions: UiActions,
val schedulersProvider: SchedulersProvider
) {
@AssistedInject.Factory
interface Factory {
fun create(uiActions: UiActions): IntroVideoEffectHandler
}
fun build(): ObservableTransformer<IntroVideoEffect, IntroVideoEvent> = RxMobius
.subtypeEffectHandler<IntroVideoEffect, IntroVideoEvent>()
.addAction(OpenVideo::class.java, { uiActions.openVideo() }, schedulersProvider.ui())
.addAction(OpenHome::class.java, { uiActions.openHome() }, schedulersProvider.ui())
.build()
}
| 0 | null | 0 | 0 | 79b5055be07a4e9b46b84b0a157bb07f6cc254ad | 894 | simple-android | MIT License |
src/test/kotlin/g0501_0600/s0504_base_7/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0504_base_7
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun convertToBase7() {
assertThat(Solution().convertToBase7(100), equalTo("202"))
}
@Test
fun convertToBase72() {
assertThat(Solution().convertToBase7(-7), equalTo("-10"))
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 407 | LeetCode-in-Kotlin | MIT License |
app/src/main/java/com/sachin/app/storyapp/data/repository/DetailRepository.kt | sachinkumar53 | 684,631,959 | false | {"Kotlin": 138151} | package com.sachin.app.storyapp.data.repository
import android.content.Context
import android.text.format.DateFormat
import com.google.firebase.firestore.CollectionReference
import com.sachin.app.storyapp.data.di.PublicationCollectionRef
import com.sachin.app.storyapp.data.di.UserCollectionRef
import com.sachin.app.storyapp.data.model.Rating
import com.sachin.app.storyapp.data.model.StoryDetail
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class DetailRepository @Inject constructor(
@ApplicationContext
private val context: Context,
@PublicationCollectionRef
private val publications: CollectionReference,
@UserCollectionRef
private val users: CollectionReference,
private val reviewRepository: ReviewRepository
) {
suspend fun getStory(storyId: String): StoryDetail {
return publications.document(storyId)
.get().await().let { document ->
val author = users.document(document["author_id"].toString()).get().await()
val rating = reviewRepository.getTotalRating(storyId).firstOrNull()
StoryDetail(
id = document.id,
coverUrl = document["cover_url"].toString(),
title = document["title"].toString(),
description = document["description"].toString(),
content = document["content"].toString(),
publishedDate = DateFormat.getLongDateFormat(context).format(
document["published_on"].toString().toLong()
),
authorName = author["name"].toString(),
authorPhotoUrl = author["photo_url"].toString(),
rating = rating ?: Rating.zero(),
genre = document["genre"].toString()
)
}
}
}
| 0 | Kotlin | 0 | 0 | 2e5edc23ec66e27ae1054b8236bcbc728bcbaeee | 1,973 | StoryApp | MIT License |
src/main/kotlin/kr/co/finda/androidtemplate/model/ScreenType.kt | FindaDeveloper | 337,247,380 | false | null | package kr.co.finda.androidtemplate.model
enum class ScreenType(
val postfix: String,
val template: Template
) {
ACTIVITY("Activity", Template.ACTIVITY),
FRAGMENT("Fragment", Template.FRAGMENT),
BOTTOM_SHEET("BottomSheet", Template.BOTTOM_SHEET),
} | 5 | Kotlin | 1 | 5 | f75cbf9e89c8b2233a5a30d06f1ffa26e770010c | 269 | FindaTemplatePlugin-Android | MIT License |
src/main/kotlin/com/bsuir/hrm/dataanalyzer/DataAnalyzerApplication.kt | herman2lv | 640,611,590 | false | null | package com.bsuir.hrm.dataanalyzer
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.context.annotation.Bean
import org.springframework.web.client.RestTemplate
@SpringBootApplication
class DataAnalyzerApplication {
@Bean
fun restTemplate(builder: RestTemplateBuilder): RestTemplate {
return builder.build()
}
}
fun main(args: Array<String>) {
runApplication<DataAnalyzerApplication>(*args)
}
| 0 | Kotlin | 0 | 1 | 32cbd51b25c12d866ad5ec255c779201c9bfa1b8 | 576 | market-analyzer-lab | Apache License 2.0 |
app/src/main/java/com/zjamss/sunny/logic/Repository.kt | ZJamss | 459,480,104 | false | null | package com.zjamss.sunny.logic
import android.content.Context
import androidx.lifecycle.liveData
import com.zjamss.sunny.logic.dao.PlaceDao
import com.zjamss.sunny.logic.exception.GlobalException
import com.zjamss.sunny.logic.model.DailyResponse
import com.zjamss.sunny.logic.model.Place
import com.zjamss.sunny.logic.model.Weather
import com.zjamss.sunny.logic.service.SunnyService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import java.lang.Exception
import kotlin.coroutines.CoroutineContext
/**
* @Description: 仓库类
* @Author: ZJamss
* @Create: 2022/2/15 21:48
**/
object Repository {
//liveData()函数中提供了一个挂起函数的上下文
fun searchPlaces(query: String) = fire(Dispatchers.IO) {
val placeResponse = SunnyService.searchPlaces(query)
if (placeResponse.status == "ok") {
val places = placeResponse.places
Result.success(places)
} else {
Result.failure(GlobalException.ResponseStatusErrorException(eName = "响应状态:${placeResponse.status}"))
}
}
fun refreshWeather(lng: String, lat: String) = fire(Dispatchers.IO) {
coroutineScope {
val deferredRealtime = async {
SunnyService.getRealtimeWeather(lng, lat)
}
val deferredDaily = async {
SunnyService.getDailyWeather(lng, lat)
}
val realtimeResponse = deferredRealtime.await()
val dailyResponse = deferredDaily.await()
if (realtimeResponse.status == "ok" && dailyResponse.status == "ok") {
val weather =
Weather(realtimeResponse.result.realtime, dailyResponse.result.daily)
Result.success(weather)
} else {
Result.failure(GlobalException.ResponseStatusErrorException())
}
}
}
private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
liveData<Result<T>>(context) {
val result = try {
block()
} catch (e: Exception) {
Result.failure<T>(e)
}
emit(result)
}
fun savePlace(place: Place) = PlaceDao.savePlace(place)
fun getSavedPlace() = PlaceDao.getSavePlace()
fun isPlaceSaved() = PlaceDao.isPlaceSaved()
} | 0 | Kotlin | 0 | 0 | f3ecf00897bec4cf7be864ed854e344fe187e12e | 2,370 | Sunny | Apache License 2.0 |
src/main/kotlin/com/bastronaut/traderboard/models/Symbol.kt | bastronaut | 127,566,728 | false | null | package com.bastronaut.traderboard.models
/**
* Class to represent a trading symbol
*/
class Symbol
| 0 | Kotlin | 0 | 0 | 5ba1c9e2969eddcf2ba62e026fbbf68999cdd417 | 104 | traderboard | MIT License |
Control Flow/Latihan/Latihan 3/src/Task.kt | anangkur | 200,490,004 | false | null | fun main() {
val listNumber = 1.rangeTo(30)
for (number in listNumber) {
// TODO 1
if (number%2 == 0)
continue
// TODO
if (number > 10)
break
// TODO 3
val result = ((2 + number) * number)
println("result is $result")
}
} | 0 | Kotlin | 1 | 0 | e2151c0a27075f47a1963f0c802ff6b834b3b849 | 316 | dicoding-basic-kotlin-submission | MIT License |
app/src/main/java/com/oxapps/materialcountdown/creation/CategoryPickerDialog.kt | Flozzo | 46,596,362 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "Java": 4, "XML": 35, "Kotlin": 13} | /*
* 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
*
* 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.oxapps.materialcountdown.creation
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatDialog
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.ListView
import android.widget.SimpleAdapter
import com.oxapps.materialcountdown.R
import com.oxapps.materialcountdown.model.Category
class CategoryPickerDialog(context: Context) : AppCompatDialog(context) {
lateinit var onCategorySet: (category: Category) -> Unit
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.set_category)
val categoryList = layoutInflater.inflate(R.layout.dialog_category_list, null) as ListView
val categoryMap = Category.values().map { category ->
mapOf(
"icon" to getGreyDrawable(category.icon),
"name" to context.getString(category.getName())
)
}
val from = arrayOf("icon", "name")
val to = intArrayOf(R.id.iv_category_logo, R.id.category_name)
val adapter = SimpleAdapter(context, categoryMap, R.layout.category_item, from, to)
adapter.viewBinder = SimpleAdapter.ViewBinder { view, data, _ ->
if (view is ImageView) {
view.setImageDrawable(data as Drawable)
return@ViewBinder true
}
false
}
categoryList.divider = null
categoryList.adapter = adapter
setContentView(categoryList)
categoryList.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
val category = Category.values()[position]
onCategorySet(category)
hide()
}
}
private fun getGreyDrawable(icon: Int): Drawable {
val drawable = ContextCompat.getDrawable(context, icon)!!.mutate()
drawable.setColorFilter(-0x76000000, PorterDuff.Mode.MULTIPLY)
return drawable
}
}
| 1 | null | 1 | 1 | 3eb52ad33004f6c76b45afdb9f2911afc0e6b805 | 2,717 | MaterialCountdown | Apache License 2.0 |
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/unidecode/x98.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4427197, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.formats.unidecode
internal val x98 = arrayOf(
// 0x9800: 頀 => Hu
"\u0048\u0075\u0020",
// 0x9801: 頁 => Ye
"\u0059\u0065\u0020",
// 0x9802: 頂 => Ding
"\u0044\u0069\u006e\u0067\u0020",
// 0x9803: 頃 => Qing
"\u0051\u0069\u006e\u0067\u0020",
// 0x9804: 頄 => Pan
"\u0050\u0061\u006e\u0020",
// 0x9805: 項 => Xiang
"\u0058\u0069\u0061\u006e\u0067\u0020",
// 0x9806: 順 => Shun
"\u0053\u0068\u0075\u006e\u0020",
// 0x9807: 頇 => Han
"\u0048\u0061\u006e\u0020",
// 0x9808: 須 => Xu
"\u0058\u0075\u0020",
// 0x9809: 頉 => Yi
"\u0059\u0069\u0020",
// 0x980a: 頊 => Xu
"\u0058\u0075\u0020",
// 0x980b: 頋 => Gu
"\u0047\u0075\u0020",
// 0x980c: 頌 => Song
"\u0053\u006f\u006e\u0067\u0020",
// 0x980d: 頍 => Kui
"\u004b\u0075\u0069\u0020",
// 0x980e: 頎 => Qi
"\u0051\u0069\u0020",
// 0x980f: 頏 => Hang
"\u0048\u0061\u006e\u0067\u0020",
// 0x9810: 預 => Yu
"\u0059\u0075\u0020",
// 0x9811: 頑 => Wan
"\u0057\u0061\u006e\u0020",
// 0x9812: 頒 => Ban
"\u0042\u0061\u006e\u0020",
// 0x9813: 頓 => Dun
"\u0044\u0075\u006e\u0020",
// 0x9814: 頔 => Di
"\u0044\u0069\u0020",
// 0x9815: 頕 => Dan
"\u0044\u0061\u006e\u0020",
// 0x9816: 頖 => Pan
"\u0050\u0061\u006e\u0020",
// 0x9817: 頗 => Po
"\u0050\u006f\u0020",
// 0x9818: 領 => Ling
"\u004c\u0069\u006e\u0067\u0020",
// 0x9819: 頙 => Ce
"\u0043\u0065\u0020",
// 0x981a: 頚 => Jing
"\u004a\u0069\u006e\u0067\u0020",
// 0x981b: 頛 => Lei
"\u004c\u0065\u0069\u0020",
// 0x981c: 頜 => He
"\u0048\u0065\u0020",
// 0x981d: 頝 => Qiao
"\u0051\u0069\u0061\u006f\u0020",
// 0x981e: 頞 => E
"\u0045\u0020",
// 0x981f: 頟 => E
"\u0045\u0020",
// 0x9820: 頠 => Wei
"\u0057\u0065\u0069\u0020",
// 0x9821: 頡 => Jie
"\u004a\u0069\u0065\u0020",
// 0x9822: 頢 => Gua
"\u0047\u0075\u0061\u0020",
// 0x9823: 頣 => Shen
"\u0053\u0068\u0065\u006e\u0020",
// 0x9824: 頤 => Yi
"\u0059\u0069\u0020",
// 0x9825: 頥 => Shen
"\u0053\u0068\u0065\u006e\u0020",
// 0x9826: 頦 => Hai
"\u0048\u0061\u0069\u0020",
// 0x9827: 頧 => Dui
"\u0044\u0075\u0069\u0020",
// 0x9828: 頨 => Pian
"\u0050\u0069\u0061\u006e\u0020",
// 0x9829: 頩 => Ping
"\u0050\u0069\u006e\u0067\u0020",
// 0x982a: 頪 => Lei
"\u004c\u0065\u0069\u0020",
// 0x982b: 頫 => Fu
"\u0046\u0075\u0020",
// 0x982c: 頬 => Jia
"\u004a\u0069\u0061\u0020",
// 0x982d: 頭 => Tou
"\u0054\u006f\u0075\u0020",
// 0x982e: 頮 => Hui
"\u0048\u0075\u0069\u0020",
// 0x982f: 頯 => Kui
"\u004b\u0075\u0069\u0020",
// 0x9830: 頰 => Jia
"\u004a\u0069\u0061\u0020",
// 0x9831: 頱 => Le
"\u004c\u0065\u0020",
// 0x9832: 頲 => Tian
"\u0054\u0069\u0061\u006e\u0020",
// 0x9833: 頳 => Cheng
"\u0043\u0068\u0065\u006e\u0067\u0020",
// 0x9834: 頴 => Ying
"\u0059\u0069\u006e\u0067\u0020",
// 0x9835: 頵 => Jun
"\u004a\u0075\u006e\u0020",
// 0x9836: 頶 => Hu
"\u0048\u0075\u0020",
// 0x9837: 頷 => Han
"\u0048\u0061\u006e\u0020",
// 0x9838: 頸 => Jing
"\u004a\u0069\u006e\u0067\u0020",
// 0x9839: 頹 => Tui
"\u0054\u0075\u0069\u0020",
// 0x983a: 頺 => Tui
"\u0054\u0075\u0069\u0020",
// 0x983b: 頻 => Pin
"\u0050\u0069\u006e\u0020",
// 0x983c: 頼 => Lai
"\u004c\u0061\u0069\u0020",
// 0x983d: 頽 => Tui
"\u0054\u0075\u0069\u0020",
// 0x983e: 頾 => Zi
"\u005a\u0069\u0020",
// 0x983f: 頿 => Zi
"\u005a\u0069\u0020",
// 0x9840: 顀 => Chui
"\u0043\u0068\u0075\u0069\u0020",
// 0x9841: 顁 => Ding
"\u0044\u0069\u006e\u0067\u0020",
// 0x9842: 顂 => Lai
"\u004c\u0061\u0069\u0020",
// 0x9843: 顃 => Yan
"\u0059\u0061\u006e\u0020",
// 0x9844: 顄 => Han
"\u0048\u0061\u006e\u0020",
// 0x9845: 顅 => Jian
"\u004a\u0069\u0061\u006e\u0020",
// 0x9846: 顆 => Ke
"\u004b\u0065\u0020",
// 0x9847: 顇 => Cui
"\u0043\u0075\u0069\u0020",
// 0x9848: 顈 => Jiong
"\u004a\u0069\u006f\u006e\u0067\u0020",
// 0x9849: 顉 => Qin
"\u0051\u0069\u006e\u0020",
// 0x984a: 顊 => Yi
"\u0059\u0069\u0020",
// 0x984b: 顋 => Sai
"\u0053\u0061\u0069\u0020",
// 0x984c: 題 => Ti
"\u0054\u0069\u0020",
// 0x984d: 額 => E
"\u0045\u0020",
// 0x984e: 顎 => E
"\u0045\u0020",
// 0x984f: 顏 => Yan
"\u0059\u0061\u006e\u0020",
// 0x9850: 顐 => Hun
"\u0048\u0075\u006e\u0020",
// 0x9851: 顑 => Kan
"\u004b\u0061\u006e\u0020",
// 0x9852: 顒 => Yong
"\u0059\u006f\u006e\u0067\u0020",
// 0x9853: 顓 => Zhuan
"\u005a\u0068\u0075\u0061\u006e\u0020",
// 0x9854: 顔 => Yan
"\u0059\u0061\u006e\u0020",
// 0x9855: 顕 => Xian
"\u0058\u0069\u0061\u006e\u0020",
// 0x9856: 顖 => Xin
"\u0058\u0069\u006e\u0020",
// 0x9857: 顗 => Yi
"\u0059\u0069\u0020",
// 0x9858: 願 => Yuan
"\u0059\u0075\u0061\u006e\u0020",
// 0x9859: 顙 => Sang
"\u0053\u0061\u006e\u0067\u0020",
// 0x985a: 顚 => Dian
"\u0044\u0069\u0061\u006e\u0020",
// 0x985b: 顛 => Dian
"\u0044\u0069\u0061\u006e\u0020",
// 0x985c: 顜 => Jiang
"\u004a\u0069\u0061\u006e\u0067\u0020",
// 0x985d: 顝 => Ku
"\u004b\u0075\u0020",
// 0x985e: 類 => Lei
"\u004c\u0065\u0069\u0020",
// 0x985f: 顟 => Liao
"\u004c\u0069\u0061\u006f\u0020",
// 0x9860: 顠 => Piao
"\u0050\u0069\u0061\u006f\u0020",
// 0x9861: 顡 => Yi
"\u0059\u0069\u0020",
// 0x9862: 顢 => Man
"\u004d\u0061\u006e\u0020",
// 0x9863: 顣 => Qi
"\u0051\u0069\u0020",
// 0x9864: 顤 => Rao
"\u0052\u0061\u006f\u0020",
// 0x9865: 顥 => Hao
"\u0048\u0061\u006f\u0020",
// 0x9866: 顦 => Qiao
"\u0051\u0069\u0061\u006f\u0020",
// 0x9867: 顧 => Gu
"\u0047\u0075\u0020",
// 0x9868: 顨 => Xun
"\u0058\u0075\u006e\u0020",
// 0x9869: 顩 => Qian
"\u0051\u0069\u0061\u006e\u0020",
// 0x986a: 顪 => Hui
"\u0048\u0075\u0069\u0020",
// 0x986b: 顫 => Zhan
"\u005a\u0068\u0061\u006e\u0020",
// 0x986c: 顬 => Ru
"\u0052\u0075\u0020",
// 0x986d: 顭 => Hong
"\u0048\u006f\u006e\u0067\u0020",
// 0x986e: 顮 => Bin
"\u0042\u0069\u006e\u0020",
// 0x986f: 顯 => Xian
"\u0058\u0069\u0061\u006e\u0020",
// 0x9870: 顰 => Pin
"\u0050\u0069\u006e\u0020",
// 0x9871: 顱 => Lu
"\u004c\u0075\u0020",
// 0x9872: 顲 => Lan
"\u004c\u0061\u006e\u0020",
// 0x9873: 顳 => Nie
"\u004e\u0069\u0065\u0020",
// 0x9874: 顴 => Quan
"\u0051\u0075\u0061\u006e\u0020",
// 0x9875: 页 => Ye
"\u0059\u0065\u0020",
// 0x9876: 顶 => Ding
"\u0044\u0069\u006e\u0067\u0020",
// 0x9877: 顷 => Qing
"\u0051\u0069\u006e\u0067\u0020",
// 0x9878: 顸 => Han
"\u0048\u0061\u006e\u0020",
// 0x9879: 项 => Xiang
"\u0058\u0069\u0061\u006e\u0067\u0020",
// 0x987a: 顺 => Shun
"\u0053\u0068\u0075\u006e\u0020",
// 0x987b: 须 => Xu
"\u0058\u0075\u0020",
// 0x987c: 顼 => Xu
"\u0058\u0075\u0020",
// 0x987d: 顽 => Wan
"\u0057\u0061\u006e\u0020",
// 0x987e: 顾 => Gu
"\u0047\u0075\u0020",
// 0x987f: 顿 => Dun
"\u0044\u0075\u006e\u0020",
// 0x9880: 颀 => Qi
"\u0051\u0069\u0020",
// 0x9881: 颁 => Ban
"\u0042\u0061\u006e\u0020",
// 0x9882: 颂 => Song
"\u0053\u006f\u006e\u0067\u0020",
// 0x9883: 颃 => Hang
"\u0048\u0061\u006e\u0067\u0020",
// 0x9884: 预 => Yu
"\u0059\u0075\u0020",
// 0x9885: 颅 => Lu
"\u004c\u0075\u0020",
// 0x9886: 领 => Ling
"\u004c\u0069\u006e\u0067\u0020",
// 0x9887: 颇 => Po
"\u0050\u006f\u0020",
// 0x9888: 颈 => Jing
"\u004a\u0069\u006e\u0067\u0020",
// 0x9889: 颉 => Jie
"\u004a\u0069\u0065\u0020",
// 0x988a: 颊 => Jia
"\u004a\u0069\u0061\u0020",
// 0x988b: 颋 => Tian
"\u0054\u0069\u0061\u006e\u0020",
// 0x988c: 颌 => Han
"\u0048\u0061\u006e\u0020",
// 0x988d: 颍 => Ying
"\u0059\u0069\u006e\u0067\u0020",
// 0x988e: 颎 => Jiong
"\u004a\u0069\u006f\u006e\u0067\u0020",
// 0x988f: 颏 => Hai
"\u0048\u0061\u0069\u0020",
// 0x9890: 颐 => Yi
"\u0059\u0069\u0020",
// 0x9891: 频 => Pin
"\u0050\u0069\u006e\u0020",
// 0x9892: 颒 => Hui
"\u0048\u0075\u0069\u0020",
// 0x9893: 颓 => Tui
"\u0054\u0075\u0069\u0020",
// 0x9894: 颔 => Han
"\u0048\u0061\u006e\u0020",
// 0x9895: 颕 => Ying
"\u0059\u0069\u006e\u0067\u0020",
// 0x9896: 颖 => Ying
"\u0059\u0069\u006e\u0067\u0020",
// 0x9897: 颗 => Ke
"\u004b\u0065\u0020",
// 0x9898: 题 => Ti
"\u0054\u0069\u0020",
// 0x9899: 颙 => Yong
"\u0059\u006f\u006e\u0067\u0020",
// 0x989a: 颚 => E
"\u0045\u0020",
// 0x989b: 颛 => Zhuan
"\u005a\u0068\u0075\u0061\u006e\u0020",
// 0x989c: 颜 => Yan
"\u0059\u0061\u006e\u0020",
// 0x989d: 额 => E
"\u0045\u0020",
// 0x989e: 颞 => Nie
"\u004e\u0069\u0065\u0020",
// 0x989f: 颟 => Man
"\u004d\u0061\u006e\u0020",
// 0x98a0: 颠 => Dian
"\u0044\u0069\u0061\u006e\u0020",
// 0x98a1: 颡 => Sang
"\u0053\u0061\u006e\u0067\u0020",
// 0x98a2: 颢 => Hao
"\u0048\u0061\u006f\u0020",
// 0x98a3: 颣 => Lei
"\u004c\u0065\u0069\u0020",
// 0x98a4: 颤 => Zhan
"\u005a\u0068\u0061\u006e\u0020",
// 0x98a5: 颥 => Ru
"\u0052\u0075\u0020",
// 0x98a6: 颦 => Pin
"\u0050\u0069\u006e\u0020",
// 0x98a7: 颧 => Quan
"\u0051\u0075\u0061\u006e\u0020",
// 0x98a8: 風 => Feng
"\u0046\u0065\u006e\u0067\u0020",
// 0x98a9: 颩 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98aa: 颪 => Oroshi
"\u004f\u0072\u006f\u0073\u0068\u0069\u0020",
// 0x98ab: 颫 => Fu
"\u0046\u0075\u0020",
// 0x98ac: 颬 => Xia
"\u0058\u0069\u0061\u0020",
// 0x98ad: 颭 => Zhan
"\u005a\u0068\u0061\u006e\u0020",
// 0x98ae: 颮 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98af: 颯 => Sa
"\u0053\u0061\u0020",
// 0x98b0: 颰 => Ba
"\u0042\u0061\u0020",
// 0x98b1: 颱 => Tai
"\u0054\u0061\u0069\u0020",
// 0x98b2: 颲 => Lie
"\u004c\u0069\u0065\u0020",
// 0x98b3: 颳 => Gua
"\u0047\u0075\u0061\u0020",
// 0x98b4: 颴 => Xuan
"\u0058\u0075\u0061\u006e\u0020",
// 0x98b5: 颵 => Shao
"\u0053\u0068\u0061\u006f\u0020",
// 0x98b6: 颶 => Ju
"\u004a\u0075\u0020",
// 0x98b7: 颷 => Bi
"\u0042\u0069\u0020",
// 0x98b8: 颸 => Si
"\u0053\u0069\u0020",
// 0x98b9: 颹 => Wei
"\u0057\u0065\u0069\u0020",
// 0x98ba: 颺 => Yang
"\u0059\u0061\u006e\u0067\u0020",
// 0x98bb: 颻 => Yao
"\u0059\u0061\u006f\u0020",
// 0x98bc: 颼 => Sou
"\u0053\u006f\u0075\u0020",
// 0x98bd: 颽 => Kai
"\u004b\u0061\u0069\u0020",
// 0x98be: 颾 => Sao
"\u0053\u0061\u006f\u0020",
// 0x98bf: 颿 => Fan
"\u0046\u0061\u006e\u0020",
// 0x98c0: 飀 => Liu
"\u004c\u0069\u0075\u0020",
// 0x98c1: 飁 => Xi
"\u0058\u0069\u0020",
// 0x98c2: 飂 => Liao
"\u004c\u0069\u0061\u006f\u0020",
// 0x98c3: 飃 => Piao
"\u0050\u0069\u0061\u006f\u0020",
// 0x98c4: 飄 => Piao
"\u0050\u0069\u0061\u006f\u0020",
// 0x98c5: 飅 => Liu
"\u004c\u0069\u0075\u0020",
// 0x98c6: 飆 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98c7: 飇 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98c8: 飈 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98c9: 飉 => Liao
"\u004c\u0069\u0061\u006f\u0020",
// 0x98ca: 飊 => [?]
"\u005b\u003f\u005d\u0020",
// 0x98cb: 飋 => Se
"\u0053\u0065\u0020",
// 0x98cc: 飌 => Feng
"\u0046\u0065\u006e\u0067\u0020",
// 0x98cd: 飍 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98ce: 风 => Feng
"\u0046\u0065\u006e\u0067\u0020",
// 0x98cf: 飏 => Yang
"\u0059\u0061\u006e\u0067\u0020",
// 0x98d0: 飐 => Zhan
"\u005a\u0068\u0061\u006e\u0020",
// 0x98d1: 飑 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98d2: 飒 => Sa
"\u0053\u0061\u0020",
// 0x98d3: 飓 => Ju
"\u004a\u0075\u0020",
// 0x98d4: 飔 => Si
"\u0053\u0069\u0020",
// 0x98d5: 飕 => Sou
"\u0053\u006f\u0075\u0020",
// 0x98d6: 飖 => Yao
"\u0059\u0061\u006f\u0020",
// 0x98d7: 飗 => Liu
"\u004c\u0069\u0075\u0020",
// 0x98d8: 飘 => Piao
"\u0050\u0069\u0061\u006f\u0020",
// 0x98d9: 飙 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98da: 飚 => Biao
"\u0042\u0069\u0061\u006f\u0020",
// 0x98db: 飛 => Fei
"\u0046\u0065\u0069\u0020",
// 0x98dc: 飜 => Fan
"\u0046\u0061\u006e\u0020",
// 0x98dd: 飝 => Fei
"\u0046\u0065\u0069\u0020",
// 0x98de: 飞 => Fei
"\u0046\u0065\u0069\u0020",
// 0x98df: 食 => Shi
"\u0053\u0068\u0069\u0020",
// 0x98e0: 飠 => Shi
"\u0053\u0068\u0069\u0020",
// 0x98e1: 飡 => Can
"\u0043\u0061\u006e\u0020",
// 0x98e2: 飢 => Ji
"\u004a\u0069\u0020",
// 0x98e3: 飣 => Ding
"\u0044\u0069\u006e\u0067\u0020",
// 0x98e4: 飤 => Si
"\u0053\u0069\u0020",
// 0x98e5: 飥 => Tuo
"\u0054\u0075\u006f\u0020",
// 0x98e6: 飦 => Zhan
"\u005a\u0068\u0061\u006e\u0020",
// 0x98e7: 飧 => Sun
"\u0053\u0075\u006e\u0020",
// 0x98e8: 飨 => Xiang
"\u0058\u0069\u0061\u006e\u0067\u0020",
// 0x98e9: 飩 => Tun
"\u0054\u0075\u006e\u0020",
// 0x98ea: 飪 => Ren
"\u0052\u0065\u006e\u0020",
// 0x98eb: 飫 => Yu
"\u0059\u0075\u0020",
// 0x98ec: 飬 => Juan
"\u004a\u0075\u0061\u006e\u0020",
// 0x98ed: 飭 => Chi
"\u0043\u0068\u0069\u0020",
// 0x98ee: 飮 => Yin
"\u0059\u0069\u006e\u0020",
// 0x98ef: 飯 => Fan
"\u0046\u0061\u006e\u0020",
// 0x98f0: 飰 => Fan
"\u0046\u0061\u006e\u0020",
// 0x98f1: 飱 => Sun
"\u0053\u0075\u006e\u0020",
// 0x98f2: 飲 => Yin
"\u0059\u0069\u006e\u0020",
// 0x98f3: 飳 => Zhu
"\u005a\u0068\u0075\u0020",
// 0x98f4: 飴 => Yi
"\u0059\u0069\u0020",
// 0x98f5: 飵 => Zhai
"\u005a\u0068\u0061\u0069\u0020",
// 0x98f6: 飶 => Bi
"\u0042\u0069\u0020",
// 0x98f7: 飷 => Jie
"\u004a\u0069\u0065\u0020",
// 0x98f8: 飸 => Tao
"\u0054\u0061\u006f\u0020",
// 0x98f9: 飹 => Liu
"\u004c\u0069\u0075\u0020",
// 0x98fa: 飺 => Ci
"\u0043\u0069\u0020",
// 0x98fb: 飻 => Tie
"\u0054\u0069\u0065\u0020",
// 0x98fc: 飼 => Si
"\u0053\u0069\u0020",
// 0x98fd: 飽 => Bao
"\u0042\u0061\u006f\u0020",
// 0x98fe: 飾 => Shi
"\u0053\u0068\u0069\u0020",
// 0x98ff: 飿 => Duo
"\u0044\u0075\u006f\u0020",
)
| 8 | Kotlin | 6 | 25 | e18e9cf0bad7497da15b40f6c81ba4234ec83917 | 14,858 | kotwords | Apache License 2.0 |
src/main/kotlin/org/javacs/kt/KotlinWorkspaceService.kt | georgewfraser | 126,650,939 | false | {"Kotlin": 175368, "TypeScript": 6109, "Java": 6063, "Shell": 288} | package org.javacs.kt
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.services.WorkspaceService
import org.javacs.kt.symbols.workspaceSymbols
import java.net.URI
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
class KotlinWorkspaceService(private val sf: SourceFiles, private val sp: SourcePath, private val cp: CompilerClassPath) : WorkspaceService {
override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams) {
for (change in params.changes) {
val path = Paths.get(URI.create(change.uri))
when (change.type) {
FileChangeType.Created -> {
sf.createdOnDisk(path)
cp.createdOnDisk(path)
}
FileChangeType.Deleted -> {
sf.deletedOnDisk(path)
cp.deletedOnDisk(path)
}
FileChangeType.Changed -> {
sf.changedOnDisk(path)
cp.changedOnDisk(path)
}
null -> {
// Nothing to do
}
}
}
}
override fun didChangeConfiguration(params: DidChangeConfigurationParams) {
LOG.info(params.toString())
}
override fun symbol(params: WorkspaceSymbolParams): CompletableFuture<List<SymbolInformation>> {
val result = workspaceSymbols(params.query, sp)
return CompletableFuture.completedFuture(result)
}
override fun didChangeWorkspaceFolders(params: DidChangeWorkspaceFoldersParams) {
for (change in params.event.added) {
LOG.info("Adding workspace ${change.uri} to source path")
val root = Paths.get(URI.create(change.uri))
sf.addWorkspaceRoot(root)
cp.addWorkspaceRoot(root)
}
for (change in params.event.removed) {
LOG.info("Dropping workspace ${change.uri} from source path")
val root = Paths.get(URI.create(change.uri))
sf.removeWorkspaceRoot(root)
cp.removeWorkspaceRoot(root)
}
}
} | 0 | Kotlin | 2 | 32 | 326af74acdf2de9d518314cfaeee65d4fc6d8a80 | 2,120 | kotlin-language-server | MIT License |
src/main/kotlin/model/SearchFilter.kt | SchoolSyncAr | 782,715,163 | false | {"Kotlin": 64179, "Shell": 438, "Dockerfile": 243} | package ar.org.schoolsync.model
import ar.org.schoolsync.model.enums.Status
import jakarta.persistence.criteria.Join
import jakarta.persistence.criteria.JoinType
import jakarta.persistence.criteria.Root
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
class SearchFilter(
var searchField: String = "",
private var orderParam: String = "",
private var sortDirection: String = "",
) {
private fun getDirection() = if (sortDirection == "asc") Sort.Direction.ASC else Sort.Direction.DESC
fun getSortUser() = Sort.by(
Sort.Order(Sort.Direction.DESC, "pinned"),
if (orderParam.isNotEmpty()) Sort.Order(getDirection(), orderParam) else Sort.Order.asc("date")
)
fun getSortAdmin() = Sort.by(
if (orderParam.isNotEmpty()) Sort.Order(getDirection(), orderParam) else Sort.Order.asc("date")
)
}
class SearchFilterBuilder(
private val filter: SearchFilter,
private val isRegistry: Boolean = false
) {
private var specs: Specification<CommonNotification> = Specification.where(null)
private val regex = Regex("(autor|titulo|contenido):([^:]*)(?= autor:| titulo:| contenido:|$)")
private val matches: Sequence<MatchResult>? =
if (filter.searchField.isEmpty()) null else regex.findAll(filter.searchField)
private val filterMap = matches?.associate { it.groupValues[1] to it.groupValues[2].trim() }
fun from(): SearchFilterBuilder {
extractSpect(FilterTypes.AUTOR)
return this
}
fun title(): SearchFilterBuilder {
extractSpect(FilterTypes.TITULO)
return this
}
fun content(): SearchFilterBuilder {
extractSpect(FilterTypes.CONTENIDO)
return this
}
fun userId(id:Long): SearchFilterBuilder {
specs = specs.and { root, _, criteriaBuilder ->
criteriaBuilder.equal(root.get<Long>("receiver").get<Long>("id"), id)
}
return this
}
fun active(): SearchFilterBuilder {
specs = specs.and { root, _, criteriaBuilder ->
val rootJoined = if (isRegistry) joinedRoot(root) else root
criteriaBuilder.equal(
rootJoined.get<Status>("status"),
Status.ACTIVE
)
}
return this
}
fun build(): Specification<CommonNotification> {
if (filterMap.isNullOrEmpty()) {
searchEverywhere()
}
return specs
}
private fun extractSpect(type: FilterTypes) {
filterMap?.let { map ->
map[type.name.lowercase()]?.let { value ->
specs = specs.and { root, _, criteriaBuilder ->
val rootJoined = if (isRegistry) joinedRoot(root) else root
criteriaBuilder.like(
criteriaBuilder.lower(rootJoined.get(type.eng)),
"%${value.lowercase()}%"
)
}
}
}
}
private fun searchEverywhere() {
filter.searchField.takeIf { it.isNotEmpty() }?.let { searchValue ->
val searchValueLower = searchValue.lowercase()
specs = specs.and { root, _, criteriaBuilder ->
val rootJoined = if (isRegistry) joinedRoot(root) else root
criteriaBuilder.or(
criteriaBuilder.like(
criteriaBuilder.lower(rootJoined.get(FilterTypes.TITULO.eng)),
"%$searchValueLower%"
),
criteriaBuilder.like(
criteriaBuilder.lower(rootJoined.get(FilterTypes.AUTOR.eng)),
"%$searchValueLower%"
),
criteriaBuilder.like(
criteriaBuilder.lower(rootJoined.get(FilterTypes.CONTENIDO.eng)),
"%$searchValueLower%"
)
)
}
}
}
private fun joinedRoot(root: Root<CommonNotification>): Join<NotificationRegistry, Notification> =
root.join("notification", JoinType.LEFT)
}
enum class FilterTypes(val eng: String) {
TITULO("title"), AUTOR("senderName"), CONTENIDO("content")
} | 17 | Kotlin | 0 | 1 | e398392a1176cb39da250c0c5d7fa3287f736b90 | 4,238 | schoolsync-be | MIT License |
backend-common/src/main/kotlin/ru/otus/model/context/ExchangeContext.kt | forestforestoff | 355,617,147 | true | {"Kotlin": 76987, "Dockerfile": 616, "Shell": 232} | package ru.otus.model.context
import ru.otus.model.PrincipalModel
import ru.otus.model.Rating
import ru.otus.model.Vote
import java.time.Instant
import java.util.*
data class ExchangeContext(
val created: Instant = Instant.now(),
val contextUid: UUID = UUID.randomUUID(),
var status: ContextStatus = ContextStatus.INIT,
var errors: MutableList<IError> = mutableListOf(),
val userSession: ISessionWrapper<*> = EmptySession(),
var principalModel: PrincipalModel = PrincipalModel.NONE,
var useAuth: Boolean = true,
var rating: Rating = Rating.NONE,
var vote: Vote = Vote.NONE
)
| 0 | Kotlin | 0 | 0 | 91750efe7a952dd145019989efdaa0d9f716ddb4 | 614 | otuskotlin-202012-rating-fs | MIT License |
lib/src/main/java/com/irurueta/android/navigation/inertial/calibration/noise/MagnetometerNormEstimator.kt | albertoirurueta | 440,663,799 | false | null | /*
* Copyright (C) 2022 <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.
*/
package com.irurueta.android.navigation.inertial.calibration.noise
import android.content.Context
import com.irurueta.android.navigation.inertial.collectors.MagnetometerSensorCollector
import com.irurueta.android.navigation.inertial.collectors.MagnetometerSensorType
import com.irurueta.android.navigation.inertial.collectors.SensorDelay
import com.irurueta.navigation.inertial.calibration.noise.AccumulatedMagneticFluxDensityMeasurementNoiseEstimator
import com.irurueta.units.MagneticFluxDensity
import com.irurueta.units.MagneticFluxDensityConverter
import com.irurueta.units.MagneticFluxDensityUnit
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Estimates magnetometer measurement norm.
* This estimator takes a given number of magnetometer measurements during a given duration of time
* to estimate magnetometer norm average, standard deviation and variance, as well as average time
* interval between measurements.
* For best accuracy of estimated results, device should remain static while data is being
* collected. In such case, average magnetometer norm should match expected Earth magnetic flux
* density magnitude at current location and timestamp.
*
* @param context Android context.
* @property sensorType One of the supported magnetometer sensor types.
* @param sensorDelay Delay of sensor between samples.
* @param maxSamples Maximum number of samples to take into account before completion. This is
* only taken into account if using either [StopMode.MAX_SAMPLES_ONLY] or
* [StopMode.MAX_SAMPLES_OR_DURATION].
* @param maxDurationMillis Maximum duration expressed in milliseconds to take into account
* before completion. This is only taken into account if using either
* [StopMode.MAX_DURATION_ONLY] or [StopMode.MAX_SAMPLES_OR_DURATION].
* @param stopMode Determines when this estimator will consider its estimation completed.
* @param completedListener Listener to notify when estimation is complete.
* @param unreliableListener Listener to notify when sensor becomes unreliable, and thus,
* estimation must be discarded.
* @property measurementListener Listener to notify collected sensor measurement.
* @throws IllegalArgumentException when either [maxSamples] or [maxDurationMillis] is negative.
*/
class MagnetometerNormEstimator(
context: Context,
val sensorType: MagnetometerSensorType = MagnetometerSensorType.MAGNETOMETER_UNCALIBRATED,
sensorDelay: SensorDelay = SensorDelay.FASTEST,
maxSamples: Int = DEFAULT_MAX_SAMPLES,
maxDurationMillis: Long = DEFAULT_MAX_DURATION_MILLIS,
stopMode: StopMode = StopMode.MAX_SAMPLES_OR_DURATION,
completedListener: OnEstimationCompletedListener<MagnetometerNormEstimator>? = null,
unreliableListener: OnUnreliableListener<MagnetometerNormEstimator>? = null,
var measurementListener: MagnetometerSensorCollector.OnMeasurementListener? = null
) : AccumulatedMeasurementEstimator<MagnetometerNormEstimator,
AccumulatedMagneticFluxDensityMeasurementNoiseEstimator, MagnetometerSensorCollector,
MagneticFluxDensityUnit, MagneticFluxDensity>(
context,
sensorDelay,
maxSamples,
maxDurationMillis,
stopMode,
completedListener,
unreliableListener
) {
/**
* Listener to handle magnetometer measurements.
*/
private val magnetometerMeasurementListener =
MagnetometerSensorCollector.OnMeasurementListener { bx, by, bz, hardIronX, hardIronY, hardIronZ, timestamp, accuracy ->
val norm =
sqrt(bx.toDouble().pow(2.0) + by.toDouble().pow(2.0) + bz.toDouble().pow(2.0))
val normT = MagneticFluxDensityConverter.microTeslaToTesla(norm)
handleMeasurement(normT, timestamp, accuracy)
measurementListener?.onMeasurement(
bx,
by,
bz,
hardIronX,
hardIronY,
hardIronZ,
timestamp,
accuracy
)
}
/**
* Internal noise estimator of magnetometer magnitude measurements.
* This can be used to estimate statistics about a given measurement magnitude.
*/
override val noiseEstimator = AccumulatedMagneticFluxDensityMeasurementNoiseEstimator()
/**
* Collector for magnetometer measurements.
*/
override val collector = MagnetometerSensorCollector(
context,
sensorType,
sensorDelay,
magnetometerMeasurementListener,
accuracyChangedListener
)
} | 0 | Kotlin | 0 | 0 | 02ee04164a36bc0238fa3b78e8842a799475fcf5 | 5,118 | irurueta-android-navigation-inertial | Apache License 2.0 |
navigation/src/test/java/com/sensorberg/libs/navigation/NavigatorImplTest.kt | sensorberg | 255,345,915 | false | null | package com.sensorberg.libs.navigation
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.navigation.NavDirections
import io.mockk.mockk
import org.assertj.core.api.Assertions.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class NavigatorImplTest {
@get:Rule val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var classUnderTest: NavigatorImpl
@Before
fun setUp() {
classUnderTest = NavigatorImpl()
}
@Test
fun `should observe Navigation Up event`() {
classUnderTest.up()
var actual: Navigation? = null
classUnderTest.observe(alwaysResumedLifeCycleOwnwer(), Observer {
actual = it.getOrNull()
})
assertThat(actual).isEqualTo(Navigation.Up)
}
@Test
fun `should observe Navigation Direction event`() {
val expected: NavDirections = mockk()
classUnderTest.to(expected)
var actual: Navigation? = null
classUnderTest.observe(alwaysResumedLifeCycleOwnwer(), Observer {
actual = it.getOrNull()
})
assertThat(actual).isInstanceOf(Navigation.Direction::class.java)
assertThat((actual as Navigation.Direction).navDirections).isEqualTo(expected)
}
private fun alwaysResumedLifeCycleOwnwer(): LifecycleOwner {
return ControllableLifeCycle().apply { setState(Lifecycle.State.RESUMED) }
}
} | 1 | Kotlin | 1 | 2 | 408eb81b218702040c626088d0b1436468a5d867 | 1,420 | android-navigation | MIT License |
app/src/main/java/com/keykat/keykat/brawlkat/service/model/datasource/NotificationDataSource.kt | betterafter | 275,093,766 | false | {"Java": 333257, "Kotlin": 87511} | package com.keykat.keykat.brawlkat.service.model.datasource
import com.keykat.keykat.brawlkat.common.exceptions.InvalidBaseDataException
import com.keykat.keykat.brawlkat.common.exceptions.InvalidPlayerDataException
import com.keykat.keykat.brawlkat.service.model.data.NotificationData
import com.keykat.keykat.brawlkat.common.util.parser.kat_brawlersParser
import com.keykat.keykat.brawlkat.common.util.parser.kat_eventsParser
import com.keykat.keykat.brawlkat.common.util.parser.kat_mapsParser
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.nio.charset.StandardCharsets
const val IP = "193.122.98.86"
const val BOUNDARY = "this_is_a_kat_data_boundary!"
const val TIMEOUT = 4000
class NotificationDataSource {
fun getBaseData(): Result<NotificationData> {
val resData: ArrayList<String> = ArrayList()
try {
val socketAddress: SocketAddress = InetSocketAddress(IP, 9000)
val socket = Socket()
socket.soTimeout = TIMEOUT
socket.connect(socketAddress, TIMEOUT)
val bytes: ByteArray
// 데이터 보내기
// starlist api는 서버에 보낼 데이터가 없기 때문에 개행문자만을 보내 수신 종료한다.
var result: String = "/" + "/" + "nofficial"
result += "\n"
val os = socket.getOutputStream()
bytes = result.toByteArray(StandardCharsets.UTF_8)
os.write(bytes)
os.flush()
val data = socket.getInputStream()
val input = InputStreamReader(data)
val reader = BufferedReader(input)
result = reader.readLine()
var startidx = 0
var split: Int
// API 데이터 파싱
var splited: String
while (true) {
split = result.indexOf(BOUNDARY, startidx)
if (split == -1) break
splited = result.substring(startidx, split)
resData.add(splited)
startidx = split + BOUNDARY.length
}
reader.close()
os.close()
socket.close()
val eventsParser = kat_eventsParser(resData[0])
val brawlersParser = kat_brawlersParser(resData[1])
val mapsParser = kat_mapsParser(resData[2])
return if (resData.isEmpty()) {
Result.failure(InvalidBaseDataException(resData.toString()))
} else {
kotlin.runCatching {
NotificationData(
eventsParser.DataParser(),
brawlersParser.DataParser(),
mapsParser.DataParser(),
null
)
}
}
} catch (e: Exception) {
return Result.failure(InvalidBaseDataException(resData.toString()))
}
}
fun getPlayerData(
tag: String,
type: String,
apiType: String
): Result<NotificationData> {
val resData = java.util.ArrayList<String>()
try {
val socketAddress: SocketAddress = InetSocketAddress(IP, 9000)
val socket = Socket()
socket.soTimeout = TIMEOUT
socket.connect(socketAddress, TIMEOUT)
val bytes: ByteArray
var result: String? = null
// 데이터 보내기
// playerTag를 먼저 보냄.
if (apiType == "official") {
result = "%23$tag"
} else if (apiType == "nofficial") {
result = tag
}
result = type + "/" + result + "/" + apiType
val os = socket.getOutputStream()
bytes = result.toByteArray(StandardCharsets.UTF_8)
os.write(bytes)
os.flush()
// os 를 flush한 후 데이터 종료 완료를 알리기 위해 개행문자를 보내 데이터 수신을 완료한다.
val end = "\n"
os.write(end.toByteArray())
os.flush()
val data = socket.getInputStream()
val input = InputStreamReader(data)
val reader = BufferedReader(input)
result = reader.readLine()
var startidx = 0
var split: Int
// API 데이터 파싱
var splited: String
while (true) {
split = result.indexOf(BOUNDARY, startidx)
if (split == -1) break
splited = result.substring(startidx, split)
resData.add(splited)
startidx = split + BOUNDARY.length
}
input.close()
data.close()
reader.close()
socket.close()
return if (resData.isEmpty()) {
Result.failure(InvalidPlayerDataException(resData.toString()))
} else {
kotlin.runCatching {
NotificationData(null, null, null, resData)
}
}
} catch (e: Exception) {
return Result.failure(InvalidPlayerDataException(resData.toString()))
}
}
} | 11 | Java | 1 | 1 | e44ed64fffe9d5adabd446de3291a84e2ec171e2 | 5,111 | BrawlKat | MIT License |
sample-app/src/main/java/com/ryccoatika/simplesocket/ui/client/Client.kt | ryccoatika | 704,089,886 | false | {"Kotlin": 17630, "Java": 11739, "Shell": 550} | package com.ryccoatika.simplesocket.ui.client
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ryccoatika.simplesocket.ui.theme.AppTheme
import com.ryccoatika.socketclient.SocketClient
import com.ryccoatika.socketclient.SocketClientCallback
import java.lang.Exception
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Client(
navigateUp: () -> Unit,
) {
var host by remember { mutableStateOf("") }
var port by remember { mutableIntStateOf(0) }
var message by remember { mutableStateOf("") }
var incomingMessages by remember { mutableStateOf("") }
var isConnected by remember { mutableStateOf(false) }
var socketClient by remember { mutableStateOf<SocketClient?>(null) }
val socketClientCallback = remember {
object : SocketClientCallback {
override fun onConnected() {
Log.i("190401", "onConnected")
isConnected = true
}
override fun onConnectionFailure(e: Exception) {
Log.i("190401", "onConnectFailure: $e")
isConnected = false
socketClient = null
}
override fun onMessageReceived(message: String) {
Log.i("190401", "onMessageReceived: $message")
incomingMessages = message
}
override fun onDisconnected() {
Log.i("190401", "onDisconnected")
isConnected = false
socketClient = null
}
}
}
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = navigateUp) {
Icon(
Icons.Default.ArrowBack,
contentDescription = "back",
)
}
},
title = { Text("Client") },
)
}
) { paddingValues ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(paddingValues)
.padding(
horizontal = 32.dp,
vertical = 16.dp,
)
.fillMaxSize()
) {
OutlinedTextField(
value = host,
label = {
Text(text = "ip address")
},
enabled = !isConnected,
onValueChange = {
host = it
},
)
Spacer(Modifier.height(5.dp))
OutlinedTextField(
value = port.takeIf { it != 0 }?.toString() ?: "",
label = {
Text(text = "port")
},
enabled = !isConnected,
onValueChange = {
port = it.toIntOrNull() ?: 0
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
)
)
Spacer(Modifier.height(5.dp))
if (!isConnected) {
OutlinedButton(
onClick = {
socketClient = SocketClient(host, port).also {
it.setSocketClientCallback(socketClientCallback)
it.connect()
}
},
) {
Text(text = "Connect")
}
}
if (isConnected) {
OutlinedButton(
onClick = {
socketClient?.disconnect()
socketClient = null
},
) {
Text(text = "Disconnect")
}
}
Spacer(Modifier.height(30.dp))
if (isConnected) {
if (incomingMessages.isNotEmpty()) {
Text("Incoming message from server:\n$incomingMessages")
}
Spacer(Modifier.height(10.dp))
OutlinedTextField(
value = message,
label = {
Text(text = "enter message")
},
onValueChange = {
message = it
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Send,
),
keyboardActions = KeyboardActions(
onSend = {
socketClient?.sendMessage(message)
}
)
)
}
}
}
}
@Preview
@Composable
private fun ClientPreview() {
AppTheme {
Client(
navigateUp = {},
)
}
} | 0 | Kotlin | 0 | 0 | cb03d57aec506a02a8d1ef7d31553bd61ba49766 | 6,246 | simple-socket | MIT License |
tuttur/src/main/java/com/tahakorkem/tuttur/listadapter/BaseMultiViewListAdapter.kt | tahakorkem | 525,312,255 | false | null | package com.tahakorkem.tuttur.listadapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.tahakorkem.tuttur.listadapter.common.BaseViewHolder
import com.tahakorkem.tuttur.listadapter.common.Bindable
import com.tahakorkem.tuttur.listadapter.common.TutturDiffCallback
import com.tahakorkem.tuttur.listadapter.common.Identifiable
abstract class BaseMultiViewListAdapter<I : Identifiable>
@JvmOverloads constructor(
diffCallback: DiffUtil.ItemCallback<I> = TutturDiffCallback()
) :
ListAdapter<I, BaseViewHolder<ViewDataBinding>>(diffCallback) {
protected abstract val bindables: List<Bindable<out I>>
private val bindableIndicesMap by lazy {
bindables.toDistinctMapIndexed { i, item -> item.clazz to i }
}
final override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): BaseViewHolder<ViewDataBinding> {
return BaseViewHolder.create(
bindables[viewType].layoutId,
LayoutInflater.from(parent.context),
parent,
onCreate = {
onCreate(viewType)
}
)
}
final override fun onBindViewHolder(
holder: BaseViewHolder<ViewDataBinding>,
position: Int
) {
val item = getItem(position)
holder.bindTo {
onBind(holder, position, item)
}
}
final override fun onBindViewHolder(
holder: BaseViewHolder<ViewDataBinding>,
position: Int,
payloads: MutableList<Any>
) {
super.onBindViewHolder(holder, position, payloads)
}
final override fun getItemViewType(position: Int): Int {
return getItem(position)::class.let { clazz ->
bindableIndicesMap[clazz] ?: error("No proper bindable found for $clazz")
}
}
open fun ViewDataBinding.onBind(holder: BaseViewHolder<ViewDataBinding>, index: Int, item: I) =
Unit
open fun ViewDataBinding.onCreate(viewType: Int) = Unit
}
private inline fun <T, K, V> Iterable<T>.toDistinctMapIndexed(block: (index: Int, item: T) -> Pair<K, V>): Map<K, V> {
val map = mutableMapOf<K, V>()
for ((i, item) in this.withIndex()) {
val (key, value) = block(i, item)
if (key in map) {
error("Key $key is already in the map. Duplicated keys are not allowed.")
}
map[key] = value
}
return map
} | 0 | Kotlin | 0 | 0 | e762329e719ab246b55b2aa3ac28ff3a162dc509 | 2,541 | tuttur | MIT License |
Core/src/main/java/com/randos/core/di/DataStoreModule.kt | vsnappy1 | 787,726,120 | false | {"Kotlin": 149524} | package com.randos.core.di
import android.app.Application
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import com.randos.core.data.DataStoreManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class DataStoreModule {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_preferences")
@Provides
fun provideDataStore(application: Application): DataStoreManager {
return DataStoreManager(application.dataStore)
}
} | 0 | Kotlin | 0 | 0 | 26c3f781dfc42f4fae6c629c8ca6580638d63129 | 742 | MusicVibe | Apache License 2.0 |
src/main/kotlin/com/sokoobo/damzel/parsers/util/Collection.kt | sokoobo | 869,785,019 | false | {"Kotlin": 163808, "HTML": 4051} | @file:JvmName("CollectionUtils")
package com.sokoobo.damzel.parsers.util
import androidx.collection.ArrayMap
import androidx.collection.ArraySet
import java.util.*
public fun <T> MutableCollection<T>.replaceWith(subject: Iterable<T>) {
clear()
addAll(subject)
}
fun <T, C : MutableCollection<in T>> Iterable<Iterable<T>>.flattenTo(destination: C): C {
for (element in this) {
destination.addAll(element)
}
return destination
}
fun <T> List<T>.medianOrNull(): T? = when {
isEmpty() -> null
else -> get((size / 2).coerceIn(indices))
}
public inline fun <T, R> Collection<T>.mapToSet(transform: (T) -> R): Set<R> {
return mapTo(ArraySet(size), transform)
}
inline fun <T, R> Collection<T>.mapNotNullToSet(transform: (T) -> R?): Set<R> {
val destination = ArraySet<R>(size)
for (item in this) {
destination.add(transform(item) ?: continue)
}
return destination
}
public inline fun <T, reified R> Array<T>.mapToArray(transform: (T) -> R): Array<R> = Array(size) { i ->
transform(get(i))
}
fun <K, V> List<Pair<K, V>>.toMutableMap(): MutableMap<K, V> = toMap(ArrayMap(size))
public fun <T> MutableList<T>.move(sourceIndex: Int, targetIndex: Int) {
if (sourceIndex <= targetIndex) {
Collections.rotate(subList(sourceIndex, targetIndex + 1), -1)
} else {
Collections.rotate(subList(targetIndex, sourceIndex + 1), 1)
}
}
inline fun <T> List<T>.areItemsEquals(other: List<T>, equals: (T, T) -> Boolean): Boolean {
if (size != other.size) {
return false
}
for (i in indices) {
val a = this[i]
val b = other[i]
if (!equals(a, b)) {
return false
}
}
return true
}
fun <T> Iterator<T>.nextOrNull(): T? = if (hasNext()) next() else null
inline fun <T, K, V> Collection<T>.associateGrouping(transform: (T) -> Pair<K, V>): Map<K, Set<V>> {
val result = LinkedHashMap<K, MutableSet<V>>(size)
for (item in this) {
val (k, v) = transform(item)
result.getOrPut(k) { LinkedHashSet() }.add(v)
}
return result
}
fun <K> MutableMap<K, Int>.incrementAndGet(key: K): Int {
var value = get(key) ?: 0
value++
put(key, value)
return value
}
| 0 | Kotlin | 0 | 0 | 535e638059205ac87e77615cdc436b2500574f7d | 2,079 | damzel-parsers | MIT License |
core/src/commonMain/kotlin/work/socialhub/kmisskey/api/request/mutes/MutesCreateRequest.kt | uakihir0 | 756,689,268 | false | {"Kotlin": 248708, "Shell": 2141, "Makefile": 316} | package work.socialhub.kmisskey.api.request.mutes
import kotlinx.serialization.Serializable
import work.socialhub.kmisskey.api.model.TokenRequest
import kotlin.js.JsExport
@JsExport
@Serializable
class MutesCreateRequest : TokenRequest() {
var userId: String? = null
}
| 0 | Kotlin | 1 | 6 | f59e9296d3e1976cd92fe853b5811f63a38b8d41 | 276 | kmisskey | MIT License |
android/app/src/main/java/com/algorand/android/modules/backupprotocol/domain/usecase/CreateBackupProtocolPayloadUseCase.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.backupprotocol.domain.usecase
import com.algorand.android.core.AccountManager
import com.algorand.android.deviceregistration.domain.usecase.DeviceIdUseCase
import com.algorand.android.models.Account
import com.algorand.android.modules.backupprotocol.mapper.BackupProtocolElementMapper
import com.algorand.android.modules.backupprotocol.mapper.BackupProtocolPayloadMapper
import com.algorand.android.modules.backupprotocol.model.BackupProtocolPayload
import com.algorand.android.modules.backupprotocol.util.BackupProtocolUtils.convertAccountTypeToBackupProtocolAccountType
import com.algorand.android.utils.extensions.encodeBase64
import javax.inject.Inject
class CreateBackupProtocolPayloadUseCase @Inject constructor(
private val deviceIdUseCase: DeviceIdUseCase,
private val accountManager: AccountManager,
private val backupProtocolElementMapper: BackupProtocolElementMapper,
private val backupProtocolPayloadMapper: BackupProtocolPayloadMapper
) {
suspend operator fun invoke(accountList: List<String>): BackupProtocolPayload? {
val deviceId = deviceIdUseCase.getSelectedNodeDeviceId() ?: return null
val accountBackupProtocolElementList = accountList.mapNotNull { accountAddress ->
val account = accountManager.getAccount(accountAddress) ?: return@mapNotNull null
if (account.type != Account.Type.STANDARD) return@mapNotNull null
val accountType = convertAccountTypeToBackupProtocolAccountType(account.type) ?: return@mapNotNull null
backupProtocolElementMapper.mapToBackupProtocolElement(
address = account.address,
name = account.name,
accountType = accountType,
privateKey = account.getSecretKey()?.encodeBase64() ?: return@mapNotNull null,
metadata = null
)
}
return backupProtocolPayloadMapper.mapToBackupProtocolPayload(
deviceId = deviceId,
providerName = DEFAULT_PROVIDER_NAME,
accounts = accountBackupProtocolElementList
)
}
companion object {
private const val DEFAULT_PROVIDER_NAME = "Pera Wallet"
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 2,799 | pera-wallet | Apache License 2.0 |
src/main/kotlin/Day11.kt | clechasseur | 267,632,210 | false | null | object Day11 {
private val input = IsolatedArea(listOf(
Floor(setOf(
InterestingObject("thulium", ObjectType.GENERATOR),
InterestingObject("thulium", ObjectType.MICROCHIP),
InterestingObject("plutonium", ObjectType.GENERATOR),
InterestingObject("strontium", ObjectType.GENERATOR)
)),
Floor(setOf(
InterestingObject("plutonium", ObjectType.MICROCHIP),
InterestingObject("strontium", ObjectType.MICROCHIP)
)),
Floor(setOf(
InterestingObject("promethium", ObjectType.GENERATOR),
InterestingObject("promethium", ObjectType.MICROCHIP),
InterestingObject("ruthenium", ObjectType.GENERATOR),
InterestingObject("ruthenium", ObjectType.MICROCHIP)
)),
Floor(emptySet())
), elevatorFloorIdx = 0)
fun part1(): Int = countSteps(input)
fun part2(): Int = countSteps(
IsolatedArea(listOf(
Floor(input.floors[0].objects + setOf(
InterestingObject("elerium", ObjectType.GENERATOR),
InterestingObject("elerium", ObjectType.MICROCHIP),
InterestingObject("dilithium", ObjectType.GENERATOR),
InterestingObject("dilithium", ObjectType.MICROCHIP)
)),
input.floors[1],
input.floors[2],
input.floors[3]
), elevatorFloorIdx = input.elevatorFloorIdx)
)
private fun countSteps(initialState: IsolatedArea): Int {
var steps = 0
var states = setOf(initialState)
var seenStates = emptySet<Int>()
while (states.none { it.finished }) {
states = states.asSequence().flatMap { nextSteps(it) }.filterNot { it.hashCode() in seenStates }.toSet()
seenStates = seenStates + states.map { it.hashCode() }
require(states.isNotEmpty()) { "No way to get to the final state" }
steps++
}
return steps
}
private fun nextSteps(state: IsolatedArea): Sequence<IsolatedArea> = sequence {
val curFloorIdx = state.elevatorFloorIdx
when (curFloorIdx) {
state.floors.indices.first -> listOf(state.floors.indices.first + 1)
state.floors.indices.last -> listOf(state.floors.indices.last - 1)
else -> listOf(curFloorIdx - 1, curFloorIdx + 1)
}.forEach { destFloorIdx ->
state.floors[curFloorIdx].objects.forEach { obj ->
val newFloors = state.floors.toMutableList()
newFloors[curFloorIdx] = Floor(newFloors[curFloorIdx].objects - obj)
newFloors[destFloorIdx] = Floor(newFloors[destFloorIdx].objects + obj)
val newState = IsolatedArea(newFloors, destFloorIdx)
if (newState.valid) {
yield(newState)
}
}
state.floors[curFloorIdx].objects.forEachIndexed { idx1, obj1 ->
state.floors[curFloorIdx].objects.drop(idx1 + 1).forEach { obj2 ->
val newFloors = state.floors.toMutableList()
newFloors[curFloorIdx] = Floor(newFloors[curFloorIdx].objects - setOf(obj1, obj2))
newFloors[destFloorIdx] = Floor(newFloors[destFloorIdx].objects + setOf(obj1, obj2))
val newState = IsolatedArea(newFloors, destFloorIdx)
if (newState.valid) {
yield(newState)
}
}
}
}
}
private enum class ObjectType(val id: String) {
GENERATOR("G"),
MICROCHIP("M"),
}
private data class InterestingObject(val element: String, val type: ObjectType) {
override fun toString(): String = "${element[0].toUpperCase()}${element[1]}${type.id}"
}
private data class Floor(val objects: Set<InterestingObject>) {
val valid: Boolean
get() = !(objects.any { it.type == ObjectType.GENERATOR } && objects.any { microchip ->
microchip.type == ObjectType.MICROCHIP && objects.none { generator ->
generator.type == ObjectType.GENERATOR && generator.element == microchip.element
}
})
override fun toString(): String = "[${objects.joinToString(",")}]"
}
private data class IsolatedArea(val floors: List<Floor>, val elevatorFloorIdx: Int) {
init {
require(floors.size == 4) { "Isolated area needs to have 4 floors" }
require(elevatorFloorIdx in floors.indices) { "Elevator needs to be on a valid floor" }
}
val valid: Boolean
get() = floors.all { it.valid }
val finished: Boolean
get() = floors.dropLast(1).all { it.objects.isEmpty() } && elevatorFloorIdx == floors.indices.last
override fun toString(): String = "{[" + floors.mapIndexed { i, f ->
"$i${if (i == elevatorFloorIdx) "*" else ""}: $f"
}.joinToString(",") + "]}"
}
} | 0 | Kotlin | 0 | 0 | 120795d90c47e80bfa2346bd6ab19ab6b7054167 | 5,033 | adventofcode2016 | MIT License |
packages/server-core/src/main/kotlin/org/migor/feedless/annotation/AnnotationResolver.kt | damoeb | 314,677,857 | false | {"HTML": 3499376, "Kotlin": 1565240, "TypeScript": 647818, "SCSS": 67132, "TeX": 34128, "XSLT": 11997, "JavaScript": 10350, "Shell": 4928, "Dockerfile": 3860, "PLpgSQL": 480} | package org.migor.feedless.annotation
import com.netflix.graphql.dgs.DgsComponent
import com.netflix.graphql.dgs.DgsMutation
import com.netflix.graphql.dgs.InputArgument
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import org.migor.feedless.AppProfiles
import org.migor.feedless.api.ApiParams
import org.migor.feedless.api.throttle.Throttled
import org.migor.feedless.generated.DgsConstants
import org.migor.feedless.generated.types.CreateAnnotationInput
import org.migor.feedless.generated.types.DeleteAnnotationInput
import org.migor.feedless.session.useRequestContext
import org.migor.feedless.util.CryptUtil.handleCorrId
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Profile
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.RequestHeader
@DgsComponent
@Profile("${AppProfiles.agent} & ${AppProfiles.api}")
class AnnotationResolver {
private val log = LoggerFactory.getLogger(AnnotationResolver::class.simpleName)
@Autowired
private lateinit var annotationService: AnnotationService
@Throttled
@DgsMutation(field = DgsConstants.MUTATION.CreateAnnotation)
@PreAuthorize("hasAuthority('USER')")
@Transactional(propagation = Propagation.REQUIRED)
suspend fun createAnnotation(
@RequestHeader(ApiParams.corrId) corrIdParam: String,
@InputArgument data: CreateAnnotationInput
): Annotation = withContext(useRequestContext(currentCoroutineContext())) {
val corrId = handleCorrId(corrIdParam)
log.debug("[$corrId] createAnnotation $data")
annotationService.createAnnotation(corrId, data).toDto()
}
@Throttled
@DgsMutation(field = DgsConstants.MUTATION.DeleteAnnotation)
@PreAuthorize("hasAuthority('USER')")
@Transactional(propagation = Propagation.REQUIRED)
suspend fun deleteAnnotation(
@RequestHeader(ApiParams.corrId) corrIdParam: String,
@InputArgument data: DeleteAnnotationInput
): Boolean = withContext(useRequestContext(currentCoroutineContext())) {
val corrId = handleCorrId(corrIdParam)
log.debug("[$corrId] deleteAnnotation $data")
annotationService.deleteAnnotation(corrId, data)
}
}
private fun AnnotationEntity.toDto(): Annotation {
TODO("Not yet implemented")
}
| 15 | HTML | 25 | 235 | 52d57ee229026a5ffa6432e753bbe94328a7149b | 2,481 | feedless | Apache License 2.0 |
goblin-embedded/src/main/java/org/goblinframework/embedded/servlet/HttpServletRequestAdapter.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.embedded.servlet
import org.goblinframework.core.util.ProxyUtils
import org.goblinframework.core.util.ReflectionUtils
import javax.servlet.http.HttpServletRequest
object HttpServletRequestAdapter {
val adapter: HttpServletRequest by lazy {
ProxyUtils.createInterfaceProxy(HttpServletRequest::class.java) { invocation ->
val method = invocation.method
if (ReflectionUtils.isToStringMethod(method)) {
return@createInterfaceProxy "HttpServletRequestAdapter"
}
throw UnsupportedOperationException("Unsupported HttpServletRequest method [${method.name}]")
}
}
} | 0 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 632 | goblinframework | Apache License 2.0 |
app/src/androidTest/java/com/jefferson/apps/real_world/android/real_worldandroidapp/common/data/di/TestCacheModule.kt | jeffersoncsilva | 840,062,108 | false | {"Kotlin": 122563} | package com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.di
import androidx.room.Room
import androidx.test.platform.app.InstrumentationRegistry
import com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.cache.Cache
import com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.cache.PetSaveDatabase
import com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.cache.RoomCache
import com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.cache.daos.AnimalsDao
import com.jefferson.apps.real_world.android.real_worldandroidapp.common.data.cache.daos.OrganizationsDao
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
abstract class TestCacheModule {
@Binds
abstract fun bindCache(cache: RoomCache): Cache
companion object{
@Provides
@Singleton
fun provideRoomDatabase(): PetSaveDatabase{
return Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().context,
PetSaveDatabase::class.java
)
.allowMainThreadQueries()
.build()
}
@Provides
fun provideAnimalsDao(petSaveDatabase: PetSaveDatabase): AnimalsDao = petSaveDatabase.animalsDao()
@Provides
fun provideOrganizationsDao(petSaveDatabase: PetSaveDatabase): OrganizationsDao = petSaveDatabase.organizationsDao()
}
} | 0 | Kotlin | 0 | 0 | 3a3a23da1931cf23f5668a81286744057a539ff8 | 1,615 | realworldandroid | Apache License 2.0 |
app/src/main/java/st235/com/github/calculator/presentation/calculator/keyboard/action/ActionButton.kt | st235 | 293,614,114 | false | null | package st235.com.github.calculator.presentation.calculator.keyboard.action
import st235.com.github.calculator.presentation.calculator.keyboard.KeyboardButton
import st235.com.github.uicore.themes.ThemeNode
data class ActionButton(
override val id: String,
val value: String,
val themeNode: ThemeNode
): KeyboardButton(themeNode)
| 0 | Kotlin | 0 | 0 | c8c334e5b72a9abb7951f34d2be5b08f522942b0 | 344 | xcalc-android | MIT License |
plugins/toolkit/jetbrains-core/src/software/aws/toolkits/jetbrains/settings/ToolkitSettingsConfigurable.kt | aws | 91,485,909 | false | null | // Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.settings
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.options.SearchableConfigurable
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.Align
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.bindItem
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.bindText
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.builder.toNullableProperty
import software.aws.toolkits.core.utils.htmlWrap
import software.aws.toolkits.jetbrains.core.executables.ExecutableInstance
import software.aws.toolkits.jetbrains.core.executables.ExecutableInstance.ExecutableWithPath
import software.aws.toolkits.jetbrains.core.executables.ExecutableManager
import software.aws.toolkits.jetbrains.core.executables.ExecutableType
import software.aws.toolkits.jetbrains.core.experiments.ToolkitExperimentManager
import software.aws.toolkits.jetbrains.core.experiments.isEnabled
import software.aws.toolkits.jetbrains.core.experiments.setState
import software.aws.toolkits.jetbrains.core.help.HelpIds
import software.aws.toolkits.jetbrains.core.tools.AutoDetectableToolType
import software.aws.toolkits.jetbrains.core.tools.ManagedToolType
import software.aws.toolkits.jetbrains.core.tools.ToolManager
import software.aws.toolkits.jetbrains.core.tools.ToolSettings
import software.aws.toolkits.jetbrains.core.tools.ToolType
import software.aws.toolkits.jetbrains.core.tools.Version
import software.aws.toolkits.jetbrains.core.tools.getTool
import software.aws.toolkits.jetbrains.core.tools.toValidationInfo
import software.aws.toolkits.jetbrains.core.tools.validateCompatability
import software.aws.toolkits.jetbrains.services.lambda.sam.SamExecutable
import software.aws.toolkits.resources.message
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.CompletionException
// TODO: pending migration for other non-Q settings
class ToolkitSettingsConfigurable :
BoundConfigurable(message("aws.settings.toolkit.configurable.title")),
SearchableConfigurable {
private val samExecutableInstance: SamExecutable
get() = ExecutableType.getExecutable(SamExecutable::class.java)
val samExecutablePath: TextFieldWithBrowseButton = createCliConfigurationElement(samExecutableInstance, SAM)
private val defaultRegionHandling: ComboBox<UseAwsCredentialRegion> = ComboBox(UseAwsCredentialRegion.values())
private val profilesNotification: ComboBox<ProfilesNotification> = ComboBox(ProfilesNotification.values())
override fun createPanel() = panel {
group(message("aws.settings.global_label")) {
row {
label(message("settings.credentials.prompt_for_default_region_switch.setting_label"))
cell(defaultRegionHandling).resizableColumn().align(AlignX.FILL).bindItem(
AwsSettings.getInstance()::useDefaultCredentialRegion,
AwsSettings.getInstance()::useDefaultCredentialRegion.toNullableProperty()::set
)
}
row {
label(message("settings.profiles.label"))
cell(profilesNotification).resizableColumn().align(AlignX.FILL).bindItem(
AwsSettings.getInstance()::profilesNotification,
AwsSettings.getInstance()::profilesNotification.toNullableProperty()::set
)
}
}
group(message("executableCommon.configurable.title")) {
row {
label(message("aws.settings.sam.location"))
// samExecutablePath = createCliConfigurationElement(samExecutableInstance, SAM)
cell(samExecutablePath).align(AlignX.FILL).resizableColumn()
browserLink(message("aws.settings.learn_more"), HelpIds.SAM_CLI_INSTALL.url)
}
ToolType.EP_NAME.extensionList.forEach { toolType ->
row(toolType.displayName) {
textFieldWithBrowseButton(fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileDescriptor())
.bindText(
{ ToolSettings.getInstance().getExecutablePath(toolType).orEmpty() },
{ ToolSettings.getInstance().setExecutablePath(toolType, it.takeIf { v -> v.isNotBlank() }) }
)
.validationOnInput {
it.textField.text.takeIf { t -> t.isNotBlank() }?.let { path ->
ToolManager.getInstance().validateCompatability(Path.of(path), toolType).toValidationInfo(toolType, component)
}
}.applyToComponent {
setEmptyText(toolType, textField as JBTextField)
}.resizableColumn()
.align(Align.FILL)
browserLink(message("aws.settings.learn_more"), toolType.documentationUrl())
}
}
}
group(message("aws.toolkit.experimental.title")) {
row { label(message("aws.toolkit.experimental.description").htmlWrap()).component.icon = AllIcons.General.Warning }
ToolkitExperimentManager.visibleExperiments().forEach { toolkitExperiment ->
row {
checkBox(toolkitExperiment.title()).bindSelected(toolkitExperiment::isEnabled, toolkitExperiment::setState)
.comment(toolkitExperiment.description())
}
}
}
}
override fun apply() {
validateAndSaveCliSettings(
samExecutablePath.textField as JBTextField,
"sam",
samExecutableInstance,
getSavedExecutablePath(samExecutableInstance, false),
getSamPathWithoutSpaces()
)
super.apply()
}
override fun reset() {
val awsSettings = AwsSettings.getInstance()
samExecutablePath.setText(getSavedExecutablePath(samExecutableInstance, false))
defaultRegionHandling.selectedItem = awsSettings.useDefaultCredentialRegion
profilesNotification.selectedItem = awsSettings.profilesNotification
}
override fun getDisplayName(): String = message("aws.settings.toolkit.configurable.title")
override fun getId(): String = "aws.old"
private fun createCliConfigurationElement(executableType: ExecutableType<*>, cliName: String): TextFieldWithBrowseButton {
val autoDetectPath = getSavedExecutablePath(executableType, true)
val executablePathField = JBTextField()
val field = TextFieldWithBrowseButton(executablePathField)
if (autoDetectPath != null) {
executablePathField.emptyText.setText(autoDetectPath)
}
field.addBrowseFolderListener(
message("aws.settings.find.title", cliName),
message("aws.settings.find.description", cliName),
null,
FileChooserDescriptorFactory.createSingleLocalFileDescriptor()
)
return field
}
// modifyMessageBasedOnDetectionStatus will append "Auto-detected: ...." to the
// message if the executable is found this is used for setting the empty box text
private fun getSavedExecutablePath(executableType: ExecutableType<*>, modifyMessageBasedOnDetectionStatus: Boolean): String? = try {
ExecutableManager.getInstance().getExecutable(executableType).thenApply {
if (it is ExecutableWithPath) {
if (it !is ExecutableInstance.Executable) {
return@thenApply (it as ExecutableWithPath).executablePath.toString()
} else {
val path = it.executablePath.toString()
val autoResolved = it.autoResolved
if (autoResolved && modifyMessageBasedOnDetectionStatus) {
return@thenApply message("aws.settings.auto_detect", path)
} else if (autoResolved) {
// If it is auto detected, we do not want to return text as the
// box will be filled by empty text with the auto-resolve message
return@thenApply null
} else {
return@thenApply path
}
}
}
null
}.toCompletableFuture().join()
} catch (ignored: CompletionException) {
null
}
private fun setEmptyText(toolType: ToolType<Version>, field: JBTextField) {
val resolved = (toolType as? AutoDetectableToolType<*>)?.resolve()
field.emptyText.text = when {
resolved != null && toolType.getTool()?.path == resolved -> message("executableCommon.auto_resolved", resolved)
toolType is ManagedToolType<*> -> message("executableCommon.auto_managed")
else -> message("common.none")
}
}
private fun validateAndSaveCliSettings(
textField: JBTextField,
executableName: String,
executableType: ExecutableType<*>,
saved: String?,
currentInput: String?
) {
// If input is null, wipe out input and try to autodiscover
if (currentInput == null) {
ExecutableManager.getInstance().removeExecutable(executableType)
ExecutableManager.getInstance()
.getExecutable(executableType)
.thenRun {
val autoDetectPath = getSavedExecutablePath(executableType, true)
runInEdt(ModalityState.any()) {
if (autoDetectPath != null) {
textField.emptyText.setText(autoDetectPath)
} else {
textField.emptyText.setText("")
}
}
}
return
}
if (currentInput == saved) {
return
}
val path: Path
try {
path = Paths.get(currentInput)
require(Files.isExecutable(path) && path.toFile().exists() && path.toFile().isFile)
} catch (e: Exception) {
throw ConfigurationException(message("aws.settings.executables.executable_invalid", executableName, currentInput))
}
val instance = ExecutableManager.getInstance().validateExecutablePath(executableType, path)
if (instance is ExecutableInstance.BadExecutable) {
throw ConfigurationException(instance.validationError)
}
// We have validated so now we can set
ExecutableManager.getInstance().setExecutablePath(executableType, path)
}
private fun getSamPathWithoutSpaces() = StringUtil.nullize(samExecutablePath.text.trim { it <= ' ' })
companion object {
private const val SAM = "sam"
}
}
| 519 | null | 220 | 757 | a81caf64a293b59056cef3f8a6f1c977be46937e | 11,501 | aws-toolkit-jetbrains | Apache License 2.0 |
json/src/commonTest/kotlin/dev/danperez/ynab/json/account/TestAccount.kt | danielPerez97 | 619,363,218 | false | null | package dev.danperez.ynab.json.account
import dev.danperez.ynab.json.BaseJsonTest
import dev.danperez.ynab.json.Response
import dev.danperez.ynab.json.readBufferedSource
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.okio.decodeFromBufferedSource
import kotlin.test.Test
import kotlin.test.assertEquals
@OptIn(ExperimentalSerializationApi::class)
class TestAccount: BaseJsonTest()
{
@Test
fun testAccountSerializes()
{
val source = "account/Account.json".readBufferedSource()
val account = json.decodeFromBufferedSource<Account>(source)
assertEquals("string", account.id)
}
@Test
fun testAccountResponseSerializes()
{
val source = "account/AccountResponse.json".readBufferedSource()
val accountMessage = json.decodeFromBufferedSource<Response<Account>>(source)
require(accountMessage is Response.Ok<Account>)
assertEquals("string", accountMessage.data.id)
}
} | 0 | Kotlin | 0 | 0 | c3707ad6b5a934240535aaf9594f297fd38ad9c6 | 997 | ynab-kmp | Apache License 2.0 |
app/src/main/java/linc/com/colorsapp/utils/Extensions.kt | lincollincol | 253,084,573 | false | null | package linc.com.colorsapp.utils
import android.os.Parcel
import androidx.fragment.app.Fragment
fun <E> MutableList<E>.updateAll(newList: List<E>) {
this.clear()
this.addAll(newList)
}
fun Parcel.writeBoolean(flag: Boolean?) {
when(flag) {
true -> writeInt(1)
false -> writeInt(0)
else -> writeInt(-1)
}
}
fun Parcel.readBoolean(): Boolean? {
return when(readInt()) {
1 -> true
0 -> false
else -> null
}
}
fun Fragment.getName() = this::class.simpleName
| 0 | Kotlin | 0 | 0 | 1a247d29a43dddd04269d86e1e54ceaab2abb4a6 | 531 | ColorsApp | MIT License |
src/main/kotlin/icu/windea/pls/localisation/ParadoxLocalisationSpellchecker.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.localisation
import com.intellij.psi.*
import com.intellij.psi.util.*
import com.intellij.spellchecker.tokenizer.*
import icu.windea.pls.localisation.psi.ParadoxLocalisationTypes.*
//拼写检查:
//检查key、value、comment
class ParadoxLocalisationSpellchecker : SpellcheckingStrategy() {
override fun getTokenizer(element: PsiElement): Tokenizer<*> {
return when(element.elementType) {
PROPERTY_KEY_ID,COMMAND_SCOPE,COMMAND_FIELD, ICON_ID -> TEXT_TOKENIZER
STRING_TOKEN -> TEXT_TOKENIZER
COMMENT,ROOT_COMMENT,END_OF_LINE_COMMENT -> TEXT_TOKENIZER
else -> EMPTY_TOKENIZER
}
}
}
| 1 | Kotlin | 1 | 6 | 31eb30d9de8366ee932d9b158d855137cd66d0da | 610 | Paradox-Language-Support | MIT License |
example/src/main/java/video/api/livestream/example/ui/preferences/PreferencesFragment.kt | apivideo | 358,516,043 | false | null | package video.api.livestream.example.ui.preferences
import android.os.Bundle
import androidx.preference.ListPreference
import androidx.preference.PreferenceFragmentCompat
import video.api.livestream.app.R
import video.api.livestream.enums.Resolution
class PreferencesFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
override fun onResume() {
super.onResume()
inflatesPreferences()
}
private fun inflatesPreferences() {
(findPreference(getString(R.string.video_resolution_key)) as ListPreference?)?.apply {
val resolutionsList = Resolution.values().map { it.toString() }.toTypedArray()
entryValues = resolutionsList
entries = resolutionsList
if (value == null) {
value = Resolution.RESOLUTION_720.toString()
}
}
}
} | 1 | Kotlin | 1 | 17 | 3bf902e6fc042b970567c6967705e4ee6f91aaee | 989 | android-live-stream | MIT License |
feature/settings/domain/src/main/java/com/viplearner/notes/settings/domain/usecase/SetSyncStateUseCase.kt | VIPlearner | 678,766,501 | false | {"Kotlin": 272893} | package com.viplearner.notes.settings.domain.usecase
import com.viplearner.notes.settings.domain.repository.SettingsRepository
import javax.inject.Inject
class SetSyncStateUseCase @Inject constructor(
private val settingsRepository: SettingsRepository
) {
suspend operator fun invoke(value: Boolean) =
settingsRepository.setSyncState(value)
} | 0 | Kotlin | 0 | 0 | becf4c8e908c26d578aa8387a8b9aee88d60ef27 | 360 | VIPNotes | MIT License |
app/src/main/java/com/dubedivine/samples/features/base/BaseActivity.kt | dubeboy | 102,972,979 | false | null | package com.dubedivine.samples.features.base
import android.os.Bundle
import android.support.v4.util.LongSparseArray
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import butterknife.ButterKnife
import com.dubedivine.samples.MvpStarterApplication
import com.dubedivine.samples.injection.component.ActivityComponent
import com.dubedivine.samples.injection.component.ConfigPersistentComponent
import com.dubedivine.samples.injection.component.DaggerConfigPersistentComponent
import com.dubedivine.samples.injection.module.ActivityModule
import timber.log.Timber
import java.util.concurrent.atomic.AtomicLong
/**
* Abstract activity that every other Activity in this application must implement. It provides the
* following functionality:
* - Handles creation of Dagger components and makes sure that instances of
* ConfigPersistentComponent are kept across configuration changes.
* - Set up and handles a GoogleApiClient instance that can be used to access the Google sign in
* api.
* - Handles signing out when an authentication error event is received.
*/
abstract class BaseActivity : AppCompatActivity() {
private var mActivityComponent: ActivityComponent? = null
private var mActivityId: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout)
ButterKnife.bind(this) //setting the view to be this one
// Create the ActivityComponent and reuses cached ConfigPersistentComponent if this is
// being called after a configuration change.
mActivityId = savedInstanceState?.getLong(KEY_ACTIVITY_ID) ?: NEXT_ID.getAndIncrement()
val configPersistentComponent: ConfigPersistentComponent
if (sComponentsArray.get(mActivityId) == null) {
Timber.i("Creating new ConfigPersistentComponent id=%d", mActivityId)
configPersistentComponent = DaggerConfigPersistentComponent.builder()
.applicationComponent(MvpStarterApplication[this].component)
.build()
sComponentsArray.put(mActivityId, configPersistentComponent)
} else {
Timber.i("Reusing ConfigPersistentComponent id=%d", mActivityId)
configPersistentComponent = sComponentsArray.get(mActivityId)
}
mActivityComponent = configPersistentComponent.activityComponent(ActivityModule(this))
mActivityComponent?.inject(this)
}
abstract val layout: Int
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(KEY_ACTIVITY_ID, mActivityId)
}
override fun onDestroy() {
if (!isChangingConfigurations) {
Timber.i("Clearing ConfigPersistentComponent id=%d", mActivityId)
sComponentsArray.remove(mActivityId)
}
super.onDestroy()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
fun activityComponent(): ActivityComponent {
return mActivityComponent as ActivityComponent
}
/*
* fast logging function
* */
fun l(msg : String) {
Timber.i(msg)
}
// static class dude
companion object {
private val KEY_ACTIVITY_ID = "KEY_ACTIVITY_ID"
private val NEXT_ID = AtomicLong(0)
private val sComponentsArray = LongSparseArray<ConfigPersistentComponent>()
}
}
| 0 | Kotlin | 1 | 1 | 0dccd66d69fc3f1ae7cbecbab397d8de6f29cc5c | 3,637 | Peerlink-mobile | The Unlicense |
Android/app/src/main/java/uk/ac/kcl/spiderbyte/model/Event.kt | dimitrisppt | 158,471,767 | false | {"Objective-C": 4114835, "JavaScript": 1107960, "CSS": 366516, "Swift": 130850, "Kotlin": 129358, "Java": 101394, "C++": 55435, "HTML": 51940, "C": 45891, "Ruby": 3785, "MATLAB": 1355} | package uk.ac.kcl.spiderbyte.model
/**
* Created by Alin on 09/02/2018.
*/
data class Event(var title : String, var desc : String, var day : String, var starttime: String, var endtime: String, var location: String, var mailingList: ArrayList<String> ) {
constructor() : this("", "", "", "", "", "", arrayListOf<String>())
fun toMap(): Map<String, Any> {
val fetchResult = mapOf(
"title" to title,
"desc" to desc,
"day" to day,
"starttime" to starttime,
"endtime" to endtime,
"location" to location,
"mailingList" to mailingList)
return if(isValidEvent()) {
fetchResult
}
else {
mapOf(
)
}
}
fun isValidEvent(): Boolean {
if(title.isNotEmpty() && desc.isNotEmpty() && day.isNotEmpty() && starttime.isNotEmpty() && endtime.isNotEmpty() && location.isNotEmpty()) {
return true
}
return false
}
} | 1 | Objective-C | 1 | 1 | d29c5aada6159f4a8d1eb7f554d4032690b74344 | 1,040 | Communication-App-Group-Project | The Unlicense |
src/main/kotlin/lgbt/mystic/syscan/tool/output/SimpleOutputFormat.kt | GayPizzaSpecifications | 483,374,805 | false | {"Kotlin": 74435, "Dockerfile": 231} | package lgbt.mystic.syscan.tool.output
import lgbt.mystic.syscan.artifact.Artifact
import java.io.PrintStream
object SimpleOutputFormat : OutputFormat {
override fun write(out: PrintStream, artifact: Artifact) {
val metadata = artifact.metadata
out.println("${metadata.kind.id} ${metadata.id}")
for ((namespace, properties) in metadata.asCategoryMap()) {
out.println(" $namespace")
for ((key, value) in properties) {
out.println(" $key = ${value.encode()}")
}
}
}
}
| 0 | Kotlin | 0 | 1 | 3f200ee98e919d2b6734014efc8065d6baf21707 | 519 | syscan | MIT License |
app/src/main/java/com/falcon/restaurants/presentation/view/common/dialogs/ServerErrorDialogFragment.kt | muhammed-ahmad | 407,126,448 | false | null | package com.falcon.restaurants.presentation.view.common.dialogs
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
class ServerErrorDialogFragment : BaseDialog() {
companion object{
const val ERROR: String = "ERROR"
fun newInstance(error: String): ServerErrorDialogFragment {
val fragment = ServerErrorDialogFragment()
val args = Bundle()
args.putString(ERROR, error)
fragment.arguments =args
return fragment
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val error: String = arguments!!.getString(ERROR) as String
val alertDialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireActivity())
alertDialogBuilder.setTitle("Server Error")
alertDialogBuilder.setMessage("Error: $error")
alertDialogBuilder.setPositiveButton("OK"
) { dialog, which -> TODO("Not yet implemented") }
alertDialogBuilder.setNegativeButton("Cancel"
) { dialog, which ->
if (dialog != null) {
dialog.dismiss()
}
}
return alertDialogBuilder.create()
}
} | 0 | null | 1 | 3 | 8796dcedbd5598b9e591ab702e6445e478ce4662 | 1,228 | restaurants | MIT License |
common/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/data/projectsrepository/ProjectsRepositoryExceptions.kt | Wavesonics | 499,367,913 | false | {"Kotlin": 1630287, "Swift": 32452, "CSS": 2064, "Ruby": 1578, "Shell": 361} | package com.darkrockstudios.apps.hammer.common.data.projectsrepository
import dev.icerock.moko.resources.StringResource
class ValidationFailedException(val errorMessage: StringResource) : IllegalArgumentException()
class ProjectCreationFailedException(val errorMessage: StringResource?) : IllegalArgumentException()
class ProjectRenameFailed(val reason: Reason) : Exception() {
enum class Reason {
InvalidName, AlreadyExists, SourceDoesNotExist, MoveFailed
}
} | 19 | Kotlin | 6 | 128 | 5eb281596110fe9c315f9c53d5412a93078f870d | 466 | hammer-editor | MIT License |
klogging/src/jvmMain/kotlin/io/klogging/sending/Seq.kt | klogging | 378,410,833 | false | null | /*
Copyright 2021-2024 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.klogging.sending
import io.klogging.internal.trace
import io.klogging.internal.warn
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
/**
* Send a CLEF event string to a Seq server.
*
* @param url URL of the Seq server
* @param eventString one or more CLEF-formatted, newline-separated log event(s)
*/
internal actual fun sendToSeq(
url: String,
apiKey: String?,
checkCertificate: Boolean,
eventString: String,
) {
val conn = seqConnection(url, apiKey, checkCertificate)
try {
trace("Seq", "Sending events to Seq in context ${Thread.currentThread().name}")
conn.outputStream.use { it.write(eventString.toByteArray()) }
val response = conn.inputStream.use { String(it.readAllTheBytes()) }
if (conn.responseCode >= 400) {
warn("Seq", "Error response ${conn.responseCode} sending CLEF message: $response")
}
} catch (e: IOException) {
warn("Seq", "Exception sending CLEF message: $e")
}
}
/** Construct an HTTP connection to the Seq server. */
private fun seqConnection(serverUrl: String, apiKey: String?, checkCertificate: Boolean): HttpURLConnection {
val url = URL("$serverUrl/api/events/raw")
val conn = if (serverUrl.startsWith("https://")) {
(url.openConnection() as HttpsURLConnection).also {
if (!checkCertificate) Certificates.relaxHostChecking(it)
}
} else {
url.openConnection() as HttpURLConnection
}
conn.requestMethod = "POST"
conn.setRequestProperty("Content-Type", "application/vnd.serilog.clef")
if (apiKey != null) conn.setRequestProperty("X-Seq-ApiKey", apiKey)
conn.doOutput = true
return conn
}
| 17 | null | 18 | 91 | 89ae2ddc6aedc9f4f68267ebd8b0b0f0da43e81d | 2,360 | klogging | Apache License 2.0 |
core/src/com/fabiantarrach/breakinout/game/entity/goodie/SmallerPaddle.kt | ftarrach | 158,593,064 | false | null | package com.fabiantarrach.breakinout.game.entity.goodie
import com.fabiantarrach.breakinout.game.component.rectangle.Rectangle
import com.fabiantarrach.breakinout.game.entity.Paddle
import com.fabiantarrach.breakinout.util.GdxColor
import com.fabiantarrach.breakinout.util.engine.EntityDatabase
class SmallerPaddle(rectangle: Rectangle) : Goodie(rectangle) {
override val color: GdxColor = GdxColor.BLUE
override fun activate(database: EntityDatabase) =
database.each(Paddle::class) {
it.smaller()
Reset(it).start()
}
private class Reset(private val paddle: Paddle) : Thread() {
override fun run() {
Thread.sleep(5000)
paddle.bigger()
}
}
} | 0 | Kotlin | 0 | 0 | 8ebe8338ad5702f6f12e1cf7ce46b25addf5ebda | 673 | BreakinOut | MIT License |
src/main/kotlin/com/mrwhoami/qqservices/RandomNumberGenerator.kt | MrWhoami | 285,504,347 | false | null | package com.mrwhoami.qqservices
import net.mamoe.mirai.event.events.GroupMessageEvent
import net.mamoe.mirai.message.data.PlainText
import net.mamoe.mirai.message.data.at
import net.mamoe.mirai.message.data.content
import net.mamoe.mirai.message.data.isContentEmpty
import kotlin.random.Random
class RandomNumberGenerator {
init {
BotHelper.registerFunctions(
"随机数生成器",
listOf("#RNG <start> <end>", "#RNG <end>", "#RNG")
)
}
suspend fun onGrpMsg(event: GroupMessageEvent) {
// Check if this is text message
val msg = event.message
if (!msg.all { block -> block.isContentEmpty() || block is PlainText }) {
return
}
// Check if this is an order
val msgContent = msg.content
if (!msgContent.startsWith("#RNG")) {
return
}
val customer = event.sender
// Parse args and check.
val args = msgContent.split(" ")
val num_args = args.filter { arg -> arg.toIntOrNull() != null }.map { arg -> arg.toInt() }
// Check args number and give default value
val start = if (num_args.size > 1) num_args[0] else 0
val end = when(num_args.size) {
0 -> 100
1 -> num_args[0]
else -> num_args[1]
}
if (end <= start) {
event.group.sendMessage(customer.at() + "End must larger than start.")
} else {
val result = Random.nextInt(start, end)
event.group.sendMessage(customer.at() + "RNG [$start,$end) -> $result")
}
}
} | 2 | Kotlin | 9 | 11 | ef6e7efbb8b44c38c22abb000aafb4d02b22d3a9 | 1,599 | SDDDBotServices | Apache License 2.0 |
app/src/main/java/h/lillie/reborntube/settings/DebugSettings.kt | LillieH1000 | 517,439,028 | false | {"Kotlin": 203460} | package h.lillie.reborntube.settings
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import android.widget.TableRow
import androidx.appcompat.app.AppCompatActivity
import h.lillie.reborntube.classes.Loader
import h.lillie.reborntube.R
import h.lillie.reborntube.player.Player
import h.lillie.reborntube.databases.AppHistoryDB
import h.lillie.reborntube.databases.PlayerHistoryDB
import java.io.File
class DebugSettings : AppCompatActivity() {
private val videoIDs: List<String> = arrayListOf("0yqm7vrCp-g", "wq_VD_wX12U", "B7HaMN_mcKk", "SQ_BWki10Y8", "DRwtxBtYZzg", "jfKfPfyJRdk", "LACbVhgtx9I", "pbins17akHs", "Qskm9MTz2V4", "NocXEwsJGOQ")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.debugsettings)
val videoSettingsRow: TableRow = findViewById(R.id.videoSettingsRow)
videoSettingsRow.setOnClickListener {
loadVideo(0)
}
val videoTranslatedSettingsRow: TableRow = findViewById(R.id.videoTranslatedSettingsRow)
videoTranslatedSettingsRow.setOnClickListener {
loadVideo(1)
}
val twoOneVideoSettingsRow: TableRow = findViewById(R.id.twoOneVideoSettingsRow)
twoOneVideoSettingsRow.setOnClickListener {
loadVideo(2)
}
val shortsVideoSettingsRow: TableRow = findViewById(R.id.shortsVideoSettingsRow)
shortsVideoSettingsRow.setOnClickListener {
loadVideo(3)
}
val videoOnDemandSettingsRow: TableRow = findViewById(R.id.videoOnDemandSettingsRow)
videoOnDemandSettingsRow.setOnClickListener {
loadVideo(4)
}
val liveStreamSettingsRow: TableRow = findViewById(R.id.liveStreamSettingsRow)
liveStreamSettingsRow.setOnClickListener {
loadVideo(5)
}
val contentCheckVideoSettingsRow: TableRow = findViewById(R.id.contentCheckVideoSettingsRow)
contentCheckVideoSettingsRow.setOnClickListener {
loadVideo(6)
}
val ageRestrictedVideoSettingsRow: TableRow = findViewById(R.id.ageRestrictedVideoSettingsRow)
ageRestrictedVideoSettingsRow.setOnClickListener {
loadVideo(7)
}
val sponsorBlockStartSegmentVideoSettingsRow: TableRow = findViewById(R.id.sponsorBlockStartSegmentVideoSettingsRow)
sponsorBlockStartSegmentVideoSettingsRow.setOnClickListener {
loadVideo(8)
}
val sponsorBlockDualSegmentVideoSettingsRow: TableRow = findViewById(R.id.sponsorBlockDualSegmentVideoSettingsRow)
sponsorBlockDualSegmentVideoSettingsRow.setOnClickListener {
loadVideo(9)
}
val clearAppHistorySettingsRow: TableRow = findViewById(R.id.clearAppHistorySettingsRow)
clearAppHistorySettingsRow.setOnClickListener {
val appHistoryDB = AppHistoryDB(this@DebugSettings)
appHistoryDB.delete()
appHistoryDB.close()
Toast.makeText(this@DebugSettings, "Successfully cleared app history", Toast.LENGTH_SHORT).show()
}
val clearPlayerHistorySettingsRow: TableRow = findViewById(R.id.clearPlayerHistorySettingsRow)
clearPlayerHistorySettingsRow.setOnClickListener {
val playerHistoryDB = PlayerHistoryDB(this@DebugSettings)
playerHistoryDB.delete()
playerHistoryDB.close()
Toast.makeText(this@DebugSettings, "Successfully cleared player history", Toast.LENGTH_SHORT).show()
}
val deleteAllDownloadsSettingsRow: TableRow = findViewById(R.id.deleteAllDownloadsSettingsRow)
deleteAllDownloadsSettingsRow.setOnClickListener {
val folder = File("${[email protected]}").list()
for (file in folder!!) {
if (file.contains(".mp4")) {
File([email protected], file).delete()
}
}
Toast.makeText(this@DebugSettings, "Successfully deleted all downloads", Toast.LENGTH_SHORT).show()
}
}
private fun loadVideo(videoArrayPosition: Int) {
val loader = Loader()
val status: Boolean = loader.playerInit(this@DebugSettings, videoIDs[videoArrayPosition], videoIDs, videoArrayPosition, true, true).toString().toBoolean()
if (!status) {
Toast.makeText(this@DebugSettings, "Video Unsupported", Toast.LENGTH_SHORT).show()
} else if (status) {
startActivity(Intent(this@DebugSettings, Player::class.java))
}
}
} | 1 | Kotlin | 1 | 9 | eaa742388611583b4c0838891f44c1d288359428 | 4,607 | RebornTube | MIT License |
projects/fabric/src/main/kotlin/site/siredvin/peripheralworks/fabric/FabricPeripheralWorksPlatform.kt | SirEdvin | 489,471,520 | false | null | package site.siredvin.peripheralworks.fabric
import dan200.computercraft.api.pocket.IPocketUpgrade
import dan200.computercraft.api.pocket.PocketUpgradeSerialiser
import dan200.computercraft.api.turtle.ITurtleUpgrade
import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser
import net.minecraft.core.Registry
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.Container
import net.minecraft.world.item.CreativeModeTab
import net.minecraft.world.item.Item
import net.minecraft.world.item.crafting.Recipe
import net.minecraft.world.item.crafting.RecipeSerializer
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityType
import site.siredvin.peripheralworks.xplat.PeripheralWorksPlatform
import java.util.function.Supplier
object FabricPeripheralWorksPlatform : PeripheralWorksPlatform {
override fun <T : Item> registerItem(key: ResourceLocation, item: Supplier<T>): Supplier<T> {
val registeredItem = Registry.register(BuiltInRegistries.ITEM, key, item.get())
return Supplier { registeredItem }
}
override fun <T : Block> registerBlock(key: ResourceLocation, block: Supplier<T>, itemFactory: (T) -> Item): Supplier<T> {
val registeredBlock = Registry.register(BuiltInRegistries.BLOCK, key, block.get())
Registry.register(BuiltInRegistries.ITEM, key, itemFactory(registeredBlock))
return Supplier { registeredBlock }
}
override fun <V : BlockEntity, T : BlockEntityType<V>> registerBlockEntity(key: ResourceLocation, blockEntityTypeSup: Supplier<T>): Supplier<T> {
val registeredBlockEntityType = Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, key, blockEntityTypeSup.get())
return Supplier { registeredBlockEntityType }
}
override fun registerCreativeTab(key: ResourceLocation, tab: CreativeModeTab): Supplier<CreativeModeTab> {
val registeredTab = Registry.register(BuiltInRegistries.CREATIVE_MODE_TAB, key, tab)
return Supplier { registeredTab }
}
override fun <C : Container, T : Recipe<C>> registerRecipeSerializer(
key: ResourceLocation,
serializer: RecipeSerializer<T>,
): Supplier<RecipeSerializer<T>> {
val registeredRecipe = Registry.register(BuiltInRegistries.RECIPE_SERIALIZER, key, serializer)
return Supplier { registeredRecipe }
}
override fun <V : IPocketUpgrade> registerPocketUpgrade(
key: ResourceLocation,
serializer: PocketUpgradeSerialiser<V>,
): Supplier<PocketUpgradeSerialiser<V>> {
val registry: Registry<PocketUpgradeSerialiser<*>> = (
BuiltInRegistries.REGISTRY.get(PocketUpgradeSerialiser.registryId().location())
?: throw IllegalStateException("Something is not correct with turtle registry")
) as Registry<PocketUpgradeSerialiser<*>>
val registered = Registry.register(registry, key, serializer)
return Supplier { registered }
}
override fun <V : ITurtleUpgrade> registerTurtleUpgrade(
key: ResourceLocation,
serializer: TurtleUpgradeSerialiser<V>,
): Supplier<TurtleUpgradeSerialiser<V>> {
val registry: Registry<TurtleUpgradeSerialiser<*>> = (
BuiltInRegistries.REGISTRY.get(TurtleUpgradeSerialiser.registryId().location())
?: throw IllegalStateException("Something is not correct with turtle registry")
) as Registry<TurtleUpgradeSerialiser<*>>
val registered = Registry.register(registry, key, serializer)
return Supplier { registered }
}
}
| 3 | Kotlin | 2 | 6 | 4261ad04499375f16704c8df3f3faeb0e314ac54 | 3,714 | UnlimitedPeripheralWorks | MIT License |
app/src/main/java/com/aowen/monolith/feature/search/MatchSearchSection.kt | heatcreep | 677,508,642 | false | {"Kotlin": 1109821} | package com.aowen.monolith.feature.search
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.aowen.monolith.R
import com.aowen.monolith.data.MatchDetails
import com.aowen.monolith.ui.components.PlayerLoadingCard
import com.aowen.monolith.ui.theme.BadgeBlueGreen
import com.aowen.monolith.ui.theme.NeroBlack
import com.aowen.monolith.ui.utils.handleTimeSinceMatch
@Composable
fun MatchSearchSection(
isLoading: Boolean,
foundMatch: MatchDetails,
navigateToMatchDetails: (String, String) -> Unit = {_, _ -> }
) {
Column {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Match",
color = MaterialTheme.colorScheme.secondary,
style = MaterialTheme.typography.titleMedium
)
}
Spacer(modifier = Modifier.size(16.dp))
AnimatedContent(
targetState = isLoading,
label = ""
) { isLoadingSearch ->
if (isLoadingSearch) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
PlayerLoadingCard(
titleWidth = 100.dp,
subtitleWidth = 75.dp
)
}
} else {
Column(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Card(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.primaryContainer)
.border(
1.dp,
MaterialTheme.colorScheme.secondary,
RoundedCornerShape(4.dp)
)
.clickable {
navigateToMatchDetails(
foundMatch.dawn.players.first().playerId,
foundMatch.matchId
)
},
shape = RoundedCornerShape(4.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
)
) {
Row(
modifier = Modifier
.fillMaxWidth(1f)
.padding(
start = 8.dp,
bottom = 1.dp
)
.padding(vertical = 16.dp, horizontal = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(28.dp)
) {
Column(
modifier = Modifier
.width(72.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier
.size(32.dp),
contentScale = ContentScale.Crop,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.secondary),
painter = painterResource(id = R.drawable.map_icon),
contentDescription = null
)
Text(
textAlign = TextAlign.Start,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
text = handleTimeSinceMatch(foundMatch.endTime)
)
}
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = "Match *${foundMatch.matchId.takeLast(4)}",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.ExtraBold,
color = MaterialTheme.colorScheme.secondary
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = foundMatch.region.uppercase(),
modifier = Modifier
.background(
MaterialTheme.colorScheme.secondary,
RoundedCornerShape(4.dp)
)
.padding(4.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
Text(
text = foundMatch.gameMode.uppercase(),
modifier = Modifier
.background(
BadgeBlueGreen,
RoundedCornerShape(4.dp)
)
.padding(4.dp),
style = MaterialTheme.typography.bodySmall,
color = NeroBlack
)
}
}
}
}
}
}
}
}
}
} | 11 | Kotlin | 0 | 2 | 2bb3c9c13fc0fd49e4d796e5f22fb59103657655 | 8,632 | predecessor-monolith | MIT License |
app/src/main/java/com/br/baseproject/ui/view/ChatActivity.kt | Gian-f | 544,413,970 | false | null | package com.br.baseproject.ui.view
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.br.baseproject.R
import com.br.baseproject.databinding.ActivityChatBinding
class ChatActivity : AppCompatActivity() {
private lateinit var binding: ActivityChatBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityChatBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView=binding.navView
navView.setOnItemSelectedListener {
when(it.itemId) {
R.id.navigation_conversas -> {
true
}
R.id.navigation_perfil -> {
true
}
else -> false
}
}
}
} | 0 | Kotlin | 0 | 0 | 3944a79c2958f9248e4a309f9f1631d1a8f575ac | 1,148 | Crud-with-RoomDatabase | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.