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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
composeApp/src/commonMain/kotlin/presentation/list/ListContent.kt
|
yeldar-nurpeissov
| 817,743,263
| false
|
{"Kotlin": 12745, "Swift": 621, "HTML": 347, "CSS": 102}
|
package presentation.list
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.arkivanov.decompose.extensions.compose.subscribeAsState
@Composable
fun ListContent(
component: ListComponent,
modifier: Modifier = Modifier,
) {
val state by component.model.subscribeAsState()
Scaffold(
modifier = modifier,
topBar = { TopAppBar(title = { Text("List") }) }
) { paddingValues ->
LazyColumn(
state = rememberLazyListState(),
modifier = Modifier.padding(paddingValues)
) {
items(state) { post ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { component.onPostClicked(post) }
.padding(16.dp)
) {
Text(post.title)
}
}
}
}
}
| 0
|
Kotlin
|
1
| 1
|
99077f1248481967c0661f0391df76512c945899
| 1,113
|
decompose-quick-guide
|
Apache License 2.0
|
app/src/main/java/com/bikcode/rickandmortycompose/domain/use_case/GetSelectedCharacterUC.kt
|
Bikcodeh
| 412,662,765
| false
|
{"Kotlin": 120155}
|
package com.bikcode.rickandmortycompose.domain.use_case
import com.bikcode.rickandmortycompose.domain.model.Character
import com.bikcode.rickandmortycompose.domain.repository.CharacterRepository
import javax.inject.Inject
class GetSelectedCharacterUC @Inject constructor(private val characterRepository: CharacterRepository) {
suspend operator fun invoke(characterId: Int): Character? {
return characterRepository.getSelectedCharacter(characterId = characterId)
}
}
| 0
|
Kotlin
|
1
| 0
|
65f77b49df3ed70b7469dc69deaed8bc56fdef9a
| 484
|
RickAndMortyCompose
|
MIT License
|
app/src/main/java/com/example/calculatorapp/enums.kt
|
thisishisham1
| 689,881,117
| false
|
{"Kotlin": 35118}
|
package com.example.calculatorapp
enum class ButtonType {
LOW, MEDIUM, HIGH
}
| 0
|
Kotlin
|
0
| 0
|
e59aaf88d41c8578faa1bb002153e1b2b3fc90d8
| 82
|
Calculator-App
|
MIT License
|
app/src/main/kotlin/no/nav/paw/arbeidssokerregisteret/app/funksjoner/SkrivNyTilstandTilDb.kt
|
navikt
| 698,089,423
| false
|
{"Kotlin": 30219}
|
package no.nav.paw.arbeidssokerregisteret.app.funksjoner
import no.nav.paw.arbeidssokerregisteret.app.PeriodeTilstandV1
import org.apache.kafka.streams.processor.api.Processor
import org.apache.kafka.streams.processor.api.ProcessorContext
import org.apache.kafka.streams.processor.api.Record
import org.apache.kafka.streams.state.KeyValueStore
import org.slf4j.LoggerFactory
enum class Operasjon{
SLETT, OPPRETT_ELLER_OPPDATER
}
class SkrivNyTilstandTilDb(
private val tilstandDbNavn: String,
private val oppdater: (PeriodeTilstandV1) -> Operasjon
): Processor<String, PeriodeTilstandV1, String, PeriodeTilstandV1> {
private var tilstandsDb: KeyValueStore<String, PeriodeTilstandV1>? = null
private var context: ProcessorContext<String, PeriodeTilstandV1>? = null
override fun init(context: ProcessorContext<String, PeriodeTilstandV1>?) {
super.init(context)
this.context = context
tilstandsDb = context?.getStateStore(tilstandDbNavn)
}
override fun process(record: Record<String, PeriodeTilstandV1>?) {
if (record == null) return
process(
requireNotNull(context) { "Context er ikke initialisert" },
requireNotNull(tilstandsDb) { "TilstandsDb er ikke initialisert" },
record
)
}
private fun process(
ctx: ProcessorContext<String, PeriodeTilstandV1>,
db: KeyValueStore<String, PeriodeTilstandV1>,
record: Record<String, PeriodeTilstandV1>
) {
LoggerFactory.getLogger(this::class.java).info("Oppdaterer tilstand: ${record.value()}")
val operasjon = oppdater(record.value())
when(operasjon){
Operasjon.OPPRETT_ELLER_OPPDATER -> db.put(record.key(), record.value())
Operasjon.SLETT -> db.delete(record.key())
}
LoggerFactory.getLogger(this::class.java).info("Videresender tilstand: ${record.value()}")
ctx.forward(record)
}
}
| 0
|
Kotlin
|
0
| 0
|
0791af57c6bd7cdac3adbd7034cc99a0e9dae58c
| 1,957
|
paw-arbeidssokerregisteret-event-prosessor
|
MIT License
|
app/src/main/java/com/macisdev/mileageapp/database/NoteDao.kt
|
miguelamacias
| 442,502,832
| false
|
{"Kotlin": 138545}
|
package com.macisdev.mileageapp.database
import androidx.lifecycle.LiveData
import androidx.room.*
import com.macisdev.mileageapp.model.Note
@Dao
interface NoteDao {
@Query("SELECT * FROM Note WHERE id = (:id)")
fun getNote(id: String): LiveData<Note>
@Query("SELECT * FROM Note WHERE vehiclePlateNumber = (:vehiclePlateNumber) ORDER BY date DESC")
fun getNotesByVehicle(vehiclePlateNumber: String) : LiveData<List<Note>>
@Query("SELECT * FROM Note WHERE vehiclePlateNumber = (:vehiclePlateNumber) AND type = (:type) ORDER BY date DESC")
fun getNotesByVehicleAndType(vehiclePlateNumber: String, type: String) : LiveData<List<Note>>
@Insert
fun addNote(note: Note)
@Update
fun updateNote(note: Note)
@Delete
fun deleteNote(note: Note)
}
| 0
|
Kotlin
|
1
| 1
|
0e7494a171f4aa49c136a633cea8c780ec6440a7
| 791
|
MileageApp
|
MIT License
|
CleanArchitecture/src/main/java/com/jesen/cleanarchitecture/feature_note/domain/use_case/DeleteNote.kt
|
Jesen0823
| 388,484,600
| false
| null |
package com.jesen.cleanarchitecture.feature_note.domain.use_case
import com.jesen.cleanarchitecture.feature_note.domain.model.NoteModel
import com.jesen.cleanarchitecture.feature_note.domain.repository.NoteRepository
class DeleteNote(
private val repository: NoteRepository
) {
suspend operator fun invoke(note: NoteModel) {
repository.deleteNote(note)
}
}
| 0
|
Kotlin
|
4
| 4
|
6a130fe009f7ab3008db0b847d80ca6412278738
| 379
|
UseCompose
|
Apache License 2.0
|
Android/application/app/src/main/java/com/arpadfodor/stolenvehicledetector/android/app/view/utils/MasterFragment.kt
|
aaronfodor
| 249,640,199
| false
|
{"Jupyter Notebook": 16761258, "Kotlin": 349389, "TeX": 234852, "Lua": 17047, "Makefile": 2005, "Batchfile": 321, "Shell": 9}
|
package com.arpadfodor.stolenvehicledetector.android.app.view.utils
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.arpadfodor.stolenvehicledetector.android.app.R
import com.arpadfodor.stolenvehicledetector.android.app.viewmodel.utils.MasterDetailViewModel
import com.arpadfodor.stolenvehicledetector.android.app.model.repository.dataclasses.UserRecognition
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.fragment_master.*
class MasterFragment : AppFragment(){
companion object{
val TAG = MasterFragment::class.java.simpleName
lateinit var viewModel: MasterDetailViewModel
var title = ""
var sendSucceedSnackBarText = ""
var sendFailedSnackBarText = ""
var alreadySentSnackBarText = ""
var deletedSnackBarText = ""
var deleteFailedSnackBarText = ""
fun setParams(viewModel: MasterDetailViewModel, title: String,
sendSucceedSnackBarText: String, sendFailedSnackBarText: String, alreadySentSnackBarText: String,
deletedSnackBarText: String, deleteFailedSnackBarText: String){
this.viewModel = viewModel
this.title = title
this.sendSucceedSnackBarText = sendSucceedSnackBarText
this.sendFailedSnackBarText = sendFailedSnackBarText
this.alreadySentSnackBarText = alreadySentSnackBarText
this.deletedSnackBarText = deletedSnackBarText
this.deleteFailedSnackBarText = deleteFailedSnackBarText
}
}
private lateinit var adapter: RecognitionListAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_master, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?){
super.onViewCreated(view, savedInstanceState)
recognition_list_title.text = title
adapter = RecognitionListAdapter(requireContext(), createEventListener())
recognition_list.adapter = adapter
recognition_list.layoutManager = LinearLayoutManager(requireContext())
}
override fun subscribeToViewModel() {
// Create the observer
val listObserver = Observer<List<UserRecognition>> { list ->
adapter.submitList(list)
adapter.notifyDataSetChanged()
}
// Observe the LiveData, passing in this viewLifeCycleOwner as the LifecycleOwner and the observer
viewModel.recognitions.observe(requireActivity(), listObserver)
}
override fun appearingAnimations(){}
override fun subscribeListeners(){}
override fun unsubscribe(){}
private fun createEventListener() : RecognitionEventListener {
return RecognitionEventListener(
editClickListener = { id ->
viewModel.selectRecognition(id)
},
sendClickListener = { id ->
val recognition = DetailFragment.viewModel.getRecognitionById(id)
recognition?.let{
if(recognition.isSent){
val currentContext = context
val currentView = view
currentContext ?: return@RecognitionEventListener
currentView ?: return@RecognitionEventListener
AppSnackBarBuilder.buildInfoSnackBar(
currentContext,
currentView, alreadySentSnackBarText,
Snackbar.LENGTH_SHORT
).show()
}
else{
viewModel.sendRecognition(id) { isSuccess ->
val currentContext = context
val currentView = view
currentContext ?: return@sendRecognition
currentView ?: return@sendRecognition
when (isSuccess) {
true -> {
AppSnackBarBuilder.buildSuccessSnackBar(
currentContext,
currentView, sendSucceedSnackBarText,
Snackbar.LENGTH_SHORT
).show()
}
else -> {
AppSnackBarBuilder.buildAlertSnackBar(
currentContext,
currentView, sendFailedSnackBarText,
Snackbar.LENGTH_SHORT
).show()
}
}
}
}
}
},
deleteClickListener = { id ->
viewModel.deleteRecognition(id){ isSuccess ->
val currentContext = context
val currentView = view
currentContext ?: return@deleteRecognition
currentView ?: return@deleteRecognition
when (isSuccess) {
true -> {
AppSnackBarBuilder.buildInfoSnackBar(
currentContext,
currentView, deletedSnackBarText,
Snackbar.LENGTH_SHORT
).show()
}
else -> {
AppSnackBarBuilder.buildAlertSnackBar(
currentContext,
currentView, deleteFailedSnackBarText,
Snackbar.LENGTH_SHORT
).show()
}
}
}
}
)
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
ff455c0daa2ca3bcf1f38b9f17833db8f0d449a0
| 6,247
|
StolenVehicleDetector
|
MIT License
|
src/test/kotlin/io/littlelanguages/mil/compiler/CompilerTests.kt
|
littlelanguages
| 393,599,824
| false
|
{"Kotlin": 89278, "C": 44308, "Shell": 1631, "Makefile": 328}
|
package io.littlelanguages.mil.compiler
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.style.scopes.FunSpecContainerContext
import io.kotest.matchers.shouldBe
import io.littlelanguages.data.Either
import io.littlelanguages.data.Left
import io.littlelanguages.data.Right
import io.littlelanguages.mil.Errors
import io.littlelanguages.mil.compiler.llvm.Context
import io.littlelanguages.mil.compiler.llvm.Module
import io.littlelanguages.mil.compiler.llvm.targetTriple
import io.littlelanguages.mil.dynamic.Binding
import io.littlelanguages.mil.dynamic.translate
import io.littlelanguages.mil.static.Scanner
import io.littlelanguages.mil.static.parse
import org.bytedeco.llvm.LLVM.LLVMValueRef
import org.yaml.snakeyaml.Yaml
import java.io.*
private val yaml = Yaml()
class CompilerTests : FunSpec({
context("Conformance Tests") {
val context = Context(targetTriple())
val content = File("./src/test/kotlin/io/littlelanguages/mil/compiler/compiler.yaml").readText()
val scenarios: Any = /*emptyList<String>() */ yaml.load(content)
if (scenarios is List<*>) {
parserConformanceTest(builtinBindings, context, this, scenarios)
}
context.dispose()
}
})
fun compile(builtinBindings: List<Binding<CompileState, LLVMValueRef>>, context: Context, input: String): Either<List<Errors>, Module> =
parse(Scanner(StringReader(input))) mapLeft { listOf(it) } andThen { translate(builtinBindings, it) } andThen { compile(context, "./test.mlsp", it) }
suspend fun parserConformanceTest(
builtinBindings: List<Binding<CompileState, LLVMValueRef>>,
context: Context,
ctx: FunSpecContainerContext,
scenarios: List<*>
) {
scenarios.forEach { scenario ->
val s = scenario as Map<*, *>
val nestedScenario = s["scenario"] as Map<*, *>?
if (nestedScenario == null) {
val name = s["name"] as String
val input = s["input"] as String
val output = s["output"]
ctx.test(name) {
val lhs = when (val llvmState = compile(builtinBindings, context, input)) {
is Left ->
llvmState.left.joinToString("")
is Right -> {
val module = llvmState.right
// LLVM.LLVMDumpModule(module)
// System.err.println(LLVM.LLVMPrintModuleToString(module).string)
module.writeBitcodeToFile("test.bc")
runCommand(arrayOf("clang", "test.bc", "src/main/c/lib.o", "./src/main/c/main.o", "./bdwgc/gc.a", "-o", "test.bin"))
val commandOutput = runCommand(arrayOf("./test.bin"))
module.dispose()
commandOutput
}
}
val rhs =
(output as Any).toString().trim()
lhs shouldBe rhs
}
} else {
val name = nestedScenario["name"] as String
val tests = nestedScenario["tests"] as List<*>
ctx.context(name) {
parserConformanceTest(builtinBindings, context, this, tests)
}
}
}
}
private fun runCommand(commands: Array<String>): String {
val rt = Runtime.getRuntime()
val proc = rt.exec(commands)
val sb = StringBuffer()
fun readInputStream(input: InputStream) {
BufferedReader(InputStreamReader(input)).use { reader ->
var s: String?
while (reader.readLine().also { s = it } != null) {
sb.append(s)
sb.append("\n")
}
}
}
readInputStream(proc.inputStream)
readInputStream(proc.errorStream)
return sb.toString().trim()
}
| 0
|
Kotlin
|
0
| 2
|
56bf90123d9e512410e83c254f6fd4efff1c6ea5
| 3,818
|
ll-mini-ilisp-kotlin-llvm
|
MIT License
|
src/main/kotlin/com/mt/notion/common/request/Direction.kt
|
motui
| 479,945,371
| false
| null |
package com.mt.notion.common.request
/**
* Direction
*
* @author it.motui
*/
enum class Direction constructor(private val value: String) {
Ascending("ascending"),
Descending("descending"),
;
override fun toString(): String = value
}
| 0
|
Kotlin
|
0
| 1
|
80b7b256d8d7c34b15cf79d1e5f539c8ef4736b4
| 256
|
notion-sdk-kotlin
|
MIT License
|
app/src/main/java/xyz/fairportstudios/popularin/interfaces/DeleteCommentRequestCallback.kt
|
rgxcp
| 277,228,278
| false
| null |
package xyz.fairportstudios.popularin.interfaces
interface DeleteCommentRequestCallback {
fun onSuccess()
fun onError(message: String)
}
| 0
|
Kotlin
|
0
| 0
|
ac82b65d5f43d07b64aa5010218c663983c839cb
| 145
|
PopularinKotlin
|
MIT License
|
travelmaker_android/app/src/main/java/com/gumibom/travelmaker/ui/main/myrecord/ItemClickListener.kt
|
serotonins
| 808,489,421
| false
|
{"Kotlin": 481004, "Java": 174550, "HTML": 4622, "Dockerfile": 516}
|
package com.gumibom.travelmaker.ui.main.myrecord
import android.view.View
interface ItemClickListener {
fun moveRecordDetail(pamphletId : Long, view : View)
}
| 0
|
Kotlin
|
0
| 0
|
eb8dee9dd6979722026a6d20fab96b56c4a63b1b
| 164
|
TravelMaker
|
MIT License
|
permisos-gradle/src/main/java/cn/nikeo/permisos/gradle/PermisosClassTransformer.kt
|
nikeorever
| 309,748,994
| false
| null |
package cn.nikeo.permisos.gradle
import javassist.ClassPool
import javassist.CtClass
import javassist.Modifier
import javassist.bytecode.CodeIterator
import javassist.bytecode.Opcode
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.util.zip.ZipInputStream
typealias CodeArray = javassist.bytecode.ByteArray // Avoids conflict with Kotlin's stdlib ByteArray
internal class PermisosClassTransformer(
val taskName: String,
allInputs: List<File>,
private val sourceRootOutputDir: File,
private val copyNonTransformed: Boolean
) {
private val logger = LoggerFactory.getLogger(PermisosClassTransformer::class.java)
// A ClassPool created from the given input files, this allows us to use the higher
// level Javaassit APIs, but requires class parsing/loading.
private val classPool: ClassPool = ClassPool(true).also { pool ->
allInputs.forEach {
pool.appendClassPath(it.path)
}
}
init {
sourceRootOutputDir.mkdirs()
}
/**
* Transforms the classes inside the jar and copies re-written class files if and only if they are
* transformed.
*
* @param inputFile The jar file to transform, must be a jar.
* @return true if at least one class within the jar was transformed.
*/
fun transformJarContents(inputFile: File): Boolean {
require(inputFile.isJarFile()) {
"Invalid file, '$inputFile' is not a jar."
}
// Validate transform is not applied to a jar when copying is enabled, meaning the transformer
// is being used in the Android transform API pipeline which does not need to transform jars
// and handles copying them.
check(!copyNonTransformed) {
"Transforming a jar is not supported with 'copyNonTransformed'."
}
var transformed = false
ZipInputStream(FileInputStream(inputFile)).use { input ->
var entry = input.nextEntry
while (entry != null) {
if (entry.isClassFile()) {
val clazz = classPool.makeClass(input, false)
transformed = transformClassToOutput(clazz) || transformed
}
entry = input.nextEntry
}
}
return transformed
}
/**
* Transform a single class file.
*
* @param inputFile The file to transform, must be a class file.
* @return true if the class file was transformed.
*/
fun transformFile(inputFile: File): Boolean {
check(inputFile.isClassFile()) {
"Invalid file, '$inputFile' is not a class."
}
val clazz = inputFile.inputStream().use { classPool.makeClass(it, false) }
return transformClassToOutput(clazz)
}
private fun transformClassToOutput(clazz: CtClass): Boolean {
val transformed = transformClass(clazz)
if (transformed || copyNonTransformed) {
clazz.writeFile(sourceRootOutputDir.path)
}
return transformed
}
private fun transformClass(clazz: CtClass): Boolean {
if (!clazz.hasAnnotation(PERMISOS_ANNOTATION)) {
// Not a Permisos annotated class, don't do anything.
return false
}
// TODO(user): Handle classes with '$' in their name if they do become an issue.
val superclassName = clazz.classFile.superclass
val permisosSuperclassName =
clazz.packageName + ".Permisos_" + clazz.simpleName.replace("$", "_")
logger.info(
"[$taskName] Transforming ${clazz.name} to extend $permisosSuperclassName instead of " +
"$superclassName."
)
val permisosSuperclass = classPool.get(permisosSuperclassName)
clazz.superclass = permisosSuperclass
transformSuperMethodCalls(clazz, superclassName, permisosSuperclassName)
return true
}
/**
* Iterates over each declared method, finding in its bodies super calls. (e.g. super.onCreate())
* and rewrites the method reference of the invokespecial instruction to one that uses the new
* superclass.
*
* The invokespecial instruction is emitted for code that between other things also invokes a
* method of a superclass of the current class. The opcode invokespecial takes two operands, each
* of 8 bit, that together represent an address in the constant pool to a method reference. The
* method reference is computed at compile-time by looking the direct superclass declaration, but
* at runtime the code behaves like invokevirtual, where as the actual method invoked is looked up
* based on the class hierarchy.
*
* However, it has been observed that on APIs 19 to 22 the Android Runtime (ART) jumps over the
* direct superclass and into the method reference class, causing unexpected behaviours.
* Therefore, this method performs the additional transformation to rewrite direct super call
* invocations to use a method reference whose class in the pool is the new superclass. Note that
* this is not necessary for constructor calls since the Javassist library takes care of those.
*
* @see: https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-6.html#jvms-6.5.invokespecial
* @see: https://source.android.com/devices/tech/dalvik/dalvik-bytecode
*/
private fun transformSuperMethodCalls(
clazz: CtClass,
oldSuperclassName: String,
newSuperclassName: String
) {
val constantPool = clazz.classFile.constPool
clazz.declaredMethods
.filter {
it.methodInfo.isMethod &&
!Modifier.isStatic(it.modifiers) &&
!Modifier.isAbstract(it.modifiers) &&
!Modifier.isNative(it.modifiers)
}
.forEach { method ->
val codeAttr = method.methodInfo.codeAttribute
val code = codeAttr.code
codeAttr.iterator().forEachInstruction { index, opcode ->
// We are only interested in 'invokespecial' instructions.
if (opcode != Opcode.INVOKESPECIAL) {
return@forEachInstruction
}
// If the method reference of the instruction is not using the old superclass then we
// should not rewrite it.
val methodRef = CodeArray.readU16bit(code, index + 1)
val currentClassRef = constantPool.getMethodrefClassName(methodRef)
if (currentClassRef != oldSuperclassName) {
return@forEachInstruction
}
val nameAndTypeRef = constantPool.getMethodrefNameAndType(methodRef)
val newSuperclassRef = constantPool.addClassInfo(newSuperclassName)
val newMethodRef =
constantPool.addMethodrefInfo(newSuperclassRef, nameAndTypeRef)
logger.info(
"[$taskName] Redirecting an invokespecial in " +
"${clazz.name}.${method.name}:${method.signature} at code index $index from " +
"method ref #$methodRef to #$newMethodRef."
)
CodeArray.write16bit(newMethodRef, code, index + 1)
}
}
}
// Iterate over each instruction in a CodeIterator.
private fun CodeIterator.forEachInstruction(body: CodeIterator.(Int, Int) -> Unit) {
while (hasNext()) {
val index = next()
this.body(index, byteAt(index))
}
}
companion object {
private const val PERMISOS_ANNOTATION = "cn.nikeo.permisos.weaving.Permisos"
}
}
| 0
|
Kotlin
|
1
| 3
|
f0004212da13d9f0dbc5239dc6fe6b79b874a287
| 7,885
|
permisos
|
Apache License 2.0
|
src/main/kotlin/se/svt/oss/mediaanalyzer/ffprobe/FfprobeAnalyzer.kt
|
svt
| 285,523,429
| false
|
{"Kotlin": 47704}
|
// SPDX-FileCopyrightText: 2020 Sveriges Television AB
//
// SPDX-License-Identifier: Apache-2.0
package se.svt.oss.mediaanalyzer.ffprobe
import com.fasterxml.jackson.databind.ObjectMapper
import se.svt.oss.mediaanalyzer.util.ProcessUtil
class FfprobeAnalyzer
@JvmOverloads constructor(private val objectMapper: ObjectMapper = ObjectMapper().findAndRegisterModules()) {
fun analyze(file: String, ffprobeInputParams: LinkedHashMap<String, String?>): ProbeResult {
val command = buildList<String> {
add("ffprobe")
add("-v")
add("quiet")
add("-of")
add("json")
add("-show_streams")
add("-show_format")
add("-show_error")
ffprobeInputParams.forEach { (key, value) ->
add("-$key")
value?.let { add(it) }
}
add(file)
}
val (exitCode, probeResult) = ProcessUtil.runAndParse<ProbeResult>(
objectMapper,
*command.toTypedArray()
)
if (exitCode != 0 || probeResult.error != null) {
val message = probeResult.error?.string ?: "exitcode: $exitCode"
throw RuntimeException("ffprobe failed for $file: $message")
}
return probeResult
}
@JvmOverloads
fun isInterlaced(file: String, videoIndex: Int = 0, ffprobeInputParams: LinkedHashMap<String, String?>): Boolean {
val command = buildList<String> {
add("ffprobe")
add("-v")
add("quiet")
add("-of")
add("json")
add("-read_intervals")
add("%+5")
add("-select_streams")
add("v:$videoIndex")
add("-show_entries")
add("frame=interlaced_frame")
add("-show_error")
ffprobeInputParams.forEach { (key, value) ->
add("-$key")
value?.let { add(it) }
}
add(file)
}
val (exitCode, probeResult) = ProcessUtil.runAndParse<ProbeResult>(
objectMapper,
*command.toTypedArray()
)
if (exitCode != 0 || probeResult.error != null) {
val message = probeResult.error?.string ?: "exitcode: $exitCode"
throw RuntimeException("ffprobe failed for $file: $message")
}
if (probeResult.frames.isEmpty()) {
throw RuntimeException("Error parsing ffprobe output!")
}
val (interlaced, noninterlaced) = probeResult.frames.partition { it.interlaced_frame }
return interlaced.size > noninterlaced.size
}
}
| 1
|
Kotlin
|
2
| 16
|
db2df5d7bc692f74a2d3b61320f2cd785723bfa9
| 2,649
|
media-analyzer
|
Apache License 2.0
|
app/src/main/java/caios/android/material_visualizer_sample/MainActivity.kt
|
matsumo0922
| 482,550,958
| false
|
{"Kotlin": 9791}
|
package caios.android.material_visualizer_sample
import android.graphics.Point
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Size
import android.view.Window
import android.view.animation.LinearInterpolator
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import caios.android.material_visualizer.VisualizerAdapter
import caios.android.material_visualizer.VisualizerCallback
import caios.android.material_visualizer_sample.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val random = Random(System.currentTimeMillis())
binding.visualizer.setCallback(object : VisualizerCallback() {
override fun onDrawFrame(index: Int): Float {
return random.nextFloat() * 50
}
})
binding.recButton.setOnClickListener {
if(binding.visualizer.isActive()) {
binding.visualizer.stop()
} else {
binding.visualizer.start()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b2b9c2eaf8a228418fd30fcd14d36b0611773b9f
| 1,323
|
MaterialVisualizer
|
MIT License
|
examples/auth/flutter-mfa/android/app/src/main/kotlin/com/example/mfa_app/MainActivity.kt
|
supabase
| 214,587,193
| false
|
{"TypeScript": 8573478, "MDX": 4900669, "JavaScript": 958992, "CSS": 179592, "SCSS": 77562, "PLpgSQL": 17498, "Makefile": 8137, "Dockerfile": 2231, "Python": 1355, "Shell": 798}
|
package com.example.mfa_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 461
|
TypeScript
|
5585
| 61,023
|
8e4a094f2639202c725d27409d6585e7026b1d6e
| 124
|
supabase
|
Apache License 2.0
|
project/common/src/main/kotlin/ink/ptms/artifex/script/ScriptTaskEvaluator.kt
|
TabooLib
| 492,563,163
| false
|
{"Kotlin": 246610, "Java": 3390}
|
package ink.ptms.artifex.script
import java.util.function.Consumer
/**
* Artifex
* ink.ptms.artifex.script.ScriptTaskEvaluator
*
* 脚本执行任务
*
* @author 坏黑
* @since 2022/6/13 22:59
*/
interface ScriptTaskEvaluator {
/**
* 是否挂载脚本(默认 false)
*/
fun mount(mount: Boolean): ScriptTaskEvaluator
/**
* 是否打印挂载信息(默认 true)
*/
fun loggingMounted(loggingMounted: Boolean): ScriptTaskEvaluator
/**
* 是否打印释放信息(默认 true)
*/
fun loggingReleased(loggingReleased: Boolean): ScriptTaskEvaluator
/**
* 创建执行后回调函数
*/
fun afterEval(func: Consumer<Script>): ScriptTaskEvaluator
/**
* 通过 [ScriptRuntimeProperty] 执行脚本,返回执行结果
*/
fun apply(property: ScriptRuntimeProperty, report: Consumer<ScriptResult.Diagnostic>? = null): Boolean
}
| 1
|
Kotlin
|
7
| 24
|
eeb2e09552ad1d7bc67f82d56191be8693b329af
| 807
|
artifex
|
Creative Commons Zero v1.0 Universal
|
android/src/main/kotlin/com/qkd/kdplayer/KDPlayerService.kt
|
quangkhuongduy0195
| 436,851,270
| false
| null |
package com.qkd.kdplayer
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.MediaMetadata
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.metadata.Metadata
import com.google.android.exoplayer2.metadata.MetadataOutput
import com.google.android.exoplayer2.metadata.icy.IcyInfo
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.ui.PlayerNotificationManager.BitmapCallback
import com.google.android.exoplayer2.ui.PlayerNotificationManager.MediaDescriptionAdapter
import kotlinx.coroutines.*
import java.net.URL
import kotlin.reflect.KParameter
class KDPlayerService : Service(), Player.Listener, MetadataOutput {
companion object {
const val KdPlayer = "KdPlayer"
const val NOTIFICATION_CHANNEL_ID = "kd_channel_id"
const val NOTIFICATION_ID = 1
const val ACTION_STATE_CHANGED = "state_changed"
const val ACTION_STATE_CHANGED_EXTRA = "state"
const val ACTION_NEW_METADATA = "matadata_changed"
const val ACTION_NEW_METADATA_EXTRA = "matadata"
const val ACTION_CURRENT_CHANGED = "current_changed"
const val ACTION_CURRENT_CHANGED_EXTRA = "current"
const val ACTION_DURATION_CHANGED = "duration_changed"
const val ACTION_DURATION_CHANGED_EXTRA = "duration"
}
var metadataArtwork: Bitmap? = null
private var durationSet : Boolean = false
private var defaultArtwork: Bitmap? = null
private var playerNotificationManager: PlayerNotificationManager? = null
private var notificationTitle = ""
private var isForegroundService = false
private var metadataList: MutableList<String>? = null
private var localBinder = LocalBinder()
private val handler = Handler(Looper.getMainLooper())
private val player: ExoPlayer by lazy {
ExoPlayer.Builder(this).build()
}
private val localBroadcastManager: LocalBroadcastManager by lazy {
LocalBroadcastManager.getInstance(this)
}
inner class LocalBinder : Binder() {
// Return this instance of RadioPlayerService so clients can call public methods.
fun getService(): KDPlayerService = this@KDPlayerService
}
override fun onBind(intent: Intent?): IBinder {
return localBinder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
player.repeatMode = Player.REPEAT_MODE_OFF
player.addListener(this)
// player.addMetadataOutput(this)
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
playerNotificationManager?.setPlayer(null)
player.release()
android.os.Process.killProcess(android.os.Process.myPid())
}
fun setMediaItem(streamTitle: String, streamUrl: String) {
Log.d(KdPlayer, "setMediaItem");
val mediaItems: List<MediaItem> = runBlocking {
GlobalScope.async {
parseUrls(streamUrl).map { MediaItem.fromUri(it) }
}.await()
}
metadataList = null
defaultArtwork = null
metadataArtwork = null
notificationTitle = streamTitle
playerNotificationManager?.invalidate() ?: createNotificationManager()
sentCurrentPosition(0)
sendDuration(0);
player.stop()
player.clearMediaItems()
player.seekTo(0)
player.addMediaItems(mediaItems)
player.playWhenReady = true
player.pause()
}
fun setDefaultArtwork(image: Bitmap) {
defaultArtwork = image
playerNotificationManager?.invalidate()
}
fun play() {
handler.removeCallbacks(updateProgressAction)
handler.post(updateProgressAction)
player.playWhenReady = true
}
fun pause() {
handler.removeCallbacks(updateProgressAction)
player.playWhenReady = false
}
fun stop() {
player.stop()
}
fun setSeekTo(value: Long){
player.seekTo(value)
}
/** Extract URLs from user link. */
private fun parseUrls(url: String): List<String> {
var urls: List<String> = emptyList()
urls = when (url.substringAfterLast(".")) {
"pls" -> {
URL(url).readText().lines().filter {
it.contains("=http") }.map {
it.substringAfter("=")
}
}
"m3u" -> {
val content = URL(url).readText().trim()
listOf(content)
}
else -> {
listOf(url)
}
}
return urls
}
/** Creates a notification manager for background playback. */
private fun createNotificationManager() {
val mediaDescriptionAdapter = object : MediaDescriptionAdapter {
override fun createCurrentContentIntent(player: Player): PendingIntent? {
return null
}
override fun getCurrentLargeIcon(player: Player, callback: BitmapCallback): Bitmap? {
metadataArtwork = downloadImage(metadataList?.get(2))
if (metadataArtwork != null) callback.onBitmap(metadataArtwork!!)
return defaultArtwork
}
override fun getCurrentContentTitle(player: Player): String {
return metadataList?.get(0) ?: notificationTitle
}
override fun getCurrentContentText(player: Player): String? {
return metadataList?.get(1)
}
}
val notificationListener = object : PlayerNotificationManager.NotificationListener {
override fun onNotificationPosted(notificationId: Int, notification: Notification, ongoing: Boolean) {
if(ongoing && !isForegroundService) {
startForeground(notificationId, notification)
isForegroundService = true
}
}
override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
stopForeground(true)
isForegroundService = false
stopSelf()
}
}
playerNotificationManager = PlayerNotificationManager.Builder(this, NOTIFICATION_ID, NOTIFICATION_CHANNEL_ID)
.setNotificationListener(notificationListener)
.setChannelNameResourceId(R.string.channel_name)
.setMediaDescriptionAdapter(mediaDescriptionAdapter)
.build()
playerNotificationManager?.setUsePlayPauseActions(true)
playerNotificationManager?.setUseNextAction(true);
playerNotificationManager?.setUsePreviousAction(true);
playerNotificationManager?.setUseNextActionInCompactView(true);
playerNotificationManager?.setUsePreviousActionInCompactView(true);
playerNotificationManager?.setUseFastForwardAction(false)
playerNotificationManager?.setUseFastForwardActionInCompactView(false)
playerNotificationManager?.setUseRewindAction(false)
playerNotificationManager?.setUseRewindActionInCompactView(false)
playerNotificationManager?.setPlayer(player)
}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
// Notify the client if the playback state was changed
val stateIntent = Intent(ACTION_STATE_CHANGED)
when(playbackState){
Player.STATE_BUFFERING -> {
Log.d(KdPlayer, "PlayerState-STATE_BUFFERING: $playWhenReady")
}
Player.STATE_ENDED -> {
Log.d(KdPlayer, "PlayerState-STATE_ENDED: $playWhenReady")
stateIntent.putExtra(ACTION_STATE_CHANGED_EXTRA, false)
player.seekTo(0);
player.playWhenReady = true;
player.pause()
handler.removeCallbacks(updateProgressAction)
}
Player.STATE_IDLE -> {
Log.d(KdPlayer, "PlayerState-STATE_IDLE: $playWhenReady")
player.prepare()
durationSet = false;
Log.d(KdPlayer, "${player.duration}")
}
Player.STATE_READY -> {
Log.d(KdPlayer, "PlayerState-STATE_READY: $playWhenReady")
Log.d(KdPlayer, "PlayerState-STATE_READY: ${player.duration}")
if(!durationSet) {
durationSet = true
val realDurationMillis = player.duration
sendDuration(realDurationMillis)
}
stateIntent.putExtra(ACTION_STATE_CHANGED_EXTRA, playWhenReady)
}
}
localBroadcastManager.sendBroadcast(stateIntent)
}
private fun sendDuration(durationMillis: Long) {
val durationIntent = Intent(ACTION_DURATION_CHANGED)
durationIntent.putExtra(ACTION_DURATION_CHANGED_EXTRA, durationMillis)
localBroadcastManager.sendBroadcast(durationIntent)
}
private fun updateProgress() {
sentCurrentPosition(player.currentPosition)
handler.postDelayed(updateProgressAction, 10)
}
private val updateProgressAction = Runnable { updateProgress() }
private fun sentCurrentPosition(currentPosition : Long) {
val currentIntent = Intent(ACTION_CURRENT_CHANGED)
currentIntent.putExtra(ACTION_CURRENT_CHANGED_EXTRA, currentPosition)
localBroadcastManager.sendBroadcast(currentIntent)
}
override fun onMediaMetadataChanged(mediaMetadata: MediaMetadata) {
super.onMediaMetadataChanged(mediaMetadata)
val title: String = mediaMetadata.title?.toString() ?: ""
val cover: String = mediaMetadata.artworkUri.toString()
Log.d(KdPlayer, title);
Log.d(KdPlayer, cover);
val image = mediaMetadata.artworkData?.let { BitmapFactory.decodeByteArray(mediaMetadata.artworkData, 0, it.size) };
defaultArtwork = image
metadataList = title.split(" - ").toMutableList()
if (metadataList!!.lastIndex == 0) metadataList!!.add("")
metadataList!!.add(cover)
playerNotificationManager?.invalidate()
val metadataIntent = Intent(ACTION_NEW_METADATA)
metadataIntent.putStringArrayListExtra(ACTION_NEW_METADATA_EXTRA, metadataList!! as ArrayList<String>)
localBroadcastManager.sendBroadcast(metadataIntent)
}
override fun onMetadata(metadata: Metadata) {
val icyInfo: IcyInfo = metadata[0] as IcyInfo
val title: String = icyInfo.title ?: return
val cover: String = icyInfo.url ?: ""
metadataList = title.split(" - ").toMutableList()
if (metadataList!!.lastIndex == 0) metadataList!!.add("")
metadataList!!.add(cover)
playerNotificationManager?.invalidate()
val metadataIntent = Intent(ACTION_NEW_METADATA)
metadataIntent.putStringArrayListExtra(ACTION_NEW_METADATA_EXTRA, metadataList!! as ArrayList<String>)
localBroadcastManager.sendBroadcast(metadataIntent)
}
fun downloadImage(value: String?): Bitmap? {
if (value == null) return null
var bitmap: Bitmap? = null
try {
val url = URL(value)
bitmap = runBlocking {
withContext(Dispatchers.Default) {
BitmapFactory.decodeStream(url.openStream())
}
}
} catch (e: Throwable) {
println(e)
}
return bitmap
}
}
| 0
|
Kotlin
|
0
| 0
|
3efb828011920a28d33b8012fbbf1c71669573d8
| 12,155
|
kdplayer
|
MIT License
|
platform/session/src/main/kotlin/platform/session/di/SessionModule.kt
|
Alaksion
| 743,354,018
| false
|
{"Kotlin": 36550}
|
package platform.session.di
import org.kodein.di.DI
import org.kodein.di.bindSingleton
import org.kodein.di.instance
import platform.session.AuthHandler
import platform.session.AuthHandlerImpl
import platform.session.SessionHandler
import platform.session.SessionHandlerImpl
import platform.session.UserSingleton
val sessionModule = DI.Module("platform-session") {
bindSingleton<AuthHandler> {
AuthHandlerImpl(
auth = instance(),
userSingleton = UserSingleton
)
}
bindSingleton<SessionHandler> {
SessionHandlerImpl(
userSingleton = UserSingleton,
userRepository = instance()
)
}
}
| 0
|
Kotlin
|
0
| 0
|
3eb8e517d69c92bfad59e4203ef8a391d6422cdd
| 681
|
ImagefyAndroid
|
MIT License
|
app/src/main/java/com/example/emafoods/feature/signin/di/SignInModule.kt
|
vladr7
| 625,532,633
| false
| null |
package com.example.emafoods.feature.signin.di
import com.example.emafoods.core.domain.network.AuthService
import com.example.emafoods.feature.signin.domain.usecase.AddUserDataToRemoteDatabaseUseCase
import com.example.emafoods.feature.signin.domain.usecase.SignInAnonymousUseCase
import com.example.emafoods.feature.signin.domain.usecase.SignInGoogleUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object SignInModule {
@Provides
@Singleton
fun provideSignInGoogleUseCase(
authService: AuthService
) = SignInGoogleUseCase(
authService = authService
)
@Provides
@Singleton
fun provideSignInAnonymousUseCase(
authService: AuthService
) = SignInAnonymousUseCase(
authService = authService
)
@Provides
@Singleton
fun provideAddUserDataToRemoteDatabaseUseCase(
authService: AuthService,
) = AddUserDataToRemoteDatabaseUseCase(
authService = authService,
)
}
| 0
|
Kotlin
|
0
| 4
|
0362b3c40ba4596a41d68b09e74e4f1c2dc76bf1
| 1,124
|
EmaFoods
|
Apache License 2.0
|
kroki-utils/src/main/kotlin/io/github/kerubistan/kroki/io/RandomInputStream.kt
|
kerubistan
| 186,172,310
| false
|
{"Kotlin": 195200}
|
package io.github.kerubistan.kroki.io
import java.io.InputStream
import java.util.*
class RandomInputStream(
private val random: Random = Random(),
private val length: Int = random.nextInt()
) : InputStream() {
private var counter = 0
override fun read(): Int {
return if (counter >= length) {
-1
} else {
counter++
random.nextInt()
}
}
override fun read(buffer: ByteArray): Int {
val available = length - counter
return when {
available <= 0 -> {
-1
}
buffer.size < available -> {
random.nextBytes(buffer)
counter += buffer.size
buffer.size
}
else -> {
val temp = ByteArray(available)
random.nextBytes(temp)
temp.copyInto(buffer)
counter += available
available
}
}
}
}
| 0
|
Kotlin
|
2
| 3
|
1618cca5c1d3736760cb0f807336d90378d450ab
| 754
|
kroki
|
Apache License 2.0
|
app/src/main/java/com/anandj/tinker/core/time/LocalDateTimeAdapter.kt
|
anand-loop
| 784,848,046
| false
|
{"Kotlin": 67870}
|
package com.anandj.tinker.core.time
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class LocalDateTimeAdapter {
private val formatter = DateTimeFormatter.ISO_DATE_TIME
@FromJson
fun fromJson(json: String): LocalDateTime {
return LocalDateTime.parse(json, formatter)
}
@ToJson
fun toJson(value: LocalDateTime): String {
return value.format(formatter)
}
}
| 0
|
Kotlin
|
0
| 0
|
e275c17c47c73180b7be4d6feef2dc354823bbbd
| 496
|
Tinker
|
Apache License 2.0
|
src/commonMain/kotlin/xyz/eatsteak/kusaint/webdynpro/eventqueue/EventQueueUtils.kt
|
EATSTEAK
| 392,236,459
| false
| null |
package xyz.eatsteak.kusaint.webdynpro.eventqueue
const val EVENT_SPECTATOR = "~E001"
const val EVENT_DATA_START = "~E002"
const val EVENT_DATA_END = "~E003"
const val EVENT_DATA_COLON = "~E004"
const val EVENT_DATA_COMMA = "~E005"
fun String.toEventQueueString(): String = this.fold(StringBuilder()) { builder, char ->
if ((char in '0'..'9') || (char in 'a'..'z' || char in 'A'..'Z') || char == '-' || char == '.' || char == '_' || char == '~') {
builder.append(char)
} else {
builder.append("~${char.code.toString(16).uppercase().padStart(4, '0')}")
}
}.toString()
fun String.fromEventQueueString(): String = Regex("~([A-z0-9]{4})").replace(this) {
it.value.replace("~", "").toInt(16).toChar().toString()
}
| 5
|
Kotlin
|
1
| 3
|
705b40d8ef450d97efd95a50ee94c622851a0460
| 744
|
kusaint
|
Apache License 2.0
|
app/src/main/java/com/powelllaboratoriesfsm/features/nearbyshops/presentation/ShopAddressUpdateListener.kt
|
DebashisINT
| 558,285,083
| false
|
{"Kotlin": 28543924, "Java": 1666150}
|
package com.powelllaboratoriesfsm.features.nearbyshops.presentation
import android.app.Dialog
import com.powelllaboratoriesfsm.app.domain.AddShopDBModelEntity
/**
* Created by Kinsuk on 16-11-2017.
*/
interface ShopAddressUpdateListener {
fun onUpdateClick(address: AddShopDBModelEntity?)
fun getDialogInstance(mdialog: Dialog?)
fun onAddedDataSuccess()
}
| 0
|
Kotlin
|
0
| 0
|
f2764306c066accfdacd74ccb38f006546fe1ecc
| 374
|
PowellLaboratories
|
Apache License 2.0
|
app/src/main/java/com/breezeiksindustries/features/menuBeat/MenuBeatRepositoryProvider.kt
|
DebashisINT
| 863,536,151
| false
|
{"Kotlin": 15890094, "Java": 1030472}
|
package com.breezeiksindustries.features.menuBeat
import com.breezeiksindustries.features.addshop.model.AddShopRequestData
import com.breezeiksindustries.features.addshop.model.AddShopResponse
import io.reactivex.Observable
/**
* Created by Pratishruti on 22-11-2017.
*/
object MenuBeatRepositoryProvider {
fun provideAddShopRepository(): MenuBeatRepository {
return MenuBeatRepository(MenuBeatApi.create())
}
fun provideAddShopWithoutImageRepository(): MenuBeatRepository {
return MenuBeatRepository(MenuBeatApi.createWithoutMultipart())
}
}
| 0
|
Kotlin
|
0
| 0
|
77cc3b80d20adbe55363e1825240b8e2c6a44cf3
| 579
|
IKSIndustries
|
Apache License 2.0
|
src/main/kotlin/no/nav/amt/distribusjon/journalforing/JournalforingstatusRepository.kt
|
navikt
| 775,942,443
| false
|
{"Kotlin": 152205, "PLpgSQL": 635, "Dockerfile": 173}
|
package no.nav.amt.distribusjon.journalforing
import kotliquery.Row
import kotliquery.queryOf
import no.nav.amt.distribusjon.db.Database
import no.nav.amt.distribusjon.journalforing.model.Journalforingstatus
import java.util.UUID
class JournalforingstatusRepository {
private fun rowmapper(row: Row) = Journalforingstatus(
hendelseId = row.uuid("hendelse_id"),
journalpostId = row.string("journalpost_id"),
)
fun insert(journalforingstatus: Journalforingstatus) = Database.query {
val sql =
"""
insert into journalforingstatus (hendelse_id, journalpost_id)
values(:hendelse_id, :journalpost_id)
""".trimIndent()
val params = mapOf(
"hendelse_id" to journalforingstatus.hendelseId,
"journalpost_id" to journalforingstatus.journalpostId,
)
it.update(queryOf(sql, params))
}
fun get(hendelseId: UUID) = Database.query {
val sql =
"""
select *
from journalforingstatus
where hendelse_id = :hendelse_id
""".trimIndent()
val query = queryOf(sql, mapOf("hendelse_id" to hendelseId))
it.run(query.map(::rowmapper).asSingle)
}
}
| 0
|
Kotlin
|
0
| 0
|
7feb526e1406ce3fabc0fa9b0425f116b8527ebd
| 1,257
|
amt-distribusjon
|
MIT License
|
app/src/main/java/com/controlevacinacao/extiv/Banco.kt
|
Davi-ChavesN
| 876,492,166
| false
|
{"Kotlin": 29920}
|
package com.controlevacinacao.extiv
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class Banco(context: Context): SQLiteOpenHelper(context, "DataBase", null, 1) {
companion object {
@Volatile
private var INSTANCE: Banco? = null
fun getInstance(context: Context): Banco {
return INSTANCE ?: synchronized(this) {
val instance = Banco(context.applicationContext)
INSTANCE = instance
instance
}
}
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("PRAGMA foreign_keys=ON;")
val SQL_criacao1 = """
CREATE TABLE usuarios (
codigo INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT,
email TEXT,
usuario TEXT,
senha TEXT
);
"""
db.execSQL(SQL_criacao1)
val SQL_criacao2 = """
CREATE TABLE pets (
codigo INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT,
raca TEXT,
porte TEXT,
data_nascimento TEXT,
codigo_dono INTEGER,
FOREIGN KEY(codigo_dono) REFERENCES usuarios(codigo)
);
"""
db.execSQL(SQL_criacao2)
val SQL_criacao3 = """
CREATE TABLE vacinas (
codigo INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT,
descricao TEXT
);
"""
db.execSQL(SQL_criacao3)
val SQL_criacao4 = """
CREATE TABLE pet_vacina (
codigo_pet INTEGER,
codigo_vacina INTEGER,
data_aplicacao DATE,
FOREIGN KEY(codigo_pet) REFERENCES pets(codigo),
FOREIGN KEY(codigo_vacina) REFERENCES vacinas(codigo)
);
"""
db.execSQL(SQL_criacao4)
// Insert sample data
val insertVacina = db.compileStatement("INSERT INTO vacinas (nome, descricao) VALUES (?, ?)")
insertVacina.bindString(1, "Vacina Antirrábica")
insertVacina.bindString(2, "Protege contra a raiva")
insertVacina.executeInsert()
insertVacina.bindString(1, "Vacina V8")
insertVacina.bindString(2, "Protege contra oito doenças")
insertVacina.executeInsert()
insertVacina.bindString(1, "<NAME>")
insertVacina.bindString(2, "Protege contra giardíase")
insertVacina.executeInsert()
// Make sure to insert a user before pets if you have a foreign key constraint
// val insertUsuario = db.compileStatement("INSERT INTO usuarios (nome, email, usuario, senha) VALUES (?, ?, ?, ?)")
// insertUsuario.bindString(1, "<NAME>")
// insertUsuario.bindString(2, "<EMAIL>")
// insertUsuario.bindString(3, "johndoe")
// insertUsuario.bindString(4, "password")
// insertUsuario.executeInsert()
//
// val insertPet = db.compileStatement("INSERT INTO pets (nome, raca, porte, data_nascimento, codigo_dono) " +
// "VALUES (?, ?, ?, ?, ?)")
// insertPet.bindString(1, "Caco")
// insertPet.bindString(2, "Yorkshire")
// insertPet.bindString(3, "Pequeno")
// insertPet.bindString(4, "2007-01-01")
// insertPet.bindLong(5, 1) // Make sure this user exists
// insertPet.executeInsert()
//
// insertPet.bindString(1, "Lady")
// insertPet.bindString(2, "Poodle")
// insertPet.bindString(3, "Médio")
// insertPet.bindString(4, "2009-01-01")
// insertPet.bindLong(5, 1)
// insertPet.executeInsert()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS pets")
db.execSQL("DROP TABLE IF EXISTS usuarios")
db.execSQL("DROP TABLE IF EXISTS vacinas")
db.execSQL("DROP TABLE IF EXISTS pet_vacina")
onCreate(db)
}
}
| 0
|
Kotlin
|
0
| 0
|
7ac74a70de9c13d8c181071d426e5334ba4909b6
| 4,067
|
SistemaDeVacinacao
|
MIT License
|
source-code/final-project/app/src/main/java/com/droidcon/workmanager/helper/AppConstants.kt
|
droidcon-academy
| 719,032,898
| false
|
{"Kotlin": 78870}
|
package com.droidcon.workmanager.helper
object AppConstants {
const val IMAGE_ID = "IMAGE_ID"
const val IMAGE_PATH = "IMAGE_PATH"
const val IMAGE_RESIZER_PROGRESS = "IMAGE_RESIZER_PROGRESS"
}
| 0
|
Kotlin
|
0
| 0
|
54967001dce9b5ac3bd966ab4fb2cb0bd4afc3f1
| 204
|
android-mc-workmanager-compose
|
Apache License 2.0
|
app/src/main/java/com/ferrariofilippo/saveapp/view/NewTagFragment.kt
|
ferrariofilippo
| 683,187,933
| false
|
{"Kotlin": 305575}
|
// Copyright (c) 2024 <NAME>
// Licensed under the MIT License. See the LICENSE.
package com.ferrariofilippo.saveapp.view
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AutoCompleteTextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.ferrariofilippo.saveapp.MainActivity
import com.ferrariofilippo.saveapp.R
import com.ferrariofilippo.saveapp.SaveAppApplication
import com.ferrariofilippo.saveapp.databinding.FragmentNewTagBinding
import com.ferrariofilippo.saveapp.model.entities.Tag
import com.ferrariofilippo.saveapp.util.ColorUtil
import com.ferrariofilippo.saveapp.util.TagUtil
import com.ferrariofilippo.saveapp.view.adapters.ColorDropdownAdapter
import com.ferrariofilippo.saveapp.view.adapters.TagsDropdownAdapter
import com.ferrariofilippo.saveapp.view.viewmodels.NewTagViewModel
import kotlinx.coroutines.runBlocking
class NewTagFragment : Fragment() {
private lateinit var viewModel: NewTagViewModel
private lateinit var _noneString: String
private var _whiteColor: Int = 0
private var _binding: FragmentNewTagBinding? = null
private val binding get(): FragmentNewTagBinding = _binding!!
// Overrides
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentNewTagBinding
.inflate(inflater, container, false)
.apply {
lifecycleOwner = viewLifecycleOwner
vm = viewModel
}
checkIfEditing()
setupUI()
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this)[NewTagViewModel::class.java]
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
// Methods
private fun checkIfEditing() {
val tagId = arguments?.getInt("tagId") ?: 0
if (tagId == 0)
return
val application = requireActivity().application as SaveAppApplication
val tag = runBlocking { application.tagRepository.getById(tagId) }
viewModel.oldTag = tag
viewModel.tagName.value = tag?.name
viewModel.tagColor.value = tag?.color ?: viewModel.defaultColor
viewModel.isIncomeTag.value = tag?.isIncome
viewModel.isIncomeTagSwitchEnabled.value = false
}
private fun setupUI() {
binding.saveButton.setOnClickListener { viewModel.insert() }
binding.cancelButton.setOnClickListener { (activity as MainActivity).popLastView() }
setupColorPicker()
setupParentTagPicker()
viewModel.onNameChanged = { manageNameError() }
}
private fun setupColorPicker() {
val colorAutoComplete = binding.colorInput.editText as AutoCompleteTextView
val adapter = ColorDropdownAdapter(
binding.colorInput.context,
R.layout.color_dropdown_item,
ColorUtil.colors
)
colorAutoComplete.setAdapter(adapter)
colorAutoComplete.setOnItemClickListener { parent, _, position, _ ->
val selection = parent.adapter.getItem(position) as Int
viewModel.tagColor.value = ColorUtil.getColorOrDefault(requireContext(), selection)
}
}
private fun setupParentTagPicker() {
val parentTagAutoComplete = binding.tagParentInput.editText as AutoCompleteTextView
viewModel.tags.observe(viewLifecycleOwner, Observer {
if (it.isNotEmpty()) {
val tags = it.toMutableList()
if (viewModel.oldTag != null) {
TagUtil.removeAllExpensesOrIncomes(tags, viewModel.oldTag!!.isIncome)
TagUtil.removeAllChildrenTags(tags, viewModel.oldTag!!)
tags.remove(viewModel.oldTag)
}
_noneString = requireContext().getString(R.string.none)
_whiteColor = requireContext().getColor(R.color.white)
tags.add(0, Tag(0, _noneString, _whiteColor, false))
val adapter = TagsDropdownAdapter(
binding.tagParentInput.context,
R.layout.tag_dropdown_item,
tags.toTypedArray()
)
parentTagAutoComplete.setAdapter(adapter)
parentTagAutoComplete.setOnItemClickListener { parent, _, position, _ ->
val selection = parent.adapter.getItem(position) as Tag
if (selection.id == 0) {
viewModel.parentTag = null
viewModel.isIncomeTagSwitchEnabled.value = viewModel.oldTag != null && true
} else {
viewModel.parentTag = selection
viewModel.isIncomeTagSwitchEnabled.value = false
viewModel.isIncomeTag.value = selection.isIncome
}
}
if (viewModel.oldTag != null && viewModel.oldTag!!.parentTagId != 0) {
val i = it.indexOfFirst { tag -> tag.id == viewModel.oldTag!!.parentTagId }
parentTagAutoComplete.setText(it[i].fullName, false)
viewModel.parentTag = it[i]
}
}
})
}
private fun manageNameError() {
val ctx = requireContext()
val res = ctx.resources
val name = viewModel.tagName.value
val fullName =
if (viewModel.parentTag == null) name
else String.format(ctx.getString(R.string.tag_complete_name), viewModel.parentTag!!.fullName, name ?: "")
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (name == null || name!!.isBlank()) {
binding.tagNameInput.error = res.getString(R.string.name_error)
} else if (viewModel.tags.value?.indexOfFirst { it.fullName == fullName } != -1) {
binding.tagNameInput.error = res.getString(R.string.name_already_used)
} else {
binding.tagNameInput.error = null
}
}
}
| 0
|
Kotlin
|
0
| 1
|
5c6b236f1128af5e7d855d53d90c7f670c0d3806
| 6,282
|
SaveApp_Kotlin
|
MIT License
|
app/src/main/kotlin/com/dmko/bulldogvods/features/vods/domain/entities/VodPlaybackPosition.kt
|
dmitrykochanov
| 477,314,891
| false
| null |
package com.dmko.bulldogvods.features.vods.domain.entities
data class VodPlaybackPosition(
val vodId: String,
val playbackPosition: Long
)
| 0
|
Kotlin
|
0
| 1
|
0aa6ec12113a0366c81c236cc6288e72ed15798c
| 148
|
BulldogVods
|
MIT License
|
Server/application/src/communication/ExceptionHandler.kt
|
aaronfodor
| 249,640,199
| false
|
{"Jupyter Notebook": 16761258, "Kotlin": 349389, "TeX": 234852, "Lua": 17047, "Makefile": 2005, "Batchfile": 321, "Shell": 9}
|
package com.arpadfodor.stolenvehicledetector.communication
import java.lang.RuntimeException
object ExceptionHandler {
fun isNoException(statusCode: Int) : Boolean{
return when(statusCode){
StatusCodes.SUCCESS -> true
else -> false
}
}
fun throwAppropriateException(statusCode: Int) : Nothing{
when(statusCode){
StatusCodes.NOT_MODIFIED -> throw NotModified()
StatusCodes.CONFLICT -> throw Conflict()
StatusCodes.BAD_REQUEST -> throw BadRequest()
StatusCodes.NOT_FOUND -> throw NotFound()
StatusCodes.UNAUTHORIZED -> throw InvalidCredentials()
StatusCodes.INTERNAL_SERVER_ERROR -> throw InternalServerError()
else -> throw RuntimeException("$statusCode")
}
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
ff455c0daa2ca3bcf1f38b9f17833db8f0d449a0
| 821
|
StolenVehicleDetector
|
MIT License
|
src/main/java/org/radarbase/management/web/rest/criteria/CriteriaRange.kt
|
RADAR-base
| 90,646,368
| false
|
{"Kotlin": 1000491, "TypeScript": 476028, "HTML": 280734, "Java": 24215, "SCSS": 20166, "Scala": 16198, "JavaScript": 3395, "Dockerfile": 2950, "Shell": 734, "CSS": 425}
|
/*
* Copyright (c) 2021. The Hyve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* See the file LICENSE in the root of this repository.
*/
package org.radarbase.management.web.rest.criteria
open class CriteriaRange<T : Comparable<T>?>(var from: T? = null, var to: T? = null,
var `is`: T? = null
) {
fun from(): T? {
return if (this.`is` == null) from else null
}
fun to(): T? {
return if (this.`is` == null) to else null
}
val isEmpty: Boolean
/**
* Whether the criteria range contains any values at all.
*/
get() = from == null && to == null && `is` == null
/**
* Validate this criteria range whether the from and to ranges are in order.
*/
fun validate() {
require(!(`is` == null && from != null && to != null && from!!.compareTo(to!!) > 0)) { "CriteriaRange must have a from range that is smaller then the to range." }
}
override fun toString(): String {
return ("CriteriaRange{" + "from=" + from()
+ ", to=" + to()
+ ", is=" + this.`is`
+ '}')
}
}
| 85
|
Kotlin
|
16
| 21
|
7d5d527beaf6e9d20f7f8bb95dfc110eb46fe300
| 1,263
|
ManagementPortal
|
Apache License 2.0
|
app/src/main/java/ru/solandme/washwait/data/net/owm/OWNetworkDataSourceImpl.kt
|
solandmedotru
| 160,739,363
| false
| null |
package ru.solandme.washwait.data.net.owm
import android.util.Log
import ru.solandme.washwait.R
import ru.solandme.washwait.data.db.entity.Advices
import ru.solandme.washwait.data.db.entity.Location
import ru.solandme.washwait.data.db.entity.WeatherEntity
import ru.solandme.washwait.data.db.entity.Wind
import ru.solandme.washwait.internal.NoConnectivityException
import ru.solandme.washwait.data.net.owm.owcResponse.OWCurrentWeatherResponse
import ru.solandme.washwait.data.net.owm.owfResponse.OWForecastResponse
import ru.solandme.washwait.data.net.WeatherNetworkDataSource
import ru.solandme.washwait.data.net.owm.owfResponse.X
class OWNetworkDataSourceImpl(
private val openWeatherApiService: OpenWeatherApiService
) : WeatherNetworkDataSource {
override suspend fun getForecastWeather(lat: String, lon: String, units: String, language: String): List<WeatherEntity> {
var forecast: MutableList<WeatherEntity> = mutableListOf()
try {
val fetchedForecast = openWeatherApiService
.getForecastWeatherAsync(lat, lon, units, language)
.await()
return if (fetchedForecast.isSuccessful) {
forecast = forecastMapping(fetchedForecast.body()!!)
forecast
} else forecast
} catch (e: NoConnectivityException) {
Log.e("Connectivity", "No internet connection.", e)
}
return forecast
}
override suspend fun getForecastWeather(location: String, units: String, language: String): List<WeatherEntity> {
var forecast: MutableList<WeatherEntity> = mutableListOf()
try {
val fetchedForecast = openWeatherApiService
.getForecastWeatherAsync(location, units, language)
.await()
return if (fetchedForecast.isSuccessful) {
forecast = forecastMapping(fetchedForecast.body()!!)
forecast
} else forecast
} catch (e: NoConnectivityException) {
Log.e("Connectivity", "No internet connection.", e)
}
return forecast
}
private fun forecastMapping(response: OWForecastResponse): MutableList<WeatherEntity> {
val forecast: MutableList<WeatherEntity> = mutableListOf()
response.list.indices.forEach { id ->
forecast.add(WeatherEntity(
id,
response.list[id].humidity,
response.list[id].pressure.toInt(),
response.list[id].temp.day.toInt(),
response.list[id].temp.max.toInt(),
response.list[id].temp.min.toInt(),
Wind(response.list[id].deg, response.list[id].speed),
response.list[id].weather[0].description,
getAdvices(response.list[id].weather[0].id),
getWeatherPicture(response.list[id].weather[0].icon),
Location(response.city.lat, response.city.lon, response.city.name),
response.list[id].dt.toLong()
))
}
return forecast
}
private fun getAdvices(response: Int): Advices {
var needGlasses = false
var needUmbrella = false
var needWash = false
var needLight = false
var needWear = false
when (response) {
in 200..531 -> {
needUmbrella = true
needWash = false
}
in 600..622 -> {
needWear = true
needWash = false
}
in 700..761 -> {
needLight = true
}
800 -> {
needGlasses = true
}
}
return Advices(needGlasses, needUmbrella, needWash, needLight, needWear)
}
private fun weatherMapping(id: Int, fetchedCurrentWeather: OWCurrentWeatherResponse): WeatherEntity {
return WeatherEntity(
id,
fetchedCurrentWeather.main.humidity,
fetchedCurrentWeather.main.pressure.toInt(),
fetchedCurrentWeather.main.temp.toInt(),
fetchedCurrentWeather.main.tempMax.toInt(),
fetchedCurrentWeather.main.tempMin.toInt(),
Wind(fetchedCurrentWeather.wind.deg, fetchedCurrentWeather.wind.speed),
fetchedCurrentWeather.weather[id].description,
getAdvices(fetchedCurrentWeather.id),
getWeatherPicture(fetchedCurrentWeather.weather[id].icon),
Location(fetchedCurrentWeather.coord.lat,
fetchedCurrentWeather.coord.lon,
fetchedCurrentWeather.name
),
fetchedCurrentWeather.dt.toLong()
)
}
private fun getWeatherPicture(icon: String): Int {
when (icon) {
"01d" -> return R.drawable.ic_weather_icons_02
"01n" -> return R.drawable.ic_weather_icons_02
"02d" -> return R.drawable.ic_weather_icons_05
"02n" -> return R.drawable.ic_weather_icons_05
"03d" -> return R.drawable.ic_weather_icons_03
"03n" -> return R.drawable.ic_weather_icons_03
"04d" -> return R.drawable.ic_weather_icons_04
"04n" -> return R.drawable.ic_weather_icons_04
"09d" -> return R.drawable.ic_weather_icons_12
"09n" -> return R.drawable.ic_weather_icons_12
"10d" -> return R.drawable.ic_weather_icons_08
"10n" -> return R.drawable.ic_weather_icons_08
"11d" -> return R.drawable.ic_weather_icons_06
"11n" -> return R.drawable.ic_weather_icons_06
"13d" -> return R.drawable.ic_weather_icons_10
"13n" -> return R.drawable.ic_weather_icons_10
"50d" -> return R.drawable.ic_weather_icons_09
"50n" -> return R.drawable.ic_weather_icons_09
else -> return R.drawable.ic_weather_icons_02
}
}
}
| 0
|
Kotlin
|
1
| 0
|
d0dfb638e9c9bd647ef69742ea123385a33d83d4
| 6,043
|
WashWaitNew
|
Apache License 2.0
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/ThirdMax.kt
|
ashtanko
| 203,993,092
| false
|
{"Kotlin": 6608183, "Shell": 1168, "Makefile": 961}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
private const val MAX = 3
/**
* This function finds the third maximum number in a given array of integers.
* It uses a priority queue and a set to keep track of the maximum numbers.
* The function iterates over the array and for each number, it adds it to the set and the priority queue.
* If the size of the priority queue exceeds 3, it removes the smallest number.
* Finally, if the size of the priority queue is 2, it removes the smallest number again, leaving the third maximum
* number at the top of the queue.
* The function returns the top of the queue, which is the third maximum number.
*
* @param nums The array of integers to find the third maximum number in.
* @return The third maximum number in the array.
*/
fun thirdMax(nums: IntArray): Int {
val pq: PriorityQueue<Int> = PriorityQueue()
val set: MutableSet<Int> = HashSet()
for (n in nums) {
if (set.add(n)) {
pq.offer(n)
if (pq.size > MAX) pq.poll()
}
}
if (pq.size == 2) pq.poll()
return pq.peek() ?: -1
}
| 4
|
Kotlin
|
0
| 19
|
d7f842ebc3041ed6a407782d4f5da2e6a53c34df
| 1,716
|
kotlab
|
Apache License 2.0
|
core/template/src/main/java/app/xlei/vipexam/template/writing/WritingViewModel.kt
|
1939323749
| 720,476,549
| false
|
{"Kotlin": 503767}
|
package app.xlei.vipexam.ui.question.writing
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class WritingViewModel @Inject constructor(
writingUiState: WritingUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(writingUiState)
val uiState: StateFlow<WritingUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban // function scope
)
}
}
fun setWritings(){
val writings = mutableListOf<WritingUiState.Writing>()
_uiState.value.muban!!.shiti.forEach {
writings.add(
WritingUiState.Writing(
question = it.primQuestion,
refAnswer = it.refAnswer,
image = it.primPic,
description = it.discription
)
)
}
_uiState.update {
it.copy(
writings = writings
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
aeab06b6250b64f00cded32cc4c582702fc93c1d
| 1,337
|
vipexam
|
Apache License 2.0
|
sms/src/main/java/com/beeper/sms/commands/outgoing/Backfill.kt
|
raymand211092
| 610,818,444
| false
| null |
package com.beeper.sms.commands.outgoing
import com.beeper.sms.BuildConfig
data class Backfill(
var chat_guid: String,
var messages: List<Message>
){
override fun toString(): String {
return "Backfill(chat_guid='$chat_guid', messages:'${messages.map { it.guid }}')"
}
}
| 0
|
Kotlin
|
0
| 0
|
d667c9c4376ab1e4564ccdfd5d579124f14d5cf7
| 295
|
android-sms
|
Apache License 2.0
|
app/src/main/java/jp/gr/java_conf/mmktomato/fluffyplayer/PlayerActivity.kt
|
mmktomato
| 111,898,025
| false
| null |
package jp.gr.java_conf.mmktomato.fluffyplayer
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.databinding.DataBindingUtil
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import jp.gr.java_conf.mmktomato.fluffyplayer.databinding.ActivityPlayerBinding
import jp.gr.java_conf.mmktomato.fluffyplayer.db.model.PlaylistItem
import jp.gr.java_conf.mmktomato.fluffyplayer.di.component.DependencyInjector
import jp.gr.java_conf.mmktomato.fluffyplayer.proxy.DbxNodeMetadata
import jp.gr.java_conf.mmktomato.fluffyplayer.player.PlayerService
import jp.gr.java_conf.mmktomato.fluffyplayer.ui.presenter.PlayerActivityPresenter
import jp.gr.java_conf.mmktomato.fluffyplayer.ui.presenter.PlayerActivityPresenterImpl
import jp.gr.java_conf.mmktomato.fluffyplayer.ui.viewmodel.PlayerActivityViewModel
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
class PlayerActivity : ActivityBase() {
private lateinit var presenter: PlayerActivityPresenter
/**
* the connection to the service.
*/
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
presenter.initializePlayerServiceState(binder)
}
// Called when the connection with the service disconnects unexpectedly.
override fun onServiceDisconnected(name: ComponentName?) {
presenter.unbindPlayerServiceState()
}
}
/**
* Initializes the `presenter`.
*/
private suspend fun initializePresenter() {
val viewModel = PlayerActivityViewModel()
val binding = DataBindingUtil.setContentView<ActivityPlayerBinding>(this, R.layout.activity_player)
binding.viewModel = viewModel
val playerServiceIntent = Intent(this, PlayerService::class.java)
presenter = PlayerActivityPresenterImpl(
viewModel = viewModel,
dbxMetadataArray = intent.getSerializableExtra("dbxMetadataArray") as Array<DbxNodeMetadata>?,
nowPlayingItem = intent.getSerializableExtra("nowPlayingItem") as PlaylistItem?,
playerServiceIntent = playerServiceIntent,
startService = { intent -> startService(intent) },
bindService = { intent -> bindService(intent, connection, Context.BIND_AUTO_CREATE) },
unbindService = { unbindService(connection) },
getString = ::getString,
playButton = findViewById<Button>(R.id.playButton),
resources = resources,
mediaMetadataRetriever = MediaMetadataRetriever())
DependencyInjector.injector.inject(presenter as PlayerActivityPresenterImpl, this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player)
launch(UI) {
initializePresenter()
presenter.onCreate()
}
}
override fun onDestroy() {
super.onDestroy()
presenter.onDestroy()
}
}
| 0
|
Kotlin
|
0
| 0
|
1a9c6fe3b24a3ff9903255f9a6cfd310c82d0191
| 3,270
|
FluffyPlayer
|
MIT License
|
Controls/src/commonMain/kotlin/io/nacular/doodle/controls/theme/range/KeyHandlingUtils.kt
|
nacular
| 108,631,782
| false
|
{"Kotlin": 3150677}
|
package io.nacular.doodle.controls.theme.range
import io.nacular.doodle.controls.range.RangeValueSlider
import io.nacular.doodle.controls.range.ValueSlider
import io.nacular.doodle.controls.range.size
import io.nacular.doodle.core.ContentDirection
import io.nacular.doodle.event.KeyEvent
import io.nacular.doodle.event.KeyText.Companion.ArrowDown
import io.nacular.doodle.event.KeyText.Companion.ArrowLeft
import io.nacular.doodle.event.KeyText.Companion.ArrowRight
import io.nacular.doodle.event.KeyText.Companion.ArrowUp
import kotlin.math.pow
private val MIN_OFFSET = 10.0.pow(-10)
internal fun handleKeyPress(slider: ValueSlider<*>, event: KeyEvent) {
val positiveIncrement = slider.snapSize?.takeIf { it > 0 }?.let { snapSize ->
(snapSize - slider.value.toDouble() % snapSize).takeIf { it > MIN_OFFSET } ?: snapSize
} ?: (slider.range.size.toDouble() / 100)
val negativeIncrement = -(slider.snapSize?.takeIf { it > 0 }?.let { snapSize ->
(slider.value.toDouble() % snapSize).takeIf { it > MIN_OFFSET } ?: snapSize
} ?: (slider.range.size.toDouble() / 100))
val (incrementKey, decrementKey) = when (slider.contentDirection) {
ContentDirection.LeftRight -> ArrowRight to ArrowLeft
else -> ArrowLeft to ArrowRight
}
when (event.key) {
ArrowUp, incrementKey -> slider.adjust(by = positiveIncrement)
ArrowDown, decrementKey -> slider.adjust(by = negativeIncrement)
}
}
internal fun handleKeyPress(slider: RangeValueSlider<*>, event: KeyEvent) {
val positiveIncrement = slider.snapSize?.takeIf { it > 0 }?.let { snapSize ->
(snapSize - slider.value.start.toDouble() % snapSize).takeIf { it > MIN_OFFSET } ?: snapSize
} ?: (slider.range.size.toDouble() / 100)
val negativeIncrement = -(slider.snapSize?.takeIf { it > 0 }?.let { snapSize ->
(slider.value.start.toDouble() % snapSize).takeIf { it > MIN_OFFSET } ?: snapSize
} ?: (slider.range.size.toDouble() / 100))
val (incrementKey, decrementKey) = when (slider.contentDirection) {
ContentDirection.LeftRight -> ArrowRight to ArrowLeft
else -> ArrowLeft to ArrowRight
}
when (event.key) {
ArrowUp, incrementKey -> slider.adjust(startBy = positiveIncrement, endBy = positiveIncrement)
ArrowDown, decrementKey -> slider.adjust(startBy = negativeIncrement, endBy = negativeIncrement)
}
}
| 3
|
Kotlin
|
26
| 613
|
f7414d4c30cdd7632992071234223653e52b978c
| 2,454
|
doodle
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/GreaterThanEqual.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
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.rounded.Icons
public val Icons.Bold.GreaterThanEqual: ImageVector
get() {
if (_greaterThanEqual != null) {
return _greaterThanEqual!!
}
_greaterThanEqual = Builder(name = "GreaterThanEqual", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(20.98f, 22.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
lineTo(4.48f, 24.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(15.0f)
curveToRelative(0.828f, 0.0f, 1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(17.573f, 10.229f)
lineToRelative(-13.687f, 5.894f)
curveToRelative(-0.761f, 0.328f, -1.111f, 1.21f, -0.784f, 1.972f)
curveToRelative(0.245f, 0.567f, 0.798f, 0.906f, 1.379f, 0.906f)
curveToRelative(0.197f, 0.0f, 0.399f, -0.039f, 0.593f, -0.122f)
lineToRelative(13.686f, -5.894f)
curveToRelative(1.382f, -0.595f, 2.24f, -1.93f, 2.24f, -3.484f)
reflectiveCurveToRelative(-0.858f, -2.889f, -2.239f, -3.483f)
lineTo(5.074f, 0.123f)
curveToRelative(-0.763f, -0.33f, -1.644f, 0.024f, -1.972f, 0.784f)
curveToRelative(-0.327f, 0.761f, 0.023f, 1.643f, 0.784f, 1.971f)
lineToRelative(13.688f, 5.895f)
curveToRelative(0.396f, 0.17f, 0.426f, 0.6f, 0.426f, 0.728f)
reflectiveCurveToRelative(-0.03f, 0.558f, -0.427f, 0.729f)
close()
}
}
.build()
return _greaterThanEqual!!
}
private var _greaterThanEqual: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,672
|
icons
|
MIT License
|
src/main/kotlin/me/jakejmattson/modmail/preconditions/PrefixPrecondition.kt
|
JakeJMattson
| 282,723,425
| false
| null |
package me.jakejmattson.modmail.preconditions
import me.jakejmattson.discordkt.dsl.precondition
import me.jakejmattson.modmail.services.Configuration
@Suppress("unused")
fun prefixPrecondition(configuration: Configuration) = precondition {
if (guild == null) return@precondition
if (message == null) return@precondition
if (author.isBot) return@precondition
val guildConfig = configuration[guild!!] ?: return@precondition
val content = message!!.content
if (content.startsWith(guildConfig.prefix) || content.startsWith("/"))
fail()
}
| 0
|
Kotlin
|
3
| 15
|
854ffde1e15df82307f22251c322d9e16b56f7b3
| 569
|
ModMail
|
MIT License
|
app/src/test/java/com/everis/androidintermedio2/LoginTest.kt
|
carlosiniesta7
| 238,405,612
| false
| null |
package com.everis.androidintermedio2
import com.example.data2.GetElementRepository
import com.example.domain2.DoLogin
import org.junit.Assert.assertEquals
import org.junit.Test
class LoginTest {
private val repository = GetElementRepository()
private val doLogin = DoLogin(repository)
@Test
fun loginTest() {
val result = doLogin.invoke()
assertEquals(
true,
result
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1ade23717d1a811c9db67f662cb3ce3f34bde4de
| 442
|
intermedio2-android
|
Apache License 2.0
|
app/src/main/kotlin/com/hypeapps/instasplit/ui/group_single/GroupSingleViewModel.kt
|
ntietje1
| 777,278,972
| false
|
{"Kotlin": 197240}
|
package com.hypeapps.instasplit.ui.group_single
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.CreationExtras
import com.hypeapps.instasplit.application.App
import com.hypeapps.instasplit.core.InstaSplitRepository
import com.hypeapps.instasplit.core.model.entity.Expense
import com.hypeapps.instasplit.core.model.entity.bridge.ExpenseWrapper
import com.hypeapps.instasplit.core.model.entity.bridge.GroupWrapper
import com.hypeapps.instasplit.core.utils.UserManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class GroupSingleViewModel(
private val repository: InstaSplitRepository,
private val userManager: UserManager
) : ViewModel() {
private val _state = MutableStateFlow(GroupSingleState())
val state: StateFlow<GroupSingleState> = _state.asStateFlow()
suspend fun getMemberImage(): String {
return repository.fetchMemberImage().url
}
suspend fun getExpenseImage(): String {
return repository.fetchExpenseImage().url
}
fun getBalance(expenseWrapper: ExpenseWrapper): Double {
val user = userManager.currentUserId
return expenseWrapper.getBalance(user)
}
private fun updateExpenseWrappers(expenses: List<Expense>) {
expenses.forEach { expense ->
repository.getExpenseWrapper(expense.expenseId!!)
.observeForever { expenseWrapper ->
val currentWrappers = _state.value.expenseWrappers.toMutableList()
val existingWrapperIndex = currentWrappers.indexOfFirst { it.expense.expenseId == expense.expenseId }
if (existingWrapperIndex != -1) {
currentWrappers[existingWrapperIndex] = expenseWrapper
} else {
expenseWrapper?.let {
currentWrappers.add(it)
}
}
_state.value = _state.value.copy(expenseWrappers = currentWrappers)
}
}
}
private fun updateGroupWrapper(groupWrapper: GroupWrapper) {
_state.value = GroupSingleState(groupWrapper)
}
fun updateGroupId(groupId: Int) {
println("updateGroupId($groupId)")
viewModelScope.launch {
repository.getGroupWrapper(groupId).observeForever { groupWrapper ->
println("updateGroupId($groupId) -> groupWrapper: $groupWrapper")
updateGroupWrapper(groupWrapper)
updateExpenseWrappers(groupWrapper.expenses)
}
}
}
companion object {
val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val app = checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) as App
return GroupSingleViewModel(
app.appContainer.repository,
app.appContainer.userManager
) as T
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e3643c4c179bdeb1db4d11d57be9fa303810a47a
| 3,326
|
InstaSplit
|
MIT License
|
vmdata/src/main/java/com/vmloft/develop/library/data/common/DSPManager.kt
|
lzan13
| 195,352,610
| false
|
{"Kotlin": 1107159, "HTML": 2953}
|
package com.vmloft.develop.library.data.common
import com.vmloft.develop.library.base.common.CSPManager
/**
* Create by lzan13 on 2020/4/25 19:48
* 描述:SharedPreference 管理
*/
object DSPManager {
/**
* 记录登录信息
*/
private val signEntry = "sign"
private val tokenKey = "tokenKey"
private val signIdKey = "signIdKey" // 当前登录 id
private val signUserKey = "signUserKey"
private val historyUserKey = "historyUserKey"
private val signMatchKey = "signMatchKey"
private val lastRoomKey = "lastRoomKey" // 记录最后加入的房间信息
/**
* 记录时间
*/
private val timeEntry = "time"
private val appConfigTimeKey = "appConfigTimeKey" // 上次请求客户端配置时间
private val checkVersionTimeKey = "checkVersionTimeKey" // 上次版本检查时间
private val categoryTimeKey = "categoryTimeKey" // 上次获取分类时间
private val giftTimeKey = "giftTimeKey" // 上次获取职业时间
private val privatePolicyTimeKey = "privatePolicyTimeKey" // 上次请求隐私政策时间
private val professionTimeKey = "professionTimeKey" // 上次获取职业时间
private val userAgreementTimeKey = "userAgreementTimeKey" // 上次请求用户协议时间
private val userNormTimeKey = "userNormTimeKey" // 上次请求用户行为规范时间
private val publishPostTimeKey = "userNormTimeKey" // 上次发布内容时间
/**
* -------------------------------------------------------------------------------
* 记录登录信息
*/
/**
* token 需要实时更新
*/
fun getToken(): String = CSPManager.get(signEntry, tokenKey, "") as String
fun putToken(token: String) {
CSPManager.put(signEntry, tokenKey, token)
}
/**
* 当前登录账户 Id
*/
fun getSignId(): String = CSPManager.get(signEntry, signIdKey, "") as String
fun putSignId(userId: String) {
CSPManager.put(signEntry, signIdKey, userId)
}
/**
* 当前账户登录记录
*
* @return 如果为空,说明没有登录记录
*/
fun getSignUser(): String = CSPManager.get(signEntry, signUserKey, "") as String
fun putSignUser(userJson: String) {
CSPManager.put(signEntry, signUserKey, userJson)
}
/**
* 上一个账户登录记录
*
* @return 如果为空,说明没有登录记录
*/
fun getHistoryUser(): String = CSPManager.get(signEntry, historyUserKey, "") as String
fun putHistoryUser(userJson: String) {
CSPManager.putAsync(signEntry, historyUserKey, userJson)
}
/**
* 当前账户匹配信息
*
* @return 如果为空,说明没有登录记录
*/
fun getSelfMatch(): String = CSPManager.get(signEntry, signMatchKey, "") as String
fun putSelfMatch(json: String) {
CSPManager.put(signEntry, signMatchKey, json)
}
/**
* 最后加入的房间记录
*/
fun getLastRoom(): String = CSPManager.get(signEntry, lastRoomKey, "") as String
fun putLastRoom(json: String) {
CSPManager.put(signEntry, lastRoomKey, json)
}
/**
* -------------------------------------------------------------------------------
* 记录时间信息
*/
/**
* 最近一次请求隐私政策时间
*/
fun getAppConfigTime(): Long = CSPManager.get(timeEntry, appConfigTimeKey, 0L) as Long
fun setAppConfigTime(time: Long) {
CSPManager.putAsync(timeEntry, appConfigTimeKey, time)
}
/**
* 最近一次版本检查时间
*/
fun getCheckVersionTime(): Long = CSPManager.get(timeEntry, checkVersionTimeKey, 0L) as Long
fun setCheckVersionTime(time: Long) {
CSPManager.putAsync(timeEntry, checkVersionTimeKey, time)
}
/**
* 最近一次分类获取缓存时间
*/
fun getCategoryTime(): Long = CSPManager.get(timeEntry, categoryTimeKey, 0L) as Long
fun setCategoryTime(time: Long) {
CSPManager.putAsync(timeEntry, categoryTimeKey, time)
}
/**
* 最近一次礼物获取缓存时间
*/
fun getGiftTime(): Long = CSPManager.get(timeEntry, giftTimeKey, 0L) as Long
fun setGiftTime(time: Long) {
CSPManager.putAsync(timeEntry, giftTimeKey, time)
}
/**
* 最近一次请求隐私政策时间
*/
fun getPrivatePolicyTime(): Long = CSPManager.get(timeEntry, privatePolicyTimeKey, 0L) as Long
fun setPrivatePolicyTime(time: Long) {
CSPManager.putAsync(timeEntry, privatePolicyTimeKey, time)
}
/**
* 最近一次职业获取缓存时间
*/
fun getProfessionTime(): Long = CSPManager.get(timeEntry, professionTimeKey, 0L) as Long
fun setProfessionTime(time: Long) {
CSPManager.putAsync(timeEntry, professionTimeKey, time)
}
/**
* 最近一次请求用户协议时间
*/
fun getUserAgreementTime(): Long = CSPManager.get(timeEntry, userAgreementTimeKey, 0L) as Long
fun setUserAgreementTime(time: Long) {
CSPManager.putAsync(timeEntry, userAgreementTimeKey, time)
}
/**
* 最近一次请求用户行为规范时间
*/
fun getUserNormTime(): Long = CSPManager.get(timeEntry, userNormTimeKey, 0L) as Long
fun setUserNormTime(time: Long) {
CSPManager.putAsync(timeEntry, userNormTimeKey, time)
}
/**
* 最近一次发布内容时间
*/
fun getPublishPostTime(): Long = CSPManager.get(timeEntry, publishPostTimeKey, 0L) as Long
fun setPublishPostTime(time: Long) {
CSPManager.putAsync(timeEntry, publishPostTimeKey, time)
}
}
| 4
|
Kotlin
|
96
| 195
|
48a78c321b0a9c1e9770be53c1564f8c37eb6467
| 5,038
|
VMTemplateAndroid
|
MIT License
|
src/test/kotlin/org/paradise/ipaq/integration/IntegrationConfig.kt
|
TerrenceMiao
| 97,383,297
| false
| null |
package org.paradise.ipaq.integration
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
import org.mockito.Matchers.any
import org.mockito.Matchers.anyString
import org.mockito.Mockito.*
import org.paradise.ipaq.TestData
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.ClassPathResource
import org.springframework.data.redis.connection.RedisConnection
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.ValueOperations
import java.nio.charset.Charset
/**
* Created by terrence on 26/5/17.
*/
@Configuration
class IntegrationConfig {
@Bean
fun connectionFactory(): RedisConnectionFactory {
val redisConnectionFactory = mock(RedisConnectionFactory::class.java)
val redisConnection = mock(RedisConnection::class.java)
`when`(redisConnectionFactory.connection).thenReturn(redisConnection)
return redisConnectionFactory
}
@Bean
fun stringRedisTemplate(): StringRedisTemplate {
val stringRedisTemplate = mock(StringRedisTemplate::class.java)
val valueOperations = mock(ValueOperations::class.java)
@Suppress("UNCHECKED_CAST")
`when`(stringRedisTemplate.opsForValue()).thenReturn(valueOperations as ValueOperations<String, String>?)
// Redis get()
`when`(valueOperations!!.get(eq(TestData.QUERY_ADDRESS + ", " + TestData.QUERY_COUNTRY)))
.thenReturn(StringUtils.EMPTY)
.thenReturn(IOUtils.toString(ClassPathResource("search-resp.json").inputStream, Charset.defaultCharset()))
`when`(valueOperations.get(eq(TestData.QUERY_ID + ", " + TestData.QUERY_COUNTRY)))
.thenReturn(StringUtils.EMPTY)
.thenReturn(IOUtils.toString(ClassPathResource("format-resp.json").inputStream, Charset.defaultCharset()))
// Redis set()
doNothing().`when`<ValueOperations<String, String>>(valueOperations).set(any(String::class.java), any(String::class.java))
// Redis delete()
doNothing().`when`(stringRedisTemplate).delete(anyString())
return stringRedisTemplate
}
}
| 0
|
Kotlin
|
0
| 0
|
4a4c5d6b2ad72f85289c6b78470383b3861e1411
| 2,326
|
IPAQ
|
Apache License 2.0
|
extension-client/src/commonMain/kotlin/bruhcollective/itaysonlab/ksteam/models/persona/AvatarHash.kt
|
iTaysonLab
| 585,761,817
| false
|
{"Kotlin": 488681}
|
package bruhcollective.itaysonlab.ksteam.models.persona
import bruhcollective.itaysonlab.ksteam.EnvironmentConstants
import kotlin.jvm.JvmInline
@JvmInline
value class AvatarHash internal constructor(internal val hash: String) {
companion object {
val Empty = AvatarHash("")
}
val hasAvatar get() = hash.isNotEmpty()
val small get() = "${base}.jpg"
val medium get() = "${base}_medium.jpg"
val full get() = "${base}_full.jpg"
private val base get() = "${EnvironmentConstants.AVATAR_CDN_BASE}${hash}"
}
| 1
|
Kotlin
|
1
| 32
|
5b1c17ed54fde891c59ecad8651bb4f15bafcd2d
| 541
|
kSteam
|
MIT License
|
src/main/kotlin/config/NAccount.kt
|
Nekoer
| 483,529,691
| false
| null |
package com.hcyacg.config
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class NAccount (
@SerialName("phone")
var phone: String = "",
@SerialName("password")
var password:String = ""
)
| 0
|
Kotlin
|
0
| 0
|
a771e4c6e0fea9415c9800e8afcd540052602785
| 257
|
mirai-plugins-music
|
Apache License 2.0
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/util/JodaMigration.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.util
fun org.joda.time.LocalDate.toJavaTime(): java.time.LocalDate = java.time.LocalDate.of(year, monthOfYear, dayOfMonth)
fun org.joda.time.Instant.toJavaInstant(): java.time.Instant = java.time.Instant.ofEpochMilli(millis)
fun java.time.Duration.toJoda(): org.joda.time.Duration = org.joda.time.Duration(toMillis())
| 120
|
Kotlin
|
514
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 348
|
cwa-app-android
|
Apache License 2.0
|
data/repository/src/main/java/com/netchar/repository/NetworkBoundResource.kt
|
netchar
| 171,912,089
| false
| null |
/*
* Copyright © 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netchar.repository
import com.netchar.common.utils.CoroutineDispatchers
abstract class NetworkBoundResource<TResourceData : Any, TNetworkData : Any>(
dispatchers: CoroutineDispatchers
) : BoundResource<TResourceData, TNetworkData>(dispatchers) {
override fun saveRemoteDataInStorage(data: TNetworkData) {
// ignore
}
override fun getStorageData(): TResourceData? = null
override fun isNeedRefresh(localData: TResourceData): Boolean = true
}
| 1
|
Kotlin
|
3
| 4
|
2bcccb5a5cc161831a11c7976eb2cb1ba7c90923
| 1,082
|
Wallpaperify
|
Apache License 2.0
|
app/src/main/java/com/brins/locksmith/ui/activity/ChromeImportActivity.kt
|
BrinsLee
| 224,311,693
| false
| null |
package com.brins.locksmith.ui.activity
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.widget.Toast
import com.brins.locksmith.R
import com.brins.locksmith.data.password.PassWordItem
import com.brins.locksmith.ui.dialog.MissPasswordDialogFragment
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_chrome_import.*
class ChromeImportActivity : BaseActivity() {
override fun getLayoutResId(): Int {
return R.layout.activity_chrome_import
}
override fun onCreateAfterBinding(savedInstanceState: Bundle?) {
super.onCreateAfterBinding(savedInstanceState)
if (mKeyguardManager.isKeyguardSecure) {
launchFingerAuth()
} else {
MissPasswordDialogFragment.showSelf(supportFragmentManager)
}
}
public override fun authencitatedCallback() {
super.authencitatedCallback()
if (mPassportViewModel.loadPassport()) {
showLoading(getString(R.string.loading))
ImportPassword().execute()
} else {
/**首次使用,创建passport*/
Toast.makeText(this, getString(R.string.load_passport_fail), Toast.LENGTH_SHORT).show()
GuideActivity.startThis(this@ChromeImportActivity)
}
}
inner class ImportPassword : AsyncTask<String, String, ArrayList<PassWordItem>>() {
override fun onPreExecute() {
super.onPreExecute()
mSavePasswordViewModel.loadPasswordItem()
}
override fun doInBackground(vararg params: String?): ArrayList<PassWordItem> {
val bundle = intent.extras
val uri: Uri = bundle.get("android.intent.extra.STREAM") as Uri
val filename_array = uri.toString().split("/")
val uri_inputStream = contentResolver.openInputStream(uri)
return mSavePasswordViewModel.loadPasswordItem(uri_inputStream) { s: String ->
publishProgress(s)
}
}
override fun onProgressUpdate(vararg values: String) {
super.onProgressUpdate(*values)
Toast.makeText(this@ChromeImportActivity, values[0], Toast.LENGTH_SHORT).show()
}
override fun onPostExecute(result: ArrayList<PassWordItem>) {
result.forEach{
mSavePasswordViewModel.savePassWord(it)
}
hideLoading()
val intent = Intent(this@ChromeImportActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e1fd0e515a410c49c33c6b9e94411ae07936f1e3
| 2,621
|
Locksmith
|
MIT License
|
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/data/signer/SeparateFlowSigner.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 7662708, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_account_impl.data.signer
import io.novafoundation.nova.common.base.errors.SigningCancelledException
import io.novafoundation.nova.common.utils.MutableSharedState
import io.novafoundation.nova.feature_account_api.presenatation.sign.SignInterScreenCommunicator
import io.novafoundation.nova.feature_account_api.presenatation.sign.SignInterScreenRequester
import io.novafoundation.nova.feature_account_api.presenatation.sign.SignatureWrapper
import io.novafoundation.nova.feature_account_api.presenatation.sign.awaitConfirmation
import jp.co.soramitsu.fearless_utils.encrypt.SignatureWrapper
import jp.co.soramitsu.fearless_utils.runtime.extrinsic.signer.Signer
import jp.co.soramitsu.fearless_utils.runtime.extrinsic.signer.SignerPayloadExtrinsic
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
abstract class SeparateFlowSigner(
private val signingSharedState: MutableSharedState<SignerPayloadExtrinsic>,
private val signFlowRequester: SignInterScreenRequester,
) : Signer {
override suspend fun signExtrinsic(payloadExtrinsic: SignerPayloadExtrinsic): SignatureWrapper {
signingSharedState.set(payloadExtrinsic)
val result = withContext(Dispatchers.Main) {
try {
signFlowRequester.awaitConfirmation()
} finally {
signingSharedState.reset()
}
}
if (result is SignInterScreenCommunicator.Response.Signed) {
return SignatureWrapper(result.signature)
} else {
throw SigningCancelledException()
}
}
}
| 13
|
Kotlin
|
5
| 9
|
66a5c0949aee03a5ebe870a1b0d5fa3ae929516f
| 1,624
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/cwdt/restaurantroulette/group/PendingPreferencesComponent.kt
|
coleweinman
| 777,892,680
| false
|
{"Kotlin": 101528, "Python": 6570}
|
package com.cwdt.restaurantroulette.group
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.cwdt.restaurantroulette.PreferencesComponent
import com.cwdt.restaurantroulette.friends.UserListItem
import com.cwdt.restaurantroulette.model.RRGroup
@Composable
fun PendingPreferencesComponent(
modifier: Modifier,
group: RRGroup,
uid: String,
snackbarHostState: SnackbarHostState,
onSave: () -> Unit
) {
val scope = rememberCoroutineScope()
if (group.isParticipantLockedIn(uid)) {
val participants = group.getParticipants()
LazyColumn {
items(participants.size) {
val participant = participants[it]
UserListItem(user = participant) {
if (group.isParticipantLockedIn(participant.uid)) {
Text("LOCKED IN")
} else {
Text("PENDING")
}
}
}
}
} else {
PreferencesComponent(
modifier = Modifier.padding(8.dp),
scope = scope,
snackbarHostState = snackbarHostState,
onSave = { onSave() }
)
}
}
| 0
|
Kotlin
|
0
| 0
|
a1fa85ca4ed7392f428e3e0fae1df4b59c00b4c2
| 1,569
|
restaurant-roulette
|
MIT License
|
core/util/src/main/java/dev/ryzhoov/util/ui/BaseBottomSheetDialogFragment.kt
|
v1aditech
| 581,266,106
| false
|
{"Kotlin": 161157}
|
package dev.ryzhoov.util.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
abstract class BaseBottomSheetDialogFragment<T : ViewBinding> : BottomSheetDialogFragment(),
BindingInflater<T> {
private var _binding: T? = null
protected val binding: T get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = inflateBinding()
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
}
| 0
|
Kotlin
|
0
| 0
|
5b0fc12bf74f19f765d99d5671b0f599bebd17a9
| 776
|
napomnix
|
Apache License 2.0
|
SDK-KT/src/main/kotlin/com/xzakota/wordpress/model/links/Href.kt
|
xzakota
| 873,625,385
| false
|
{"Kotlin": 56169, "Java": 3477}
|
package com.xzakota.wordpress.model.links
import com.alibaba.fastjson2.annotation.JSONField
open class Href {
@JSONField(name = "href")
var href : String? = null
}
| 0
|
Kotlin
|
0
| 0
|
e5477bd0130df1fcc9a57062934000511d10ce9e
| 174
|
WordPressSDK
|
Apache License 2.0
|
src/main/kotlin/org/teamvoided/template/Template.kt
|
TeamVoided
| 701,375,971
| false
|
{"Kotlin": 8687, "Java": 546}
|
package org.teamvoided.template
import io.netty.buffer.Unpooled
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking
import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import net.minecraft.network.PacketByteBuf
import net.minecraft.util.Identifier
import org.slf4j.LoggerFactory
import org.teamvoided.template.items.AAItems
import org.teamvoided.template.items.GunItem
@Suppress("unused")
object Template {
const val MODID = "astral_armory"
val OFF_HAND_FIRE = id("off_hand_fire")
@JvmField
val LOGGER = LoggerFactory.getLogger(Template::class.java)
fun commonInit() {
LOGGER.info("Hello from Common")
AAItems.init()
ClientPreAttackCallback.EVENT.register { _, player, clicks ->
val x = player.offHandStack
if (x.item is GunItem && clicks != 0) {
ClientPlayNetworking.send(OFF_HAND_FIRE, PacketByteBuf(Unpooled.buffer()))
return@register true
}
return@register false
}
ServerPlayNetworking.registerGlobalReceiver(OFF_HAND_FIRE) { _, player, _, _, _ ->
val x = player.offHandStack
(x.item as GunItem).preAttack(x,player, player.world)
}
}
fun clientInit() {
LOGGER.info("Hello from Client")
}
fun id(path: String) = Identifier(MODID, path)
}
| 0
|
Kotlin
|
0
| 0
|
ef94b1491d133d46a15f2e18fb5ced6d770d8e45
| 1,453
|
AstralArsonal
|
MIT License
|
app/src/main/java/com/celzero/bravedns/net/go/GoVpnAdapter.kt
|
celzero
| 270,683,546
| false
| null |
/*
* Copyright 2021 RethinkDNS and its authors
* Copyright 2019 Jigsaw Operations LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.celzero.bravedns.net.go
import android.content.Context
import android.content.res.Resources
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.ParcelFileDescriptor
import android.util.Log
import android.widget.Toast
import com.celzero.bravedns.BuildConfig
import com.celzero.bravedns.R
import com.celzero.bravedns.data.AppConfig
import com.celzero.bravedns.data.AppConfig.Companion.dnscryptRelaysToRemove
import com.celzero.bravedns.data.AppConfig.TunnelOptions
import com.celzero.bravedns.database.DNSProxyEndpoint
import com.celzero.bravedns.database.ProxyEndpoint
import com.celzero.bravedns.service.PersistentState
import com.celzero.bravedns.ui.DNSConfigureWebViewActivity.Companion.BLOCKLIST_REMOTE_FOLDER_NAME
import com.celzero.bravedns.ui.HomeScreenActivity.GlobalVariable.DEBUG
import com.celzero.bravedns.util.Constants
import com.celzero.bravedns.util.Constants.Companion.DEFAULT_DOH_URL
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_RD
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TAG
import com.celzero.bravedns.util.Constants.Companion.ONDEVICE_BLOCKLIST_FILE_TD
import com.celzero.bravedns.util.LoggerConstants.Companion.LOG_TAG_VPN
import com.celzero.bravedns.util.Utilities.Companion.getNonLiveDnscryptServers
import com.celzero.bravedns.util.Utilities.Companion.remoteBlocklistDir
import com.celzero.bravedns.util.Utilities.Companion.remoteBlocklistFile
import com.celzero.bravedns.util.Utilities.Companion.showToastUiCentered
import dnsx.BraveDNS
import dnsx.Dnsx
import doh.Transport
import intra.Tunnel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import protect.Protector
import settings.Settings
import tun2socks.Tun2socks
import java.io.File
import java.io.IOException
/**
* This is a VpnAdapter that captures all traffic and routes it through a go-tun2socks instance with
* custom logic for Intra.
* */
class GoVpnAdapter(private val context: Context, private val externalScope: CoroutineScope,
private var tunFd: ParcelFileDescriptor?) : KoinComponent {
private val persistentState by inject<PersistentState>()
private val appConfig by inject<AppConfig>()
// The Intra session object from go-tun2socks. Initially null.
private var tunnel: Tunnel? = null
suspend fun start(tunnelOptions: TunnelOptions) {
connectTunnel(tunnelOptions)
}
private suspend fun connectTunnel(tunnelOptions: TunnelOptions) {
if (tunnel != null) {
return
}
try {
// TODO : #321 As of now the app fallback on an unmaintained url. Requires a rewrite as
// part of v055
val dohURL: String = getDohUrl()
val transport: Transport = makeDohTransport(dohURL, tunnelOptions.listener)
Log.i(LOG_TAG_VPN,
"Connect tunnel with url " + dohURL + ", dnsMode: " + tunnelOptions.tunDnsMode + ", blockMode: " + tunnelOptions.tunFirewallMode + ", proxyMode: " + tunnelOptions.tunProxyMode)
if (tunFd == null) return
tunnel = Tun2socks.connectIntraTunnel(tunFd!!.fd.toLong(), tunnelOptions.fakeDns,
transport, getProtector(), tunnelOptions.blocker,
tunnelOptions.listener)
if (DEBUG) {
Tun2socks.enableDebugLog()
}
setBraveDnsBlocklistMode(tunnelOptions.tunDnsMode, dohURL)
setTunnelMode(tunnelOptions)
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, e.message, e)
tunnel?.disconnect()
tunnel = null
}
}
private fun isRethinkDnsUrl(url: String): Boolean {
return url.contains(Constants.BRAVEDNS_DOMAIN) || url.contains(Constants.RETHINKDNS_DOMAIN)
}
private suspend fun setTunnelMode(tunnelOptions: TunnelOptions) {
if (tunnelOptions.tunDnsMode.isDnscrypt()) {
setDnscryptMode(tunnelOptions)
return
}
if (tunnelOptions.tunProxyMode.isTunProxyOrbot()) {
tunnel?.setTunMode(tunnelOptions.tunDnsMode.mode, tunnelOptions.tunFirewallMode.mode,
Settings.ProxyModeSOCKS5)
} else {
tunnel?.setTunMode(tunnelOptions.tunDnsMode.mode, tunnelOptions.tunFirewallMode.mode,
tunnelOptions.tunProxyMode.mode)
}
stopDnscryptIfNeeded()
setDnsProxyIfNeeded(tunnelOptions.tunDnsMode)
setSocks5TunnelModeIfNeeded(tunnelOptions.tunProxyMode)
}
private fun setBraveDnsBlocklistMode(tunDnsMode: AppConfig.TunDnsMode, dohUrl: String) {
if (BuildConfig.DEBUG) Log.d(LOG_TAG_VPN, "init bravedns mode")
tunnel?.braveDNS = null
if (!tunDnsMode.isDoh() && !tunDnsMode.isDnscrypt()) return
// No need to set the brave mode for DNS Proxy (implementation pending in underlying Go library).
// TODO: remove the check once the implementation completed in underlying Go library
io {
if (persistentState.blocklistEnabled) {
setBraveDNSLocalMode()
} else {
setBraveDNSRemoteMode(dohUrl)
}
}
}
private fun setBraveDNSRemoteMode(dohURL: String) {
// Brave mode remote will be set only if the selected DoH is RethinkDns
if (!isRethinkDnsUrl(dohURL)) {
return
}
try {
val remoteDir = remoteBlocklistDir(context, BLOCKLIST_REMOTE_FOLDER_NAME,
persistentState.remoteBlocklistTimestamp) ?: return
val remoteFile = remoteBlocklistFile(remoteDir.absolutePath,
ONDEVICE_BLOCKLIST_FILE_TAG) ?: return
if (remoteFile.exists()) {
tunnel?.braveDNS = Dnsx.newBraveDNSRemote(remoteFile.absolutePath)
Log.i(LOG_TAG_VPN, "remote-bravedns enabled")
} else {
Log.w(LOG_TAG_VPN, "filetag.json for remote-bravedns missing")
}
} catch (ex: Exception) {
Log.e(LOG_TAG_VPN, "cannot set remote-bravedns: ${ex.message}", ex)
}
}
private fun stopDnscryptIfNeeded() {
try {
if (tunnel?.dnsCryptProxy != null) {
tunnel?.stopDNSCryptProxy()
Log.i(LOG_TAG_VPN, "connect-tunnel - stopDNSCryptProxy")
}
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, "stop dnscrypt failure: " + e.message, e)
}
}
fun setDnscryptMode(tunnelOptions: TunnelOptions) {
io {
if (tunnel == null) return@io
val servers: String = appConfig.getDnscryptServers()
val routes: String = appConfig.getDnscryptRelayServers()
val serversIndex: String = appConfig.getDnscryptServersToRemove()
try {
if (tunnel?.dnsCryptProxy == null) {
val response: String? = tunnel?.startDNSCryptProxy(servers, routes,
tunnelOptions.listener)
Log.i(LOG_TAG_VPN, "startDNSCryptProxy: $servers,$routes, Response: $response")
} else {
val serversToRemove: String? = tunnel?.dnsCryptProxy?.liveServers()?.let {
getNonLiveDnscryptServers(it, serversIndex)
}
if (!serversToRemove.isNullOrBlank()) {
tunnel?.dnsCryptProxy?.removeServers(serversToRemove)
}
if (dnscryptRelaysToRemove.isNotEmpty()) {
tunnel?.dnsCryptProxy?.removeRoutes(dnscryptRelaysToRemove)
dnscryptRelaysToRemove = ""
}
if (routes.isNotEmpty()) {
tunnel?.dnsCryptProxy?.removeRoutes(routes)
}
tunnel?.dnsCryptProxy?.addServers(servers)
if (routes.isNotEmpty()) tunnel?.dnsCryptProxy?.addRoutes(routes)
Log.i(LOG_TAG_VPN, "DNSCrypt with routes: $routes, servers: $servers")
}
} catch (ex: Exception) {
Log.e(LOG_TAG_VPN, "connect-tunnel: dns crypt failure", ex)
handleDnscryptFailure()
}
if (servers.isNotEmpty()) {
refreshDnscrypt(tunnelOptions)
}
}
}
private suspend fun setDnsProxyIfNeeded(tunDnsMode: AppConfig.TunDnsMode) {
if (!tunDnsMode.isDnsProxy()) return
try {
val dnsProxy: DNSProxyEndpoint = appConfig.getConnectedProxyDetails()
if (DEBUG) Log.d(LOG_TAG_VPN,
"setDNSProxy mode set: " + dnsProxy.proxyIP + ", " + dnsProxy.proxyPort)
tunnel?.startDNSProxy(dnsProxy.proxyIP, dnsProxy.proxyPort.toString())
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, "connect-tunnel: could not connect to dnsproxy: ${e.message}", e)
handleDnsProxyFailure()
}
}
/**
* TODO - Move these code to common place and set the tunnel mode and
* other parameters. Return the tunnel to the adapter.
*/
private fun setProxyMode(userName: String?, password: String?, ipAddress: String?, port: Int) {
try {
tunnel?.startProxy(userName, password, ipAddress, port.toString())
Log.i(LOG_TAG_VPN, "Proxy mode set: $userName$ipAddress$port")
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, "connect-tunnel: could not start proxy $userName@$ipAddress:$port",
e)
}
}
private suspend fun refreshDnscrypt(tunnelOptions: TunnelOptions) {
if (tunnel?.dnsCryptProxy == null) {
handleDnscryptFailure()
return
}
io {
try {
val liveServers: String? = tunnel?.dnsCryptProxy?.refresh()
appConfig.updateDnscryptLiveServers(liveServers)
Log.i(LOG_TAG_VPN,
"Refresh LiveServers: $liveServers, tunnelOptions: $tunnelOptions")
if (liveServers.isNullOrEmpty()) {
tunnel?.stopDNSCryptProxy()
handleDnscryptFailure()
} else {
tunnel?.setTunMode(Settings.DNSModeCryptPort,
tunnelOptions.tunFirewallMode.mode,
tunnelOptions.tunProxyMode.mode)
setSocks5TunnelModeIfNeeded(tunnelOptions.tunProxyMode)
}
} catch (e: Exception) {
handleDnscryptFailure()
Log.e(LOG_TAG_VPN, "connect-tunnel: could not start dnscrypt-proxy: ${e.message}",
e)
}
}
}
private suspend fun handleDnscryptFailure() {
appConfig.setDefaultConnection()
showDnscryptConnectionFailureToast()
Log.i(LOG_TAG_VPN, "connect-tunnel: falling back to doh since dnscrypt failed")
}
private suspend fun handleDnsProxyFailure() {
appConfig.setDefaultConnection()
showDnsProxyConnectionFailureToast()
Log.i(LOG_TAG_VPN, "connect-tunnel: falling back to doh since dns proxy failed")
}
private fun showDnscryptConnectionFailureToast() {
ui {
showToastUiCentered(context, context.getString(R.string.dns_crypt_connection_failure),
Toast.LENGTH_SHORT)
}
}
private fun showDnsProxyConnectionFailureToast() {
ui {
showToastUiCentered(context, context.getString(R.string.dns_proxy_connection_failure),
Toast.LENGTH_SHORT)
}
}
private suspend fun setSocks5TunnelModeIfNeeded(tunProxyMode: AppConfig.TunProxyMode) {
if (!tunProxyMode.isTunProxySocks5() && !tunProxyMode.isTunProxyOrbot()) return
val socks5: ProxyEndpoint? = if (tunProxyMode.isTunProxyOrbot()) {
appConfig.getOrbotProxyDetails()
} else {
appConfig.getSocks5ProxyDetails()
}
if (socks5 == null) {
Log.w(LOG_TAG_VPN, "could not fetch socks5 details for proxyMode: $tunProxyMode")
return
}
setProxyMode(socks5.userName, socks5.password, socks5.proxyIP, socks5.proxyPort)
Log.i(LOG_TAG_VPN, "Socks5 mode set: " + socks5.proxyIP + "," + socks5.proxyPort)
}
fun hasTunnel(): Boolean {
return (tunnel != null)
}
// We don't need socket protection in these versions because the call to
// "addDisallowedApplication" effectively protects all sockets in this app.
private fun getProtector(): Protector? {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
return null
}
return null // Android 6 and below not supported
}
fun close() {
if (tunnel != null) {
tunnel?.disconnect()
Log.i(LOG_TAG_VPN, "Tunnel disconnect")
}
try {
tunFd?.close()
} catch (e: IOException) {
Log.e(LOG_TAG_VPN, e.message, e)
}
tunFd = null
tunnel = null
}
@Throws(Exception::class)
private fun makeDohTransport(url: String?, listener: GoIntraListener): Transport {
//TODO : Check the below code
//@NonNull String realUrl = PersistentState.Companion.expandUrl(vpnService, url);
val dohIPs: String = getIpString(context, url)
return Tun2socks.newDoHTransport(url, dohIPs, getProtector(), null, listener)
}
/**
* Updates the DOH server URL for the VPN. If Go-DoH is enabled, DNS queries will be handled in
* Go, and will not use the Java DoH implementation. If Go-DoH is not enabled, this method
* has no effect.
*/
suspend fun updateTun(tunnelOptions: TunnelOptions) {
// changes made in connectTunnel()
if (tunFd == null) {
// Adapter is closed.
return
}
if (tunnel == null) {
// Attempt to re-create the tunnel. Creation may have failed originally because the DoH
// server could not be reached. This will update the DoH URL as well.
connectTunnel(tunnelOptions)
return
}
// Overwrite the DoH Transport with a new one, even if the URL has not changed. This function
// is called on network changes, and it's important to switch to a fresh transport because the
// old transport may be using sockets on a deleted interface, which may block until they time
// out.
val dohURL: String = getDohUrl()
try {
// For invalid URL connection request.
// Check makeDohTransport, if it is not resolved don't close the tunnel.
// So handling the exception in makeDohTransport and not resetting the tunnel. Below is the exception thrown from Tun2socks.aar
// I/GoLog: Failed to read packet from TUN: read : bad file descriptor
val dohTransport: Transport = makeDohTransport(dohURL, tunnelOptions.listener)
tunnel?.dns = dohTransport
Log.i(LOG_TAG_VPN, "connect tunnel with doh: $dohURL, opts: $tunnelOptions")
// Set brave dns to tunnel - Local/Remote
setBraveDnsBlocklistMode(tunnelOptions.tunDnsMode, dohURL)
setTunnelMode(tunnelOptions)
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, e.message, e)
tunnel?.disconnect()
tunnel = null
}
}
private suspend fun getDohUrl(): String {
var dohURL: String? = ""
try {
dohURL = appConfig.getDOHDetails()?.dohURL
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, "error while fetching doh details", e)
}
if (dohURL == null) dohURL = DEFAULT_DOH_URL
return dohURL
}
private fun setBraveDNSLocalMode() {
try {
val stamp: String = persistentState.localBlocklistStamp
Log.i(LOG_TAG_VPN, "local-bravedns stamp: $stamp")
if (stamp.isEmpty()) {
return
}
tunnel?.braveDNS = makeLocalBraveDns()
tunnel?.braveDNS?.stamp = stamp
} catch (ex: Exception) {
Log.e(LOG_TAG_VPN, "could not set local-bravedns: ${ex.message}", ex)
}
}
fun setBraveDnsStamp() {
try {
if (tunnel == null) return
if (tunnel?.braveDNS?.onDeviceBlock() == true) {
tunnel?.braveDNS?.stamp = persistentState.localBlocklistStamp
} else {
Log.w(LOG_TAG_VPN,
"bravedns mode is not local but trying to set local stamp, this should not happen")
}
} catch (e: java.lang.Exception) {
Log.e(LOG_TAG_VPN, "could not set set local-bravedns stamp: ${e.message}", e)
}
}
private fun makeLocalBraveDns(): BraveDNS? {
return try {
// FIXME: canonical path may go missing but is unhandled
val path: String = context.filesDir.canonicalPath + File.separator + persistentState.localBlocklistTimestamp
Dnsx.newBraveDNSLocal(path + ONDEVICE_BLOCKLIST_FILE_TD,
path + ONDEVICE_BLOCKLIST_FILE_RD,
path + ONDEVICE_BLOCKLIST_FILE_BASIC_CONFIG,
path + ONDEVICE_BLOCKLIST_FILE_TAG)
} catch (e: Exception) {
Log.e(LOG_TAG_VPN, "Local brave dns set exception :${e.message}", e)
// Set local blocklist enabled to false if there is a failure creating bravedns
persistentState.blocklistEnabled = false
null
}
}
companion object {
suspend fun establish(context: Context, scope: CoroutineScope,
tunFd: ParcelFileDescriptor?): GoVpnAdapter? {
if (tunFd == null) return null
return GoVpnAdapter(context, scope, tunFd)
}
fun getIpString(context: Context?, url: String?): String {
val res: Resources? = context?.resources
val urls: Array<out String>? = res?.getStringArray(R.array.urls)
val ips: Array<out String>? = res?.getStringArray(R.array.ips)
if (urls == null) return ""
for (i in urls.indices) {
// TODO: Consider relaxing this equality condition to a match on just the domain.
// Code has been modified from equals to contains to match on the domain. Need to
// come up with some other solution to check by extracting the domain name
if (urls[i].contains((url.toString()))) {
if (ips != null) return ips[i]
}
}
return ""
}
}
init {
this.tunFd = tunFd
}
private fun io(f: suspend () -> Unit) {
externalScope.launch {
withContext(Dispatchers.IO) {
f()
}
}
}
private fun ui(f: suspend () -> Unit) {
externalScope.launch {
withContext(Dispatchers.Main) {
f()
}
}
}
}
| 169
|
Kotlin
|
47
| 557
|
161674b1cdbdd72fefee5edd953179a637e00f6f
| 20,426
|
rethink-app
|
Apache License 2.0
|
app/src/main/java/com/perqin/letmego/data/destination/DestinationRepo.kt
|
perqin
| 141,682,322
| false
| null |
package com.perqin.letmego.data.destination
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import com.perqin.letmego.App
import com.perqin.letmego.R
import com.perqin.letmego.data.place.Place
import com.perqin.letmego.data.room.appDatabase
/**
* Created by perqinxie on 2018/07/20.
*/
object DestinationRepo {
private val dao = appDatabase.destinationDao()
fun isDestinationExisting(place: Place): LiveData<Boolean> {
return Transformations.map(dao.countLiveDestination(place.latitude, place.longitude)) {
it == 1
}
}
suspend fun add(place: Place, address: String) {
val displayName = place.suggestedName?:App.context.getString(R.string.point_on_map)
dao.add(Destination(null, place.latitude, place.longitude,
Destination.COORDINATE_TENCENT, displayName, address))
}
suspend fun remove(place: Place) {
dao.remove(*dao.getDestinationsAt(place.latitude, place.longitude).toTypedArray())
}
fun getAllLiveDestinations() = dao.getAllLiveDestinations()
suspend fun updateRemarkOfDestination(destination: Destination, newRemark: String) {
dao.updateRemarkOfDestination(Destination(destination.id, destination.latitude, destination.longitude,
Destination.COORDINATE_TENCENT, newRemark, destination.address))
}
suspend fun deleteDestination(destination: Destination) {
dao.deleteDestination(destination)
}
suspend fun getDestinationById(destinationId: Long): Destination {
return dao.getDestinationById(destinationId)
}
}
| 2
|
Kotlin
|
0
| 0
|
ca98409fbf988990a0be322a6e9abbe390c61d57
| 1,618
|
let-me-go
|
MIT License
|
src/main/kotlin/extensions/RandomExtension.kt
|
Geckostya
| 728,324,326
| false
|
{"Kotlin": 5180}
|
package extensions
import math.Vec2
import kotlin.random.Random
fun Random.nextVec2(untilX: Int, untilY: Int) = Vec2(nextInt(untilX), nextInt(untilY))
| 0
|
Kotlin
|
0
| 0
|
01c0d4fc0870c30e544af517fc0b853c0bd33ed8
| 152
|
KotlinMathFighter
|
The Unlicense
|
rest/src/main/kotlin/com/gitlab/kordlib/rest/builder/user/CurrentUserModifyBuilder.kt
|
cybernetics
| 314,534,887
| true
|
{"Kotlin": 995285}
|
package com.gitlab.kordlib.rest.builder.user
import com.gitlab.kordlib.rest.Image
import com.gitlab.kordlib.common.annotation.KordDsl
import com.gitlab.kordlib.common.entity.optional.Optional
import com.gitlab.kordlib.common.entity.optional.delegate.delegate
import com.gitlab.kordlib.common.entity.optional.map
import com.gitlab.kordlib.common.entity.optional.mapNullable
import com.gitlab.kordlib.rest.builder.RequestBuilder
import com.gitlab.kordlib.rest.json.request.CurrentUserModifyRequest
@KordDsl
class CurrentUserModifyBuilder : RequestBuilder<CurrentUserModifyRequest> {
private var _username: Optional<String> = Optional.Missing()
var username: String? by ::_username.delegate()
private var _avatar: Optional<Image?> = Optional.Missing()
var avatar: Image? by ::_avatar.delegate()
override fun toRequest(): CurrentUserModifyRequest = CurrentUserModifyRequest(
_username, _avatar.mapNullable { it?.dataUri }
)
}
| 0
| null |
0
| 0
|
3bebe2f796bff84205c9ea6cceae51e2c41dee76
| 963
|
kord
|
MIT License
|
backintime-plugin/compiler/src/main/kotlin/com/github/kitakkun/backintime/compiler/backend/utils/IrBuilderUtils.kt
|
kitakkun
| 706,655,959
| false
|
{"Kotlin": 233626, "Ruby": 574}
|
package com.github.kitakkun.backintime.compiler.backend.utils
import com.github.kitakkun.backintime.compiler.backend.ValueContainerClassInfo
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope
import org.jetbrains.kotlin.ir.builders.irBlock
import org.jetbrains.kotlin.ir.builders.irBranch
import org.jetbrains.kotlin.ir.builders.irCall
import org.jetbrains.kotlin.ir.builders.irComposite
import org.jetbrains.kotlin.ir.builders.irElseBranch
import org.jetbrains.kotlin.ir.builders.irEquals
import org.jetbrains.kotlin.ir.builders.irGet
import org.jetbrains.kotlin.ir.builders.irString
import org.jetbrains.kotlin.ir.builders.irWhen
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrWhen
import org.jetbrains.kotlin.ir.types.classOrNull
context(IrPluginContext)
fun IrBuilderWithScope.irPropertySetterCall(
propertySetter: IrSimpleFunction,
dispatchReceiverParameter: IrValueParameter,
valueParameter: IrValueParameter,
) = irCall(propertySetter).apply {
this.dispatchReceiver = irGet(dispatchReceiverParameter)
putValueArgument(0, irGet(valueParameter))
}
fun IrBuilderWithScope.irPropertyGetterCall(
propertyGetter: IrSimpleFunction,
dispatchReceiverParameter: IrValueParameter,
) = irCall(propertyGetter).apply {
this.dispatchReceiver = irGet(dispatchReceiverParameter)
}
context(IrPluginContext)
fun IrBuilderWithScope.irValueContainerPropertySetterCall(
propertyGetter: IrSimpleFunction,
dispatchReceiverParameter: IrValueParameter,
valueParameter: IrValueParameter,
valueContainerClassInfo: ValueContainerClassInfo,
): IrExpression? {
val propertyGetterCall = irPropertyGetterCall(propertyGetter, dispatchReceiverParameter)
val klass = propertyGetter.returnType.classOrNull?.owner ?: return null
val preSetterCallSymbols = valueContainerClassInfo.preSetterFunctionNames
.mapNotNull { klass.getSimpleFunctionsRecursively(it).firstOrNull { it.owner.valueParameters.isEmpty() } }
val setterCallSymbol = klass.getSimpleFunctionsRecursively(valueContainerClassInfo.setterFunctionName)
.firstOrNull { it.owner.valueParameters.size == 1 } ?: return null
// 一部関数のシンボルが欠落している場合は処理継続不可
if (preSetterCallSymbols.size != valueContainerClassInfo.preSetterFunctionNames.size) return null
val preSetterCalls = preSetterCallSymbols.map { irCall(it).apply { dispatchReceiver = propertyGetterCall } }
val setterCall = irCall(setterCallSymbol).apply {
dispatchReceiver = propertyGetterCall
putValueArgument(0, irGet(valueParameter))
}
return irComposite {
+preSetterCalls
+setterCall
}
}
/**
* generate IrWhen which has branches for each properties like below:
* when (propertyName) {
* "property1" -> { /* do something */ }
* "property2" -> { /* do something */ }
* else -> { /* do something */ }
* }
*/
context(IrPluginContext)
fun IrBuilderWithScope.irWhenByProperties(
properties: List<IrProperty>,
propertyNameParameter: IrValueParameter,
buildBranchResultExpression: IrBuilderWithScope.(IrProperty) -> IrExpression?,
elseBranchExpression: IrBuilderWithScope.(propertyNameParameter: IrValueParameter) -> IrExpression,
): IrWhen {
val branches = properties.mapNotNull { property ->
val condition = irEquals(irGet(propertyNameParameter), irString(property.name.asString()))
val result = buildBranchResultExpression(property) ?: return@mapNotNull null
irBranch(condition = condition, result = result)
}.plus(irElseBranch(irBlock { +elseBranchExpression(propertyNameParameter) }))
return irWhen(
type = irBuiltIns.unitType,
branches = branches,
)
}
| 6
|
Kotlin
|
0
| 9
|
52f12b6bcb879bda7105651820391c56075d3e70
| 3,980
|
back-in-time-plugin
|
Apache License 2.0
|
plugin/src/functionalTest/kotlin/caching/ipfs/IpfsBuildCachePluginFunctionalTest.kt
|
galargh
| 431,016,149
| false
|
{"Shell": 34361, "Kotlin": 17388, "Makefile": 1714, "Dockerfile": 642}
|
package caching.ipfs
import kotlin.test.Test
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.rules.TemporaryFolder
/**
* A simple functional test for the 'caching.ipfs.ipfs-build-cache' plugin.
*/
class IpfsBuildCachePluginFunctionalTest {
@get:Rule val tempFolder = TemporaryFolder()
private fun getProjectDir() = tempFolder.root
private fun getBuildFile() = getProjectDir().resolve("build.gradle")
private fun getSettingsFile() = getProjectDir().resolve("settings.gradle")
@Test fun `can start IpfsBuildCache`() {
// Setup the test build
getSettingsFile().writeText("""
plugins {
id('caching.ipfs.ipfs-build-cache')
}
buildCache {
local {
enabled = false
}
remote(caching.ipfs.IpfsBuildCache) {
push = true
}
}
""")
getBuildFile().writeText("")
// Run the build
val runner = GradleRunner.create()
runner.withPluginClasspath()
runner.withArguments("help", "--build-cache")
runner.withProjectDir(getProjectDir())
runner.build();
}
}
| 12
|
Shell
|
1
| 3
|
d4a7c3cd4e84a419845f675c13e6920d207e45d6
| 1,110
|
gradle-ipfs-build-cache
|
MIT License
|
engine/src/main/kotlin/de/hanno/hpengine/transform/EntityAddedSystem.kt
|
hannomalie
| 330,376,962
| false
|
{"Kotlin": 1068277, "GLSL": 681257, "JavaScript": 3160, "Shell": 137, "Batchfile": 65}
|
package de.hanno.hpengine.transform
import com.artemis.BaseEntitySystem
import com.artemis.BaseSystem
import com.artemis.annotations.All
import com.artemis.utils.IntBag
import de.hanno.hpengine.component.TransformComponent
import de.hanno.hpengine.graphics.state.RenderState
import de.hanno.hpengine.model.EntitiesStateHolder
import de.hanno.hpengine.system.Extractor
import org.koin.core.annotation.Single
@Single(binds = [BaseSystem::class, EntityAddedSystem::class, Extractor::class])
@All(value = [TransformComponent::class])
class EntityAddedSystem (
private val entitiesStateHolder: EntitiesStateHolder,
): BaseEntitySystem(), Extractor {
var cycle = 0L
var entityAddedInCycle = 0L
var componentAddedInCycle = 0L
override fun inserted(entities: IntBag?) {
entityAddedInCycle = cycle
componentAddedInCycle = cycle
}
override fun processSystem() {
cycle++
}
override fun extract(currentWriteState: RenderState) {
val entitiesState = currentWriteState[entitiesStateHolder.entitiesState]
entitiesState.entityAddedInCycle = entityAddedInCycle
entitiesState.componentAddedInCycle = componentAddedInCycle
}
}
| 0
|
Kotlin
|
0
| 0
|
d0ecc78d2d90033758d480b2383d8d5c3d2febd3
| 1,200
|
hpengine
|
MIT License
|
aboutlibraries-core/src/commonMain/kotlin/com/mikepenz/aboutlibraries/entity/Funding.kt
|
mikepenz
| 19,025,014
| false
|
{"Kotlin": 519334, "JavaScript": 13528, "CSS": 10378, "HTML": 8580, "Ruby": 2019, "Python": 1500, "Shell": 254}
|
package com.mikepenz.aboutlibraries.entity
/**
* Describes the [Funding] as defined by the dependency.
* This is only supported for projects hosted for dependencies hosted on: https://github.com/mikepenz/AboutLibraries#special-repository-support
* Or can be manually supplied.
*
* @param platform name of the platform allowing to fund the project
* @param url url pointing towards the location to fund the project
*/
data class Funding(
val platform: String,
val url: String
)
| 8
|
Kotlin
|
441
| 3,445
|
78ecebfc979b25d9afd1a9e316ed88821487aa23
| 492
|
AboutLibraries
|
Apache License 2.0
|
app/src/main/java/com/panda/pda/app/operation/qms/quality_task_detail/QualityDetailFragment.kt
|
Givennn
| 402,701,983
| false
| null |
package com.panda.pda.app.operation.qms.quality_task_detail
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import by.kirich1409.viewbindingdelegate.viewBinding
import com.google.android.material.tabs.TabLayoutMediator
import com.panda.pda.app.R
import com.panda.pda.app.base.BaseFragment
import com.panda.pda.app.base.extension.getGenericObjectString
import com.panda.pda.app.base.extension.getStringObject
import com.panda.pda.app.base.retrofit.DataListNode
import com.panda.pda.app.databinding.FragmentQualityDetailBinding
import com.panda.pda.app.operation.qms.data.model.QualityDetailModel
import com.panda.pda.app.operation.qms.data.model.QualitySubTaskDetailModel
import com.panda.pda.app.operation.qms.data.model.QualityTaskRecordModel
import com.squareup.moshi.Types
/**
* created by AnJiwei 2021/9/28
*/
class QualityDetailFragment : BaseFragment(R.layout.fragment_quality_detail) {
private val viewBinding by viewBinding<FragmentQualityDetailBinding>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.topAppBar.setNavigationOnClickListener { navBackListener.invoke(it) }
val recordList = arguments?.getGenericObjectString<DataListNode<QualityTaskRecordModel>>(
Types.newParameterizedType(
DataListNode::class.java,
QualityTaskRecordModel::class.java
)
)
val subTask = arguments?.getStringObject<QualitySubTaskDetailModel>()
val task = arguments?.getStringObject<QualityDetailModel>()
viewBinding.apply {
viewPage.adapter = object : FragmentStateAdapter(parentFragmentManager, lifecycle) {
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> QualityDetailInfoFragment(subTask, task)
1 -> QualityDetailRecordFragment(recordList)
else -> throw IndexOutOfBoundsException()
}
}
}
TabLayoutMediator(tabLayout, viewPage) { tab, position ->
tab.text = when (position) {
0 -> getString(R.string.basic_info)
1 -> getString(R.string.operate_record)
else -> ""
}
}.attach()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
24f6284eed22b1fe91b5462a0cdd5a466d6531ad
| 2,609
|
pda
|
MIT License
|
buildSrc/src/main/java/Versions.kt
|
TeiganPenna
| 521,852,619
| false
| null |
import java.util.Locale
object Versions {
// Sdk and tools
const val COMPILE_SDK = 33
const val MIN_SDK = 30
const val TARGET_SDK = 30
const val DETEKT_TWITTER = "0.0.26"
// App dependencies
const val ACCOMPANIST = "0.28.0"
const val ACTIVITY_COMPOSE = "1.6.1"
const val COMPOSE = "1.3.2"
const val COMPOSE_MATERIAL = "1.3.1"
const val COMPOSE_REORDERABLE = "0.9.6"
const val COMPOSE_RUNTIME = "1.3.3"
const val COMPOSE_UI = "1.3.3"
const val HILT = "2.44.2"
const val HILT_NAVIGATION = "1.0.0"
const val KTX = "1.9.0"
const val LIFECYCLE = "2.5.1"
const val NAVIGATION_COMPOSE = "2.5.3"
const val ROOM = "2.5.0"
// Test dependencies
const val ANDROID_TEST_RUNNER = "1.5.2"
const val ASSERTJ = "3.24.1"
const val CORE_TESTING = "2.1.0"
const val ESPRESSO = "3.5.1"
const val JUNIT_JUPITER_ANDROID = "1.3.0"
const val JUNIT_JUPITER = "5.9.2"
const val KOTLINX_COROUTINES = "1.6.4"
const val MOCKITO_ANDROID = "4.11.0"
const val MOCKITO_KOTLIN = "4.1.0"
const val MOCKK = "1.13.3"
const val TEST_EXT_JUNIT = "1.1.5"
fun isStable(version: String): Boolean {
val stableKeyword = listOf("RELEASE", "FINAL", "GA")
.any { version.toUpperCase(Locale.getDefault()).contains(it) }
val regex = "^[0-9,.v-]+(-r)?$".toRegex()
return stableKeyword || regex.matches(version)
}
}
| 2
|
Kotlin
|
0
| 0
|
b4aad40ec8250d8ffcf2f45c9a7b3e31e229ee3a
| 1,437
|
SpotGym
|
Apache License 2.0
|
src/test/kotlin/com/cognifide/gradle/common/CommonPluginTest.kt
|
wttech
| 237,183,159
| false
| null |
package com.cognifide.gradle.common
import org.gradle.testfixtures.ProjectBuilder
import kotlin.test.Test
class CommonPluginTest {
@Test fun `plugin could be set up`() {
// Create a test project and apply the plugin
val project = ProjectBuilder.builder().build()
project.plugins.apply("com.cognifide.gradle.common")
// Verify the result
// assertNotNull(project.tasks.findByName("greeting"))
}
}
| 9
|
Kotlin
|
1
| 1
|
d184caf617d63c3ed5fa827db6b936c79ad2bc05
| 447
|
gradle-common-plugin
|
Apache License 2.0
|
src/main/kotlin/com/msg/gcms/domain/image/presentation/data/dto/UploadImagesDto.kt
|
GSM-MSG
| 592,816,374
| false
| null |
package com.msg.gcms.domain.image.presentation.data.dto
import org.springframework.web.multipart.MultipartFile
data class UploadImagesDto (
val images: List<MultipartFile>
)
| 10
|
Kotlin
|
0
| 8
|
d55e8ed3f343acca0c3937cf07b6fcfb8dd30598
| 179
|
GCMS-BackEnd
|
MIT License
|
src/main/kotlin/ray/mintcat/barrier/event/BarrierPlayerLeavePolyEvent.kt
|
FxRayHughes
| 469,282,424
| false
|
{"Kotlin": 64842}
|
package ray.mintcat.barrier.event
import org.bukkit.entity.Player
import ray.mintcat.barrier.common.BarrierPoly
import taboolib.platform.type.BukkitProxyEvent
class BarrierPlayerJoinPolyEvent(
val player: Player,
val poly: BarrierPoly
) : BukkitProxyEvent()
| 1
|
Kotlin
|
6
| 4
|
c2b78a9e72a2eb4ed757ca53e2eaa36d1c3a2fcf
| 267
|
Barrier
|
Creative Commons Zero v1.0 Universal
|
lib/src/test/kotlin/me/tb/cashuclient/UtilitiesTest.kt
|
thunderbiscuit
| 639,993,752
| false
| null |
/*
* Copyright 2023 thunderbiscuit and contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the ./LICENSE file.
*/
package me.tb.cashuclient
import fr.acinq.bitcoin.PublicKey
import fr.acinq.secp256k1.Hex
import me.tb.cashuclient.types.SwapRequired
import java.lang.IllegalArgumentException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UtilitiesTest {
@Test
fun `splitAmount correctly splits small amounts`() {
assertEquals<List<ULong>>(
expected = listOf<ULong>(1uL, 4uL, 8uL),
actual = decomposeAmount(13uL)
)
}
// ULong.MAX_VALUE = 18446744073709551615
@Test
fun `splitAmount correctly splits large amounts`() {
assertEquals<List<ULong>>(
expected = listOf(1uL, 2uL, 4uL, 8uL, 16uL, 32uL, 64uL, 128uL, 256uL, 512uL, 1024uL, 2048uL, 4096uL, 8192uL, 16384uL, 32768uL, 65536uL, 131072uL, 262144uL, 524288uL, 1048576uL, 2097152uL, 4194304uL, 8388608uL, 16777216uL, 33554432uL, 67108864uL, 134217728uL, 268435456uL, 536870912uL, 1073741824uL, 2147483648uL, 4294967296UL, 8589934592UL, 17179869184UL, 34359738368UL, 68719476736UL, 137438953472UL, 274877906944UL, 549755813888UL, 1099511627776uL, 2199023255552uL, 4398046511104uL, 8796093022208uL, 17592186044416uL, 35184372088832uL, 70368744177664uL, 140737488355328uL, 281474976710656uL, 562949953421312uL, 1125899906842624uL, 2251799813685248uL, 4503599627370496uL, 9007199254740992uL, 18014398509481984uL, 36028797018963968uL, 72057594037927936uL, 144115188075855872uL, 288230376151711744uL, 576460752303423488uL, 1152921504606846976uL, 2305843009213693952uL, 4611686018427387904uL, 9223372036854775808uL),
actual = decomposeAmount(18446744073709551615uL)
)
}
@Test
fun `splitAmount throws an exception on 0 amount values`() {
assertFailsWith<IllegalArgumentException> {
decomposeAmount(0uL)
}
}
// @Test
// fun `splitAmount throws an exception on negative amount values`() {
// assertFailsWith<IllegalArgumentException> {
// splitAmount(-1)
// }
// }
@Test
fun `hashToCurve returns correct point 1`() {
val point: PublicKey = hashToCurve(Hex.decode("0000000000000000000000000000000000000000000000000000000000000000"))
assertEquals<String>(
expected = "0266687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925",
actual = point.toHex()
)
}
@Test
fun `hashToCurve returns correct point 2`() {
val point: PublicKey = hashToCurve(Hex.decode("0000000000000000000000000000000000000000000000000000000000000001"))
assertEquals<String>(
expected = "02ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5",
actual = point.toHex()
)
}
@Test
fun `hashToCurve returns correct point after some iterations`() {
val point: PublicKey = hashToCurve(Hex.decode("0000000000000000000000000000000000000000000000000000000000000002"))
assertEquals<String>(
expected = "02076c988b353fcbb748178ecb286bc9d0b4acf474d4ba31ba62334e46c97c416a",
actual = point.toHex()
)
}
@Test
fun `isSplitRequired works as intended`() {
val denominations = listOf<ULong>(64uL, 32uL, 16uL, 16uL, 4uL, 4uL, 4uL, 1uL)
val splitRequired = isSwapRequired(denominations, 87uL)
assertEquals(
expected = SwapRequired.Yes(requiredAmount = 23uL, almostFinishedList = listOf(64uL), availableForSwap = listOf<ULong>(32uL, 16uL, 16uL, 4uL, 4uL, 4uL, 1uL)),
actual = splitRequired
)
}
}
| 1
| null |
1
| 5
|
c32fa92a7323527de822c474a96520d64cdb0a56
| 3,747
|
cashu-client
|
Apache License 2.0
|
EmergencyApp/app/src/main/java/com/dicoding/emergencyapp/data/retrofit/news/NewsApiConfig.kt
|
briancatraguna
| 364,262,679
| false
| null |
package com.dicoding.emergencyapp.data.retrofit.news
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class NewsApiConfig {
companion object {
fun getApiService(): NewsApiService{
val loggingInterceptor =
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://newsapi.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
return retrofit.create(NewsApiService::class.java)
}
}
}
| 1
|
Kotlin
|
2
| 9
|
5e2d2f6325650bdf5b406876270dd9dbbfda9491
| 877
|
SixPackTeamApp
|
MIT License
|
151004/Bashlikov/rv_task01/src/main/kotlin/by/bashlikovvv/domain/repository/ITweetsRepository.kt
|
4ndreSha
| 786,098,271
| true
|
{"Markdown": 8, "Text": 9, "Ignore List": 61, "Shell": 22, "Maven POM": 64, "Batchfile": 21, "Java": 2243, "INI": 70, "XML": 192, "JSON": 157, "YAML": 37, "JSON with Comments": 3, "SQL": 14, "Microsoft Visual Studio Solution": 27, "C#": 1212, "Go Checksums": 1, "Go Module": 1, "Go": 20, "Java Properties": 8, "HTML": 3, "Git Attributes": 3, "HTTP": 19, "Gradle": 2, "JavaScript": 1, "Gradle Kotlin DSL": 21, "Dockerfile": 4, "Kotlin": 343, "OASv3-yaml": 1, "TOML": 1, "EditorConfig": 7, "CSS": 4, "HTML+Razor": 6, "Java Server Pages": 5}
|
package by.bashlikovvv.domain.repository
import by.bashlikovvv.api.dto.response.TweetDto
interface ITweetsRepository : IBaseRepository<TweetDto, Long>
| 0
|
Java
|
0
| 0
|
dc1c5a73e76fe62335aa4615069a19d257f5b3b3
| 152
|
DC2024-01-27
|
MIT License
|
app/src/main/java/com/jbc7ag/apod/network/ImagesNasaProperty.kt
|
jbc7ag
| 398,625,964
| false
| null |
package com.jbc7ag.apod.network
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
@Parcelize
data class ImagesNasaProperty(
val collection: DataImages,
): Parcelable
@Parcelize
data class DataImages(
val version: String?,
val metadata: Metadata?,
val href: String?,
val items: List<Items>,
@Json(name= "links")
val pagination: List<Pagination>?,
): Parcelable
@Parcelize
data class Metadata(
val total_hits: Int?
): Parcelable
@Parcelize
data class Items(
val data: List<DataItems>,
val href: String?,
val links: List<Links>?,
): Parcelable
@Parcelize
data class DataItems(
val nasa_id: String,
val secondary_creator: String?,
val description: String?,
val title: String?,
val keywords: Array<String>?,
val center: String?,
@Json(name = "date_created")
val dataCreated: String?,
@Json(name = "description_508")
val description508: String?,
@Json(name = "media_type")
val mediaType: String?
): Parcelable
@Parcelize
data class Links(
val render: String?,
val href: String?,
val rel: String?,
): Parcelable
@Parcelize
data class Pagination(
val prompt: String?,
val href: String?,
val rel: String?,
): Parcelable
| 0
|
Kotlin
|
0
| 0
|
77bf6bb25302e22b7f5878622e575618a35bd9d9
| 1,287
|
apod
|
MIT License
|
odinmain/src/main/kotlin/me/odinmain/commands/impl/TermsimCommand.kt
|
odtheking
| 657,580,559
| false
|
{"Kotlin": 957390, "Java": 106846, "GLSL": 17728}
|
package me.odinmain.commands.impl
import me.odinmain.commands.commodore
import me.odinmain.features.impl.floor7.p3.termsim.*
import me.odinmain.utils.ServerUtils
import me.odinmain.utils.getRandom
import net.minecraft.item.EnumDyeColor
import kotlin.math.round
val termSimCommand = commodore("termsim") {
runs { ping: Long?, amount: Long? ->
if (amount == null) StartGui.open(ping ?: 0)
else openTerminal(ping ?: 0, amount)
} suggests {
listOf(round(ServerUtils.averagePing).toLong().toString())
}
runs{ string: String, ping: Long? ->
when (string) {
"pains" -> CorrectPanes.open(ping ?: 0, 1)
"rubix" -> Rubix.open(ping ?: 0, 1)
"order" -> InOrder.open(ping ?: 0, 1)
"sw" -> StartsWith(StartsWith.letters.shuffled().first()).open(ping ?: 0, 1)
"select" -> SelectAll(EnumDyeColor.entries.getRandom().name.replace("_", " ").uppercase()).open(ping ?: 0, 1)
}
}
}
| 4
|
Kotlin
|
17
| 41
|
631b297e1c74272c409f7db1cbf86c8c334e7915
| 985
|
Odin
|
MIT License
|
app/src/main/java/com/zhangteng/app/mvvm/repository/BaseMvvmDemoFragmentRepository.kt
|
DL-ZhangTeng
| 536,516,272
| false
|
{"Kotlin": 192886}
|
package com.zhangteng.app.mvvm.repository
import com.zhangteng.mvvm.base.BaseNetRepository
class BaseMvvmDemoFragmentRepository : BaseNetRepository() {
private val mService by lazy {
//HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java)
}
}
| 0
|
Kotlin
|
0
| 1
|
b8d0d469cc342abf95f874c028e17b25e636f250
| 281
|
MVVM
|
The Unlicense
|
ynab-http/src/main/kotlin/dev/danperez/ynab/http/CategoriesService.kt
|
danielPerez97
| 619,363,218
| false
| null |
package dev.danperez.ynab.http
import dev.danperez.ynab.json.Response
import dev.danperez.ynab.json.budget.Category
import dev.danperez.ynab.json.budget.CategoryGroup
import retrofit2.http.GET
import retrofit2.http.PATCH
import retrofit2.http.Path
interface CategoriesService
{
/**
* @param budgetId The id of the budget. “last-used” can be used to specify the last used budget and “default” can
* be used if default budget selection is enabled (see: https://api.ynab.com/#oauth-default-budget).
*/
@GET("/budget/{budget_id}/categories")
suspend fun getCategories(
@Path("budget_id") budgetId: String,
): Response<List<CategoryGroup>>
/**
* @param budgetId The id of the budget. “last-used” can be used to specify the last used budget and “default” can
* be used if default budget selection is enabled (see: https://api.ynab.com/#oauth-default-budget).
*
* @param categoryId The id of the category
*/
@GET("/budget/{budget_id}/categories/{category_id}")
suspend fun getCategoryById(
@Path("budget_id") budgetId: String,
@Path("category_id") categoryId: String,
): Response<Category>
/**
* @param budgetId The id of the budget. “last-used” can be used to specify the last used budget and “default” can
* be used if default budget selection is enabled (see: https://api.ynab.com/#oauth-default-budget).
*
* @param month The budget month in ISO format (e.g. 2016-12-01) (“current” can also be used to specify the current calendar month (UTC))
*
* @param categoryId The id of the category
*/
@GET("/budget/{budget_id}/months/{month}/categories/{category_id}")
suspend fun getCategoryForMonth(
@Path("budget_id") budgetId: String,
@Path("month") month: String,
@Path("category_id") categoryId: String,
): Response<Category>
/**
* @param budgetId The id of the budget. “last-used” can be used to specify the last used budget and “default” can
* be used if default budget selection is enabled (see: https://api.ynab.com/#oauth-default-budget).
*
* @param month The budget month in ISO format (e.g. 2016-12-01) (“current” can also be used to specify the current calendar month (UTC))
*
* @param categoryId The id of the category
*/
@PATCH("/budget/{budget_id}/months/{month}/categories/{category_id}")
suspend fun updateCategoryForMonth(
@Path("budget_id") budgetId: String,
@Path("month") month: String,
@Path("category_id") categoryId: String,
): Response<Category>
}
| 0
|
Kotlin
|
0
| 0
|
c3707ad6b5a934240535aaf9594f297fd38ad9c6
| 2,612
|
ynab-kmp
|
Apache License 2.0
|
app/src/main/java/pl/grajek/actions/util/Extentions.kt
|
dawids222
| 169,272,010
| false
| null |
package pl.grajek.actions.util
import android.content.SharedPreferences
import android.support.design.widget.TabLayout
import java.util.*
fun TabLayout.next() {
val tab = getTabAt(selectedTabPosition + 1)
tab?.select()
}
fun TabLayout.previous() {
val tab = getTabAt(selectedTabPosition - 1)
tab?.select()
}
fun Date.now(): Date {
val milliseconds = System.currentTimeMillis()
return Date(milliseconds)
}
fun Date.add(milliseconds: Long): Date {
val time = this.time + milliseconds
return Date(time)
}
fun SharedPreferences.edit(callback: (SharedPreferences.Editor) -> Unit) {
val editor = this.edit()
callback(editor)
editor.apply()
}
| 0
|
Kotlin
|
0
| 0
|
dc8c674b0b171ee68698133bcd023b2e26279612
| 685
|
Actions
|
MIT License
|
src/main/kotlin/neverwintertoolkit/file/key/KeyFile.kt
|
jeffmcclure
| 775,771,544
| false
|
{"Kotlin": 588796, "Shell": 226}
|
package neverwintertoolkit.file.key
import neverwintertoolkit.FileTypeIdMap
import neverwintertoolkit.command.GlobalOptions
import neverwintertoolkit.file.bif.BifFile
import neverwintertoolkit.readString
import neverwintertoolkit.readStringNullTerminated
import neverwintertoolkit.readUInt
import neverwintertoolkit.readUShort
import java.io.BufferedInputStream
import java.io.RandomAccessFile
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.nio.file.Paths
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import kotlin.io.path.inputStream
import kotlin.io.path.name
class KeyFile(val file: Path, val globalOptions: GlobalOptions = GlobalOptions()) {
val status = globalOptions.status
val keyHeder: KeyHeader by lazy { readHeader() }
data class KeyHeader(
val fileType: String,
val fileVersion: String,
val bifCount: UInt = 0u,
val keyCount: UInt = 0u,
val offsetToFileTable: UInt = 0u,
val offsetToKeyTable: UInt = 0u,
var buildYear: UInt = 0u,
var buildDay: UInt = 0u,
var buildDate: LocalDate = LocalDate.parse(
"${buildYear.toInt() + 1900}-${buildDay.inc().toString().padStart(3, '0')}",
DateTimeFormatter.ISO_ORDINAL_DATE
),
val reserved: ByteArray = ByteArray(0)
)
private fun readHeader(): KeyHeader {
file.inputStream().buffered().use { input ->
val fileType = input.readString(4)
val fileVersion = input.readString(4)
val bifCount = input.readUInt()
val keyCount = input.readUInt()
val offsetToFileTable = input.readUInt()
val offsetToKeyTable = input.readUInt()
val buildYear = input.readUInt()
val buildDay = input.readUInt()
var reserved = input.readNBytes(32)
// val dateStr = "${buildYear.toInt() + 1900}-${buildDay.inc().toString().padStart(3, '0')}"
// val buildDate = LocalDate.parse(dateStr, DateTimeFormatter.ISO_ORDINAL_DATE)
if ("KEY " != fileType) throw RuntimeException("Warning fileType != 'KEY ' for $file")
return KeyHeader(
fileType = fileType,
fileVersion = fileVersion,
bifCount = bifCount,
keyCount = keyCount,
offsetToFileTable = offsetToFileTable,
offsetToKeyTable = offsetToKeyTable,
buildYear = buildYear,
buildDay = buildDay,
reserved = reserved,
)
}
}
data class FileEntry(
val index: Int,
val fileSize: UInt,
val filenameOffset: UInt,
val filenameSize: UShort,
val drives: UShort,
val fileName: String
)
fun list(patterns: List<String>, printArchiveName: Boolean) {
globalOptions.logTrace { keyHeder.toString() }
listFiles(patterns)
listKeys(patterns, printArchiveName, false)
}
fun extract(patterns: List<String>, printArchiveName:Boolean, toStdout: Boolean = false) {
listKeys(patterns, printArchiveName=printArchiveName, extract = true, toStdout = toStdout)
}
val files: List<FileEntry> by lazy { readFiles() }
private fun listFiles(patterns: List<String> = emptyList()) {
val rePatterns: List<PathMatcher> = patterns.map { FileSystems.getDefault().getPathMatcher("glob:${it.lowercase()}") } ?: emptyList()
files.forEach { fileEntry: FileEntry ->
if (globalOptions.traceEnabled || rePatterns.isEmpty() || rePatterns.any { it.matches(Path.of(fileEntry.fileName.lowercase()).fileName) })
if (globalOptions.traceEnabled)
status.println(fileEntry)
else
status.println(fileEntry.fileName)
}
}
private fun readFiles(): List<FileEntry> {
return RandomAccessFile(file.toFile(), "r").use { input ->
(0..<keyHeder.bifCount.toInt()).map { index ->
input.seek(keyHeder.offsetToFileTable.toLong() + index * 12)
val fileSize = input.readUInt()
val filenameOffset = input.readUInt()
val filenameSize = input.readUShort()
val drives = input.readUShort()
input.seek(filenameOffset.toLong())
val fileName = input.readString(filenameSize.toInt()).replace('\\', '/')
val fileEntry = FileEntry(
index = index,
fileSize = fileSize,
filenameOffset = filenameOffset,
filenameSize = filenameSize,
drives = drives,
fileName = fileName
)
fileEntry
}
}
}
data class KeyEntry(
val resRef: String,
val resourceType: UShort,
val resId: UInt,
val fileIndex: Int? = null,
val resourceIndex: Int? = null,
val fullPath: Path
)
fun listKeys(patternsx: List<String>, extract: Boolean, printArchiveName: Boolean, toStdout: Boolean = false) {
val rePatterns: List<PathMatcher> = patternsx.map { FileSystems.getDefault().getPathMatcher("glob:${it.lowercase()}") } ?: emptyList()
file.inputStream().buffered().use { input: BufferedInputStream ->
// input.seek(keyHeder.offsetToKeyTable.toLong() + it * 22)
input.skip(keyHeder.offsetToKeyTable.toLong())
repeat(keyHeder.keyCount.toInt()) {
val resRef = input.readStringNullTerminated(16)
val resourceType = input.readUShort()
val resId = input.readUInt()
val fileIndex = resId.toInt() shr 20
val resourceIndex = resId.toInt() - (fileIndex shl 20)
val fileEntry = files[fileIndex]
val resourceName = resRef.lowercase() + FileTypeIdMap[resourceType.toInt()]!!.extension
val dir = Paths.get(fileEntry.fileName)
val fullPath = dir.resolve(resourceName)
val keyEntry = KeyEntry(
resRef = resRef,
resourceType = resourceType,
resId = resId,
fileIndex = fileIndex,
resourceIndex = resourceIndex,
fullPath = fullPath
)
if (rePatterns.isEmpty() || rePatterns.any { it.matches(fullPath.fileName) }) {
if (extract) {
val bifFile = file.parent.parent.resolve(Path.of(fileEntry.fileName))
val bif = BifFile(bifFile, globalOptions)
val varResourcEntry = bif.getVariableEntry(resourceIndex)
if (!toStdout) {
if (!Files.isDirectory(dir))
Files.createDirectories(dir)
if (printArchiveName)
status.format("%s Extracting: %-50s %10d", file.name, fullPath, varResourcEntry.fileSize.toLong())
else
status.format(" Extracting: %-50s %10d", fullPath, varResourcEntry.fileSize.toLong())
status.flush()
bif.extract(resourceIndex, fullPath)
status.println()
} else {
if (printArchiveName)
System.out.format("Extracting: %-50s %10d\n", fullPath, varResourcEntry.fileSize.toLong())
else
System.out.format("%s Extracting: %-50s %10d\n", file.name, fullPath, varResourcEntry.fileSize.toLong())
bif.extract(resourceIndex, System.out)
}
} else {
if (globalOptions.traceEnabled)
if (printArchiveName)
status.format("%s %s", file.name, keyEntry)
else
status.println(keyEntry)
else if (globalOptions.debugEnabled) {
val bifFile = file.parent.parent.resolve(Path.of(fileEntry.fileName))
val bif = BifFile(bifFile, globalOptions)
val varResourcEntry = bif.getVariableEntry(resourceIndex)
status.format("%-50s %10d\n", keyEntry.fullPath, varResourcEntry.fileSize.toLong())
} else
status.println(fullPath)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cee94ea196ec37bebcfde75f6dc402f088d58bb4
| 8,886
|
nwt
|
MIT License
|
app/src/main/kotlin/au/id/rlac/unitconverter/converter/UnitConverter.kt
|
rlac
| 36,999,945
| false
| null |
package au.id.rlac.unitconverter.converter
import android.content.Context
import au.id.rlac.unitconverter.R
import au.id.rlac.util.android.use
import java.math.BigDecimal
import java.util.*
/**
* Converts a numeric value for one [Measure] to the equivalent value for another [Measure].
*
* A [UnitConverter] has a base [Measure] along with a set of [Conversion] objects that can convert
* values to and from the base [Measure] to their own [Measure].
*
* @property base The base [Measure] all [converters] work with.
* @property displayNameResId Display name for the unit converter.
* @property theme The theme associated with this unit converter.
* @param converters Converters that convert to the [base]. Each [Conversion] is adds its [Measure]
* as a supported type to this unit converter.
*/
enum class UnitConverter(private val base: Measure,
val displayNameResId: Int,
val theme: Int,
vararg converters: Conversion) {
TEMPERATURE(
Measure.CELSIUS,
R.string.temperature,
R.style.TemperatureTheme,
Conversion.fahrenheit),
LENGTH(
Measure.METRE,
R.string.length,
R.style.LengthTheme,
Conversion(Measure.CENTIMETRE, BigDecimal(0.01)),
Conversion(Measure.KILOMETRE, BigDecimal(1000.0)),
Conversion(Measure.INCH, BigDecimal(0.0254)),
Conversion(Measure.FEET, BigDecimal(0.3048)),
Conversion(Measure.YARD, BigDecimal(0.9144)),
Conversion(Measure.MILE, BigDecimal(1609.344))),
MASS(
Measure.GRAM,
R.string.mass,
R.style.MassTheme,
Conversion(Measure.OUNCE, BigDecimal(28.3495)),
Conversion(Measure.STONE, BigDecimal(6350.29)),
Conversion(Measure.POUND, BigDecimal(453.592)),
Conversion(Measure.KILOGRAM, BigDecimal(1000.0))),
VOLUME(
Measure.LITRE,
R.string.volume,
R.style.VolumeTheme,
Conversion(Measure.MILLILITRE, BigDecimal(0.001)),
Conversion(Measure.FLUIDOUNCE, BigDecimal(0.0295735)),
Conversion(Measure.CUP, BigDecimal(0.236588)),
Conversion(Measure.PINT, BigDecimal(0.473176)),
Conversion(Measure.GALLON, BigDecimal(3.78541))),
ENERGY(
Measure.KILOJOULE,
R.string.energy,
R.style.EnergyTheme,
Conversion(Measure.KILOCALORIE, BigDecimal(4.184)));
class Theme private constructor(val colorPrimary: Int, val colorPrimaryDark: Int) {
companion object {
operator fun invoke(context: Context, uc: UnitConverter): Theme {
with(context.getResources().newTheme()) {
setTo(context.getTheme())
applyStyle(uc.theme, true)
return obtainStyledAttributes(R.styleable.AppCompatTheme).use {
Theme(it.getColor(R.styleable.AppCompatTheme_colorPrimary, 0),
it.getColor(R.styleable.AppCompatTheme_colorPrimaryDark, 0))
}
}
}
}
}
private val converterMap: Map<Measure, Conversion> = Collections.unmodifiableMap(
with(HashMap<Measure, Conversion>()) {
converters.forEach { c -> put(c.targetMeasurement, c) }
put(base, Conversion(base, BigDecimal.ONE))
this
})
/**
* @param forSystem If set filters the list to measurements for this system only.
* @return the list of units supported by this converter's convert method.
*/
fun supportedUnits(forSystem: MeasurementSystem? = null): List<Measure> =
with(converterMap.map({ it.key }).sortedBy { it.weight }) {
if (forSystem == null) this
else filter { it.system == forSystem }
}
/**
* Convert the value of a unit to its equivalent value as another measure.
*
* @param from The unit type to convert from.
* @param to The unit type to convert to.
* @param value The value of the unit to convert from.
* @return the converted value.
* @throws IllegalArgumentException if the from or to unit is not supported by the converter.
*/
fun convert(from: Measure, to: Measure, value: BigDecimal): BigDecimal {
val fromConverter = converterMap[from]
val toConverter = converterMap[to]
if (fromConverter == null) throw IllegalArgumentException("from unit ${from} not supported.")
if (toConverter == null) throw IllegalArgumentException("to unit ${to} not supported.")
return toConverter.fromBase(fromConverter.toBase(value))
}
}
| 0
|
Kotlin
|
0
| 3
|
5db7673e848db323b6a78eb501d7cf4d65be123b
| 4,385
|
unitconverter
|
Apache License 2.0
|
src/main/kotlin/khome/entities/StateAndAttributes.kt
|
cybernetics
| 281,265,077
| true
|
{"Kotlin": 161626}
|
package khome.entities
import java.time.Instant
/**
* The State interface
*
* Defines the minimum structure of a valid state object.
*
* @param T the type of the actual state value.
*/
interface State<T> {
val value: T
}
/**
* The Attributes interface
*
* Defines the minimum structure of a valid attributes object.
* */
interface Attributes {
val userId: String?
val lastChanged: Instant
val lastUpdated: Instant
val friendlyName: String
}
| 0
| null |
0
| 0
|
68391c731b7489b3f7a69faaf807f7a95bb17e25
| 474
|
khome
|
MIT License
|
src/main/kotlin/dsl/DSLToolbarExtension.kt
|
isyscore
| 336,950,526
| false
|
{"Kotlin": 220307, "Java": 5620, "HTML": 643}
|
@file:Suppress("unused", "DuplicatedCode")
package com.isyscore.kotlin.swing.dsl
import com.isyscore.kotlin.swing.component.*
import com.isyscore.kotlin.swing.inline.newClassInstance
import org.apache.batik.anim.dom.SAXSVGDocumentFactory
import org.apache.batik.swing.JSVGCanvas
import org.apache.batik.util.XMLResourceDescriptor
import java.awt.*
import java.io.File
import java.io.InputStream
import java.net.URI
import java.net.URL
import java.util.*
import javax.swing.*
import javax.swing.table.TableColumnModel
import javax.swing.table.TableModel
import javax.swing.tree.TreeModel
import javax.swing.tree.TreeNode
@ContextDsl
fun rootToolbar(orientation: Int = JToolBar.HORIZONTAL, block: JToolBar.() -> Unit): JToolBar = JToolBar(orientation).apply(block)
fun JToolBar.panel(layout: LayoutManager? = BorderLayout(), block: JPanel.() -> Unit): JPanel {
val pnl = JPanel(layout).apply(block)
add(pnl)
return pnl
}
fun JToolBar.borderPanel(hgap: Int = 0, vgap: Int = 0, block: BorderPanel.() -> Unit): BorderPanel {
val pnl = BorderPanel(hgap, vgap).apply(block)
add(pnl)
return pnl
}
fun JToolBar.clearPanel(block: ClearPanel.() -> Unit): ClearPanel {
val pnl = ClearPanel().apply(block)
add(pnl)
return pnl
}
fun JToolBar.vertPanel(align: Int = VertFlowLayout.TOP, hgap: Int = 4, vgap: Int = 4, hfill: Boolean = true, vfill: Boolean = false, block: VertPanel.() -> Unit): VertPanel {
val pnl = VertPanel(align, hgap, vgap, hfill, vfill).apply(block)
add(pnl)
return pnl
}
fun JToolBar.horzPanel(align: Int = FlowLayout.CENTER, hgap: Int = 5, vgap: Int = 5, block: HorzPanel.() -> Unit): HorzPanel {
val pnl = HorzPanel(align, hgap, vgap).apply(block)
add(pnl)
return pnl
}
fun JToolBar.gridPanel(rows: Int, cols: Int, hgap: Int = 0, vgap: Int = 0, block: GridPanel.() -> Unit): GridPanel {
val pnl = GridPanel(rows, cols, hgap, vgap).apply(block)
add(pnl)
return pnl
}
fun JToolBar.wrapPanel(align: Int = FlowLayout.LEFT, hgap: Int = 5, vgap: Int = 5, block: WrapPanel.() -> Unit): WrapPanel {
val pnl = WrapPanel(align, hgap, vgap).apply(block)
add(pnl)
return pnl
}
fun JToolBar.pager(tabPlacement: Int = JTabbedPane.TOP, tabLayoutPolicy: Int = JTabbedPane.SCROLL_TAB_LAYOUT, block: JTabbedPane.() -> Unit): JTabbedPane {
val pager = JTabbedPane(tabPlacement, tabLayoutPolicy).apply(block)
add(pager)
return pager
}
fun JToolBar.scroller(vsbPolicy: Int = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, hsbPolicy: Int = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED, block: JScrollPane.() -> Unit): JScrollPane {
val scroll = JScrollPane(vsbPolicy, hsbPolicy).apply(block)
add(scroll)
return scroll
}
fun JToolBar.split(orientation: Int = JSplitPane.HORIZONTAL_SPLIT, block: JSplitPane.() -> Unit): JSplitPane {
val sp = JSplitPane(orientation).apply(block)
add(sp)
return sp
}
fun JToolBar.toolbar(orientation: Int = JToolBar.HORIZONTAL, block: JToolBar.() -> Unit): JToolBar {
val tb = JToolBar(orientation).apply(block)
add(tb)
return tb
}
fun JToolBar.layer(block: JLayeredPane.() -> Unit): JLayeredPane {
val lay = JLayeredPane().apply(block)
add(lay)
return lay
}
fun JToolBar.label(title: String? = null, icon: Icon? = null, horizontalAlignment: Int = JLabel.LEFT, block: JLabel.() -> Unit): JLabel {
val lbl = JLabel(title, icon, horizontalAlignment).apply(block)
add(lbl)
return lbl
}
fun JToolBar.input(text: String? = null, column: Int = 0, block: KTextField.() -> Unit): KTextField {
val txt = KTextField(text, column).apply(block)
add(txt)
return txt
}
fun <T> JToolBar.combobox(model: ComboBoxModel<T>? = null, array: Array<T>? = null, vector: Vector<T>? = null, block: JComboBox<T>.() -> Unit): JComboBox<T> {
val cb = when {
model != null -> JComboBox(model)
array != null -> JComboBox(array)
vector != null -> JComboBox(vector)
else -> JComboBox()
}.apply(block)
add(cb)
return cb
}
fun JToolBar.button(title: String? = null, icon: Icon? = null, block: JButton.() -> Unit): JButton {
val b = JButton(title, icon).apply(block)
add(b)
return b
}
fun JToolBar.checkbox(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JCheckBox.() -> Unit): JCheckBox {
val chk = JCheckBox(title, icon, selected).apply(block)
add(chk)
return chk
}
fun JToolBar.radio(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JRadioButton.() -> Unit): JRadioButton {
val rd = JRadioButton(title, icon, selected).apply(block)
add(rd)
return rd
}
fun JToolBar.toggle(title: String? = null, icon: Icon? = null, selected: Boolean = false, block: JToggleButton.() -> Unit): JToggleButton {
val tg = JToggleButton(title, icon, selected).apply(block)
add(tg)
return tg
}
fun JToolBar.textArea(text: String? = null, rows: Int = 0, columns: Int = 0, block: KTextArea.() -> Unit): KTextArea {
val ta = KTextArea(text, rows, columns).apply(block)
add(ta)
return ta
}
fun JToolBar.inputPassword(text: String? = null, column: Int = 0, block: KPasswordField.() -> Unit): KPasswordField {
val txt = KPasswordField(text, column).apply(block)
add(txt)
return txt
}
fun JToolBar.textPane(block: KTextPane.() -> Unit): KTextPane {
val txt = KTextPane().apply(block)
add(txt)
return txt
}
fun JToolBar.editorPane(contentType: String? = null, text: String? = null, url: URL? = null, block: KEditorPane.() -> Unit): KEditorPane {
val txt = when {
url != null -> KEditorPane(url)
contentType != null -> KEditorPane(contentType, text)
else -> KEditorPane()
}.apply(block)
add(txt)
return txt
}
fun JToolBar.spinner(model: SpinnerModel? = null, block: JSpinner.() -> Unit): JSpinner {
val sp = (if (model == null) JSpinner() else JSpinner(model)).apply(block)
add(sp)
return sp
}
fun <T> JToolBar.list(model: ListModel<T>? = null, array: Array<T>? = null, vector: Vector<T>? = null, block: JList<T>.() -> Unit): JList<T> {
val list = when {
model != null -> JList(model)
array != null -> JList(array)
vector != null -> JList(vector)
else -> JList()
}.apply(block)
add(list)
return list
}
fun JToolBar.table(
model: TableModel? = null,
columnModel: TableColumnModel? = null,
selectionModel: ListSelectionModel? = null,
rows: Int = -1,
cols: Int = -1,
vecRowData: Vector<out Vector<*>>? = null,
vecColumnNames: Vector<*>? = null,
arrayRowData: Array<Array<*>>? = null,
arrayColumnNames: Array<*>? = null,
block: JTable.() -> Unit
): JTable {
val table = when {
model != null -> JTable(model, columnModel, selectionModel)
rows != -1 && cols != -1 -> JTable(rows, cols)
vecRowData != null && vecColumnNames != null -> JTable(vecRowData, vecColumnNames)
arrayRowData != null && arrayColumnNames != null -> JTable(arrayRowData, arrayColumnNames)
else -> JTable()
}.apply(block)
add(table)
return table
}
fun JToolBar.tree(
model: TreeModel? = null, node: TreeNode? = null, array: Array<*>? = null, vector: Vector<*>? = null, hashtable: Hashtable<*, *>? = null, block: JTree.() -> Unit
): JTree {
val tree = when {
model != null -> JTree(model)
node != null -> JTree(node)
array != null -> JTree(array)
vector != null -> JTree(vector)
hashtable != null -> JTree(hashtable)
else -> JTree()
}.apply(block)
add(tree)
return tree
}
fun JToolBar.progress(orient: Int = JProgressBar.HORIZONTAL, min: Int = 0, max: Int = 100, block: JProgressBar.() -> Unit): JProgressBar {
val p = JProgressBar(orient, min, max).apply(block)
add(p)
return p
}
fun JToolBar.scrollbar(orientation: Int = JScrollBar.VERTICAL, value: Int = 0, extent: Int = 10, min: Int = 0, max: Int = 100, block: JScrollBar.() -> Unit): JScrollBar {
val sb = JScrollBar(orientation, value, extent, min, max).apply(block)
add(sb)
return sb
}
fun JToolBar.separator(orientation: Int = JSeparator.HORIZONTAL, block: JSeparator.() -> Unit): JSeparator {
val sp = JSeparator(orientation).apply(block)
add(sp)
return sp
}
fun JToolBar.slider(orientation: Int = JSlider.HORIZONTAL, min: Int = 0, max: Int = 100, value: Int = 0, block: JSlider.() -> Unit): JSlider {
val sl = JSlider(orientation, min, max, value).apply(block)
add(sl)
return sl
}
fun JToolBar.box(axis: Int = 0, block: Box.() -> Unit): Box {
val box = Box(axis).apply(block)
add(box)
return box
}
fun JToolBar.image(data: ByteArray? = null, img: Image? = null, filename: String? = null, location: URL? = null, block: StretchIcon.() -> Unit): StretchIcon {
val icon = when {
data != null -> StretchIcon(imageData = data)
img != null -> StretchIcon(image = img)
filename != null -> StretchIcon(filename = filename)
location != null -> StretchIcon(location = location)
else -> throw IllegalArgumentException("All image sources are empty.")
}.apply(block)
val lbl = JLabel(icon, JLabel.CENTER)
add(lbl)
return icon
}
fun JToolBar.svg(uri: URI? = null, file: File? = null, inputStream: InputStream? = null, block: JSVGCanvas.() -> Unit): JSVGCanvas {
val canvas = JSVGCanvas()
when {
file != null -> canvas.uri = file.toURI().toString()
else -> {
val parser = XMLResourceDescriptor.getXMLParserClassName()
val factory = SAXSVGDocumentFactory(parser)
canvas.svgDocument = when {
uri != null -> factory.createSVGDocument(uri.toString())
inputStream != null -> factory.createSVGDocument("", inputStream)
else -> throw IllegalArgumentException("All image sources are empty.")
}
}
}
canvas.apply(block)
add(canvas)
return canvas
}
inline fun <reified T : Component> JToolBar.custom(vararg params: Any, block: T.() -> Unit): T {
val comp = newClassInstance<T>(*params).apply(block)
add(comp)
return comp
}
fun <T : Component> JToolBar.comp(comp: T, block: T.() -> Unit): T {
comp.apply(block)
add(comp)
return comp
}
| 0
|
Kotlin
|
0
| 2
|
3f5ea19ea036e3c0a5cddb54dc172d7dab9da04c
| 10,323
|
common-swing
|
MIT License
|
app/src/main/java/com/spaceapp/domain/model/explore_galaxy_data/Comet.kt
|
AhmetOcak
| 552,274,999
| false
|
{"Kotlin": 365290}
|
package com.spaceapp.domain.model.explore_galaxy_data
data class Comet(
val cometName: String,
val cometDescription: String,
val cometRadius: Double
)
| 0
|
Kotlin
|
1
| 2
|
f8a8c6d90874fc70566cdbd310231b5ec41baad3
| 164
|
Explore-Universe
|
MIT License
|
src/main/kotlin/org/eclipse/uprotocol/cloudevent/serialize/CloudEventSerializers.kt
|
eclipse-uprotocol
| 717,101,886
| false
|
{"Kotlin": 459377}
|
/*
* Copyright (c) 2024 General Motors GTO LLC
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* SPDX-FileType: SOURCE
* SPDX-FileCopyrightText: 2023 General Motors GTO LLC
* SPDX-License-Identifier: Apache-2.0
*/
package org.eclipse.uprotocol.cloudevent.serialize
/**
* Provides Singleton instances of the CloudEvent Serializers.
*/
enum class CloudEventSerializers(private val cloudEventSerializer: CloudEventSerializer) {
JSON(CloudEventToJsonSerializer()),
PROTOBUF(CloudEventToProtobufSerializer());
fun serializer(): CloudEventSerializer {
return cloudEventSerializer
}
}
| 7
|
Kotlin
|
3
| 3
|
f9a2cffd1e11ef1bf7499cfce779c212df645827
| 1,368
|
up-kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/snapguard/utils/Validator.kt
|
Vahid-Soudagar
| 729,505,282
| false
|
{"Kotlin": 35793}
|
package com.example.snapguard.utils
import android.util.Patterns
import android.widget.EditText
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
/**
* Utility class containing functions for validating email, password, and confirming passwords.
*
* This class provides methods to validate email addresses, passwords, and confirm that passwords
* match. It supports integration with Android's Material Design components like TextInputEditText
* and TextInputLayout for seamless integration into modern Android UIs.
*
* @property emailValidator Validates the format of an email address and checks for emptiness.
* @property passwordValidator Validates the strength of a password based on specified criteria.
* @property confirmPasswordValidator Checks if a password matches a confirmed password.
*/
class Validator {
companion object {
/**
* Validates the format of an email address and checks for emptiness.
*
* @param textInputEditText The TextInputEditText containing the email address.
* @param textInputLayout The TextInputLayout associated with the email input field.
* @return `true` if the email is valid; otherwise, `false`.
*/
fun emailValidator(textInputEditText: TextInputEditText, textInputLayout: TextInputLayout): Boolean {
val email = textInputEditText.text.toString()
val isValid = Patterns.EMAIL_ADDRESS.matcher(email).matches()
if (email.isNullOrEmpty()) {
textInputLayout.error = "Email cannot be Empty"
return false
}
if (!isValid) {
textInputLayout.error = "Enter Valid Email Address"
return false
}
textInputLayout.error = null
return isValid
}
/**
* Validates the strength of a password based on specified criteria.
*
* @param textInputEditText The TextInputEditText containing the password.
* @param textInputLayout The TextInputLayout associated with the password input field.
* @return `true` if the password is valid; otherwise, `false`.
*/
fun passwordValidator(textInputEditText: TextInputEditText, textInputLayout: TextInputLayout): Boolean {
val password = textInputEditText.text.toString()
val passwordPattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&+=!])(?=\\S+\$).{6,14}$".toRegex()
if (password.isNullOrEmpty()) {
textInputLayout.error = "Password cannot be Empty"
return false
}
if (!passwordPattern.matches(password)) {
textInputLayout.error =
"Password must be between 6 to 14 characters, contain 1 upper, 1 lower, 1 digit, and 1 special character"
return false
}
textInputLayout.error = null
return true
}
/**
* Checks if a password matches a confirmed password.
*
* @param passwordEditText The TextInputEditText containing the original password.
* @param passwordLayout The TextInputLayout associated with the original password input field.
* @param confirmPasswordEditText The TextInputEditText containing the confirmed password.
* @param confirmPasswordLayout The TextInputLayout associated with the confirmed password input field.
* @return `true` if the passwords match; otherwise, `false`.
*/
fun confirmPasswordValidator(
passwordEditText: TextInputEditText,
passwordLayout: TextInputLayout,
confirmPasswordEditText: TextInputEditText,
confirmPasswordLayout: TextInputLayout
): Boolean {
val password = passwordEditText.text.toString()
val confirmPassword = confirmPasswordEditText.text.toString()
if (password != confirmPassword) {
confirmPasswordLayout.error = "Passwords do not match"
return false
}
confirmPasswordLayout.error = null
return true
}
fun editTextValidator (editText: EditText) : Boolean {
val data = editText.text.toString()
return !data.isNullOrEmpty()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
004af8daa2ee5d88405bce5f637224bc1576f7d5
| 4,429
|
SnapGuard
|
MIT License
|
app/src/main/java/gq/kirmanak/mealient/data/share/ShareRecipeRepo.kt
|
kirmanak
| 431,195,533
| false
|
{"Kotlin": 476781}
|
package gq.kirmanak.mealient.data.share
interface ShareRecipeRepo {
suspend fun saveRecipeByURL(url: CharSequence): String
}
| 16
|
Kotlin
|
2
| 99
|
6f8a9520f3736ae641e4541d24afb0dcf9623ea0
| 130
|
Mealient
|
MIT License
|
commutil/src/main/java/com/fz/common/network/NetworkUtil.kt
|
peihua8858
| 380,141,169
| false
|
{"Kotlin": 425329, "Java": 208918}
|
package com.fz.common.network
import android.content.Context
import androidx.fragment.app.Fragment
import com.fz.common.ContextInitializer
import com.fz.common.R
import com.fz.common.text.isNonEmpty
import com.fz.toast.ToastCompat
fun Context.isConnected(): Boolean {
return Connectivity.isConnected(this)
}
fun Context.isConnected(showNetworkErrorTips: Boolean): Boolean {
return NetworkUtil.isConnected(this, showNetworkErrorTips)
}
fun Fragment?.isConnected(showNetworkErrorTips: Boolean): Boolean {
return NetworkUtil.isConnected(this, showNetworkErrorTips)
}
fun Fragment?.isConnected(): Boolean {
return NetworkUtil.isConnected(this)
}
fun Context.getNetworkType(): NetworkType {
return NetworkUtil.getNetworkType(this)
}
fun Context.isConnectedWifi(context: Context): Boolean {
return NetworkUtil.isConnectedWifi(context)
}
fun Context.isConnectedMobile(context: Context): Boolean {
return NetworkUtil.isConnectedMobile(context)
}
fun Context.isConnectionFast(context: Context): Boolean {
return NetworkUtil.isConnectionFast(context)
}
/**
* 网络工具类
*
* @author dingpeihua
* @version 1.0
* @date 2017/11/8 10:18
*/
object NetworkUtil {
/**
* 检测网络是否连接
*
* @author dingpeihua
* @date 2016/10/19 16:42
* @version 1.0
*/
@JvmStatic
fun isConnected(): Boolean {
return ContextInitializer.mContext.let { Connectivity.isConnected(it) }
}
/**
* 检测网络是否连接
*
* @author dingpeihua
* @date 2016/10/19 16:42
* @version 1.0
*/
@JvmStatic
fun isConnected(context: Context): Boolean {
return Connectivity.isConnected(context)
}
/**
* 检测网络是否连接
*
* @param showNetworkErrorTips true 在没有网络时提示,否则不提示
* @author dingpeihua
* @date 2016/10/19 16:42
* @version 1.0
*/
@JvmStatic
fun isConnected(context: Context, showNetworkErrorTips: Boolean): Boolean {
val isConnect = isConnected(context)
if (!isConnect && showNetworkErrorTips) {
showToast(context, context.getString(R.string.tips_check_network))
}
return isConnect
}
/**
* 检测网络是否连接
*
* @author dingpeihua
* @date 2016/10/19 16:42
* @version 1.0
*/
@JvmStatic
fun isConnected(fragment: Fragment?, showNetworkErrorTips: Boolean): Boolean {
if (fragment != null) {
val isConnect = isConnected(fragment.requireContext())
if (!isConnect && showNetworkErrorTips) {
showToast(fragment.context, fragment.getString(R.string.tips_check_network))
}
return isConnect
}
return false
}
/**
* 检测网络是否连接
*
* @author dingpeihua
* @date 2016/10/19 16:42
* @version 1.0
*/
@JvmStatic
fun isConnected(fragment: Fragment?): Boolean {
return isConnected(fragment, false)
}
@JvmStatic
fun getNetworkType(context: Context): NetworkType {
return Connectivity.getNetworkType(context)
}
@JvmStatic
fun isConnectedWifi(context: Context): Boolean {
return Connectivity.isConnectedWifi(context)
}
@JvmStatic
fun isConnectedMobile(context: Context): Boolean {
return Connectivity.isConnectedMobile(context)
}
@JvmStatic
fun isConnectionFast(context: Context): Boolean {
return Connectivity.isConnectionFast(context)
}
private fun showToast(context: Context?, message: String?) {
if (message.isNonEmpty()) {
ToastCompat.showMessage(context, message)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
cb29a1ca4524de97a0294c57757fe97016efcfe6
| 3,621
|
kotlinCommonUtils
|
Apache License 2.0
|
nms/1_8_R3/src/main/kotlin/me/gamercoder215/battlecards/wrapper/v1_8_R3/Wrapper1_8_R3.kt
|
GamerCoder215
| 555,359,817
| false
| null |
package me.gamercoder215.battlecards.wrapper.v1_8_R3
import me.gamercoder215.battlecards.impl.CardAttribute
import me.gamercoder215.battlecards.impl.cards.IBattleCard
import me.gamercoder215.battlecards.util.BattleParticle
import me.gamercoder215.battlecards.wrapper.BattleInventory
import me.gamercoder215.battlecards.wrapper.NBTWrapper
import me.gamercoder215.battlecards.wrapper.Wrapper
import net.md_5.bungee.api.chat.BaseComponent
import net.minecraft.server.v1_8_R3.*
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer
import org.bukkit.entity.Creature
import org.bukkit.entity.Player
import org.bukkit.entity.Wither
@Suppress("unchecked_cast")
internal class Wrapper1_8_R3 : Wrapper {
override fun getCommandVersion(): Int = 1
override fun sendActionbar(player: Player, message: String) {
val packet = PacketPlayOutChat(ChatComponentText(message), 2.toByte())
(player as CraftPlayer).handle.playerConnection.sendPacket(packet)
}
override fun sendActionbar(player: Player, component: BaseComponent) {
sendActionbar(player, component.toLegacyText())
}
override fun setBossBarVisibility(boss: Wither, visible: Boolean) {
// Withers do not have boss bars until 1.9
}
fun toNMS(attribute: CardAttribute): AttributeBase {
return when (attribute) {
CardAttribute.MAX_HEALTH -> GenericAttributes.maxHealth
CardAttribute.ATTACK_DAMAGE -> GenericAttributes.ATTACK_DAMAGE
CardAttribute.KNOCKBACK_RESISTANCE -> GenericAttributes.c
CardAttribute.SPEED -> GenericAttributes.MOVEMENT_SPEED
else -> throw IllegalArgumentException("Invalid attribute: $attribute")
} as AttributeBase
}
override fun loadProperties(en: Creature, card: IBattleCard<*>) {
val nms: EntityCreature = (en as CraftCreature).handle
val dropsF = EntityLiving::class.java.getDeclaredField("drops")
dropsF.isAccessible = true
val drops = dropsF.get(nms) as MutableList<ItemStack>
drops.clear()
for (entry in card.statistics.attributes) {
if (entry.key == CardAttribute.DEFENSE) continue // TODO Finish Defense Calculation for 1.8
val attribute = toNMS(entry.key)
val value = entry.value
var handle: AttributeInstance? = nms.getAttributeInstance(attribute)
if (handle == null) {
val attributesF = AttributeMapBase::class.java.getDeclaredField("b")
attributesF.isAccessible = true
val attributes = attributesF.get(nms) as MutableMap<String, AttributeInstance>
handle = AttributeModifiable(nms.attributeMap, attribute)
attributes[attribute.name] = handle
}
handle.value = value
}
val goals = PathfinderGoalSelector::class.java.getDeclaredField("b").apply { isAccessible = true }.get(nms.goalSelector).run {
(this as Set<Any>).map { it::class.java.getDeclaredField("a").apply { isAccessible = true }.get(it).run { this as PathfinderGoal } }
}
goals.filter {
it is PathfinderGoalAvoidTarget<*> || it is PathfinderGoalRestrictSun || it is PathfinderGoalFleeSun || it is PathfinderGoalBeg || it is PathfinderGoalBreed
}.forEach { nms.goalSelector.a(it) }
nms.goalSelector.a(2, FollowCardOwner1_8_R3(nms, card))
val targets = PathfinderGoalSelector::class.java.getDeclaredField("b").apply { isAccessible = true }.get(nms.targetSelector).run {
(this as Set<Any>).map { it::class.java.getDeclaredField("a").apply { isAccessible = true }.get(it).run { this as PathfinderGoal } }
}
targets.filterIsInstance<PathfinderGoalNearestAttackableTarget<*>>().forEach { nms.targetSelector.a(it) }
nms.targetSelector.a(1, CardOwnerHurtByTargetGoal1_8_R3(nms, card))
nms.targetSelector.a(2, CardOwnerHurtTargetGoal1_8_R3(nms, card))
nms.targetSelector.a(3, PathfinderGoalHurtByTarget(nms, true))
val tag = NBTTagCompound()
nms.b(tag)
tag.setBoolean("battlecard", true)
nms.a(tag)
}
override fun getNBTWrapper(item: org.bukkit.inventory.ItemStack): NBTWrapper {
return NBTWrapper1_8_R3(item)
}
override fun isCard(en: Creature): Boolean {
val tag = NBTTagCompound()
(en as CraftCreature).handle.b(tag)
return tag.getBoolean("battlecard")
}
override fun createInventory(id: String, name: String, size: Int): BattleInventory {
return BattleInventory1_8_R3(id, name, size)
}
private fun toNMS(particle: BattleParticle): EnumParticle {
return when (particle) {
BattleParticle.CLOUD -> EnumParticle.CLOUD
else -> throw IllegalArgumentException("Invalid particle: $particle")
}
}
override fun spawnParticle(
particle: BattleParticle, location: Location, count: Int,
dX: Double, dY: Double, dZ: Double,
speed: Double, force: Boolean
) {
if (location.world == null) return
val packet = PacketPlayOutWorldParticles(toNMS(particle), force, location.x.toFloat(), location.y.toFloat(), location.z.toFloat(), dX.toFloat(), dY.toFloat(), dZ.toFloat(), speed.toFloat(), count)
Bukkit.getOnlinePlayers().forEach{ (it as CraftPlayer).handle.playerConnection.sendPacket(packet) }
}
}
| 0
|
Kotlin
|
0
| 3
|
f037835be5f78b687fc59c5ac33f7eabf29a1318
| 5,542
|
BattleCards
|
Apache License 2.0
|
dslk/src/main/java/com/mozhimen/dslk/properties/TextView.kt
|
mozhimen
| 851,115,225
| false
|
{"Kotlin": 150390}
|
package com.mozhimen.dslk.properties
import android.content.res.Resources
import android.graphics.Color
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.view.KeyEvent
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.mozhimen.dslk.funcs.EditorActionListener
import com.mozhimen.dslk.funcs.TextWatcher
import com.mozhimen.kotlin.utilk.android.util.dp2pxI
/**
* @ClassName TextView
* @Description TODO
* @Author Mozhimen / <NAME>
* @Date 2024/9/2 23:06
* @Version 1.0
*/
inline var TextView.maxLength: Int
get() =1
set(value) {
filters = arrayOf<InputFilter>(LengthFilter(value))
}
inline var TextView.text_res: Int
get() =-1
set(value) {
setText(value)
}
inline var TextView.hint_color: String
get() =""
set(value) {
setHintTextColor(Color.parseColor(value))
}
inline var TextView.hint_color_res: Int
get() =-1
set(value) {
setHintTextColor(ContextCompat.getColor(context, value))
}
inline var TextView.hint_text_res: Int
get() =-1
set(value) {
setHint(value)
}
inline var TextView.hint_text: String
get() =""
set(value) {
setHint(value)
}
inline var TextView.line_space_multiplier: Float
get() =-1f
set(value) {
setLineSpacing(lineSpacingExtra, value)
}
inline var TextView.line_space_extra: Float
get() =-1f
set(value) {
setLineSpacing(value, lineSpacingMultiplier)
}
inline var TextView.textStyle: Int
get() =-1
set(value) = setTypeface(typeface, value)
inline var TextView.textColor: String
get() =""
set(value) {
setTextColor(Color.parseColor(value))
}
inline var TextView.text_color_res: Int
get() =-1
set(value) {
setTextColor(ContextCompat.getColor(context, value))
}
inline var TextView.fontFamily: Int
get() =1
set(value) {
try {
typeface = ResourcesCompat.getFont(context, value)
} catch (e: Resources.NotFoundException) {
}
}
inline var TextView.drawable_start: Int
get() =-1
set(value) {
setCompoundDrawablesRelativeWithIntrinsicBounds(value, 0, 0, 0)
}
inline var TextView.drawable_end: Int
get() =-1
set(value) {
setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, value, 0)
}
inline var TextView.drawable_top: Int
get() =-1
set(value) {
setCompoundDrawablesRelativeWithIntrinsicBounds(0, value, 0, 0)
}
inline var TextView.drawable_bottom: Int
get() =-1
set(value) {
setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, value)
}
inline var TextView.drawable_padding: Int
get() =0
set(value) {
compoundDrawablePadding = value.dp2pxI()
}
inline var TextView.onTextChange: TextWatcher
get() = TextWatcher()
set(value) {
val textWatcher = object : android.text.TextWatcher {
override fun afterTextChanged(s: Editable?) {
value.afterTextChanged.invoke(s)
}
override fun beforeTextChanged(
text: CharSequence?,
start: Int,
count: Int,
after: Int
) {
value.beforeTextChanged.invoke(text, start, count, after)
}
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
value.onTextChanged.invoke(text, start, before, count)
}
}
addTextChangedListener(textWatcher)
}
inline var TextView.onEditorAction: EditorActionListener
get() =EditorActionListener()
set(value) {
val editorActionListener = object : TextView.OnEditorActionListener {
override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
return value.onEditorAction(v, actionId, event)
}
}
setOnEditorActionListener(editorActionListener)
}
| 0
|
Kotlin
|
0
| 0
|
167b1f856b12336cb933ff5a6a52c7c38daab907
| 4,110
|
ADslKit
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/controller/validators/VisitorContactValidator.kt
|
ministryofjustice
| 409,259,375
| false
| null |
package uk.gov.justice.digital.hmpps.visitscheduler.controller.validators
import uk.gov.justice.digital.hmpps.visitscheduler.dto.VisitorDto
import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import javax.validation.Payload
import kotlin.reflect.KClass
@Target(AnnotationTarget.FIELD)
@MustBeDocumented
@Constraint(validatedBy = [VisitorContactValidator::class])
annotation class VisitorContactValidation(
val message: String = "{javax.validation.constraints.visitor.contact.message}",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
class VisitorContactValidator : ConstraintValidator<VisitorContactValidation, Set<VisitorDto>> {
override fun isValid(childList: Set<VisitorDto>?, context: ConstraintValidatorContext?): Boolean {
var visitContactCount = 0
childList?.let { list ->
list.forEach {
it.visitContact?.let { visitContact ->
if (visitContact) visitContactCount++
}
}
}
// Cannot have more than one visit contact
return visitContactCount <= 1
}
}
| 3
|
Kotlin
|
2
| 6
|
01dcad3b0defb675a12da8d0f14cc130766410ff
| 1,140
|
visit-scheduler
|
MIT License
|
app/src/main/java/fr/isen/amadori/androiderestaurant/fragments/DetailsFragment.kt
|
Seltux
| 332,701,793
| false
| null |
package fr.isen.amadori.androiderestaurant.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.squareup.picasso.Picasso
import fr.isen.amadori.androiderestaurant.R
import fr.isen.amadori.androiderestaurant.databinding.FragmentDetailsBinding
private lateinit var binding: FragmentDetailsBinding
class DetailsFragment : Fragment() {
companion object{
const val ARG = "argument"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentDetailsBinding.inflate(inflater,container,false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
arguments?.takeIf {
it.containsKey(ARG).apply {
val image = arguments?.getString(ARG)
if(!image.isNullOrEmpty()){
Picasso.get().load(image).into(binding.idCarouselImage)
}else{
Picasso.get().load(R.drawable.jokes_about_italians).into(binding.idCarouselImage)
}
}
}
super.onViewCreated(view, savedInstanceState)
}
}
| 0
|
Kotlin
|
0
| 0
|
0566acd749d55511698d68415880a6d5e50db0ed
| 1,348
|
AndroidERestaurantAmadori
|
Apache License 2.0
|
app/src/main/java/com/android_algo/presentation/boids/BoidsFragment.kt
|
julianczaja
| 399,513,595
| false
| null |
package com.android_algo.presentation.boids
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.android_algo.databinding.BoidsFragmentBinding
import com.google.android.material.slider.Slider
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class BoidsFragment : Fragment() {
private var _binding: BoidsFragmentBinding? = null
private val binding get() = _binding!!
private val viewModel: BoidsViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = BoidsFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.bottomSheetContent.boidOptions.sliderSeparation.addOnChangeListener { _, value, _ ->
binding.boidsSimulationView.setSeparationGain(value)
}
binding.bottomSheetContent.boidOptions.sliderAlignment.addOnChangeListener { _, value, _ ->
binding.boidsSimulationView.setAlignmentGain(value)
}
binding.bottomSheetContent.boidOptions.sliderCohesion.addOnChangeListener { _, value, _ ->
binding.boidsSimulationView.setCohesionGain(value)
}
binding.bottomSheetContent.boidOptions.sliderSight.addOnChangeListener { _, value, _ ->
binding.boidsSimulationView.setSightRange(value)
}
// binding.bottomSheetContent.boidOptions.sliderBoidsCount.addOnChangeListener { _, value, _ ->
// binding.boidsSimulationView.setBoidsCount(value.toInt())
// }
binding.bottomSheetContent.boidOptions.sliderBoidsCount.addOnSliderTouchListener(object :
Slider.OnSliderTouchListener {
override fun onStartTrackingTouch(slider: Slider) {}
override fun onStopTrackingTouch(slider: Slider) {
binding.boidsSimulationView.setBoidsCount(slider.value.toInt())
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
1
| 1
|
de94518a3eb4440d56779c5106c669feb0a26167
| 2,351
|
android_algo
|
MIT License
|
src/main/kotlin/ar/edu/unsam/controller/RepositorController.kt
|
madescoces
| 716,182,897
| false
|
{"Kotlin": 11029}
|
package ar.edu.unsam.controller
import ar.edu.unsam.errors.BusinessException
import ar.edu.unsam.errors.NotFoundException
import ar.edu.unsam.model.Repositor
import ar.edu.unsam.model.RepositorDTO
import ar.edu.unsam.service.RepositorService
import io.swagger.v3.oas.annotations.Operation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@CrossOrigin("*")
@RequestMapping("/repositores")
class RepositorController {
@Autowired
val repositorService: RepositorService? = null
@GetMapping
@Operation(summary = "Trae todos los repositores")
fun getAll(): ResponseEntity<List<RepositorDTO>>{
return try{
ResponseEntity(repositorService!!.getAll(), HttpStatus.OK)
} catch (e:Exception){
ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@GetMapping("/{id}")
fun getByID(@PathVariable("id") idRepositor:Int): ResponseEntity<Repositor>{
return try{
ResponseEntity(repositorService!!.getById(idRepositor), HttpStatus.OK)
} catch (e:Exception){
ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
} catch (e:NotFoundException) {
ResponseEntity(HttpStatus.NOT_FOUND)
}
}
@PostMapping
fun create (@RequestBody repositor:Repositor): ResponseEntity<Any>{
return try{
repositorService!!.create(repositor)
val responseHeader = HttpHeaders()
responseHeader.set("location","/repositores" + "/" + repositor.idRepositor)
ResponseEntity(responseHeader, HttpStatus.CREATED)
} catch (e: BusinessException) {
ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@PutMapping
fun update (@RequestBody repositor:Repositor): ResponseEntity<Any>{
return try{
repositorService!!.create(repositor)
ResponseEntity(HttpStatus.OK)
} catch (e: BusinessException) {
ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@DeleteMapping("/{id}")
fun delete(@PathVariable("id") idRepositor:Int): ResponseEntity<Repositor>{
return try{
repositorService!!.delete(idRepositor)
ResponseEntity(HttpStatus.OK)
} catch (e:Exception){
ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR)
} catch (e:NotFoundException) {
ResponseEntity(HttpStatus.NOT_FOUND)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fc1d15a09613df7c6abc9d4f58da7a661d7c934d
| 2,435
|
grupo3-supermercado-be
|
MIT License
|
shared/core/system/src/webCommonMain/kotlin/io/edugma/core/system/theme/ThemeUtils.android.kt
|
Edugma
| 474,423,768
| false
|
{"Kotlin": 959067, "JavaScript": 2398, "Swift": 1255, "HTML": 299, "Ruby": 102}
|
package io.edugma.core.system.theme
import io.edugma.core.api.model.ThemeMode
actual object ThemeUtils {
actual fun setTheme(mode: ThemeMode) {
// TODO web
}
}
| 1
|
Kotlin
|
0
| 2
|
788e4998105e7229e8d32512cfa457fd9c063a50
| 178
|
app
|
MIT License
|
src/main/kotlin/blue/starry/rummager/Env.kt
|
SlashNephy
| 353,593,596
| false
| null |
package blue.starry.rummager
import kotlin.properties.ReadOnlyProperty
object Env {
val TWITTER_CK by string
val TWITTER_CS by string
val TWITTER_AT by string
val TWITTER_ATS by string
val USE_PRIVATE_API by boolean
val SEARCH_QUERY by string
val SEARCH_INTERVAL_SECONDS by long { 30 }
val IGNORE_SOURCES by stringList
val IGNORE_SCREEN_NAMES by stringList
val DISCORD_WEBHOOK_URL by string
val DISCORD_WEBHOOK_URL_FROM_FOLLOWERS by stringOrNull
val DRYRUN by boolean
}
private val string: ReadOnlyProperty<Env, String>
get() = ReadOnlyProperty { _, property ->
System.getenv(property.name) ?: error("Env: ${property.name} is not present.")
}
private val stringOrNull: ReadOnlyProperty<Env, String?>
get() = ReadOnlyProperty { _, property ->
System.getenv(property.name)
}
private fun long(default: () -> Long) = ReadOnlyProperty<Env, Long> { _, property ->
System.getenv(property.name)?.toLongOrNull() ?: default()
}
private val stringList: ReadOnlyProperty<Env, List<String>>
get() = ReadOnlyProperty { _, property ->
System.getenv(property.name)?.split(",").orEmpty()
}
private fun String?.toBooleanFazzy(): Boolean {
return when (this) {
null -> false
"1", "yes" -> true
else -> toLowerCase().toBoolean()
}
}
private val boolean: ReadOnlyProperty<Env, Boolean>
get() = ReadOnlyProperty { _, property ->
System.getenv(property.name).toBooleanFazzy()
}
| 6
|
Kotlin
|
0
| 3
|
982499d10de448cf4478601f9340119fdc59d07f
| 1,513
|
rummager
|
MIT License
|
src/main/kotlin/org/neo4j/graphql/handler/CypherDirectiveHandler.kt
|
michael-forman
| 285,477,008
| true
|
{"Kotlin": 170037, "Python": 1290}
|
package org.neo4j.graphql.handler
import graphql.language.Field
import graphql.schema.*
import org.neo4j.graphql.*
class CypherDirectiveHandler(
type: GraphQLFieldsContainer,
private val isQuery: Boolean,
private val cypherDirective: Cypher,
fieldDefinition: GraphQLFieldDefinition)
: BaseDataFetcher(type, fieldDefinition) {
class Factory(schemaConfig: SchemaConfig) : AugmentationHandler(schemaConfig) {
override fun createDataFetcher(rootType: GraphQLObjectType, fieldDefinition: GraphQLFieldDefinition): DataFetcher<Cypher>? {
val cypherDirective = fieldDefinition.cypherDirective() ?: return null
// TODO cypher directives can also return scalars
val type = fieldDefinition.type.inner() as? GraphQLFieldsContainer
?: return null
val isQuery = rootType.name == QUERY
return CypherDirectiveHandler(type, isQuery, cypherDirective, fieldDefinition)
}
}
override fun generateCypher(variable: String, field: Field, env: DataFetchingEnvironment): Cypher {
val mapProjection = projectFields(variable, field, type, env, null)
val ordering = orderBy(variable, field.arguments)
val skipLimit = SkipLimit(variable, field.arguments).format()
return if (isQuery) {
val (query, params) = cypherDirective(variable, fieldDefinition, field, cypherDirective, emptyList())
Cypher("UNWIND $query AS $variable" +
" RETURN ${mapProjection.query} AS $variable$ordering${skipLimit.query}",
(params + mapProjection.params + skipLimit.params))
} else {
val (query, params) = cypherDirectiveQuery(variable, fieldDefinition, field, cypherDirective, emptyList())
Cypher("CALL apoc.cypher.doIt($query) YIELD value" +
" WITH value[head(keys(value))] AS $variable" +
" RETURN ${mapProjection.query} AS $variable$ordering${skipLimit.query}",
(params + mapProjection.params + skipLimit.params))
}
}
}
| 0
| null |
0
| 0
|
4792d3f41c00c5680b6ff0f66bd8c84057a50468
| 2,120
|
neo4j-graphql-java
|
Apache License 2.0
|
includedBuild/gradleConfiguration/src/main/kotlin/com/badoo/reaktive/configuration/DarwinPlugin.kt
|
sellmair
| 408,352,255
| true
|
{"Kotlin": 1638373, "Swift": 6396, "HTML": 1097, "Java": 245, "Ruby": 150}
|
package com.badoo.reaktive.configuration
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
@Suppress("UnstableApiUsage")
class DarwinPlugin : Plugin<Project> {
override fun apply(target: Project) {
configureDarwinCompilation(target)
}
private fun configureDarwinCompilation(target: Project) {
target.extensions.configure(KotlinMultiplatformExtension::class.java) {
if (Target.shouldDefineTarget(target, Target.IOS)) {
iosArm32()
iosArm64()
iosX64()
iosSimulatorArm64()
}
if (Target.shouldDefineTarget(target, Target.WATCHOS)) {
watchosArm32()
watchosArm64()
watchosX86()
watchosX64()
watchosSimulatorArm64()
}
if (Target.shouldDefineTarget(target, Target.TVOS)) {
tvosArm64()
tvosX64()
tvosSimulatorArm64()
}
if (Target.shouldDefineTarget(target, Target.MACOS)) {
macosX64()
macosArm64()
}
}
}
}
| 0
| null |
0
| 0
|
3539f128f22806070310bed9a7d96694051226ab
| 1,237
|
Reaktive
|
Apache License 2.0
|
app/src/main/java/com/mendelin/tmdb_koin/ui/favorites/FavoritesAdapter.kt
|
MadalinBalint
| 478,475,208
| false
| null |
package com.mendelin.tmdb_koin.ui.favorites
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.mendelin.tmdb_koin.ItemMovieListResultBinding
import com.mendelin.tmdb_koin.ItemTvListResultBinding
import com.mendelin.tmdb_koin.R
import com.mendelin.tmdb_koin.common.FavoriteType
import com.mendelin.tmdb_koin.common.IDetails
import com.mendelin.tmdb_koin.data.model.entity.MovieListResultItem
import com.mendelin.tmdb_koin.data.model.entity.MultipleItem
import com.mendelin.tmdb_koin.data.model.entity.TvListResultItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.koin.java.KoinJavaComponent.inject
class FavoritesAdapter : ListAdapter<MultipleItem, FavoritesAdapter.MultipleViewHolder>(MultipleDiffCallback()) {
private val favoritesList: ArrayList<MultipleItem> = ArrayList()
class MultipleViewHolder(var binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
private val viewmodel by inject<FavoritesViewModel>(FavoritesViewModel::class.java)
fun bindMovie(movie: MovieListResultItem) {
(binding as ItemMovieListResultBinding).apply {
property = movie
callback = IDetails {
val args = Bundle()
args.putInt("movieId", movie.id)
movieCard.findNavController().navigate(R.id.movieDetailsFragment, args)
}
btnFavoriteMovie.isChecked = true
btnFavoriteMovie.setOnCheckedChangeListener { _, check ->
CoroutineScope(Dispatchers.IO).launch {
viewmodel.deleteFavoriteMovie(movie.id)
delay(200)
viewmodel.fetchFavoritesList()
}
}
executePendingBindings()
}
}
fun bindTvShow(tvShow: TvListResultItem) {
(binding as ItemTvListResultBinding).apply {
property = tvShow
callback = IDetails {
val args = Bundle()
args.putString("tvShowName", tvShow.name)
args.putInt("tvShowId", tvShow.id)
tvListCard.findNavController().navigate(R.id.tvShowDetailsFragment, args)
}
btnFavoriteTvShow.isChecked = true
btnFavoriteTvShow.setOnCheckedChangeListener { _, check ->
CoroutineScope(Dispatchers.IO).launch {
viewmodel.deleteFavoriteTvShow(tvShow.id)
delay(200)
viewmodel.fetchFavoritesList()
}
}
executePendingBindings()
}
}
}
class MultipleDiffCallback : DiffUtil.ItemCallback<MultipleItem>() {
override fun areItemsTheSame(oldItem: MultipleItem, newItem: MultipleItem): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: MultipleItem, newItem: MultipleItem): Boolean {
return oldItem.content == newItem.content
}
}
override fun getItemViewType(position: Int): Int {
return favoritesList[position].type.value
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MultipleViewHolder {
return when (viewType) {
FavoriteType.FAVORITE_MOVIE.value ->
MultipleViewHolder(ItemMovieListResultBinding.inflate(LayoutInflater.from(parent.context), parent, false))
FavoriteType.FAVORITE_TV_SHOW.value ->
MultipleViewHolder(ItemTvListResultBinding.inflate(LayoutInflater.from(parent.context), parent, false))
else -> throw IndexOutOfBoundsException("View type $viewType should be between 0..1")
}
}
override fun onBindViewHolder(holder: MultipleViewHolder, position: Int) {
when (getItemViewType(position)) {
FavoriteType.FAVORITE_MOVIE.value ->
holder.bindMovie(favoritesList[position].content as MovieListResultItem)
FavoriteType.FAVORITE_TV_SHOW.value ->
holder.bindTvShow(favoritesList[position].content as TvListResultItem)
}
}
fun setList(list: List<MultipleItem>) {
favoritesList.apply {
clear()
addAll(list)
}
submitList(favoritesList)
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 0
|
adc3020a33eebc2ee438434b1ab303d6a4980007
| 4,809
|
TmdbAppKoin
|
Apache License 2.0
|
src/main/kotlin/io/unthrottled/doki/icon/provider/associations/AssociationModels.kt
|
gitter-badger
| 288,093,239
| true
|
{"Kotlin": 134962}
|
package io.unthrottled.doki.icon.provider.associations
class IconAssociationDefinition(
val name: String,
val associationPattern: String,
val iconPath: String
)
data class IconAssociation(
val associationRegex: Regex,
val iconPath: String
)
// todo: schema
enum class Associations(val fileName: String) {
DIRECTORY("directory.association.json"),
FILE("file.association.json");
}
class AssociationModels(
val associations: List<IconAssociationDefinition>
)
| 0
| null |
0
| 0
|
5fbe5da38d607faccd3b6b3d7f3a52c6013ad1a3
| 475
|
doki-theme-jetbrains
|
MIT License
|
app/src/main/java/com/stocksexchange/android/utils/managers/KeyboardManager.kt
|
libertaria-project
| 183,030,087
| true
|
{"Kotlin": 2210140}
|
package com.stocksexchange.android.utils.managers
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
/**
* Responsible for showing and hiding the keyboard on the screen.
*/
class KeyboardManager private constructor(context: Context) {
companion object {
fun newInstance(context: Context): KeyboardManager = KeyboardManager(context)
}
private var isRecycled: Boolean = false
private var inputMethodManager: InputMethodManager? =
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
/**
* Requests that the keyboard be show to the user.
*
* @param view The currently focused view which would
* like to receiver soft keyboard input.
*/
fun showKeyboard(view: View?) {
if(view != null) {
inputMethodManager?.showSoftInput(view, 0)
}
}
/**
* Requests that the keyboard be hidden from the user.
*
* @param view The currently focused view
*/
fun hideKeyboard(view: View?) {
if(view != null) {
inputMethodManager?.hideSoftInputFromWindow(view.windowToken, 0)
}
}
/**
* Recycles the manager resources, etc.
*/
fun recycle() {
if(isRecycled) {
return
}
inputMethodManager = null
isRecycled = true
}
}
| 0
|
Kotlin
|
0
| 0
|
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
| 1,417
|
Android-app
|
MIT License
|
app/src/main/java/com/fsmmmssaleschampionhoneywell/features/alarm/api/report_confirm_api/ReviewConfirmRepo.kt
|
DebashisINT
| 644,251,838
| false
| null |
package com.fsmmmssaleschampionhoneywell.features.alarm.api.report_confirm_api
import com.fsmmmssaleschampionhoneywell.base.BaseResponse
import com.fsmmmssaleschampionhoneywell.features.alarm.model.ReviewConfirmInputModel
import io.reactivex.Observable
/**
* Created by Saikat on 21-02-2019.
*/
class ReviewConfirmRepo(val apiService: ReviewConfirmApi) {
fun reviewConfirm(reviewConfirm: ReviewConfirmInputModel): Observable<BaseResponse> {
return apiService.reviewConfirm(reviewConfirm)
}
}
| 0
|
Kotlin
|
0
| 0
|
de788c0759321b9e93fedfd4dcb4af5afb3f2e4e
| 511
|
Honeywell
|
Apache License 2.0
|
app/src/main/java/com/csy/afv/ui/adapter/FindAdapter.kt
|
evolraelc
| 226,625,975
| false
| null |
package com.csy.afv.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.csy.afv.R
import com.csy.afv.mvp.model.bean.FindBean
import com.csy.afv.utils.ImageLoadUtils
/**
* @Author:CSY
* @Date:
* @Description: 将“发现”界面的数据和view里面的组件绑定,由于只有初步显示,没有详细信息显示,所以工具较为简单
*/
class FindAdapter(context: Context,list: MutableList<FindBean>?) : BaseAdapter(){
var mContext : Context? = null
var mList : MutableList<FindBean>? = null
var mInflater : LayoutInflater? = null
init {
mContext = context
mList = list
mInflater = LayoutInflater.from(context)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
//配置图片封面和绑定数据
var view : View
var holder : FindViewHolder
if (convertView == null) {
view = mInflater!!.inflate(R.layout.item_find,parent,false)
holder = FindViewHolder(view)
view.tag = holder
}else{
view = convertView
holder = view.tag as FindViewHolder
}
ImageLoadUtils.display(mContext!!,holder.iv_photo, mList?.get(position)?.bgPicture!!)
holder.tv_title?.text = mList?.get(position)!!.name
return view
}
override fun getItem(position: Int): FindBean? {
return mList?.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
if(mList!=null){
return mList!!.size
}else{
return 0
}
}
class FindViewHolder(itemView : View){
var iv_photo : ImageView? = null
var tv_title : TextView? = null
init {
tv_title = itemView.findViewById(R.id.tv_title) as TextView?
iv_photo = itemView.findViewById(R.id.iv_photo) as ImageView?
}
}
}
| 0
|
Kotlin
|
0
| 1
|
de53540d829be7c0a3037811a6f7cec48cabbbb1
| 2,045
|
AFV
|
Apache License 2.0
|
app/src/main/kotlin/io/github/andraantariksa/crates/feature_crates/ui/sign_in/SignInActivity.kt
|
andraantariksa
| 237,919,842
| false
| null |
package io.github.andraantariksa.crates.feature_crates.ui.sign_in
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import dagger.hilt.android.AndroidEntryPoint
import io.github.andraantariksa.crates.feature_crates.ui.common.theme.CratesTheme
import io.github.andraantariksa.crates.feature_crates.ui.sign_in.screen.SignInScreen
@AndroidEntryPoint
class SignInActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CratesTheme {
SignInScreen()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2dd0faff903762540794a11c22e66c0eaf20a1f8
| 666
|
crates
|
MIT License
|
cosec-spring-boot-starter/src/main/kotlin/me/ahoo/cosec/spring/boot/starter/jwt/JwtProperties.kt
|
Ahoo-Wang
| 567,999,401
| false
|
{"Kotlin": 588793, "Dockerfile": 594}
|
/*
* Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.cosec.spring.boot.starter.jwt
import me.ahoo.cosec.api.CoSec
import me.ahoo.cosec.spring.boot.starter.EnabledCapable
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.NestedConfigurationProperty
import org.springframework.boot.context.properties.bind.DefaultValue
import java.time.Duration
/**
* Jwt Properties .
*
* @author <NAME>
*/
@ConfigurationProperties(prefix = JwtProperties.PREFIX)
class JwtProperties(
@DefaultValue("true") override var enabled: Boolean = true,
@DefaultValue("hmac256") var algorithm: Algorithm = Algorithm.HMAC256,
var secret: String,
@NestedConfigurationProperty var tokenValidity: TokenValidity = TokenValidity()
) : EnabledCapable {
companion object {
const val PREFIX = CoSec.COSEC_PREFIX + "jwt"
}
data class TokenValidity(
var access: Duration = Duration.ofMinutes(10),
var refresh: Duration = Duration.ofDays(7)
)
enum class Algorithm {
HMAC256, HMAC384, HMAC512
}
}
| 1
|
Kotlin
|
4
| 32
|
ea4af7a66c1ab4d6560d7f3ba5d7026cd6904c26
| 1,710
|
CoSec
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.