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
domain/src/main/java/com/thelazybattley/domain/local/usecase/impl/GetLocationUseCaseImpl.kt
dellosaneil
720,658,411
false
{"Kotlin": 220688}
package com.thelazybattley.domain.local.usecase.impl import com.thelazybattley.domain.local.usecase.GetLocationUseCase import com.thelazybattley.domain.repository.WeatherRepository import javax.inject.Inject class GetLocationUseCaseImpl @Inject constructor( private val repository: WeatherRepository ): GetLocationUseCase { override suspend fun invoke() = repository.getLocation() }
0
Kotlin
0
0
e4a5c6038257f3d172fe2c999fb88323ddf628c4
393
weather-app
Apache License 2.0
app/src/main/java/io/github/stcksmsh/beogradplusplus/TopBar.kt
stcksmsh
692,860,368
false
{"Kotlin": 20891}
package io.github.stcksmsh.beogradplusplus import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.outlined.Call import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.* import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import kotlin.system.exitProcess @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopBar(Ticket: MutableState<String>, Number: MutableState<String>){ Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .background(Color.Transparent) .fillMaxWidth() .padding(horizontal = 10.dp) ) { Row( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, ){ IconButton( onClick = { exitProcess(0) } ){ Icon(Icons.Default.ArrowBack , contentDescription = "testing") } Text(text = "9011 ") } Row( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, ){ var expandedMainMenu by remember { mutableStateOf(false) } var expandedTicketMenu by remember{ mutableStateOf(false) } var expandedNumberMenu by remember{ mutableStateOf(false) } val ticketTypes = arrayOf("A90", "B90", "C90", "A1", "B1", "C1", "A7", "B7", "C7", "A30", "B30", "C30") Icon(Icons.Outlined.Call, contentDescription = "N/A") IconButton(onClick = {expandedMainMenu = !expandedMainMenu}){ Icon(Icons.Outlined.Settings , contentDescription = "testing") } DropdownMenu( /// main menu expanded = expandedMainMenu, onDismissRequest = {expandedMainMenu = false} ){ Column( modifier = Modifier.padding(16.dp) ){ DropdownMenuItem(text = { Text("Change ticket") }, onClick = { expandedTicketMenu = true; expandedMainMenu = false}) DropdownMenuItem( text = { Text("Change number") }, onClick = {;expandedNumberMenu = true; expandedMainMenu = false} ) } } DropdownMenu( /// ticket menu expanded = expandedTicketMenu, onDismissRequest = { expandedTicketMenu = false; expandedMainMenu = true}) { Column( modifier = Modifier.padding(16.dp) ){ ticketTypes.forEach { item -> DropdownMenuItem( text = { Text(item) }, onClick = { Ticket.apply { this.value = item };expandedTicketMenu = false }) } } } DropdownMenu( /// number menu expanded = expandedNumberMenu, onDismissRequest = {expandedNumberMenu =false; expandedMainMenu = true} ){ Column( modifier = Modifier .padding(16.dp) ){ BasicTextField( value = Number.value, onValueChange = {Number.value = it}, keyboardActions = KeyboardActions( onDone = { // Hide the keyboard when done expandedNumberMenu = false } ), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done ), ) } } } } }
3
Kotlin
0
0
0933321808de173a58b00fb9cb4f4aeb0e6bbc18
4,629
BeogradPlusPlus
MIT License
common/src/commonMain/kotlin/com.chrynan.video.common/repository/VideoRepository.kt
chRyNaN
174,161,260
false
null
package com.chrynan.video.common.repository import com.chrynan.video.common.model.api.VideoDetails import com.chrynan.video.common.model.core.ID import com.chrynan.video.common.model.core.UriString import kotlinx.coroutines.flow.Flow interface VideoRepository { fun getVideoDetails(providerUri: UriString, videoId: ID): Flow<VideoDetails> }
0
Kotlin
0
8
63456dcfdd57dbee9ff02b2155b7e1ec5761db81
348
Video
Apache License 2.0
time-service/app/src/test/kotlin/com/example/marvel/domain/recordcollection/RecordCollectionDetailedViewDefaultTest.kt
soberich
194,400,851
false
null
package com.example.marvel.domain.recordcollection import com.example.marvel.api.RecordDetailedView import io.mockk.MockKAnnotations import io.mockk.impl.annotations.MockK import java.time.YearMonth import org.junit.Before class RecordCollectionDetailedViewDefaultTest { private lateinit var cut: RecordCollectionDetailedViewDefault private val id = 0L private val version = 1 @MockK lateinit var yearMonth: YearMonth private val projectId = "projectId" private val employeeId = 0L private val records = listOf<RecordDetailedView>() @Before fun setUp() { MockKAnnotations.init(this, relaxUnitFun = true) // cut = RecordCollectionDetailedViewDefault(id, version, yearMonth, projectId, employeeId, records) } }
0
Kotlin
1
6
f737108d2fb4fdab4e003ba7aeae252e557d7b1f
778
marvel
MIT License
app/src/main/java/com/laotoua/dawnislandk/screens/posts/PostsFragment.kt
dd-fantasy
284,289,786
true
{"Kotlin": 556259, "HTML": 16531}
/* * Copyright 2020 Fishballzzz * * * * 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.laotoua.dawnislandk.screens.posts import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItems import com.afollestad.materialdialogs.list.listItemsSingleChoice import com.laotoua.dawnislandk.DawnApp import com.laotoua.dawnislandk.MainNavDirections import com.laotoua.dawnislandk.R import com.laotoua.dawnislandk.data.local.entity.Post import com.laotoua.dawnislandk.databinding.FragmentPostBinding import com.laotoua.dawnislandk.screens.MainActivity import com.laotoua.dawnislandk.screens.adapters.QuickAdapter import com.laotoua.dawnislandk.screens.util.Layout.updateHeaderAndFooter import com.laotoua.dawnislandk.screens.widgets.BaseNavFragment import com.laotoua.dawnislandk.screens.widgets.popups.ImageViewerPopup import com.laotoua.dawnislandk.screens.widgets.popups.PostPopup import com.laotoua.dawnislandk.util.DawnConstants import com.laotoua.dawnislandk.util.EventPayload import com.laotoua.dawnislandk.util.SingleLiveEvent import com.laotoua.dawnislandk.util.lazyOnMainOnly import com.lxj.xpopup.XPopup import me.dkzwm.widget.srl.RefreshingListenerAdapter import me.dkzwm.widget.srl.config.Constants import timber.log.Timber class PostsFragment : BaseNavFragment() { private var binding: FragmentPostBinding? = null private var mAdapter: QuickAdapter<Post>? = null private val viewModel: PostsViewModel by viewModels { viewModelFactory } private val postPopup: PostPopup by lazyOnMainOnly { PostPopup(requireActivity(), sharedVM) } private var isFabOpen = false private val postObs = Observer<List<Post>> { if (mAdapter == null) return@Observer if (it.isEmpty()) { if (!mAdapter!!.hasEmptyView()) mAdapter!!.setDefaultEmptyView() mAdapter!!.setDiffNewData(null) return@Observer } // set forum when navigate from website url if (sharedVM.selectedForumId.value == null) { sharedVM.setForumId(it.first().fid) } mAdapter!!.setDiffNewData(it.toMutableList()) Timber.i("${this.javaClass.simpleName} Adapter will have ${it.size} threads") } private val forumIdObs = Observer<String> { if (mAdapter == null) return@Observer if (viewModel.currentFid != it) mAdapter!!.setList(emptyList()) viewModel.setForum(it) } private val loadingObs = Observer<SingleLiveEvent<EventPayload<Nothing>>> { if (mAdapter == null || binding == null) return@Observer it.getContentIfNotHandled()?.run { updateHeaderAndFooter(binding!!.srlAndRv.refreshLayout, mAdapter!!, this) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_fragment_post, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.forumRule -> { val fid = sharedVM.selectedForumId.value if (fid == null) { Toast.makeText( requireContext(), R.string.please_try_again_later, Toast.LENGTH_SHORT ).show() return true } val fidInt: Int? try { fidInt = fid.toInt() } catch (e: Exception) { Toast.makeText(context, R.string.did_not_select_forum_id, Toast.LENGTH_SHORT) .show() return true } MaterialDialog(requireContext()).show { val biId = if (fidInt > 0) fidInt else 1 val resourceId: Int = context.resources.getIdentifier( "bi_$biId", "drawable", context.packageName ) icon(resourceId) title(text = sharedVM.getForumDisplayName(fid)) message(text = sharedVM.getForumMsg(fid)) { html { link -> val uri = if (link.startsWith("/")) { DawnConstants.nmbHost + link } else link val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) if (intent.resolveActivity(requireActivity().packageManager) != null) { startActivity(intent) } } } positiveButton(R.string.acknowledge) } return true } else -> super.onOptionsItemSelected(item) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { if (mAdapter == null) { mAdapter = QuickAdapter<Post>(R.layout.list_item_post, sharedVM).apply { setOnItemClickListener { _, _, position -> getItem(position).run { val navAction = MainNavDirections.actionGlobalCommentsFragment(id, fid) findNavController().navigate(navAction) } } setOnItemLongClickListener { _, _, position -> MaterialDialog(requireContext()).show { title(R.string.post_options) listItems(R.array.post_options) { _, index, _ -> if (index == 0) { MaterialDialog(requireContext()).show { title(R.string.report_reasons) listItemsSingleChoice(res = R.array.report_reasons) { _, _, text -> postPopup.setupAndShow( "18",//值班室 "18", newPost = true, quote = ">>No.${getItem(position).id}\n${context.getString( R.string.report_reasons )}: $text\n" ) } cancelOnTouchOutside(false) } } } } true } addChildClickViewIds(R.id.attachedImage) setOnItemChildClickListener { _, view, position -> if (view.id == R.id.attachedImage) { val viewerPopup = ImageViewerPopup(requireContext()) viewerPopup.setSingleSrcView(view as ImageView?, getItem(position)) XPopup.Builder(context) .asCustom(viewerPopup) .show() } } loadMoreModule.setOnLoadMoreListener { viewModel.getPosts() } } } if (binding != null) { Timber.d("Fragment View Reusing!") } else { Timber.d("Fragment View Created") binding = FragmentPostBinding.inflate(inflater, container, false) binding!!.srlAndRv.refreshLayout.apply { setOnRefreshListener(object : RefreshingListenerAdapter() { override fun onRefreshing() { viewModel.refresh() } }) } binding!!.srlAndRv.recyclerView.apply { layoutManager = LinearLayoutManager(context) adapter = mAdapter setHasFixedSize(true) addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy > 0) { hideFabMenu() binding?.fabMenu?.hide() binding?.fabMenu?.isClickable = false } else if (dy < 0) { binding?.fabMenu?.show() binding?.fabMenu?.isClickable = true } } }) } binding!!.fabMenu.setOnClickListener { toggleFabMenu() } binding!!.post.setOnClickListener { if (sharedVM.selectedForumId.value == null) { Toast.makeText( requireContext(), R.string.please_try_again_later, Toast.LENGTH_SHORT ).show() return@setOnClickListener } hideFabMenu() postPopup.setupAndShow( sharedVM.selectedForumId.value, sharedVM.selectedForumId.value!!, true ) } binding!!.announcement.setOnClickListener { hideFabMenu() DawnApp.applicationDataStore.nmbNotice?.let { notice -> MaterialDialog(requireContext()).show { title(res = R.string.announcement) message(text = notice.content) { html() } positiveButton(R.string.close) } } } binding!!.flingInterceptor.bindListener { (activity as MainActivity).showDrawer() } } return binding!!.root } override fun onResume() { super.onResume() // initial load if (viewModel.posts.value.isNullOrEmpty()) { binding?.srlAndRv?.refreshLayout?.autoRefresh( Constants.ACTION_NOTHING, false ) } viewModel.loadingStatus.observe(viewLifecycleOwner, loadingObs) viewModel.posts.observe(viewLifecycleOwner, postObs) sharedVM.selectedForumId.observe(viewLifecycleOwner, forumIdObs) } override fun onPause() { super.onPause() viewModel.loadingStatus.removeObserver(loadingObs) viewModel.posts.removeObserver(postObs) sharedVM.selectedForumId.removeObserver(forumIdObs) } private fun hideFabMenu() { val rotateBackward = AnimationUtils.loadAnimation( requireContext(), R.anim.rotate_backward ) binding?.fabMenu?.startAnimation(rotateBackward) binding?.announcement?.hide() binding?.post?.hide() isFabOpen = false } private fun showFabMenu() { val rotateForward = AnimationUtils.loadAnimation( requireContext(), R.anim.rotate_forward ) binding?.fabMenu?.startAnimation(rotateForward) binding?.announcement?.show() binding?.post?.show() isFabOpen = true } private fun toggleFabMenu() { if (isFabOpen) { hideFabMenu() } else { showFabMenu() } } override fun onDestroyView() { super.onDestroyView() if (!DawnApp.applicationDataStore.getViewCaching()) { mAdapter = null binding = null } Timber.d("Fragment View Destroyed ${binding == null}") } }
0
Kotlin
0
0
80f8f28b499a41c84360a9201147df3b54bb9e77
12,993
DawnIslandK
Apache License 2.0
src/main/kotlin/edu/csh/chase/kjson/JsonArray.kt
chaseberry
42,316,899
false
null
package edu.csh.chase.kjson import java.io.IOException import java.io.StringWriter import java.io.Writer import java.util.* class JsonArray() : JsonBase(), Iterable<Any?> { private val array = ArrayList<Any?>() override val size: Int get() { return array.size } val indices: IntRange get() { return array.indices } constructor(tokener: JsonTokener) : this() { if (tokener.nextClean() != '[') { throw tokener.syntaxError("A JSONArray must start with '['") } if (tokener.nextClean() != ']') { tokener.back() while (true) { if (tokener.nextClean() == ',') { tokener.back() array.add(null) } else { tokener.back() array.add(tokener.nextValue()) } when (tokener.nextClean()) { ',' -> { if (tokener.nextClean() == ']') { return } tokener.back() } ']' -> return else -> throw tokener.syntaxError("Expected a ',' or ']'") } } } } constructor(jsonString: String) : this(JsonTokener(jsonString)) constructor(list: Collection<Any?>) : this() { array.addAll(list.filter { it.isValidJsonType() }) } constructor(vararg array: Any?) : this() { this.array.addAll(array.filter { it.isValidJsonType() }) } private fun getValue(index: Int): Any? { if (index !in array.indices) { return null } return array[index] } private fun setValue(index: Int, value: Any?) { if (index !in array.indices) { return//Throws exception? } if (!value.isValidJsonType()) { throw JsonException("$value is not a valid JsonException") } array[index] = value } //Setters /** * Sets a value inside this JsonArray * Will fail silenty if the index is out of bounds * * @param index The index to set the value of * @param value The value to put at the given index * * @throws JsonException if the value is not a valid Json Value */ fun set(index: Int, value: Any?) { setValue(index, value) } //Putters /** * Adds one or more values to this JsonArray * Will filter out invalid Json Values * * @param value The value to add */ fun put(vararg value: Any?): JsonArray { value.filter { it.isValidJsonType() }.forEach { array.add(it) } return this } /** * Adds one or more values to this JsonArray * Will filter out invalid Json Values and values that are null * * @param value The value to add */ fun putNotNull(vararg value: Any?): JsonArray { value.filter { it != null && it.isValidJsonType() }.forEach { array.add(it) } return this } //Getters /** * Gets a value from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The value found at the given index, or null if the index is out of bounds */ operator fun get(index: Int): Any? = getValue(index) /** * Gets a value from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The value found at the given index, or default if the value is null or index out of bounds */ operator fun get(index: Int, default: Any): Any = getValue(index) ?: default /** * Gets a Boolean from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The Boolean found at the given index, or null if the index is out of bounds */ fun getBoolean(index: Int): Boolean? = getValue(index) as? Boolean /** * Grabs a value from this JsonArray and attempts to coerce it to a Boolean * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceBoolean(index: Int): Boolean? = Coercers.toBoolean(get(index)) /** Gets a Boolean from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The Boolean found at the given index, or default if the value is null or index out of bounds */ fun getBoolean(index: Int, default: Boolean): Boolean = getBoolean(index) ?: default /** * Grabs a value from this JsonArray and attempts to coerce it to a Boolean * If no value is present, or the value could not be coerced, it will return the provided default * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceBoolean(index: Int, default: Boolean): Boolean = coerceBoolean(index) ?: default /** * Gets an Int from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The Int found at the given index, or null if the index is out of bounds */ fun getInt(index: Int): Int? = getValue(index) as? Int /** * Grabs a value from this JsonArray and attempts to coerce it to an Int * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceInt(index: Int): Int? = Coercers.toInt(get(index)) /** * Gets an Int from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The Int found at the given index, or default if the value is null or index out of bounds */ fun getInt(index: Int, default: Int): Int = getInt(index) ?: default /** * Grabs a value from this JsonArray and attempts to coerce it to an Int * If no value is present, or the value could not be coerced, it will return the provided default * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceInt(index: Int, default: Int): Int = coerceInt(index) ?: default /** * Gets a Double from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The Double found at the given index, or null if the index is out of bounds */ fun getDouble(index: Int): Double? = getValue(index) as? Double /** * Grabs a value from this JsonArray and attempts to coerce it to a Double * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceDouble(index: Int): Double? = Coercers.toDouble(get(index)) /** * Gets a Double from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The Double found at the given index, or default if the value is null or index out of bounds */ fun getDouble(index: Int, default: Double): Double = getDouble(index) ?: default /** * Grabs a value from this JsonArray and attempts to coerce it to a Double * If no value is present, or the value could not be coerced, it will return the provided default * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceDouble(index: Int, default: Double): Double = coerceDouble(index) ?: default /** * Gets a String from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The String found at the given index, or null if the index is out of bounds */ fun getString(index: Int): String? = getValue(index) as? String /** * Grabs a value from this JsonArray and attempts to coerce it to a String * Coercing to a String will only return null if the value is null/not present. All other values are .toString() * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceString(index: Int): String? = Coercers.toString(get(index)) /** * Gets a String from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The String found at the given index, or default if the value is null or index out of bounds */ fun getString(index: Int, default: String): String = getString(index) ?: default /** * Grabs a value from this JsonArray and attempts to coerce it to a String * If no value is present, or the value could not be coerced, it will return the provided default * Coercing to a String will only return null if the value is null/not present. All other values are .toString() * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceString(index: Int, default: String): String = coerceString(index) ?: default /** * Gets a JsonObject from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The JsonObject found at the given index, or null if the index is out of bounds */ fun getJsonObject(index: Int): JsonObject? = getValue(index) as? JsonObject /** * Gets a JsonObject from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The JsonObject found at the given index, or default if the value is null or index out of bounds */ fun getJsonObject(index: Int, default: JsonObject): JsonObject = getJsonObject(index) ?: default /** * Gets a JsonArray from this JsonArray * If the index is out of bounds of the array it will return null * * @param index The index of the array to get the value from * @return The JsonArray found at the given index, or null if the index is out of bounds */ fun getJsonArray(index: Int): JsonArray? = getValue(index) as? JsonArray /** * Gets a JsonArray from this JsonArray * If no value is found, or the value is null, will return default instead * * @param index The index of the array to get the value from * @param default The default value * @return The JsonArray found at the given index, or default if the value is null or index out of bounds */ fun getJsonArray(index: Int, default: JsonArray): JsonArray = getJsonArray(index) ?: default /** * Gets the value from a given index if the value is a number * * @param index The index to pull the value from * @return The Float from the given index, null if no value or not a number */ @Deprecated(message = "Not parsed", replaceWith = ReplaceWith("coerceFloat(index)")) fun getFloat(index: Int): Float? = coerceFloat(index) /** * Grabs a value from this JsonArray and attempts to coerce it to a Float * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceFloat(index: Int): Float? = Coercers.toFloat(get(index)) /** * Gets the value from the given index if the value is a number * * @param index The index to pull a value from * @param default The default value is no value is found * @return The Float from the given index, default if no value or not a number */ @Deprecated(message = "Not parsed", replaceWith = ReplaceWith("coerceFloat(index, default)")) fun getFloat(index: Int, default: Float): Float = coerceFloat(index, default) /** * Grabs a value from this JsonArray and attempts to coerce it to a Float * If no value is present, or the value could not be coerced, it will return the provided default * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceFloat(index: Int, default: Float): Float = coerceFloat(index) ?: default /** * Gets the value from a given index if the value is a number * * @param index The index to pull the value from * @return The Float from the given index, null if no value or not a number */ @Deprecated(message = "Not the default parsed number type", replaceWith = ReplaceWith("coerceLong(index)")) fun getLong(index: Int): Long? = coerceLong(index) /** * Grabs a value from this JsonArray and attempts to coerce it to a Long * * @param index The array index to grab the value from * @return The coerced value, or null */ fun coerceLong(index: Int): Long? = Coercers.toLong(get(index)) /** * Gets the value from the given index if the value is a number * * @param index The index to pull a value from * @param default The default value is no value is found * @return The Float from the given index, default if no value or not a number */ @Deprecated(message = "Not the default parsed number type", replaceWith = ReplaceWith("coerceLong(index, default)")) fun getLong(index: Int, default: Long): Long = coerceLong(index, default) /** * Grabs a value from this JsonArray and attempts to coerce it to a Long * If no value is present, or the value could not be coerced, it will return the provided default * * @param index The array index to grab the value from * @param default The default value to return * @return The coerced value, or default */ fun coerceLong(index: Int, default: Long): Long = coerceLong(index) ?: default //Other Functions /** * Gets an immutable copy of this JsonArray's internal array * * @return An immutable array */ fun getInternalArray(): List<Any?> = Collections.unmodifiableList(array.map { when (it) { is JsonObject -> it.getInternalMap() is JsonArray -> it.getInternalArray() else -> it } }) fun remove(index: Int): Any? = array.remove(index) operator fun contains(index: Int): Boolean { return index in array.indices } override fun jsonSerialize(): String { return this.toString(false) } override fun iterator(): Iterator<Any?> { return array.iterator() } override fun equals(other: Any?): Boolean { return other is JsonArray && array == other.array } override fun toString(): String { return toString(false) } override fun toString(shouldIndent: Boolean, depth: Int): String { val sw = StringWriter() synchronized(sw.buffer) { return this.write(sw, shouldIndent, depth).toString() } } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ fun write(writer: Writer): Writer { return this.write(writer, false) } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor * The number of spaces to add to each level of indentation. * @param indent * The indention of the top level. * @return The writer. * @throws JSONException */ fun write(writer: Writer, shouldIndent: Boolean, depth: Int = 1): Writer { try { var addComa = false writer.write("[") for (value in array) { if (addComa) { writer.write(",") } if (shouldIndent) { writer.write("\n") writer.indent(depth) } writer.write(JsonValues.toString(value, shouldIndent, depth + 1)) addComa = true } if (shouldIndent) { writer.write("\n") writer.indent(depth - 1) } writer.write("]") return writer } catch (e: IOException) { throw JsonException(e) } } }
1
Kotlin
1
1
1adcd91adc93be3c6f628d61b703176a861ebe7c
17,827
KJson
Apache License 2.0
packages/connector/interface/src/entities/CollectionField.kt
onesuper
383,790,225
true
{"TypeScript": 1301636, "Kotlin": 78113, "Shell": 6335, "Mustache": 4893, "JavaScript": 3357, "HTML": 2613, "Dockerfile": 1275, "CSS": 782}
package io.tellery.entities data class CollectionField(val collection: String, val schema: String?)
0
null
0
0
a4b1b6bd9422226cc3abf1d61a16f57f88553db0
101
tellery
Apache License 2.0
src/test/kotlin/utils/models/StateCheckableProcess.kt
NoGe4Ek
618,101,180
false
null
package utils.models import ipc.Process import kotlin.test.assertTrue class StateCheckableProcess(name: String, port: Int) : Process(name, port) { fun isTearDownCorrectly() { assertTrue(clientSockets.all { it.isClosed } && serverSocket.isClosed) assertTrue(clientThreads.all { it.isAlive.not() } && serverThread?.isAlive?.not() ?: true) } fun isSetupCorrectly() { assertTrue(clientSockets.all { it.isConnected } && !serverSocket.isClosed) assertTrue(clientThreads.all { it.isAlive } && serverThread?.isAlive ?: true) } }
1
Kotlin
0
1
a59e0aa15b04578befea3e81f6af09f484a49794
571
BabyBlockchain
Apache License 2.0
feature/search/src/main/java/com/him/sama/spotifycompose/search/component/Header.kt
arohim
762,735,266
false
{"Kotlin": 251979}
package com.him.sama.spotifycompose.search.component import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.him.sama.spotifycompose.common.ui.R @Composable fun Header() { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { AsyncImage( modifier = Modifier .size(36.dp) .background( color = Color.LightGray, shape = CircleShape ) .clip(CircleShape), model = "https://media.istockphoto.com/id/1129342275/th/%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B8%96%E0%B9%88%E0%B8%B2%E0%B8%A2/%E0%B9%80%E0%B8%9E%E0%B8%A5%E0%B8%B4%E0%B8%94%E0%B9%80%E0%B8%9E%E0%B8%A5%E0%B8%B4%E0%B8%99%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B9%80%E0%B8%9E%E0%B8%A5%E0%B8%87%E0%B9%82%E0%B8%9B%E0%B8%A3%E0%B8%94%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%82%E0%B8%B2.jpg?s=1024x1024&w=is&k=20&c=TpYBPuy0gKY7MGzBnnIW2zhz3a76BgtGto4ZQIRkv4U=", contentScale = ContentScale.Crop, contentDescription = null ) Spacer(modifier = Modifier.width(16.dp)) Text( text = "Search", style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onPrimary ) Spacer(modifier = Modifier.weight(1f)) Icon( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription = null, tint = Color.White ) } }
0
Kotlin
0
0
826694a8a38dc6f53b48e3a337c8bd15a0f8549c
2,445
SpotifyJetpackCompose
Apache License 2.0
sample/src/main/java/com/fvalela/calendarjetpackcompose/sample/DefaultWithIncreasedVerticalPaddingCalendar.kt
fvalela1
348,388,275
false
null
package com.fvalela.calendarjetpackcompose.sample import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.fvalela.calendarjetpackcompose.CalendarJetpackCompose import com.fvalela.calendarjetpackcompose.sample.ui.CalendarJetpackComposeSampleTheme class DefaultWithIncreasedVerticalPaddingCalendar : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CalendarJetpackComposeSampleTheme(darkTheme = false) { Surface( color = MaterialTheme.colors.background, modifier = Modifier.fillMaxHeight() ) { Column(Modifier.fillMaxSize()) { DefaultWithIncreasedVerticalPaddingCalendarHelper() } } } } } } @Composable private fun DefaultWithIncreasedVerticalPaddingCalendarHelper() { CalendarJetpackCompose( verticalPadding = 10.dp ) }
4
Kotlin
0
9
b3d86ef07805c448afeb5d9f0bfff7675efd516a
1,453
CalendarJetpackCompose
Apache License 2.0
src/test/kotlin/g2501_2600/s2579_count_total_number_of_colored_cells/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2579_count_total_number_of_colored_cells import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun coloredCells() { assertThat(Solution().coloredCells(1), equalTo(1L)) } @Test fun coloredCells2() { assertThat(Solution().coloredCells(2), equalTo(5L)) } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
419
LeetCode-in-Kotlin
MIT License
src/main/kotlin/ru/krindra/vknorthtypes/groups/GroupsGetRequestsFieldsResponse.kt
kravandir
745,597,090
false
{"Kotlin": 633233}
package ru.krindra.vknorthtypes.groups import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.krindra.vknorthtypes.users.UsersUserFull @Serializable() data class GroupsGetRequestsFieldsRawResponse ( @SerialName("count") val count: Int, @SerialName("items") val items: List<UsersUserFull>, ) @Serializable() data class GroupsGetRequestsFieldsResponse ( val response: GroupsGetRequestsFieldsRawResponse )
0
Kotlin
0
0
508d2d1d59c4606a99af60b924c6509cfec6ef6c
456
VkNorthTypes
MIT License
poreia-core/src/main/kotlin/io/github/smecsia/poreia/core/impl/BasicThreadPoolBuilder.kt
smecsia
532,748,095
false
{"Kotlin": 222991}
package io.github.smecsia.poreia.core.impl import io.github.smecsia.poreia.core.api.ThreadPool import io.github.smecsia.poreia.core.api.ThreadPoolBuilder import java.util.concurrent.Executors.newFixedThreadPool class BasicThreadPoolBuilder : ThreadPoolBuilder { override fun build(size: Int): ThreadPool { val executor = newFixedThreadPool(size) return object : ThreadPool { override fun shutdownNow() { executor.shutdownNow() } override fun submit(task: () -> Unit) { executor.submit(task) } override fun isShutdown(): Boolean { return executor.isShutdown } } } }
0
Kotlin
0
1
16245df5f8431a730e4161dddf646e0c14432d51
721
poreia
MIT License
src/test/kotlin/com/boardgames/uno/exceptions/ValidationExceptionTest.kt
shiviraj
463,034,209
false
{"Kotlin": 83840, "Procfile": 96}
package com.boardgames.exceptions import com.boardgames.exceptions.exceptions.ErrorResponse import com.boardgames.exceptions.exceptions.ServiceError import com.boardgames.exceptions.exceptions.ValidationErrorDetails import com.boardgames.exceptions.exceptions.ValidationException import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class ValidationExceptionTest { @Test fun `should get all error codes in validation exception concatenated with comma`() { val validationException = ValidationException( ValidationErrorDetails( listOf( ErrorResponse(Error("code1", "message1")), ErrorResponse(Error("code2", "message2")) ) ), "message" ) validationException.errorCodes shouldBe "code1, code2" } } class Error(override val errorCode: String, override val message: String) : ServiceError
0
Kotlin
0
0
a1bd2f4eab38e121f65c2e8bf798097f16e9e836
950
boilerplate-backend
MIT License
src/main/kotlin/dev/janssenbatista/pomodorotimer/utils/PreferenceUtils.kt
janssenbatista
630,281,629
false
null
package dev.janssenbatista.pomodorotimer.utils import dev.janssenbatista.pomodorotimer.models.Preferences import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* object PreferenceUtils { private val userHomePath: String = System.getProperty("user.home") private val preferencesFilePath = Paths.get("$userHomePath/.config/pomodoro-timer/app.properties") private val properties = Properties() fun loadPreferences(): Preferences { var preferences: Preferences val configPath: Path? val appConfigPath: Path? val fileInputStream = FileInputStream(File(preferencesFilePath.toUri())) if (!Files.exists(preferencesFilePath)) { configPath = if (!Files.exists(Paths.get("$userHomePath/.config"))) { Files.createDirectory(Paths.get("$userHomePath/.config")) } else { Paths.get("$userHomePath/.config") } appConfigPath = if (!Files.exists(Paths.get("$configPath/pomodoro-timer"))) { Files.createDirectory(Paths.get("$configPath/pomodoro-timer")) } else { Paths.get("$configPath/pomodoro-timer") } Files.createFile(Paths.get("$appConfigPath/app.properties")) properties.load(fileInputStream) preferences = Preferences( workTime = 25 * 60 * 1000, shortBreakTime = 5 * 60 * 1000, longBreakTime = 15 * 60 * 1000, theme = "light", alertSound = "sound_one" ) savePreferences(preferences) } else { properties.apply { load(fileInputStream) preferences = Preferences( workTime = this.getProperty("WORK_TIME").toInt(), shortBreakTime = this.getProperty("SHORT_BREAK_TIME").toInt(), longBreakTime = this.getProperty("LONG_BREAK_TIME").toInt(), theme = this.getProperty("THEME"), alertSound = this.getProperty("ALERT_SOUND") ) } } fileInputStream.close() return preferences } fun savePreferences(preferences: Preferences) { val fileOutputStream = FileOutputStream(File(preferencesFilePath.toUri())) properties.apply { setProperty("WORK_TIME", preferences.workTime.toString()) setProperty("SHORT_BREAK_TIME", preferences.shortBreakTime.toString()) setProperty("LONG_BREAK_TIME", preferences.longBreakTime.toString()) setProperty("THEME", preferences.theme) setProperty("ALERT_SOUND", preferences.alertSound) store(fileOutputStream, "Preferences") } fileOutputStream.close() } }
0
Kotlin
0
1
cc87aa67e51b27558934a41ef98650e520f21f77
2,935
desktop-pomodoro-timer
MIT License
app/src/main/java/com/speakerboxlite/rxentity/Entity.kt
AlexExiv
240,526,542
false
null
package com.speakerboxlite.rxentity interface Entity<Key: Comparable<Key>> { val _key: Key } typealias EntityInt = Entity<Int> typealias EntityLong = Entity<Long> typealias EntityString = Entity<String> interface EntityBack<Key: Comparable<Key>> { val _key: Key } typealias EntityBackInt = EntityBack<Int> typealias EntityBackLong = EntityBack<Long> typealias EntityBackString = EntityBack<String> interface EntityFactory<Key: Comparable<Key>, in Source: EntityBack<Key>, out Dest: Entity<Key>> { fun map(entity: Source): Dest }
0
Kotlin
0
0
d100c2a1bd34c0e791df6e812f30a611b6779725
546
RxEntity-Kotlin
MIT License
modules/services/core-ui/src/main/java/com/markettwits/core_ui/di/ProvideViewMoel.kt
MarketTwits
689,047,730
false
{"Kotlin": 242276}
package com.markettwits.core_ui.di import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import com.markettwits.core.di.ProvideViewModel @Composable inline fun <reified T : ViewModel> ApplicationViewModel(): T = (LocalContext.current.applicationContext as ProvideViewModel).viewModel( checkNotNull( LocalViewModelStoreOwner.current ), T::class.java )
0
Kotlin
0
0
6d40b53a68a12cffc635027e6ff9f10f86f06bb2
531
WaifuPics
MIT License
app/src/main/java/com/renaisn/reader/ui/qrcode/QrCodeActivity.kt
RenaisnNce
598,532,496
false
null
package com.renaisn.reader.ui.qrcode import android.content.Intent import android.graphics.BitmapFactory import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.google.zxing.Result import com.king.zxing.CameraScan.OnScanResultCallback import com.renaisn.reader.R import com.renaisn.reader.base.BaseActivity import com.renaisn.reader.databinding.ActivityQrcodeCaptureBinding import com.renaisn.reader.utils.QRCodeUtils import com.renaisn.reader.utils.SelectImageContract import com.renaisn.reader.utils.launch import com.renaisn.reader.utils.readBytes import com.renaisn.reader.utils.viewbindingdelegate.viewBinding class QrCodeActivity : BaseActivity<ActivityQrcodeCaptureBinding>(), OnScanResultCallback { override val binding by viewBinding(ActivityQrcodeCaptureBinding::inflate) private val selectQrImage = registerForActivityResult(SelectImageContract()) { it?.uri?.readBytes(this)?.let { bytes -> val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) onScanResultCallback(QRCodeUtils.parseCodeResult(bitmap)) } } override fun onActivityCreated(savedInstanceState: Bundle?) { val fTag = "qrCodeFragment" val qrCodeFragment = QrCodeFragment() supportFragmentManager.beginTransaction() .replace(R.id.fl_content, qrCodeFragment, fTag) .commit() } override fun onCompatCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.qr_code_scan, menu) return super.onCompatCreateOptionsMenu(menu) } override fun onCompatOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_choose_from_gallery -> selectQrImage.launch() } return super.onCompatOptionsItemSelected(item) } override fun onScanResultCallback(result: Result?): Boolean { val intent = Intent() intent.putExtra("result", result?.text) setResult(RESULT_OK, intent) finish() return true } }
1
Kotlin
1
4
4ac03e214e951f7f4f337d4da1f7e39fa715d1c0
2,058
Renaisn_Android
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/lightsail/CfnStaticIpPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.lightsail import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.lightsail.CfnStaticIpProps @Generated public fun buildCfnStaticIpProps(initializer: @AwsCdkDsl CfnStaticIpProps.Builder.() -> Unit): CfnStaticIpProps = CfnStaticIpProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
402
aws-cdk-kt
Apache License 2.0
app-backend/src/main/kotlin/link/kotlin/server/plugins/HTTP.kt
KotlinBy
40,936,978
false
null
package link.kotlin.server.plugins import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import io.ktor.application.Application import io.ktor.application.call import io.ktor.application.install import io.ktor.auth.authentication import io.ktor.auth.jwt.JWTPrincipal import io.ktor.auth.jwt.jwt import io.ktor.features.CachingHeaders import io.ktor.features.ContentNegotiation import io.ktor.features.DefaultHeaders import io.ktor.features.StatusPages import io.ktor.http.CacheControl import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.content.CachingOptions import io.ktor.locations.Locations import io.ktor.response.respond import io.ktor.serialization.json import kotlin.reflect.KProperty import kotlin.time.Duration fun Application.defaults( jwtConfiguration: JwtConfiguration, ) { install(Locations) install(ContentNegotiation) { json() } install(DefaultHeaders) { header("X-Application", "awesome-kotlin/v2") } install(CachingHeaders) { options { outgoingContent -> when (outgoingContent.contentType?.withoutParameters()) { ContentType.Text.CSS -> CachingOptions( CacheControl.MaxAge( maxAgeSeconds = Duration .days(365) .inWholeSeconds .toInt() ) ) else -> null } } } install(StatusPages) { exception<AuthenticationException> { cause -> call.respond(HttpStatusCode.Unauthorized) } exception<AuthorizationException> { cause -> call.respond(HttpStatusCode.Forbidden) } exception<ConstraintViolationException> { cause -> call.respond(HttpStatusCode.BadRequest, cause.fields) } } authentication { jwt("jwt") { realm = jwtConfiguration.realm verifier( JWT .require(Algorithm.HMAC512(jwtConfiguration.secret)) .withAudience(jwtConfiguration.audience) .withIssuer(jwtConfiguration.issuer) .build() ) validate { credential -> if (credential.payload.audience.contains(jwtConfiguration.audience)) { JWTPrincipal(credential.payload) } else { null } } } } } data class JwtConfiguration( val audience: String, val realm: String, val issuer: String, val secret: String, ) class AuthenticationException : RuntimeException() class AuthorizationException : RuntimeException() class ConstraintViolationException( val fields: List<ConstraintViolationFields> ) : RuntimeException() data class ConstraintViolationFields( val message: String, val fields: List<KProperty<*>> )
20
Kotlin
1127
9,869
38a336cb6953e0e7a1f0b511aee7902a3996fbb5
2,994
awesome-kotlin
Apache License 2.0
cryptography-core/src/commonMain/kotlin/algorithms/Digest.kt
whyoleg
492,907,371
false
{"Kotlin": 1074574, "JavaScript": 318}
/* * Copyright (c) 2023-2024 <NAME>. Use of this source code is governed by the Apache 2.0 license. */ @file:OptIn(CryptographyProviderApi::class) package dev.whyoleg.cryptography.algorithms import dev.whyoleg.cryptography.* import dev.whyoleg.cryptography.operations.* //simple hash algorithms, that can be used in HMAC/ECDSA contexts @SubclassOptInRequired(CryptographyProviderApi::class) public interface Digest : CryptographyAlgorithm { override val id: CryptographyAlgorithmId<Digest> public fun hasher(): Hasher } @DelicateCryptographyApi public object MD5 : CryptographyAlgorithmId<Digest>("MD5") @DelicateCryptographyApi public object SHA1 : CryptographyAlgorithmId<Digest>("SHA-1") public object SHA224 : CryptographyAlgorithmId<Digest>("SHA-224") public object SHA256 : CryptographyAlgorithmId<Digest>("SHA-256") public object SHA384 : CryptographyAlgorithmId<Digest>("SHA-384") public object SHA512 : CryptographyAlgorithmId<Digest>("SHA-512") @Suppress("ClassName") public object SHA3_224 : CryptographyAlgorithmId<Digest>("SHA3-224") @Suppress("ClassName") public object SHA3_256 : CryptographyAlgorithmId<Digest>("SHA3-256") @Suppress("ClassName") public object SHA3_384 : CryptographyAlgorithmId<Digest>("SHA3-384") @Suppress("ClassName") public object SHA3_512 : CryptographyAlgorithmId<Digest>("SHA3-512")
10
Kotlin
20
302
69b77a88b4b81109704475ed02be48d263d1a1c8
1,343
cryptography-kotlin
Apache License 2.0
criminal-intent/src/main/java/com/bignerdranch/android/criminalintent/crimefragment/CrimeViewModel.kt
v43d3rm4k4r
541,134,762
false
null
package com.bignerdranch.android.criminalintent.crimefragment import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.bignerdranch.android.criminalintent.CrimeRepository import com.bignerdranch.android.criminalintent.model.Crime import java.io.File import java.util.* class CrimeViewModel : ViewModel() { private val crimeRepository = CrimeRepository.get() private val crimeIdLiveData = MutableLiveData<UUID>() // current crime var crimeLiveData: LiveData<Crime?> = Transformations.switchMap(crimeIdLiveData) { crimeId -> crimeRepository.getCrime(crimeId) } fun loadCrime(crimeId: UUID) { crimeIdLiveData.value = crimeId } fun updateCrime(crime: Crime) = crimeRepository.updateCrime(crime) fun deleteCrime(crime: Crime) = crimeRepository.deleteCrime(crime) fun getPhotoFile(crime: Crime): File = crimeRepository.getPhotoFile(crime) }
0
Kotlin
0
2
b61a3976e89f60b36fcb49b89924423b1c06dc3a
961
BigNerdRanchAndroid
Apache License 2.0
src/main/kotlin/pl/exbook/exbook/category/adapter/mongodb/DatabaseCategoryRepository.kt
Ejden
339,380,956
false
null
package pl.exbook.exbook.category.adapter.mongodb import org.springframework.stereotype.Component import pl.exbook.exbook.category.domain.Category import pl.exbook.exbook.shared.CategoryId import pl.exbook.exbook.category.domain.CategoryRepository import pl.exbook.exbook.category.domain.Image @Component class DatabaseCategoryRepository(private val mongoCategoryRepository: MongoCategoryRepository) : CategoryRepository { override fun save(category: Category): Category { return mongoCategoryRepository.save(category.toDocument()).toDomain() } override fun getById(id: CategoryId): Category? { return mongoCategoryRepository.findById(id.raw)?.toDomain() } override fun findByName(name: String): Category? { return mongoCategoryRepository.findByName(name)?.toDomain() } override fun findAll(): List<Category> { return mongoCategoryRepository.findAll().map { it.toDomain() } } } private fun Category.toDocument() = CategoryDocument( id = this.id.raw, name = this.name, image = this.image?.toDocument(), parentId = this.parentId?.raw ) private fun Image.toDocument() = ImageDocument(this.url) private fun CategoryDocument.toDomain() = Category( id = CategoryId(this.id), name = this.name, image = this.image?.toDomain(), parentId = this.parentId?.let { CategoryId(it) } ) private fun ImageDocument.toDomain() = Image(this.url)
3
Kotlin
0
1
977fffb4e75b5850efd74d2d0165b09bb5740117
1,431
exbook-backend
The Unlicense
app/src/commonMain/kotlin/features/scan/ScanScreenModel.kt
JuulLabs
293,729,751
false
{"Kotlin": 85988, "Swift": 617, "HTML": 237}
package com.juul.sensortag.features.scan import cafe.adriel.voyager.core.model.ScreenModel import cafe.adriel.voyager.core.model.screenModelScope import cafe.adriel.voyager.core.screen.Screen import com.juul.kable.Bluetooth import com.juul.kable.ExperimentalApi import com.juul.kable.Peripheral import com.juul.kable.PlatformAdvertisement import com.juul.kable.logs.Logging.Level.Data import com.juul.sensortag.bluetooth.requirements.BluetoothRequirements import com.juul.sensortag.bluetooth.requirements.Deficiency.BluetoothOff import com.juul.sensortag.bluetooth.requirements.Deficiency.LocationServicesDisabled import com.juul.sensortag.features.scan.DeviceLocator.State.NotYetScanned import com.juul.sensortag.features.scan.DeviceLocator.State.Scanning import com.juul.sensortag.features.sensor.SensorScreen import com.juul.sensortag.peripheral import com.juul.sensortag.permissions.Permission import com.juul.sensortag.permissions.PermissionState import com.juul.sensortag.permissions.PermissionsController import com.juul.sensortag.requestPermission import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class ScanScreenModel( val permissionsController: PermissionsController, bluetoothRequirements: BluetoothRequirements, ) : ScreenModel { private val _navigation = MutableSharedFlow<Screen>() val navigation = _navigation.asSharedFlow() private val _showConnectPermissionAlertDialog = MutableStateFlow(false) val showConnectPermissionAlertDialog = _showConnectPermissionAlertDialog.asStateFlow() private val _snackbarText = MutableStateFlow<String?>(null) val snackbarText = _snackbarText.asStateFlow() private val isBluetoothSupported = MutableStateFlow<Boolean?>(null) private val permissionState = MutableStateFlow(PermissionState.NotDetermined) private val isPermissionGranted = permissionState.map { it == PermissionState.Granted } /** `null` until scan permission has been requested. */ private val isRequestingScanPermission = MutableStateFlow<Boolean?>(null) @OptIn(ExperimentalCoroutinesApi::class) private val requirements = isPermissionGranted.flatMapLatest { isGranted -> bluetoothRequirements.deficiencies.takeIf { isGranted } ?: flowOf(null) } private val deviceLocator = DeviceLocator( onRequestDeviceSuccess = { _navigation.emit(SensorScreen()) }, // JavaScript-only onStatus = _snackbarText::emit, ) val viewState: StateFlow<ViewState> = combine( isBluetoothSupported, permissionState, requirements, deviceLocator.state, deviceLocator.advertisements, ) { isSupported, permissionState, requirements, scanState, advertisements -> when (isSupported) { false -> ViewState.Unsupported true -> when (permissionState) { PermissionState.NotDetermined, PermissionState.NotGranted, PermissionState.Denied -> ViewState.Scan PermissionState.Granted -> when { requirements == null -> null scanState == NotYetScanned -> ViewState.Scan BluetoothOff in requirements -> ViewState.BluetoothOff LocationServicesDisabled in requirements -> ViewState.LocationServicesDisabled else -> ViewState.Devices(scanState, advertisements) } PermissionState.DeniedAlways -> ViewState.PermissionDenied else -> error("Unhandled permission state: $permissionState") } null -> ViewState.Scan } }.filterNotNull() .stateIn(screenModelScope, SharingStarted.WhileSubscribed(), ViewState.Scan) init { screenModelScope.launch { @OptIn(ExperimentalApi::class) isBluetoothSupported.value = Bluetooth.isSupported() } } /** * Re-check permissions when screen resumes (can occur after coming back from app settings * screen where user may have granted needed permissions). */ fun onResumed() { screenModelScope.launch { when (isRequestingScanPermission.value) { // After requesting permission, onResume is triggered, so we reset the // "is requesting" state here. true -> isRequestingScanPermission.value = false false -> requestAndUpdateScanPermission() // On Apple (until authorized) even checking the permission state will show a // permission dialog. We guard against showing the dialog prior to actually wanting // to request the permission by only checking permission after we've explicitly // requested permission. null -> {} // No-op } } } fun scan() { if (deviceLocator.state.value == Scanning) return // Scan already in progress. if (permissionState.value == PermissionState.Granted) { deviceLocator.run() } else { screenModelScope.launch { requestAndUpdateScanPermission() if (permissionState.value == PermissionState.Granted) { deviceLocator.run() } } } } fun onAdvertisementClicked(advertisement: PlatformAdvertisement) { screenModelScope.launch { when (requestConnectPermission()) { PermissionState.Granted -> navigateToSensorScreen(advertisement) PermissionState.DeniedAlways -> _showConnectPermissionAlertDialog.value = true else -> {} // No-op } } } fun clear() { screenModelScope.launch { _snackbarText.value = null deviceLocator.clear() } } fun openAppSettings() { permissionsController.openAppSettings() } fun dismissAlert() { _showConnectPermissionAlertDialog.value = false } private suspend fun navigateToSensorScreen(advertisement: PlatformAdvertisement) { deviceLocator.cancelAndJoin() peripheral = Peripheral(advertisement) { logging { level = Data } } _navigation.emit(SensorScreen()) } private suspend fun requestAndUpdateScanPermission() { // Once we've been granted permission we no longer need to request permission. Apple and // Android will kill the app if permissions are revoked. if (permissionState.value == PermissionState.Granted) return isRequestingScanPermission.value = true permissionsController.requestPermission(Permission.BLUETOOTH_SCAN)?.let { permissionState.value = it } } private suspend fun requestConnectPermission() = permissionsController.requestPermission(Permission.BLUETOOTH_CONNECT) }
2
Kotlin
14
54
e6c4ec1d8d42f42d5a44b2ddc9fc211e7e6b9568
7,397
sensortag
Apache License 2.0
selectiondialog/src/main/java/br/com/kamarugosan/selectiondialog/SelectionAdapter.kt
Kamarugo-san
377,204,165
false
null
package br.com.kamarugosan.selectiondialog import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import java.util.* import kotlin.collections.ArrayList class SelectionAdapter( private val fullDataSet: List<SelectionOption>, private val selectionListener: SelectionItemClickListener ) : RecyclerView.Adapter<SelectionViewHolder>() { private var filteredDataSet: List<SelectionOption> = ArrayList(fullDataSet) var selectedItem: Int? = null var lastFilter: String? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectionViewHolder { return SelectionViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.item_selection, parent, false), object : SelectionItemClickListener { override fun onSelect(position: Int) { selectItem(position, false) selectionListener.onSelect(position) } } ) } override fun onBindViewHolder(holder: SelectionViewHolder, position: Int) { val item = filteredDataSet[position] val isSelected = selectedItem?.equals(item.index) ?: false holder.bind(item, isSelected) } override fun getItemCount(): Int = filteredDataSet.size fun selectItem(index: Int, notifySelectedView: Boolean = true) { val oldSelectedItem = selectedItem selectedItem = index if (oldSelectedItem != null) { notifyItemChanged(oldSelectedItem) } if (notifySelectedView) { notifyItemChanged(index) } } fun disableOption(index: Int) { if (fullDataSet[index].enabled) { fullDataSet[index].enabled = false notifyByOptionIndex(index) } } fun enableOption(index: Int) { if (!fullDataSet[index].enabled) { fullDataSet[index].enabled = true notifyByOptionIndex(index) } } private fun notifyByOptionIndex(index: Int) { filteredDataSet.forEachIndexed { i, selectionOption -> if (selectionOption.index == index) { notifyItemChanged(i) return@forEachIndexed } } } fun clearSelection() { if (selectedItem != null) { var itemToUpdate: Int = selectedItem!! filteredDataSet.forEachIndexed { index, selectionOption -> if (selectionOption.index == selectedItem!!) { itemToUpdate = index return@forEachIndexed } } selectedItem = null notifyItemChanged(itemToUpdate) } } fun filter(filter: String?): Int { filteredDataSet = if (filter == null || filter.isEmpty()) { ArrayList(fullDataSet) } else { val clearedFilter = filter.lowercase().unaccent() val newFilteredDataSet: MutableList<SelectionOption> = ArrayList() var dataSetToFilter = fullDataSet lastFilter?.apply { // Optimizing search by reducing the set to filter if the new one is a continuation // of the last. if (this.isNotEmpty() && filter.startsWith(this)) { dataSetToFilter = filteredDataSet } } dataSetToFilter.forEach { if (it.filterText.contains(clearedFilter)) { newFilteredDataSet.add(it) } } newFilteredDataSet } lastFilter = filter notifyDataSetChanged() return filteredDataSet.size } }
0
Kotlin
0
3
743403d998573fcfc6878b455cd3dab2e397271a
3,747
selection-dialog
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kmastodon/api/FollowRequestsResource.kt
uakihir0
783,390,459
false
{"Kotlin": 167667, "Ruby": 2191, "Shell": 2164, "Makefile": 319}
package work.socialhub.kmastodon.api import work.socialhub.kmastodon.api.request.followrequests.FollowRequestsAuthorizeFollowRequestRequest import work.socialhub.kmastodon.api.request.followrequests.FollowRequestsRejectFollowRequestRequest import work.socialhub.kmastodon.api.response.Response import work.socialhub.kmastodon.api.response.ResponseUnit import work.socialhub.kmastodon.api.response.followrequests.FollowRequestsFollowRequestsResponse import kotlin.js.JsExport @JsExport interface FollowRequestsResource { /** * Fetching a list of follow requests. */ fun followRequests( ): Response<Array<FollowRequestsFollowRequestsResponse>> /** * Authorizing follow requests. */ fun authorizeFollowRequest( request: FollowRequestsAuthorizeFollowRequestRequest ): ResponseUnit /** * Rejecting follow requests. */ fun rejectFollowRequest( request: FollowRequestsRejectFollowRequestRequest ): ResponseUnit }
0
Kotlin
0
1
8d3278cff7a164cbe9e9ad978a9b28e743d1c96d
993
kmastodon
MIT License
aws/ses/src/main/kotlin/io/bluetape4k/aws/ses/model/MessageSupport.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.aws.ses.model import software.amazon.awssdk.services.ses.model.Body import software.amazon.awssdk.services.ses.model.Content import software.amazon.awssdk.services.ses.model.Message import software.amazon.awssdk.services.ses.model.MessageTag import java.nio.charset.Charset inline fun message(initializer: Message.Builder.() -> Unit): Message { return Message.builder().apply(initializer).build() } fun messageOf(subject: Content, body: Body): Message { return message { subject(subject).body(body) } } fun body(initializer: Body.Builder.() -> Unit): Body { return Body.builder().apply(initializer).build() } fun bodyOf(text: String, html: String, charset: Charset = Charsets.UTF_8): Body = body { text(contentOf(text, charset)) html(contentOf(html, charset)) } fun bodyAsText(text: String, charset: Charset = Charsets.UTF_8): Body = body { text(contentOf(text, charset)) } fun bodyAsHtml(html: String, charset: Charset = Charsets.UTF_8): Body = body { html(contentOf(html, charset)) } inline fun content(initializer: Content.Builder.() -> Unit): Content { return Content.builder().apply(initializer).build() } fun contentOf(data: String? = null, charset: Charset = Charsets.UTF_8) = content { data(data) charset(charset.name()) } inline fun messageTag(initializer: MessageTag.Builder.() -> Unit): MessageTag { return MessageTag.builder().apply(initializer).build() } fun messageTagOf(name: String, value: String) = messageTag { name(name) value(value) }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
1,540
bluetape4k
MIT License
src/main/kotlin/io/openfuture/chain/core/component/StatePool.kt
OpenFuturePlatform
135,143,034
false
{"Kotlin": 466643, "Dockerfile": 210, "Shell": 74}
package io.openfuture.chain.core.component import io.openfuture.chain.core.model.entity.state.State import io.openfuture.chain.crypto.util.HashUtils import org.bouncycastle.pqc.math.linearalgebra.ByteUtils import org.springframework.stereotype.Component import java.util.concurrent.ConcurrentHashMap @Component class StatePool { private val pool: MutableMap<String, State> = ConcurrentHashMap() fun getPool(): Map<String, State> = pool fun getStates(): List<State> = pool.values.toList() fun get(address: String): State? = pool[address] fun update(state: State): State? { state.hash = ByteUtils.toHexString(HashUtils.doubleSha256(state.getBytes())) return pool.put(state.address, state) } fun clear() { pool.clear() } }
2
Kotlin
16
64
f7e511b3ba17cc75d7f23618008dd89a7b83c4c0
785
open-chain
MIT License
dekorator-api/src/main/kotlin/io/github/mottljan/api/util/TryCoroutine.kt
mottljan
391,745,665
false
null
package io.github.mottljan.api.util import kotlinx.coroutines.CancellationException /** * tryCoroutine/catch DSL enables to try/catch the exceptions thrown from the suspend functions * exactly the same like by using standard try/catch blocks with the difference that it does not * catch [CancellationException] and automatically rethrows it to the caller. Same as try/catch, it * can serve either as a statement or an expression. */ // suspend is intentional to force usage only in coroutines since normal functions should use classic try/catch @Suppress("TooGenericExceptionCaught") internal suspend inline fun <T> tryCoroutine(tryBlock: () -> T): TryCoroutineResult<T> { return try { TryCoroutineResult.Success(tryBlock()) } catch (e: Throwable) { TryCoroutineResult.Error(e) } } internal sealed class TryCoroutineResult<out T> { data class Success<T>(val result: T) : TryCoroutineResult<T>() data class Error<T>(val throwable: Throwable) : TryCoroutineResult<T>() } internal inline infix fun <T> TryCoroutineResult<T>.catch(catchBlock: (Throwable) -> T): T = when (this) { is TryCoroutineResult.Success -> result is TryCoroutineResult.Error -> { if (throwable is CancellationException) throw throwable else catchBlock(throwable) } }
1
Kotlin
0
18
5f2f03dbbe82e943fcb96bac5639dedf50bf4c5b
1,303
grpc-dekorator
Apache License 2.0
multiplatform/src/commonMain/kotlin/com/vsevolodganin/clicktrack/utils/parcelable/Parcelable.kt
vganin
293,315,190
false
{"Kotlin": 627064, "C++": 4113, "Ruby": 2549, "Swift": 526, "CMake": 281}
@file:Suppress("DEPRECATION") // FIXME: Look into Parcelize not working with K2 package com.vsevolodganin.clicktrack.utils.parcelable import com.arkivanov.essenty.parcelable.Parcelable import com.arkivanov.essenty.parcelable.Parceler // FIXME: Workarounds problems with K2: https://issuetracker.google.com/issues/315775835#comment16 @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) expect annotation class Parcelize() @Retention(AnnotationRetention.SOURCE) @Repeatable @Target(AnnotationTarget.CLASS, AnnotationTarget.PROPERTY) expect annotation class TypeParceler<T, P : Parceler<in T>>() @Target(AnnotationTarget.PROPERTY) @Retention(AnnotationRetention.SOURCE) expect annotation class IgnoredOnParcel() typealias Parcelable = Parcelable typealias Parceler<T> = Parceler<T>
10
Kotlin
1
22
e0de3d92ee1921eda2053064fd4ae082b831caa9
804
click-track
Apache License 2.0
app/src/main/java/com/payment/app/utils/Rtc.kt
thearistotlemethod
818,344,304
false
{"Kotlin": 254976, "Java": 939}
package com.payment.app.utils import java.util.Calendar class Rtc { var year: Byte = 0 var mon: Byte = 0 var day: Byte = 0 var hour: Byte = 0 var min: Byte = 0 var sec: Byte = 0 var dow: Byte = 0 companion object { fun now(): Rtc { val calendar = Calendar.getInstance() val rtc = Rtc() rtc.year = ((calendar.get(1) % 100).toByte()) rtc.mon = ((calendar.get(2) + 1).toByte()) rtc.day = calendar.get(5).toByte() rtc.hour = calendar.get(11).toByte() rtc.min = calendar.get(12).toByte() rtc.sec = calendar.get(13).toByte() return rtc } } }
0
Kotlin
0
0
47035b2775e35a021c3891721810553ae8700413
698
BasePosAppTemplate
Apache License 2.0
src/main/kotlin/com/nosuchdevice/XoneK2ExtensionDefinition.kt
thorinside
449,010,008
false
null
package com.nosuchdevice import com.bitwig.extension.api.PlatformType import com.bitwig.extension.controller.AutoDetectionMidiPortNamesList import com.bitwig.extension.controller.ControllerExtension import com.bitwig.extension.controller.ControllerExtensionDefinition import com.bitwig.extension.controller.api.ControllerHost import java.util.* class XoneK2ExtensionDefinition : ControllerExtensionDefinition() { override fun getName(): String = "XoneK2" override fun getAuthor(): String = "thorinside" override fun getVersion(): String = "0.0.1" override fun getId(): UUID = UUID.fromString("bb39163a-5b61-4548-908d-f4fed5b39786") override fun getRequiredAPIVersion(): Int = 15 override fun getHardwareVendor(): String = "Allen & Heath" override fun getHardwareModel(): String = "XONE:K2" override fun getNumMidiInPorts(): Int = 1 override fun getNumMidiOutPorts(): Int = 1 override fun listAutoDetectionMidiPortNames(list: AutoDetectionMidiPortNamesList, platformType: PlatformType) { when (platformType) { PlatformType.WINDOWS -> { // TODO: Set the correct names of the ports for auto detection on Windows platform here // and uncomment this when port names are correct. // list.add(new String[]{"Input Port 0"}, new String[]{"Output Port 0"}); } PlatformType.MAC -> { list.add(arrayOf("XONE:K2"), arrayOf("XONE:K2")); } PlatformType.LINUX -> { // TODO: Set the correct names of the ports for auto detection on Windows platform here // and uncomment this when port names are correct. // list.add(new String[]{"Input Port 0"}, new String[]{"Output Port 0"}); } } } override fun createInstance(host: ControllerHost): ControllerExtension { return XoneK2Extension(this, host) } }
0
Kotlin
0
0
30ae6cef0991faab0c1cecd536e852245954366d
1,950
bitwig_xone_k2_kotlin
The Unlicense
app/src/main/kotlin/ru/khiraevmalik/theguardiannews/mvi_base/CoroutinesMviViewModel.kt
Hiraev
278,637,711
false
null
package ru.khiraevmalik.theguardiannews.mvi_base import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import ru.khiraevmalik.theguardiannews.CoroutinesViewModel import ru.khiraevmalik.theguardiannews.mvi_no_reactive.Store import ru.khiraevmalik.theguardiannews.mvi_no_reactive.lifecycle.SingleLiveData abstract class CoroutinesMviViewModel<A, U, E, S, Ev>( private val store: Store<A, U, E, S, Ev> ) : CoroutinesViewModel() where U : A, E : A { private val mState = MutableLiveData<S>() private val mEvents = SingleLiveData<Ev>() val state: LiveData<S> = mState val events: LiveData<Ev> = mEvents init { store.setOnStateChangeListener { newState -> mState.postValue(newState) } store.setEventsListener { event -> mEvents.postValue(event) } } override fun onCleared() { super.onCleared() store.dispose() } fun proceed(action: A) { store.proceed(action) } }
0
Kotlin
0
0
19ce6605f1d8c33def4d0a70340c8e75bd4c9a20
1,016
TheGuardianNews
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kbsky/util/json/JsonElementUtil.kt
uakihir0
735,265,237
false
{"Kotlin": 221471, "Shell": 1425, "Makefile": 315}
package work.socialhub.kbsky.util.json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive object JsonElementUtil { fun JsonElement.type(): String? { return jsonObject["\$type"]?.jsonPrimitive?.content } }
3
Kotlin
1
7
ff9e1649652acb85c3aabda7d1709a47e02ceb02
311
kbsky
MIT License
app/src/main/java/ru/haroncode/wordlearn/domain/repository/WordAssetRepository.kt
Hukumister
182,296,995
false
null
package ru.haroncode.wordlearn.domain.repository import android.content.res.AssetManager import de.siegmar.fastcsv.reader.CsvReader import io.reactivex.Single import javax.inject.Inject import ru.haroncode.wordlearn.word.model.Word /** * @author HaronCode. */ interface WordAssetRepository { fun findAllFor(categoryId: Long): Single<List<Word>> } class WordAssetRepositoryImpl @Inject constructor( private val assetManager: AssetManager, private val csvReader: CsvReader ) : WordAssetRepository { companion object { private const val WORDS_FILE_NAME = "words.csv" } override fun findAllFor(categoryId: Long): Single<List<Word>> = Single.never() }
0
Kotlin
0
5
1b98049eace38ed832f1ff41ddccd50b37b0f611
687
WordLearn
MIT License
seskar/seskar-compiler-plugin/src/main/kotlin/seskar/compiler/key/extensions/DefaultKeyExtension.kt
turansky
279,976,108
false
{"Kotlin": 93979, "Shell": 286}
package seskar.compiler.key.extensions import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.platform.isJs import seskar.compiler.key.backend.DefaultKeyTransformer internal class DefaultKeyExtension : IrGenerationExtension { override fun generate( moduleFragment: IrModuleFragment, pluginContext: IrPluginContext, ) { pluginContext.platform ?.takeIf { it.isJs() } ?: return moduleFragment.transformChildren(DefaultKeyTransformer(pluginContext), null) } }
0
Kotlin
5
41
6ef30dfce12e2ff8b98c616a9113719fa9d787db
707
seskar
Apache License 2.0
qchatkit/src/main/java/com/netease/yunxin/kit/qchatkit/repo/model/QChatSystemNotificationInfo.kt
shine2008
608,936,203
true
{"Java Properties": 2, "Gradle Kotlin DSL": 5, "Shell": 1, "Markdown": 1, "Batchfile": 1, "INI": 2, "Proguard": 3, "Kotlin": 52, "Java": 206}
/* * Copyright (c) 2022 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be * found in the LICENSE file. */ package com.netease.yunxin.kit.qchatkit.repo.model sealed class QChatSystemMessageToTypeInfo object Server : QChatSystemMessageToTypeInfo() object Channel : QChatSystemMessageToTypeInfo() object ServerAccIds : QChatSystemMessageToTypeInfo() object ChannelAccIds : QChatSystemMessageToTypeInfo() object AccIds : QChatSystemMessageToTypeInfo() sealed class QChatSystemNotificationTypeInfo object ServerMemberInvite : QChatSystemNotificationTypeInfo() object ServerMemberInviteReject : QChatSystemNotificationTypeInfo() object ServerMemberApply : QChatSystemNotificationTypeInfo() object ServerMemberApplyReject : QChatSystemNotificationTypeInfo() object ServerCreate : QChatSystemNotificationTypeInfo() object ServerRemove : QChatSystemNotificationTypeInfo() object ServerUpdate : QChatSystemNotificationTypeInfo() object ServerMemberInviteDone : QChatSystemNotificationTypeInfo() object ServerMemberInviteAccept : QChatSystemNotificationTypeInfo() object ServerMemberApplyDone : QChatSystemNotificationTypeInfo() object ServerMemberApplyAccept : QChatSystemNotificationTypeInfo() object ServerMemberKick : QChatSystemNotificationTypeInfo() object ServerMemberLeave : QChatSystemNotificationTypeInfo() object ServerMemberUpdate : QChatSystemNotificationTypeInfo() object ChannelCreate : QChatSystemNotificationTypeInfo() object ChannelRemove : QChatSystemNotificationTypeInfo() object ChannelUpdate : QChatSystemNotificationTypeInfo() object ChannelUpdateWhiteBlackRole : QChatSystemNotificationTypeInfo() object ChannelUpdateWhiteBlackRoleMember : QChatSystemNotificationTypeInfo() object ChannelUpdateQuickComment : QChatSystemNotificationTypeInfo() object ChannelCategoryCreate : QChatSystemNotificationTypeInfo() object ChannelCategoryRemove : QChatSystemNotificationTypeInfo() object ChannelCategoryUpdate : QChatSystemNotificationTypeInfo() object ChannelCategoryUpdateWhiteBlackRole : QChatSystemNotificationTypeInfo() object ChannelCategoryUpdateWhiteBlackMember : QChatSystemNotificationTypeInfo() object ServerRoleMemberAdd : QChatSystemNotificationTypeInfo() object ServerRoleMemberDelete : QChatSystemNotificationTypeInfo() object ServerRoleAuthUpdate : QChatSystemNotificationTypeInfo() object ChannelRoleAuthUpdate : QChatSystemNotificationTypeInfo() object MemberRoleAuthUpdate : QChatSystemNotificationTypeInfo() object ChannelVisibilityUpdate : QChatSystemNotificationTypeInfo() object ServerEnterLeave : QChatSystemNotificationTypeInfo() object ServerMemberJoinByInviteCode : QChatSystemNotificationTypeInfo() object VisitorChannelVisibilityUpdate : QChatSystemNotificationTypeInfo() object MyMemberInfoUpdate : QChatSystemNotificationTypeInfo() object Custom : QChatSystemNotificationTypeInfo() class QChatSystemNotificationInfo( val serverId: Long?, val channelId: Long?, val toAccIds: List<String>?, val fromAccount: String?, val toType: QChatSystemMessageToTypeInfo?, val fromClientType: Int?, val fromDeviceId: String?, val fromNick: String?, val time: Long?, val updateTime: Long?, val type: QChatSystemNotificationTypeInfo?, val msgIdClient: String?, val msgIdServer: String?, val body: String?, val attach: String?, val attachment: Any?, val extension: String?, val status: Int?, val pushPayload: String?, val pushContent: String?, val isPersistEnable: Boolean? ) { override fun toString(): String { return "QChatSystemNotificationInfo(serverId=$serverId, channelId=$channelId, toAccIds=$toAccIds, fromAccount=$fromAccount, toType=$toType, fromClientType=$fromClientType, fromDeviceId=$fromDeviceId, fromNick=$fromNick, time=$time, updateTime=$updateTime, type=$type, msgIdClient=$msgIdClient, msgIdServer=$msgIdServer, body=$body, attach=$attach, attachment=$attachment, extension=$extension, status=$status, pushPayload=$pushPayload, pushContent=$pushContent, isPersistEnable=$isPersistEnable)" } }
0
Java
0
0
9058d04b2d04d8d2ffad9fdda4d0d377ab90e50b
4,091
qchat-uikit-android
MIT License
src/main/kotlin/com/team2898/robot/subsystems/Climb.kt
TheFlyingHedgehogs
446,919,594
false
null
package com.team2898.robot.subsystems import com.bpsrobotics.engine.controls.StallDetection import com.bpsrobotics.engine.utils.Millis import com.bpsrobotics.engine.utils.Volts import com.bpsrobotics.engine.utils.plus import com.bpsrobotics.engine.utils.seconds import com.ctre.phoenix.motorcontrol.NeutralMode import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX import com.team2898.robot.Constants.CLIMBER_ENDSTOP_L import com.team2898.robot.Constants.CLIMBER_ENDSTOP_R import com.team2898.robot.RobotMap.CLIMBER_LEFT_ENCODER_A import com.team2898.robot.RobotMap.CLIMBER_LEFT_ENCODER_B import com.team2898.robot.RobotMap.CLIMBER_LEFT_LIMIT_SWITCH import com.team2898.robot.RobotMap.CLIMBER_LEFT_MAIN import com.team2898.robot.RobotMap.CLIMBER_LEFT_SECONDARY import com.team2898.robot.RobotMap.CLIMBER_RIGHT_ENCODER_A import com.team2898.robot.RobotMap.CLIMBER_RIGHT_ENCODER_B import com.team2898.robot.RobotMap.CLIMBER_RIGHT_LIMIT_SWITCH import com.team2898.robot.RobotMap.CLIMBER_RIGHT_MAIN import com.team2898.robot.RobotMap.CLIMBER_RIGHT_SECONDARY import edu.wpi.first.util.sendable.SendableBuilder import edu.wpi.first.wpilibj.* import edu.wpi.first.wpilibj2.command.SubsystemBase object Climb : SubsystemBase() { private val leftArmMain = WPI_TalonSRX(CLIMBER_LEFT_MAIN) private val leftArmSecondary = WPI_TalonSRX(CLIMBER_LEFT_SECONDARY) private val rightArmMain = WPI_TalonSRX(CLIMBER_RIGHT_MAIN) private val rightArmSecondary = WPI_TalonSRX(CLIMBER_RIGHT_SECONDARY) init { listOf(leftArmMain, leftArmSecondary, rightArmMain, rightArmSecondary).forEach { it.configFactoryDefault() it.configContinuousCurrentLimit(20) it.configPeakCurrentLimit(30, 50) it.setNeutralMode(NeutralMode.Brake) // it.enableVoltageCompensation(true) } rightArmMain.inverted = true rightArmSecondary.inverted = true } fun ignoreLimits() { leftArm.isZeroed = false rightArm.isZeroed = false } fun openLoop(value: Volts) { leftArm.openLoop(value) rightArm.openLoop(value) } private val leftArm = Arm( listOf(leftArmMain, leftArmSecondary), Encoder(CLIMBER_LEFT_ENCODER_A, CLIMBER_LEFT_ENCODER_B).apply { this.setReverseDirection(false) }, DigitalInput(CLIMBER_LEFT_LIMIT_SWITCH), CLIMBER_ENDSTOP_L, true ) private val rightArm = Arm( listOf(rightArmMain, rightArmSecondary), Encoder(CLIMBER_RIGHT_ENCODER_A, CLIMBER_RIGHT_ENCODER_B).apply { this.setReverseDirection(true) }, DigitalInput(CLIMBER_RIGHT_LIMIT_SWITCH), CLIMBER_ENDSTOP_R, true ) // private val piston1 = DoubleSolenoid(PneumaticsModuleType.REVPH, CLIMB_L_FORWARD, CLIMB_L_REVERSE) // private val piston2 = DoubleSolenoid(PneumaticsModuleType.REVPH, CLIMB_R_FORWARD, CLIMB_R_REVERSE) fun pistons(value: DoubleSolenoid.Value) { // piston1.set(value) // piston2.set(value) Intake.openIntake() } private class Arm( private val motors: List<WPI_TalonSRX>, val encoder: Encoder, private val limitSwitch: DigitalInput, private val endStop: Int, private val invertedLimitSwitch: Boolean = false ) { private var lastLimitSwitchValue = false private val stallDetector = StallDetection(Millis(1000)) private var stallTimeout = 0.seconds val limitSwitchv get() = if (invertedLimitSwitch) !limitSwitch.get() else limitSwitch.get() var isZeroed = false var isResetting = false fun openLoop(value: Volts) { isResetting = false motors.forEach { it.setVoltage(value.value.run { when { limitSwitchv /*|| (encoder.get() <= 0.0 && isZeroed)*/ -> coerceAtLeast(0.0) // encoder.get() >= endStop -> coerceAtMost(0.0) else -> this } }) } } fun update() { // if (stallDetector.isStalled(motors.first().motorOutputPercent, encoder.distance)) { // System.err.println("STALLED CLIMB, DISABLING FOR 5 SECONDS") // stallTimeout = Timer.getFPGATimestamp().seconds + 5.seconds // } if (Timer.getFPGATimestamp() < stallTimeout.value) { motors.forEach { it.set(0.0) } return } val limitSwitchValue = limitSwitchv val leadingEdge = limitSwitchValue && !lastLimitSwitchValue lastLimitSwitchValue = limitSwitchValue if (leadingEdge) { isZeroed = true encoder.reset() } if (!isResetting) { if ((limitSwitchValue /*|| (encoder.get() <= 0.0 && isZeroed)*/) && motors.first().motorOutputPercent < 0) { motors.forEach { it.set(0.0) } } // if (encoder.get() >= endStop && motors.first().motorOutputPercent > 0) { // motors.forEach { it.set(0.0) } // } } } fun resetClimb() { isResetting = true motors.forEach { it.set(-0.2) } } } override fun periodic() { leftArm.update() rightArm.update() } fun resetClimb() { leftArm.resetClimb() rightArm.resetClimb() } override fun initSendable(builder: SendableBuilder) { builder.setSmartDashboardType("Subsystem") builder.addDoubleProperty("left encoder", leftArm.encoder::getDistance) {} builder.addDoubleProperty("right encoder", rightArm.encoder::getDistance) {} builder.addBooleanProperty("left limit switch", leftArm::limitSwitchv) {} builder.addBooleanProperty("right limit switch", rightArm::limitSwitchv) {} } }
0
Kotlin
0
1
6e35698cf194d7cdbec05ecee8873f0c16fabeb5
5,900
2022-rapid-react
Apache License 2.0
app/src/main/java/me/kmmiller/theduckypodcast/main/surveys/ChartAdapter.kt
kmmiller10
156,945,292
false
null
package me.kmmiller.theduckypodcast.main.surveys import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.mikephil.charting.charts.BarChart import com.github.mikephil.charting.charts.PieChart import me.kmmiller.theduckypodcast.R import me.kmmiller.theduckypodcast.databinding.BarChartViewHolderBinding import me.kmmiller.theduckypodcast.databinding.PieChartViewHolderBinding import me.kmmiller.theduckypodcast.models.BarChartData import me.kmmiller.theduckypodcast.models.BaseChartData import me.kmmiller.theduckypodcast.models.PieChartData import me.kmmiller.theduckypodcast.utils.set class ChartAdapter(private val items: ArrayList<BaseChartData>) : RecyclerView.Adapter<BaseChartViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseChartViewHolder { val inflater = LayoutInflater.from(parent.context) return when(viewType) { BaseChartData.Type.BAR.ordinal -> BarChartViewHolder(BarChartViewHolderBinding.inflate(inflater, parent, false)) BaseChartData.Type.PIE.ordinal -> PieChartViewHolder(PieChartViewHolderBinding.inflate(inflater, parent, false)) else -> BarChartViewHolder(BarChartViewHolderBinding.inflate(inflater, parent, false)) // Default to bar chart } } override fun onBindViewHolder(holder: BaseChartViewHolder, position: Int) { val item = items[position] holder.setTitle(item.title) holder.setTotalResponseCount(item.totalResponseCount) when(item.getType()) { BaseChartData.Type.BAR -> { val bar = item as BarChartData (holder as BarChartViewHolder).setChart(bar.chart) } BaseChartData.Type.PIE -> { val pie = item as PieChartData (holder as PieChartViewHolder).setChart(pie.chart) } } } override fun getItemViewType(position: Int): Int = items[position].getType().ordinal override fun getItemCount(): Int = items.size inner class BarChartViewHolder(private val binding: BarChartViewHolderBinding) : BaseChartViewHolder(binding.root) { override fun setTitle(title: String) { binding.title.text = title } override fun setTotalResponseCount(totalResponseCount: Int) { binding.yAxisLabel.text = String.format(binding.root.context.getString(R.string.responses), totalResponseCount) } fun setChart(chart: BarChart) { binding.chart.set(chart) } } inner class PieChartViewHolder(private val binding: PieChartViewHolderBinding) : BaseChartViewHolder(binding.root) { override fun setTitle(title: String) { binding.title.text = title } override fun setTotalResponseCount(totalResponseCount: Int) { binding.responseCountLabel.text = String.format(binding.root.context.getString(R.string.responses), totalResponseCount) } fun setChart(chart: PieChart) { binding.chart.set(chart) } } }
7
Kotlin
1
1
7f00dbeacb9b96a783206647b0c7cc41bedff0c3
3,131
TheDuckyPodcast
Apache License 2.0
app/src/main/java/me/kmmiller/theduckypodcast/main/surveys/ChartAdapter.kt
kmmiller10
156,945,292
false
null
package me.kmmiller.theduckypodcast.main.surveys import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.mikephil.charting.charts.BarChart import com.github.mikephil.charting.charts.PieChart import me.kmmiller.theduckypodcast.R import me.kmmiller.theduckypodcast.databinding.BarChartViewHolderBinding import me.kmmiller.theduckypodcast.databinding.PieChartViewHolderBinding import me.kmmiller.theduckypodcast.models.BarChartData import me.kmmiller.theduckypodcast.models.BaseChartData import me.kmmiller.theduckypodcast.models.PieChartData import me.kmmiller.theduckypodcast.utils.set class ChartAdapter(private val items: ArrayList<BaseChartData>) : RecyclerView.Adapter<BaseChartViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseChartViewHolder { val inflater = LayoutInflater.from(parent.context) return when(viewType) { BaseChartData.Type.BAR.ordinal -> BarChartViewHolder(BarChartViewHolderBinding.inflate(inflater, parent, false)) BaseChartData.Type.PIE.ordinal -> PieChartViewHolder(PieChartViewHolderBinding.inflate(inflater, parent, false)) else -> BarChartViewHolder(BarChartViewHolderBinding.inflate(inflater, parent, false)) // Default to bar chart } } override fun onBindViewHolder(holder: BaseChartViewHolder, position: Int) { val item = items[position] holder.setTitle(item.title) holder.setTotalResponseCount(item.totalResponseCount) when(item.getType()) { BaseChartData.Type.BAR -> { val bar = item as BarChartData (holder as BarChartViewHolder).setChart(bar.chart) } BaseChartData.Type.PIE -> { val pie = item as PieChartData (holder as PieChartViewHolder).setChart(pie.chart) } } } override fun getItemViewType(position: Int): Int = items[position].getType().ordinal override fun getItemCount(): Int = items.size inner class BarChartViewHolder(private val binding: BarChartViewHolderBinding) : BaseChartViewHolder(binding.root) { override fun setTitle(title: String) { binding.title.text = title } override fun setTotalResponseCount(totalResponseCount: Int) { binding.yAxisLabel.text = String.format(binding.root.context.getString(R.string.responses), totalResponseCount) } fun setChart(chart: BarChart) { binding.chart.set(chart) } } inner class PieChartViewHolder(private val binding: PieChartViewHolderBinding) : BaseChartViewHolder(binding.root) { override fun setTitle(title: String) { binding.title.text = title } override fun setTotalResponseCount(totalResponseCount: Int) { binding.responseCountLabel.text = String.format(binding.root.context.getString(R.string.responses), totalResponseCount) } fun setChart(chart: PieChart) { binding.chart.set(chart) } } }
7
Kotlin
1
1
7f00dbeacb9b96a783206647b0c7cc41bedff0c3
3,131
TheDuckyPodcast
Apache License 2.0
app/src/test/kotlin/net/primal/android/networking/relays/RelaysManagerTest.kt
PrimalHQ
639,579,258
false
null
package net.primal.android.networking.relays import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import net.primal.android.core.coroutines.CoroutinesTestRule import net.primal.android.test.advanceUntilIdleAndDelay import net.primal.android.user.accounts.active.ActiveAccountStore import net.primal.android.user.accounts.active.ActiveUserAccountState import net.primal.android.user.domain.Relay import net.primal.android.user.domain.UserAccount import okhttp3.OkHttpClient import org.junit.Rule import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class RelaysManagerTest { @get:Rule val coroutinesTestRule = CoroutinesTestRule() private val invalidRelays = listOf( Relay(url = "abcdefghijkl", true, true), Relay(url = "wss://nostr-relay.untethr.me\t", true, true), Relay(url = "⬤ wss://nostr-pub.wellorder.net", true, true), Relay(url = "wss://filter.nostr.wine/npubxyz\n", true, true), ) private fun buildRelayPoolFactory( relays: List<Relay> = emptyList() ) = mockk<RelayPoolFactory>() { every { create(any()) } returns RelayPool( dispatchers = coroutinesTestRule.dispatcherProvider, relays = relays, okHttpClient = OkHttpClient() ) } private fun buildActiveAccountStore( relays: List<Relay> = emptyList() ) = mockk<ActiveAccountStore>(relaxed = true) { every { activeAccountState } returns flowOf( ActiveUserAccountState.ActiveUserAccount( data = UserAccount .buildLocal(pubkey = "") .copy(relays = relays) ) ) } @Test fun `invalid relays does not cause the crash`() = runTest { RelaysManager( relayPoolFactory = buildRelayPoolFactory(relays = invalidRelays), activeAccountStore = buildActiveAccountStore(relays = invalidRelays), ) advanceUntilIdleAndDelay() } }
23
null
6
75
28904131060311b08176729c5146feea39c549fc
2,100
primal-android-app
MIT License
app/src/main/java/com/niedzwiecki/przemyslguide/ui/base/BaseViewModel.kt
niedzwiedz90
136,378,890
false
null
package com.niedzwiecki.przemyslguide.ui.base import android.databinding.BaseObservable import android.os.Bundle /** * Created by niedzwiedz on 29.06.17. */ open class BaseViewModel<T : Navigator> : BaseObservable(), ViewModel { internal var navigator: Navigator? = null private var context: T? = null val isNavigatorAttached: Boolean get() = navigator != null override fun attachNavigator(navigator: Navigator) { this.navigator = navigator } override fun detachNavigator() { navigator = null } override fun onActivityResult(navigator: Navigator, requestCode: Int, resultCode: Int, data: Bundle) { } override fun onDestroy() { } override fun onCreate() { } override fun saveInstanceState(bundle: Bundle) { } override fun restoreInstanceState(bundle: Bundle) { } override fun attachContext(context: Navigator) { this.context = context as T } fun getNavigator(): Navigator? { checkNavigatorAttached() return navigator } fun checkNavigatorAttached() { if (!isNavigatorAttached) throw MvpViewNotAttachedException() } fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray, activity: BaseActivity) { } class MvpViewNotAttachedException : RuntimeException("Please call attachNavigator(Context) before" + " requesting data to the ViewModel") }
1
null
1
1
5b8ca41c275cb873a229a4c20110248f61e7b19a
1,468
CityGuide
Apache License 2.0
src/test/kotlin/just4fun/holomorph/mains/Discovery.kt
just-4-fun
105,437,872
false
null
package just4fun.holomorph.mains import just4fun.holomorph.DefineSchema import just4fun.holomorph.Type import just4fun.holomorph.Types import just4fun.holomorph.types.CollectionType import just4fun.holomorph.mains.javas.Point4d import just4fun.holomorph.measureTime import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.full.memberProperties import kotlin.reflect.full.starProjectedType val N = 10 fun main(a: Array<String>) { measurePrims() measureString() measurePrimArrays() measureArrayPrims() measureArrayAny() measureArrayString() measureArrayUnknown() measureCollStandard() measureArrayList() measureMap() measureUnit() measureMix1() measureEnum() discover(listOf("ok")::class.starProjectedType)// converts to java.utils... some private class // class Obj(@DefineSchema(arrayOf("x", "y", "z", "w")) val point: Point4d, val a: Int, val b: Int) discover(Obj::class.starProjectedType) } fun discover(types: List<KType>) = types.forEach { discover(it) } fun discover(type: KType) = Types.resolve(type, type.classifier as KClass<*>) ?: println("Failed dicovery of $type") fun types(klas: KClass<*>) = klas.memberProperties.map { it.returnType } fun measurePrims() { val klasses = listOf(Int::class, Long::class, Short::class, Byte::class, Double::class, Float::class, Char::class, Boolean::class) val types = klasses.map { it.starProjectedType } measureTime("PRIMS", N) { discover(types) } }//20000 ns /8 fun measureString() { //val type = java.lang.String::class.starProjectedType val type = String::class.starProjectedType measureTime("STRING", N) { discover(type) } }//4000 ns fun measurePrimArrays() { val klasses = listOf(IntArray::class, LongArray::class, ShortArray::class, ByteArray::class, DoubleArray::class, FloatArray::class, CharArray::class, BooleanArray::class) val types = klasses.map { it.starProjectedType }// turns all to Array<*> measureTime("PRIM ARRs", N) { discover(types) } }//40000 ns /8 fun measureArrayPrims() { class Obj(val v1: Array<Int>, val v2: Array<Long>, val v3: Array<Short>, val v4: Array<Byte>, val v5: Array<Double>, val v6: Array<Float>, val v7: Array<Char>, val v8: Array<Boolean>) measureTime("ARR PRIMs", N) { discover(types(Obj::class)) } }//50000 ns /8 fun measureArrayAny() { class Obj(val v1: Array<Any?>) measureTime("ARR ANY", N) { discover(types(Obj::class)) } }//10000 ns fun measureArrayString() { //val setArray = run{ PropType.cache.add(ARRAYof(STRING))} class Obj(val v1: Array<String?>) measureTime("ARR STR", N) { discover(types(Obj::class)) } }//10000 ns fun measureArrayUnknown() { class Obj(val v1: Array<Obj>, val v2: Array<Obj?>) measureTime("ARR ???", N) { discover(types(Obj::class)) } }//11000 ns fun measureCollStandard() { class Obj(val v1: List<Int?>, val v2: MutableList<Int>, val v3: Set<Int?>, val v4: MutableSet<Int>) measureTime("COLL STD ANY", N) { discover(types(Obj::class)) } }//105000 ns /4 fun measureArrayList() { class Obj(val v1: ArrayList<Int?>, val v2: ArrayList<Obj?>) @Suppress("UNCHECKED_CAST") class AListType<E: Any>(elementType: Type<E>): CollectionType<ArrayList<*>, E>(ArrayList::class, elementType) { override fun newInstance(): ArrayList<E> = ArrayList() override fun addElement(e: E?, index: Int, seq: ArrayList<*>): ArrayList<E> = (seq as ArrayList<E>).also { (it as ArrayList<E?>) += e } } Types.defineType(ArrayList::class) { et -> AListType(et[0]) } measureTime("ARRLIST ANY", N) { discover(types(Obj::class)) } }//140000 ns /2 fun measureMap() { class Obj(val v1: MutableMap<String, Any>, val v2: Map<String, Any?>) measureTime("MAP ANY", N) { discover(types(Obj::class)) } }//55000 ns /2 fun measureUnit() { //class UnitObj(val v1: Unit) class Obj(val v1: Unit, val v2: java.lang.Void) measureTime("UNIT", N) { discover(types(Obj::class)) } }//26000 ns fun measureMix1() { class Obj(val v0: Int, val v1: Long, val v2: Short, val v3: Byte, val v4: Char, val v5: Double, val v6: Float, val v7: Boolean, val v8: String?) measureTime("MIX 1", N) { discover(types(Obj::class)) } }//30000 ns /8 enum class Vals {OK, FAIL } fun measureEnum() { class Obj(val v0: Vals) measureTime("ENUM", N) { discover(types(Obj::class)) } }//30000 ns /8
0
Kotlin
1
2
5cbeb6827417670626f083f5f71e31da5fa55eab
4,269
holomorph
Apache License 2.0
src/client/kotlin/xveon/roadmap/core/RoadmapScanner.kt
XVNexus
633,999,690
false
null
package xveon.roadmap import net.minecraft.client.network.ClientPlayerEntity class RoadmapScanner(val roadmap: Roadmap) { fun scan(player: ClientPlayerEntity): Boolean { // Used to keep track of which blocks are scanned and store a queue of blocks waiting to be scanned val tracker = ScannedBlockTracker(roadmap) val originBlock = UtilClient.getFloorBlockAtPos(player.blockPos, Pair(Config["scan_height"] as Int, 0), player) ?: return false if (!originBlock.isRoad) return false originBlock.clearance = UtilClient.getClearanceOfBlock(originBlock, Config["scan_height"] as Int, player) roadmap.setBlock(originBlock) roadmap.removeMarker(originBlock.pos, RoadmapMarkerType.CUTOFF_POINT) tracker.markPosScanned(originBlock.pos) tracker.enqueuePendingPositions(UtilClient.getAdjacentPositions(originBlock.pos)) var i = 0 while (tracker.hasPendingPositions()) { i++ val nextPendingPos = tracker.dequeuePendingPos() if (!UtilClient.isPosInRange(nextPendingPos, Config["scan_radius"] as Double, player)) { if (!roadmap.containsBlock(nextPendingPos, Constants.MARKER_HEIGHT)) roadmap.addMarker(nextPendingPos, RoadmapMarkerType.CUTOFF_POINT) tracker.markPosScanned(nextPendingPos) continue } val nextScannedBlock = UtilClient.getFloorBlockAtPos(nextPendingPos, Pair(1, 1), player) if (nextScannedBlock == null) { roadmap.setBlock(RoadmapBlock(nextPendingPos, 0, "_")) roadmap.removeMarker(nextPendingPos, RoadmapMarkerType.CUTOFF_POINT) tracker.markPosScanned(nextPendingPos) continue } nextScannedBlock.clearance = UtilClient.getClearanceOfBlock(nextScannedBlock, Config["scan_height"] as Int, player) roadmap.setBlock(nextScannedBlock) roadmap.removeMarker(nextPendingPos, RoadmapMarkerType.CUTOFF_POINT) tracker.markPosScanned(nextScannedBlock.pos) if (nextScannedBlock.isRoad) tracker.enqueuePendingPositions(UtilClient.getAdjacentPositions(nextScannedBlock.pos)) if (i >= Constants.MAX_SCAN_ITERATIONS) { RoadmapClient.logger.warn("Scan reached ${Constants.MAX_SCAN_ITERATIONS} iterations, stopping early.") return true } } RoadmapClient.logger.info("Scan ran for ${i + 1} iterations.") return true } }
0
Kotlin
0
0
a03d400c26459f4a5fd8190723648971011c7f0f
2,578
roadmap
Apache License 2.0
app/src/main/java/com/shhatrat/loggerek/models/Cache.kt
Shhatrat
94,308,787
false
null
package com.shhatrat.loggerek.models /** * Created by szymon on 7/1/17. */ data class Cache( val name : String, val location : String, val type : String, val recommendations : Int, val founds : Int, val req_passwd : Boolean){ }
0
Kotlin
0
0
cf9c633915faa5e622c4d2b9bc9fbace520bfc07
278
Loggerek-old
Apache License 2.0
shared/src/main/java/de/loosetie/k8s/dsl/impls/Ingress.kt
loosetie
283,145,621
false
{"Kotlin": 12443871}
package de.loosetie.k8s.dsl.impls import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonPropertyOrder import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasParent import de.loosetie.k8s.dsl.manifests.* @JsonPropertyOrder("apiVersion", "kind", "metadata", "spec", "status") class Ingress_networking_k8s_io_v1beta1_k8s1_16Impl( @JsonIgnore override val parent: K8sManifest? = null ) : Ingress_networking_k8s_io_v1beta1_k8s1_16, HasParent { override lateinit var metadata: ObjectMeta_meta_v1_k8s1_16 override lateinit var spec: Ingressspec_networking_k8s_io_v1beta1_k8s1_16 override var status: Ingressstatus_networking_k8s_io_v1beta1_k8s1_16? = null } @JsonPropertyOrder("apiVersion", "kind", "metadata", "spec", "status") class Ingress_networking_k8s_io_v1beta1_k8s1_17Impl( @JsonIgnore override val parent: K8sManifest? = null ) : Ingress_networking_k8s_io_v1beta1_k8s1_17, HasParent { override lateinit var metadata: ObjectMeta_meta_v1_k8s1_17 override lateinit var spec: Ingressspec_networking_k8s_io_v1beta1_k8s1_17 override var status: Ingressstatus_networking_k8s_io_v1beta1_k8s1_17? = null } typealias Ingress_networking_k8s_io_v1beta1_k8s1_18Impl = Ingress_networking_k8s_io_v1beta1_k8s1_17Impl @JsonPropertyOrder("apiVersion", "kind", "metadata", "spec", "status") class Ingress_networking_k8s_io_v1_k8s1_19Impl( @JsonIgnore override val parent: K8sManifest? = null ) : Ingress_networking_k8s_io_v1_k8s1_19, HasParent { override lateinit var metadata: ObjectMeta_meta_v1_k8s1_19 override lateinit var spec: Ingressspec_networking_k8s_io_v1_k8s1_19 override var status: Ingressstatus_networking_k8s_io_v1_k8s1_19? = null } typealias Ingress_networking_k8s_io_v1_k8s1_20Impl = Ingress_networking_k8s_io_v1_k8s1_19Impl typealias Ingress_networking_k8s_io_v1_k8s1_21Impl = Ingress_networking_k8s_io_v1_k8s1_20Impl
0
Kotlin
0
1
3dd2d00220dbf71151d56b75b3bd7f26583b1fd3
1,905
k8s-dsl
Apache License 2.0
owntracks-android-2.5/project/app/src/oss/java/org/owntracks/android/location/geofencing/GeofencingEvent.kt
wir3z
737,346,188
false
{"Kotlin": 928031, "Groovy": 374736, "Java": 12862, "Shell": 4540}
package org.owntracks.android.location.geofencing import android.content.Intent import android.location.Location data class GeofencingEvent( val errorCode: Int?, val geofenceTransition: Int?, val triggeringGeofences: List<Geofence>?, val triggeringLocation: Location? ) { fun hasError(): Boolean = true // OSS doesn't support triggering geofences with events, so we just return a stub with an error // code set companion object { @JvmStatic fun fromIntent(@Suppress("UNUSED_PARAMETER") intent: Intent): GeofencingEvent { return GeofencingEvent(1, null, null, null) } } }
0
Kotlin
3
5
ae982c61c5fcc5d809f4b29f0208c19cede61f5d
618
hubitat
Apache License 2.0
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/eventTime.kt
duanwucui
152,172,153
true
{"Kotlin": 267756}
// GENERATED package com.fkorotkov.kubernetes import io.fabric8.kubernetes.api.model.Event import io.fabric8.kubernetes.api.model.MicroTime fun Event.`eventTime`(block: MicroTime.() -> Unit = {}) { if(this.`eventTime` == null) { this.`eventTime` = MicroTime() } this.`eventTime`.block() }
0
Kotlin
0
0
4b9a21e59fad78ed7b79a94ac8993c1041623d18
305
k8s-kotlin-dsl
MIT License
app/src/main/java/com/eye/eye/ui/setting/AboutActivity.kt
HelloWorldFeng
282,585,640
false
null
package com.eye.eye.ui.setting import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Html import com.eye.eye.R import com.eye.eye.ui.common.ui.BaseActivity import com.eye.eye.ui.common.ui.WebViewActivity import com.eye.eye.ui.common.ui.WebViewActivity.Companion.DEFAULT_TITLE import com.eye.eye.ui.common.ui.WebViewActivity.Companion.DEFAULT_URL import com.eye.eye.util.GlobalUtil import kotlinx.android.synthetic.main.activity_about.* import kotlinx.android.synthetic.main.layout_title_bar.* /* * 关于界面 * */ class AboutActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) } override fun setupViews() { super.setupViews() tvTitle.text = GlobalUtil.getString(R.string.about) val version = "${GlobalUtil.getString(R.string.version)}${GlobalUtil.appVersionName}" tvAboutVersion.text = version tvThanksTips.text = String.format(GlobalUtil.getString(R.string.thanks_to),GlobalUtil.appName) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { tvOpenSourceList.text = Html.fromHtml("<u>" + GlobalUtil.getString(R.string.open_source_project_list) + "</u>", 0) }else{ tvOpenSourceList.text = Html.fromHtml("<u>" + GlobalUtil.getString(R.string.open_source_project_list) + "</u>") } ivLogo.setImageDrawable(GlobalUtil.getAppIcon()) btnEncourage.setOnClickListener { //转跳到GitHub主页 WebViewActivity.start(this,DEFAULT_TITLE,DEFAULT_URL,true) } tvOpenSourceList.setOnClickListener { OpenSourceProjectsActivity.start(this@AboutActivity) } } companion object { fun start(context: Context){ context.startActivity(Intent(context, AboutActivity::class.java)) } } }
0
Kotlin
0
0
4ca1b3b66266366b3ad6a2b64d8341f3fd946324
2,011
Eye
Apache License 2.0
app/src/main/java/com/eye/eye/ui/setting/AboutActivity.kt
HelloWorldFeng
282,585,640
false
null
package com.eye.eye.ui.setting import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Html import com.eye.eye.R import com.eye.eye.ui.common.ui.BaseActivity import com.eye.eye.ui.common.ui.WebViewActivity import com.eye.eye.ui.common.ui.WebViewActivity.Companion.DEFAULT_TITLE import com.eye.eye.ui.common.ui.WebViewActivity.Companion.DEFAULT_URL import com.eye.eye.util.GlobalUtil import kotlinx.android.synthetic.main.activity_about.* import kotlinx.android.synthetic.main.layout_title_bar.* /* * 关于界面 * */ class AboutActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) } override fun setupViews() { super.setupViews() tvTitle.text = GlobalUtil.getString(R.string.about) val version = "${GlobalUtil.getString(R.string.version)}${GlobalUtil.appVersionName}" tvAboutVersion.text = version tvThanksTips.text = String.format(GlobalUtil.getString(R.string.thanks_to),GlobalUtil.appName) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { tvOpenSourceList.text = Html.fromHtml("<u>" + GlobalUtil.getString(R.string.open_source_project_list) + "</u>", 0) }else{ tvOpenSourceList.text = Html.fromHtml("<u>" + GlobalUtil.getString(R.string.open_source_project_list) + "</u>") } ivLogo.setImageDrawable(GlobalUtil.getAppIcon()) btnEncourage.setOnClickListener { //转跳到GitHub主页 WebViewActivity.start(this,DEFAULT_TITLE,DEFAULT_URL,true) } tvOpenSourceList.setOnClickListener { OpenSourceProjectsActivity.start(this@AboutActivity) } } companion object { fun start(context: Context){ context.startActivity(Intent(context, AboutActivity::class.java)) } } }
0
Kotlin
0
0
4ca1b3b66266366b3ad6a2b64d8341f3fd946324
2,011
Eye
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/FunctionsOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/FunctionsOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val FunctionsOutlined: SvgIconComponent
12
Kotlin
5
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
216
kotlin-wrappers
Apache License 2.0
epoxyModels/src/main/java/de/mustafagercek/epoxybase_lib/util/ViewExtensions.kt
mustafagercek
191,807,577
false
null
package de.mustafagercek.epoxybase_lib.util import android.content.Context import android.util.TypedValue fun Context.dpToPx(dp: Int): Int { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics ).toInt() }
0
Kotlin
0
5
5bb19f874400764b632a47c7ca319fa8422ebb79
288
epoxy-base
Apache License 2.0
app/src/main/java/com/codepath/apps/restclienttemplate/models/User.kt
farhatc100
469,560,153
false
null
package com.codepath.apps.restclienttemplate.models import org.json.JSONObject class User { var name: String = "" var screeName: String = "" var publicImageUrl: String = "" companion object { fun fromJson(jsonObject: JSONObject): User { val user = User() user.name = jsonObject.getString("name") user.screeName = jsonObject.getString("screen_name") user.publicImageUrl = jsonObject.getString("profile_image_url_https") return user } } }
1
Kotlin
0
0
81c79022706a134c77f7c49209e96ae61034a3d5
538
SimpleTweet
Apache License 2.0
src/main/kotlin/com/waicool20/skrypton/sikulix/ISikuliRegion.kt
waicool20
103,044,311
false
null
/* * The MIT License (MIT) * * Copyright (c) SKrypton by waicool20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.waicool20.skrypton.sikulix import org.sikuli.script.* import java.awt.Rectangle import org.sikuli.script.Region /** * Interfaces that copies most of the [Region] APIs * Mainly used for allowing easy delegation of [SKryptonMatch] functions to [SKryptonRegion]. * See [here](http://doc.sikuli.org/region.html) for more information. */ interface ISikuliRegion { /** * Set location of this region. * * @param loc New location to set to. * @return Region with the new location */ fun setLocation(loc: Location): SKryptonRegion /** * Sets the Region of Interest, mainly used to speed up searches. */ fun setROI() /** * Sets the Region of Interest, mainly used to speed up searches. * * @param rect Sets the ROI to this rectangle. */ fun setROI(rect: Rectangle) /** * Sets the Region of Interest, mainly used to speed up searches. * * @param region Sets the ROI to this region. */ fun setROI(region: Region) /** * Sets the Region of Interest, mainly used to speed up searches. * * @param X x coordinate of top left corner of ROI * @param Y Y coordinate of top left corner of ROI * @param W Width of ROI * @param H Height of ROI */ fun setROI(X: Int, Y: Int, W: Int, H: Int) /** * Gets the center of the region. * * @return Center point. */ fun getCenter(): Location /** * Gets the top left location of the region. * * @return Top left point. */ fun getTopLeft(): Location /** * Gets the top right location of the region. * * @return Top right point. */ fun getTopRight(): Location /** * Gets the bottom left location of the region. * * @return Bottom left point. */ fun getBottomLeft(): Location /** * Gets the bottom right location of the region. * * @return Bottom right point. */ fun getBottomRight(): Location /** * Gets the last match matched in this region. * * @return Last match if found else null. */ fun getLastMatch(): SKryptonMatch? /** * Gets last matches matched in this region. * * @return [Iterator] of matches. May be empty. */ fun getLastMatches(): Iterator<SKryptonMatch> /** * Returns a new Region object, whose upper left corner is relocated adding the location’s x * and y value to the respective values of the given region. Width and height are the same. * So this clones a region at a different place. * * @param loc Location object to offset by * @return Region with offset coordinates. */ fun offset(loc: Location): SKryptonRegion /** * Creates a region grown to the given values in pixels. Negative values can be passed to * shrink instead. * * @param l Amount to grow on left side. * @param r Amount to grow on right side. * @param t Amount to grow on top side. * @param b Amount to grow on bottom side. * @return Grown region. */ fun grow(l: Int, r: Int, t: Int, b: Int): SKryptonRegion /** * Creates a region grown to the given values in pixels. Negative values can be passed to * shrink instead. * * @param w Amount to grow horizontally. * @param h Amount to grow vertically. * @return Grown region. */ fun grow(w: Int, h: Int): SKryptonRegion /** * Creates a region grown to the given values in pixels. Negative values can be passed to * shrink instead. * * @param range Amount to grow on each side. * @return Grown region. */ fun grow(range: Int): SKryptonRegion /** * Creates a region grown in pixels specified by [org.sikuli.basics.Settings.DefaultPadding]. * * @return Grown region. */ fun grow(): SKryptonRegion /** * Creates a new region containing both regions. * * @param region Region to unite with. * @return The combined region. */ fun union(region: Region): SKryptonRegion /** * Creates a region that is the intersection of the given regions. * * @param region The region to intersect with. * @return The intersected region. */ fun intersection(region: Region): SKryptonRegion /** * Gets the region above the top side with same width, the new region extends to the top screen * border. * * @return The above region. */ fun above(): SKryptonRegion /** * Gets the region below the bottom side with same width, the new region extends to the bottom * screen border. * * @return The below region. */ fun below(): SKryptonRegion /** * Gets the region left to the left side with same height, the new region extends to the left * screen border. * * @return The left region. */ fun left(): SKryptonRegion /** * Gets the region right to the right side with same height, the new region extends to the right * screen border. * * @return The right region. */ fun right(): SKryptonRegion /** * Gets the region above the top side with same width, the new region extends by `height` pixels. * * @param height Height of the new region. * @return The above region. */ fun above(height: Int): SKryptonRegion /** * Gets the region below the bottom side with same width, the new region extends by `height` pixels. * * @param height Height of the new region. * @return The below region. */ fun below(height: Int): SKryptonRegion /** * Gets the region left to the left side with same height, the new region extends by `width` pixels. * * @param width Width of the new region. * @return The left region. */ fun left(width: Int): SKryptonRegion /** * Gets the region right to the right side with same height, the new region extends by `width` pixels. * * @param width Width of the new region. * @return The right region. */ fun right(width: Int): SKryptonRegion //<editor-fold desc="Search operations"> /** * Finds the given target in the region and returns the best match. * If AutoWaitTimeout is set, this is equivalent to wait(). Otherwise only one search attempt * will be done. * * @param PSI [Pattern], [String] or [Image]. * @param target A search criteria. * @return Found element. * @throws FindFailed If the find operation failed. */ fun <PSI : Any> find(target: PSI): SKryptonMatch /** * Finds all occurrences of the given target in the region and returns an * [Iterator] of [SKryptonMatch]. * * @param PSI [Pattern], [String] or [Image]. * @param target A search criteria. * @return [Iterator] of matches. * @throws FindFailed If the find operation failed. */ fun <PSI : Any> findAll(target: PSI): Iterator<SKryptonMatch> /** * Waits for the target to appear until the AutoWaitTimeout value is exceeded. * * @param PSI [Pattern], [String] or [Image]. * @param target The target to search for. * @return The found match. * @throws FindFailed If the find operation finally failed. */ fun <PSI : Any> wait(target: PSI): SKryptonMatch /** * Waits for the target to appear or timeout (in second) is passed. * * @param PSI [Pattern], [String] or [Image]. * @param target The target to search for. * @param timeout Timeout in seconds. * @return The found match. * @throws FindFailed If the find operation finally failed. */ fun <PSI : Any> wait(target: PSI, timeout: Double): SKryptonMatch /** * Check if target exists (with the default autoWaitTimeout) * * @param PSI [Pattern], [String] or [Image]. * @param target The target to check for. * @return The found match, null if not found */ fun <PSI : Any> exists(target: PSI): SKryptonMatch? /** * Check if target exists (with the default autoWaitTimeout) * * @param PSI [Pattern], [String] or [Image]. * @param target The target to check for. * @return The found match, null if not found */ fun <PSI : Any> exists(target: PSI, timeout: Double): SKryptonMatch? //</editor-fold> //<editor-fold desc="Mouse and Keyboard Actions"> /** * Left click at the region's last successful match, uses center if there is no last match. * If region is a match, click targetOffset. * * @return 1 if possible, 0 otherwise. */ fun click(): Int /** * Attempts to find the target and click it. * * @param target Target to click. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> click(target: PFRML): Int /** * Attempts to find the target and click it with modifiers. * * @param target Target to click. * @param modifiers Modifiers to press while clicking. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> click(target: PFRML, modifiers: Int): Int /** * Like [click] but double that. */ fun doubleClick(): Int /** * Like [click] but double that. * * @param target Target to click. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> doubleClick(target: PFRML): Int /** * Like [click] but double that. * * @param target Target to click. * @param modifiers Modifiers to press while clicking. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> doubleClick(target: PFRML, modifiers: Int): Int /** * Like [click] but uses right mouse button instead. */ fun rightClick(): Int /** * Like [click] but uses right mouse button instead. * * @param target Target to click. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> rightClick(target: PFRML): Int /** * Like [click] but uses right mouse button instead. * * @param target Target to click. * @param modifiers Modifiers to press while clicking. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> rightClick(target: PFRML, modifiers: Int): Int /** * Move the mouse pointer to region's last successful match, uses center if no last match. * If region is a match, move to targetOffset. Same as [mouseMove]. * * @return 1 if possible, 0 otherwise. */ fun hover(): Int /** * Attempts to find the target and move the mouse pointer to it. * * @param target Target to move the pointer to. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> hover(target: PFRML): Int /** * Drags from region's last match and drop at given target using left mouse button. * * @param PFRML [Pattern], Filename ([String]), [Region], [Match] or [Location]. * @param target Target to drop at. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> dragDrop(target: PFRML): Int /** * Drag from a position and drop to another using left mouse button. * * @param PFRML [Pattern], Filename ([String]), [Region], [Match] or [Location]. * @param t1 Source position. * @param t2 Target position. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> dragDrop(t1: PFRML, t2: PFRML): Int /** * Initiates a mouse drag action. (Moves mouse to a location and presses without releasing) * * @param PFRML [Pattern], Filename ([String]), [Region], [Match] or [Location]. * @param target Location to start the mouse drag action * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> drag(target: PFRML): Int /** * Ends a mouse drop action. (Moves mouse to a location and releases the button) * * @param PFRML [Pattern], Filename ([String]), [Region], [Match] or [Location]. * @param target Location to release the mouse button. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> dropAt(target: PFRML): Int /** * Types the given text into the current caret position. Only ASCII characters are supported. * * @param text Text to type. * @return 1 if possible, 0 otherwise. */ fun type(text: String): Int /** * Types the given text into the current caret position. Only ASCII characters are supported. * * @param text Text to type. * @param modifiers Modifiers to press while typing. * @return 1 if possible, 0 otherwise. */ fun type(text: String, modifiers: String): Int /** * Types the given text into the current caret position. Only ASCII characters are supported. * * @param text Text to type. * @param modifiers Modifiers to press while typing. * @return 1 if possible, 0 otherwise. */ fun type(text: String, modifiers: Int): Int /** * Types the given text into the target. Only ASCII characters are supported. * * @param target Target to type into * @param text Text to type. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> type(target: PFRML, text: String): Int /** * Types the given text into the target. Only ASCII characters are supported. * * @param target Target to type into * @param text Text to type. * @param modifiers Modifiers to press while typing. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> type(target: PFRML, text: String, modifiers: String): Int /** * Types the given text into the target. Only ASCII characters are supported. * * @param target Target to type into * @param text Text to type. * @param modifiers Modifiers to press while typing. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> type(target: PFRML, text: String, modifiers: Int): Int /** * Pastes the given text into the current caret position. * * @param text Text to paste. * @return 1 if possible, 0 otherwise. */ fun paste(text: String): Int /** * Pastes the given text into the target. * * @param target Target to paste into * @param text Text to paste. * @return 1 if possible, 0 otherwise. */ fun <PFRML : Any> paste(target: PFRML, text: String): Int //</editor-fold> //<editor-fold desc="Low-level Mouse and Keyboard Actions"> /** * Presses mouse buttons. * * @param buttons The mouse buttons to press. */ fun mouseDown(buttons: Int) /** * Releases all mouse buttons. */ fun mouseUp() /** * Releases mouse buttons. * * @param buttons The mouse buttons to release. */ fun mouseUp(buttons: Int) /** * Moves the mouse pointer to the region's last successful match. Same as [hover]. * * @return 1 if possible, 0 otherwise */ fun mouseMove(): Int /** * Moves the mouse from the current position to the offset position. * * @param xoff Horizontal offset, negative number are offset to the left. * @param yoff Vertical offset, negative number are offset to the top. * @return 1 if possible, 0 otherwise. */ fun mouseMove(xoff: Int, yoff: Int): Int /** * Moves the mouse to the given target. * * @param target Target to move the pointer to. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> mouseMove(target: PFRML): Int /** * Spins the mouse wheel. * * @param direction Direction to spin the mouse wheel in. * @param steps Number of steps the wheel is spinned. * @return 1 if possible, 0 otherwise. */ fun wheel(direction: Int, steps: Int): Int /** * Spins the mouse wheel at the given target * * @param target Target to spin the wheel at. * @param direction Direction to spin the mouse wheel in. * @param steps Number of steps the wheel is spinned. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> wheel(target: PFRML, direction: Int, steps: Int): Int /** * Spins the mouse wheel at the given target * * @param target Target to spin the wheel at. * @param direction Direction to spin the mouse wheel in. * @param steps Number of steps the wheel is spinned. * @param stepDelay The delay in milliseconds between each wheel step. * @return 1 if possible, 0 otherwise. * @throws FindFailed If the find operation failed. */ fun <PFRML : Any> wheel(target: PFRML, direction: Int, steps: Int, stepDelay: Int): Int /** * Presses a specific key. * * @param keycode The key to press. */ fun keyDown(keycode: Int) /** * Presses the keys specified by the string. * * @param keys Keys to be pressed. */ fun keyDown(keys: String) /** * Releases all keys */ fun keyUp() /** * Releases a specific key. * * @param keycode The key to release. */ fun keyUp(keycode: Int) /** * Releases the keys specified by the string. * * @param keys Keys to be released. */ fun keyUp(keys: String) //</editor-fold> //<editor-fold desc="Highlight Action"> /** * Highlights the region. * * @return Highlighted region. */ fun highlight(): SKryptonRegion /** * Highlights the region with the given color * * @param color Color to highlight with, can be color name or hex color codes. * @return Highlighted region. */ fun highlight(color: String): SKryptonRegion /** * Highlights the region for the given duration. * * @param secs Duration to highlight in seconds. * @return Highlighted region. */ fun highlight(secs: Int): SKryptonRegion /** * Highlights the region for the given duration. * * @param secs Duration to highlight in seconds. * @return Highlighted region. */ fun highlight(secs: Float): SKryptonRegion /** * Highlights the region for the given duration and color. * * @param secs Duration to highlight in seconds. * @param color Color to highlight with, can be color name or hex color codes. * @return Highlighted region. */ fun highlight(secs: Int, color: String): SKryptonRegion /** * Highlights the region for the given duration and color. * * @param secs Duration to highlight in seconds. * @param color Color to highlight with, can be color name or hex color codes. * @return Highlighted region. */ fun highlight(secs: Float, color: String): SKryptonRegion //</editor-fold> /** * Gets the [Location] of the target. * * @param PSIMRL [Pattern], [String], [Image], [Match], [Region] or [Location]. * @param target Target to find. * @return Location of target. * @throws FindFailed If the find operation failed. */ fun <PSIMRL : Any> getLocationFromTarget(target: PSIMRL): Location //<editor-fold desc="Kotlin operator overloads"> /** * Same as [union]. * * @return Combined region. */ operator fun plus(region: Region): SKryptonRegion /** * Compares the regions in terms of area. * * @return Positive number if this region is larger, 0 if equal, negative if smaller. */ operator fun compareTo(region: Region): Int //</editor-fold> }
0
Kotlin
0
8
0ec26e1858d36b4c829d45f17b1c22d35afcfc9c
21,372
SKrypton
MIT License
library/src/main/java/tmg/utilities/extensions/LocalTimeExtensions.kt
thementalgoose
164,951,044
false
null
package tmg.utilities.extensions import org.threeten.bp.LocalTime import org.threeten.bp.format.DateTimeFormatter import java.util.* @JvmOverloads fun LocalTime.format(format: String, locale: Locale = Locale.ENGLISH): String { val dateTimeFormatter = DateTimeFormatter.ofPattern(format, locale) return this.format(dateTimeFormatter) }
0
Kotlin
0
1
be5964b88f932b6b3b54e1a51c8608299d25d909
344
android-utilities
Apache License 2.0
src/test/kotlin/test/model/ProjectConfig.kt
opengood-aio
314,074,661
false
{"Kotlin": 192357}
package test.model import io.opengood.gradle.constant.EnvVars import io.opengood.gradle.enumeration.LanguageType import io.opengood.gradle.enumeration.ProjectType import io.opengood.gradle.enumeration.PublicationType import test.enumeration.defaultFeatures data class ProjectConfig( val languageType: LanguageType, val name: String = "test", val group: String = "io.test", val version: String = "1.0.0", val srcDir: Boolean = true, val buildGradle: Boolean = true, val settingsGradle: Boolean = true, val projectType: ProjectType = ProjectType.APP, val features: Int = defaultFeatures, val publications: List<PublicationType> = listOf(PublicationType.GITHUB, PublicationType.MAVEN_CENTRAL_PORTAL), val credentials: Map<String, String> = mapOf( EnvVars.GITHUB_USER to "example", EnvVars.GITHUB_TOKEN to "fake", ), )
0
Kotlin
0
0
3859fa32dfa3f748489d980830309d8a2ffe3f79
901
config-gradle-plugin
MIT License
app/src/main/java/lpzmrc/test/djungle/io/data/repository/GalleryRepository.kt
lpzmrc
250,509,107
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 60, "XML": 36, "Java": 1}
package lpzmrc.test.djungle.io.data.repository import lpzmrc.test.djungle.io.core.api.dto.Photo import lpzmrc.test.djungle.io.core.api.service.GalleryService import lpzmrc.test.djungle.io.core.network.ktx.toResource import lpzmrc.test.djungle.io.core.network.model.Resource import org.koin.core.KoinComponent import org.koin.core.inject import timber.log.Timber class GalleryRepository : KoinComponent { private val service: GalleryService by inject() suspend fun fetchPhotos(): Resource<List<Photo>?> { return try { service.fetchPhotos().run { if (isSuccessful) { body()?.let { toResource() } ?: Resource.error(message(), errorCode = Resource.ErrorCodes.ERROR.ordinal) } else { toResource() } } } catch (exception: Exception) { Timber.e(exception) Resource.error("An error has occurred", errorCode = Resource.ErrorCodes.EXCEPTION.ordinal) } } }
1
null
1
1
ec8529fa6e0ec7c9062527eb11ab7305f3d085e6
1,065
test-djungle
The Unlicense
ethereumtests/src/test/kotlin/GeneralStateTestCaseRunnerTest.kt
wjsrobertson
424,259,165
true
{"Kotlin": 493906, "Gherkin": 105660, "Java": 76369, "Solidity": 16962, "Shell": 871}
package org.kevem.ethereumtests import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.apache.http.client.methods.HttpPost import org.apache.http.entity.ContentType import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClients import org.apache.http.util.EntityUtils import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.* import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import org.kevem.evm.* import org.kevem.evm.collections.BigIntegerIndexedList import org.kevem.common.conversions.bytesToString import org.kevem.common.conversions.toByteList import org.kevem.evm.gas.* import org.kevem.evm.model.* import org.kevem.rpc.* import org.kevem.web.Server import org.kevem.rpc.module.EthSendTransactionRequest import org.kevem.rpc.module.EvmContext import org.web3j.crypto.ECKeyPair import org.web3j.crypto.Keys import java.math.BigInteger import java.time.Clock import java.time.Instant import java.time.ZoneId @Disabled @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GeneralStateTestCaseRunnerTest { private val server = Server() private val client = HttpClients.createDefault() private val mapper = jacksonObjectMapper() @AfterEach fun tearDown() { server.stop() client.close() } private val executor = createExecutor() @DisplayName("ethereum-test GeneralStateTest pack") @ParameterizedTest(name = "{0}") @MethodSource(value = ["testCases"]) internal fun `ethereum-test GeneralStateTest pack`(testCase: GeneralStateTestExplodedCase): Unit = with(testCase) { println(testCase.name) val keyPair = ECKeyPair.create(toByteList(transaction.secretKey).map { it.javaByte() }.toByteArray()) val gasPrice = toBigInteger(transaction.gasPrice) val features = Features(emptyList()) val evmConfig = EvmConfig( coinbase = Address(env.currentCoinbase), features = features ) val instant = Instant.ofEpochSecond(toBigInteger(env.currentTimestamp).toLong()) val difficulty = toBigInteger(env.currentDifficulty) val blockGasLimit = toBigInteger(env.currentGasLimit) val appConfig = AppConfig( coinbase = env.currentCoinbase, difficulty = difficulty, gasPrice = gasPrice, blockGasLimit = blockGasLimit, genesisBlockTimestamp = instant ) val tp = TransactionProcessor( executor = createExecutor(), config = evmConfig ) val accounts = parseAccounts(pre) val clock = Clock.fixed(instant, ZoneId.of("UTC")) val genesisBlock = MinedBlock( block = Block( number = BigInteger.ZERO, difficulty = difficulty, gasLimit = blockGasLimit, timestamp = Instant.MIN ), gasUsed = BigInteger.ZERO, hash = toByteList(env.previousHash), transactions = emptyList() ) val statefulTransactionProcessor = StatefulTransactionProcessor( tp, clock, WorldState(listOf(genesisBlock), accounts) ) val localAccount = LocalAccount(Keys.getAddress(keyPair), transaction.secretKey) val standardRpc = StandardRPC( StandardEvmOperations( statefulTransactionProcessor, evmConfig ), appConfig, LocalAccounts(listOf(localAccount)) ) val testRpc = TestRPC( statefulTransactionProcessor ) val evmContext = EvmContext(standardRpc, testRpc) server.start("localhost", 9002, false, evmContext) val txRequest = EthSendTransactionRequest( "2.0", "eth_sendTransaction", 1L, listOf( SendTransactionParamDTO( from = localAccount.address.toString(), to = transaction.to, value = transaction.value, gasPrice = transaction.gasPrice, gas = transaction.gasLimit, data = transaction.data, nonce = transaction.nonce ) ) ) val request = mapper.writeValueAsString(txRequest) val httppost = HttpPost("http://localhost:9002/").apply { entity = StringEntity(request, ContentType.APPLICATION_JSON) } val response = client.execute(httppost) val responseBody = EntityUtils.toString(response.entity) println(responseBody) val wsResult = statefulTransactionProcessor.getWorldState() results.forEach { val (a, expectedResult) = it val address = Address(a) if (expectedResult.shouldnotexist == "1") assertThat(wsResult.accounts.accountExists(address)).isFalse() //else //assertThat(wsResult.accounts.accountExists(address)).isTrue() expectedResult.balance?.also { expectedBalance -> val balance = wsResult.accounts.balanceOf(address) assertThat(balance).isEqualTo(toBigInteger0xTo0(expectedBalance)) } expectedResult.nonce?.also { expectedNonce -> val nonce = wsResult.accounts.nonceOf(address) assertThat(nonce).isEqualTo(toBigInteger0xTo0(expectedNonce)) } expectedResult.code?.also { expectedCode -> val code = wsResult.accounts.codeAt(address) val codeString = bytesToString(code.toList()) assertThat(codeString).isEqualTo(expectedCode) } expectedResult.storage?.also { expectedStorage -> expectedStorage.forEach { val (index, expectedValue) = it val value = wsResult.accounts.storageAt(address, toBigInteger(index)) //assertThat(value).isEqualTo(Word.coerceFrom(expectedValue)) } } } } companion object { private val loader = ExplodedGeneralTestCaseLoader() @JvmStatic fun testCases(): List<GeneralStateTestExplodedCase> = loader.loadTestCases() } private fun assertOutDataMatches(out: String?, executed: ExecutionContext) = assertThat(executed.lastReturnData).isEqualTo(toByteList(out)) private fun assertPostAccountsMatch(accounts: Accounts, executed: ExecutionContext) = accounts.list().forEach { a -> val account: Account = executed.accounts.list().find { it.address == a.address } ?: fail("no account with address ${a.address}") assertThat(a).isEqualTo(account) } private fun createExecutor(): Executor = Executor( GasCostCalculator( BaseGasCostCalculator(CallGasCostCalc(), PredefinedContractGasCostCalc()), MemoryUsageGasCostCalculator( MemoryUsageGasCalc() ) ) ) private fun parseAccounts(post: Map<String, GeneralStateTestCasePre>?): Accounts { val accountList = post?.map { entry -> val (a, d) = entry val contract = if (d.code != "0x") Contract( code = BigIntegerIndexedList.fromByteString(d.code), storage = Storage( d.storage.map { e -> val (k, v) = e Pair(toBigInteger(k), Word.coerceFrom(v)) }.toMap() ) ) else null Account( Address(a), toBigInteger(d.balance), contract, nonce = toBigInteger(d.nonce) ) } ?: emptyList() return Accounts(accountList) } /* use from general location */ private fun toBigInteger0xTo0(num: String): BigInteger = toBigInteger(num.replace("^0x$".toRegex(), "0")) private fun toBigInteger(number: String) = if (number.startsWith("0x")) BigInteger(cleanHexNumber(number), 16) else BigInteger(number) private fun cleanHexNumber(number: String) = number.replaceFirst("0x0+", "0x0").replaceFirst("0x", "") fun toBigIntegerOrNull(number: String?) = if (number == null) null else if (number.startsWith("0x")) BigInteger(cleanHexNumber(number), 16) else BigInteger(number) }
11
Kotlin
1
0
a5652a063b5d168394af94b54fe5559dab712736
8,618
kevem
Apache License 2.0
fifi-auth/src/commonMain/kotlin/com/paoapps/fifi/auth/di/Koin.kt
Paoapps
684,655,570
false
{"Kotlin": 141680}
package com.paoapps.fifi.auth.di import com.paoapps.fifi.auth.AuthApi import com.paoapps.fifi.auth.Claims import com.paoapps.fifi.auth.IdentifiableClaims import com.paoapps.fifi.auth.SettingsTokenStore import com.paoapps.fifi.auth.TokenDecoder import com.paoapps.fifi.auth.TokenStore import com.paoapps.fifi.auth.api.AuthClientApi import com.paoapps.fifi.auth.model.AuthModel import com.paoapps.fifi.auth.model.AuthModelImpl import com.paoapps.fifi.di.AppDefinition import com.paoapps.fifi.model.Model import com.paoapps.fifi.model.ModelEnvironment import org.koin.core.logger.Logger import org.koin.core.module.Module import org.koin.core.qualifier.named import org.koin.core.scope.Scope import org.koin.dsl.KoinAppDeclaration import org.koin.dsl.module internal expect fun platformInjections(serviceName: String, module: Module) enum class PlatformModuleQualifier { ENCRYPTED_SETTINGS, SETTINGS } data class Authentication<UserId, AccessTokenClaims: IdentifiableClaims<UserId>, RefreshTokenClaims: Claims>( val tokenDecoder: TokenDecoder<UserId, AccessTokenClaims, RefreshTokenClaims>, val authApi: (scope: Scope) -> AuthApi ) fun <Environment: ModelEnvironment, UserId, AccessTokenClaims: IdentifiableClaims<UserId>, RefreshTokenClaims: Claims, Api: AuthClientApi<UserId, AccessTokenClaims>> initKoinApp( authAppDefinition: AuthAppDefinition<Environment, UserId, AccessTokenClaims, RefreshTokenClaims, Api>, additionalModules: List<Module> = emptyList(), logger: Logger? = null, appDeclaration: KoinAppDeclaration = {}, ) = com.paoapps.fifi.di.initKoinApp( authAppDefinition, additionalModules + module { single<AuthModel<AccessTokenClaims, Environment, UserId, Api>> { val model: Model<Environment, Api> = get() authAppDefinition.authModel (model) } single<TokenStore> { SettingsTokenStore(get(named(PlatformModuleQualifier.ENCRYPTED_SETTINGS))) } single { authAppDefinition.authentication.tokenDecoder } single { authAppDefinition.authentication.authApi.invoke(this) } platformInjections(authAppDefinition.serviceName, this) }, logger, appDeclaration ) interface AuthAppDefinition<Environment: ModelEnvironment, UserId, AccessTokenClaims: IdentifiableClaims<UserId>, RefreshTokenClaims: Claims, Api: AuthClientApi<UserId, AccessTokenClaims>>: AppDefinition<Environment, Api> { val serviceName: String val authentication: Authentication<UserId, AccessTokenClaims, RefreshTokenClaims> fun authModel(model: Model<Environment, Api>): AuthModel<AccessTokenClaims, Environment, UserId, Api> { return AuthModelImpl(model) } }
0
Kotlin
0
6
09393dd0bc6af21751ad41a9e4ba510da3c54af1
2,722
fifi
MIT License
spring/src/main/kotlin/tw/waterballsa/gaas/spring/repositories/dao/RoomDAO.kt
Game-as-a-Service
623,554,204
false
null
package tw.waterballsa.gaas.spring.repositories.dao import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository import tw.waterballsa.gaas.spring.repositories.data.RoomData @Repository interface RoomDAO : MongoRepository<RoomData, String> { fun existsByHostId(hostId: String): Boolean }
25
Kotlin
5
22
2aef70e99d85e8f9cf5592da523c8acc42428122
350
Lobby-Platform-Service
Apache License 2.0
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/di/staking/dashboard/StakingDashboardModule.kt
novasamatech
415,834,480
false
null
package io.novafoundation.nova.feature_staking_impl.di.staking.dashboard import dagger.Module import dagger.Provides import io.novafoundation.nova.common.data.network.NetworkApiCreator import io.novafoundation.nova.common.di.scope.FeatureScope import io.novafoundation.nova.core_db.dao.StakingDashboardDao import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository import io.novafoundation.nova.feature_dapp_api.data.repository.DAppMetadataRepository import io.novafoundation.nova.feature_staking_api.data.dashboard.StakingDashboardUpdateSystem import io.novafoundation.nova.feature_staking_api.domain.dashboard.StakingDashboardInteractor import io.novafoundation.nova.feature_staking_impl.BuildConfig import io.novafoundation.nova.feature_staking_impl.data.dashboard.cache.RealStakingDashboardCache import io.novafoundation.nova.feature_staking_impl.data.dashboard.cache.StakingDashboardCache import io.novafoundation.nova.feature_staking_impl.data.dashboard.network.stats.RealStakingStatsDataSource import io.novafoundation.nova.feature_staking_impl.data.dashboard.network.stats.StakingStatsDataSource import io.novafoundation.nova.feature_staking_impl.data.dashboard.network.stats.api.StakingStatsApi import io.novafoundation.nova.feature_staking_impl.data.dashboard.network.updaters.RealStakingDashboardUpdateSystem import io.novafoundation.nova.feature_staking_impl.data.dashboard.network.updaters.chain.StakingDashboardUpdaterFactory import io.novafoundation.nova.feature_staking_impl.data.dashboard.repository.RealStakingDashboardRepository import io.novafoundation.nova.feature_staking_impl.data.dashboard.repository.RealTotalStakeChainComparatorProvider import io.novafoundation.nova.feature_staking_impl.data.dashboard.repository.StakingDashboardRepository import io.novafoundation.nova.feature_staking_impl.data.dashboard.repository.TotalStakeChainComparatorProvider import io.novafoundation.nova.feature_staking_impl.domain.dashboard.RealStakingDashboardInteractor import io.novafoundation.nova.feature_wallet_api.domain.interfaces.WalletRepository import io.novafoundation.nova.runtime.di.REMOTE_STORAGE_SOURCE import io.novafoundation.nova.runtime.ethereum.StorageSharedRequestsBuilderFactory import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry import io.novafoundation.nova.runtime.storage.source.StorageDataSource import javax.inject.Named @Module class StakingDashboardModule { @Provides @FeatureScope fun provideStakingDashboardRepository(dao: StakingDashboardDao): StakingDashboardRepository = RealStakingDashboardRepository(dao) @Provides @FeatureScope fun provideStakingStatsApi(apiCreator: NetworkApiCreator): StakingStatsApi { return apiCreator.create(StakingStatsApi::class.java, customBaseUrl = BuildConfig.DASHBOARD_SUBQUERY_URL) } @Provides @FeatureScope fun provideStakingStatsDataSource(api: StakingStatsApi): StakingStatsDataSource = RealStakingStatsDataSource(api) @Provides @FeatureScope fun provideStakingDashboardCache(dao: StakingDashboardDao): StakingDashboardCache = RealStakingDashboardCache(dao) @Provides @FeatureScope fun provideStakingDashboardUpdaterFactory( @Named(REMOTE_STORAGE_SOURCE) remoteStorageSource: StorageDataSource, stakingDashboardCache: StakingDashboardCache ) = StakingDashboardUpdaterFactory(stakingDashboardCache, remoteStorageSource) @Provides @FeatureScope fun provideUpdateSystem( stakingStatsDataSource: StakingStatsDataSource, accountRepository: AccountRepository, chainRegistry: ChainRegistry, updaterFactory: StakingDashboardUpdaterFactory, sharedRequestsBuilderFactory: StorageSharedRequestsBuilderFactory, stakingDashboardRepository: StakingDashboardRepository, ): StakingDashboardUpdateSystem = RealStakingDashboardUpdateSystem( stakingStatsDataSource = stakingStatsDataSource, accountRepository = accountRepository, chainRegistry = chainRegistry, updaterFactory = updaterFactory, sharedRequestsBuilderFactory = sharedRequestsBuilderFactory, stakingDashboardRepository = stakingDashboardRepository ) @Provides @FeatureScope fun provideTotalStakeComparatorProvider(): TotalStakeChainComparatorProvider = RealTotalStakeChainComparatorProvider() @Provides @FeatureScope fun provideInteractor( dashboardRepository: StakingDashboardRepository, chainRegistry: ChainRegistry, accountRepository: AccountRepository, stakingDashboardUpdateSystem: StakingDashboardUpdateSystem, dAppMetadataRepository: DAppMetadataRepository, walletRepository: WalletRepository, totalStakeChainComparatorProvider: TotalStakeChainComparatorProvider ): StakingDashboardInteractor = RealStakingDashboardInteractor( dashboardRepository = dashboardRepository, chainRegistry = chainRegistry, accountRepository = accountRepository, stakingDashboardSyncTracker = stakingDashboardUpdateSystem, walletRepository = walletRepository, dAppMetadataRepository = dAppMetadataRepository, totalStakeChainComparatorProvider = totalStakeChainComparatorProvider ) }
9
Kotlin
3
5
67bd23703276cdc1b804919d0baa679ada28db7f
5,290
nova-wallet-android
Apache License 2.0
android/src/main/java/com/hereexplore/features/polyline/PolylineViewManagerSpec.kt
ajakka
723,753,715
false
{"TypeScript": 41565, "Kotlin": 39672, "Swift": 23274, "Objective-C": 5287, "JavaScript": 4800, "Ruby": 4387, "Objective-C++": 810, "C": 103}
package com.mapshere.components.polyline import android.view.ViewGroup import com.facebook.react.bridge.ReadableArray import com.facebook.react.uimanager.ViewGroupManager abstract class PolylineViewManagerSpec<T : ViewGroup> : ViewGroupManager<T>() { abstract fun setGeoPolyline(view: T, value: ReadableArray?) abstract fun setLineType(view: T, value: String) abstract fun setLineWidth(view: T, value: Double) abstract fun setLineColor(view: T, value: Double) abstract fun setOutlineWidth(view: T, value: Double) abstract fun setOutlineColor(view: T, value: Double) abstract fun setLineLength(view: T, value: Double) abstract fun setGapColor(view: T, value: Double) abstract fun setGapLength(view: T, value: Double) abstract fun setCapShape(view: T, value: String) }
2
TypeScript
6
84
23fadb2abafe10986d3490ee627d0929f62c06be
799
react-native-here-explore
MIT License
Wave/src/main/java/com/example/wave/lib/Water_Wave.kt
yusufkhan08070817
775,579,032
false
{"Kotlin": 6094}
package com.example.wave.lib import android.animation.ObjectAnimator import android.content.Context import android.os.Handler import android.os.Looper import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.ImageView import android.widget.RelativeLayout import com.example.wave.R import java.util.Random class Water_Wave @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { private lateinit var handler: Handler private var i = 0 private val range = 2100f private lateinit var wave1: ImageView private lateinit var wave2: ImageView private lateinit var wave3: ImageView private lateinit var wave4: ImageView private lateinit var restimage: ImageView init { LayoutInflater.from(context).inflate(R.layout.waterwave, this, true) handler = Handler(Looper.getMainLooper()) wave1 = findViewById(R.id.waterwave1) wave2 = findViewById(R.id.waterwave2) wave3 = findViewById(R.id.waterwave3) wave4 = findViewById(R.id.waterwave4) restimage = findViewById(R.id.restwater) } fun initWave() { handlerLooper { if (i % 2 == 0) { val last = Random().nextInt(100) waveAnimation(wave1, -range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave2, range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave3, -range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave4, range, 10f * i + last, waveOBJ.duratation) if (i < 50) rest(restimage, 10f * i + last, waveOBJ.duratation * 2) else rest(restimage, 8f * i, waveOBJ.duratation * 2) } else { val last = Random().nextInt(100) waveAnimation(wave1, range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave2, -range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave3, range, 10f * i + Random().nextInt(100), waveOBJ.duratation) waveAnimation(wave4, -range, 10f * i + last, waveOBJ.duratation) } ++i } } private fun handlerLooper(function: () -> Unit) { handler.postDelayed(object : Runnable { override fun run() { function() val fu = function handlerLooper(fu) } }, waveOBJ.duratation) } private fun waveAnimation(v: View, tx: Float, ty: Float, duration: Long) { val translateX = ObjectAnimator.ofFloat(v, "translationX", tx) val translateY = ObjectAnimator.ofFloat(v, "translationY", -ty) translateX.duration = duration translateY.duration = duration translateY.start() translateX.start() } private fun rest(v: View, ty: Float, duration: Long) { val translateY = ObjectAnimator.ofFloat(v, "scaleY", ty) translateY.duration = duration translateY.start() } }
0
Kotlin
0
0
05de846cf5869b23b6eb2109b261e67cec7a48cb
3,251
WaterWave
MIT License
src/main/kotlin/no/nav/omsorgspenger/overføringer/Grunnlag.kt
navikt
293,469,365
false
null
package no.nav.omsorgspenger.overføringer import no.nav.omsorgspenger.fordelinger.FordelingGirMelding import no.nav.omsorgspenger.midlertidigalene.MidlertidigAleneVedtak import no.nav.omsorgspenger.overføringer.apis.SpleisetOverføringGitt import no.nav.omsorgspenger.overføringer.meldinger.OverføreOmsorgsdagerMelding import no.nav.omsorgspenger.personopplysninger.VurderRelasjonerMelding import no.nav.omsorgspenger.utvidetrett.UtvidetRettVedtak internal data class Grunnlag( internal val overføreOmsorgsdager: OverføreOmsorgsdagerMelding.Behovet, internal val utvidetRettVedtak: List<UtvidetRettVedtak>, internal val fordelingGirMeldinger: List<FordelingGirMelding>, internal val midlertidigAleneVedtak: List<MidlertidigAleneVedtak>, internal val koronaOverføringer: List<SpleisetOverføringGitt>, internal val relasjoner: Set<VurderRelasjonerMelding.Relasjon> )
9
Kotlin
0
2
1bf257bb4c5579855e801087d0aa44249389907d
889
omsorgspenger-rammemeldinger
MIT License
processor/src/main/java/ru/unit/orchestra_features/processor/generator/code/feature/property/StateProperty.kt
why-iskra
689,642,973
false
{"Kotlin": 102496}
package ru.unit.orchestra_features.processor.generator.code.feature.property import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import ru.unit.orchestra_features.processor.model.FeatureModel import ru.unit.orchestra_features.common.support.Feature import ru.unit.orchestra_features.processor.utils.extension.asClassName import ru.unit.orchestra_features.processor.utils.extension.synchronizedCodeBlock class StateProperty { companion object { fun name() = "state" } fun generate(featureModel: FeatureModel) = PropertySpec.builder( name = name(), type = Feature.State::class.asTypeName() .parameterizedBy(featureModel.clazz.asClassName()) ).apply { addModifiers(KModifier.OVERRIDE) val toggles = featureModel.dependsOn.map( DependsOnToggleProperty::name ) + listOf( ToggleProperty.name() ) getter( FunSpec.getterBuilder().apply { addCode( CodeBlock.synchronizedCodeBlock("this") { addStatement( "return·%T(${toggles.joinToString("·&&·")}, ${DataProperty.name()})", Feature.State::class.asTypeName().parameterizedBy(featureModel.clazz.asClassName()) ) } ) }.build() ) }.build() }
0
Kotlin
0
1
7b9b9301f4b377cae180d0025d03dbff86af8bfd
1,473
orchestra-features
MIT License
vector/src/main/java/im/vector/app/features/call/conference/JitsiWidgetData.kt
tchapgouv
340,329,238
false
{"Kotlin": 15930464, "HTML": 68524, "Shell": 57406, "Java": 28010, "Python": 25875, "FreeMarker": 7662, "JavaScript": 6925, "Ruby": 1587}
/* * Copyright (c) 2020 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.call.conference import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * This is jitsi widget data * https://github.com/matrix-org/matrix-doc/blob/b910b8966524febe7ffe78f723127a5037defe64/api/widgets/definitions/jitsi_data.yaml */ @JsonClass(generateAdapter = true) data class JitsiWidgetData( @Json(name = "domain") val domain: String, @Json(name = "conferenceId") val confId: String, @Json(name = "isAudioOnly") val isAudioOnly: Boolean = false, @Json(name = "auth") val auth: String? = null )
4
Kotlin
6
9
b248ca2dbb0953761d2780e4fba756acc3899958
1,183
tchap-android
Apache License 2.0
app/src/main/java/com/test/data/repository/FavoriteRepository.kt
ETSEmpiricalStudyKotlinAndroidApps
496,716,943
true
{"Kotlin": 111686, "Java": 1387}
package com.test.data.repository import androidx.annotation.WorkerThread import androidx.paging.Pager import androidx.room.withTransaction import com.test.data.database.EventsDb import com.test.data.database.dao.FavoritesDao import com.test.data.model.FavoriteEventsDTO import com.test.data.repository.settings.PagingConfigSettings import javax.inject.Inject class FavoriteRepository @Inject constructor( private val eventsDB: EventsDb, private val favoritesDao: FavoritesDao, ) { @WorkerThread suspend fun add(item: FavoriteEventsDTO) { eventsDB.withTransaction { favoritesDao.insert(item) } } @WorkerThread suspend fun delete(id: String) { eventsDB.withTransaction { favoritesDao.deleteById(id) } } fun getFavorites() = Pager( config = PagingConfigSettings.create(), pagingSourceFactory = { eventsDB.favorites().getPagedSource() } ).flow }
0
null
0
0
4a06616b14298e4003fb0ed15b012f2f1b4cd19b
958
RoomPaging3TestProject
Apache License 2.0
feature/anime/core/source/local/api/src/main/java/com/lelestacia/hayate/feature/anime/core/source/local/api/entity/aired/AnimePropEntity.kt
gab-stargazer
717,145,817
false
{"Kotlin": 459698}
package com.lelestacia.hayate.feature.anime.core.source.local.api.entity.aired import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class AnimePropEntity( @Json(name = "from") val from: AnimePropFromEntity, @Json(name = "to") val to: AnimePropToEntity )
0
Kotlin
0
4
892b443a225f787aa99631a3fb02fad517f7f19f
328
hayate
MIT License
src/main/java/uk/ac/shef/tracker/core/utils/Validator.kt
oakgroup
630,448,719
false
{"Kotlin": 375304}
/* * Copyright (c) 2023. * This code was developed by <NAME>, The University of Sheffield. * All rights reserved. * No part of this code can be used without the explicit written permission by the author */ package uk.ac.shef.tracker.core.utils import android.text.TextUtils import android.util.Patterns /** * Utility class that provides some useful methods for data validation */ @Suppress("unused", "MemberVisibilityCanBePrivate") object Validator { /** * Validate mail address * * @param mailAddress mail address to validate * @return true if mail address is valid */ fun validateMail(mailAddress: String?): Boolean { return !TextUtils.isEmpty(mailAddress) && Patterns.EMAIL_ADDRESS.matcher(mailAddress!!).matches() } /** * Validate website url * * @param url the url to validate * @return true if mail address is valid */ fun validateUrl(url: String?): Boolean { return !TextUtils.isEmpty(url) && Patterns.WEB_URL.matcher(url!!).matches() } }
0
Kotlin
0
0
55d317e94e18d25c54843270cdcf50039cab6c49
1,058
android-bhf-tracker
MIT License
shared/src/commonMain/kotlin/org/nautilusapp/nautilus/scouting/analysis/models/crescendo/CrescendoAutoAverage.kt
nautilus-frc
663,757,256
false
{"Kotlin": 650874, "Swift": 118676}
package org.nautilusapp.nautilus.scouting.analysis.models.crescendo data class CrescendoAutoAverage( val leaveRate: Double, val ampNotes: Double, val speakerNotes: Double )
8
Kotlin
0
0
150fc63feeb0368e3e024f977eb50bd2d89c3e8c
185
companion
MIT License
src/1/1546.kt
WhiteKr
408,140,568
false
null
import java.io.BufferedReader import java.io.InputStreamReader fun main() = with(BufferedReader(InputStreamReader(System.`in`))) { val N: Int = readLine().toInt() val scores: Array<String> = readLine().trim().split(' ').toTypedArray() val data = IntArray(N) var max: Int = scores.map { it.toInt() }.toIntArray().maxOrNull()!! var sum = .0 for (i in 0 until N) { data[i] = scores[i].toInt() sum += data[i] if (max < data[i]) max = data[i] } print(((sum / N) * 100) / max) }
5
Kotlin
0
1
913fcc9f293c62a1b4e67bccb075820578e097ea
542
Baekjoon-grass
MIT License
sdk/analytics/src/main/java/com/klaviyo/analytics/networking/requests/PushTokenApiRequest.kt
klaviyo
282,284,680
false
null
package com.klaviyo.analytics.networking.requests import com.klaviyo.analytics.DeviceProperties import com.klaviyo.analytics.model.Profile import com.klaviyo.core.Registry /** * Defines the content of an API request to append a push token to a [Profile] * * Using legacy V2 API until push tokens are supported by a V3 endpoint * * @constructor */ internal class PushTokenApiRequest( queuedTime: Long? = null, uuid: String? = null ) : KlaviyoApiRequest(PATH, RequestMethod.POST, queuedTime, uuid) { private companion object { const val PATH = "client/push-tokens" const val METADATA = "device_metadata" const val TOKEN = "token" const val PLATFORM = "platform" const val VENDOR = "vendor" const val VENDOR_FCM = "FCM" const val ENABLEMENT_STATUS = "enablement_status" const val NOTIFICATIONS_ENABLED = "AUTHORIZED" const val NOTIFICATIONS_DISABLED = "UNAUTHORIZED" const val BACKGROUND = "background" const val BG_AVAILABLE = "AVAILABLE" const val BG_UNAVAILABLE = "DENIED" } override val type: String = "Push Token" /** * HTTP request headers */ override var headers: Map<String, String> = mapOf( HEADER_CONTENT to TYPE_JSON, HEADER_ACCEPT to TYPE_JSON, HEADER_REVISION to V3_REVISION, HEADER_USER_AGENT to DeviceProperties.userAgent ) /** * HTTP request query params */ override var query: Map<String, String> = mapOf( COMPANY_ID to Registry.config.apiKey ) override val successCodes: IntRange get() = HTTP_ACCEPTED..HTTP_ACCEPTED constructor(token: String, profile: Profile) : this() { body = jsonMapOf( DATA to mapOf( TYPE to PUSH_TOKEN, ATTRIBUTES to filteredMapOf( TOKEN to token, PLATFORM to DeviceProperties.platform, VENDOR to VENDOR_FCM, ENABLEMENT_STATUS to if (DeviceProperties.notificationPermission) NOTIFICATIONS_ENABLED else NOTIFICATIONS_DISABLED, BACKGROUND to if (DeviceProperties.backgroundData) BG_AVAILABLE else BG_UNAVAILABLE, METADATA to DeviceProperties.buildMetaData(), PROFILE to mapOf(*ProfileApiRequest.formatBody(profile)) ) ) ) } }
0
Kotlin
2
6
a8b4f5751f5f204c0f5a9548148f4b6a138f5ce7
2,419
klaviyo-android-sdk
MIT License
sdk/analytics/src/main/java/com/klaviyo/analytics/networking/requests/PushTokenApiRequest.kt
klaviyo
282,284,680
false
null
package com.klaviyo.analytics.networking.requests import com.klaviyo.analytics.DeviceProperties import com.klaviyo.analytics.model.Profile import com.klaviyo.core.Registry /** * Defines the content of an API request to append a push token to a [Profile] * * Using legacy V2 API until push tokens are supported by a V3 endpoint * * @constructor */ internal class PushTokenApiRequest( queuedTime: Long? = null, uuid: String? = null ) : KlaviyoApiRequest(PATH, RequestMethod.POST, queuedTime, uuid) { private companion object { const val PATH = "client/push-tokens" const val METADATA = "device_metadata" const val TOKEN = "token" const val PLATFORM = "platform" const val VENDOR = "vendor" const val VENDOR_FCM = "FCM" const val ENABLEMENT_STATUS = "enablement_status" const val NOTIFICATIONS_ENABLED = "AUTHORIZED" const val NOTIFICATIONS_DISABLED = "UNAUTHORIZED" const val BACKGROUND = "background" const val BG_AVAILABLE = "AVAILABLE" const val BG_UNAVAILABLE = "DENIED" } override val type: String = "Push Token" /** * HTTP request headers */ override var headers: Map<String, String> = mapOf( HEADER_CONTENT to TYPE_JSON, HEADER_ACCEPT to TYPE_JSON, HEADER_REVISION to V3_REVISION, HEADER_USER_AGENT to DeviceProperties.userAgent ) /** * HTTP request query params */ override var query: Map<String, String> = mapOf( COMPANY_ID to Registry.config.apiKey ) override val successCodes: IntRange get() = HTTP_ACCEPTED..HTTP_ACCEPTED constructor(token: String, profile: Profile) : this() { body = jsonMapOf( DATA to mapOf( TYPE to PUSH_TOKEN, ATTRIBUTES to filteredMapOf( TOKEN to token, PLATFORM to DeviceProperties.platform, VENDOR to VENDOR_FCM, ENABLEMENT_STATUS to if (DeviceProperties.notificationPermission) NOTIFICATIONS_ENABLED else NOTIFICATIONS_DISABLED, BACKGROUND to if (DeviceProperties.backgroundData) BG_AVAILABLE else BG_UNAVAILABLE, METADATA to DeviceProperties.buildMetaData(), PROFILE to mapOf(*ProfileApiRequest.formatBody(profile)) ) ) ) } }
0
Kotlin
2
6
a8b4f5751f5f204c0f5a9548148f4b6a138f5ce7
2,419
klaviyo-android-sdk
MIT License
omh-core/src/main/java/com/openmobilehub/android/coreplugin/model/OMHExtension.kt
openmobilehub
748,394,297
false
{"Kotlin": 21313, "Shell": 524}
package com.openmobilehub.android.coreplugin.model import com.openmobilehub.android.coreplugin.utils.ERROR_BUNDLES_BUT_NO_SERVICES import com.openmobilehub.android.coreplugin.utils.ERROR_BUNDLES_WITHOUT_NAME import com.openmobilehub.android.coreplugin.utils.ERROR_BUNDLES_WITH_INCORRECT_NAME import javax.inject.Inject import org.gradle.api.Action import org.gradle.api.InvalidUserDataException import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.api.provider.MapProperty open class OMHExtension @Inject constructor(private val project: Project) { private val enableLocalProjectsProperty: Property<Boolean> = project.objects.property(Boolean::class.java) var enableLocalProjects: Boolean set(value) = enableLocalProjectsProperty.set(value) get() = enableLocalProjectsProperty.orNull ?: false private val bundles: MapProperty<String, Bundle> = project.objects.mapProperty( String::class.java, Bundle::class.java ) fun bundle(id: String, configuration: Action<in Bundle>) { val bundle = project.objects.newInstance(Bundle::class.java, project) bundle.id.set(id.trim()) configuration.execute(bundle) bundles.put(bundle.id.get(), bundle) } //region Validations private fun getDependenciesFromAllBundles(): List<String> { val dependenciesInAllBundlesList = mutableListOf<String>() if (bundles.isPresent && bundles.get().isNotEmpty()) { bundles.get().values.forEach { dependenciesInAllBundlesList.addAll(it.getDependencies()) } } return dependenciesInAllBundlesList } private fun isThereANamelessBundle(bundlesMap: Map<String, Bundle>): Boolean { bundlesMap.forEach { bundle -> if (bundle.key.isEmpty()) return true } return false } private fun isThereABundleWithIncorrectName(bundlesMap: Map<String, Bundle>): Boolean { bundlesMap.forEach { bundle -> if (!bundleNameRegex.matches(bundle.key)) return true } return false } /** * Validate that bundles and services are required at the time of using the plugin in clients. */ @SuppressWarnings("CyclomaticComplexMethod") fun validateIntegrity() { var errorMsg = "" // Bundles Integrity if (errorMsg.isEmpty() && bundles.isPresent && bundles.get().isNotEmpty()) { val bundlesMap = bundles.get() if (isThereANamelessBundle(bundlesMap)) { errorMsg = ERROR_BUNDLES_WITHOUT_NAME } if (errorMsg.isEmpty() && isThereABundleWithIncorrectName(bundlesMap)) { errorMsg = ERROR_BUNDLES_WITH_INCORRECT_NAME } if (errorMsg.isEmpty() && getDependenciesFromAllBundles().isEmpty() && !enableLocalProjects) { errorMsg = ERROR_BUNDLES_BUT_NO_SERVICES } } if (errorMsg.isNotEmpty()) throw InvalidUserDataException(errorMsg) } //endregion internal fun getBundles() = bundles companion object { private val bundleNameRegex = Regex("^[a-zA-Z][a-zA-Z0-9_]*(?:_[a-zA-Z0-9_]+)*$") } }
0
Kotlin
0
0
04254efbfdbd99c9dd8b681fac6d38838c03676d
3,232
android-omh-core
Apache License 2.0
app/src/main/java/com/mongodb/rchatapp/RChatApplication.kt
mongodb-developer
362,073,912
false
{"Kotlin": 55858, "Java": 2473}
package com.mongodb.rchatapp import android.app.Application import com.mongodb.rchatapp.di.koinModules import io.realm.Realm import io.realm.RealmConfiguration import io.realm.log.LogLevel import io.realm.log.RealmLog import io.realm.mongodb.App import io.realm.mongodb.AppConfiguration import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class RChatApplication : Application() { val realmSync by lazy { App(AppConfiguration.Builder(BuildConfig.RealmAppId).build()) } override fun onCreate() { super.onCreate() setupRealm() setupKoin() } private fun setupRealm() { Realm.init(this) val config = RealmConfiguration.Builder() .name("rChatDb.db") .allowQueriesOnUiThread(false) .schemaVersion(1) .deleteRealmIfMigrationNeeded() .build() Realm.setDefaultConfiguration(config) if (BuildConfig.DEBUG) RealmLog.setLevel(LogLevel.ALL) } private fun setupKoin() { startKoin { androidLogger(Level.NONE) androidContext(this@RChatApplication) modules(modules = koinModules()) } } }
0
Kotlin
0
0
dd2f4d99efc814e1be6f8400141fc01aca974b17
1,313
RChatApp
Apache License 2.0
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/MainActivity.kt
SaitamaCodeAndroid
611,679,030
false
{"Markdown": 5, "Gradle": 23, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 20, "Batchfile": 1, "Kotlin": 211, "INI": 11, "Proguard": 10, "XML": 104, "Java": 531, "JSON": 3, "YAML": 1, "HTML": 1, "CSS": 2, "JavaScript": 1}
package com.airbnb.epoxy.sample import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import android.os.Parcelable import android.view.View import androidx.annotation.ColorInt import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.airbnb.epoxy.EpoxyRecyclerView import com.airbnb.epoxy.EpoxyTouchHelper import com.airbnb.epoxy.EpoxyTouchHelper.DragCallbacks import com.airbnb.epoxy.sample.SampleController.AdapterCallbacks import com.airbnb.epoxy.sample.models.CarouselModelGroup import java.util.Collections import java.util.Random /** * Example activity usage for [com.airbnb.epoxy.EpoxyController]. */ class MainActivity : AppCompatActivity(), AdapterCallbacks { private val controller = SampleController(this) private var carousels: MutableList<CarouselData>? = ArrayList() @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<View>(R.id.recycler_view) as EpoxyRecyclerView recyclerView.layoutManager = GridLayoutManager(this, 2) recyclerView.setController(controller) if (savedInstanceState != null) { carousels = savedInstanceState.getParcelableArrayList( CAROUSEL_DATA_KEY, CarouselData::class.java, ) } initTouch(recyclerView) updateController() } private fun initTouch(recyclerView: RecyclerView) { // Swiping is not used since it interferes with the carousels, but here is an example of // how we would set it up. // EpoxyTouchHelper.initSwiping(recyclerView) // .leftAndRight() // .withTarget(CarouselModelGroup.class) // .andCallbacks(new SwipeCallbacks<CarouselModelGroup>() { // // @Override // public void onSwipeProgressChanged(CarouselModelGroup model, View itemView, // float swipeProgress) { // // Fades a background color in the further you swipe. A different color is used // for swiping left vs right. // int alpha = (int) (Math.abs(swipeProgress) * 255); // if (swipeProgress > 0) { // itemView.setBackgroundColor(Color.argb(alpha, 0, 255, 0)); // } else { // itemView.setBackgroundColor(Color.argb(alpha, 255, 0, 0)); // } // } // // @Override // public void onSwipeCompleted(CarouselModelGroup model, View itemView, int position, // int direction) { // carousels.remove(model.data); // updateController(); // } // // @Override // public void clearView(CarouselModelGroup model, View itemView) { // itemView.setBackgroundColor(Color.WHITE); // } // }); EpoxyTouchHelper.initDragging(controller) .withRecyclerView(recyclerView) .forVerticalList() .withTarget(CarouselModelGroup::class.java) .andCallbacks(object : DragCallbacks<CarouselModelGroup?>() { @ColorInt val selectedBackgroundColor = Color.argb(200, 200, 200, 200) var backgroundAnimator: ValueAnimator? = null override fun onDragStarted( model: CarouselModelGroup?, itemView: View, adapterPosition: Int ) { backgroundAnimator = ValueAnimator .ofObject(ArgbEvaluator(), Color.WHITE, selectedBackgroundColor) backgroundAnimator?.addUpdateListener { animator: ValueAnimator -> itemView.setBackgroundColor( animator.animatedValue as Int ) } backgroundAnimator?.start() itemView .animate() .scaleX(1.05f) .scaleY(1.05f) } override fun onDragReleased( model: CarouselModelGroup?, itemView: View, ) { if (backgroundAnimator != null) { backgroundAnimator!!.cancel() } backgroundAnimator = ValueAnimator.ofObject( ArgbEvaluator(), (itemView.background as ColorDrawable).color, Color.WHITE ) backgroundAnimator?.addUpdateListener { animator: ValueAnimator -> itemView.setBackgroundColor( animator.animatedValue as Int ) } backgroundAnimator?.start() itemView .animate() .scaleX(1f) .scaleY(1f) } override fun clearView( model: CarouselModelGroup?, itemView: View ) { onDragReleased(model, itemView) } override fun onModelMoved( fromPosition: Int, toPosition: Int, modelBeingMoved: CarouselModelGroup?, itemView: View? ) { val carouselIndex = carousels!!.indexOf(modelBeingMoved?.data) carousels?.add( carouselIndex + (toPosition - fromPosition), carousels!!.removeAt(carouselIndex) ) } }) } override fun onSaveInstanceState(state: Bundle) { super.onSaveInstanceState(state) state.putParcelableArrayList(CAROUSEL_DATA_KEY, carousels as ArrayList<out Parcelable?>?) controller.onSaveInstanceState(state) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) controller.onRestoreInstanceState(savedInstanceState) } private fun updateController() { carousels?.let { controller.setData(it.toList()) } } override fun onAddCarouselClicked() { val carousel = CarouselData( carousels!!.size.toLong(), ArrayList(), ) addColorToCarousel(carousel) carousels!!.add(0, carousel) updateController() } private fun addColorToCarousel(carousel: CarouselData?) { val colors = carousel!!.colors colors.add(0, ColorData(randomColor(), colors.size.toLong())) } override fun onClearCarouselsClicked() { carousels!!.clear() updateController() } override fun onShuffleCarouselsClicked() { carousels?.shuffle() updateController() } override fun onChangeAllColorsClicked() { for (carouselData in carousels!!) { for (colorData in carouselData.colors) { colorData.colorInt = randomColor() } } updateController() } override fun onAddColorToCarouselClicked(carousel: CarouselData?) { addColorToCarousel(carousel) updateController() } override fun onClearCarouselClicked(carousel: CarouselData?) { carousel!!.colors.clear() updateController() } override fun onShuffleCarouselColorsClicked(carousel: CarouselData?) { carousel?.colors?.shuffle() updateController() } override fun onChangeCarouselColorsClicked(carousel: CarouselData?) { for (colorData in carousel!!.colors) { colorData.colorInt = randomColor() } updateController() } override fun onColorClicked(carousel: CarouselData?, colorPosition: Int) { val carouselPosition = carousels!!.indexOf(carousel) val colorData = carousels!![carouselPosition].colors[colorPosition] colorData.setPlayAnimation(!colorData.shouldPlayAnimation()) updateController() } companion object { private val RANDOM = Random() private const val CAROUSEL_DATA_KEY = "carousel_data_key" private fun randomColor(): Int { val r = RANDOM.nextInt(256) val g = RANDOM.nextInt(256) val b = RANDOM.nextInt(256) return Color.rgb(r, g, b) } } }
0
Java
0
0
b4552866fb0170a5882ec920f41578a68db2af54
8,841
Epoxy
Apache License 2.0
Chapter 12/02_mars_data.kt
bpbpublications
649,604,575
false
{"Kotlin": 94438, "Java": 3484, "Shell": 275}
data class MarsData( val price: Int, // currency price (in dollars?) val id: Int, // unique id number for the plot of land val type: String, // either "buy" or "rent" val img_src: String // a url of an image )
0
Kotlin
0
1
3e8dfdb8ca03911063fe97d0e1e020f958e4dcdd
226
Scalable-Android-Applications-in-Kotlin
MIT License
app/src/test/java/cz/palda97/lpclient/model/pipeline/PipelineViewTest.kt
Palda97
280,530,029
false
null
package cz.palda97.lpclient.model.pipeline import cz.palda97.lpclient.* import cz.palda97.lpclient.model.entities.pipelineview.PipelineViewFactory import org.junit.Test import org.junit.Assert.* class PipelineViewTest : MockkTest() { @Test fun parse() { val factory = PipelineViewFactory(SERVER, PIPELINE_VIEW_LIST) val content = factory.serverWithPipelineViews.mailContent assertNotNull(content) content!! assertEquals(SERVER, content.server) val pipelines = content.pipelineViewList.map { it.pipelineView } assertEquals(2, pipelines.size) //TODO(maybe test this in androidTest) val marks = content.pipelineViewList.map { it.mark } assertListContentMatch(listOf(null, null), marks) } companion object { private const val PIPELINE_VIEW_LIST = "[\n" + " {\n" + " \"@graph\": [\n" + " {\n" + " \"@id\": \"http://localhost:8080/resources/pipelines/1611789953288\",\n" + " \"@type\": [\n" + " \"http://linkedpipes.com/ontology/Pipeline\"\n" + " ],\n" + " \"http://www.w3.org/2004/02/skos/core#prefLabel\": [\n" + " {\n" + " \"@value\": \"LegendaryFoodOntology2\"\n" + " }\n" + " ]\n" + " }\n" + " ],\n" + " \"@id\": \"http://localhost:8080/resources/pipelines/1611789953288\"\n" + " },\n" + " {\n" + " \"@graph\": [\n" + " {\n" + " \"@id\": \"http://localhost:8080/resources/pipelines/1611793092057\",\n" + " \"@type\": [\n" + " \"http://linkedpipes.com/ontology/Pipeline\"\n" + " ],\n" + " \"http://www.w3.org/2004/02/skos/core#prefLabel\": [\n" + " {\n" + " \"@value\": \"defCrab\"\n" + " }\n" + " ]\n" + " }\n" + " ],\n" + " \"@id\": \"http://localhost:8080/resources/pipelines/1611793092057\"\n" + " }\n" + "]" } }
0
Kotlin
0
0
e2e1c188a21dac4cd78d9242633dc094ba50ef64
2,667
LinkedPipesAndroidClient
MIT License
data/src/main/java/com/synrgyacademy/data/local/model/HistorySearchingEntity.kt
Synrgy-Academy-Final-Project
738,116,027
false
{"Kotlin": 429514, "Ruby": 1824}
package com.synrgyacademy.data.local.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.synrgyacademy.domain.model.airport.AirportDataModel import com.synrgyacademy.domain.model.airport.HistoryDataModel import com.synrgyacademy.domain.model.passenger.PassengerTotal @Entity(tableName = "history_searching") data class HistorySearchingEntity ( @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo("departureData") val departureData: AirportDataModel, @ColumnInfo("arrivalData") val arrivalData: AirportDataModel, @ColumnInfo(name = "departureDate") val departureDate: String, @ColumnInfo(name = "searchingDate") val searchingDate: String, @ColumnInfo(name = "passenger") val passenger: PassengerTotal, @ColumnInfo(name = "airplaneClass") val airplaneClass: String ) { fun toHistoryDataModel(): HistoryDataModel{ return HistoryDataModel( id = id, departureData = departureData, arrivalData = arrivalData, departureDate = departureDate, searchingDate = searchingDate, passenger = passenger, airplaneClass = airplaneClass ) } companion object { fun from(historyDataModel: HistoryDataModel): HistorySearchingEntity { return HistorySearchingEntity( id = historyDataModel.id, departureData = historyDataModel.departureData, arrivalData = historyDataModel.arrivalData, departureDate = historyDataModel.departureDate, searchingDate = historyDataModel.searchingDate, passenger = historyDataModel.passenger, airplaneClass = historyDataModel.airplaneClass ) } } }
0
Kotlin
0
0
d7fefca1200efd6eae4a33a34ef0511d90dfd54a
1,848
Android
MIT License
feature-user-impl/src/main/java/jp/co/soramitsu/users/presentation/list/UsersAdapter.kt
ModeNode
300,518,840
true
{"Kotlin": 57393}
package jp.co.soramitsu.users.presentation.list import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import jp.co.soramitsu.feature_user_api.domain.model.User import jp.co.soramitsu.users.R import kotlinx.android.synthetic.main.item_user.view.firstNameTv import kotlinx.android.synthetic.main.item_user.view.lastNameTv class UsersAdapter( private val userClickListener: (User) -> Unit ) : ListAdapter<User, UserViewHolder>(DiffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false) return UserViewHolder(view) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { holder.bind(getItem(position), userClickListener) } } class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(user: User, userClickListener: (User) -> Unit) { with(itemView) { firstNameTv.text = user.firstName lastNameTv.text = user.lastName setOnClickListener { userClickListener(user) } } } } object DiffCallback : DiffUtil.ItemCallback<User>() { override fun areItemsTheSame(oldItem: User, newItem: User): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: User, newItem: User): Boolean { return oldItem == newItem } }
0
null
0
0
15d40658cc79c518e038f40531f56917cd9233e7
1,649
fearless-Android
Apache License 2.0
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/generic5.kt
ingokegel
72,937,917
true
null
// IS_APPLICABLE: false // WITH_STDLIB fun test() { foo <caret>{ bar<Int>() } } fun foo(f: () -> Unit) {} fun <T> bar(): T = TODO()
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
138
intellij-community
Apache License 2.0
demo/frontend/src/main/kotlin/eu/rigeldev/uirig/demo/state/LoggedInState.kt
teyckmans
154,056,343
false
null
package eu.rigeldev.uirig.demo.state import eu.rigeldev.uirig.update.Update /** * @author <NAME> <<EMAIL>> */ class LoggedInState private constructor(builder : LoggedInStateBuilder) { val baseApiUrl : String val username : String val roles : List<String> val warnings : List<String> val pageName : PageName init { this.baseApiUrl = builder.baseApiUrl this.username = builder.username this.roles = builder.roles this.warnings = builder.warnings this.pageName = builder.pageName } override fun toString(): String { return "LoggedInState(baseApiUrl='$baseApiUrl', username='$username', roles=$roles, warnings=$warnings, pageName=$pageName)" } class LoggedInStateBuilder { var baseApiUrl : String = "" var username : String = "" var roles : List<String> = emptyList() var warnings : List<String> = emptyList() var pageName : PageName = PageName.HOME fun from(notLoggedInState: NotLoggedInState): LoggedInStateBuilder { this.baseApiUrl = notLoggedInState.baseApiUrl this.username = notLoggedInState.username this.roles = emptyList() this.warnings = emptyList() this.pageName = PageName.HOME return this } fun from(loggedInState: LoggedInState): LoggedInStateBuilder { this.baseApiUrl = loggedInState.baseApiUrl this.username = loggedInState.username this.roles = ArrayList(loggedInState.roles) this.warnings = ArrayList(loggedInState.warnings) this.pageName = loggedInState.pageName return this } fun baseApiUrl(baseApiUrl: String): LoggedInStateBuilder { this.baseApiUrl = baseApiUrl return this } fun username(username: String): LoggedInStateBuilder { this.username = username return this } fun roles(roles: List<String>): LoggedInStateBuilder { this.roles = roles return this } fun warnings(warnings: List<String>): LoggedInStateBuilder { this.warnings = warnings return this } fun pageName(pageName: PageName): LoggedInStateBuilder { this.pageName = pageName return this } fun build(): LoggedInState { return LoggedInState(this) } fun buildUpdate() : Update { return Update(this.build()) } } companion object { fun loggedInState() : LoggedInStateBuilder { return LoggedInStateBuilder() } fun loggedInState(notLoggedInState : NotLoggedInState) : LoggedInStateBuilder { return this.loggedInState() .from(notLoggedInState) } fun loggedInState(loggedInState : LoggedInState) : LoggedInStateBuilder { return this.loggedInState() .from(loggedInState) } } }
1
null
0
0
42ee75a05b845dc7f589adf78c396a2df17d6be2
3,072
ui-rig-examples
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/SignalBarsFair.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.SignalBarsFair: ImageVector get() { if (_signalBarsFair != null) { return _signalBarsFair!! } _signalBarsFair = Builder(name = "SignalBarsFair", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(10.5f, 11.0f) horizontalLineToRelative(-1.0f) curveToRelative(-1.379f, 0.0f, -2.5f, 1.122f, -2.5f, 2.5f) verticalLineToRelative(2.55f) curveToRelative(-0.162f, -0.033f, -0.329f, -0.05f, -0.5f, -0.05f) horizontalLineToRelative(-1.0f) curveToRelative(-1.379f, 0.0f, -2.5f, 1.121f, -2.5f, 2.5f) verticalLineToRelative(3.0f) curveToRelative(0.0f, 1.379f, 1.121f, 2.5f, 2.5f, 2.5f) horizontalLineToRelative(5.0f) curveToRelative(1.379f, 0.0f, 2.5f, -1.121f, 2.5f, -2.5f) verticalLineToRelative(-8.0f) curveToRelative(0.0f, -1.378f, -1.121f, -2.5f, -2.5f, -2.5f) close() moveTo(7.0f, 22.0f) horizontalLineToRelative(-1.5f) curveToRelative(-0.275f, 0.0f, -0.5f, -0.225f, -0.5f, -0.5f) verticalLineToRelative(-3.0f) curveToRelative(0.0f, -0.275f, 0.225f, -0.5f, 0.5f, -0.5f) horizontalLineToRelative(1.0f) curveToRelative(0.275f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f) verticalLineToRelative(3.5f) close() moveTo(11.0f, 21.5f) curveToRelative(0.0f, 0.275f, -0.225f, 0.5f, -0.5f, 0.5f) horizontalLineToRelative(-1.5f) verticalLineToRelative(-8.5f) curveToRelative(0.0f, -0.275f, 0.225f, -0.5f, 0.5f, -0.5f) horizontalLineToRelative(1.0f) curveToRelative(0.275f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f) verticalLineToRelative(8.0f) close() } } .build() return _signalBarsFair!! } private var _signalBarsFair: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,994
icons
MIT License
src/main/kotlin/pl/jwizard/core/bot/BotEventHandler.kt
jwizard-bot
512,298,084
false
{"Kotlin": 272965}
/* * Copyright (c) 2024 by JWizard * Originally developed by <NAME> <https://miloszgilga.pl> */ package pl.jwizard.core.bot import net.dv8tion.jda.api.events.channel.ChannelDeleteEvent import net.dv8tion.jda.api.events.guild.GuildBanEvent import net.dv8tion.jda.api.events.guild.GuildJoinEvent import net.dv8tion.jda.api.events.guild.GuildLeaveEvent import net.dv8tion.jda.api.events.guild.GuildReadyEvent import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMuteEvent import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.events.role.RoleDeleteEvent import net.dv8tion.jda.api.events.session.ShutdownEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import org.springframework.context.annotation.Lazy import org.springframework.stereotype.Component import pl.jwizard.core.audio.AloneOnChannelListener import pl.jwizard.core.audio.AudioPlayerActivityEventsHandler import pl.jwizard.core.command.CommandProxyListener import pl.jwizard.core.command.SlashCommandRegisterer import pl.jwizard.core.command.action.ActionProxyListener import pl.jwizard.core.db.GuildSettingsSupplier @Component class BotEventHandler( @Lazy private val botInstance: BotInstance, private val aloneOnChannelListener: AloneOnChannelListener, private val guildSettingsSupplier: GuildSettingsSupplier, private val audioPlayerActivityEventsHandler: AudioPlayerActivityEventsHandler, private val commandProxyListener: CommandProxyListener, private val actionProxyListener: ActionProxyListener, private val slashCommandRegisterer: SlashCommandRegisterer, ) : ListenerAdapter() { override fun onMessageReceived(event: MessageReceivedEvent) = commandProxyListener.onRegularCommand(event) override fun onSlashCommandInteraction(event: SlashCommandInteractionEvent) = commandProxyListener.onSlashCommand(event) override fun onButtonInteraction(event: ButtonInteractionEvent) = actionProxyListener.onPressButton(event) override fun onCommandAutoCompleteInteraction(event: CommandAutoCompleteInteractionEvent) = slashCommandRegisterer.onAutocompleteInteraction(event) override fun onGuildVoiceUpdate(event: GuildVoiceUpdateEvent) { if (event.channelLeft == null) { // join to channel audioPlayerActivityEventsHandler.setBotDeafen(event) } aloneOnChannelListener.onEveryVoiceUpdate(event) } override fun onGuildVoiceMute(event: GuildVoiceMuteEvent) = audioPlayerActivityEventsHandler.stopPlayingContentAndFreeze(event) override fun onRoleDelete(event: RoleDeleteEvent) = audioPlayerActivityEventsHandler.recreateDjRoleOnDelete(event) override fun onChannelDelete(event: ChannelDeleteEvent) = audioPlayerActivityEventsHandler.unsetMusicTextChannelOnDelete(event) override fun onGuildJoin(event: GuildJoinEvent) { guildSettingsSupplier.persistGuildSettings(event.guild) audioPlayerActivityEventsHandler.createDjRoleOnJoin(event) slashCommandRegisterer.registerGuildCommands(event.guild) } override fun onGuildReady(event: GuildReadyEvent) { guildSettingsSupplier.persistGuildSettings(event.guild) slashCommandRegisterer.registerGuildCommands(event.guild) } override fun onGuildLeave(event: GuildLeaveEvent) = guildSettingsSupplier.deleteGuildSettings(event.guild) override fun onGuildBan(event: GuildBanEvent) = guildSettingsSupplier.deleteGuildSettings(event.guild) override fun onShutdown(event: ShutdownEvent) = botInstance.shutdown(event) }
1
Kotlin
0
2
d177ef4ba3b65c87581afff5be8832bcef43012c
3,735
jwizard-core
Apache License 2.0
engine/src/main/kotlin/io/rsbox/engine/message/impl/SetMapFlagMessage.kt
TheProdigy94
199,138,033
false
null
package io.rsbox.engine.message.impl import io.rsbox.engine.message.Message /** * @author Tom <<EMAIL>> */ data class SetMapFlagMessage(val x: Int, val z: Int) : Message
0
Kotlin
0
0
b83537fb4cb39be1a9fb22354477b9063d518d0d
173
rsbox
Apache License 2.0
app/src/main/java/com/breezefieldkrishnatea/features/survey/GroupNameOnClick.kt
DebashisINT
796,590,044
false
{"Kotlin": 14426399, "Java": 1021853}
package com.breezefieldkrishnatea.features.survey interface GroupNameOnClick { fun grOnClick(data: String) }
0
Kotlin
0
0
4a1bcf05788be9bb1afdbf5922e9ec38d7f60f84
114
HareKrishnaEntp
Apache License 2.0
library/src/main/kotlin/org/mjdev/libs/barcodescanner/bysquare/lzma/LenDecoder.kt
mimoccc
804,873,510
false
{"Kotlin": 244846, "Shell": 336}
package org.mjdev.libs.barcodescanner.bysquare.lzma import org.mjdev.libs.barcodescanner.bysquare.lzma.RangeDecoder.Companion.initBitModels import java.io.IOException internal class LenDecoder { private val choice = ShortArray(2) private val lowCoder = arrayOfNulls<BitTreeDecoder>(Base.kNumPosStatesMax) private val midCoder = arrayOfNulls<BitTreeDecoder>(Base.kNumPosStatesMax) private val highCoder = BitTreeDecoder(Base.kNumHighLenBits) private var numPosStates = 0 fun create(numPosStates: Int) { while (this.numPosStates < numPosStates) { lowCoder[this.numPosStates] = BitTreeDecoder(Base.kNumLowLenBits) midCoder[this.numPosStates] = BitTreeDecoder(Base.kNumMidLenBits) this.numPosStates++ } } fun init() { initBitModels(choice) for (posState in 0 until numPosStates) { lowCoder[posState]?.init() midCoder[posState]?.init() } highCoder.init() } @Throws(IOException::class) fun decode(rangeDecoder: RangeDecoder, posState: Int): Int { if (rangeDecoder.decodeBit(choice, 0) == 0) { return lowCoder[posState]?.decode(rangeDecoder) ?: 0 } var symbol = Base.kNumLowLenSymbols symbol += if (rangeDecoder.decodeBit(choice, 1) == 0) { midCoder[posState]?.decode(rangeDecoder) ?: 0 } else { Base.kNumMidLenSymbols + highCoder.decode(rangeDecoder) } return symbol } }
0
Kotlin
0
0
6f99b62284c335faeef849c5cee8771ffc760ed6
1,522
barcodescanner
Apache License 2.0
app/src/main/java/com/yuvrajsinghgmx/shopsmart/datastore/instance.kt
yuvrajsinghgmx
861,953,585
false
{"Kotlin": 46964}
package com.yuvrajsinghgmx.shopsmart.datastore import android.content.Context import androidx.datastore.preferences.preferencesDataStore val Context.dataStore by preferencesDataStore(name = "shopping_list")
9
Kotlin
16
9
79fdfa2b7f305bae270f6f4e0402c81c7c178cee
208
ShopSmart
MIT License
app/src/main/java/com/devspace/myapplication/common/model/RecipesResponse.kt
metaces
833,882,487
false
{"Kotlin": 36876}
package com.devspace.myapplication.common.model data class RecipesResponse( val recipes: List<RecipeDto> )
0
Kotlin
0
0
cbc092f05e0772c113b9e4692e525b9df6894c18
112
easy-recipes
MIT License
app/src/main/java/com/example/mobilliumcase/decorator/SimpleItemDecorator.kt
umitemre
494,565,005
false
null
package com.example.mobilliumcase.decorator import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import android.util.TypedValue import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import kotlin.math.roundToInt class SimpleItemDecorator(private val context: Context, orientation: Int) : DividerItemDecoration(context, orientation) { override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val paddingHorizontal = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 16f, context.resources.displayMetrics ).roundToInt() val divider: Drawable = drawable ?: return val dividerRight = parent.width - paddingHorizontal val childCount = parent.childCount for (i in 0 until childCount - 1) { // Get child val child = parent.getChildAt(i) // Get layout params of the child val params = child.layoutParams as RecyclerView.LayoutParams val dividerTop = child.bottom + params.bottomMargin val dividerBottom = dividerTop + divider.intrinsicHeight divider.setBounds(paddingHorizontal, dividerTop, dividerRight, dividerBottom) divider.draw(c) } } }
0
Kotlin
0
0
7254bbca773d0da8e4b8d42776401f7253857752
1,375
TMDB_Android_App
MIT License
language-server/taxi-lang-server-app/src/main/java/lang/taxi/lsp/TaxiLanguageServerApp.kt
taxilang
601,101,781
false
{"Kotlin": 1614057, "ANTLR": 66122, "TypeScript": 7231, "JavaScript": 4324, "Shell": 1468, "Java": 1454, "MDX": 425}
package lang.taxi.lsp import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class TaxiLanguageServerApp { companion object { @JvmStatic fun main(args: Array<String>) { val app = SpringApplication(TaxiLanguageServerApp::class.java) app.run(*args) } } }
8
Kotlin
5
75
b94c71c7c8751c05c4f466c58c4483dac3f2e421
396
taxilang
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/FireFlameSimple.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.FireFlameSimple: ImageVector get() { if (_fireFlameSimple != null) { return _fireFlameSimple!! } _fireFlameSimple = Builder(name = "FireFlameSimple", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(19.738f, 5.105f) lineToRelative(-3.734f, -3.465f) curveToRelative(-1.076f, -1.058f, -2.498f, -1.641f, -4.004f, -1.641f) reflectiveCurveToRelative(-2.928f, 0.583f, -3.973f, 1.61f) lineToRelative(-3.809f, 3.536f) curveTo(-0.065f, 9.452f, -0.065f, 16.457f, 4.219f, 20.763f) curveToRelative(2.078f, 2.088f, 4.842f, 3.237f, 7.781f, 3.237f) reflectiveCurveToRelative(5.703f, -1.149f, 7.781f, -3.237f) curveToRelative(4.284f, -4.306f, 4.284f, -11.311f, -0.043f, -15.657f) close() moveTo(17.654f, 18.645f) curveToRelative(-1.511f, 1.519f, -3.519f, 2.354f, -5.654f, 2.354f) reflectiveCurveToRelative(-4.144f, -0.836f, -5.654f, -2.354f) curveToRelative(-3.124f, -3.138f, -3.124f, -8.244f, -0.043f, -11.341f) lineToRelative(3.797f, -3.525f) curveToRelative(0.511f, -0.503f, 1.187f, -0.779f, 1.9f, -0.779f) reflectiveCurveToRelative(1.39f, 0.276f, 1.932f, 0.81f) lineToRelative(3.723f, 3.454f) curveToRelative(3.124f, 3.138f, 3.124f, 8.244f, 0.0f, 11.382f) close() moveTo(14.828f, 12.138f) curveToRelative(1.562f, 1.57f, 1.562f, 4.114f, 0.0f, 5.684f) curveToRelative(-0.781f, 0.785f, -1.805f, 1.177f, -2.828f, 1.177f) curveToRelative(-1.024f, 0.0f, -2.047f, -0.392f, -2.829f, -1.177f) curveToRelative(-1.562f, -1.57f, -1.562f, -4.114f, 0.0f, -5.684f) lineToRelative(1.586f, -1.63f) curveToRelative(0.345f, -0.34f, 0.794f, -0.509f, 1.243f, -0.509f) reflectiveCurveToRelative(0.898f, 0.17f, 1.243f, 0.509f) lineToRelative(1.585f, 1.63f) close() } } .build() return _fireFlameSimple!! } private var _fireFlameSimple: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,177
icons
MIT License
src/test/kotlin/homework5/ParserTreeTest.kt
martilut
342,898,976
false
{"Kotlin": 107965}
package homework5 import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.io.File internal class ParserTreeTest { companion object { @JvmStatic fun expressionsToCalculate(): List<Arguments> = listOf( Arguments.of("(+ 200 3)", 203), Arguments.of("(- 70 40)", 30), Arguments.of("(/ 144 12)", 12), Arguments.of("(* 100 1423)", 142300), Arguments.of("(/ (* (+ 2 2) 3)) 4)", 3), Arguments.of("(* (+ (/ 6 2) (- 3 4)) 2)", 4), ) @JvmStatic fun expressionsToPrint(): List<Arguments> = listOf( Arguments.of("(+ 200 3)", "1"), Arguments.of("(- 70 40)", "2"), Arguments.of("(/ 144 12)", "3"), Arguments.of("(* 100 1423)", "4"), Arguments.of("(/ (* (+ 2 2) 3)) 4)", "5"), Arguments.of("(* (+ (/ 6 2) (- 3 4)) 2)", "6"), ) } @MethodSource("expressionsToCalculate") @ParameterizedTest(name = "TestResults") fun getResult(expression: String, answer: Int) { val tree = ParserTree(parseExpression(expression)) assertEquals(answer, tree.getResult()) } private fun listToString(list: MutableList<String>): String { list.removeLast() var text = "" for (element in list) { text += element } return text } @MethodSource("expressionsToPrint") @ParameterizedTest(name = "OutputResults") fun outputTree(expression: String, fileNumber: String) { val expectedOutput = File(javaClass.getResource("testParser$fileNumber.txt").path) .readText() .replace("\r\n", "\n") val tree = ParserTree(parseExpression(expression)) assertEquals(expectedOutput, tree.getOutputTree()) } }
0
Kotlin
0
0
091a57cbca3fca8869ea5b61d2e0f2f77ccdb792
1,959
spbu_2021_kotlin_homeworks
Apache License 2.0
app/src/main/java/com/andrepassos/marvelheroes/network/api/MarvelService.kt
VoidHash
754,655,410
false
{"Kotlin": 54940}
package com.andrepassos.marvelheroes.network.api import com.andrepassos.marvelheroes.BuildConfig import com.andrepassos.marvelheroes.util.DataUtil import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object MarvelService { private const val BASE_URL = "http://gateway.marvel.com/v1/public/" private fun getRetrofit(): Retrofit { val timeStamp = System.currentTimeMillis().toString() val apiSecret = BuildConfig.MARVEL_SECRET val apiKey = BuildConfig.MARVEL_KEY val hash = DataUtil.getHash(timeStamp, apiSecret, apiKey) val headerInterceptor = Interceptor { chain -> var request: Request = chain.request() val url: HttpUrl = request.url.newBuilder() .addQueryParameter("ts", timeStamp) .addQueryParameter("apikey", apiKey) .addQueryParameter("hash", hash) .build() request = request.newBuilder().url(url).build() chain.proceed(request) } val logInterceptor = HttpLoggingInterceptor() logInterceptor.level = HttpLoggingInterceptor.Level.BODY val okHttpClient = OkHttpClient() .newBuilder() .addInterceptor(headerInterceptor) .addInterceptor(logInterceptor) .build() return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() } val api: MarvelApi = getRetrofit().create(MarvelApi::class.java) }
0
Kotlin
0
0
c67ead84aad4bba9261f07c9e0e14fc04685a6b3
1,747
marvel-compose-app
MIT License
Kotlin/step2/src/main/kotlin/step2/App.kt
chaking
84,820,596
false
{"Text": 17, "XML": 12, "Markdown": 1, "JavaScript": 12, "HTML": 7, "JSON": 11, "Elm": 1, "C++": 9, "Kotlin": 13, "Python": 8, "Jupyter Notebook": 1, "Java": 4, "Makefile": 9, "Scala": 6, "INI": 6, "Swift": 13, "Ignore List": 7, "JSON with Comments": 2, "Git Attributes": 2, "EditorConfig": 2, "CSS": 2, "Gradle Kotlin DSL": 11, "Shell": 5, "Batchfile": 5, "Gradle": 2, "Java Properties": 1}
/* * This Kotlin source file was generated by the Gradle 'init' task. */ package step2 import hello.kotlin.lib.Lib fun main(args: Array<String>) { println(Lib().greeting) }
1
null
1
1
a394f100155fa4eb1032c09cdc85816b7104804b
181
study
MIT License
src/main/kotlin/com/template/blog/controller/BlogApiController.kt
Example-Collection
378,571,820
false
null
package com.template.blog.controller import com.template.blog.dto.BlogDetailResponseDto import com.template.blog.service.BlogService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RestController @RestController class BlogApiController(val blogService: BlogService) { @GetMapping("/v1/blog/{blogId}") fun getById(@PathVariable blogId: Int) : BlogDetailResponseDto { return blogService.getById(blogId) } }
0
Kotlin
0
0
6302b69acebb30eee2ddea3a34c8137112536f57
545
Spring-Redis-Cache-Example
MIT License
app/src/main/java/com/realtomjoney/pyxlmoose/fragments/colorpicker/hex/HexadecimalColorPickerFragment+variables.kt
realtomjoney
419,545,692
false
null
package com.realtomjoney.pyxlmoose.fragments.colorpicker.hex import com.realtomjoney.pyxlmoose.databinding.FragmentHexadecimalColorPickerBinding var binding_: FragmentHexadecimalColorPickerBinding? = null val binding get() = binding_!!
15
Kotlin
2
30
ecea3c6d807483c31fa61fbf8d127e9ed92d1258
239
PyxlMoose
MIT License
src/main/kotlin/io/foxcapades/lib/cli/builder/arg/BigIntegerArgument.kt
Foxcapades
850,780,005
false
{"Kotlin": 253956}
package io.foxcapades.lib.cli.builder.arg import java.math.BigInteger /** * Argument type for containing [BigInteger] values. * * @since 1.0.0 */ interface BigIntegerArgument : ScalarArgument<BigInteger>
8
Kotlin
0
0
457d895219666963b70ac10df70092a7b778ebea
210
lib-kt-cli-builder
MIT License
app/src/main/java/com/nawrot/mateusz/compass/home/CompassActivity.kt
mateusz-nawrot
111,402,545
false
null
package com.nawrot.mateusz.compass.home import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.view.View import com.jakewharton.rxbinding2.view.RxView import com.nawrot.mateusz.compass.R import com.nawrot.mateusz.compass.base.* import com.nawrot.mateusz.compass.home.destination.DestinationDialog import com.nawrot.mateusz.compass.home.destination.DestinationDialogActivityInterface import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.activity_compass.* import javax.inject.Inject class CompassActivity : BaseActivity(), CompassView, DestinationDialogActivityInterface { private val LOCATION_PERMISSION_CODE: Int = 1 private var currentAngle: Float = 0f private var destinationLatitude: Double? = null private var destinationLongitude: Double? = null @Inject lateinit var presenter: CompassPresenter override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_compass) setSupportActionBar(toolbar) RxView.clicks(locationFab).subscribe { presenter.destinationButtonClicked() } } override fun onStart() { super.onStart() presenter.attachView(this) presenter.getDirection() } override fun onStop() { super.onStop() presenter.detachView() } override fun rotateCompass(angle: Float) { if (angle.difference(-currentAngle) < 1f) { return } formatAngleText(angle.toInt()) currentAngle = -angle compassArrow.rotateImage(currentAngle) } override fun showLocationPermissionRationale() { compassActivityCoordinator.showSnackbar(getString(R.string.location_rationale_message), action = getString(R.string.grant_location_permission), actionListener = { requestLocationPermission() }) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { LOCATION_PERMISSION_CODE -> { if (grantResults.isEmpty() || grantResults[0] == PackageManager.PERMISSION_DENIED) { //location permission denied presenter.locationPermissionDenied() } presenter.getDirection(false) return } } } override fun requestLocationPermission() { requestPermissionCompat(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_CODE) } override fun locationPermissionGranted(): Boolean { return isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) } override fun showDestinationDialog() { DestinationDialog.getInstance(destinationLatitude, destinationLongitude).show(supportFragmentManager, DestinationDialog.TAG) } override fun destinationCoordinatesEntered(latitude: Double?, longitude: Double?) { presenter.destinationCoordinatesEntered(latitude, longitude) } override fun hideDestinationIndicator() { destinationLatitude = null destinationLongitude = null destinationIndicator.visibility = View.GONE locationIcon.setDrawable(R.drawable.ic_location_off) locationFab.setDrawable(R.drawable.ic_add_location) } override fun showDestinationIndicator(latitude: Double, longitude: Double) { destinationLatitude = latitude destinationLongitude = longitude locationIcon.setDrawable(R.drawable.ic_location_on) locationFab.setDrawable(R.drawable.ic_edit_location) destinationIndicator.visibility = View.VISIBLE destinationIndicator.text = getString(R.string.lat_lng_placeholder, latitude, longitude) } override fun getDestinationLatitude(): Double? { return destinationLatitude } override fun getDestinationLongitude(): Double? { return destinationLongitude } private fun formatAngleText(angle: Int) { var formattedAngle = angle formattedAngle = if (formattedAngle < 0) { Math.abs(formattedAngle) } else { 360 - formattedAngle } angleIndicator.text = formattedAngle.toString() } }
0
Kotlin
0
1
fca6ca190a3cf16141726bfb955bd2cff1a8bb33
4,367
compass
Apache License 2.0
screen/main/src/main/kotlin/ru/maksonic/beresta/screen/main/ui/SnackBarKey.kt
maksonic
580,058,579
false
{"Kotlin": 1622432}
package ru.maksonic.beresta.screen.main.ui /** * @Author maksonic on 07.09.2023 */ enum class SnackBarKey(val id: Long) { REMOVED_NOTES(0) }
0
Kotlin
0
0
227b0a5f6c27b0f731b1f6e81b1fe2deeaa720aa
147
Beresta
MIT License