path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/kombinator/symbols/Repetition.kt
|
aeckar
| 793,882,854 | false |
{"Kotlin": 76031}
|
package kombinator.symbols
import kombinator.ContextFreeToken
import kombinator.charstreams.LexicalAnalyzerState
import kombinator.util.debug
import kombinator.util.debugStatus
import kombinator.util.debugWithIndent
/**
* Symbol created by use of the '+' operator.
*/
internal class Repetition(val inner: Symbol) : Symbol() {
override fun attemptMatch(lexerState: LexicalAnalyzerState): ContextFreeToken {
debugWithIndent {
+"-> Repetition (${this@Repetition})"
+"Attempting match to inner... [x1]"
}
val children = mutableListOf<ContextFreeToken>()
var subMatch = inner.match(lexerState)
while (subMatch !== ContextFreeToken.NOTHING) {
children += subMatch
if (subMatch.substring.isEmpty()) {
break
}
debug { +"Attempting inner.match()... [x${children.size + 1}]" }
subMatch = inner.match(lexerState)
}
return tokenOrNothingAndCacheFail(lexerState, children.isNotEmpty(), children).debugStatus()
}
override fun toDebugString() = "${inner.toIntermediateString()}+"
}
| 0 |
Kotlin
|
0
| 0 |
47c7a9424b0ab77d5d2301df354c06d3df643890
| 1,139 |
kombinator
|
MIT License
|
app/src/main/java/com/bignerdranch/android/crime/CrimeListFragment.kt
|
jimmyboy8930
| 865,681,749 | false |
{"Kotlin": 22808}
|
package com.bignerdranch.android.crime
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.bignerdranch.android.crime.databinding.FragmentCrimeListBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.Date
import java.util.UUID
private const val TAG="CrimeListFragment"
class CrimeListFragment : Fragment (){
private val crimeListViewModel : CrimeListViewModel by viewModels()
private var _binding: FragmentCrimeListBinding? = null
private val binding
get()= checkNotNull(_binding){
"error: can we see the view?"
}
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// Log.d(TAG, "Total crimes: ${crimeListViewModel.crimes.size}")
// }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentCrimeListBinding.inflate(layoutInflater, container, false)
binding.crimeRecyclerView.layoutManager = LinearLayoutManager(context)
// val crimes = crimeListViewModel.crimes
// val adapter = CrimeListAdapter(crimes)
// binding.crimeRecyclerView.adapter = adapter
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val menuHost : MenuHost = requireActivity()
menuHost.addMenuProvider(object: MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.fragment_crime_list, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId){
R.id.new_crime -> {
showNewCrime()
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED){
//val crimes = crimeListViewModel.loadCrimes()
crimeListViewModel.crimes.collect(){ crimes ->
binding.crimeRecyclerView.adapter = CrimeListAdapter(crimes){ crimeId ->
findNavController().navigate(
CrimeListFragmentDirections.showCrimeDetail(crimeId)
//R.id.show_crime_detail
)
}
}
}
}
}
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// //setHasOptionsMenu(true)
//
// }
// override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// //super.onCreateOptionsMenu(menu, inflater)
// inflater.inflate(R.menu.fragment_crime_list, menu)
// }
//
//
//
// override fun onOptionsItemSelected(item: MenuItem): Boolean {
// return when(item.itemId){
// R.id.new_crime -> {
// showNewCrime()
// true
// }
// else -> super.onContextItemSelected(item)
// }
// }
private fun showNewCrime(){
viewLifecycleOwner.lifecycleScope.launch {
val newCrime = Crime(
id = UUID.randomUUID(),
title="",
date = Date(),
isSolved = false
)
crimeListViewModel.addCrime(newCrime)
findNavController().navigate(
CrimeListFragmentDirections.showCrimeDetail(newCrime.id)
)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 |
Kotlin
|
0
| 0 |
59707a673981740cfa2015254e8a3633fcefe2fd
| 4,466 |
crime-app
|
MIT License
|
jetpack Compose/2.Text Styling/app/src/main/java/com/mimo2k/composetextstyle/MainActivity.kt
|
Mimo2k
| 423,546,122 | false |
{"Kotlin": 88170}
|
package com.mimo2k.composetextstyle
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.mimo2k.composetextstyle.ui.theme.ComposeTextStyleTheme
import java.time.format.TextStyle
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val fontFamily = FontFamily(
Font(R.font.ubuntu_light, FontWeight.Light), // assigning root id to Font fun
Font(R.font.ubuntu_medium, FontWeight.Medium),
Font(R.font.ubuntu_bold, FontWeight.Bold),
Font(R.font.ubuntu_regular, FontWeight.Normal)
)
setContent {
Box(modifier = Modifier
.fillMaxSize() // will occupy entire screen
.background(Color(0xff101010))) // hexadecimal color
{
Text(
// text = "Jetpack Compose", // text
// annotated String
text = buildAnnotatedString {
withStyle(
style = SpanStyle(
color = Color.Red,
fontSize = 50.sp
)
){
append("J")
}
append("etpack ")
withStyle(
style = SpanStyle(
color = Color.Red,
fontSize = 50.sp
)
){
append("C")
}
append("ompose")
},
color = Color.White, // color of text
fontSize = 30.sp, //font size of text
fontFamily = fontFamily, // assigning font
fontWeight = FontWeight.Bold, // default weight
textAlign = TextAlign.Center, // aligning text
fontStyle = FontStyle.Italic, // text Style
// textDecoration = TextDecoration.Underline // underline
)
}
}
}
}
| 0 |
Kotlin
|
6
| 16 |
9185a7b44d3c8fb38c8a1614c91b4cfc9439071b
| 3,202 |
Android-Development
|
MIT License
|
jpa/src/main/kotlin/me/jiangcai/common/jpa/CriteriaBuilder.kt
|
mingshz
| 166,675,112 | false | null |
package me.jiangcai.common.jpa
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.Expression
fun CriteriaBuilder.groupConcat(stringExpr: Expression<String>): Expression<out String> {
return function("group_concat", String::class.java, stringExpr)
}
| 1 |
Kotlin
|
1
| 1 |
8c9566723e6fe39c4fadc1262212a9e4aa3fd660
| 289 |
library
|
MIT License
|
src/main/kotlin/com/between_freedom_and_space/mono_backend/profiles/api/mappers/BaseProfileModelToProfileModelMapper.kt
|
Between-Freedom-and-Space
| 453,797,438 | false |
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
|
package com.between_freedom_and_space.mono_backend.profiles.api.mappers
import com.between_freedom_and_space.mono_backend.common.components.ModelMapper
import com.between_freedom_and_space.mono_backend.profiles.api.models.ProfileModel
import com.between_freedom_and_space.mono_backend.profiles.services.models.BaseProfileModel
class BaseProfileModelToProfileModelMapper: ModelMapper<BaseProfileModel, ProfileModel> {
override fun map(original: BaseProfileModel): ProfileModel {
return ProfileModel(
id = original.id,
nickName = original.nickName,
nameAlias = original.nameAlias,
description = original.description,
iconId = original.iconId,
location = original.location,
createdDate = original.createdDate,
updatedDate = original.updatedDate,
)
}
}
| 0 |
Kotlin
|
0
| 1 |
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
| 871 |
Mono-Backend
|
Apache License 2.0
|
chi-compiler/src/main/kotlin/gh/marad/chi/core/analyzer/TypeChecking.kt
|
marad
| 424,295,144 | false |
{"Kotlin": 316466, "Java": 241258, "ANTLR": 7061, "Batchfile": 2689}
|
package gh.marad.chi.core.analyzer
import gh.marad.chi.core.*
import gh.marad.chi.core.parser.ChiSource
import org.jgrapht.Graph
import org.jgrapht.alg.shortestpath.DijkstraShortestPath
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
fun checkModuleAndPackageNames(expr: Expression, messages: MutableList<Message>) {
if (expr is Package) {
if (expr.moduleName.isEmpty()) {
messages.add(InvalidModuleName(expr.moduleName, expr.sourceSection.toCodePoint()))
}
if (expr.packageName.isEmpty()) {
messages.add(InvalidPackageName(expr.packageName, expr.sourceSection.toCodePoint()))
}
}
}
fun checkImports(expr: Expression, messages: MutableList<Message>) {
if (expr is Import) {
if (expr.moduleName.isEmpty()) {
messages.add(InvalidModuleName(expr.moduleName, expr.sourceSection.toCodePoint()))
}
if (expr.packageName.isEmpty()) {
messages.add(InvalidPackageName(expr.packageName, expr.sourceSection.toCodePoint()))
}
if (!expr.withinSameModule) {
expr.entries.forEach {
if (it.isPublic == false && !it.isTypeImport) {
messages.add(ImportInternal(it.name, it.sourceSection.toCodePoint()))
}
}
}
}
}
fun checkThatTypesContainAccessedFieldsAndFieldIsAccessible(expr: Expression, messages: MutableList<Message>) {
if (expr is FieldAccess && expr.receiver.type.isCompositeType()) {
val type = expr.receiver.type as CompositeType
val hasMember = type.hasMember(expr.fieldName)
if (!hasMember) {
messages.add(MemberDoesNotExist(expr.receiver.type, expr.fieldName, expr.memberSection.toCodePoint()))
}
if (!expr.typeIsModuleLocal && !type.isPublic(expr.fieldName)) {
messages.add(CannotAccessInternalName(expr.fieldName, expr.memberSection.toCodePoint()))
}
}
}
fun checkThatVariableIsDefinedAndAccessible(expr: Expression, messages: MutableList<Message>) {
if (expr is VariableAccess) {
val symbolInfo = expr.definitionScope.getSymbol(expr.name)
if (symbolInfo != null) {
if (!expr.isModuleLocal && !symbolInfo.public) {
messages.add(CannotAccessInternalName(expr.name, expr.sourceSection.toCodePoint()))
}
} else {
messages.add(UnrecognizedName(expr.name, expr.sourceSection.toCodePoint()))
}
}
}
fun checkThatAssignmentDoesNotChangeImmutableValue(expr: Expression, messages: MutableList<Message>) {
if (expr is Assignment) {
val symbol = expr.definitionScope.getSymbol(expr.name)
if (symbol?.mutable == false) {
messages.add(CannotChangeImmutableVariable(expr.sourceSection.toCodePoint()))
}
}
}
fun checkThatFunctionHasAReturnValue(expr: Expression, messages: MutableList<Message>) {
if (expr is Fn) {
val expected = expr.returnType
if (expr.body.body.isEmpty() && expected != Type.unit) {
messages.add(MissingReturnValue(expected, expr.body.sourceSection.toCodePoint()))
}
}
}
fun checkThatFunctionCallsReceiveAppropriateCountOfArguments(expr: Expression, messages: MutableList<Message>) {
if (expr is FnCall) {
val valueType = expr.function.type
if (valueType is FnType &&
valueType.paramTypes.count() != expr.parameters.count()
) {
messages.add(
FunctionArityError(
valueType.paramTypes.count(),
expr.parameters.count(),
expr.sourceSection.toCodePoint()
)
)
}
}
}
fun checkForOverloadedFunctionCallCandidate(expr: Expression, messages: MutableList<Message>) {
if (expr is FnCall) {
val valueType = expr.function.type
if (valueType is OverloadedFnType) {
val argumentTypes = expr.parameters.map { it.type }
if (valueType.getType(argumentTypes) == null) {
messages.add(
NoCandidatesForFunction(
argumentTypes,
valueType.types.map { it.fnType }.toSet(),
expr.sourceSection.toCodePoint()
)
)
}
}
}
}
fun checkThatFunctionCallsActuallyCallFunctions(expr: Expression, messages: MutableList<Message>) {
if (expr is FnCall) {
val valueType = expr.function.type
if (valueType !is FnType && valueType !is OverloadedFnType) {
messages.add(NotAFunction(expr.sourceSection.toCodePoint()))
}
}
}
fun checkThatExpressionTypeIsDefined(expr: Expression, messages: MutableList<Message>) {
if (expr.type == Type.undefined && messages.isEmpty()) {
messages.add(TypeInferenceFailed(expr.sourceSection.toCodePoint()))
}
}
fun checkGenericTypes(expr: Expression, messages: MutableList<Message>) {
if (expr is FnCall && expr.function.type is FnType && expr.callTypeParameters.isNotEmpty()) {
val fnType = expr.function.type as FnType
// check that all generic type parameters were passed
if (fnType.genericTypeParameters.size != expr.callTypeParameters.size) {
messages.add(
GenericTypeArityError(
fnType.genericTypeParameters.size,
expr.callTypeParameters.size,
expr.function.sourceSection.toCodePoint()
)
)
}
// check that parameters passed to the function have the same type that is declared in generic type parameters
val typeParameterNameToParamIndex =
fnType.paramTypes.foldIndexed(mutableListOf<Pair<String, Int>>()) { paramIndex, acc, type ->
if (type is GenericTypeParameter) {
acc.add(type.typeParameterName to paramIndex)
}
acc
}.toMap()
fnType.genericTypeParameters.forEachIndexed { genericTypeParameterIndex, genericTypeParameter ->
val genericParamIndex = typeParameterNameToParamIndex[genericTypeParameter.typeParameterName]
val genericParam = genericParamIndex?.let { expr.parameters[genericParamIndex] }
?: return@forEachIndexed
val expectedType = expr.callTypeParameters[genericTypeParameterIndex]
val actualType = genericParam.type
if (!typesMatch(expectedType, actualType)) {
messages.add(
TypeMismatch(
expectedType,
actualType,
expr.parameters[genericParamIndex].sourceSection.toCodePoint()
)
)
}
}
}
}
fun typesMatch(
expected: Type,
actual: Type,
): Boolean {
if (expected == Type.any) {
// accept any type
return true
}
return expected == actual || isSubType(actual, expected) || matchStructurally(
expected,
actual
)
}
fun matchStructurally(expected: Type, actual: Type): Boolean {
val expectedSubtypes = expected.getAllSubtypes()
val actualSubtypes = actual.getAllSubtypes()
return expected.javaClass == actual.javaClass &&
expectedSubtypes.size == actualSubtypes.size &&
expectedSubtypes.zip(actualSubtypes)
.all { typesMatch(it.first, it.second) }
}
fun checkTypes(expr: Expression, messages: MutableList<Message>) {
fun checkTypeMatches(
expected: Type,
actual: Type,
sourceSection: ChiSource.Section?,
) {
if (!typesMatch(expected, actual)) {
messages.add(TypeMismatch(expected, actual, sourceSection.toCodePoint()))
}
}
fun checkPrefixOp(op: PrefixOp) {
when (op.op) {
"!" -> if (op.expr.type != Type.bool) {
messages.add(TypeMismatch(Type.bool, op.expr.type, op.sourceSection.toCodePoint()))
}
else -> TODO("Unimplemented prefix operator")
}
}
fun checkAssignment(expr: Assignment) {
val scope = expr.definitionScope
val expectedType = scope.getSymbolType(expr.name)
if (expectedType != null) {
checkTypeMatches(expectedType, expr.value.type, expr.sourceSection)
}
}
fun checkNameDeclaration(expr: NameDeclaration) {
if (expr.expectedType != null) {
checkTypeMatches(expr.expectedType, expr.value.type, expr.value.sourceSection)
}
}
fun checkFn(expr: Fn) {
val expected = expr.returnType
if (expr.returnType == Type.unit) {
return
}
if (expr.body.body.isNotEmpty()) {
val actual = expr.body.type
val sourceSection = expr.body.body.last().sourceSection
checkTypeMatches(expected, actual, sourceSection)
}
}
fun checkFnCall(expr: FnCall) {
val fnType = expr.function.type
if (fnType is FnType) {
val genericParamToTypeFromPassedParameters =
matchCallTypes(
fnType.paramTypes,
expr.parameters.map { it.type })
fnType.paramTypes.zip(expr.parameters) { definition, passed ->
val expectedType = definition.construct(genericParamToTypeFromPassedParameters)
val actualType = passed.type
if (expectedType is FnType && actualType is FnType
&& expectedType.returnType == Type.unit
&& actualType.paramTypes.size == expectedType.paramTypes.size
) {
// if types are FnType and expected FnType returns unit - then check only arguments - return value doesn't matter
val allArgumentsMatch =
expectedType.paramTypes.zip(actualType.paramTypes).all { (expected, actual) ->
typesMatch(expected, actual)
}
if (!allArgumentsMatch) {
messages.add(TypeMismatch(expectedType, actualType, passed.sourceSection.toCodePoint()))
}
} else {
checkTypeMatches(
expectedType,
actualType,
passed.sourceSection
)
}
}
if (expr.callTypeParameters.isNotEmpty()) {
val genericParamToTypeFromDefinedParameters =
matchTypeParameters(fnType.genericTypeParameters, expr.callTypeParameters)
fnType.genericTypeParameters.forEach { param ->
val expected = genericParamToTypeFromDefinedParameters[param]!!
val actual = genericParamToTypeFromPassedParameters[param]
if (actual != null && !typesMatch(expected, actual)) {
messages.add(GenericTypeMismatch(expected, actual, param, expr.sourceSection.toCodePoint()))
}
}
}
}
}
fun checkFieldAssignment(expr: FieldAssignment) {
val memberType = (expr.receiver.type as CompositeType).memberType(expr.fieldName)!!
val assignedType = expr.value.type
checkTypeMatches(expected = memberType, actual = assignedType, expr.value.sourceSection)
}
fun checkIfElseType(expr: IfElse) {
val conditionType = expr.condition.type
if (conditionType != Type.bool) {
messages.add(TypeMismatch(Type.bool, conditionType, expr.condition.sourceSection.toCodePoint()))
}
}
fun checkInfixOp(expr: InfixOp) {
val leftType = expr.left.type
val rightType = expr.right.type
if (leftType != rightType) {
messages.add(TypeMismatch(expected = leftType, rightType, expr.right.sourceSection.toCodePoint()))
} else if (expr.op in arrayOf("|", "&", "<<", ">>") && !leftType.isNumber()) {
messages.add(TypeMismatch(expected = Type.intType, leftType, expr.left.sourceSection.toCodePoint()))
} else if (expr.op in arrayOf("|", "&", "<<", ">>") && !rightType.isNumber()) {
messages.add(TypeMismatch(expected = Type.intType, rightType, expr.right.sourceSection.toCodePoint()))
}
}
fun checkCast(expr: Cast) {
}
fun checkWhileLoop(expr: WhileLoop) {
checkTypeMatches(Type.bool, expr.condition.type, expr.sourceSection)
}
fun checkIndexOperator(expr: IndexOperator) {
if (expr.variable.type.isIndexable()) {
checkTypeMatches(expr.variable.type.expectedIndexType(), expr.index.type, expr.index.sourceSection)
} else {
messages.add(TypeIsNotIndexable(expr.variable.type, expr.variable.sourceSection.toCodePoint()))
}
}
fun checkIndexedAssignment(expr: IndexedAssignment) {
if (expr.variable.type.isIndexable()) {
checkTypeMatches(expr.variable.type.expectedIndexType(), expr.index.type, expr.index.sourceSection)
checkTypeMatches(expr.variable.type.indexedElementType(), expr.value.type, expr.value.sourceSection)
} else {
messages.add(TypeIsNotIndexable(expr.variable.type, expr.variable.sourceSection.toCodePoint()))
}
}
fun checkIs(expr: Is) {
}
@Suppress("UNUSED_VARIABLE")
val ignored: Any = when (expr) {
is Program -> {} // nothing to check
is Package -> {} // nothing to check
is Import -> {} // nothing to check
is DefineVariantType -> {} // nothing to check
is Assignment -> checkAssignment(expr)
is NameDeclaration -> checkNameDeclaration(expr)
is Block -> {} // nothing to check
is Fn -> checkFn(expr)
is FnCall -> checkFnCall(expr)
is Atom -> {} // nothing to check
is VariableAccess -> {} // nothing to check
is FieldAccess -> {} // nothing to check
is FieldAssignment -> checkFieldAssignment(expr)
is IfElse -> checkIfElseType(expr)
is InfixOp -> checkInfixOp(expr)
is PrefixOp -> checkPrefixOp(expr)
is Cast -> checkCast(expr)
is Group -> {} // nothing to check
is WhileLoop -> checkWhileLoop(expr)
is IndexOperator -> checkIndexOperator(expr)
is IndexedAssignment -> checkIndexedAssignment(expr)
is Is -> checkIs(expr)
is Break -> {} // nothing to check
is Continue -> {} // nothing to check
is EffectDefinition -> {} // TODO: maybe something?
is Handle -> {} // TODO: check that effect branches return the same type that handle expects
is InterpolatedString -> {} // nothing to check
}
}
private var typeGraph: Graph<String, DefaultEdge> =
DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge::class.java).also {
it.addVertex("unit")
it.addVertex("int")
it.addVertex("float")
it.addEdge("int", "float")
}
fun isSubType(subtype: Type, supertype: Type): Boolean {
return if (subtype != supertype && typeGraph.containsVertex(subtype.name) && typeGraph.containsVertex(supertype.name)) {
val dijkstraAlgo = DijkstraShortestPath(typeGraph)
val path = dijkstraAlgo.getPath(subtype.name, supertype.name)
path != null
} else {
false
}
}
| 26 |
Kotlin
|
0
| 11 |
d93f2df6472476a0de365edc5f146826ce608c58
| 15,535 |
chi-compiler-kotlin
|
MIT License
|
app/src/main/java/com/example/foodies/ui/fragments/search/SearchFragment.kt
|
MathRoda
| 503,037,547 | false |
{"Kotlin": 47026}
|
package com.example.foodies.ui.fragments.search
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import coil.load
import com.example.foodies.databinding.FragmentSearchBinding
import com.example.foodies.ui.activities.MealActivity
import com.example.foodies.ui.fragments.home.HomeFragment
import com.example.foodies.viewmodel.SearchViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SearchFragment : Fragment() {
private lateinit var binding: FragmentSearchBinding
private val viewModel: SearchViewModel by viewModels()
private var mealId = ""
private var mealStr = ""
private var mealThumb = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentSearchBinding.inflate(inflater, container, false)
observeSearched()
setOnMealCardClick()
return binding.root
}
private fun setOnMealCardClick() {
binding.searchedMealCard.setOnClickListener {
val intent = Intent(activity, MealActivity::class.java)
intent.putExtra(HomeFragment.MEAL_ID, mealId)
intent.putExtra(HomeFragment.MEAL_NAME, mealStr)
intent.putExtra(HomeFragment.MEAL_THUMB, mealThumb)
startActivity(intent)
}
}
private fun observeSearched() {
binding.icSearch.setOnClickListener {
onSearchClick()
viewModel.searchedMeal.observe(viewLifecycleOwner) {
binding.apply {
imgSearchedMeal.load(it.strMealThumb)
tvSearchedMeal.text = it.strMeal
searchedMealCard.visibility = View.VISIBLE
}
mealId = it.idMeal
mealStr = it.strMeal!!
mealThumb = it.strMealThumb!!
}
}
}
private fun onSearchClick() {
viewModel.getSearchedMeal(binding.edSearch.text.toString(), requireContext())
}
}
| 0 |
Kotlin
|
3
| 6 |
5a758be16627ba16ccbc755445e20e50b090faf5
| 2,248 |
Foodies-App
|
MIT License
|
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/AudienceCategory.kt
|
oapicf
| 489,369,143 | false |
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
|
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import org.openapitools.client.models.AudienceSubcategory
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
*
*
* @param key Interest unique key (same as ID).
* @param name Interest name.
* @param ratio Interest's percent of category's total audience.
* @param index Interest affinity index.
* @param id Interest ID.
* @param subcategories Subcategory interest distribution
*/
data class AudienceCategory (
/* Interest unique key (same as ID). */
@Json(name = "key")
val key: kotlin.String? = null,
/* Interest name. */
@Json(name = "name")
val name: kotlin.String? = null,
/* Interest's percent of category's total audience. */
@Json(name = "ratio")
val ratio: java.math.BigDecimal? = null,
/* Interest affinity index. */
@Json(name = "index")
val index: java.math.BigDecimal? = null,
/* Interest ID. */
@Json(name = "id")
val id: kotlin.String? = null,
/* Subcategory interest distribution */
@Json(name = "subcategories")
val subcategories: kotlin.collections.List<AudienceSubcategory>? = null
)
| 0 |
Java
|
0
| 2 |
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
| 1,426 |
pinterest-sdk
|
MIT License
|
app/src/main/java/com/cyl/musiclake/api/music/netease/NeteaseApiServiceImpl.kt
|
futuristic-fighters
| 190,428,257 | true |
{"Java Properties": 2, "Text": 2, "YAML": 1, "Markdown": 3, "Gradle": 4, "Shell": 1, "Batchfile": 1, "Ignore List": 3, "Proguard": 2, "Java": 166, "XML": 335, "HTML": 1, "JavaScript": 2, "Kotlin": 199, "AIDL": 2}
|
package com.cyl.musiclake.api.music.netease
import com.cyl.musicapi.netease.*
import com.cyl.musiclake.api.music.MusicUtils
import com.cyl.musiclake.api.net.ApiManager
import com.cyl.musiclake.bean.Artist
import com.cyl.musiclake.bean.HotSearchBean
import com.cyl.musiclake.bean.Music
import com.cyl.musiclake.bean.Playlist
import com.cyl.musiclake.common.Constants
import com.cyl.musiclake.utils.SPUtils
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
/**
* Created by D22434 on 2018/1/5.
*/
object NeteaseApiServiceImpl {
private val TAG = "NeteaseApiServiceImpl"
val apiService by lazy { ApiManager.getInstance().create(NeteaseApiService::class.java, SPUtils.getAnyByKey(SPUtils.SP_KEY_NETEASE_API_URL, Constants.BASE_NETEASE_URL)) }
/**
* 获取歌单歌曲
*/
fun getTopArtists(limit: Int, offset: Int): Observable<MutableList<Artist>> {
return apiService.getTopArtists(offset, limit)
.flatMap { it ->
Observable.create(ObservableOnSubscribe<MutableList<Artist>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Artist>()
it.list.artists?.forEach {
val playlist = Artist()
playlist.artistId = it.id.toString()
playlist.name = it.name
playlist.picUrl = it.picUrl
playlist.score = it.score
playlist.musicSize = it.musicSize
playlist.albumSize = it.albumSize
playlist.type = Constants.NETEASE
list.add(playlist)
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
* 获取歌单歌曲数据
*/
fun getTopPlaylists(cat: String, limit: Int): Observable<MutableList<Playlist>> {
return apiService.getTopPlaylist(cat, limit)
.flatMap { it ->
Observable.create(ObservableOnSubscribe<MutableList<Playlist>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Playlist>()
it.playlists?.forEach {
val playlist = Playlist()
playlist.pid = it.id.toString()
playlist.name = it.name
playlist.coverUrl = it.coverImgUrl
playlist.des = it.description
playlist.date = it.createTime
playlist.updateDate = it.updateTime
playlist.playCount = it.playCount.toLong()
playlist.type = Constants.PLAYLIST_WY_ID
list.add(playlist)
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
* 获取歌单歌曲数据
*/
fun getTopPlaylistsHigh(tag: String, limit: Int, before: Long?): Observable<MutableList<Playlist>> {
val map = mutableMapOf<String, Any>()
map["cate"] = tag
map["limit"] = limit
before?.let {
map["before"] = it
}
return apiService.getTopPlaylistHigh(map)
.flatMap {
Observable.create(ObservableOnSubscribe<MutableList<Playlist>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Playlist>()
it.playlists?.forEach {
val playlist = Playlist()
playlist.pid = it.id.toString()
playlist.name = it.name
playlist.coverUrl = it.coverImgUrl
playlist.des = it.description
playlist.date = it.createTime
playlist.updateDate = it.updateTime
playlist.playCount = it.playCount.toLong()
playlist.type = Constants.PLAYLIST_WY_ID
list.add(playlist)
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
* 获取精品歌单歌曲数据
*/
fun getPlaylistDetail(id: String): Observable<Playlist> {
return apiService.getPlaylistDetail(id)
.flatMap {
Observable.create(ObservableOnSubscribe<Playlist> { e ->
try {
if (it.code == 200) {
it.playlist?.let {
val playlist = Playlist()
playlist.pid = it.id.toString()
playlist.name = it.name
playlist.coverUrl = it.coverImgUrl
playlist.des = it.description
playlist.date = it.createTime
playlist.updateDate = it.updateTime
playlist.playCount = it.playCount.toLong()
playlist.type = Constants.PLAYLIST_WY_ID
playlist.musicList = MusicUtils.getNeteaseMusicList(it.tracks)
e.onNext(playlist)
}
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
* 获取推荐mv
*/
fun getNewestMv(limit: Int): Observable<MvInfo> {
return apiService.getNewestMv(limit)
}
/**
* 获取推荐mv
*/
fun getTopMv(limit: Int, offset: Int): Observable<MvInfo> {
return apiService.getTopMv(offset, limit)
}
/**
* 获取mv信息
*/
fun getMvDetailInfo(mvid: String): Observable<MvDetailInfo> {
return apiService.getMvDetailInfo(mvid)
}
/**
* 获取相似mv
*/
fun getSimilarMv(mvid: String): Observable<SimilarMvInfo> {
return apiService.getSimilarMv(mvid)
}
/**
* 获取mv评论
*/
fun getMvComment(mvid: String): Observable<MvComment> {
return apiService.getMvComment(mvid)
}
/**
* 获取热搜
*/
fun getHotSearchInfo(): Observable<MutableList<HotSearchBean>> {
return apiService.getHotSearchInfo()
.flatMap { it ->
Observable.create(ObservableOnSubscribe<MutableList<HotSearchBean>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<HotSearchBean>()
it.result.hots?.forEach {
list.add(HotSearchBean(it.first))
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
* 搜索
*/
fun searchMoreInfo(keywords: String, limit: Int, offset: Int, type: Int): Observable<SearchInfo> {
val url = SPUtils.getAnyByKey(SPUtils.SP_KEY_NETEASE_API_URL, Constants.BASE_NETEASE_URL) + "search?keywords= $keywords&limit=$limit&offset=$offset&type=$type"
// return apiService.searchNetease(url)
// @Query("keywords") keywords: String, @Query("limit") limit: Int, @Query("offset") offset: Int, @Query("type") type: Int
return apiService.searchNetease(url)
}
/**
* 获取风格
*/
fun getCatList(): Observable<CatListBean> {
return apiService.getCatList()
}
/**
* 获取banner
*/
fun getBanners(): Observable<BannerResult> {
return apiService.getBanner()
}
/**
*登录
*/
fun loginPhone(username: String, pwd: String, isEmail: Boolean): Observable<LoginInfo> {
return if (isEmail)
apiService.loginEmail(username, pwd)
else
apiService.loginPhone(username, pwd)
}
fun getLoginStatus(): Observable<LoginInfo> {
return apiService.getLoginStatus()
}
/**
*推荐歌曲
*/
fun recommendSongs(): Observable<MutableList<Music>> {
return apiService.recommendSongs()
.flatMap {
Observable.create(ObservableOnSubscribe<MutableList<Music>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Music>()
list.addAll(MusicUtils.getNeteaseRecommendMusic(it.recommend))
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable(it.msg))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
*推荐歌单
*/
fun recommendPlaylist(): Observable<MutableList<Playlist>> {
return apiService.recommendPlaylist()
.flatMap { it ->
Observable.create(ObservableOnSubscribe<MutableList<Playlist>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Playlist>()
it.recommend?.forEach {
val playlist = Playlist()
playlist.pid = it.id.toString()
playlist.name = it.name
playlist.coverUrl = if (it.coverImgUrl != null) it.coverImgUrl else it.creator.avatarUrl
playlist.des = it.description
playlist.date = it.createTime
playlist.updateDate = it.updateTime
playlist.playCount = it.playCount.toLong()
playlist.type = Constants.PLAYLIST_WY_ID
list.add(playlist)
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable(it.msg))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
/**
*获取用户歌单
*/
fun getUserPlaylist(uid: String): Observable<MutableList<Playlist>> {
return apiService.getUserPlaylist(uid)
.flatMap { it ->
Observable.create(ObservableOnSubscribe<MutableList<Playlist>> { e ->
try {
if (it.code == 200) {
val list = mutableListOf<Playlist>()
it.playlist?.forEach {
val playlist = Playlist()
playlist.pid = it.id.toString()
playlist.name = it.name
playlist.coverUrl = it.coverImgUrl
playlist.des = it.description
playlist.date = it.createTime
playlist.updateDate = it.updateTime
playlist.total = it.trackCount.toLong()
playlist.playCount = it.playCount.toLong()
playlist.type = Constants.PLAYLIST_WY_ID
list.add(playlist)
}
e.onNext(list)
e.onComplete()
} else {
e.onError(Throwable("网络异常"))
}
} catch (ep: Exception) {
e.onError(ep)
}
})
}
}
}
| 0 |
Java
|
0
| 0 |
96e0306d2207ec907e76e2222156b937bf2c848b
| 14,155 |
MusicLake
|
Apache License 2.0
|
src/main/kotlin/com/github/insanusmokrassar/PsychomatrixBase/di/realisations/UseCasesDIImpl.kt
|
InsanusMokrassar
| 147,266,746 | false | null |
package com.github.insanusmokrassar.PsychomatrixBase.di.realisations
import com.github.insanusmokrassar.PsychomatrixBase.di.EntitiesDI
import com.github.insanusmokrassar.PsychomatrixBase.di.UseCasesDI
import com.github.insanusmokrassar.PsychomatrixBase.domain.UseCases.*
import com.github.insanusmokrassar.PsychomatrixBase.domain.interactors.*
open class UseCasesDIImpl(
entitiesDI: EntitiesDI
) : UseCasesDI, EntitiesDI by entitiesDI {
override val calculatePsychomatrixByDateUseCase: CalculatePsychomatrixByDateUseCase by lazy {
CalculatePsychomatrixByDateUseCaseInteractor()
}
override val modifyPsychomatrixUseCase: ModifyPsychomatrixUseCase by lazy {
ModifyPsychomatrixUseCaseInteractor()
}
override val ceilDescriptionUseCase: CeilDescriptionUseCase by lazy {
CeilDescriptionInteractor()
}
}
| 0 |
Kotlin
|
0
| 0 |
ae0ea72f557939714928b829a3c022b4690d050a
| 854 |
PsychomatrixBase
|
Apache License 2.0
|
support-refs_heads_androidx-master-dev-ui.tar/ui-android-text/src/main/java/androidx/text/TextLayout.kt
|
cpinan
| 215,833,397 | false | null |
/*
* Copyright 2018 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 androidx.text
import android.graphics.Canvas
import android.graphics.Path
import android.os.Build
import android.text.Layout
import android.text.Spanned
import android.text.TextDirectionHeuristic
import android.text.TextDirectionHeuristics
import android.text.TextPaint
import android.text.TextUtils
import androidx.annotation.Px
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
import androidx.annotation.VisibleForTesting
import androidx.text.LayoutCompat.ALIGN_CENTER
import androidx.text.LayoutCompat.ALIGN_LEFT
import androidx.text.LayoutCompat.ALIGN_NORMAL
import androidx.text.LayoutCompat.ALIGN_OPPOSITE
import androidx.text.LayoutCompat.ALIGN_RIGHT
import androidx.text.LayoutCompat.BreakStrategy
import androidx.text.LayoutCompat.DEFAULT_ALIGNMENT
import androidx.text.LayoutCompat.DEFAULT_BREAK_STRATEGY
import androidx.text.LayoutCompat.DEFAULT_HYPHENATION_FREQUENCY
import androidx.text.LayoutCompat.DEFAULT_JUSTIFICATION_MODE
import androidx.text.LayoutCompat.DEFAULT_LINESPACING_EXTRA
import androidx.text.LayoutCompat.DEFAULT_LINESPACING_MULTIPLIER
import androidx.text.LayoutCompat.DEFAULT_TEXT_DIRECTION
import androidx.text.LayoutCompat.HyphenationFrequency
import androidx.text.LayoutCompat.JustificationMode
import androidx.text.LayoutCompat.TEXT_DIRECTION_ANY_RTL_LTR
import androidx.text.LayoutCompat.TEXT_DIRECTION_FIRST_STRONG_LTR
import androidx.text.LayoutCompat.TEXT_DIRECTION_FIRST_STRONG_RTL
import androidx.text.LayoutCompat.TEXT_DIRECTION_LOCALE
import androidx.text.LayoutCompat.TEXT_DIRECTION_LTR
import androidx.text.LayoutCompat.TEXT_DIRECTION_RTL
import androidx.text.LayoutCompat.TextDirection
import androidx.text.LayoutCompat.TextLayoutAlignment
import androidx.text.style.BaselineShiftSpan
import kotlin.math.ceil
/**
* Wrapper for Static Text Layout classes.
*
* @param charSequence text to be laid out.
* @param width the maximum width for the text
* @param textPaint base paint used for text layout
* @param alignment text alignment for the text layout. One of [TextLayoutAlignment].
* @param ellipsize whether the text needs to be ellipsized. If the maxLines is set and text
* cannot fit in the provided number of lines.
* @param textDirectionHeuristic the heuristics to be applied while deciding on the text direction.
* @param lineSpacingMultiplier the multiplier to be applied to each line of the text.
* @param lineSpacingExtra the extra height to be added to each line of the text.
* @param includePadding defines whether the extra space to be applied beyond font ascent and
* descent,
* @param maxLines the maximum number of lines to be laid out.
* @param breakStrategy the strategy to be used for line breaking
* @param hyphenationFrequency set the frequency to control the amount of automatic hyphenation
* applied.
* @param justificationMode whether to justify the text.
* @param leftIndents the indents to be applied to the left of the text as pixel values. Each
* element in the array is applied to the corresponding line. For lines past the last element in
* array, the last element repeats.
* @param rightIndents the indents to be applied to the right of the text as pixel values. Each
* element in the array is applied to the corresponding line. For lines past the last element in
* array, the last element repeats.
* @param layoutIntrinsics previously calculated [LayoutIntrinsics] for this text
* @see StaticLayoutCompat
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
class TextLayout constructor(
charSequence: CharSequence,
width: Float = 0.0f,
textPaint: TextPaint,
@TextLayoutAlignment alignment: Int = DEFAULT_ALIGNMENT,
ellipsize: TextUtils.TruncateAt? = null,
@TextDirection textDirectionHeuristic: Int = DEFAULT_TEXT_DIRECTION,
lineSpacingMultiplier: Float = DEFAULT_LINESPACING_MULTIPLIER,
@Px lineSpacingExtra: Float = DEFAULT_LINESPACING_EXTRA,
includePadding: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
@BreakStrategy breakStrategy: Int = DEFAULT_BREAK_STRATEGY,
@HyphenationFrequency hyphenationFrequency: Int = DEFAULT_HYPHENATION_FREQUENCY,
@JustificationMode justificationMode: Int = DEFAULT_JUSTIFICATION_MODE,
leftIndents: IntArray? = null,
rightIndents: IntArray? = null,
val layoutIntrinsics: LayoutIntrinsics = LayoutIntrinsics(
charSequence,
textPaint,
textDirectionHeuristic
)
) {
val maxIntrinsicWidth: Float
get() = layoutIntrinsics.maxIntrinsicWidth
val minIntrinsicWidth: Float
get() = layoutIntrinsics.minIntrinsicWidth
val didExceedMaxLines: Boolean
/**
* Please do not access this object directly from runtime code.
*/
@VisibleForTesting
val layout: Layout
init {
val end = charSequence.length
val frameworkTextDir = getTextDirectionHeuristic(textDirectionHeuristic)
val frameworkAlignment = TextAlignmentAdapter.get(alignment)
// BoringLayout won't adjust line height for baselineShift,
// use StaticLayout for those spans.
val hasBaselineShiftSpans = if (charSequence is Spanned) {
// nextSpanTransition returns limit if there isn't any span.
charSequence.nextSpanTransition(-1, end, BaselineShiftSpan::class.java) < end
} else {
false
}
val boringMetrics = layoutIntrinsics.boringMetrics
layout = if (boringMetrics != null && layoutIntrinsics.maxIntrinsicWidth <= width &&
!hasBaselineShiftSpans) {
BoringLayoutCompat.Builder(
charSequence,
textPaint,
ceil(width).toInt(),
boringMetrics
)
.setAlignment(frameworkAlignment)
.setIncludePad(includePadding)
.setEllipsize(ellipsize)
.setEllipsizedWidth(ceil(width).toInt())
.build()
} else {
StaticLayoutCompat.Builder(
charSequence,
textPaint,
ceil(width).toInt()
)
.setAlignment(frameworkAlignment)
.setTextDirection(frameworkTextDir)
.setLineSpacingExtra(lineSpacingExtra)
.setLineSpacingMultiplier(lineSpacingMultiplier)
.setIncludePad(includePadding)
.setEllipsize(ellipsize)
.setEllipsizedWidth(ceil(width).toInt())
.setMaxLines(maxLines)
.setBreakStrategy(breakStrategy)
.setHyphenationFrequency(hyphenationFrequency)
.setJustificationMode(justificationMode)
.setIndents(leftIndents, rightIndents)
.build()
}
didExceedMaxLines = if (Build.VERSION.SDK_INT <= 25) {
/* Before API 25, the layout.lineCount will be set to maxLines when there are more
actual text lines in the layout.
So in those versions, we first check if maxLines equals layout.lineCount. If true,
we check whether the offset of the last character in Layout is the last character
in string. */
if (maxLines != layout.lineCount) {
false
} else {
layout.getLineEnd(layout.lineCount - 1) != charSequence.length
}
} else {
layout.lineCount > maxLines
}
}
val lineCount: Int
get() = layout.lineCount
val text: CharSequence
get() = layout.text
val height: Int
get() = layout.height
fun getLineLeft(lineIndex: Int): Float = layout.getLineLeft(lineIndex)
fun getLineRight(lineIndex: Int): Float = layout.getLineRight(lineIndex)
fun getLineTop(line: Int): Float = layout.getLineTop(line).toFloat()
fun getLineBottom(line: Int): Float = layout.getLineBottom(line).toFloat()
fun getLineBaseline(line: Int): Float = layout.getLineBaseline(line).toFloat()
fun getLineHeight(lineIndex: Int): Float =
(layout.getLineBottom(lineIndex) - layout.getLineTop(lineIndex)).toFloat()
fun getLineWidth(lineIndex: Int): Float = layout.getLineWidth(lineIndex)
fun getLineForVertical(vertical: Int): Int = layout.getLineForVertical(vertical)
fun getOffsetForHorizontal(line: Int, horizontal: Float): Int =
layout.getOffsetForHorizontal(line, horizontal)
fun getPrimaryHorizontal(offset: Int): Float = layout.getPrimaryHorizontal(offset)
fun getSecondaryHorizontal(offset: Int): Float = layout.getSecondaryHorizontal(offset)
fun getLineForOffset(offset: Int): Int = layout.getLineForOffset(offset)
fun isRtlCharAt(offset: Int): Boolean = layout.isRtlCharAt(offset)
fun getParagraphDirection(line: Int): Int = layout.getParagraphDirection(line)
fun getSelectionPath(start: Int, end: Int, dest: Path) =
layout.getSelectionPath(start, end, dest)
/**
* @return true if the given line is ellipsized, else false.
*/
fun isEllipsisApplied(lineIndex: Int): Boolean = layout.getEllipsisCount(lineIndex) > 0
fun paint(canvas: Canvas) {
layout.draw(canvas)
}
}
@RequiresApi(api = 18)
internal fun getTextDirectionHeuristic(@TextDirection textDirectionHeuristic: Int):
TextDirectionHeuristic {
return when (textDirectionHeuristic) {
TEXT_DIRECTION_LTR -> TextDirectionHeuristics.LTR
TEXT_DIRECTION_LOCALE -> TextDirectionHeuristics.LOCALE
TEXT_DIRECTION_RTL -> TextDirectionHeuristics.RTL
TEXT_DIRECTION_FIRST_STRONG_RTL -> TextDirectionHeuristics.FIRSTSTRONG_RTL
TEXT_DIRECTION_ANY_RTL_LTR -> TextDirectionHeuristics.ANYRTL_LTR
TEXT_DIRECTION_FIRST_STRONG_LTR -> TextDirectionHeuristics.FIRSTSTRONG_LTR
else -> TextDirectionHeuristics.FIRSTSTRONG_LTR
}
}
/** @hide */
@RestrictTo(LIBRARY_GROUP)
object TextAlignmentAdapter {
val ALIGN_LEFT_FRAMEWORK: Layout.Alignment
val ALIGN_RIGHT_FRAMEWORK: Layout.Alignment
init {
val values = Layout.Alignment.values()
var alignLeft = Layout.Alignment.ALIGN_NORMAL
var alignRight = Layout.Alignment.ALIGN_NORMAL
for (value in values) {
if (value.name == "ALIGN_LEFT") {
alignLeft = value
continue
}
if (value.name == "ALIGN_RIGHT") {
alignRight = value
continue
}
}
ALIGN_LEFT_FRAMEWORK = alignLeft
ALIGN_RIGHT_FRAMEWORK = alignRight
}
fun get(@TextLayoutAlignment value: Int): Layout.Alignment {
return when (value) {
ALIGN_LEFT -> ALIGN_LEFT_FRAMEWORK
ALIGN_RIGHT -> ALIGN_RIGHT_FRAMEWORK
ALIGN_CENTER -> Layout.Alignment.ALIGN_CENTER
ALIGN_OPPOSITE -> Layout.Alignment.ALIGN_OPPOSITE
ALIGN_NORMAL -> Layout.Alignment.ALIGN_NORMAL
else -> Layout.Alignment.ALIGN_NORMAL
}
}
}
| 1 |
Kotlin
|
1
| 3 |
a4298de63f0cb4848269a9fe5b6a5ab59d68a4e5
| 11,695 |
Android-Jetpack-Composer
|
Apache License 2.0
|
idea/tests/testData/refactoring/extractFunction/experimental/filterPropagatingMarkers.kt
|
JetBrains
| 278,369,660 | false | null |
// WITH_RUNTIME
// PARAM_DESCRIPTOR: val z: kotlin.Int defined in baz
// PARAM_TYPES: kotlin.Int
@RequiresOptIn
annotation class Marker
@RequiresOptIn
annotation class Another
@Marker
fun foo(x: Int): Int = x
@Another
fun bar(x: Int) {
println(x)
}
@OptIn(Marker::class, Another::class)
fun baz() {
val z = foo(1)
<selection>println(z)
bar(z)</selection>
}
| 1 | null |
30
| 82 |
cc81d7505bc3e9ad503d706998ae8026c067e838
| 377 |
intellij-kotlin
|
Apache License 2.0
|
android/src/main/java/com/ramitsuri/choresclient/android/ui/theme/Dimens.kt
|
ramitsuri
| 426,858,599 | false |
{"Kotlin": 377737, "Shell": 7264, "Ruby": 1624, "Swift": 1574}
|
package com.ramitsuri.choresclient.android.ui.theme
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
val LocalDimensions = staticCompositionLocalOf { Dimens() }
data class Dimens(
val small: Dp = 4.dp,
val medium: Dp = 8.dp,
val large: Dp = 16.dp,
val extraLarge: Dp = 32.dp,
val paddingCardView: Dp = 12.dp,
val minBottomSheetHeight: Dp = 264.dp,
val iconWidthSmall: Dp = 16.dp,
val iconWidthLarge: Dp = 48.dp,
val minAssignmentItemHeight: Dp = 64.dp,
)
| 0 |
Kotlin
|
0
| 2 |
a572db116ecd3b2a8d65702cdc8f6581026534bb
| 570 |
chores-client
|
MIT License
|
app/src/main/java/ru/holofox/anicoubs/features/data/network/api/vk/services/VKApiUtilsService.kt
|
Holofox
| 199,176,207 | false | null |
package ru.holofox.anicoubs.features.data.network.api.vk.services
import ru.holofox.anicoubs.features.data.network.api.vk.ResponseApiParserToLong
import ru.holofox.anicoubs.features.data.network.api.vk.VKBaseApiCommand
class VKApiUtilsService {
companion object METHODS {
private const val UTILS_GET_SERVER_TIME = "utils.getServerTime"
}
class GetServerTime : VKBaseApiCommand<Long>(
method = UTILS_GET_SERVER_TIME,
parser = ResponseApiParserToLong()
)
}
| 0 |
Kotlin
|
0
| 0 |
70dec75d35f7b044c2817c07c5e37e687bb1c9cc
| 499 |
android-anicoubs
|
MIT License
|
app/src/main/java/me/jacoblewis/dailyexpense/data/mappers/PaymentMapper.kt
|
jacobklewis
| 146,213,926 | false | null |
package me.jacoblewis.dailyexpense.data.mappers
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import me.jacoblewis.dailyexpense.commons.ifAll
import me.jacoblewis.dailyexpense.data.models.Payment
import me.jacoblewis.dailyexpense.data.models.firebase.FBPayment
import java.util.*
class PaymentMapper(val userRef: DocumentReference) : BaseMapper<Payment, FBPayment> {
override fun toFirebase(roomModel: Payment): FBPayment {
val categoryRef = FirebaseFirestore.getInstance().document("categories/${roomModel.categoryId}")
return FBPayment(userRef, roomModel.cost, Timestamp(roomModel.creationDate.time), roomModel.notes, categoryRef)
}
override fun toRoom(firebaseModel: FBPayment): Payment? {
return ifAll(firebaseModel.cost, firebaseModel.creationDate, firebaseModel.notes, firebaseModel.category) { cost, date, notes, cat ->
Payment(cost, Calendar.getInstance().also { it.time = date.toDate() }, notes, categoryId = cat.id, needsSync = false)
}
}
}
| 1 |
Kotlin
|
0
| 1 |
adf04fbd238c6212141396ea8b3b244b251d35f4
| 1,115 |
daily-expense-tracker
|
Apache License 2.0
|
app/src/main/java/com/example/twitturin/profile/domain/model/User.kt
|
extractive-mana-pulse
| 708,689,521 | false |
{"Kotlin": 318582, "Java": 2351}
|
package com.example.twitturin.profile.domain.model
import android.os.Parcelable
import com.example.twitturin.tweet.domain.model.Tweet
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import java.io.Serializable
@Parcelize
data class User (
@SerializedName("major" ) var major : String? = null,
@SerializedName("studentId" ) var studentId : String? = null,
@SerializedName("username" ) var username : String? = null,
@SerializedName("fullName" ) var fullName : String? = null,
@SerializedName("email" ) var email : String? = null,
@SerializedName("age" ) var age : Int? = null,
@SerializedName("country" ) var country : String? = null,
@SerializedName("kind" ) var kind : String? = null,
@SerializedName("profilePicture" ) var profilePicture : String? = null,
@SerializedName("followingCount" ) var followingCount : Int? = null,
@SerializedName("followersCount" ) var followersCount : Int? = null,
@SerializedName("bio" ) var bio : String? = null,
@SerializedName("birthday" ) var birthday : String? = null,
@SerializedName("id" ) var id : String? = null,
@SerializedName("token" ) var token : String? = null,
): Parcelable
| 1 |
Kotlin
|
0
| 1 |
9c94fd0f8b139cdf0412839140f6632e8cbf3c91
| 1,283 |
Twittur-In-
|
MIT License
|
app/src/main/java/com/zaurh/notefirelocal/data_store/StoreSettings.kt
|
zaurh
| 629,096,638 | false |
{"Kotlin": 85120}
|
package com.zaurh.notefirelocal.data_store
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("notefire_local")
class StoreSettings(private val context: Context) {
companion object {
val GRID_CELLS = intPreferencesKey("grid_cells")
val DARK_MODE = booleanPreferencesKey("dark_mode")
}
val getGridCells: Flow<Int> = context.dataStore.data
.map { preferences ->
preferences[GRID_CELLS] ?: 2
}
suspend fun saveGridCells(gridCells: Int) {
context.dataStore.edit { preferences ->
preferences[GRID_CELLS] = gridCells
}
}
val getDarkMode: Flow<Boolean?> = context.dataStore.data
.map { preferences ->
preferences[DARK_MODE] ?: false
}
suspend fun saveDarkMode(switched: Boolean) {
context.dataStore.edit { preferences ->
preferences[DARK_MODE] = switched
}
}
}
| 0 |
Kotlin
|
1
| 2 |
e2b41724f412ce9484a334b934c8aaf64b438324
| 1,381 |
NotefireLocal
|
MIT License
|
buildSrc/src/main/java/config/LibraryDependency.kt
|
pokk
| 263,073,196 | false | null |
/*
* MIT License
*
* Copyright (c) 2021 Jieyi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package config
object LibraryDependency {
object Version {
const val ARV = "1.0.16"
const val KINFER = "2.4.0"
const val MATERIAL = "1.5.0-alpha02"
const val ANDROIDX = "1.0.0"
const val ANNOTATION = "1.3.0-alpha01"
const val APPCOMPAT = "1.4.0-alpha03"
const val APP_STARTUP = "1.1.0"
const val CARDVIEW = ANDROIDX
const val RECYCLERVIEW = "1.2.1"
const val PAGING = "3.1.0-alpha03"
const val CONSTRAINTLAYOUT = "2.1.0"
const val COORDINATORLAYOUT = "1.1.0"
const val AAC_LIFECYCLE = "2.4.0-alpha03"
const val DATASTORE = "1.0.0"
const val KODEIN = "7.7.0"
const val KTX = "1.7.0-alpha01"
const val ACTIVITY_KTX = "1.3.1"
const val FRAGMENT_KTX = "1.4.0-alpha07"
const val PALETTE_KTX = "1.0.0"
const val COLLECTION_KTX = "1.2.0-alpha01"
const val NAVIGATION_KTX = "2.4.0-alpha07"
const val WORK_KTX = "2.7.0-alpha05"
const val DYN_ANIM_KTX = "1.0.0-alpha01"
const val ROOM = "2.4.0-alpha04"
const val MMKV = "1.2.10"
const val PLAY_CORE = "1.10.0"
const val COIL = "1.3.2"
const val RETROFIT2 = "2.9.0"
const val OKHTTP3 = "5.0.0-alpha.2"
const val JSOUP = "1.14.2"
const val MOSHI = "1.12.0"
const val AUTO_SERVICE = "1.0"
const val FIREBASE_BOM = "28.4.0"
const val FIREBASE_AUTH_GOOGLE = "19.2.0"
const val FIREBASE_AUTH_FACEBOOK = "11.2.0"
const val EXOPLAYER = "2.15.0"
const val SHAPE_OF_VIEW = "1.4.7"
const val REALTIME_BLUR = "1.2.1"
const val LOTTIE = "4.1.0"
const val SENTRY = "5.1.1"
}
object Jieyi {
const val KNIFER = "studio.pokkbaby:kotlinknifer:${Version.KINFER}"
const val ARV = "com.devrapid.jieyi:adaptiverecyclerview:${Version.ARV}"
}
object Tool {
const val JSOUP = "org.jsoup:jsoup:${Version.JSOUP}"
const val MOSHI = "com.squareup.moshi:moshi:${Version.MOSHI}"
const val MOSHI_ADAPTER = "com.squareup.moshi:moshi-adapters:${Version.MOSHI}"
const val MOSHI_KOTLIN = "com.squareup.moshi:moshi-kotlin:${Version.MOSHI}"
const val MOSHI_CODEGEN = "com.squareup.moshi:moshi-kotlin-codegen:${Version.MOSHI}"
const val AUTO_SERVICE = "com.google.auto.service:auto-service:${Version.AUTO_SERVICE}"
}
object JetPack {
const val MATERIAL_DESIGN = "com.google.android.material:material:${Version.MATERIAL}"
const val APPCOMPAT = "androidx.appcompat:appcompat:${Version.APPCOMPAT}"
const val APP_STARTUP = "androidx.startup:startup-runtime:${Version.APP_STARTUP}"
const val ANNOT = "androidx.annotation:annotation:${Version.ANNOTATION}"
const val RECYCLERVIEW = "androidx.recyclerview:recyclerview:${Version.RECYCLERVIEW}"
const val PAGING = "androidx.paging:paging-runtime:${Version.PAGING}"
const val CARDVIEW = "androidx.cardview:cardview:${Version.CARDVIEW}"
const val CONSTRAINT_LAYOUT = "androidx.constraintlayout:constraintlayout:${Version.CONSTRAINTLAYOUT}"
const val COORDINATOR_LAYOUT = "androidx.coordinatorlayout:coordinatorlayout:${Version.COORDINATORLAYOUT}"
const val LIFECYCLE_SAVEDSTATE = "androidx.lifecycle:lifecycle-viewmodel-savedstate:${Version.AAC_LIFECYCLE}"
const val LIFECYCLE_COMPILER = "androidx.lifecycle:lifecycle-compiler:${Version.AAC_LIFECYCLE}"
const val LIFECYCLE_JAVA8 = "androidx.lifecycle:lifecycle-common-java8:${Version.AAC_LIFECYCLE}"
const val LIFECYCLE_SERVICE = "androidx.lifecycle:lifecycle-service:${Version.AAC_LIFECYCLE}"
const val NAVIGATION_DYNAMIC_FEATURE =
"androidx.navigation:navigation-dynamic-features-fragment:${Version.NAVIGATION_KTX}"
const val DATASTORE = "androidx.datastore:datastore-preferences:${Version.DATASTORE}"
}
object AndroidKtx {
const val KTX = "androidx.core:core-ktx:${Version.KTX}"
const val ACTIVITY_KTX = "androidx.activity:activity-ktx:${Version.ACTIVITY_KTX}"
const val FRAGMENT_KTX = "androidx.fragment:fragment-ktx:${Version.FRAGMENT_KTX}"
const val PALETTE_KTX = "androidx.palette:palette-ktx:${Version.PALETTE_KTX}"
const val COLLECTION_KTX = "androidx.collection:collection-ktx:${Version.COLLECTION_KTX}"
const val VIEWMODEL_KTX = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Version.AAC_LIFECYCLE}"
const val LIVEDATA_KTX = "androidx.lifecycle:lifecycle-livedata-ktx:${Version.AAC_LIFECYCLE}"
const val RUNTIME_KTX = "androidx.lifecycle:lifecycle-runtime-ktx:${Version.AAC_LIFECYCLE}"
const val NAVIGATION_FRAGMENT_KTX = "androidx.navigation:navigation-fragment-ktx:${Version.NAVIGATION_KTX}"
const val NAVIGATION_UI_KTX = "androidx.navigation:navigation-ui-ktx:${Version.NAVIGATION_KTX}"
const val WORKER_KTX = "androidx.work:work-runtime-ktx:${Version.WORK_KTX}"
const val DYN_ANIM_KTX = "androidx.dynamicanimation-ktx:${Version.DYN_ANIM_KTX}"
}
object Database {
const val ROOM = "androidx.room:room-runtime:${Version.ROOM}"
const val ROOM_KTX = "androidx.room:room-ktx:${Version.ROOM}"
const val ROOM_ANNOTATION = "androidx.room:room-compiler:${Version.ROOM}"
const val MMKV = "com.tencent:mmkv-static:${Version.MMKV}"
}
object Di {
const val KODEIN_ANDROID_X = "org.kodein.di:kodein-di-framework-android-x:${Version.KODEIN}"
}
object Internet {
const val OKHTTP = "com.squareup.okhttp3:okhttp:${Version.OKHTTP3}"
const val OKHTTP_INTERCEPTOR = "com.squareup.okhttp3:logging-interceptor:${Version.OKHTTP3}"
const val RETROFIT2 = "com.squareup.retrofit2:retrofit:${Version.RETROFIT2}"
const val RETROFIT2_CONVERTER_MOSHI = "com.squareup.retrofit2:converter-moshi:${Version.RETROFIT2}"
const val COIL = "io.coil-kt:coil:${Version.COIL}"
}
object Firebase {
const val FIREBASE_BOM = "com.google.firebase:firebase-bom:${Version.FIREBASE_BOM}"
const val PLAY_CORE = "com.google.android.play:core:${Version.PLAY_CORE}"
const val FIREBASE_AUTH = "com.google.firebase:firebase-auth-ktx"
const val FIREBASE_AUTH_GOOGLE = "com.google.android.gms:play-services-auth:${Version.FIREBASE_AUTH_GOOGLE}"
const val FIREBASE_AUTH_FACEBOOK = "com.facebook.android:facebook-login:${Version.FIREBASE_AUTH_FACEBOOK}"
const val FIREBASE_DB = "com.google.firebase:firebase-database-ktx"
const val FIREBASE_FIRESTORE = "com.google.firebase:firebase-firestore-ktx"
const val FIREBASE_MESSAGING = "com.google.firebase:firebase-messaging-ktx"
const val FIREBASE_CRASHLYTICS = "com.google.firebase:firebase-crashlytics-ktx"
const val FIREBASE_PERFORMANCE = "com.google.firebase:firebase-perf-ktx"
const val FIREBASE_CONFIG = "com.google.firebase:firebase-config-ktx"
const val FIREBASE_ML = "com.google.firebase:firebase-ml-vision"
}
object Analytics {
const val FIREBASE_ANALYTICS = "com.google.firebase:firebase-analytics-ktx"
const val SENTRY = "io.sentry:sentry-android:${Version.SENTRY}"
}
object Media {
const val EXOPLAYER_CORE = "com.google.android.exoplayer:exoplayer-core:${Version.EXOPLAYER}"
}
object Ui {
const val SHAPE_OF_VIEW = "io.github.florent37:shapeofview:${Version.SHAPE_OF_VIEW}"
const val REALTIME_BLUR = "com.github.mmin18:realtimeblurview:${Version.REALTIME_BLUR}"
const val LOTTIE = "com.airbnb.android:lottie:${Version.LOTTIE}"
}
}
| 1 | null |
3
| 14 |
13555785784396b53ab8b6d502341fc51fda163b
| 8,810 |
DropBeat
|
MIT License
|
API/Ponto Inteligente/src/main/kotlin/com/wendergalan/pontointeligente/security/SecurityConfig.kt
|
WenderGalan
| 151,712,934 | false | null |
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig(
val funcionarioDetailsService: FuncionarioDetailsService) : WebSecurityConfigurerAdapter() {
override fun configure(auth: AuthenticationManagerBuilder?) {
auth?.authenticationProvider(authenticationProvider())
}
override fun configure(http: HttpSecurity?) {
http?.authorizeRequests()?.anyRequest()?.authenticated()?.and()?.httpBasic()?.and()?.sessionManagement()?.sessionCreationPolicy(SessionCreationPolicy.STATELESS)?.and()?.csrf()?.disable()
}
@Bean
fun authenticationProvider(): DaoAuthenticationProvider {
val authProvider = DaoAuthenticationProvider()
authProvider.setUserDetailsService(funcionarioDetailsService)
authProvider.setPasswordEncoder(encoder())
return authProvider
}
@Bean
fun encoder(): PasswordEncoder = BCryptPasswordEncoder()
}
| 0 |
Kotlin
|
1
| 0 |
196f56e4701561c143922bafda219f8f24bdb908
| 1,837 |
ponto-inteligente
|
Apache License 2.0
|
src/commonTest/kotlin/com/fab1an/kotlinjsonstream/JsonReaderTest.kt
|
fab1an
| 617,309,008 | false | null |
package com.fab1an.kotlinjsonstream
import kotlin.test.Test
import kotlin.test.assertFailsWith
class JsonReaderTest {
@Test
fun closeSource() {
JsonReader("""{}""").close()
}
@Test
fun readJson() {
val json = JsonReader("""{"stringProp":"string", "intProp":0}""")
json.beginObject()
json.nextName() shouldEqual "stringProp"
json.nextString() shouldEqual "string"
json.nextName() shouldEqual "intProp"
json.nextInt() shouldEqual 0
json.endObject()
}
@Test
fun readDouble() {
val json = JsonReader("""{"doubleProp":1.0}""")
json.beginObject()
json.nextName() shouldEqual "doubleProp"
json.nextDouble() shouldEqual 1.0
json.endObject()
}
@Test
fun throwOnIntWithExponents() {
val json = JsonReader("""[1.0E+2]""")
json.beginArray()
assertFailsWith<NumberFormatException> {
json.nextInt()
}
}
@Test
fun throwOnLongWithExponents() {
val json = JsonReader("""[1.0E+2]""")
json.beginArray()
assertFailsWith<NumberFormatException> {
json.nextLong()
}
}
@Test
fun readDoubleWithExponents() {
val json = JsonReader("""[1.0E+2,1.0e+2,1E+0,1.2E-2]""")
json.beginArray()
json.nextDouble() shouldEqual 100.0
json.nextDouble() shouldEqual 100.0
json.nextDouble() shouldEqual 1.0
json.nextDouble() shouldEqual 0.012
json.endArray()
}
@Test
fun errorOnInvalidNumber() {
JsonReader("""[.1]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextInt()
}
}
JsonReader("""[00]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextInt()
}
}
JsonReader("""[-00]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextInt()
}
}
JsonReader("""[1.0EE+2]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextDouble()
}
}
JsonReader("""[1.0f+2]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextDouble()
}
}
JsonReader("""[1.0e]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextDouble()
}
}
JsonReader("""[1.0f]""").apply {
beginArray()
assertFailsWith<NumberFormatException> {
nextDouble()
}
}
}
@Test
fun readBoolean() {
var json = JsonReader("""{"boolProp":true}""")
json.beginObject()
json.nextName() shouldEqual "boolProp"
json.nextBoolean() shouldEqual true
json.endObject()
json = JsonReader("""{"boolProp":false}""")
json.beginObject()
json.nextName() shouldEqual "boolProp"
json.nextBoolean() shouldEqual false
json.endObject()
}
@Test
fun readMixedNestedArray() {
val json = JsonReader("""{ "array": [1, "zwei", 3, "vier"] }""")
json.beginObject()
json.nextName() shouldEqual "array"
json.beginArray()
json.nextInt() shouldEqual 1
json.nextString() shouldEqual "zwei"
json.nextInt() shouldEqual 3
json.nextString() shouldEqual "vier"
json.endArray()
json.endObject()
}
@Test
fun readNestedObject() {
val json = JsonReader("""{ "obj": {"value": 1} }""")
json.beginObject()
json.nextName() shouldEqual "obj"
json.beginObject()
json.nextName() shouldEqual "value"
json.nextInt() shouldEqual 1
json.endObject()
json.endObject()
}
@Test
fun errorNoCommaInArray() {
val json = JsonReader("""[1 "zwei"]""")
json.beginArray()
json.nextInt() shouldEqual 1
assertFailsWith<IllegalStateException> {
json.nextString()
}
}
@Test
fun peekNameInObject() {
val json = JsonReader(""" { "p1": 0, "p2": 1 } """)
json.beginObject()
json.peek() shouldEqual JsonToken.NAME
json.nextName() shouldEqual "p1"
json.skipValue()
json.peek() shouldEqual JsonToken.NAME
json.nextName() shouldEqual "p2"
json.skipValue()
json.endObject()
}
@Test
fun errorNoCommaInObject() {
val json = JsonReader("""{"value1":0 "value2":1}""")
json.beginObject()
json.nextName() shouldEqual "value1"
json.nextInt() shouldEqual 0
assertFailsWith<IllegalStateException> {
json.nextName()
}
}
@Test
fun errorMismatchedBrackets() {
val json = JsonReader("""{"test": [}]""")
json.beginObject()
json.nextName() shouldEqual "test"
json.beginArray()
assertFailsWith<IllegalStateException> {
json.endArray()
}
}
@Test
fun errorValueInsideObject() {
val json = JsonReader("""{5}""")
json.beginObject()
assertFailsWith<IllegalStateException> {
json.nextName()
}
}
@Test
fun hasNextArray() {
var json = JsonReader("""[]""")
json.beginArray()
json.hasNext() shouldEqual false
json.endArray()
json = JsonReader("""[1,2]""")
json.beginArray()
json.hasNext() shouldEqual true
json.nextInt()
json.hasNext() shouldEqual true
json.nextInt()
json.hasNext() shouldEqual false
json.endArray()
}
@Test
fun hasNextObject() {
var json = JsonReader("""{}""")
assertFailsWith<IllegalStateException> { json.hasNext() }
json = JsonReader("""{}""")
json.beginObject()
json.hasNext() shouldEqual false
json.endObject()
json = JsonReader("""{"a":"", "b":""}""")
json.beginObject()
json.hasNext() shouldEqual true
json.nextName()
json.nextString()
json.hasNext() shouldEqual true
json.nextName()
json.nextString()
json.hasNext() shouldEqual false
json.endObject()
}
@Test
fun skipNullValue() {
JsonReader("""{"temp": null}""").apply {
beginObject()
nextName() shouldEqual "temp"
peek() shouldEqual JsonToken.NULL
skipValue()
endObject()
}
JsonReader("""[1,null,3]""").apply {
beginArray()
peek() shouldEqual JsonToken.NUMBER
nextInt() shouldEqual 1
peek() shouldEqual JsonToken.NULL
skipValue()
peek() shouldEqual JsonToken.NUMBER
nextInt() shouldEqual 3
endArray()
}
}
@Test
fun skipTopLevelStringNumber() {
val json = JsonReader("""5""")
assertFailsWith<IllegalStateException> {
json.skipValue()
}
}
@Test
fun failOnSkippingInvalidNumber() {
val json = JsonReader("""[--5]""")
json.beginArray()
assertFailsWith<NumberFormatException> {
json.skipValue()
}
}
@Test
fun failOnInvalidNumber() {
val json = JsonReader("""[--5]""")
json.beginArray()
assertFailsWith<NumberFormatException> {
json.nextInt()
}
}
@Test
fun skipBoolValue() {
val json = JsonReader("""{"val1": true, "val2": false, "val3": "string"}""")
json.beginObject()
json.nextName() shouldEqual "val1"
json.skipValue()
json.nextName() shouldEqual "val2"
json.skipValue()
json.nextName() shouldEqual "val3"
json.nextString() shouldEqual "string"
json.endObject()
}
@Test
fun skipDoubleValue() {
val json = JsonReader("""[1.0]""")
json.beginArray()
json.skipValue()
json.endArray()
}
@Test
fun skipObject() {
val json = JsonReader("""{"val1": {"innerVal1": ""}, "val2": "b"}""")
json.beginObject()
json.nextName() shouldEqual "val1"
json.skipValue()
json.nextName() shouldEqual "val2"
json.nextString() shouldEqual "b"
json.endObject()
}
@Test
fun skipValueAtBeginOfArray() {
val json = JsonReader("""[2,"b",3]""")
json.beginArray()
json.nextInt() shouldEqual 2
json.skipValue()
json.nextInt() shouldEqual 3
json.endArray()
}
@Test
fun skipValueInsideArray() {
val json = JsonReader("""[2,"b",3]""")
json.beginArray()
json.nextInt() shouldEqual 2
json.skipValue()
json.nextInt() shouldEqual 3
json.endArray()
}
@Test
fun escapedString() {
val json = JsonReader("""[ "Escaped: \",\\,\/,\b,\f,\n,\r,\t,\u0000,\uFFFF" ]""")
json.beginArray()
json.nextString() shouldEqual "Escaped: \",\\,/,\b,\u000c,\n,\r,\t,\u0000,\uFFFF"
json.endArray()
}
@Test
fun escapedName() {
val json = JsonReader("""{ "Escaped: \",\\,\/,\b,\f,\n,\r,\t,\u0000,\uFFFF": 0 }""")
json.apply {
beginObject()
nextName() shouldEqual "Escaped: \",\\,/,\b,\u000c,\n,\r,\t,\u0000,\uFFFF"
nextInt() shouldEqual 0
endObject()
}
}
@Test
fun readBackslashesInString() {
val json = JsonReader(""" { "title": "C:\\PROGRA~1\\" } """)
json.beginObject()
json.nextName() shouldEqual "title"
json.nextString() shouldEqual """C:\PROGRA~1\"""
json.endObject()
}
@Test
fun readNullInObject() {
val json = JsonReader(""" { "title": null } """)
json.beginObject()
json.nextName() shouldEqual "title"
json.nextNull()
json.endObject()
}
@Test
fun readNullInArray() {
val json = JsonReader(""" [1,null,3] """)
json.beginArray()
json.nextInt() shouldEqual 1
json.nextNull()
json.nextInt() shouldEqual 3
json.endArray()
}
@Test
fun readLong() {
val json = JsonReader(""" [${Long.MAX_VALUE}] """)
json.beginArray()
json.nextLong() shouldEqual Long.MAX_VALUE
json.endArray()
}
@Test
fun noLeadingCommaInArray() {
val json = JsonReader("""[,0]""")
json.beginArray()
assertFailsWith<IllegalStateException> {
json.nextInt()
}
}
@Test
fun noLeadingCommaInObject() {
val json = JsonReader("""{,"value": 0}""")
json.beginObject()
assertFailsWith<IllegalStateException> {
json.nextName()
}
}
@Test
fun noTrailingCommaInArray() {
val json = JsonReader("""[0,]""")
json.beginArray()
json.nextInt() shouldEqual 0
assertFailsWith<IllegalStateException> {
json.endArray()
}
}
@Test
fun noTrailingCommaInNestedArray() {
val json = JsonReader("""[[],]""")
json.beginArray()
json.beginArray()
json.endArray()
assertFailsWith<IllegalStateException> {
json.endArray()
}
}
@Test
fun noTrailingCommaInObject() {
val json = JsonReader("""{"value": 0,}""")
json.beginObject()
json.nextName() shouldEqual "value"
json.nextInt() shouldEqual 0
assertFailsWith<IllegalStateException> {
json.endObject()
}
}
@Test
fun noTrailingCommaInNestedObject() {
val json = JsonReader("""{"value": {},}""")
json.beginObject()
json.nextName() shouldEqual "value"
json.beginObject()
json.endObject()
assertFailsWith<IllegalStateException> {
json.endObject()
}
}
@Test
fun numberInObject() {
val json = JsonReader("""{"value": 1,2}""")
json.beginObject()
json.nextName() shouldEqual "value"
json.nextInt() shouldEqual 1
assertFailsWith<IllegalStateException> {
json.nextInt()
}
}
@Test
fun unparseableIntegerThatIsTooLarge() {
val json = JsonReader("""[92147483647]""")
json.apply {
beginArray()
assertFailsWith<NumberFormatException> {
json.nextInt()
}
}
}
@Test
fun unparseableIntegerThatHasFraction() {
val json = JsonReader("""[1.0]""")
json.apply {
beginArray()
assertFailsWith<NumberFormatException> {
json.nextInt()
}
}
}
@Test
fun readSpecialLong() {
val long = 7451037802904629050
val json = JsonReader("""[$long]""")
json.apply {
beginArray()
json.nextLong() shouldEqual long
}
}
}
| 0 | null |
1
| 3 |
d011116b61a2a7cbd4dae422c1630fbe8737b75c
| 13,251 |
kotlin-json-stream
|
Apache License 2.0
|
app/src/main/java/com/huotu/android/mifang/widget/FrescoImageLoader.kt
|
hottech-jxd
| 163,493,643 | false | null |
package com.huotu.android.mifang.widget
import android.content.Context
import android.net.Uri
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CollapsingToolbarLayout
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.huotu.android.mifang.util.FrescoDraweeController
import com.huotu.android.mifang.util.FrescoDraweeListener
import com.youth.banner.Banner
import com.youth.banner.loader.ImageLoader
import com.facebook.drawee.generic.GenericDraweeHierarchy
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.huotu.android.mifang.R
class FrescoImageLoader(var banner : Banner, var width :Int , var defaultHeight:Int)
:ImageLoader(), FrescoDraweeListener.ImageCallback{
constructor(collapsingToolbarLayout : CollapsingToolbarLayout? , banner :Banner, width:Int, defaultHeight: Int, defaultPicture:Int):this(banner , width, defaultHeight){
this.defaultPicture = defaultPicture
this.collapsingToolbarLayout=collapsingToolbarLayout
}
private var collapsingToolbarLayout:CollapsingToolbarLayout?=null
private var defaultPicture:Int=R.mipmap.avator
override fun createImageView(context: Context?): ImageView {
var simpleDraweeView = SimpleDraweeView(context)
val builder = GenericDraweeHierarchyBuilder(context!!.resources)
val hierarchy = builder
.setPlaceholderImage(defaultPicture)
.setPlaceholderImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.setFailureImage(defaultPicture)
.setFailureImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
.build()
simpleDraweeView.hierarchy= hierarchy
return simpleDraweeView
}
override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
FrescoDraweeController.loadImage(imageView as SimpleDraweeView , width , defaultHeight , path.toString() , this)
}
override fun imageCallback(width: Int, height: Int, simpleDraweeView: SimpleDraweeView?) {
if(simpleDraweeView==null) return
var layoutParams = simpleDraweeView.layoutParams
layoutParams.width = width
layoutParams.height = height
simpleDraweeView.layoutParams =layoutParams
var layout2 = banner.layoutParams
layout2.height=height
banner.layoutParams=layout2
if(collapsingToolbarLayout!=null){
var layout3 = collapsingToolbarLayout!!.layoutParams
layout3.height=height
collapsingToolbarLayout!!.layoutParams=layout3
}
}
override fun imageFailure(width: Int, height: Int, simpleDraweeView: SimpleDraweeView?) {
var layout2 = banner.layoutParams
layout2.height=height
banner.layoutParams=layout2
}
}
| 1 | null |
1
| 1 |
d409993f3900a1ebef52bfd8ea2bbbd7799bce79
| 3,052 |
mifang-shopman-android
|
Apache License 2.0
|
app/src/main/java/org/simple/clinic/home/patients/links/PatientsTabLinkEffect.kt
|
simpledotorg
| 132,515,649 | false |
{"Kotlin": 6102869, "Shell": 1660, "HTML": 545}
|
package org.simple.clinic.home.patients.links
sealed class PatientsTabLinkEffect
object LoadCurrentFacility : PatientsTabLinkEffect()
object LoadQuestionnaires : PatientsTabLinkEffect()
object LoadQuestionnaireResponses : PatientsTabLinkEffect()
object OpenMonthlyScreeningReportsListScreen : PatientsTabLinkEffect()
object OpenMonthlySuppliesReportsListScreen : PatientsTabLinkEffect()
object OpenPatientLineListDownloadDialog : PatientsTabLinkEffect()
object OpenDrugStockReportsScreen : PatientsTabLinkEffect()
| 7 |
Kotlin
|
74
| 226 |
efdb8235b38476f1f75d09f0503587ee280f09e2
| 522 |
simple-android
|
MIT License
|
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/editor/GitLabMergeRequestEditorDiscussionViewModel.kt
|
SamB
| 215,873,627 | false |
{"Text": 9365, "INI": 518, "YAML": 419, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 9, "Shell": 633, "Markdown": 740, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 256, "XML": 7809, "SVG": 4411, "Kotlin": 58041, "Java": 83545, "HTML": 3781, "Java Properties": 215, "Gradle": 449, "Maven POM": 95, "JavaScript": 228, "CSS": 79, "JSON": 1472, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 676, "Groovy": 3156, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 48, "Python": 17005, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 192, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 16, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui.editor
import com.intellij.collaboration.async.combineState
import com.intellij.collaboration.async.mapState
import com.intellij.collaboration.ui.codereview.diff.DiscussionsViewOption
import com.intellij.collaboration.ui.codereview.editor.EditorMapped
import com.intellij.diff.util.Side
import git4idea.changes.GitTextFilePatchWithHistory
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.plugins.gitlab.mergerequest.data.mapToLocation
import org.jetbrains.plugins.gitlab.ui.comment.GitLabMergeRequestDiscussionViewModel
import org.jetbrains.plugins.gitlab.ui.comment.GitLabMergeRequestStandaloneDraftNoteViewModelBase
import org.jetbrains.plugins.gitlab.ui.comment.GitLabNoteViewModel
import org.jetbrains.plugins.gitlab.ui.comment.NewGitLabNoteViewModel
class GitLabMergeRequestEditorDiscussionViewModel internal constructor(
base: GitLabMergeRequestDiscussionViewModel,
diffData: GitTextFilePatchWithHistory,
discussionsViewOption: StateFlow<DiscussionsViewOption>
) : GitLabMergeRequestDiscussionViewModel by base, EditorMapped {
override val line: StateFlow<Int?> = base.position.mapState {
it?.mapToLocation(diffData, Side.RIGHT)?.takeIf { it.first == Side.RIGHT }?.second
}
override val isVisible: StateFlow<Boolean> = isResolved.combineState(discussionsViewOption) { isResolved, viewOption ->
return@combineState when (viewOption) {
DiscussionsViewOption.ALL -> true
DiscussionsViewOption.UNRESOLVED_ONLY -> !isResolved
DiscussionsViewOption.DONT_SHOW -> false
}
}
}
class GitLabMergeRequestEditorDraftNoteViewModel internal constructor(
base: GitLabMergeRequestStandaloneDraftNoteViewModelBase,
diffData: GitTextFilePatchWithHistory,
discussionsViewOption: StateFlow<DiscussionsViewOption>
) : GitLabNoteViewModel by base, EditorMapped {
override val line: StateFlow<Int?> = base.position.mapState {
it?.mapToLocation(diffData, Side.RIGHT)?.takeIf { it.first == Side.RIGHT }?.second
}
override val isVisible: StateFlow<Boolean> = discussionsViewOption.mapState {
when (it) {
DiscussionsViewOption.UNRESOLVED_ONLY, DiscussionsViewOption.ALL -> true
DiscussionsViewOption.DONT_SHOW -> false
}
}
}
class GitLabMergeRequestEditorNewDiscussionViewModel internal constructor(
base: NewGitLabNoteViewModel,
val originalLine: Int,
discussionsViewOption: StateFlow<DiscussionsViewOption>
) : NewGitLabNoteViewModel by base, EditorMapped {
override val line: StateFlow<Int?> = MutableStateFlow(originalLine)
override val isVisible: StateFlow<Boolean> = discussionsViewOption.mapState { it != DiscussionsViewOption.DONT_SHOW }
}
| 1 | null |
1
| 1 |
37c7118b1a4fb7f21c1a2636355c91f2a7d9ba05
| 2,861 |
intellij-community
|
Apache License 2.0
|
src/main/kotlin/org/abimon/visi/collections/Pools.kt
|
UnderMybrella
| 83,109,125 | false | null |
package org.abimon.visi.collections
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class Pool<T>(private val poolSize: Int = -1) {
private val poolables: MutableList<Poolable<T>> = ArrayList()
/**
* Get the first available [Poolable] instance, or null if none are free
*/
fun get(): Poolable<T>? {
synchronized(poolables) {
return poolables.firstOrNull(Poolable<T>::isFree)
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Throws a [TimeOutException]
*/
private fun getOrWait(wait: Long, unit: TimeUnit): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = get()
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
/**
* Get the first available [Poolable] instance which matches [matches], or null if none of the instances are free that match
*/
private fun getWhich(matches: (T) -> Boolean): Poolable<T>? {
synchronized(poolables) {
return poolables.filter { poolable -> matches(poolable()) }.firstOrNull(Poolable<T>::isFree)
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Will hang until one becomes available
*/
fun getOrWaitUntil(wait: Long, unit: TimeUnit, matches: (T) -> Boolean): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = getWhich(matches)
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
private fun getFirst(sort: (T, T) -> Int): Poolable<T>? {
synchronized(poolables) {
return poolables.filter(Poolable<T>::isFree).sortedWith(Comparator { one, two -> sort(one(), two())}).firstOrNull()
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Will hang until one becomes available
*/
fun getFirstOrWaitUntil(wait: Long, unit: TimeUnit, sort: (T, T) -> Int): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = getFirst(sort)
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
/**
* Gets the first available [Poolable] instance, or adds [add] to the pool if there is space. If there is no space and none are free, returns null
*/
fun getOrAdd(add: () -> Poolable<T>): Poolable<T>? {
synchronized(poolables) {
if(poolables.size >= poolSize)
return get()
val poolable = poolables.firstOrNull(Poolable<T>::isFree)
if(poolable == null) {
val newPoolable = add()
poolables.add(newPoolable)
return newPoolable
}
return poolable
}
}
/**
* Gets the first available [Poolable] instance, or adds [add] to the pool if there is space. If there is no space and none are free, wait.
*/
fun getOrAddOrWait(wait: Long, unit: TimeUnit, add: () -> Poolable<T>): Poolable<T> {
synchronized(poolables) {
if(poolables.size >= poolSize)
return getOrWait(wait, unit)
val poolable = poolables.firstOrNull(Poolable<T>::isFree)
if(poolable == null) {
val newPoolable = add()
poolables.add(newPoolable)
return newPoolable
}
return poolable
}
}
fun getFree(): List<Poolable<T>> = poolables.filter(Poolable<T>::isFree)
fun retire(poolable: Poolable<T>): Boolean = poolables.remove(poolable)
fun add(poolable: Poolable<T>): Boolean = if(poolables.size >= poolSize) false else poolables.add(poolable)
}
interface Poolable<out T> {
fun get(): T
fun isFree(): Boolean
operator fun invoke(): T = get()
}
class PoolableObject<out T>(private val obj: T) : Poolable<T> {
private var inUse = false
override fun get(): T = synchronized(obj as Any) { obj }
override fun isFree(): Boolean = !inUse
fun use(run: (T) -> Unit) {
inUse = true
try {
synchronized(obj as Any) {
run(obj)
}
}
finally {
inUse = false
}
}
}
| 0 | null |
3
| 1 |
7fdb31da497792cc58787940d1321698d8ff410f
| 5,108 |
Visi
|
MIT License
|
sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/RecyclerViewItem.kt
|
alt236
| 17,951,611 | false | null |
package uk.co.alt236.btlescan.ui.common.recyclerview
interface RecyclerViewItem
| 13 |
Java
|
303
| 849 |
bfd2eecba6df3158005837d619c84d1f1033ba1b
| 80 |
Bluetooth-LE-Library---Android
|
Apache License 2.0
|
js/js.translator/testData/incremental/invalidation/companionProperties/lib1/l1.0.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
class MyClass {
companion object {
val stringProperty = "0"
}
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 80 |
kotlin
|
Apache License 2.0
|
js/js.translator/testData/incremental/invalidation/companionProperties/lib1/l1.0.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
class MyClass {
companion object {
val stringProperty = "0"
}
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 80 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/io/ashdavies/operator/FilterOperator.kt
|
ashdavies
| 177,180,130 | false | null |
package io.ashdavies.operator
import io.ashdavies.lifecycle.LiveDataScope
internal class FilterOperator<T>(private val predicate: (T) -> Boolean) : Operator<T, T> {
override fun invoke(scope: LiveDataScope<T>, value: T) {
if (predicate(value)) {
scope.emit(value)
}
}
}
| 0 |
Kotlin
|
1
| 4 |
09739852177e5e28600ba7c3dcfe9d63314c9dd9
| 291 |
lifecycle-flow
|
Apache License 2.0
|
src/main/kotlin/io/github/pr0methean/ochd/materials/block/barehand/Torch.kt
|
Pr0methean
| 507,628,226 | false | null |
package io.github.pr0methean.ochd.materials.block.barehand
import io.github.pr0methean.ochd.TaskPlanningContext
import io.github.pr0methean.ochd.materials.block.axe.OverworldWood
import io.github.pr0methean.ochd.materials.block.pickaxe.Ore
import io.github.pr0methean.ochd.tasks.PngOutputTask
import io.github.pr0methean.ochd.texturebase.Material
object Torch: Material {
override fun outputTasks(ctx: TaskPlanningContext): Sequence<PngOutputTask> = sequence {
val torchBase = ctx.stack {
layer("torchBase", OverworldWood.OAK.highlight)
layer("torchShadow", OverworldWood.OAK.shadow)
}
yield(ctx.out(ctx.stack {
copy(torchBase)
layer("torchFlameSmall")
}, "block/torch"))
yield(ctx.out(ctx.stack {
copy(torchBase)
layer("soulTorchFlameSmall")
}, "block/soul_torch"))
yield(ctx.out(ctx.stack {
copy(torchBase)
layer("torchRedstoneHead")
}, "block/redstone_torch_off"))
yield(ctx.out(ctx.stack {
copy(torchBase)
layer("torchRedstoneHead", Ore.REDSTONE.highlight)
layer("torchRedstoneHeadShadow", Ore.REDSTONE.shadow)
}, "block/redstone_torch"))
}
}
| 1 |
Kotlin
|
0
| 5 |
3e8182114f7fe0fb70fcd6fa445c28dc5470a3f5
| 1,269 |
OcHd-KotlinBuild
|
Apache License 2.0
|
examples/mailsettings/GetForwardBounceMailSettings.kt
|
desiderantes
| 148,538,242 | false | null |
import java.io.IOException
import com.sendgrid.Method
import com.sendgrid.Request
import com.sendgrid.Response
import com.sendgrid.SendGrid
//////////////////////////////////////////////////////////////////
// Retrieve forward bounce mail settings
// GET /mail_settings/forward_bounce
object GetForwardBounceMailSettings {
@Throws(IOException::class)
fun main(args: Array<String>) {
try {
val sg = SendGrid(System.getenv("SENDGRID_API_KEY"))
val request = Request()
request.setMethod(Method.GET)
request.setEndpoint("mail_settings/forward_bounce")
val response = sg.api(request)
System.out.println(response.getStatusCode())
System.out.println(response.getBody())
System.out.println(response.getHeaders())
} catch (ex: IOException) {
throw ex
}
}
}
| 0 |
Kotlin
|
0
| 0 |
9f188c75d3b3cfa4dc04ea6e5ac8eaf0430af4dd
| 896 |
sendgrid-kotlin
|
MIT License
|
app/src/main/java/com/pri/architecture_boilerplate/util/CBProgressDialog.kt
|
priyanka-rani
| 218,155,486 | false | null |
package com.pri.architecture_boilerplate.util
import android.app.Dialog
import android.content.Context
import android.view.Window
import android.widget.ProgressBar
/**
* Created by Priyanka on 13/11/18.
*/
class CBProgressDialog//..we need the context else we can not create the dialog so get context in constructor
(internal var context: Context) {
internal var dialog: Dialog? = null
val isShowing: Boolean
get() = dialog?.isShowing ?: false
init {
dialog = Dialog(context)
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
//...set cancelable false so that it's never get hidden
dialog?.setCanceledOnTouchOutside(false)
dialog?.setCancelable(true)
//...that's the layout i told you will inflate later
dialog?.setContentView(ProgressBar(context))
dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
//...initialize the imageView form infalted layout
/* *//*
it was never easy to load gif into an ImageView before Glide or Others library
and for doing this we need DrawableImageViewTarget to that ImageView
*//*
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(gifImageView);
//...now load that gif which we put inside the drawble folder here with the help of Glide
Glide.with(activity).load(R.drawable.loading_new).placeholder(R.drawable.loading_new).centerCrop().crossFade().into(imageViewTarget);*/
//...finaly show it
}
fun showDialog() {
dialog?.show()
}
//..also create a method which will hide the dialog when some work is done
fun hideDialog() {
dialog?.dismiss()
}
}
| 1 | null |
1
| 1 |
18a74203aebf027e66254925663023aefb6b685b
| 1,747 |
architecture_dagger_binding_pri
|
Apache License 2.0
|
src/main/kotlin/com/compiler/server/compiler/components/KotlinEnvironment.kt
|
CGNonofr
| 370,662,196 | true |
{"Kotlin": 355664, "Dockerfile": 1169}
|
package com.compiler.server.compiler.components
import com.compiler.server.model.bean.LibrariesFile
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import component.KotlinEnvironment
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.serialization.js.JsModuleDescriptor
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.io.File
@Configuration
class KotlinEnvironmentConfiguration(val librariesFile: LibrariesFile) {
@Bean
fun kotlinEnvironment(): KotlinEnvironment {
val classPath =
listOfNotNull(librariesFile.jvm)
.flatMap {
it.listFiles()?.toList()
?: throw error("No kotlin libraries found in: ${librariesFile.jvm.absolutePath}")
}
val additionalJsClasspath = listOfNotNull(librariesFile.js)
return KotlinEnvironment(classPath, additionalJsClasspath)
}
}
| 0 | null |
0
| 0 |
21aec48ec378e4070f6e63a48f30cda00404cb3c
| 1,810 |
kotlin-compiler-server
|
Apache License 2.0
|
app/src/main/java/com/myapp/medled/adapters/recycler_view/DoctorTypesRecyclerViewAdapter.kt
|
F-Y-E-F
| 307,081,321 | false | null |
package com.myapp.medled.adapters.recycler_view
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.myapp.medled.R
import com.myapp.medled.adapters.recycler_view.view_holders.DoctorsTypesViewHolder
import com.myapp.medled.models.DoctorTypeCard
import com.myapp.medled.screens.doctor.AllDoctorsInterface
class DoctorTypesRecyclerViewAdapter(private val listOfDoctorsTypes: ArrayList<DoctorTypeCard>,private val listener:AllDoctorsInterface):RecyclerView.Adapter<DoctorsTypesViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoctorsTypesViewHolder {
return DoctorsTypesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.photo_and_desc_card,parent,false))
}
override fun getItemCount(): Int {
return listOfDoctorsTypes.size
}
override fun onBindViewHolder(holder: DoctorsTypesViewHolder, position: Int) {
//---------------------------------| setup data |-----------------------------------
holder.description.text = listOfDoctorsTypes[holder.adapterPosition].name
holder.photo.setImageResource(listOfDoctorsTypes[holder.adapterPosition].photo)
//------------------------| set colors of bg and text |--------------------------
holder.allBox.backgroundTintList = ContextCompat.getColorStateList(holder.itemView.context,if(listOfDoctorsTypes[holder.adapterPosition].isChoose) R.color.colorPrimary else R.color.backgroundLightGray)
holder.description.setTextColor(ContextCompat.getColor(holder.itemView.context,if(listOfDoctorsTypes[holder.adapterPosition].isChoose) R.color.white else R.color.darkGray))
//-------------------| set layout width and height |---------------------
val params: ViewGroup.LayoutParams = holder.allBox.layoutParams
params.width = 370
params.height = 370
holder.allBox.layoutParams = params
//=======================================================================
//click on card
holder.allBox.setOnClickListener {
doctorCardClick(holder.adapterPosition)
}
}
//-----------------------| Click on card |---------------------------
private fun doctorCardClick(index:Int){
listener.changeType(listOfDoctorsTypes[index].name)
listOfDoctorsTypes.forEach { it.isChoose=false }
listOfDoctorsTypes[index].isChoose = true
notifyDataSetChanged()
}
//===================================================================
}
| 0 |
Kotlin
|
0
| 1 |
e13b29a1be0cda44071d6326fff65025464dc0fd
| 2,622 |
medled-compiled-version
|
The Unlicense
|
feature/search/src/main/kotlin/com/seosh817/moviehub/feature/search/SearchScreen.kt
|
seosh817
| 722,390,551 | false | null |
package com.seosh817.moviehub.feature.search
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemContentType
import androidx.paging.compose.itemKey
import com.seosh817.moviehub.core.designsystem.component.SearchTextField
import com.seosh817.moviehub.core.designsystem.theme.AppDimens
import com.seosh817.moviehub.core.model.MovieType
import com.seosh817.moviehub.core.model.UserMovie
import com.seosh817.ui.ContentsLoading
import com.seosh817.ui.error.ConfirmErrorContents
import com.seosh817.ui.search.SearchRowItem
@Composable
fun SearchRoute(
modifier: Modifier = Modifier,
onMovieClick: (MovieType, Long) -> Unit,
onShowSnackbar: suspend (String, String?, SnackbarDuration) -> Boolean,
viewModel: SearchViewModel = hiltViewModel(),
) {
val searchPagingItems: LazyPagingItems<UserMovie> = viewModel.searchImagePagingItems.collectAsLazyPagingItems()
val query by viewModel.queryStateFlow.collectAsState()
val searchUiEvent by viewModel.searchUiEvent.collectAsState(initial = null)
val searchUiState by viewModel.searchUiState.collectAsState()
SearchScreen(
modifier = modifier,
searchPagingItems = searchPagingItems,
query = query,
searchUiState = searchUiState,
searchUiEvent = searchUiEvent,
onTextChanged = {
viewModel.sendEvent(SearchUiEvent.OnQueryChanged(it))
},
onClearIconClick = {
viewModel.sendEvent(SearchUiEvent.ClearSearchQuery)
},
onShowSnackbar = onShowSnackbar,
onMovieClick = {
onMovieClick(MovieType.POPULAR, it)
},
onBookmarkClick = { userMovie, bookmarked ->
viewModel.sendEvent(SearchUiEvent.OnBookmarkClick(userMovie, bookmarked))
},
)
}
@Composable
fun SearchScreen(
modifier: Modifier = Modifier,
searchPagingItems: LazyPagingItems<UserMovie>,
query: String,
searchUiState: SearchUiState,
searchUiEvent: SearchUiEvent?,
onTextChanged: (String) -> Unit = {},
onClearIconClick: () -> Unit = {},
onMovieClick: (Long) -> Unit,
onShowSnackbar: suspend (String, String?, SnackbarDuration) -> Boolean,
onBookmarkClick: (UserMovie, Boolean) -> Unit,
) {
val bookmarkedSuccessMessage = stringResource(id = R.string.bookmarked_success)
val bookmarkedFailedMessage = stringResource(id = R.string.bookmarked_failed)
val okText = stringResource(id = R.string.ok)
LaunchedEffect(key1 = searchUiEvent) {
when (searchUiEvent) {
is SearchUiEvent.ShowBookmarkedMessage -> {
if (searchUiEvent.isBookmarked) {
onShowSnackbar(bookmarkedSuccessMessage, okText, SnackbarDuration.Short)
} else {
onShowSnackbar(bookmarkedFailedMessage, okText, SnackbarDuration.Short)
}
}
else -> {}
}
}
Column(
modifier = modifier
.background(MaterialTheme.colorScheme.background)
.fillMaxSize()
.statusBarsPadding()
) {
SearchTextField(
modifier = modifier.fillMaxWidth(),
value = query,
hint = stringResource(id = R.string.enter_keyword),
onValueChanged = onTextChanged,
onClickClearKeyword = onClearIconClick
)
SearchContents(
modifier = Modifier
.fillMaxSize(),
query = query,
searchMovieItems = searchPagingItems,
onMovieClick = onMovieClick,
onBookmarkClick = onBookmarkClick
)
}
if (searchUiState is SearchUiState.Loading) {
Box(Modifier.fillMaxSize()) {
ContentsLoading(
modifier = Modifier
.align(Alignment.Center)
)
}
}
}
@Composable
fun SearchContents(
modifier: Modifier,
query: String,
searchMovieItems: LazyPagingItems<UserMovie>,
onMovieClick: (Long) -> Unit,
onBookmarkClick: (UserMovie, Boolean) -> Unit
) {
val lazyListState = rememberLazyListState()
if (query.isEmpty()) {
ConfirmErrorContents(
modifier = modifier.fillMaxSize(),
message = stringResource(id = R.string.search_empty),
)
} else {
when (searchMovieItems.loadState.refresh) {
is LoadState.Loading -> {
ContentsLoading(
modifier = modifier.fillMaxSize(),
)
}
is LoadState.Error -> {
val error = (searchMovieItems.loadState.refresh as LoadState.Error).error
val errorMessage: String
if (error is NoSuchElementException) {
errorMessage = stringResource(id = R.string.no_search_result)
ConfirmErrorContents(
modifier = modifier.fillMaxSize(),
message = errorMessage,
)
} else {
errorMessage = error.message ?: stringResource(id = R.string.refresh_error)
ConfirmErrorContents(
modifier = modifier.fillMaxSize(),
cause = errorMessage,
)
}
}
is LoadState.NotLoading -> {
LazyColumn(
state = lazyListState,
contentPadding = PaddingValues(
horizontal = AppDimens.PaddingSmall,
vertical = AppDimens.PaddingSmall
),
verticalArrangement = Arrangement.spacedBy(AppDimens.PaddingSmall),
) {
items(
count = searchMovieItems.itemCount,
key = searchMovieItems.itemKey(),
contentType = searchMovieItems.itemContentType()
) { index ->
val userMovie: UserMovie? = searchMovieItems[index]
if (userMovie != null) {
SearchRowItem(
modifier = modifier
.fillMaxSize()
.clip(MaterialTheme.shapes.small)
.background(MaterialTheme.colorScheme.background)
.clickable {
onMovieClick.invoke(userMovie.id)
},
userMovie = userMovie,
onClickBookmark = {
onBookmarkClick.invoke(userMovie, !userMovie.isBookmarked)
}
)
}
}
}
}
}
}
}
| 12 | null |
0
| 3 |
774dd544024d1605ec5ac5b99c50fb686f6d7027
| 8,289 |
MovieHub
|
Apache License 2.0
|
kotest-tests/kotest-tests-timeout/src/test/kotlin/com/sksamuel/kotest/timeout/ProjectConfig.kt
|
dimsuz
| 406,852,344 | true |
{"Kotlin": 3184249, "CSS": 352, "Java": 145}
|
package com.sksamuel.kotest.timeout
import io.kotest.core.config.AbstractProjectConfig
import io.kotest.core.spec.SpecExecutionOrder
import kotlin.time.Duration
class ProjectConfig : AbstractProjectConfig() {
override val specExecutionOrder = SpecExecutionOrder.Annotated
override val timeout = Duration.milliseconds(1000)
}
| 0 | null |
0
| 0 |
fdfc73238beec9d15daf5af4315ca9b4589ee739
| 333 |
kotest
|
Apache License 2.0
|
engrave/src/main/java/com/angcyo/engrave/dslitem/EngraveOptionWheelItem.kt
|
angcyo
| 229,037,684 | false | null |
package com.angcyo.engrave.dslitem
import android.content.Context
import com.angcyo.dialog2.dslitem.DslLabelWheelItem
import com.angcyo.dsladapter.DslAdapterItem
import com.angcyo.dsladapter.updateAllItemBy
import com.angcyo.engrave.EngraveHelper
import com.angcyo.engrave.R
import com.angcyo.engrave.data.EngraveOptionInfo
import com.angcyo.library.ex.toHexInt
import com.angcyo.objectbox.laser.pecker.entity.MaterialEntity
import com.angcyo.widget.DslViewHolder
/**
* 雕刻选项item
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/06/02
*/
class EngraveOptionWheelItem : DslLabelWheelItem() {
/**数据*/
var itemEngraveOptionInfo: EngraveOptionInfo? = null
init {
itemLayoutId = R.layout.item_engrave_option_layout
itemWheelSelector = { dialog, index, item ->
//赋值操作
when (itemTag) {
EngraveOptionInfo::material.name -> {
//当切换了材质
itemEngraveOptionInfo?.apply {
val materialEntity = itemWheelList?.get(index) as? MaterialEntity
material = materialEntity?.toText()?.toString() ?: material
power = materialEntity?.power?.toByte() ?: power
depth = materialEntity?.depth?.toByte() ?: depth
//更新其他
_updatePowerDepthItem()
}
}
EngraveOptionInfo::power.name -> {
itemEngraveOptionInfo?.apply {
power = getSelectedByte(index, power)
EngraveHelper.lastPower = power.toHexInt()
//重置为自定义
_updateMaterialItem()
}
}
EngraveOptionInfo::depth.name -> {
itemEngraveOptionInfo?.apply {
depth = getSelectedByte(index, depth)
EngraveHelper.lastDepth = depth.toHexInt()
//重置为自定义
_updateMaterialItem()
}
}
EngraveOptionInfo::time.name -> {
itemEngraveOptionInfo?.apply {
time = getSelectedByte(index, time)
}
}
}
false
}
}
override fun onItemBind(
itemHolder: DslViewHolder,
itemPosition: Int,
adapterItem: DslAdapterItem,
payloads: List<Any>
) {
itemWheelUnit = when (itemTag) {
EngraveOptionInfo::power.name, EngraveOptionInfo::depth.name -> "%"
else -> null
}
super.onItemBind(itemHolder, itemPosition, adapterItem, payloads)
}
override fun showWheelDialog(context: Context) {
super.showWheelDialog(context)
}
/**获取选中的byte数据*/
fun getSelectedByte(index: Int, def: Byte): Byte =
itemWheelList?.get(index)?.toString()?.toIntOrNull()?.toByte() ?: def
/**更新功率/深度的数据*/
fun _updatePowerDepthItem() {
itemDslAdapter?.updateAllItemBy {
if (it is EngraveOptionWheelItem) {
if (it.itemTag == EngraveOptionInfo::power.name) {
//功率
it.itemSelectedIndex = EngraveHelper.findOptionIndex(
it.itemWheelList,
itemEngraveOptionInfo?.power
)
true
} else if (it.itemTag == EngraveOptionInfo::depth.name) {
//深度
it.itemSelectedIndex = EngraveHelper.findOptionIndex(
it.itemWheelList,
itemEngraveOptionInfo?.depth
)
true
} else {
false
}
} else {
false
}
}
}
/**重置为自定义*/
fun _updateMaterialItem() {
itemDslAdapter?.updateAllItemBy {
if (it is EngraveOptionWheelItem && it.itemTag == EngraveOptionInfo::material.name) {
//材质item, 选中第一个, 自定义
it.itemSelectedIndex = 0
true
} else {
false
}
}
}
}
| 0 |
Kotlin
|
4
| 2 |
96a6ea873c8486a06525e752038ab2630b3c86ca
| 4,302 |
UICoreEx
|
MIT License
|
src/main/kotlin/table/x055.kt
|
oklookat
| 808,293,457 | false |
{"Kotlin": 806745, "Python": 4615}
|
package table
internal val x055 = listOf(
"You ", // 0x00
"Yan ", // 0x01
"Gu ", // 0x02
"Gu ", // 0x03
"Bai ", // 0x04
"Han ", // 0x05
"Suo ", // 0x06
"Chun ", // 0x07
"Yi ", // 0x08
"Ai ", // 0x09
"Jia ", // 0x0a
"Tu ", // 0x0b
"Xian ", // 0x0c
"Huan ", // 0x0d
"Li ", // 0x0e
"Xi ", // 0x0f
"Tang ", // 0x10
"Zuo ", // 0x11
"Qiu ", // 0x12
"Che ", // 0x13
"Wu ", // 0x14
"Zao ", // 0x15
"Ya ", // 0x16
"Dou ", // 0x17
"Qi ", // 0x18
"Di ", // 0x19
"Qin ", // 0x1a
"Ma ", // 0x1b
"Mal ", // 0x1c
"Hong ", // 0x1d
"Dou ", // 0x1e
"Kes ", // 0x1f
"Lao ", // 0x20
"Liang ", // 0x21
"Suo ", // 0x22
"Zao ", // 0x23
"Huan ", // 0x24
"Lang ", // 0x25
"Sha ", // 0x26
"Ji ", // 0x27
"Zuo ", // 0x28
"Wo ", // 0x29
"Feng ", // 0x2a
"Yin ", // 0x2b
"Hu ", // 0x2c
"Qi ", // 0x2d
"Shou ", // 0x2e
"Wei ", // 0x2f
"Shua ", // 0x30
"Chang ", // 0x31
"Er ", // 0x32
"Li ", // 0x33
"Qiang ", // 0x34
"An ", // 0x35
"Jie ", // 0x36
"Yo ", // 0x37
"Nian ", // 0x38
"Yu ", // 0x39
"Tian ", // 0x3a
"Lai ", // 0x3b
"Sha ", // 0x3c
"Xi ", // 0x3d
"Tuo ", // 0x3e
"Hu ", // 0x3f
"Ai ", // 0x40
"Zhou ", // 0x41
"Nou ", // 0x42
"Ken ", // 0x43
"Zhuo ", // 0x44
"Zhuo ", // 0x45
"Shang ", // 0x46
"Di ", // 0x47
"Heng ", // 0x48
"Lan ", // 0x49
"A ", // 0x4a
"Xiao ", // 0x4b
"Xiang ", // 0x4c
"Tun ", // 0x4d
"Wu ", // 0x4e
"Wen ", // 0x4f
"Cui ", // 0x50
"Sha ", // 0x51
"Hu ", // 0x52
"Qi ", // 0x53
"Qi ", // 0x54
"Tao ", // 0x55
"Dan ", // 0x56
"Dan ", // 0x57
"Ye ", // 0x58
"Zi ", // 0x59
"Bi ", // 0x5a
"Cui ", // 0x5b
"Chuo ", // 0x5c
"He ", // 0x5d
"Ya ", // 0x5e
"Qi ", // 0x5f
"Zhe ", // 0x60
"Pei ", // 0x61
"Liang ", // 0x62
"Xian ", // 0x63
"Pi ", // 0x64
"Sha ", // 0x65
"La ", // 0x66
"Ze ", // 0x67
"Qing ", // 0x68
"Gua ", // 0x69
"Pa ", // 0x6a
"Zhe ", // 0x6b
"Se ", // 0x6c
"Zhuan ", // 0x6d
"Nie ", // 0x6e
"Guo ", // 0x6f
"Luo ", // 0x70
"Yan ", // 0x71
"Di ", // 0x72
"Quan ", // 0x73
"Tan ", // 0x74
"Bo ", // 0x75
"Ding ", // 0x76
"Lang ", // 0x77
"Xiao ", // 0x78
"", // 0x79
"Tang ", // 0x7a
"Chi ", // 0x7b
"Ti ", // 0x7c
"An ", // 0x7d
"Jiu ", // 0x7e
"Dan ", // 0x7f
"Ke ", // 0x80
"Yong ", // 0x81
"Wei ", // 0x82
"Nan ", // 0x83
"Shan ", // 0x84
"Yu ", // 0x85
"Zhe ", // 0x86
"La ", // 0x87
"Jie ", // 0x88
"Hou ", // 0x89
"Han ", // 0x8a
"Die ", // 0x8b
"Zhou ", // 0x8c
"Chai ", // 0x8d
"Wai ", // 0x8e
"Re ", // 0x8f
"Yu ", // 0x90
"Yin ", // 0x91
"Zan ", // 0x92
"Yao ", // 0x93
"Wo ", // 0x94
"Mian ", // 0x95
"Hu ", // 0x96
"Yun ", // 0x97
"Chuan ", // 0x98
"Hui ", // 0x99
"Huan ", // 0x9a
"Huan ", // 0x9b
"Xi ", // 0x9c
"He ", // 0x9d
"Ji ", // 0x9e
"Kui ", // 0x9f
"Zhong ", // 0xa0
"Wei ", // 0xa1
"Sha ", // 0xa2
"Xu ", // 0xa3
"Huang ", // 0xa4
"Du ", // 0xa5
"Nie ", // 0xa6
"Xuan ", // 0xa7
"Liang ", // 0xa8
"Yu ", // 0xa9
"Sang ", // 0xaa
"Chi ", // 0xab
"Qiao ", // 0xac
"Yan ", // 0xad
"Dan ", // 0xae
"Pen ", // 0xaf
"Can ", // 0xb0
"Li ", // 0xb1
"Yo ", // 0xb2
"Zha ", // 0xb3
"Wei ", // 0xb4
"Miao ", // 0xb5
"Ying ", // 0xb6
"Pen ", // 0xb7
"Phos ", // 0xb8
"Kui ", // 0xb9
"Xi ", // 0xba
"Yu ", // 0xbb
"Jie ", // 0xbc
"Lou ", // 0xbd
"Ku ", // 0xbe
"Sao ", // 0xbf
"Huo ", // 0xc0
"Ti ", // 0xc1
"Yao ", // 0xc2
"He ", // 0xc3
"A ", // 0xc4
"Xiu ", // 0xc5
"Qiang ", // 0xc6
"Se ", // 0xc7
"Yong ", // 0xc8
"Su ", // 0xc9
"Hong ", // 0xca
"Xie ", // 0xcb
"Yi ", // 0xcc
"Suo ", // 0xcd
"Ma ", // 0xce
"Cha ", // 0xcf
"Hai ", // 0xd0
"Ke ", // 0xd1
"Ta ", // 0xd2
"Sang ", // 0xd3
"Tian ", // 0xd4
"Ru ", // 0xd5
"Sou ", // 0xd6
"Wa ", // 0xd7
"Ji ", // 0xd8
"Pang ", // 0xd9
"Wu ", // 0xda
"Xian ", // 0xdb
"Shi ", // 0xdc
"Ge ", // 0xdd
"Zi ", // 0xde
"Jie ", // 0xdf
"Luo ", // 0xe0
"Weng ", // 0xe1
"Wa ", // 0xe2
"Si ", // 0xe3
"Chi ", // 0xe4
"Hao ", // 0xe5
"Suo ", // 0xe6
"Jia ", // 0xe7
"Hai ", // 0xe8
"Suo ", // 0xe9
"Qin ", // 0xea
"Nie ", // 0xeb
"He ", // 0xec
"Cis ", // 0xed
"Sai ", // 0xee
"Ng ", // 0xef
"Ge ", // 0xf0
"Na ", // 0xf1
"Dia ", // 0xf2
"Ai ", // 0xf3
"", // 0xf4
"Tong ", // 0xf5
"Bi ", // 0xf6
"Ao ", // 0xf7
"Ao ", // 0xf8
"Lian ", // 0xf9
"Cui ", // 0xfa
"Zhe ", // 0xfb
"Mo ", // 0xfc
"Sou ", // 0xfd
"Sou ", // 0xfe
"Tan ", // 0xff
)
| 0 |
Kotlin
|
0
| 0 |
b85c17dfaeef152a7d8313f612570149d0b6acba
| 4,112 |
unidecode4k
|
MIT License
|
app/src/main/java/com/foxek/simpletimer/presentation/round/RoundAdapter.kt
|
Foxek
| 152,570,565 | false | null |
package com.foxek.simpletimer.presentation.round
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import com.foxek.simpletimer.R
import com.foxek.simpletimer.data.model.Round
import com.foxek.simpletimer.common.utils.Constants.EMPTY
import com.foxek.simpletimer.common.utils.Constants.WITH_REST_TYPE
import com.foxek.simpletimer.common.utils.formatIntervalData
import com.foxek.simpletimer.common.utils.formatIntervalNumber
import com.foxek.simpletimer.presentation.base.BaseAdapter
import com.foxek.simpletimer.presentation.base.BaseDiffCallback
import kotlinx.android.synthetic.main.item_round.view.*
class RoundAdapter : BaseAdapter<Round, RoundAdapter.ViewHolder>() {
var clickListener: ((round: Round) -> Unit)? = null
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
// small fix
holder.itemView.post {
notifyItemRangeChanged(holder.layoutPosition + 1, itemCount)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return with(parent) {
LayoutInflater.from(context).inflate(R.layout.item_round, this, false)
}.run(::ViewHolder)
}
override fun getDiffCallback(oldItems: List<Round>, newItems: List<Round>): DiffUtil.Callback? {
return object : BaseDiffCallback<Round>(oldItems, newItems) {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return oldItem.workInterval == newItem.workInterval
&& oldItem.restInterval == newItem.restInterval
&& oldItem.name == newItem.name
&& oldItem.type == newItem.type
&& oldItem.positionInWorkout == newItem.positionInWorkout
}
}
}
inner class ViewHolder constructor(view: View) : BaseViewHolder<Round>(view) {
override fun bind(model: Round) {
itemView.apply {
item_interval_work_time.text = formatIntervalData(model.workInterval)
if (model.type == WITH_REST_TYPE) {
item_interval_rest_time.text = formatIntervalData(model.restInterval)
item_interval_rest_hint.text = resources.getString(R.string.timer_rest_time)
} else {
item_interval_rest_time.text = ""
item_interval_rest_hint.text = resources.getString(R.string.timer_without_rest)
}
item_interval_title.text = if (model.name == EMPTY) {
formatIntervalNumber(model.positionInWorkout + 1)
} else {
model.name
}
setOnClickListener { clickListener?.invoke(model) }
}
}
}
}
| 0 |
Kotlin
|
1
| 5 |
74a69a2e4d90d57104271eec0b81baaedb41dad1
| 3,298 |
WiseTimer
|
Apache License 2.0
|
save-backend/src/main/kotlin/com/saveourtool/save/backend/storage/TestsSourceSnapshotStorage.kt
|
saveourtool
| 300,279,336 | false | null |
package com.saveourtool.save.backend.storage
import com.saveourtool.save.backend.configs.ConfigProperties
import com.saveourtool.save.backend.repository.*
import com.saveourtool.save.backend.service.ExecutionService
import com.saveourtool.save.backend.service.TestSuitesService
import com.saveourtool.save.entities.TestSuitesSource
import com.saveourtool.save.entities.TestsSourceSnapshot
import com.saveourtool.save.entities.TestsSourceSnapshot.Companion.toEntity
import com.saveourtool.save.request.TestFilesRequest
import com.saveourtool.save.storage.AbstractStorageWithDatabase
import com.saveourtool.save.storage.concatS3Key
import com.saveourtool.save.test.TestFilesContent
import com.saveourtool.save.test.TestsSourceSnapshotDto
import com.saveourtool.save.utils.*
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.core.io.buffer.DataBufferUtils
import org.springframework.core.io.buffer.DefaultDataBufferFactory
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import software.amazon.awssdk.services.s3.S3AsyncClient
import kotlin.io.path.*
/**
* Storage for snapshots of [com.saveourtool.save.entities.TestSuitesSource]
*/
@Component
class TestsSourceSnapshotStorage(
configProperties: ConfigProperties,
s3Client: S3AsyncClient,
testsSourceSnapshotRepository: TestsSourceSnapshotRepository,
private val testSuitesSourceRepository: TestSuitesSourceRepository,
private val testSuitesService: TestSuitesService,
private val executionService: ExecutionService,
) : AbstractStorageWithDatabase<TestsSourceSnapshotDto, TestsSourceSnapshot, TestsSourceSnapshotRepository>(
s3Client,
configProperties.s3Storage.bucketName,
concatS3Key(configProperties.s3Storage.prefix, "tests-source-snapshot"),
testsSourceSnapshotRepository
) {
override fun createNewEntityFromDto(dto: TestsSourceSnapshotDto): TestsSourceSnapshot = dto.toEntity { testSuitesSourceRepository.getByIdOrNotFound(it) }
override fun findByDto(
dto: TestsSourceSnapshotDto
): TestsSourceSnapshot? = repository.findBySourceIdAndCommitId(
sourceId = dto.sourceId,
commitId = dto.commitId,
)
override fun beforeDelete(entity: TestsSourceSnapshot) {
executionService.unlinkTestSuitesFromAllExecution(testSuitesService.getBySourceSnapshot(entity))
}
/**
* @param request
* @return [TestFilesContent] filled with test files
*/
fun getTestContent(request: TestFilesRequest): Mono<TestFilesContent> {
val tmpSourceDir = createTempDirectory("source-")
val tmpArchive = createTempFile(tmpSourceDir, "archive-", ARCHIVE_EXTENSION)
val sourceContent = download(request.testsSourceSnapshot)
.map { DefaultDataBufferFactory.sharedInstance.wrap(it) }
.cast(DataBuffer::class.java)
return DataBufferUtils.write(sourceContent, tmpArchive.outputStream())
.map { DataBufferUtils.release(it) }
.collectList()
.map {
tmpArchive.extractZipHere()
tmpArchive.deleteExisting()
}
.map {
val testFilePath = request.test.filePath
val additionalTestFilePath = request.test.additionalFiles.firstOrNull()
val result = TestFilesContent(
tmpSourceDir.resolve(testFilePath).readLines(),
additionalTestFilePath?.let { tmpSourceDir.resolve(it).readLines() },
)
tmpSourceDir.toFile().deleteRecursively()
result
}
}
/**
* @param testSuitesSource
* @return true if all [TestsSourceSnapshot] (found by [testSuitesSource]) deleted successfully, otherwise -- false
*/
fun deleteAll(testSuitesSource: TestSuitesSource): Mono<Boolean> = blockingToFlux { repository.findAllBySource(testSuitesSource) }
.flatMap { delete(it.toDto()) }
.all { it }
}
| 160 |
Kotlin
|
1
| 31 |
d83a26b101c0f809d39a6deab4e183de04cc7832
| 4,000 |
save-cloud
|
MIT License
|
MuvieAndroidApp/src/main/java/com/teewhydope/muvieapp/android/di/CoilModule.kt
|
teewhydope
| 408,187,945 | false | null |
package com.teewhydope.muvieapp.android.di
import android.app.Application
import coil.ImageLoader
import com.teewhydope.muvieapp.android.R
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
//Hilt Coil Module Setup
@InstallIn(SingletonComponent::class)
@Module
object CoilModule {
@Provides
@Singleton
fun provideImageLoader(app: Application): ImageLoader{
return ImageLoader.Builder(app)
.error(R.drawable.black_background)
.placeholder(R.drawable.black_background)
.availableMemoryPercentage(0.25) // Don't know what is recommended?
.crossfade(true)
.build()
}
}
| 1 | null |
1
| 4 |
22ba7cbc9c911ee57604a775d6f62bb66d5a5e23
| 752 |
MuvieApp
|
MIT License
|
kotlin-antd/antd-samples/src/main/kotlin/samples/avatar/Basic.kt
|
PCasafont
| 284,043,514 | true |
{"Kotlin": 1197947, "CSS": 29526, "HTML": 6470, "JavaScript": 980}
|
package samples.avatar
import antd.avatar.avatar
import kotlinx.html.id
import react.*
import react.dom.*
fun RBuilder.basic() {
div("avatar-container") {
attrs.id = "avatar-basic"
div {
div {
avatar {
attrs {
size = 64
icon = "user"
}
}
avatar {
attrs {
size = "large"
icon = "user"
}
}
avatar {
attrs.icon = "user"
}
avatar {
attrs {
size = "small"
icon = "user"
}
}
}
div {
avatar {
attrs {
shape = "square"
size = 64
icon = "user"
}
}
avatar {
attrs {
shape = "square"
size = "large"
icon = "user"
}
}
avatar {
attrs {
shape = "square"
icon = "user"
}
}
avatar {
attrs {
shape = "square"
size = "small"
icon = "user"
}
}
}
}
}
}
| 0 | null |
0
| 0 |
29d81bd5e8d27b239550aaa9725d912a9a5768f4
| 1,679 |
kotlin-js-wrappers
|
Apache License 2.0
|
src/test/kotlin/no/java/mooseheadreborn/repository/ParticipantRepositoryMock.kt
|
javaBin
| 835,594,711 | false |
{"Kotlin": 71034, "TypeScript": 53888, "HTML": 3293, "Shell": 1428, "Procfile": 180, "CSS": 21}
|
package no.java.mooseheadreborn.repository
import no.java.mooseheadreborn.jooq.public_.tables.records.*
import java.time.*
class ParticipantRepositoryMock:ParticipantRepository {
val participantStore:MutableList<ParticiantRecord> = mutableListOf()
val partRegistrationStore:MutableList<ParticipantRegistrationRecord> = mutableListOf()
override fun addParticipantRegistration(participantRegistrationRecord: ParticipantRegistrationRecord) {
partRegistrationStore.add(participantRegistrationRecord)
}
override fun addParticipant(particiantRecord: ParticiantRecord): ParticiantRecord {
participantStore.add(particiantRecord)
return particiantRecord
}
override fun participantRegistrationByParticipantId(participantId: String): List<ParticipantRegistrationRecord> =
partRegistrationStore.filter { it.particiapantId == participantId }
override fun participantRegistrationByRegisterKey(registerKey: String): ParticipantRegistrationRecord? = partRegistrationStore.firstOrNull { it.registerToken == registerKey }
override fun participantByEmail(email: String): ParticiantRecord? = participantStore.firstOrNull { it.email == email }
override fun participantByAccessKey(accessKey: String): ParticiantRecord? = participantStore.firstOrNull { it.accessKey == accessKey }
override fun participantById(participantId: String): ParticiantRecord? = participantStore.firstOrNull { it.id == participantId }
override fun setActive(id: String) {
val particiantRecord:ParticiantRecord = participantStore.firstOrNull { it.id == id }?:return
particiantRecord.activatedAt = OffsetDateTime.now()
}
override fun allParticipants(): List<ParticiantRecord> = participantStore
override fun updateAccessKey(id: String, accessKey: String) {
val particiantRecord:ParticiantRecord = participantStore.firstOrNull { it.id == id }?:return
particiantRecord.accessKey = accessKey
}
override fun setParticipantRegistrationUsed(participantRegistrationRecordId: String) {
val participantRegistrationRecord:ParticipantRegistrationRecord = partRegistrationStore.firstOrNull { it.id == participantRegistrationRecordId }?:return
participantRegistrationRecord.usedAt = OffsetDateTime.now()
}
}
| 0 |
Kotlin
|
0
| 0 |
96a1e41030a870e921acc9a90fb3dbe538c3a9c8
| 2,309 |
mooseheadreborn
|
Apache License 2.0
|
domain/src/main/java/com/doctoror/fuckoffmusicplayer/domain/genres/GenresProvider.kt
|
Doctoror
| 72,659,203 | false | null |
/*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.doctoror.fuckoffmusicplayer.domain.genres
import android.database.Cursor
import io.reactivex.Observable
const val COLUMN_ID = 0
const val COLUMN_NAME = 1
interface GenresProvider {
fun load(): Observable<Cursor>
fun load(searchFilter: String?): Observable<Cursor>
}
| 1 | null |
17
| 77 |
1de98b8e5a6513fa41374a432d47122075187ad4
| 886 |
PainlessMusicPlayer
|
Apache License 2.0
|
subscription-service/src/test/kotlin/com/egm/stellio/subscription/SubscriptionServiceApplicationTests.kt
|
vraybaud
| 341,897,203 | true |
{"Kotlin": 893927, "Shell": 5950, "Dockerfile": 844}
|
package com.egm.stellio.subscription
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class SubscriptionServiceApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | null |
0
| 0 |
e2c9ee575eaf3397f6262618c98356fe0dbd6d6a
| 237 |
stellio-context-broker
|
Apache License 2.0
|
app/src/main/java/com/gmail/hamedvakhide/instaclone/repository/FirebaseRepository.kt
|
hamooo90
| 386,210,737 | false | null |
package com.gmail.hamedvakhide.instaclone.repository
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import com.gmail.hamedvakhide.instaclone.model.Comment
import com.gmail.hamedvakhide.instaclone.model.Post
import com.gmail.hamedvakhide.instaclone.model.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthException
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.tasks.await
import java.lang.Exception
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class FirebaseRepository @Inject constructor(
private val firebaseAuth: FirebaseAuth,
private val firebaseDatabase: FirebaseDatabase,
private val firebaseStorage: FirebaseStorage
) : FirebaseRepoInterface {
val postsMutableLiveDataList =
MutableLiveData<MutableList<Post>>() // contains list of all posts that current user follow their publisher
val isPostsLikedByCurrentUserMutableLiveDataList =
MutableLiveData<MutableList<Boolean>>() // a list that shows posts are liked by user or not
val postsLikesNumberMutableLiveDataList = MutableLiveData<MutableList<Long>>()
val postsCommentsNumberMutableLiveDataList = MutableLiveData<MutableList<Long>>()
val postsPublishersInfoMutableLiveDataList = MutableLiveData<MutableList<User>>()
val commentsPublishersInfoMutableLiveDataList = MutableLiveData<MutableList<User>>()
/////////////////////// auth //////////////////////////
suspend fun login(email: String, password: String): String {
firebaseAuth.signInWithEmailAndPassword(email, password).await()
return firebaseAuth.currentUser?.email ?: throw FirebaseAuthException("", "")
}
suspend fun register(
fullName: String,
userName: String,
email: String,
password: String
): String {
return try {
val data = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
val currentUserId = getUserId()
val userMap = HashMap<String, Any>()
userMap["uid"] = currentUserId
userMap["fullname"] = fullName.toLowerCase(Locale.getDefault())
userMap["username"] = userName.toLowerCase(Locale.getDefault())
userMap["email"] = email
userMap["bio"] = "This bio is empty"
userMap["image"] =
"https://firebasestorage.googleapis.com/v0/b/instaclone-365b0.appspot.com/o/Default%20images%2Fprofile.png?alt=media&token=<PASSWORD>"
/////add user info in db
firebaseDatabase.reference.child("Users").child(currentUserId).setValue(userMap).await()
////add user in user following list!!
////see your post in home fragment
firebaseDatabase.reference.child("Follow")
.child(currentUserId)
.child("Following").child(currentUserId)
.setValue(true)
data.user?.email.toString()
} catch (e: Exception) {
firebaseAuth.signOut()
e.message.toString()
}
}
fun signOut() {
firebaseAuth.signOut()
}
fun getUserId(): String{
return firebaseAuth.currentUser!!.uid
}
/////////////////////// auth //////////////////////////
//////////////// firebase read ///////////////////
fun getPosts() {
val followingList: MutableList<String> = ArrayList()
var postList: MutableList<Post> = ArrayList()
val postsRef = firebaseDatabase
.reference
.child("Posts")
val followingRef = firebaseDatabase
.reference.child("Follow").child(firebaseAuth.currentUser!!.uid).child("Following")
followingRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
(followingList as ArrayList<String>).clear()
for (item in snapshot.children) {
item.key?.let { (followingList as ArrayList<String>).add(it) }
}
//////////get posts////////
postsRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
postList.clear()
for (item in snapshot.children) {
val post = item.getValue(Post::class.java)
for (userId in followingList!!) {
if (post!!.getPublisher() == userId) {
postList.add(post)
}
postsMutableLiveDataList.postValue(postList)
}
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
fun isPostsLiked(postsList: MutableList<Post>) {
val postLikedList: MutableList<Boolean> = ArrayList()
postLikedList.clear()
var counter = 0
for (post in postsList) {
counter++
val likeRef = firebaseDatabase.reference
.child("Likes")
.child(post.getPostId())
.child(getUserId())
likeRef.addValueEventListener(object : ValueEventListener {
val position = counter - 1
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
if (postLikedList.size < postsList.size) {
postLikedList.add(true)
} else {
postLikedList[position] = true
}
} else {
if (postLikedList.size < postsList.size) {
postLikedList.add(false)
} else {
postLikedList[position] = false
}
}
isPostsLikedByCurrentUserMutableLiveDataList.postValue(postLikedList)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
fun getPostsLikesNumber(postsList: MutableList<Post>) {
val postsLikesNumberList: MutableList<Long> = ArrayList()
postsLikesNumberList.clear()
var counter = 0
for (post in postsList) {
counter++
val likeRef = firebaseDatabase.reference
.child("Likes")
.child(post.getPostId())
likeRef.addValueEventListener(object : ValueEventListener {
val position = counter - 1
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
if (postsLikesNumberList.size < postsList.size) {
postsLikesNumberList.add(snapshot.childrenCount)
} else {
postsLikesNumberList[position] = snapshot.childrenCount
}
} else {
if (postsLikesNumberList.size < postsList.size) {
postsLikesNumberList.add(0)
} else {
postsLikesNumberList[position] = 0
}
}
postsLikesNumberMutableLiveDataList.postValue(postsLikesNumberList)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
fun getPostsCommentsNumber(postsList: MutableList<Post>) {
val postsCommentsNumberList: MutableList<Long> = ArrayList()
postsCommentsNumberList.clear()
var counter = 0
for (post in postsList) {
counter++
val commentsRef = firebaseDatabase.reference
.child("comments")
.child(post.getPostId())
commentsRef.addValueEventListener(object : ValueEventListener {
val position = counter - 1
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
if (postsCommentsNumberList.size < postsList.size) {
postsCommentsNumberList.add(snapshot.childrenCount)
} else {
postsCommentsNumberList[position] = snapshot.childrenCount
}
} else {
if (postsCommentsNumberList.size < postsList.size) {
postsCommentsNumberList.add(0)
} else {
postsCommentsNumberList[position] = 0
}
}
postsCommentsNumberMutableLiveDataList.postValue(postsCommentsNumberList)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
fun getPostsPublishersInfo(postsList: MutableList<Post>) {
val postsPublishersInfoList: MutableList<User> = ArrayList()
postsPublishersInfoList.clear()
var counter = 0
for (post in postsList) {
if (postsPublishersInfoList.size < postsList.size) {
postsPublishersInfoList.add(User())
}
counter++
val userRef = firebaseDatabase.reference
.child("Users")
.child(post.getPublisher())
userRef.addValueEventListener(object : ValueEventListener {
var position = counter - 1
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val user = snapshot.getValue<User>(User::class.java)
postsPublishersInfoList[position] = user!!
}
postsPublishersInfoMutableLiveDataList.postValue(postsPublishersInfoList)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
@ExperimentalCoroutinesApi
override fun getPostComments(postId: String) = callbackFlow<Result<List<Comment>>> {
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val items = snapshot.children.map { ds ->
ds.getValue(Comment::class.java)
}
[email protected]<Result<List<Comment>>>(Result.success(items.filterNotNull()))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<List<Comment>>>(Result.failure(error.toException()))
}
}
firebaseDatabase
.reference
.child("comments")
.child(postId).addValueEventListener(listener)
awaitClose {
firebaseDatabase
.reference
.child("comments")
.child(postId).removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun getCurrentUserProfilePic() = callbackFlow<Result<String>> {
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var userImg = ""
if (snapshot.exists()) {
val user = snapshot.getValue<User>(User::class.java)
userImg = user!!.getImage()
}
[email protected](Result.success(userImg))
}
override fun onCancelled(error: DatabaseError) {
[email protected](Result.failure(error.toException()))
}
}
val singleUserRef = firebaseDatabase.reference.child("Users").child(firebaseAuth.currentUser!!.uid)
singleUserRef.addListenerForSingleValueEvent(listener)
awaitClose {
singleUserRef.removeEventListener(listener)
}
}
fun getCommentsPublisherInfo(commentsList: MutableList<Comment>){
val commentsPublisherInfoList : MutableList<User> = ArrayList()
commentsPublisherInfoList.clear()
var counter = 0
for (comment in commentsList) {
counter++
val userRef = firebaseDatabase.reference
.child("Users")
.child(comment.getPublisher())
userRef.addValueEventListener(object :ValueEventListener{
val position = counter-1
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
val user = snapshot.getValue<User>(User::class.java)
if(commentsPublisherInfoList.size < commentsList.size){
commentsPublisherInfoList.add(user!!)
}else{
commentsPublisherInfoList[position] = user!!
}
}
commentsPublishersInfoMutableLiveDataList.postValue(commentsPublisherInfoList)
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
@ExperimentalCoroutinesApi
override fun getUserInfo(userId: String) = callbackFlow<Result<User>> {
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var user = User()
if (snapshot.exists()) {
user = snapshot.getValue<User>(User::class.java)!!
}
[email protected]<Result<User>>(Result.success(user))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<User>>(Result.failure(error.toException()))
}
}
val singleUserRef = firebaseDatabase.reference.child("Users").child(userId)
singleUserRef.addValueEventListener(listener)
awaitClose {
singleUserRef.removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun getUserFollowers(userId: String) = callbackFlow<Result<List<String>>> {
val followerList : List<String> = ArrayList()
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(followerList as ArrayList<String>).clear()
if(snapshot.exists()){
for (item in snapshot.children) {
item.key?.let { (followerList as ArrayList<String>).add(it) }
}
}
[email protected]<Result<List<String>>>(Result.success(followerList))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<List<String>>>(Result.failure(error.toException()))
}
}
val followerRef = firebaseDatabase
.reference.child("Follow").child(userId).child("Follower")
followerRef.addValueEventListener(listener)
awaitClose {
followerRef.removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun getUserFollowings(userId: String) = callbackFlow<Result<List<String>>> {
val followingList : List<String> = ArrayList()
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(followingList as ArrayList<String>).clear()
if(snapshot.exists()){
for (item in snapshot.children) {
item.key?.let { (followingList as ArrayList<String>).add(it) }
}
}
[email protected]<Result<List<String>>>(Result.success(followingList))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<List<String>>>(Result.failure(error.toException()))
}
}
val followerRef = firebaseDatabase
.reference.child("Follow").child(userId).child("Following")
followerRef.addListenerForSingleValueEvent(listener)
awaitClose {
followerRef.removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun getUserPosts(userId: String) = callbackFlow<Result<List<Post>>> {
val postList: List<Post> = ArrayList()
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(postList as ArrayList<Post>).clear()
if(snapshot.exists()){
for(item in snapshot.children){
val post = item.getValue(Post::class.java)
if (post!!.getPublisher() == userId) {
postList.add(post)
}
}
}
[email protected]<Result<List<Post>>>(Result.success(postList))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<List<Post>>>(Result.failure(error.toException()))
}
}
val postsRef = firebaseDatabase
.reference
.child("Posts")
postsRef.addValueEventListener(listener)
awaitClose {
postsRef.removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun searchUser(text: String) = callbackFlow<Result<List<User>>> {
val userList: List<User> = ArrayList()
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
(userList as ArrayList<User>).clear()
if(snapshot.exists()){
for(item in snapshot.children){
val user = item.getValue(User::class.java)
if (user != null && user.getUid() != getUserId()) {
userList.add(user)
}
}
}
[email protected]<Result<List<User>>>(Result.success(userList))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<List<User>>>(Result.failure(error.toException()))
}
}
val query = firebaseDatabase.reference
.child("Users")
.orderByChild("fullname")
.startAt(text).endAt(text+"\uf8ff")
query.addValueEventListener(listener)
awaitClose {
query.removeEventListener(listener)
}
}
@ExperimentalCoroutinesApi
override fun isUserFollowed(userId: String) = callbackFlow<Result<Boolean>>{
val listener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
var isFollowed = false
if (snapshot.child(userId).exists()) {
isFollowed = true
}
[email protected]<Result<Boolean>>(Result.success(isFollowed))
}
override fun onCancelled(error: DatabaseError) {
[email protected]<Result<Boolean>>(Result.failure(error.toException()))
}
}
val followingRef = firebaseDatabase.reference
.child("Follow")
.child(getUserId())
.child("Following")
followingRef.addValueEventListener(listener)
awaitClose {
followingRef.removeEventListener(listener)
}
}
//////////////// firebase read ///////////////////
//////////////// firebase write //////////////////
suspend fun likePost(postId: String) {
firebaseDatabase.reference
.child("Likes")
.child(postId)
.child(firebaseAuth.currentUser!!.uid)
.setValue(true)
.await()
}
suspend fun unLikePost(postId: String) {
firebaseDatabase.reference
.child("Likes")
.child(postId)
.child(firebaseAuth.currentUser!!.uid)
.removeValue()
.await()
}
suspend fun follow(userId: String) {
try {
firebaseDatabase.reference
.child("Follow")
.child(getUserId())
.child("Following")
.child(userId)
.setValue(true)
.await()
firebaseDatabase.reference
.child("Follow")
.child(userId)
.child("Follower")
.child(getUserId())
.setValue(true)
.await()
} catch (e: Exception){
e.printStackTrace()
}
}
suspend fun unFollow(userId: String) {
try {
firebaseDatabase.reference
.child("Follow")
.child(getUserId())
.child("Following")
.child(userId)
.removeValue()
.await()
firebaseDatabase.reference
.child("Follow")
.child(userId)
.child("Follower")
.child(getUserId())
.removeValue()
.await()
} catch (e: Exception){
e.printStackTrace()
}
}
suspend fun updateUserProfileInfo(fullName: String, userName: String, bio: String): Boolean{
val userMap = HashMap<String, Any>()
userMap["fullname"] = fullName
userMap["username"] = userName
userMap["bio"] = bio
///
return try {
firebaseDatabase.reference.child("Users").child(getUserId()).updateChildren(userMap).await()
true
} catch (e: Exception){
e.printStackTrace()
false
}
}
suspend fun updateUserProfileInfoWithImage(fullName: String, userName: String, bio: String, imageUrl: String): Boolean{
val userMap = HashMap<String, Any>()
userMap["fullname"] = fullName
userMap["username"] = userName
userMap["bio"] = bio
userMap["image"] = imageUrl
///
return try {
firebaseDatabase.reference.child("Users").child(getUserId()).updateChildren(userMap).await()
true
} catch (e: Exception){
e.printStackTrace()
false
}
}
suspend fun uploadImage(imageUri: Uri, isPost: Boolean): String{
var storageProfilePicsRef = firebaseStorage.reference.child("ProfilePics")
val userId = getUserId()
var picRef = storageProfilePicsRef.child("$userId.jpg")
if(isPost) {
storageProfilePicsRef = firebaseStorage.reference.child("PostPics")
picRef = storageProfilePicsRef.child(System.currentTimeMillis().toString() + ".jpg")
}
return try {
// upload image
val taskUpload = picRef.putFile(imageUri).await()
// get uploaded image url
val dlUrl = taskUpload.task.snapshot.storage.downloadUrl.await()
dlUrl.toString()
} catch (e:Exception){
e.printStackTrace()
""
}
}
suspend fun addNewPost(caption: String, imageUrl: String): Boolean{
val postsRef = firebaseDatabase.reference
.child("Posts")
/// Creates a random key
val postId = postsRef.push().key
val postMap = HashMap<String, Any>()
postMap["postId"] = postId!!
postMap["caption"] = caption
postMap["publisher"] = getUserId()
postMap["image"] = imageUrl
return try {
postsRef.child(postId).updateChildren(postMap).await()
true
} catch (e: Exception){
e.printStackTrace()
false
}
}
suspend fun addComment(comment: String, postId: String) : String {
val commentRef = firebaseDatabase.reference
.child("comments")
.child(postId)
val commentMap = HashMap<String, Any>()
val commentId = commentRef.push().key
commentMap["comment"] = comment
commentMap["publisher"] = firebaseAuth.currentUser!!.uid
commentMap["commentId"] = commentId!!
return try {
commentRef.child(commentId).setValue(commentMap).await()
"done"
} catch (e: Exception) {
"failed"
}
}
//////////////// firebase write //////////////////
}
| 0 |
Kotlin
|
0
| 0 |
1e9c3bb3ec42cd63b7124029b729f7431402eaed
| 25,933 |
InstaClone_Kotlin_MVVM
|
Apache License 2.0
|
basic-images/src/commonMain/kotlin/app/lexilabs/basic/images/BasicUrl.kt
|
LexiLabs-App
| 819,675,592 | false |
{"Kotlin": 66120}
|
package app.lexilabs.basic.images
/**
* Used to convert the [String] of an absolute file path to an [BasicUrl] object.
* This was a critical feature to prevent URL Strings from being confused with Path Strings.
*
* Example:
* ```kotlin
* val url = BasicUrl("https://picsum.photos/200")
* println(url.toString())
* ```
*/
@ExperimentalBasicImages
public class BasicUrl(urlString: String) {
private val url: String = urlString
/**
* Returns the URL [String] originally passed to the [BasicUrl] object.
*/
override fun toString(): String {
return url
}
}
| 9 |
Kotlin
|
1
| 8 |
533e1ca7fa705f2162e6dd6e2bf5455409995c3b
| 596 |
basic
|
MIT License
|
example/android/app/src/main/kotlin/csj/flutter_github_example/MainActivity.kt
|
chetansj27
| 290,418,816 | false |
{"Dart": 48327, "Kotlin": 2433, "Swift": 929, "Ruby": 895, "Objective-C": 727}
|
package csj.flutter_github_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 |
Dart
|
0
| 2 |
9c56e9aa99ec93079ca93620040cf07fc7639ad1
| 131 |
flutter_github
|
MIT License
|
kMapper-core/src/commonMain/kotlin/de/kotlinBerlin/kMapper/MappingBuilders.kt
|
KotlinBerlin
| 287,190,313 | false | null |
@file:Suppress("unused")
@file:JvmName("MappingBuilderUtil")
package de.kotlinBerlin.kMapper
import de.kotlinBerlin.kMapper.extensions.name
import de.kotlinBerlin.kMapper.internal.*
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KType
import kotlin.reflect.typeOf
@ExperimentalStdlibApi
inline fun <reified S : Any, reified T : Any> defineSimpleMapping(crossinline mapping: (S) -> T) =
defineMapping<S, T> {
defConstructor { mapping(it) }
}
@ExperimentalStdlibApi
inline fun <reified S, reified T> defineMapping(crossinline init: MappingBuilder<S, T>.() -> Unit): Mapping<S, T> =
defineMapping(typeOf<S>(), typeOf<T>()) { init() }
fun <S, T> defineMapping(sourceType: KType, targetType: KType, init: MappingBuilder<S, T>.() -> Unit): Mapping<S, T> =
BasicMappingBuilder<S, T>(sourceType, targetType).run {
init()
build()
}
@ExperimentalStdlibApi
inline fun <reified S : Any, reified T : Any> defineSimpleBidirectionalMapping(crossinline targetMapping: (S) -> T, crossinline sourceMapping: (T) -> S) =
defineBidirectionalMapping<S, T> {
defSourceConstructor { sourceMapping(it) }
defTargetConstructor { targetMapping(it) }
}
@ExperimentalStdlibApi
inline fun <reified S, reified T> defineBidirectionalMapping(crossinline init: BidirectionalMappingBuilder<S, T>.() -> Unit): BidirectionalMapping<S, T> =
defineBidirectionalMapping(typeOf<S>(), typeOf<T>()) { init() }
fun <S, T> defineBidirectionalMapping(
sourceClass: KType,
targetClass: KType,
init: BidirectionalMappingBuilder<S, T>.() -> Unit
): BidirectionalMapping<S, T> = BasicBidirectionalMappingBuilder<S, T>(sourceClass, targetClass).run {
init()
build()
}
interface MappingBuilder<S, T> {
val sourceType: KType
val targetType: KType
fun defConstructor(constructor: (S) -> T)
fun run(mapping: Mapping<S, T>)
//Basic mappings
infix fun <V> ReadPath<S, V>.map(writePath: WritePath<T, V>)
//Mappings by functions
infix fun <V> ((S) -> V).map(setter: (T, V) -> Unit): Unit = this.toReadPath() map setter.toWritePath()
//Mappings from functions to properties
infix fun <V> ((S) -> V).map(setter: KMutableProperty1<T, V>): Unit = this.toReadPath() map setter.toWritePath()
//Mappings from properties to paths
infix fun <V> ReadPath<S, V>.map(setter: KMutableProperty1<T, V>): Unit = this map setter.toWritePath()
//Mappings from functions to paths
infix fun <V> ReadPath<S, V>.map(setter: (T, V) -> Unit): Unit = this map setter.toWritePath()
infix fun <V> ((S) -> V).map(setter: WritePath<T, V>): Unit = this.toReadPath() map setter
}
interface BidirectionalMappingBuilder<S, T> {
val sourceType: KType
val targetType: KType
fun defSourceConstructor(constructor: (T) -> S)
fun defTargetConstructor(constructor: (S) -> T)
fun run(mapping: BidirectionalMapping<S, T>)
fun runToSource(mapping: Mapping<T, S>)
fun runToTarget(mapping: Mapping<S, T>)
//Basic mappings (bidirectional, and unidirectional)
infix fun <V, V1> ReadWritePath<S, V, V1>.map(readWritePath: ReadWritePath<T, V1, V>)
infix fun <V> WritePath<S, V>.mapToSource(readPath: ReadPath<T, V>)
infix fun <V> ReadPath<S, V>.mapToTarget(writePath: WritePath<T, V>)
//Bidirectional mappings between Properties
infix fun <V> KMutableProperty1<S, V>.map(property: KMutableProperty1<T, V>) = this.toReadWritePath() map property.toReadWritePath()
//Bidirectional mappings between Properties and paths
infix fun <V> ReadWritePath<S, V, V>.map(property: KMutableProperty1<T, V>): Unit = this map property.toReadWritePath()
infix fun <V> KMutableProperty1<S, V>.map(property: ReadWritePath<T, V, V>): Unit = this.toReadWritePath() map property
//Unidirectional mappings by functions
infix fun <V> ((S, V) -> Unit).mapToSource(getter: (T) -> V): Unit = this.toWritePath() mapToSource getter.toReadPath()
infix fun <V> ((S) -> V).mapToTarget(setter: (T, V) -> Unit): Unit = this.toReadPath() mapToTarget setter.toWritePath()
//Unidirectional mappings from Properties to functions and reverse
infix fun <V> KMutableProperty1<S, V>.mapToSource(getter: (T) -> V): Unit = this.toWritePath() mapToSource getter.toReadPath()
infix fun <V> ((S) -> V).mapToTarget(setter: KMutableProperty1<T, V>): Unit = this.toReadPath() mapToTarget setter.toWritePath()
//Unidirectional mappings from Properties to paths and reverse
infix fun <V> KMutableProperty1<S, V>.mapToSource(getter: ReadPath<T, V>): Unit = this.toWritePath() mapToSource getter
infix fun <V> ReadPath<S, V>.mapToTarget(setter: KMutableProperty1<T, V>): Unit = this mapToTarget setter.toWritePath()
//Unidirectional mappings from functions to paths and reverse
infix fun <V> ((S, V) -> Unit).mapToSource(getter: ReadPath<T, V>): Unit = this.toWritePath() mapToSource getter
infix fun <V> WritePath<S, V>.mapToSource(getter: (T) -> V): Unit = this mapToSource getter.toReadPath()
infix fun <V> ReadPath<S, V>.mapToTarget(setter: (T, V) -> Unit): Unit = this mapToTarget setter.toWritePath()
infix fun <V> ((S) -> V).mapToTarget(setter: WritePath<T, V>): Unit = this.toReadPath() mapToTarget setter
}
internal fun <T, V> ((T) -> V).toReadPath() = BasicReadPath(this.name, this)
internal fun <T, V> ((T, V) -> Unit).toWritePath() = BasicWritePath(this.name, this)
internal fun <T, V> KMutableProperty1<T, V>.toWritePath() = BasicWritePath(this.name, this::set)
internal fun <T, V> KMutableProperty1<T, V>.toReadWritePath() = BasicReadWritePath(this.name, this, this::set)
| 1 | null |
1
| 1 |
65d68719bff59f3316fe378f5585445bf22aa2bc
| 5,700 |
kMapper
|
Apache License 2.0
|
core/src/test/kotlin/com/github/leomartins1999/xmlify/mapper/EnumMapperTests.kt
|
leomartins1999
| 478,761,413 | false |
{"Kotlin": 105924}
|
package com.github.leomartins1999.xmlify.mapper
import com.github.leomartins1999.xmlify.model.LeafElement
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class EnumMapperTests {
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
@Test
fun `maps an enum by it's name`() {
val dir = Direction.NORTH
val element = xmlify { dir }
assertEquals(LeafElement("direction", "NORTH"), element)
}
}
| 0 |
Kotlin
|
0
| 0 |
1fef698d6ec279814578d542ec698e86d0e90d58
| 483 |
xmlify
|
MIT License
|
app/src/main/java/gc/david/dfm/faq/GetFaqsRepository.kt
|
siempredelao
| 13,180,148 | false | null |
/*
* Copyright (c) 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gc.david.dfm.faq
import gc.david.dfm.faq.model.Faq
/**
* Created by david on 19.12.16.
*/
interface GetFaqsRepository {
fun getFaqs(): Set<Faq>
}
| 4 |
Kotlin
|
2
| 3 |
de6bc1610b9a5d30c0766f78aac479f04272dde4
| 755 |
Distance-From-Me-Android
|
Apache License 2.0
|
clpfd/src/main/kotlin/clpfd/reflection/FdSize.kt
|
giuseppeboezio
| 575,936,179 | false | null |
package clpfd.reflection
import clpCore.chocoModel
import clpCore.flip
import clpCore.getOuterVariable
import clpCore.variablesMap
import it.unibo.tuprolog.core.Integer
import it.unibo.tuprolog.core.Substitution
import it.unibo.tuprolog.core.Term
import it.unibo.tuprolog.core.Var
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.exception.error.TypeError
import it.unibo.tuprolog.solve.primitive.BinaryRelation
import it.unibo.tuprolog.solve.primitive.Solve
import org.chocosolver.solver.variables.IntVar
object FdDegree: BinaryRelation.NonBacktrackable<ExecutionContext>("fd_degree") {
override fun Solve.Request<ExecutionContext>.computeOne(first: Term, second: Term): Solve.Response {
ensuringArgumentIsVariable(0)
val variable = first.castToVar()
if(!second.let { it is Var || it is Integer })
throw TypeError.forArgument(context, signature, TypeError.Expected.INTEGER, second)
val chocoModel = chocoModel
val subContext = context.substitution
val varsMap = chocoModel.variablesMap(listOf(variable), subContext).flip()
val firstOriginal = first.castToVar().getOuterVariable(subContext)
// the variable has not been previously defined, or it is not an integer variable
if(varsMap.let { it.isEmpty() || it[firstOriginal] !is IntVar }){
return if(second is Var)
replyWith(Substitution.of(second.getOuterVariable(subContext) to Integer.of(0)))
else if(second.castToInteger().value.toInt() == 0)
replySuccess()
else
replyFail()
}
else{
chocoModel.solver.propagate()
val numConstraints = (varsMap[firstOriginal] as IntVar).nbProps
return if(second is Var)
replyWith(Substitution.of(second.getOuterVariable(subContext) to Integer.of(numConstraints)))
else {
if(second.castToInteger().value.toInt() == numConstraints)
replySuccess()
else
replyFail()
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
281977dd427f1825bf680b72be9e6ac50be5dffe
| 2,134 |
SchoolTimetable
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/gian/client/ItauClient.kt
|
gianmsouza
| 395,672,736 | true |
{"Kotlin": 64998}
|
package br.com.zup.gian.client
import br.com.zup.gian.registrarchave.itau.DadosDaContaResponse
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
@Client("\${itau.erp}")
interface ItauClient {
@Get("/api/v1/clientes/{clienteId}/contas{?tipo}")
fun buscarDadosConta(
@PathVariable clienteId: String,
@QueryValue tipo: String
): HttpResponse<DadosDaContaResponse>
}
| 0 |
Kotlin
|
0
| 0 |
51dd2506d114c2d977e1b3b640b8c5b78639b5d9
| 567 |
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
src/main/kotlin/org/geepawhill/kontentment/MainView.kt
|
GeePawHill
| 635,065,699 | false | null |
package org.geepawhill.kontentment
import javafx.geometry.Orientation
import javafx.scene.Parent
import tornadofx.*
class MainView(val model: Model) : Fragment() {
val clockLabel = label(model.gametime) {
model.windowing.normalLabel(this)
}
val playButton = button("Play") {
action {
model.playOrPause()
}
model.isPlaying.addListener { _, _, _ ->
if (model.isPlaying.value == true) text = "Pause"
else text = "Play"
}
}
override val root: Parent = borderpane {
top = toolbar {
this += clockLabel
this += playButton
}
center = splitpane {
orientation = Orientation.HORIZONTAL
this += CanvasAndDetailView(model)
this += ScriptView(model)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
294777421b6651e00c30c779af8740db2d4cbfcf
| 837 |
kontentment2
|
MIT License
|
common/src/commonMain/kotlin/com/artemchep/keyguard/provider/bitwarden/repository/BitwardenSendRepository.kt
|
AChep
| 669,697,660 | false |
{"Kotlin": 5516822, "HTML": 45876}
|
package com.artemchep.keyguard.provider.bitwarden.repository
import com.artemchep.keyguard.core.store.bitwarden.BitwardenSend
interface BitwardenSendRepository : BaseRepository<BitwardenSend> {
}
| 66 |
Kotlin
|
31
| 995 |
557bf42372ebb19007e3a8871e3f7cb8a7e50739
| 198 |
keyguard-app
|
Linux Kernel Variant of OpenIB.org license
|
app/src/main/java/com/foobarust/android/utils/BottomSheetExtensions.kt
|
foobar-UST
| 285,792,732 | false | null |
package com.foobarust.deliverer.utils
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.coroutines.suspendCancellableCoroutine
/**
* Created by kevin on 1/27/21
*/
fun BottomSheetBehavior<*>.isExpanded() = state == BottomSheetBehavior.STATE_EXPANDED
fun BottomSheetBehavior<*>.isCollapsed() = state == BottomSheetBehavior.STATE_COLLAPSED
fun BottomSheetBehavior<*>.expand() {
state = BottomSheetBehavior.STATE_EXPANDED
}
fun BottomSheetBehavior<*>.collapse() {
state = BottomSheetBehavior.STATE_COLLAPSED
}
/**
* Hide the bottom sheet for a given condition.
*/
fun BottomSheetBehavior<*>.hideIf(hide: Boolean) {
isHideable = true
state = if (hide) {
BottomSheetBehavior.STATE_HIDDEN
} else {
BottomSheetBehavior.STATE_COLLAPSED
}
isHideable = false
}
/**
* Set the peek height of the bottom sheet to the minimum height that
* a specific view can be fully displayed at the bottom.
*/
suspend fun bottomSheetPeekTo(bottomSheet: ViewGroup, toView: View) {
val behavior = BottomSheetBehavior.from(bottomSheet).apply {
peekHeight = 0
}
return suspendCancellableCoroutine { continuation ->
val listener = object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
bottomSheet.viewTreeObserver.removeOnGlobalLayoutListener(this)
behavior.setPeekHeight(toView.bottom, true)
}
}
bottomSheet.viewTreeObserver.addOnGlobalLayoutListener(listener)
continuation.invokeOnCancellation {
bottomSheet.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
}
| 0 |
Kotlin
|
2
| 2 |
b4358ef0323a0b7a95483223496164e616a01da5
| 1,788 |
foobar-android
|
MIT License
|
src/main/kotlin/com/strawhats/kenerator/services/MyApplicationService.kt
|
Rshalika
| 300,654,331 | false | null |
package com.strawhats.kenerator.services
import com.strawhats.kenerator.MyBundle
class MyApplicationService {
init {
println(MyBundle.message("applicationService"))
}
}
| 0 |
Kotlin
|
0
| 1 |
a24fedcc36a915c8c0a1751af70a7f9fa6d1793b
| 188 |
kenerator
|
Apache License 2.0
|
app/src/main/java/com/geetgobindsingh/lifecycleapp/activities/ActivityB.kt
|
geetgobindsingh
| 710,327,279 | false |
{"Kotlin": 26364}
|
package com.geetgobindsingh.lifecycleapp.activities
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ScrollView
import androidx.appcompat.widget.AppCompatTextView
import com.geetgobindsingh.lifecycleapp.LifecycleApp
import com.geetgobindsingh.lifecycleapp.R
class ActivityB : BaseActivity() {
private var logTextView: AppCompatTextView? = null
override fun getScreenName(): String {
return "ActivityB"
}
var scrollView: ScrollView? = null
override fun getScrollingView(): ScrollView? {
return scrollView
}
override fun getTextView(): AppCompatTextView? {
return logTextView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_b)
logTextView = findViewById<AppCompatTextView>(R.id.logTextView)
scrollView = findViewById<ScrollView>(R.id.scrollView)
findViewById<Button>(R.id.backToPreviousActivity).setOnClickListener {
LifecycleApp.getInstance().log(getScreenName(), "'Go to Previous Activity' - Button Clicked")
sendRefreshUIBroadcast()
finish()
}
findViewById<Button>(R.id.goToNextActivity).setOnClickListener {
LifecycleApp.getInstance().log(getScreenName(), "'Go to Next Activity' - Button Clicked")
sendRefreshUIBroadcast()
startActivity(Intent(this, ActivityC::class.java))
}
findViewById<Button>(R.id.clearLogs).setOnClickListener {
LifecycleApp.getInstance().getLogs().clear()
LifecycleApp.getInstance().log(getScreenName(), "'Clear Logs' - Button Clicked")
sendRefreshUIBroadcast()
}
}
}
| 0 |
Kotlin
|
0
| 2 |
015f126508583e4972cee98019accc4a195729aa
| 1,782 |
LifecycleApp
|
MIT License
|
api/src/main/kotlin/sbp/model/Milestone.kt
|
NoumenaDigital
| 638,984,160 | false | null |
package sbp.model
import arrow.core.getOrHandle
import com.noumenadigital.npl.api.generated.sbp.InvoiceFacade
import com.noumenadigital.npl.api.generated.sbp.MilestoneFacade
import com.noumenadigital.platform.engine.client.AuthorizationProvider
import com.noumenadigital.platform.engine.client.EngineClientApi
fun MilestoneFacade.toMilestoneDetails(engineClient: EngineClientApi, auth: AuthorizationProvider) =
MilestoneDetails(this, this.getBlockchainRef(engineClient, auth))
fun MilestoneFacade.getBlockchainRef(engineClient: EngineClientApi, auth: AuthorizationProvider): String? {
return fields.originalInvoice?.let { invoice ->
val invoiceProtocol = engineClient.getProtocolStateById(invoice.id, auth).getOrHandle { throw it }
val invoiceFacade = InvoiceFacade(invoiceProtocol)
invoiceFacade.fields.blockchainRef
}
}
| 0 |
Kotlin
|
0
| 0 |
5b3895569f4e2a26a6c73229cd32a3d15539a80c
| 861 |
sbp-dxd-m3
|
Apache License 2.0
|
src/main/kotlin/io/github/sevenparadigms/gateway/websocket/support/WebSocketFactory.kt
|
SevenParadigms
| 462,078,738 | false | null |
package io.github.sevenparadigms.gateway.websocket.support
import com.fasterxml.jackson.databind.JsonNode
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.RemovalCause
import io.github.sevenparadigms.gateway.kafka.EventDrivenPublisher
import io.github.sevenparadigms.gateway.kafka.model.UserConnectEvent
import io.github.sevenparadigms.gateway.kafka.model.UserDisconnectEvent
import io.github.sevenparadigms.gateway.websocket.model.MessageWrapper
import io.github.sevenparadigms.gateway.websocket.model.WebSocketEntryPoint
import io.github.sevenparadigms.gateway.websocket.model.WebSocketSessionChain
import org.apache.commons.lang3.ObjectUtils
import org.sevenparadigms.kotlin.common.debug
import org.sevenparadigms.kotlin.common.info
import org.sevenparadigms.kotlin.common.parseJson
import org.springframework.core.io.ByteArrayResource
import org.springframework.data.r2dbc.support.Beans
import org.springframework.http.HttpMethod
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketMessage
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.publisher.SignalType
import java.util.concurrent.TimeUnit
@Component
@WebSocketEntryPoint("/wsf")
class WebSocketFactory(val kafkaPublisher: EventDrivenPublisher) : WebSocketHandler {
private val clients = Caffeine.newBuilder()
.maximumSize(Beans.getProperty(Constants.GATEWAY_CACHE_SIZE, Long::class.java, 10000))
.expireAfterAccess(
Beans.getProperty(Constants.GATEWAY_CACHE_ACCESS, Long::class.java, 1800000),
TimeUnit.MILLISECONDS
)
.removalListener { key: String?, value: WebSocketSessionChain?, cause: RemovalCause ->
if (cause.wasEvicted() && ObjectUtils.isNotEmpty(key)) {
kafkaPublisher.publishDisconnect(
UserDisconnectEvent(key, value!!.tokenHash, true)
).subscribe {
value.session.close()
info { "WebSocket disconnected by timeout with user[$key]" }
}
}
}.build<String, WebSocketSessionChain>()
override fun handle(session: WebSocketSession) = session.handshakeInfo.principal
.cast(UsernamePasswordAuthenticationToken::class.java)
.flatMap { authToken: UsernamePasswordAuthenticationToken ->
val output = session.send(Flux.create {
authToken.credentials
clients.put(authToken.name, WebSocketSessionChain(
session = session, tokenHash = authToken.credentials as Long, chain = it))
})
val input = session.receive()
.map { obj: WebSocketMessage -> obj.payloadAsText.parseJson(MessageWrapper::class.java) }
.doOnNext { handling(it, authToken.name) }.then()
Mono.zip(input, output).then().doFinally { signal: SignalType ->
val sessionChain = clients.getIfPresent(authToken.name)!!
kafkaPublisher.publishDisconnect(
UserDisconnectEvent(authToken.name, sessionChain.tokenHash, false)
).subscribe {
clients.invalidate(authToken.name)
sessionChain.session.close()
info { "Connection close with signal[${signal.name}] and user[${authToken.name}]" }
}
}
kafkaPublisher.publishConnect(
UserConnectEvent(authToken.name, authToken.authorities.map { it.authority })
)
}
fun handling(message: MessageWrapper, username: String) {
val webClient = Beans.of(WebClient.Builder::class.java).baseUrl(message.baseUrl).build()
val response = when (message.type) {
HttpMethod.GET -> webClient.get().uri(message.uri).retrieve()
HttpMethod.POST -> webClient.post().uri(message.uri).body(BodyInserters.fromValue(message.body!!)).retrieve()
HttpMethod.PUT -> webClient.put().uri(message.uri).body(BodyInserters.fromValue(message.body!!)).retrieve()
HttpMethod.DELETE -> webClient.delete().uri(message.uri).retrieve()
HttpMethod.PATCH -> webClient.patch().uri(message.uri).body(BodyInserters.fromValue(message.body!!))
.retrieve()
HttpMethod.HEAD -> webClient.head().uri(message.uri).retrieve()
HttpMethod.OPTIONS -> webClient.options().uri(message.uri).retrieve()
HttpMethod.TRACE -> webClient.method(HttpMethod.TRACE).uri(message.uri).retrieve()
}
response
.onStatus({ status -> status.isError })
{ clientResponse ->
clientResponse.bodyToMono(ByteArrayResource::class.java)
.map { responseAnswer: ByteArrayResource ->
WebClientResponseException(
clientResponse.rawStatusCode(),
clientResponse.statusCode().name,
clientResponse.headers().asHttpHeaders(),
responseAnswer.byteArray,
Charsets.UTF_8
)
}
}
.bodyToMono(JsonNode::class.java).subscribe {
info { "Request[${message.baseUrl}${message.uri}] by user[$username] accepted" }
debug { it.toString() }
val sessionChain = clients.getIfPresent(username)
sessionChain?.sendMessage(message.copy(body = it))
}
}
fun get(username: String): WebSocketSessionChain? = clients.getIfPresent(username)
fun size() = clients.estimatedSize()
}
| 1 |
Kotlin
|
0
| 2 |
58b60230a84df78f3c9014e2e1fc3e92e2c440c4
| 6,158 |
spring-cloud-websocket-gateway
|
Apache License 2.0
|
idea/testData/intentions/declarations/convertMemberToExtension/valWithDefaultGetter.kt
|
JakeWharton
| 99,388,807 | true | null |
// WITH_RUNTIME
// SKIP_ERRORS_BEFORE
class Owner {
val <caret>p: Int
get
}
| 0 |
Kotlin
|
28
| 83 |
4383335168338df9bbbe2a63cb213a68d0858104
| 86 |
kotlin
|
Apache License 2.0
|
kool-core/src/desktopMain/kotlin/de/fabmax/kool/FileSystemAssetLoader.kt
|
fabmax
| 81,503,047 | false | null |
package de.fabmax.kool
import de.fabmax.kool.modules.audio.AudioClipImpl
import de.fabmax.kool.modules.filesystem.FileSystemDirectory
import de.fabmax.kool.modules.filesystem.getFileOrNull
import de.fabmax.kool.pipeline.TextureData2d
import de.fabmax.kool.platform.imageAtlasTextureData
import de.fabmax.kool.util.Uint8Buffer
import java.io.ByteArrayInputStream
actual fun fileSystemAssetLoader(baseDir: FileSystemDirectory): AssetLoader {
return FileSystemAssetLoader(baseDir)
}
class FileSystemAssetLoader(val baseDir: FileSystemDirectory): AssetLoader() {
override suspend fun loadBlob(blobRef: BlobAssetRef): LoadedBlobAsset {
val blob = loadData(blobRef.path)
return LoadedBlobAsset(blobRef, blob)
}
override suspend fun loadTexture(textureRef: TextureAssetRef): LoadedTextureAsset {
val refCopy = TextureData2dRef(textureRef.path, textureRef.props)
val texData = loadTextureData2d(refCopy).data as TextureData2d?
return LoadedTextureAsset(textureRef, texData)
}
override suspend fun loadTextureAtlas(textureRef: TextureAtlasAssetRef): LoadedTextureAsset {
val refCopy = TextureData2dRef(textureRef.path, textureRef.props)
val texData = loadTextureData2d(refCopy).data as TextureData2d?
val atlasData = texData?.let {
imageAtlasTextureData(it, textureRef.tilesX, textureRef.tilesY)
}
return LoadedTextureAsset(textureRef, atlasData)
}
override suspend fun loadTextureData2d(textureData2dRef: TextureData2dRef): LoadedTextureAsset {
val tex = loadData(textureData2dRef.path)
val texData = tex?.toArray()?.let { bytes ->
ByteArrayInputStream(bytes).use {
PlatformAssetsImpl.readImageData(it, MimeType.forFileName(textureData2dRef.path), textureData2dRef.props)
}
}
return LoadedTextureAsset(textureData2dRef, texData)
}
override suspend fun loadAudioClip(audioRef: AudioClipRef): LoadedAudioClipAsset {
val blob = loadBlob(BlobAssetRef(audioRef.path))
val clip = blob.data?.let { buf ->
AudioClipImpl(buf.toArray(), audioRef.path.substringAfterLast('.').lowercase())
}
return LoadedAudioClipAsset(audioRef, clip)
}
private suspend fun loadData(path: String): Uint8Buffer? {
return if (Assets.isDataUri(path)) {
decodeDataUri(path)
} else {
baseDir.getFileOrNull(path)?.read()
}
}
}
| 13 | null |
15
| 247 |
c642b04a5912235d0777915935f023cb8d6d9b93
| 2,500 |
kool
|
Apache License 2.0
|
src/main/kotlin/ink/ptms/chemdah/module/kether/compat/ActionMythic.kt
|
TabooLib
| 338,114,548 | false | null |
package ink.ptms.chemdah.module.kether.compat
import ink.ptms.chemdah.util.getPlayer
import ink.ptms.um.Mythic
import ink.ptms.um.Skill
import taboolib.common.platform.function.submit
import taboolib.module.kether.*
import java.util.concurrent.CompletableFuture
/**
* Chemdah
* ink.ptms.chemdah.module.kether.compat.ActionMythicMobs
*
* @author sky
* @since 2021/2/10 6:39 下午
*/
class ActionMythic {
class MythicMobsCast(val mechanic: Skill, val trigger: Skill.Trigger) : ScriptAction<Void>() {
override fun run(frame: ScriptFrame): CompletableFuture<Void> {
val player = frame.getPlayer()
submit { mechanic.execute(trigger, player, player, emptySet(), emptySet(), 0f, emptyMap()) }
return CompletableFuture.completedFuture(null);
}
}
companion object {
/**
* mm cast skill_name
* mm cast skill_name with api
*/
@KetherParser(["mythicmobs", "mm"], shared = true)
fun parser() = scriptParser {
when (it.expects("cast")) {
"cast" -> {
val skill = it.nextToken()
val mechanic = Mythic.API.getSkillMechanic(skill) ?: error("unknown skill $skill")
val trigger = try {
it.mark()
it.expects("with", "as", "by")
Mythic.API.getSkillTrigger(it.nextToken())
} catch (ex: Throwable) {
it.reset()
Mythic.API.getSkillTrigger("DEFAULT")
}
MythicMobsCast(mechanic, trigger)
}
else -> error("out of case")
}
}
}
}
| 6 |
Kotlin
|
43
| 55 |
e38bf92ca8a55ae1cef8ae512e9fb1573da084ce
| 1,748 |
chemdah
|
MIT License
|
lib_appinject/src/main/java/com/yh/appinject/base/ViewBindingFragment.kt
|
CListery
| 494,658,527 | false | null |
package com.yh.appbasic.ui
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewbinding.ViewBinding
import android.os.isCurrentLooper
import com.kotlin.memoryId
abstract class ViewBindingFragment<VB : ViewBinding> : Fragment() {
protected val mTag by lazy { "${this::class.java.simpleName}[${this.memoryId}(${mAct.memoryId})]" }
//
protected var _binder: VB? = null
protected val uiLooper by lazy { Looper.getMainLooper() }
protected val uiHandler by lazy { Handler(uiLooper, null) }
//
protected val mAct: FragmentActivity? by lazy { this.activity }
protected val mCtx: Context? by lazy { this.context }
override fun onAttach(context: Context) {
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
beforeOnCreate(savedInstanceState)
super.onCreate(savedInstanceState)
}
open fun beforeOnCreate(savedInstanceState: Bundle?) {
}
override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater {
return super.onGetLayoutInflater(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binder = binderCreator(inflater, container, savedInstanceState)
if(null == binder) {
activity?.finish()
return null
}
_binder = binder
return binder.root
}
abstract fun binderCreator(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): VB?
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
preInit(savedInstanceState)
_binder?.onInit(savedInstanceState)
afterInit(savedInstanceState)
}
open fun preInit(savedInstanceState: Bundle?) {
}
abstract fun VB.onInit(savedInstanceState: Bundle?)
open fun afterInit(savedInstanceState: Bundle?) {
}
open fun changeBinder(changer: VB.() -> Unit): Boolean {
if(null == _binder) {
return false
}
if(uiLooper.isCurrentLooper) {
try {
_binder?.changer()
} catch(e: Exception) {
e.printStackTrace()
return false
}
} else {
uiHandler.post {
changeBinder(changer)
}
}
return true
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
override fun onStart() {
super.onStart()
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
}
override fun onDestroy() {
super.onDestroy()
}
override fun onDetach() {
super.onDetach()
}
}
| 0 |
Kotlin
|
0
| 0 |
9d85eb1abf83b0313805bf196a6fe65ac5504a87
| 3,494 |
AppInject
|
MIT License
|
guide/example/example-serializer-23.kt
|
Kotlin
| 97,827,246 | false |
{"Kotlin": 2262082, "Java": 1343}
|
// This file was automatically generated from serializers.md by Knit tool. Do not edit.
package example.exampleSerializer23
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.descriptors.*
// NOT @Serializable
class Project(val name: String, val language: String)
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = Project::class)
object ProjectSerializer
fun main() {
val data = Project("kotlinx.serialization", "Kotlin")
println(Json.encodeToString(ProjectSerializer, data))
}
| 407 |
Kotlin
|
621
| 5,396 |
d4d066d72a9f92f06c640be5a36a22f75d0d7659
| 596 |
kotlinx.serialization
|
Apache License 2.0
|
app/src/main/java/com/jaiselrahman/wastatus/data/db/DB.kt
|
HEMAL-PATEL
| 173,679,580 | true |
{"Kotlin": 83164}
|
package com.jaiselrahman.wastatus.data.db
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.jaiselrahman.wastatus.App
import com.jaiselrahman.wastatus.R
import com.jaiselrahman.wastatus.model.Video
@Database(entities = [Video::class], version = 1, exportSchema = false)
abstract class DB : RoomDatabase() {
abstract fun videoDao(): VideoDao
companion object {
private val db = Room.databaseBuilder(
App.getContext(),
DB::class.java,
App.getContext().getString(R.string.app_name)
).setJournalMode(JournalMode.TRUNCATE)
.build()
val videoDao = db.videoDao()
}
}
| 0 |
Kotlin
|
0
| 0 |
024e91b8cf5031b71b38c435ac17c73464617ef2
| 701 |
WAStatus
|
Apache License 2.0
|
kirinmaru-android/src/test/java/stream/reconfig/kirinmaru/android/vo/ConverterTest.kt
|
amirulzin
| 121,656,356 | false |
{"Gradle": 5, "Markdown": 2, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "EditorConfig": 1, "Proguard": 1, "JSON": 1, "Kotlin": 158, "XML": 54, "INI": 1, "Java": 6, "YAML": 1}
|
package stream.reconfig.kirinmaru.android.vo
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Test for string set TypeConverter (Room)
*/
class ConverterTest {
@Test
fun intoString() {
val x = Novel.Converter().fromSet(setOf("a", "b", "c"))
assertTrue(x == "~%a~%b~%c")
}
@Test
fun intoSet() {
val x = Novel.Converter().toSet("~%a~%b~%c")
val arr = arrayOf("a", "b", "c")
x.forEachIndexed { i, s -> assertTrue(arr[i] == s) }
}
}
| 1 | null |
1
| 1 |
15c1eeafe8f467a55008b402e30d97e6966926f3
| 479 |
Kirinmaru
|
Apache License 2.0
|
core/src/main/kotlin/com/redmadrobot/debug/core/inapp/shake/ShakeListener.kt
|
RedMadRobot
| 516,407,635 | false | null |
package com.redmadrobot.debug.core.inapp.shake
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
internal class ShakeListener(private val onAction: () -> Unit) : SensorEventListener {
companion object {
private const val TRIGGER_MOTION_BORDER = 10.0f
private const val VECTOR_COUNT = 3
private const val EVENT_TIME_DELAY = 1000L
}
private var lastTimestamp: Long = System.currentTimeMillis()
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int): Unit = Unit
override fun onSensorChanged(event: SensorEvent?) {
event?.let { sensorEvent ->
val values = sensorEvent.values
val commonVector = values.take(VECTOR_COUNT)
.map {
val valueWithoutGravity = it / SensorManager.GRAVITY_EARTH
valueWithoutGravity * valueWithoutGravity
}.sum()
val currentTime = System.currentTimeMillis()
val isSignificantEvent = commonVector > TRIGGER_MOTION_BORDER
val isNewEvent = currentTime > lastTimestamp + EVENT_TIME_DELAY
if (isSignificantEvent && isNewEvent) {
lastTimestamp = currentTime
onAction.invoke()
}
}
}
}
| 6 | null |
4
| 6 |
bcc29b8cc73cd27b3ba5a305e2858b62d90c79c7
| 1,363 |
debug-panel-android
|
MIT License
|
compiler/fir/fir-serialization/src/org/jetbrains/kotlin/fir/serialization/FirElementAwareStringTable.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.serialization
import org.jetbrains.kotlin.fir.declarations.FirClass
import org.jetbrains.kotlin.fir.declarations.FirClassLikeDeclaration
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.metadata.serialization.StringTable
import org.jetbrains.kotlin.name.ClassId
interface FirElementAwareStringTable : StringTable {
fun getQualifiedClassNameIndex(classId: ClassId): Int =
getQualifiedClassNameIndex(classId.asString(), classId.isLocal)
fun getFqNameIndex(classLikeDeclaration: FirClassLikeDeclaration<*>): Int {
val classId = classLikeDeclaration.symbol.classId.takeIf { !it.isLocal }
?: getLocalClassIdReplacement(classLikeDeclaration as FirClass<*>)
?: throw IllegalStateException("Cannot get FQ name of local class: ${classLikeDeclaration.render()}")
return getQualifiedClassNameIndex(classId)
}
fun getLocalClassIdReplacement(firClass: FirClass<*>): ClassId? = null
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,201 |
kotlin
|
Apache License 2.0
|
app/src/main/java/com/rumeysaozer/chatapp/adapter/MesajAdapter.kt
|
rumeysaozer0
| 440,526,371 | false |
{"Kotlin": 39562}
|
package com.rumeysaozer.chatapp.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.rumeysaozer.chatapp.model.Mesajlar
import com.rumeysaozer.chatapp.R
class MesajAdapter(val context: Context, val messageList: ArrayList<Mesajlar>): RecyclerView.Adapter <RecyclerView.ViewHolder>(){
val ITEM_RECEIVE = 1
val ITEM_SENT = 2
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if(viewType == 1){
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.kullanici_konusma_recycler_row, parent, false)
return AliciViewHolder(view)
}
else{
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.kullanici_konusma_recycler_row2, parent, false)
return GondericiViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMessage = messageList[position]
if(holder.javaClass == GondericiViewHolder::class.java){
val viewHolder = holder as GondericiViewHolder
holder.mesajGonder.text = currentMessage.mesaj
}
else{
val viewHGolder = holder as AliciViewHolder
holder.mesajAl.text = currentMessage.mesaj
}
}
override fun getItemViewType(position: Int): Int {
val currentMessage = messageList[position]
if(FirebaseAuth.getInstance().currentUser?.uid.equals(currentMessage.gondericiId)){
return ITEM_SENT
}
else{
return ITEM_RECEIVE
}
}
override fun getItemCount(): Int {
if(messageList.size >0){
return messageList.size
}
else{
return 0
}
}
class GondericiViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val mesajGonder = itemView.findViewById<TextView>(R.id.kkrvTvgonder)
}
class AliciViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val mesajAl = itemView.findViewById<TextView>(R.id.kkrvTval)
}
}
| 0 |
Kotlin
|
0
| 0 |
76d50f780eeec3d21a326561f6560660778f1051
| 2,378 |
ChatApp
|
MIT License
|
core/src/main/java/com/cataractaction/core/di/DataStoreModule.kt
|
CatarAction-C23-PS004
| 642,576,405 | false | null |
package com.cataractaction.core.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import com.cataractaction.core.data.source.local.preferences.ProfilePreferences
import com.cataractaction.core.domain.usecase.ProfilePreferencesInteractor
import com.cataractaction.core.domain.usecase.ProfilePreferencesUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "cataractaction")
@Module
@InstallIn(SingletonComponent::class)
class DataStoreModule {
@Provides
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.dataStore
@Provides
@Singleton
fun provideProfilePreferences(dataStore: DataStore<Preferences>): ProfilePreferences =
ProfilePreferences(dataStore)
@Provides
@Singleton
fun provideProfilePreferencesUseCase(@ApplicationContext context: Context): ProfilePreferencesUseCase =
ProfilePreferencesInteractor(provideProfilePreferences(provideDataStore(context)))
}
| 0 |
Kotlin
|
0
| 1 |
d011ca0c57b696e4b488b29e73c820a01a633b9c
| 1,352 |
CatarAction-Mobile
|
The Unlicense
|
msdemob/src/main/kotlin/io/capdevila/poc/msarchitecture/msdemob/config/MsdemobConfiguration.kt
|
xcapdevila
| 100,391,466 | false | null |
package io.capdevila.poc.msarchitecture.msdemob.config
import org.springframework.cloud.client.loadbalancer.LoadBalanced
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.client.RestTemplate
@Configuration
class MsdemobConfiguration {
@Bean
@LoadBalanced
fun restTemplate(): RestTemplate {
return RestTemplate()
}
}
| 0 |
Kotlin
|
0
| 0 |
95df9633ae20516ab47d9e3ab98466a9f86365a2
| 434 |
msarchitecture-poc-kotlin
|
MIT License
|
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/buildings/HomeOfficeLine.kt
|
walter-juan
| 868,046,028 | false |
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.remix.remix.buildings
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.BuildingsGroup
public val BuildingsGroup.HomeOfficeLine: ImageVector
get() {
if (_homeOfficeLine != null) {
return _homeOfficeLine!!
}
_homeOfficeLine = Builder(name = "HomeOfficeLine", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.673f, 1.612f)
lineTo(20.8f, 9.0f)
horizontalLineTo(17.827f)
lineTo(12.0f, 3.703f)
lineTo(6.0f, 9.158f)
verticalLineTo(19.0f)
horizontalLineTo(11.0f)
verticalLineTo(21.0f)
horizontalLineTo(5.0f)
curveTo(4.448f, 21.0f, 4.0f, 20.552f, 4.0f, 20.0f)
verticalLineTo(11.0f)
lineTo(1.0f, 11.0f)
lineTo(11.327f, 1.612f)
curveTo(11.709f, 1.265f, 12.291f, 1.265f, 12.673f, 1.612f)
close()
moveTo(14.0f, 11.0f)
horizontalLineTo(23.0f)
verticalLineTo(18.0f)
horizontalLineTo(14.0f)
verticalLineTo(11.0f)
close()
moveTo(16.0f, 13.0f)
verticalLineTo(16.0f)
horizontalLineTo(21.0f)
verticalLineTo(13.0f)
horizontalLineTo(16.0f)
close()
moveTo(24.0f, 21.0f)
horizontalLineTo(13.0f)
verticalLineTo(19.0f)
horizontalLineTo(24.0f)
verticalLineTo(21.0f)
close()
}
}
.build()
return _homeOfficeLine!!
}
private var _homeOfficeLine: ImageVector? = null
| 0 |
Kotlin
|
0
| 3 |
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,589 |
compose-icon-collections
|
MIT License
|
sdk/src/main/java/com/eyeson/sdk/model/meeting/incoming/SnapshotUpdateDto.kt
|
eyeson-team
| 488,502,949 | false |
{"Kotlin": 458128}
|
package com.eyeson.sdk.model.meeting.incoming
import com.eyeson.sdk.model.api.SnapshotDto
import com.eyeson.sdk.model.local.api.UserInfo
import com.eyeson.sdk.model.local.meeting.SnapshotUpdate
import com.eyeson.sdk.model.meeting.base.MeetingBaseMessageDto
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class SnapshotUpdateDto(
@Json(name = "type") override val type: String,
@Json(name = "snapshots") val snapshots: List<SnapshotDto>
) : MeetingBaseMessageDto {
override fun toLocal(): SnapshotUpdate {
return SnapshotUpdate(
snapshots = snapshots.map {
SnapshotUpdate.Snapshot(
id = it.id,
name = it.name,
creator = UserInfo(
id = it.creator.id,
name = it.creator.name,
avatar = it.creator.avatar,
guest = it.creator.guest,
joinedAt = it.creator.joinedAt
),
createdAt = it.createdAt,
downloadLink = it.links.download
)
}
)
}
}
| 0 |
Kotlin
|
0
| 3 |
91b6586577d7735ea566bdc1701a1419ae0d930e
| 1,229 |
android-sdk
|
MIT License
|
src/main/kotlin/therealfarfetchd/tubes/common/api/block/IFlowingItemProvider.kt
|
Darkstrumn
| 131,374,601 | true |
{"Kotlin": 369119, "Assembly": 52301, "Shell": 2306, "GLSL": 1113}
|
package therealfarfetchd.tubes.common.api.block
import therealfarfetchd.quacklib.common.api.util.math.Vec3
import therealfarfetchd.tubes.common.api.item.ColoredItemStack
interface IFlowingItemProvider {
fun getItems(): Set<Pair<ColoredItemStack, Vec3>>
}
| 0 |
Kotlin
|
0
| 0 |
9c5f4d614eb7af91dec06400a658b0c6eb9fb656
| 258 |
HCTM
|
MIT License
|
app/src/main/java/com/tuppersoft/marvel/features/charactersdetails/comiccover/ComicItem.kt
|
JaviSFH
| 313,085,710 | false |
{"Kotlin": 54980}
|
package com.tuppersoft.marvel.features.charactersdetails.comiccover
import com.tuppersoft.domain.models.comic.Comic
import com.tuppersoft.marvel.core.platform.GlobalItem
import com.tuppersoft.marvel.core.platform.GlobalItem.TypeItem.NORMAL
data class ComicItem(val comic: Comic) : GlobalItem() {
override val typeItem: TypeItem
get() = NORMAL
}
| 0 | null |
0
| 0 |
39217055f8e4a8e3695e478217dfbb7f7a4b814a
| 360 |
marvel-app
|
Apache License 2.0
|
app/src/main/java/com/example/dotoring/ui/message/messageDetail/data/chatSource.kt
|
LimSumi
| 643,888,852 | false | null |
package com.example.dotoring.ui.message.messageDetail.data
import com.example.dotoring.ui.message.messageDetail.MessageDetail
//
//
class chatSource {
fun loadChat(): List<MessageDetail> {
return listOf<MessageDetail>(
MessageDetail(
letterId = 6,
content = "넵 알겠습니다.",
writer = false,
nickname = "sonny567",
createdAt = "2023-07-28"
),MessageDetail(
letterId = 5,
content = "그럼 목요일 7시 어떠세요?",
writer = true,
nickname = "qwer1111",
createdAt = "2023-07-28"
),
MessageDetail(
letterId = 4,
content = "저는 수요일 빼고 다 괜찮습니다!!.",
writer = false,
nickname = "sonny567",
createdAt = "2023-07-28"
),
MessageDetail(
letterId = 3,
content = "혹시 어떤 요일이 괜찮으실까요??",
writer = true,
nickname = "qwer1111",
createdAt = "2023-07-28"
)
)
}
}
| 13 |
Kotlin
|
2
| 0 |
f6854b6cbb2107d95f658ea30798e055d89783cf
| 1,155 |
Dotoring_AOS
|
MIT License
|
plugin-common/src/main/kotlin/ru/itbasis/jvmwrapper/core/downloader/AbstractDownloader.kt
|
itbasis
| 143,887,823 | false | null |
package ru.itbasis.jvmwrapper.core.downloader
import mu.KLogger
import ru.itbasis.jvmwrapper.core.HttpClient
import ru.itbasis.jvmwrapper.core.SystemInfo
import ru.itbasis.jvmwrapper.core.checksum256
import ru.itbasis.kotlin.utils.copyTo
import java.io.File
abstract class AbstractDownloader {
protected abstract val logger: KLogger
abstract val remoteArchiveFile: RemoteArchiveFile
open fun auth() {}
open fun license() {}
fun download(target: File, downloadProcessListener: DownloadProcessListener? = null) {
download(remoteArchiveFile = remoteArchiveFile, target = target, downloadProcessListener = downloadProcessListener)
}
open fun download(remoteArchiveFile: RemoteArchiveFile, target: File, downloadProcessListener: DownloadProcessListener? = null) {
if (target.isFile && target.checksum256(remoteArchiveFile.checksum)) {
return
}
auth()
license()
val entity = httpClient.getEntity(remoteArchiveFile.url)
val sizeTotal = entity.contentLength
target.outputStream().use { fos ->
entity.content.buffered().copyTo(target = fos, listenerStep = sizeTotal / 10_000) { sizeCurrent ->
return@copyTo downloadProcessListener == null || downloadProcessListener.invoke(
remoteArchiveFile.url, sizeCurrent, sizeTotal
)
}
fos.flush()
}
require(target.isFile) {
val msg = "$target is not a file"
logger.error { msg }
msg
}
}
open fun RemoteArchiveFile.isRequireAuthentication() =
false
protected abstract fun String?.getRemoteArchiveFile(): RemoteArchiveFile?
open fun String.urlWithinHost() =
this
val archiveArchitecture = if (SystemInfo.is32Bit) "i586" else "x64"
val httpClient = HttpClient()
internal fun String.htmlContent(httpClient: HttpClient): String {
return httpClient.getContent(urlWithinHost())
}
}
| 8 |
Kotlin
|
0
| 2 |
c9066a0147d979b66175ae8decf82307dea7f69d
| 1,794 |
jvm-wrapper-ide-plugins
|
MIT License
|
build-logic/src/main/kotlin/LibsLibrary.kt
|
NikolayKuts
| 831,630,647 | false |
{"Kotlin": 46666}
|
data class LibsLibrary(
val groupId: String,
val artifactId: String,
val version: String
)
| 0 |
Kotlin
|
0
| 0 |
9fd6ef454f7cdedbb9e2920674bb1e95ab7ee5ff
| 102 |
LoKdroid
|
Apache License 2.0
|
app/src/main/java/com/apiguave/tinderclonecompose/chat/ChatViewModel.kt
|
alejandro-piguave
| 567,907,964 | false |
{"Kotlin": 204908}
|
package com.apiguave.tinderclonecompose.chat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.apiguave.tinderclonedomain.match.Match
import com.apiguave.tinderclonedomain.usecase.GetMessagesUseCase
import com.apiguave.tinderclonedomain.usecase.SendMessageUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class ChatViewModel(
private val getMessagesUseCase: GetMessagesUseCase,
private val sendMessageUseCase: SendMessageUseCase): ViewModel() {
private val _match = MutableStateFlow<Match?>(null)
val match = _match.asStateFlow()
fun getMessages(matchId: String) = getMessagesUseCase(matchId)
fun sendMessage(text: String){
val matchId = _match.value?.id ?: return
viewModelScope.launch {
sendMessageUseCase(matchId, text)
}
}
fun setMatch(match: Match){
_match.value = match
}
}
| 1 |
Kotlin
|
11
| 41 |
120ad9a2ffa80638977f8eba1a77f21f83f67be8
| 986 |
TinderCloneCompose
|
MIT License
|
common/src/test/kotlin/com/helloclue/sse/SseParseLineTest.kt
|
biowink
| 223,560,480 | false | null |
package com.helloclue.sse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertTrue
class SseParseLineTest {
@Test
fun `onEventType is called when the field is "event" with correct event type`() {
val eventType = "fun"
parseSseLine(
line = "event:$eventType",
onEventEnd = { assertTrue(true) },
onEventType = { assertEquals(eventType, it) },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertFails { } },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onEventData is called when the field is "data" with correct value of data`() {
val value = "YOHO"
parseSseLine(
line = "data:$value",
onEventEnd = { assertTrue(true) },
onEventType = { assertFails { } },
onEventData = { assertEquals(value, it) },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertFails { } },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onEventData is called when the field is "data" and leading space is removed from value if any`() {
val value = " +02"
val expectedValue = "+02"
parseSseLine(
line = "data:$value",
onEventEnd = { assertTrue(true) },
onEventType = { assertFails { } },
onEventData = { assertEquals(expectedValue, it) },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertFails { } },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onEventId is called when the field is "id"`() {
val eventId = ""
parseSseLine(
line = "id:$eventId",
onEventEnd = { assertFails { } },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertEquals(eventId, it) },
onRetryTime = { assertFails { } },
onComment = { assertTrue(true) },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onRetryTime is called when the field is "retry" and the value consists of ASCII digits`() {
val retryTime = 3000L
parseSseLine(
line = "retry:$retryTime",
onEventEnd = { assertFails { } },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertEquals(retryTime, it) },
onComment = { assertTrue(true) },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onInvalidReconnectionTime is called when the field is "retry" and the value is not ASCII digits`() {
val retryTime = "¯\\_(ツ)_/¯"
parseSseLine(
line = "retry:$retryTime",
onEventEnd = { assertFails { } },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertTrue(true) },
onInvalidReconnectionTime = { assertEquals(retryTime, it) },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onInvalidField is called when there is unknown field`() {
val field = "¯\\_(ツ)_/¯"
parseSseLine(
line = "$field:",
onEventEnd = { assertFails { } },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertTrue(true) },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertEquals(field, it) }
)
}
@Test
fun `onComment is called when the line starts with colon`() {
parseSseLine(
line = ":",
onEventEnd = { assertFails { } },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertTrue(true) },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
@Test
fun `onEventEnd is called when there is empty line`() {
parseSseLine(
line = "",
// Verify on event end is called
onEventEnd = { assertTrue(true) },
onEventType = { assertFails { } },
onEventData = { assertFails { } },
onEventId = { assertFails { } },
onRetryTime = { assertFails { } },
onComment = { assertFails { } },
onInvalidReconnectionTime = { assertFails { } },
onInvalidField = { assertFails { } }
)
}
}
| 2 |
Kotlin
|
2
| 41 |
4fbd373adfe2acfd57dc3f96a0ba95be1243427b
| 5,509 |
oksse
|
MIT License
|
app/src/main/java/com.terracode.blueharvest/utils/constants/Constants.kt
|
Capstone-Terracoders
| 718,832,727 | false |
{"Kotlin": 141529}
|
package com.terracode.blueharvest.utils.constants
/**
* Enum class to declare conversion constants for units.
* Each constant represents a conversion factor from one unit to another.
*
* @author <NAME> 3/2/2024
*
* @property value The value representing the conversion factor.
*
* @value CM_TO_INCH Conversion factor from centimeters to inches.
* @value MPH_TO_KMH Conversion factor from miles per hour to kilometers per hour.
*/
enum class UnitConstants(val value: Double) {
CM_TO_INCH(0.3937),
MPH_TO_KMH(0.621371),
}
/**
* Enum class to declare text size constants.
* Each constant represents a specific text size value.
*
* @property value The value representing the text size.
*
* @value MIN_TEXT_SIZE Minimum text size constant.
* @value MAX_TEXT_SIZE Maximum text size constant.
*/
enum class TextConstants(val value: Float) {
MIN_TEXT_SIZE(12f),
MAX_TEXT_SIZE(32f),
DEFAULT_TEXT_SIZE(20f)
}
enum class PreferenceKeys {
//---Accessibility Settings---//
SELECTED_COLOR_POSITION,
SELECTED_LANGUAGE_POSITION,
SELECTED_TEXT_SIZE,
SELECTED_UNIT,
//---Display Values---//
MAX_RPM_DISPLAYED_INPUT,
MAX_HEIGHT_DISPLAYED_INPUT,
OPTIMAL_RPM_RANGE_INPUT,
OPTIMAL_HEIGHT_RANGE_INPUT,
//---Safety Parameters---//
MAX_RAKE_RPM,
MIN_RAKE_HEIGHT,
//---Operation Parameters---//
RPM_COEFFICIENT,
HEIGHT_COEFFICIENT
}
enum class HomeKeys {
RECORD_BUTTON,
NOTIFICATION
}
enum class NotificationTypes {
NOTIFICATION,
WARNING,
ERROR
}
enum class MaxUserInputInt(val value: Int) {
MAX_DEFAULT_INPUT(100000),
MAX_HEIGHT_INPUT(300)
}
enum class MaxUserInputString(val value: String) {
MAX_DEFAULT_INPUT("100,000"),
MAX_HEIGHT_INPUT("300")
}
| 68 |
Kotlin
|
0
| 0 |
85d18410db1de38ea7d93d1fdf65549a18dd13fc
| 1,772 |
Mobile-Application
|
MIT License
|
opentelemetry-springboot-starter/src/main/kotlin/cloud/djet/spring/autoconfigure/OpenTelemetryAutoConfiguration.kt
|
DJetCloud
| 389,661,155 | false | null |
package cloud.djet.spring.autoconfigure
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.context.propagation.ContextPropagators
import io.opentelemetry.sdk.OpenTelemetrySdk
import io.opentelemetry.sdk.resources.Resource
import io.opentelemetry.sdk.trace.SdkTracerProvider
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor
import io.opentelemetry.sdk.trace.export.SpanExporter
import io.opentelemetry.sdk.trace.samplers.Sampler
import org.springframework.beans.factory.ObjectProvider
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
@Configuration
class OpenTelemetryAutoConfiguration(private val env: Environment) {
companion object {
private const val probability = 1.0
}
@Bean
@ConditionalOnMissingBean
fun openTelemetry(
propagatorsProvider: ObjectProvider<ContextPropagators>,
spanExportersProvider: ObjectProvider<List<SpanExporter>>
): OpenTelemetry {
val appName = env.getProperty("spring.application.name") ?: "unknown-springboot-app"
val tracerProviderBuilder =
SdkTracerProvider.builder()
.setResource(Resource.create(Attributes.of(
AttributeKey.stringKey("service.name"), appName
)))
spanExportersProvider.getIfAvailable { emptyList() }
.stream() // todo SimpleSpanProcessor...is that really what we want here?
.map { SimpleSpanProcessor.create(it) }
.forEach { tracerProviderBuilder.addSpanProcessor(it) }
val tracerProvider = tracerProviderBuilder
.setSampler(Sampler.traceIdRatioBased(probability))
.build()
val propagators = propagatorsProvider.getIfAvailable { ContextPropagators.noop() }
return OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.setPropagators(propagators)
.buildAndRegisterGlobal()
}
}
| 0 |
Kotlin
|
0
| 1 |
c1d19850010e6d416f3c74cc829d575cb061e395
| 2,214 |
djet-spring-kotlin
|
Apache License 2.0
|
java/dagger/hilt/android/plugin/src/main/kotlin/dagger/hilt/android/plugin/AndroidEntryPointClassTransformer.kt
|
brijesh211
| 261,571,404 | true |
{"YAML": 1, "Starlark": 102, "Markdown": 5, "Text": 1, "Ignore List": 1, "XML": 22, "Java": 1060, "Shell": 15, "Gradle": 14, "INI": 9, "Kotlin": 26, "Batchfile": 1, "Python": 1, "Protocol Buffer": 1, "Maven POM": 2}
|
/*
* Copyright (C) 2020 The Dagger 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 dagger.hilt.android.plugin
import dagger.hilt.android.plugin.util.isClassFile
import dagger.hilt.android.plugin.util.isJarFile
import java.io.File
import java.io.FileInputStream
import java.util.zip.ZipInputStream
import javassist.ClassPool
import javassist.CtClass
import org.slf4j.LoggerFactory
/**
* A helper class for performing the transform.
*
* Create it with the list of all available source directories along with the root output directory
* and use [AndroidEntryPointClassTransformer.transformFile] or
* [AndroidEntryPointClassTransformer.transformJarContents] to perform the actual transformation.
*/
internal class AndroidEntryPointClassTransformer(
val taskName: String,
allInputs: List<File>,
private val sourceRootOutputDir: File,
private val copyNonTransformed: Boolean
) {
private val logger = LoggerFactory.getLogger(AndroidEntryPointClassTransformer::class.java)
// A ClassPool created from the given input files, this allows us to use the higher
// level Javaassit APIs, but requires class parsing/loading.
private val classPool: ClassPool = ClassPool(true).also { pool ->
allInputs.forEach {
pool.appendClassPath(it.path)
}
}
init {
sourceRootOutputDir.mkdirs()
}
/**
* Transforms the classes inside the jar and copies re-written class files if and only if they are
* transformed.
*
* @param inputFile The jar file to transform, must be a jar.
*/
fun transformJarContents(inputFile: File) {
require(inputFile.isJarFile()) {
"Invalid file, '$inputFile' is not a jar."
}
// Validate transform is not applied to a jar when copying is enabled, meaning the transformer
// is being used in the Android transform API pipeline which does not need to transform jars
// and handles copying them.
check(!copyNonTransformed) {
"Transforming a jar is not supported with 'copyNonTransformed'."
}
ZipInputStream(FileInputStream(inputFile)).use { input ->
var entry = input.nextEntry
while (entry != null) {
if (entry.isClassFile()) {
val clazz = classPool.makeClass(input, false)
transformClassToOutput(clazz)
}
entry = input.nextEntry
}
}
}
/**
* Transform a single class file.
*
* @param inputFile The file to transform, must be a class file.
*/
fun transformFile(inputFile: File) {
check(inputFile.isClassFile()) {
"Invalid file, '$inputFile' is not a class."
}
val clazz = inputFile.inputStream().use { classPool.makeClass(it, false) }
transformClassToOutput(clazz)
}
private fun transformClassToOutput(clazz: CtClass) {
val transformed = transformClass(clazz)
if (transformed || copyNonTransformed) {
clazz.writeFile(sourceRootOutputDir.path)
}
}
private fun transformClass(clazz: CtClass): Boolean {
if (!clazz.hasAnnotation("dagger.hilt.android.AndroidEntryPoint")) {
// Not a AndroidEntryPoint annotated class, don't do anything.
return false
}
// TODO(danysantiago): Handle classes with '$' in their name if they do become an issue.
val superclassName = clazz.classFile.superclass
val entryPointSuperclassName =
clazz.packageName + ".Hilt_" + clazz.simpleName.replace("$", "_")
logger.info(
"[$taskName] Transforming ${clazz.name} to extend $entryPointSuperclassName instead of " +
"$superclassName."
)
clazz.superclass = classPool.get(entryPointSuperclassName)
return true
}
}
| 0 | null |
0
| 0 |
b7148941604249764fcf1b01b5482b1b84f5462e
| 4,124 |
dagger
|
Apache License 2.0
|
node/src/main/kotlin/edu/dhu/auction/node/flow/AccountCreateFlow.kt
|
Sqrelord
| 370,037,377 | false | null |
package edu.dhu.auction.node.flow
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.accounts.contracts.states.AccountInfo
import com.r3.corda.lib.accounts.workflows.accountService
import com.r3.corda.lib.accounts.workflows.flows.ShareAccountInfo
import net.corda.core.flows.FlowException
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.InitiatingFlow
import net.corda.core.flows.StartableByRPC
import java.util.concurrent.ExecutionException
@InitiatingFlow
@StartableByRPC
class AccountCreateFlow(private val username: String) : FlowLogic<AccountInfo>() {
@Suspendable
@Throws(FlowException::class)
override fun call(): AccountInfo {
return try {
val accountInfo = accountService.createAccount(username).get()
val parties = serviceHub.networkMapCache.allNodes
.map { it.legalIdentities.first() }
.filter { it != ourIdentity }
subFlow(ShareAccountInfo(accountInfo, parties))
accountInfo.state.data
} catch (e: InterruptedException) {
throw FlowException(e.message, e.cause)
} catch (e: ExecutionException) {
throw FlowException(e.message, e.cause)
}
}
}
| 1 | null |
3
| 10 |
06a41af276cc2e50d1373fbec3011a540f5b1796
| 1,252 |
blockchain-auction-server
|
Apache License 2.0
|
app/src/main/java/com/dilshan/qr__barcode_scanner/MainActivity.kt
|
lasithadilshan
| 345,253,043 | false | null |
package com.dilshan.qr__barcode_scanner
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.budiyev.android.codescanner.AutoFocusMode
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.CodeScannerView
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ErrorCallback
import com.budiyev.android.codescanner.ScanMode
private const val CAMERA_REQUEST_CODE = 101;
class MainActivity : AppCompatActivity() {
private lateinit var codeScanner: CodeScanner
private lateinit var scannerView:CodeScannerView
private lateinit var tvTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvTextView = findViewById(R.id.tv_textView)
scannerView = findViewById(R.id.scanner_view)
setupPermissions()
codeScanner()
}
private fun codeScanner() {
codeScanner = CodeScanner(this, scannerView)
codeScanner.apply {
camera = CodeScanner.CAMERA_BACK
formats = CodeScanner.ALL_FORMATS
autoFocusMode = AutoFocusMode.SAFE
scanMode = ScanMode.CONTINUOUS
isAutoFocusEnabled = true
isFlashEnabled = false
decodeCallback = DecodeCallback {
runOnUiThread {
tvTextView.text = it.text
}
}
errorCallback = ErrorCallback {
runOnUiThread {
Log.e("Main", "Camera initialization error: ${it.message}")
}
}
}
scannerView.setOnClickListener {
codeScanner.startPreview()
}
}
override fun onResume() {
super.onResume()
codeScanner.startPreview()
}
override fun onPause() {
codeScanner.releaseResources()
super.onPause()
}
private fun setupPermissions() {
val permission = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA)
if (permission != PackageManager.PERMISSION_GRANTED) {
makeRequest()
}
}
private fun makeRequest() {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA),
CAMERA_REQUEST_CODE)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
CAMERA_REQUEST_CODE -> {
if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"You need the camera permission to be able to use this app!",Toast.LENGTH_SHORT).show()
}else{
//successful
}
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
817abc03f004f2e96d0d8fb7284e48a9ffffd086
| 3,171 |
QR_and_Barcode_Scanner
|
Apache License 2.0
|
axon-vote/src/main/kotlin/daggerok/counter/CounterAggregator.kt
|
daggerok
| 102,229,956 | false | null |
package daggerok.counter
import org.axonframework.commandhandling.CommandHandler
import org.axonframework.commandhandling.model.AggregateIdentifier
import org.axonframework.commandhandling.model.AggregateLifecycle
import org.axonframework.eventsourcing.EventSourcingHandler
import org.axonframework.spring.stereotype.Aggregate
import org.springframework.stereotype.Component
@Component("axonCounterAggregator")
@Aggregate(repository = "axonCounterRepository")
class CounterAggregator() {
@AggregateIdentifier
lateinit var counterId: String
var enabled: Boolean = false
var counter: Int = 0
@CommandHandler
constructor(cmd: CreateCounterCommand) : this() {
AggregateLifecycle.apply(CounterCreatedEvent(cmd.counterId))
}
@EventSourcingHandler
fun on(evt: CounterCreatedEvent) {
counterId = evt.counterId!!
}
@CommandHandler
fun handle(cmd: EnableCounterCommand) {
if (!enabled) AggregateLifecycle.apply(CounterEnabledEvent(cmd.counterId))
}
@EventSourcingHandler
fun on(evt: CounterEnabledEvent) {
enabled = true
}
@CommandHandler
fun handle(cmd: DisableCounterCommand) {
if (enabled) AggregateLifecycle.apply(CounterDisabledEvent(cmd.counterId))
}
@EventSourcingHandler
fun on(evt: CounterDisabledEvent) {
enabled = false
}
@CommandHandler
fun handle(cmd: IncrementCounterCommand) {
if (!enabled) throw CounterDisabledException()
AggregateLifecycle.apply(CounterIncrementedEvent(cmd.counterId, cmd.amount))
}
@EventSourcingHandler
fun on(evt: CounterIncrementedEvent) {
counter += evt.amount!!
}
@CommandHandler
fun handle(cmd: DecrementCounterCommand) {
if (!enabled) throw CounterDisabledException()
AggregateLifecycle.apply(CounterDecrementedEvent(cmd.counterId, cmd.amount))
}
@EventSourcingHandler
fun on(evt: CounterDecrementedEvent) {
counter -= evt.amount!!
}
@CommandHandler
fun handle(cmd: ResetCounterCommand) {
if (!enabled) throw CounterDisabledException()
AggregateLifecycle.apply(CounterResettedEvent(cmd.counterId))
}
@EventSourcingHandler
fun on(evt: CounterResettedEvent) {
counter = evt.to!!
}
}
| 10 | null |
38
| 97 |
11340b9fe8b0b53445d7ed869d409d378999e334
| 2,169 |
spring-5-examples
|
MIT License
|
src/test/kotlin/com/nakoradio/geoleg/services/EngineTest.kt
|
Arch-vile
| 288,817,123 | false | null |
package com.nakoradio.geoleg.services
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.nakoradio.geoleg.model.LocationReading
import com.nakoradio.geoleg.model.Quest
import com.nakoradio.geoleg.model.Scenario
import com.nakoradio.geoleg.model.State
import com.nakoradio.geoleg.model.TechnicalError
import com.nakoradio.geoleg.model.WebAction
import com.nakoradio.geoleg.utils.Time
import java.lang.IllegalStateException
import java.time.OffsetDateTime
import java.util.UUID
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.not
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.Matchers.nullValue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class EngineTest {
private val jsonmappper = ObjectMapper().registerModule(KotlinModule())
private val loader = ScenarioLoader(jsonmappper)
var now: OffsetDateTime = OffsetDateTime.now()
private val timeProvider = object : Time() {
override fun now(): OffsetDateTime {
return now
}
}
// Engine has location verification turned on
private val engine = Engine(
true,
timeProvider,
loader
)
@BeforeEach
fun beforeEach() {
now = OffsetDateTime.now()
}
@Test
fun `Happy flow entire scenario`() {
// Given: Testing the real scenario from config
val scenario = loader.table.scenarios[0]
// When: Scanning the first QR (will point to scenario init)
var action = engine.initScenario(null, scenario.name)
// Then: Scenario is initialized
assertThat(
action,
equalTo(
// User directed to complete first quest
WebAction(
LocationReadingViewModel("/engine/complete/ancient-blood/0/6a5fc6c0f8ec", null, null),
// State initialized for scenario
State(
scenario.name, 0, timeProvider.now().plusYears(10), timeProvider.now(), null,
action.state!!.userId, 0, timeProvider.now()
)
)
)
)
var state = action.state!!
tick()
// User redirected to complete first quest, location does not matter
action = engine.complete(state, scenario.name, 0, scenario.quests[0].secret, locationSomewhere().asString())
// Then: Quest completed
assertQuestCompleted(action, state)
state = action.state!!
tick()
// When: User starts next quest, this is the quest to the sign, again location where starting this does not matter
action = startQuest(state, loader.nextQuest(state), locationSomewhere())
// Then: Quest started
assertQuestStarted(action, state)
state = action.state!!
tick()
// When: User scans the first QR on the field
action = scanTargetQR(state)
// Then: Quest completed
assertQuestCompleted(action, state)
state = action.state!!
tick()
/**
* SILTA quest
*/
// started the SILTA quests
action = startNextQuest(state)
// Then: We'll set the scenario start timestamp here
// as we started the first on field leg. Otherwise total
// time for scenario would be calculated including time
// needed to travel from home to the first on field quest.
assertThat(action.state!!.scenarioStarted, equalTo(now))
state = assertStartedAndThenCompleteIt(action, state, now)
/**
* KUUSI quest
*/
state = startAndCompleteNextQuest(state)
/**
* KATAJA quest
*/
state = startAndCompleteNextQuest(state)
/**
* KELO quest
*/
state = startAndCompleteNextQuest(state)
/**
* MASTO quest
*/
state = startAndCompleteNextQuest(state)
/**
* HELIKOPTERI quest
*/
state = startAndCompleteNextQuest(state)
/**
* KATAJA quest (again)
*/
state = startAndCompleteNextQuest(state)
/**
* SIILO quest
*/
// When: User starts the quest
action = startNextQuest(state)
// Then: Quest started
assertQuestStarted(action, state)
state = action.state!!
tick()
// When: User completes the quest
action = scanTargetQR(state)
// Then: Quest completed
assertThat(
action,
equalTo(
WebAction(
// Then: Show quest success view
ScenarioEndViewModel(loader.currentQuest(state).successPage),
// And: Quest completion marked to state
state.copy(questCompleted = timeProvider.now())
)
)
)
tick()
}
private fun startAndCompleteNextQuest(currentState: State): State {
// When: User starts the quest
var action = startNextQuest(currentState)
return assertStartedAndThenCompleteIt(action, currentState)
}
private fun assertStartedAndThenCompleteIt(
action: WebAction,
previousState: State
) = assertStartedAndThenCompleteIt(action, previousState, null)
private fun assertStartedAndThenCompleteIt(
action: WebAction,
previousState: State,
scenarioStartedTime: OffsetDateTime?
): State {
// Then: Quest started
assertQuestStarted(action, previousState, scenarioStartedTime)
var newState = action.state!!
tick()
// When: User completes the quest
var nextAction = scanTargetQR(newState)
// Then: Quest completed
assertQuestCompleted(nextAction, newState)
tick()
return nextAction.state!!
}
private fun tick() {
now = now.plusMinutes(5)
}
/**
* Flow for the first quest is:
* 1) User scans the QR on Geocaching.com
* 2) On a redirect to `/engine/init/:scenario` state cookie is set for `currentQuest=0`
* 3) User is automatically redirected to complete the first quest (state not changed)
*
* So first quest is the one started and automatically completed by scanning the QR code on the
* geocaching.com site so this is a bit different from your normal `running a quest` state.
*
* These tests are for the case where user has visited the init page (has `currentQuest=0` state)
* and is directed to complete the first quest. After first quest completion page shows the background
* story for the scenario and "Go" button to start the second quest.
*
*/
@Nested
inner class `Running the first quest` {
private val scenario = loader.table.scenarios[1]
private val currentQuest = scenario.quests[0]
/**
* User has visited the `/engine/init/:scenario` and is now being redirected to complete
* the first quest.
*/
@Nested
inner class `Quest ongoing` {
private val currentState = stateForRunningQuest(scenario, currentQuest)
/**
* Init scenario will redirect to this action to automatically complete
* the intro after location read.
*/
@Test
fun `Complete the quest does not check location`() {
// When: Intro quest is completed with random location
val action = engine.complete(
currentState, scenario.name, 0, currentQuest.secret,
locationSomewhere().asString()
)
// Then: Show success page
assertQuestCompleted(action, currentState)
}
@Test
fun `Rescanning the QR code will reinitialize the scenario`() {
// When: Scanning the QR code again, i.e. calling the scenario init
val outcome = engine.initScenario(currentState, scenario.name)
// Then: Scenario is restarted
assertScenarioRestartAction(currentState, scenario, outcome)
}
/**
* Trying to complete any other later quest than second one should restart the scenario.
* Special handling for the first quest only. No real reason apart for the second quest
* , see above test case but let's make it work the same for other later quests also.
*
* User is scanning the QR code of a later quest.
*/
@Test
fun `Scanning QR of a later quest should restart the scenario`() {
// When: Completing later quest
val outcome = scanQR(currentState, scenario, scenario.quests[3])
// Then: Restart the scenario
assertScenarioRestartAction(currentState, scenario, outcome)
}
/**
* Start url action for first quest is never called. Should never happen so is ok to just fail.
*/
@Test
fun `Calling start URL of first quest will give error`() {
assertThrows<IllegalStateException> {
engine.startQuest(
currentState,
scenario.name,
0,
scenario.quests[0].secret,
LocationReading(2.2, 1.1, timeProvider.now()).asString()
)
}
}
@Test
fun `Calling start URL of a later quest will continue countdown`() {
// Trying to start a later quest
val outcome = engine.startQuest(
currentState,
scenario.name,
3,
scenario.quests[3].secret,
freshLocation(scenario.quests[3])
)
assertCountdownContinues(outcome, currentState)
}
}
/**
* User has visited the automatic redirection to `/engine/complete/...` and completed the
* quest. He is currently shown the quest success page.
*/
@Nested
inner class `Quest completed` {
private val currentState = stateForRunningQuest(scenario, currentQuest).copy(questCompleted = timeProvider.now().minusSeconds(13))
/**
* User is currently on the first quest complete page (as it was automatically
* completed). Reloading page should complete the quest again.
*/
@Test
fun `Reloading page completes current quest again`() {
// When: Completing current quest again
val outcome = engine.complete(
currentState, scenario.name, currentQuest.order, currentQuest.secret,
// Any location will do
// TODO: Why cannot this just take actual location instead. Do the string parsing on controller.
locationSomewhere().asString()
)
// Then: Quest success page shown
assertQuestSuccessViewShown(outcome, currentState)
}
/**
* Second quest (target location is the first QR on the field) can be started anywhere,
* as the "Go" button is shown after the autocompleting first quest. Most likely second
* quest is started at home.
*/
@Test
fun `Clicking GO to start second quest does not require valid location`() {
// When: Starting the second quest with random location
val secondQuest = nextQuest(scenario, currentQuest)
val outcome = startQuest(
currentState, secondQuest, locationSomewhere()
)
// Then: Second quest successfully started
assertQuestStarted(outcome, currentState, secondQuest)
}
/**
* A special case for first-second quest.
*
* User has scanned the online qr and completed the first quest (#0) (it completes automatically)
* but has not clicked to start the next quest. Active quest is still 0.
*
* He could have received the coordinates for the second quest (#1) by other means or from
* someone else. Now that he scans the second quest code, we can just restart the scenario.
* We could just complete the second quest, but maybe safer to just restart the scenario.
*/
@Test
fun `Scanning QR of next quest should restart the scenario`() {
// When: Trying to complete second quest
val result = scanQR(currentState, scenario, nextQuest(scenario, currentQuest))
// Then: Restart the scenario
assertScenarioRestartAction(currentState, scenario, result)
}
}
}
/**
*
* First quest is the introduction quest that is automatically instantly completed. Second
* quest is thus also started right away at home. This has the following implications
* for the second quest processing logic:
* - Second quest has unlimited time to complete
*
* For these tests, user has just started second quest by clicking the "GO" and is on the
* countdown page (`/engine/start/:scenario/1/:secret/:location`)
*/
@Nested
inner class `Second quest` {
private val scenario = loader.table.scenarios[1]
private val currentQuest = scenario.quests[1]
@Nested
inner class `Quest ongoing` {
// Second quest has unlimited time to complete
private val currentState = stateForRunningQuest(scenario, currentQuest)
@Nested
inner class `Restarting current quest (template)` :
BaseTestClassForRestartingCurrentQuest(
currentState,
{ outcome -> assertCountdownContinues(outcome, currentState) }
)
@Test
fun `Second quest has no DL`() {
assertThat(currentState.questDeadline, nullValue())
}
@Test
fun `Scanning QR completes the quest`() {
// When: Completing the quest
val outcome = scanQR(currentState, scenario, currentQuest)
// Then: Quest completed
assertQuestCompleted(outcome, currentState)
}
@Test
fun `Scanning QR past deadline`() {
// Given: DL is long gone already
now = OffsetDateTime.now().plusYears(100)
// When: Scanning the QR
val outcome = scanQR(currentState, scenario, currentQuest)
// Then: Quest completed, second quest has no deadline
assertQuestCompleted(outcome, currentState)
}
@Test
fun `Scanning QR should fail if location is not fresh`() {
// And: Old location reading
val expiredLocationRead =
locationFor(currentQuest).copy(createdAt = timeProvider.now().minusDays(200))
// When: Scanning the QR code
// Then: Error about expired location
val error = assertThrows<TechnicalError> {
scanQR(currentState, scenario, currentQuest, expiredLocationRead)
}
assertThat(error.message, equalTo("Could not get fresh location, try rescanning the QR"))
}
@Test
fun `Scanning QR should fail if location is not close to quest location`() {
// Given: Location far from quest location
var location = locationSomewhere()
// When: Scanning the QR
// Then: Error about not being close to target location
val error = assertThrows<TechnicalError> {
scanQR(currentState, scenario, currentQuest, location)
}
assertThat(error.message, equalTo("Coordinates not matching QR location, try rescanning the QR"))
}
@Test
fun `Scanning later quest's QR code should continue countdown`() {
// When: Scanning QR code of later quest
val outcome = scanQR(currentState, scenario, scenario.quests[4])
// Then: Countdown continues
assertCountdownContinues(outcome, currentState)
}
@Test
fun `Scanning later quest's QR code with bad location should continue countdown`() {
// When: Scanning QR code of later quest
val outcome =
scanQR(currentState, scenario, scenario.quests[4], locationSomewhere())
// Then: Countdown continues
assertCountdownContinues(outcome, currentState)
}
@Test
fun `Starting next quest before completing this keeps countdown running`() {
// When: Starting the next quest
val outcome = startQuest(currentState, loader.nextQuest(currentState))
// Then: Countdown keeps running
assertCountdownContinues(outcome, currentState)
}
@Test
fun `Starting next quest with wrong location keeps running the countdown`() {
// When: Starting the next quest with too far location
val action =
startQuest(currentState, loader.nextQuest(currentState), locationSomewhere())
// Then: Countdown keeps on running
assertCountdownContinues(action, currentState)
}
@Test
fun `Starting next quest with stale location before completing this keeps countdown running`() {
val nextQuest = loader.nextQuest(currentState)
// When: Starting the next quest before completing this
var action = startQuest(
currentState,
nextQuest,
locationFor(nextQuest).copy(createdAt = timeProvider.now().minusYears(1))
)
// Then: Countdown continues (even with location reading expired)
assertCountdownContinues(action, currentState)
}
@Test
fun `Starting later quest should keep on running countdown`() {
// When: Trying to start upcoming quest
val outcome = startQuest(currentState, scenario.quests[4])
// Then: Countdown continues
assertCountdownContinues(outcome, currentState)
}
@Test
fun `Starting later quest (with bad location) should keep on running countdown`() {
// When: Trying to start upcoming quest with bad location
val outcome =
startQuest(currentState, scenario.quests[4], locationSomewhere())
// Then: Countdown continues
assertCountdownContinues(outcome, currentState)
}
}
}
@Nested
inner class `After completing second quest` {
private val scenario = loader.table.scenarios[1]
private val currentQuest = scenario.quests[1]
// Second quest has unlimited time to complete
private val currentState = stateForRunningQuest(scenario, currentQuest).copy(questCompleted = timeProvider.now())
@Test
fun `Starting next quest fails if expired location`() {
val nextQuest = nextQuest(scenario, currentQuest)
// When: Starting the next quest with stale location
// Then: Will give location expired error
val error = assertThrows<TechnicalError> {
startQuest(
currentState,
nextQuest,
locationFor(nextQuest).copy(createdAt = timeProvider.now().minusYears(1))
)
}
assertThat(error.message, equalTo("Could not get fresh location, try rescanning the QR"))
}
@Test
fun `Starting next quest fails if wrong location`() {
val nextQuest = nextQuest(scenario, currentQuest)
// When: Starting the next quest with too far location
// Then: Will give GPS error
val error = assertThrows<TechnicalError> {
startQuest(currentState, nextQuest, locationSomewhere())
}
assertThat(error.message, equalTo("Coordinates not matching QR location, try rescanning the QR"))
}
@Test
fun `Starting next quest successful`() {
// When: Starting the next quest
val nextQuest = nextQuest(scenario, currentQuest)
val outcome = startQuest(currentState, nextQuest)
// Then: Quest is started
assertQuestStarted(outcome, currentState, nextQuest, now)
}
}
/**
* User has state for currently doing the Nth quest
*/
@Nested
inner class `Nth quest` {
private val scenario = loader.table.scenarios[1]
private val currentQuest = scenario.quests[5]
/**
* Quest has been started but not yet completed
*/
@Nested
inner class `Quest ongoing` {
private val currentState = stateForRunningQuest(scenario, currentQuest)
@Nested
inner class `Quest DL has expired` {
// Quest DL has expired
private val currentState = stateForRunningQuest(scenario, currentQuest)
.copy(questDeadline = timeProvider.now().minusYears(1))
@Nested
inner class `Completing quest should show timeout failure (template)` : BaseTestClassForCompletingCurrentQuest(
currentState,
{ outcome -> assertQuestFailed(outcome, currentState) }
)
@Nested
inner class `Completing out of order quests should show failure (template)` :
BaseTestClassForCompletingOutOfOrderQuests(
currentState,
{ outcome -> assertQuestFailed(outcome, currentState) }
)
@Nested
inner class `Restarting current quest should show failure (template)` : BaseTestClassForRestartingCurrentQuest(
currentState,
{ outcome -> assertQuestFailed(outcome, currentState) }
)
@Nested
inner class `Starting another quest should show failure (template)` :
BaseTestClassForStartingAnotherQuest(
currentState,
{ o -> assertQuestFailed(o, currentState) }
)
}
@Nested
inner class `Quest DL not exceeded` {
@Nested
inner class `Should complete current quest (template)` : BaseTestClassForCompletingCurrentQuest(
currentState,
{ outcome -> assertQuestCompleted(outcome, currentState) }
)
@Nested
inner class `Should continue countdown (template)` : BaseTestClassForStartingAnotherQuest(
currentState,
{ outcome -> assertCountdownContinues(outcome, currentState) }
)
@Nested
inner class `Should continue countdown also (template)` :
BaseTestClassForRestartingCurrentQuest(currentState, { outcome -> assertCountdownContinues(outcome, currentState) })
@Nested
inner class `Completing out of order quests (template)` :
BaseTestClassForCompletingOutOfOrderQuests(
currentState,
{ outcome -> assertCountdownContinues(outcome, currentState) }
)
}
}
/**
* User has completed this quest successfully by scanning the QR. Next quest has not yet
* been started.
*/
@Nested
inner class `Quest completed` {
private val currentState =
stateForRunningQuest(scenario, currentQuest)
.copy(
questCompleted = timeProvider.now().minusSeconds(13)
)
@Nested
inner class `Quest DL has expired` {
@Test
fun `MISSING TESTS`() {
}
}
@Nested
inner class `Quest DL not exceeded` {
@Nested
inner class `Recompleting current quest (template)` : BaseTestClassForReCompletingCurrentQuest(currentState)
@Nested
inner class `Starting next quest` {
@Test
fun `Successfully start next quest`() {
// When: Starting next quest
val action = startNextQuest(currentState)
// Then: Countdown for the next quest
assertQuestStarted(action, currentState)
}
/**
* Important scenario to cover. After completing the quest, user has all the time
* they need to read the next story before clicking go. It is very likely that
* current quest's DL expires while reading the story. Starting the next quest
* should be possible nevertheless.
*/
@Test
fun `Successfully start next quest after this quest's DL expired`() {
val nextQuest = nextQuest(scenario, currentQuest)
// Given: DL for current quest has expired (after successfully completing it)
val state = currentState.copy(
questDeadline = timeProvider.now().minusSeconds(10)
)
// When: Starting next quest
val action = startQuest(state, nextQuest)
// Then: Quest is started
assertQuestStarted(action, currentState)
}
@Test
fun `fail if location reading is not fresh enough`() {
// Given: Location that is old
val location = LocationReading(
currentQuest.location!!.lat, currentQuest.location!!.lon,
timeProvider.now().minusMinutes(2)
)
// When: Starting the quest
val error = assertThrows<TechnicalError> {
startQuest(currentState, loader.nextQuest(currentState), location)
}
assertThat(error.message, equalTo("Could not get fresh location, try rescanning the QR"))
}
/**
* Quest is meant to be started from the previous quest's endpoint. Otherwise
* you could cheat in the next quest by first failing the quest once
* to get the location and on a second try go close to the quest endpoint
* already before starting the timer.
*
*/
@Test
fun `fail if location is not close enough to current quest's endpoint`() {
// Given: Location that is not close to current quest's end point
val location = LocationReading(
// About 200 meters off
currentQuest.location!!.lat + 0.002, currentQuest.location!!.lon,
timeProvider.now()
)
// When: Starting the quest
val error = assertThrows<TechnicalError> {
startQuest(currentState, loader.nextQuest(currentState), location)
}
// Then: Error about location
assertThat(error.message, equalTo("Coordinates not matching QR location, try rescanning the QR"))
}
@Test
fun `fail if state's scenario is different from param`() {
// And: State with different scenario
val state = State.empty(timeProvider)
.copy(scenario = "not correct")
// When: Starting the quest
val error = assertThrows<TechnicalError> {
engine.startQuest(
state,
scenario.name,
state.currentQuest + 1,
loader.nextQuest(currentState).secret,
freshLocation(loader.nextQuest(currentState))
)
}
assertThat(error.message, equalTo("Not good: Bad cookie scenario"))
}
/**
* If we try to start current quest again, we should just keep on running it without
* changing anything. This could happen by reloading the browser window.
*
*/
@Test
fun `Trying to start quest again keeps it running`() {
// When: Starting this quest again
val action = startQuest(currentState, currentQuest)
// Then: Just continue countdown
assertCountdownContinues(action, currentState)
}
}
}
}
}
@Nested
inner class `Quest without coordinates` {
@Nested
inner class `Running` {
private val scenario = loader.table.scenarios[0]
private val questWithoutCoordinates = scenario.quests[8]
private val currentState = stateForRunningQuest(scenario, questWithoutCoordinates)
@Test
fun `Asserting test preconditions`() {
// Just making sure that the quest actually does not have coordinates
assertThat(questWithoutCoordinates.location, nullValue())
}
@Test
fun `Location reading page, should not include coordinates`() {
// When initiating complete
val outcome = engine.initComplete(scenario.name, questWithoutCoordinates.order, questWithoutCoordinates.secret)
// Location reading should not include quest coordinates
assertThat((outcome as LocationReadingViewModel).lat, nullValue())
}
@Nested
inner class `Should continue countdown (template)` : BaseTestClassForRestartingCurrentQuest(
currentState, { outcome -> assertCountdownContinues(outcome, currentState) }
)
}
}
@Nested
inner class `Quests that share QR codes` {
// Quest 8 is reusing quest 4 QR
private val scenario = loader.table.scenarios[0]
private val laterQuestWithSharedQR = scenario.quests[8]
private val earlierQuestWithSharedQR = scenario.quests[4]
@Nested
inner class `Running the later quest` {
private val currentState = stateForRunningQuest(scenario, laterQuestWithSharedQR)
@Test
fun `Can be completed with the shared QR`() {
// When: Completing the quest, with the shared QR of quest 2. Values come from URL params.
val outcome = scanQR(currentState, scenario, earlierQuestWithSharedQR)
// Then: Quest successfully completed
assertQuestCompleted(outcome, currentState)
}
@Test
fun `Uses the location of the earlier QR quest`() {
// The later quest does not have location set
assertThat(laterQuestWithSharedQR.location, nullValue())
// Earlier quest has location
assertThat(earlierQuestWithSharedQR.location, not(nullValue()))
// Scanning QR will fail if not valid location
assertThrows<TechnicalError> {
scanQR(currentState, scenario, earlierQuestWithSharedQR, locationSomewhere())
}
}
}
@Nested
inner class `Starting the later quest sharing the QR` {
// User has completed previous quest and is about to start the later quest that
// uses the shared QR
private val currentState =
stateForRunningQuest(scenario, previousQuest(scenario, laterQuestWithSharedQR))
.copy(questCompleted = timeProvider.now().minusMinutes(1))
/**
* Small twist, user does not get the coordinates of the later quest to the shared
* location. They must identify it by the description given on the story.
*/
@Test
fun `Countdown page should not show coordinates`() {
val outcome = startNextQuest(currentState)
assertThat(
outcome,
equalTo(
WebAction(
// Then: Show countdown view
CountdownViewModel(
laterQuestWithSharedQR.countdownPage,
timeProvider.now().toEpochSecond(),
laterQuestWithSharedQR.countdown?.let {
timeProvider.now().plusSeconds(it).toEpochSecond()
},
laterQuestWithSharedQR.fictionalCountdown,
null, null
),
// And: State is updated for the quest to start
updatedStateForNewlyStartedQuest(currentState, laterQuestWithSharedQR)
)
)
)
}
}
}
/**
* User does not have a state cookie. They have never started any scenario, have cleared
* the cookies or are using a different browser.
*/
@Nested
inner class `User does not have state cookie` {
val scenario = loader.table.scenarios[0]
/**
* Starting the scenario by scanning the QR code on the Geocaching.com website.
*/
@Test
fun `Starting the scenario`() {
// When: Initiating scenario without a state
val action = engine.initScenario(null, scenario.name)
// Then: State set to scenario start
assertThat(
action.state,
equalTo(
State(
scenario = scenario.name,
currentQuest = 0,
questStarted = timeProvider.now(),
questCompleted = null,
questDeadline = timeProvider.now().plusYears(10),
userId = action.state!!.userId,
scenarioRestartCount = 0,
scenarioStarted = timeProvider.now()
)
)
)
// And: Quest complete called next after location location got
assertThat(
action.modelAndView as LocationReadingViewModel,
equalTo(
LocationReadingViewModel(
"/engine/complete/${scenario.name}/0/${scenario.quests[0].secret}",
null,
null
)
)
)
}
/**
* Scanning QR code (other then first or second) without having any cookies.
* Could happen by accidentally switching browser or clearing cookies.
* Or if you just randomly find the QR code without going through previous
* quests.
*
* MissingCookie page has instructions for the user about the Geocache and how to get
* started.
*
*/
@Test
fun `Scanning a random qr code`() {
// When: Completing third quest without state
val action = engine.complete(
null,
scenario.name,
2,
scenario.quests[2].secret,
freshLocation(scenario.quests[2])
)
// Then: Missing cookie page shown
assertMissingCookieErrorShown(action)
}
@Test
fun `Scanning second quest's QR code`() {
// When: Completing second quest without state
val action = scanQR(null, scenario, scenario.quests[1])
// Then: Missing cookie page shown
assertMissingCookieErrorShown(action)
}
/**
* Calling a start action for any quest. Start action is called when clicking
* the "Go" on the web page to start the next quest. It is hard to come up with
* a scenario where user would call start without any state. Technically possible
* of course by clearing cookies and navigating browser history.
*/
@Test
fun `Starting a quest without a state`() {
// Not possible as controller does not accept request without cookie
}
}
@Nested
inner class `All the hacky stuff`() {
val scenario = loader.table.scenarios[0]
@Test
fun `trying to complete first quest of non existing scenario`() {
// Given: User has state set for completing the intro quest
// When: Completing intro for non existing scenario
assertThrows<TechnicalError> {
engine.complete(
stateForRunningQuest(scenario, scenario.quests[0]),
"other scenario",
0,
scenario.quests[0].secret,
locationSomewhere().asString()
)
}
}
/**
* Use is only allowed to successfully scan the first quest's QR with state for a different
* scenario. For any other quest, we should show the bad scenario error page that will have
* a link to reset the scenario.
*/
@Test
fun `Scanning any on field QR of another scenario restart the scenario of the scanned QR`() {
// Given: User has the wrong scenario
val state = stateForRunningQuest(scenario, scenario.quests[3]).copy(
scenario = "wrong scenario"
)
// When: Trying to scan any QR of another quest
val result = scanQR(state, scenario, scenario.quests[3])
// Then: Restart the scenario
assertScenarioRestartAction(state, scenario, result)
}
@Test
fun `Failure when starting quest of another scenario`() {
// Given: State that has different scenario
val state = stateForRunningQuest(scenario, scenario.quests[2]).copy(
scenario = "this is not correct scenario"
)
// When: Starting quest
// Then: Error on quest
val error = assertThrows<TechnicalError> {
val questToStart = scenario.quests[2]
engine.startQuest(
state,
scenario.name,
2,
questToStart.secret,
freshLocation(questToStart)
)
}
assertThat(error.message, equalTo("Not good: Bad cookie scenario"))
}
@Test
fun `Calling complete URL with malformed location string`() {
// When: Trying to scan QR with malformed location string
// Then: Error given
val error = assertThrows<TechnicalError> {
val currentState = stateForRunningQuest(scenario, scenario.quests[3])
engine.complete(
currentState,
scenario.name,
3,
scenario.quests[3].secret,
"badLocation"
)
}
assertThat(error.message, equalTo("Alas, something went wrong"))
}
@Test
fun `Calling complete URL with bad secret`() {
// When: Trying to complete quest with bad secret
// Then: Error
val error = assertThrows<TechnicalError> {
val currentState = stateForRunningQuest(scenario, scenario.quests[3])
engine.complete(
currentState,
scenario.name,
3,
"bad secret",
freshLocation(scenario.quests[3])
)
}
assertThat(error.message, equalTo("No such quest secret for you my friend"))
}
@Test
fun `Start for the first quest should never be called`() {
val state = stateForRunningQuest(scenario, loader.questFor(scenario.name, 0))
assertThrows<IllegalStateException> {
startQuest(state, scenario.quests[0])
}
}
/**
* Re-scanning the qr code after starting the quest. So the scenario would be:
* 1. User arrives at the quest end location
* 2. User scans the code
* 3. User starts the next quest
* 4. User scans the code again (points to quest complete action)
*
* In this case we should just show the countdown page for the already started quest.
*/
@Test
fun `Trying to complete an already completed quest`() {
// Given: User is currently doing quest 3
val currentQuest = scenario.quests[3]
val previousQuest = scenario.quests[2]
// Given: State is set for running quest 3
val state = stateForRunningQuest(scenario, currentQuest)
// When: Scanning the previous QR code, so basically trying to complete an earlier quest
// Then: No state is returned, only view
val viewModel = scanQR(state, scenario, previousQuest)
// Then: Countdown view shown for the already started quest
assertCountdownContinues(viewModel, state)
}
}
@Nested
inner class `User has state for unknown scenario` {
// Given: State has unknown scenario (only possible if scenarios renamed or removed)
val currentState =
State(
"unknown",
0,
null,
timeProvider.now().minusMinutes(3),
null,
UUID.randomUUID(),
2,
timeProvider.now().minusMinutes(10)
)
@Test
fun `trying to complete first quest of actual scenario`() {
// When: Executing the intro's `complete` action
val scenario = loader.table.scenarios[0]
val action = engine.complete(
currentState,
scenario.name, 0, scenario.quests[0].secret, locationSomewhere().asString()
)
// Then: Scenario restarted
assertScenarioRestartAction(currentState, scenario, action)
}
}
@Nested
inner class `User has state for different scenario` {
val currentScenario = loader.table.scenarios[0]
val currentState = stateForRunningQuest(currentScenario, currentScenario.quests[3])
val anotherScenario = loader.table.scenarios[1]
@Test
fun `Scanning QR of another scenario`() {
// When: Scanning QR of a quest in another scenario
val questOfAnotherScenario = anotherScenario.quests[3]
val outcome = engine.complete(
currentState,
anotherScenario.name,
questOfAnotherScenario.order,
questOfAnotherScenario.secret,
freshLocation(questOfAnotherScenario)
)
// Then: The other scenario is started
assertScenarioRestartAction(currentState, anotherScenario, outcome)
}
@Test
fun `trying to complete first quest of another scenario`() {
// When: Completing first quest of another scenario
val action = engine.complete(
currentState,
anotherScenario.name, 0, anotherScenario.quests[0].secret,
locationSomewhere().asString()
)
// Then: Intro quest is successfully restarted
assertScenarioRestartAction(currentState, anotherScenario, action)
}
@Test
fun `trying to complete another scenario's intro with this scenario's secret`() {
// Given: User has state set for completing the intro quest of current scenario
val state =
stateForRunningQuest(currentScenario, currentScenario.quests[0])
// When: Trying to complete a different scenario with this scenario's secret
val scenarioNameOfAnotherExistingScenario = anotherScenario.name
val result = engine.complete(
state, scenarioNameOfAnotherExistingScenario, 0,
currentScenario.quests[0].secret, locationSomewhere().asString()
)
// Then: Restarting the other scenario scenario
assertScenarioRestartAction(state, anotherScenario, result)
}
}
/**
* Loading (and reloading) the `/engine/init/$scenarioName` action
*/
@Nested
inner class `Scenario initialization` {
@Test
fun `init scenario will reset the existing state for scenario`() {
val scenario = loader.table.scenarios[0]
// Given: State with old dates and later quest order
val existingState = stateForRunningQuest(scenario, scenario.quests[4])
.copy(
questStarted = timeProvider.now().minusDays(39),
questDeadline = timeProvider.now().minusDays(20)
)
// When: scenario is initialized
val (viewModel, newState) = engine.initScenario(
existingState,
scenario.name
)
assertThat(
newState,
equalTo(
existingState.copy(
// Then: State is reset to first quest
currentQuest = 0,
// And: questDeadline is set far in future, to "never" expire
questDeadline = timeProvider.now().plusYears(10),
// And: Restart count is increased by one
scenarioRestartCount = existingState.scenarioRestartCount + 1,
questStarted = timeProvider.now(),
// And: Scenario start is reset
scenarioStarted = timeProvider.now()
)
)
)
}
@Test
fun `init scenario will reset the state of another scenario`() {
val scenario = loader.table.scenarios[0]
// Given: State for another scenario
val existingState = stateForRunningQuest(scenario, scenario.quests[0])
.copy(scenario = "the other scenario")
// When: scenario is initialized
val (url, newState) = engine.initScenario(
existingState,
scenario.name
)
assertThat(
newState,
equalTo(
existingState.copy(
// Then: State is intialized for this scenario
scenario = scenario.name,
// Then: State is reset to first quest
currentQuest = 0,
// And: questDeadline is set far in future, to "never" expire
questDeadline = timeProvider.now().plusYears(10),
// And: Restart count is set to 0
scenarioRestartCount = 0,
questStarted = timeProvider.now(),
scenarioStarted = timeProvider.now()
)
)
)
}
/**
* Scenario will be initialized when user scans the QR code on the Geocaching site.
* The trick is that we will set the proper state and then redirect the user to the
* quest complete url. This will result to the quest success page be shown for the user.
*
* It is good that we already use as much as the flow already on initialization so that
* any technical difficulties will be catched early before heading to the field.
*/
@Test
fun `initializing scenario redirects to quest complete url`() {
val scenario = loader.table.scenarios[0]
// When: scenario is initialized with bad secret
val (viewModel, newState) = engine.initScenario(
State.empty(timeProvider),
scenario.name
)
// Then: Redirected to quest complete
// We want to read the location also although not needed, as this could allow user to
// catch any technical errors on location reading already at home.
assertThat(
(viewModel as LocationReadingViewModel),
equalTo(
LocationReadingViewModel(
"/engine/complete/ancient-blood/0/6a5fc6c0f8ec",
null, null
)
)
)
}
}
@Nested
inner class `Running last quest` {
val scenario = loader.table.scenarios[1]
val questToComplete = scenario.quests.last()
val state = stateForRunningQuest(scenario, questToComplete)
@Test
fun `Scenario success when scanning this QR`() {
// When: Scanning the last QR
val action = scanQR(state, scenario, questToComplete)
// Then: Success page is shown
assertThat(
action,
equalTo(
WebAction(
ScenarioEndViewModel("quests/testing_7_success"),
state.copy(questCompleted = timeProvider.now())
)
)
)
}
@Test
fun `Scenario success if scanning any other QR after last quest completed even if DL passed`() {
// Given: Last quest completed
val newState = state.copy(questCompleted = timeProvider.now())
// And: Deadline for last quest passed
now = timeProvider.now().plusDays(10)
// When: Scanning some QR
val action = scanQR(newState, scenario, loader.previousQuest(newState))
// Then: Success page is shown
assertThat(
action,
equalTo(
WebAction(
ScenarioEndViewModel("quests/testing_7_success"),
newState
)
)
)
}
}
private fun freshLocation(questToStart: Quest) =
if (questToStart.location != null) {
LocationReading(
questToStart.location!!.lat, questToStart.location!!.lon,
timeProvider.now()
).asString()
} else { locationSomewhere().asString() }
fun assertScenarioRestartAction(existingState: State?, action: WebAction) {
return assertScenarioRestartAction(existingState, loader.findScenario(existingState!!.scenario), action)
}
fun assertScenarioRestartAction(existingState: State?, scenario: Scenario, action: WebAction) {
assertThat(
action,
equalTo(
WebAction(
// Then: Go through location reading back to completing the first quest
LocationReadingViewModel(
"/engine/complete/${scenario.name}/0/${scenario.quests[0].secret}",
null,
null
),
// Then: State is reset to the intro quest
State(
scenario = scenario.name,
currentQuest = 0,
questDeadline = timeProvider.now().plusYears(10),
questStarted = timeProvider.now(),
questCompleted = null,
userId = existingState?.userId ?: action.state!!.userId,
scenarioRestartCount =
if (existingState?.scenario == scenario.name) {
existingState.scenarioRestartCount + 1
} else {
0
},
scenarioStarted = timeProvider.now()
)
)
)
)
}
fun assertQuestFailed(
outcome: WebAction,
currentState: State
) {
assertQuestFailed(outcome, currentState, loader.currentQuest(currentState))
}
fun assertQuestFailed(
outcome: WebAction,
currentState: State,
questToComplete: Quest
) {
assertThat(
outcome,
equalTo(
WebAction(
// Then: Show quest failure view
QuestFailedViewModel(questToComplete.failurePage, currentState),
// And: State is not changing
currentState
)
)
)
}
/**
* No change to state, just show the success
*/
fun assertQuestSuccessViewShown(outcome: WebAction, currentState: State) {
// Make sure quest is not already completed
assertThat(currentState.questCompleted, notNullValue())
assertThat(
outcome,
equalTo(
WebAction(
// Then: Show quest success view
QuestEndViewModel(
loader.currentQuest(currentState).successPage,
loader.nextQuest(currentState),
loader.currentQuest(currentState)
),
// And: State not changed
currentState
)
)
)
}
fun assertQuestCompleted(outcome: WebAction, currentState: State) {
// Make sure quest is not already completed
assertThat(currentState.questCompleted, nullValue())
assertThat(
outcome,
equalTo(
WebAction(
// Then: Show quest success view
QuestEndViewModel(
loader.currentQuest(currentState).successPage,
loader.nextQuest(currentState),
loader.currentQuest(currentState)
),
// And: Quest completion marked to state
currentState.copy(questCompleted = timeProvider.now())
)
)
)
}
fun assertQuestStarted(
outcome: WebAction,
currentState: State,
scenarioStartedTime: OffsetDateTime?
) {
assertQuestStarted(outcome, currentState, loader.nextQuest(currentState), scenarioStartedTime)
}
fun assertQuestStarted(outcome: WebAction, currentState: State) {
assertQuestStarted(outcome, currentState, loader.nextQuest(currentState), null)
}
fun assertQuestStarted(outcome: WebAction, currentState: State, questToStart: Quest) {
assertQuestStarted(outcome, currentState, questToStart, null)
}
fun assertQuestStarted(
outcome: WebAction,
currentState: State,
questToStart: Quest,
scenarioStartedTime: OffsetDateTime?
) {
assertThat(
outcome,
equalTo(
WebAction(
// Then: Show countdown view
CountdownViewModel(
questToStart.countdownPage,
timeProvider.now().toEpochSecond(),
questToStart.countdown?.let {
timeProvider.now().plusSeconds(it).toEpochSecond()
},
questToStart.fictionalCountdown,
questToStart.location?.lat, questToStart.location?.lon
),
// And: State is updated for the quest to start
updatedStateForNewlyStartedQuest(currentState, questToStart, scenarioStartedTime)
)
)
)
}
private fun updatedStateForNewlyStartedQuest(
currentState: State,
questToStart: Quest
) =
updatedStateForNewlyStartedQuest(currentState, questToStart, null)
private fun updatedStateForNewlyStartedQuest(
currentState: State,
questToStart: Quest,
scenarioStartedTime: OffsetDateTime?
) = currentState.copy(
scenarioStarted = scenarioStartedTime ?: currentState.scenarioStarted,
currentQuest = questToStart.order,
questStarted = timeProvider.now(),
questDeadline = questToStart.countdown?.let {
timeProvider.now().plusSeconds(it)
},
questCompleted = null
)
private fun assertCountdownContinues(
outcome: WebAction,
currentState: State
) {
val currentQuest = loader.currentQuest(currentState)
assertThat(
outcome,
equalTo(
WebAction(
// Then: Countdown continues
CountdownViewModel(
currentQuest.countdownPage,
currentState.questStarted.toEpochSecond(),
currentState.questDeadline?.let { it.toEpochSecond() },
currentQuest.fictionalCountdown,
currentQuest.location?.lat,
currentQuest.location?.lon
),
// And: State is not changed
currentState
)
)
)
}
private fun assertMissingCookieErrorShown(action: WebAction) {
assertThat(
action,
equalTo(
// And: Missing cookie error shown
WebAction(
OnlyView("missingCookie"),
// And: State not set
null
)
)
)
}
private fun stateForRunningQuest(scenario: Scenario, currentQuest: Quest) = State(
scenario.name,
currentQuest.order,
currentQuest.countdown?.let { timeProvider.now().plusSeconds(it) },
timeProvider.now().minusMinutes(1),
null,
UUID.randomUUID(),
5,
timeProvider.now().minusHours(1)
)
private fun nextQuest(scenario: Scenario, currentQuest: Quest) =
scenario.quests[currentQuest.order + 1]
private fun previousQuest(scenario: Scenario, currentQuest: Quest) =
scenario.quests[currentQuest.order - 1]
// Scanning the QR of the current quest
private fun scanTargetQR(state: State?) =
scanQR(state, loader.findScenario(state!!.scenario), loader.currentQuest(state))
private fun scanTargetQR(state: State?, location: LocationReading) =
scanQR(state, loader.findScenario(state!!.scenario), loader.currentQuest(state), location)
// Calling engine complete is what happens when you scan the QR
private fun scanQR(state: State?, scenario: Scenario, quest: Quest) =
engine.complete(state, scenario.name, quest.order, quest.secret, freshLocation(quest))
private fun scanQR(state: State?, quest: Quest) =
engine.complete(state, state!!.scenario, quest.order, quest.secret, freshLocation(quest))
private fun scanQR(
state: State?,
quest: Quest,
atLocation: LocationReading
) =
engine.complete(state, state!!.scenario, quest.order, quest.secret, atLocation.asString())
private fun scanQR(
state: State?,
scenario: Scenario,
quest: Quest,
atLocation: LocationReading
) =
engine.complete(state, scenario.name, quest.order, quest.secret, atLocation.asString())
private fun startQuest(
state: State,
questToStart: Quest,
location: LocationReading
) =
engine.startQuest(
state,
state.scenario,
questToStart.order,
questToStart.secret,
location.asString()
)
private fun startQuest(state: State, questToStart: Quest): WebAction =
engine.startQuest(
state, state.scenario, questToStart.order, questToStart.secret,
freshLocation(loader.currentQuest(state))
)
private fun restartCurrentQuest(state: State): WebAction =
engine.startQuest(
state, state.scenario, state.currentQuest, loader.currentQuest(state).secret,
freshLocation(loader.currentQuest(state))
)
private fun startNextQuest(state: State): WebAction {
assertThat(state.questCompleted, notNullValue())
return engine.startQuest(
state, state.scenario, state.currentQuest + 1,
loader.nextQuest(state).secret,
freshLocation(loader.currentQuest(state))
)
}
fun locationFor(quest: Quest) =
LocationReading(quest.location!!.lat, quest.location!!.lon, timeProvider.now())
fun locationSomewhere() =
LocationReading(2.0, 3.0, timeProvider.now())
abstract inner class BaseTestClassForStartingAnotherQuest(
val currentState: State,
val verify: (outcome: WebAction) -> Unit
) {
@Test
fun `when starting earlier quest`() {
// When: Starting earlier quest
var action = startQuest(currentState, loader.previousQuest(currentState))
// Then:
verify(action)
}
@Test
fun `when starting earlier quest without proper location`() {
// When: Starting earlier quest
var action = startQuest(currentState, loader.previousQuest(currentState), locationSomewhere())
// Then:
verify(action)
}
@Test
fun `when starting later quest`() {
// When: Starting later quest
var action = startQuest(currentState, loader.questFor(currentState.scenario, currentState.currentQuest + 2))
// Then:
verify(action)
}
@Test
fun `when starting later quest without proper location`() {
// When: Starting later quest
var action = startQuest(currentState, loader.questFor(currentState.scenario, currentState.currentQuest + 2), locationSomewhere())
// Then:
verify(action)
}
@Test
fun `when starting next quest`() {
// When: Starting next quest, without completing current one
var action = startQuest(currentState, loader.nextQuest(currentState))
// Then:
verify(action)
}
@Test
fun `when starting next quest without proper location`() {
// When: Starting next quest, without completing current one
var action = startQuest(currentState, loader.nextQuest(currentState), locationSomewhere())
// Then:
verify(action)
}
}
/**
* Common tests for completing current quest
*/
abstract inner class BaseTestClassForCompletingCurrentQuest(val currentState: State, val verify: (outcome: WebAction) -> Unit) {
@Test
fun `when scanning QR`() {
// When: Completing the quest
val viewModel = scanTargetQR(currentState)
// Then:
verify(viewModel)
}
@Test
fun `or fail if location is not close to quest location`() {
// And: Location not close to target
// When: Completing quest
// Then: Error about not being close to target location
val error = assertThrows<TechnicalError> {
scanTargetQR(currentState, locationSomewhere())
}
assertThat(error.message, equalTo("Coordinates not matching QR location, try rescanning the QR"))
}
@Test
fun `or fail if location is not fresh`() {
// And: Old location reading
val oldLocation = LocationReading(
loader.currentQuest(currentState).location!!.lat,
loader.currentQuest(currentState).location!!.lon,
timeProvider.now().minusDays(200)
)
// When: Scanning the QR
// Then: Error about expired location
val error = assertThrows<TechnicalError> {
scanTargetQR(currentState, oldLocation)
}
assertThat(error.message, equalTo("Could not get fresh location, try rescanning the QR"))
}
}
abstract inner class BaseTestClassForCompletingOutOfOrderQuests(
val currentState: State,
val verify: (outcome: WebAction) -> Unit
) {
@Test
fun `when scanning earlier QR`() {
// When: Scanning QR code of earlier quest
val outcome = scanQR(
currentState,
loader.questFor(currentState.scenario, currentState.currentQuest - 2)
)
// Then:
verify(outcome)
}
// Could easily happen by just going back in browser history
@Test
fun `when scanning earlier QR without proper location`() {
// When: Scanning QR code of earlier quest
val outcome = scanQR(
currentState,
loader.questFor(currentState.scenario, currentState.currentQuest - 2),
locationSomewhere()
)
// Then:
verify(outcome)
}
// Scanning the QR that you just used to complete the previous quest.
// 1. Go to QR and scan it to complete quest
// 2. Start next quest
// 3. Scan again the same QR as in step 1
@Test
fun `when scanning previous QR`() {
// When: Scanning QR code of previous quest
val outcome = scanQR(currentState, loader.previousQuest(currentState))
// Then:
verify(outcome)
}
// Could easily happen by going back in browser history
@Test
fun `when scanning previous QR without proper location`() {
// When: Scanning QR code of previous quest
val outcome = scanQR(currentState, loader.previousQuest(currentState), locationSomewhere())
// Then:
verify(outcome)
}
@Test
fun `when scanning later QR`() {
// When: Scanning QR code of later quest
val outcome = scanQR(currentState, loader.nextQuest(currentState))
// Then:
verify(outcome)
}
@Test
fun `when scanning later QR without proper location`() {
// When: Scanning QR code of later quest
val outcome = scanQR(currentState, loader.nextQuest(currentState), locationSomewhere())
// Then:
verify(outcome)
}
/**
* User cannot end up here by scanning QR code (because the intro quest QR code points to
* init scenario action instead of complete) but can access this e.g. by using browser
* history or such.
*
* TODO: Did we already change so that actually first qr points to complete also? We should.
* then update the above description.
*
* Let's just keep running current quest.
*/
@Test
fun `Restart scenario when scanning first QR`() {
// When: Executing the intro's `complete` action, anywhere
val action =
engine.complete(
currentState,
currentState.scenario,
0,
loader.findScenario(currentState.scenario).quests[0].secret,
locationSomewhere().asString()
)
// Then: Scenario is restarted
assertScenarioRestartAction(currentState, action)
}
/**
* Allows restarting the scenario no matter what.
*/
@Test
fun `Restart scenario when scanning second QR`() {
// When: Scanning second (first on field) quest's QR
val secondQuest = loader.findScenario(currentState.scenario).quests[1]
val result = scanQR(currentState, secondQuest)
// Then: Restart the scenario
assertScenarioRestartAction(currentState, result)
}
}
abstract inner class BaseTestClassForReCompletingCurrentQuest(val currentState: State) {
@Test
fun verifyPreconditions() {
assertThat(currentState.questCompleted, notNullValue())
}
@Test
fun `Recompleting should show quest success page`() {
val outcome = scanTargetQR(currentState)
assertQuestSuccessViewShown(outcome, currentState)
}
}
/**
* Tests for reloading the browser after user has started a quest. After clicking "go" the
* countdown is shown on the url with `/start`. It is not unlikely that the browser window
* could be reloaded while user is on this page.
*/
abstract inner class BaseTestClassForRestartingCurrentQuest(
val currentState: State,
val verify: (outcome: WebAction) -> Unit
) {
/**
* With reloading browser window
*/
@Test
fun `when restarting current quest near start point`() {
// When: Restarting this quest
val action = startQuest(currentState, loader.currentQuest(currentState))
// Then:
verify(action)
}
/**
* User reloads browser window while already proceeded on current quest
* outside the accepted range of the QR. Important for the user not to
* loose the target coordinates.
*/
@Test
fun `when restarting current quest far from start point`() {
// When: Restarting this quest
val action = startQuest(
currentState,
loader.currentQuest(currentState),
locationSomewhere()
)
// Then:
verify(action)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
dea8c292fd4087565eac3fff1e1773fa2eb9e5d5
| 72,379 |
geoleg
|
MIT License
|
android/src/main/java/com/reactjjkit/imageListView/PhotoCell.kt
|
Only-IceSoul
| 253,558,959 | false | null |
package com.reactjjkit.imageListView
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Outline
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.view.View
import android.view.ViewOutlineProvider
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout
import com.reactjjkit.R
import com.reactjjkit.layoutUtils.JJColorDrawable
import com.reactjjkit.layoutUtils.JJLayout
import com.reactjjkit.layoutUtils.JJScreen
@SuppressLint("ViewConstructor")
class PhotoCell(context: Context, colorAccent : Int,
selectableIconSize: Int = JJScreen.dp(11f).toInt() ) : ConstraintLayout(context),SelectableView {
private val mColorAccent = colorAccent
private val mImageView = AppCompatImageView(context)
private val mImageSelectionContainer = ConstraintLayout(context)
private val mImageSelection = AppCompatImageView(context)
private val mBgRing = JJColorDrawable().setShape(1)
.setFillColor(Color.parseColor("#40FFFFFF"))
.setStroke(selectableIconSize*0.1f,Color.WHITE)
private var mPosition = 0
init {
val colorState = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_pressed) ,intArrayOf(-android.R.attr.state_pressed)), intArrayOf(Color.BLACK,Color.BLACK))
val bg = GradientDrawable()
bg.shape = GradientDrawable.RECTANGLE
bg.color = ColorStateList.valueOf(Color.WHITE)
bg.cornerRadii = floatArrayOf(0f,0f,0f,0f,0f,0f,0f,0f)
val rect = RoundRectShape(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f), null, null)
val shape = ShapeDrawable(rect)
background = RippleDrawable(colorState,bg,shape)
clipToOutline = true
outlineProvider = object: ViewOutlineProvider() {
override fun getOutline(view: View?, outline: Outline?) {
outline?.setRoundRect(0,0,view!!.width,view.height,0f)
}
}
mImageSelectionContainer.id = generateId()
mImageSelection.id = generateId()
mImageView.id = generateId()
addView(mImageView)
mImageSelectionContainer.addView(mImageSelection)
addView(mImageSelectionContainer)
mImageView.scaleType = ImageView.ScaleType.CENTER_CROP
mImageSelectionContainer.background = mBgRing
mImageSelection.scaleType = ImageView.ScaleType.FIT_CENTER
val sizeSelectImage = (selectableIconSize*0.48f).toInt()
JJLayout.clSetView(mImageView)
.clFillParent()
.clDisposeView()
.clSetView(mImageSelectionContainer)
.clTopToTopParent(JJScreen.pointW(20))
.clEndToEndParent(JJScreen.pointW(20))
.clHeight(selectableIconSize).clWidth(selectableIconSize)
.clSetView(mImageSelection)
.clHeight(sizeSelectImage)
.clWidth(sizeSelectImage)
.clCenterInParent()
.clDisposeView()
}
private var mGeneratorId = 1
private fun generateId(): Int {
mGeneratorId++
return mGeneratorId
}
fun isIconSelectionVisible(boolean: Boolean) : PhotoCell {
mImageSelectionContainer.visibility = if(boolean) View.VISIBLE else View.GONE
return this
}
fun setImageTransitionName(string: String): PhotoCell {
mImageView.transitionName = string
return this
}
fun setItemPosition(pos:Int): PhotoCell {
mPosition = pos
return this
}
fun getPosition(): Int {
return mPosition
}
fun getImageView(): AppCompatImageView {
return mImageView
}
override fun isSelected(boolean: Boolean) {
if(boolean) {
mImageSelection.setImageResource(R.drawable.ic_done_medium)
mBgRing.setFillColor(mColorAccent)
mBgRing.invalidateSelf()
}
else {
mImageSelection.setImageBitmap(null)
mBgRing.setFillColor(Color.parseColor("#40FFFFFF"))
mBgRing.invalidateSelf()
}
}
}
| 0 |
Swift
|
1
| 14 |
dcfc52ed70de4ba64722ea5981a6904373f7851d
| 4,375 |
react-native-jjkit
|
Apache License 2.0
|
http4k-contract/openapi/src/main/kotlin/org/http4k/util/deprecatedContract.kt
|
http4k
| 86,003,479 | false |
{"Kotlin": 2855594, "Java": 41165, "HTML": 14220, "Shell": 3200, "Handlebars": 1455, "Pug": 944, "JavaScript": 777, "Dockerfile": 256, "CSS": 248}
|
package org.http4k.util
@Deprecated("moved", ReplaceWith("org.http4k.contract.jsonschema.JsonSchema<T>"))
typealias JsonSchema<T> = org.http4k.contract.jsonschema.JsonSchema<T>
@Deprecated("moved", ReplaceWith("org.http4k.contract.jsonschema.JsonSchemaCreator<IN, OUT>"))
typealias JsonSchemaCreator<IN, OUT> = org.http4k.contract.jsonschema.JsonSchemaCreator<IN, OUT>
| 34 |
Kotlin
|
249
| 2,615 |
7ad276aa9c48552a115a59178839477f34d486b1
| 371 |
http4k
|
Apache License 2.0
|
common/common_base/src/main/java/com/cl/common_base/pop/activity/BasePopActivity.kt
|
alizhijun
| 528,318,389 | false | null |
package com.cl.common_base.pop.activity
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.children
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.mtjsoft.barcodescanning.extentions.dp2px
import com.cl.common_base.R
import com.cl.common_base.adapter.HomeKnowMoreAdapter
import com.cl.common_base.base.BaseActivity
import com.cl.common_base.bean.FinishTaskReq
import com.cl.common_base.constants.Constants
import com.cl.common_base.databinding.BasePopActivityBinding
import com.cl.common_base.video.videoUiHelp
import com.cl.common_base.ext.logI
import com.cl.common_base.ext.resourceObserver
import com.cl.common_base.ext.sp2px
import com.cl.common_base.help.PlantCheckHelp
import com.cl.common_base.intercome.InterComeHelp
import com.cl.common_base.util.ViewUtils
import com.cl.common_base.web.WebActivity
import com.cl.common_base.widget.slidetoconfirmlib.ISlideListener
import com.cl.common_base.widget.toast.ToastUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.XPopup.getAnimationDuration
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.lxj.xpopup.widget.SmartDragLayout
import com.shuyu.gsyvideoplayer.GSYVideoManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* 通用弹窗
* 富文本页面
*/
@AndroidEntryPoint
class BasePopActivity : BaseActivity<BasePopActivityBinding>() {
/**
* 是否展示固定按钮、师傅哦展示滑动解锁按钮、滑动解锁按钮文案
*/
private val isShowButton by lazy { intent.getBooleanExtra(KEY_IS_SHOW_BUTTON, false) }
private val showButtonText by lazy { intent.getStringExtra(KEY_IS_SHOW_BUTTON_TEXT) }
private val isShowUnlockButton by lazy { intent.getBooleanExtra(KEY_IS_SHOW_UNLOCK_BUTTON, false) }
private val unLockButtonEngage by lazy { intent.getStringExtra(KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE) }
/**
* 固定按钮的意图、滑动解锁的意图
*/
private val isJumpPage by lazy { intent.getBooleanExtra(KEY_INTENT_JUMP_PAGE, false) }
private val isUnlockTask by lazy { intent.getBooleanExtra(KEY_INTENT_UNLOCK_TASK, false) }
/**
* 用于固定解锁的或者跳转的id
*/
private val fixedId by lazy { intent.getStringExtra(KEY_FIXED_TASK_ID) }
/**
* 解锁ID
*/
private val unLockId by lazy { intent.getStringExtra(KEY_UNLOCK_TASK_ID) }
/**
* 文字颜色
*/
private val titleColor by lazy { intent.getStringExtra(KEY_TITLE_COLOR) }
/**
* veg、auto展示ID
*/
private val categoryCode by lazy { intent.getStringExtra(KEY_CATEGORYCODE) }
override fun initView() {
// 添加状态蓝高度
// ViewCompat.setOnApplyWindowInsetsListener(binding.smart) { v, insets ->
// binding.smart.updateLayoutParams<ViewGroup.MarginLayoutParams> {
// topMargin = insets.systemWindowInsetTop
// }
// return@setOnApplyWindowInsetsListener insets
// }
binding.smart.setDuration(getAnimationDuration())
binding.smart.enableDrag(true)
binding.smart.dismissOnTouchOutside(false)
binding.smart.isThreeDrag(false)
binding.smart.open()
binding.smart.setOnCloseListener(callback)
binding.ivClose.setOnClickListener { directShutdown() }
// 是否展示固定按钮、是否展示滑动解锁
ViewUtils.setVisible(isShowButton, binding.btnNext)
ViewUtils.setVisible(isShowUnlockButton, binding.slideToConfirm)
binding.btnNext.text = showButtonText ?: "Next"
binding.btnNext.setOnClickListener {
fixedProcessingLogic()
}
binding.slideToConfirm.setEngageText(unLockButtonEngage ?: "Slide to Unlock")
binding.slideToConfirm.slideListener = object : ISlideListener {
override fun onSlideStart() {
}
override fun onSlideMove(percent: Float) {
}
override fun onSlideCancel() {
}
override fun onSlideDone() {
binding.slideToConfirm.postDelayed(Runnable { binding.slideToConfirm.reset() }, 500)
// 解锁完毕、调用解锁功能
fixedProcessingLogic()
}
}
}
/**
* 固定跳转逻辑判断
*/
private fun fixedProcessingLogic() {
if (!isHaveCheckBoxViewType()) return
if (isJumpPage) {
fixedId?.let {
// 这是个动态界面,我也不知道为什么不做成动态按钮
when (it) {
Constants.Fixed.KEY_FIXED_ID_PREPARE_THE_SEED -> {
// 如果是准备种子、那么直接跳转到种子界面
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(Constants.Global.KEY_TXT_ID, Constants.Fixed.KEY_FIXED_ID_SEED_GERMINATION_PREVIEW)
intent.putExtra(KEY_FIXED_TASK_ID, Constants.Fixed.KEY_FIXED_ID_SEED_GERMINATION_PREVIEW)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON, true)
intent.putExtra(KEY_INTENT_UNLOCK_TASK, true)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE, "Slide to Unlock")
startActivity(intent)
}
Constants.Fixed.KEY_FIXED_ID_ACTION_NEEDED -> {
// 这是是直接调用接口
mViewModel.intoPlantBasket()
}
// 种植前检查
Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_CLONE_CHECK,
Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_SEED_CHECK -> {
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(Constants.Global.KEY_TXT_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_1)
intent.putExtra(KEY_FIXED_TASK_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_1)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON, true)
intent.putExtra(KEY_INTENT_UNLOCK_TASK, true)
intent.putExtra(KEY_UNLOCK_TASK_ID, unLockId)
intent.putExtra(KEY_CATEGORYCODE, categoryCode)
intent.putExtra(KEY_TITLE_COLOR, "#006241")
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE, "Slide to Next")
startActivity(intent)
}
// 解锁Veg\auto这个周期\或者重新开始
Constants.Fixed.KEY_FIXED_ID_AUTOFLOWERING_STAGE_PREVIEW,
Constants.Fixed.KEY_FIXED_ID_VEGETATIVE_STAGE_PREVIEW -> {
if (unLockId.isNullOrEmpty()) {
// startRunning 接口
mViewModel.startRunning(botanyId = "", goon = false)
} else {
// 解锁接口
mViewModel.finishTask(FinishTaskReq(taskId = unLockId))
mViewModel.tuYaUser?.uid?.let { it1 -> mViewModel.checkPlant(it1) }
}
}
else -> {
// 跳转下一页
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(Constants.Global.KEY_TXT_ID, fixedId)
startActivity(intent)
}
}
return
}
}
if (isUnlockTask) {
fixedId?.let {
when (it) {
// 如果是预览界面、那么直接开始种植、然后关闭界面
Constants.Fixed.KEY_FIXED_ID_SEED_GERMINATION_PREVIEW -> {
mViewModel.startRunning(botanyId = "", goon = false)
}
// 种子换水
Constants.Fixed.KEY_FIXED_ID_WATER_CHANGE_GERMINATION -> {
acFinish()
}
Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_1 -> {
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(KEY_UNLOCK_TASK_ID, unLockId)
intent.putExtra(Constants.Global.KEY_TXT_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_2)
intent.putExtra(KEY_FIXED_TASK_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_2)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON, true)
intent.putExtra(KEY_INTENT_UNLOCK_TASK, true)
intent.putExtra(KEY_TITLE_COLOR, "#006241")
intent.putExtra(KEY_CATEGORYCODE, categoryCode)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE, "Slide to Next")
startActivity(intent)
}
Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_2 -> {
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(KEY_UNLOCK_TASK_ID, unLockId)
intent.putExtra(Constants.Global.KEY_TXT_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_3)
intent.putExtra(KEY_FIXED_TASK_ID, Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_3)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON, true)
intent.putExtra(KEY_INTENT_UNLOCK_TASK, true)
intent.putExtra(KEY_TITLE_COLOR, "#006241")
intent.putExtra(KEY_CATEGORYCODE, categoryCode)
intent.putExtra(KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE, "Slide to Unlock")
startActivity(intent)
}
Constants.Fixed.KEY_FIXED_ID_TRANSPLANT_3 -> {
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(KEY_UNLOCK_TASK_ID, unLockId)
intent.putExtra(Constants.Global.KEY_TXT_ID, if (categoryCode == "100002" || categoryCode == "100004") Constants.Fixed.KEY_FIXED_ID_AUTOFLOWERING_STAGE_PREVIEW else Constants.Fixed.KEY_FIXED_ID_VEGETATIVE_STAGE_PREVIEW)
intent.putExtra(KEY_FIXED_TASK_ID, if (categoryCode == "100002" || categoryCode == "100004") Constants.Fixed.KEY_FIXED_ID_AUTOFLOWERING_STAGE_PREVIEW else Constants.Fixed.KEY_FIXED_ID_VEGETATIVE_STAGE_PREVIEW)
intent.putExtra(KEY_IS_SHOW_BUTTON, true)
intent.putExtra(KEY_INTENT_JUMP_PAGE, true)
intent.putExtra(KEY_TITLE_COLOR, "#006241")
intent.putExtra(KEY_IS_SHOW_BUTTON_TEXT, if (categoryCode == "100002" || categoryCode == "100004") "Unlock Autoflowering" else "Unlock Veg")
startActivity(intent)
}
else -> {
mViewModel.finishTask(FinishTaskReq(taskId = it))
}
}
return
}
}
if (!isJumpPage && !isUnlockTask) {
// 如果都不是、那么直接关闭界面
acFinish()
}
}
private fun isHaveCheckBoxViewType(): Boolean {
/*logI("123123:::: ${adapter.data.filter { data -> data.value?.isCheck == false }.size}")*/
val size = adapter.data.filter { data -> data.value?.isCheck == false && data.type == "option" }.size
size.let { checkCount ->
if (checkCount != 0) {
ToastUtil.shortShow("Please select all item")
}
return checkCount == 0
}
}
private val callback by lazy {
object : SmartDragLayout.OnCloseListener {
override fun onClose() {
directShutdown()
}
override fun onDrag(y: Int, percent: Float, isScrollUp: Boolean) {
// binding.smart.alpha = percent
}
override fun onOpen() {
}
}
}
/**
* 初始化Video
*/
private fun initVideo(url: String, autoPlay: Boolean) {
binding.videoItemPlayer.apply {
videoUiHelp(url, -1)
if (autoPlay) startPlayLogic()
}
}
override fun observe() {
mViewModel.apply {
// 插入篮子植物接口
intoPlantBasket.observe(this@BasePopActivity, resourceObserver {
loading { showProgressLoading() }
error { errorMsg, code ->
hideProgressLoading()
ToastUtil.shortShow(errorMsg)
}
success {
hideProgressLoading()
acFinish()
}
})
richText.observe(this@BasePopActivity, resourceObserver {
error { errorMsg, _ ->
ToastUtil.shortShow(errorMsg)
hideProgressLoading()
}
success {
hideProgressLoading()
if (null == data) return@success
// 初始化头部Video
data.topPage?.firstOrNull { it.type == "video" }?.apply {
// 显示头部视频
binding.videoItemPlayer.visibility = View.VISIBLE
value?.url?.let { initVideo(it, value.autoplay == true) }
}
// 标题
data.bar?.let {
binding.tvTitle.text = it
binding.tvTitle.setTextColor(Color.parseColor(titleColor ?: "#000000"))
}
// 动态添加按钮
// 不是video的都需要添加
val list = data.topPage?.filter { it.type != "video" }
list?.forEachIndexed { _, topPage ->
val tv = TextView(this@BasePopActivity)
tv.setBackgroundResource(R.drawable.create_state_button)
tv.isEnabled = true
tv.text = topPage.value?.txt
val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(60))
lp.setMargins(dp2px(20), dp2px(5), dp2px(20), dp2px(5))
tv.layoutParams = lp
tv.gravity = Gravity.CENTER
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, sp2px(18f).toFloat())
tv.setTextColor(Color.WHITE)
binding.flRoot.addView(tv)
}
binding.flRoot.children.forEach {
val tv = (it as? TextView)
tv?.setOnClickListener {
list?.firstOrNull { data -> data.value?.txt == tv.text.toString() }?.apply {
when (type) {
"pageClose" -> [email protected]()
"pageDown" -> {
if (!isHaveCheckBoxViewType()) return@setOnClickListener
// 跳转下一页
val intent = Intent(this@BasePopActivity, BasePopActivity::class.java)
intent.putExtra(Constants.Global.KEY_TXT_ID, value?.txtId)
startActivity(intent)
}
"finishTask" -> {
if (!isHaveCheckBoxViewType()) return@setOnClickListener
// 完成任务
mViewModel.finishTask(FinishTaskReq(taskId = taskId))
}
}
}
}
}
// 适配器设置数据
adapter.setList(data.page)
}
})
// 完成任务
finishTask.observe(this@BasePopActivity, resourceObserver {
error { errorMsg, _ ->
hideProgressLoading()
ToastUtil.shortShow(errorMsg)
}
success {
hideProgressLoading()
// finishTask 需要直接关闭页面
mViewModel.richText.value?.data?.topPage?.firstOrNull { it.type == "finishTask" }?.apply {
acFinish()
}
}
})
// 植物检查
checkPlant.observe(this@BasePopActivity, resourceObserver {
error { errorMsg, _ ->
hideProgressLoading()
ToastUtil.shortShow(errorMsg)
}
success {
hideProgressLoading()
data?.let { PlantCheckHelp().plantStatusCheck(this@BasePopActivity, it, true) }
}
})
}
}
override fun initData() {
mViewModel.getRichText(txtId = txtId, type = txtType)
binding.rvList.layoutManager = linearLayoutManager
binding.rvList.adapter = adapter
scrollListener()
adapterClickEvent()
}
private fun scrollListener() {
binding.rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition()
val lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
//大于0说明有播放
if (GSYVideoManager.instance().playPosition >= 0) {
//当前播放的位置
val position = GSYVideoManager.instance().playPosition
//对应的播放列表TAG
if (GSYVideoManager.instance().playTag == "$position" && (position < firstVisibleItem || position > lastVisibleItem)) {
//如果滑出去了上面和下面就是否,和今日头条一样
//是否全屏
if (!GSYVideoManager.isFullState(this@BasePopActivity)) {
adapter.data[position].videoPosition = GSYVideoManager.instance().currentPosition
// 不释放全部
// GSYVideoManager.instance().setListener(this@KnowMoreActivity)
// GSYVideoManager.onPause()
// 释放全部
GSYVideoManager.releaseAllVideos()
adapter.notifyItemChanged(position)
}
}
}
super.onScrolled(recyclerView, dx, dy)
}
})
}
private fun adapterClickEvent() {
adapter.apply {
addChildClickViewIds(R.id.iv_pic, R.id.tv_html, R.id.tv_learn, R.id.cl_go_url, R.id.cl_support, R.id.cl_discord, R.id.cl_learn, R.id.cl_check, R.id.tv_page_txt, R.id.tv_txt)
setOnItemChildClickListener { _, view, position ->
val bean = data[position]
when (view.id) {
R.id.iv_pic -> {
// 弹出图片
XPopup.Builder(context)
.asImageViewer(
(view as? ImageView),
bean.value?.url,
SmartGlideImageLoader()
)
.show()
}
// 跳转HTML
R.id.cl_go_url,
R.id.tv_html -> {
val intent = Intent(context, WebActivity::class.java)
intent.putExtra(WebActivity.KEY_WEB_URL, bean.value?.url)
intent.putExtra(WebActivity.KEY_WEB_TITLE_NAME, bean.value?.title)
context.startActivity(intent)
}
// 阅读更多
R.id.cl_learn,
R.id.tv_learn -> {
// todo 请求id
bean.value?.txtId?.let {
// 继续请求弹窗
val intent = Intent(context, BasePopActivity::class.java)
intent.putExtra(Constants.Global.KEY_TXT_ID, it)
context.startActivity(intent)
}
}
// 跳转到客服
R.id.cl_support -> {
InterComeHelp.INSTANCE.openInterComeHome()
}
// 跳转到Discord
R.id.cl_discord -> {
val intent = Intent(context, WebActivity::class.java)
if (bean.value?.url.isNullOrEmpty()) {
intent.putExtra(WebActivity.KEY_WEB_URL, "https://discord.gg/FCj6UGCNtU")
} else {
intent.putExtra(WebActivity.KEY_WEB_URL, bean.value?.url)
}
intent.putExtra(WebActivity.KEY_WEB_TITLE_NAME, "hey abby")
context.startActivity(intent)
}
// 勾选框
R.id.cl_check -> {
view.findViewById<CheckBox>(R.id.curing_box)?.apply {
logI("before: ${data[position].value?.isCheck}")
data[position].value?.isCheck = !isChecked
isChecked = !isChecked
logI("after: ${data[position].value?.isCheck}")
}
}
// 跳转到HTML
R.id.tv_page_txt -> {
if (bean.value?.url.isNullOrEmpty()) return@setOnItemChildClickListener
// 跳转到HTML
val intent = Intent(context, WebActivity::class.java)
intent.putExtra(WebActivity.KEY_WEB_URL, bean.value?.url)
context.startActivity(intent)
}
R.id.tv_txt -> {
if (bean.value?.url.isNullOrEmpty()) return@setOnItemChildClickListener
// 跳转到HTML
val intent = Intent(context, WebActivity::class.java)
intent.putExtra(WebActivity.KEY_WEB_URL, bean.value?.url)
context.startActivity(intent)
}
}
}
}
}
override fun BasePopActivityBinding.initBinding() {
binding.apply {
lifecycleOwner = this@BasePopActivity
viewModel = mViewModel
executePendingBindings()
}
}
// 富文本适配器
private val adapter by lazy {
HomeKnowMoreAdapter(mutableListOf())
}
private val linearLayoutManager by lazy {
LinearLayoutManager(this@BasePopActivity)
}
private val txtId by lazy {
intent.getStringExtra(Constants.Global.KEY_TXT_ID)
}
private val txtType by lazy {
intent.getStringExtra(Constants.Global.KEY_TXT_TYPE)
}
private val taskId by lazy {
intent.getStringExtra(Constants.Global.KEY_TASK_ID)
}
@Inject
lateinit var mViewModel: BaseViewModel
// 系统返回键
override fun onBackPressed() {
if (GSYVideoManager.backFromWindowFull(this)) {
return
}
directShutdown()
}
// 关闭页面的回调
private fun acFinish() {
setResult(Activity.RESULT_OK)
finish()
}
// 直接关闭
private fun directShutdown() {
finish()
}
override fun onResume() {
super.onResume()
GSYVideoManager.onResume()
}
override fun onPause() {
super.onPause()
GSYVideoManager.onPause()
}
override fun onDestroy() {
super.onDestroy()
GSYVideoManager.releaseAllVideos()
}
companion object {
const val KEY_IS_SHOW_BUTTON = "key_is_show_button"
const val KEY_IS_SHOW_UNLOCK_BUTTON = "key_is_show_unlock_button"
const val KEY_IS_SHOW_UNLOCK_BUTTON_ENGAGE = "key_is_show_unlock_button_engage"
const val KEY_IS_SHOW_BUTTON_TEXT = "key_is_show_button_text"
// 意图
const val KEY_INTENT_JUMP_PAGE = "key_intent_jump_page"
const val KEY_INTENT_UNLOCK_TASK = "key_intent_unlock_task"
// 用于固定的跳转
const val KEY_FIXED_TASK_ID = "key_fixed_task_id"
// 解锁ID
const val KEY_UNLOCK_TASK_ID = "key_unlock_id"
// Title颜色
const val KEY_TITLE_COLOR = "key_title_color"
// 调用哪个解锁Veg\auto的ID
const val KEY_CATEGORYCODE = "key_categorycode"
// 设备ID
const val KEY_DEVICE_ID = "key_device_id"
// 配件ID
const val KEY_PART_ID = "key_part_id"
// 自动化Id
const val KEY_AUTOMATION_ID = "key_auto_id"
}
}
| 0 |
Kotlin
|
0
| 0 |
572784e6c6910a7f5254b316b0ac0c74349443aa
| 25,300 |
abby
|
Apache License 2.0
|
src/main/kotlin/org/move/lang/core/types/infer/TypeFlags.kt
|
pontem-network
| 279,299,159 | false |
{"Kotlin": 2117384, "Move": 38257, "Lex": 5509, "HTML": 2114, "Java": 1275}
|
package org.move.lang.core.types.infer
import org.move.lang.core.types.ty.Ty
typealias TypeFlags = Int
const val HAS_TY_INFER_MASK: TypeFlags = 1
const val HAS_TY_TYPE_PARAMETER_MASK: TypeFlags = 2
const val HAS_TY_STRUCT_MASK: TypeFlags = 4
const val HAS_TY_UNKNOWN_MASK: TypeFlags = 8
fun mergeFlags(tys: Collection<Ty>): TypeFlags =
tys.fold(0) { a, b -> a or b.flags }
data class HasTypeFlagVisitor(val mask: TypeFlags) : TypeVisitor {
override fun invoke(ty: Ty): Boolean = ty.flags.and(mask) != 0
companion object {
val HAS_TY_INFER_VISITOR = HasTypeFlagVisitor(HAS_TY_INFER_MASK)
val HAS_TY_TYPE_PARAMETER_VISITOR = HasTypeFlagVisitor(HAS_TY_TYPE_PARAMETER_MASK)
val HAS_TY_STRUCT_VISITOR = HasTypeFlagVisitor(HAS_TY_STRUCT_MASK)
val HAS_TY_UNKNOWN_VISITOR = HasTypeFlagVisitor(HAS_TY_UNKNOWN_MASK)
val NEEDS_INFER = HasTypeFlagVisitor(HAS_TY_INFER_MASK)
val NEEDS_SUBST = HasTypeFlagVisitor(HAS_TY_TYPE_PARAMETER_MASK)
}
}
| 3 |
Kotlin
|
29
| 69 |
c0192da133a0d0b0cb22456f55d3ee8c7a973109
| 1,003 |
intellij-move
|
MIT License
|
composeApp/src/commonMain/kotlin/com/github/claaj/konci/data/process/ConciliarFiles.kt
|
claaj
| 686,362,324 | false |
{"Kotlin": 72172}
|
package com.github.claaj.konci.data.process
import com.github.claaj.konci.data.format.dfAfip
import com.github.claaj.konci.data.format.dfSuss
import com.github.claaj.konci.data.format.dfConvenioMultiPercepciones
import com.github.claaj.konci.data.format.dfConvenioMultiRetenciones
import com.github.claaj.konci.data.format.dfTangoIIBBPercepciones
import com.github.claaj.konci.data.format.dfTangoIIBBRetenciones
import com.github.claaj.konci.data.format.dfTangoPercepciones
import com.github.claaj.konci.data.format.dfTangoRetenciones
import com.github.claaj.konci.enums.Impuestos
import com.github.claaj.konci.enums.Regimen
import org.jetbrains.kotlinx.dataframe.DataFrame
import org.jetbrains.kotlinx.dataframe.api.concat
import org.jetbrains.kotlinx.dataframe.api.count
import org.jetbrains.kotlinx.dataframe.api.dataFrameOf
import org.jetbrains.kotlinx.dataframe.api.head
import java.nio.file.Path
import kotlin.math.absoluteValue
fun conciliarFiles(
pathsExternal: List<Path>,
pathsLocal: List<Path>,
regimen: Regimen,
impuesto: Impuestos
): DataFrame<*> {
val (formatExternal, formatLocal) = getFormatFunctions(regimen, impuesto)
val dfExternal = formatExternal(pathsExternal)
val dfLocal = formatLocal(pathsLocal)
val columns = getDataFrameColumns(impuesto)
var dfFilter = dataFrameOf(columns, listOf())
val uniqueCuits = uniqueCuits(dfExternal, dfLocal)
for (cuit in uniqueCuits) {
if (!checkImportesSum(dfExternal, dfLocal, cuit)) {
for (importe in uniqueImportesByCuit(dfExternal, dfLocal, cuit)) {
val afipFilter = filterByCuitImporte(dfExternal, cuit, importe)
val tangoFilter = filterByCuitImporte(dfLocal, cuit, importe)
val countDiff = afipFilter.count() - tangoFilter.count()
if (countDiff > 0) {
dfFilter = dfFilter.concat(afipFilter.head(countDiff.absoluteValue))
}
if (countDiff < 0) {
dfFilter = dfFilter.concat(tangoFilter.head(countDiff.absoluteValue))
}
}
}
}
return dfFilter
}
private fun getDataFrameColumns(impuesto: Impuestos): List<String> {
return when (impuesto) {
Impuestos.IIBB -> listOf("CUIT", "N_COMP", "FECHA", "IMPORTE", "PROVINCIA", "ORIGEN")
else -> listOf("CUIT", "RAZON_SOC", "N_COMP", "FECHA", "IMPORTE", "ORIGEN")
}
}
private fun getFormatFunctions(
regimen: Regimen,
impuesto: Impuestos
): Pair<(List<Path>) -> DataFrame<*>, (List<Path>) -> DataFrame<*>> {
return when(regimen) {
Regimen.Percepciones -> {
when(impuesto) {
Impuestos.Ganancias -> Pair(::dfAfip, ::dfTangoPercepciones)
Impuestos.IIBB -> Pair(::dfConvenioMultiPercepciones, ::dfTangoIIBBPercepciones)
Impuestos.IVA -> Pair(::dfAfip, ::dfTangoPercepciones)
Impuestos.SUSS -> Pair(::dfSuss, ::dfTangoPercepciones)
}
}
Regimen.Retenciones -> {
when(impuesto) {
Impuestos.Ganancias -> Pair(::dfAfip, ::dfTangoRetenciones)
Impuestos.IIBB -> Pair(::dfConvenioMultiRetenciones, ::dfTangoIIBBRetenciones)
Impuestos.IVA -> Pair(::dfAfip, ::dfTangoRetenciones)
Impuestos.SUSS -> Pair(::dfSuss, ::dfTangoRetenciones)
}
}
Regimen.Ambos -> throw UnsupportedOperationException()
}
}
| 0 |
Kotlin
|
0
| 0 |
63129ed4f72b24f37ff783450b960e36af7b32be
| 3,486 |
konci
|
MIT License
|
app/src/main/java/com/example/android/navigation/TitleFragment.kt
|
DarlynCR
| 500,573,176 | false |
{"Kotlin": 21521}
|
package com.example.android.navigation
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.NavigationUI
import com.example.android.navigation.databinding.FragmentTitleBinding
class TitleFragment : Fragment(R.layout.fragment_title) {
private lateinit var binding : FragmentTitleBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Para agregar un menú a solo un fragmento
//Este método Indica que el fragmento tiene elementos de menu para contribuir
setHasOptionsMenu(true)
binding = FragmentTitleBinding.bind(view)
Log.i("TitleFragment", "onViewCreated called")
binding.playButton.setOnClickListener {
val action = TitleFragmentDirections.actionTitleFragmentToGameFragment()
findNavController().navigate(action)
}
binding.btnRules.setOnClickListener {
val action = TitleFragmentDirections.actionTitleFragmentToRulesFragment()
findNavController().navigate(action)
}
binding.btnAbout.setOnClickListener {
val action = TitleFragmentDirections.actionTitleFragmentToAboutFragment()
findNavController().navigate(action)
}
}
//Llamadas a los métodos del ciclo de vida del fragment
override fun onAttach(context: Context) {
super.onAttach(context)
Log.i("TitleFragment", "onAttach called")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i("TitleFragment", "onCreate called")
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.i("TitleFragment", "onCreateView called")
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onStart() {
super.onStart()
Log.i("TitleFragment", "onStart called")
}
override fun onResume() {
super.onResume()
Log.i("TitleFragment", "onResume called")
}
override fun onPause() {
super.onPause()
Log.i("TitleFragment", "onPause called")
}
override fun onStop() {
super.onStop()
Log.i("TitleFragment", "onStop called")
}
override fun onDestroyView() {
super.onDestroyView()
Log.i("TitleFragment", "onDestroyView called")
}
override fun onDetach() {
super.onDetach()
Log.i("TitleFragment", "onDetach called")
}
//Para llamar a este método primero se debe llamar el método setHasOptionsMenu(true)
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
//menu: menu de opciones en el que coloca sus artículos.
//Se agrega el menú de opciones e infla el archivo de recursos del menú.
inflater.inflate(R.menu.title_menu, menu)
}
//Se le da funcionalidad al menú inflado para el fragment
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return NavigationUI.
onNavDestinationSelected(item,requireView().findNavController())
|| super.onOptionsItemSelected(item)
}
}
| 0 |
Kotlin
|
0
| 0 |
baebd31a0ec9b3edcb7109227af267b737599f34
| 3,512 |
AndroidTrivia-Starter
|
Apache License 2.0
|
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/OnMultiControlModeChangeListener.kt
|
didi
| 144,705,602 | false |
{"Markdown": 26, "Ruby": 5, "Text": 5, "Ignore List": 26, "XML": 404, "OpenStep Property List": 14, "Objective-C": 804, "JSON": 140, "Objective-C++": 1, "C": 8, "Swift": 25, "HTML": 10, "JavaScript": 102, "Vue": 53, "CSS": 2, "Less": 2, "Shell": 19, "Gradle": 27, "Java Properties": 6, "Batchfile": 2, "EditorConfig": 1, "INI": 19, "Proguard": 15, "Java": 732, "Kotlin": 517, "AIDL": 2, "C++": 3, "CMake": 1, "YAML": 3, "Dart": 42, "JSON with Comments": 1}
|
package com.didichuxing.doraemonkit.kit.mc
import com.didichuxing.doraemonkit.kit.test.TestMode
/**
* didi Create on 2022/4/14 .
*
* Copyright (c) 2022/4/14 by didiglobal.com.
*
* @author <a href="<EMAIL>">zhangjun</a>
* @version 1.0
* @Date 2022/4/14 10:52 上午
* @Description 用一句话说明文件功能
*/
interface OnMultiControlModeChangeListener {
fun onMultiControlModeChanged(testMode: TestMode)
}
| 252 |
Java
|
3074
| 20,003 |
166a1a92c6fd509f6b0ae3e8dd9993f631b05709
| 405 |
DoKit
|
Apache License 2.0
|
app/src/main/java/ds/meterscanner/mvvm/view/ChartsActivity.kt
|
mykola-dev
| 80,344,682 | false | null |
package ds.meterscanner.mvvm.view
import android.app.Activity
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import ds.bindingtools.withBindable
import ds.meterscanner.R
import ds.meterscanner.mvvm.BindableActivity
import ds.meterscanner.mvvm.ChartsView
import ds.meterscanner.mvvm.viewmodel.ChartsViewModel
import ds.meterscanner.mvvm.viewmodel.Period
import ds.meterscanner.util.FileTools
import kotlinx.android.synthetic.main.activity_charts.*
import kotlinx.android.synthetic.main.toolbar.*
import lecho.lib.hellocharts.gesture.ZoomType
import lecho.lib.hellocharts.model.ColumnChartData
import lecho.lib.hellocharts.model.Viewport
import lecho.lib.hellocharts.util.ChartUtils
class ChartsActivity : BindableActivity<ChartsViewModel>(), ChartsView {
override fun provideViewModel(): ChartsViewModel = defaultViewModelOf()
override fun getLayoutId(): Int = R.layout.activity_charts
override fun bindView() {
super.bindView()
toolbar.title = getString(R.string.charts)
columnsChart.isScrollEnabled = false
columnsChart.isZoomEnabled = false
linesChart.isScrollEnabled = false
linesChart.isZoomEnabled = false
previewChart.setViewportChangeListener(ViewportListener(columnsChart, linesChart))
radioGroup.setOnCheckedChangeListener { _, checkedId -> viewModel.onCheckedChanged(checkedId) }
withBindable(viewModel) {
bind(::linesData, {
linesChart.lineChartData = it
val v = Viewport(linesChart.maximumViewport.left, 30f, linesChart.maximumViewport.right, -30f)
linesChart.maximumViewport = v
})
bind(::columnsData, columnsChart::setColumnChartData)
bind(::columnsData, {
val previewData = ColumnChartData(it)
previewData
.columns
.flatMap { it.values }
.forEach { it.color = ChartUtils.DEFAULT_DARKEN_COLOR }
previewData.axisYLeft = null
previewData.axisXBottom = null
previewChart.columnChartData = previewData
val tempViewport = Viewport(columnsChart.maximumViewport)
val visibleItems = 20
tempViewport.left = tempViewport.right - visibleItems
previewChart.currentViewport = tempViewport
previewChart.zoomType = ZoomType.HORIZONTAL
})
bind(this::checkedButtonId, radioGroup::check, radioGroup::getCheckedRadioButtonId)
bind(::showProgress, { radioGroup.isEnabled = !it })
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.charts, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(when (viewModel.period) {
Period.ALL -> R.id.action_period_all
Period.YEAR -> R.id.action_period_year
Period.LAST_SEASON -> R.id.action_period_season
}).isChecked = true
menu.findItem(R.id.action_correction).isChecked = viewModel.positiveCorrection
menu.findItem(R.id.action_show_temp).isChecked = viewModel.tempVisible
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.isCheckable)
item.isChecked = !item.isChecked
when (item.itemId) {
R.id.action_correction -> viewModel.toggleCorection(item.isChecked)
R.id.action_show_temp -> viewModel.toggleTemperature(item.isChecked)
R.id.action_period_all -> viewModel.period = Period.ALL
R.id.action_period_year -> viewModel.period = Period.YEAR
R.id.action_period_season -> viewModel.period = Period.LAST_SEASON
R.id.action_export_csv -> FileTools.chooseDir(this, FileTools.CSV_FILE_NAME)
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Requests.SAVE_FILE && resultCode == Activity.RESULT_OK) {
viewModel.onDirectoryChoosen(contentResolver, data!!.data)
}
}
}
| 1 |
Kotlin
|
6
| 31 |
7e2a6e15721a7d52a98ca753a462645d6cee41ff
| 4,380 |
energy-meter-scanner
|
MIT License
|
librettist-core/src/commonMain/kotlin/dev/bnorm/librettist/show/SlideSection.kt
|
bnorm
| 767,108,847 | false |
{"Kotlin": 1443893}
|
package dev.bnorm.librettist.show
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.compositionLocalOf
@Immutable
class SlideSection(
val title: @Composable () -> Unit,
) {
companion object {
val Empty = SlideSection {}
val header: @Composable () -> Unit
@Composable
get() = LocalSlideSection.current.title
}
}
private val LocalSlideSection = compositionLocalOf { SlideSection.Empty }
@ShowBuilderDsl
fun ShowBuilder.section(
title: String,
block: ShowBuilder.() -> Unit,
) {
section(
title = { Text(title) },
block = block,
)
}
@ShowBuilderDsl
fun ShowBuilder.section(
title: @Composable () -> Unit,
block: ShowBuilder.() -> Unit,
) {
val upstream = this
val section = SlideSection(title)
object : ShowBuilder {
override fun slide(
states: Int,
enterTransition: (AdvanceDirection) -> EnterTransition,
exitTransition: (AdvanceDirection) -> ExitTransition,
content: SlideContent<SlideState<Int>>,
) {
upstream.slide(states, enterTransition, exitTransition) {
CompositionLocalProvider(LocalSlideSection provides section) {
content()
}
}
}
}.block()
}
| 0 |
Kotlin
|
0
| 6 |
e2bafa505d2fd2ed54e3bb5f6ab6dd7927374ee4
| 1,573 |
librettist
|
Apache License 2.0
|
src/main/kotlin/com/piashcse/route/UserRoute.kt
|
BaoLam2610
| 767,528,883 | false |
{"Kotlin": 136200, "FreeMarker": 59, "Procfile": 55}
|
package com.piashcse.route
import com.papsign.ktor.openapigen.route.path.auth.principal
import com.papsign.ktor.openapigen.route.path.auth.put
import com.papsign.ktor.openapigen.route.path.normal.NormalOpenAPIRoute
import com.papsign.ktor.openapigen.route.path.normal.get
import com.papsign.ktor.openapigen.route.path.normal.post
import com.papsign.ktor.openapigen.route.response.respond
import com.papsign.ktor.openapigen.route.route
import com.piashcse.controller.UserController
import com.piashcse.entities.user.ChangePassword
import com.piashcse.entities.user.UsersEntity
import com.piashcse.models.user.body.*
import com.piashcse.plugins.RoleManagement
import com.piashcse.utils.*
import io.ktor.http.*
import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.SimpleEmail
fun NormalOpenAPIRoute.userRoute(userController: UserController) {
route("login").post<Unit, Response, LoginBody> { _, requestBody ->
requestBody.validation()
respond(ApiResponse.success(userController.login(requestBody), HttpStatusCode.OK))
}
route("register").post<Unit, Response, RegistrationBody> { _, requestBody ->
requestBody.validation()
respond(
ApiResponse.success(
userController.registration(requestBody),
HttpStatusCode.OK,
message = "Đăng ký thành công"
)
)
}
route("forget-password").get<ForgetPasswordEmail, Response> { params ->
params.validation()
userController.forgetPassword(params)?.let {
SimpleEmail().apply {
hostName = AppConstants.SmtpServer.HOST_NAME
setSmtpPort(AppConstants.SmtpServer.PORT)
setAuthenticator(
DefaultAuthenticator(
AppConstants.SmtpServer.DEFAULT_AUTHENTICATOR,
AppConstants.SmtpServer.DEFAULT_AUTHENTICATOR_PASSWORD
)
)
isSSLOnConnect = true
setFrom("<EMAIL>")
subject = AppConstants.SmtpServer.EMAIL_SUBJECT
setMsg("Your verification code is : ${it.verificationCode}")
addTo(params.email)
send()
}
respond(
ApiResponse.success(
"${AppConstants.SuccessMessage.VerificationCode.VERIFICATION_CODE_SENT_TO} ${params.email}",
HttpStatusCode.OK
)
)
}
}
route("verify-change-password").get<ConfirmPassword, Response> { params ->
params.validation()
UserController().changeForgetPasswordByVerificationCode(params).let {
when (it) {
AppConstants.DataBaseTransaction.FOUND -> {
respond(
ApiResponse.success(
AppConstants.SuccessMessage.Password.PASSWORD_CHANGE_SUCCESS, HttpStatusCode.OK
)
)
}
AppConstants.DataBaseTransaction.NOT_FOUND -> {
respond(
ApiResponse.success(
AppConstants.SuccessMessage.VerificationCode.VERIFICATION_CODE_IS_NOT_VALID,
HttpStatusCode.OK
)
)
}
}
}
}
authenticateWithJwt(RoleManagement.ADMIN.role, RoleManagement.SELLER.role, RoleManagement.USER.role) {
route("change-password").put<ChangePassword, Response, Unit, JwtTokenBody> { params, _ ->
userController.changePassword(principal().userId, params)?.let {
if (it is UsersEntity) respond(
ApiResponse.success(
"Password has been changed", HttpStatusCode.OK
)
)
if (it is ChangePassword) respond(
ApiResponse.failure(
"Old password is wrong", HttpStatusCode.OK
)
)
} ?: run {
throw UserNotExistException()
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ba8dd5fc05c813b04fe286c5e815991f58854f32
| 4,213 |
Ktor-EcommerceServer
|
Apache License 2.0
|
src/dev/lunarcoffee/blazelight/shared/TimeZoneManager.kt
|
lunarcoffee
| 214,299,039 | false |
{"Kotlin": 166835, "CSS": 18966, "JavaScript": 1102}
|
package dev.lunarcoffee.blazelight.shared
import java.time.ZoneId
object TimeZoneManager {
private val excludedIdPrefixes = setOf("Etc/", "SystemV/", "Universal")
// All UTC offset distinct [ZoneId]s.
val timeZones = ZoneId
.getAvailableZoneIds()
.filter { id ->
val notExcluded = excludedIdPrefixes.none { id.startsWith(it) }
val likelyNotObscure = !id.all { it.isUpperCase() || it.isDigit() || it == '-' }
notExcluded && likelyNotObscure
}
.map { ZoneId.of(it) }
.sortedBy { it.id }
fun toTimeZone(str: String) = timeZones[str.toInt()]!!
}
| 0 |
Kotlin
|
0
| 1 |
3f0a227fe8d48cbeece5d677e8e36974d00e4e9c
| 638 |
Blazelight
|
MIT License
|
app/src/main/java/com/example/recipes/screens/myrecipes/MyRecipesViewModel.kt
|
DurlacherT
| 641,836,611 | false | null |
package com.example.recipes.screens.allrecipes
import androidx.compose.runtime.mutableStateOf
import com.example.recipes.EDIT_RECIPE_SCREEN
import com.example.recipes.OVERVIEW_SCREEN
import com.example.recipes.SETTINGS_SCREEN
import com.example.recipes.RECIPE_ID
import com.example.recipes.model.Recipe
import com.example.recipes.model.service.ConfigurationService
import com.example.recipes.model.service.LogService
import com.example.recipes.model.service.StorageService
import com.example.recipes.screens.RecipesViewModel
import com.example.recipes.screens.myrecipes.RecipeActionOption
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class OverviewViewModel @Inject constructor(
logService: LogService,
private val storageService: StorageService,
private val configurationService: ConfigurationService
) : RecipesViewModel(logService) {
val options = mutableStateOf<List<String>>(listOf())
val recipes = storageService.recipe
fun loadTaskOptions() {
val hasEditOption = configurationService.isShowRecipeEditButtonConfig
options.value = RecipeActionOption.getOptions(hasEditOption)
}
fun onTaskCheckChange(task: Recipe) {
launchCatching { storageService.update(task.copy(completed = !task.completed)) }
}
fun onAddClick(openScreen: (String) -> Unit) = openScreen(EDIT_RECIPE_SCREEN)
fun onSettingsClick(openScreen: (String) -> Unit) = openScreen(SETTINGS_SCREEN)
fun onOverviewClick(openScreen: (String) -> Unit) = openScreen(OVERVIEW_SCREEN)
fun onTaskActionClick(openScreen: (String) -> Unit, task: Recipe, action: String) {
when (RecipeActionOption.getByTitle(action)) {
RecipeActionOption.EditRecipe -> openScreen("$EDIT_RECIPE_SCREEN?$RECIPE_ID={${task.id}}")
RecipeActionOption.ToggleFlag -> onFlagTaskClick(task)
RecipeActionOption.DeleteRecipe -> onDeleteTaskClick(task)
}
}
private fun onFlagTaskClick(task: Recipe) {
launchCatching { storageService.update(task.copy(flag = !task.flag)) }
}
private fun onDeleteTaskClick(task: Recipe) {
launchCatching { storageService.delete(task.id) }
}
}
| 0 |
Kotlin
|
0
| 0 |
74d3a677c3dbad22fd03227003e699b0dad28cee
| 2,149 |
recipes
|
Apache License 2.0
|
floatingwindows/src/main/java/com/lyl/floatingwindows/interf/IDragFloatListener.kt
|
arpsyalin
| 370,188,107 | false | null |
package com.lyl.floatingwindows.interf
interface IDragFloatListener {
fun onMoveChange(x: Float, y: Float)
fun onMoveUp()
}
| 0 |
Kotlin
|
0
| 0 |
9b835b1d879fb209e50c44e8f04b993704cf8b51
| 132 |
floatingwindows
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.