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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ui-landingScreen/src/main/java/com/praxis/feat/authentication/ui/search/SearchTwitter.kt | shubhamsinghmutualmobile | 452,160,545 | false | {"Kotlin": 218752, "Shell": 287} | package com.praxis.feat.authentication.ui.search
data class SearchTwitter(
var searchCategory: String,
var hashTagTitle: String,
var totalTweets: String,
var imageUrl: String?
)
data class SearchHeader(
var category: String,
var time: Long,
var title: String,
var subtitle: String,
var imageUrl: String
)
| 0 | Kotlin | 0 | 0 | 9c02b3fa5b443c88b356a1fb3fe6e471e337c74a | 343 | ComposeTweet | Apache License 2.0 |
lib/src/main/kotlin/it/scoppelletti/spaceship/ads/app/ConsentAgeFragment.kt | dscoppelletti | 395,695,274 | false | null | /*
* Copyright (C) 2018 <NAME>, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier")
package it.scoppelletti.spaceship.ads.app
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.annotation.UiThread
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import by.kirich1409.viewbindingdelegate.viewBinding
import it.scoppelletti.spaceship.ads.R
import it.scoppelletti.spaceship.ads.databinding.ConsentAgeFragmentBinding
import it.scoppelletti.spaceship.ads.lifecycle.ConsentFragmentViewModel
import it.scoppelletti.spaceship.app.appComponent
import it.scoppelletti.spaceship.lifecycle.ViewModelProviderEx
/**
* Prompts the user for her age status.
*
* @see it.scoppelletti.spaceship.ads.app.AbstractConsentActivity
* @since 1.0.0
*/
@UiThread
public class ConsentAgeFragment : Fragment(
R.layout.it_scoppelletti_ads_consentage_fragment
) {
private lateinit var viewModel: ConsentFragmentViewModel
private lateinit var navController: NavController
private val binding by viewBinding(ConsentAgeFragmentBinding::bind)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.txtMessage.movementMethod = LinkMovementMethod.getInstance()
binding.cmdAdult.setOnClickListener {
navController.navigate(ConsentAgeFragmentDirections.actionAdult())
}
binding.cmdUnderage.setOnClickListener {
navController.navigate(
ConsentAgeFragmentDirections.actionConsentUnderage())
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
val activity: FragmentActivity
val viewModelProvider: ViewModelProviderEx
super.onViewStateRestored(savedInstanceState)
navController = findNavController()
activity = requireActivity()
viewModelProvider = activity.appComponent().viewModelProvider()
viewModel = viewModelProvider.get(this,
ConsentFragmentViewModel::class.java)
viewModel.text.observe(viewLifecycleOwner) { text ->
binding.txtMessage.text = text
}
viewModel.buildText(getString(R.string.it_scoppelletti_ads_html_age))
}
}
| 0 | Kotlin | 0 | 0 | 37a4f832df4aba3a9f7dbd7b5b79c3aacd9aebea | 3,043 | spaceship-ads | Apache License 2.0 |
src/main/kotlin/org/jetbrains/research/testspark/display/utils/kotlin/KotlinDisplayUtils.kt | JetBrains-Research | 563,889,235 | false | {"Kotlin": 733171, "Java": 5347, "Shell": 1563} | package org.jetbrains.research.testspark.display.utils.kotlin
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiManager
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.containers.stream
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.research.testspark.bundles.plugin.PluginLabelsBundle
import org.jetbrains.research.testspark.data.UIContext
import org.jetbrains.research.testspark.display.utils.ErrorMessageManager
import org.jetbrains.research.testspark.display.utils.template.DisplayUtils
import org.jetbrains.research.testspark.kotlin.KotlinPsiClassWrapper
import org.jetbrains.research.testspark.langwrappers.PsiClassWrapper
import org.jetbrains.research.testspark.testmanager.kotlin.KotlinTestAnalyzer
import org.jetbrains.research.testspark.testmanager.kotlin.KotlinTestGenerator
import java.io.File
import java.util.Locale
import javax.swing.JOptionPane
class KotlinDisplayUtils : DisplayUtils {
override fun applyTests(project: Project, uiContext: UIContext?, testCaseComponents: List<String>): Boolean {
val descriptor = FileChooserDescriptor(true, true, false, false, false, false)
// Apply filter with folders and java files with main class
WriteCommandAction.runWriteCommandAction(project) {
descriptor.withFileFilter { file ->
file.isDirectory || (
file.extension?.lowercase(Locale.getDefault()) == "kotlin" && (
PsiManager.getInstance(project).findFile(file!!) as KtFile
).classes.stream().map { it.name }
.toArray()
.contains(
(
PsiManager.getInstance(project)
.findFile(file) as PsiJavaFile
).name.removeSuffix(".kt"),
)
)
}
}
val fileChooser = FileChooser.chooseFiles(
descriptor,
project,
LocalFileSystem.getInstance().findFileByPath(project.basePath!!),
)
/**
* Cancel button pressed
*/
if (fileChooser.isEmpty()) return false
/**
* Chosen files by user
*/
val chosenFile = fileChooser[0]
/**
* Virtual file of a final java file
*/
var virtualFile: VirtualFile? = null
/**
* PsiClass of a final java file
*/
var ktClass: KtClass? = null
/**
* PsiJavaFile of a final java file
*/
var psiKotlinFile: KtFile? = null
if (chosenFile.isDirectory) {
// Input new file data
var className: String
var fileName: String
var filePath: String
// Waiting for correct file name input
while (true) {
val jOptionPane =
JOptionPane.showInputDialog(
null,
PluginLabelsBundle.get("optionPaneMessage"),
PluginLabelsBundle.get("optionPaneTitle"),
JOptionPane.PLAIN_MESSAGE,
null,
null,
null,
)
// Cancel button pressed
jOptionPane ?: return false
// Get class name from user
className = jOptionPane as String
// Set file name and file path
fileName = "${className.split('.')[0]}.kt"
filePath = "${chosenFile.path}/$fileName"
// Check the correctness of a class name
if (!Regex("[A-Z][a-zA-Z0-9]*(.kt)?").matches(className)) {
ErrorMessageManager.showErrorWindow(PluginLabelsBundle.get("incorrectFileNameMessage"))
continue
}
// Check the existence of a file with this name
if (File(filePath).exists()) {
ErrorMessageManager.showErrorWindow(PluginLabelsBundle.get("fileAlreadyExistsMessage"))
continue
}
break
}
// Create new file and set services of this file
WriteCommandAction.runWriteCommandAction(project) {
chosenFile.createChildData(null, fileName)
virtualFile = VirtualFileManager.getInstance().findFileByUrl("file://$filePath")!!
psiKotlinFile = (PsiManager.getInstance(project).findFile(virtualFile!!) as KtFile)
val ktPsiFactory = KtPsiFactory(project)
ktClass = ktPsiFactory.createClass("class ${className.split(".")[0]} {}")
if (uiContext!!.testGenerationOutput.runWith.isNotEmpty()) {
val annotationEntry =
ktPsiFactory.createAnnotationEntry("@RunWith(${uiContext.testGenerationOutput.runWith})")
ktClass!!.addBefore(annotationEntry, ktClass!!.body)
}
psiKotlinFile!!.add(ktClass!!)
}
} else {
// Set services of the chosen file
virtualFile = chosenFile
psiKotlinFile = (PsiManager.getInstance(project).findFile(virtualFile!!) as KtFile)
val classNameNoSuffix = psiKotlinFile!!.name.removeSuffix(".kt")
ktClass = psiKotlinFile?.declarations?.filterIsInstance<KtClass>()?.find { it.name == classNameNoSuffix }
}
// Add tests to the file
WriteCommandAction.runWriteCommandAction(project) {
appendTestsToClass(
project,
uiContext,
testCaseComponents,
KotlinPsiClassWrapper(ktClass as KtClass),
psiKotlinFile!!,
)
}
// Open the file after adding
FileEditorManager.getInstance(project).openTextEditor(
OpenFileDescriptor(project, virtualFile!!),
true,
)
return true
}
override fun appendTestsToClass(
project: Project,
uiContext: UIContext?,
testCaseComponents: List<String>,
selectedClass: PsiClassWrapper,
outputFile: PsiFile,
) {
// block document
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(
PsiDocumentManager.getInstance(project).getDocument(outputFile as KtFile)!!,
)
// insert tests to a code
testCaseComponents.reversed().forEach {
val testMethodCode =
KotlinTestAnalyzer.extractFirstTestMethodCode(
KotlinTestGenerator.formatCode(
project,
it.replace("\r\n", "\n")
.replace("verifyException(", "// verifyException("),
uiContext!!.testGenerationOutput,
),
)
// Fix Windows line separators
.replace("\r\n", "\n")
PsiDocumentManager.getInstance(project).getDocument(outputFile)!!.insertString(
selectedClass.rBrace!!,
testMethodCode,
)
}
// insert other info to a code
PsiDocumentManager.getInstance(project).getDocument(outputFile)!!.insertString(
selectedClass.rBrace!!,
uiContext!!.testGenerationOutput.otherInfo + "\n",
)
// Create the imports string
val importsString = uiContext.testGenerationOutput.importsCode.joinToString("\n") + "\n\n"
// Find the insertion offset
val insertionOffset = outputFile.importList?.startOffset
?: outputFile.packageDirective?.endOffset
?: 0
// Insert the imports into the document
PsiDocumentManager.getInstance(project).getDocument(outputFile)?.let { document ->
document.insertString(insertionOffset, importsString)
PsiDocumentManager.getInstance(project).commitDocument(document)
}
val packageName = uiContext.testGenerationOutput.packageName
val packageStatement = if (packageName.isEmpty()) "" else "package $packageName\n\n"
// Insert the package statement at the beginning of the document
PsiDocumentManager.getInstance(project).getDocument(outputFile)?.let { document ->
document.insertString(0, packageStatement)
PsiDocumentManager.getInstance(project).commitDocument(document)
}
}
}
| 96 | Kotlin | 19 | 51 | e1553b15f05f8e125f17aba1e062e4f3ad2c00e3 | 9,356 | TestSpark | MIT License |
fishqr/src/main/java/com/clsrfish/fishqr/page/qrgen/viewholder/TemplateViewHolder.kt | clsrfish | 337,752,439 | false | null | package com.clsrfish.fishqr.page.qrgen.viewholder
import android.view.ViewGroup
import com.clsrfish.common.list.BaseViewHolder
/**
* @author clsrfish
* @since 3/6/21 00:31
* @email <EMAIL>
*/
class TemplateViewHolder(parent: ViewGroup) : BaseViewHolder(parent, 0) {
} | 0 | Kotlin | 0 | 0 | 9c819f30cd0a77aae5111322165da09080afbfbb | 273 | fishproject | Apache License 2.0 |
petcare/src/main/java/io/wso2/android/api_authenticator/sdk/petcare/features/home/presentation/util/profile/ProfileImage.kt | Achintha444 | 731,559,375 | false | {"Kotlin": 616611, "Java": 1580} | package io.wso2.android.api_authenticator.sdk.petcare.features.home.presentation.util.profile
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.rememberAsyncImagePainter
@Composable
fun ProfileImage(imageUrl: String) {
Image(
modifier = Modifier
.size(104.dp)
.clip(CircleShape)
.border(1.dp, MaterialTheme.colorScheme.primary, CircleShape),
painter = rememberAsyncImagePainter(imageUrl),
contentDescription = "Profile Picture",
contentScale = ContentScale.FillBounds
)
}
| 0 | Kotlin | 0 | 0 | cbcd9412241bf81da34724d789ed528fc2b17040 | 949 | wso2-android-api-authenticator-sdk | Apache License 2.0 |
compiler/src/main/kotlin/gay/pizza/pork/compiler/LocalState.kt | GayPizzaSpecifications | 680,636,847 | false | {"Kotlin": 319507} | package gay.pizza.pork.compiler
import gay.pizza.pork.ast.gen.Symbol
import gay.pizza.pork.bytecode.MutableRel
class LocalState(val symbol: CompilableSymbol) {
private var internalLoopState: LoopState? = null
val loopState: LoopState?
get() = internalLoopState
private var localVarIndex: UInt = 0u
private val variables = mutableListOf<MutableList<StubVar>>()
fun startLoop(startOfLoop: UInt, exitJumpTarget: MutableRel) {
internalLoopState = LoopState(
startOfLoop = startOfLoop,
exitJumpTarget = exitJumpTarget,
scopeDepth = (internalLoopState?.scopeDepth ?: 0u) + 1u,
enclosing = internalLoopState
)
}
fun endLoop() {
internalLoopState = internalLoopState?.enclosing
}
fun createLocal(symbol: Symbol): StubVar {
val scope = variables.last()
val variable = StubVar(localVarIndex++, symbol)
scope.add(variable)
return variable
}
fun pushScope() {
variables.add(mutableListOf())
}
fun popScope() {
variables.removeLast()
}
fun resolve(symbol: Symbol): Loadable {
for (scope in variables.reversed()) {
val found = scope.firstOrNull { it.symbol == symbol }
if (found != null) {
return Loadable(stubVar = found)
}
}
val found = this.symbol.compilableSlab.resolve(symbol)
if (found != null) {
return Loadable(call = found)
}
throw RuntimeException("Unable to resolve symbol: ${symbol.id}")
}
}
| 0 | Kotlin | 1 | 0 | 4c50d48e1e9b73430af9cede99e3d9a6dfedb740 | 1,451 | pork | MIT License |
app/src/main/java/com/example/android/marsrealestate/overview/OverviewViewModel.kt | Dineo-s | 342,964,599 | false | null | /*
* Copyright 2019, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.android.marsrealestate.overview
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.marsrealestate.network.MarsApi
import com.example.android.marsrealestate.network.MarsApiService
import com.example.android.marsrealestate.network.MarsProperty
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Exception
enum class MarsApiStatus { LOADING, ERROR, DONE }
/**
* The [ViewModel] that is attached to the [OverviewFragment].
*/
class OverviewViewModel : ViewModel() {
// The internal MutableLiveData String that stores the most recent response
private val _status = MutableLiveData<MarsApiStatus>()
// The external immutable LiveData for the response String
val status: LiveData<MarsApiStatus>
get() = _status
private val _properties = MutableLiveData<List<MarsProperty>>()
val properties: LiveData<List<MarsProperty>>
get() = _properties
/**
* Call getMarsRealEstateProperties() on init so we can display status immediately.
*/
init {
getMarsRealEstateProperties()
}
/**
* Sets the value of the status LiveData to the Mars API status.
*/
//method using callbacks
/* private fun getMarsRealEstateProperties() {
//_response.value =
MarsApi.retrofitService.getProperties().enqueue(object : Callback<List<MarsProperty>> {
override fun onResponse(call: Call<List<MarsProperty>>, response: Response<List<MarsProperty>>) {
_response.value = "Success: ${response.body()?.size} Mars properties retrieved"
}
override fun onFailure(call: Call<List<MarsProperty>>, t: Throwable) {
_response.value = "Failure:${t.message}"
}
})
}*/
//using coroutines
private fun getMarsRealEstateProperties() {
viewModelScope.launch {
_status.value = MarsApiStatus.LOADING
try {
val listResults = MarsApi.retrofitService.getProperties()
// _response.value = "Success: ${listResults?.size} Mars properties retrieved"
_status.value = MarsApiStatus.DONE
Log.d("Myviemodel", "Success ${listResults?.size}")
//if (listResults.size > 0){
_properties.value = listResults
// }
} catch (e: Exception) {
// _response.value = "Failure: ${e.message}"
_status.value = MarsApiStatus.ERROR
_properties.value = ArrayList()//empty
Log.d("Myviemodel", "Failure ${e.message}")
}
}
}
}
| 0 | Kotlin | 0 | 0 | ae96d7337abc1e392e94eb0db9bb52bac824e179 | 3,551 | MarsRealEstate-Starter | Apache License 2.0 |
kool-pong-tutorial/src/commonMain/kotlin/template/PongPaddle.kt | 4lfg24 | 858,405,375 | false | {"Kotlin": 74405, "HTML": 1550, "JavaScript": 451} | package pongTutorial
import de.fabmax.kool.input.KeyboardInput
import de.fabmax.kool.input.UniversalKeyCode
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.physics.RigidDynamic
import de.fabmax.kool.scene.Mesh
import kotlin.math.abs
class PongPaddle(var body:RigidDynamic, var mesh: Mesh, moveUpButton:UniversalKeyCode, moveDownButton:UniversalKeyCode) {
var speed=0f
init {
KeyboardInput.addKeyListener(moveUpButton, "move up", filter = {it.isPressed}){
//whenever the up key is pressed we want to move the paddle up
speed= 0.5f
}
KeyboardInput.addKeyListener(moveDownButton, "move down", filter = {it.isPressed}){
//same thing for when the down key is pressed
speed= -0.5f
}
//for the contact listener
body.tags.put("object", this)
}
fun update(){
//this is necessary when using kinematic actors, because they act
//different compared to normal rigid actors to update their position
//you need to first update their target's position, for further explanation
//check the PhysX documentation at: https://nvidia-omniverse.github.io/PhysX/physx/5.1.3/docs/RigidBodyDynamics.html#kinematic-actors
body.setKinematicTarget(body.position.add(Vec3f(0f, speed, 0f), MutableVec3f()))
//if the paddle reaches the top or bottom wall invert its speed
if (abs(body.position.y)>=40f){
body.setKinematicTarget(body.position.subtract(Vec3f(0f, speed, 0f), MutableVec3f()))
speed*=-1
}
}
} | 0 | Kotlin | 0 | 0 | f864948f16a8168911a9945c976681be347386e0 | 1,630 | kool-pong-tutorial | MIT License |
app/router/src/main/java/com/gmail/jiangyang5157/router/fragment/transition/FragmentTransitionBuilder.kt | jiangyang5157 | 553,993,370 | false | null | package com.gmail.jiangyang5157.router.fragment.transition
import androidx.fragment.app.Fragment
import com.gmail.jiangyang5157.router.core.Route
import com.gmail.jiangyang5157.router.fragment.FragmentRouterDsl
@FragmentRouterDsl
class FragmentTransitionBuilder {
private var transition: FragmentTransition = EmptyFragmentTransition
@FragmentRouterDsl
fun register(transition: FragmentTransition) {
this.transition += transition
}
@JvmName("registerGeneric")
@FragmentRouterDsl
inline fun <reified ExitFragment : Fragment, reified ExitRoute : Route,
reified EnterFragment : Fragment, reified EnterRoute : Route> register(
transition: GenericFragmentTransition<ExitFragment, ExitRoute, EnterFragment, EnterRoute>
) = register(transition.reified().erased())
@FragmentRouterDsl
fun clear() {
this.transition = EmptyFragmentTransition
}
fun build(): FragmentTransition = transition
}
| 0 | Kotlin | 0 | 0 | 721b02a40885ef5406d8f63e4e615fa26ab3cadd | 967 | kotlin-multiplatform-mobile | MIT License |
core/src/main/java/com/sun/auth/core/TestUtils.kt | sun-asterisk | 575,642,139 | false | {"Kotlin": 204985, "Shell": 4578} | package com.sun.auth.core
inline fun <reified T : Any, R> T.setPrivateProperty(name: String, mock: R) =
T::class.java
.declaredFields
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.set(this, mock)
inline fun <reified T> T.callPrivateFunc(name: String, vararg args: Any?): Any? =
T::class.java
.declaredMethods
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.invoke(this, *args)
inline fun <reified T : Any, R> T.getPrivateProperty(name: String): R? =
T::class.java
.declaredFields
.firstOrNull { it.name == name }
?.apply { isAccessible = true }
?.get(this) as? R
| 2 | Kotlin | 0 | 1 | 43900c2adda86b620fe53354c53f2fa3998b7144 | 714 | tech-standard-android-auth | Apache License 2.0 |
domain/src/main/kotlin/com/ilgiz/kitsu/domain/repositories/AnimeRepository.kt | ilgiz05 | 493,248,856 | false | null | package com.ilgiz.kitsu.domain.repositories
import com.ilgiz.kitsu.domain.either.Either
import com.ilgiz.kitsu.domain.models.anime.SingleAnimeModel
import kotlinx.coroutines.flow.Flow
interface AnimeRepository {
fun fetchAnimeDetails(id: String): Flow<Either<String, SingleAnimeModel>>
} | 0 | Kotlin | 0 | 0 | f9d4b4b9899bc2faa3fc992233c3187774d3d8d8 | 293 | kitsuApi | MIT License |
pschd-core/src/test/kotlin/wang/nerom/pschd/test/ElectionTest.kt | Nerom | 201,171,507 | false | null | package wang.nerom.pschd.test
import org.junit.Test
import wang.nerom.pschd.config.PschdConfig
import wang.nerom.pschd.leader.PschdNode
import wang.nerom.pschd.util.HostUtil
class ElectionTest {
@Test
fun electionTest() {
val localIpv4 = HostUtil.getIpv4()
println("local ipv4: [$localIpv4]")
val candidates = "$localIpv4:9101,$localIpv4:9102,$localIpv4:9103"
val config1 = PschdConfig()
config1.localPort = 9101
config1.candidates = candidates
val node1 = PschdNode(config1)
node1.doInit()
val config2 = PschdConfig()
config2.localPort = 9102
config2.candidates = candidates
val node2 = PschdNode(config2)
node2.doInit()
val config3 = PschdConfig()
config3.localPort = 9103
config3.candidates = candidates
val node3 = PschdNode(config3)
node3.doInit()
while (true) {
Thread.sleep(10000)
}
}
@Test
fun electionNode1Test() {
val localIpv4 = HostUtil.getIpv4()
println("local ipv4: [$localIpv4]")
val candidates = "$localIpv4:9101,$localIpv4:9102,$localIpv4:9103"
val config1 = PschdConfig()
config1.localPort = 9101
config1.candidates = candidates
val node1 = PschdNode(config1)
node1.doInit()
while (true) {
Thread.sleep(10000)
}
}
@Test
fun electionNode2Test() {
val localIpv4 = HostUtil.getIpv4()
println("local ipv4: [$localIpv4]")
val candidates = "$localIpv4:9101,$localIpv4:9102,$localIpv4:9103"
val config2 = PschdConfig()
config2.localPort = 9102
config2.candidates = candidates
val node2 = PschdNode(config2)
node2.doInit()
while (true) {
Thread.sleep(10000)
}
}
@Test
fun electionNode3Test() {
val localIpv4 = HostUtil.getIpv4()
println("local ipv4: [$localIpv4]")
val candidates = "$localIpv4:9101,$localIpv4:9102,$localIpv4:9103"
val config3 = PschdConfig()
config3.localPort = 9103
config3.candidates = candidates
val node3 = PschdNode(config3)
node3.doInit()
while (true) {
Thread.sleep(10000)
}
}
} | 0 | Kotlin | 0 | 0 | 711efd97025a95fa61e03276ef481717a2d8a98d | 2,324 | pschd | Apache License 2.0 |
mediator/src/main/kotlin/no/nav/dagpenger/saksbehandling/api/config/ApiConfig.kt | navikt | 571,475,339 | false | {"Kotlin": 116667, "Mustache": 8476, "PLpgSQL": 2764, "HTML": 699, "Dockerfile": 77} | package no.nav.dagpenger.saksbehandling.api.config
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.JacksonConverter
import io.ktor.serialization.jackson.jackson
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.auth.Authentication
import io.ktor.server.plugins.callloging.CallLogging
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import no.nav.dagpenger.saksbehandling.api.config.auth.jwt
fun Application.apiConfig() {
install(CallLogging) {
disableDefaultColors()
}
install(ContentNegotiation) {
jackson {
register(ContentType.Application.Json, JacksonConverter(objectMapper))
}
}
install(Authentication) {
jwt("azureAd")
}
}
| 0 | Kotlin | 0 | 0 | c33ed0b786e3a8618de8cadb3771ec203c2c0ec2 | 802 | dp-saksbehandling | MIT License |
mediator/src/main/kotlin/no/nav/dagpenger/saksbehandling/api/config/ApiConfig.kt | navikt | 571,475,339 | false | {"Kotlin": 116667, "Mustache": 8476, "PLpgSQL": 2764, "HTML": 699, "Dockerfile": 77} | package no.nav.dagpenger.saksbehandling.api.config
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.JacksonConverter
import io.ktor.serialization.jackson.jackson
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.auth.Authentication
import io.ktor.server.plugins.callloging.CallLogging
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import no.nav.dagpenger.saksbehandling.api.config.auth.jwt
fun Application.apiConfig() {
install(CallLogging) {
disableDefaultColors()
}
install(ContentNegotiation) {
jackson {
register(ContentType.Application.Json, JacksonConverter(objectMapper))
}
}
install(Authentication) {
jwt("azureAd")
}
}
| 0 | Kotlin | 0 | 0 | c33ed0b786e3a8618de8cadb3771ec203c2c0ec2 | 802 | dp-saksbehandling | MIT License |
src/main/kotlin/no/nav/tilleggsstonader/sak/vedtak/barnetilsyn/VedtakTilsynBarn.kt | navikt | 685,490,225 | false | {"Kotlin": 1581371, "HTML": 39172, "Gherkin": 39138, "Shell": 924, "Dockerfile": 164} | package no.nav.tilleggsstonader.sak.vedtak.barnetilsyn
import no.nav.tilleggsstonader.sak.infrastruktur.database.Sporbar
import no.nav.tilleggsstonader.sak.vedtak.TypeVedtak
import no.nav.tilleggsstonader.sak.vedtak.barnetilsyn.dto.Beregningsresultat
import no.nav.tilleggsstonader.sak.vedtak.barnetilsyn.dto.Utgift
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Embedded
import java.util.UUID
/**
* Trenger vi noe mer enn data her? Kan den kanskje dekke alle tilfeller?
* Eller om ma har vedtak, og beregningsgrunnlag som et eget?
* Trenger man begrunnelse som eget felt?
*/
data class VedtakTilsynBarn(
@Id
val behandlingId: UUID,
val type: TypeVedtak,
val vedtak: VedtaksdataTilsynBarn? = null,
val beregningsresultat: VedtaksdataBeregningsresultat? = null,
val avslagBegrunnelse: String? = null,
@Embedded(onEmpty = Embedded.OnEmpty.USE_EMPTY)
val sporbar: Sporbar = Sporbar(),
) {
init {
when (type) {
TypeVedtak.INNVILGELSE -> {
require(beregningsresultat != null) { "Mangler beregningsresultat for type=$type" }
require(vedtak != null) { "Mangler vedtak for type=$type" }
}
TypeVedtak.AVSLAG -> {
require(avslagBegrunnelse != null) { "Avslag må begrunnes" }
}
}
}
}
data class VedtaksdataTilsynBarn(
val utgifter: Map<UUID, List<Utgift>>,
)
data class VedtaksdataBeregningsresultat(
val perioder: List<Beregningsresultat>,
)
| 3 | Kotlin | 1 | 0 | c234139abe2b80a0c5d814bb5796a92dc5346f86 | 1,556 | tilleggsstonader-sak | MIT License |
composeApp/src/commonMain/kotlin/com/jetbrains/kmpapp/presentation/screens/notes/NotesListScreen.kt | massana2110 | 806,387,488 | false | {"Kotlin": 18527, "Swift": 665} | package com.jetbrains.kmpapp.presentation.screens.notes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import com.jetbrains.kmpapp.database.dao.NotesDao
data class NotesListScreen(
private val notesDao: NotesDao
): Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.current
val notes by notesDao.getAllPeople().collectAsState(initial = emptyList())
Scaffold(
floatingActionButton = {
FloatingActionButton(onClick = {
navigator?.push(AddNoteScreen(notesDao))
}, containerColor = Color.Green) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Add note")
}
}
) {
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Adaptive(200.dp),
contentPadding = it,
verticalItemSpacing = 4.dp,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
items(6) {
Card(modifier = Modifier.fillMaxWidth().wrapContentHeight(), colors = CardDefaults.cardColors(containerColor = Color.Yellow)) {
Text(text = "Ejemplo de nota")
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 1464035e78efbf51dff0662406f502a71c417c4e | 2,300 | NotesAppKMP | Apache License 2.0 |
app/src/main/java/com/aayushpuranik/todolist/presentation/viewModels/RegistrationViewModel.kt | dev-aayushpuranik | 871,340,204 | false | {"Kotlin": 9913} | package com.aayushpuranik.todolist.presentation.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.aayushpuranik.todolist.domain.model.Person
import com.aayushpuranik.todolist.domain.useCase.RegistrationUserCase
import com.aayushpuranik.todolist.presentation.UIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class RegistrationViewModel @Inject constructor(): ViewModel() {
val uiState: MutableLiveData<UIState> by lazy {
MutableLiveData<UIState>()
}
@Inject
lateinit var userCase: RegistrationUserCase
fun addContact(person: Person) {
CoroutineScope(Dispatchers.Main).launch {
val result = userCase.execute(person)
result.onSuccess {
uiState.value = UIState.Success("Success")
}.onFailure { exception ->
handleValidationError(exception = exception)
}
}
}
private fun handleValidationError(exception: Throwable) {
uiState.value = UIState.Error(exception.message ?: "Something went wrong")
}
} | 0 | Kotlin | 0 | 0 | a01a6b79e533ad68c7d83b82bcf89fc080da700b | 1,257 | ToDoList | Apache License 2.0 |
golemiokotlinlib/src/commonMain/kotlin/io/github/martinjelinek/golemiokotlinlib/v2/service/impl/remote/MedicalInstitutionsRemoteRepository.kt | martinjelinek | 763,563,087 | false | {"Kotlin": 230955} | package io.github.martinjelinek.golemiokotlinlib.v2.service.impl.remote
import io.github.martinjelinek.golemiokotlinlib.common.entity.responsedata.MedicalGroup
import io.github.martinjelinek.golemiokotlinlib.common.network.IGolemioApi
import io.github.martinjelinek.golemiokotlinlib.v2.service.IMedicalInstitutionsRepository
/**
* Repository handling medical institutions requests via [api].
*/
internal class MedicalInstitutionsRemoteRepository(
private val api: IGolemioApi
) : IMedicalInstitutionsRepository {
override suspend fun getAllMedicalInstitutions(
latlng: Pair<String, String>?,
range: Int?,
districts: List<String>?,
group: MedicalGroup?,
limit: Int?,
offset: Int?,
updatedSince: String?
) = api.getAllMedicalInstitutions(latlng, range, districts, group, limit, offset, updatedSince)
override suspend fun getMedicalInstitutionById(id: String) = api.getMedicalInstitutionById(id)
override suspend fun getMedicalInstitutionTypes() = api.getMedicalInstitutionTypes()
}
| 0 | Kotlin | 0 | 2 | 19bd309bc9455f71deefbe9c246d2852da9109b5 | 1,062 | golemiokotlin | MIT License |
network/src/main/java/com/sandisetiawan444/network/ApiFactory.kt | sansets | 237,624,534 | false | null | package com.sandisetiawan444.network
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
object ApiFactory {
private fun request(): Retrofit {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.let {
it.level = HttpLoggingInterceptor.Level.HEADERS
it.level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build()
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
}
fun <T> createService(service: Class<T>): T {
return request().create(service)
}
} | 0 | Kotlin | 0 | 3 | 2de991708570de929a148c8af2a76b7dbcea7b19 | 1,061 | ModularSample | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/navigation/Navigation.kt | daniel-waiguru | 343,233,209 | false | {"Kotlin": 24746} | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.navigation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.navigate
import androidx.navigation.compose.rememberNavController
import com.example.androiddevchallenge.ui.PetDetailsScreen
import com.example.androiddevchallenge.ui.PetListScreen
@ExperimentalFoundationApi
@Composable
fun Navigation() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "pets") {
composable("pets") {
PetListScreen { pet ->
initPetDetailsScreen(navController, pet.id)
}
}
composable(
"petDetail/{petId}",
arguments = listOf(
navArgument("petId") {
type = NavType.IntType
}
)
) {
val petId = it.arguments?.getInt("petId")
petId?.let { id ->
PetDetailsScreen(navController, id)
}
}
}
}
fun initPetDetailsScreen(navController: NavController, petId: Int) {
navController.navigate("petDetail/$petId")
}
| 0 | Kotlin | 1 | 1 | 61d1c45440bc55ab876bd878216366c3d00359f9 | 2,028 | Pet-Adoption | Apache License 2.0 |
app/src/main/java/de/lmu/arcasegrammar/viewhelpers/ChoiceQuizLayout.kt | fionade | 353,734,737 | false | null | package de.lmu.arcasegrammar.viewhelpers
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AccelerateInterpolator
import androidx.appcompat.content.res.AppCompatResources
import com.google.android.material.chip.Chip
import de.lmu.arcasegrammar.R
import de.lmu.arcasegrammar.databinding.ChoiceQuizBinding
import de.lmu.arcasegrammar.logging.FirebaseLogger
import de.lmu.arcasegrammar.sentencebuilder.Sentence
class ChoiceQuizLayout(context: Context, private val sentence: Sentence, private val listener: QuizLayoutResponder) : QuizLayout(context) {
// View binding
private var _binding: ChoiceQuizBinding? = null
private val binding get() = _binding!!
// Quiz setup
private var optionList: Array<Chip>
// Logger
private var firebaseLogger: FirebaseLogger = FirebaseLogger.getInstance()
init {
_binding = ChoiceQuizBinding.inflate(LayoutInflater.from(context), this)
optionList = arrayOf(binding.option1, binding.option2, binding.option3)
optionList.forEach { it ->
it.setOnClickListener {onOptionSelected(it) }
}
setQuiz()
}
override fun setQuiz() {
binding.part1.text = sentence.firstPart
binding.part2.text = sentence.secondPart
binding.attribution.text = sentence.attribution ?: ""
binding.option1.text = sentence.distractors[0]
binding.option2.text = sentence.distractors[1]
binding.option3.text = sentence.distractors[2]
firebaseLogger.addLogMessage("show_quiz", sentence.stringify())
binding.root.visibility = View.VISIBLE
}
override fun resetQuiz() {
// binding.root.visibility = View.GONE
// bottomSheet.state = BottomSheetBehavior.STATE_HIDDEN
// reset the radio group so no item is preselected on subsequent quizzes
binding.options.clearCheck()
binding.tickmark.alpha = 0f
binding.incorrectmark.alpha = 0f
optionList.forEach {
it.setChipBackgroundColorResource(R.color.colorOptionBackground)
it.setTextColor(
AppCompatResources.getColorStateList(
context,
R.color.chip_states
)
)
it.isCheckable = true
}
}
private fun onOptionSelected(view: View) {
val chip = view as Chip
if(view.text == sentence.wordToChoose) {
// correct solution found
firebaseLogger.addLogMessage("answer_selected", "correct: ${view.text}")
chip.setChipBackgroundColorResource(R.color.colorAnswerCorrect)
optionList.forEach {
it.isCheckable = false
}
binding.incorrectmark.animate().alpha(0f).setDuration(100)
.setInterpolator(AccelerateInterpolator()).start()
binding.tickmark.animate().alpha(1f).setDuration(800)
.setInterpolator(AccelerateInterpolator()).start()
binding.root.postDelayed({
listener.reset()
}, 3000) // hide quiz 3 seconds after a correct answer
}
else if (binding.tickmark.alpha < 0.1) {
chip.setChipBackgroundColorResource(R.color.colorAnswerIncorrect)
binding.incorrectmark.animate().alpha(1f).setDuration(800)
.setInterpolator(AccelerateInterpolator()).start()
// cannot be selected twice
chip.isCheckable = false
firebaseLogger.addLogMessage("answer_selected", "wrong: ${view.text}")
}
}
} | 0 | Kotlin | 0 | 1 | 01d607914988bb1155a91e3a31f3dd29b0f2c896 | 3,639 | case-ar | Apache License 2.0 |
shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/network/FeedFetcher.kt | msasikanth | 632,826,313 | false | null | /*
* Copyright 2023 <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.sasikanth.rss.reader.network
import io.ktor.client.HttpClient
import io.ktor.client.engine.darwin.Darwin
import kotlinx.coroutines.CoroutineDispatcher
internal actual fun feedFetcher(ioDispatcher: CoroutineDispatcher): FeedFetcher {
val httpClient =
HttpClient(Darwin) {
engine {
configureRequest {
setTimeoutInterval(60.0)
setAllowsCellularAccess(true)
}
}
}
return FeedFetcher(httpClient = httpClient, feedParser = IOSFeedParser(ioDispatcher))
}
| 0 | Kotlin | 0 | 6 | 0258e3ed2f2e9a5ea2eba91530b828e133046802 | 1,113 | reader | Apache License 2.0 |
shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/network/FeedFetcher.kt | msasikanth | 632,826,313 | false | null | /*
* Copyright 2023 <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.sasikanth.rss.reader.network
import io.ktor.client.HttpClient
import io.ktor.client.engine.darwin.Darwin
import kotlinx.coroutines.CoroutineDispatcher
internal actual fun feedFetcher(ioDispatcher: CoroutineDispatcher): FeedFetcher {
val httpClient =
HttpClient(Darwin) {
engine {
configureRequest {
setTimeoutInterval(60.0)
setAllowsCellularAccess(true)
}
}
}
return FeedFetcher(httpClient = httpClient, feedParser = IOSFeedParser(ioDispatcher))
}
| 0 | Kotlin | 0 | 6 | 0258e3ed2f2e9a5ea2eba91530b828e133046802 | 1,113 | reader | Apache License 2.0 |
service-text/src/test/kotlin/io/net/text/TextApplicationTests.kt | spcookie | 671,080,496 | false | null | package io.net.text
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class TextApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Kotlin | 0 | 0 | 1661dd76ccb40f6d8fd002b49328e22918d0a9b8 | 206 | qq-robot | Apache License 2.0 |
utils/tgbotapi-serialization/src/main/kotlin/by/jprof/telegram/bot/utils/tgbotapi_serialization/TgBotAPI.kt | JavaBy | 367,980,780 | false | null | package by.jprof.telegram.bot.utils.tgbotapi_serialization
import by.jprof.telegram.bot.utils.tgbotapi_serialization.serializers.TextContentSerializer
import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.message.content.abstracts.MessageContent
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
object TgBotAPI {
val module = SerializersModule {
polymorphic(MessageContent::class) {
// subclass(AnimationContent::class, AnimationContentSerializer())
// subclass(AudioContent::class, AudioContentSerializer())
// subclass(AudioMediaGroupContent::class, AudioMediaGroupContentSerializer())
// subclass(ContactContent::class, ContactContentSerializer())
// subclass(DiceContent::class, DiceContentSerializer())
// subclass(DocumentContent::class, DocumentContentSerializer())
// subclass(DocumentMediaGroupContent::class, DocumentMediaGroupContentSerializer())
// subclass(GameContent::class, GameContentSerializer())
// subclass(InvoiceContent::class, InvoiceContentSerializer())
// subclass(LocationContent::class, LocationContentSerializer())
// subclass(MediaCollectionContent::class, MediaCollectionContentSerializer())
// subclass(MediaContent::class, MediaContentSerializer())
// subclass(MediaGroupContent::class, MediaGroupContentSerializer())
// subclass(PhotoContent::class, PhotoContentSerializer())
// subclass(PollContent::class, PollContentSerializer())
// subclass(StickerContent::class, StickerContentSerializer())
subclass(TextContent::class, TextContentSerializer())
// subclass(VenueContent::class, VenueContentSerializer())
// subclass(VideoContent::class, VideoContentSerializer())
// subclass(VideoNoteContent::class, VideoNoteContentSerializer())
// subclass(VisualMediaGroupContent::class, VisualMediaGroupContentSerializer())
// subclass(VoiceContent::class, VoiceContentSerializer())
}
}
}
| 21 | Kotlin | 2 | 2 | 7e0f2c68e3acc9ff239effa34f5823e4ef8212c9 | 2,195 | jprof_by_bot | MIT License |
src/kotlin/ru/ifmo/antll1/entities/Grammar.kt | niki999922 | 283,890,943 | false | null | package ru.ifmo.antll1.entities
import ru.ifmo.antll1.entities.table.FFTable
import ru.ifmo.antll1.entities.table.LineTable
import ru.ifmo.antll1.entities.table.Table
import ru.ifmo.antll1.generator.LexerGenerator
import ru.ifmo.antll1.generator.ParserGenerator
import java.lang.Exception
import java.nio.file.Path
import java.util.*
import kotlin.collections.ArrayList
class Grammar {
public val tokens = mutableListOf<TokenQ>()
public val rules = mutableListOf<Rule>()
public val ignore = mutableListOf<Ignore>()
lateinit var headers: CodeStep
lateinit var startRule: String
lateinit var grammarName: String
/**
* @param path location for generated files
* @param packageName package generated classes
*/
fun build(path: Path, packageName: String = "") {
val lexerBuilder = LexerGenerator(packageName, grammarName, tokens, ignore)
val parserBuilder = ParserGenerator(packageName, grammarName, rules, tokens, ignore, startRule, headers)
try{
lexerBuilder.build(path.toFile())
parserBuilder.build(path.toFile())
} catch (exception : Exception) {
println("Generating was occurred exception: ${exception.message}")
println(exception.stackTrace)
}
}
}
fun generateOwnRules(): List<Rule> {
val rules = LinkedList<Rule>()
val e = Rule("E")
var c = Condition()
c.steps.add(RuleTermStep("r", "T"))
c.steps.add(CodeStep("code code 1"))
c.steps.add(RuleTermStep("", "E1"))
c.steps.add(CodeStep("code code 2"))
e.conditions.add(c)
rules.add(e)
val e1 = Rule("E1")
c = Condition()
c.steps.add(RuleTermStep("", "PLUS"))
c.steps.add(RuleTermStep("", "T"))
c.steps.add(CodeStep("code code 3"))
c.steps.add(RuleTermStep("", "E1"))
e1.conditions.add(c)
c = Condition()
c.steps.add(CodeStep(""))
e1.conditions.add(c)
rules.add(e1)
val t = Rule("T")
c = Condition()
c.steps.add(RuleTermStep("", "F"))
c.steps.add(RuleTermStep("p", "T1"))
c.steps.add(CodeStep("code code 4"))
t.conditions.add(c)
rules.add(t)
val t1 = Rule("T1")
c = Condition()
c.steps.add(RuleTermStep("", "MUL"))
c.steps.add(RuleTermStep("", "F"))
c.steps.add(RuleTermStep("", "T1"))
t1.conditions.add(c)
c = Condition()
c.steps.add(CodeStep(""))
t1.conditions.add(c)
rules.add(t1)
val f = Rule("F")
c = Condition()
c.steps.add(RuleTermStep("", "OP_B"))
c.steps.add(RuleTermStep("", "E"))
c.steps.add(RuleTermStep("", "CL_B"))
f.conditions.add(c)
c = Condition()
c.steps.add(RuleTermStep("","NUM"))
f.conditions.add(c)
rules.add(f)
return rules
}
fun generateOwnRules2(): List<Rule> {
val rules = LinkedList<Rule>()
val e = Rule("E")
var c = Condition()
c.steps.add(RuleTermStep("r", "T"))
c.steps.add(CodeStep("code code 1"))
c.steps.add(RuleTermStep("", "E1"))
c.steps.add(CodeStep("code code 2"))
e.conditions.add(c)
rules.add(e)
val e1 = Rule("E1")
c = Condition()
c.steps.add(RuleTermStep("", "PLUS"))
c.steps.add(RuleTermStep("", "T1"))
c.steps.add(RuleTermStep("", "E1"))
c.steps.add(RuleTermStep("", "E1"))
e1.conditions.add(c)
c = Condition()
c.steps.add(CodeStep(""))
e1.conditions.add(c)
rules.add(e1)
val t = Rule("T")
c = Condition()
c.steps.add(RuleTermStep("", "F"))
c.steps.add(RuleTermStep("p", "T1"))
c.steps.add(CodeStep("code code 4"))
t.conditions.add(c)
rules.add(t)
val t1 = Rule("T1")
c = Condition()
c.steps.add(RuleTermStep("", "MUL"))
c.steps.add(RuleTermStep("", "F"))
c.steps.add(RuleTermStep("", "T1"))
t1.conditions.add(c)
c = Condition()
c.steps.add(CodeStep(""))
t1.conditions.add(c)
rules.add(t1)
val f = Rule("F")
c = Condition()
c.steps.add(RuleTermStep("", "OP_B"))
c.steps.add(RuleTermStep("", "E"))
c.steps.add(RuleTermStep("", "CL_B"))
f.conditions.add(c)
c = Condition()
c.steps.add(RuleTermStep("","NUM"))
f.conditions.add(c)
rules.add(f)
return rules
}
fun createTable(rules: List<Rule>, list: List<String>, startRule: String): Table {
val table = Table(list, startRule)
rules.forEach { rule ->
val fftable = FFTable()
table.rules[rule.name] = fftable
rule.conditions.forEach { cond ->
val lineT = LineTable()
if (cond.steps.size == 1 && cond.steps[0].stepType == StepType.CODE) {
lineT.steps.add("EPS")
} else {
cond.steps.filter { it.stepType == StepType.NON_CODE }.forEach {
lineT.steps.add((it as RuleTermStep).rightPart)
}
}
fftable.conditions.add(lineT)
}
}
return table
}
fun main() {
val rules = generateOwnRules2()
val tokens = listOf("PLUS", "MUL", "NUM", "OP_B", "CL_B", "EPS") //need add EPS
val table = createTable(rules, tokens, "E")
table.buildFirst()
table.buildFollow()
println("")
} | 0 | Kotlin | 0 | 0 | 3b980c6c7348dbdcbc7eaf69b28db0083540efc0 | 5,147 | parser-generator | MIT License |
client/client-hapi/src/commonMain/kotlin/de/jlnstrk/transit/api/hapi/model/location/HapiStopOrCoordLocation.kt | jlnstrk | 229,599,180 | false | {"Kotlin": 729374} | package de.jlnstrk.transit.api.hapi.model.location
public sealed interface HapiStopOrCoordLocation | 0 | Kotlin | 0 | 0 | 9f700364f78ebc70b015876c34a37b36377f0d9c | 99 | transit | Apache License 2.0 |
WW/app/src/main/java/com/ersubhadip/domains/dto/adapterModels/BlogModel.kt | Subhadiptech | 585,628,839 | false | null | package com.ersubhadip.domains.dto.adapterModels
data class BlogModel(
val id: Int,
val blogTitle: String,
val blogDesc: String,
val blogUrl: String,
)
| 0 | Kotlin | 0 | 0 | 5d1ef1d9ac615cd0cdc14297f0aae0bf941f3c44 | 174 | SheBuild_Hack | W3C Software Notice and License (2002-12-31) |
apps/intellij/src/main/kotlin/dev/nx/console/models/NxVersion.kt | nrwl | 137,811,219 | false | {"TypeScript": 612398, "Kotlin": 285501, "SCSS": 17440, "HTML": 14999, "JavaScript": 9873, "CSS": 635} | package dev.nx.console.models
import kotlinx.serialization.Serializable
@Serializable() data class NxVersion(val minor: Int, val major: Int, val full: String) {}
| 43 | TypeScript | 191 | 1,209 | b6eb1094a722bec165fc0305e8707a15d1b151b6 | 164 | nx-console | MIT License |
src/mingwX64Test/kotlin/services/api/client/CandilibreClientTests.kt | tritus | 294,231,475 | false | null | package services.api.client
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import kotlin.test.Test
import kotlin.test.assertEquals
class CandilibreClientTests {
@Test
fun testGet() {
runBlocking {
val client = HttpClient("https", "jsonplaceholder.typicode.com", "", "testToken")
val response = client.get<List<TodoTestObject>>("todos", "id" to "1")
val expected = listOf(
TodoTestObject(
1,
1,
"delectus aut autem",
false
)
)
assertEquals(expected, response)
}
}
@Test
fun testPatch() {
runBlocking {
val client = HttpClient("https", "jsonplaceholder.typicode.com", "", "testToken")
val body = TodoTestObject(
1,
1,
"testTitle",
true
)
val response = client.patch<TodoTestObject, TodoTestObject>("posts/1", body)
val expected = TodoTestObject(
1,
1,
"testTitle",
true
)
assertEquals(expected, response)
}
}
@Serializable
private data class TodoTestObject(
val userId: Int? = null,
val id: Int? = null,
val title: String? = null,
val completed: Boolean? = null
)
} | 13 | Kotlin | 8 | 7 | b8c742a74cce050fcceb196ca2158cdc598542bc | 1,484 | candilibre | MIT License |
android/app/src/main/kotlin/com/vonage/tutorial/opentok/opentok_flutter_samples/one_to_one_video/OpentokVideoPlatformView.kt | Vonage-Community | 508,751,202 | false | {"Kotlin": 56903, "Swift": 35393, "Dart": 28210, "Ruby": 1369, "Objective-C": 38} | package com.vonage.tutorial.opentok.opentok_flutter_samples.one_to_one_video
import android.content.Context
import android.view.View
import io.flutter.plugin.platform.PlatformView
class OpentokVideoPlatformView(context: Context) : PlatformView {
private val videoContainer: OpenTokVideoContainer = OpenTokVideoContainer(context)
val subscriberContainer get() = videoContainer.subscriberContainer
val publisherContainer get() = videoContainer.publisherContainer
override fun getView(): View {
return videoContainer
}
override fun dispose() {}
} | 10 | Kotlin | 2 | 5 | e2c99c64a0c87af6c842778bd49aa9d702bcb6a2 | 580 | sample-video-flutter-app | Apache License 2.0 |
rules.kts | henrithing | 436,598,614 | true | {"Kotlin": 707} | val permissiveLicenses = licenseClassifications.licensesByCategory["permissive"].orEmpty()
val copyleftLicenses = licenseClassifications.licensesByCategory["copyleft"].orEmpty()
// The complete set of licenses covered by policy rules.
val handledLicenses = listOf(
permissiveLicenses,
).flatten().let {
it.toSet()
}
fun PackageRule.LicenseRule.isHandled() =
object : RuleMatcher {
override val description = "isHandled($license)"
override fun matches() = license in handledLicenses
}
// Define the set of policy rules.
val ruleSet = ruleSet(ortResult, licenseInfoResolver) {}
// Populate the list of policy rule violations to return.
ruleViolations += ruleSet.violations | 0 | Kotlin | 0 | 0 | ccd2a6297f6f4d0a7eb66ee9eec3fc439ecebed2 | 707 | policy-configuration | Creative Commons Zero v1.0 Universal |
feature-ui/licenses/src/commonMain/kotlin/com/addhen/fosdem/ui/licenses/component/LicensesPreference.kt | eyedol | 170,208,282 | false | {"Kotlin": 547488, "Shell": 3072, "Swift": 1713} | // Copyright 2024, Addhen Limited and the FOSDEM Event app project contributors
// SPDX-License-Identifier: Apache-2.0
package com.addhen.fosdem.ui.licenses.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun Preference(
title: String,
modifier: Modifier = Modifier,
summary: (@Composable () -> Unit)? = null,
control: (@Composable () -> Unit)? = null,
) {
Surface(modifier = modifier) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
Text(
text = title,
style = MaterialTheme.typography.bodyLarge,
)
if (summary != null) {
ProvideTextStyle(
MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant,
),
) {
summary()
}
}
}
control?.invoke()
}
}
}
@Composable
fun PreferenceHeader(
title: String,
modifier: Modifier = Modifier,
tonalElevation: Dp = 0.dp,
) {
Surface(modifier = modifier, tonalElevation = tonalElevation) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
}
| 7 | Kotlin | 0 | 1 | e3dd0a21b1fdc0abc7fefb349caa2773f2d65fcb | 1,933 | fosdem-event-app | Apache License 2.0 |
src/main/kotlin/no/nav/k9brukerdialogapi/ytelse/omsorgspengerutbetalingarbeidstaker/domene/Barn.kt | navikt | 460,765,798 | false | {"Kotlin": 849179, "Dockerfile": 103} | package no.nav.k9brukerdialogapi.ytelse.omsorgspengerutbetalingarbeidstaker.domene
import com.fasterxml.jackson.annotation.JsonFormat
import no.nav.k9.søknad.felles.type.NorskIdentitetsnummer
import no.nav.k9brukerdialogapi.general.erFørEllerLik
import no.nav.k9brukerdialogapi.general.erLikEllerEtter
import no.nav.k9brukerdialogapi.general.krever
import no.nav.k9brukerdialogapi.general.validerIdentifikator
import no.nav.k9brukerdialogapi.oppslag.barn.BarnOppslag
import no.nav.k9.søknad.felles.personopplysninger.Barn as K9Barn
import java.time.LocalDate
class Barn(
private var identitetsnummer: String? = null,
private val aktørId: String? = null,
@JsonFormat(pattern = "yyyy-MM-dd") private val fødselsdato: LocalDate,
private val navn: String,
private val type: TypeBarn
) {
companion object {
internal fun List<Barn>.somK9BarnListe() = kunFosterbarn().map { it.somK9Barn() }
private fun List<Barn>.kunFosterbarn() = this.filter { it.type == TypeBarn.FOSTERBARN }
internal fun List<Barn>.valider(felt: String) = this.flatMapIndexed { index, barn ->
barn.valider("$felt[$index]")
}
}
internal fun valider(felt: String) = mutableListOf<String>().apply {
validerIdentifikator(identitetsnummer, "$felt.identitetsnummer")
krever(navn.isNotBlank(), "$felt.navn kan ikke være tomt eller blankt.")
krever(
fødselsdato.erLikEllerEtter(LocalDate.now().minusYears(19)),
"$felt.fødselsdato kan ikke være mer enn 19 år siden."
)
krever(
fødselsdato.erFørEllerLik(LocalDate.now()),
"$felt.fødselsdato kan ikke være i fremtiden."
)
}
internal fun leggTilIdentifikatorHvisMangler(barnFraOppslag: List<BarnOppslag>){
if(identitetsnummer == null) identitetsnummer = barnFraOppslag.find { it.aktørId == this.aktørId }?.identitetsnummer
}
internal fun somK9Barn(): K9Barn {
val barn = K9Barn()
if (identitetsnummer != null) {
barn.medNorskIdentitetsnummer(NorskIdentitetsnummer.of(identitetsnummer));
} else {
barn.medFødselsdato(fødselsdato)
}
return barn
}
}
enum class TypeBarn {
FRA_OPPSLAG,
FOSTERBARN,
ANNET
}
| 1 | Kotlin | 0 | 0 | 8bb3947ffc2be0ddd39dd5a1f9c79bec4e9c145a | 2,288 | k9-brukerdialog-api | MIT License |
words-lib/src/main/kotlin/tech/soit/words/lib/smali/SmaliElementTypes.kt | boyan01 | 284,055,924 | false | null | package tech.soit.words.lib.smali
import org.jf.smali.smaliParser
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
object SmaliElementTypes {
@Suppress("NOTHING_TO_INLINE")
private inline fun token(): ReadOnlyProperty<SmaliElementTypes, SmaliElementType> {
return object : ReadOnlyProperty<SmaliElementTypes, SmaliElementType> {
override fun getValue(
thisRef: SmaliElementTypes,
property: KProperty<*>
): SmaliElementType {
val name = property.name
return SmaliElementType(name, smaliParser.tokenNames.indexOf(name))
}
}
}
// 类说明 .class
val CLASS_DESCRIPTOR by token()
val I_ACCESS_LIST by token()
val I_SUPPER by token()
val I_SOURCE by token()
val I_METHODS by token()
val I_FIELDS by token()
val I_ANNOTATIONS by token()
val I_IMPLEMENTS by token()
} | 0 | Kotlin | 0 | 1 | 0890d02eb81d5407b9265202d096cd44e6d41784 | 955 | check-apk-words | Apache License 2.0 |
app/src/main/java/emu/cosmic/data/CosmicSettings.kt | shadergz | 664,406,301 | false | {"C++": 360624, "Kotlin": 52114, "CMake": 5937} | package emu.cosmic.data
import android.content.Context
import android.content.res.Resources.NotFoundException
import emu.cosmic.CosmicApplication
class CosmicSettings private constructor(context: Context) {
var appStorage by DelegateDataStore<String>(
SettingContainer(context, SettingsKeys.AppStorage))
var gpuTurboMode by DelegateDataStore<Boolean>(
SettingContainer(context, SettingsKeys.GpuTurboMode))
var customDriver by DelegateDataStore<String>(
SettingContainer(context, SettingsKeys.CustomDriver))
var eeMode by DelegateDataStore<Int>(
SettingContainer(context, SettingsKeys.EEMode))
var biosPath by DelegateDataStore<String>(
SettingContainer(context, SettingsKeys.BiosPath))
// Creating a static object to store all our configurations
// This object will reside in the global heap memory (Accessible to JNI)
companion object {
val globalSettings by lazy { CosmicSettings(CosmicApplication.context) }
var updateSettings: Boolean = false
private var dsCachedSet: HashMap<String, Any>? = null
private fun updateAllValues() {
if (!updateSettings)
return
dsCachedSet?.clear()
val dsCached = mapOf(
"dsdb_app_storage" to globalSettings.appStorage,
"dsdb_gpu_turbo_mode" to globalSettings.gpuTurboMode,
"dsdb_gpu_custom_driver" to globalSettings.customDriver,
"dsdb_ee_mode" to globalSettings.eeMode,
"dsdb_bios_path" to globalSettings.biosPath
)
dsCachedSet = HashMap(dsCached)
updateSettings = false
}
@JvmStatic
fun getDataStoreValue(config: String) : Any {
if (!updateSettings)
updateSettings = dsCachedSet == null
updateAllValues()
dsCachedSet?.let {
if (!it.containsKey(config))
throw NotFoundException(config)
return it[config]!!
}
return {}
}
}
} | 10 | C++ | 5 | 192 | d960de0b62a4637f8a2368ee1e5f0c5f69a95ef4 | 2,102 | cosmic-station | MIT License |
app/src/main/java/com/example/movieapp/features/Home/domain/MainViewModel.kt | NolifekNTB | 751,407,208 | false | {"Kotlin": 238529} | package com.example.movieapp.features.Home.domain
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.movieapp.core.database.entities.AnimeItemTopCharacters
import com.example.movieapp.core.database.entities.AnimeItemTopHits
import com.example.movieapp.core.network.RetrofitInstance
import com.example.movieapp.core.network.models.shared.AnimeData
import com.example.movieapp.core.network.models.topCharacters.DataTopCharacters
import com.example.movieapp.features.Home.data.repositories.AnimeRepository
import com.example.movieapp.features.Home.data.repositories.AnimeRepositoryTopCharacters
import com.example.movieapp.features.Home.data.model.topHitsAndTopCharacters
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
private val repoTopHits: AnimeRepository,
private val repoTopCharacters: AnimeRepositoryTopCharacters
): ViewModel() {
private val apiTopHits = RetrofitInstance.animeApiTopHits
private val apiTopCharacters = RetrofitInstance.animeApiTopCharacters
init {
fetchPost()
}
fun fetchPost() {
viewModelScope.launch {
try{
val topHitsFromDb = repoTopHits.getAllAnime().first()
if (topHitsFromDb.isEmpty()) {
val responseTopHits = apiTopHits.getTopHits()
insertTopHits(mapRetrofitToRoomTopHits(responseTopHits))
}
val topCharactersFromDb = repoTopCharacters.getAllAnime().first()
if(topCharactersFromDb.isEmpty()){
val responseTopCharacters = apiTopCharacters.getTopCharacters()
insertTopCharacters(mapRetrofitToRoomTopCharacters(responseTopCharacters))
Log.d("", "topCharacters -> $responseTopCharacters")
}
} catch (e: Exception){
Log.e("codeDebugging", "fetchPost -> $e")
}
}
}
private fun mapRetrofitToRoomTopHits(animeData: AnimeData): List<AnimeItemTopHits> {
val animeItemList = mutableListOf<AnimeItemTopHits>()
animeData.data.forEach { data ->
val animeItem = AnimeItemTopHits(
name = data.title,
image = data.images.jpg.image_url,
rating = data.score,
year = data.year,
genres = data.genres,
description = data.synopsis,
trailer = data.trailer
)
animeItemList.add(animeItem)
}
return animeItemList
}
private fun mapRetrofitToRoomTopCharacters(animeData: DataTopCharacters): List<AnimeItemTopCharacters> {
val animeItemList = mutableListOf<AnimeItemTopCharacters>()
animeData.data.forEach { data ->
val animeItem = AnimeItemTopCharacters(
name = data.name,
image = data.images.jpg.image_url,
)
animeItemList.add(animeItem)
}
return animeItemList
}
fun getLists(): topHitsAndTopCharacters {
val list1 = getListTopHits()
val list2 = getListNewSeasons()
return topHitsAndTopCharacters(
topHits = list1,
topCharacters = list2
)
}
fun getListTopHits(): Flow<List<AnimeItemTopHits>> {
return repoTopHits.getAllAnime()
}
fun getListNewSeasons(): Flow<List<AnimeItemTopCharacters>> {
return repoTopCharacters.getAllAnime()
}
private fun insertTopHits(animeList: List<AnimeItemTopHits>) {
CoroutineScope(viewModelScope.coroutineContext).launch{
repoTopHits.insertAllAnime(
animeList
)
}
}
private fun insertTopCharacters(animeList: List<AnimeItemTopCharacters>) {
CoroutineScope(viewModelScope.coroutineContext).launch{
repoTopCharacters.insertAllAnime(
animeList
)
}
}
suspend fun searchAllAnime(query: String): List<AnimeItemTopHits> {
return repoTopHits.searchAnimeByName(query)
}
} | 0 | Kotlin | 0 | 0 | 8305f925e7f1a760c9a2b029cf3f5dd4f41cde2d | 4,348 | Movie-app | MIT License |
gradle/plugins/src/main/kotlin/net/twisterrob/gradle/build/compilation/JavaCompatibilityPlugin.kt | TWiStErRob | 116,494,236 | false | null | package net.twisterrob.gradle.build.compilation
import net.twisterrob.gradle.build.dsl.libs
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.withModule
class JavaCompatibilityPlugin : Plugin<Project> {
override fun apply(target: Project) {
target.dependencies.components {
// AGP 8.0.0-alpha10 requires Java 17 (https://issuetracker.google.com/issues/241546506)
// But Google didn't change the Java compiler and class file format to be Java 17 yet.
// Even AGP 8.1.0-beta03 is published with Java 11 bytecode
// according to its gradle-module-metadata and class header.
// AGP 8.2.0-alpha03 onwards is published with Java 17 bytecode according to its metadata.
// ```
// Execution failed for task ':common:compileKotlin'.
// > Could not resolve all files for configuration ':common:compileClasspath'.
// > Could not resolve com.android.tools.build:gradle:8.2.0-alpha05.
// Required by: project :common
// > No matching variant of com.android.tools.build:gradle:8.2.0-alpha05 was found.
// The consumer was configured to find a library for use during compile-time, compatible with Java 11,
// preferably not packaged as a jar, preferably optimized for standard JVMs,
// and its dependencies declared externally,
// as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' but:
// - Variant 'apiElements' capability com.android.tools.build:gradle:8.2.0-alpha05 declares ...:
// - Incompatible because this component declares a component, compatible with Java 17
// and the consumer needed a component, compatible with Java 11
// ```
// This project still uses Java 11 for compatibility with AGP 7.x.
// Let's rewrite the metadata of AGP 8.2, so that the produced jars can still be used with Java 11.
// https://docs.gradle.org/current/userguide/component_metadata_rules.html
val javaVersion = target.libs.versions.java.get()
.let { JavaVersion.toVersion(it).majorVersion.toInt() }
//@formatter:off
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:gradle") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:gradle-api") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:gradle-settings-api") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:builder") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:builder-model") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:builder-test-api") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:manifest-merger") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:aapt2-proto") { params(javaVersion) }
withModule<LatestAgpTargetJvmLoweringRule>("com.android.tools.build:aaptcompiler") { params(javaVersion) }
//@formatter:on
}
}
}
| 81 | Kotlin | 4 | 12 | a94aad990bad3b5556dbea287d003113d59bf6cc | 3,090 | net.twisterrob.gradle | The Unlicense |
presentation/src/main/java/com/intact/moviesbox/presentation/viewmodels/FragmentListViewModel.kt | tamselvan89 | 256,683,380 | true | {"Kotlin": 173396} | package com.intact.moviesbox.presentation.viewmodels
import androidx.lifecycle.MutableLiveData
import com.intact.moviesbox.domain.entities.MovieDomainDTO
import com.intact.moviesbox.domain.entities.NowPlayingMoviesDomainDTO
import com.intact.moviesbox.domain.entities.TopRatedMoviesDomainDTO
import com.intact.moviesbox.domain.entities.UpcomingMoviesDomainDTO
import com.intact.moviesbox.domain.usecases.GetNowPlayingMoviesUseCase
import com.intact.moviesbox.domain.usecases.GetTopRatedMoviesUseCase
import com.intact.moviesbox.domain.usecases.GetUpcomingMoviesUseCase
import com.intact.moviesbox.domain.usecases.SaveMovieDetailUseCase
import com.intact.moviesbox.presentation.mapper.Mapper
import com.intact.moviesbox.presentation.model.*
import com.intact.moviesbox.presentation.viewmodels.base.BaseViewModel
import timber.log.Timber
import javax.inject.Inject
/**
* view models don't care about the source of data. They are only
* dependable on the observables handed over by use cases. View models
* don't have any idea how to get and set the data. View models convert these
* observables into live data using live data reactive streams and expose
* only live data
*
* If you want an Observable to emit a specific sequence of items before it
* begins emitting the items normally expected from it, apply the StartWith
* operator to it.
*
* handling the error cases in rx can be checked at
* https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators
* doOnError, onErrorComplete, onErrorResumeNext, onErrorReturn, onErrorReturnItem
* onExceptionResumeNext, retry, retryUntil, retryWhen
*/
class FragmentListViewModel @Inject constructor(
private val movieMapper: Mapper<MovieDomainDTO, MovieDTO>,
private val saveMovieDetailUseCase: SaveMovieDetailUseCase,
private val getUpcomingMoviesUseCase: GetUpcomingMoviesUseCase,
private val getTopRatedMoviesUseCase: GetTopRatedMoviesUseCase,
private val getNowPlayingMoviesUseCase: GetNowPlayingMoviesUseCase,
private val topRatedMoviesMapper: Mapper<TopRatedMoviesDomainDTO, TopRatedMoviesDTO>,
private val upcomingMoviesMapper: Mapper<UpcomingMoviesDomainDTO, UpcomingMoviesDTO>,
private val nowPlayingMoviesMapper: Mapper<NowPlayingMoviesDomainDTO, NowPlayingMoviesDTO>
) : BaseViewModel() {
private val isLoading = MutableLiveData<Boolean>()
private val topRatedErrorLiveData = MutableLiveData<ErrorDTO>()
private val upcomingErrorLiveData = MutableLiveData<ErrorDTO>()
private val loadingProgressLiveData = MutableLiveData<Boolean>()
private val nowPlayingErrorLiveData = MutableLiveData<ErrorDTO>()
private val topRatedMoviesLiveData = MutableLiveData<ArrayList<MovieDTO>>()
private val upcomingMoviesLiveData = MutableLiveData<ArrayList<MovieDTO>>()
private val nowPlayingMoviesLiveData = MutableLiveData<ArrayList<MovieDTO>>()
// get now playing movies
fun getNowPlayingMovies(pageNumber: String) {
isLoading.value = true
getCompositeDisposable().add(
getNowPlayingMoviesUseCase.buildUseCase(GetNowPlayingMoviesUseCase.Param(pageNumber = pageNumber))
.doOnSubscribe {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = true
}
}
.doOnTerminate {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = false
}
}
.map {
nowPlayingMoviesMapper.to(it)
}
.subscribe({ it ->
Timber.d("Success: Now playing movies response received: ${it.movies}")
nowPlayingMoviesLiveData.value = it.movies
}, {
nowPlayingErrorLiveData.value =
ErrorDTO(code = 400, message = it.localizedMessage)
})
)
}
// get the top rated movies
fun getTopRatedMovies(pageNumber: String) {
isLoading.value = true
getCompositeDisposable().add(
getTopRatedMoviesUseCase.buildUseCase(GetTopRatedMoviesUseCase.Param(pageNumber = pageNumber))
.doOnSubscribe {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = true
}
}
.doOnTerminate {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = false
}
}
.map { topRatedMoviesMapper.to(it) }
.subscribe({ it ->
Timber.d("Success: Top rated movies response received: ${it.movies}")
topRatedMoviesLiveData.value = it.movies
}, {
topRatedErrorLiveData.value =
ErrorDTO(code = 400, message = it.localizedMessage)
})
)
}
// get the upcoming movies
fun getUpcomingMovies(pageNumber: String) {
isLoading.value = true
getCompositeDisposable().add(
getUpcomingMoviesUseCase.buildUseCase(GetUpcomingMoviesUseCase.Param(pageNumber = pageNumber))
.doOnSubscribe {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = true
}
}
.doOnTerminate {
// only for the first page we are asking for update
if (pageNumber == "1") {
loadingProgressLiveData.value = false
}
}
.map { upcomingMoviesMapper.to(it) }
.subscribe({
Timber.d("Success: Upcoming movies response received: ${it.movies}")
upcomingMoviesLiveData.value = it.movies
}, {
upcomingErrorLiveData.value =
ErrorDTO(code = 400, message = it.localizedMessage)
})
)
}
// save the movie detail
fun saveMovieDetail(movieDTO: MovieDTO) {
getCompositeDisposable().add(
saveMovieDetailUseCase.buildUseCase(
SaveMovieDetailUseCase.Param(movieDomainDTO = movieMapper.from(movieDTO))
).subscribe({
Timber.d("Movie successfully saved in DB")
}, {
Timber.d("Error while saving: ${it.localizedMessage}")
}
)
)
}
fun getTopRatedErrorLiveData() = topRatedErrorLiveData
fun getUpcomingErrorLiveData() = upcomingErrorLiveData
fun getNowPlayingErrorLiveData() = nowPlayingErrorLiveData
fun getLoadingProgressLiveData() = loadingProgressLiveData
fun getTopRatedMoviesListLiveData() = topRatedMoviesLiveData
fun getUpcomingMoviesListLiveData() = upcomingMoviesLiveData
fun getNowPlayingMoviesListLiveData() = nowPlayingMoviesLiveData
// val topRatedMoviesLiveData: LiveData<Resource<NowPlayingMoviesModel>>
// get() = nowPlayingMoviesUseCase
// .buildUseCase(NowPlayingMoviesUseCase.Param("1"))
// .map { nowPlayingMoviesMapper.to(it) }
// .map { Resource.success(it) }
// .startWith(Resource.loading())
// .onErrorResumeNext(
// Function {
// Observable.just(Resource.error(it.localizedMessage))
// }
// )
// .toFlowable(BackpressureStrategy.LATEST) // not working with single observable
// .toLiveData()
} | 0 | null | 0 | 0 | eacba479cdf46ad36cc3287e7d401c68068b68bf | 7,992 | MovieBox | Apache License 2.0 |
booking-service/src/main/kotlin/no/octopod/cinema/booking/converter/OrderConverter.kt | kissorjeyabalan | 153,418,423 | false | null | package no.octopod.cinema.booking.converter
import no.octopod.cinema.common.dto.OrderDto
import no.octopod.cinema.booking.entity.OrderEntity
import no.octopod.cinema.common.hateos.HalPage
import kotlin.streams.toList
class OrderConverter {
companion object {
fun transform(orderEntity: OrderEntity): OrderDto {
return OrderDto(
id = orderEntity.id,
order_time = orderEntity.orderTime,
user_id = orderEntity.userId,
price = orderEntity.price,
screening_id = orderEntity.screeningId,
payment_token = orderEntity.paymentToken,
tickets = orderEntity.tickets
)
}
fun transform(entities: List<OrderEntity>, page: Int, limit: Int): HalPage<OrderDto> {
val offset = ((page - 1) * limit).toLong()
val dtoList: MutableList<OrderDto> = entities.stream()
.skip(offset)
.limit(limit.toLong())
.map { transform(it) }
.toList().toMutableList()
val pageDto = HalPage<OrderDto>()
pageDto.data = dtoList
pageDto.count = entities.size.toLong()
pageDto.pages = ((pageDto.count / limit)).toInt()
return pageDto
}
}
} | 1 | Kotlin | 1 | 0 | a3f2d25a418929f678b94f74f3ce37d17c081472 | 1,368 | kino-application | MIT License |
src/main/kotlin/utils/gradleUtils.kt | adamko-dev | 619,933,823 | false | {"Kotlin": 59374} | package dev.adamko.gradle.dev_publish.utils
import org.gradle.api.artifacts.Configuration
import org.gradle.api.file.RelativePath
/**
* Mark this [Configuration] as one that will be consumed by other subprojects.
*
* ```
* isCanBeResolved = false
* isCanBeConsumed = true
* isCanBeDeclared = false
* ```
*/
internal fun Configuration.asProvider(
visible: Boolean = true
) {
isCanBeResolved = false
isCanBeConsumed = true
isCanBeDeclared = false
isVisible = visible
}
/**
* Mark this [Configuration] as one that will fetch artifacts (also known as 'resolving').
*
* ```
* isCanBeResolved = true
* isCanBeConsumed = false
* isCanBeDeclared = false
* ```
* */
internal fun Configuration.asConsumer(
visible: Boolean = false
) {
isCanBeResolved = true
isCanBeConsumed = false
isCanBeDeclared = false
isVisible = visible
}
/**
* Mark this [Configuration] for declaring dependencies in the `dependencies {}` block.
*
* ```
* isCanBeResolved = false
* isCanBeConsumed = false
* isCanBeDeclared = true
* ```
* */
internal fun Configuration.forDependencies(
visible: Boolean = false
) {
isCanBeResolved = false
isCanBeConsumed = false
isCanBeDeclared = true
isVisible = visible
}
/** Drop the first [count] directories from the [RelativePath] */
internal fun RelativePath.dropDirectories(count: Int): RelativePath =
RelativePath(true, *segments.drop(count).toTypedArray())
/** Drop the first directory from the [RelativePath] */
internal fun RelativePath.dropDirectory(): RelativePath =
dropDirectories(1)
| 2 | Kotlin | 0 | 3 | 52681746f5c5c7002b9cbcac09d799fc82156969 | 1,566 | dev-publish-plugin | Apache License 2.0 |
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/chapter2_material_widgets/ConstraintLayoutSample.kt | SmartToolFactory | 326,400,374 | false | null | package com.smarttoolfactory.tutorial1_1basics.chapter2_material_widgets
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.layoutId
@Preview
@Composable
fun DecoupledConstraintLayout() {
BoxWithConstraints {
val constraints = if (minWidth < 600.dp) {
decoupledConstraints(margin = 16.dp) // Portrait constraints
} else {
decoupledConstraints(margin = 32.dp) // Landscape constraints
}
ConstraintLayout(constraints) {
Button(
onClick = { /* Do something */ },
modifier = Modifier.layoutId("button")
) {
Text("Button")
}
Text("Text", Modifier.layoutId("text"))
}
}
}
private fun decoupledConstraints(margin: Dp): ConstraintSet {
return ConstraintSet {
val button = createRefFor("button")
val text = createRefFor("text")
constrain(button) {
top.linkTo(parent.top, margin = margin)
}
constrain(text) {
top.linkTo(button.bottom, margin)
}
}
}
@Preview
@Composable
private fun ConstraintLayoutGuidlineSample() {
ConstraintLayout(
modifier = Modifier.fillMaxSize().border(2.dp, Color.Red)
) {
// Create guideline from the start of the parent at 10% the width of the Composable
val startGuideline = createGuidelineFromStart(0.4f)
// Create guideline from the end of the parent at 10% the width of the Composable
val endGuideline = createGuidelineFromEnd(0.1f)
// Create guideline from 16 dp from the top of the parent
val topGuideline = createGuidelineFromTop(16.dp)
// Create guideline from 16 dp from the bottom of the parent
val bottomGuideline = createGuidelineFromBottom(16.dp)
val button = createRef()
val text = createRef()
Button(
onClick = { /* Do something */ },
modifier = Modifier
.constrainAs(button) {
start.linkTo(startGuideline)
}
) {
Text("Button")
}
Text(
text = "Text",
modifier = Modifier
.background(Color.Yellow)
.constrainAs(text) {
start.linkTo(button.end, 10.dp)
}
)
}
}
@Preview
@Composable
fun ConstraintLayoutDemo() {
ConstraintLayout(modifier = Modifier.size(200.dp)) {
val (redBox, blueBox, yellowBox, text) = createRefs()
Box(modifier = Modifier
.size(50.dp)
.background(Color.Red)
.constrainAs(redBox) {})
Box(modifier = Modifier
.size(50.dp)
.background(Color.Blue)
.constrainAs(blueBox) {
top.linkTo(redBox.bottom)
start.linkTo(redBox.end)
})
Box(modifier = Modifier
.size(50.dp)
.background(Color.Yellow)
.constrainAs(yellowBox) {
bottom.linkTo(blueBox.bottom)
start.linkTo(blueBox.end, 20.dp)
}
)
Text("Hello World", modifier = Modifier
.constrainAs(text) {
top.linkTo(parent.top)
start.linkTo(yellowBox.start)
}
)
}
}
@Preview
@Composable
private fun ConstraintLayoutAnimationTest() {
/*
height = Dimension.value(10.dp)
width = Dimension.ratio("4:1") // The width will be 40dp
width = Dimension.wrapContent
height = Dimension.ratio("1:0.25") // The height will be a fourth of the resulting wrapContent width
*/
val buttonId = "Button"
val textId = "Text"
val constraintSet1 = remember {
ConstraintSet {
val button = createRefFor(buttonId)
val text = createRefFor(textId)
constrain(button) {
top.linkTo(parent.top)
}
constrain(text) {
top.linkTo(button.bottom)
}
}
}
val constraintSet2 = remember {
ConstraintSet {
val button = createRefFor(buttonId)
val text = createRefFor(textId)
constrain(button) {
top.linkTo(parent.top)
start.linkTo(parent.start)
}
constrain(text) {
// change width
width = Dimension.value(100.dp)
start.linkTo(button.end)
top.linkTo(parent.top)
}
}
}
var show by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier.fillMaxSize()
) {
ConstraintLayout(
modifier = Modifier.fillMaxWidth()
.background(Color.Yellow)
.animateContentSize()
.then(
if (show) Modifier.height(300.dp) else Modifier.height(150.dp)
),
constraintSet = if (show) constraintSet2 else constraintSet1,
animateChanges = true
) {
Button(
onClick = { /* Do something */ },
modifier = Modifier.layoutId(buttonId)
) {
Text("Button")
}
Text(
text = "Text", Modifier.layoutId(textId).background(Color.Red)
)
}
Button(
onClick = {
show = show.not()
}
) {
Text("Show $show")
}
}
} | 5 | null | 312 | 3,006 | efea98b63e63a85b80f7dc1bd4ca6d769e35905d | 6,719 | Jetpack-Compose-Tutorials | Apache License 2.0 |
src/main/kotlin/ru/krindra/vknorthtypes/base/BaseRequestParam.kt | kravandir | 745,597,090 | false | {"Kotlin": 633233} | package ru.krindra.vknorthtypes.base
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class BaseRequestParam (
@SerialName("key") val key: String,
@SerialName("value") val value: String,
)
| 0 | Kotlin | 0 | 0 | 508d2d1d59c4606a99af60b924c6509cfec6ef6c | 251 | VkNorthTypes | MIT License |
app/src/main/java/no/mhl/showroom/ui/MainActivity.kt | maxhvesser | 226,089,730 | false | {"Kotlin": 41079} | package no.mhl.showroom.ui
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import no.mhl.showroom.R
class MainActivity : AppCompatActivity() {
// region Initialisation
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
// endregion
} | 0 | Kotlin | 1 | 3 | 75e810f652ebaf4f9b4d0f316df6a70ca969f7f3 | 630 | showroom | Apache License 2.0 |
app/src/androidTest/java/com/steleot/jetpackcompose/playground/compose/foundation/RowScreenTest.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.compose.foundation
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.steleot.jetpackcompose.playground.MainActivity
import com.steleot.jetpackcompose.playground.compose.theme.TestTheme
import org.junit.Rule
import org.junit.Test
class RowScreenTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun testRowScreen() {
composeTestRule.setContent {
TestTheme {
RowScreen()
}
}
// todo
}
} | 0 | Kotlin | 16 | 161 | d853dddc7b00735dc9067f3325a2662977a01348 | 579 | Jetpack-Compose-Playground | Apache License 2.0 |
app/src/main/java/com/example/graphicdesign/logic/model/LogonResponse.kt | yi-sheep | 300,780,511 | false | null | package com.example.graphicdesign.logic.model
data class LogonResponse(val result:Boolean,val user:User)
data class User(val account:String,val password:String,val token:String) | 0 | Kotlin | 0 | 0 | 5f1eea36609d620b7dce02e0a87fdc3014b09e32 | 178 | GraphicDesign | Apache License 2.0 |
player/events/src/main/java/com/tidal/sdk/player/events/model/EndReason.kt | tidal-music | 806,866,286 | false | {"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911} | package com.tidal.sdk.player.events.model
import androidx.annotation.Keep
@Keep
enum class EndReason {
COMPLETE,
ERROR,
OTHER,
}
| 27 | Kotlin | 0 | 23 | 1f654552133ef7794fe9bb7677bc7fc94c713aa3 | 144 | tidal-sdk-android | Apache License 2.0 |
src/main/kotlin/com/dodo/fplbot/service/CronService.kt | dorukco | 487,645,111 | false | {"Kotlin": 36341, "Dockerfile": 191} | package com.dodo.fplbot.service
import mu.KLogging
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
@Service
class CronService(
private val contentService: ContentService
) {
companion object : KLogging()
@Scheduled(cron = "\${update.cron}")
fun scheduleFixedDelayTask() {
logger.info { "Event update is starting..." }
val updatedContent = contentService.getContent()
contentService.processMatchEvents(updatedContent)
contentService.updateEventContent(updatedContent)
}
} | 0 | Kotlin | 1 | 0 | 241189ad83fb8f431ac1329fe532008502d020ca | 586 | fpl-bot | Apache License 2.0 |
paging-retrofit-sample/app/src/main/java/com/star_zero/pagingretrofitsample/di/AppModule.kt | Youngfellows | 470,202,711 | false | {"Kotlin": 237191} | package com.star_zero.pagingretrofitsample.di
import com.star_zero.pagingretrofitsample.HttpLogger
import com.star_zero.pagingretrofitsample.api.GitHubAPI
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideApi(): GitHubAPI {
val okhttp = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor(HttpLogger()).apply {
setLevel(HttpLoggingInterceptor.Level.BASIC)
})
.build()
val retrofit = Retrofit.Builder()
.client(okhttp)
.baseUrl("https://api.github.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()
return retrofit.create(GitHubAPI::class.java)
}
}
| 0 | Kotlin | 0 | 0 | 046aff540194f6ebc5f97d92c9ba514eff1313d3 | 1,028 | UseCasePaging3.x | Apache License 2.0 |
core/network/src/main/java/ytemplate/android/core/network/di/ApiModule.kt | codeandtheory | 612,178,341 | false | {"Kotlin": 185287, "Shell": 2179} | package ytemplate.android.core.network.di
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import ytemplate.android.core.network.apis.PostApi
import ytemplate.android.core.network.apis.PostApiImpl
/**
* ApiModule, will bind the repository and data source instance based on the demand
*
* @constructor Create empty Api module
*/
@Module
@InstallIn(SingletonComponent::class)
interface ApiModule {
/**
* Bind post api
*
* @param postApi
* @return
*/
@Binds
fun bindPostApi(postApi: PostApiImpl): PostApi
}
| 11 | Kotlin | 3 | 22 | 8c7ebb298c16f9a72d6538b8ec0fb241a9fc7454 | 617 | ytemplate-android | Apache License 2.0 |
Lab3/src/main/kotlin/PageRank.kt | knu-3-velychko | 276,469,956 | false | null | class PageRank(val fName: String, val e: Double) {
var size = 0
val alpha = 0.75
val A: Matrix by lazy {
Matrix(fName)
}
val R: Matrix by lazy {
size = A.size
val array = Array(size) {
Array(size) { 1.0 / (size).toDouble() }
}
Matrix(array)
}
val M: Matrix by lazy {
alpha * A + (1 - alpha) * R
}
val result: Array<Double> by lazy {
var matrix = M
var prev = Array(size) { 1 / (size).toDouble() }
var x = matrix * prev
while (norm(x, prev) > e) {
prev = x
x = matrix * prev
}
x
}
val maxValue: Double? by lazy {
result.max()
}
val pos: Int? by lazy {
result.indexOf(maxValue)
}
private fun norm(v1: Array<Double>, v2: Array<Double>): Double {
var norm = 0.0
for (i in v1.indices)
norm += (v1[i] - v2[i]) * (v1[i] - v2[i])
return norm
}
} | 0 | Kotlin | 0 | 0 | 79eaf1bfc471495bd2155b3ec5d4f4aa539d8704 | 991 | NumericalMethods | MIT License |
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/InsetBoxShadowDrawable.kt | react-native-tvos | 177,633,560 | false | {"C++": 4398815, "Java": 2649623, "JavaScript": 2551815, "Objective-C++": 1803949, "Kotlin": 1628327, "Objective-C": 1421207, "Ruby": 453872, "CMake": 109113, "TypeScript": 85912, "Shell": 58251, "C": 57980, "Assembly": 14920, "HTML": 1473, "Swift": 739} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uimanager.drawable
import android.content.Context
import android.graphics.BlurMaskFilter
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.drawable.Drawable
import androidx.annotation.RequiresApi
import com.facebook.react.uimanager.FilterHelper
import com.facebook.react.uimanager.PixelUtil.dpToPx
import com.facebook.react.uimanager.PixelUtil.pxToDp
import com.facebook.react.uimanager.style.BorderInsets
import com.facebook.react.uimanager.style.BorderRadiusStyle
import com.facebook.react.uimanager.style.ComputedBorderRadius
import com.facebook.react.uimanager.style.CornerRadii
import kotlin.math.roundToInt
internal const val MIN_INSET_BOX_SHADOW_SDK_VERSION = 29
// "the resulting shadow must approximate {...} a Gaussian blur with a standard deviation equal
// to half the blur radius"
// https://www.w3.org/TR/css-backgrounds-3/#shadow-blur
private const val BLUR_RADIUS_SIGMA_SCALE = 0.5f
private val ZERO_RADII = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)
/** Draws an inner box-shadow https://www.w3.org/TR/css-backgrounds-3/#shadow-shape */
@RequiresApi(MIN_INSET_BOX_SHADOW_SDK_VERSION)
internal class InsetBoxShadowDrawable(
private val context: Context,
borderRadius: BorderRadiusStyle? = null,
borderInsets: BorderInsets? = null,
private val shadowColor: Int,
private val offsetX: Float,
private val offsetY: Float,
private val blurRadius: Float,
private val spread: Float,
) : Drawable() {
public var borderRadius = borderRadius
set(value) {
if (value != field) {
field = value
invalidateSelf()
}
}
public var borderInsets = borderInsets
set(value) {
if (value != field) {
field = value
invalidateSelf()
}
}
private val shadowPaint =
Paint().apply {
color = shadowColor
if (blurRadius > 0) {
maskFilter =
BlurMaskFilter(
FilterHelper.sigmaToRadius(blurRadius * BLUR_RADIUS_SIGMA_SCALE),
BlurMaskFilter.Blur.NORMAL)
}
}
override fun setAlpha(alpha: Int) {
shadowPaint.alpha = (((alpha / 255f) * (Color.alpha(shadowColor) / 255f)) * 255f).roundToInt()
invalidateSelf()
}
override fun setColorFilter(colorFilter: ColorFilter?) {
shadowPaint.colorFilter = colorFilter
invalidateSelf()
}
override fun getOpacity(): Int =
((shadowPaint.alpha / 255f) / (Color.alpha(shadowColor) / 255f) * 255f).roundToInt()
override fun draw(canvas: Canvas) {
val computedBorderRadii = computeBorderRadii()
val computedBorderInsets = computeBorderInsets()
val paddingBoxRect =
RectF(
bounds.left + (computedBorderInsets?.left ?: 0f),
bounds.top + (computedBorderInsets?.top ?: 0f),
bounds.right - (computedBorderInsets?.right ?: 0f),
bounds.bottom - (computedBorderInsets?.bottom ?: 0f))
val paddingBoxRadii =
computedBorderRadii?.let {
floatArrayOf(
innerRadius(it.topLeft.horizontal, computedBorderInsets?.left),
innerRadius(it.topLeft.vertical, computedBorderInsets?.top),
innerRadius(it.topRight.horizontal, computedBorderInsets?.right),
innerRadius(it.topRight.vertical, computedBorderInsets?.top),
innerRadius(it.bottomRight.horizontal, computedBorderInsets?.right),
innerRadius(it.bottomRight.vertical, computedBorderInsets?.bottom),
innerRadius(it.bottomLeft.horizontal, computedBorderInsets?.left),
innerRadius(it.bottomLeft.vertical, computedBorderInsets?.bottom))
}
val x = offsetX.dpToPx()
val y = offsetY.dpToPx()
val spreadExtent = spread.dpToPx()
val innerRect =
RectF(paddingBoxRect).apply {
inset(spreadExtent, spreadExtent)
offset(x, y)
}
// Graciously stolen from Blink
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/paint/box_painter_base.cc;l=338;drc=0a301506035e13015ea5c8dd39164d0d5954fa60
val blurExtent = FilterHelper.sigmaToRadius(blurRadius)
val outerRect =
RectF(innerRect).apply {
inset(-blurExtent, -blurExtent)
if (spreadExtent < 0) {
inset(spreadExtent, spreadExtent)
}
union(RectF(this).apply { offset(-x, -y) })
}
canvas.save().let { saveCount ->
if (paddingBoxRadii != null) {
canvas.clipPath(
Path().apply { addRoundRect(paddingBoxRect, paddingBoxRadii, Path.Direction.CW) })
val innerRadii =
paddingBoxRadii.map { adjustRadiusForSpread(it, -spreadExtent) }.toFloatArray()
canvas.drawDoubleRoundRect(outerRect, ZERO_RADII, innerRect, innerRadii, shadowPaint)
} else {
canvas.clipRect(paddingBoxRect)
canvas.drawDoubleRoundRect(outerRect, ZERO_RADII, innerRect, ZERO_RADII, shadowPaint)
}
canvas.restoreToCount(saveCount)
}
}
private fun computeBorderRadii(): ComputedBorderRadius? {
val resolvedBorderRadii =
borderRadius?.resolve(
layoutDirection,
context,
bounds.width().toFloat().pxToDp(),
bounds.height().toFloat().pxToDp())
return if (resolvedBorderRadii?.hasRoundedBorders() == true) {
ComputedBorderRadius(
topLeft =
CornerRadii(
resolvedBorderRadii.topLeft.horizontal.dpToPx(),
resolvedBorderRadii.topLeft.vertical.dpToPx()),
topRight =
CornerRadii(
resolvedBorderRadii.topRight.horizontal.dpToPx(),
resolvedBorderRadii.topRight.vertical.dpToPx()),
bottomLeft =
CornerRadii(
resolvedBorderRadii.bottomLeft.horizontal.dpToPx(),
resolvedBorderRadii.bottomLeft.vertical.dpToPx()),
bottomRight =
CornerRadii(
resolvedBorderRadii.bottomRight.horizontal.dpToPx(),
resolvedBorderRadii.bottomRight.vertical.dpToPx()),
)
} else {
null
}
}
private fun computeBorderInsets(): RectF? =
borderInsets?.resolve(layoutDirection, context)?.let {
RectF(it.left.dpToPx(), it.top.dpToPx(), it.right.dpToPx(), it.bottom.dpToPx())
}
private fun innerRadius(radius: Float, borderInset: Float?): Float =
(radius - (borderInset ?: 0f)).coerceAtLeast(0f)
}
| 7 | C++ | 147 | 942 | 692bc66a98c8928c950bece9a22d04c13f0c579d | 6,865 | react-native-tvos | MIT License |
src/main/kotlin/com/fobgochod/endpoints/action/http/ResetDataAction.kt | fobgochod | 686,046,719 | false | {"Kotlin": 125996, "Java": 113739} | package com.fobgochod.endpoints.action.http
import com.fobgochod.endpoints.action.EndpointsAction
import com.fobgochod.endpoints.framework.PsiFileUtils
import com.fobgochod.endpoints.util.EndpointsBundle
import com.fobgochod.endpoints.view.EndpointsManager
import com.fobgochod.endpoints.view.tree.node.EndpointNode
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
class ResetDataAction : EndpointsAction() {
init {
templatePresentation.icon = AllIcons.General.Reset
templatePresentation.text = EndpointsBundle.message("action.http.test.reset.data.text")
}
override fun actionPerformed(e: AnActionEvent, project: Project) {
val selectPath = PsiFileUtils.getSelectedPath(project)
if (selectPath is EndpointNode) {
selectPath.source.reset(true)
val view = EndpointsManager.getView(project)
view.testPanel.reset(selectPath.source)
}
}
}
| 0 | Kotlin | 0 | 0 | 7a1e2f84bc2f21ec42d009be0f6981782557fe08 | 1,015 | endpoints | Apache License 2.0 |
app/src/main/java/com/example/if1001/ui/MapsActivity.kt | irscin | 358,382,160 | false | null | package com.example.if1001.ui
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.example.if1001.R
import com.example.if1001.firebase.FirebaseManager
import com.example.if1001.models.RestaurantModel
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.FirebaseApp
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
companion object {
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
}
private lateinit var mMap: GoogleMap
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var userLocation: Location
private lateinit var databaseReference: DatabaseReference
private lateinit var firebaseManager : FirebaseManager
private lateinit var restaurants : ArrayList<RestaurantModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
databaseReference = FirebaseDatabase.getInstance().reference
firebaseManager = FirebaseManager()
restaurants = firebaseManager.loadDatabase()
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.uiSettings.isZoomControlsEnabled = true
mMap.setOnMarkerClickListener(this)
setUpMap()
for(restaurant in restaurants) {
val restaurantLatLng = LatLng(
restaurant.coords["lat"]!!.toDouble(),
restaurant.coords["long"]!!.toDouble()
)
val t = placeMarker(restaurantLatLng, restaurants.indexOf(restaurant))
Log.d("1", t.toString())
}
}
override fun onMarkerClick(marker: Marker?): Boolean {
launchRestaurantActivity(marker)
return false
}
private fun launchRestaurantActivity(marker: Marker?) {
val restaurantIdx = marker!!.tag.toString().toInt()
val intent = Intent(this, RestaurantActivity::class.java)
intent.putExtra("restaurantName", restaurants[restaurantIdx].name)
intent.putExtra("restaurantAddress", restaurants[restaurantIdx].address)
intent.putExtra("restaurantMenu", restaurants[restaurantIdx].menu)
intent.putExtra("restaurantAbout", restaurants[restaurantIdx].about)
var total=0.0;
var average: Double=0.0;
var numberOfItems=1;
for(i in restaurants[restaurantIdx].rating){
total+=i.rating
average = total/numberOfItems;
numberOfItems++;
}
intent.putExtra("restaurantRating", average)
val bundle = Bundle()
intent.putExtras(bundle)
startActivity(intent)
}
private fun setUpMap() {
if(ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST_CODE
)
return
}
mMap.isMyLocationEnabled = true
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if(location != null) {
userLocation = location
val currentLatLng = LatLng(userLocation.latitude, userLocation.longitude)
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 17.0f))
}
else {
displayToast("Zoom your map to see restaurants")
}
}
}
private fun displayToast(message: String) {
val duration = Toast.LENGTH_LONG
val toast = Toast.makeText(applicationContext, message, duration)
toast.show()
}
private fun placeMarker(location: LatLng, tag: Int) {
val markerOption = MarkerOptions().position(location)
val addressText = getAddress(location)
markerOption.title(addressText)
val marker = mMap.addMarker(markerOption)
marker.tag = tag
}
private fun getAddress(latLng: LatLng): String {
val geocoder = Geocoder(this)
val addresses: List<Address>?
val address: Address?
var addressText = ""
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
if(addresses != null && addresses.isNotEmpty()) {
address = addresses[0]
for(i in 0 until address.maxAddressLineIndex + 1) {
addressText += if (i == 0) address.getAddressLine(i) else "\n" + address.getAddressLine(
i
)
}
}
} catch (e: Exception) {
Log.e("MapsActivity", e.localizedMessage)
}
return addressText
}
} | 0 | Kotlin | 0 | 0 | 416d8b19603f1e8ed0651b76bfa7d1b7cb82a565 | 6,152 | if1001 | MIT License |
TheCocktailDB/app/src/main/java/com/example/thecocktaildb/viewmodel/ViewModel.kt | acasadoquijada | 286,512,663 | false | null | package com.example.thecocktaildb.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.thecocktaildb.R
import com.example.thecocktaildb.model.drink.Drink
import com.example.thecocktaildb.repository.Repository
class ViewModel(application: Application) : AndroidViewModel(application) {
private var repository: Repository = Repository()
private val categoryList: MutableList<String> = ArrayList()
var query: String = ""
init{
val context = getApplication<Application>().applicationContext
categoryList.add(context.getString(R.string.category_alcohol))
categoryList.add(context.getString(R.string.category_no_alcohol))
categoryList.add(context.getString(R.string.category_ordinary_drink))
categoryList.add(context.getString(R.string.category_cocktail))
categoryList.add(context.getString(R.string.category_cocktail_glass))
categoryList.add(context.getString(R.string.category_champagne_flute))
}
fun getDrinkList(query: String): MutableLiveData<List<Drink>>{
return repository.getDrinkList(query)
}
fun getDrinkListSize(): Int{
return repository.getDrinkListSize()
}
fun getDrink(drinkId: Long = -1L): MutableLiveData<Drink>{
return repository.getDrink(drinkId)
}
fun getDrinkId(position: Int): Long{
return repository.getDrinkId(position)
}
fun updateRandomDrink(){
repository.updateRandomDrink()
}
fun getCategories(): List<String>{
return categoryList
}
fun getCategoryName(position: Int): String{
return categoryList[position]
}
} | 0 | Kotlin | 0 | 0 | f452a01727463d8a1087f0429b679631e0e8cb9b | 1,729 | TheCocktailDB | MIT License |
api/src/main/kotlin/dev/akif/crud/simpler/SimplerModel.kt | makiftutuncu | 588,961,629 | false | {"Kotlin": 102236} | package dev.akif.crud.simpler
import dev.akif.crud.*
import java.io.Serializable
/**
* Simpler variant of [CRUDModel] which is also a [CRUDCreateModel],
* a [CRUDUpdateModel], a [CRUDDTO], a [CRUDCreateDTO] and a [CRUDUpdateDTO]
*
* @param I Id type of the data
*/
interface SimplerModel<out I : Serializable> : CRUDModel<I>, CRUDCreateModel, CRUDUpdateModel, CRUDDTO<I>,
CRUDCreateDTO, CRUDUpdateDTO
| 15 | Kotlin | 1 | 8 | 463739c3d30c337aac4b2d9fff02701021c334c0 | 412 | spring-boot-crud | MIT License |
android/testSrc/com/android/tools/idea/lang/aidl/AidlFindUsageTest.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.tools.idea.lang.aidl
import com.android.tools.idea.lang.aidl.psi.AidlParcelableDeclaration
import com.google.common.truth.Truth.assertThat
import com.intellij.psi.PsiReferenceExpression
import org.jetbrains.android.AndroidTestCase
class AidlFindUsageTest : AndroidTestCase() {
override fun setUp() {
super.setUp()
myFixture.addFileToProject(
"src/Interface.java",
//language=Java
"""// This is the skeleton of generated file of Interface AIDL file.
public interface Interface {
public static abstract class Stub implements Interface {
public Stub() {
}
private static class Proxy implements Interface {
@Override
public void foo(int a) {
}
}
}
void foo(int a);
}
""".trimIndent())
myFixture.addFileToProject(
"src/Main.java",
//language=Java
"""
class Main {
static void main(String []args) {
Interface i = new Interface.Proxy();
i.foo(1);
}
}
""".trimIndent())
}
fun testFindMethodUsage() {
myFixture.configureByText(
"file.aidl",
"""interface Interface {
void fo<caret>o(int a);
}""")
val elementAtCaret = myFixture.elementAtCaret
val foundElements = myFixture.findUsages(elementAtCaret)
assertThat(foundElements).hasSize(1)
val element = foundElements.first().element!!
assertThat(element).isInstanceOf(PsiReferenceExpression::class.java)
assertThat(element.containingFile.name).isEqualTo("Main.java")
}
fun testFindInterfaceUsage() {
myFixture.configureByText(
"file.aidl",
"""interface Inter<caret>face {
void foo(int a);
}""")
val elementAtCaret = myFixture.elementAtCaret
val foundElements = myFixture.findUsages(elementAtCaret)
assertThat(foundElements).isNotNull()
val counts = foundElements.groupingBy { it.element?.containingFile!!.name }.eachCount()
assertThat(counts["Interface.java"]).isEqualTo(2)
assertThat(counts["Main.java"]).isEqualTo(2)
}
fun testParcelableUsage() {
val file = myFixture.addFileToProject(
"src/Rect.java",
//language=Java
"""
class Rect extends Parcelable {}
""".trimIndent())
myFixture.configureByText("file.aidl",
"""parcelable Rec<caret>t;""")
val elementAtCaret = myFixture.elementAtCaret.parent
assertThat(elementAtCaret).isInstanceOf(AidlParcelableDeclaration::class.java)
assertThat((elementAtCaret as AidlParcelableDeclaration).generatedPsiElement!!.containingFile).isEqualTo(file)
}
}
| 0 | Java | 187 | 751 | 16d17317f2c44ec46e8cd2180faf9c349d381a06 | 3,353 | android | Apache License 2.0 |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/community/chat/SetChatEmojiCollectionReq.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 679531} | package org.anime_game_servers.multi_proto.gi.data.community.chat
import org.anime_game_servers.core.base.Version.GI_2_1_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
@AddedIn(GI_2_1_0)
@ProtoCommand(REQUEST)
internal interface SetChatEmojiCollectionReq {
var chatEmojiCollectionData: ChatEmojiCollectionData
}
| 1 | Kotlin | 3 | 6 | b342ff34dfb0f168a902498b53682c315c40d44e | 476 | anime-game-multi-proto | MIT License |
example/android/app/src/main/kotlin/com/example/singel_page_route_example/MainActivity.kt | AndreeJait | 462,204,385 | false | {"Dart": 9823, "Kotlin": 1496, "Swift": 936, "Ruby": 860, "Objective-C": 750} | package com.example.singel_page_route_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 82950ba4aceae0062ab180e42aa5431e997a6196 | 142 | singel_page_route | Apache License 2.0 |
app/src/main/java/com/finnmglas/launcher/UIObject.kt | finnmglas | 263,334,528 | false | null | package com.finnmglas.launcher
import android.app.Activity
import android.view.WindowManager
/**
* An interface implemented by every [Activity], Fragment etc. in Launcher.
* It handles themes and window flags - a useful abstraction as it is the same everywhere.
*/
interface UIObject {
fun onStart() {
if (this is Activity) setWindowFlags(window)
applyTheme()
setOnClicks()
adjustLayout()
}
// Don't use actual themes, rather create them on the fly for faster theme-switching
fun applyTheme() { }
fun setOnClicks() { }
fun adjustLayout() { }
} | 28 | Kotlin | 26 | 91 | 340ee7315293b028c060638e058516435bca296a | 606 | Launcher | MIT License |
app/src/main/java/com/finnmglas/launcher/UIObject.kt | finnmglas | 263,334,528 | false | null | package com.finnmglas.launcher
import android.app.Activity
import android.view.WindowManager
/**
* An interface implemented by every [Activity], Fragment etc. in Launcher.
* It handles themes and window flags - a useful abstraction as it is the same everywhere.
*/
interface UIObject {
fun onStart() {
if (this is Activity) setWindowFlags(window)
applyTheme()
setOnClicks()
adjustLayout()
}
// Don't use actual themes, rather create them on the fly for faster theme-switching
fun applyTheme() { }
fun setOnClicks() { }
fun adjustLayout() { }
} | 28 | Kotlin | 26 | 91 | 340ee7315293b028c060638e058516435bca296a | 606 | Launcher | MIT License |
ktorm-core/src/main/kotlin/me/liuwj/ktorm/schema/Column.kt | yinhe | 199,580,160 | false | null | /*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.liuwj.ktorm.schema
import me.liuwj.ktorm.expression.ArgumentExpression
import me.liuwj.ktorm.expression.ColumnDeclaringExpression
import me.liuwj.ktorm.expression.ColumnExpression
import me.liuwj.ktorm.expression.ScalarExpression
import kotlin.reflect.KProperty1
/**
* Base class of column bindings. A column might be bound to a simple property, nested properties,
* or a reference to another table.
*/
sealed class ColumnBinding
/**
* Bind the column to nested properties, eg. `employee.manager.department.id`.
*
* @property properties the nested properties, cannot be empty.
*/
data class NestedBinding(val properties: List<KProperty1<*, *>>) : ColumnBinding()
/**
* Bind the column to a reference table, equivalent to a foreign key in relational databases.
* Entity finding functions would automatically left join all references (recursively) by default.
*
* @property referenceTable the reference table.
* @property onProperty the property used to hold the referenced entity object.
* @see me.liuwj.ktorm.entity.joinReferencesAndSelect
* @see me.liuwj.ktorm.entity.createEntity
*/
data class ReferenceBinding(val referenceTable: Table<*>, val onProperty: KProperty1<*, *>) : ColumnBinding()
/**
* Common interface of [Column] and [ScalarExpression].
*/
interface ColumnDeclaring<T : Any> {
/**
* The [SqlType] of this column or expression.
*/
val sqlType: SqlType<T>
/**
* Convert this instance to a [ScalarExpression].
*
* If this instance is a [Column], return a [ColumnExpression], otherwise if it's already a [ScalarExpression],
* return `this` directly.
*/
fun asExpression(): ScalarExpression<T>
/**
* Wrap this instance as a [ColumnDeclaringExpression].
*
* This function is useful when we use columns or expressions as the selected columns in a query. If this instance
* is a [Column], a label identifying the selected columns will be set to [ColumnDeclaringExpression.declaredName],
* otherwise if it's a [ScalarExpression], the property will be set to null.
*/
fun asDeclaringExpression(): ColumnDeclaringExpression
/**
* Wrap the given [argument] as an [ArgumentExpression] using the [sqlType].
*/
fun wrapArgument(argument: T?): ArgumentExpression<T>
}
/**
* Represents database columns.
*/
sealed class Column<T : Any> : ColumnDeclaring<T> {
/**
* The [Table] that this column belongs to.
*/
abstract val table: Table<*>
/**
* The column's name.
*/
abstract val name: String
/**
* The column's label, used to identify the selected columns and obtain query results.
*
* For example, `select a.name as label from dual`, in which `a.name as label` is a column declaring, and `label`
* is the label.
*
* @see ColumnDeclaringExpression
*/
abstract val label: String
/**
* The column's binding. A column might be bound to a simple property, nested properties,
* or a reference to another table, null if the column doesn't bind to any property.
*/
abstract val binding: ColumnBinding?
/**
* If the column was bound to a reference table, return the table, otherwise return null.
*
* Shortcut for `(binding as? ReferenceBinding)?.referenceTable`.
*/
val referenceTable: Table<*>? get() = (binding as? ReferenceBinding)?.referenceTable
/**
* Convert this column to a [ColumnExpression].
*/
override fun asExpression(): ColumnExpression<T> {
return ColumnExpression(table.alias ?: table.tableName, name, sqlType)
}
/**
* Wrap this column as a [ColumnDeclaringExpression].
*/
override fun asDeclaringExpression(): ColumnDeclaringExpression {
return ColumnDeclaringExpression(expression = asExpression(), declaredName = label)
}
/**
* Wrap the given [argument] as an [ArgumentExpression] using the [sqlType].
*/
override fun wrapArgument(argument: T?): ArgumentExpression<T> {
return ArgumentExpression(argument, sqlType)
}
/**
* Return a string representation of this column.
*/
override fun toString(): String {
return "${table.alias ?: table.tableName}.$name"
}
/**
* Indicates whether some other object is "equal to" this column.
* Two columns are equal only if they are the same instance.
*/
final override fun equals(other: Any?): Boolean {
return this === other
}
/**
* Return a hash code value for this column.
*/
final override fun hashCode(): Int {
return System.identityHashCode(this)
}
}
/**
* Simple implementation of [Column].
*/
data class SimpleColumn<T : Any>(
override val table: Table<*>,
override val name: String,
override val sqlType: SqlType<T>,
override val binding: ColumnBinding? = null
) : Column<T>() {
override val label: String = "${table.alias ?: table.tableName}_$name"
override fun toString(): String {
return "${table.alias ?: table.tableName}.$name"
}
}
/**
* Aliased column, wrapping a [SimpleColumn] and an extra [alias] to modify the lable, designed to bind a column to
* multiple bindings.
*
* Ktorm provides an `aliased` function to create a copy of an existing column with a specific alias, then we can bind
* this new-created column to any property we want, and the origin column's binding is not influenced, that’s the way
* Ktorm supports multiple bindings on a column.
*
* The generated SQL is like: `select name as label, name as label1 from dual`.
*
* Note that aliased bindings are only available for queries, they will be ignored when inserting or updating entities.
*
* @property originColumn the origin column.
* @property alias the alias used to modify the origin column's label.
*/
data class AliasedColumn<T : Any>(
val originColumn: SimpleColumn<T>,
val alias: String,
override val binding: ColumnBinding? = null
) : Column<T>() {
override val table: Table<*> = originColumn.table
override val name: String = originColumn.name
override val label: String = "${table.alias ?: table.tableName}_$alias"
override val sqlType: SqlType<T> = originColumn.sqlType
override fun toString(): String {
return "$originColumn as $alias"
}
}
| 0 | null | 0 | 1 | da4386ae7199952f682c21d1f2b11ba5d9b559e1 | 6,985 | Ktorm | Apache License 2.0 |
parser/src/main/kotlin/org/ksharp/parser/ksharp/IndentationOffset.kt | ksharp-lang | 573,931,056 | false | {"Kotlin": 1332972, "Java": 27644, "TypeScript": 3266} | package org.ksharp.parser.ksharp
import org.ksharp.common.Either
import org.ksharp.parser.*
import java.util.*
interface Offset {
val size: Int
val fixed: Boolean
val type: OffsetType
}
private data class OffsetImpl(override var size: Int, override var fixed: Boolean, override var type: OffsetType) :
Offset
enum class OffsetAction {
Invalid,
Same,
Repeating,
Previous,
End
}
enum class OffsetType(val action: OffsetAction) {
Normal(OffsetAction.Previous),
Optional(OffsetAction.Same),
Repeating(OffsetAction.Repeating)
}
private val EmptyOffset = OffsetImpl(0, true, OffsetType.Optional)
class IndentationOffset {
private val offsets = Stack<OffsetImpl>()
val currentOffset: Offset get() = if (offsets.isEmpty()) EmptyOffset else offsets.peek()
private fun update(size: Int, sameResult: OffsetAction): OffsetAction {
if (offsets.isEmpty()) {
return OffsetAction.End
}
val last = offsets.peek()
if (last.size > size) {
return update(size, offsets.pop().type.action)
}
if (last.size < size) {
if (last.fixed) return OffsetAction.Invalid
last.size = size
last.fixed = true
if (last.type == OffsetType.Optional)
last.type = OffsetType.Normal
}
return if (last.type == OffsetType.Repeating) {
OffsetAction.Repeating
} else sameResult
}
fun add(size: Int, type: OffsetType): Boolean {
val (allowed, calculatedSize) = if (offsets.isEmpty()) true to size
else if (offsets.peek().size <= size) {
val last = offsets.peek()
// avoid ambiguity
if (last.type == OffsetType.Repeating && last.size == size) {
true to (size + 1)
} else true to size
} else (false to 0)
if (allowed) {
offsets.push(OffsetImpl(calculatedSize, false, type))
}
return allowed
}
fun addRelative(type: OffsetType) {
val position = if (offsets.isEmpty()) 0 else {
offsets.peek().size + 1
}
offsets.push(OffsetImpl(position, false, type))
}
fun update(size: Int) = update(size, OffsetAction.Same)
fun remove(offset: Offset) {
if (offsets.isNotEmpty() && offsets.peek() === offset) {
offsets.pop()
}
}
}
enum class IndentationOffsetType {
StartOffset,
EndOffset,
Relative,
NextToken
}
private fun KSharpLexerIterator.addIndentationOffset(
indentationType: IndentationOffsetType,
type: OffsetType,
): KSharpLexerIterator {
val lexerState = state.value
val indentationOffset = lexerState.indentationOffset
when (indentationType) {
IndentationOffsetType.StartOffset -> indentationOffset.add(
lexerState.lineOffset.size(lastStartOffset),
type
)
IndentationOffsetType.EndOffset -> indentationOffset.add(lexerState.lineOffset.size(lastEndOffset), type)
IndentationOffsetType.Relative -> indentationOffset.addRelative(type)
IndentationOffsetType.NextToken -> {
val lookAHeadCheckPoint = state.lookAHeadState.checkpoint()
if (hasNext()) {
val t = next()
if (t.type == BaseTokenType.NewLine) {
indentationOffset.addRelative(type)
} else
indentationOffset.add(
lexerState.lineOffset.size(t.startOffset),
type
)
}
lookAHeadCheckPoint.end(PreserveTokens)
}
}
return this
}
private fun Token.sameAsOffset(offset: Offset) =
type == BaseTokenType.NewLine && text.indentLength() == offset.size
private fun <T> T.discardOffset(lexer: KSharpLexerIterator, offset: Offset): T {
val lookAhead = lexer.state.lookAHeadState.checkpoint()
lexer.state.value.indentationOffset.remove(offset)
if (lexer.hasNext()) {
val token = lexer.next()
val action = if (token.sameAsOffset(offset)) {
ConsumeTokens
} else PreserveTokens
lookAhead.end(action)
}
return this
}
fun KSharpConsumeResult.addIndentationOffset(
indentationType: IndentationOffsetType,
type: OffsetType
): KSharpConsumeResult =
map {
it.tokens.addIndentationOffset(indentationType, type)
it
}
private val Token.newLineStartOffset: Int
get() =
startOffset + (if (text.startsWith("\r\n")) 2 else 1)
fun KSharpLexerIterator.enableIndentationOffset(): KSharpLexerIterator {
val lexerState = state.value
val indentationOffset = lexerState.indentationOffset
return generateLexerIterator(state) {
while (hasNext()) {
val token = next()
if (token.type == BaseTokenType.NewLine) {
val indentLength = token.text.indentLength()
lexerState.lineOffset.add(token.newLineStartOffset)
val result = indentationOffset.update(indentLength)
if (result == OffsetAction.Same && indentLength != 0) continue
}
return@generateLexerIterator token
}
null
}
}
fun KSharpConsumeResult.thenRepeatingIndentation(
requireAlwaysNewLine: Boolean,
block: (KSharpConsumeResult) -> KSharpParserResult
): KSharpConsumeResult =
flatMap {
val lexer = it.tokens.addIndentationOffset(IndentationOffsetType.Relative, OffsetType.Repeating)
val indentationOffset = lexer.state.value.indentationOffset
val offset = indentationOffset.currentOffset
val tokenPredicate: (Token) -> Boolean = { tk ->
tk.type == BaseTokenType.NewLine && indentationOffset.currentOffset == offset
}
Either.Right(it)
.thenLoopIndexed { l, index ->
if (index != 0 || requireAlwaysNewLine) {
l.consume(tokenPredicate, true)
.let(block)
} else
l.ifConsume(tokenPredicate, true, block).or {
block(l.collect())
}
}.discardOffset(lexer, offset)
}
fun KSharpConsumeResult.withAlignedIndentationOffset(
indentationType: IndentationOffsetType,
block: (KSharpConsumeResult) -> KSharpConsumeResult
): KSharpConsumeResult =
flatMap {
val lexer = it.tokens.addIndentationOffset(indentationType, OffsetType.Normal)
val indentationOffset = lexer.state.value.indentationOffset
val offset = indentationOffset.currentOffset
val tokenPredicate: (Token) -> Boolean = { tk ->
tk.type == BaseTokenType.NewLine && indentationOffset.currentOffset == offset
}
block(Either.Right(it))
.thenOptional(tokenPredicate, true)
.discardOffset(lexer, offset)
}
fun <T> KSharpLexerIterator.withNextTokenIndentationOffset(
type: OffsetType,
block: (KSharpLexerIterator) -> T
): T {
val lexerState = state.value
val indentationOffset = lexerState.indentationOffset
addIndentationOffset(IndentationOffsetType.NextToken, type)
val currentOffset = indentationOffset.currentOffset
return block(this).discardOffset(this, currentOffset)
}
fun <T> KSharpLexerIterator.withIndentationOffset(
indentationType: IndentationOffsetType,
type: OffsetType,
block: (KSharpLexerIterator) -> T
): T {
val indentationOffset = state.value.indentationOffset
addIndentationOffset(indentationType, type)
val currentOffset = indentationOffset.currentOffset
return block(this).discardOffset(this, currentOffset)
}
fun KSharpConsumeResult.thenWithIndentationOffset(
indentationType: IndentationOffsetType,
type: OffsetType,
block: (KSharpConsumeResult) -> KSharpConsumeResult
): KSharpConsumeResult = flatMap {
it.tokens.withIndentationOffset(indentationType, type) { _ ->
block(Either.Right(it))
}
}
| 3 | Kotlin | 0 | 0 | 5105a9253c2550cd59c8458e73e44cde5e03162b | 8,055 | ksharp-kt | Apache License 2.0 |
core/src/commonTest/kotlin/maryk/core/query/changes/ListChangeTest.kt | marykdb | 290,454,412 | false | {"Kotlin": 3277548, "JavaScript": 1004} | package maryk.core.query.changes
import kotlinx.datetime.LocalDateTime
import maryk.checkJsonConversion
import maryk.checkProtoBufConversion
import maryk.checkYamlConversion
import maryk.core.extensions.toUnitLambda
import maryk.core.query.RequestContext
import maryk.core.values.div
import maryk.test.models.EmbeddedMarykModel
import maryk.test.models.TestMarykModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.expect
class ListChangeTest {
private val listPropertyChange = ListChange(
TestMarykModel { listOfString::ref }.change(
addValuesAtIndex = mapOf(2u to "a", 3u to "abc"),
addValuesToEnd = listOf("four", "five"),
deleteValues = listOf("three")
)
)
private val context = RequestContext(
mapOf(
TestMarykModel.name toUnitLambda { TestMarykModel }
),
dataModel = TestMarykModel
)
@Test
fun convertToProtoBufAndBack() {
checkProtoBufConversion(this.listPropertyChange, ListChange, { this.context })
}
@Test
fun convertToJSONAndBack() {
checkJsonConversion(this.listPropertyChange, ListChange, { this.context })
}
@Test
fun convertToYAMLAndBack() {
expect(
"""
listOfString:
addValuesToEnd: [four, five]
addValuesAtIndex:
2: a
3: abc
deleteValues: [three]
""".trimIndent()
) {
checkYamlConversion(this.listPropertyChange, ListChange, { this.context })
}
}
@Test
fun changeValuesTest() {
val original = TestMarykModel(
string = "<NAME>",
int = 5,
uint = 3u,
double = 2.3,
dateTime = LocalDateTime(2018, 7, 18, 0, 0),
list = listOf(3, 4, 5),
embeddedValues = EmbeddedMarykModel(
value = "test",
marykModel = TestMarykModel(
string = "<NAME>",
int = 3,
uint = 67u,
double = 232523.3,
dateTime = LocalDateTime(2020, 10, 18, 0, 0),
list = listOf(33, 44, 55)
)
)
)
val changed = original.change(
ListChange(
TestMarykModel { list::ref }.change(
deleteValues = listOf(3),
addValuesAtIndex = mapOf(
1u to 999
),
addValuesToEnd = listOf(8)
)
)
)
assertEquals(listOf(4, 999, 5, 8), changed { list })
assertEquals(listOf(3, 4, 5), original { list })
val deepChanged = original.change(
ListChange(
TestMarykModel { embeddedValues { marykModel { list::ref } } }.change(
deleteValues = listOf(33),
addValuesAtIndex = mapOf(
1u to 9999
),
addValuesToEnd = listOf(88)
)
)
)
assertEquals(listOf(44, 9999, 55, 88), deepChanged { embeddedValues } / { marykModel } / { list })
assertEquals(listOf(33, 44, 55), original { embeddedValues } / { marykModel } / { list })
}
}
| 1 | Kotlin | 1 | 8 | 530e0b7f41cc16920b69b7c8adf7b5718733ce2f | 3,377 | maryk | Apache License 2.0 |
app/src/main/java/com/example/suzimap/MainActivity.kt | suzisuzisuzi | 759,155,553 | false | {"Kotlin": 10761} | package com.example.suzimap
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.DialogFragment
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.maps.android.heatmaps.HeatmapTileProvider
import com.google.maps.android.heatmaps.WeightedLatLng
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
class MainActivity : AppCompatActivity(), OnMapReadyCallback {
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
private lateinit var mMap: GoogleMap
private lateinit var heatmapTileProvider: HeatmapTileProvider
private lateinit var mapView: com.google.android.gms.maps.MapView // Initialize mapView here
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
mapView = findViewById(R.id.mapView) // Correctly initialize mapView
mapView.onCreate(savedInstanceState) // Important to call this
mapView.getMapAsync(this)
val changeMapType: ImageButton = findViewById(R.id.btnChangeMapType)
var currentMapType = GoogleMap.MAP_TYPE_NORMAL
changeMapType.setOnClickListener {
currentMapType = when (currentMapType) {
GoogleMap.MAP_TYPE_NORMAL -> GoogleMap.MAP_TYPE_SATELLITE
GoogleMap.MAP_TYPE_SATELLITE -> GoogleMap.MAP_TYPE_TERRAIN
GoogleMap.MAP_TYPE_TERRAIN -> GoogleMap.MAP_TYPE_HYBRID
GoogleMap.MAP_TYPE_HYBRID -> GoogleMap.MAP_TYPE_NORMAL
else -> GoogleMap.MAP_TYPE_NORMAL
}
mMap.mapType = currentMapType
}
}
// Implement lifecycle methods
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
mapView.onPause()
super.onPause()
}
override fun onStop() {
mapView.onStop()
super.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
mapView.onDestroy()
super.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onMapReady(googleMap: GoogleMap) {
mMap=googleMap
mMap.mapType = GoogleMap.MAP_TYPE_SATELLITE
with(mMap.uiSettings) {
isZoomControlsEnabled = true
isCompassEnabled = true
isMyLocationButtonEnabled = true
isMapToolbarEnabled = true
isScrollGesturesEnabled = true
isZoomGesturesEnabled = true
isTiltGesturesEnabled = true
isRotateGesturesEnabled = true
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= android.content.pm.PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1)
return
}
mMap.isMyLocationEnabled = true
// example of adding a marker with an info window
mMap.addMarker(
MarkerOptions()
.position(LatLng(19.0, 73.0))
.title("Hot Women")
.snippet("Test Category for SUZI development"))
val defaultLocation = LatLng(19.0, 73.0)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 8f))
addHeatmap()
}
private fun addHeatmap() {
CoroutineScope(ioDispatcher).launch {
try {
val geoJsonData = fetchGeoJsonData("https://suzi-backend.onrender.com/gheatmap/test")
val list = parseGeoJsonData(geoJsonData)
withContext(Dispatchers.Main) {
heatmapTileProvider = HeatmapTileProvider.Builder()
.weightedData(list)
.radius(50)
.opacity(1.0)
.build()
mMap.addTileOverlay(com.google.android.gms.maps.model.TileOverlayOptions().tileProvider(heatmapTileProvider))
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(this@MainActivity, "Network timeout, please try again.", Toast.LENGTH_LONG).show()
}
}
}
}
private suspend fun fetchGeoJsonData(url: String): String = withContext(ioDispatcher) {
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
val response = client.newCall(request).execute()
return@withContext response.body?.string() ?: ""
}
private fun parseGeoJsonData(data: String): List<WeightedLatLng> {
val list = ArrayList<WeightedLatLng>()
val jsonArray = JSONArray(data)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val lat = jsonObject.getDouble("latitude")
val lng = jsonObject.getDouble("longitude")
val rating = jsonObject.getDouble("rating")
list.add(WeightedLatLng(LatLng(lat, lng), rating))
}
return list
}
}
| 0 | Kotlin | 0 | 0 | efdf76f315920436d91629b35dab5f6e78313b60 | 6,294 | SUZI-android | MIT License |
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/ui/adapter/BaseRecyclerViewAdapter.kt | yasin1376 | 275,321,087 | true | {"Kotlin": 83192, "Java": 23693} | /*
* Copyright (c) 2020 <NAME>.
* All rights reserved.
*/
package com.nguyenhoanglam.imagepicker.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
abstract class BaseRecyclerViewAdapter<T : RecyclerView.ViewHolder?>(val context: Context) : RecyclerView.Adapter<T>() {
val inflater: LayoutInflater = LayoutInflater.from(context)
} | 0 | null | 0 | 1 | e9321b5988ad93659bf756c65afadc7b2daea4cf | 415 | ImagePicker | Apache License 2.0 |
src/test/kotlin/de/niemeyer/aoc/direction/CompassDirectionScreenTest.kt | stefanniemeyer | 572,897,543 | false | null | package de.niemeyer.aoc.direction
import de.niemeyer.aoc.points.Point2D
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@Nested
@DisplayName("CompassDirectionScreen")
class CompassDirectionScreenTest {
val directions = listOf(
CompassDirectionScreen.North,
CompassDirectionScreen.NorthEast,
CompassDirectionScreen.East,
CompassDirectionScreen.SouthEast,
CompassDirectionScreen.South,
CompassDirectionScreen.SouthWest,
CompassDirectionScreen.West,
CompassDirectionScreen.NorthWest
)
val directionString = listOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")
@Test
@DisplayName("offset")
fun getOffset() {
assertAll(
{ assertThat(CompassDirectionScreen.North.offset).isEqualTo(Point2D(0, -1)) },
{ assertThat(CompassDirectionScreen.NorthEast.offset).isEqualTo(Point2D(1, -1)) },
{ assertThat(CompassDirectionScreen.East.offset).isEqualTo(Point2D(1, 0)) },
{ assertThat(CompassDirectionScreen.SouthEast.offset).isEqualTo(Point2D(1, 1)) },
{ assertThat(CompassDirectionScreen.South.offset).isEqualTo(Point2D(0, 1)) },
{ assertThat(CompassDirectionScreen.SouthWest.offset).isEqualTo(Point2D(-1, 1)) },
{ assertThat(CompassDirectionScreen.West.offset).isEqualTo(Point2D(-1, 0)) },
{ assertThat(CompassDirectionScreen.NorthWest.offset).isEqualTo(Point2D(-1, -1)) },
)
}
@Test
@DisplayName("degree")
fun getDegree() {
val degrees = List(8) { it * 45 }
degrees.forEachIndexed { idx, degree ->
assertThat(directions[idx].degree).isEqualTo(degree)
}
}
@Test
@DisplayName("fromDegree")
fun testFromDegree() {
val degrees = List(8) { it * 45 }
degrees.forEach { degree ->
assertThat(CompassDirectionScreen.fromDegree(degree).degree).isEqualTo(degree)
}
}
@Test
@DisplayName("turnLeft")
fun getTurnLeft() {
(0..3).forEach {
(0..3).forEach {
val org = directions[it * 2]
val next = directions[(directions.size + (it - 1) * 2) % directions.size]
val left = org.turnLeft
assertThat(left).isEqualTo(next)
}
}
}
@Test
@DisplayName("turnRight")
fun getTurnRight() {
(0..3).forEach {
val org = directions[it * 2]
val next = directions[((it + 1) * 2) % directions.size]
val right = org.turnRight
assertThat(right).isEqualTo(next)
}
}
@Test
@DisplayName("turnHalfLeft")
fun getTurnHalfLeft() {
(0..7).forEach {
(0..7).forEach {
val org = directions[it]
val next = directions[(directions.size + it - 1) % directions.size]
val halfLeft = org.turnHalfLeft
assertThat(halfLeft).isEqualTo(next)
}
}
}
@Test
@DisplayName("turnHalfRight")
fun getTurnHalfRight() {
(0..7).forEach {
(0..7).forEach {
val org = directions[it]
val next = directions[(directions.size + it + 1) % directions.size]
val halfRight = org.turnHalfRight
assertThat(halfRight).isEqualTo(next)
}
}
}
@Test
@DisplayName("CompassDirectionScreen.toString")
fun testToString() {
directions.forEachIndexed { idx, direction ->
assertThat(direction.toString()).isEqualTo(directionString[idx])
}
}
@Test
@DisplayName("String.toCompassDirectionScreen")
fun testToCompassDirectionScreen() {
directionString.forEachIndexed { idx, direction ->
assertThat(direction.toCompassDirectionScreen()).isEqualTo(directions[idx])
}
}
}
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 4,061 | AoC-2022 | Apache License 2.0 |
sam-kotlin-core/src/main/kotlin/software/elborai/api/services/async/AccountServiceAsync.kt | DefinitelyATestOrg | 787,029,213 | false | {"Kotlin": 12996764, "Shell": 3638, "Dockerfile": 366} | // File generated from our OpenAPI spec by Stainless.
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package software.elborai.api.services.async
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import kotlin.LazyThreadSafetyMode.PUBLICATION
import java.time.LocalDate
import java.time.Duration
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.Base64
import java.util.Optional
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.stream.Stream
import software.elborai.api.core.Enum
import software.elborai.api.core.NoAutoDetect
import software.elborai.api.errors.IncreaseInvalidDataException
import software.elborai.api.models.Account
import software.elborai.api.models.AccountBalanceParams
import software.elborai.api.models.AccountCloseParams
import software.elborai.api.models.AccountCreateParams
import software.elborai.api.models.AccountListPageAsync
import software.elborai.api.models.AccountListParams
import software.elborai.api.models.AccountRetrieveParams
import software.elborai.api.models.AccountUpdateParams
import software.elborai.api.models.BalanceLookup
import software.elborai.api.core.ClientOptions
import software.elborai.api.core.http.HttpMethod
import software.elborai.api.core.http.HttpRequest
import software.elborai.api.core.http.HttpResponse.Handler
import software.elborai.api.core.http.BinaryResponseContent
import software.elborai.api.core.JsonField
import software.elborai.api.core.JsonValue
import software.elborai.api.core.RequestOptions
import software.elborai.api.errors.IncreaseError
import software.elborai.api.services.emptyHandler
import software.elborai.api.services.errorHandler
import software.elborai.api.services.json
import software.elborai.api.services.jsonHandler
import software.elborai.api.services.multipartFormData
import software.elborai.api.services.stringHandler
import software.elborai.api.services.binaryHandler
import software.elborai.api.services.withErrorHandler
interface AccountServiceAsync {
/** Create an Account */
suspend fun create(params: AccountCreateParams, requestOptions: RequestOptions = RequestOptions.none()): Account
/** Retrieve an Account */
suspend fun retrieve(params: AccountRetrieveParams, requestOptions: RequestOptions = RequestOptions.none()): Account
/** Update an Account */
suspend fun update(params: AccountUpdateParams, requestOptions: RequestOptions = RequestOptions.none()): Account
/** List Accounts */
suspend fun list(params: AccountListParams, requestOptions: RequestOptions = RequestOptions.none()): AccountListPageAsync
/** Retrieve an Account Balance */
suspend fun balance(params: AccountBalanceParams, requestOptions: RequestOptions = RequestOptions.none()): BalanceLookup
/** Close an Account */
suspend fun close(params: AccountCloseParams, requestOptions: RequestOptions = RequestOptions.none()): Account
}
| 1 | Kotlin | 0 | 0 | 3a5229b8bc5cf400f07efbd41e00b9cf40663f97 | 3,093 | sam-kotlin | Apache License 2.0 |
app/src/main/java/com/dreamsoftware/melodiqtv/ui/screens/home/HomeScreen.kt | sergio11 | 201,446,449 | false | {"Kotlin": 556766} | package com.dreamsoftware.melodiqtv.ui.screens.home
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.tv.material3.CarouselState
import androidx.tv.material3.ExperimentalTvMaterial3Api
import com.dreamsoftware.fudge.component.FudgeTvScreen
@OptIn(ExperimentalTvMaterial3Api::class)
val carouselSaver =
Saver<CarouselState, Int>(save = { it.activeItemIndex }, restore = { CarouselState(it) })
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel(),
onOpenCategory: (String) -> Unit,
onOpenSongDetail: (String) -> Unit,
onGoToSubscriptions: () -> Unit
) {
val carouselState = rememberSaveable(saver = carouselSaver) { CarouselState(0) }
FudgeTvScreen(
viewModel = viewModel,
onInitialUiState = { HomeUiState() },
onSideEffect = {
when(it) {
is HomeSideEffects.OpenSongCategory -> onOpenCategory(it.categoryId)
is HomeSideEffects.OpenSongDetail -> onOpenSongDetail(it.id)
HomeSideEffects.NoActivePremiumSubscription -> onGoToSubscriptions()
}
},
onInit = {
fetchData()
}
) { uiState ->
HomeScreenContent(
state = uiState,
carouselState = carouselState,
actionListener = viewModel
)
}
}
| 0 | Kotlin | 0 | 1 | ad82e5cf46929cfb1c30608c89e717929939a8d2 | 1,533 | melodiqtv_android | MIT License |
compiler/src/test/kotlin/com/wokdsem/kinject/compiler/imports/ImportSyntaxTest.kt | Wokdsem | 346,815,703 | false | {"Kotlin": 91154} | package com.wokdsem.kinject.compiler.imports
import com.tschuchort.compiletesting.SourceFile
import com.wokdsem.kinject.compiler.asserCompilationError
import org.junit.jupiter.api.Test
class ImportSyntaxTest {
@Test
fun `assert import imports declarations from a module`() {
val graph = SourceFile.kotlin(
"TestGraph.kt", """
package test
import com.wokdsem.kinject.Graph
import com.wokdsem.kinject.import.import
import com.wokdsem.kinject.scope.exportFactory
@Graph class TestGraph {
fun importModule(n: Int) = import { Module() }
}
class Module {
fun provideNumber() = exportFactory { 5 }
}
"""
)
asserCompilationError(graph, "KTestGraph", "Import declaration does not accept parameters")
}
@Test
fun `assert import when importing a module behind a typealias the typealias visibility cannot be more restricted`() {
val graph = SourceFile.kotlin(
"TestGraph.kt", """
package test
import com.wokdsem.kinject.Graph
import com.wokdsem.kinject.import.import
import com.wokdsem.kinject.import.Import
import com.wokdsem.kinject.scope.exportFactory
internal typealias Alias = Module
@Graph class TestGraph {
fun importModule(): Import<Alias> = import { Module() }
}
class Module {
fun provideNumber() = exportFactory { 5 }
}
"""
)
asserCompilationError(graph, "KTestGraph", "Typealias visibility must not be more restrictive than the class where it's used")
}
} | 0 | Kotlin | 0 | 25 | 13fde0c28f66eef2c1a53b893edecdb07462e556 | 1,770 | kInject2 | Apache License 2.0 |
redukt-core/src/commonMain/kotlin/com/daftmobile/redukt/core/threading/KtThread.kt | DaftMobile | 597,542,701 | false | null | package com.daftmobile.redukt.core.threading
/**
* Represents a unified native thread.
*/
public sealed interface KtThread {
/**
* Name of the thread returned directly by the platform.
* It might not be the best identification of a native thread (e.g. on JVM it might contain coroutine name).
*/
public val rawName: String?
/**
* Name of the thread that is adjusted to identify native thread properly (e.g. removes coroutine name on JVM).
* It returns [UNSPECIFIED] if [rawName] is null.
*/
public val name: String
public companion object {
public const val UNSPECIFIED: String = "UNSPECIFIED"
}
}
/**
* Creates a [KtThread] with given [rawName]. It doesn't create a real native thread.
* It is just for thread identification.
*/
internal fun KtThread(rawName: String?): KtThread = KtThreadImpl(rawName)
private class KtThreadImpl(override val rawName: String?) : KtThread {
override val name: String = rawName?.substringBeforeLast(" @") ?: KtThread.UNSPECIFIED
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as KtThreadImpl
if (name != other.name) return false
return true
}
override fun hashCode(): Int = name.hashCode()
override fun toString(): String {
return "Thread($name)"
}
}
| 0 | Kotlin | 0 | 4 | a67dc67645a04cb6be1a1c0bcd64997ba83ae03d | 1,433 | ReduKt | MIT License |
app/src/main/java/com/ranga/todo/ui/add/AddItemState.kt | rtippisetty | 857,640,891 | false | {"Kotlin": 45642} | package com.ranga.todo.ui.add
sealed class AddItemState {
data object Success : AddItemState()
data object Error : AddItemState()
data object InProgress : AddItemState()
data object None : AddItemState()
}
| 0 | Kotlin | 0 | 0 | 131c2ebfa184e19d2596f9a6a7418022d87f11ca | 223 | Todo | MIT License |
src/deklarasiVariabel.kt | feetbo90 | 167,954,201 | false | null |
/*
var / val nama_variabel : type_data = nilai
var bilangan : Int = 10
Float, Double, boolean,
operator aritmatika
+ , - , /, *, %
*/
import java.util.Scanner
fun main(args: Array<String>) {
var bilangan : Int = 10
var bilanganInputan : Int?
var bilangan2 : Int?
var hasil : Int?
var input = Scanner(System.`in`)
println("Masukkan bilangan : ")
bilanganInputan = input.nextInt()
println("Masukkan bilangan kedua : ")
bilangan2 = input.nextInt()
var pembagian = bilanganInputan.toDouble() / bilangan2.toDouble()
hasil = bilanganInputan + bilangan2
println(" Maka hasil penjumlahannya adalah : $pembagian")
} | 0 | Kotlin | 0 | 0 | 2fc2dacee2e9665a6ad31495f42bf6cdacb45969 | 689 | KotlinIntroduction | Apache License 2.0 |
app/src/main/java/com/linkerpad/linkerpad/ForgetPasswordActivity.kt | LinkerpadStartup | 142,832,347 | false | null | package com.linkerpad.linkerpad
import android.content.Context
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.widget.EditText
import butterknife.BindView
import com.mobsandgeeks.saripaar.ValidationError
import com.mobsandgeeks.saripaar.Validator
import com.mobsandgeeks.saripaar.annotation.Email
import com.mobsandgeeks.saripaar.annotation.NotEmpty
import kotlinx.android.synthetic.main.forget_password_layout.*
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper
class ForgetPasswordActivity : AppCompatActivity()/*, Validator.ValidationListener */ {
/* @NotEmpty
@Email
@BindView(R.id.forgetPasswordEmailEdt)
lateinit var forgetPasswordEmailEdt_: EditText*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.forget_password_layout)
// forgetPasswordEmailEdt_ = findViewById(R.id.forgetPasswordEmailEdt) as EditText
/* var validator = Validator(this@ForgetPasswordActivity)
validator.setValidationListener(this@ForgetPasswordActivity)*/
submitForgetPasswordBtn.setOnClickListener {
// validator.validate()
[email protected]()
}
cancelForgetPasswordBtn.setOnClickListener { [email protected]() }
}
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
/*
override fun onValidationFailed(errors: MutableList<ValidationError>?) {
if (forgetPasswordEmailEdt_.text.toString() == "")
forgetPasswordEmailEdt_.setError("ایمیل خالی است!")
else
forgetPasswordEmailEdt_.setError("فرمت ایمیل نادرست!")
}
override fun onValidationSucceeded() {
AlertDialog.Builder(this@ForgetPasswordActivity)
.setMessage("ایمیل بازیابی با موفقیت ارسال شد!")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
}*/
}
| 0 | Kotlin | 0 | 0 | 49b1645da41de6b631e3d526f44970449151baa5 | 2,272 | Linkerpad-phase0- | MIT License |
discovery-common/src/main/kotlin/io/datawire/discovery/auth/JWTAuthProviderFactory.kt | datawire | 46,312,788 | false | null | /*
* Copyright 2016 Datawire. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datawire.discovery.auth
import com.fasterxml.jackson.annotation.JsonProperty
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.LoggerFactory
import io.vertx.ext.auth.jwt.JWTAuth
/**
* Constructs instances of [JWTAuth] for use within a Vert.x verticle.
*/
data class JWTAuthProviderFactory(
@JsonProperty("keyStorePath") private val keyStorePath: String,
@JsonProperty("keyStoreType") private val keyStoreType: String,
@JsonProperty("keyStorePassword") private val keyStorePassword: String
) {
private val log = LoggerFactory.getLogger(JWTAuthProviderFactory::class.java)
/**
* Constructs a new instance of [JWTAuth] for the given [Vertx] instance and with the current objects internal
* parameters.
*
* @param vertx the Vert.x instance to associate the created [JWTAuth] object with.
*/
fun build(vertx: Vertx): JWTAuth {
log.debug("Building JWT AuthProvider (keystore: {0})", keyStorePath)
return JWTAuth.create(vertx, buildKeyStoreConfig())
}
/**
* Constructs a [JsonObject] that contains configuration for [JWTAuth].
*/
fun buildKeyStoreConfig(): JsonObject {
val result = JsonObject().put("keyStore", JsonObject(mapOf(
"path" to keyStorePath,
"type" to keyStoreType,
"password" to keyStorePassword
)))
return result
}
} | 4 | Kotlin | 3 | 12 | 66ae8441261f11779611f9fceac869fefc04e6ab | 1,991 | discovery | Apache License 2.0 |
app/src/main/java/com/sztorm/notecalendar/DayItem.kt | Sztorm | 342,018,745 | false | null | package com.sztorm.notecalendar
import java.time.LocalDate
data class DayItem(val date: LocalDate, val dayOfMonth: String, val dayOfWeek: String) | 3 | Kotlin | 0 | 9 | 6d48535839826811dc5755ee6f5c02f73dc05132 | 147 | NoteCalendar | MIT License |
homesdk_sample/device_config/src/main/java/com/tuya/appsdk/sample/device/config/zigbee/adapter/ZigBeeGatewayListAdapter.kt | tuya | 333,367,604 | false | null | package com.tuya.appsdk.sample.device.config.zigbee.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tuya.appsdk.sample.device.config.R
import com.tuya.appsdk.sample.device.config.util.sp.Preference
import com.tuya.appsdk.sample.device.config.zigbee.sub.DeviceConfigZbSubDeviceActivity
import com.tuya.smart.sdk.bean.DeviceBean
/**
* Zigbee Gateway List
*
* @author aiwen <a href="mailto:<EMAIL>"/>
* @since 2/25/21 10:18 AM
*/
class ZigBeeGatewayListAdapter(context: Context) :
RecyclerView.Adapter<ZigBeeGatewayListAdapter.ViewHolder>() {
var data: ArrayList<DeviceBean> = arrayListOf()
var currentGatewayId: String by Preference(
context,
DeviceConfigZbSubDeviceActivity.CURRENT_GATEWAY_ID,
""
)
var currentGatewayName: String by Preference(
context,
DeviceConfigZbSubDeviceActivity.CURRENT_GATEWAY_NAME,
""
)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflate = LayoutInflater.from(parent.context)
.inflate(R.layout.device_zb_gateway_list, parent, false)
val viewHolder = ViewHolder(inflate)
viewHolder.itemView.setOnClickListener {
val deviceBean = data[viewHolder.adapterPosition]
currentGatewayId = deviceBean.devId
currentGatewayName = deviceBean.name
notifyDataSetChanged()
}
return viewHolder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
data[position].let {
holder.itemName.text = it.name
// Switch ZigBee Gateway
if (currentGatewayId == it.devId) {
holder.itemIcon.setImageResource(R.drawable.ic_check)
} else {
holder.itemIcon.setImageResource(0)
}
}
}
override fun getItemCount(): Int {
return data.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemName: TextView = itemView.findViewById(R.id.tvName)
val itemIcon: ImageView = itemView.findViewById(R.id.ivIcon)
}
} | 0 | Kotlin | 8 | 9 | a3a8bd8160d948e378b839e7ed6647675c3dc08c | 2,374 | tuya-home-android-sdk-sample-kotlin | MIT License |
web-backend/src/main/java/com/github/aivanovski/testswithme/web/data/file/FileSystemProviderImpl.kt | aivanovski | 815,197,496 | false | {"Kotlin": 800559, "Clojure": 13655, "Shell": 1883, "Scala": 850, "Dockerfile": 375} | package com.github.aivanovski.testswithme.web.data.file
import arrow.core.Either
import arrow.core.raise.either
import java.io.IOException
import kotlin.io.path.Path
import kotlin.io.path.readBytes
class FileSystemProviderImpl : FileSystemProvider {
override fun getCurrentDirPath(): Either<IOException, String> =
either {
val currentDir = System.getProperty(PROPERTY_USER_DIR)
if (currentDir.isNullOrBlank()) {
raise(IOException("Unable to get system property: $PROPERTY_USER_DIR"))
}
currentDir
}
override fun readBytes(relativePath: String): Either<IOException, ByteArray> =
either {
val currentDir = getCurrentDirPath().bind()
// Add check that absolutePath is still inside currentDir
val absolutePath = if (relativePath.startsWith("/")) {
currentDir + relativePath
} else {
"$currentDir/$relativePath"
}
val file = Path(absolutePath)
try {
file.readBytes()
} catch (exception: IOException) {
raise(exception)
}
}
companion object {
private const val PROPERTY_USER_DIR = "user.dir"
}
} | 0 | Kotlin | 0 | 0 | 0366b4dc9afc396dcb782c2bf1cb8ad230895a18 | 1,291 | tests-with-me | Apache License 2.0 |
feature-profile/src/main/java/com/stslex/feature_profile/data/implementation/ProfileRepositoryImpl.kt | stslex | 475,504,690 | false | {"Kotlin": 235179} | package com.stslex.feature_profile.data.implementation
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.stslex.core.Mapper
import com.stslex.core.ValueState
import com.stslex.core_data_source.dao.NoteDao
import com.stslex.core_firebase.utils.abstraction.FirebaseAppInitialisationUtil
import com.stslex.core_model.common.PrimaryMapper
import com.stslex.core_model.model.NoteEntity
import com.stslex.core_model.transformer.TransformerEqualTypeValues
import com.stslex.core_firebase.data.abstraction.FirebaseNotesService
import com.stslex.feature_profile.data.abstraction.ProfileRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import java.io.IOException
class ProfileRepositoryImpl(
private val remoteNotesService: FirebaseNotesService,
private val firebaseInitializer: FirebaseAppInitialisationUtil,
private val mapperNoteSize: Mapper.ToUI<List<NoteEntity>, ValueState<Int>>,
private val transformerNoteEquals: TransformerEqualTypeValues<List<NoteEntity>, Int>,
private val mapperNoteListRemote: Mapper.Data<List<NoteEntity>, Map<String, Any>>,
private val noteDao: NoteDao,
private val flowMapper: PrimaryMapper
) : ProfileRepository {
override fun signOut() {
Firebase.auth.signOut()
}
override fun initFirebaseApp() {
firebaseInitializer()
}
override suspend fun downloadNotes(): ValueState<Unit> =
when (val localNotesState = flowMapper.map(noteDao::getAllNotesRow)) {
is ValueState.Success -> when (val remoteNotesState =
remoteNotesService.getRemoteNotes()) {
is ValueState.Success -> {
val notesToWrite = remoteNotesState.data.filterNot {
localNotesState.data.contains(it)
}
try {
noteDao.insertAllNotes(notesToWrite)
ValueState.Success(Unit)
} catch (exception: IOException) {
ValueState.Failure(exception)
}
}
is ValueState.Failure -> ValueState.Failure(remoteNotesState.exception)
is ValueState.Loading -> ValueState.Loading
}
is ValueState.Failure -> ValueState.Failure(localNotesState.exception)
is ValueState.Loading -> ValueState.Loading
}
override suspend fun uploadNotes(): Flow<ValueState<Void>> = flow {
val result = when (val localNotesState = flowMapper.map(noteDao::getAllNotesRow)) {
is ValueState.Success -> remoteNotesService.uploadNotesToRemoteDatabase(
mapperNoteListRemote.map(localNotesState.data)
)
is ValueState.Failure -> ValueState.Failure(localNotesState.exception)
is ValueState.Loading -> ValueState.Loading
}
emit(result)
}
override val remoteNotesSize: Flow<ValueState<Int>>
get() = remoteNotesService.remoteNotes.map {
it.map(mapperNoteSize)
}
override val syncNotesSize: Flow<ValueState<Int>>
get() = localNotes.combineTransform(remoteNotesService.remoteNotes) { local, remote ->
val result = local.transform(transformerNoteEquals, remote)
emit(result)
}
override val localNotes: Flow<ValueState<List<NoteEntity>>>
get() = flowMapper.map(noteDao::getAllNotesFlow)
override val localNotesSize: Flow<ValueState<Int>>
get() = flowMapper.map(noteDao::getNotesSize)
} | 4 | Kotlin | 0 | 1 | c3e1e1aeebfdbe014af58117e7293ec38af29bfb | 3,670 | CNotes | Apache License 2.0 |
app/src/main/java/com/example/bottomsheetsample/bottomsheet/base/BaseBottomSheetDialog.kt | taehee28 | 724,967,666 | false | {"Kotlin": 27219} | package com.example.bottomsheetsample.bottomsheet.base
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.example.bottomsheetsample.databinding.DialogBottomSheetBaseBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
/**
* 커스텀 바텀 시트의 틀이 되는 Base 클래스.
* 바텀 시트 내에서 화면을 이동한다는 전제로 만들어짐.
*/
abstract class BaseBottomSheetDialog : BottomSheetDialogFragment() {
private var _binding: DialogBottomSheetBaseBinding? = null
protected val baseBinding
get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
_binding = DialogBottomSheetBaseBinding.inflate(inflater, container, false)
return baseBinding.root
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// 바텀시트 내용이 커도 한번에 펼쳐지도록, 중간에 걸리지 않도록 설정
val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
dialog.setOnShowListener { dialogInterface ->
val _dialog = dialogInterface as BottomSheetDialog
_dialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)?.also {
BottomSheetBehavior.from(it).apply {
state = BottomSheetBehavior.STATE_EXPANDED
skipCollapsed = true
}
}
}
return dialog
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | 0 | Kotlin | 0 | 0 | b3ffc09258a93388153f54e5234c1da2de1dcf38 | 1,873 | BottomSheetSample | MIT License |
mazes-for-programmers/kotlin/src/main/kotlin/io/github/ocirne/mazes/demos/RandomMaze.kt | ocirne | 496,354,199 | false | {"Kotlin": 127854, "Python": 88203} | package io.github.ocirne.mazes.demos
fun main() {
TODO()
// Ausgabe Seed
// Auswahl des Grids
// Auswahl des Algorithmus
// Weave: optional
// DeadEndkiller
// Braid
// Colorisierung der Hintergründe
// Colorisierung der Wände
// Ausgabe:
// Insets
// Path
// Marker
} | 0 | Kotlin | 0 | 0 | dbd59fe45bbad949937ccef29910a0b6d075cbb3 | 330 | mazes | The Unlicense |
app/src/main/java/com/github/llmaximll/gym/fragments/otherfragments/ProfileFragment.kt | llMaximll | 362,189,718 | false | null | package com.github.llmaximll.gym.fragments.otherfragments
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.github.llmaximll.gym.BuildConfig
import com.github.llmaximll.gym.R
import com.github.llmaximll.gym.vm.ProfileVM
import java.util.concurrent.TimeUnit
private const val NAME_SHARED_PREFERENCES = "shared_preferences"
private const val SP_USERNAME = "sp_username"
private const val SP_TOKEN = "sp_t"
private const val TAG = "ProfileFragment"
private const val REQUEST_DIALOG_CODE_BIO = 1
private const val REQUEST_DIALOG_CODE_START_DIALOG = 2
private const val REQUEST_DIALOG_CODE_TIMEOUT = 3
private const val SP_HEIGHT = "sp_height"
private const val SP_WEIGHT = "sp_weight"
private const val SP_GENDER = "sp_gender"
private const val SP_NOTIFICATIONS ="sp_notifications"
private const val SP_TIMEOUT_COUNT = "sp_timeout_count"
class ProfileFragment : Fragment() {
interface Callbacks {
fun onProfileFragment()
}
private lateinit var signOutImageButton: ImageButton
private lateinit var viewModel: ProfileVM
private lateinit var username: String
private lateinit var weightTextView: TextView
private lateinit var heightTextView: TextView
private lateinit var nameTextView: TextView
private lateinit var genderTextView: TextView
private lateinit var biometricTextView: TextView
private lateinit var shadowImageViewActivity: ImageView
private lateinit var dialogTextView: TextView
private lateinit var policyTextView: TextView
private lateinit var notificationsSwitch: SwitchCompat
private lateinit var restTimeTextView: TextView
private var callbacks: Callbacks? = null
private var notifications: Boolean = false
override fun onAttach(context: Context) {
super.onAttach(context)
callbacks = context as Callbacks
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
username = sharedPreference?.getString(SP_USERNAME, "null-username")!!
notifications = sharedPreference.getBoolean(SP_NOTIFICATIONS, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = layoutInflater.inflate(R.layout.fragment_profile, container, false)
weightTextView = view.findViewById(R.id.count_scores_textView)
heightTextView = view.findViewById(R.id.count_minutes_textView)
nameTextView = view.findViewById(R.id.title_textView)
genderTextView = view.findViewById(R.id.minutes_textView)
signOutImageButton = view.findViewById(R.id.stop_imageButton)
biometricTextView = view.findViewById(R.id.biometric_textView)
shadowImageViewActivity = activity?.findViewById(R.id.shadow_imageView)!!
dialogTextView = view.findViewById(R.id.dialog_textView)
policyTextView = view.findViewById(R.id.policy_textView)
notificationsSwitch = view.findViewById(R.id.notifications_switch)
restTimeTextView = view.findViewById(R.id.rest_time_textView)
initObservers()
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
viewModel.getProfile(sharedPreference?.getInt(SP_TOKEN, 0).toString())
val rest = sharedPreference?.getLong(SP_TIMEOUT_COUNT, 30L) ?: 30L
restTimeTextView.text = "${rest.toInt() / 1000} sec"
notificationsSwitch.isChecked = notifications
val gender = sharedPreference?.getInt(SP_GENDER, 0)
genderTextView.text = if (gender == 1) "Male" else "Female"
return view
}
override fun onStart() {
super.onStart()
restTimeTextView.setOnClickListener {
shadowImageViewActivity.isVisible = true
animateAlpha(shadowImageViewActivity)
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
val rest = sharedPreference?.getLong(SP_TIMEOUT_COUNT, 30L) ?: 30L
val dialogFragment = TimeoutDialogFragment.newInstance(rest)
dialogFragment.setTargetFragment(this, REQUEST_DIALOG_CODE_TIMEOUT)
dialogFragment.show(parentFragmentManager, "TimeoutDialogFragment")
onPause()
}
biometricTextView.setOnClickListener {
shadowImageViewActivity.isVisible = true
animateAlpha(shadowImageViewActivity)
val dialogFragment = ProfileBioDialogFragment.newInstance()
dialogFragment.setTargetFragment(this, REQUEST_DIALOG_CODE_BIO)
dialogFragment.show(parentFragmentManager, "ProfileBioDialogFragment")
onPause()
}
dialogTextView.setOnClickListener {
shadowImageViewActivity.isVisible = true
animateAlpha(shadowImageViewActivity)
val dialogFragment = GenderDialogFragment.newInstance()
dialogFragment.setTargetFragment(this, REQUEST_DIALOG_CODE_START_DIALOG)
dialogFragment.show(parentFragmentManager, "GenderDialogFragment")
onPause()
}
policyTextView.setOnClickListener {
callbacks?.onProfileFragment()
}
signOutImageButton.setOnClickListener {
viewModel.signOut(username)
}
notificationsSwitch.setOnCheckedChangeListener { _, isChecked ->
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
if (isChecked) {
val result = viewModel.setAlarmManager(requireContext())
if (result) {
val editor = sharedPreference?.edit()
editor?.putBoolean(SP_NOTIFICATIONS, true)
editor?.apply()
toast("Уведомления включены")
} else
toast("Не удалось включить уведомления")
} else {
val result = viewModel.stopAlarmManager(requireContext())
val editor = sharedPreference?.edit()
editor?.putBoolean(SP_NOTIFICATIONS, false)
editor?.apply()
if (result) toast("Уведомления выключены")
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_DIALOG_CODE_BIO -> {
val weight = data?.getIntExtra(ProfileBioDialogFragment.NAME_TAG_WEIGHT, 1)
val height = data?.getIntExtra(ProfileBioDialogFragment.NAME_TAG_HEIGHT, 1)
if (weight != null && height != null) {
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
viewModel.editProfile(sharedPreference?.getInt(SP_TOKEN, 1).toString(), weight.toString(), height.toString())
}
}
REQUEST_DIALOG_CODE_START_DIALOG -> {
val bool = data?.getBooleanExtra(GenderDialogFragment.NAME_TAG_GENDER, false)
if (bool != null) {
val gender = if (bool) 1 else 0
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPreference?.edit()
editor?.putInt(SP_GENDER, gender)
editor?.apply()
genderTextView.text = if (bool) "Male" else "Female"
toast("Данные обновлены")
}
}
REQUEST_DIALOG_CODE_TIMEOUT -> {
val count = data?.getIntExtra(TimeoutDialogFragment.INTENT_TAG_TIMEOUT_COUNT, 30)
if (count != null) {
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPreference?.edit()
editor?.putLong(SP_TIMEOUT_COUNT, TimeUnit.SECONDS.toMillis(count.toLong()))
editor?.apply()
restTimeTextView.text = "$count sec"
}
}
}
}
}
override fun onResume() {
super.onResume()
shadowImageViewActivity.isVisible = false
shadowImageViewActivity.alpha = 0f
}
override fun onDetach() {
super.onDetach()
callbacks = null
}
private fun initObservers() {
viewModel = ViewModelProvider(this).get(ProfileVM::class.java)
viewModel.cosmeticView.message.observe(
viewLifecycleOwner,
{ message ->
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
viewModel.getProfile(sharedPreference?.getInt(SP_TOKEN, 1).toString())
toast(message)
}
)
viewModel.profile.observe(
viewLifecycleOwner,
{ profile ->
if (profile.isNotEmpty()) {
val sharedPreference =
context?.getSharedPreferences(NAME_SHARED_PREFERENCES, Context.MODE_PRIVATE)
val editor = sharedPreference?.edit()
if (nameTextView.text.toString() != profile[0].username) {
editor?.putString(SP_USERNAME, profile[0].username)
nameTextView.text = profile[0].username
}
weightTextView.text = profile[0].weight
heightTextView.text = profile[0].height
editor?.putInt(SP_WEIGHT, profile[0].weight.toInt())
editor?.putInt(SP_HEIGHT, profile[0].height.toInt())
editor?.apply()
}
log(TAG, "profile=$profile")
}
)
}
private fun animateAlpha(view: View) {
val animatorAlpha = ObjectAnimator.ofFloat(
view,
"alpha",
1.0f
)
animatorAlpha.duration = 500
animatorAlpha.start()
}
private fun toast(message: String) {
val toast = Toast.makeText(requireContext(), message, Toast.LENGTH_LONG)
toast.setGravity(Gravity.TOP, 0, 0)
toast.show()
}
private fun log(tag: String, message: String) {
if (BuildConfig.DEBUG) {
Log.i(tag, message)
}
}
companion object {
fun newInstance(): ProfileFragment = ProfileFragment()
}
} | 0 | Kotlin | 0 | 2 | eac6a6dd634660acf362adbd7afcb9495f3c3ca3 | 11,719 | Gym | Apache License 2.0 |
app/src/main/java/co/specialforce/data/response/getWeight/GetWeightResponse.kt | osamhack2020 | 303,081,543 | false | null | package co.specialforce.data.response.getWeight
data class GetWeightResponse(val success: Boolean, val result: List<WeightArray>,
val min_max_avg: WeightMinMaxAvg) | 0 | Kotlin | 0 | 4 | 683b8da58882a78fa583bdda276b906f9e4612c4 | 193 | App_SpecialForces_SpecialWarrior | Apache License 2.0 |
app/src/main/kotlin/land/sungbin/androidx/viewer/utils/GitHubFetchLoggingContext.kt | jisungbin | 829,412,179 | false | {"Kotlin": 71964} | /*
* Developed by <NAME> 2024.
*
* Licensed under the MIT.
* Please see full license: https://github.com/jisungbin/androidx-aosp-viewer/blob/trunk/LICENSE
*/
package land.sungbin.androidx.viewer.utils
import land.sungbin.androidx.fetcher.RemoteLoggingContext
import okhttp3.logging.HttpLoggingInterceptor
val GitHubFetchLoggingContext = RemoteLoggingContext(level = HttpLoggingInterceptor.Level.BODY)
| 1 | Kotlin | 0 | 3 | 5242291f54d8d11e44ab85cb1d8a0eec7117b070 | 409 | androidx-aosp-viewer | MIT License |
typesystem/src/main/kotlin/org/ksharp/typesystem/substitution/ParametricSubstitution.kt | ksharp-lang | 573,931,056 | false | null | package org.ksharp.typesystem.substitution
import org.ksharp.common.ErrorOrValue
import org.ksharp.common.Location
import org.ksharp.typesystem.ErrorOrType
import org.ksharp.typesystem.incompatibleType
import org.ksharp.typesystem.types.ParametricType
import org.ksharp.typesystem.types.Type
class ParametricSubstitution : CompoundSubstitution<ParametricType>() {
override val Type.isSameTypeClass: Boolean
get() = this is ParametricType
override fun compoundExtract(
context: SubstitutionContext,
location: Location,
type1: ParametricType,
type2: ParametricType
): ErrorOrValue<Boolean> =
if (type1.type() == type2.type()) {
type1.params.extract(context, location, type2.params)
} else incompatibleType(location, type1, type2)
override fun substitute(
context: SubstitutionContext,
location: Location,
type: ParametricType,
typeContext: Type
): ErrorOrType =
type.params.substitute(context, location, typeContext).map {
ParametricType(type.typeSystem, type.attributes, type.type, it)
}
}
| 5 | Kotlin | 0 | 0 | 7b8e13db6ec2c4ee42777c6f3d6a2172469bb5c0 | 1,143 | ksharp-kt | Apache License 2.0 |
ticket-restaurant-log-lib/src/main/kotlin/es/juandavidvega/ticketrestaurantlog/lib/TicketTypeRecorder.kt | jdvr | 161,951,526 | false | null | package es.juandavidvega.ticketrestaurantlog.lib
import es.juandavidvega.ticketrestaurantlog.lib.dao.TicketTypeSaver
import es.juandavidvega.ticketrestaurantlog.lib.models.InvalidTicketTypeAmountException
import es.juandavidvega.ticketrestaurantlog.lib.models.TicketType
class TicketTypeRecorder(val saver: TicketTypeSaver) {
fun record(ticketType: TicketType) {
if (ticketType.amount <= 0) {
throw InvalidTicketTypeAmountException()
}
saver.save(ticketType)
}
}
| 0 | Kotlin | 0 | 0 | 6c924ca7c61330d7df2a9042ecb4b4ae5cf30d46 | 510 | ticket-restaurant-log | The Unlicense |
magnet-processor/src/main/java/magnet/processor/instances/aspects/scoping/ScopingAttributeParser.kt | beworker | 123,189,523 | false | null | package magnet.processor.instances.aspects.scoping
import magnet.processor.instances.parser.AttributeParser
import magnet.processor.instances.parser.ParserInstance
import javax.lang.model.element.AnnotationValue
import javax.lang.model.element.Element
object ScopingAttributeParser : AttributeParser("scoping") {
override fun <E : Element> Scope<E>.parse(value: AnnotationValue): ParserInstance<E> =
instance.copy(scoping = value.value.toString())
}
| 0 | null | 19 | 174 | 7c1807822724c86fe5c9839e5ca52c6455f3ac6e | 464 | magnet | Apache License 2.0 |
app/src/main/java/com/doctorblue/thehiveshop/utils/Resource.kt | doctor-blue | 331,880,770 | false | null | package com.doctorblue.thehiveshop.utils
sealed class Resource<out T> {
data class Success<out T>(val data: T) : Resource<T>()
data class Error<out T>(val data: T?, val message: String) : Resource<T>()
data class Loading<out T>(val data: T?) : Resource<T>()
} | 0 | Kotlin | 1 | 1 | 67c432f1bb7e2956bf0a6bbef3a161c7c6fd5afe | 272 | the-hive-shop | MIT License |
core/src/main/java/com/exozet/android/core/connectivity/ConnectivityHelper.kt | exozet | 133,497,547 | false | null | package com.europapark.services.connectivity
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.os.AsyncTask
import android.os.Build
import android.os.Build.VERSION_CODES
import android.provider.Settings
import android.telephony.TelephonyManager
import android.util.Log
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import java.net.UnknownHostException
import java.nio.channels.IllegalBlockingModeException
import java.util.*
import java.util.concurrent.CancellationException
/**
* Check device's network connectivity and speed. Check Internet access *
* @author rodrigo https://stackoverflow.com/users/5520417/rodrigo
*/
class ConnectivityAndInternetAccess(hosts: ArrayList<String>) {
/**
* Gets the hosts
* @return The hosts
*/
/**
* Adjusts the value of the hosts
* @param hosts The hosts
*/
private var hosts: ArrayList<String> = hosts
private set(hosts) {
Companion.hosts = hosts
field = hosts
}
/**
* Checks that Internet is available. Network calls shouldn't be called from main thread otherwise it will throw @link{[android.os.NetworkOnMainThreadException]}
*/
private class InternetConnectionCheckAsync internal constructor(context: Context?) : AsyncTask<Void?, Void?, Boolean>() {
/**
* Delivers the context
*/
/**
* Adjusts the value of the field that stores the context
* @param context The context
*/
@SuppressLint("StaticFieldLeak")
var context: Context? = null
/**
* Cancels the activity if the device is not connected to a network.
*/
override fun onPreExecute() {
if (!isConnected(context)) {
cancel(true)
}
}
/**
* Creates an instance of this class
* @param context The context
*/
init {
this.context = context
}
/**
* Tells whether there is Internet access
* @param voids The list of arguments
* @return True if Internet can be accessed
*/
override fun doInBackground(vararg voids: Void?): Boolean {
return isConnectedToInternet(context)
}
}
companion object {
//------------------------------------------- Connectivity --------------------------------------------------------------------------
/**
* Gets the minimum speed for fast connection
* @return The minimum speed for fast connection
*/
/**
* The minimum speed for the connection to be considered fast
*
*/
private const val minimumSpeedForFastConnection = 3072
/**
* Get the active network's info.
*
* @param context The Context.
* @return The active NetworkInfo.
*/
private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
var networkInfo: NetworkInfo? = null
val cm = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (cm != null) {
networkInfo = cm.activeNetworkInfo
}
return networkInfo
}
/**
* Get active network.
*
* @param context The Context.
* @return The active NetworkInfo.
*/
private fun getActiveNetwork(context: Context): Network? {
var networkInfo: Network? = null
val cm = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (cm != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
networkInfo = cm.activeNetwork
} else {
Log.e("UnusableMethod", "Cannot use this method for the current API Level")
}
}
return networkInfo
}
/**
* Get the network info.
*
* @param context The Context.
* @return The active NetworkInfo.
*/
private fun getActiveNetworkInfo(context: Context, network: Network?): NetworkInfo? {
var networkInfo: NetworkInfo? = null
val cm = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (cm != null && network != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
networkInfo = cm.getNetworkInfo(network)
} else {
Log.e("UnusableMethod", "Cannot use this method for the current API Level")
}
}
return networkInfo
}
/**
* Gets the info of all networks
* @param context The context
* @return An array of @link {NetworkInfo}
*/
private fun getAllNetworkInfo(context: Context?): Array<NetworkInfo?> {
val cm = context
?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var nwInfo = arrayOfNulls<NetworkInfo>(0)
if (cm != null) {
if (Build.VERSION.SDK_INT < VERSION_CODES.M) {
nwInfo = cm.allNetworkInfo
} else {
Log.e("UnusableMethod", "Cannot use this method for the current API Level")
}
}
return nwInfo
}
/**
* Gives the connectivity manager
* @param context The context
* @return the @code{[ConnectivityManager]}
*/
private fun getConnectivityManager(context: Context?): ConnectivityManager {
return context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}
/**
* Tells whether the network is facilitating fast network switching
* @param context The context.
* @param network The network.
* @return @code{true} if the network is facilitating fast network switching
*/
private fun isNetworkFacilitatingFastNetworkSwitching(
context: Context,
network: Network
): Boolean {
var isNetworkFacilitatingFastNetworkSwitching = false
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)) {
isNetworkFacilitatingFastNetworkSwitching = true
}
} else {
Log.e("UnusableMethod", null)
}
return isNetworkFacilitatingFastNetworkSwitching
}
/**
* Tells whether the network can be used by apps
* @param context The context.
* @param network The network.
* @return @code{true} if the network can by used by apps
*/
private fun isNetworkUsableByApps(context: Context, network: Network): Boolean {
var isNetworkUsableByApps = false
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)) {
isNetworkUsableByApps = true
}
} else {
Log.e("UnusableMethod", null)
}
return isNetworkUsableByApps
}
private fun isNetworkSuspended(context: Context, network: Network): Boolean {
var isNetworkSuspended = false
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
isNetworkSuspended = true
}
} else {
Log.e("UnusableMethod", null)
}
return isNetworkSuspended
}
/**
* Check if there is any connectivity at all to a specific network.
*
* @param context The Context.
* @return @code{true} if we are connected to a network, false otherwise.
*/
fun isActiveNetworkConnected(context: Context): Boolean {
var isConnected = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val network = getActiveNetwork(context)
if (network != null) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if (networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
) /*API >= 28*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API >= 28*/ {
isConnected = true
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
isConnected = true
}
} else {
if (networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /*API >= 21*/) {
isConnected = true
}
}
}
}
}
} else {
Log.e("NullNetworkCapabilities", null)
}
} else {
Log.e("NullNetwork", null)
}
} else {
val info = getActiveNetworkInfo(context)
/*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can return
@code{true} when Wi-Fi is disabled (http://stackoverflow.com/a/2937915)
*/isConnected = info != null && info.isAvailable && info.isConnected
}
return isConnected
}
/**
* Check if there is any connectivity at all to a specific network.
*
* @param context The Context.
* @param network The network
* @return @code{true} if we are connected to a network, false otherwise.
*/
fun isConnected(context: Context, network: Network?): Boolean {
var isConnected = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
) /*API >= 28*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API >= 28*/ {
isConnected = true
}
}
}
} else {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities!!.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
isConnected = true
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
isConnected = true
}
}
}
} else {
val info = getActiveNetworkInfo(context)
/*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can return
@code{true} when Wi-Fi is disabled (http://stackoverflow.com/a/2937915)
*/isConnected = info != null && info.isAvailable && info.isConnected
}
return isConnected
}
/**
* Check if there is any connectivity at all.
*
* @param context the Context.
* @return @code{true} if we are connected to a network, false otherwise.
*/
@JvmStatic
fun isConnected(context: Context?): Boolean {
var isConnected = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networks = connectivityManager.allNetworks
for (network in networks) {
if (network != null) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /* API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /* API >= 28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /* API >= 28*/ {
isConnected = true
break
}
} else {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
isConnected = true
break
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
isConnected = true
break
}
}
}
} else {
Log.e("NullNetworkCapabilities", null)
}
} else {
Log.e("NullNetwork", null)
}
}
} else {
val infos = getAllNetworkInfo(context)
for (info in infos) { /*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can
return @code{true} when Wi-Fi is disabled (http://stackoverflow
.com/a/2937915)
*/
isConnected = info != null && info.isAvailable && info.isConnected
if (isConnected) {
break
}
}
}
return isConnected
}
/**
* Check if there is any connectivity to a Wifi network.
*
* @param context the Context.
* @return @code{true} if we are connected to a Wifi network, false otherwise.
*/
fun isConnectedWifi(context: Context?): Boolean {
var isConnectedWifi = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networks = connectivityManager.allNetworks
for (network in networks) {
if (network != null) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /* API >= 21*/
&& networkCapabilities
.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API>=23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API>=28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API>=28*/ {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
)
) {
isConnectedWifi = true
break
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
)
) {
isConnectedWifi = true
break
}
}
} else {
if (networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) /*API >= 21*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
)
) {
isConnectedWifi = true
break
}
}
}
}
}
}
} else {
Log.e("NullNetworkCapabilities", null)
}
} else {
Log.e("NullNetwork", null)
}
}
} else {
val infos = getAllNetworkInfo(context)
for (info in infos) { /*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can
return @code{true} when Wi-Fi is disabled (http://stackoverflow
.com/a/2937915)
*/
isConnectedWifi = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_WIFI)
if (isConnectedWifi) {
break
}
}
}
return isConnectedWifi
}
/**
* Check if there is any connectivity to a Wifi network on a specific network.
*
* @param context The context.
* @param network The network
* @return @code{true} if we are connected to a Wifi network, false otherwise.
*/
fun isConnectedWifi(context: Context, network: Network?): Boolean {
var isConnectedWifi = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API>=23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API>=28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API>=28*/ {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
) {
isConnectedWifi = true
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
) {
isConnectedWifi = true
}
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
) {
isConnectedWifi = true
}
}
}
}
}
}
} else {
val info = getActiveNetworkInfo(
context,
network
)
/*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can return
@code{true} when Wi-Fi is disabled (http://stackoverflow.com/a/2937915)
*/isConnectedWifi = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_WIFI)
}
return isConnectedWifi
}
/**
* Check if there is any connectivity to a Wifi network with airplane mode on.
*
* @param context The context.
* @return @code{true} if we are connected to a Wifi network over airplane mode
*/
fun isConnectedWifiOverAirplaneMode(context: Context): Boolean {
return isConnectedWifi(context) && isAirplaneModeOn(context)
}
/**
* Check if there is any connectivity to a Wifi network on a specific network with airplane mode on.
*
* @param context The context.
* @param network The network
* @return @code{true} if we are connected to a specific Wifi network over
* airplane mode.
*/
fun isConnectedWifiOverAirplaneMode(context: Context, network: Network?): Boolean {
return isConnectedWifi(context, network) && isAirplaneModeOn(context)
}
/**
* Checks via @link{TelephonyManager} if there is mobile data connection
* @return @code{true} if the device has mobile data connection
* @param context the context
*/
fun isConnectedMobileTelephonyManager(context: Context): Boolean {
val tm = context
.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
var state = 0
if (tm != null) {
state = tm.dataState
}
return state == TelephonyManager.DATA_CONNECTED
}
/**
* Check if there is any connectivity to a mobile network.
*
* @param context The Context.
* @param network The network
* @return @code{true} if we are connected to a mobile network.
*/
fun isConnectedMobile(context: Context, network: Network?): Boolean {
var isConnectedMobile = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API>=23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API>=28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API>=28*/ {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
) {
isConnectedMobile = true
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
) {
isConnectedMobile = true
}
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
) {
isConnectedMobile = true
}
}
}
}
}
}
} else {
val info = getActiveNetworkInfo(
context,
network
)
/*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can return
@code{true} when Wi-Fi is disabled (http://stackoverflow.com/a/2937915)
*/isConnectedMobile = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_MOBILE)
}
return isConnectedMobile
}
/**
* Check if there is any connectivity to a mobile network.
*
* @param context the Context.
* @return true if we are connected to a mobile network.
*/
fun isConnectedMobile(context: Context?): Boolean {
var isConnectedWifi = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networks = connectivityManager.allNetworks
for (network in networks) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API >= 28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API >= 28*/ {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_CELLULAR
)
) {
isConnectedWifi = true
break
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_CELLULAR
)
) {
isConnectedWifi = true
break
}
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_CELLULAR
)
) {
isConnectedWifi = true
break
}
}
}
}
}
}
}
} else {
val infos = getAllNetworkInfo(context)
for (info in infos) { /*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can
return @code{true} when Wi-Fi is disabled (http://stackoverflow
.com/a/2937915)
*/
isConnectedWifi = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_MOBILE)
if (isConnectedWifi) {
break
}
}
}
return isConnectedWifi
}
/**
* Check if there is any connectivity to a ethernet network.
*
* @param context the Context.
* @return true if we are connected to a ethernet network.
*/
fun isConnectedEthernet(context: Context?): Boolean {
var isConnectedEthernet = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networks = connectivityManager.allNetworks
for (network in networks) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API >= 28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API >= 28*/ {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_ETHERNET
)
) {
isConnectedEthernet = true
break
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_ETHERNET
)
) {
isConnectedEthernet = true
break
}
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_ETHERNET
)
) {
isConnectedEthernet = true
break
}
}
}
}
}
}
}
} else {
val infos = getAllNetworkInfo(context)
for (info in infos) { /*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can
return @code{true} when Wi-Fi is disabled (http://stackoverflow
.com/a/2937915)
*/
isConnectedEthernet = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_ETHERNET)
if (isConnectedEthernet) {
break
}
}
}
return isConnectedEthernet
}
/**
* Check if a specific network has ethernet connectivity.
*
* @param context The Context.
* @param network The network
* @return true if we are connected to a ethernet network.
*/
fun isConnectedEthernet(context: Context, network: Network?): Boolean {
var isConnectedEthernet = false
val connectivityManager = getConnectivityManager(context)
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
if (network != null) {
if (networkCapabilities != null) {
if ((networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /* API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
)) /*API >= 28*/
|| networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_FOREGROUND
)
) /*API >= 28*/ {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) {
isConnectedEthernet = true
}
}
}
}
} else {
if (network != null) {
if (networkCapabilities != null) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/
&& networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_VALIDATED
) /*API >= 23*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) {
isConnectedEthernet = true
}
}
} else {
if (networkCapabilities
.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) /*API >= 21*/) {
if (networkCapabilities
.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) {
isConnectedEthernet = true
}
}
}
}
}
}
} else {
val info = getActiveNetworkInfo(
context,
network
)
/*
Works on emulator and devices. Note the use of @link{NetworkInfo
.isAvailable} - without this, @link{NetworkInfo.isConnected} can return
@code{true} when Wi-Fi is disabled (http://stackoverflow.com/a/2937915)
*/isConnectedEthernet = (info != null && info.isAvailable && info.isConnected
&& info.type == ConnectivityManager.TYPE_ETHERNET)
}
return isConnectedEthernet
}
/**
* Check if there is fast connectivity.
*
* @param context the Context.
* @return true if we have "fast" connectivity.
*/
fun isConnectedFast(context: Context): Boolean {
var isConnectedFast = false
if (Build.VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
val networkInfos = getAllNetworkInfo(context)
for (networkInfo in networkInfos) {
isConnectedFast = (networkInfo != null && networkInfo.isAvailable
&& networkInfo.isConnected
&& isConnectionFast(networkInfo.type, networkInfo.subtype))
if (isConnectedFast) {
break
}
}
} else {
val connectivityManager = getConnectivityManager(context)
val allNetworks = connectivityManager.allNetworks
for (network in allNetworks) {
if (network != null && isConnected(context, network)) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (networkCapabilities != null) {
val linkDownstreamBandwidthKbps = networkCapabilities
.linkDownstreamBandwidthKbps
val linkUpstreamBandwidthKbps = networkCapabilities
.linkUpstreamBandwidthKbps
if (linkDownstreamBandwidthKbps >= minimumSpeedForFastConnection
&& linkUpstreamBandwidthKbps >= minimumSpeedForFastConnection
) {
isConnectedFast = true
break
}
}
}
}
}
return isConnectedFast
}
/**
* Check if there is fast connectivity over a specific network.
*
* @param context The Context.
* @param network The network
* @return @code{true} if we have "fast" connectivity.
*/
fun isConnectedFast(context: Context, network: Network?): Boolean {
var isConnectedFast = false
if (Build.VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
val networkInfo = getActiveNetworkInfo(context, network)
isConnectedFast = (networkInfo != null && networkInfo.isAvailable
&& networkInfo.isConnected
&& isConnectionFast(networkInfo.type, networkInfo.subtype))
} else {
val connectivityManager = getConnectivityManager(context)
if (network != null && isConnected(context, network)) {
val networkCapabilities = connectivityManager
.getNetworkCapabilities(network)
if (networkCapabilities != null) {
val linkDownstreamBandwidthKbps = networkCapabilities
.linkDownstreamBandwidthKbps
val linkUpstreamBandwidthKbps = networkCapabilities
.linkUpstreamBandwidthKbps
if (linkDownstreamBandwidthKbps >= minimumSpeedForFastConnection
&& linkUpstreamBandwidthKbps >= minimumSpeedForFastConnection
) {
isConnectedFast = true
}
}
}
}
return isConnectedFast
}
/**
* Determines if the airplane mode is on
* @param context The context
* @return @code{true} if the airplane mode is on
*/
@TargetApi(VERSION_CODES.JELLY_BEAN_MR1)
fun isAirplaneModeOn(context: Context): Boolean {
val isAirplaneModeOn: Boolean = if (Build.VERSION.SDK_INT < VERSION_CODES.JELLY_BEAN_MR1) {
Settings.System.getInt(
context.contentResolver,
Settings.System.AIRPLANE_MODE_ON, 0
) != 0
} else {
Settings.Global.getInt(
context.contentResolver,
Settings.Global.AIRPLANE_MODE_ON, 0
) != 0
}
return isAirplaneModeOn
}
/**
* Check if the connection is fast
* @param type The network type
* @param subType The network subtype
* @return @code {true} if the connection is fast
*/
private fun isConnectionFast(type: Int, subType: Int): Boolean {
val connectedFast: Boolean
connectedFast = if (type == ConnectivityManager.TYPE_WIFI
|| type == ConnectivityManager.TYPE_ETHERNET
) {
true
} else if (type == ConnectivityManager.TYPE_MOBILE) {
when (subType) {
TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_LTE -> true
TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_IDEN, TelephonyManager.NETWORK_TYPE_UNKNOWN -> false
else -> false
}
} else {
false
}
return connectedFast
}
//-------------------------------------- Internet Reachability Verification ----------------------------------------------------
/**
* A list of hosts to verify Internet access
*/
private var hosts: ArrayList<String> = object : ArrayList<String>() {
init {
add("google.com")
add("facebook.com")
add("apple.com")
add("amazon.com")
add("twitter.com")
add("linkedin.com")
add("microsoft.com")
}
}
/**
* Tells whether Internet is reachable
* @return true if Internet is reachable, false otherwise
* @param context The context
*/
fun isInternetReachable(context: Context?): Boolean {
val isInternetReachable: Boolean
try {
val internetConnectionCheckAsync: InternetConnectionCheckAsync = InternetConnectionCheckAsync(context)
isInternetReachable = internetConnectionCheckAsync.execute()
.get()
return isInternetReachable
} catch (e: CancellationException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
/**
* Tells whether Internet is reachable
* @return true if Internet is reachable, false otherwise
* @param context The context
* @param hosts The hosts
*/
fun isInternetReachable(context: Context?, hosts: ArrayList<String>): Boolean {
val isInternetReachable: Boolean
try {
val internetConnectionCheckAsync = InternetConnectionCheckAsync(
context
)
val connectivityAndInternetAccessCheck = ConnectivityAndInternetAccess(hosts)
connectivityAndInternetAccessCheck.hosts = hosts
isInternetReachable = internetConnectionCheckAsync.execute().get()
return isInternetReachable
} catch (e: CancellationException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
/**
* Tells whether there is Internet connection
* @param context The context
* @return @code {true} if there is Internet connection
*/
private fun isConnectedToInternet(context: Context?): Boolean {
var isAvailable = false
if (isConnected(context)) {
try {
for (h in hosts) {
if (isHostAvailable(h)) {
isAvailable = true
break
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
return isAvailable
}
/**
* Tells whether there is Internet connection
* @param context The context
* @param hosts The hosts
* @return @code {true} if there is Internet connection
*/
private fun isConnectedToInternet(context: Context, hosts: ArrayList<String>): Boolean {
var isAvailable = false
if (isConnected(context)) {
try {
for (h in hosts) {
if (isHostAvailable(h)) {
isAvailable = true
break
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
return isAvailable
}
/**
* Checks if the host is available
* @param hostName The name of the host
* @return @code{true} if the host is available
* @throws IOException If it happens
*/
@Throws(IOException::class, IllegalBlockingModeException::class, IllegalArgumentException::class)
private fun isHostAvailable(hostName: String): Boolean {
var isHostAvailable: Boolean
isHostAvailable = false
try {
Socket().use { socket ->
val port = 80
val socketAddress = InetSocketAddress(hostName, port)
socket.connect(socketAddress, 3000)
isHostAvailable = true
}
} catch (unknownHost: UnknownHostException) {
isHostAvailable = false
}
return isHostAvailable
}
}
}
| 1 | null | 2 | 11 | 72cbb02bc262b1c26450b570e41842ab65406c3e | 59,600 | AndroidCore | MIT License |
lazyrecycler/src/main/java/com/dokar/lazyrecycler/DiffCallback.kt | dokar3 | 344,170,886 | false | {"Kotlin": 75914} | package com.dokar.lazyrecycler
import androidx.recyclerview.widget.DiffUtil
/**
* DSL function to create a [DiffUtil.ItemCallback].
*
* ### Example:
*
* ```kotlin
* val diffCallback = diffCallback {
* areItemsTheSame { oldItem, newItem -> oldItem.id == newItem.id }
* areContentsTheSame { oldItem, newItem -> oldItem == newItem }
* }
* ```
*/
inline fun <I : Any> differCallback(
block: DiffCallback<I>.() -> Unit
): DiffUtil.ItemCallback<I> = DiffCallback<I>().also(block)
open class DiffCallback<I : Any> : DiffUtil.ItemCallback<I>() {
private var areItemsTheSame: AreItemsTheSame<I>? = null
private var areContentsTheSame: AreContentsTheSame<I>? = null
override fun areItemsTheSame(oldItem: I, newItem: I): Boolean {
return areItemsTheSame?.invoke(oldItem, newItem) ?: false
}
override fun areContentsTheSame(oldItem: I, newItem: I): Boolean {
return areContentsTheSame?.invoke(oldItem, newItem) ?: false
}
fun areItemsTheSame(expression: AreItemsTheSame<I>) {
areItemsTheSame = expression
}
fun areContentsTheSame(expression: AreContentsTheSame<I>) {
areContentsTheSame = expression
}
}
| 0 | Kotlin | 0 | 18 | 9cf53080a1a6e90d0da087487c5b98bf659ca438 | 1,194 | LazyRecycler | Apache License 2.0 |
jvm/core-common/src/main/kotlin/com/mussonindustrial/embr/common/EmbrCommonContextExtension.kt | mussonindustrial | 755,767,058 | false | {"Kotlin": 133814, "TypeScript": 47233, "JavaScript": 4721, "HTML": 2823, "CSS": 1212} | package com.mussonindustrial.embr.common
interface EmbrCommonContextExtension {
fun getModuleSafe(moduleId: String): Any?
fun <T> ifModule(
moduleId: String,
action: () -> T,
): T?
}
| 7 | Kotlin | 1 | 8 | 9b5a2f6b02f1a7defa920232dc2716542f5ca047 | 213 | embr | MIT License |
TomaRamosUandes/app/src/main/java/com/ifgarces/tomaramosuandes/local_db/UserStatsDAO.kt | ifgarces | 281,504,652 | false | null | package com.ifgarces.tomaramosuandes.local_db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.ifgarces.tomaramosuandes.models.UserStats
// Note: it is supossed to be just one instance of the `UserStats` class in the Room local database, i.e. its table should contain one row.
@Dao
interface UserStatsDAO {
@Query(value = "DELETE FROM ${UserStats.TABLE_NAME}")
fun clear()
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(value :UserStats)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(value :UserStats)
@Query(value = "SELECT * FROM ${UserStats.TABLE_NAME}")
fun getStats() :List<UserStats> // this list should always contain one element, if not, throw error or somethin'
} | 7 | Kotlin | 0 | 0 | 7af58f0d442d906b25970a65dd5fed7411ca79f0 | 847 | TomaRamosUandes_android | MIT License |
io/okio/src/main/kotlin/io/bluetape4k/okio/base64/AbstractBase64Sink.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.okio.base64
import okio.Buffer
import okio.ByteString
import okio.ForwardingSink
import okio.Sink
/**
* 데이터를 Base64로 인코딩하여 [Sink]에 쓰는 [Sink] 구현체.
* NOTE: Apache Commons의 Base64 인코딩은 okio의 Base64 인코딩과 다르다. (특히 한글의 경우)
*
* ```
* val output = Buffer()
* val sink = createSink(output) // Base64Sink(output) or ApacheBase64Sink(output)
*
* val expected = faker.lorem().paragraph()
* log.debug { "Plain string: $expected" }
*
* val source = bufferOf(expected)
* sink.write(source, source.size)
*
* val base64Encoded = output.readUtf8() // base64 encoded string
* ```
*
* @see ApacheBase64Sink
* @see ApacheBase64Source
* @see Base64Sink
* @see Base64Source
*/
abstract class AbstractBase64Sink(delegate: Sink): ForwardingSink(delegate) {
protected abstract fun getEncodedBuffer(plainByteString: ByteString): Buffer
override fun write(source: Buffer, byteCount: Long) {
val bytesToRead = byteCount.coerceAtMost(source.size)
val readByteString = source.readByteString(bytesToRead)
// Base64 encode
val encodedSink = getEncodedBuffer(readByteString)
super.write(encodedSink, encodedSink.size)
}
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 1,191 | bluetape4k | MIT License |
integrations/dd-sdk-android-compose/src/main/kotlin/com/datadog/android/compose/internal/ComposeNavigationObserver.kt | DataDog | 219,536,756 | false | {"Kotlin": 9121111, "Java": 1179237, "C": 79303, "Shell": 63055, "C++": 32351, "Python": 5556, "CMake": 2000} | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.compose.internal
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import com.datadog.android.rum.RumMonitor
import com.datadog.android.rum.tracking.AcceptAllNavDestinations
import com.datadog.android.rum.tracking.ComponentPredicate
import com.datadog.android.rum.tracking.convertToRumViewAttributes
internal class ComposeNavigationObserver(
private val trackArguments: Boolean = true,
private val destinationPredicate: ComponentPredicate<NavDestination> =
AcceptAllNavDestinations(),
private val navController: NavController,
private val rumMonitor: RumMonitor
) : LifecycleEventObserver, NavController.OnDestinationChangedListener {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_RESUME) {
// once listener is added, it will receive current destination if available
navController.addOnDestinationChangedListener(this)
} else if (event == Lifecycle.Event.ON_PAUSE) {
navController.currentDestination?.route?.let {
rumMonitor.stopView(it)
}
navController.removeOnDestinationChangedListener(this)
}
}
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
if (destinationPredicate.accept(destination)) {
destination.route?.let {
startView(destination, it, arguments)
}
}
}
internal fun onDispose() {
// just a safe-guard if ON_PAUSE wasn't called
navController.removeOnDestinationChangedListener(this)
}
private fun startView(
navDestination: NavDestination,
route: String,
arguments: Bundle?
) {
val viewName = destinationPredicate.getViewName(navDestination) ?: route
rumMonitor.startView(
key = route,
name = viewName,
attributes = if (trackArguments) {
arguments.convertToRumViewAttributes()
} else {
emptyMap()
}
)
}
}
| 44 | Kotlin | 60 | 151 | d7e640cf6440ab150c2bbfbac261e09b27e258f4 | 2,615 | dd-sdk-android | Apache License 2.0 |
client/android/div-lottie/src/main/java/com/yandex/div/lottie/DivLottieUtils.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.lottie
import android.view.View
import androidx.core.view.ViewCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
internal fun View.launchOnAttachedToWindow(
action: suspend CoroutineScope.() -> Unit
) {
val listener = ScopedOnAttachStateChangeListener(action)
if (ViewCompat.isAttachedToWindow(this)) {
listener.performActionInScope()
}
addOnAttachStateChangeListener(listener)
setTag(R.id.lottie_on_attach_to_window_listener, listener)
}
internal fun View.clearOnAttachedToWindowScope() {
val listener = getTag(R.id.lottie_on_attach_to_window_listener) as? ScopedOnAttachStateChangeListener
if (listener != null) {
listener.clearScope()
removeOnAttachStateChangeListener(listener)
}
}
private class ScopedOnAttachStateChangeListener(
val action: suspend CoroutineScope.() -> Unit
) : View.OnAttachStateChangeListener {
private var attachScope: CoroutineScope? = null
override fun onViewAttachedToWindow(view: View) {
performActionInScope()
}
override fun onViewDetachedFromWindow(view: View) {
clearScope()
}
fun performActionInScope() {
val scope = attachScope ?: CoroutineScope(Dispatchers.Unconfined)
scope.launch {
action()
}
attachScope = scope
}
fun clearScope() {
attachScope?.cancel()
attachScope = null
}
}
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 1,526 | divkit | Apache License 2.0 |
app/src/main/kotlin/me/thanel/quickimage/db/uploadhistory/UploadHistoryProvider.kt | Tunous | 88,639,812 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 28, "Kotlin": 20, "Java": 1} | package me.thanel.quickimage.db.uploadhistory
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.provider.BaseColumns
import android.util.Log
import me.thanel.quickimage.db.DbHelper
class UploadHistoryProvider : ContentProvider() {
private lateinit var dbHelper: DbHelper
override fun onCreate(): Boolean {
dbHelper = DbHelper(context)
return true
}
override fun getType(uri: Uri) = null
override fun insert(uri: Uri, values: ContentValues?): Uri? {
if (uriMatcher.match(uri) != MATCH_ALL) return null
val db = dbHelper.writableDatabase
val rowId = db.insert(UploadHistoryTable.TABLE_NAME, null, values)
if (rowId <= 0) return null
context?.contentResolver?.notifyChange(CONTENT_URI, null)
return ContentUris.withAppendedId(CONTENT_URI, rowId)
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
val queryBuilder = SQLiteQueryBuilder()
val match = uriMatcher.match(uri)
queryBuilder.tables = UploadHistoryTable.TABLE_NAME
when (match) {
MATCH_ALL -> {
// no-op
}
MATCH_ID -> {
queryBuilder.appendWhere("${BaseColumns._ID} = ${uri.lastPathSegment}")
}
else -> {
Log.e(UploadHistoryProvider::class.java.simpleName, "query: invalid request: $uri")
return null
}
}
val sort = sortOrder ?: "${UploadHistoryTable.COLUMN_TIMESTAMP} desc"
val db = dbHelper.readableDatabase
val cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sort)
cursor?.setNotificationUri(context.contentResolver, uri)
return cursor
}
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<out String>?): Int {
val match = uriMatcher.match(uri)
val db = dbHelper.writableDatabase
val count = when (match) {
MATCH_ALL -> {
db.update(UploadHistoryTable.TABLE_NAME, values, selection, selectionArgs)
}
MATCH_ID -> {
if (selection != null && selectionArgs != null) {
throw UnsupportedOperationException(
"Cannot update URI $uri with a where clause")
}
db.update(UploadHistoryTable.TABLE_NAME, values, "${BaseColumns._ID} = ?",
arrayOf(uri.lastPathSegment))
}
else -> {
throw UnsupportedOperationException("Cannot update URI: $uri")
}
}
if (count > 0) {
context?.contentResolver?.notifyChange(CONTENT_URI, null)
}
return count
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
val match = uriMatcher.match(uri)
val db = dbHelper.writableDatabase
val count = when (match) {
MATCH_ALL -> {
db.delete(UploadHistoryTable.TABLE_NAME, selection, selectionArgs)
}
MATCH_ID -> {
if (selection != null && selectionArgs != null) {
throw UnsupportedOperationException(
"Cannot delete URI $uri with a where clause")
}
db.delete(UploadHistoryTable.TABLE_NAME, "${BaseColumns._ID} = ?",
arrayOf(uri.lastPathSegment))
}
else -> {
throw UnsupportedOperationException("Cannot delete URI: $uri")
}
}
if (count > 0) {
context?.contentResolver?.notifyChange(CONTENT_URI, null)
}
return count
}
companion object {
private const val MATCH_ALL = 0
private const val MATCH_ID = 1
val CONTENT_URI: Uri = Uri.parse("content://me.thanel.quickimage/history")
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI("me.thanel.quickimage", "history", MATCH_ALL)
addURI("me.thanel.quickimage", "history/#", MATCH_ID)
}
}
}
| 1 | null | 1 | 1 | 69a349a2726d56e1a881e62d43a0e7cf5e36f104 | 4,526 | QuickImage | Apache License 2.0 |
app/src/main/kotlin/me/thanel/quickimage/db/uploadhistory/UploadHistoryProvider.kt | Tunous | 88,639,812 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 28, "Kotlin": 20, "Java": 1} | package me.thanel.quickimage.db.uploadhistory
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.provider.BaseColumns
import android.util.Log
import me.thanel.quickimage.db.DbHelper
class UploadHistoryProvider : ContentProvider() {
private lateinit var dbHelper: DbHelper
override fun onCreate(): Boolean {
dbHelper = DbHelper(context)
return true
}
override fun getType(uri: Uri) = null
override fun insert(uri: Uri, values: ContentValues?): Uri? {
if (uriMatcher.match(uri) != MATCH_ALL) return null
val db = dbHelper.writableDatabase
val rowId = db.insert(UploadHistoryTable.TABLE_NAME, null, values)
if (rowId <= 0) return null
context?.contentResolver?.notifyChange(CONTENT_URI, null)
return ContentUris.withAppendedId(CONTENT_URI, rowId)
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
val queryBuilder = SQLiteQueryBuilder()
val match = uriMatcher.match(uri)
queryBuilder.tables = UploadHistoryTable.TABLE_NAME
when (match) {
MATCH_ALL -> {
// no-op
}
MATCH_ID -> {
queryBuilder.appendWhere("${BaseColumns._ID} = ${uri.lastPathSegment}")
}
else -> {
Log.e(UploadHistoryProvider::class.java.simpleName, "query: invalid request: $uri")
return null
}
}
val sort = sortOrder ?: "${UploadHistoryTable.COLUMN_TIMESTAMP} desc"
val db = dbHelper.readableDatabase
val cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sort)
cursor?.setNotificationUri(context.contentResolver, uri)
return cursor
}
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<out String>?): Int {
val match = uriMatcher.match(uri)
val db = dbHelper.writableDatabase
val count = when (match) {
MATCH_ALL -> {
db.update(UploadHistoryTable.TABLE_NAME, values, selection, selectionArgs)
}
MATCH_ID -> {
if (selection != null && selectionArgs != null) {
throw UnsupportedOperationException(
"Cannot update URI $uri with a where clause")
}
db.update(UploadHistoryTable.TABLE_NAME, values, "${BaseColumns._ID} = ?",
arrayOf(uri.lastPathSegment))
}
else -> {
throw UnsupportedOperationException("Cannot update URI: $uri")
}
}
if (count > 0) {
context?.contentResolver?.notifyChange(CONTENT_URI, null)
}
return count
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
val match = uriMatcher.match(uri)
val db = dbHelper.writableDatabase
val count = when (match) {
MATCH_ALL -> {
db.delete(UploadHistoryTable.TABLE_NAME, selection, selectionArgs)
}
MATCH_ID -> {
if (selection != null && selectionArgs != null) {
throw UnsupportedOperationException(
"Cannot delete URI $uri with a where clause")
}
db.delete(UploadHistoryTable.TABLE_NAME, "${BaseColumns._ID} = ?",
arrayOf(uri.lastPathSegment))
}
else -> {
throw UnsupportedOperationException("Cannot delete URI: $uri")
}
}
if (count > 0) {
context?.contentResolver?.notifyChange(CONTENT_URI, null)
}
return count
}
companion object {
private const val MATCH_ALL = 0
private const val MATCH_ID = 1
val CONTENT_URI: Uri = Uri.parse("content://me.thanel.quickimage/history")
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI("me.thanel.quickimage", "history", MATCH_ALL)
addURI("me.thanel.quickimage", "history/#", MATCH_ID)
}
}
}
| 1 | null | 1 | 1 | 69a349a2726d56e1a881e62d43a0e7cf5e36f104 | 4,526 | QuickImage | Apache License 2.0 |
android/src/main/java/com/mcal/android/MainActivity.kt | TimScriptov | 654,850,391 | false | null | package com.mcal.android
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.MaterialTheme
import com.mcal.common.App
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
App()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
if (Environment.isExternalStorageManager()) {
//todo when permission is granted
} else {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
val uri = Uri.fromParts("package", packageName, null)
intent.setData(uri)
startActivity(intent)
}
}
} | 0 | Kotlin | 1 | 4 | b0e77cef85de9fdc308ecfa28170edb3f19f3b4b | 1,043 | DexEditor | Apache License 2.0 |
common/src/test/kotlin/studio/forface/ktmdb/ProjectTests.kt | 4face-studi0 | 154,903,789 | false | null | package studio.forface.ktmdb
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JSON
import studio.forface.ktmdb.entities.GenrePojo
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* @author <NAME>.
*
* A common Test class for the whole Project.
* We use this for run some basic tests.
*/
class ProjectTests {
private val genre = GenrePojo(0, "horror" )
@Test
fun testingMultiplatformCode_runsCorrectly() {
assertEquals("horror", genre.name )
}
@Test
fun testingMultiplatformCode_canSerialize() {
val s = JSON.stringify( ASimpleClass(1 ) )
println( s )
}
}
@Serializable
data class ASimpleClass( @SerialName( "a" ) val a: Int ) | 0 | Kotlin | 0 | 3 | bfcba0cc37a22aef54ecb3f65334dcceb84dbc4f | 766 | KTmdb | Apache License 2.0 |
data/src/main/java/com/ocakmali/data/entity/GrinderFtsEntity.kt | ocakmali | 155,255,987 | false | null | package com.ocakmali.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Fts4
import com.ocakmali.data.db.GrinderConstants.COLUMN_NAME
import com.ocakmali.data.db.GrinderConstants.FTS_TABLE_NAME
@Fts4(contentEntity = GrinderEntity::class)
@Entity(tableName = FTS_TABLE_NAME)
data class GrinderFtsEntity(@ColumnInfo(name = COLUMN_NAME) val name: String) | 0 | Kotlin | 0 | 1 | cde32648afdab7c6f2dbc65ba8be7a2458ea8c1a | 395 | BrewWay | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.