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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/database/src/main/kotlin/com/mobiledevpro/database/dao/StockAlertDao.kt | mobiledevpro | 434,560,335 | false | {"Kotlin": 98027, "Java": 3283} | /*
* Copyright 2021 | <NAME> | http://mobile-dev.pro
*
*
* 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.mobiledevpro.database.dao
import androidx.room.Dao
import androidx.room.Query
import com.mobiledevpro.database.entity.StockAlertEntity
import io.reactivex.Observable
/**
* Dao for alert log
*
* Created on Jan 18, 2022.
*
*/
@Dao
interface StockAlertDao : BaseDao<StockAlertEntity> {
@Query(
"SELECT * FROM stock_alert ORDER BY timeMs DESC"
)
fun selectAll(): Observable<List<StockAlertEntity>>
} | 1 | Kotlin | 1 | 3 | 374a766ae6e3c7a038465ae5f45a08549a6c78e8 | 1,057 | Android-WorkManager-Demo | Apache License 2.0 |
app/src/main/java/com/project/gitUser/database/GitUserDataEntity.kt | CodingRock-Star | 392,255,419 | false | null | package com.project.gitUser.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Entity class for the which defines the Git Table in the GitUser DataBase.
*/
@Entity(tableName = "gitUserTable")
data class GitUserDatabase(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
@ColumnInfo(name = "name")
val name: String?,
@ColumnInfo(name = "full_name")
val fullName: String?,
@ColumnInfo(name = "description")
val description: String?,
@ColumnInfo(name = "url")
val url: String?,
@ColumnInfo(name = "html_url")
val web_url: String?,
@ColumnInfo(name = "stargazers_count")
val stars: Int,
@ColumnInfo(name = "forks_count")
val forks: Int,
@ColumnInfo(name = "language")
val language: String?,
@ColumnInfo(name = "watchers_count")
val watcherCount: String?,
@ColumnInfo(name = "created_at")
val createdAt: String?,
@ColumnInfo(name = "updated_at")
val updated: String?,
@ColumnInfo(name = "avatar_url")
val avatar_url: String?
)
| 0 | Kotlin | 0 | 1 | f2932747acc0fc006fd502bb81699e8dc5472d7b | 1,088 | GitSearchApp | The Unlicense |
bidappAds/src/commonMain/kotlin/io/bidapp/kmp/BIDBanner.kt | bidapphub | 787,934,281 | false | {"Kotlin": 34902} | package io.bidapp.kmp
expect class BIDBanner(applicationActivity: Any?, bidBannerSize: BIDAdFormat){
fun bindBanner(container : Any?)
fun getBannerSize() : BIDAdFormat?
fun setBannerViewDelegate(bidBannerShow: BIDBannerShow)
fun refresh()
fun startAutorefresh(interval: Double)
fun stopAutorefresh()
fun destroy()
}
| 0 | Kotlin | 0 | 0 | 26e5e7509c5bbf95cfd9ff5c8dfd43c9ccb21845 | 349 | bidapp-kotlin-multiplatform-plugin | MIT License |
src/com/nerdscorner/android/plugin/github/ui/tablemodels/GHBranchTableModel.kt | marcherdiego | 274,920,064 | false | {"XML": 9, "Ignore List": 1, "Text": 1, "Markdown": 1, "SVG": 3, "Kotlin": 53, "Java": 8} | package com.nerdscorner.android.plugin.github.ui.tablemodels
import com.nerdscorner.android.plugin.github.domain.gh.GHBranchWrapper
import java.io.Serializable
class GHBranchTableModel(branches: MutableList<GHBranchWrapper>, colNames: Array<String>)
: BaseModel<GHBranchWrapper>(branches, colNames), Serializable {
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
if (rowIndex < 0 || rowIndex >= items.size) {
return null
}
val branch = items[rowIndex]
return when (columnIndex) {
COLUMN_NAME -> branch.ghBranch.name
COLUMN_STATUS -> branch.buildStatus
COLUMN_TRIGGER_BUILD -> TRIGGER_BUILD
else -> null
}
}
override fun compare(one: GHBranchWrapper, other: GHBranchWrapper): Int {
return super.compare(other, one)
}
companion object {
const val COLUMN_NAME = 0
const val COLUMN_STATUS = 1
const val COLUMN_TRIGGER_BUILD = 2
private const val TRIGGER_BUILD = "Re-run"
}
}
| 0 | Kotlin | 1 | 9 | b346f5af63cdf95c08221469b384cedaa8e74a2d | 1,062 | github-tools-plugin | Apache License 2.0 |
src/main/kotlin/com/example/kotlin/app/service/core/event/IEventHandler.kt | nimvb | 175,698,920 | false | null | package com.example.kotlin.app.service.core.event
/**
* Defines required API for event initiator
*/
interface IEventHandler<T> : IEvent<T> {
/**
* Returns list of current event subscribers
*/
fun getListeners(): List<T>
} | 0 | Kotlin | 0 | 1 | 907e236c5a0385fc139345d031f5b8e2d3ff3a40 | 243 | mvp-kotlin | MIT License |
src/main/kotlin/com/github/fisherman08/micronautbooks/implementations/jooqimpl/table/BookAuthorTable.kt | fisherman08 | 334,301,590 | false | null | package com.github.fisherman08.micronautbooks.implementations.jooqimpl.table
import org.jooq.impl.DSL
import java.util.*
object BookAuthorTable {
val table = DSL.table("book_author")
val bookId = DSL.field("book_id", UUID::class.java)
val authorId = DSL.field("author_id", UUID::class.java)
}
| 0 | Kotlin | 0 | 1 | e0ba367eed3d3b7b84c3bf33336c0de72bad96e1 | 309 | micronaut_book_management | MIT License |
src/test/kotlin/DelimitedBlocksTest.kt | srackham | 99,287,737 | false | null | import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.rimumarkup.Api
import org.rimumarkup.DelimitedBlocks
import org.rimumarkup.Io
class DelimitedBlocksTest {
@BeforeEach
fun before() {
Api.init()
}
@Test
fun renderTest() {
var input = "Test"
var reader = Io.Reader(input)
var writer = Io.Writer()
DelimitedBlocks.render(reader, writer)
assertEquals("<p>Test</p>", writer.toString())
input = " Indented"
reader = Io.Reader(input)
writer = Io.Writer()
DelimitedBlocks.render(reader, writer)
assertEquals("<pre><code>Indented</code></pre>", writer.toString())
}
}
| 0 | Kotlin | 0 | 0 | a3eb3fb401b0ad6323470508ec68d97f956cdd48 | 754 | rimu-kt | MIT License |
app/src/main/java/com/example/androiddevchallenge/Welcome.kt | Dartek12 | 347,237,108 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.androiddevchallenge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.navigate
@Composable
fun Welcome(navController: NavHostController) {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
WelcomeImage()
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.Center,
) {
BrandingName()
Spacer(modifier = Modifier.height(32.dp))
BigButton("Sign up", backgroundColor = MaterialTheme.colors.primary)
Spacer(modifier = Modifier.height(8.dp))
BigButton(
"Log in", backgroundColor = MaterialTheme.colors.secondary,
onClick = {
navController.navigate("login")
}
)
}
}
}
@Composable
fun BrandingName() {
val vectorRes = if (MaterialTheme.colors.isLight) {
R.drawable.ic_light_logo
} else {
R.drawable.ic_dark_logo
}
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
Image(imageVector = ImageVector.vectorResource(id = vectorRes), contentDescription = "Logo")
}
}
@Composable
fun WelcomeImage() {
val vectorRes = if (MaterialTheme.colors.isLight) {
R.drawable.ic_light_welcome
} else {
R.drawable.ic_dark_welcome
}
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Image(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
imageVector = ImageVector.vectorResource(id = vectorRes),
contentDescription = "Background",
contentScale = ContentScale.Crop
)
}
}
| 0 | Kotlin | 0 | 0 | a556739784e885dfd5177102c4ba604633042810 | 3,405 | Challenge---speed-round | Apache License 2.0 |
apps/student/src/main/java/com/instructure/student/features/files/details/FileDetailsLocalDataSource.kt | instructure | 179,290,947 | false | {"Kotlin": 16085132, "Dart": 4413539, "HTML": 185120, "Ruby": 32390, "Shell": 19157, "Java": 13488, "Groovy": 11717, "JavaScript": 9505, "CSS": 1356, "Swift": 404, "Dockerfile": 112, "Objective-C": 37} | /*
* Copyright (C) 2023 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.instructure.student.features.files.details
import com.instructure.canvasapi2.models.FileFolder
import com.instructure.pandautils.room.offline.daos.FileFolderDao
import com.instructure.pandautils.room.offline.daos.LocalFileDao
class FileDetailsLocalDataSource(
private val fileFolderDao: FileFolderDao,
private val localFileFolderDao: LocalFileDao,
) : FileDetailsDataSource {
override suspend fun getFileFolderFromURL(url: String, fileId: Long, forceNetwork: Boolean): FileFolder? {
val file = fileFolderDao.findById(fileId) ?: return null
val localFile = localFileFolderDao.findById(fileId) ?: return null
return file.copy(url = localFile.path).toApiModel()
}
} | 7 | Kotlin | 102 | 127 | f82ec380673be5812c88bbc6b15c3d960515c6d8 | 1,370 | canvas-android | Apache License 2.0 |
src/main/kotlin/no/nav/tms/utbetalingsoversikt/api/ytelse/domain/external/UtbetalingEkstern.kt | navikt | 418,463,132 | false | {"Kotlin": 116359, "Dockerfile": 263} | package no.nav.tms.utbetalingsoversikt.api.ytelse.domain.external
import kotlinx.serialization.Serializable
import java.time.LocalDate
@Serializable
data class UtbetalingEkstern(
val utbetaltTil: AktoerEkstern,
val utbetalingsmetode: String,
val utbetalingsstatus: String,
val posteringsdato: String,
val forfallsdato: String? = null,
val utbetalingsdato: String? = null,
val utbetalingNettobeloep: Double? = null,
val utbetalingsmelding: String? = null,
val utbetaltTilKonto: BankkontoEkstern? = null,
val ytelseListe: List<YtelseEkstern> = emptyList(),
) {
fun harKontonummer() = utbetaltTilKonto != null && utbetaltTilKonto.kontonummer.isNotBlank()
val erUtbetalt = utbetalingsdato != null
fun isInPeriod(fomDate: LocalDate, toDate: LocalDate) = ytelsesdato() in fomDate..toDate
fun ytelsesdato() = LocalDate.parse(utbetalingsdato ?: forfallsdato)
}
| 0 | Kotlin | 0 | 0 | ba27d3ec361723e7648399fac5b95b0b77e49ac1 | 928 | tms-utbetalingsoversikt-api | MIT License |
GradleToolKit/src/main/kotlin/com/ss/android/ugc/bytex/gradletoolkit/BaseVariant.kt | willpyshan13 | 233,095,205 | false | null | package com.ss.android.ugc.bytex.gradletoolkit
import com.android.build.api.artifact.ArtifactType
import com.android.build.gradle.api.BaseVariant
import com.android.build.gradle.internal.api.BaseVariantImpl
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import com.android.build.gradle.internal.scope.VariantScope
import com.android.build.gradle.internal.variant.BaseVariantData
import com.android.build.gradle.tasks.MergeResources
import org.gradle.api.artifacts.ArtifactCollection
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import java.io.File
val BaseVariant.scope: VariantScope
get() = if (ANDROID_GRADLE_PLUGIN_VERSION.major < 4 || (ANDROID_GRADLE_PLUGIN_VERSION.major == 4 && ANDROID_GRADLE_PLUGIN_VERSION.minor == 0)) {
this.scope40
} else {
this.scope41
}
private val BaseVariant.scope40: VariantScope
get() = ReflectionUtils.callMethod<BaseVariantData>(this, javaClass, "getVariantData", arrayOf(), arrayOf()).scope
private val BaseVariant.scope41: VariantScope
get() = ReflectionUtils.getField<Any>(this, BaseVariantImpl::class.java, "componentProperties").let {
ReflectionUtils.callMethod<BaseVariantData>(it, it.javaClass, "getVariantScope", arrayOf(), arrayOf()) as VariantScope
}
fun BaseVariant.getArtifactCollection(configType: AndroidArtifacts.ConsumedConfigType, artifactScope: AndroidArtifacts.ArtifactScope, artifactType: AndroidArtifacts.ArtifactType): ArtifactCollection {
return if (ANDROID_GRADLE_PLUGIN_VERSION.major < 4 || (ANDROID_GRADLE_PLUGIN_VERSION.major == 4 && ANDROID_GRADLE_PLUGIN_VERSION.minor == 0)) {
this.getArtifactCollection40(configType, artifactScope, artifactType)
} else {
this.getArtifactCollection41(configType, artifactScope, artifactType)
}
}
private fun BaseVariant.getArtifactCollection40(configType: AndroidArtifacts.ConsumedConfigType, artifactScope: AndroidArtifacts.ArtifactScope, artifactType: AndroidArtifacts.ArtifactType): ArtifactCollection {
return scope.getArtifactCollection(configType, artifactScope, artifactType)
}
private fun BaseVariant.getArtifactCollection41(configType: AndroidArtifacts.ConsumedConfigType, artifactScope: AndroidArtifacts.ArtifactScope, artifactType: AndroidArtifacts.ArtifactType): ArtifactCollection {
return ReflectionUtils.getField<Any>(this, BaseVariantImpl::class.java, "componentProperties").let {
ReflectionUtils.callPublicMethod<Any>(it, it.javaClass, "getVariantDependencies", arrayOf(), arrayOf()).let {
ReflectionUtils.callPublicMethod<ArtifactCollection>(it, it.javaClass, "getArtifactCollection", arrayOf(
AndroidArtifacts.ConsumedConfigType::class.java, AndroidArtifacts.ArtifactScope::class.java, AndroidArtifacts.ArtifactType::class.java
), arrayOf(configType, artifactScope, artifactType))
}
}
}
fun BaseVariant.getArtifactFiles(artifactType: ArtifactType): Collection<File> {
return if (ANDROID_GRADLE_PLUGIN_VERSION.major > 3 || (ANDROID_GRADLE_PLUGIN_VERSION.major == 3 && ANDROID_GRADLE_PLUGIN_VERSION.minor >= 5)) {
this.getArtifactFiles35_(artifactType)
} else {
this.getArtifactFiles30_(artifactType)
}
}
private fun BaseVariant.getArtifactFiles35_(artifactType: ArtifactType): Collection<File> {
return scope.artifacts.getFinalProducts<Directory>(artifactType).orNull?.map { it.asFile }?.toSet()
?: emptyList()
}
private fun BaseVariant.getArtifactFiles30_(artifactType: ArtifactType): Collection<File> {
return scope.artifacts.getArtifactFiles(artifactType).files
}
val BaseVariant.blameLogOutputFolder: File
get() = if (ANDROID_GRADLE_PLUGIN_VERSION.major < 4 || (ANDROID_GRADLE_PLUGIN_VERSION.major == 4 && ANDROID_GRADLE_PLUGIN_VERSION.minor == 0)) {
this.blameLogOutputFolder40
} else {
this.blameLogOutputFolder41
}
private val BaseVariant.blameLogOutputFolder40: File
get() = scope.resourceBlameLogDir
private val BaseVariant.blameLogOutputFolder41: File
get() = mergeResources.let {
ReflectionUtils.callMethod<DirectoryProperty>(it, MergeResources::class.java, "getBlameLogOutputFolder", arrayOf(), arrayOf()).asFile.get()
} | 0 | null | 0 | 1 | 2f09ca1e11a4d07cf93fdb016a2bc8d8a8cfa780 | 4,263 | ByteX | Apache License 2.0 |
app/src/main/java/com/bluecat/githubfeed/ui/adapters/FeedAdapter.kt | BlueCat-Community | 213,360,545 | false | null | package com.bluecat.githubfeed.ui.adapters
import android.view.View
import com.bluecat.githubfeed.R
import com.bluecat.githubfeed.model.TestData
import com.bluecat.githubfeed.ui.viewHolders.FeedViewHolder
import com.skydoves.baserecyclerviewadapter.BaseAdapter
import com.skydoves.baserecyclerviewadapter.SectionRow
class FeedAdapter(private val delegate: FeedViewHolder.Delegate) : BaseAdapter() {
private val sectionItem = 0
init {
addSection(ArrayList<TestData>())
}
fun addItems(sampleItem: TestData) {
addItemOnSection(sectionItem, sampleItem)
notifyDataSetChanged()
}
fun removeItem(index: Int) {
sections()[0].removeAt(index)
notifyDataSetChanged()
}
override fun layout(sectionRow: SectionRow) = R.layout.item_feed
override fun viewHolder(layout: Int, view: View) = FeedViewHolder(view, delegate)
} | 15 | Kotlin | 5 | 8 | a94e8ff6c9692df0f7eeb89d470abe661cd0acc0 | 888 | GithubFeed | Apache License 2.0 |
src/main/kotlin/io/nshusa/rsam/binary/Archive.kt | GregHib | 138,198,808 | false | {"Kotlin": 283100, "CSS": 1905} | package io.nshusa.rsam.binary
import io.nshusa.rsam.util.ByteBufferUtils
import io.nshusa.rsam.util.CompressionUtils
import io.nshusa.rsam.util.HashUtils
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.ByteBuffer
import java.util.*
import java.util.zip.CRC32
class Archive(entries: Array<ArchiveEntry?>) {
var isExtracted: Boolean = false
private set
private val entries = LinkedHashMap<Int, ArchiveEntry>()
val entryCount: Int
get() = entries.size
class ArchiveEntry(val hash: Int, val uncompressedSize: Int, val compressedSize: Int, val data: ByteArray)
init {
Arrays.asList(*entries).forEach { it -> this.entries[it!!.hash] = it }
}
@Synchronized
@Throws(IOException::class)
fun encode(): ByteArray {
var size = 2 + entries.size * 10
for (file in entries.values) {
size += file.compressedSize
}
var buffer: ByteBuffer
if (!isExtracted) {
buffer = ByteBuffer.allocate(size + 6)
ByteBufferUtils.write24Int(buffer, size)
ByteBufferUtils.write24Int(buffer, size)
} else {
buffer = ByteBuffer.allocate(size)
}
buffer.putShort(entries.size.toShort())
for (entry in entries.values) {
buffer.putInt(entry.hash)
ByteBufferUtils.write24Int(buffer, entry.uncompressedSize)
ByteBufferUtils.write24Int(buffer, entry.compressedSize)
}
for (file in entries.values) {
buffer.put(file.data)
}
val data: ByteArray
if (!isExtracted) {
data = buffer.array()
} else {
val unzipped = buffer.array()
val zipped = CompressionUtils.bzip2(unzipped)
if (unzipped.size == zipped.size) {
throw RuntimeException("error zipped size matches original")
}
buffer = ByteBuffer.allocate(zipped.size + 6)
ByteBufferUtils.write24Int(buffer, unzipped.size)
ByteBufferUtils.write24Int(buffer, zipped.size)
buffer.put(zipped, 0, zipped.size)
data = buffer.array()
}
return data
}
@Throws(IOException::class)
fun readFile(name: String): ByteBuffer {
return readFile(HashUtils.nameToHash(name))
}
@Throws(IOException::class)
fun readFile(hash: Int): ByteBuffer {
for (entry in entries.values) {
if (entry.hash != hash) {
continue
}
return if (!isExtracted) {
val decompressed = ByteArray(entry.uncompressedSize)
CompressionUtils.debzip2(entry.data, decompressed)
ByteBuffer.wrap(decompressed)
} else {
ByteBuffer.wrap(entry.data)
}
}
throw FileNotFoundException(String.format("file=%d could not be found.", hash))
}
@Throws(IOException::class)
fun replaceFile(oldHash: Int, newName: String, data: ByteArray): Boolean {
return replaceFile(oldHash, HashUtils.nameToHash(newName), data)
}
@Throws(IOException::class)
fun replaceFile(oldHash: Int, newHash: Int, data: ByteArray): Boolean {
if (!entries.containsKey(oldHash))
return false
val entry: ArchiveEntry
val compressed = CompressionUtils.bzip2(data)
entry = if (data.size > compressed.size) {
Archive.ArchiveEntry(newHash, data.size, compressed.size, compressed)
} else {
Archive.ArchiveEntry(newHash, data.size, data.size, data)
}
entries.replace(oldHash, entry)
return true
}
@Throws(IOException::class)
fun writeFile(name: String, data: ByteArray): Boolean {
return writeFile(HashUtils.nameToHash(name), data)
}
@Throws(IOException::class)
fun writeFile(hash: Int, data: ByteArray): Boolean {
if (entries.containsKey(hash)) {
replaceFile(hash, hash, data)
}
val entry: ArchiveEntry
entry = if (!isExtracted) {
val compressed = CompressionUtils.bzip2(data)
Archive.ArchiveEntry(hash, data.size, compressed.size, compressed)
} else {
Archive.ArchiveEntry(hash, data.size, data.size, data)
}
entries[hash] = entry
return true
}
fun rename(oldHash: Int, newName: String): Boolean {
return rename(oldHash, HashUtils.nameToHash(newName))
}
fun rename(oldHash: Int, newHash: Int): Boolean {
if (!entries.containsKey(oldHash)) {
return false
}
val old = entries[oldHash] ?: return false
entries.replace(oldHash, ArchiveEntry(newHash, old.uncompressedSize, old.compressedSize, old.data))
return true
}
@Throws(FileNotFoundException::class)
fun getEntry(name: String): ArchiveEntry? {
return getEntry(HashUtils.nameToHash(name))
}
@Throws(FileNotFoundException::class)
fun getEntry(hash: Int): ArchiveEntry? {
if (entries.containsKey(hash)) {
return entries[hash]
}
throw FileNotFoundException(String.format("Could not find entry: %d.", hash))
}
@Throws(IOException::class)
fun getEntryAt(index: Int): ArchiveEntry {
if (index >= entries.size) {
throw FileNotFoundException(String.format("File at index=%d could not be found.", index))
}
for ((pos, entry) in entries.values.withIndex()) {
if (pos == index) {
return entry
}
}
throw FileNotFoundException(String.format("File at index=%d could not be found.", index))
}
fun indexOf(name: String): Int {
return indexOf(HashUtils.nameToHash(name))
}
fun indexOf(hash: Int): Int {
for ((index, entry) in entries.values.withIndex()) {
if (entry.hash == hash) {
return index
}
}
return -1
}
operator fun contains(name: String): Boolean {
return contains(HashUtils.nameToHash(name))
}
operator fun contains(hash: Int): Boolean {
return entries.containsKey(hash)
}
fun remove(name: String): Boolean {
return remove(HashUtils.nameToHash(name))
}
fun remove(hash: Int): Boolean {
if (entries.containsKey(hash)) {
entries.remove(hash)
return true
}
return false
}
fun getEntries(): Array<ArchiveEntry> {
return entries.values.toTypedArray()
}
companion object {
val TITLE_ARCHIVE = 1
val CONFIG_ARCHIVE = 2
val INTERFACE_ARCHIVE = 3
val MEDIA_ARCHIVE = 4
val VERSION_LIST_ARCHIVE = 5
val TEXTURE_ARCHIVE = 6
val WORDENC_ARCHIVE = 7
val SOUND_ARCHIVE = 8
@Throws(IOException::class)
fun decode(buffer: ByteBuffer): Archive {
var buffer = buffer
val uncompressedLength = ByteBufferUtils.readU24Int(buffer)
val compressedLength = ByteBufferUtils.readU24Int(buffer)
var extracted = false
if (uncompressedLength != compressedLength) {
val compressed = ByteArray(compressedLength)
val decompressed = ByteArray(uncompressedLength)
buffer.get(compressed)
CompressionUtils.debzip2(compressed, decompressed)
buffer = ByteBuffer.wrap(decompressed)
extracted = true
}
val entries = buffer.short.toInt() and 0xFFFF
val hashes = IntArray(entries)
val uncompressedSizes = IntArray(entries)
val compressedSizes = IntArray(entries)
val archiveEntries = arrayOfNulls<ArchiveEntry>(entries)
val entryBuf = ByteBuffer.wrap(buffer.array())
entryBuf.position(buffer.position() + entries * 10)
for (i in 0 until entries) {
hashes[i] = buffer.int
uncompressedSizes[i] = ByteBufferUtils.readU24Int(buffer)
compressedSizes[i] = ByteBufferUtils.readU24Int(buffer)
val entryData = ByteArray(compressedSizes[i])
entryBuf.get(entryData)
archiveEntries[i] = ArchiveEntry(hashes[i], uncompressedSizes[i], compressedSizes[i], entryData)
}
val archive = Archive(archiveEntries)
archive.isExtracted = extracted
return archive
}
@Throws(IOException::class)
fun encodeChecksum(archives: Array<Archive>): ByteBuffer {
// Integer.BYTES represents the crc stores as an integer which has 4 bytes, + Intger.BYTES because a pre calculated value is after the crcs which is in the form of a int as well
val buffer = ByteBuffer.allocate(archives.size * Integer.BYTES + Integer.BYTES)
val checksum = CRC32()
val crcs = IntArray(archives.size)
for (i in 1 until crcs.size) {
val archive = archives[i]
checksum.reset()
val encoded = archive.encode()
checksum.update(encoded, 0, encoded.size)
val crc = checksum.value.toInt()
crcs[i] = crc
buffer.putInt(crc)
}
// predefined value
var calculated = 1234
for (index in archives.indices) {
calculated = (calculated shl 1) + crcs[index]
}
buffer.putShort(calculated.toShort())
return buffer
}
}
} | 0 | Kotlin | 4 | 6 | 80ffcfc36f7dd397f1d6e1f6d74d3b5c16c70749 | 9,716 | interface-editor | MIT License |
data/src/main/java/com/semicolon/data/remote/response/ranks/inquiryRank/user/UserRankResponse.kt | Walkhub | 443,006,389 | false | null | package com.semicolon.data.remote.response.ranks.inquiryRank.user
import com.google.gson.annotations.SerializedName
import com.semicolon.domain.entity.rank.UserRankEntity
data class UserRankResponse(
@SerializedName("rank_list") val rankList: List<UserRank>
) {
data class UserRank(
@SerializedName("user_id") val userId: Int,
@SerializedName("name") val name: String,
@SerializedName("grade") val grade: Int,
@SerializedName("class_num") val classNum: Int,
@SerializedName("number") val number: Int,
@SerializedName("ranking") val ranking: Int,
@SerializedName("profile_image_url") val profileImageUrl: String,
@SerializedName("walk_count") val walkCount: Int
)
fun UserRank.toEntity() =
UserRankEntity.UserRank(
userId = userId,
name = name,
grade = grade,
classNum = classNum,
number = number,
ranking = ranking,
profileImageUrl = profileImageUrl,
walkCount = walkCount
)
}
fun UserRankResponse.toEntity() =
UserRankEntity(
rankList = rankList.map { it.toEntity() }
) | 30 | Kotlin | 1 | 15 | c2d85ebb9ae8b200be22e9029dcfdcbfed19e473 | 1,182 | walkhub_android | MIT License |
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/CoroutineBuilderAsyncRBawait.kt | muthu1001 | 683,734,410 | false | {"Kotlin": 202264} | package com.lukaslechner.coroutineusecasesonandroid.playground
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main(){
launchWithAsyncAwait()
}
fun launchWithAsyncAwait(){
println("main starts")
runBlocking {
println("runBlocking starts")
val deffered = async {
println("async starts")
mockNetworkRequest4()
}
val result = deffered.await()
println(result)
println("runBlocking ends")
}
println("main ends")
}
suspend fun mockNetworkRequest4(): String{
delay(1500)
return "Data retrieved successfully"
} | 0 | Kotlin | 0 | 0 | 7543eabe1ffbb788a809c799b09b4c6f1fabd697 | 694 | KotlinCoroutines | Apache License 2.0 |
app/src/main/java/com/pedrodavidmcr/agarden/plants/viewmodel/PlantDetailViewModelFactory.kt | pedrodaviddev | 130,232,921 | false | {"Kotlin": 62934} | package com.pedrodavidmcr.agarden.plants.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.pedrodavidmcr.agarden.plants.domain.repository.PlantsRepository
import com.pedrodavidmcr.agarden.plants.domain.repository.SamplesRepository
class PlantDetailViewModelFactory(
private val plantRepository: PlantsRepository,
private val samplesRepository: SamplesRepository,
private val plantId: Int)
: ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
PlantDetailViewModel(plantRepository, samplesRepository, plantId) as T
} | 0 | Kotlin | 0 | 0 | 047ec14b06efcb13d72ff90ce9a3bedace03e739 | 675 | a-garden-mobile | MIT License |
app/src/main/java/com/quickstart/android/compose/MainActivity.kt | sheldonirwin | 321,003,269 | false | null | package com.quickstart.android.compose
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.*
import com.quickstart.android.compose.ui.QuickstartAndroidComposeTheme
sealed class Screen(val route: String, @StringRes val resourceId: Int, val icon: ImageVector) {
object Login: Screen(
"login",
R.string.login,
Icons.Filled.Lock,
)
object Home: Screen(
"home",
R.string.home,
Icons.Filled.Home,
)
object Profile: Screen(
"profile",
R.string.profile,
Icons.Filled.Person,
)
}
val items = listOf(
Screen.Login,
Screen.Home,
Screen.Profile,
)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuickstartAndroidComposeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
// Greeting("Android")
Main()
}
}
}
}
}
@Composable
fun Main() {
val navController = rememberNavController()
Scaffold(
bottomBar = {
BottomNav(navController)
}
) {
NavHost(navController, startDestination = Screen.Home.route) {
composable(Screen.Login.route) { Login() }
composable(Screen.Home.route) { Home() }
composable(Screen.Profile.route) { Profile() }
}
}
}
@Composable
fun BottomNav(navController: NavController) {
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.arguments?.getString(KEY_ROUTE)
items.forEach { screen ->
BottomNavigationItem(
icon = { Icon(screen.icon) },
label = { Text(stringResource(screen.resourceId)) },
selected = currentRoute == screen.route,
onClick = {
// Pop back-stack entry to prevent back..back..back..back.. accumulation
navController.popBackStack(navController.graph.startDestination, false)
// Navigate if not already on the target route
if (currentRoute != screen.route) {
navController.navigate(screen.route)
}
},
)
}
}
}
@Composable
fun Home() {
Greeting(name = "Home page")
}
@Composable
fun Profile() {
Greeting(name = "Profile page")
}
@Composable
fun Login() {
Greeting(name = "Login page")
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!", modifier = Modifier.padding(24.dp))
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
QuickstartAndroidComposeTheme {
Greeting("Android")
}
} | 0 | Kotlin | 0 | 0 | 4581c5105c65d0b05c5d0447afe3776c7ab6f7c4 | 3,801 | qs-android-compose | MIT License |
app/src/main/java/com/example/admanager/activity/MainActivity.kt | Android-Venture | 614,335,216 | false | null | package com.example.admanager.activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.example.admanager.AD_FLOW
import com.example.admanager.R
import com.sofit.adsimplementationhelper.ad_classes.AdmobClass
import com.sofit.adsimplementationhelper.common.AdParamsPrefs
class MainActivity : AppCompatActivity() {
private lateinit var handler: Handler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
AdmobClass.loadAdmobInterstitial(this, AdParamsPrefs.getParams(this)!!,"Main Activity")
AdmobClass.loadNativeAdmob(this, AdParamsPrefs.getParams(this)!!,"Main Activity")
handler = Handler(Looper.getMainLooper())
handler.postDelayed({
val intent = Intent(this,AdTestActivity::class.java)
intent.putExtra(AD_FLOW,"Main Activity To Ad Test")
startActivity(intent)
finish()
}, 5000)
}
} | 2 | Kotlin | 0 | 0 | a9bec644991e8651ea964d25a24d611c9e8178ce | 1,107 | AdModule-android | MIT License |
src/main/kotlin/eZmaxApi/models/EzsigntemplateformfieldgroupCreateObjectV1Request.kt | eZmaxinc | 271,950,932 | false | {"Kotlin": 6909939} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import eZmaxApi.models.EzsigntemplateformfieldgroupRequestCompound
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Request for POST /1/object/ezsigntemplateformfieldgroup
*
* @param aObjEzsigntemplateformfieldgroup
*/
data class EzsigntemplateformfieldgroupCreateObjectV1Request (
@Json(name = "a_objEzsigntemplateformfieldgroup")
val aObjEzsigntemplateformfieldgroup: kotlin.collections.List<EzsigntemplateformfieldgroupRequestCompound>
)
| 0 | Kotlin | 0 | 0 | 961c97a9f13f3df7986ea7ba55052874183047ab | 782 | eZmax-SDK-kotlin | MIT License |
yaml-validator-tags/src/main/kotlin/io/github/kezhenxu94/validators/math/MathValidator.kt | yaml-validator | 250,129,940 | false | null | /**
* Copyright 2020 yaml-validator
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.kezhenxu94.validators.math
import io.github.kezhenxu94.core.Referable
import io.github.kezhenxu94.core.Validatable
import io.github.kezhenxu94.exceptions.ValidateException
internal abstract class MathValidator(protected val expected: Number = 0.0) : Validatable, Referable<Any> {
protected abstract val tag: String
override var reference: Any? = null
override fun validate(candidate: Any?) {
val actual = when (candidate) {
is Number -> candidate.toDouble()
is String -> candidate.toDouble()
else -> throw ValidateException("$tag validator cannot be applied to non-number values, actual: $candidate")
}
try {
if (reference == null) {
validateAnchor(actual)
} else {
validateAlias(actual)
}
} finally {
reference = candidate
}
}
protected abstract fun validateAnchor(anchor: Number)
protected abstract fun validateAlias(alias: Number)
}
| 2 | Kotlin | 1 | 5 | a98a64fe79aca309734df3fa959b2176b35aa0d1 | 1,637 | yaml-validator | Apache License 2.0 |
app/src/main/java/soup/animation/sample/drawable/notification/NotificationChannels.kt | fornewid | 205,703,351 | false | null | package soup.animation.sample.drawable.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
object NotificationChannels {
const val NOTIFICATION = "NOTIFICATION"
fun init(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.getSystemService<NotificationManager>()
?.createNotificationChannels(createChannels())
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannels(): List<NotificationChannel> {
return listOf(
NotificationChannel(
NOTIFICATION,
"Notification",
NotificationManager.IMPORTANCE_HIGH
)
)
}
}
| 0 | Kotlin | 0 | 13 | 4dcc8d4a20b973567987afb0ca31935c10f806b3 | 887 | android-animation-10p-more | Apache License 2.0 |
TravelerService/src/test/kotlin/it/polito/travelerservice/ProfileControllerTests.kt | tndevelop | 586,797,974 | false | null | package it.polito.travelerservice
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.security.Keys
import it.polito.travelerservice.entities.UserDetails
import it.polito.travelerservice.repositories.TicketPurchasedRepository
import it.polito.travelerservice.repositories.UserDetailsRepository
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.json.JSONObject
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.client.getForEntity
import org.springframework.boot.test.web.client.postForEntity
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.http.*
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import org.springframework.web.util.UriComponentsBuilder
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import java.util.*
@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ProfileControllerTests {
@LocalServerPort
protected var port: Int = 0
@Autowired
lateinit var restTemplate: TestRestTemplate
@Autowired
lateinit var userDetailsRepository : UserDetailsRepository
@Value("\${key}")
lateinit var key: String
@BeforeEach
fun destroyAll() {
userDetailsRepository.deleteAll()
}
@Test
fun getProfile() {
val baseUrl = "http://localhost:$port"
val userDetails = UserDetails("Name")
userDetailsRepository.save(userDetails)
val user = userDetailsRepository.findByName("Name")
assert(user != null)
val claims = Jwts.claims().setSubject("Name")
claims["roles"] = arrayListOf("ROLE_CUSTOMER")
val token = Jwts.builder()
.setSubject("Name")
.setClaims(claims)
.setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + 7*24*60*60*1000)) //exp in 7 days
.signWith(Keys.hmacShaKeyFor(key.toByteArray()))
.compact()
val headers = HttpHeaders()
headers.setContentType(MediaType.APPLICATION_JSON)
headers.set("Authorization", "Bearer $token")
val response: ResponseEntity<String> = restTemplate.exchange(
"$baseUrl/my/profile",
HttpMethod.GET,
HttpEntity<String>(null, headers),
String::class.java
)
Assertions.assertEquals(HttpStatus.ACCEPTED, response.statusCode)
val responseObject = JSONObject(response.body)
assert(responseObject.get("name") == "Name")
}
@Test
fun getProfileNoUser() {
val baseUrl = "http://localhost:$port"
val claims = Jwts.claims().setSubject("Name")
claims["roles"] = arrayListOf("ROLE_CUSTOMER")
val token = Jwts.builder()
.setSubject("Name")
.setClaims(claims)
.setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + 7*24*60*60*1000)) //exp in 7 days
.signWith(Keys.hmacShaKeyFor(key.toByteArray()))
.compact()
val headers = HttpHeaders()
headers.setContentType(MediaType.APPLICATION_JSON)
headers.set("Authorization", "Bearer $token")
val response: ResponseEntity<String> = restTemplate.exchange(
"$baseUrl/my/profile",
HttpMethod.GET,
HttpEntity<String>(null, headers),
String::class.java
)
Assertions.assertEquals(HttpStatus.FORBIDDEN, response.statusCode)
}
@Test
fun updateProfile() {
val baseUrl = "http://localhost:$port"
val userDetails = UserDetails("Name")
userDetailsRepository.save(userDetails)
val user = userDetailsRepository.findByName("Name")
assert(user != null)
val claims = Jwts.claims().setSubject("Name")
claims["roles"] = arrayListOf("ROLE_CUSTOMER")
val token = Jwts.builder()
.setSubject("Name")
.setClaims(claims)
.setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + 7*24*60*60*1000)) //exp in 7 days
.signWith(Keys.hmacShaKeyFor(key.toByteArray()))
.compact()
val headers = HttpHeaders()
headers.setContentType(MediaType.APPLICATION_JSON)
headers.set("Authorization", "Bearer $token")
val request = user!!.apply { address = "New address" }
val response: ResponseEntity<String> = restTemplate.exchange(
"$baseUrl/my/profile",
HttpMethod.PUT,
HttpEntity<UserDetails>(request, headers),
String::class.java
)
Assertions.assertEquals(HttpStatus.ACCEPTED, response.statusCode)
val userNew = userDetailsRepository.findByName("Name")
assert(userNew!!.address == "New address")
}
@Test
fun updateProfileWrongUsername() {
val baseUrl = "http://localhost:$port"
val userDetails = UserDetails("Name")
userDetailsRepository.save(userDetails)
val user = userDetailsRepository.findByName("Name")
assert(user != null)
val claims = Jwts.claims().setSubject("Name")
claims["roles"] = arrayListOf("ROLE_CUSTOMER")
val token = Jwts.builder()
.setSubject("Name")
.setClaims(claims)
.setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + 7*24*60*60*1000)) //exp in 7 days
.signWith(Keys.hmacShaKeyFor(key.toByteArray()))
.compact()
val headers = HttpHeaders()
headers.setContentType(MediaType.APPLICATION_JSON)
headers.set("Authorization", "Bearer $token")
val request = user!!.apply { address = "New address"; name = "Wrong Name" }
val response: ResponseEntity<String> = restTemplate.exchange(
"$baseUrl/my/profile",
HttpMethod.PUT,
HttpEntity<UserDetails>(request, headers),
String::class.java
)
Assertions.assertEquals(HttpStatus.BAD_REQUEST, response.statusCode)
}
} | 0 | Kotlin | 1 | 0 | ebf7f88811287d89c98ff2f9e076c7fcf2a294b3 | 7,068 | Spring-PublicTransportSystem | MIT License |
movies/remote/tmdb/src/commonMain/kotlin/movies/remote/tmdb/movie/MovieSearchService.kt | 4face-studi0 | 280,630,732 | false | null | package movies.remote.tmdb.movie
import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import movies.remote.tmdb.model.MoviePageResult
internal class MovieSearchService(
client: HttpClient
) {
private val client = client.config {
defaultRequest {
url.path("search", "movie")
parameter("append_to_response", "credits")
}
}
suspend fun search(query: String) = client.get<MoviePageResult> {
parameter("query", query )
}
}
| 24 | Kotlin | 1 | 3 | 572514b24063815fba93809a9169a470f89fd445 | 527 | CineScout | Apache License 2.0 |
src/main/kotlin/settings/LanguageItemValidator.kt | i-am-arunkumar | 393,908,591 | true | {"Kotlin": 100873} | package settings
import com.intellij.ui.CollectionListModel
/**
* Validation logic for UI TextFields in [LanguageItemPanel]
*/
class LanguageItemValidator(val listModel: CollectionListModel<SolutionLanguage>) : LanguageItemModel.Validator {
override fun validateName(name: String): String? {
return if (listModel.items.count { it.name == name } == 1) null else "Language Name already exists"
}
override fun validateExtension(extension: String): String? {
return if (extension.isNotEmpty()) null else "Extension should not empty"
}
override fun validateBuildCommand(buildCommand: String): String? {
val input = buildCommand.contains(AutoCpSettings.INPUT_PATH_KEY)
val output = buildCommand.contains(AutoCpSettings.OUTPUT_PATH_KEY)
// TODO: check if single quotes are useful so that we can just hardcode double quotes directly on the path
val inputDoubleQuotes = buildCommand.contains("\"" + AutoCpSettings.INPUT_PATH_KEY + "\"")
val inputSingleQuotes = buildCommand.contains("'" + AutoCpSettings.INPUT_PATH_KEY + "'")
val outputDoubleQuotes = buildCommand.contains("\"" + AutoCpSettings.OUTPUT_PATH_KEY + "\"")
val outputSingleQuotes = buildCommand.contains("'" + AutoCpSettings.OUTPUT_PATH_KEY + "'")
return if (!input)
"buildCommand: ${AutoCpSettings.INPUT_PATH_KEY} missing"
else if (!output)
"buildCommand: ${AutoCpSettings.OUTPUT_PATH_KEY} missing"
else if (!inputSingleQuotes && !inputDoubleQuotes)
"buildCommand: ${AutoCpSettings.INPUT_PATH_KEY} should be wrapped with single or double quotes"
else if (!outputSingleQuotes && !outputDoubleQuotes)
"buildCommand: ${AutoCpSettings.INPUT_PATH_KEY} should be wrapped with single or double quotes"
else
null
}
} | 0 | null | 0 | 0 | 4f72acfdb83c7917faa397818bd198b67fd3d6d8 | 1,866 | AutoCp | MIT License |
src/main/kotlin/ru/grishankov/network/ktor/Response.kt | AlexeyGrishankov | 530,579,923 | false | {"Kotlin": 4963} | package ru.grishankov.network.ktor
/**
* Network response
*/
sealed class Response<out Data : Any, out Failure : Any> {
/**
* Successful response
*
* @param data response data
* @param code response code
*/
data class Ok<Data : Any>(val data: Data, val code: Int) : Response<Data, Nothing>()
/**
* Wrong response / Wrong response API
*
* @param code response code
*/
data class ApiError<Data : Any, Failure : Any>(val data: Data, val code: Int) : Response<Nothing, Failure>()
/**
* Network response error
*
* @param error instance of throw
*/
data class NetworkError(val error: Throwable?) : Response<Nothing, Nothing>()
/**
* Unknown response error
*
* @param error instance of throw
*/
data class UnknownError(val error: Throwable?) : Response<Nothing, Nothing>()
} | 0 | Kotlin | 0 | 1 | b591464c726f750dc6443c8087ba4ea700b79f9b | 891 | ktor-client-network-adapter | MIT License |
app/src/main/java/com/example/primeiroprojetodevspace/ResultActivity.kt | al1neferreira | 727,922,077 | false | {"Kotlin": 5103} | package com.example.primeiroprojetodevspace
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val tvResult: TextView = findViewById(R.id.textView_result)
val tvClassificacao: TextView = findViewById(R.id.textView_classificacao)
val result = intent.getFloatExtra("EXTRA_RESULT", 0.1f)
tvResult.text = result.toString()
val classificacao =
if (result < 18.5f) {
"Magreza"
} else if (result in 18.5f..24.9f) {
"Peso normal"
} else if (result in 25f..29.9f) {
"Sobrepeso"
} else if (result in 30f..34.9f) {
"Obesidade Classe I"
} else if (result in 35f..39.9f) {
"Obesidade Classe II"
} else {
"Obesidade Classe III"
}
tvClassificacao.text = getString(R.string.message_classificacao, classificacao)
val btnReferencia: Button = findViewById(R.id.btn_referencia)
btnReferencia.setOnClickListener {
val intent2 = Intent(this, ReferenceTableActivity::class.java)
startActivity(intent2)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
finish()
return super.onOptionsItemSelected(item)
}
} | 0 | Kotlin | 0 | 0 | 72dad5b7b401397c88e9665504dba8d5a39bd95a | 1,762 | CalculadoraIMC | MIT License |
lib/src/commonMain/kotlin/xyz/mcxross/ksui/model/Faucet.kt | mcxross | 611,172,630 | false | {"Kotlin": 269246, "Shell": 3152} | /*
* Copyright 2024 McXross
*
* 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 xyz.mcxross.ksui.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable data class FixedAmountRequest(val recipient: String)
@Serializable
data class FaucetRequest(
@SerialName("FixedAmountRequest") val fixedAmountRequest: FixedAmountRequest
)
@Serializable
data class FaucetResponse(
val transferredGasObjects: List<TransferredGasObject>,
val error: String? = null,
)
| 0 | Kotlin | 2 | 5 | a6750e05596b280e833edede3be0a5bc44d34b5a | 1,026 | ksui | Apache License 2.0 |
indexer/src/test/kotlin/tech/edgx/prise/indexer/testutil/TestHelpers.kt | Edgxtech | 772,437,133 | false | {"Kotlin": 454378, "Java": 7742, "Dockerfile": 361, "Shell": 220} | package tech.edgx.prise.indexer.testutil
import tech.edgx.prise.indexer.domain.DexPriceHistoryView
import tech.edgx.prise.indexer.util.Helpers
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
class TestHelpers {
companion object {
var test_units_a: List<String> = listOf<String>(
"8e51398904a5d3fc129fbf4f1589701de23c7824d5c90fdb9490e15a434841524c4933",
"<KEY>",
"1d7f33bd23d85e1a25d87d86fac4f199c3197a2f7afeb662a0f34e1e776f726c646d6f62696c65746f6b656e",
"4368b0c0c36f8e346fb90f40b1f5e9a360b37035d1e37f32b2d7f558454747534c59",
"2441ab3351c3b80213a98f4e09ddcf7dabe4879c3c94cc4e7205cb6346495245",
"9e975c76508686eb2d57985dbaea7e3843767a31b4dcf4e99e5646834d41595a",
"0b55c812e3a740b8c7219a190753181b097426c14c558ad75d0b48f9474f4f474c45") // Not listed in registry
var test_units_b: List<String> = listOf<String>(
"ee0633e757fdd1423220f43688c74678abde1cead7ce265ba8a24fcd43424c50",
"af2e27f580f7f08e93190a81f72462f153026d06450924726645891b44524950",
"4623ab311b7d982d8d26fcbe1a9439ca56661aafcdcd8d8a0ef31fd6475245454e53")
var test_units_c: List<String> = listOf<String>(
"279c909f348e533da5808898f87f9a14bb2c3dfbbacccd631d927a3f534e454b",
"<KEY>")
var test_units_d: List<String> = listOf<String>(
"279c909f348e533da5808898f87f9a14bb2c3dfbbacccd631d927a3f534e454b")
var test_units_e = listOf("9a9693a9a37912a5097918f97918d15240c92ab729a0b7c4aa144d7753554e444145")
fun saveToJson(json: String, fileName: String) {
File(fileName).writeText(json)
}
fun OutputStream.writeDexPriceHistoriesCsv(vals: List<DexPriceHistoryView>?) {
val writer = bufferedWriter()
writer.write("unit,amount2,amount1,time,dex")
writer.newLine()
vals?.forEach {
writer.write("${it.policy_id+it.asset_name},${it.amount2},${it.amount1},${it.slot- Helpers.slotConversionOffset},${it.dex}")
writer.newLine()
}
writer.flush()
}
fun writeToCsv(vals: List<DexPriceHistoryView>?, filename: String) {
FileOutputStream(filename).apply { writeDexPriceHistoriesCsv(vals) }
}
}
} | 0 | Kotlin | 0 | 4 | 46083bb5b99315df65463aefe958401070c35e38 | 2,353 | prise | MIT License |
src/test/kotlin/com/atlassian/performance/tools/infrastructure/api/jvm/OracleJdkIT.kt | dagguh | 177,132,082 | true | {"Kotlin": 185147} | package com.atlassian.performance.tools.infrastructure.api.jvm
import org.junit.Test
class OracleJdkIT {
@Test
fun shouldSupportJstat() {
JstatSupport(OracleJDK()).shouldSupportJstat()
}
@Test
fun shouldGatherThreadDump() {
ThreadDumpTest(OracleJDK()).shouldGatherThreadDump()
}
} | 1 | Kotlin | 0 | 0 | 0dabffd2181ab005e04c2a1631cdb6abba56aaf3 | 324 | infrastructure | Apache License 2.0 |
app/src/main/java/com/cyberlogitec/freight9/ui/trademarket/MarketContainerFilterViewModel.kt | manosbatsis | 549,532,234 | false | null | package com.cyberlogitec.freight9.ui.trademarket
import android.content.Context
import com.cyberlogitec.freight9.common.BaseActivity
import com.cyberlogitec.freight9.common.BaseViewModel
import com.cyberlogitec.freight9.lib.model.Container
import com.cyberlogitec.freight9.lib.rx.Parameter
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import timber.log.Timber
class MarketContainerFilterViewModel(context: Context) : BaseViewModel(context), ContainerFilterInputs, ContainerFilterOutputs {
val inPuts: ContainerFilterInputs = this
private val refreshRdterm = PublishSubject.create<Parameter>()
private val refreshType = PublishSubject.create<Parameter>()
private val refreshSize = PublishSubject.create<Parameter>()
private val clickToApply = PublishSubject.create<List<Container>>()
val outPuts: ContainerFilterOutputs = this
private val gotoMarket = PublishSubject.create<Parameter>()
private val refreshContainerRdterm = PublishSubject.create<List<Container>>()
private val refreshContainerType = PublishSubject.create<List<Container>>()
private val refreshContainerSize = PublishSubject.create<List<Container>>()
init {
clickToApply.bindToLifeCycle()
.subscribe {
enviorment.containerRepository.storeContainersInDb(it)
gotoMarket.onNext(Parameter.CLICK)
}
refreshRdterm.flatMap{ enviorment.containerRepository.getContainersFromDb("rdterm") }
.filter { it.isNotEmpty() }
.bindToLifeCycle()
.subscribe (refreshContainerRdterm)
refreshType.flatMap{ enviorment.containerRepository.getContainersFromDb("type") }
.filter { it.isNotEmpty() }
.bindToLifeCycle()
.subscribe (refreshContainerType)
refreshSize.flatMap{ enviorment.containerRepository.getContainersFromDb("size") }
.filter { it.isNotEmpty() }
.bindToLifeCycle()
.subscribe (refreshContainerSize)
}
override fun onResume(view: BaseActivity<BaseViewModel>) {
super.onResume(view)
refreshRdterm.onNext(Parameter.CLICK)
refreshType.onNext(Parameter.CLICK)
refreshSize.onNext(Parameter.CLICK)
}
override fun clickToApply(list:List<Container>) {
Timber.v("clickCarrierFilterApply")
return clickToApply.onNext(list)
}
override fun gotoMarket(): Observable<Parameter> {
Timber.v("gotoMarket")
return gotoMarket
}
override fun refreshContainerRdterm(): Observable<List<Container>> {
Timber.v("refreshRdterm")
return refreshContainerRdterm
}
override fun refreshContainerType(): Observable<List<Container>> {
Timber.v("refreshContainerType")
return refreshContainerType
}
override fun refreshContainerSize(): Observable<List<Container>> {
Timber.v("refreshContainerSize")
return refreshContainerSize
}
}
interface ContainerFilterInputs {
fun clickToApply(list: List<Container>)
}
interface ContainerFilterOutputs {
fun gotoMarket() : Observable<Parameter>
fun refreshContainerRdterm() : Observable<List<Container>>
fun refreshContainerType() : Observable<List<Container>>
fun refreshContainerSize() : Observable<List<Container>>
}
| 0 | null | 0 | 0 | ca9c94c2b83f5808edca00a4abc99f0b8b836817 | 3,405 | fremvp | Apache License 2.0 |
app/src/main/java/com/mjr/app/alleasy/fragment/physics/kinematics/vum/VUMAcceleration2.kt | gabrielmjr | 508,812,095 | false | {"Java": 62070, "Kotlin": 43799} | package com.mjr.app.alleasy.fragment.physics.kinematics.vum
import com.mjr.app.alleasy.activity.AbstractPhysicalCalculation
import com.mjr.app.alleasy.model.Data
class VUMAcceleration2 : AbstractPhysicalCalculation() {
override fun setTemplateAttributes() {
datas.apply {
add(Data("∆v = ", "m/s"))
add(Data("ti = ", "s"))
add(Data("t = ", "s"))
}
}
override fun onCalculateClickListener() {}
} | 1 | null | 1 | 1 | 6bca4475b1cb3af00e605677c4afd56e0862c3cc | 460 | AllEasy | Apache License 2.0 |
core/src/main/kotlin/voodoo/provider/JenkinsProvider.kt | elytra | 119,208,408 | false | {"Markdown": 7, "Git Config": 1, "Gradle Kotlin DSL": 8, "INI": 4, "Shell": 15, "Text": 2, "Ignore List": 2, "Batchfile": 2, "Groovy": 1, "Java": 2, "Kotlin": 262, "Java Properties": 45, "YAML": 1, "JSON": 378, "XML": 3} | package voodoo.provider
import com.eyeem.watchadoin.Stopwatch
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import voodoo.core.GeneratedConstants.VERSION
import voodoo.data.EntryReportData
import voodoo.data.Quadruple
import voodoo.data.flat.Entry
import voodoo.data.lock.LockEntry
import voodoo.memoize
import voodoo.util.download
import voodoo.util.jenkins.Artifact
import voodoo.util.jenkins.BuildWithDetails
import voodoo.util.jenkins.JenkinsServer
import voodoo.util.jenkins.Job
import java.io.File
import java.time.Instant
import java.util.*
/**
* Created by nikky on 30/12/17.
* @author Nikky
*/
object JenkinsProvider : ProviderBase("Jenkins Provider") {
const val useragent = "voodoo/$VERSION (https://github.com/DaemonicLabs/Voodoo)"
override suspend fun resolve(
entry: Entry,
mcVersion: String,
addEntry: SendChannel<Pair<Entry, String>>
): LockEntry {
entry as Entry.Jenkins
require(entry.job.isNotBlank()) { "entry: '${entry.id}' does not have the jenkins job set" }
// if (entry.job.isBlank()) {
// entry.job = entry.id
// }
val job = job(entry.job, entry.jenkinsUrl)
val buildNumber = job.lastSuccessfulBuild?.number ?: throw IllegalStateException("buildnumber not set")
return entry.lock { commonComponent ->
LockEntry.Jenkins(
common = commonComponent,
jenkinsUrl = entry.jenkinsUrl,
job = entry.job,
buildNumber = buildNumber,
fileNameRegex = entry.fileNameRegex
)
}
}
suspend fun getDownloadUrl(
entry: LockEntry.Jenkins
): Pair<String, String> {
val build = build(entry.job, entry.jenkinsUrl, entry.buildNumber)
val artifact = artifact(entry.job, entry.jenkinsUrl, entry.buildNumber, entry.fileNameRegex)
val url = build.url + "artifact/" + artifact.relativePath
return url to artifact.fileName
}
override suspend fun download(
stopwatch: Stopwatch,
entry: LockEntry,
targetFolder: File,
cacheDir: File
): Pair<String?, File>? = stopwatch {
entry as LockEntry.Jenkins
require(entry.job.isNotBlank()) { "entry: '${entry.id}' does not have the jenkins job set" }
// if (entry.job.isBlank()) {
// entry.job = entry.id
// }
val (url, fileName) = getDownloadUrl(entry)
val targetFile = targetFolder.resolve(entry.fileName ?: fileName)
targetFile.download(url, cacheDir.resolve("JENKINS").resolve(entry.job).resolve(entry.buildNumber.toString()))
return@stopwatch url to targetFile
}
override suspend fun generateName(entry: LockEntry): String {
entry as LockEntry.Jenkins
return "${entry.job} ${entry.buildNumber}"
}
override suspend fun getAuthors(entry: LockEntry): List<String> {
entry as LockEntry.Jenkins
return listOf(entry.job.substringBeforeLast('/').substringBeforeLast('/').substringAfterLast('/'))
}
override suspend fun getProjectPage(entry: LockEntry): String {
entry as LockEntry.Jenkins
val server = server(entry.jenkinsUrl)
return server.getUrl(entry.job)
}
override suspend fun getVersion(entry: LockEntry): String {
entry as LockEntry.Jenkins
val artifact = artifact(entry.job, entry.jenkinsUrl, entry.buildNumber, entry.fileNameRegex)
return artifact.fileName
}
override suspend fun getReleaseDate(entry: LockEntry): Instant? {
entry as LockEntry.Jenkins
val build = build(entry.job, entry.jenkinsUrl, entry.buildNumber)
return Instant.ofEpochSecond(build.timestamp)
}
private val artifactCache: MutableMap<Quadruple<String, String, Int, String>, Artifact> =
Collections.synchronizedMap(hashMapOf())
suspend fun artifact(jobName: String, url: String, buildNumber: Int, fileNameRegex: String): Artifact {
val a = Quadruple(jobName, url, buildNumber, fileNameRegex)
return artifactCache.getOrPut(a) { artifactCall(jobName, url, buildNumber, fileNameRegex) }
}
private suspend fun artifactCall(jobName: String, url: String, buildNumber: Int, fileNameRegex: String): Artifact {
val build = build(jobName, url, buildNumber)
val re = Regex(fileNameRegex)
return build.artifacts.find {
re.matches(it.fileName)
} ?: run {
logger.error("artifacts: ${build.artifacts.map { it.fileName }}")
throw IllegalStateException("no artifact matching $re found")
}
}
private val buildCache: MutableMap<Triple<String, String, Int>, BuildWithDetails> =
Collections.synchronizedMap(hashMapOf())
suspend fun build(jobName: String, url: String, buildNumber: Int): BuildWithDetails {
val a = Triple(jobName, url, buildNumber)
return buildCache.getOrPut(a) { buildCall(jobName, url, buildNumber) }
}
private suspend fun buildCall(jobName: String, url: String, buildNumber: Int): BuildWithDetails {
logger.info("get build $buildNumber")
delay(20)
return job(jobName, url).getBuildByNumber(buildNumber, useragent)!!
}
private val jobCache: MutableMap<Pair<String, String>, Job> = Collections.synchronizedMap(hashMapOf())
suspend fun job(jobName: String, url: String): Job {
val a = jobName to url
return jobCache.getOrPut(a) { jobCall(jobName, url) }
}
private suspend fun jobCall(jobName: String, url: String): Job {
val server = server(url)
logger.info("get jenkins job $jobName")
return server.getJob(jobName, useragent) ?: throw Exception("no such job: '$jobName' on $url")
}
val server = ::serverCall.memoize()
private fun serverCall(url: String): JenkinsServer {
logger.info("get jenkins server $url")
return JenkinsServer(url)
}
override fun reportData(entry: LockEntry): MutableMap<EntryReportData, String> {
entry as LockEntry.Jenkins
val (url, fileName) = runBlocking {
getDownloadUrl(entry)
}
return super.reportData(entry).also { data ->
// data["BaseUrl"] = entry.jenkinsUrl // do we need this ?
data[EntryReportData.FILE_NAME] = entry.fileName ?: fileName
data[EntryReportData.DIRECT_URL] = url
data[EntryReportData.JENKINS_JOB] = entry.job
data[EntryReportData.JENKINS_BUILD] = "${entry.buildNumber}"
}
}
}
| 1 | null | 1 | 1 | 5a4e0217b1f8d2af193e8c04d1bee0258fd1cc5a | 6,649 | Voodoo | MIT License |
AudioSample/app/src/main/java/com/hyy/readeraudiosample/TestDataFactory.kt | Youngfellows | 478,843,914 | false | {"Java": 1395696, "Kotlin": 131102, "C++": 26974, "Makefile": 4041} | package com.hyy.readeraudiosample
import com.hyy.readeraudiosample.model.ChapterAudioItem
/**
* 测试数据工厂
*/
object TestDataFactory {
fun mediaItem1(): ChapterAudioItem = ChapterAudioItem(
"Chapter One",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/01_-_Intro_-_The_Way_Of_Waking_Up_feat_Alan_Watts.mp3",
"18888",
90,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun mediaItem2(): ChapterAudioItem = ChapterAudioItem(
"Chapter Two",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/02_-_Geisha.mp3",
"18889",
267,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun mediaItem3(): ChapterAudioItem = ChapterAudioItem(
"Chapter Three",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/03_-_Voyage_I_-_Waterfall.mp3",
"18890",
264,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun mediaItem4(): ChapterAudioItem = ChapterAudioItem(
"Chapter Four",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/04_-_The_Music_In_You.mp3",
"18891",
223,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun mediaItem5(): ChapterAudioItem = ChapterAudioItem(
"Chapter Five",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/05_-_The_Calm_Before_The_Storm.mp3",
"18892",
229,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun mediaItem6(): ChapterAudioItem = ChapterAudioItem(
"Chapter Six",
"Book Hyy",
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/06_-_No_Pain_No_Gain.mp3",
"18893",
304,
"https://storage.googleapis.com/automotive-media/album_art_2.jpg"
)
fun novelModel(): ChapterAudioItem = ChapterAudioItem(
"Chapter One",
"Test",
"http://tts.sg.ufileos.com/audio/dev/33/54733/11670333/1/1607933874.mp3",
"1001",
429,
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/art.jpg"
)
fun novelMode2(): ChapterAudioItem = ChapterAudioItem(
"Chapter One",
"Test",
"https://storage.googleapis.com/automotive-media/Tell_The_Angels.mp3",
"1001",
429,
"https://storage.googleapis.com/uamp/The_Kyoto_Connection_-_Wake_Up/art.jpg"
)
} | 1 | null | 1 | 1 | d156363a1c591c7ce47f07e3e3ad311a2eced45b | 2,673 | MediaBrowserServicePlayer | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/SquarePlus.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.SquarePlus: ImageVector
get() {
if (_squarePlus != null) {
return _squarePlus!!
}
_squarePlus = Builder(name = "SquarePlus", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.0f, 11.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
lineTo(7.0f, 13.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(4.0f)
lineTo(11.0f, 7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(24.0f, 3.0f)
lineTo(24.0f, 24.0f)
lineTo(0.0f, 24.0f)
lineTo(0.0f, 3.0f)
curveTo(0.0f, 1.346f, 1.346f, 0.0f, 3.0f, 0.0f)
lineTo(21.0f, 0.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
close()
moveTo(22.0f, 3.0f)
curveToRelative(0.0f, -0.552f, -0.449f, -1.0f, -1.0f, -1.0f)
lineTo(3.0f, 2.0f)
curveToRelative(-0.551f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
lineTo(2.0f, 22.0f)
lineTo(22.0f, 22.0f)
lineTo(22.0f, 3.0f)
close()
}
}
.build()
return _squarePlus!!
}
private var _squarePlus: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,519 | icons | MIT License |
src/main/java/com/rokucraft/rokubot/command/commands/ReloadCommand.kt | Rokucraft | 320,306,024 | false | null | package com.rokucraft.rokubot.command.commands
import com.rokucraft.rokubot.RokuBot
import com.rokucraft.rokubot.command.AbstractCommand
import com.rokucraft.rokubot.util.ColorConstants.GREEN
import com.rokucraft.rokubot.util.EmbedUtil.createErrorEmbed
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.entities.MessageEmbed
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions
import net.dv8tion.jda.api.interactions.commands.build.Commands
import org.slf4j.LoggerFactory
import org.spongepowered.configurate.ConfigurateException
class ReloadCommand(private val bot: RokuBot) : AbstractCommand() {
override val data = Commands.slash("reload", "Reload the bot configuration")
.setDefaultPermissions(DefaultMemberPermissions.DISABLED)
override fun execute(event: SlashCommandInteractionEvent) {
event.deferReply(true).queue()
var response: MessageEmbed
try {
bot.reloadSettings()
response = EmbedBuilder()
.setColor(GREEN)
.setTitle("Successfully reloaded!")
.build()
} catch (e: ConfigurateException) {
response = createErrorEmbed("Something went wrong while trying to reload the bot.")
LOGGER.error("Something went wrong while trying to reload the bot.", e)
}
event.hook
.setEphemeral(true)
.sendMessageEmbeds(response)
.queue()
}
companion object {
private val LOGGER = LoggerFactory.getLogger(ReloadCommand::class.java)
}
}
| 0 | Kotlin | 2 | 5 | bfa48be75357d36e2fe4305b305b3ceaf42d1b09 | 1,669 | RokuBot | MIT License |
vk-api-core/src/main/kotlin/name/anton3/vkapi/executors/ThrottledMethodExecutor.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | package name.anton3.vkapi.executors
import com.fasterxml.jackson.databind.ObjectMapper
import name.anton3.executors.core.DynamicRequest
import name.anton3.executors.instances.ThrottledExecutor
import name.anton3.executors.util.batchAwareRequestStorage
import name.anton3.vkapi.core.MethodExecutor
import name.anton3.vkapi.transport.TransportClient
import name.anton3.vkapi.method.VkMethod
import name.anton3.vkapi.vktypes.VkResponse
import java.io.Closeable
import java.time.Duration
import kotlin.coroutines.CoroutineContext
class ThrottledMethodExecutor(
private val base: MethodExecutor,
coroutineContext: CoroutineContext,
rateLimit: Int,
ratePeriod: Duration = Duration.ofSeconds(1L)
) : MethodExecutor, Closeable {
private val throttler: ThrottledExecutor<VkMethod<*, *>, VkResponse<*>> =
ThrottledExecutor(base, coroutineContext, rateLimit, ratePeriod, batchAwareRequestStorage())
override suspend fun execute(dynamicRequest: DynamicRequest<VkMethod<*, *>>): VkResponse<*> {
return throttler.execute(dynamicRequest)
}
override val transportClient: TransportClient get() = base.transportClient
override val objectMapper: ObjectMapper get() = base.objectMapper
override fun close() {
throttler.close()
}
}
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 1,285 | kotlin-vk-api | MIT License |
browser-kotlin/src/jsMain/kotlin/web/gpu/GPUShaderModuleDescriptor.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6878116} | // Automatically generated - do not modify!
package web.gpu
sealed external interface GPUShaderModuleDescriptor :
GPUObjectDescriptorBase {
var code: String
var sourceMap: Any?
}
| 0 | Kotlin | 7 | 29 | 5452a44a583f43542295dae6c7d128a52cd0d84c | 193 | types-kotlin | Apache License 2.0 |
android/app/src/main/java/br/com/oxente/transp/App.kt | DavidCabral | 328,985,367 | false | {"Pascal": 327519, "Kotlin": 91332} | package br.com.oxente.transp
import android.app.Application
import com.blankj.utilcode.util.Utils
import com.google.gson.GsonBuilder
class App : Application() {
companion object {
private var instance: App? = null
fun getInstance(): App {
return instance!!
}
val gson = GsonBuilder()
/*.registerTypeAdapter(Date::class.java, JsonDeserializer<Date> { json, _, _ -> Date(json.asJsonPrimitive.asLong) })
.registerTypeAdapter(Date::class.java, JsonSerializer<Date> { src, _, _ -> if (src == null) null else JsonPrimitive(src.time) })*/
.setDateFormat("dd-MM-yyyy HH:mm:ss")
.create()!!
}
init {
instance = this
}
override fun onCreate() {
super.onCreate()
Utils.init(this)
}
}
| 0 | Pascal | 2 | 2 | 4e298ec94e4c02455f5b1b9e38aa36a0869b01c0 | 839 | TransporteApp | MIT License |
laws/src/commonMain/kotlin/com/github/fsbarata/functional/control/MonadLaws.kt | fsbarata | 277,280,202 | false | null | package com.github.fsbarata.functional.control
import com.github.fsbarata.functional.Context
import kotlin.test.Test
interface MonadLaws<M>: ApplicativeLaws<M> {
val monadScope: Monad.Scope<M>
@Suppress("UNCHECKED_CAST")
private fun <T> eachPossibilityMonad(block: (Monad<M, Int>) -> T) =
eachPossibility { block(it as Monad<M, Int>) }
override val applicativeScope: Applicative.Scope<M> get() = monadScope
@Test
fun `bind left identity`() {
val a = 7
val k = { x: Int -> monadScope.just(x * 3) }
val r1 = k(a)
val r2 = monadScope.bind(monadScope.just(a), k)
assertEqualF(r1, r2)
}
@Test
fun `bind right identity`() {
eachPossibilityMonad { m ->
val b = m.bind { monadScope.just(it) }
assertEqualF(m, b)
}
}
@Test
fun `bind associativity`() {
eachPossibilityMonad { m ->
val k = { a: Int -> monadScope.just(a + 2) }
val h = { a: Int -> monadScope.just(a * 2) }
val r1 = m.bind { x -> monadScope.bind(k(x), h) }
val r2 = m.bind(k).bind(h)
assertEqualF(r1, r2)
}
}
@Test
fun `ap is correct`() {
eachPossibilityMonad { m ->
val mf = monadScope.just { a: Int -> a * 2 }
val r1 = m.ap(mf)
val r2 = monadScope.bind(mf) { x1 -> m.bind { x2 -> monadScope.just(x1(x2)) } }
assertEqualF(r1, r2)
}
}
@Test
fun `lift2 is correct`() {
eachPossibilityMonad { m1 ->
eachPossibilityMonad { m2 ->
val f = { a: Int, b: Int -> (a + 2) * 3 + b }
val r1 = m1.lift2(m2, f)
val r2 = m1.bind { x1 -> m2.bind { x2 -> monadScope.just(f(x1, x2)) } }
assertEqualF(r1, r2)
}
}
}
@Test
fun `map is correct`() {
eachPossibilityMonad { m ->
assertEqualF(
m.map { it * 3 },
m.bind { monadScope.just(it * 3) })
}
}
private fun Monad.Scope<M>.multiply(
x: Context<M, Int>,
y: Int,
): Context<M, Int> =
if (y == 0) just(0)
else bind(x) { just(y * it) }
@Test
fun `multiply accepts monad`() {
assertEqualF(monadScope.just(15), monadScope.multiply(monadScope.just(5), 3))
assertEqualF(monadScope.just(0), monadScope.multiply(monadScope.just(5), 0))
eachPossibilityMonad { assertEqualF(monadScope.just(0), monadScope.multiply(it, 0)) }
}
} | 0 | Kotlin | 1 | 0 | c9a91da54bf04b7b42357b3137961363cffcc61f | 2,151 | kotlin-functional | Apache License 2.0 |
kmem/src/commonMain/kotlin/com/soywiz/kmem/ArrayAdd.kt | korlibs | 110,341,365 | false | null | package com.soywiz.kmem
fun arrayadd(array: ByteArray, value: Byte, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = (array[n] + value).toByte() }
fun arrayadd(array: ShortArray, value: Short, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = (array[n] + value).toShort() }
fun arrayadd(array: IntArray, value: Int, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: LongArray, value: Long, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: FloatArray, value: Float, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: DoubleArray, value: Double, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: Int8Buffer, value: Byte, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = (array[n] + value).toByte() }
fun arrayadd(array: Int16Buffer, value: Short, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = (array[n] + value).toShort() }
fun arrayadd(array: Int32Buffer, value: Int, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: Float32Buffer, value: Float, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
fun arrayadd(array: Float64Buffer, value: Double, start: Int = 0, end: Int = array.size): Unit { for (n in start until end) array[n] = array[n] + value }
| 3 | Kotlin | 5 | 11 | 13783c74ca82d2eba8b328b51aa4f158f642aeb3 | 1,722 | kmem | MIT License |
src/client/kotlin/org/teamvoided/grappled/util/GapRenderLayers.kt | theendercore | 814,108,674 | false | {"Kotlin": 26641, "Java": 544} | package org.teamvoided.grappled.util
import com.mojang.blaze3d.vertex.VertexFormat
import com.mojang.blaze3d.vertex.VertexFormats
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.RenderLayer.MultiPhaseParameters
import net.minecraft.client.render.RenderPhase
import net.minecraft.util.Identifier
import net.minecraft.util.Util
import java.util.function.Function
object GapRenderLayers {
private val GRAPPLING_HOOK_LAYER: Function<Identifier, RenderLayer.MultiPhase> =
Util.memoize { texture ->
RenderLayer.of(
"grappling_hook_layer",
VertexFormats.POSITION_COLOR_TEXTURE_OVERLAY_LIGHT_NORMAL,
VertexFormat.DrawMode.QUADS,
1536,
true,
false,
MultiPhaseParameters.builder()
.shader(RenderPhase.BEACON_BEAM_SHADER) //make custom shader for this also copy `RenderPhase.ENTITY_CUTOUT_NONNULL_SHADER`
.texture(RenderPhase.Texture(texture, false, false))
.transparency(RenderPhase.NO_TRANSPARENCY)
.cull(RenderPhase.DISABLE_CULLING)
.lightmap(RenderPhase.ENABLE_LIGHTMAP)
.overlay(RenderPhase.ENABLE_OVERLAY_COLOR)
.build(true)
)
}
fun getGrapplingHookLayer(texture: Identifier) = GRAPPLING_HOOK_LAYER.apply(texture)
}
| 0 | Kotlin | 0 | 0 | e271f7c991c03411a27b0557d4056b200232112f | 1,448 | Grappled | MIT License |
OnlinePK-Android/app/src/main/java/com/netease/yunxin/nertc/demo/feedback/FeedbackActivity.kt | Dongshanxu | 436,919,018 | true | {"Objective-C": 1460921, "Kotlin": 612297, "Java": 270376, "Swift": 124861, "C": 7263, "Python": 2874, "Ruby": 1065} | /*
* Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file
*/
package com.netease.yunxin.nertc.demo.feedback
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.blankj.utilcode.util.ToastUtils
import com.netease.yunxin.login.sdk.AuthorManager
import com.netease.yunxin.nertc.demo.R
import com.netease.yunxin.nertc.demo.basic.BaseActivity
import com.netease.yunxin.nertc.demo.basic.StatusBarConfig
import com.netease.yunxin.nertc.demo.feedback.expand.QuestionItem
import com.netease.yunxin.nertc.demo.feedback.network.FeedbackServiceImpl
import io.reactivex.observers.ResourceSingleObserver
import java.util.*
class FeedbackActivity : BaseActivity() {
private val userModel = AuthorManager.getUserInfo()
private val questionTypeList = ArrayList<QuestionItem>()
private var tvDemoName: TextView? = null
private var tvQuestionType: TextView? = null
private var etQuestionDesc: EditText? = null
private var btnCommit: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed_back)
paddingStatusBarHeight(findViewById(R.id.cl_root))
initViews()
}
private fun initViews() {
val close = findViewById<View>(R.id.iv_close)
close.setOnClickListener { v: View? -> finish() }
tvQuestionType = findViewById(R.id.tv_question_type)
tvQuestionType?.setOnClickListener(View.OnClickListener { v: View? ->
QuestionTypeActivity.Companion.launchForResult(
this@FeedbackActivity,
CODE_REQUEST_FOR_QUESTION,
questionTypeList
)
})
tvDemoName = findViewById(R.id.tv_demo_name)
tvDemoName?.setOnClickListener(View.OnClickListener { v: View? ->
DemoNameActivity.launchForResult(
this@FeedbackActivity,
CODE_REQUEST_FOR_NAME,
tvDemoName?.text.toString()
)
})
etQuestionDesc = findViewById(R.id.et_question_desc)
etQuestionDesc?.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
checkAndUpdateCommitBtn()
}
override fun afterTextChanged(s: Editable) {}
})
btnCommit = findViewById(R.id.tv_commit)
btnCommit?.setOnClickListener(View.OnClickListener { v: View? ->
FeedbackServiceImpl.demoSuggest(
userModel!!, tvDemoName?.text.toString(),
etQuestionDesc?.text.toString(),
*formatItemsForIntArray(questionTypeList)
)
.subscribe(object : ResourceSingleObserver<Boolean?>() {
override fun onSuccess(aBoolean: Boolean) {
if (aBoolean) {
ToastUtils.showShort(getString(R.string.app_feedback_success))
finish()
} else {
ToastUtils.showShort(getString(R.string.app_feedback_failed))
}
}
override fun onError(e: Throwable) {
ToastUtils.showShort(getString(R.string.app_feedback_failed))
}
})
})
}
override fun provideStatusBarConfig(): StatusBarConfig? {
return StatusBarConfig.Builder()
.statusBarDarkFont(false)
.build()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CODE_REQUEST_FOR_QUESTION && !onQuestionType(resultCode, data)) {
return
}
if (requestCode == CODE_REQUEST_FOR_NAME && !onDemoName(resultCode, data)) {
return
}
checkAndUpdateCommitBtn()
}
/**
* 接收问题类型
*
* @return true 成功处理,false 处理失败
*/
private fun onQuestionType(resultCode: Int, data: Intent?): Boolean {
if (resultCode != RESULT_OK || data == null) {
return false
}
questionTypeList.clear()
val result =
data.getSerializableExtra(QuestionTypeActivity.Companion.KEY_PARAM_QUESTION_TYPE_LIST) as ArrayList<QuestionItem>?
if (result == null || result.isEmpty()) {
tvQuestionType!!.text = ""
checkAndUpdateCommitBtn()
return false
}
questionTypeList.addAll(result)
tvQuestionType!!.text = formatItemsForString(questionTypeList)
return true
}
/**
* 接收demo 名称
*
* @return true 成功处理,false 处理失败
*/
private fun onDemoName(resultCode: Int, data: Intent?): Boolean {
if (resultCode != RESULT_OK || data == null) {
return false
}
val demoName = data.getStringExtra(DemoNameActivity.Companion.KEY_PARAM_DEMO_NAME)
if (TextUtils.isEmpty(demoName)) {
tvDemoName!!.text = ""
checkAndUpdateCommitBtn()
return false
}
tvDemoName!!.text = demoName
return true
}
private fun checkAndUpdateCommitBtn() {
val disable = (TextUtils.isEmpty(tvQuestionType!!.text)
|| TextUtils.isEmpty(etQuestionDesc!!.text.toString())
|| TextUtils.isEmpty(tvDemoName!!.text.toString()))
btnCommit!!.isEnabled = !disable
}
private fun formatItemsForString(items: List<QuestionItem>): String {
val builder = StringBuilder()
for (item in items) {
builder.append(item.name)
builder.append(",")
}
val questionType = builder.toString()
return questionType.substring(0, questionType.length - 1)
}
private fun formatItemsForIntArray(items: List<QuestionItem>): IntArray {
val typeArray = IntArray(items.size)
var i = 0
for (item in items) {
typeArray[i++] = item.id
}
return typeArray
}
companion object {
private const val CODE_REQUEST_FOR_QUESTION = 1000
private const val CODE_REQUEST_FOR_NAME = 1001
}
} | 0 | Objective-C | 0 | 0 | e334a9a3c07cd03be26a78b08ca78b38fc097582 | 6,645 | OnlinePK | MIT License |
app/src/main/java/com/example/bookdiscover/library/LibraryFragment.kt | Tyler-CY | 509,632,541 | false | null | package com.example.bookdiscover.library
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.coroutineScope
import com.example.bookdiscover.database.AppDatabase
import com.example.bookdiscover.databinding.FragmentLibraryBinding
import kotlinx.coroutines.launch
/**
* The main fragment used in LibraryActivity
*/
class LibraryFragment : Fragment() {
private val sharedViewModel: LibraryViewModel by activityViewModels {
LibraryViewModelFactory(
AppDatabase.getDatabase(activity!!).libraryDao()
)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Data-binding with XML
val binding = FragmentLibraryBinding.inflate(inflater)
binding.apply {
// ResultViewModel determines the lifecycle of the binding.
lifecycleOwner = viewLifecycleOwner
viewModel = sharedViewModel
}
/**
* Use a coroutineScope to get the Flow data from the DAO of the sharedViewModel.
* TODO: Might not be a good idea to use a new LibraryAdapter every time "bookmarks" updates. Try
* TODO: to mimic the implementation used in GenreFragment.
*/
lifecycle.coroutineScope.launch {
sharedViewModel.bookmarks().collect {
if (it.isNotEmpty()){
// Access the RecyclerView.
val recyclerView = binding.libraryRecyclerView
binding.libraryRecyclerView.isVisible = true
recyclerView.adapter = LibraryAdapter([email protected]!!, it)
}
else {
binding.libraryRecyclerView.isVisible = false
val textView = TextView(activity!!)
textView.text = "No records."
textView.textSize = 24F
textView.id = View.generateViewId()
binding.libraryLayout.addView(textView, 0)
// Sets the textView to the middle by using ConstraintSet
val constraintSet = ConstraintSet()
constraintSet.clone(binding.libraryLayout)
constraintSet.connect(textView.id, ConstraintSet.TOP, binding.libraryLayout.id, ConstraintSet.TOP)
constraintSet.connect(textView.id, ConstraintSet.START, binding.libraryLayout.id, ConstraintSet.START)
constraintSet.connect(textView.id, ConstraintSet.END, binding.libraryLayout.id, ConstraintSet.END)
constraintSet.connect(textView.id, ConstraintSet.BOTTOM, binding.libraryLayout.id, ConstraintSet.BOTTOM)
constraintSet.applyTo(binding.libraryLayout)
}
}
}
// Inflate the layout for this fragment
return binding.root
}
} | 0 | Kotlin | 0 | 0 | 7f6febfe9c7aefc9aa6bfeee52a0607df5504175 | 3,216 | Book-Discover | MIT License |
app/src/main/java/com/codemate/koffeemate/ui/userselector/UserItemAnimator.kt | CodemateLtd | 76,640,942 | false | null | /*
* Copyright 2017 Codemate Ltd
*
* 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.codemate.koffeemate.ui.userselector
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.RecyclerView
import android.view.animation.DecelerateInterpolator
import com.codemate.koffeemate.ui.userselector.adapter.UserSelectorAdapter
import kotlinx.android.synthetic.main.recycler_item_user.view.*
class UserItemAnimator : DefaultItemAnimator() {
private val interpolator = DecelerateInterpolator(3f)
override fun animateAdd(viewHolder: RecyclerView.ViewHolder): Boolean {
if (viewHolder is UserSelectorAdapter.ViewHolder) {
viewHolder.itemView.userName.alpha = 0f
viewHolder.itemView.profileImage.alpha = 0.5f
viewHolder.itemView.profileImage.scaleX = 0f
viewHolder.itemView.profileImage.scaleY = 0f
viewHolder.itemView.profileImage.rotation = 180f
viewHolder.itemView.profileImage.animate()
.setInterpolator(interpolator)
.setDuration(500)
.setStartDelay((250 + viewHolder.layoutPosition * 75).toLong())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
viewHolder.itemView.userName.animate()
.alpha(1f)
.withEndAction { [email protected](viewHolder) }
.start()
}
})
.alpha(1f)
.scaleX(1f)
.scaleY(1f)
.rotation(0f)
.start()
}
return true
}
} | 9 | Kotlin | 6 | 36 | e7e30b0f93126e52f2dabddb5254de39c7ac0303 | 2,437 | Koffeemate | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ecs/PlacementConstraintPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.ecs
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.ecs.CfnService
@Generated
public fun buildPlacementConstraintProperty(initializer: @AwsCdkDsl
CfnService.PlacementConstraintProperty.Builder.() -> Unit):
CfnService.PlacementConstraintProperty =
CfnService.PlacementConstraintProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | b22e397ff37c5fce365a5430790e5d83f0dd5a64 | 469 | aws-cdk-kt | Apache License 2.0 |
src/main/kotlin/me/luna/trollhack/event/events/combat/CrystalSpawnEvent.kt | NotMonika | 509,752,527 | false | {"Kotlin": 2035807, "Java": 168054, "GLSL": 91098} | package me.luna.trollhack.event.events.combat
import me.luna.trollhack.event.Event
import me.luna.trollhack.event.EventBus
import me.luna.trollhack.event.EventPosting
import me.luna.trollhack.util.combat.CrystalDamage
class CrystalSpawnEvent(
val entityID: Int,
val crystalDamage: CrystalDamage
) : Event, EventPosting by Companion {
companion object : EventBus()
} | 0 | Kotlin | 0 | 0 | 543ac418b69e0c7359cde487e828b4c3d2260241 | 379 | MorisaHack | Do What The F*ck You Want To Public License |
src/main/kotlin/com/appifyhub/monolith/domain/mapper/UserOpsMapper.kt | appifyhub | 323,403,014 | false | null | package com.appifyhub.monolith.domain.mapper
import com.appifyhub.monolith.domain.common.applySettable
import com.appifyhub.monolith.domain.user.Organization
import com.appifyhub.monolith.domain.user.User
import com.appifyhub.monolith.domain.user.UserId
import com.appifyhub.monolith.domain.user.ops.OrganizationUpdater
import com.appifyhub.monolith.domain.user.ops.UserCreator
import com.appifyhub.monolith.domain.user.ops.UserUpdater
import com.appifyhub.monolith.util.TimeProvider
import org.springframework.security.crypto.password.PasswordEncoder
fun UserUpdater.applyTo(
user: User,
passwordEncoder: PasswordEncoder,
timeProvider: TimeProvider,
): User = user
// non-null values
.applySettable(rawSignature) { copy(signature = passwordEncoder.encode(it)) }
.applySettable(type) { copy(type = it) }
.applySettable(authority) { copy(authority = it) }
.applySettable(contactType) { copy(contactType = it) }
.applySettable(allowsSpam) { copy(allowsSpam = it) }
// possible null values
.applySettable(name) { copy(name = it) }
.applySettable(contact) { copy(contact = it) }
.applySettable(verificationToken) { copy(verificationToken = it) }
.applySettable(birthday) { copy(birthday = it) }
.applySettable(company) { copy(company = it?.applyTo(company)) }
.copy(updatedAt = timeProvider.currentDate)
fun OrganizationUpdater.applyTo(organization: Organization?): Organization? =
organization
?.applySettable(name) { copy(name = it) }
?.applySettable(street) { copy(street = it) }
?.applySettable(postcode) { copy(postcode = it) }
?.applySettable(city) { copy(city = it) }
?.applySettable(countryCode) { copy(countryCode = it) }
fun UserCreator.toUser(
userId: String,
passwordEncoder: PasswordEncoder,
timeProvider: TimeProvider,
): User = User(
id = UserId(userId = userId, projectId = projectId),
signature = passwordEncoder.encode(rawSecret),
name = name,
type = type,
authority = authority,
allowsSpam = allowsSpam,
contact = contact,
contactType = contactType,
verificationToken = null,
birthday = birthday,
createdAt = timeProvider.currentDate,
updatedAt = timeProvider.currentDate,
company = company,
)
| 26 | Kotlin | 0 | 0 | 6c35d77cfe6e8d6ed29257935372aa5c35c63785 | 2,199 | monolith | MIT License |
app/src/main/java/com/juvetic/calcio/ui/teamdetail/TeamDetailActivity.kt | fikrirazzaq | 175,538,261 | false | null | package com.juvetic.calcio.ui.teamdetail
import android.os.Bundle
import com.juvetic.calcio.R
import com.juvetic.calcio.base.BaseActivity
class TeamDetailActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_team_detail)
title = ""
val teamDetailFragment = TeamDetailFragment
.newInstance(intent.getStringExtra(TeamDetailFragment.TEAM_ID))
supportFragmentManager
.beginTransaction()
.replace(R.id.content, teamDetailFragment)
.commit()
}
}
| 0 | Kotlin | 0 | 0 | 941724a0a19af3584dc6341fc712a15d5896fc0c | 637 | Calcio | MIT License |
plugins/types/src/main/kotlin/org/rsmod/plugins/types/NamedInventory.kt | rsmod | 293,875,986 | false | {"Kotlin": 812861} | package org.rsmod.plugins.types
@JvmInline
public value class NamedInventory(public val id: Int)
| 2 | Kotlin | 63 | 79 | e1e1a85d7a4d1840ca0738e3401d18ee40424860 | 98 | rsmod | ISC License |
app/src/main/java/com/financialchecker/ui/expense/ExpenseFragment.kt | userddssilva | 750,118,533 | false | {"Kotlin": 34957} | /*
* MIT License
*
* Copyright (c) 2024 Financial Checker
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.financialchecker.ui.expense
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.financialchecker.R
import com.financialchecker.databinding.FragmentExpenseBinding
import com.financialchecker.model.adapter.ExpenseAdapter
import com.financialchecker.model.data.Expense
import com.financialchecker.model.data.ExpenseCategory
import com.google.android.material.floatingactionbutton.FloatingActionButton
class ExpenseFragment : Fragment() {
private var _binding: FragmentExpenseBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
activity?.title = getString(R.string.expense)
val expenseViewModel =
ViewModelProvider(this).get(ExpenseViewModel::class.java)
_binding = FragmentExpenseBinding.inflate(inflater, container, false)
val root: View = binding.root
val addExpenseButton: FloatingActionButton = binding.floatingActionButton
addExpenseButton.setOnClickListener {
val intent = Intent(context, CreateExpenseActivity::class.java)
startActivity(intent)
}
val expense = Expense(
"Dinner for Two",
"23/02/2023",
34.4,
ExpenseCategory("Restaurante", true),
false
)
val expenses = arrayListOf<Expense>()
for (i in 1..10) {
expenses.add(expense)
}
val expensesRecycleView = binding.rcExpenses
expensesRecycleView.layoutManager = LinearLayoutManager(context)
expensesRecycleView.adapter = ExpenseAdapter(expenses)
// val textView: TextView = binding.textHome
// expenseViewModel.text.observe(viewLifecycleOwner) {
// textView.text = it
// }
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 40b1124b165a92780ea85be85ddf1f188c595eda | 3,461 | financial-checker-mobile | MIT License |
immutable-arrays/core/src/test/kotlin/com/danrusu/pods4k/immutableArrays/SequencesTest.kt | daniel-rusu | 774,714,857 | false | {"Kotlin": 197797} | package com.danrusu.pods4k.immutableArrays
import com.danrusu.pods4k.immutableArrays.ImmutableArray
import com.danrusu.pods4k.immutableArrays.ImmutableIntArray
import com.danrusu.pods4k.immutableArrays.toImmutableArray
import com.danrusu.pods4k.immutableArrays.toImmutableIntArray
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isA
class SequencesTest {
@Test
fun `toImmutableArray validation`() {
with(sequenceOf(1, 3, 5)) {
val genericImmutableArray = this.toImmutableArray()
expectThat(genericImmutableArray).isA<ImmutableArray<Int>>()
expectThat(genericImmutableArray).containsExactly(1, 3, 5)
val primitiveImmutableArray = this.toImmutableIntArray()
expectThat(primitiveImmutableArray).isA<ImmutableIntArray>()
expectThat(primitiveImmutableArray).containsExactly(1, 3, 5)
}
}
}
| 0 | Kotlin | 0 | 0 | 49229433ec7d238bffcac929d18014a8107c7723 | 927 | pods4k | Apache License 2.0 |
app/src/main/java/com/concordium/wallet/ui/walletconnect/WalletConnectProgressFragment.kt | Concordium | 750,205,274 | false | {"Kotlin": 1618843, "Java": 247867, "HTML": 53707, "CSS": 256} | package com.concordium.wallet.ui.walletconnect
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.concordium.wallet.R
import com.concordium.wallet.databinding.FragmentWalletConnectProgressBinding
class WalletConnectProgressFragment : Fragment(R.layout.fragment_wallet_connect_progress) {
val createdView: MutableLiveData<CreatedView> = MutableLiveData()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
createdView.postValue(
CreatedView(
view = FragmentWalletConnectProgressBinding.bind(view),
lifecycleOwner = viewLifecycleOwner
)
)
}
data class CreatedView(
val view: FragmentWalletConnectProgressBinding,
val lifecycleOwner: LifecycleOwner,
)
}
| 14 | Kotlin | 0 | 1 | ac1dd9087feb19081be4d92e65bb8bb4136750f9 | 968 | cryptox-android | Apache License 2.0 |
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/types/BotCommandScopeChatMember.kt | gagarski | 314,041,476 | false | null | package ski.gagar.vxutil.vertigram.types
data class BotCommandScopeChatMember(
val chatId: ChatId,
val userId: Long
) : BotCommandScope {
override val type: BotCommandScopeType = BotCommandScopeType.CHAT_MEMBER
}
| 0 | Kotlin | 0 | 0 | 9cb9209e905df3602fc87147c317ca75fdc12ad0 | 227 | vxutil | Apache License 2.0 |
blockchain-development-kit/accelerators/corda/service-bus-integration/corda-transaction-builder/src/main/kotlin/net/corda/workbench/transactionBuilder/events/EventFactory.kt | brendalee | 164,572,746 | true | {"HTML": 3970966, "Python": 1081109, "Java": 880816, "C#": 491991, "Kotlin": 358099, "JavaScript": 161542, "PowerShell": 85556, "CSS": 23314, "PLpgSQL": 16377, "Shell": 14135, "Batchfile": 8685, "Dockerfile": 4167, "Scala": 840, "ASP": 105} | package net.corda.workbench.transactionBuilder.events
import net.corda.workbench.commons.event.Event
import java.util.*
/**
* Build events for storage. TODO it would
* be nice to have typed classes here, but Event
* is currently defined as a data class & so cant be extended
*/
object EventFactory {
fun CORDA_APP_DEPLOYED(appname: String, network: String, appId: UUID, scannablePackages : List<String>): Event {
return Event(type = "CordaAppDeployed",
aggregateId = network,
payload = mapOf<String, Any>("appname" to appname,
"appId" to appId.toString(),
"network" to network,
"scannablePackages" to scannablePackages))
}
fun AGENT_STARTED(network: String, port: Int, pid: Long): Event {
return Event(type = "AgentStarted",
aggregateId = network,
payload = mapOf("network" to network,
"port" to port,
"pid" to pid))
}
fun AGENT_STOPPED(network: String, pid: Long, message: String): Event {
return Event(type = "AgentStopped",
aggregateId = network,
payload = mapOf("network" to network,
"pid" to pid,
"message" to message))
}
}
| 0 | HTML | 0 | 0 | 717c3872eb6eac2de6afd10740f6e2310e318b5a | 1,351 | blockchain | MIT License |
libs/db/db-core/src/main/kotlin/net/corda/db/core/CreateDataSourceMethod.kt | corda | 346,070,752 | false | {"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.db.core
import java.time.Duration
@Suppress("LongParameterList")
fun createUnpooledDataSource(
driverClass: String,
jdbcUrl: String,
username: String,
password: String,
datasourceFactory: DataSourceFactory = DataSourceFactoryImpl(),
maximumPoolSize: Int = 5,
): CloseableDataSource {
return datasourceFactory.create(
enablePool = false,
driverClass = driverClass,
jdbcUrl = jdbcUrl,
username = username,
password = <PASSWORD>,
maximumPoolSize = maximumPoolSize,
minimumPoolSize = 1,
idleTimeout = Duration.ofMinutes(2),
maxLifetime = Duration.ofMinutes(30),
keepaliveTime = Duration.ZERO,
validationTimeout = Duration.ofSeconds(5),
)
} | 14 | Kotlin | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 775 | corda-runtime-os | Apache License 2.0 |
client/src/test/java/org/phoenixframework/liveview/test/ui/view/LazyColumnShotTest.kt | liveview-native | 459,214,950 | false | {"Kotlin": 2229783, "Elixir": 104334, "ANTLR": 4846} | package org.phoenixframework.liveview.test.ui.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.junit.Test
import org.phoenixframework.liveview.constants.Attrs.attrHorizontalAlignment
import org.phoenixframework.liveview.constants.Attrs.attrReverseLayout
import org.phoenixframework.liveview.constants.Attrs.attrStyle
import org.phoenixframework.liveview.constants.Attrs.attrVerticalArrangement
import org.phoenixframework.liveview.constants.ComposableTypes.lazyColumn
import org.phoenixframework.liveview.constants.ComposableTypes.row
import org.phoenixframework.liveview.constants.ComposableTypes.text
import org.phoenixframework.liveview.constants.HorizontalAlignmentValues
import org.phoenixframework.liveview.constants.ModifierNames.modifierFillMaxSize
import org.phoenixframework.liveview.constants.ModifierNames.modifierFillMaxWidth
import org.phoenixframework.liveview.constants.ModifierNames.modifierPadding
import org.phoenixframework.liveview.constants.ModifierNames.modifierWeight
import org.phoenixframework.liveview.constants.ModifierTypes.typeDp
import org.phoenixframework.liveview.constants.VerticalArrangementValues
import org.phoenixframework.liveview.extensions.optional
import org.phoenixframework.liveview.test.base.LiveViewComposableTest
class LazyColumnShotTest : LiveViewComposableTest() {
private fun rowsForTemplate(count: Int, fill: Boolean = true): String {
return StringBuffer().apply {
(1..count).forEach {
append(
"""
<$row $attrStyle="$modifierPadding($typeDp(8))">
<$text ${if (fill) "$attrStyle=\"$modifierWeight(1)\"" else ""}>Item ${it}</$text>
<$text>#${it}</$text>
</$row>
"""
)
}
}.toString()
}
private fun LazyListScope.rowsForNativeComposable(rowCount: Int, fill: Boolean = true) {
items((1..rowCount).toList()) { num ->
Row(Modifier.padding(8.dp)) {
Text(text = "Item $num", Modifier.optional(fill, Modifier.weight(1f)))
Text(text = "#$num")
}
}
}
@Test
fun simpleLazyColumnTest() {
val rowCount = 30
compareNativeComposableWithTemplate(
nativeComposable = {
LazyColumn {
this.rowsForNativeComposable(rowCount)
}
}, template = """
<$lazyColumn>
${rowsForTemplate(rowCount)}
</$lazyColumn>
"""
)
}
@Test
fun lazyColumnReverseTest() {
val rowCount = 30
compareNativeComposableWithTemplate(
nativeComposable = {
LazyColumn(reverseLayout = true) {
this.rowsForNativeComposable(rowCount)
}
}, template = """
<$lazyColumn $attrReverseLayout="true">
${rowsForTemplate(rowCount)}
</$lazyColumn>
"""
)
}
@Test
fun lazyColumnVerticalArrangement() {
val rowCount = 5
compareNativeComposableWithTemplate(
nativeComposable = {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceAround,
) {
this.rowsForNativeComposable(rowCount)
}
}, template = """
<$lazyColumn $attrStyle="$modifierFillMaxSize()"
$attrVerticalArrangement="${VerticalArrangementValues.spaceAround}">
${rowsForTemplate(rowCount)}
</$lazyColumn>
"""
)
}
@Test
fun lazyColumnHorizontalAlignment() {
val rowCount = 5
compareNativeComposableWithTemplate(
nativeComposable = {
LazyColumn(
Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.End,
) {
this.rowsForNativeComposable(rowCount, false)
}
}, template = """
<$lazyColumn $attrStyle="$modifierFillMaxWidth()"
$attrHorizontalAlignment="${HorizontalAlignmentValues.end}">
${rowsForTemplate(rowCount, false)}
</$lazyColumn>
"""
)
}
} | 110 | Kotlin | 3 | 99 | 966beddce2bbf216f85b908e9ec8a43bc572433c | 4,999 | liveview-client-jetpack | MIT License |
engine/src/main/kotlin/io/rsbox/engine/model/entity/RSNpc.kt | TheProdigy94 | 199,138,033 | false | null | package io.rsbox.engine.model.entity
import com.google.common.base.MoreObjects
import io.rsbox.api.entity.Npc
import io.rsbox.engine.fs.def.NpcDef
import io.rsbox.engine.fs.def.VarbitDef
import io.rsbox.engine.model.EntityType
import io.rsbox.engine.model.RSTile
import io.rsbox.engine.model.RSWorld
import io.rsbox.engine.model.combat.AttackStyle
import io.rsbox.engine.model.combat.CombatClass
import io.rsbox.engine.model.combat.CombatStyle
import io.rsbox.engine.model.combat.NpcCombatDef
import io.rsbox.engine.model.npcdrops.NpcDropTableDef
import io.rsbox.api.UpdateBlockType
/**
* @author Tom <<EMAIL>>
*/
open class RSNpc private constructor(val id: Int, world: RSWorld, val spawnTile: RSTile) : RSPawn(world), Npc {
constructor(id: Int, tile: RSTile, world: RSWorld) : this(id, world, spawnTile = RSTile(tile)) {
this.tile = tile
}
constructor(owner: RSPlayer, id: Int, tile: RSTile, world: RSWorld) : this(id, world, spawnTile = RSTile(tile)) {
this.tile = tile
this.owner = owner
}
/**
* This flag indicates whether or not this npc's AI should be processed.
*
* As there's a small chance that most npcs will be in the viewport of a real
* player, we don't really need to process a lot of the logic that comes with
* the AI.
*/
private var active = false
/**
* The owner of an npc will be the only [RSPlayer] who can view this npc.
* If the owner is no longer online, this npc will be removed from the world.
*
* @see [io.rsbox.engine.task.WorldRemoveTask]
*/
var owner: RSPlayer? = null
/**
* This flag indicates whether or not this npc will respawn after death.
*/
var respawns = false
/**
* The radius from [spawnTile], in tiles, which the npc can randomly walk.
*/
var walkRadius = 0
/**
* The current hitpoints the npc has.
*/
private var hitpoints = 10
/**
* The [NpcCombatDef] assigned to our npc. This can change at any point to
* another combat definition, for example if we want to transmogify the npc,
* it may want to use a different [NpcCombatDef].
*/
lateinit var combatDef: NpcCombatDef
/**
* The [NpcDropTableDef] assigned to our npc.
*/
lateinit var dropTableDef: NpcDropTableDef
/**
* The [CombatClass] the npc will use on its next attack.
*/
var combatClass = CombatClass.MELEE
/**
* The [AttackStyle] the npc will use on its next attack.
*/
var attackStyle = AttackStyle.CONTROLLED
/**
* The [CombatStyle] the npc will use on its next attack.
*/
var combatStyle = CombatStyle.STAB
/**
* The [Stats] for this npc.
*/
var stats = Stats(world.gameContext.npcStatCount)
/**
* Check if the npc will be aggressive towards the parameter player.
*/
var aggroCheck: ((RSNpc, RSPlayer) -> Boolean)? = null
/**
* Gets the [NpcDef] corresponding to our [id].
*/
val def: NpcDef = world.definitions.get(NpcDef::class.java, id)
/**
* Getter property for our npc name.
*/
val name: String
get() = def.name
/**
* Getter property for a set of any species that our npc may be categorised
* as.
*/
val species: Set<Any>
get() = combatDef.species
/**
* NPCSpawn object reference
*/
var npcSpawnObj: NPCSpawn? = null
override val entityType: EntityType = EntityType.NPC
override fun isRunning(): Boolean = false
override fun getSize(): Int = world.definitions.get(NpcDef::class.java, id).size
override fun getCurrentHp(): Int = hitpoints
override fun getMaxHp(): Int = combatDef.hitpoints
override fun setCurrentHp(level: Int) {
this.hitpoints = level
}
override fun addBlock(block: UpdateBlockType) {
val bits = world.npcUpdateBlocks.updateBlocks[block]!!
blockBuffer.addBit(bits.bit)
}
override fun hasBlock(block: UpdateBlockType): Boolean {
val bits = world.npcUpdateBlocks.updateBlocks[block]!!
return blockBuffer.hasBit(bits.bit)
}
override fun cycle() {
if (timers.isNotEmpty) {
timerCycle()
}
hitsCycle()
}
/**
* This method will get the "visually correct" npc id for this npc from
* [player]'s view point.
*
* Npcs can change their appearance for each player depending on their
* [NpcDef.transforms] and [NpcDef.varp]/[NpcDef.varbit].
*/
fun getTransform(player: RSPlayer): Int {
if (def.varbit != -1) {
val varbitDef = world.definitions.get(VarbitDef::class.java, def.varbit)
val state = player.varps.getBit(varbitDef.varp, varbitDef.startBit, varbitDef.endBit)
return def.transforms!![state]
}
if (def.varp != -1) {
val state = player.varps.getState(def.varp)
return def.transforms!![state]
}
return id
}
/**
* @see [RSNpc.active]
*/
fun setActive(active: Boolean) {
this.active = active
}
/**
* @see [RSNpc.active]
*/
fun isActive(): Boolean = active
/**
* Verifies if the npc is currently spawned in the world.
*/
fun isSpawned(): Boolean = index > 0
override fun toString(): String = MoreObjects.toStringHelper(this).add("id", id).add("name", name).add("index", index).add("active", active).toString()
companion object {
internal const val RESET_PAWN_FACE_DELAY = 25
}
/**
* @param nStats the max amount of stats an npc has.
*/
class Stats(val nStats: Int) {
private val currentLevels = Array(nStats) { 1 }
private val maxLevels = Array(nStats) { 1 }
fun getCurrentLevel(skill: Int): Int = currentLevels[skill]
fun getMaxLevel(skill: Int): Int = maxLevels[skill]
fun setCurrentLevel(skill: Int, level: Int) {
currentLevels[skill] = level
}
fun setMaxLevel(skill: Int, level: Int) {
maxLevels[skill] = level
}
/**
* Alters the current level of the skill by adding [value] onto it.
*
* @param skill the skill level to alter.
*
* @param value the value which to add onto the current skill level.
* This value can be negative to decrement the level.
*
* @param capValue the amount of levels which can be surpass the max
* level in the skill. For example, if this value is set to [3] on a
* skill that has is [99], that means that the level can be altered
* from [99] to [102].
*/
fun alterCurrentLevel(skill: Int, value: Int, capValue: Int = 0) {
check(capValue == 0 || capValue < 0 && value < 0 || capValue > 0 && value >= 0) {
"Cap value and alter value must always be the same signum (+ or -)."
}
val altered = when {
capValue > 0 -> Math.min(getCurrentLevel(skill) + value, getMaxLevel(skill) + capValue)
capValue < 0 -> Math.max(getCurrentLevel(skill) + value, getMaxLevel(skill) + capValue)
else -> Math.min(getMaxLevel(skill), getCurrentLevel(skill) + value)
}
val newLevel = Math.max(0, altered)
val curLevel = getCurrentLevel(skill)
if (newLevel != curLevel) {
setCurrentLevel(skill = skill, level = newLevel)
}
}
/**
* Decrease the level of [skill].
*
* @param skill the skill level to alter.
*
* @param value the amount of levels which to decrease from [skill], as a
* positive number.
*
* @param capped if true, the [skill] level cannot decrease further than
* [getMaxLevel] - [value].
*/
fun decrementCurrentLevel(skill: Int, value: Int, capped: Boolean) = alterCurrentLevel(skill, -value, if (capped) -value else 0)
/**
* Increase the level of [skill].
*
* @param skill the skill level to alter.
*
* @param value the amount of levels which to increase from [skill], as a
* positive number.
*
* @param capped if true, the [skill] level cannot increase further than
* [getMaxLevel].
*/
fun incrementCurrentLevel(skill: Int, value: Int, capped: Boolean) = alterCurrentLevel(skill, value, if (capped) 0 else value)
companion object {
/**
* The default count of stats for npcs.
*/
const val DEFAULT_NPC_STAT_COUNT = 5
}
}
} | 0 | Kotlin | 0 | 0 | b83537fb4cb39be1a9fb22354477b9063d518d0d | 8,749 | rsbox | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ide/wizard/NewEmptyProjectBuilder.kt | phat-zhong24 | 419,398,920 | true | 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 com.intellij.ide.wizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ui.UIBundle
import com.intellij.util.ui.EmptyIcon
import javax.swing.Icon
class NewEmptyProjectBuilder : AbstractNewProjectWizardBuilder() {
override fun getPresentableName() = UIBundle.message("label.project.wizard.empty.project.generator.name")
override fun getDescription() = UIBundle.message("label.project.wizard.empty.project.generator.description")
override fun getNodeIcon(): Icon = EmptyIcon.ICON_0
override fun createStep(context: WizardContext) = NewProjectWizardBaseStep(context)
} | 0 | null | 0 | 0 | c96da9589f4b9a5ccd1e653c4ab636132f6726d1 | 772 | intellij-community | Apache License 2.0 |
src/commonTest/kotlin/OnSuspendableLatestTest.kt | sergejsha | 398,620,667 | false | {"Kotlin": 88761} | package de.halfbit.comachine.tests
import de.halfbit.comachine.comachine
import de.halfbit.comachine.startInScope
import de.halfbit.comachine.tests.utils.await
import de.halfbit.comachine.tests.utils.executeBlockingTest
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class OnSuspendableLatestTest {
data class State(val done: Boolean = false)
data class Event(val index: Int)
@Test
fun newEventsReplaceTheCurrentOneIfItWasInProgress() {
val events = mutableListOf<Event>()
var firstEventJob: Job? = null
val allEventsSent = CompletableDeferred<Unit>()
val machine = comachine<State, Event>(startWith = State()) {
whenIn<State> {
onLatest<Event> { event ->
events.add(event)
coroutineScope {
if (event.index == 0) {
firstEventJob = launch { delay(2000) }
}
withTimeout(2000) {
allEventsSent.await()
}
events.add(event)
state.update { copy(done = true) }
}
}
}
}
executeBlockingTest {
val states = mutableListOf<State>()
launch {
machine.state.collect {
states += it
println("$it")
}
}
machine.startInScope(this)
repeat(10) {
machine.send(Event(index = it))
}
allEventsSent.complete(Unit)
machine.await<State> { done }
assertTrue(
actual = events.size >= 3,
message = "The list can have less events, because some events can be" +
" cancelled even before they are scheduled for launch. Nonetheless," +
" the very first and the very last event (twice, because the last event" +
" is processed completely) are expected."
)
assertEquals(events[0], Event(index = 0))
assertEquals(events[events.lastIndex - 1], Event(index = 9))
assertEquals(events[events.lastIndex], Event(index = 9))
assertTrue(
actual = firstEventJob?.isCancelled == true,
message = "Expect first event's job to be cancelled"
)
}
}
} | 1 | Kotlin | 3 | 26 | ba535fa1305c97ef307e9c1712b7eaf67f626c32 | 2,787 | comachine | Apache License 2.0 |
app/src/main/java/com/copper/debt/di/module/MainModule.kt | glebxhleb | 281,331,933 | false | null | package com.copper.debt.di.module
import com.copper.debt.ui.debts.list.DebtAdapter
import dagger.Module
import dagger.Provides
@Module
class MainModule {
@Provides
fun debtAdapter(): DebtAdapter = DebtAdapter()
}
| 0 | Kotlin | 0 | 0 | 3681f3b71d87c92234aec1da8a9a3493d6490ea9 | 224 | Debt | Apache License 2.0 |
word-generator/src/main/kotlin/com/github/pjozsef/wordgenerator/cache/InMemoryCache.kt | pjozsef | 248,344,539 | false | null | package com.github.pjozsef.wordgenerator.cache
import com.github.benmanes.caffeine.cache.Cache as CaffeineCache
class InMemoryCache<K: Any,V>(val caffeineCache: CaffeineCache<K,V>): Cache<K,V> {
override fun get(key: K) = caffeineCache.getIfPresent(key)
override fun set(key: K, value: V) = caffeineCache.put(key, value)
}
| 16 | Kotlin | 0 | 0 | 07253c715b577d5d6b7d943c6509cb01eb0d95ed | 334 | word-generator | MIT License |
app/src/main/java/org/d3if2146/hitungbmi/ui/hitung/HitungFragment.kt | naufalmng | 522,475,438 | false | {"Kotlin": 35041} | package org.d3if2146.hitungbmi.ui.hitung
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import org.d3if2146.hitungbmi.R
import org.d3if2146.hitungbmi.core.data.source.db.BmiDb
import org.d3if2146.hitungbmi.core.data.source.model.HasilBmi
import org.d3if2146.hitungbmi.core.data.source.model.KategoriBmi
import org.d3if2146.hitungbmi.core.data.source.model.UserInput
import org.d3if2146.hitungbmi.databinding.FragmentHitungBinding
import org.d3if2146.hitungbmi.setupBtnOnLongClickListener
import java.lang.Exception
class HitungFragment : Fragment() {
private var _binding: FragmentHitungBinding? = null
private val binding get() = _binding!!
private val hitungViewModel: HitungViewModel by lazy {
val db = BmiDb.getInstance(requireContext())
val factory = HitungViewModelFactory(db.dao)
ViewModelProvider(this, factory)[HitungViewModel::class.java]
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHitungBinding.inflate(inflater, container, false)
setHasOptionsMenu(true)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupBtnListeners()
requireActivity().setupBtnOnLongClickListener(binding.btnHitung)
requireActivity().setupBtnOnLongClickListener(binding.btnReset)
setupObservers()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.option_menu,menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.menu_about -> {
findNavController().navigate(R.id.action_hitungFragment_to_aboutFragment)
return true
}
R.id.menu_histori -> {
findNavController().navigate(R.id.action_hitungFragment_to_historyFragment)
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun setupObservers() {
hitungViewModel.hasilBmi.observe(requireActivity()) {
if (it != null) {
showResult(it)
}
}
hitungViewModel.navigasi.observe(viewLifecycleOwner) {
if (it == null) return@observe
findNavController().navigate(
HitungFragmentDirections.actionHitungFragmentToSaranFragment(it,getUserInput())
)
hitungViewModel.selesaiNavigasi()
}
// hitungViewModel.data.observe(viewLifecycleOwner) {
// if (it == null) return@observe
// Log.d("HitungFragment", "Data tersimpan. ID ${it.id}")
// }
}
private fun setupBtnListeners() {
with(binding){
btnBagikan.setOnClickListener{
shareData()
}
btnLihatSaran.setOnClickListener{
hitungViewModel.mulaiNavigasi()
}
btnHitung.setOnClickListener{
hitungBmi()
}
btnReset.setOnClickListener{
binding.etBb.clearFocus()
binding.etTb.clearFocus()
reset()
}
}
}
private fun shareData() {
val selectedId = binding.rgGender.rgGender.checkedRadioButtonId
val gender = if (selectedId == R.id.rbPria)
getString(R.string.pria)
else {
getString(R.string.wanita)
}
val msg = getString(R.string.bagikan_template,binding.etBb.text,binding.etTb.text,gender,binding.tvBmi.text,binding.tvKategori.text)
val shareIntent = Intent(Intent.ACTION_SEND)
with(shareIntent){
type = "text/plain"
putExtra(Intent.EXTRA_TEXT,msg)
}
try {
startActivity(shareIntent)
}catch (e: Exception){
Log.e("INTENT SEND", e.toString())
return
}
}
private fun getUserInput(): UserInput {
val berat = binding.etBb.text.toString()
val tinggi = binding.etTb.text.toString()
val selectedId = binding.rgGender.rgGender.checkedRadioButtonId
val gender = if (selectedId == R.id.rbPria)
getString(R.string.pria)
else {
getString(R.string.wanita)
}
return hitungViewModel.getUserInput(berat,tinggi,gender)
}
private fun hitungBmi() {
val berat = binding.etBb.text.toString()
val tinggi = binding.etTb.text.toString()
val selectedId = binding.rgGender.rgGender.checkedRadioButtonId
val gender = if (selectedId == R.id.rbPria)
getString(R.string.pria)
else {
getString(R.string.wanita)
}
if(TextUtils.isEmpty(berat)){
Toast.makeText(context, getString(R.string.berat_invalid), Toast.LENGTH_SHORT).show()
return
}
if(TextUtils.isEmpty(tinggi)){
Toast.makeText(context, getString(R.string.tinggi_invalid), Toast.LENGTH_SHORT).show()
return
}
if(selectedId == -1){
Toast.makeText(context, getString(R.string.gender_invalid), Toast.LENGTH_SHORT).show()
return
}
hitungViewModel.hitungBmi(berat,tinggi,selectedId == R.id.rbPria)
hitungViewModel.saveUserInput(berat,tinggi,gender)
}
private fun showResult(result: HasilBmi){
binding.tvBmi.text = getString(R.string.bmi,result.bmi)
binding.tvKategori.text = getString(R.string.kategori,getKategoriLabel(result.kategori))
binding.tvBmi.visibility = View.VISIBLE
binding.tvKategori.visibility = View.VISIBLE
binding.divider.visibility = View.VISIBLE
binding.btnReset.visibility = View.VISIBLE
binding.buttonGroup.visibility = View.VISIBLE
}
private fun reset() {
binding.btnReset.visibility = View.GONE
binding.tvBmi.visibility = View.GONE
binding.tvKategori.visibility = View.GONE
binding.divider.visibility = View.GONE
binding.buttonGroup.visibility = View.GONE
binding.etBb.text?.clear()
binding.etTb.text?.clear()
binding.tvBmi.text = null
binding.tvKategori.text = null
binding.rgGender.rgGender.clearCheck()
hitungViewModel.deleteUserInput()
}
private fun getKategoriLabel(kategori: KategoriBmi): String{
val stringRes = when(kategori){
KategoriBmi.KURUS -> R.string.kurus
KategoriBmi.GEMUK -> R.string.gemuk
KategoriBmi.IDEAL -> R.string.ideal
}
return getString(stringRes)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 | Kotlin | 0 | 0 | 49a1660db7db23ea8c5bac69aab6a3d87d5c8312 | 7,287 | hitungBmi | Apache License 2.0 |
game-server/game/src/main/kotlin/com/osrs/game/actor/hit/HealthBar.kt | runetopic | 613,076,716 | false | {"Kotlin": 296499, "Witcher Script": 2511} | package com.osrs.game.actor.hit
import com.osrs.game.actor.Actor
@JvmInline
value class HealthBar(val id: Int) {
companion object {
val Default = HealthBar(0)
val Medium = HealthBar(10)
val Large = HealthBar(20)
}
fun percentage(e: Actor): Int {
val total = e.totalHitpoints()
val current = e.currentHitpoints().coerceAtMost(total)
// TODO 30 is only hard-coded for players
var percentage = if (total == 0) 0 else current * 30 / total
if (percentage == 0 && current > 0) {
percentage = 1
}
return percentage
}
}
| 1 | Kotlin | 1 | 10 | 2a5186b2b7befa7c364e0b989da68ed83070a926 | 623 | osrs-server | MIT License |
app/src/main/java/com/example/marshallsmetronome/ValidationUtils.kt | wizzardx | 715,224,305 | false | {"Kotlin": 165325, "JavaScript": 280} | /**
* Functions related to input validation and normalization.
*/
package com.example.marshallsmetronome
/**
* Validates a string input to ensure it represents a valid integer within specified bounds.
*
* This function checks if the input string can be converted to an integer and
* whether it falls within the predefined bounds of 1 and `Constants.MaxUserInputNum`
* (inclusive). It is primarily used to validate user inputs for settings like
* cycle duration, work intervals, or rest intervals in the application. If the
* input is not a valid integer or falls outside the acceptable range, an
* appropriate error message is returned. Otherwise, the function returns null,
* indicating a valid input.
*
* @param value The string input to be validated.
* @return A string containing an error message if the input is invalid, or null if the input is valid.
*/
fun validateIntInput(value: String): String? {
val intVal = value.toIntOrNull()
return when {
intVal == null -> "Invalid number"
intVal < 1 -> "Must be at least 1"
intVal > Constants.MaxUserInputNum -> "Must be at most 100"
else -> null // valid input
}
}
/**
* Normalizes a string input to ensure it contains only numeric digits.
*
* This function checks the provided `input` string and returns it if it's either
* empty or contains only digit characters. If `input` contains any non-digit
* characters, the function returns the `orig` string, which represents the
* original or previous value.
*
* @param input The string to be normalized.
* @param orig The original string to revert to if `input` is invalid.
* @return A string that is either the normalized input or the original string.
*/
fun normaliseIntInput(
input: String,
orig: String,
): String {
return if (input.isEmpty() || input.all { it.isDigit() }) {
input // Use newText if it's empty or all digits
} else {
orig // Retain the previous value of text if the input contains non-digit characters
}
}
/**
* Safely casts a Long value to an Int.
* Throws an ArithmeticException if the Long value is outside the range of Int.
*
* @return The Int value corresponding to this Long.
* @throws ArithmeticException if this value is not within the range of Int.
*/
fun Long.safeToInt(): Int {
if (this < Int.MIN_VALUE || this > Int.MAX_VALUE) {
throw ArithmeticException("Long value $this cannot be cast to Int without data loss.")
}
return this.toInt()
}
| 0 | Kotlin | 0 | 0 | 27f8a76ffa70df7a6ee9d5facf97c12f7f88d54d | 2,507 | MarshallsMetronome | Creative Commons Attribution 4.0 International |
app/src/main/java/com/jmnetwork/e_jartas/viewModel/ManajemenTiangViewModel.kt | CV-JM-Network | 807,372,558 | false | {"Kotlin": 170497} | package com.jmnetwork.e_jartas.viewModel
import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jmnetwork.e_jartas.model.ProviderData
import com.jmnetwork.e_jartas.model.ProviderRequest
import com.jmnetwork.e_jartas.repository.ManajemenTiangRepositoryImpl
import com.jmnetwork.e_jartas.utils.Constants
import com.jmnetwork.e_jartas.utils.MySharedPreferences
class ManajemenTiangViewModel(application: Application) : ViewModel() {
private val appContext: Application = application
private var myPreferences = MySharedPreferences(appContext)
private var repository = ManajemenTiangRepositoryImpl()
private val tokenAuth = myPreferences.getValue(Constants.TOKEN_AUTH).toString()
private val idAdmin = myPreferences.getValueInteger(Constants.USER_IDADMIN)
val providerData: MutableLiveData<Map<Int, ProviderData>> = MutableLiveData(mapOf())
val totalData: MutableLiveData<Int> = MutableLiveData(0)
fun getProvider(limit: Int, page: Int) {
repository.getProvider(appContext, limit, page, tokenAuth).observeForever {
totalData.postValue(it.totalData.totalData)
val currentData = providerData.value?.toMutableMap() ?: mutableMapOf()
val updatedData = currentData.toMutableMap()
it.data.forEach { data ->
if (updatedData[data.idProvider] == null) {
updatedData[data.idProvider] = data
}
}
providerData.postValue(updatedData)
}
}
private var requestData: ProviderRequest = ProviderRequest(
emptyList(), "", ""
)
fun setRequestData(
additional: List<String>,
alamat: String,
provider: String
): String {
val fields = listOf(
alamat to "Alamat Provider",
provider to "Nama Provider"
)
for ((field, message) in fields) {
if (field.isEmpty()) return "$message tidak boleh kosong"
}
requestData = ProviderRequest(
emptyList(),
alamat,
provider
)
return ""
}
fun addProvider(callback: (String, String) -> Unit) {
repository.addProvider(appContext, idAdmin, requestData, tokenAuth).observeForever {
callback(it.status, it.message)
}
}
fun blacklistProvider(idProvider: Int, isBlacklist: Boolean, callback: (String, String) -> Unit) {
repository.blacklistProvider(appContext, idAdmin, idProvider, isBlacklist, tokenAuth).observeForever { it ->
if (it.status == "success") {
val currentData = providerData.value?.toMutableMap() ?: mutableMapOf()
val updatedData = currentData.toMutableMap()
updatedData[idProvider]?.let {
updatedData[idProvider] = it.copy(blackList = if (isBlacklist) "ya" else "tidak")
}
providerData.postValue(updatedData)
}
callback(it.status, it.message)
}
}
fun editProvider(idProvider: Int, callback: (String, String) -> Unit) {
repository.editProvider(appContext, idAdmin, idProvider, requestData, tokenAuth).observeForever { it ->
if (it.status == "success") {
val currentData = providerData.value?.toMutableMap() ?: mutableMapOf()
val updatedData = currentData.toMutableMap()
updatedData[idProvider]?.let {
updatedData[idProvider] = it.copy(
alamat = requestData.alamat,
provider = requestData.provider
)
}
providerData.postValue(updatedData)
}
callback(it.status, it.message)
}
}
fun deleteProvider(idProvider: Int, callback: (String, String) -> Unit) {
repository.deleteProvider(appContext, idAdmin, idProvider, tokenAuth).observeForever {
if (it.status == "success") {
val currentData = providerData.value?.toMutableMap() ?: mutableMapOf()
val updatedData = currentData.toMutableMap()
updatedData.remove(idProvider)
providerData.postValue(updatedData)
}
callback(it.status, it.message)
}
}
} | 0 | Kotlin | 0 | 0 | 3c0b0988a1eda182100348d4e9ca4a3d2eee26c0 | 4,390 | E-Jartas | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appmesh/ListenerTlsValidationContextTrustPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.appmesh
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.appmesh.CfnVirtualNode
@Generated
public fun buildListenerTlsValidationContextTrustProperty(initializer: @AwsCdkDsl
CfnVirtualNode.ListenerTlsValidationContextTrustProperty.Builder.() -> Unit):
CfnVirtualNode.ListenerTlsValidationContextTrustProperty =
CfnVirtualNode.ListenerTlsValidationContextTrustProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | 451a1e42282de74a9a119a5716bd95b913662e7c | 549 | aws-cdk-kt | Apache License 2.0 |
features/stream/src/main/java/com/m3u/features/stream/fragments/MaskGesture.kt | realOxy | 592,741,804 | false | {"Kotlin": 734765} | package com.m3u.features.stream.fragments
internal enum class MaskGesture {
VOLUME, BRIGHTNESS
}
| 19 | Kotlin | 9 | 95 | 67e7185408a544094c7b4403f8309a52dad4aca0 | 102 | M3UAndroid | Apache License 2.0 |
src/test/kotlin/io/github/t3r1jj/storapi/factory/StorageFactory.kt | t3rmian | 160,053,549 | false | null | package io.github.t3r1jj.storapi.factory
import io.github.t3r1jj.storapi.upstream.UpstreamStorage
interface StorageFactory<S : UpstreamStorage> : UpstreamStorageFactory<S> {
fun createStorageWithoutAccess(): S
}
| 0 | Kotlin | 0 | 0 | 3021cb852e8b16bfd101e6fb4bc2589363ee4f76 | 218 | storapi | MIT License |
stack/src/main/kotlin/com/example/hello/infra/Stack.kt | jensbarthel | 713,360,193 | false | {"Kotlin": 9283, "Dockerfile": 408} | package com.example.hello.infra
import com.pulumi.Context
import com.pulumi.asset.FileArchive
import com.pulumi.azurenative.resources.ResourceGroup
import com.pulumi.azurenative.storage.Blob
import com.pulumi.azurenative.storage.BlobArgs
import com.pulumi.azurenative.storage.BlobContainer
import com.pulumi.azurenative.storage.BlobContainerArgs
import com.pulumi.azurenative.storage.StorageAccount
import com.pulumi.azurenative.storage.StorageAccountArgs
import com.pulumi.azurenative.storage.StorageFunctions
import com.pulumi.azurenative.storage.enums.HttpProtocol
import com.pulumi.azurenative.storage.enums.Kind
import com.pulumi.azurenative.storage.enums.Permissions
import com.pulumi.azurenative.storage.enums.SignedResource
import com.pulumi.azurenative.storage.enums.SkuName
import com.pulumi.azurenative.storage.inputs.ListStorageAccountKeysArgs
import com.pulumi.azurenative.storage.inputs.ListStorageAccountServiceSASArgs
import com.pulumi.azurenative.storage.inputs.SkuArgs
import com.pulumi.azurenative.web.AppServicePlan
import com.pulumi.azurenative.web.AppServicePlanArgs
import com.pulumi.azurenative.web.WebApp
import com.pulumi.azurenative.web.WebAppArgs
import com.pulumi.azurenative.web.enums.FtpsState
import com.pulumi.azurenative.web.enums.SupportedTlsVersions
import com.pulumi.azurenative.web.inputs.NameValuePairArgs
import com.pulumi.azurenative.web.inputs.SiteConfigArgs
import com.pulumi.azurenative.web.inputs.SkuDescriptionArgs
import com.pulumi.core.Output
import java.io.File
class Stack {
fun provision(ctx: Context) {
// Create a separate resource group for this example.
val resourceGroup = ResourceGroup("linux-fn-rg")
// Storage account is required by Function App.
// Also, we will upload the function code to the same storage account.
val storageAccount = StorageAccount(
"linux-fn-sa", StorageAccountArgs.builder()
.accountName("linuxfnsa")
.resourceGroupName(resourceGroup.name())
.kind(Kind.StorageV2)
.sku(
SkuArgs.builder()
.name(SkuName.Standard_LRS)
.build()
)
.build()
)
// Function code archives will be stored in this container.
val codeContainer = BlobContainer(
"zips", BlobContainerArgs.builder()
.resourceGroupName(resourceGroup.name())
.accountName(storageAccount.name())
.build()
)
// Upload Azure Function's code as a zip archive to the storage account.
val codeBlob = Blob(
"zip", BlobArgs.builder()
.resourceGroupName(resourceGroup.name())
.accountName(storageAccount.name())
.containerName(codeContainer.name())
.source(FileArchive(findAppArchive().absolutePath))
.build()
)
// Define a Consumption Plan for the Function App.
// You can change the SKU to Premium or App Service Plan if needed.
val plan = AppServicePlan(
"plan", AppServicePlanArgs.builder()
.resourceGroupName(resourceGroup.name())
.kind("Linux")
.reserved(true) // required for Linux
.sku(
SkuDescriptionArgs.builder()
.tier("Dynamic")
.name("Y1")
.capacity(1)
.build()
)
.build()
)
// Build the connection string and zip archive's SAS URL. They will go to Function App's settings.
val storageConnectionString: Output<String> = getConnectionString(resourceGroup.name(), storageAccount.name())
val codeBlobUrl: Output<String> = signedBlobReadUrl(codeBlob, codeContainer, storageAccount, resourceGroup)
val app = storageConnectionString.applyValue { conn ->
WebApp(
"function", WebAppArgs.builder()
.resourceGroupName(resourceGroup.name())
.serverFarmId(plan.getId())
.kind("functionapp,linux,container")
.httpsOnly(true)
.siteConfig(
SiteConfigArgs.builder()
.numberOfWorkers(1)
.minTlsVersion(SupportedTlsVersions._1_2)
.ftpsState(FtpsState.Disabled)
.appSettings(
NameValuePairArgs.builder().name("AzureWebJobsStorage").value(conn).build(),
NameValuePairArgs.builder().name("WEBSITE_RUN_FROM_PACKAGE").value(codeBlobUrl)
.build(),
NameValuePairArgs.builder().name("FUNCTIONS_EXTENSION_VERSION").value("~4").build(),
NameValuePairArgs.builder().name("FUNCTIONS_WORKER_RUNTIME").value("powershell")
.build()
).build()
)
.build()
)
}
ctx.export("functionName", app.apply(WebApp::name))
ctx.export(
"endpoint", Output.format(
"https://%s/api/hello", // 'hello' corresponds to app/src/main/function/hello
app.apply(WebApp::defaultHostName)
)
)
}
private fun getConnectionString(resourceGroupName: Output<String?>?, accountName: Output<String?>?): Output<String> {
// Retrieve the primary storage account key.
val primaryStorageKey = StorageFunctions.listStorageAccountKeys(
ListStorageAccountKeysArgs.builder()
.resourceGroupName(resourceGroupName)
.accountName(accountName)
.build()
)
.applyValue { r -> r.keys().get(0).value() }
// Build the connection string to the storage account.
return Output.format(
"DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s",
accountName, primaryStorageKey
)
}
fun signedBlobReadUrl(
blob: Blob, container: BlobContainer, account: StorageAccount, resourceGroup: ResourceGroup
): Output<String> {
val blobSASServiceSasToken = StorageFunctions.listStorageAccountServiceSAS(
ListStorageAccountServiceSASArgs.builder()
.resourceGroupName(resourceGroup.name())
.accountName(account.name())
.protocols(HttpProtocol.Https)
.sharedAccessExpiryTime("2030-01-01")
.sharedAccessStartTime("2021-01-01")
.resource(SignedResource.C)
.permissions(Permissions.R)
.canonicalizedResource(Output.format("/blob/%s/%s", account.name(), container.name()))
.contentType("application/json")
.cacheControl("max-age=5")
.contentDisposition("inline")
.contentEncoding("deflate")
.build()
)
.applyValue { sas -> sas.serviceSasToken() }
return Output.format(
"https://%s.blob.core.windows.net/%s/%s?$%s",
account.name(), container.name(), blob.name(), blobSASServiceSasToken
)
}
private fun findAppArchive(): File {
val files = File("../app/build/dist")
.listFiles { dir: File?, name: String -> name.endsWith("-app.zip") }
check(!(files == null || files.size == 0)) {
"Could not find app archive in `./app/build/dist/*-app.zip`;" +
" did you run `gradle app:packageDistribution`?"
}
check(files.size <= 1) {
"Found more than one app archive `./app/build/dist/*-app.zip`;" +
" confused which one to use."
}
return files[0]
}
}
| 0 | Kotlin | 0 | 0 | 099e86235c2dc018789215961e9c3f6d5c32f671 | 8,026 | azure-kotlin-function-graal-spring | Apache License 2.0 |
kotlin/src/_1a_kotlin_types.kt | gregopet | 110,318,408 | false | {"CSS": 279572, "JavaScript": 261184, "HTML": 64989, "Kotlin": 13574, "Ruby": 1435} | import java.lang.Math.pow
import java.net.CookieManager
import java.util.concurrent.CountDownLatch
import kotlin.math.log10
fun numbers(a: Array<String>) {
//#tag::number_types[]
val intVal = 42
val doubleVal = 42.0
val longVal = 42L
val floatVal = 42F
val shortVal: Short = 42
val byteVal: Byte = intVal.toByte()
//#end::number_types[]
}
fun strings(a: Array<String>) {
//#tag::strings[]
val introduction = "I'm Luna, a lvl 22 human adventurer"
val description = """
I'm Luna, a lvl 22 human adventurer.
I am currently unharmed and carry nothing in my pockets.
My wooden sword "Sparrow" is ready in my hand.
"""
//#end::strings[]
}
fun strings1(a: Array<String>) {
//#tag::strings1[]
val name = "Luna"
println("My name $name is ${name.length} letters long")
//#end::strings1[]
}
//#tag::special_types[]
fun vrnemKarkoli(): Any {
return CountDownLatch(5)
}
fun neVrnemNicesar(): Unit {
println("Unit si lahko predstavljamo kot Void")
}
fun nikoliSeNeVrnem(): Nothing {
throw IllegalStateException("Adijo, kruti svet")
}
//#end::special_types[]
/*
fun nullability() {
//#tag::null1[]
val requirement1: String = null // NAPAKA!
val requirement2: String? = null
//#end::null1[]
}
*/
/*
fun nullability2() {
//#tag::null2[]
var requirement1 = "Udeleženci se morajo smehljati"
requirement1 = null // NAPAKA!
//#end::null2[]
}
*/
fun blah23() {
//#tag::null_lateinit[]
lateinit var zaenkratNeVem: String
zaenkratNeVem = "Zdaj pa vem!"
//#end::null_lateinit[]
}
//#tag::nullInterface[]
interface SkillBuff {
val factor: Double
}
//#end::nullInterface[]
/*
//#tag::null3[]
fun getActualPower(baseSkill: Double, buff: SkillBuff?): Double {
return baseSkill * buff.factor // NAPAKA!
}
//#end::null3[]
*/
//#tag::null4[]
fun getActualPower(baseSkill: Double, buff: SkillBuff?): Double {
if (buff != null) {
return baseSkill * buff.factor
} else {
return baseSkill
}
}
//#end::null4[]
//#tag::null5[]
fun getActualPower1(baseSkill: Double, buff: SkillBuff?): Double {
val factor = buff?.factor ?: 1.0
return baseSkill * factor
}
//#end::null5[]
//#tag::null6[]
fun getActualPower2(baseSkill: Double, buff: SkillBuff?): Double {
return baseSkill * buff!!.factor
}
//#end::null6[]
//#tag::null7[]
fun main(args: Array<String>) {
// Prevajalnik dopusti potencialno napako!
System.console().readLine()
}
//#end::null7[] | 0 | CSS | 0 | 1 | 3aa2d511c13b663ba3dfa0d3780b77e274c9c9d0 | 2,410 | uvod-v-kotlin | The Unlicense |
src/main/kotlin/org/uevola/jsonautovalidation/common/schemas/IsEmail.kt | ugoevola | 646,607,242 | false | {"Kotlin": 81751} | package org.uevola.jsonautovalidation.common.schemas
/*language=JSON*/
val isEmail = """
{
"type": "string",
"format": "email"
}
""".trimIndent() | 0 | Kotlin | 0 | 0 | f3cca3660b402e4408ae452b66a008c5835bc753 | 150 | json-auto-validation | MIT License |
map/src/main/kotlin/de/darkatra/bfme2/map/serialization/Serde.kt | DarkAtra | 325,887,805 | false | null | package de.darkatra.bfme2.map.serialization
internal interface Serde<T> : Serializer<T>, Deserializer<T>
| 1 | Kotlin | 0 | 3 | 5dc078e102c3028e13d368e1ba930b089e9f0f84 | 106 | bfme2-modding-utils | MIT License |
graql-lib/src/main/kotlin/com/thirtytwonineteen/graql/lib/config/delegation/impl/DefaultGraQLFetchConfigurator.kt | joe-thirtytwonineteen | 826,776,300 | false | {"Kotlin": 103762, "Shell": 103} | package com.thirtytwonineteen.graql.lib.config.delegation.impl
import DefaultGraQLDelegatingFetch
import com.thirtytwonineteen.graql.GraQLDelegate
import com.thirtytwonineteen.graql.GraQLFetch
import com.thirtytwonineteen.graql.lib.config.delegation.GraQLDelegationConfigurator
import com.thirtytwonineteen.graql.lib.exceptions.GraQLGlobalExceptionHandler
import io.micronaut.context.BeanContext
import io.micronaut.inject.BeanDefinition
import jakarta.inject.Named
import jakarta.inject.Singleton
import java.lang.reflect.Method
@Singleton
@Named("graQLFetchConfigurator")
class DefaultGraQLFetchConfigurator(
private val beanContext: BeanContext,
private val exceptionHandler: GraQLGlobalExceptionHandler,
) : GraQLDelegationConfigurator<GraQLFetch> {
override fun createDelegate(beanDefinition: BeanDefinition<*>, method: Method, a: Annotation): List<GraQLDelegate> {
val annotation = a as GraQLFetch
/*
if (method.parameters.size != 1) {
throw GraQLDelegationException("Cannot create GraQLFetch delegate for ${method.declaringClass.simpleName}::${method.name}: it does not require exactly one parameter.")
}
*/
val requestParameter = method.parameters.first()
return listOf(
DefaultGraQLDelegatingFetch(
exceptionHandler = exceptionHandler,
type = when {
annotation.type.isBlank() -> requestParameter.type.simpleName
else -> annotation.type
},
field = when {
annotation.field.isBlank() -> method.name
else -> annotation.field
},
method = method,
target = beanContext.getBean(beanDefinition),
)
)
}
} | 0 | Kotlin | 0 | 0 | 8fe881775f2398c7f5f059d3010110b019e29e58 | 1,814 | graql | Apache License 2.0 |
momas-announcer/src/main/kotlin/cc/momas/announcer/model/AnnounceOutVo.kt | Sod-Momas | 326,139,950 | false | {"CSS": 1966411, "Java": 1803375, "JavaScript": 1376355, "HTML": 175322, "Kotlin": 31052, "Less": 20352, "Dockerfile": 195, "Batchfile": 159, "Shell": 66} | package cc.momas.announcer.model
import java.sql.Date
/**
* @author Sod-Momas
* @since 2019.12.19
*/
data class AnnounceOutVo(
private val id: Int? = null,
private val title: String? = null,
private val titleImageUrl: String? = null,
private val content: String? = null,
private val isShow: Boolean? = null,
private val sortNo: Int? = null,
private val senderName: String? = null,
private val deprecateDatetime: Date? = null,
private val tag: String? = null,
private val insertUserId: Long? = null,
private val updateUserId: Long? = null,
private val insertDatetime: Date? = null,
private val updateDatetime: Date? = null
) | 0 | CSS | 0 | 0 | de4fa5f11fb71f98dd8541d3d22412a1756687c9 | 654 | momas-project | Apache License 2.0 |
sources/libraries/extensions/src/main/kotlin/com/egoriku/ladyhappy/extensions/FragmentManager.kt | egorikftp | 102,286,802 | false | {"Kotlin": 477671, "JavaScript": 3040, "Shell": 289} | package com.egoriku.ladyhappy.extensions
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LifecycleOwner
fun FragmentManager.setFragmentResultListenerWrapper(
requestKey: String,
lifecycleOwner: LifecycleOwner,
listener: ((requestKey: String, bundle: Bundle) -> Unit)
) {
setFragmentResultListener(
requestKey,
lifecycleOwner,
{ s, bundle -> listener.invoke(s, bundle) }
)
}
| 12 | Kotlin | 22 | 261 | da53bf026e104b84eebb7c2660c2feae26c6d965 | 468 | Lady-happy-Android | Apache License 2.0 |
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/problems/InstantExecutionProblems.kt | jhutchings1 | 270,161,082 | true | {"Groovy": 28125733, "Java": 26610716, "Kotlin": 3304894, "C++": 1805886, "JavaScript": 208288, "CSS": 174615, "C": 98580, "HTML": 68891, "XSLT": 42845, "Perl": 37849, "Scala": 25650, "Shell": 7675, "Swift": 6972, "Objective-C": 840, "CoffeeScript": 620, "Objective-C++": 441, "GAP": 424, "Assembly": 277, "Gherkin": 191, "Python": 57, "Brainfuck": 54, "Ruby": 16} | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.problems
import org.gradle.BuildAdapter
import org.gradle.BuildResult
import org.gradle.instantexecution.InstantExecutionProblemsException
import org.gradle.instantexecution.InstantExecutionReport
import org.gradle.instantexecution.TooManyInstantExecutionProblemsException
import org.gradle.instantexecution.extensions.getBroadcaster
import org.gradle.instantexecution.initialization.InstantExecutionStartParameter
import org.gradle.internal.event.ListenerManager
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import java.util.concurrent.CopyOnWriteArrayList
private
const val maxCauses = 5
@ServiceScope(Scopes.BuildTree)
class InstantExecutionProblems(
private
val startParameter: InstantExecutionStartParameter,
private
val report: InstantExecutionReport,
private
val listenerManager: ListenerManager
) : ProblemsListener, AutoCloseable {
private
val broadcaster = listenerManager.getBroadcaster<ProblemsListener>()
private
val problemHandler = ProblemHandler()
private
val buildFinishedHandler = BuildFinishedProblemsHandler()
private
val problems = CopyOnWriteArrayList<PropertyProblem>()
private
var isFailOnProblems = startParameter.failOnProblems
init {
listenerManager.addListener(problemHandler)
listenerManager.addListener(buildFinishedHandler)
}
override fun close() {
listenerManager.removeListener(problemHandler)
listenerManager.removeListener(buildFinishedHandler)
}
override fun onProblem(problem: PropertyProblem) {
broadcaster.onProblem(problem)
}
fun failingBuildDueToSerializationError() {
isFailOnProblems = false
}
private
fun List<PropertyProblem>.causes() = mapNotNull { it.exception }.take(maxCauses)
private
inner class ProblemHandler : ProblemsListener {
override fun onProblem(problem: PropertyProblem) {
problems.add(problem)
}
}
private
inner class BuildFinishedProblemsHandler : BuildAdapter() {
override fun buildFinished(result: BuildResult) {
if (result.gradle?.parent != null || problems.isEmpty()) {
return
}
report.writeReportFiles(problems)
if (isFailOnProblems) {
// TODO - always include this as a build failure; currently it is disabled when a serialization problem happens
throw InstantExecutionProblemsException(problems.causes(), problems, report.htmlReportFile)
} else if (problems.size > startParameter.maxProblems) {
throw TooManyInstantExecutionProblemsException(problems.causes(), problems, report.htmlReportFile)
} else {
report.logConsoleSummary(problems)
}
}
}
}
| 0 | null | 0 | 0 | b13c57a145258a4cb56a0b9877e0a5437f478168 | 3,534 | gradle | Apache License 2.0 |
wear/src/main/java/com/blazecode/tsviewer/wear/complication/ComplicationDataHolder.kt | BlazeCodeDev | 434,321,563 | false | null | /*
*
* * Copyright (c) BlazeCode / <NAME>, 2023.
*
*/
package com.blazecode.tsviewer.wear.complication
import data.TsClient
object ComplicationDataHolder {
var list: MutableList<TsClient> = mutableListOf()
var time: Long = 0
} | 2 | Kotlin | 1 | 15 | 7ec64b226826526cee0164feb156681b0eae76de | 242 | TSViewer | MIT License |
app/src/main/java/com/arjun/connect/util/SearchUsersAdapter.kt | ArjunJadeja | 527,292,695 | false | null | package com.arjun.connect.util
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.arjun.connect.R
import com.arjun.connect.data.User
import com.bumptech.glide.Glide
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
class SearchUsersAdapter(
options: FirestoreRecyclerOptions<User>,
private val listener: IAddUserAdapter
) :
FirestoreRecyclerAdapter<User, SearchUsersAdapter.PostViewHolder>(options) {
class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val profileImage: ImageView = itemView.findViewById(R.id.profileImageView)
val name: TextView = itemView.findViewById(R.id.nameTextView)
val username: TextView = itemView.findViewById(R.id.usernameTextView)
val addUser: ImageButton = itemView.findViewById(R.id.addUserButton)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val viewHolder = PostViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.add_users_card, parent, false)
)
viewHolder.addUser.setOnClickListener {
listener.onAddClicked(snapshots.getSnapshot(viewHolder.bindingAdapterPosition).id)
}
return viewHolder
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int, model: User) {
holder.apply {
Glide.with(itemView).load(model.profileImageUrl).into(holder.profileImage)
name.text = model.name
username.text = "@${model.username}"
}
}
}
interface IAddUserAdapter {
fun onAddClicked(userId: String)
}
| 0 | Kotlin | 0 | 0 | a7d26ebc5e49661ca849351ceac1eab650989a48 | 1,862 | Connect | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/managerecallsapi/db/DocumentTest.kt | ministryofjustice | 371,053,303 | false | null | package uk.gov.justice.digital.hmpps.managerecallsapi.db
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import uk.gov.justice.digital.hmpps.managerecallsapi.config.WrongDocumentTypeException
import uk.gov.justice.digital.hmpps.managerecallsapi.domain.DocumentId
import uk.gov.justice.digital.hmpps.managerecallsapi.domain.RecallId
import uk.gov.justice.digital.hmpps.managerecallsapi.domain.UserId
import uk.gov.justice.digital.hmpps.managerecallsapi.domain.random
import java.time.OffsetDateTime
class DocumentTest {
@Test
fun `document throws exception with unversioned category and version`() {
assertThrows<WrongDocumentTypeException> {
Document(
::DocumentId.random(),
::RecallId.random(),
DocumentCategory.OTHER,
"file.txt",
1,
null,
OffsetDateTime.now(),
::UserId.random()
)
}
}
@Test
fun `document throws exception with versioned category and null version`() {
assertThrows<WrongDocumentTypeException> {
Document(
::DocumentId.random(),
::RecallId.random(),
DocumentCategory.LICENCE,
"file.txt",
null,
null,
OffsetDateTime.now(),
::UserId.random()
)
}
}
@Test
fun `versioned document accepts versioned category`() {
Document(
::DocumentId.random(),
::RecallId.random(),
DocumentCategory.LICENCE,
"file.txt",
1,
null,
OffsetDateTime.now(),
::UserId.random()
)
}
}
| 1 | Kotlin | 0 | 0 | f1dba7537ed62e109c2f1338dd5c505f7e4ff000 | 1,547 | manage-recalls-api | MIT License |
app/src/main/java/com/example/futureweather/ui/manage/ManagePlaceAdapter.kt | 111111JY | 286,500,490 | false | null | package com.example.futureweather.ui.manage
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.example.futureweather.R
import com.example.futureweather.extension.showToast
import com.example.futureweather.logic.model.PlaceResponse
import com.example.futureweather.ui.weather.WeatherActivity
import com.example.futureweather.widget.DiyDialog
import kotlinx.android.synthetic.main.activity_weather.*
import java.util.*
class ManagePlaceAdapter(
private val fragment: ManageFragment,
private val placeList: ArrayList<PlaceResponse.Place>
) :
RecyclerView.Adapter<ManagePlaceAdapter.ViewHolder>() {
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val placeName: TextView = view.findViewById(R.id.placeName)
val placeAddress: TextView = view.findViewById(R.id.placeAddress)
val refreshWeatherBtn: ImageView = view.findViewById(R.id.refreshWeatherBtn)
val manageDeleteBtn: TextView = view.findViewById(R.id.manageDeleteBtn)
val setLocationBtn: TextView = view.findViewById(R.id.setLocationBtn)
val placeInfoLayout: RelativeLayout = view.findViewById(R.id.placeInfoLayout)
val operatingLayout: LinearLayout = view.findViewById(R.id.operatingLayout)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.manage_place_item, parent, false)
val holder = ViewHolder(view)
holder.manageDeleteBtn.setOnClickListener {
showDeleteDialog(parent.context, holder.adapterPosition)
holder.operatingLayout.visibility = View.GONE
}
holder.setLocationBtn.setOnClickListener {
showLocationDialog(parent.context, holder.adapterPosition)
holder.operatingLayout.visibility = View.GONE
}
holder.refreshWeatherBtn.setOnClickListener {
val position = holder.adapterPosition
val place = placeList[position]
val activity = fragment.activity
if (activity is WeatherActivity) {
activity.drawerLayout.closeDrawers()
activity.viewModel.locationLng = place.location.lng
activity.viewModel.locationLat = place.location.lat
activity.viewModel.placeName = place.name
activity.refreshWeather()
}
}
holder.placeInfoLayout.setOnClickListener {
if (holder.operatingLayout.visibility == View.GONE) {
holder.operatingLayout.visibility = View.VISIBLE
} else if (holder.operatingLayout.visibility == View.VISIBLE) {
holder.operatingLayout.visibility = View.GONE
}
}
return holder
}
override fun getItemCount() = placeList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val placeInfo = placeList[position]
holder.placeName.text = placeInfo.name
holder.placeAddress.text = placeInfo.address
}
private fun showDeleteDialog(context: Context, position: Int) {
val diyDialogView =
LayoutInflater.from(context).inflate(R.layout.dialog_diy_layout, null)
val confirmBtn = diyDialogView.findViewById<TextView>(R.id.confirm_button)
val cancelBtn = diyDialogView.findViewById<TextView>(R.id.cancel_button)
val contentText = diyDialogView.findViewById<TextView>(R.id.content_text)
val contentAnimation =
diyDialogView.findViewById<LottieAnimationView>(R.id.content_animation)
confirmBtn.text = fragment.getString(R.string.note_delete)
cancelBtn.text = fragment.getString(R.string.note_cancel)
contentText.text = fragment.getString(R.string.note_delete_content)
val dialog = DiyDialog(context, R.style.DiyDialog, diyDialogView)
cancelBtn.setOnClickListener {
dialog.closeDiyDialog()
}
confirmBtn.setOnClickListener {
if (placeList.size > 1){
//移除指定位置的地区
placeList.removeAt(position)
//保存现在的地区列表
fragment.viewModel.savePlace(placeList)
contentText.visibility = View.GONE
contentAnimation.setAnimation(R.raw.delete_finish)
contentAnimation.visibility = View.VISIBLE
contentAnimation.loop(false)
if (!contentAnimation.isAnimating) {
contentAnimation.playAnimation()
}
contentAnimation.addAnimatorUpdateListener {
if (it.animatedFraction == 1F) {
dialog.closeDiyDialog()
}
}
//通知recyclerview刷新列表
notifyDataSetChanged()
} else {
fragment.getString(R.string.note_delete_size1).showToast()
}
}
dialog.setCanceledOnTouchOutside(false)
dialog.showDiyDialog()
}
private fun showLocationDialog(context: Context, position: Int) {
val diyDialogView =
LayoutInflater.from(context).inflate(R.layout.dialog_diy_layout, null)
val confirmBtn = diyDialogView.findViewById<TextView>(R.id.confirm_button)
val cancelBtn = diyDialogView.findViewById<TextView>(R.id.cancel_button)
val contentText = diyDialogView.findViewById<TextView>(R.id.content_text)
val contentAnimation =
diyDialogView.findViewById<LottieAnimationView>(R.id.content_animation)
confirmBtn.text = fragment.getString(R.string.note_confirm)
cancelBtn.text = fragment.getString(R.string.note_cancel)
contentText.text = fragment.getString(R.string.note_location_content)
val dialog = DiyDialog(context, R.style.DiyDialog, diyDialogView)
cancelBtn.setOnClickListener {
dialog.closeDiyDialog()
}
confirmBtn.setOnClickListener {
if (placeList.size > 1) {
//将原有置顶当前地区与现需置顶的地区位置对换
Collections.swap(placeList, 0, position)
}
//刷新当前地区
fragment.refreshNowPlaceName()
//保存现在的地区列表
fragment.viewModel.savePlace(placeList)
//刷新当前地区的天气
val place = placeList[0]
val activity = fragment.activity
if (activity is WeatherActivity) {
activity.viewModel.locationLng = place.location.lng
activity.viewModel.locationLat = place.location.lat
activity.viewModel.placeName = place.name
activity.refreshWeather()
}
contentAnimation.addAnimatorUpdateListener {
if (it.animatedFraction == 1F) {
dialog.closeDiyDialog()
if (activity is WeatherActivity) {
activity.drawerLayout.closeDrawers()
}
}
}
contentText.visibility = View.GONE
contentAnimation.setAnimation(R.raw.set_done_finish)
contentAnimation.visibility = View.VISIBLE
contentAnimation.loop(false)
if (!contentAnimation.isAnimating) {
contentAnimation.playAnimation()
}
//通知recyclerview刷新列表
notifyDataSetChanged()
}
dialog.setCanceledOnTouchOutside(false)
dialog.showDiyDialog()
}
} | 0 | Kotlin | 0 | 1 | f0453ea7faf361eb5d664e7a0b66695262a46ca3 | 7,800 | FutureWeather | Apache License 2.0 |
app/src/main/java/com/sergeyrodin/citiestask/data/source/CountriesRepository.kt | rodins | 351,663,237 | false | null | package com.sergeyrodin.citiestask.data.source
import androidx.lifecycle.LiveData
interface CountriesRepository {
suspend fun getCountries(): List<Country>
suspend fun loadCountriesAndCitiesToDb()
suspend fun deleteAllCountries()
} | 0 | Kotlin | 0 | 0 | 75f27f4280fb8f4c6b90393e772e8c4ddf4af28d | 245 | android_cities_task | Apache License 2.0 |
app/src/main/kotlin/org/crispy/app/CrispyApp.kt | joshuadavis | 399,123,021 | false | null | package org.crispy.app
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
open class CrispyApp
fun main(args: Array<String>) {
runApplication<CrispyApp>(*args)
}
| 5 | Kotlin | 0 | 0 | ac3e683f9a550e08401883500f16264e4030acbd | 256 | crispy-disco | MIT License |
app/src/main/java/com/example/themoviedb/ui/widget/ImageInfoList.kt | KhomDrake | 247,378,064 | false | null | package com.example.themoviedb.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.themoviedb.R
import com.example.themoviedb.extension.gone
import com.example.themoviedb.extension.visible
import com.example.themoviedb.models.application.ImageInfo
import com.example.themoviedb.ui.adapter.RecyclerViewAdapterImageList
import com.facebook.shimmer.ShimmerFrameLayout
class ImageInfoList @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private val imagesViewRecyclerView: RecyclerView
private val imagesShimmer: ShimmerFrameLayout
private val errorButton: Button
private val noContent: TextView
init {
inflate(context, R.layout.image_info_list, this)
imagesViewRecyclerView = findViewById(R.id.recyclerview)
imagesShimmer = findViewById(R.id.list_of_images_info)
errorButton = findViewById(R.id.error_button)
noContent = findViewById(R.id.no_content)
onLoading(loading = true)
}
fun onLoading(loading: Boolean) {
if(loading) {
imagesShimmer.visible()
errorButton.gone()
imagesViewRecyclerView.gone()
noContent.gone()
} else {
imagesShimmer.gone()
}
}
fun onData(
imagesInfo: List<ImageInfo>,
noContentText: String = context.getString(R.string.no_content_text_default),
onClickImageInfo: (ImageInfo) -> Unit = {}
) {
imagesShimmer.gone()
errorButton.gone()
imagesViewRecyclerView.visible()
noContent.text = noContentText
if(imagesInfo.isNotEmpty()) {
setupData(imagesInfo, onClickImageInfo)
noContent.gone()
imagesViewRecyclerView.visible()
}
else {
noContent.visible()
imagesViewRecyclerView.gone()
}
}
fun onError() {
imagesShimmer.gone()
errorButton.visible()
imagesViewRecyclerView.gone()
}
fun onErrorClickListener(listener: () -> Unit) {
errorButton.setOnClickListener { listener.invoke() }
}
private fun setupData(imagesInfo: List<ImageInfo>, onClickImageInfo: (ImageInfo) -> Unit) {
imagesViewRecyclerView.adapter =
RecyclerViewAdapterImageList(
imagesInfo,
onClickImageInfo
)
imagesViewRecyclerView.layoutManager = LinearLayoutManager(
context,
LinearLayoutManager.HORIZONTAL,
false
)
}
} | 0 | Kotlin | 0 | 0 | bb00644c3932656a498e00cee503bb86b81b9e58 | 2,875 | The-Movie-Db | MIT License |
app/src/main/java/dev/patrickgold/florisboard/ime/extension/AssetSource.kt | hosseinkhojany | 356,598,539 | false | null |
package dev.patrickgold.florisboard.ime.extension
import java.util.*
/**
* Sealed class which specifies where an asset comes from. There are 3 different types, all of which
* require a different approach on how to access the actual asset.
*/
sealed class AssetSource {
/**
* The asset comes pre-built with the application, thus all paths must be relative to the asset
* directory of FlorisBoard.
*/
object Assets : AssetSource()
/**
* The asset is saved in the internal storage of FlorisBoard, all relative paths must therefore
* be treated as such.
*/
object Internal : AssetSource()
/**
* Asset source is an external extension, which requires the package name and possibly other
* data. Currently NYI.
* TODO: Implement external extensions
*/
data class External(val packageName: String) : AssetSource() {
override fun toString(): String {
return super.toString()
}
}
companion object {
private val externalRegex: Regex = """^external\\(([a-z]+\\.)*[a-z]+\\)\$""".toRegex()
fun fromString(str: String): Result<AssetSource> {
return when (val string = str.toLowerCase(Locale.ENGLISH)) {
"assets" -> Result.success(Assets)
"internal" -> Result.success(Internal)
else -> {
if (string.matches(externalRegex)) {
val packageName = string.substring(9, string.length - 1)
Result.success(External(packageName))
} else {
Result.failure(Exception("'$str' is not a valid AssetSource."))
}
}
}
}
}
override fun toString(): String {
return when (this) {
is Assets -> "assets"
is Internal -> "internal"
is External -> "external($packageName)"
}
}
}
| 0 | Kotlin | 0 | 0 | e9fc3246d834d626b073563c175a4a1445b739f1 | 1,966 | KeyLogger | Apache License 2.0 |
ethereumkit/src/main/java/org/p2p/ethereumkit/internal/api/jsonrpc/GetTransactionByHashJsonRpc.kt | p2p-org | 306,035,988 | false | null | package org.p2p.ethereumkit.internal.api.jsonrpc
import com.google.gson.reflect.TypeToken
import org.p2p.ethereumkit.internal.api.jsonrpc.models.RpcTransaction
import java.lang.reflect.Type
import org.p2p.core.rpc.JsonRpc
class GetTransactionByHashJsonRpc(
@Transient val transactionHash: ByteArray
) : JsonRpc<List<Any>, RpcTransaction>(
method = "eth_getTransactionByHash",
params = listOf(transactionHash)
) {
@Transient
override val typeOfResult: Type = object : TypeToken<RpcTransaction>() {}.type
}
| 8 | Kotlin | 16 | 28 | 71b282491cdafd26be1ffc412a971daaa9c06c61 | 539 | key-app-android | MIT License |
src/jsTest/kotlin/app/CityGuesserViewModelTest.kt | jossiwolf | 489,154,391 | false | {"Kotlin": 51432, "HTML": 1258} | package app
import io.data2viz.geojson.Geometry
import io.data2viz.geojson.Position
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import kotlin.test.Ignore
import kotlin.test.Test
@OptIn(ExperimentalCoroutinesApi::class)
class CityGuesserViewModelTest {
@Ignore
@Test
fun test_cities() = runTest {
val viewModel = CityGuesserViewModel()
val city = Stub.City(lng = 0.0, lat = 0.0)
viewModel.getCitiesForLevel(arrayOf(city), 0)
}
}
interface Stub {
companion object : Stub
}
fun Stub.Point(
position: Position
) = io.data2viz.geojson.Point(position)
fun Stub.Position(
lng: Double,
lat: Double
) = doubleArrayOf(lng, lat)
fun Stub.Feature(
geometry: Geometry,
id: Any? = null,
properties: Any? = null
) = io.data2viz.geojson.Feature(
geometry = geometry,
id = id,
properties = properties
)
fun Stub.City(
lng: Double,
lat: Double,
id: Any? = null,
properties: Any? = null
) = io.data2viz.geojson.Feature(
geometry = Stub.Point(Stub.Position(lng = lng, lat = lat)),
id = id,
properties = properties
) | 0 | Kotlin | 0 | 0 | 6279ba6fe7870f4d4cb88bc225669cda7d54505b | 1,160 | city-guesser | MIT License |
app/src/main/java/com/batdemir/template/di/module/local/LocalModule.kt | batdemir | 332,173,381 | false | null | package com.batdemir.template.di.module.local
import android.content.Context
import androidx.room.Room
import com.batdemir.template.data.local.AppDatabase
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module(
includes = [
LocalDaoModule::class,
LocalDataSourceModule::class
]
)
object LocalModule {
@Singleton
@Provides
fun provideDatabase(context: Context): AppDatabase {
return Room
.databaseBuilder(context, AppDatabase::class.java, "batdemir.db")
.fallbackToDestructiveMigration()
.build()
}
} | 0 | Kotlin | 0 | 3 | ccb7a52935871d1639312ffb1f1e5e5686320380 | 612 | kotlin.template.project | Apache License 2.0 |
presentation/src/main/java/tgo1014/listofbeers/presentation/ui/composables/SingleSelectionFilter.kt | Tgo1014 | 433,974,074 | false | {"Kotlin": 89548} | package tgo1014.listofbeers.presentation.ui.composables
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import tgo1014.listofbeers.presentation.models.Filter
import tgo1014.listofbeers.presentation.models.FilterState
import tgo1014.listofbeers.presentation.models.translation
import tgo1014.listofbeers.presentation.ui.composables.previews.DefaultPreview
import tgo1014.listofbeers.presentation.ui.composables.providers.ThemeProvider
import tgo1014.listofbeers.presentation.ui.theme.ListOfBeersTheme
@Composable
fun SingleSelectionFilter(
filters: List<FilterState>,
onClick: (Filter) -> Unit,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp)
) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = contentPadding,
modifier = modifier
) {
items(filters) {
PrimaryContainerFilterChip(text = it.filter.translation(), isSelected = it.isSelected) {
onClick(it.filter)
}
}
}
}
@DefaultPreview
@Composable
private fun SingleSelectionFilterPreview(
@PreviewParameter(ThemeProvider::class) materialYouColors: Boolean
) = ListOfBeersTheme(materialYouColors = materialYouColors) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
val items = listOf(FilterState(Filter.BLONDE, false), FilterState(Filter.LAGER, true))
SingleSelectionFilter(filters = items, onClick = {})
}
} | 0 | Kotlin | 0 | 0 | ada222b8c5128281ee36aa10fae055bf00e543ce | 1,897 | listOfBeers | Apache License 2.0 |
app/src/main/java/com/mindorks/sample/whatsapp/screen/main/view/MainViewModel.kt | MindorksOpenSource | 261,391,043 | false | null | package com.mindorks.sample.whatsapp.screen.main.view
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private var _screenState = MutableLiveData(ScreenState(ScreenState.Screen.CHATS))
var screenState: LiveData<ScreenState> = _screenState
fun navigateTo(state: ScreenState.Screen) {
_screenState.value = ScreenState(state)
}
} | 2 | Kotlin | 97 | 564 | 9d9d80595ce1cd98286b326281ca2d623e60f091 | 454 | Jetpack-Compose-WhatsApp-Clone | Apache License 2.0 |
boneslibrary/src/main/java/com/eudycontreras/boneslibrary/framework/bones/Bone.kt | EudyContreras | 253,115,353 | false | null | package com.eudycontreras.boneslibrary.framework.bones
import android.graphics.*
import android.view.View
import android.widget.TextView
import com.eudycontreras.boneslibrary.AndroidColor
import com.eudycontreras.boneslibrary.MAX_OFFSET
import com.eudycontreras.boneslibrary.MIN_OFFSET
import com.eudycontreras.boneslibrary.common.*
import com.eudycontreras.boneslibrary.extensions.addCircle
import com.eudycontreras.boneslibrary.extensions.addRoundRect
import com.eudycontreras.boneslibrary.extensions.horizontalPadding
import com.eudycontreras.boneslibrary.extensions.verticalPadding
import com.eudycontreras.boneslibrary.framework.bones.BoneProperties.Companion.OVERFLOW_THRESHOLD
import com.eudycontreras.boneslibrary.framework.shimmer.ShimmerRay
import com.eudycontreras.boneslibrary.properties.Color
import com.eudycontreras.boneslibrary.properties.CornerRadii
import com.eudycontreras.boneslibrary.properties.MutableColor
import com.eudycontreras.boneslibrary.properties.ShapeType
/**
* Copyright (C) 2020 Bones
*
* @Project Project Bones
* @author <NAME>.
* @since March 2020
*/
internal class Bone(
val owner: View,
val boneProperties: BoneProperties
) : DrawableShape(), FadeTarget, UpdateTarget, Disposable, ContentLoader {
private val shimmerRays: MutableList<ShimmerRay> = mutableListOf()
private var shapeType: ShapeType = ShapeType.RECTANGULAR
private val overMode: PorterDuffXfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)
private fun getLength(owner: View): Float {
return owner.measuredWidth.toFloat() - if (boneProperties.dissectBones == true) {
owner.horizontalPadding
} else MIN_OFFSET
}
private fun getThickness(owner: View): Float {
return owner.measuredHeight.toFloat() - if (boneProperties.dissectBones == true) {
owner.verticalPadding
} else MIN_OFFSET
}
fun compute(view: View) {
if (boneProperties.color != null) {
this.color = MutableColor.fromColor(boneProperties.color)
}
this.shapeType = boneProperties.shapeType ?: this.shapeType
this.corners = boneProperties.cornerRadii?.copy() ?: CornerRadii()
if (this.color != null) {
if (boneProperties.shadeMultiplier != MAX_OFFSET) {
this.color = this.color?.adjust(boneProperties.shadeMultiplier)
}
}
this.bounds.width = boneProperties.width ?: getLength(owner)
this.bounds.height = boneProperties.height ?: getThickness(owner)
this.bounds.x = (view.measuredWidth.toFloat() / 2) - this.bounds.width / 2
this.bounds.y = (view.measuredHeight.toFloat() / 2) - this.bounds.height / 2
boneProperties.getRayShimmerProps()?.let {
shimmerRays.clear()
ShimmerRay.createRays(
bounds = bounds,
shimmerRays = shimmerRays,
properties = it
)
}
}
override fun restore() { }
override fun concealContent() { }
override fun revealContent() { }
override fun prepareContentFade() {
owner.alpha = MIN_OFFSET
owner.visibility = View.VISIBLE
}
override fun fadeContent(fraction: Float) {
owner.alpha = MAX_OFFSET * fraction
}
override fun onUpdate(fraction: Float) {
if (boneProperties.isDisposed) return
if (shimmerRays.size > 0) {
for (ray in shimmerRays) {
ray.onUpdate(fraction)
}
}
}
override fun onFade(fraction: Float) {
if (boneProperties.isDisposed) return
opacity = Color.MAX_COLOR - (Color.MAX_COLOR * fraction).toInt()
if (shimmerRays.size > 0) {
for (ray in shimmerRays) {
ray.onFade(fraction)
}
}
}
override fun dispose() {
shimmerRays.clear()
}
fun onRender(
canvas: Canvas,
paint: Paint,
path: Path,
rayPath: Path
) {
if (boneProperties.isDisposed) return
buildPaths(path, rayPath)
if (this.color != null) {
paint.shader = null
paint.color = this.color?.toColor() ?: AndroidColor.TRANSPARENT
paint.style = Paint.Style.FILL
canvas.drawPath(path, paint)
}
paint.xfermode = overMode
if (shimmerRays.size > 0) {
for (ray in shimmerRays) {
ray.onRender(canvas, paint, rayPath)
}
}
}
private fun buildPaths(path: Path, rayPath: Path) {
when (shapeType) {
ShapeType.RECTANGULAR -> {
val isTextView = owner is TextView
val maxThickness = boneProperties.maxThickness
val highRatio = height >= maxThickness * OVERFLOW_THRESHOLD
val dissectBones = boneProperties.height == null && boneProperties.dissectBones == true
if (dissectBones && isTextView && highRatio) {
val part = boneProperties.sectionDistance + maxThickness
val times = ((bounds.height - maxThickness) / part).toInt()
var padding = maxThickness / 2
for (it in 0..times) {
val top = bounds.top + (it * maxThickness) + padding
val bottom = top + maxThickness
path.addRoundRect(bounds, radii, top = top, bottom = bottom)
rayPath.addRoundRect(bounds, radii, top = top, bottom = bottom)
padding += boneProperties.sectionDistance
}
} else {
path.addRoundRect(bounds, radii)
rayPath.addRoundRect(bounds, radii)
}
}
ShapeType.CIRCULAR -> {
path.addCircle(radius, radius, radius)
rayPath.addCircle(radius, radius, radius)
}
}
}
companion object {
@JvmStatic
fun build(view: View, properties: BoneProperties, manager: BoneManager): Bone {
return Bone(view, properties).apply {
this.elevation = view.elevation
this.boneProperties.enabledListener = {
if (!it) {
manager.dispose(this)
}
}
}
}
}
}
| 3 | Kotlin | 15 | 88 | 9608f59e023256419777c552f64ffc699433e070 | 6,438 | Skeleton-Bones | MIT License |
src/org/jetbrains/r/editor/mlcompletion/update/MachineLearningCompletionProjectOpenListener.kt | JetBrains | 214,212,060 | false | null | package org.jetbrains.r.editor.mlcompletion.update
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.roots.ProjectFileIndex
import org.jetbrains.concurrency.runAsync
import org.jetbrains.r.RFileType
import org.jetbrains.r.editor.mlcompletion.update.MachineLearningCompletionNotifications.showPopup
import org.jetbrains.r.settings.MachineLearningCompletionSettings
import java.util.concurrent.atomic.AtomicBoolean
class MachineLearningCompletionProjectOpenListener : ProjectManagerListener {
companion object {
val notifiedAnyProject = AtomicBoolean(false)
}
override fun projectOpened(project: Project) {
if (notifiedAnyProject.get() || !MachineLearningCompletionSettings.getInstance().state.isEnabled) {
return
}
runAsync {
if (isNotRProject(project) || !notifiedAnyProject.compareAndSet(false, true)) {
return@runAsync
}
val modelDownloaderService = MachineLearningCompletionDownloadModelService.getInstance()
modelDownloaderService.initiateUpdateCycle(isModal = false, reportIgnored = false) { (artifactsToUpdate, size) ->
if (artifactsToUpdate.isNotEmpty()) {
showPopup(project, artifactsToUpdate, size)
}
}
}
}
private fun isNotRProject(project: Project): Boolean =
ProjectFileIndex.getInstance(project).iterateContent { !FileTypeRegistry.getInstance().isFileOfType(it, RFileType) }
}
| 1 | Kotlin | 8 | 46 | e7e253fb683644c22d9dee8c68f6f884686e2910 | 1,537 | Rplugin | Apache License 2.0 |
src/main/kotlin/pl/wendigo/chrome/domain/domsnapshot/DOMSnapshotDomain.kt | caleb-allen | 166,148,335 | true | {"Kotlin": 661039, "Go": 11452, "HTML": 6118, "Shell": 1510, "Groovy": 824} | package pl.wendigo.chrome.domain.domsnapshot
/**
* This domain facilitates obtaining document snapshots with DOM, layout, and style information.
*/
class DOMSnapshotDomain internal constructor(private val connectionRemote: pl.wendigo.chrome.DebuggerProtocol) {
/**
* Disables DOM snapshot agent for the given page.
*/
fun disable(): io.reactivex.Single<pl.wendigo.chrome.ResponseFrame> {
return connectionRemote.runAndCaptureResponse("DOMSnapshot.disable", null, pl.wendigo.chrome.ResponseFrame::class.java).map {
it.value()
}
}
/**
* Enables DOM snapshot agent for the given page.
*/
fun enable(): io.reactivex.Single<pl.wendigo.chrome.ResponseFrame> {
return connectionRemote.runAndCaptureResponse("DOMSnapshot.enable", null, pl.wendigo.chrome.ResponseFrame::class.java).map {
it.value()
}
}
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
fun getSnapshot(input: GetSnapshotRequest): io.reactivex.Single<GetSnapshotResponse> {
return connectionRemote.runAndCaptureResponse("DOMSnapshot.getSnapshot", input, GetSnapshotResponse::class.java).map {
it.value()
}
}
/**
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
fun captureSnapshot(input: CaptureSnapshotRequest): io.reactivex.Single<CaptureSnapshotResponse> {
return connectionRemote.runAndCaptureResponse("DOMSnapshot.captureSnapshot", input, CaptureSnapshotResponse::class.java).map {
it.value()
}
}
/**
* Returns flowable capturing all DOMSnapshot domains events.
*/
fun events(): io.reactivex.Flowable<pl.wendigo.chrome.ProtocolEvent> {
return connectionRemote.captureAllEvents().map { it.value() }.filter {
it.protocolDomain() == "DOMSnapshot"
}
}
}
/**
* Represents request frame that can be used with DOMSnapshot.getSnapshot method call.
*
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
data class GetSnapshotRequest (
/**
* Whitelist of computed styles to return.
*/
val computedStyleWhitelist: List<String>,
/**
* Whether or not to retrieve details of DOM listeners (default false).
*/
val includeEventListeners: Boolean? = null,
/**
* Whether to determine and include the paint order index of LayoutTreeNodes (default false).
*/
val includePaintOrder: Boolean? = null,
/**
* Whether to include UA shadow tree in the snapshot (default false).
*/
val includeUserAgentShadowTree: Boolean? = null
)
/**
* Represents response frame for DOMSnapshot.getSnapshot method call.
*
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
data class GetSnapshotResponse(
/**
* The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document.
*/
val domNodes: List<DOMNode>,
/**
* The nodes in the layout tree.
*/
val layoutTreeNodes: List<LayoutTreeNode>,
/**
* Whitelisted ComputedStyle properties for each node in the layout tree.
*/
val computedStyles: List<ComputedStyle>
)
/**
* Represents request frame that can be used with DOMSnapshot.captureSnapshot method call.
*
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
data class CaptureSnapshotRequest (
/**
* Whitelist of computed styles to return.
*/
val computedStyles: List<String>
)
/**
* Represents response frame for DOMSnapshot.captureSnapshot method call.
*
* Returns a document snapshot, including the full DOM tree of the root node (including iframes,
template contents, and imported documents) in a flattened array, as well as layout and
white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is
flattened.
*/
data class CaptureSnapshotResponse(
/**
* The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document.
*/
val documents: List<DocumentSnapshot>,
/**
* Shared string table that all string properties refer to with indexes.
*/
val strings: List<String>
)
| 0 | Kotlin | 0 | 0 | be4e679384018724e133d3f8021bc1d1fa0c86f0 | 5,336 | chrome-reactive-kotlin | Apache License 2.0 |
app/src/main/java/com/sunnyweather/android/logic/model/RealtimeResponse.kt | Osiris-tevin | 600,701,667 | false | null | package com.sunnyweather.android.logic.model
import com.google.gson.annotations.SerializedName
/**
* 实时天气信息
*/
data class RealtimeResponse(val status: String, val result: Result){
data class Result(val realtime: Realtime)
/**
* @param skycon 天气状况
* @param temperature 温度
* @param airQuality 空气质量
*/
data class Realtime(val skycon: String, val temperature: Float, @SerializedName("air_quality") val airQuality: AirQuality)
data class AirQuality(val aqi: AQI)
/**
* AQI空气质量
* @param chn 污染物浓度
*/
data class AQI(val chn: Float)
} | 0 | Kotlin | 0 | 0 | 125e021eed28d39b37c6491e5e518804929d4992 | 600 | SunnyWeather | Apache License 2.0 |
src/main/kotlin/ar/edu/unq/mientradita/persistence/match/MatchRepositoryCustomImpl.kt | FeNixCrew | 403,775,742 | false | {"Kotlin": 153585} | package ar.edu.unq.mientradita.persistence.match
import ar.edu.unq.mientradita.model.Match
import ar.edu.unq.mientradita.model.Team
import ar.edu.unq.mientradita.model.Ticket
import ar.edu.unq.mientradita.model.user.Spectator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
import java.util.*
import javax.persistence.EntityManager
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Join
import javax.persistence.criteria.Predicate
import javax.persistence.criteria.Root
@Repository
class MatchRepositoryCustomImpl : MatchRepositoryCustom {
@Autowired
private lateinit var em: EntityManager
override fun searchNextMatchsBy(partialTeamName: String, isFinished: Boolean?, aDate: LocalDateTime): List<Match> {
val cb = em.criteriaBuilder
val cq: CriteriaQuery<Match> = cb.createQuery(Match::class.java)
val match: Root<Match> = cq.from(Match::class.java)
val matchWithHomeTeam = cb.like(cb.upper(match.get<Team>("home").get("name")), "%${partialTeamName.toUpperCase()}%")
val matchWithAwayTeam = cb.like(cb.upper(match.get<Team>("away").get("name")), "%${partialTeamName.toUpperCase()}%")
val predicates: MutableList<Predicate> = ArrayList()
val matchWithAnyTeam = cb.or(matchWithHomeTeam, matchWithAwayTeam)
predicates.add(matchWithAnyTeam)
if (isFinished != null) {
val expectedTime = aDate.minusMinutes(90)
if (isFinished) {
val finished = cb.lessThan(match.get("matchStartTime"), expectedTime)
predicates.add(finished)
} else {
val notFinished = cb.greaterThanOrEqualTo(match.get("matchStartTime"), expectedTime)
predicates.add(notFinished)
}
}
cq.where(*predicates.toTypedArray())
cq.orderBy(cb.asc(match.get<LocalDateTime>("matchStartTime")))
return em.createQuery(cq).resultList
}
override fun matchFromTeamBetweenDate(team: String, wantedStartTime: LocalDateTime): Optional<Match> {
val cb = em.criteriaBuilder
val cq: CriteriaQuery<Match> = cb.createQuery(Match::class.java)
val match: Root<Match> = cq.from(Match::class.java)
val matchWithHomeTeam = cb.like(cb.upper(match.get<Team>("home").get("name")), team.toUpperCase())
val matchWithAwayTeam = cb.like(cb.upper(match.get<Team>("away").get("name")), team.toUpperCase())
val playBefore = cb.between(match.get("matchStartTime"), wantedStartTime.minusHours(72), wantedStartTime.plusHours(72))
val matchWithAnyTeam = cb.or(matchWithHomeTeam, matchWithAwayTeam)
val condition = cb.and(matchWithAnyTeam, playBefore)
cq.where(condition)
val result = em.createQuery(cq).resultList
return if (result.size > 0) {
Optional.of(result[0])
} else {
Optional.empty()
}
}
override fun matchsOf(actualTime: LocalDateTime, plusDays: Long): List<Match> {
val cb = em.criteriaBuilder
val cq: CriteriaQuery<Match> = cb.createQuery(Match::class.java)
val match: Root<Match> = cq.from(Match::class.java)
val playAfter = cb.greaterThanOrEqualTo(match.get("matchStartTime"), actualTime)
val playBefore = cb.lessThan(match.get("matchStartTime"), actualTime.plusDays(plusDays))
val condition = cb.and(playAfter, playBefore)
cq.where(condition)
cq.orderBy(cb.asc(match.get<LocalDateTime>("matchStartTime")))
return em.createQuery(cq).resultList
}
override fun rememberOf(actualTime: LocalDateTime): List<MailAndMatch> {
val cb = em.criteriaBuilder
val cq: CriteriaQuery<MailAndMatch> = cb.createQuery(MailAndMatch::class.java)
val spectator: Root<Spectator> = cq.from(Spectator::class.java)
val spectatorAndTicket: Join<Spectator, Ticket> = spectator.join("tickets")
val playAfter = cb.greaterThanOrEqualTo(spectatorAndTicket.get<Match>("match").get("matchStartTime"), actualTime.plusHours(24))
val playBefore = cb.lessThan(spectatorAndTicket.get<Match>("match").get("matchStartTime"), actualTime.plusHours(48))
val condition = cb.and(playAfter, playBefore)
cq.where(condition)
cq.multiselect(
spectator.get<String>("email"),
spectatorAndTicket.get<Match>("match")
)
return em.createQuery(cq).resultList
}
override fun getSpectatorsAttendance(match: Match): List<SpectatorAttendance> {
val cb = em.criteriaBuilder
val cq: CriteriaQuery<SpectatorAttendance> = cb.createQuery(SpectatorAttendance::class.java)
val spectator: Root<Spectator> = cq.from(Spectator::class.java)
val spectatorAndTicket: Join<Spectator, Ticket> = spectator.join("tickets")
val isMatch = cb.equal(spectatorAndTicket.get<Match>("match").get<Long>("id"), match.id)
cq.where(isMatch)
cq.orderBy(cb.asc(spectator.get<Long>("dni")))
cq.multiselect(
spectator.get<Long>("id"),
spectator.get<Int>("dni"),
spectator.get<String>("name"),
spectator.get<String>("surname"),
spectatorAndTicket.get<LocalDateTime?>("presentTime")
)
return em.createQuery(cq).resultList
}
}
data class MailAndMatch(val mail: String, val match: Match)
data class SpectatorAttendance(
val id: Long,
val dni: Int,
val name: String,
val surname: String,
val presentTime: LocalDateTime?,
) | 0 | Kotlin | 0 | 1 | 3276ea3935a722ee6486ec6e2c08e224b6a4f87c | 5,702 | MiEntradita-backend | MIT License |
app/src/main/java/cu/suitetecsa/sdkandroid/presentation/balance/component/CustomLinearProgressBar.kt | suitetecsa | 676,273,066 | false | {"Kotlin": 113453, "HTML": 14924} | package cu.suitetecsa.sdkandroid.presentation.balance.component
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@Composable
fun CustomLinearProgressBar(
modifier: Modifier = Modifier,
color: Color = MaterialTheme.colorScheme.primary,
progress: Float? = null
) {
progress?.let {
LinearProgressIndicator(
progress = { progress },
modifier = modifier,
color = color,
trackColor = Color.Transparent
)
} ?: run {
LinearProgressIndicator(
modifier = modifier,
color = color,
trackColor = Color.Transparent
)
}
}
| 8 | Kotlin | 0 | 2 | b64d7a27e648d2b7d0172d26e32191f7b175b394 | 827 | sdk-android | MIT License |
onboarding/src/main/java/br/com/awaycard/onboarding/data/User.kt | faraujolf | 350,855,869 | false | null | package br.com.awaycard.onboarding.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class User(
@PrimaryKey val uid: Int = PK_INITIAL_VALUE,
@ColumnInfo(name = "nickname") val nickname: String
) {
companion object {
const val PK_INITIAL_VALUE = 0
}
} | 0 | Kotlin | 0 | 2 | bfe795f432e57a8d409820a48bca13ad2f9e92fc | 337 | away-card | MIT License |
feature/selector/src/main/java/com/wakeupgetapp/feature/selector/customExchangeDialog/NameCurrencyColumn.kt | wakeupgetapp | 805,482,568 | false | {"Kotlin": 197375} | package com.wakeupgetapp.feature.selector.customExchangeDialog
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.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wakeupgetapp.core.ui.common.CurrencyBaseText
import com.wakeupgetapp.core.ui.common.CurrencyEditableText
import com.wakeupgetapp.core.ui.common.CurrencyTextContainer
import com.wakeupgetapp.core.ui.common.util.PlaceComponentWithMeasuredWidth
import com.wakeupgetapp.core.ui.common.util.WidestCurrencyCodeText
import com.wakeupgetapp.feature.selector.R
@Composable
fun CurrencyNameColumn(
firstCurrencyName: MutableState<String>, secondCurrencyName: MutableState<String>
) {
Column(modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)) {
NameCurrencyRow(rowName = stringResource(id = R.string.dialog_base),
currencyName = firstCurrencyName.value,
hint = "USD",
onValueChange = {
if (it.length < 4) firstCurrencyName.value = it.uppercase()
})
Spacer(modifier = Modifier.size(16.dp))
NameCurrencyRow(rowName = stringResource(id = R.string.dialog_target),
currencyName = secondCurrencyName.value,
hint = "EUR",
onValueChange = {
if (it.length < 4) secondCurrencyName.value = it.uppercase()
})
}
}
@Composable
fun NameCurrencyRow(rowName: String, currencyName: String, hint: String, onValueChange: (String) -> Unit) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
CurrencyBaseText(
modifier = Modifier.weight(1f, fill = false),
text = rowName,
textAlign = TextAlign.Start,
color = Color.Black
)
CurrencyTextContainer(
borderColor = Color.DarkGray, modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.End)
) {
PlaceComponentWithMeasuredWidth(viewToMeasure = {
WidestCurrencyCodeText(fontSize = 30.sp)
}) {
CurrencyEditableText(
modifier = Modifier.width(it),
text = currencyName,
hint = hint,
textColor = Color.DarkGray,
hintColor = Color.Gray,
colorBrush = SolidColor(Color.DarkGray),
fontSize = 30.sp,
textAlign = TextAlign.Center,
onValueChange = onValueChange
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | a4e6dfe2f106b54faf62e06b6dc655e4575e9eb2 | 3,413 | CurrencyCalculator | Apache License 2.0 |
android/src/oldarch/FastOpencvSpec.kt | lukaszkurantdev | 837,538,282 | false | {"TypeScript": 111942, "C++": 108164, "Kotlin": 5440, "Ruby": 3278, "Objective-C": 2794, "Objective-C++": 2412, "CMake": 1662, "JavaScript": 1487, "C": 103, "Swift": 62} | package com.fastopencv
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.Promise
abstract class FastOpencvSpec internal constructor(context: ReactApplicationContext) :
ReactContextBaseJavaModule(context) {
abstract fun install(): Boolean
}
| 3 | TypeScript | 5 | 41 | e71b738337ea2dc87aec5b624db973e20d59056b | 347 | react-native-fast-opencv | MIT License |
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/api/chat/ChatAction.kt | vendelieu | 496,567,172 | false | {"Kotlin": 520294, "CSS": 356} | @file:Suppress("MatchingDeclarationName")
package eu.vendeli.tgbot.api.chat
import eu.vendeli.tgbot.interfaces.Action
import eu.vendeli.tgbot.types.chat.ChatAction
import eu.vendeli.tgbot.types.internal.TgMethod
import eu.vendeli.tgbot.utils.getReturnType
class SendChatAction(action: ChatAction, messageThreadId: Int? = null) : Action<Boolean>() {
override val method = TgMethod("sendChatAction")
override val returnType = getReturnType()
init {
parameters["action"] = action
if (messageThreadId != null) parameters["message_thread_id"] = messageThreadId
}
}
@Suppress("NOTHING_TO_INLINE")
inline fun chatAction(action: ChatAction, messageThreadId: Int? = null) = SendChatAction(action, messageThreadId)
inline fun chatAction(messageThreadId: Int? = null, block: () -> ChatAction) = chatAction(block(), messageThreadId)
inline fun sendChatAction(messageThreadId: Int? = null, block: () -> ChatAction) = chatAction(block(), messageThreadId)
@Suppress("NOTHING_TO_INLINE")
inline fun sendChatAction(action: ChatAction, messageThreadId: Int? = null) = chatAction(action, messageThreadId)
| 5 | Kotlin | 6 | 116 | 744bbcf1fe96fcb52c50ddf11cf2dd9a3f98c4b5 | 1,126 | telegram-bot | Apache License 2.0 |
app/src/main/java/com/teamnexters/mosaic/data/local/RealmSchedulers.kt | ojh102 | 166,809,463 | false | null | package com.teamnexters.mosaic.data.local
import android.os.HandlerThread
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
object RealmSchedulers {
private val REALM_HANDLER_THREAD: HandlerThread = createAndStart("MosaicRealm")
private val realmIO: Scheduler = AndroidSchedulers.from(REALM_HANDLER_THREAD.looper)
private fun createAndStart(name: String): HandlerThread {
val handlerThread = HandlerThread(name)
handlerThread.start()
return handlerThread
}
@Synchronized
fun realmIO(): Scheduler {
return realmIO
}
} | 0 | Kotlin | 0 | 0 | 16b69be0d8e82a235222699d9bb38daf44fdac42 | 618 | Mosaic_Android | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.