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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/inz/z/note_book/view/adapter/ScheduleRvAdapter.kt | Memory-Z | 234,554,362 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Java": 94, "Kotlin": 161, "XML": 301, "INI": 2} | package com.inz.z.note_book.view.adapter
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.inz.z.base.base.AbsBaseRvAdapter
import com.inz.z.base.base.AbsBaseRvViewHolder
import com.inz.z.base.util.BaseTools
import com.inz.z.note_book.R
import com.inz.z.note_book.bean.inside.ScheduleStatus
import com.inz.z.note_book.database.bean.TaskSchedule
import kotlinx.android.synthetic.main.item_schedule.view.*
import java.util.*
/**
* 计划项 适配器
* @author Zhenglj
* @version 1.0.0
* Create by inz in 2020/05/18 10:17.
*/
class ScheduleRvAdapter(mContext: Context?) :
AbsBaseRvAdapter<TaskSchedule, ScheduleRvAdapter.ScheduleRvViewHolder>(mContext) {
companion object {
const val TAG = "ScheduleRvAdapter"
}
var listener: ScheduleRvAdapterListener? = null
init {
}
override fun onCreateVH(parent: ViewGroup, viewType: Int): ScheduleRvViewHolder {
val view = mLayoutInflater.inflate(R.layout.item_schedule, parent, false)
return ScheduleRvViewHolder(view)
}
override fun onBindVH(holder: ScheduleRvViewHolder, position: Int) {
val schedule = list[position]
val repeat = schedule.scheduleRepeat
holder.scheduleRepeatSwitch.isChecked = schedule.scheduleStatue == ScheduleStatus.DOING
val time = BaseTools.getDateFormat(
mContext.getString(R.string._date_time_format_h_m),
Locale.getDefault()
).format(schedule.scheduleTime)
holder.scheduleTimeTv.text = time
holder.scheduleRepeatDateTv.text = schedule.getScheduleRepeatTimeJsonStr(mContext)
holder.scheduleTagTv.text = schedule.scheduleTag
}
/**
* item View
*/
inner class ScheduleRvViewHolder(itemView: View) : AbsBaseRvViewHolder(itemView),
View.OnClickListener, CompoundButton.OnCheckedChangeListener {
var scheduleTimeTv: TextView
var scheduleTagTv: TextView
var scheduleRepeatSwitch: Switch
var scheduleRepeatDateTv: TextView
init {
scheduleTimeTv = itemView.item_schedule_time_tv
scheduleTagTv = itemView.item_schedule_type_tv
scheduleRepeatSwitch = itemView.item_schedule_switch
scheduleRepeatDateTv = itemView.item_schedule_content_tv
itemView.setOnClickListener(this)
scheduleRepeatSwitch.setOnCheckedChangeListener(this)
}
override fun onClick(v: View?) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener?.itemClick(v, position)
}
}
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener?.itemCheckedChanged(buttonView, isChecked, position)
}
}
}
interface ScheduleRvAdapterListener {
fun itemClick(v: View?, position: Int)
fun itemCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean, position: Int)
}
} | 1 | null | 1 | 1 | 387a68ede15df55eb95477515452f415fdd23e19 | 3,281 | NoteBook | Apache License 2.0 |
app/src/androidTest/java/com/gmail/uia059466/automatoruisample/viewmodeltest/ResetPasswordViewModelTest.kt | serhiq | 321,547,595 | false | null | package com.gmail.uia059466.automatoruisample.viewmodeltest
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.gmail.uia059466.automatoruisample.R
import com.gmail.uia059466.automatoruisample.data.FieldState
import com.gmail.uia059466.automatoruisample.data.ResultRequest
import com.gmail.uia059466.automatoruisample.data.UserRepository
import com.gmail.uia059466.automatoruisample.getOrAwaitValue
import com.gmail.uia059466.automatoruisample.resetpassword.ResetPasswordViewModel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
@RunWith(AndroidJUnit4::class)
class ResetPasswordViewModelTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Mock
lateinit var repository: UserRepository
lateinit var viewModel: ResetPasswordViewModel
private val email = "<EMAIL>"
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
viewModel = ResetPasswordViewModel(repository)
}
@Test
fun whenResetSucceed_expectDisplayDialog() {
val resultRequest = ResultRequest.Success<String>(email)
Mockito.`when`(repository.resetPassword(email)).thenReturn(resultRequest)
viewModel.validateAndReset(email)
assertTrue(viewModel.showEmailSentDialog.getOrAwaitValue())
}
@Test
fun whenResetFailed_expectDisplaySnackbar() {
val resultRequest = ResultRequest.Error(R.string.email_address_no_exist)
Mockito.`when`(repository.resetPassword(email)).thenReturn(resultRequest)
viewModel.validateAndReset(email)
assertTrue(viewModel.snackbarText.getOrAwaitValue() == R.string.email_address_no_exist)
}
@Test
fun resetDataChanged_withInvalidEmail() {
viewModel.emailChanged("df")
val expected = FieldState.Invalid(R.string.invalid_email)
val actual = viewModel.state.getOrAwaitValue()
assertEquals(expected, actual)
}
@Test
fun resetDataChanged_withEmptyEmail() {
viewModel.emailChanged("")
val expected = FieldState.Invalid(R.string.missing_email_address)
val actual = viewModel.state.getOrAwaitValue()
assertEquals(expected, actual)
}
} | 0 | Kotlin | 1 | 0 | 839bcdaca2d0e66704717a7700eafc429d90b961 | 2,417 | Espresso-Login-Sample | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/auth/ui/restore_error/RestoreErrorScreenPresenter.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252} | package org.p2p.wallet.auth.ui.restore_error
import org.p2p.wallet.auth.interactor.OnboardingInteractor
import org.p2p.wallet.auth.interactor.restore.RestoreWalletInteractor
import org.p2p.wallet.auth.model.RestoreError
import org.p2p.wallet.auth.model.RestoreFailureState
import org.p2p.wallet.auth.model.RestoreSuccessState
import org.p2p.wallet.auth.repository.RestoreUserResultHandler
import org.p2p.wallet.auth.statemachine.RestoreStateMachine
import org.p2p.wallet.common.mvp.BasePresenter
import timber.log.Timber
import kotlinx.coroutines.launch
class RestoreErrorScreenPresenter(
private val restoreFailureState: RestoreFailureState.TitleSubtitleError,
private val restoreWalletInteractor: RestoreWalletInteractor,
private val onboardingInteractor: OnboardingInteractor,
private val restoreUserResultHandler: RestoreUserResultHandler,
private val restoreStateMachine: RestoreStateMachine
) :
BasePresenter<RestoreErrorScreenContract.View>(),
RestoreErrorScreenContract.Presenter {
override fun attach(view: RestoreErrorScreenContract.View) {
super.attach(view)
view.showState(restoreFailureState)
}
override fun useGoogleAccount() {
view?.startGoogleFlow()
}
override fun setGoogleIdToken(userId: String, idToken: String) {
launch {
view?.setLoadingState(isLoading = true)
restoreWalletInteractor.obtainTorusKey(userId = userId, idToken = idToken)
onboardingInteractor.currentFlow = restoreStateMachine.getSocialFlow()
restoreUserWithShares()
view?.setLoadingState(isLoading = false)
}
}
override fun useCustomShare() {
onboardingInteractor.currentFlow = restoreStateMachine.getCustomFlow()
restoreWalletInteractor.resetUserPhoneNumber()
view?.navigateToPhoneEnter()
}
override fun onStartScreenClicked() {
restoreWalletInteractor.resetUserPhoneNumber()
view?.navigateToStartScreen()
}
private suspend fun restoreUserWithShares() {
val restoreResult = restoreWalletInteractor.tryRestoreUser(restoreStateMachine.getSocialFlow())
when (val restoreHandledState = restoreUserResultHandler.handleRestoreResult(restoreResult)) {
is RestoreSuccessState -> {
restoreWalletInteractor.finishAuthFlow()
view?.navigateToPinCreate()
}
is RestoreFailureState.TitleSubtitleError -> {
view?.restartWithState(restoreHandledState)
}
is RestoreFailureState.ToastError -> {
view?.showUiKitSnackBar(message = restoreHandledState.message)
}
is RestoreFailureState.LogError -> {
Timber.e(RestoreError(restoreHandledState.message))
}
}
}
}
| 8 | Kotlin | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 2,849 | key-app-android | MIT License |
src/main/kotlin/krafana/GridPos.kt | asubb | 562,912,474 | false | {"Kotlin": 91993} | package krafana
import kotlinx.serialization.Serializable
import java.lang.Integer.max
@Serializable
data class GridPos(
var x: Int,
var y: Int,
var w: Int,
var h: Int,
)
interface GridPosSequence {
fun next(w: Int? = null, h: Int? = null): GridPos
fun closeRow()
}
const val defaultGridHeight = 10
const val gridMaxWidth = 24
fun DashboardParams.fullWidth(height: Int = defaultGridHeight): GridPos = gridPosSequence.next(24, height)
fun constant(width: Int = 24, height: Int = defaultGridHeight): GridPosSequence {
return object : GridPosSequence {
override fun next(w: Int?, h: Int?): GridPos = GridPos(0, 0, w ?: width, h ?: height)
override fun closeRow() {
// nothing to do
}
}
}
fun tileOneThird(height: Int = defaultGridHeight): GridPosSequence {
return tile(width = gridMaxWidth / 3, height)
}
fun tileOneForth(height: Int = defaultGridHeight): GridPosSequence {
return tile(width = gridMaxWidth / 4, height)
}
fun tile(width: Int = gridMaxWidth / 2, height: Int = defaultGridHeight): GridPosSequence {
require(width in 1..gridMaxWidth) { "Width should be greater than zero but less than $gridMaxWidth, but found: $width" }
require(height > 0) { "Height should be greater that zero" }
var row = 0
var col = 0
var prevH = height
return object : GridPosSequence {
override fun next(w: Int?, h: Int?): GridPos {
val gridPos = GridPos(col, row, w ?: width, h ?: height)
if (h != null) prevH = max(h, height)
col += w ?: width
if (col >= gridMaxWidth) {
row += prevH
prevH = height
col = 0
}
return gridPos
}
override fun closeRow() {
row += prevH
prevH = height
col = 0
}
}
} | 0 | Kotlin | 0 | 1 | 382f36b5fd11cdd888ff9d1d9d74ff17f5d38a3d | 1,881 | krafana | Apache License 2.0 |
graphql-dgs-spring-webmvc/src/main/kotlin/com/netflix/graphql/dgs/mvc/DgsRestController.kt | Netflix | 317,375,887 | false | null | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.graphql.dgs.mvc
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.exc.MismatchedInputException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.netflix.graphql.dgs.DgsExecutionResult
import com.netflix.graphql.dgs.DgsQueryExecutor
import com.netflix.graphql.dgs.internal.utils.MultipartVariableMapper
import com.netflix.graphql.dgs.internal.utils.TimeTracer
import com.netflix.graphql.dgs.internal.utils.VariableMappingException
import graphql.execution.reactive.SubscriptionPublisher
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.WebRequest
import org.springframework.web.multipart.MultipartFile
import java.io.InputStream
/**
* HTTP entrypoint for the framework. Functionality in this class should be limited, so that as much code as possible
* is reused between different transport protocols and the testing framework.
*
* In addition to regular graphql queries, this method also handles multipart POST requests containing files for upload.
* This is usually a POST request that has Content type set to multipart/form-data. Here is an example command.
*
* Each part in a multipart request is identified by the -F and is identified by the part name - "operations, map etc."
* The "operations" part is the graphql query containing the mutation for the file upload, with variables for files set to null.
* The "map" part and the subsequent parts specify the path of the file in the variables of the query, and will get mapped to
* construct the graphql query that looks like this:
*
* {"query": "mutation ($input: FileUploadInput!) { uploadFile(input: $input) }",
* "variables": { "input": { "description": "test", "files": [file1.txt, file2.txt] } }
*
* where files map to one or more MultipartFile(s)
*
* The remaining parts in the request contain the mapping of file name to file path, i.e. a map of MultipartFile(s)
* The format of a multipart request is also described here:
* https://github.com/jaydenseric/graphql-multipart-request-spec
*
* This class is defined as "open" only for proxy/aop use cases. It is not considered part of the API, and backwards compatibility is not guaranteed.
* Do not manually extend this class.
*/
@RestController
open class DgsRestController(
open val dgsQueryExecutor: DgsQueryExecutor,
open val mapper: ObjectMapper = jacksonObjectMapper(),
open val dgsGraphQLRequestHeaderValidator: DgsGraphQLRequestHeaderValidator = DefaultDgsGraphQLRequestHeaderValidator()
) {
companion object {
// defined in here and DgsExecutionResult, for backwards compatibility.
// keep these two variables synced.
const val DGS_RESPONSE_HEADERS_KEY = DgsExecutionResult.DGS_RESPONSE_HEADERS_KEY
private val logger: Logger = LoggerFactory.getLogger(DgsRestController::class.java)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class InputQuery(
val query: String?,
val operationName: String? = null,
val variables: Map<String, Any>? = mapOf(),
val extensions: Map<String, Any>? = mapOf()
)
}
// The @ConfigurationProperties bean name is <prefix>-<fqn>
// TODO Allow users to disable multipart-form/data
@RequestMapping(
"#{ environment['dgs.graphql.path'] ?: '/graphql' }",
consumes = [MediaType.APPLICATION_JSON_VALUE, GraphQLMediaTypes.GRAPHQL_MEDIA_TYPE_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
fun graphql(
body: InputStream,
@RequestHeader headers: HttpHeaders,
webRequest: WebRequest
): ResponseEntity<Any> {
val result = errorResponseForInvalid(headers)
if (result != null) {
return result
}
logger.debug("Starting HTTP GraphQL handling...")
val inputQuery: InputQuery
if (GraphQLMediaTypes.includesApplicationGraphQL(headers)) {
inputQuery = InputQuery(query = body.bufferedReader().readText())
} else {
try {
inputQuery = mapper.readValue(body)
} catch (ex: Exception) {
return when (ex) {
is JsonParseException ->
ResponseEntity.badRequest()
.body("Invalid query - ${ex.message ?: "no details found in the error message"}.")
is MismatchedInputException ->
ResponseEntity.badRequest()
.body("Invalid query - No content to map to input.")
else ->
ResponseEntity.badRequest()
.body("Invalid query - ${ex.message ?: "no additional details found"}.")
}
}
}
return executeQuery(inputQuery = inputQuery, headers = headers, webRequest = webRequest)
}
@RequestMapping(
"#{ environment['dgs.graphql.path'] ?: '/graphql' }",
consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
fun graphQlMultipart(
@RequestParam fileParams: Map<String, MultipartFile>,
@RequestParam(name = "operations") operation: String,
@RequestParam(name = "map") mapParam: String,
@RequestHeader headers: HttpHeaders,
webRequest: WebRequest
): ResponseEntity<Any> {
val result = errorResponseForInvalid(headers)
if (result != null) {
return result
}
val inputQuery: InputQuery = mapper.readValue(operation)
// parse the '-F map' of MultipartFile(s) containing object paths
val variables = inputQuery.variables?.toMutableMap()
?: return ResponseEntity.badRequest().body("No variables specified as part of multipart request")
val fileMapInput: Map<String, List<String>> = mapper.readValue(mapParam)
try {
fileMapInput.forEach { (fileKey, objectPaths) ->
val file = fileParams[fileKey]
if (file != null) {
// the variable mapper takes each multipart file and replaces the null portion of the query variables with the file
objectPaths.forEach { objectPath ->
MultipartVariableMapper.mapVariable(
objectPath,
variables,
file
)
}
}
}
} catch (exc: VariableMappingException) {
return ResponseEntity.badRequest()
.body("Failed mapping file upload to variable: ${exc.message}")
}
return executeQuery(
inputQuery = inputQuery.copy(variables = variables),
headers = headers,
webRequest = webRequest
)
}
private fun errorResponseForInvalid(headers: HttpHeaders): ResponseEntity<Any>? {
logger.debug("Validate HTTP Headers for the GraphQL endpoint...")
try {
dgsGraphQLRequestHeaderValidator.assert(headers)
} catch (e: DgsGraphQLRequestHeaderValidator.GraphqlRequestContentTypePredicateException) {
logger.debug("Unsupported Media-Type {}.", headers.contentType, e)
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
.body("Unsupported media type.")
} catch (e: DgsGraphQLRequestHeaderValidator.GraphQLRequestHeaderRuleException) {
logger.debug("The Request Headers failed a DGS Header validation rule.", e)
return ResponseEntity.badRequest().body(e.message)
} catch (e: DgsGraphQLRequestHeaderValidator.GraphqlRequestHeaderValidationException) {
logger.debug("The DGS Request Header Validator deemed the request headers as invalid.", e)
return ResponseEntity.badRequest().body(e.message)
} catch (e: Exception) {
logger.error("The DGS Request Header Validator failed with exception!", e)
return ResponseEntity.internalServerError().body("Unable to validate the HTTP Request Headers.")
}
return null
}
private fun executeQuery(
inputQuery: InputQuery,
headers: HttpHeaders,
webRequest: WebRequest
): ResponseEntity<Any> {
val executionResult = TimeTracer.logTime(
{
dgsQueryExecutor.execute(
inputQuery.query,
inputQuery.variables.orEmpty(),
inputQuery.extensions,
headers,
inputQuery.operationName,
webRequest
)
},
logger,
"Executed query in {}ms"
)
logger.debug(
"Execution result - Contains data: '{}' - Number of errors: {}",
executionResult.isDataPresent,
executionResult.errors.size
)
if (executionResult.isDataPresent && executionResult.getData<Any>() is SubscriptionPublisher) {
return ResponseEntity.badRequest()
.body("Trying to execute subscription on /graphql. Use /subscriptions instead!")
}
return when (executionResult) {
is DgsExecutionResult -> executionResult.toSpringResponse()
else -> DgsExecutionResult.builder().executionResult(executionResult).build().toSpringResponse()
}
}
}
| 94 | null | 289 | 3,037 | bd2d0c524e70a9d1d625d518a94926c7b53a7e7c | 10,740 | dgs-framework | Apache License 2.0 |
video_1.kt | BrunoOmoreschi | 383,563,170 | false | {"Kotlin": 22442} | //Codigo feito no VS Code
//Função principal
fun main() {
println(Int.MAX_VALUE)
println(Double.MAX_VALUE)
println(Float.MAX_VALUE)
println(Byte.MAX_VALUE)
}
//Operadores de conversão:
//toByte()
//toShort()
//toInt()
//toLong()
//toFloat()
//toDouble()
//toChar()
//toString() | 0 | Kotlin | 0 | 0 | c9706d3741cf6eeffd76f2b64e1aafbce80e4b15 | 295 | dio_inter_kotlin_intro | MIT License |
libPlayer/src/main/java/io/github/toyota32k/lib/player/model/PlaylistMediaFeed.kt | toyota-m2k | 802,415,713 | false | {"Kotlin": 163195} | package io.github.toyota32k.lib.player.model
import io.github.toyota32k.binder.list.ObservableList
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map
import kotlin.math.max
import kotlin.math.min
@Suppress("unused")
class PlaylistMediaFeed : IMediaFeed {
override val hasNext = MutableStateFlow(false)
override val hasPrevious = MutableStateFlow(false)
override val currentSource = MutableStateFlow<IMediaSource?>(null)
val currentIndexFlow by lazy { currentSource.map { if(it==null) -1 else videoSources.indexOf(it) } }
val currentIndex get() = currentSource.value?.let { videoSources.indexOf(it) } ?: -1
private val videoSources = ObservableList<IMediaSource>()
private fun sourceAt(index:Int):IMediaSource? {
return if(0<=index&&index<videoSources.size) {
videoSources[index]
} else null
}
override fun next() {
val index = videoSources.indexOf(currentSource.value)
currentSource.value = sourceAt(index+1) ?: return
}
override fun previous() {
val index = videoSources.indexOf(currentSource.value)
currentSource.value = sourceAt(index-1) ?: return
}
private fun reset() {
hasPrevious.value = false
hasNext.value = false
currentSource.value = null
videoSources.clear()
}
fun setSources(sources:List<IMediaSource>, startIndex:Int=0, position:Long=0L) {
reset()
videoSources.addAll(sources)
if (sources.isNotEmpty()) {
val si = max(0, min(startIndex, sources.size))
val pos = max(sources[si].trimming.start, position)
val src = sources[si]
src.startPosition.set(pos)
hasNext.value = si<sources.size-1
hasPrevious.value = 0<si
currentSource.value = src
}
}
fun isCurrentSource(index:Int):Boolean {
return index == currentIndex
}
fun isCurrentSource(src:IMediaSource):Boolean {
return src === currentSource.value
}
fun playAt(src:IMediaSource?, position: Long=0L):Boolean {
val index = videoSources.indexOf(src?:return false)
if(index<0) return false
return playAt(index, position)
}
fun playAt(index:Int, position:Long=0L):Boolean {
val src = sourceAt(index) ?: return false
src.startPosition.set(position)
currentSource.value = src
hasPrevious.value = 0<index
hasNext.value = index<videoSources.size-1
return true
}
} | 2 | Kotlin | 0 | 0 | c4da942036eb6e746718e38789ccc53e9aa03bb2 | 2,554 | android-media-player | Apache License 2.0 |
projects/custody-key-dates-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/integrations/prison/SentenceDetail.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 3846531, "HTML": 58177, "D2": 30565, "Ruby": 25392, "Shell": 12351, "SCSS": 6240, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1344, "Python": 268} | package uk.gov.justice.digital.hmpps.integrations.prison
import com.fasterxml.jackson.annotation.JsonAlias
import java.time.LocalDate
class SentenceDetail(
val sentenceExpiryDate: LocalDate? = null,
val confirmedReleaseDate: LocalDate? = null,
conditionalReleaseDate: LocalDate? = null,
conditionalReleaseOverrideDate: LocalDate? = null,
val licenceExpiryDate: LocalDate? = null,
val paroleEligibilityDate: LocalDate? = null,
@JsonAlias("topupSupervisionExpiryDate")
val postSentenceSupervisionEndDate: LocalDate? = null,
val homeDetentionCurfewEligibilityDate: LocalDate? = null
) {
val conditionalReleaseDate = conditionalReleaseOverrideDate ?: conditionalReleaseDate
}
| 15 | Kotlin | 0 | 2 | f53146f969b1acf4dbd147a5d588c5ad23c15a78 | 714 | hmpps-probation-integration-services | MIT License |
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceHolder.kt | ExiaHan | 119,199,272 | true | {"Gradle": 3, "Markdown": 4, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "XML": 216, "Kotlin": 394, "Java": 9} | package eu.kanade.tachiyomi.ui.catalogue
import android.os.Build
import android.view.View
import android.view.ViewGroup
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder
import eu.kanade.tachiyomi.util.dpToPx
import eu.kanade.tachiyomi.util.getRound
import eu.kanade.tachiyomi.util.gone
import eu.kanade.tachiyomi.util.visible
import io.github.mthli.slice.Slice
import kotlinx.android.synthetic.main.catalogue_main_controller_card_item.*
class SourceHolder(view: View, adapter: CatalogueAdapter) : BaseFlexibleViewHolder(view, adapter) {
private val slice = Slice(card).apply {
setColor(adapter.cardBackground)
}
init {
source_browse.setOnClickListener {
adapter.browseClickListener.onBrowseClick(adapterPosition)
}
source_latest.setOnClickListener {
adapter.latestClickListener.onLatestClick(adapterPosition)
}
}
fun bind(item: SourceItem) {
val source = item.source
setCardEdges(item)
// Set source name
title.text = source.name
// Set circle letter image.
itemView.post {
image.setImageDrawable(image.getRound(source.name.take(1).toUpperCase(),false))
}
// If source is login, show only login option
if (source is LoginSource && !source.isLogged()) {
source_browse.setText(R.string.login)
source_latest.gone()
} else {
source_browse.setText(R.string.browse)
source_latest.visible()
}
}
private fun setCardEdges(item: SourceItem) {
// Position of this item in its header. Defaults to 0 when header is null.
var position = 0
// Number of items in the header of this item. Defaults to 1 when header is null.
var count = 1
if (item.header != null) {
val sectionItems = mAdapter.getSectionItems(item.header)
position = sectionItems.indexOf(item)
count = sectionItems.size
}
when {
// Only one item in the card
count == 1 -> applySlice(2f, false, false, true, true)
// First item of the card
position == 0 -> applySlice(2f, false, true, true, false)
// Last item of the card
position == count - 1 -> applySlice(2f, true, false, false, true)
// Middle item
else -> applySlice(0f, false, false, false, false)
}
}
private fun applySlice(radius: Float, topRect: Boolean, bottomRect: Boolean,
topShadow: Boolean, bottomShadow: Boolean) {
slice.setRadius(radius)
slice.showLeftTopRect(topRect)
slice.showRightTopRect(topRect)
slice.showLeftBottomRect(bottomRect)
slice.showRightBottomRect(bottomRect)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
slice.showTopEdgeShadow(topShadow)
slice.showBottomEdgeShadow(bottomShadow)
}
setMargins(margin, if (topShadow) margin else 0, margin, if (bottomShadow) margin else 0)
}
private fun setMargins(left: Int, top: Int, right: Int, bottom: Int) {
val v = card
if (v.layoutParams is ViewGroup.MarginLayoutParams) {
val p = v.layoutParams as ViewGroup.MarginLayoutParams
p.setMargins(left, top, right, bottom)
}
}
companion object {
val margin = 8.dpToPx
}
} | 0 | Kotlin | 0 | 1 | 1a811d09179ba1beefeaebc1fa2a70466e8f2c14 | 3,551 | TachiyomiEH | Apache License 2.0 |
skiko/src/nativeTest/kotlin/org/jetbrains/skiko/tests/TestUtils.native.kt | DevSrSouza | 419,413,903 | true | {"C++": 1336286, "Kotlin": 1204053, "Objective-C++": 20637, "Dockerfile": 2426, "JavaScript": 929, "C": 704, "Shell": 555} | package org.jetbrains.skiko.tests
import kotlinx.coroutines.runBlocking
import org.jetbrains.skia.impl.InteropScope
import org.jetbrains.skia.impl.NativePointer
annotation class DoNothing
actual typealias IgnoreTestOnJvm = DoNothing
actual fun runTest(block: suspend () -> Unit) {
runBlocking { block() }
}
actual fun InteropScope.allocateBytesForPixels(size: Int): NativePointer {
return toInterop(ByteArray(size))
}
| 0 | null | 0 | 0 | ef87664647269ad7cec3cc12485f31c6bf3edd2a | 430 | skiko | Apache License 2.0 |
src/main/kotlin/link/infra/packwiz/installer/DownloadTask.kt | packwiz | 186,296,888 | false | null | package link.infra.packwiz.installer
import link.infra.packwiz.installer.metadata.IndexFile
import link.infra.packwiz.installer.metadata.ManifestFile
import link.infra.packwiz.installer.metadata.hash.Hash
import link.infra.packwiz.installer.metadata.hash.HashFormat
import link.infra.packwiz.installer.request.RequestException
import link.infra.packwiz.installer.target.ClientHolder
import link.infra.packwiz.installer.target.Side
import link.infra.packwiz.installer.target.path.PackwizFilePath
import link.infra.packwiz.installer.ui.data.ExceptionDetails
import link.infra.packwiz.installer.ui.data.IOptionDetails
import link.infra.packwiz.installer.util.Log
import okio.Buffer
import okio.HashingSink
import okio.blackholeSink
import okio.buffer
import java.io.IOException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
internal class DownloadTask private constructor(val metadata: IndexFile.File, val index: IndexFile, private val downloadSide: Side) : IOptionDetails {
var cachedFile: ManifestFile.File? = null
private var err: Exception? = null
val exceptionDetails get() = err?.let { e -> ExceptionDetails(name, e) }
fun failed() = err != null
var alreadyUpToDate = false
private var metadataRequired = true
private var invalidated = false
// If file is new or isOptional changed to true, the option needs to be presented again
private var newOptional = true
val isOptional get() = metadata.linkedFile?.option?.optional ?: false
fun isNewOptional() = isOptional && newOptional
fun correctSide() = metadata.linkedFile?.side?.let { downloadSide.hasSide(it) } ?: true
override val name get() = metadata.name
// Ensure that an update is done if it changes from false to true, or from true to false
override var optionValue: Boolean
get() = cachedFile?.optionValue ?: true
set(value) {
if (value && !optionValue) { // Ensure that an update is done if it changes from false to true, or from true to false
alreadyUpToDate = false
}
cachedFile?.optionValue = value
}
override val optionDescription get() = metadata.linkedFile?.option?.description ?: ""
fun invalidate() {
invalidated = true
alreadyUpToDate = false
}
fun updateFromCache(cachedFile: ManifestFile.File?) {
if (err != null) return
if (cachedFile == null) {
this.cachedFile = ManifestFile.File()
return
}
this.cachedFile = cachedFile
if (!invalidated) {
val currHash = try {
metadata.getHashObj(index)
} catch (e: Exception) {
err = e
return
}
if (currHash == cachedFile.hash) { // Already up to date
alreadyUpToDate = true
metadataRequired = false
}
}
if (cachedFile.isOptional) {
// Because option selection dialog might set this task to true/false, metadata is always needed to download
// the file, and to show the description and name
metadataRequired = true
}
}
fun downloadMetadata(clientHolder: ClientHolder) {
if (err != null) return
if (metadataRequired) {
try {
// Retrieve the linked metadata file
metadata.downloadMeta(index, clientHolder)
} catch (e: Exception) {
err = e
return
}
cachedFile?.let { cachedFile ->
val linkedFile = metadata.linkedFile
if (linkedFile != null) {
if (linkedFile.option.optional) {
if (cachedFile.isOptional) {
// isOptional didn't change
newOptional = false
} else {
// isOptional false -> true, set option to it's default value
// TODO: preserve previous option value, somehow??
cachedFile.optionValue = linkedFile.option.defaultValue
}
}
}
cachedFile.isOptional = isOptional
cachedFile.onlyOtherSide = !correctSide()
}
}
}
/**
* Check if the file in the destination location is already valid
* Must be done after metadata retrieval
*/
fun validateExistingFile(packFolder: PackwizFilePath, clientHolder: ClientHolder) {
if (!alreadyUpToDate) {
try {
// TODO: only do this for files that didn't exist before or have been modified since last full update?
val destPath = metadata.destURI.rebase(packFolder)
destPath.source(clientHolder).use { src ->
// TODO: clean up duplicated code
val hash: Hash<*>
val fileHashFormat: HashFormat<*>
val linkedFile = metadata.linkedFile
if (linkedFile != null) {
hash = linkedFile.hash
fileHashFormat = linkedFile.download.hashFormat
} else {
hash = metadata.getHashObj(index)
fileHashFormat = metadata.hashFormat(index)
}
val fileSource = fileHashFormat.source(src)
fileSource.buffer().readAll(blackholeSink())
if (hash == fileSource.hash) {
alreadyUpToDate = true
// Update the manifest file
cachedFile = (cachedFile ?: ManifestFile.File()).also {
try {
it.hash = metadata.getHashObj(index)
} catch (e: Exception) {
err = e
return
}
it.isOptional = isOptional
it.cachedLocation = metadata.destURI.rebase(packFolder)
metadata.linkedFile?.let { linked ->
try {
it.linkedFileHash = linked.hash
} catch (e: Exception) {
err = e
}
}
}
}
}
} catch (e: RequestException) {
// Ignore exceptions; if the file doesn't exist we'll be downloading it
} catch (e: IOException) {
// Ignore exceptions; if the file doesn't exist we'll be downloading it
}
}
}
fun download(packFolder: PackwizFilePath, clientHolder: ClientHolder) {
if (err != null) return
// Exclude wrong-side and optional false files
cachedFile?.let {
if ((it.isOptional && !it.optionValue) || !correctSide()) {
if (it.cachedLocation != null) {
// Ensure wrong-side or optional false files are removed
try {
Files.deleteIfExists(it.cachedLocation!!.nioPath)
} catch (e: IOException) {
Log.warn("Failed to delete file", e)
}
}
it.cachedLocation = null
return
}
}
if (alreadyUpToDate) return
val destPath = metadata.destURI.rebase(packFolder)
// Don't update files marked with preserve if they already exist on disk
if (metadata.preserve) {
if (destPath.nioPath.toFile().exists()) {
return
}
}
// TODO: add .disabled support?
try {
val hash: Hash<*>
val fileHashFormat: HashFormat<*>
val linkedFile = metadata.linkedFile
if (linkedFile != null) {
hash = linkedFile.hash
fileHashFormat = linkedFile.download.hashFormat
} else {
hash = metadata.getHashObj(index)
fileHashFormat = metadata.hashFormat(index)
}
val src = metadata.getSource(clientHolder)
val fileSource = fileHashFormat.source(src)
val data = Buffer()
// Read all the data into a buffer (very inefficient for large files! but allows rollback if hash check fails)
// TODO: should we instead rename the existing file, then stream straight to the file and rollback from the renamed file?
fileSource.buffer().use {
it.readAll(data)
}
if (hash == fileSource.hash) {
// isDirectory follows symlinks, but createDirectories doesn't
try {
Files.createDirectories(destPath.parent.nioPath)
} catch (e: java.nio.file.FileAlreadyExistsException) {
if (!Files.isDirectory(destPath.parent.nioPath)) {
throw e
}
}
Files.copy(data.inputStream(), destPath.nioPath, StandardCopyOption.REPLACE_EXISTING)
data.clear()
} else {
// TODO: move println to something visible in the error window
println("Invalid hash for " + metadata.destURI.toString())
println("Calculated: " + fileSource.hash)
println("Expected: $hash")
// Attempt to get the SHA256 hash
val sha256 = HashingSink.sha256(blackholeSink())
data.readAll(sha256)
println("SHA256 hash value: " + sha256.hash)
err = Exception("Hash invalid!")
data.clear()
return
}
cachedFile?.cachedLocation?.let {
if (destPath != it) {
// Delete old file if location changes
try {
Files.delete(cachedFile!!.cachedLocation!!.nioPath)
} catch (e: IOException) {
// Continue, as it was probably already deleted?
// TODO: log it
}
}
}
} catch (e: Exception) {
err = e
return
}
// Update the manifest file
cachedFile = (cachedFile ?: ManifestFile.File()).also {
try {
it.hash = metadata.getHashObj(index)
} catch (e: Exception) {
err = e
return
}
it.isOptional = isOptional
it.cachedLocation = metadata.destURI.rebase(packFolder)
metadata.linkedFile?.let { linked ->
try {
it.linkedFileHash = linked.hash
} catch (e: Exception) {
err = e
}
}
}
}
companion object {
fun createTasksFromIndex(index: IndexFile, downloadSide: Side): MutableList<DownloadTask> {
val tasks = ArrayList<DownloadTask>()
for (file in index.files) {
tasks.add(DownloadTask(file, index, downloadSide))
}
return tasks
}
}
} | 32 | null | 6 | 45 | 7420866dfc6ae1f68079a166e9804b7ec31a59ca | 8,904 | packwiz-installer | MIT License |
adam/src/main/kotlin/com/malinskiy/adam/request/reverse/ReversePortForwardingRule.kt | Malinskiy | 200,235,738 | false | {"Kotlin": 770806, "Shell": 1553, "Java": 1414} | /*
* Copyright (C) 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.malinskiy.adam.request.reverse
import com.malinskiy.adam.request.forwarding.LocalPortSpec
import com.malinskiy.adam.request.forwarding.RemotePortSpec
data class ReversePortForwardingRule(
val serial: String,
val localSpec: RemotePortSpec,
val remoteSpec: LocalPortSpec
) | 3 | Kotlin | 31 | 441 | f206bc96e4927ce07e5421f9ac2449b34ac3027c | 892 | adam | Apache License 2.0 |
kontroller/src/test/kotlin/no/ssb/kostra/validation/rule/barnevern/individrule/Individ10Test.kt | statisticsnorway | 414,216,275 | false | {"Kotlin": 1574039, "TypeScript": 57803, "Batchfile": 6608, "HTML": 694, "SCSS": 110} | package no.ssb.kostra.validation.rule.barnevern.individrule
import io.kotest.core.spec.style.BehaviorSpec
import no.ssb.kostra.SharedConstants.OSLO_MUNICIPALITY_ID
import no.ssb.kostra.validation.report.Severity
import no.ssb.kostra.validation.rule.ForAllRowItem
import no.ssb.kostra.validation.rule.KostraTestFactory.validationRuleWithArgsTest
import no.ssb.kostra.validation.rule.RuleTestData.argumentsInTest
import no.ssb.kostra.validation.rule.barnevern.individrule.IndividRuleTestData.individInTest
class Individ10Test : BehaviorSpec({
include(
validationRuleWithArgsTest(
sut = Individ10(),
expectedSeverity = Severity.ERROR,
expectedContextId = individInTest.id,
ForAllRowItem(
description = "individ without bydelsnavn",
individInTest.copy(bydelsnavn = null),
arguments = argumentsInTest.copy(region = "123400")
),
ForAllRowItem(
description = "individ with bydelsnavn, Oslo",
context = individInTest,
arguments = argumentsInTest.copy(region = "${OSLO_MUNICIPALITY_ID}14")
),
ForAllRowItem(
description = "individ without bydelsnavn, Oslo",
context = individInTest.copy(bydelsnavn = null),
expectedErrorMessage = "Filen mangler bydelsnavn.",
arguments = argumentsInTest.copy(region = "${OSLO_MUNICIPALITY_ID}14")
)
)
)
})
| 2 | Kotlin | 0 | 1 | b198a1263ddd1889f67043a7d55c44c935ade9fc | 1,524 | kostra-kontrollprogram | MIT License |
http4k-security-oauth/src/main/kotlin/org/http4k/security/oauth/server/AccessTokens.kt | s1monw1 | 209,880,847 | false | {"Gradle": 38, "Text": 6, "Shell": 13, "JSON": 3, "Markdown": 74, "Ignore List": 3, "Batchfile": 1, "YAML": 3, "Kotlin": 655, "XML": 5, "JavaScript": 5, "Java": 6, "HTML": 20, "Java Properties": 3, "Handlebars": 10, "CSS": 1, "OASv3-json": 3, "HTTP": 1, "Gradle Kotlin DSL": 2} | package org.http4k.security.oauth.server
import com.natpryce.Result
import org.http4k.security.AccessToken
/**
* Provides a consistent way to generate access tokens.
*/
interface AccessTokens {
/**
* Creates a new access token for a valid authorization code.
*/
fun create(authorizationCode: AuthorizationCode): Result<AccessToken, AuthorizationCodeAlreadyUsed>
/**
* creates a new access token for a given client.
*/
fun create(clientId: ClientId): Result<AccessToken, AccessTokenError>
} | 1 | null | 1 | 1 | ab19c6a570b2bb2121eb86e240e2f7e433cb2d45 | 530 | http4k | Apache License 2.0 |
save-frontend-common/src/main/kotlin/com/saveourtool/save/frontend/common/components/views/usersettings/right/profile/AvatarSelector.kt | saveourtool | 300,279,336 | false | {"Kotlin": 3391753, "SCSS": 86430, "JavaScript": 8966, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366} | /**
* Utilities for rendering avatars
*/
@file:Suppress("FILE_NAME_MATCH_CLASS")
package com.saveourtool.save.frontend.common.components.views.usersettings.right.profile
import com.saveourtool.save.frontend.common.components.basic.avatarForm
import com.saveourtool.save.frontend.common.components.views.usersettings.AVATAR_TITLE
import com.saveourtool.save.frontend.common.externals.fontawesome.faCamera
import com.saveourtool.save.frontend.common.externals.fontawesome.fontAwesomeIcon
import com.saveourtool.save.frontend.common.utils.*
import com.saveourtool.save.frontend.common.utils.UserInfoAwareMutablePropsWithChildren
import com.saveourtool.save.utils.AVATARS_PACKS_DIR
import com.saveourtool.save.utils.AvatarType.USER
import com.saveourtool.save.utils.CONTENT_LENGTH_CUSTOM
import com.saveourtool.save.utils.FILE_PART_NAME
import js.core.jso
import org.w3c.fetch.Headers
import react.*
import react.dom.html.ReactHTML.div
import react.dom.html.ReactHTML.img
import react.router.dom.Link
import web.cssom.*
import web.file.File
import web.http.FormData
import kotlinx.coroutines.await
val avatarSelector: FC<UserInfoAwareMutablePropsWithChildren> = FC { props ->
val (avatar, setAvatar) = useState<File?>(null)
val (selectedAvatar, setSelectedAvatar) = useState("")
val avatarWindowOpen = useWindowOpenness()
val setAvatarFromResources = useDeferredRequest {
val response = get(
url = "$apiUrl/avatar/avatar-update",
params = jso<dynamic> {
this.type = USER
this.resource = selectedAvatar
},
jsonHeaders,
loadingHandler = ::loadingHandler,
)
if (response.ok) {
props.userInfoSetter(props.userInfo?.copy(avatar = selectedAvatar))
}
}
val saveAvatar = useDeferredRequest {
avatar?.let {
val response = post(
url = "$apiUrl/avatar/upload",
params = jso<dynamic> {
this.owner = props.userInfo?.name
this.type = USER
},
Headers().apply { append(CONTENT_LENGTH_CUSTOM, avatar.size.toString()) },
FormData().apply { set(FILE_PART_NAME, avatar) },
loadingHandler = ::loadingHandler,
)
val text = response.text().await()
if (response.ok) {
props.userInfoSetter(props.userInfo?.copy(avatar = text))
}
}
}
// === image editor ===
avatarForm {
isOpen = avatarWindowOpen.isOpen()
title = AVATAR_TITLE
onCloseWindow = {
saveAvatar()
avatarWindowOpen.closeWindow()
}
imageUpload = { file ->
setAvatar(file)
}
}
div {
className = ClassName("row")
div {
className = ClassName("col-4")
div {
className = ClassName("row")
avatarEditor(
avatarWindowOpen,
)
}
}
div {
className = ClassName("col-8")
// render prepared preselected avatars 3 in row
var lowerBound = 1
for (i in 1..AVATARS_PACKAGE_COUNT) {
if (i % 3 == 0) {
div {
className = ClassName("row")
for (j in lowerBound..i) {
val newAvatar = "$AVATARS_PACKS_DIR/avatar$j.png"
div {
className = ClassName("animated-provider")
img {
className =
ClassName("avatar avatar-user width-full border color-bg-default rounded-circle shadow")
src = newAvatar
style = jso {
height = 5.1.rem
width = 5.1.rem
cursor = Cursor.pointer
}
onClick = {
setSelectedAvatar(newAvatar)
setAvatarFromResources()
}
}
}
}
lowerBound = i + 1
}
}
}
}
}
}
/**
* @param avatarWindowOpen
*/
internal fun ChildrenBuilder.avatarEditor(
avatarWindowOpen: WindowOpenness,
) {
Link {
className = ClassName("btn px-0 pt-0")
title = AVATAR_TITLE
onClick = {
avatarWindowOpen.openWindow()
}
div {
className = ClassName("card card-body shadow")
style = jso {
display = Display.flex
justifyContent = JustifyContent.center
height = 8.rem
width = 8.rem
}
div {
className = ClassName("row justify-content-center")
fontAwesomeIcon(faCamera, classes = "fa-xl")
}
div {
className = ClassName("row mt-2 justify-content-center")
+AVATAR_TITLE
}
}
}
}
| 202 | Kotlin | 3 | 38 | e101105f8e449253d5fbe81ece2668654d08639f | 5,454 | save-cloud | MIT License |
src/main/kotlin/io/emeraldpay/dshackle/upstream/grpc/EthereumGrpcUpstream.kt | bitindi | 692,819,625 | false | {"Kotlin": 974369, "Groovy": 712181, "Java": 21948, "JavaScript": 5522, "Shell": 646} | /**
* Copyright (c) 2020 EmeraldPay, Inc
* Copyright (c) 2019 ETCDEV GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.emeraldpay.dshackle.upstream.grpc
import io.emeraldpay.api.proto.BlockchainOuterClass
import io.emeraldpay.api.proto.ReactorBlockchainGrpc.ReactorBlockchainStub
import io.emeraldpay.dshackle.Chain
import io.emeraldpay.dshackle.Defaults
import io.emeraldpay.dshackle.config.ChainsConfig
import io.emeraldpay.dshackle.config.UpstreamsConfig
import io.emeraldpay.dshackle.data.BlockContainer
import io.emeraldpay.dshackle.data.BlockId
import io.emeraldpay.dshackle.reader.JsonRpcReader
import io.emeraldpay.dshackle.startup.QuorumForLabels
import io.emeraldpay.dshackle.upstream.BuildInfo
import io.emeraldpay.dshackle.upstream.Capability
import io.emeraldpay.dshackle.upstream.Head
import io.emeraldpay.dshackle.upstream.Lifecycle
import io.emeraldpay.dshackle.upstream.Upstream
import io.emeraldpay.dshackle.upstream.UpstreamAvailability
import io.emeraldpay.dshackle.upstream.calls.CallMethods
import io.emeraldpay.dshackle.upstream.ethereum.EthereumIngressSubscription
import io.emeraldpay.dshackle.upstream.ethereum.EthereumLikeUpstream
import io.emeraldpay.dshackle.upstream.ethereum.subscribe.EthereumDshackleIngressSubscription
import io.emeraldpay.dshackle.upstream.forkchoice.MostWorkForkChoice
import io.emeraldpay.dshackle.upstream.rpcclient.JsonRpcGrpcClient
import io.emeraldpay.dshackle.upstream.rpcclient.JsonRpcRequest
import io.emeraldpay.dshackle.upstream.rpcclient.JsonRpcResponse
import io.emeraldpay.etherjar.domain.BlockHash
import io.emeraldpay.etherjar.rpc.RpcException
import org.reactivestreams.Publisher
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import java.math.BigInteger
import java.time.Instant
import java.util.Locale
import java.util.concurrent.TimeoutException
import java.util.function.Function
open class EthereumGrpcUpstream(
private val parentId: String,
hash: Byte,
role: UpstreamsConfig.UpstreamRole,
private val chain: Chain,
private val remote: ReactorBlockchainStub,
client: JsonRpcGrpcClient,
overrideLabels: UpstreamsConfig.Labels?,
chainConfig: ChainsConfig.ChainConfig,
headScheduler: Scheduler,
) : EthereumLikeUpstream(
"${parentId}_${chain.chainCode.lowercase(Locale.getDefault())}",
hash,
UpstreamsConfig.PartialOptions.getDefaults().buildOptions(),
role,
null,
null,
chainConfig
),
GrpcUpstream,
Lifecycle {
private val blockConverter: Function<BlockchainOuterClass.ChainHead, BlockContainer> = Function { value ->
val parentHash =
if (value.parentBlockId.isBlank()) null
else BlockId.from(BlockHash.from("0x" + value.parentBlockId))
val block = BlockContainer(
value.height,
BlockId.from(BlockHash.from("0x" + value.blockId)),
BigInteger(1, value.weight.toByteArray()),
Instant.ofEpochMilli(value.timestamp),
false,
null,
null,
parentHash
)
block
}
override fun getSubscriptionTopics(): List<String> {
return subscriptionTopics
}
private val reloadBlock: Function<BlockContainer, Publisher<BlockContainer>> = Function { existingBlock ->
// head comes without transaction data
// need to download transactions for the block
defaultReader.read(JsonRpcRequest("eth_getBlockByHash", listOf(existingBlock.hash.toHexWithPrefix(), false)))
.flatMap(JsonRpcResponse::requireResult)
.map {
BlockContainer.fromEthereumJson(it, getId())
}
.timeout(timeout, Mono.error(TimeoutException("Timeout from upstream")))
.doOnError { t ->
setStatus(UpstreamAvailability.UNAVAILABLE)
val msg = "Failed to download block data for chain $chain on $parentId"
if (t is RpcException || t is TimeoutException) {
log.warn("$msg. Message: ${t.message}")
} else {
log.error(msg, t)
}
}
}
private val upstreamStatus = GrpcUpstreamStatus(overrideLabels)
private val grpcHead = GrpcHead(
getId(), chain, this, remote,
blockConverter, reloadBlock, MostWorkForkChoice(), headScheduler
)
private var capabilities: Set<Capability> = emptySet()
private val buildInfo: BuildInfo = BuildInfo()
private var subscriptionTopics = listOf<String>()
private val defaultReader: JsonRpcReader = client.getReader()
var timeout = Defaults.timeout
private val ethereumSubscriptions = EthereumDshackleIngressSubscription(chain, remote)
override fun getBlockchainApi(): ReactorBlockchainStub {
return remote
}
override fun proxySubscribe(request: BlockchainOuterClass.NativeSubscribeRequest): Flux<out Any> =
remote.nativeSubscribe(request)
override fun start() {
}
override fun isRunning(): Boolean {
return true
}
override fun stop() {
}
override fun getBuildInfo(): BuildInfo {
return buildInfo
}
override fun update(conf: BlockchainOuterClass.DescribeChain, buildInfo: BlockchainOuterClass.BuildInfo): Boolean {
val newBuildInfo = BuildInfo.extract(buildInfo)
val buildInfoChanged = this.buildInfo.update(newBuildInfo)
val newCapabilities = RemoteCapabilities.extract(conf)
val upstreamStatusChanged = (upstreamStatus.update(conf) || (newCapabilities != capabilities)).also {
capabilities = newCapabilities
}
conf.status?.let { status -> onStatus(status) }
val subsChanged = (conf.supportedSubscriptionsList != subscriptionTopics).also {
subscriptionTopics = conf.supportedSubscriptionsList
}
return buildInfoChanged || upstreamStatusChanged || subsChanged
}
override fun getQuorumByLabel(): QuorumForLabels {
return upstreamStatus.getNodes()
}
// ------------------------------------------------------------------------------------------
override fun getLabels(): Collection<UpstreamsConfig.Labels> {
return upstreamStatus.getLabels()
}
override fun getIngressSubscription(): EthereumIngressSubscription {
return ethereumSubscriptions
}
override fun getMethods(): CallMethods {
return upstreamStatus.getCallMethods()
}
override fun isAvailable(): Boolean {
return super.isAvailable() && grpcHead.getCurrent() != null && getQuorumByLabel().getAll().any {
it.quorum > 0
}
}
override fun getHead(): Head {
return grpcHead
}
override fun getIngressReader(): JsonRpcReader {
return defaultReader
}
@Suppress("UNCHECKED_CAST")
override fun <T : Upstream> cast(selfType: Class<T>): T {
if (!selfType.isAssignableFrom(this.javaClass)) {
throw ClassCastException("Cannot cast ${this.javaClass} to $selfType")
}
return this as T
}
override fun getCapabilities(): Set<Capability> {
return capabilities
}
override fun isGrpc(): Boolean {
return true
}
}
| 0 | Kotlin | 0 | 0 | 3dafa23728acfdfd046580dc0d1fcb9ba61718d4 | 7,826 | dshackle | Apache License 2.0 |
src/main/kotlin/flavor/pie/kludge/optionals.kt | widd | 140,985,383 | true | {"Kotlin": 87350} | package flavor.pie.kludge
import java.util.Optional
operator fun <T> Optional<T>?.not(): T? = this.unwrap()
fun <T: Any> T?.optional(): Optional<T> = Optional.ofNullable(this)
fun <T> Optional<T>?.unwrap(): T? = this?.orElse(null) | 0 | Kotlin | 0 | 0 | 86e95feb91795cc17090c8e44ff919da0a9ac100 | 234 | Kludge | MIT License |
data/RF02032/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02032"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
10 to 14
43 to 47
}
value = "#8babd1"
}
color {
location {
17 to 20
39 to 42
}
value = "#cd9ce5"
}
color {
location {
22 to 26
34 to 38
}
value = "#f2de09"
}
color {
location {
51 to 57
198 to 204
}
value = "#942e51"
}
color {
location {
51 to 57
198 to 204
}
value = "#942e51"
}
color {
location {
51 to 57
198 to 204
}
value = "#942e51"
}
color {
location {
207 to 216
431 to 440
}
value = "#820594"
}
color {
location {
207 to 216
431 to 440
}
value = "#820594"
}
color {
location {
236 to 240
262 to 266
}
value = "#05f6d8"
}
color {
location {
243 to 245
255 to 257
}
value = "#3c904c"
}
color {
location {
268 to 272
295 to 299
}
value = "#1355b1"
}
color {
location {
277 to 280
286 to 289
}
value = "#37005b"
}
color {
location {
302 to 306
420 to 424
}
value = "#aebe74"
}
color {
location {
316 to 319
406 to 409
}
value = "#434c73"
}
color {
location {
327 to 330
338 to 341
}
value = "#5854f2"
}
color {
location {
352 to 355
363 to 366
}
value = "#6a01a5"
}
color {
location {
371 to 373
403 to 405
}
value = "#956863"
}
color {
location {
375 to 376
400 to 401
}
value = "#da8f96"
}
color {
location {
454 to 459
469 to 474
}
value = "#affeea"
}
color {
location {
481 to 483
590 to 592
}
value = "#672ecc"
}
color {
location {
481 to 483
590 to 592
}
value = "#672ecc"
}
color {
location {
485 to 487
586 to 588
}
value = "#1672d3"
}
color {
location {
488 to 495
519 to 526
}
value = "#c19196"
}
color {
location {
535 to 539
574 to 578
}
value = "#283df2"
}
color {
location {
543 to 544
567 to 568
}
value = "#42e843"
}
color {
location {
601 to 603
619 to 621
}
value = "#1cd43b"
}
color {
location {
15 to 16
43 to 42
}
value = "#22adfe"
}
color {
location {
21 to 21
39 to 38
}
value = "#2d3992"
}
color {
location {
27 to 33
}
value = "#417a48"
}
color {
location {
58 to 197
}
value = "#f13a08"
}
color {
location {
217 to 235
267 to 267
300 to 301
425 to 430
}
value = "#d17456"
}
color {
location {
241 to 242
258 to 261
}
value = "#2c9cf0"
}
color {
location {
246 to 254
}
value = "#387611"
}
color {
location {
273 to 276
290 to 294
}
value = "#c8b9cc"
}
color {
location {
281 to 285
}
value = "#137db2"
}
color {
location {
307 to 315
410 to 419
}
value = "#ef6e7c"
}
color {
location {
320 to 326
342 to 351
367 to 370
406 to 405
}
value = "#4f0217"
}
color {
location {
331 to 337
}
value = "#073cea"
}
color {
location {
356 to 362
}
value = "#eda2fa"
}
color {
location {
374 to 374
402 to 402
}
value = "#f3d576"
}
color {
location {
377 to 399
}
value = "#0212d2"
}
color {
location {
460 to 468
}
value = "#cad34a"
}
color {
location {
484 to 484
589 to 589
}
value = "#c373c3"
}
color {
location {
488 to 487
527 to 534
579 to 585
}
value = "#77c9bd"
}
color {
location {
496 to 518
}
value = "#d3a3a6"
}
color {
location {
540 to 542
569 to 573
}
value = "#8e363f"
}
color {
location {
545 to 566
}
value = "#c6dca6"
}
color {
location {
604 to 618
}
value = "#650d54"
}
color {
location {
1 to 9
}
value = "#38278d"
}
color {
location {
48 to 50
}
value = "#24efa8"
}
color {
location {
205 to 206
}
value = "#82d89f"
}
color {
location {
441 to 453
}
value = "#f026e4"
}
color {
location {
475 to 480
}
value = "#a97564"
}
color {
location {
593 to 600
}
value = "#f1963a"
}
color {
location {
622 to 622
}
value = "#7b46c0"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 8,088 | Rfam-for-RNArtist | MIT License |
app/src/main/java/com/hongwei/android_lab/lab/compose/demo/DemoContent.kt | hongwei-bai | 364,924,389 | false | null | package com.hongwei.android_lab.lab.compose.demo
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navigate
import androidx.navigation.compose.rememberNavController
import com.hongwei.android_lab.lab.compose.demo.dataflow.DataFlowDemo
import com.hongwei.android_lab.lab.compose.demo.helloworld.HelloWorld
import com.hongwei.android_lab.lab.compose.demo.modifier.ModifierDemo
import com.hongwei.android_lab.lab.compose.demo.preview.Greetings
import com.hongwei.android_lab.lab.compose.demo.recomposition.RecompositionDemo
import com.hongwei.android_lab.lab.compose.demo.reuse.ReuseDemo
import com.hongwei.android_lab.lab.compose.demo.theming.Theming
import com.hongwei.android_lab.lab.compose.demo.theming.ThemingDemo
import com.hongwei.android_lab.lab.compose.view.RatesPage
@Composable
fun DemoContent() {
val navController = rememberNavController()
NavHost(navController, startDestination = "content") {
composable("content") {
ContentList(navController)
}
composable("hello") {
HelloWorld()
}
composable("preview") {
Greetings("Hongwei")
}
composable("recomposition") {
RecompositionDemo()
}
composable("theming") {
Theming()
}
composable("themingSample") {
ThemingDemo()
}
composable("modifier") {
ModifierDemo()
}
composable("dataflow") {
DataFlowDemo()
}
composable("reusability") {
ReuseDemo()
}
composable("irt") {
RatesPage()
}
}
}
@Composable
fun ContentList(navController: NavController) {
Column(modifier = Modifier.verticalScroll(ScrollState(0))) {
demoSections.forEach {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.clickable {
navController.navigate(it.route)
}
.height(64.dp)
.padding(horizontal = 16.dp)
) {
Text(
text = it.label,
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.primary
)
}
Divider()
}
}
}
val demoSections = listOf(
DemoSection.HelloWorld,
DemoSection.Preview,
DemoSection.Recomposition,
DemoSection.Theming,
DemoSection.ThemingSample,
DemoSection.ModifierDemo,
DemoSection.DataFlow,
DemoSection.Reusability,
DemoSection.IRTRebuild
)
sealed class DemoSection(val route: String, val label: String) {
object HelloWorld : DemoSection("hello", "Hello world")
object Preview : DemoSection("preview", "Preview")
object Recomposition : DemoSection("recomposition", "Recomposition")
object Theming : DemoSection("theming", "Theming")
object ThemingSample : DemoSection("themingsample", "Theming Sample")
object ModifierDemo : DemoSection("modifier", "Modifier Demo")
object DataFlow : DemoSection("dataflow", "Data Flow")
object Reusability : DemoSection("reusability", "Reusability")
object IRTRebuild : DemoSection("irt", "Rebuild rates & info page with Jetpack Compose")
} | 0 | Kotlin | 0 | 0 | c3fc0d4b4145f1ff537b7e4cbbceec8a831b3093 | 3,980 | android-lab | MIT License |
src/main/kotlin/com/timoh/aoc2018/second/part2/solution.kt | TimoHanisch | 159,952,280 | false | null | package com.timoh.aoc2018.second.part2
import java.io.File
fun main(args: Array<String>) {
val resource = ClassLoader.getSystemClassLoader().getResource("input/input2")
val ids = File(resource.toURI())
.useLines { it.toList() }
var id = ""
var intersect = ""
for (i in 0 until ids.size) {
for (j in 0 until ids.size) {
if (i != j) {
for (k in 0 until ids[i].length) {
if (ids[i][k] == ids[j][k]) {
intersect += ids[i][k]
}
}
if (intersect.length > id.length) {
id = intersect
}
intersect = ""
}
}
}
println(id)
} | 0 | Kotlin | 0 | 0 | 6487bb44daeb13763a90ac33c0a706d7641cfbb4 | 755 | aoc2018 | MIT License |
simter-auth-data/src/main/kotlin/tech/simter/auth/po/Role.kt | simter | 83,630,653 | false | null | package tech.simter.auth.po
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
import tech.simter.auth.ROLE_TABLE
import tech.simter.auth.po.base.Actor
import tech.simter.auth.po.base.PersistenceStatus
import java.time.OffsetDateTime
import java.time.temporal.ChronoUnit
/**
* The permission that someone has in a organization.
*
* The [branch] and [code] should be global unique.
*
* @author RJ
*/
@Table(ROLE_TABLE)
data class Role(
@Id override val id: Long,
override val status: Role.Status,
/** A convenient identity for program */
override val code: String,
override val name: String,
/**
* The directly belong to [Company].
*
* Null means this role is a common role for each [Company].
*/
override val company: Company? = null,
override val createOn: OffsetDateTime = OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)
) : Actor {
override val type: Actor.Type
get() = Actor.Type.Role
/** Equals to [company], it's useless */
override val branch: Company?
get() = this.company
/**
* The Role Status.
*
* @author RJ
*/
enum class Status(
override val value: Short
) : PersistenceStatus {
/** Can be used from now on */
Enabled(1),
/** Can not be used anymore */
Disabled(2)
}
} | 0 | Kotlin | 1 | 0 | ae55bdf48fc420dc7eeea33648106ff267c0a04d | 1,333 | simter-auth | MIT License |
opendc-simulator/opendc-simulator-core/src/main/kotlin/org/opendc/simulator/core/SimulationCoroutineDispatcher.kt | atlarge-research | 79,902,234 | false | null | /*
* Copyright (c) 2021 AtLarge Research
*
* 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 org.opendc.simulator.core
import kotlinx.coroutines.*
import java.lang.Runnable
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.util.*
import kotlin.coroutines.CoroutineContext
/**
* A [CoroutineDispatcher] that performs both immediate execution of coroutines on the main thread and uses a virtual
* clock for time management.
*/
@OptIn(InternalCoroutinesApi::class)
public class SimulationCoroutineDispatcher : CoroutineDispatcher(), SimulationController, Delay {
/**
* The virtual clock of this dispatcher.
*/
override val clock: Clock = VirtualClock()
/**
* Queue of ordered tasks to run.
*/
private val queue = PriorityQueue<TimedRunnable>()
/**
* Global order counter.
*/
private var _counter = 0L
/**
* The current virtual time of simulation
*/
private var _time = 0L
override fun dispatch(context: CoroutineContext, block: Runnable) {
block.run()
}
override fun dispatchYield(context: CoroutineContext, block: Runnable) {
post(block)
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
postDelayed(CancellableContinuationRunnable(continuation) { resumeUndispatched(Unit) }, timeMillis)
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle {
val node = postDelayed(block, timeMillis)
return object : DisposableHandle {
override fun dispose() {
queue.remove(node)
}
}
}
override fun toString(): String {
return "SimulationCoroutineDispatcher[time=${_time}ms, queued=${queue.size}]"
}
private fun post(block: Runnable) =
queue.add(TimedRunnable(block, _counter++))
private fun postDelayed(block: Runnable, delayTime: Long) =
TimedRunnable(block, _counter++, safePlus(_time, delayTime))
.also {
queue.add(it)
}
private fun safePlus(currentTime: Long, delayTime: Long): Long {
check(delayTime >= 0)
val result = currentTime + delayTime
if (result < currentTime) return Long.MAX_VALUE // clamp on overflow
return result
}
override fun advanceUntilIdle(): Long {
val queue = queue
val oldTime = _time
while (queue.isNotEmpty()) {
val current = queue.poll()
// If the scheduled time is 0 (immediate) use current virtual time
if (current.time != 0L) {
_time = current.time
}
current.run()
}
return _time - oldTime
}
private inner class VirtualClock(private val zone: ZoneId = ZoneId.systemDefault()) : Clock() {
override fun getZone(): ZoneId = zone
override fun withZone(zone: ZoneId): Clock = VirtualClock(zone)
override fun instant(): Instant = Instant.ofEpochMilli(millis())
override fun millis(): Long = _time
override fun toString(): String = "SimulationCoroutineDispatcher.VirtualClock[time=$_time]"
}
/**
* This class exists to allow cleanup code to avoid throwing for cancelled continuations scheduled
* in the future.
*/
private class CancellableContinuationRunnable<T>(
@JvmField val continuation: CancellableContinuation<T>,
private val block: CancellableContinuation<T>.() -> Unit
) : Runnable {
override fun run() = continuation.block()
}
/**
* A Runnable for our event loop that represents a task to perform at a time.
*/
private class TimedRunnable(
@JvmField val runnable: Runnable,
private val count: Long = 0,
@JvmField val time: Long = 0
) : Comparable<TimedRunnable>, Runnable by runnable {
override fun compareTo(other: TimedRunnable) = if (time == other.time) {
count.compareTo(other.count)
} else {
time.compareTo(other.time)
}
override fun toString() = "TimedRunnable[time=$time, run=$runnable]"
}
}
| 9 | null | 14 | 41 | 578394adfb5f1f835b7d8e24f68094968706dfaa | 5,318 | opendc | MIT License |
ProvaN1/app/src/main/java/thiago/araujo/provan1/SplashScreen.kt | YasminLuzia | 311,798,611 | false | null | package yasmin.luzia.projectquiz
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.ProgressBar
class SplashActivity : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
private var delayHandler: Handler? = null
private val SPLASH_DURATION: Long = 3000
internal var runnable = Runnable {
if(!isFinishing) {
val intent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
delayHandler = Handler()
delayHandler!!.postDelayed(runnable, SPLASH_DURATION)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
override fun onDestroy() {
super.onDestroy()
delayHandler?.let { it.removeCallbacks(runnable) }
}
} | 0 | Kotlin | 0 | 0 | ec8ca3a3422cd68ea1bf7fc90214659481690431 | 1,201 | CursoQI-MOBILE | MIT License |
shared/src/commonMain/kotlin/business/datasource/network/main/responses/BasketDeleteRequestDTO.kt | shlomyrep | 780,318,608 | false | {"Kotlin": 703708, "Swift": 23567, "Ruby": 290, "Shell": 228} | package business.datasource.network.main.responses
import business.domain.main.SalesMan
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class BasketDeleteRequestDTO(
@SerialName("product") val product: String,
@SerialName("sales_man") val salesMan: SalesMan,
)
| 0 | Kotlin | 0 | 0 | ecdf18f4bb8d3d25c15c9a6957f38b8bd99ec7ba | 325 | retailAiClient | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/cleanrooms/CfnAnalysisTemplatePropsDsl.kt | F43nd1r | 643,016,506 | false | {"Kotlin": 5279682} | package com.faendir.awscdkkt.generated.services.cleanrooms
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.cleanrooms.CfnAnalysisTemplateProps
@Generated
public fun buildCfnAnalysisTemplateProps(initializer: @AwsCdkDsl
CfnAnalysisTemplateProps.Builder.() -> Unit = {}): CfnAnalysisTemplateProps =
CfnAnalysisTemplateProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 4 | 32fa5734909e4f7f3bf59b80bd6d4d0bfb2d0dd8 | 453 | aws-cdk-kt | Apache License 2.0 |
FortuneCookie/app/src/main/java/com/dtice/fortunecookie/MainActivity.kt | dtice | 377,654,240 | false | null | package com.dtice.fortunecookie
import android.os.Bundle
import android.util.Log
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import com.dtice.fortunecookie.api.FortuneAPI
import com.dtice.fortunecookie.api.FortuneAPIClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar))
// findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show()
// }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 0 | 0 | 8e30396fc56c9cb2648e01385804f8002550b0a8 | 1,708 | AndroidToys | Apache License 2.0 |
plugins/jps-cache/src/com/intellij/jps/cache/diffExperiment/JpsCacheTools.kt | hieuprogrammer | 284,920,751 | false | null | package com.intellij.jps.cache.diffExperiment
import com.google.common.collect.Maps
import com.google.common.hash.Hashing
import com.google.common.io.CountingInputStream
import com.google.common.io.Files
import com.google.gson.Gson
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.concurrency.AppExecutorUtil
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.io.Reader
import java.nio.charset.StandardCharsets
import java.nio.file.FileVisitResult
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.math.ceil
import java.nio.file.Files as NioFiles
data class JpsCacheFileInfo(val size: Long, val path: String, @Volatile var hash: Long = 0) {
companion object {
private const val minSizeToZip = 1024
private fun gzip(input: ByteArray): ByteArray {
val output = ByteArrayOutputStream()
GZIPOutputStream(output).use { gzip ->
gzip.write(input)
}
return output.toByteArray()
}
}
private val shouldArchive = size > minSizeToZip
fun forUploading(srcFolder: File): ByteArray =
File(srcFolder, path).readBytes().let { bytes -> if (shouldArchive) gzip(bytes) else bytes }
fun afterDownloading(destFolder: File, dataStream: InputStream): Long {
val countingDataStream = CountingInputStream(dataStream)
val dest = File(destFolder, path).apply {
parentFile.mkdirs()
}
(if (shouldArchive) GZIPInputStream(countingDataStream) else countingDataStream).use { stream ->
dest.writeBytes(stream.readBytes())
}
return countingDataStream.count
}
fun getUrl(baseUrl: String) = "$baseUrl/$path/$hash"
}
class JpsCacheTools(val secondsToWaitForFuture: Long) {
companion object {
private const val EXPECTED_NUMBER_OF_FILES = 52_000
private val HASH_FUNCTION = Hashing.murmur3_128()
private const val MANIFESTS_PATH = "manifests"
}
inner class ExecutionApi {
private val futures = mutableListOf<Future<*>>()
fun execute(code: () -> Unit) {
futures.add(executor.submit(code))
}
fun waitForFutures(statusListener: ((completed: Int) -> Unit)? = null): Boolean {
val step: Int = ceil(futures.size.toDouble() / 100).toInt()
var completed = 0
var percent = 0
try {
futures.forEach {
it.get(secondsToWaitForFuture, TimeUnit.SECONDS)
statusListener?.let {
completed++
val newPercent = completed / step
if (newPercent != percent) {
percent = newPercent
it(newPercent)
}
}
}
return true
}
catch (_: TimeoutException) {
return false
}
}
}
private val executor: ExecutorService
init {
val numOfThreads = Runtime.getRuntime().availableProcessors() - 1
executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("JPS_Cache", numOfThreads)
}
fun getJsonByState(files: Collection<JpsCacheFileInfo>): String = Gson().toJson(ArrayList(files))
fun getStateByJsonFile(jsonFilePath: Path): List<JpsCacheFileInfo> = getStateByReader(
Files.newReader(jsonFilePath.toFile(), StandardCharsets.UTF_8))
fun getZippedManifestUrl(baseUrl: String, commitHash: String) = "$baseUrl/$MANIFESTS_PATH/$commitHash"
@JvmOverloads
fun getStateByFolder(rootPath: Path,
existing: Map<String, JpsCacheFileInfo>? = null): List<JpsCacheFileInfo> {
val rootFile = rootPath.toFile()
val result: MutableList<JpsCacheFileInfo> = ArrayList(EXPECTED_NUMBER_OF_FILES)
withExecutor { executor ->
NioFiles.walkFileTree(rootPath, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
val relativePath = FileUtil.getRelativePath(rootFile, file.toFile())!!.replace(File.separatorChar, '/')
val fileSize = attrs.size()
val fileInfo = JpsCacheFileInfo(fileSize, relativePath)
result.add(fileInfo)
existing?.get(relativePath)?.let { existingInfo ->
if (existingInfo.size != fileSize) {
return FileVisitResult.CONTINUE
}
}
executor.execute { fileInfo.hash = getHash(file) }
return FileVisitResult.CONTINUE
}
})
}
return result
}
fun withExecutor(statusListener: ((completed: Int) -> Unit)? = null, code: (executeApi: ExecutionApi) -> Unit): Boolean {
val api = ExecutionApi()
code(api)
return api.waitForFutures(statusListener)
}
fun getFilesToUpdate(folder: Path,
toState: List<JpsCacheFileInfo>): List<JpsCacheFileInfo> {
val toStateMap = mapFromList(toState)
val currentState = getStateByFolder(folder, toStateMap)
return getFilesToUpdate(currentState, toStateMap)
}
fun getFilesToUpdate(fromState: List<JpsCacheFileInfo>,
toState: List<JpsCacheFileInfo>): List<JpsCacheFileInfo> {
return getFilesToUpdate(fromState, mapFromList(toState))
}
private fun getFilesToUpdate(fromState: List<JpsCacheFileInfo>,
toState: Map<String, JpsCacheFileInfo>): List<JpsCacheFileInfo> =
Maps.difference(mapFromList(fromState), toState).let { difference ->
difference.entriesOnlyOnRight().map { it.value } + difference.entriesDiffering().values.map { it.rightValue() }
}
private fun getHash(file: Path): Long = Files.asByteSource(file.toFile()).hash(HASH_FUNCTION).asLong()
private fun mapFromList(list: List<JpsCacheFileInfo>): Map<String, JpsCacheFileInfo> = list.associateBy { it.path }
private fun getStateByReader(readerWithJson: Reader): List<JpsCacheFileInfo> =
Gson().fromJson(readerWithJson, Array<JpsCacheFileInfo>::class.java).toList()
}
| 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 6,111 | intellij-community | Apache License 2.0 |
app/src/main/java/com/yougame/takayamaaren/yougame/ui/main/hot/HotView.kt | 428talent | 167,779,777 | false | null | package com.yougame.takayamaaren.yougame.ui.main.hot
import com.yougame.takayamaaren.yougame.sdk.model.response.GameCollection
import com.yougame.takayamaaren.yougame.ui.base.View
interface HotView : View {
fun applyGameCollections(list: List<GameCollection>)
} | 0 | Kotlin | 0 | 0 | 7220b15262652bd59f8c8b035c88bdb02f78f6e6 | 267 | YouGame-Android | MIT License |
app/src/main/java/cn/mijack/imagedrive/util/Utils.kt | MiJack | 88,419,422 | false | null | package cn.mijack.imagedrive.util
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.text.TextUtils
import java.io.*
import java.math.BigInteger
import java.nio.channels.FileChannel
import java.security.MessageDigest
import java.text.DateFormat
import java.util.*
/**
* @author admin
* @date 2017/8/26
*/
class Utils {
companion object {
fun <E> size(collection: Collection<E>?): Int {
return collection?.size ?: 0
}
fun close(vararg closeables: Closeable) {
if (closeables != null) {
for (c: Closeable in closeables) {
try {
c?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
fun getScreenWidth(context: Context): Int {
return context.resources.displayMetrics.widthPixels;
}
fun fileMD5(file: File): String {
var value: String? = null
var fis: FileInputStream? = null
try {
fis = FileInputStream(file)
val byteBuffer = fis.channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
val md5 = MessageDigest.getInstance("MD5")
md5.update(byteBuffer)
val bi: BigInteger = BigInteger(1, md5.digest())
value = bi.toString(16)
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (null != fis) {
try {
fis.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
return value!!
}
fun fileExtensionName(file: File): String? {
//// String path = file.getPath()
// var path :String=file.path
// var lastIndexOf = file.path
//path.subSequence()
// if (lastIndexOf > 0) {
// return path.(lastIndexOf)
// }
return null
}
fun base64Encode(string: String): String? {
return null
}
//
fun base64Decode(string: String): String? {
return null
}
//
fun isEmpty(uri: Uri): Boolean {
return uri == null || TextUtils.isEmpty(uri.toString())
}
fun formatTime(time: Long): String {
return DateFormat.getDateInstance().format(Date(time))
}
fun isIntentAvailable(context: Context, intent: Intent): Boolean {
var packageManager = context.packageManager
var list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL)
return list.size > 0
}
}
} | 1 | Kotlin | 0 | 0 | 837a92c983bcb3972401f8f8177df506752625f0 | 2,971 | ImageDrive | Apache License 2.0 |
src/main/kotlin/org/jdc/template/inject/AppComponent.kt | lethalskillzz | 115,807,551 | false | null | package org.jdc.template.inject
import android.app.Application
import dagger.Component
import org.jdc.template.App
import org.jdc.template.ui.activity.SettingsActivity
import org.jdc.template.ui.fragment.SettingsFragment
import org.jdc.template.ux.ViewModelModule
import org.jdc.template.ux.about.AboutActivity
import org.jdc.template.ux.directory.DirectoryActivity
import org.jdc.template.ux.directory.DirectoryViewModel
import org.jdc.template.ux.individual.IndividualActivity
import org.jdc.template.ux.individual.IndividualViewModel
import org.jdc.template.ux.individualedit.IndividualEditActivity
import org.jdc.template.ux.individualedit.IndividualEditViewModel
import org.jdc.template.ux.startup.StartupActivity
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class, ViewModelModule::class))
interface AppComponent {
// UI
fun inject(application: App)
fun inject(target: StartupActivity)
fun inject(target: DirectoryActivity)
fun inject(target: IndividualEditActivity)
fun inject(target: SettingsActivity)
fun inject(target: AboutActivity)
fun inject(target: IndividualActivity)
fun inject(target: SettingsFragment)
fun inject(target: DirectoryViewModel)
fun inject(target: IndividualViewModel)
fun inject(target: IndividualEditViewModel)
// Exported for child-components.
fun application(): Application
}
| 0 | null | 0 | 1 | fb19980f455eefb957ae12d40b53baadc3729f38 | 1,409 | android-template | Apache License 2.0 |
app/src/main/java/com/bonifes/viewbinding/sample/base/nonreflection/BaseBindingActivity.kt | panicDev | 368,471,018 | false | null | package com.bonifes.viewbinding.sample.base.nonreflection
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
abstract class BaseBindingActivity<VB : ViewBinding>(
private val inflate: (LayoutInflater) -> VB
) : AppCompatActivity() {
lateinit var binding: VB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = inflate(layoutInflater)
setContentView(binding.root)
}
} | 1 | null | 1 | 1 | 226fa5c07442aa929b0b4f8bec272ff82cfe135d | 534 | bvbl | Apache License 2.0 |
src/main/kotlin/creature/Roles.kt | Seveen | 288,517,608 | false | null | package creature
import memory.pause
import memory.role
import screeps.api.*
import task.harvestSourcesInRoom
enum class Role {
UNASSIGNED,
BOOTSTRAPPER,
MINER,
BUILDER,
UPGRADER,
HAULER,
MAINTAINER,
CLEANER,
RAIDER
}
fun roleToEssence(role: Enum<Role>): Essence {
return when (role) {
Role.HAULER -> Hauler
Role.MINER -> Miner
Role.BOOTSTRAPPER -> Bootstrapper
Role.BUILDER -> Builder
Role.UPGRADER -> Upgrader
Role.MAINTAINER -> Maintainer
Role.CLEANER -> Cleaner
Role.RAIDER -> EnergyRaider
else -> Homunculus
}
}
fun Creep.pause() {
if (memory.pause < 10) {
//blink slowly
if (memory.pause % 3 != 0) say("\uD83D\uDEAC")
memory.pause++
} else {
memory.pause = 0
memory.role = Role.MINER
}
}
| 0 | Kotlin | 0 | 0 | ed959ae2b2e6d6d1195a338de3cbf45e700f8a6c | 866 | screeps-ai | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsnonassociationsapi/jpa/repository/NonAssociationsRepositoryTest.kt | ministryofjustice | 642,329,417 | false | null | package uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.jpa.repository
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.context.transaction.TestTransaction
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.config.AuditorAwareImpl
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.config.AuthenticationFacade
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.dto.NonAssociationReason
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.dto.NonAssociationRestrictionType
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.helper.TestBase
import uk.gov.justice.digital.hmpps.hmppsnonassociationsapi.jpa.NonAssociation
import java.time.LocalDateTime
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(AuthenticationFacade::class, AuditorAwareImpl::class)
@WithMockUser
@Transactional
class NonAssociationRepositoryTest : TestBase() {
@Autowired
lateinit var repository: NonAssociationRepository
@Test
fun createNonAssociation() {
val nonna = nonAssociation(firstPrisonerNumber = "A1234BC", secondPrisonerNumber = "D5678EF")
var savedNonna = repository.save(nonna)
savedNonna = repository.findById(savedNonna.id).orElseThrow {
Exception("NonAssociation with id=${savedNonna.id} couldn't be found")
}
assertThat(savedNonna.firstPrisonerNumber).isEqualTo(nonna.firstPrisonerNumber)
assertThat(savedNonna.firstPrisonerReason).isEqualTo(nonna.firstPrisonerReason)
assertThat(savedNonna.firstPrisonerReason.description).isEqualTo("Victim")
assertThat(savedNonna.secondPrisonerNumber).isEqualTo(nonna.secondPrisonerNumber)
assertThat(savedNonna.secondPrisonerReason).isEqualTo(nonna.secondPrisonerReason)
assertThat(savedNonna.secondPrisonerReason.description).isEqualTo("Perpetrator")
assertThat(savedNonna.restrictionType).isEqualTo(nonna.restrictionType)
assertThat(savedNonna.restrictionType.description).isEqualTo("Do Not Locate in Same Cell")
assertThat(savedNonna.comment).isEqualTo(nonna.comment)
assertThat(savedNonna.incidentReportNumber).isNull()
// By default non-associations are open
assertThat(savedNonna.isClosed).isFalse
assertThat(savedNonna.closedBy).isNull()
assertThat(savedNonna.closedAt).isNull()
assertThat(savedNonna.closedReason).isNull()
assertThat(savedNonna.whenCreated).isEqualTo(savedNonna.whenUpdated)
}
@Test
fun closeNonAssociationWithDetailsSucceeds() {
var createdNonna = repository.save(
nonAssociation(firstPrisonerNumber = "A1234BC", secondPrisonerNumber = "D5678EF"),
)
// Update the non-association to close it
val closedBy = "Aldo"
val closedReason = "They're friends now"
val closedAt = LocalDateTime.now()
createdNonna.close(closedBy, closedReason, closedAt)
repository.save(createdNonna)
// Check non-association is now closed with correct details
val updatedNonna = repository.findById(createdNonna.id).get()
assertThat(updatedNonna.isClosed).isTrue
assertThat(updatedNonna.closedBy).isEqualTo(closedBy)
assertThat(updatedNonna.closedAt).isEqualTo(closedAt)
assertThat(updatedNonna.closedReason).isEqualTo(closedReason)
}
@Test
fun closeNonAssociationWithoutDetailsFails() {
var createdNonna = repository.save(
nonAssociation(firstPrisonerNumber = "A1234BC", secondPrisonerNumber = "D5678EF"),
)
TestTransaction.flagForCommit()
TestTransaction.end()
TestTransaction.start()
createdNonna = repository.findById(createdNonna.id).orElseThrow {
Exception("NonAssociation with id=${createdNonna.id} couldn't be found")
}
// update fails because details are missing
createdNonna.isClosed = true
assertThatThrownBy {
repository.save(createdNonna)
TestTransaction.flagForCommit()
TestTransaction.end()
}.isInstanceOf(DataIntegrityViolationException::class.java)
// Check non-association is still open
val freshNonna = repository.findById(createdNonna.id).get()
assertThat(freshNonna.isClosed).isFalse
}
@Test
fun whenUpdatedIsUpdated() {
var created = repository.save(
nonAssociation(firstPrisonerNumber = "A1234BC", secondPrisonerNumber = "D5678EF"),
)
TestTransaction.flagForCommit()
TestTransaction.end()
TestTransaction.start()
created.incidentReportNumber = "test-report-id"
val updated = repository.save(created)
TestTransaction.flagForCommit()
TestTransaction.end()
TestTransaction.start()
assertThat(updated.incidentReportNumber).isEqualTo("test-report-id")
assertThat(updated.whenCreated).isEqualTo(created.whenCreated)
assertThat(updated.whenUpdated).isAfter(updated.whenCreated)
}
fun nonAssociation(firstPrisonerNumber: String, secondPrisonerNumber: String): NonAssociation {
return NonAssociation(
firstPrisonerNumber = firstPrisonerNumber,
firstPrisonerReason = NonAssociationReason.VICTIM,
secondPrisonerNumber = secondPrisonerNumber,
secondPrisonerReason = NonAssociationReason.PERPETRATOR,
restrictionType = NonAssociationRestrictionType.CELL,
comment = "John attacked Bob",
)
}
}
| 3 | Kotlin | 0 | 1 | 9c0a89ecc9193965125d5ddb0bc5686b52d60a2f | 5,801 | hmpps-non-associations-api | MIT License |
dd-sdk-android/src/main/kotlin/com/datadog/android/rum/internal/domain/event/RumEventMapper.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.rum.internal.domain.event
import com.datadog.android.api.InternalLogger
import com.datadog.android.api.SdkCore
import com.datadog.android.event.EventMapper
import com.datadog.android.event.NoOpEventMapper
import com.datadog.android.rum.GlobalRumMonitor
import com.datadog.android.rum.internal.monitor.AdvancedRumMonitor
import com.datadog.android.rum.internal.monitor.StorageEvent
import com.datadog.android.rum.model.ActionEvent
import com.datadog.android.rum.model.ErrorEvent
import com.datadog.android.rum.model.LongTaskEvent
import com.datadog.android.rum.model.ResourceEvent
import com.datadog.android.rum.model.ViewEvent
import com.datadog.android.telemetry.model.TelemetryConfigurationEvent
import com.datadog.android.telemetry.model.TelemetryDebugEvent
import com.datadog.android.telemetry.model.TelemetryErrorEvent
import java.util.Locale
internal data class RumEventMapper(
val sdkCore: SdkCore,
val viewEventMapper: EventMapper<ViewEvent> = NoOpEventMapper(),
val errorEventMapper: EventMapper<ErrorEvent> = NoOpEventMapper(),
val resourceEventMapper: EventMapper<ResourceEvent> = NoOpEventMapper(),
val actionEventMapper: EventMapper<ActionEvent> = NoOpEventMapper(),
val longTaskEventMapper: EventMapper<LongTaskEvent> = NoOpEventMapper(),
val telemetryConfigurationMapper: EventMapper<TelemetryConfigurationEvent> = NoOpEventMapper(),
private val internalLogger: InternalLogger
) : EventMapper<Any> {
override fun map(event: Any): Any? {
val mappedEvent = resolveEvent(event)
if (mappedEvent == null) {
notifyEventDropped(event)
}
return mappedEvent
}
// region Internal
private fun mapRumEvent(event: Any): Any? {
return when (event) {
is ViewEvent -> viewEventMapper.map(event)
is ActionEvent -> actionEventMapper.map(event)
is ErrorEvent -> {
if (event.error.isCrash != true) {
errorEventMapper.map(event)
} else {
event
}
}
is ResourceEvent -> resourceEventMapper.map(event)
is LongTaskEvent -> longTaskEventMapper.map(event)
is TelemetryConfigurationEvent -> telemetryConfigurationMapper.map(event)
is TelemetryDebugEvent,
is TelemetryErrorEvent -> event
else -> {
internalLogger.log(
InternalLogger.Level.WARN,
listOf(
InternalLogger.Target.MAINTAINER,
InternalLogger.Target.TELEMETRY
),
{
NO_EVENT_MAPPER_ASSIGNED_WARNING_MESSAGE
.format(Locale.US, event.javaClass.simpleName)
}
)
event
}
}
}
private fun resolveEvent(
event: Any
): Any? {
val mappedEvent = mapRumEvent(event)
// we need to check if the returned bundled mapped object is not null and same instance
// as the original one. Otherwise we will drop the event.
// In case the event is of type ViewEvent this cannot be null according with the interface
// but it can happen that if used from Java code to have null values. In this case we will
// log a warning and we will use the original event.
return if (event is ViewEvent && (mappedEvent == null || mappedEvent !== event)) {
internalLogger.log(
InternalLogger.Level.ERROR,
InternalLogger.Target.USER,
{ VIEW_EVENT_NULL_WARNING_MESSAGE.format(Locale.US, event) }
)
event
} else if (mappedEvent == null) {
internalLogger.log(
InternalLogger.Level.INFO,
InternalLogger.Target.USER,
{ EVENT_NULL_WARNING_MESSAGE.format(Locale.US, event) }
)
null
} else if (mappedEvent !== event) {
internalLogger.log(
InternalLogger.Level.WARN,
InternalLogger.Target.USER,
{ NOT_SAME_EVENT_INSTANCE_WARNING_MESSAGE.format(Locale.US, event) }
)
null
} else {
event
}
}
private fun notifyEventDropped(event: Any) {
val monitor = (GlobalRumMonitor.get(sdkCore) as? AdvancedRumMonitor) ?: return
when (event) {
is ActionEvent -> monitor.eventDropped(
event.view.id,
StorageEvent.Action(frustrationCount = event.action.frustration?.type?.size ?: 0)
)
is ResourceEvent -> monitor.eventDropped(event.view.id, StorageEvent.Resource)
is ErrorEvent -> monitor.eventDropped(event.view.id, StorageEvent.Error)
is LongTaskEvent -> {
if (event.longTask.isFrozenFrame == true) {
monitor.eventDropped(event.view.id, StorageEvent.FrozenFrame)
} else {
monitor.eventDropped(event.view.id, StorageEvent.LongTask)
}
}
else -> {
// Nothing to do
}
}
}
// endregion
companion object {
internal const val VIEW_EVENT_NULL_WARNING_MESSAGE =
"RumEventMapper: the returned mapped ViewEvent was null. " +
"The original event object will be used instead: %s"
internal const val EVENT_NULL_WARNING_MESSAGE =
"RumEventMapper: the returned mapped object was null. " +
"This event will be dropped: %s"
internal const val NOT_SAME_EVENT_INSTANCE_WARNING_MESSAGE =
"RumEventMapper: the returned mapped object was not the " +
"same instance as the original object. This event will be dropped: %s"
internal const val NO_EVENT_MAPPER_ASSIGNED_WARNING_MESSAGE =
"RumEventMapper: there was no EventMapper assigned for" +
" RUM event type: %s"
}
}
| 50 | null | 52 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 6,385 | dd-sdk-android | Apache License 2.0 |
components-core/src/main/java/com/airwallex/android/core/http/AirwallexHttpConnection.kt | airwallex | 231,053,387 | false | null | package com.airwallex.android
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.util.*
import javax.net.ssl.HttpsURLConnection
import kotlin.jvm.Throws
internal class AirwallexHttpConnection internal constructor(private val conn: HttpsURLConnection) : Closeable {
val response: AirwallexHttpResponse
@Throws(IOException::class)
get() {
val responseCode = conn.responseCode
return AirwallexHttpResponse(
code = responseCode,
body = responseBody,
headers = conn.headerFields
)
}
private val responseBody: String?
@Throws(IOException::class)
get() {
return getResponseBody(responseStream)
}
private val responseStream: InputStream?
@Throws(IOException::class)
get() {
return if (conn.responseCode in 200..299) {
conn.inputStream
} else {
conn.errorStream
}
}
@Throws(IOException::class)
private fun getResponseBody(responseStream: InputStream?): String? {
if (responseStream == null) {
return null
}
val scanner = Scanner(responseStream, CHARSET).useDelimiter("\\A")
val responseBody = if (scanner.hasNext()) {
scanner.next()
} else {
null
}
responseStream.close()
return responseBody
}
override fun close() {
responseStream?.close()
conn.disconnect()
}
private companion object {
private val CHARSET = StandardCharsets.UTF_8.name()
}
}
| 2 | null | 12 | 7 | 2898fb7f3fcbe71ee9e27981618777b195eb01c5 | 1,725 | airwallex-payment-android | MIT License |
brd-android/kyc/src/main/java/com/fabriik/kyc/ui/features/accountverification/AccountVerificationViewModel.kt | fabriik | 489,117,365 | false | null | package com.rockwallet.kyc.ui.features.accountverification
import android.app.Application
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.breadwallet.tools.security.ProfileManager
import com.rockwallet.common.data.enums.KycStatus
import com.rockwallet.common.ui.base.RockWalletViewModel
import com.rockwallet.common.utils.getString
import com.rockwallet.kyc.R
import com.rockwallet.kyc.ui.customview.AccountVerificationStatusView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.kodein.di.KodeinAware
import org.kodein.di.android.closestKodein
import org.kodein.di.erased.instance
class AccountVerificationViewModel(
application: Application,
savedStateHandle: SavedStateHandle,
) :
RockWalletViewModel<AccountVerificationContract.State, AccountVerificationContract.Event, AccountVerificationContract.Effect>(
application, savedStateHandle
), AccountVerificationEventHandler, KodeinAware {
override val kodein by closestKodein { application }
private val profileManager by kodein.instance<ProfileManager>()
init {
subscribeProfileChanges()
}
override fun createInitialState() = AccountVerificationContract.State.Empty()
override fun onBackClicked() {
setEffect { AccountVerificationContract.Effect.Back }
}
override fun onDismissClicked() {
setEffect { AccountVerificationContract.Effect.Dismiss }
}
override fun onInfoClicked() {
setEffect { AccountVerificationContract.Effect.Info }
}
override fun onLevel1Clicked() {
if (currentState is AccountVerificationContract.State.Content) {
navigateOnLevel1Clicked()
}
}
override fun onLevel2Clicked() {
if (currentState is AccountVerificationContract.State.Content) {
navigateOnLevel2Clicked()
}
}
fun updateProfile() {
profileManager.updateProfile()
}
private fun subscribeProfileChanges() {
profileManager.profileChanges()
.onEach { profile ->
if (profile == null) {
setEffect {
AccountVerificationContract.Effect.ShowToast(
getString(R.string.ErrorMessages_default)
)
}
setState { AccountVerificationContract.State.Empty(false) }
return@onEach
}
setState {
AccountVerificationContract.State.Content(
profile = profile,
level1State = mapStatusToLevel1State(profile.kycStatus),
level2State = mapStatusToLevel2State(
profile.kycStatus,
profile.kycFailureReason
)
)
}
}
.flowOn(Dispatchers.Main)
.launchIn(viewModelScope)
}
private fun navigateOnLevel1Clicked() {
val state = currentState as AccountVerificationContract.State.Content
setEffect {
when (state.profile.kycStatus) {
KycStatus.DEFAULT,
KycStatus.EMAIL_VERIFIED,
KycStatus.EMAIL_VERIFICATION_PENDING,
KycStatus.KYC1,
KycStatus.KYC2_EXPIRED,
KycStatus.KYC2_DECLINED,
KycStatus.KYC2_NOT_STARTED,
KycStatus.KYC2_RESUBMISSION_REQUESTED ->
AccountVerificationContract.Effect.GoToKycLevel1
KycStatus.KYC2_SUBMITTED ->
AccountVerificationContract.Effect.ShowToast(
getString(R.string.AccountKYCLevelTwo_VerificationPending)
)
KycStatus.KYC2 ->
AccountVerificationContract.Effect.ShowLevel1ChangeConfirmationDialog
}
}
}
private fun navigateOnLevel2Clicked() {
val state = currentState as AccountVerificationContract.State.Content
setEffect {
when (state.profile.kycStatus) {
KycStatus.DEFAULT,
KycStatus.EMAIL_VERIFIED,
KycStatus.EMAIL_VERIFICATION_PENDING ->
AccountVerificationContract.Effect.ShowToast(
getString(R.string.AccountKYCLevelTwo_CompleteLevelOneFirst)
)
KycStatus.KYC1,
KycStatus.KYC2_EXPIRED,
KycStatus.KYC2_DECLINED,
KycStatus.KYC2_NOT_STARTED,
KycStatus.KYC2_RESUBMISSION_REQUESTED ->
AccountVerificationContract.Effect.GoToKycLevel2
KycStatus.KYC2_SUBMITTED ->
AccountVerificationContract.Effect.ShowToast(
getString(R.string.AccountKYCLevelTwo_VerificationPending)
)
KycStatus.KYC2 ->
AccountVerificationContract.Effect.ShowToast(
getString(R.string.AccountKYCLevelTwo_updateLevelOne)
)
}
}
}
private fun mapStatusToLevel1State(status: KycStatus): AccountVerificationContract.Level1State {
val state = when (status) {
KycStatus.DEFAULT,
KycStatus.EMAIL_VERIFIED,
KycStatus.EMAIL_VERIFICATION_PENDING -> null
else -> AccountVerificationStatusView.StatusViewState.Verified
}
return AccountVerificationContract.Level1State(
isEnabled = true,
statusState = state
)
}
private fun mapStatusToLevel2State(status: KycStatus, kycFailureReason: String?): AccountVerificationContract.Level2State {
return when (status) {
KycStatus.DEFAULT,
KycStatus.EMAIL_VERIFIED,
KycStatus.EMAIL_VERIFICATION_PENDING ->
AccountVerificationContract.Level2State(
isEnabled = false,
statusState = null
)
KycStatus.KYC1,
KycStatus.KYC2_EXPIRED,
KycStatus.KYC2_NOT_STARTED -> AccountVerificationContract.Level2State(
isEnabled = true
)
KycStatus.KYC2_DECLINED -> AccountVerificationContract.Level2State(
isEnabled = true,
statusState = AccountVerificationStatusView.StatusViewState.Declined,
verificationError = kycFailureReason ?: getString(R.string.ErrorMessages_default)
)
KycStatus.KYC2_RESUBMISSION_REQUESTED -> AccountVerificationContract.Level2State(
isEnabled = true,
statusState = AccountVerificationStatusView.StatusViewState.Resubmit,
verificationError = kycFailureReason ?: getString(R.string.ErrorMessages_default)
)
KycStatus.KYC2_SUBMITTED -> AccountVerificationContract.Level2State(
isEnabled = true,
statusState = AccountVerificationStatusView.StatusViewState.Pending
)
KycStatus.KYC2 -> AccountVerificationContract.Level2State(
isEnabled = true,
statusState = AccountVerificationStatusView.StatusViewState.Verified
)
}
}
} | 2 | null | 1 | 1 | 8894f5c38203c64e48242dae9ae9344ed4b2a61f | 7,494 | wallet-android | MIT License |
client/android/div/src/main/java/com/yandex/div/core/view2/divs/DivImageBinder.kt | divkit | 523,491,444 | false | null | package com.yandex.div.core.view2.divs
import android.graphics.drawable.PictureDrawable
import android.widget.ImageView
import com.yandex.div.core.DivIdLoggingImageDownloadCallback
import com.yandex.div.core.dagger.DivScope
import com.yandex.div.core.images.BitmapSource
import com.yandex.div.core.images.CachedBitmap
import com.yandex.div.core.images.DivImageLoader
import com.yandex.div.core.util.ImageRepresentation
import com.yandex.div.core.util.androidInterpolator
import com.yandex.div.core.util.equalsToConstant
import com.yandex.div.core.util.isConstant
import com.yandex.div.core.util.toCachedBitmap
import com.yandex.div.core.view2.BindingContext
import com.yandex.div.core.view2.DivPlaceholderLoader
import com.yandex.div.core.view2.DivViewBinder
import com.yandex.div.core.view2.divs.widgets.DivImageView
import com.yandex.div.core.view2.errors.ErrorCollector
import com.yandex.div.core.view2.errors.ErrorCollectors
import com.yandex.div.core.widget.LoadableImageView
import com.yandex.div.internal.widget.AspectImageView
import com.yandex.div.json.expressions.ExpressionResolver
import com.yandex.div.json.expressions.equalsToConstant
import com.yandex.div.json.expressions.isConstant
import com.yandex.div.json.expressions.isConstantOrNull
import com.yandex.div2.DivAlignmentHorizontal
import com.yandex.div2.DivAlignmentVertical
import com.yandex.div2.DivBlendMode
import com.yandex.div2.DivFilter
import com.yandex.div2.DivImage
import com.yandex.div2.DivImageScale
import javax.inject.Inject
@DivScope
internal class DivImageBinder @Inject constructor(
private val baseBinder: DivBaseBinder,
private val imageLoader: DivImageLoader,
private val placeholderLoader: DivPlaceholderLoader,
private val errorCollectors: ErrorCollectors,
) : DivViewBinder<DivImage, DivImageView> {
override fun bindView(context: BindingContext, view: DivImageView, div: DivImage) {
val oldDiv = view.div
if (div === oldDiv) return
baseBinder.bindView(context, view, div, oldDiv)
view.applyDivActions(
context,
div.action,
div.actions,
div.longtapActions,
div.doubletapActions,
div.actionAnimation,
div.accessibility,
)
val divView = context.divView
val expressionResolver = context.expressionResolver
val errorCollector = errorCollectors.getOrCreate(divView.dataTag, divView.divData)
view.bindAspectRatio(div.aspect, oldDiv?.aspect, expressionResolver)
view.bindImageScale(div, oldDiv, expressionResolver)
view.bindContentAlignment(div, oldDiv, expressionResolver)
view.bindPreviewAndImage(context, div, oldDiv, errorCollector)
view.bindTint(div, oldDiv, expressionResolver)
view.bindFilters(context, div, oldDiv)
}
//region Image Scale
private fun DivImageView.bindImageScale(
newDiv: DivImage,
oldDiv: DivImage?,
resolver: ExpressionResolver,
) {
if (newDiv.scale.equalsToConstant(oldDiv?.scale)) {
return
}
applyImageScale(newDiv.scale.evaluate(resolver))
if (newDiv.scale.isConstant()) {
return
}
addSubscription(
newDiv.scale.observe(resolver) { scale -> applyImageScale(scale) }
)
}
private fun DivImageView.applyImageScale(scale: DivImageScale) {
imageScale = scale.toImageScale()
}
//endregion
//region Content Alignment
private fun DivImageView.bindContentAlignment(
newDiv: DivImage,
oldDiv: DivImage?,
resolver: ExpressionResolver
) {
if (newDiv.contentAlignmentHorizontal.equalsToConstant(oldDiv?.contentAlignmentHorizontal)
&& newDiv.contentAlignmentVertical.equalsToConstant(oldDiv?.contentAlignmentVertical)) {
return
}
applyContentAlignment(
newDiv.contentAlignmentHorizontal.evaluate(resolver),
newDiv.contentAlignmentVertical.evaluate(resolver)
)
if (newDiv.contentAlignmentHorizontal.isConstant() && newDiv.contentAlignmentVertical.isConstant()) {
return
}
val callback = { _: Any ->
applyContentAlignment(
newDiv.contentAlignmentHorizontal.evaluate(resolver),
newDiv.contentAlignmentVertical.evaluate(resolver)
)
}
addSubscription(newDiv.contentAlignmentHorizontal.observe(resolver, callback))
addSubscription(newDiv.contentAlignmentVertical.observe(resolver, callback))
}
private fun AspectImageView.applyContentAlignment(
horizontalAlignment: DivAlignmentHorizontal,
verticalAlignment: DivAlignmentVertical
) {
gravity = evaluateGravity(horizontalAlignment, verticalAlignment)
}
//endregion
//region Filters
private fun DivImageView.bindFilters(
bindingContext: BindingContext,
newDiv: DivImage,
oldDiv: DivImage?,
) {
if (newDiv.filters?.size == oldDiv?.filters?.size) {
val filtersAreTheSame = newDiv.filters?.foldIndexed(initial = true) { index, result, newFilter ->
result && newFilter.equalsToConstant(oldDiv?.filters?.get(index))
} ?: true
if (filtersAreTheSame) {
return
}
}
applyFiltersAndSetBitmap(bindingContext, newDiv.filters)
val allFiltersAreConstant = newDiv.filters?.all { filter -> filter.isConstant() }
if (allFiltersAreConstant != false) {
return
}
val callback = { _: Any -> applyFiltersAndSetBitmap(bindingContext, newDiv.filters) }
newDiv.filters?.forEach { filter ->
when (filter) {
is DivFilter.Blur ->
addSubscription(filter.value.radius.observe(bindingContext.expressionResolver, callback))
else -> Unit
}
}
}
private fun DivImageView.applyFiltersAndSetBitmap(
bindingContext: BindingContext,
filters: List<DivFilter>?
) {
val bitmap = currentBitmapWithoutFilters
if (bitmap == null) {
setImageBitmap(null)
} else {
applyBitmapFilters(bindingContext, bitmap, filters) {
setImageBitmap(it)
}
}
}
//endregion
//region Preview
private fun DivImageView.observePreview(
bindingContext: BindingContext,
newDiv: DivImage,
errorCollector: ErrorCollector
) {
addSubscription(
newDiv.preview?.observe(bindingContext.expressionResolver) { newPreview ->
if (isImageLoaded || newPreview == preview) {
return@observe
}
resetImageLoaded()
applyPreview(
bindingContext,
newDiv,
isHighPriorityShow(bindingContext.expressionResolver, this, newDiv),
errorCollector
)
}
)
}
private fun DivImageView.applyPreview(
bindingContext: BindingContext,
div: DivImage,
synchronous: Boolean,
errorCollector: ErrorCollector
) {
val resolver = bindingContext.expressionResolver
placeholderLoader.applyPlaceholder(
this,
errorCollector,
div.preview?.evaluate(resolver),
div.placeholderColor.evaluate(resolver),
synchronous = synchronous,
onSetPlaceholder = { drawable ->
if (!isImageLoaded && !isImagePreview) {
setPlaceholder(drawable)
}
},
onSetPreview = {
if (!isImageLoaded) {
when (it) {
is ImageRepresentation.Bitmap -> {
currentBitmapWithoutFilters = it.value
applyFiltersAndSetBitmap(bindingContext, div.filters)
previewLoaded()
applyTint(div.tintColor?.evaluate(resolver), div.tintMode.evaluate(resolver))
}
is ImageRepresentation.PictureDrawable -> {
previewLoaded()
setImageDrawable(it.value)
}
}
}
}
)
}
//endregion
//region Image
private fun DivImageView.bindPreviewAndImage(
context: BindingContext,
newDiv: DivImage,
oldDiv: DivImage?,
errorCollector: ErrorCollector
) {
val view = this
val imageUrlChanged = !newDiv.imageUrl.equalsToConstant(oldDiv?.imageUrl)
val previewAndPlaceholderChanged = !(newDiv.preview.equalsToConstant(oldDiv?.preview)
&& newDiv.placeholderColor.equalsToConstant(oldDiv?.placeholderColor))
val previewAndPlaceholderAreConstant = newDiv.preview.isConstantOrNull() &&
newDiv.placeholderColor.isConstant()
val needPreviewUpdate = !isImageLoaded && previewAndPlaceholderChanged
val needObservePreview = needPreviewUpdate && !previewAndPlaceholderAreConstant
if (needObservePreview) {
view.observePreview(context, newDiv, errorCollector)
}
val needObserveImageUrl = imageUrlChanged && !newDiv.imageUrl.isConstantOrNull()
if (needObserveImageUrl) {
addSubscription(
newDiv.imageUrl.observe(context.expressionResolver) {
applyImage(context, newDiv, errorCollector)
}
)
}
val applyImageWorkSkipped = !applyImage(context, newDiv, errorCollector)
if (applyImageWorkSkipped && needPreviewUpdate) {
view.applyPreview(
context,
newDiv,
isHighPriorityShow(context.expressionResolver, view, newDiv),
errorCollector,
)
}
}
private fun DivImageView.applyImage(
bindingContext: BindingContext,
div: DivImage,
errorCollector: ErrorCollector
): Boolean {
val resolver = bindingContext.expressionResolver
val imageUrl = div.imageUrl.evaluate(resolver)
if (imageUrl == this.imageUrl) {
return false
}
// Called before resetImageLoaded() to ignore high priority preview if image was previously loaded.
val isHighPriorityShowPreview = isHighPriorityShow(resolver, this, div)
resetImageLoaded()
clearTint()
loadReference?.cancel()
applyPreview(bindingContext, div, isHighPriorityShowPreview, errorCollector)
this.imageUrl = imageUrl
val reference = imageLoader.loadImage(
imageUrl.toString(),
object : DivIdLoggingImageDownloadCallback(bindingContext.divView) {
override fun onSuccess(cachedBitmap: CachedBitmap) {
super.onSuccess(cachedBitmap)
currentBitmapWithoutFilters = cachedBitmap.bitmap
applyFiltersAndSetBitmap(bindingContext, div.filters)
applyLoadingFade(div, resolver, cachedBitmap.from)
imageLoaded()
applyTint(div.tintColor?.evaluate(resolver), div.tintMode.evaluate(resolver))
invalidate()
}
override fun onSuccess(pictureDrawable: PictureDrawable) {
if (!div.isVectorCompatible()) {
val bitmap = pictureDrawable.toCachedBitmap(imageUrl)
onSuccess(bitmap)
return
}
super.onSuccess(pictureDrawable)
setImageDrawable(pictureDrawable)
applyLoadingFade(div, resolver, null)
imageLoaded()
invalidate()
}
override fun onError() {
super.onError()
[email protected] = null
}
}
)
bindingContext.divView.addLoadReference(reference, this)
loadReference = reference
return true
}
/**
* Vector format Image doesn't support color and filters.
* If color or filters are specified for Image, it should be rasterized.
*/
private fun DivImage.isVectorCompatible() : Boolean {
return tintColor == null && filters.isNullOrEmpty()
}
private fun DivImageView.applyLoadingFade(
div: DivImage,
resolver: ExpressionResolver,
bitmapSource: BitmapSource?,
) {
this.animate().cancel()
val animation = div.appearanceAnimation
val maxAlpha = div.alpha.evaluate(resolver).toFloat()
if (animation == null || bitmapSource == BitmapSource.MEMORY) {
alpha = maxAlpha
return
}
val duration = animation.duration.evaluate(resolver)
val interpolator = animation.interpolator.evaluate(resolver).androidInterpolator
alpha = animation.alpha.evaluate(resolver).toFloat()
val delay = animation.startDelay.evaluate(resolver)
this.animate()
.alpha(maxAlpha)
.setDuration(duration)
.setInterpolator(interpolator)
.setStartDelay(delay)
}
private fun isHighPriorityShow(resolver: ExpressionResolver, view: DivImageView, div: DivImage) : Boolean {
return !view.isImageLoaded && div.highPriorityPreviewShow.evaluate(resolver)
}
//endregion
//region Tint
private fun DivImageView.bindTint(
newDiv: DivImage,
oldDiv: DivImage?,
resolver: ExpressionResolver,
) {
if (newDiv.tintColor.equalsToConstant(oldDiv?.tintColor)
&& newDiv.tintMode.equalsToConstant(oldDiv?.tintMode)) {
return
}
applyTint(newDiv.tintColor?.evaluate(resolver), newDiv.tintMode.evaluate(resolver))
if (newDiv.tintColor.isConstantOrNull() && newDiv.tintMode.isConstant()) {
return
}
val callback = { _: Any ->
applyTint(newDiv.tintColor?.evaluate(resolver), newDiv.tintMode.evaluate(resolver))
}
addSubscription(newDiv.tintColor?.observe(resolver, callback))
addSubscription(newDiv.tintMode.observe(resolver, callback))
}
private fun LoadableImageView.applyTint(
tintColor: Int?,
tintMode: DivBlendMode
) {
if ((isImageLoaded || isImagePreview) && tintColor != null) {
setColorFilter(tintColor, tintMode.toPorterDuffMode())
} else {
clearTint()
}
}
private fun ImageView.clearTint() {
colorFilter = null
}
//endregion
}
| 7 | null | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 14,986 | divkit | Apache License 2.0 |
src/main/kotlin/com/msg/gcms/domain/admin/service/impl/UserDetailInfoServiceImpl.kt | GSM-MSG | 592,816,374 | false | null | package com.msg.gcms.domain.admin.service.impl
import com.msg.gcms.domain.admin.presentation.data.dto.ClubInfoDto
import com.msg.gcms.domain.admin.presentation.data.dto.UserDetailInfoDto
import com.msg.gcms.domain.admin.presentation.data.request.UserDetailInfoRequest
import com.msg.gcms.domain.admin.service.UserDetailInfoService
import com.msg.gcms.domain.admin.util.AdminConverter
import com.msg.gcms.domain.club.domain.repository.ClubRepository
import com.msg.gcms.domain.club.enums.ClubStatus
import com.msg.gcms.domain.user.domain.repository.UserRepository
import com.msg.gcms.domain.user.exception.UserNotFoundException
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import java.util.*
@Service
class UserDetailInfoServiceImpl(
private val userRepository: UserRepository,
private val clubRepository: ClubRepository,
private val adminConverter: AdminConverter
) : UserDetailInfoService {
override fun execute(userDetailInfoRequest: UserDetailInfoRequest): UserDetailInfoDto {
val user = userRepository.findByIdOrNull(UUID.fromString(userDetailInfoRequest.uuid))
?: throw UserNotFoundException()
val clubList = clubRepository.findByUserAndClubStatus(user, ClubStatus.CREATED)
.map { ClubInfoDto(
id = it.id,
bannerImg = it.bannerImg,
name = it.name,
type = it.type
) }
return adminConverter.toDto(user, clubList)
}
} | 6 | Kotlin | 0 | 8 | f2b79e643bc72c41e8845e519e5939ac1a9cfe3d | 1,581 | GCMS-BackEnd | MIT License |
app/src/main/java/com/zoonn/openglnativesampleproject/MainActivity.kt | zoonn1788 | 220,175,347 | false | {"Kotlin": 8672, "C++": 2911, "CMake": 1664} | package com.zoonn.openglnativesampleproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zoonn.openglnativesampleproject.opengl32_sample1.OpenGL32Sample1Activity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val assetsList: List<String> = listOf("native_kotlin.png", "open_gl10_1.png", "open_gl_es32_1.png")
private val sampleList: List<OpenGLNativeSampleAdapter.OpenGLNativeSamples> = listOf(
OpenGLNativeSampleAdapter.OpenGLNativeSamples("Android Native for Kotlin", "Hello from C++が表示されるサンプル", assetsList[0], HelloFromCppActivity::class.java),
OpenGLNativeSampleAdapter.OpenGLNativeSamples("OpenGL ES3.2 Sample1", "NativeでOpenGLを使う", assetsList[2], OpenGL32Sample1Activity::class.java)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//落ちる
//register()
//sample_text.text = CppFunction.stringFromJNI()
findViewById<RecyclerView>(R.id.activity_list).apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@MainActivity)
if (sampleList.size >= 0) {
adapter = OpenGLNativeSampleAdapter(sampleList)
}
}
}
fun start(clazz: Class<*>) {
val intent = Intent(this, clazz)
startActivity(intent)
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
external fun register()
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
@JvmStatic
fun hello(value: Int) = "Hello from Kotlin $value"
}
}
| 0 | Kotlin | 0 | 1 | ae394e4b5d22b86e3a40ee18f66bc1a862c16749 | 2,110 | OpenGLNativeSampleProject | MIT License |
app/src/main/java/com/todo/ui/feature/launcher/LauncherPresenter.kt | waleedsarwar86 | 134,292,766 | false | {"Gradle": 7, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "INI": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 3, "Kotlin": 72, "Java": 34, "XML": 40, "YAML": 1} | package com.todo.ui.feature.launcher
import com.todo.data.repository.TodoRepository
import com.todo.ui.base.BasePresenter
import io.reactivex.functions.Consumer
import javax.inject.Inject
import timber.log.Timber
/********* Constructors */
class LauncherPresenter : BasePresenter<LauncherContract.View>(), LauncherContract.Presenter {
/********* Dagger Injected Fields */
@Inject
lateinit var todoRepository: TodoRepository
/********* LauncherContract.Presenter Interface Methods Implementation */
override fun showNextActivity() {
addDisposable(todoRepository.isUserLoggedIn
.compose(uiSchedulersTransformer.applySchedulersToSingle())
.subscribe({ isUserLoggedIn ->
if (isUserLoggedIn) view?.showLoginActivity() else view?.showLoginActivity()
}, { Timber.e(it) }))
}
}
| 0 | Kotlin | 0 | 1 | 7b7fc8579b426383e50a3254d0c748bc068d6644 | 883 | todo-mvp-kt | Apache License 2.0 |
src/template/assertk/assertions/primativeArray.kt | uzzu | 238,722,858 | true | {"Kotlin": 246663, "Java": 134} | package assertk.assertions
import assertk.Assert
import assertk.PlatformName
import assertk.all
import assertk.assertions.support.expected
import assertk.assertions.support.show
import assertk.assertions.support.fail
$T:$N:$E = ByteArray:byteArray:Byte, IntArray:intArray:Int, ShortArray:shortArray:Short, LongArray:longArray:Long, FloatArray:floatArray:Float, DoubleArray:doubleArray:Double, CharArray:charArray:Char
/**
* Returns an assert on the $T's size.
*/
@PlatformName("$NSize")
fun Assert<$T>.size() = prop("size") { it.size }
/**
* Asserts the $T contents are equal to the expected one, using [contentDeepEquals].
* @see isNotEqualTo
*/
fun Assert<$T>.isEqualTo(expected: $T) = given { actual ->
if (actual.contentEquals(expected)) return
fail(expected, actual)
}
/**
* Asserts the $T contents are not equal to the expected one, using [contentDeepEquals].
* @see isEqualTo
*/
fun Assert<$T>.isNotEqualTo(expected: $T) = given { actual ->
if (!(actual.contentEquals(expected))) return
val showExpected = show(expected)
val showActual = show(actual)
// if they display the same, only show one.
if (showExpected == showActual) {
expected("to not be equal to:$showActual")
} else {
expected(":$showExpected not to be equal to:$showActual")
}
}
/**
* Asserts the $T is empty.
* @see [isNotEmpty]
* @see [isNullOrEmpty]
*/
@PlatformName("$NIsEmpty")
fun Assert<$T>.isEmpty() = given { actual ->
if (actual.isEmpty()) return
expected("to be empty but was:${show(actual)}")
}
/**
* Asserts the $T is not empty.
* @see [isEmpty]
*/
@PlatformName("$NIsNotEmpty")
fun Assert<$T>.isNotEmpty() = given { actual ->
if (actual.isNotEmpty()) return
expected("to not be empty")
}
/**
* Asserts the $T is null or empty.
* @see [isEmpty]
*/
@PlatformName("$NIsNullOrEmpty")
fun Assert<$T?>.isNullOrEmpty() = given { actual ->
if (actual == null || actual.isEmpty()) return
expected("to be null or empty but was:${show(actual)}")
}
/**
* Asserts the $T has the expected size.
*/
@PlatformName("$NHasSize")
fun Assert<$T>.hasSize(size: Int) {
size().isEqualTo(size)
}
/**
* Asserts the $T has the same size as the expected array.
*/
@PlatformName("$NHasSameSizeAs")
fun Assert<$T>.hasSameSizeAs(other: $T) = given { actual ->
val actualSize = actual.size
val otherSize = other.size
if (actualSize == otherSize) return
expected("to have same size as:${show(other)} ($otherSize) but was size:($actualSize)")
}
/**
* Asserts the $T contains the expected element, using `in`.
* @see [doesNotContain]
*/
@PlatformName("$NContains")
fun Assert<$T>.contains(element: $E) = given { actual ->
if (element in actual) return
expected("to contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the $T does not contain the expected element, using `!in`.
* @see [contains]
*/
@PlatformName("$NDoesNotContain")
fun Assert<$T>.doesNotContain(element: $E) = given { actual ->
if (element !in actual) return
expected("to not contain:${show(element)} but was:${show(actual)}")
}
/**
* Asserts the $T does not contain any of the expected elements.
* @see [containsAll]
*/
fun Assert<$T>.containsNone(vararg elements: $E) = given { actual ->
if (elements.none { it in actual }) {
return
}
val notExpected = elements.filter { it in actual }
expected("to contain none of:${show(elements)} some elements were not expected:${show(notExpected)}")
}
/**
* Asserts the $T contains all the expected elements, in any order. The array may also contain
* additional elements.
* @see [containsExactly]
*/
@PlatformName("$NContainsAll")
fun Assert<$T>.containsAll(vararg elements: $E) = given { actual ->
if (elements.all { actual.contains(it) }) return
val notFound = elements.filterNot { it in actual }
expected("to contain all:${show(elements)} some elements were not found:${show(notFound)}")
}
/**
* Returns an assert that assertion on the value at the given index in the array.
*
* ```
* assertThat($NOf(0, 1, 2)).index(1) { it.isPositive() }
* ```
*/
@PlatformName("$NIndexOld")
@Deprecated(message = "Use index(index) instead.", replaceWith = ReplaceWith("index(index).let(f)"))
fun Assert<$T>.index(index: Int, f: (Assert<$E>) -> Unit) {
index(index).let(f)
}
/**
* Returns an assert that assertion on the value at the given index in the array.
*
* ```
* assertThat($NOf(0, 1, 2)).index(1).isPositive()
* ```
*/
@PlatformName("$NIndex")
fun Assert<$T>.index(index: Int): Assert<$E> =
transform("${name ?: ""}${show(index, "[]")}") { actual ->
if (index in 0 until actual.size) {
actual[index]
} else {
expected("index to be in range:[0-${actual.size}) but was:${show(index)}")
}
}
/**
* Asserts the $T contains exactly the expected elements. They must be in the same order and
* there must not be any extra elements.
* @see [containsAll]
*/
@PlatformName("$NContainsExactly")
fun Assert<$T>.containsExactly(vararg elements: $E) = given { actual ->
if (actual.contentEquals(elements)) return
expected(listDifferExpected(elements.toList(), actual.toList()))
}
/**
* Asserts on each item in the $T. The given lambda will be run for each item.
*
* ```
* assertThat($NOf("one", "two")).each {
* it.hasLength(3)
* }
* ```
*/
@PlatformName("$NEach")
fun Assert<$T>.each(f: (Assert<$E>) -> Unit) = given { actual ->
all {
actual.forEachIndexed { index, item ->
f(assertThat(item, name = "${name ?: ""}${show(index, "[]")}"))
}
}
} | 0 | null | 0 | 0 | fc7c4b062c157f20d9a0777be4d2cb41c7be58ec | 5,631 | assertk | MIT License |
android-adb/src/com/android/tools/idea/adb/wireless/PairingCodePairingController.kt | phpc0de | 470,555,455 | false | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.adb.wireless
import com.android.annotations.concurrency.UiThread
import com.android.tools.idea.concurrency.FutureCallbackExecutor
import com.android.tools.idea.concurrency.catching
import com.android.tools.idea.concurrency.transform
import com.android.tools.idea.concurrency.transformAsync
import com.intellij.openapi.diagnostic.logger
import java.util.concurrent.Executor
@UiThread
class PairingCodePairingController(edtExecutor: Executor,
private val pairingService: WiFiPairingService,
private val view: PairingCodePairingView) {
private val LOG = logger<PairingCodePairingController>()
private val edtExecutor = FutureCallbackExecutor.wrap(edtExecutor)
init {
view.addListener(ViewListener())
}
/**
* Note: This call is blocking, as it displays a modal dialog
*/
fun showDialog() {
view.showDialog()
}
inner class ViewListener : PairingCodePairingView.Listener {
override fun onPairInvoked() {
LOG.info("Starting pairing code pairing process with mDNS service ${view.model.service}")
view.showPairingInProgress()
val futurePairing = pairingService.pairMdnsService(view.model.service, view.model.pairingCode)
futurePairing.transform(edtExecutor) { pairingResult ->
//TODO: Ensure not disposed and state still the same
view.showWaitingForDeviceProgress(pairingResult)
pairingResult
}.transformAsync(edtExecutor) { pairingResult ->
LOG.info("Pairing code pairing process with mDNS service ${view.model.service} succeeded, now starting to wait for device to connect")
//TODO: Ensure not disposed and state still the same
pairingService.waitForDevice(pairingResult)
}.transform(edtExecutor) { device ->
LOG.info("Device ${device} corresponding to mDNS service ${view.model.service} is now connected")
//TODO: Ensure not disposed and state still the same
view.showPairingSuccess(view.model.service, device)
}.catching(edtExecutor, Throwable::class.java) { throwable ->
LOG.warn("Pairing code pairing process failed", throwable)
//TODO: Ensure not disposed and state still the same
view.showPairingError(view.model.service, throwable)
}
}
}
}
| 0 | null | 1 | 1 | 79e20f027ca1d047b91aa7acd92fb71fa2968a09 | 2,950 | idea-android | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FaceWorried.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.FaceWorried: ImageVector
get() {
if (_faceWorried != null) {
return _faceWorried!!
}
_faceWorried = Builder(name = "FaceWorried", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(12.0f, 22.0f)
curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f)
reflectiveCurveTo(6.486f, 2.0f, 12.0f, 2.0f)
reflectiveCurveToRelative(10.0f, 4.486f, 10.0f, 10.0f)
reflectiveCurveToRelative(-4.486f, 10.0f, -10.0f, 10.0f)
close()
moveTo(7.0f, 11.5f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
close()
moveTo(15.5f, 13.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
close()
moveTo(6.782f, 8.624f)
curveToRelative(-0.198f, 0.248f, -0.489f, 0.376f, -0.783f, 0.376f)
curveToRelative(-0.218f, 0.0f, -0.438f, -0.071f, -0.622f, -0.218f)
curveToRelative(-0.433f, -0.344f, -0.503f, -0.973f, -0.159f, -1.405f)
curveToRelative(0.91f, -1.141f, 2.307f, -2.064f, 3.559f, -2.351f)
curveToRelative(0.536f, -0.124f, 1.074f, 0.212f, 1.198f, 0.751f)
reflectiveCurveToRelative(-0.213f, 1.075f, -0.751f, 1.198f)
curveToRelative(-0.812f, 0.187f, -1.816f, 0.864f, -2.441f, 1.649f)
close()
moveTo(18.782f, 7.377f)
curveToRelative(0.344f, 0.432f, 0.273f, 1.061f, -0.159f, 1.405f)
curveToRelative(-0.184f, 0.147f, -0.404f, 0.218f, -0.622f, 0.218f)
curveToRelative(-0.294f, 0.0f, -0.585f, -0.129f, -0.783f, -0.376f)
curveToRelative(-0.625f, -0.785f, -1.629f, -1.462f, -2.441f, -1.649f)
curveToRelative(-0.538f, -0.124f, -0.875f, -0.66f, -0.751f, -1.198f)
reflectiveCurveToRelative(0.66f, -0.878f, 1.198f, -0.751f)
curveToRelative(1.252f, 0.287f, 2.648f, 1.21f, 3.559f, 2.351f)
close()
moveTo(16.906f, 17.767f)
curveToRelative(0.395f, 0.597f, -0.157f, 1.365f, -0.877f, 1.214f)
curveToRelative(-0.93f, -0.195f, -1.998f, -0.98f, -4.03f, -0.981f)
curveToRelative(-2.032f, 0.0f, -3.023f, 0.785f, -3.953f, 0.981f)
curveToRelative(-0.72f, 0.151f, -1.272f, -0.617f, -0.876f, -1.214f)
curveToRelative(0.849f, -1.282f, 2.372f, -2.767f, 4.871f, -2.767f)
reflectiveCurveToRelative(4.016f, 1.484f, 4.865f, 2.767f)
close()
}
}
.build()
return _faceWorried!!
}
private var _faceWorried: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,424 | icons | MIT License |
app/src/main/java/br/com/jxr/cstv/data/remote/mappers/OpponentMapper.kt | joaoreis | 516,848,448 | false | {"Kotlin": 41799} | package br.com.jxr.cstv.data.remote.mappers
import br.com.jxr.cstv.data.remote.dto.OpponentDto
import br.com.jxr.cstv.data.remote.dto.OpponentTypeDto
import br.com.jxr.cstv.domain.model.Team
internal fun OpponentDto.toTeam(): Team =
when {
opponent == null || type != OpponentTypeDto.TEAM -> placeHolderTeam
else -> Team(
id = opponent.id,
name = opponent.name,
imageUrl = opponent.imageUrl.orEmpty()
)
}
internal fun List<OpponentDto>?.toTeams(): List<Team> {
return when {
this == null -> listOf(placeHolderTeam, placeHolderTeam)
this.isEmpty() -> listOf(placeHolderTeam, placeHolderTeam)
this.size == 1 -> map { it.toTeam() } + placeHolderTeam
else -> map { it.toTeam() }
}
}
private val placeHolderTeam = Team(
id = -1,
name = "TBD",
imageUrl = ""
)
| 0 | Kotlin | 0 | 0 | 79d3d78d98327a59c995c1d2b8214e7e1f066d45 | 879 | cstv | MIT License |
app/src/main/java/com/marcodallaba/pokeapp/ui/viewholders/PokemonViewHolder.kt | marcodb97 | 304,840,360 | false | null | package com.marcodallaba.pokeapp.ui.viewholders
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.marcodallaba.pokeapp.R
import com.marcodallaba.pokeapp.databinding.PokemonViewItemBinding
import com.marcodallaba.pokeapp.model.PokemonBase
import com.marcodallaba.pokeapp.ui.adapters.PokemonAdapter
import com.marcodallaba.pokeapp.utils.setSafeOnClickListener
import java.util.*
/**
* View Holder for a [PokemonBase] RecyclerView list item.
*/
class PokemonViewHolder(
private val binding: PokemonViewItemBinding,
onPokemonClickListener: PokemonAdapter.OnPokemonClickListener
) :
RecyclerView.ViewHolder(binding.root) {
private var pokemon: PokemonBase? = null
init {
binding.root.setSafeOnClickListener {
pokemon?.let {
onPokemonClickListener.onClick(pokemonName = it.name)
}
}
}
fun bind(pokemon: PokemonBase?) {
if (pokemon == null) {
val resources = itemView.resources
binding.pokemonName.text = resources.getString(R.string.loading)
} else {
showPokemonData(pokemon)
}
}
private fun showPokemonData(pokemon: PokemonBase) {
this.pokemon = pokemon
binding.pokemonName.text = pokemon.name.capitalize(Locale.ROOT)
}
companion object {
fun create(
parent: ViewGroup,
onPokemonClickListener: PokemonAdapter.OnPokemonClickListener
): PokemonViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding: PokemonViewItemBinding =
PokemonViewItemBinding.inflate(layoutInflater, parent, false)
return PokemonViewHolder(binding, onPokemonClickListener)
}
}
}
| 0 | Kotlin | 0 | 0 | 53d874dec840980e2ba44fdccbbf31f0a85a37e9 | 1,835 | PokeApp | Apache License 2.0 |
app/src/main/kotlin/tmidev/localaccount/di/CoroutinesModule.kt | tminet | 574,995,467 | false | {"Kotlin": 142081} | package tmidev.localaccount.di
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import tmidev.localaccount.util.CoroutinesDispatchers
import tmidev.localaccount.util.CoroutinesDispatchersImpl
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface CoroutinesModule {
@Binds
@Singleton
fun bindsCoroutinesDispatchers(
dispatchers: CoroutinesDispatchersImpl
): CoroutinesDispatchers
} | 0 | Kotlin | 1 | 4 | 4e9ad6ad32d40cfa6103f833ce7fc0259b63da54 | 508 | LocalAccount | MIT License |
app/src/main/java/com/example/dropy/di/shop/ShopRepositoryModule.kt | dropyProd | 705,360,878 | false | {"Kotlin": 3916897, "Java": 20617} | package com.example.dropy.di.shop
import com.example.dropy.network.repositories.shop.back.ShopBackendRepository
import com.example.dropy.network.repositories.shop.back.ShopBackendRepositoryImpl
import com.example.dropy.network.repositories.shop.front.ShopFrontendRepository
import com.example.dropy.network.repositories.shop.front.ShopFrontendRepositoryImpl
import com.example.dropy.network.services.payment.PaymentService
import com.example.dropy.network.services.shops.ShopsBackendService
import com.example.dropy.network.services.shops.ShopsFrontService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import io.ktor.client.*
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object ShopRepositoryModule {
@Singleton
@Provides
fun provideShopFrontEndRepository(
shopsFrontService: ShopsFrontService,
client: HttpClient,
paymentService: PaymentService
): ShopFrontendRepository {
return ShopFrontendRepositoryImpl(
shopsFrontService = shopsFrontService,
client = client,
paymentService = paymentService
)
}
@Singleton
@Provides
fun provideShopBackEndRepository(
shopsBackendService: ShopsBackendService,
client: HttpClient,
): ShopBackendRepository {
return ShopBackendRepositoryImpl(
shopsBackendService = shopsBackendService,
client = client
)
}
} | 0 | Kotlin | 0 | 0 | 6d994c9c61207bac28c49717b6c250656fe4ae6b | 1,527 | DropyLateNights | Apache License 2.0 |
app/src/main/java/org/ballistic/dreamjournalai/feature_dream/domain/use_case/GetCurrentDreamID.kt | ErickSorto | 546,852,272 | false | {"Kotlin": 779962, "TypeScript": 15023, "JavaScript": 905} | package org.ballistic.dreamjournalai.feature_dream.domain.use_case
import org.ballistic.dreamjournalai.core.Resource
import org.ballistic.dreamjournalai.feature_dream.domain.repository.DreamRepository
class GetCurrentDreamID(
private val repository: DreamRepository
) {
suspend operator fun invoke(): Resource<String> {
return repository.getCurrentDreamId()
}
} | 0 | Kotlin | 0 | 4 | 03265c5ecba06825ef5cfdd34507a30414615ef9 | 383 | Dream-Journal-AI | MIT License |
app/src/main/java/ci/projccb/mobile/repositories/databases/daos/ParcelleDao.kt | SICADEVD | 686,088,142 | false | {"Kotlin": 1532850, "Java": 20027} | package ci.projccb.mobile.repositories.databases.daos
import androidx.room.*
import ci.projccb.mobile.models.*
/**
* Created by didierboka.developer on 18/12/2021
* mail for work: (<EMAIL>)
*/
@Dao
interface ParcelleDao {
@Transaction
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(parcelleModel: ParcelleModel)
@Transaction
@Query("SELECT * FROM parcelle WHERE agentId = :agentID")
fun getAll(agentID: String?): MutableList<ParcelleModel>
@Transaction
@Query("SELECT * FROM parcelle WHERE (producteurId = :producteurId AND agentId = :agentID)")
fun getParcellesProducteur(producteurId: String?, agentID: String?): MutableList<ParcelleModel>
@Transaction
@Query("SELECT * FROM parcelle WHERE id = :id")
fun getParcelle(id: Int): LocaliteModel
@Transaction
@Query("SELECT * FROM parcelle WHERE isSynced = 0 AND agentId = :agentID")
fun getUnSyncedAll(agentID: String?): MutableList<ParcelleModel>
@Transaction
@Query("UPDATE parcelle SET id = :id, isSynced = :synced, origin = 'remote', codeParc = :codeparc WHERE uid = :localID")
fun syncData(id: Int, synced: Boolean, codeparc: String, localID: Int)
@Transaction
@Query("SELECT * FROM parcelle WHERE (isSynced = 0 AND producteurId = :producteurUid AND origin = 'local' AND agentId = :agentId)")
fun getParcellesUnSynchronizedLocal(producteurUid: String?, agentId: String?): MutableList<ParcelleModel>
@Transaction
@Query("DELETE FROM parcelle WHERE agentId = :agentID")
fun deleteAgentDatas(agentID: String?)
@Transaction
@Query("DELETE FROM parcelle WHERE uid = :uid")
fun deleteUid(uid: Long)
@Transaction
@Query("SELECT * FROM parcelle WHERE (isSynced = 0 AND producteurId = :producteurUid)")
fun getUnSyncedByProdUid(producteurUid: String?): MutableList<ParcelleModel>
} | 0 | Kotlin | 0 | 2 | ffa50c50b45bfbb2dc4ee696ebab925a56e900ac | 1,878 | ccbm | Apache License 2.0 |
app/src/main/java/com/freshdigitable/yttt/compose/TimetableTabScreen.kt | akihito104 | 613,290,086 | false | {"Kotlin": 228337} | package com.freshdigitable.yttt.compose
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.SheetState
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import com.freshdigitable.yttt.MainViewModel
import com.freshdigitable.yttt.OnAirListViewModel
import com.freshdigitable.yttt.TimetablePage
import com.freshdigitable.yttt.UpcomingListViewModel
import com.freshdigitable.yttt.compose.preview.LightModePreview
import com.freshdigitable.yttt.data.model.LiveVideo
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimetableTabScreen(
viewModel: MainViewModel = hiltViewModel(),
onAirViewModel: OnAirListViewModel = hiltViewModel(),
upcomingViewModel: UpcomingListViewModel = hiltViewModel(),
onListItemClicked: (LiveVideo.Id) -> Unit,
) {
LaunchedEffect(Unit) {
if (viewModel.canUpdate) {
viewModel.loadList()
}
}
val tabData = combine(
onAirViewModel.tabData,
upcomingViewModel.tabData,
upcomingViewModel.freeChatTab,
) { items ->
items.toList()
}.collectAsState(initial = TimetablePage.values().map { TabData(it, 0) })
val refreshing = viewModel.isLoading.observeAsState(false)
val onMenuClicked: (LiveVideo.Id) -> Unit = viewModel::onMenuClicked
val listContents: List<LazyListScope.() -> Unit> = TimetablePage.values().map {
when (it) {
TimetablePage.OnAir -> {
val onAir = onAirViewModel.items.collectAsState(emptyList())
return@map { simpleContent({ onAir.value }, onListItemClicked, onMenuClicked) }
}
TimetablePage.Upcoming -> {
val upcoming = upcomingViewModel.items.collectAsState(emptyMap())
return@map { groupedContent({ upcoming.value }, onListItemClicked, onMenuClicked) }
}
TimetablePage.FreeChat -> {
val freeChat = upcomingViewModel.freeChat.collectAsState(emptyList())
return@map { simpleContent({ freeChat.value }, onListItemClicked, onMenuClicked) }
}
}
}
TimetableTabScreen(
tabDataProvider = { tabData.value },
) { index ->
TimetableScreen(
refreshingProvider = { refreshing.value },
onRefresh = viewModel::loadList,
listContent = listContents[index],
)
}
val menuItems = viewModel.menuItems.collectAsState(emptyList())
val sheetState = rememberModalBottomSheetState()
val context = LocalContext.current
ListItemMenuSheet(
menuItemsProvider = { menuItems.value },
sheetState = sheetState,
onMenuItemClicked = { viewModel.onMenuItemClicked(it, context::startActivity) },
onDismissRequest = viewModel::onMenuClosed,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListItemMenuSheet(
menuItemsProvider: () -> Collection<TimetableMenuItem>,
sheetState: SheetState = rememberModalBottomSheetState(),
onMenuItemClicked: (TimetableMenuItem) -> Unit,
onDismissRequest: () -> Unit,
) {
val coroutineScope = rememberCoroutineScope()
val menuItems = menuItemsProvider()
if (menuItems.isNotEmpty()) {
ModalBottomSheet(
sheetState = sheetState,
onDismissRequest = onDismissRequest,
) {
MenuContent(menuItems = menuItems) {
onMenuItemClicked(it)
coroutineScope.launch { sheetState.hide() }.invokeOnCompletion {
if (!sheetState.isVisible) {
onDismissRequest()
}
}
}
}
}
}
@Composable
private fun ColumnScope.MenuContent(
menuItems: Collection<TimetableMenuItem> = TimetableMenuItem.values().toList(),
onMenuClicked: (TimetableMenuItem) -> Unit,
) {
menuItems.forEach { i ->
ListItem(
modifier = Modifier.clickable(onClick = { onMenuClicked(i) }),
headlineContent = { Text(i.text) },
)
}
Spacer(modifier = Modifier.navigationBarsPadding())
}
enum class TimetableMenuItem(val text: String) {
ADD_FREE_CHAT("check as free chat"),
REMOVE_FREE_CHAT("uncheck as free chat"),
LAUNCH_LIVE("watch live"),
;
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TimetableTabScreen(
tabDataProvider: () -> List<TabData>,
page: @Composable (Int) -> Unit,
) {
Column(modifier = Modifier.fillMaxSize()) {
val tabData = tabDataProvider()
val pagerState = rememberPagerState { tabData.size }
ScrollableTabRow(
selectedTabIndex = pagerState.currentPage,
modifier = Modifier.wrapContentSize(),
) {
val coroutineScope = rememberCoroutineScope()
tabData.forEachIndexed { index, data ->
Tab(
selected = pagerState.currentPage == index,
onClick = {
coroutineScope.launch {
pagerState.animateScrollToPage(index)
}
},
text = { Text(text = data.text()) }
)
}
}
HorizontalPager(
state = pagerState,
pageContent = { page(it) },
)
}
}
@Immutable
class TabData(
private val page: TimetablePage,
private val count: Int
) {
@Composable
@ReadOnlyComposable
fun text(): String = stringResource(id = page.textRes, count)
}
@LightModePreview
@Composable
private fun TimetableTabScreenPreview() {
AppTheme {
TimetableTabScreen(
tabDataProvider = {
listOf(
TabData(TimetablePage.OnAir, 10),
TabData(TimetablePage.Upcoming, 3),
TabData(TimetablePage.FreeChat, 7),
)
},
) { Text("page: $it") }
}
}
@LightModePreview
@Composable
private fun ModalSheetPreview() {
AppTheme {
Column(Modifier.fillMaxWidth()) {
MenuContent {}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@LightModePreview
@Composable
private fun ListItemMenuSheetPreview() {
AppTheme {
ListItemMenuSheet(
menuItemsProvider = { TimetableMenuItem.values().toList() },
onMenuItemClicked = {},
) {}
}
}
| 11 | Kotlin | 0 | 0 | d833208580e5856e544d85f152c6f06ab5100851 | 7,907 | yttt | Apache License 2.0 |
src/main/kotlin/net/emteeware/MainViewController.kt | eMTeeWare | 134,248,314 | false | {"Kotlin": 19914} | package net.emteeware
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File
import java.io.UncheckedIOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.time.LocalDate
import java.util.prefs.Preferences
private const val PREFS_LAST_USED_DIR_KEY = "lastUsedDirectory"
private const val HEADER_ROW_COUNT = 1
class MainViewController : Controller() {
private val prefs = Preferences.userRoot().node(this.javaClass.name)
val media = FXCollections.observableArrayList<Media>()
val filepreview = SimpleStringProperty("No file selected")
val importDisabled = SimpleBooleanProperty(true)
val filename = SimpleStringProperty("No file selected")
lateinit var file: File
val initialDirectory = File(prefs[PREFS_LAST_USED_DIR_KEY, System.getProperty("user.home")])
val filters = arrayOf(FileChooser.ExtensionFilter("CSV files", "*.csv"))
val lineCountString = SimpleStringProperty("No file selected")
var separatorString = SimpleStringProperty(";")
lateinit var listViewStartDate: SimpleObjectProperty<LocalDate>
fun getMediaList(): ObservableList<Media> {
return media.filtered { m -> m.watchDate.isAfter(listViewStartDate.value.minusDays(1)) }
}
private var recognizedCharset = StandardCharsets.UTF_8
private lateinit var recognizedContentVersion: ContentVersion
fun importData(file: File) {
val imdbViewingHistory = ImdbViewingHistory()
val separatorChar = separatorString.get()[0]
imdbViewingHistory.importFromCsv(file.canonicalPath, separatorChar, recognizedCharset, recognizedContentVersion)
listViewStartDate = SimpleObjectProperty(imdbViewingHistory.getMinimumWatchDate())
media.setAll(imdbViewingHistory.getTraktMediaList())
}
private fun updateInitialDirectory() {
prefs.put(PREFS_LAST_USED_DIR_KEY, file.path.dropLast(file.name.length))
}
fun loadFile(chosenFiles: List<File>) {
if (chosenFiles.isNotEmpty()) {
file = chosenFiles[0]
filename.set(file.name)
val linecount = try {
Files.lines(file.toPath()).count()
} catch (e: UncheckedIOException) {
recognizedCharset = StandardCharsets.ISO_8859_1
Files.lines(file.toPath(), recognizedCharset).count()
} catch (e: Exception) {
println(e)
0L
}
lineCountString.set("${linecount - HEADER_ROW_COUNT} entries found")
updateInitialDirectory()
val fileContentPreview = StringBuffer()
file.useLines { lines: Sequence<String> ->
lines
.take(3)
.forEach { l -> fileContentPreview.append(l).append('\n') }
}
filepreview.set(fileContentPreview.toString())
guessCvsSeparatorChar(fileContentPreview)
identifyContentVersion(fileContentPreview)
importDisabled.set(false)
}
}
private fun identifyContentVersion(fileContentPreview: StringBuffer) {
recognizedContentVersion = if (fileContentPreview.contains("(mins)") && fileContentPreview.contains("\\d\\d\\d\\d-\\d\\d-\\d\\d".toRegex())) {
ContentVersion.V2
} else {
ContentVersion.V1
}
}
private fun guessCvsSeparatorChar(fileContentPreview: StringBuffer) {
val firstline = fileContentPreview.split('\n')[0]
if (firstline.contains(',') && !firstline.contains(';')) {
separatorString.set(",")
}
}
} | 1 | Kotlin | 0 | 1 | 958fd0a0896f23cdb949c6a9ff946a6049fe8eb0 | 3,859 | emtee-shovel | Apache License 2.0 |
src/main/kotlin/net/emteeware/MainViewController.kt | eMTeeWare | 134,248,314 | false | {"Kotlin": 19914} | package net.emteeware
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File
import java.io.UncheckedIOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.time.LocalDate
import java.util.prefs.Preferences
private const val PREFS_LAST_USED_DIR_KEY = "lastUsedDirectory"
private const val HEADER_ROW_COUNT = 1
class MainViewController : Controller() {
private val prefs = Preferences.userRoot().node(this.javaClass.name)
val media = FXCollections.observableArrayList<Media>()
val filepreview = SimpleStringProperty("No file selected")
val importDisabled = SimpleBooleanProperty(true)
val filename = SimpleStringProperty("No file selected")
lateinit var file: File
val initialDirectory = File(prefs[PREFS_LAST_USED_DIR_KEY, System.getProperty("user.home")])
val filters = arrayOf(FileChooser.ExtensionFilter("CSV files", "*.csv"))
val lineCountString = SimpleStringProperty("No file selected")
var separatorString = SimpleStringProperty(";")
lateinit var listViewStartDate: SimpleObjectProperty<LocalDate>
fun getMediaList(): ObservableList<Media> {
return media.filtered { m -> m.watchDate.isAfter(listViewStartDate.value.minusDays(1)) }
}
private var recognizedCharset = StandardCharsets.UTF_8
private lateinit var recognizedContentVersion: ContentVersion
fun importData(file: File) {
val imdbViewingHistory = ImdbViewingHistory()
val separatorChar = separatorString.get()[0]
imdbViewingHistory.importFromCsv(file.canonicalPath, separatorChar, recognizedCharset, recognizedContentVersion)
listViewStartDate = SimpleObjectProperty(imdbViewingHistory.getMinimumWatchDate())
media.setAll(imdbViewingHistory.getTraktMediaList())
}
private fun updateInitialDirectory() {
prefs.put(PREFS_LAST_USED_DIR_KEY, file.path.dropLast(file.name.length))
}
fun loadFile(chosenFiles: List<File>) {
if (chosenFiles.isNotEmpty()) {
file = chosenFiles[0]
filename.set(file.name)
val linecount = try {
Files.lines(file.toPath()).count()
} catch (e: UncheckedIOException) {
recognizedCharset = StandardCharsets.ISO_8859_1
Files.lines(file.toPath(), recognizedCharset).count()
} catch (e: Exception) {
println(e)
0L
}
lineCountString.set("${linecount - HEADER_ROW_COUNT} entries found")
updateInitialDirectory()
val fileContentPreview = StringBuffer()
file.useLines { lines: Sequence<String> ->
lines
.take(3)
.forEach { l -> fileContentPreview.append(l).append('\n') }
}
filepreview.set(fileContentPreview.toString())
guessCvsSeparatorChar(fileContentPreview)
identifyContentVersion(fileContentPreview)
importDisabled.set(false)
}
}
private fun identifyContentVersion(fileContentPreview: StringBuffer) {
recognizedContentVersion = if (fileContentPreview.contains("(mins)") && fileContentPreview.contains("\\d\\d\\d\\d-\\d\\d-\\d\\d".toRegex())) {
ContentVersion.V2
} else {
ContentVersion.V1
}
}
private fun guessCvsSeparatorChar(fileContentPreview: StringBuffer) {
val firstline = fileContentPreview.split('\n')[0]
if (firstline.contains(',') && !firstline.contains(';')) {
separatorString.set(",")
}
}
} | 1 | Kotlin | 0 | 1 | 958fd0a0896f23cdb949c6a9ff946a6049fe8eb0 | 3,859 | emtee-shovel | Apache License 2.0 |
src/main/kotlin/ast/statement/ControlFlowStatement.kt | hanawatson | 454,928,396 | false | null | package wgslsmith.wgslgenerator.ast.statement
import wgslsmith.wgslgenerator.ast.WGSLType
import wgslsmith.wgslgenerator.ast.statement.ControlFlowStat.*
import wgslsmith.wgslgenerator.tables.SymbolTable
internal class ControlFlowStatement(
symbolTable: SymbolTable, override var stat: Stat, depth: Int, inLoop: Boolean = false, inFunction: Boolean = false
) : Statement {
private val statement: Statement
init {
if (stat !is ControlFlowStat) {
throw Exception("Failure to validate ControlFlowStat during ControlFlowStatement generation!")
}
statement = when (stat as ControlFlowStat) {
FOR -> ForStatement(symbolTable, stat, depth, inFunction)
IF -> IfStatement(symbolTable, stat, depth, inLoop, inFunction)
LOOP -> LoopStatement(symbolTable, stat, depth, inLoop, inFunction)
SWITCH -> SwitchStatement(symbolTable, stat, depth, inLoop, inFunction)
WHILE -> WhileStatement(symbolTable, stat, depth, inFunction)
}
}
override fun getTabbedLines(): ArrayList<String> {
return statement.getTabbedLines()
}
companion object : StatementCompanion {
override fun usedTypes(stat: Stat): ArrayList<WGSLType> {
return when (stat) {
IF -> IfStatement.usedTypes(stat)
LOOP -> LoopStatement.usedTypes(stat)
SWITCH -> SwitchStatement.usedTypes(stat)
else -> arrayListOf()
}
}
}
} | 0 | Kotlin | 0 | 1 | ffbaad4e42e78eb2eb90e752a57148e4c5f96ffb | 1,534 | wgslgenerator | MIT License |
src/main/kotlin/lmr/rcd/models/hierarchy/storage/EffectStorageInterface.kt | halgorithm | 256,116,377 | false | null | package lmr.rcd.models.hierarchy.storage
import lmr.rcd.models.decorators.EffectDecorator
import lmr.rcd.models.entity.Effect
import lmr.rcd.models.entity.EffectInterface
interface EffectStorageInterface {
fun fetchOwnEffects(): List<Effect>
fun addEffect(effect: Effect)
fun addEffect(decorator: EffectDecorator) = addEffect(decorator.effect)
fun removeEffect(effect: Effect)
fun removeEffect(decorator: EffectDecorator) = removeEffect(decorator.effect)
fun addEffects(effects: List<EffectInterface>) {
effects.forEach {
if (it is EffectDecorator) addEffect(it.effect)
else addEffect(it as Effect)
}
}
fun removeEffects(effects: List<EffectInterface>) {
effects.forEach {
if (it is EffectDecorator) removeEffect(it.effect)
else removeEffect(it as Effect)
}
}
} | 0 | Kotlin | 0 | 0 | 195af71e8794a0867598675dbacb39eae7f20bc5 | 882 | lmr-rcd-kt | Boost Software License 1.0 |
twitlin/src/common/test/kotlin/com/sorrowblue/twitlin/core/TestConstants.kt | SorrowBlue | 278,215,181 | false | null | package com.sorrowblue.twitlin.core
internal const val CONSUMER_KEY = "xvz1evFS4wEEPTGEFPHBog"
internal const val NONCE = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"
internal const val TIMESTAMP = "1318622958"
internal const val CONSUMER_SECRET = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw"
internal const val OAUTH_TOKEN = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"
internal const val OAUTH_TOKEN_SECRET = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE"
internal const val URL = "https://api.twitter.com/1.1/statuses/update.json"
internal const val METHOD = "POST"
internal const val SIGNATURE = "tnnArxj06cWHq44gCs1OSKk/jLY="
internal val PARAMETERS = listOf(
"status" to "Hello Ladies + Gentlemen, a signed OAuth request!",
"include_entities" to "true"
)
| 0 | Kotlin | 0 | 1 | a6f80a270cec89c91239837d590fe92ec869c4ff | 777 | Twitlin | MIT License |
Chapter12/chapter_12_source/app/src/main/java/com/packtpub/eunice/todolist/MainActivity.kt | PacktPublishing | 137,720,264 | false | {"Text": 1, "Markdown": 2, "Gradle": 33, "Java Properties": 23, "Shell": 11, "Batchfile": 11, "Proguard": 11, "XML": 107, "Kotlin": 46, "Java": 1, "JSON": 2, "Ruby": 2} | package com.packtpub.eunice.todolist
import android.app.DialogFragment
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), NewTaskDialogFragment.NewTaskDialogListener {
private var listView: ListView? = null
private var listAdapter: ArrayAdapter<String>? = null
private var todoListItems = ArrayList<String>()
private var showMenuItems = false
private var selectedItem = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
listView = findViewById(R.id.list_view)
populateListView()
fab.setOnClickListener { showNewTaskUI() }
listView?.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> showUpdateTaskUI(position) }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.to_do_list_menu, menu)
val editItem = menu.findItem(R.id.edit_item)
val deleteItem = menu.findItem(R.id.delete_item)
val reminderItem = menu.findItem(R.id.reminder_item)
if (showMenuItems) {
editItem.isVisible = true
deleteItem.isVisible = true
reminderItem.isVisible = true
}
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (-1 != selectedItem) {
if (R.id.edit_item == item?.itemId) {
val updateFragment = NewTaskDialogFragment.newInstance(R.string.update_task_dialog_title, todoListItems[selectedItem])
updateFragment.show(fragmentManager, "updatetask")
} else if (R.id.delete_item == item?.itemId) {
todoListItems.removeAt(selectedItem)
listAdapter?.notifyDataSetChanged()
selectedItem = -1
Snackbar.make(fab, "Task deleted successfully", Snackbar.LENGTH_LONG).setAction("Action", null).show()
} else if (R.id.reminder_item == item?.itemId) {
TimePickerFragment.newInstance(todoListItems[selectedItem])
.show(supportFragmentManager, "mainactivity")
}
}
return super.onOptionsItemSelected(item)
}
private fun showNewTaskUI() {
val newFragment = NewTaskDialogFragment.newInstance(R.string.add_new_task_dialog_title, null)
newFragment.show(fragmentManager, "newtask")
}
private fun showUpdateTaskUI(selected: Int) {
selectedItem = selected
showMenuItems = true
invalidateOptionsMenu()
}
private fun populateListView() {
listAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, todoListItems)
listView?.adapter = listAdapter
}
override fun onDialogPositiveClick(dialog: DialogFragment, task:String) {
if("newtask" == dialog.tag) {
todoListItems.add(task)
listAdapter?.notifyDataSetChanged()
Snackbar.make(fab, "Task Added Successfully", Snackbar.LENGTH_LONG).setAction("Action", null).show()
} else if ("updatetask" == dialog.tag) {
todoListItems[selectedItem] = task
listAdapter?.notifyDataSetChanged()
selectedItem = -1
Snackbar.make(fab, "Task Updated Successfully", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}
override fun onDialogNegativeClick(dialog: DialogFragment) {
}
}
| 0 | Kotlin | 11 | 15 | 887ac15cbaa65b95f94e43b0e374483bc3dce60b | 3,874 | Learning-Kotlin-by-building-Android-Applications | MIT License |
app/src/main/java/kr/co/jsh/base/edit/BasePresenter.kt | jsh-me | 257,524,610 | false | null | package kr.co.jsh.base.edit
import android.content.Intent
//TODO: 공통 메소드 추출
interface BasePresenter {
fun preparePath(extraIntent: Intent)
fun uploadFile(uri: String, type: String)
} | 2 | Kotlin | 20 | 97 | d6e63521991902f44f4afb05b6fd22fb68f3d4a3 | 192 | simple-android-editor | Apache License 2.0 |
app/src/main/java/com/calberto_barbosa_jr/fireconnectkotlinmvvm/activity/FirestoreSaveActivity.kt | calbertobarbosajr | 749,207,646 | false | {"Kotlin": 61653} | package com.calberto_barbosa_jr.fireconnectkotlinmvvm.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
import androidx.lifecycle.ViewModelProvider
import com.calberto_barbosa_jr.fireconnectkotlinmvvm.databinding.ActivityFirestoreSaveBinding
import com.calberto_barbosa_jr.fireconnectkotlinmvvm.model.User
import com.calberto_barbosa_jr.fireconnectkotlinmvvm.viewmodel.FirestoreSaveViewModel
class FirestoreSaveActivity : AppCompatActivity() {
private lateinit var binding: ActivityFirestoreSaveBinding
private lateinit var viewModel: FirestoreSaveViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFirestoreSaveBinding.inflate(layoutInflater)
setContentView(binding.root)
viewModel = ViewModelProvider(this).get(FirestoreSaveViewModel::class.java)
}
private fun showMessage(message: String) {
binding.textViewMessageFirestore.text = message
}
private fun getUserFromUI(): User {
return User(
binding.editTextNameFirestore.text.toString(),
binding.editTextCpfFirestore.text.toString(),
binding.editTextEmailFirestore.text.toString()
)
}
fun buttonSaveFirestore(view: View) {
val user = getUserFromUI()
viewModel.addDocumentToFirestore(user,
onSuccess = { showMessage("Document added successfully!") },
onFailure = { showMessage(it) }
)
}
fun buttonUpdateFirestore(view: View) {
val updates = mutableMapOf<String, Any>()
with(binding) {
editTextNameFirestore.text.toString().takeIf { it.isNotEmpty() }?.let {
updates["name"] = it
}
editTextCpfFirestore.text.toString().takeIf { it.isNotEmpty() }?.let {
updates["cpf"] = it
}
editTextEmailFirestore.text.toString().takeIf { it.isNotEmpty() }?.let {
updates["email"] = it
}
}
viewModel.updateDocumentInFirestore(updates,
onSuccess = { showMessage("Document updated successfully!") },
onFailure = { showMessage(it) }
)
}
fun buttonDeleteFirestore(view: View) {
viewModel.deleteDocumentInFirestore(
onSuccess = { showMessage("Document deleted successfully!") },
onFailure = { showMessage(it) }
)
}
}
| 0 | Kotlin | 0 | 0 | 6c15e3a796948c990f9f694b9a0168fc7bcd44a9 | 2,708 | FireConnectKotlinMVVM | MIT License |
libs/docker-client/src/main/kotlin/batect/docker/DockerTLSConfig.kt | batect | 102,647,061 | false | null | /*
Copyright 2017-2020 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.docker
import java.nio.file.Files
import java.nio.file.Path
import java.security.KeyFactory
import java.security.KeyStore
import java.security.NoSuchAlgorithmException
import java.security.PrivateKey
import java.security.cert.X509Certificate
import java.security.spec.InvalidKeySpecException
import java.security.spec.PKCS8EncodedKeySpec
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.KeyManager
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
import okhttp3.internal.tls.OkHostnameVerifier
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo
import org.bouncycastle.cert.X509CertificateHolder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.openssl.PEMKeyPair
import org.bouncycastle.openssl.PEMParser
sealed class DockerTLSConfig {
abstract val scheme: String
abstract val sslSocketFactory: SSLSocketFactory
abstract val trustManager: X509TrustManager
abstract val hostnameVerifier: HostnameVerifier
object DisableTLS : DockerTLSConfig() {
override val scheme: String = "http"
override val hostnameVerifier: HostnameVerifier = OkHostnameVerifier
// The code for the following is taken from the documentation for OkHttpClient.Builder.sslSocketFactory().
override val trustManager by lazy {
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
trustManagerFactory.trustManagers.single() as X509TrustManager
}
override val sslSocketFactory: SSLSocketFactory by lazy {
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, arrayOf(trustManager), null)
sslContext.socketFactory
}
}
data class EnableTLS(
private val verifyServer: Boolean,
private val caCertificatePath: Path,
private val clientCertificatePath: Path,
private val clientKeyPath: Path
) : DockerTLSConfig() {
override val scheme: String = "https"
override val hostnameVerifier: HostnameVerifier by lazy {
if (verifyServer) {
OkHostnameVerifier
} else {
HostnameVerifier { _, _ -> true }
}
}
private val keyStorePassword = "<PASSWORD>".toCharArray()
// This is based on the example at https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt
// and https://github.com/spotify/docker-client/blob/master/src/main/java/com/spotify/docker/client/DockerCertificates.java.
override val trustManager by lazy {
val certificates = readCertificates(caCertificatePath)
val keyStore = newEmptyKeyStore(keyStorePassword)
certificates.forEach { certificate ->
val alias = certificate.subjectX500Principal.name
keyStore.setCertificateEntry(alias, certificate)
}
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(keyStore, keyStorePassword)
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)
val trustManagers = trustManagerFactory.trustManagers
check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {
"Expected exactly one trust manager with type X.509, but got: $trustManagers"
}
trustManagers[0] as X509TrustManager
}
private val clientKeyManager: KeyManager by lazy {
val clientKey = readPrivateKey(clientKeyPath)
val clientCerts = readCertificates(clientCertificatePath)
val keyStore = newEmptyKeyStore(keyStorePassword)
keyStore.setKeyEntry("key", clientKey, keyStorePassword, clientCerts)
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(keyStore, keyStorePassword)
keyManagerFactory.keyManagers.single()
}
private fun readPrivateKey(keyPath: Path): PrivateKey {
Files.newBufferedReader(keyPath).use { reader ->
PEMParser(reader).use { parser ->
val readObject = parser.readObject()
return when (readObject) {
is PEMKeyPair -> generatePrivateKey(keyPath, readObject.privateKeyInfo)
is PrivateKeyInfo -> generatePrivateKey(keyPath, readObject)
else -> throw IllegalArgumentException("Could not read private key from path $keyPath: received unexpected type ${readObject.javaClass.name}")
}
}
}
}
private fun generatePrivateKey(keyPath: Path, privateKeyInfo: PrivateKeyInfo): PrivateKey {
val spec = PKCS8EncodedKeySpec(privateKeyInfo.encoded)
val algorithms = listOf("RSA", "EC")
val errors = algorithms.map { algorithm ->
try {
val factory = KeyFactory.getInstance(algorithm)
return factory.generatePrivate(spec)
} catch (ex: InvalidKeySpecException) {
algorithm to ex
} catch (ex: NoSuchAlgorithmException) {
algorithm to ex
}
}
throw IllegalArgumentException("Could not parse private key from $keyPath with any of $algorithms. $errors")
}
// The Spotify library uses the built-in Java CertificateFactory, but I found that doesn't work (it incorrectly loads
// the certificates). Wireshark and the OpenSSL command line utility (both viewing certs and creating an encrypted connect)
// were very helpful for debugging this.
private fun readCertificates(certificatePath: Path): Array<X509Certificate> {
val certs = mutableListOf<X509Certificate>()
val converter = JcaX509CertificateConverter()
Files.newBufferedReader(certificatePath).use { reader ->
PEMParser(reader).use { parser ->
when (val obj = parser.readObject()) {
is X509CertificateHolder -> certs.add(converter.getCertificate(obj))
else -> throw IllegalArgumentException("Expected to read a certificate from $certificatePath, but got a ${obj.javaClass.name}")
}
}
}
return certs.toTypedArray()
}
private fun newEmptyKeyStore(password: CharArray): KeyStore {
val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
keyStore.load(null, password)
return keyStore
}
override val sslSocketFactory: SSLSocketFactory by lazy {
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(arrayOf(clientKeyManager), arrayOf(trustManager), null)
sslContext.socketFactory
}
}
}
| 12 | null | 47 | 620 | 1b6cb1d79d91a70a0cb038cc29b2db1c025fea9e | 7,973 | batect | Apache License 2.0 |
input/finance/src/commonMain/kotlin/symphony/StaticSectionRowForm.kt | aSoft-Ltd | 632,021,007 | false | {"Kotlin": 293383, "HTML": 296, "JavaScript": 200} | @file:JsExport
package symphony
import cinematic.Live
import kollections.List
import kotlinx.JsExport
interface StaticSectionRowForm : SectionRow {
val total: NumberField<Double>
val children: Live<List<SectionRow>>
} | 0 | Kotlin | 0 | 0 | 352d0753bcf1a0792e64db57dc664c18c68ed3f2 | 227 | symphony | MIT License |
main/src/main/kotlin/us/wedemy/eggeum/android/main/ui/myaccount/WithdrawFragment.kt | Wedemy | 615,061,021 | false | null | /*
* Designed and developed by Wedemy 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/Wedemy/eggeum-android/blob/main/LICENSE
*/
package us.wedemy.eggeum.android.main.ui.myaccount
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import dev.chrisbanes.insetter.InsetterApplyTypeDsl
import dev.chrisbanes.insetter.applyInsetter
import kotlinx.coroutines.launch
import us.wedemy.eggeum.android.common.extension.repeatOnStarted
import us.wedemy.eggeum.android.common.base.BaseFragment
import us.wedemy.eggeum.android.main.R
import us.wedemy.eggeum.android.main.databinding.FragmentWithdrawBinding
import us.wedemy.eggeum.android.main.ui.MainActivity
import us.wedemy.eggeum.android.main.viewmodel.WithdrawViewModel
@AndroidEntryPoint
class WithdrawFragment : BaseFragment<FragmentWithdrawBinding>() {
override fun getViewBinding() = FragmentWithdrawBinding.inflate(layoutInflater)
private val viewModel by viewModels<WithdrawViewModel>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.root.applyInsetter {
type(
ime = false,
statusBars = false,
navigationBars = true,
f = InsetterApplyTypeDsl::padding,
)
}
initListener()
initObserver()
}
private fun initListener() {
with(binding) {
ivWithdrawClose.setOnClickListener {
if (!findNavController().navigateUp()) {
requireActivity().finish()
}
}
clWithdrawAgreeToNotification.setOnClickListener {
viewModel.setAgreeToWithdraw()
}
btnWithdraw.setOnClickListener {
viewModel.withdraw()
}
}
}
private fun initObserver() {
repeatOnStarted {
launch {
viewModel.agreeToWithdraw.collect { isChecked ->
binding.cbWithdrawAgreeToNotification.isChecked = isChecked
binding.btnWithdraw.isEnabled = isChecked
}
}
launch {
viewModel.navigateToLoginEvent.collect {
Toast.makeText(requireContext(), getString(R.string.withdraw_complete), Toast.LENGTH_SHORT).show()
(activity as MainActivity).navigateToLogin()
}
}
launch {
viewModel.showToastEvent.collect { message ->
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
}
}
}
}
| 9 | null | 0 | 7 | 7f25e68a6e5ba2bdf5a2a3fbdedaa75187d89487 | 2,577 | eggeum-android | MIT License |
src/main/kotlin/me/apyr/chatemotes/commands/SearchCommand.kt | apyrr | 554,905,662 | false | {"Kotlin": 73093} | package me.apyr.chatemotes.commands
import me.apyr.chatemotes.ChatEmotes
import me.apyr.chatemotes.ChatEmotesCommand
import org.bukkit.command.CommandSender
class SearchCommand : ChatEmotesCommand {
override val name: String = "s"
override val description: String = "search for an emote"
override val usage: String = "<name>"
override fun onCommand(sender: CommandSender, args: List<String>) {
}
override fun onTabComplete(sender: CommandSender, args: List<String>): List<String> {
return ChatEmotes.getInstance()
.emotes.values
.let { emotes ->
val term: String? = args.firstOrNull()?.takeIf { it.isNotEmpty() }
if (term != null) {
emotes.filter { e -> e.name.contains(term, ignoreCase = true) }
} else {
emotes
}
}
.map { "${it.name} ${it.char}" }
}
override fun hasPermission(sender: CommandSender): Boolean = true
}
| 0 | Kotlin | 1 | 3 | edf04a0d89f80a7160347330c244157f1300f022 | 921 | spigot-chatemotes | MIT License |
shared/src/commonMain/kotlin/com/presta/customer/ui/components/signWitnessForm/poller/WitnessSigningStatusPoller.kt | morgan4080 | 726,765,347 | false | {"Kotlin": 2170913, "Swift": 2162, "Ruby": 382, "Shell": 228} | package com.presta.customer.ui.components.signWitnessForm.poller
import com.presta.customer.network.longTermLoans.data.LongTermLoansRepository
import com.presta.customer.network.longTermLoans.model.guarantorResponse.PrestaGuarantorResponse
import com.presta.customer.network.longTermLoans.model.witnessRequests.PrestaWitnessRequestResponse
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.flowOn
class WitnessSigningStatusPoller(
private val dataRepository: LongTermLoansRepository,
private val dispatcher: CoroutineDispatcher
) : SignWitnessFormPoller {
@OptIn(DelicateCoroutinesApi::class)
override fun poll(
delay: Long,
token: String,
guarantorRefId: String
): Flow<Result<List<PrestaWitnessRequestResponse>>> {
return channelFlow {
while (!isClosedForSend) {
val data = dataRepository.getWitnessRequests(token, guarantorRefId)
send(data)
delay(delay)
}
}.flowOn(dispatcher)
}
override fun close() {
dispatcher.cancel()
}
} | 0 | Kotlin | 0 | 0 | 0850928853c87390a97953cfec2d21751904d3a9 | 1,302 | kmp | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/GripDotsVertical.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.GripDotsVertical: ImageVector
get() {
if (_gripDotsVertical != null) {
return _gripDotsVertical!!
}
_gripDotsVertical = Builder(name = "GripDotsVertical", 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(17.5f, 24.0f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveToRelative(1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(17.5f, 19.0f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
moveTo(6.5f, 24.0f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveToRelative(1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(6.5f, 19.0f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
moveTo(17.5f, 15.5f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveToRelative(1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(17.5f, 10.5f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
moveTo(6.5f, 15.5f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveToRelative(1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(6.5f, 10.5f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
moveTo(17.5f, 7.0f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveToRelative(1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(17.5f, 2.0f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
moveTo(6.5f, 7.0f)
curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f)
reflectiveCurveTo(4.57f, 0.0f, 6.5f, 0.0f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
close()
moveTo(6.5f, 2.0f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
close()
}
}
.build()
return _gripDotsVertical!!
}
private var _gripDotsVertical: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,374 | icons | MIT License |
app/src/main/java/archiveasia/jp/co/hakenman/activity/SettingActivity.kt | ohjjoa | 267,284,332 | true | {"Kotlin": 62696} | package archiveasia.jp.co.hakenman.activity
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import archiveasia.jp.co.hakenman.CustomLog
import archiveasia.jp.co.hakenman.R
import archiveasia.jp.co.hakenman.TimePickerDialog
import archiveasia.jp.co.hakenman.manager.PrefsManager
import kotlinx.android.synthetic.main.activity_setting.*
class SettingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setting)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = getString(R.string.setting_activity_title)
email_to_editText.setText(PrefsManager(this).emailTo)
default_beginTime_textView.text = PrefsManager(this).defaultBeginTime
default_endTime_textView.text = PrefsManager(this).defaultEndTime
val packageInfo = packageManager.getPackageInfo(packageName, 0)
version_textView.text = packageInfo.versionName
val selectedButtonId = when (PrefsManager(this).interval) {
15 -> R.id.button15
30 -> R.id.button30
else -> R.id.button1
}
interval_radio_group.check(selectedButtonId)
interval_radio_group.setOnCheckedChangeListener { _, checkedId ->
PrefsManager(this).interval = when (checkedId) {
R.id.button1 -> 1
R.id.button15 -> 15
R.id.button30 -> 30
else -> 1
}
}
default_beginTime_ConstraintLayout.setOnClickListener {
showAddDialog(R.string.set_beginTime_title,
default_beginTime_textView,
TimePickerDialog.WorkTimeType.BEGIN_TIME)
}
default_endTime_ConstraintLayout.setOnClickListener {
showAddDialog(R.string.set_endTime_title,
default_endTime_textView,
TimePickerDialog.WorkTimeType.END_TIME)
}
CustomLog.d("設定画面")
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return if (item?.itemId == android.R.id.home) {
PrefsManager(this).emailTo = email_to_editText.text.toString()
finish()
true
} else {
super.onOptionsItemSelected(item)
}
}
override fun onBackPressed() {
super.onBackPressed()
PrefsManager(this).emailTo = email_to_editText.text.toString()
}
private fun showAddDialog(titleId: Int, textView: TextView,
workTimeType: TimePickerDialog.WorkTimeType) {
TimePickerDialog(this)
.title(titleId)
.show(textView.text.toString(), workTimeType) {
textView.text = it
when (workTimeType) {
TimePickerDialog.WorkTimeType.BEGIN_TIME ->
PrefsManager(this).defaultBeginTime = it
TimePickerDialog.WorkTimeType.END_TIME ->
PrefsManager(this).defaultEndTime = it
TimePickerDialog.WorkTimeType.BREAK_TIME ->
CustomLog.d("何もしない")
}
}
}
}
| 0 | Kotlin | 0 | 0 | f30dce1bfebb4bc6afab487a27fc716d12b34175 | 3,290 | Hakenman_Android | MIT License |
compiler/psi/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeAliasStubImpl.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.psi.stubs.impl
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.util.io.StringRef
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.stubs.KotlinTypeAliasStub
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes
class KotlinTypeAliasStubImpl(
parent: StubElement<out PsiElement>?,
private val name: StringRef?,
private val qualifiedName: StringRef?,
private val isTopLevel: Boolean
) : KotlinStubBaseImpl<KtTypeAlias>(parent, KtStubElementTypes.TYPEALIAS), KotlinTypeAliasStub {
override fun getName(): String? =
StringRef.toString(name)
override fun getFqName(): FqName? =
StringRef.toString(qualifiedName)?.let { FqName(it) }
override fun isTopLevel(): Boolean = isTopLevel
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,508 | kotlin | Apache License 2.0 |
src/main/kotlin/org/ergoplatform/obolflip/ErgoPayController.kt | ObolFlip | 549,191,417 | false | {"Kotlin": 73439, "JavaScript": 5904, "HTML": 1328} | package org.ergoplatform.obolflip
import org.ergoplatform.appkit.Address
import org.ergoplatform.appkit.BoxOperations
import org.ergoplatform.ergopay.ErgoPayResponse
import org.ergoplatform.obolflip.handler.ObolFlipBoxOperations
import org.ergoplatform.obolflip.service.NodePeerService
import org.ergoplatform.obolflip.service.ObolFlipService
import org.ergoplatform.obolflip.service.PayoutService
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import java.util.*
@RestController
@CrossOrigin
class ErgoPayController(
private val nodePeerService: NodePeerService,
private val obolFlipService: ObolFlipService,
private val payoutService: PayoutService,
) {
@GetMapping("/ergopay/firstinit/{address}")
fun initFlip(@PathVariable address: String): ErgoPayResponse {
val ergoPayResponse = ErgoPayResponse()
try {
nodePeerService.getErgoClient().execute { ctx ->
val boxOperations = BoxOperations.createForSender(Address.create(address), ctx)
val unsignedTx = ObolFlipBoxOperations.firstInitOrUpdate(boxOperations)
ergoPayResponse.reducedTx = Base64.getUrlEncoder()
.encodeToString(ctx.newProverBuilder().build().reduce(unsignedTx, 0).toBytes())
}
} catch (t: Throwable) {
ergoPayResponse.messageSeverity = ErgoPayResponse.Severity.ERROR
ergoPayResponse.message = t.message
}
return ergoPayResponse
}
@GetMapping("/ergopay/purchaseTicket/{tokenType}/{address}")
fun purchaseTicket(
@PathVariable address: String,
@PathVariable tokenType: Int
): ErgoPayResponse {
val ergoPayResponse = ErgoPayResponse()
val isHead = tokenType == 0
try {
ergoPayResponse.reducedTx = Base64.getUrlEncoder().encodeToString(
obolFlipService.getTicketPurchaseTransaction(address, isHead).toBytes()
)
ergoPayResponse.message = "Please confirm to bet on ${if (isHead) "heads" else "tails"}."
ergoPayResponse.messageSeverity = ErgoPayResponse.Severity.INFORMATION
} catch (t: Throwable) {
ergoPayResponse.messageSeverity = ErgoPayResponse.Severity.ERROR
ergoPayResponse.message = t.message
}
return ergoPayResponse
}
@GetMapping("/ergopay/redeem/{roundNumber}/{address}")
fun redeemTicket(
@PathVariable address: String,
@PathVariable roundNumber: Int
): ErgoPayResponse {
val ergoPayResponse = ErgoPayResponse()
try {
ergoPayResponse.reducedTx = Base64.getUrlEncoder().encodeToString(
payoutService.redeem(address, roundNumber).toBytes()
)
ergoPayResponse.message = "Please confirm redeeming your ticket."
ergoPayResponse.messageSeverity = ErgoPayResponse.Severity.INFORMATION
} catch (t: Throwable) {
ergoPayResponse.messageSeverity = ErgoPayResponse.Severity.ERROR
ergoPayResponse.message = t.message
}
return ergoPayResponse
}
} | 0 | Kotlin | 0 | 0 | f1937b4a6a9b1345414aa2cd5bb55b7ca1b44f20 | 3,317 | obolflip-client | MIT License |
app/src/main/java/chat/rocket/android/helper/BindingAdapters.kt | WideChat | 121,754,060 | true | null | package chat.rocket.android.helper
import androidx.databinding.BindingAdapter
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
@BindingAdapter("roundedCornerRadius")
fun setRoundedCornerRadius(view: SimpleDraweeView, height: Float) {
val roundingParams = RoundingParams.fromCornersRadius(height)
view.hierarchy.roundingParams = roundingParams
} | 132 | Kotlin | 6 | 12 | ec3430da222d68e132ce0308197e769fff99ff5b | 404 | Rocket.Chat.Android | MIT License |
klang/libclang/src/main/kotlin/klang/jvm/binding/CXSourceRange.kt | ygdrasil-io | 634,882,904 | false | {"Kotlin": 292451, "C": 3541, "Shell": 2951, "Objective-C": 1076, "C++": 567} | package klang.jvm.binding
import com.sun.jna.Pointer
import com.sun.jna.Structure
import com.sun.jna.Structure.FieldOrder
@SuppressWarnings("unused")
@FieldOrder("ptr_data", "begin_int_data", "end_int_data")
sealed class CXSourceRange: Structure() {
var ptr_data: Pointer = Pointer.NULL
var begin_int_data: Int = 0
var end_int_data: Int = 0
}
class CXSourceRangeByVale: CXSourceRange(), Structure.ByValue | 2 | Kotlin | 1 | 0 | 5889fb009a06f141d238587b7288ef727873253e | 421 | klang | MIT License |
app/src/main/java/com/qaisjp/reveddit/ShareActivity.kt | qaisjp | 412,869,333 | false | {"Kotlin": 7473} | package com.qaisjp.reveddit
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
class Share : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// If a shared piece of text
if (intent.action == Intent.ACTION_SEND) {
if ("text/plain" == intent.type) {
handleSharedTextIntent(intent)
return
}
}
throw RuntimeException("Unexpected intent ${intent.type}")
}
private val USE_CUSTOM_TABS = true;
private fun handleSharedTextIntent(intent: Intent) {
val url = intent.getStringExtra(Intent.EXTRA_TEXT)!!
// lazy way to convert reddit.com to reveddit.com.
// this will edit "reddit.com" outside of the host, but for
// post links that doesn't matter—only the IDs matter.
//
// note: avoiding url.startWith because of `np.reddit.com` links.
val replacedUrl = url.replace("reddit.com", "reveddit.com")
val uri = Uri.parse(replacedUrl)
if (USE_CUSTOM_TABS) {
val builder = CustomTabsIntent.Builder()
// Make the address bar colour match reveddit's header
val colorInt: Int = Color.parseColor("#c70300")
builder.setDefaultColorSchemeParams(
CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorInt)
.build()
)
builder.build().launchUrl(this, uri)
finish()
} else {
val browserIntent = Intent(Intent.ACTION_VIEW, uri)
startActivity(browserIntent)
finish()
}
}
} | 0 | Kotlin | 0 | 0 | 909ebb3ec1a4badfaffc3810354112addb81584f | 1,920 | reveddit | MIT License |
app/src/main/kotlin/org/andstatus/app/data/checker/CheckConversations.kt | andstatus | 3,040,264 | false | {"Kotlin": 3385973, "XSLT": 14655, "HTML": 14046, "CSS": 4427, "Shell": 707} | /*
* Copyright (c) 2016 yvolk (<NAME>), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data.checker
import android.database.Cursor
import android.provider.BaseColumns
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DbUtils.closeSilently
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.SqlIds
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.UriUtils.isRealOid
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
/**
* @author <EMAIL>
*/
class CheckConversations : DataChecker() {
private val items: MutableMap<Long, NoteItem> = TreeMap()
private val replies: MutableMap<Long, MutableList<NoteItem>> = TreeMap()
private val noteIdsOfOneConversation: MutableSet<Long> = HashSet()
private inner class NoteItem {
var id: Long = 0
var originId: Long = 0
var inReplyToIdInitial: Long = 0
var inReplyToId: Long = 0
var conversationIdInitial: Long = 0
var conversationId: Long = 0
var conversationOid: String = ""
fun fixConversationId(conversationId: Long): Boolean {
val different = this.conversationId != conversationId
if (different) {
this.conversationId = conversationId
}
return different
}
fun fixInReplyToId(inReplyToId: Int): Boolean {
val different = this.inReplyToId != inReplyToId.toLong()
if (different) {
this.inReplyToId = inReplyToId.toLong()
}
return different
}
fun isChanged(): Boolean {
return isConversationIdChanged() || isInReplyToIdChanged()
}
fun isConversationIdChanged(): Boolean {
return conversationId != conversationIdInitial
}
fun isInReplyToIdChanged(): Boolean {
return inReplyToId != inReplyToIdInitial
}
override fun toString(): String {
return "NoteItem{" +
"id=" + id +
", originId=" + originId +
if (inReplyToIdInitial == inReplyToId) {
", inReplyToId=" + inReplyToId
} else {
", inReplyToId changed from " + inReplyToIdInitial +
" to " + inReplyToId
} +
if (conversationIdInitial == conversationId) {
", conversationId=" + conversationId
} else {
", conversationId changed from " + conversationIdInitial +
" to " + conversationId
} +
", conversationOid='" + conversationOid + '\'' +
'}'
}
}
fun setNoteIdsOfOneConversation(ids: MutableSet<Long>): CheckConversations {
noteIdsOfOneConversation.addAll(ids)
return this
}
override fun fixInternal(): Long {
loadNotes()
if (noteIdsOfOneConversation.isEmpty()) {
fixConversationsUsingReplies()
fixConversationsUsingConversationOid()
} else {
fixOneConversation()
}
return saveChanges(countOnly).toLong()
}
private fun loadNotes() {
items.clear()
replies.clear()
var sql = ("SELECT " + BaseColumns._ID
+ ", " + NoteTable.ORIGIN_ID
+ ", " + NoteTable.IN_REPLY_TO_NOTE_ID
+ ", " + NoteTable.CONVERSATION_ID
+ ", " + NoteTable.CONVERSATION_OID
+ " FROM " + NoteTable.TABLE_NAME)
if (noteIdsOfOneConversation.size > 0) {
sql += (" WHERE " + NoteTable.CONVERSATION_ID + " IN ("
+ "SELECT DISTINCT " + NoteTable.CONVERSATION_ID
+ " FROM " + NoteTable.TABLE_NAME + " WHERE "
+ BaseColumns._ID + SqlIds.fromIds(noteIdsOfOneConversation).getSql()
+ ")")
}
var cursor: Cursor? = null
var rowsCount: Long = 0
try {
cursor = myContext.database?.rawQuery(sql, null)
while (cursor?.moveToNext() == true) {
rowsCount++
val item = NoteItem()
item.id = DbUtils.getLong(cursor, BaseColumns._ID)
item.originId = DbUtils.getLong(cursor, NoteTable.ORIGIN_ID)
item.inReplyToId = DbUtils.getLong(cursor, NoteTable.IN_REPLY_TO_NOTE_ID)
item.inReplyToIdInitial = item.inReplyToId
item.conversationId = DbUtils.getLong(cursor, NoteTable.CONVERSATION_ID)
item.conversationIdInitial = item.conversationId
item.conversationOid = DbUtils.getString(cursor, NoteTable.CONVERSATION_OID)
items[item.id] = item
if (item.inReplyToId != 0L) {
replies.computeIfAbsent(item.inReplyToId) { ArrayList() }.add(item)
}
}
} finally {
closeSilently(cursor)
}
logger.logProgress(rowsCount.toString() + " notes loaded")
}
private fun fixConversationsUsingReplies() {
val counter = AtomicInteger()
for (item in items.values) {
if (item.inReplyToId != 0L) {
val parent = items[item.inReplyToId]
if (parent == null || parent.originId != item.originId) {
item.fixInReplyToId(0)
} else {
if (parent.conversationId == 0L) {
parent.fixConversationId(if (item.conversationId == 0L) parent.id else item.conversationId)
}
if (item.fixConversationId(parent.conversationId)) {
changeConversationOfReplies(item, 200)
}
}
}
counter.incrementAndGet()
logger.logProgressIfLongProcess { "Checked replies for " + counter.get() + " notes of " + items.size }
}
}
private fun fixConversationsUsingConversationOid() {
val counter = AtomicInteger()
val originToConversations: MutableMap<Long, MutableMap<String, NoteItem>> = ConcurrentHashMap()
for (item in items.values) {
if (item.conversationOid.isRealOid) {
val firstConversationMembers: MutableMap<String, NoteItem> = originToConversations
.computeIfAbsent(item.originId) { ConcurrentHashMap() }
val parent = firstConversationMembers[item.conversationOid]
if (parent == null) {
item.fixConversationId(if (item.conversationId == 0L) item.id else item.conversationId)
firstConversationMembers[item.conversationOid] = item
} else {
if (item.fixConversationId(parent.conversationId)) {
changeConversationOfReplies(item, 200)
}
}
}
counter.incrementAndGet()
logger.logProgressIfLongProcess { "Checked conversations for " + counter + " notes of " + items.size }
}
}
private fun changeConversationOfReplies(parent: NoteItem, level: Int) {
val replies1 = replies[parent.id] ?: return
for (item in replies1) {
if (item.originId != parent.originId) {
item.fixInReplyToId(0)
} else if (item.fixConversationId(parent.conversationId)) {
if (level > 0) {
changeConversationOfReplies(item, level - 1)
} else {
logger.logProgress("Too long conversation, couldn't fix noteId=" + item.id)
}
}
}
}
private fun fixOneConversation() {
val newConversationId = items.values.stream().map { noteItem: NoteItem -> noteItem.conversationId }
.min { obj: Long, anotherLong: Long -> obj.compareTo(anotherLong) }.orElse(0L)
check(newConversationId != 0L) { "Conversation ID=0, $noteIdsOfOneConversation" }
for (item in items.values) {
item.conversationId = newConversationId
}
}
private fun saveChanges(countOnly: Boolean): Int {
val counter = AtomicInteger()
for (item in items.values) {
if (item.isChanged()) {
var sql = ""
try {
// if (counter.get() < 5 && MyLog.isVerboseEnabled()) {
if (MyLog.isVerboseEnabled()) {
MyLog.v(this, "$item" +
", content:'" + MyQuery.noteIdToStringColumnValue(NoteTable.CONTENT, item.id) + "'"
)
}
if (!countOnly) {
sql = ("UPDATE " + NoteTable.TABLE_NAME
+ " SET "
+ (if (item.isInReplyToIdChanged()) NoteTable.IN_REPLY_TO_NOTE_ID + "=" + DbUtils.sqlZeroToNull(
item.inReplyToId
) else "")
+ (if (item.isInReplyToIdChanged() && item.isConversationIdChanged()) ", " else "")
+ (if (item.isConversationIdChanged()) NoteTable.CONVERSATION_ID + "=" + DbUtils.sqlZeroToNull(
item.conversationId
) else "")
+ " WHERE " + BaseColumns._ID + "=" + item.id)
myContext.database?.execSQL(sql)
}
counter.incrementAndGet()
logger.logProgressIfLongProcess { "Saved changes for $counter notes" }
} catch (e: Exception) {
val logMsg = "Error: " + e.message + ", SQL:" + sql
logger.logProgress(logMsg)
MyLog.e(this, logMsg, e)
}
}
}
return counter.get()
}
}
| 86 | Kotlin | 69 | 306 | 6166aded1f115e6e6a7e66ca3756f39f0434663e | 10,612 | andstatus | Apache License 2.0 |
skiko/buildSrc/src/main/kotlin/properties.kt | JetBrains | 282,864,178 | false | null | import org.gradle.api.Project
import java.io.File
enum class OS(
val id: String,
val clangFlags: Array<String>
) {
Linux("linux", arrayOf()),
Android("android", arrayOf()),
Windows("windows", arrayOf()),
MacOS("macos", arrayOf("-mmacosx-version-min=10.13")),
Wasm("wasm", arrayOf()),
IOS("ios", arrayOf())
;
val isWindows
get() = this == Windows
}
val OS.isCompatibleWithHost: Boolean
get() = when (this) {
OS.Linux -> hostOs == OS.Linux
OS.Windows -> hostOs == OS.Windows
OS.MacOS, OS.IOS -> hostOs == OS.MacOS
OS.Wasm -> true
OS.Android -> true
}
fun compilerForTarget(os: OS, arch: Arch): String =
when (os) {
OS.Linux -> when (arch) {
Arch.X64 -> "g++"
Arch.Arm64 -> "clang++"
Arch.Wasm -> "Unexpected combination: $os & $arch"
}
OS.Android -> "clang++"
OS.Windows -> "cl.exe"
OS.MacOS, OS.IOS -> "clang++"
OS.Wasm -> "emcc"
}
fun linkerForTarget(os: OS, arch: Arch): String =
if (os.isWindows) "link.exe" else compilerForTarget(os, arch)
val OS.dynamicLibExt: String
get() = when (this) {
OS.Linux, OS.Android -> ".so"
OS.Windows -> ".dll"
OS.MacOS, OS.IOS -> ".dylib"
OS.Wasm -> ".wasm"
}
enum class Arch(val id: String) {
X64("x64"),
Arm64("arm64"),
Wasm("wasm")
}
enum class SkiaBuildType(
val id: String,
val flags: Array<String>,
val clangFlags: Array<String>,
val msvcCompilerFlags: Array<String>,
val msvcLinkerFlags: Array<String>
) {
DEBUG(
"Debug",
flags = arrayOf("-DSK_DEBUG"),
clangFlags = arrayOf("-std=c++17", "-g"),
msvcCompilerFlags = arrayOf("/Zi"),
msvcLinkerFlags = arrayOf("/DEBUG"),
),
RELEASE(
id = "Release",
flags = arrayOf("-DNDEBUG"),
clangFlags = arrayOf("-std=c++17", "-O3"),
msvcCompilerFlags = arrayOf("/O2"),
msvcLinkerFlags = arrayOf("/DEBUG"),
);
override fun toString() = id
}
val hostOs by lazy {
val osName = System.getProperty("os.name")
when {
osName == "Mac OS X" -> OS.MacOS
osName == "Linux" -> OS.Linux
osName.startsWith("Win") -> OS.Windows
else -> throw Error("Unknown OS $osName")
}
}
val hostArch by lazy {
val osArch = System.getProperty("os.arch")
when (osArch) {
"x86_64", "amd64" -> Arch.X64
"aarch64" -> Arch.Arm64
else -> throw Error("Unknown arch $osArch")
}
}
fun findTargetOs() = when (System.getProperty("skiko.target.os.name")) {
"linux" -> OS.Linux
"macos" -> OS.MacOS
"windows" -> OS.Windows
"wasm" -> OS.Wasm
else -> null
}
fun findTargetArch() = when (System.getProperty("skiko.target.os.arch")) {
"x64" -> Arch.X64
"arm64" -> Arch.Arm64
"wasm" -> Arch.Wasm
else -> null
}
val targetOs = findTargetOs() ?: hostOs
val targetArch = findTargetArch() ?: hostArch
fun targetId(os: OS, arch: Arch) =
"${os.id}-${arch.id}"
val jdkHome = System.getProperty("java.home") ?: error("'java.home' is null")
class SkikoProperties(private val myProject: Project) {
val isCIBuild: Boolean
get() = myProject.hasProperty("teamcity")
val deployVersion: String
get() {
val version = myProject.property("deploy.version") as String
return if (isRelease) version else "$version-SNAPSHOT"
}
val isRelease: Boolean
get() = myProject.findProperty("deploy.release") == "true"
val buildType: SkiaBuildType
get() = if (myProject.findProperty("skiko.debug") == "true") SkiaBuildType.DEBUG else SkiaBuildType.RELEASE
val includeTestHelpers: Boolean
get() = !isRelease
fun skiaReleaseFor(os: OS, arch: Arch, buildType: SkiaBuildType): String {
val target = "${os.id}-${arch.id}"
val tag = myProject.property("dependencies.skia.$target") as String
val suffix = if (os == OS.Linux && arch == Arch.X64) "-ubuntu18" else ""
return "${tag}/Skia-${tag}-${os.id}-${buildType.id}-${arch.id}$suffix"
}
val releaseGithubVersion: String
get() = (myProject.property("release.github.version") as String)
val releaseGithubCommit: String
get() = (myProject.property("release.github.commit") as String)
val visualStudioBuildToolsDir: File?
get() = System.getenv()["SKIKO_VSBT_PATH"]?.let { File(it) }?.takeIf { it.isDirectory }
// todo: make compatible with the configuration cache
val skiaDir: File?
get() = (System.getenv()["SKIA_DIR"] ?: System.getProperty("skia.dir"))?.let { File(it) }
?.takeIf { it.isDirectory }
val composeRepoUrl: String
get() = System.getenv("COMPOSE_REPO_URL") ?: "https://maven.pkg.jetbrains.space/public/p/compose/dev"
val composeRepoUserName: String
get() = System.getenv("COMPOSE_REPO_USERNAME") ?: ""
val composeRepoKey: String
get() = System.getenv("COMPOSE_REPO_KEY") ?: ""
val signHost: String?
get() = System.getenv("JB_SIGN_HOST")
?: (myProject.findProperty("sign_host") as? String)
val signUser: String?
get() = System.getenv("JB_SIGN_USER")
?: (myProject.findProperty("sign_host_user") as? String)
val signToken: String?
get() = System.getenv("JB_SIGN_TOKEN")
?: (myProject.findProperty("sign_host_token") as? String)
val dependenciesDir: File
get() = myProject.rootProject.projectDir.resolve("dependencies")
}
object SkikoArtifacts {
// names are also used in samples, e.g. samples/SkijaInjectSample/build.gradle
val commonArtifactId = "skiko"
val jvmArtifactId = "skiko-awt"
val jsArtifactId = "skiko-js"
val jsWasmArtifactId = "skiko-js-wasm-runtime"
fun jvmRuntimeArtifactIdFor(os: OS, arch: Arch) =
"skiko-awt-runtime-${targetId(os, arch)}"
// Using custom name like skiko-<Os>-<Arch> (with a dash)
// does not seem possible (at least without adding a dash to a target's tasks),
// so we're using the default naming pattern instead.
// See https://youtrack.jetbrains.com/issue/KT-50001.
fun nativeArtifactIdFor(os: OS, arch: Arch) =
"skiko-${os.id}${arch.id}"
}
| 42 | null | 43 | 840 | cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe | 6,344 | skiko | Apache License 2.0 |
plugins/kotlin/gradle/code-insight-groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/KotlinGradleInspectionVisitor.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.gradle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.configuration.isGradleModule
import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleConstants
import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade
import org.jetbrains.kotlin.idea.roots.findGradleProjectStructure
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
const val KOTLIN_PLUGIN_CLASSPATH_MARKER = "${KotlinGradleConstants.GROUP_ID}:${KotlinGradleConstants.GRADLE_PLUGIN_ID}:"
abstract class KotlinGradleInspectionVisitor : BaseInspectionVisitor() {
override fun visitFile(file: GroovyFileBase) {
if (!FileUtilRt.extensionEquals(file.name, KotlinGradleConstants.GROOVY_EXTENSION)) return
val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex
if (!ApplicationManager.getApplication().isUnitTestMode) {
val module = fileIndex.getModuleForFile(file.virtualFile) ?: return
if (!module.isGradleModule()) return
}
if (fileIndex.isExcluded(file.virtualFile)) return
super.visitFile(file)
}
}
fun getResolvedKotlinGradleVersion(file: PsiFile) =
ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let { getResolvedKotlinGradleVersion(it) }
fun getResolvedKotlinGradleVersion(module: Module): String? {
val projectStructureNode = findGradleProjectStructure(module) ?: return null
val gradleFacade = KotlinGradleFacade.instance ?: return null
for (node in ExternalSystemApiUtil.findAll(projectStructureNode, ProjectKeys.MODULE)) {
if (node.data.internalName == module.name) {
val kotlinPluginVersion = gradleFacade.findKotlinPluginVersion(node)
if (kotlinPluginVersion != null) {
return kotlinPluginVersion
}
}
}
return null
}
| 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 2,507 | intellij-community | Apache License 2.0 |
packages/mongodb-dialects/java-driver/src/test/kotlin/com/mongodb/jbplugin/dialects/javadriver/glossary/PsiMdbTreeUtilTest.kt | mongodb-js | 797,134,624 | false | {"Kotlin": 819787, "Java": 3534, "Shell": 1673, "HTML": 254} | package com.mongodb.jbplugin.dialects.javadriver.glossary
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiType
import com.intellij.psi.PsiTypes
import com.mongodb.jbplugin.dialects.javadriver.IntegrationTest
import com.mongodb.jbplugin.mql.*
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
private typealias PsiTypeProvider = (Project) -> PsiType
@IntegrationTest
class PsiMdbTreeUtilTest {
@ParameterizedTest
@MethodSource("psiTypeToBsonType")
fun `should map all psi types to their corresponding bson types`(
typeProvider: PsiTypeProvider,
expected: BsonType,
project: Project,
) {
ApplicationManager.getApplication().invokeAndWait {
val psiType = typeProvider(project)
assertEquals(expected, psiType.toBsonType())
}
}
companion object {
@JvmStatic
fun psiTypeToBsonType(): Array<Array<Any>> =
arrayOf(
arrayOf({ project: Project -> project.findClass("org.bson.types.ObjectId") },
BsonAnyOf(BsonObjectId, BsonNull),
),
arrayOf({ _: Project -> PsiTypes.booleanType() },
BsonBoolean,
),
arrayOf({ _: Project -> PsiTypes.shortType() },
BsonInt32,
),
arrayOf({ _: Project -> PsiTypes.intType() },
BsonInt32,
),
arrayOf({ _: Project -> PsiTypes.longType() },
BsonInt64,
),
arrayOf({ _: Project -> PsiTypes.floatType() },
BsonDouble,
),
arrayOf({ _: Project -> PsiTypes.doubleType() },
BsonDouble,
),
arrayOf({ project: Project -> project.findClass("java.lang.CharSequence") },
BsonAnyOf(BsonString, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.lang.String") },
BsonAnyOf(BsonString, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.util.Date") },
BsonAnyOf(BsonDate, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.time.LocalDate") },
BsonAnyOf(BsonDate, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.time.LocalDateTime") },
BsonAnyOf(BsonDate, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.math.BigInteger") },
BsonAnyOf(BsonInt64, BsonNull),
),
arrayOf({ project: Project -> project.findClass("java.math.BigDecimal") },
BsonAnyOf(BsonDecimal128, BsonNull),
),
)
}
}
private fun Project.findClass(name: String): PsiType =
JavaPsiFacade.getElementFactory(this).createTypeByFQClassName(
name,
)
| 2 | Kotlin | 0 | 4 | 212a3007dbc6e1235aa2ef60cc053316221b447b | 3,296 | intellij | Apache License 2.0 |
app/src/main/java/com/android/support/model/ui/IAccount.kt | quangpv | 448,463,537 | false | null | package com.android.support.model.ui
import android.os.Parcelable
import com.android.support.R
import com.android.support.exception.viewError
import kotlinx.parcelize.Parcelize
interface IAccount {
val email: String get() = ""
val password: String get() = ""
val save: Boolean get() = false
}
@Parcelize
class LoginForm(
override var email: String = "",
override var password: String = "",
override var save: Boolean = false
) : IAccount, Parcelable {
fun validate() {
if (email.isBlank()) viewError(R.id.edtUserName, "Email should not be blank")
if (password.isBlank()) viewError(R.id.edtPassword, "Password should not be blank")
}
fun set(account: IAccount) {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 0 | 537c63e92640f75abbfab5dbe5159a6d67489106 | 762 | android-support | MIT License |
korte/src/commonMain/kotlin/com/soywiz/korte/internal/extraProperty.kt | korlibs | 78,780,091 | false | null | package com.soywiz.korte.internal
import kotlin.reflect.*
internal class extraProperty<R, T : Any>(val getExtraMap: R.() -> MutableMap<String, Any>, val name: String? = null, val default: () -> T) {
inline operator fun getValue(thisRef: R, property: KProperty<*>): T =
getExtraMap(thisRef)[name ?: property.name] as T? ?: default()
inline operator fun setValue(thisRef: R, property: KProperty<*>, value: T): Unit {
getExtraMap(thisRef)[name ?: property.name] = value
}
}
| 9 | Kotlin | 7 | 69 | 205c241a1c9a9a82809dc3c8d5bfbc92e414f90b | 481 | korte | MIT License |
core/kotlinx-coroutines-core/test/guide/example-channel-01.kt | tiden0614 | 150,764,314 | true | {"Kotlin": 1730428, "CSS": 8215, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 356} | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
package kotlinx.coroutines.experimental.guide.channel01
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*
fun main(args: Array<String>) = runBlocking<Unit> {
val channel = Channel<Int>()
launch {
// this might be heavy CPU-consuming computation or async logic, we'll just send five squares
for (x in 1..5) channel.send(x * x)
}
// here we print five received integers:
repeat(5) { println(channel.receive()) }
println("Done!")
}
| 0 | Kotlin | 0 | 0 | cbeef1039d7402939bac8ec4674e1a7b1adf993a | 716 | kotlinx.coroutines | Apache License 2.0 |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/symbols/KtFirSymbolProvider.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.symbols
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.renderWithType
import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState
import org.jetbrains.kotlin.idea.fir.low.level.api.api.getOrBuildFirFile
import org.jetbrains.kotlin.idea.fir.low.level.api.api.getOrBuildFirOfType
import org.jetbrains.kotlin.idea.fir.low.level.api.api.withFirDeclarationOfType
import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.frontend.api.ValidityTokenOwner
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.weakRef
import org.jetbrains.kotlin.idea.frontend.api.symbols.*
import org.jetbrains.kotlin.idea.frontend.api.tokens.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.withValidityAssertion
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
internal class KtFirSymbolProvider(
override val analysisSession: KtAnalysisSession,
firSymbolProvider: FirSymbolProvider,
private val resolveState: FirModuleResolveState,
private val firSymbolBuilder: KtSymbolByFirBuilder,
override val token: ValidityToken,
) : KtSymbolProvider(), ValidityTokenOwner {
private val firSymbolProvider by weakRef(firSymbolProvider)
override fun getParameterSymbol(psi: KtParameter): KtValueParameterSymbol = withValidityAssertion {
if (psi.isFunctionTypeParameter) {
error("Creating KtValueParameterSymbol for function type parameter is not possible. Please see the KDoc of getParameterSymbol")
}
psi.withFirDeclarationOfType<FirValueParameter, KtValueParameterSymbol>(resolveState) {
firSymbolBuilder.variableLikeBuilder.buildValueParameterSymbol(it)
}
}
override fun getFileSymbol(psi: KtFile): KtFileSymbol = withValidityAssertion {
firSymbolBuilder.buildFileSymbol(psi.getOrBuildFirFile(resolveState))
}
override fun getFunctionLikeSymbol(psi: KtNamedFunction): KtFunctionLikeSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirFunction, KtFunctionLikeSymbol>(resolveState) { fir ->
when (fir) {
is FirSimpleFunction -> firSymbolBuilder.functionLikeBuilder.buildFunctionSymbol(fir)
is FirAnonymousFunction -> firSymbolBuilder.functionLikeBuilder.buildAnonymousFunctionSymbol(fir)
else -> error("Unexpected ${fir.renderWithType()}")
}
}
}
override fun getConstructorSymbol(psi: KtConstructor<*>): KtConstructorSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirConstructor, KtConstructorSymbol>(resolveState) {
firSymbolBuilder.functionLikeBuilder.buildConstructorSymbol(it)
}
}
override fun getTypeParameterSymbol(psi: KtTypeParameter): KtTypeParameterSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirTypeParameter, KtTypeParameterSymbol>(resolveState) {
firSymbolBuilder.classifierBuilder.buildTypeParameterSymbol(it)
}
}
override fun getTypeAliasSymbol(psi: KtTypeAlias): KtTypeAliasSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirTypeAlias, KtTypeAliasSymbol>(resolveState) {
firSymbolBuilder.classifierBuilder.buildTypeAliasSymbol(it)
}
}
override fun getEnumEntrySymbol(psi: KtEnumEntry): KtEnumEntrySymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirEnumEntry, KtEnumEntrySymbol>(resolveState) {
firSymbolBuilder.buildEnumEntrySymbol(it)
}
}
override fun getAnonymousFunctionSymbol(psi: KtNamedFunction): KtAnonymousFunctionSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirSimpleFunction, KtFunctionSymbol>(resolveState) {
firSymbolBuilder.functionLikeBuilder.buildFunctionSymbol(it)
}
firSymbolBuilder.functionLikeBuilder.buildAnonymousFunctionSymbol(psi.getOrBuildFirOfType(resolveState))
}
override fun getAnonymousFunctionSymbol(psi: KtFunctionLiteral): KtAnonymousFunctionSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirAnonymousFunction, KtAnonymousFunctionSymbol>(resolveState) {
firSymbolBuilder.functionLikeBuilder.buildAnonymousFunctionSymbol(it)
}
}
override fun getVariableSymbol(psi: KtProperty): KtVariableSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirProperty, KtVariableSymbol>(resolveState) {
firSymbolBuilder.variableLikeBuilder.buildVariableSymbol(it)
}
}
override fun getAnonymousObjectSymbol(psi: KtObjectLiteralExpression): KtAnonymousObjectSymbol = withValidityAssertion {
psi.objectDeclaration.withFirDeclarationOfType<FirAnonymousObject, KtAnonymousObjectSymbol>(resolveState) {
firSymbolBuilder.classifierBuilder.buildAnonymousObjectSymbol(it)
}
}
override fun getClassOrObjectSymbol(psi: KtClassOrObject): KtClassOrObjectSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirClass, KtClassOrObjectSymbol>(resolveState) {
firSymbolBuilder.classifierBuilder.buildClassOrObjectSymbol(it)
}
}
override fun getNamedClassOrObjectSymbol(psi: KtClassOrObject): KtNamedClassOrObjectSymbol = withValidityAssertion {
require(psi !is KtObjectDeclaration || psi.parent !is KtObjectLiteralExpression)
psi.withFirDeclarationOfType<FirRegularClass, KtNamedClassOrObjectSymbol>(resolveState) {
firSymbolBuilder.classifierBuilder.buildNamedClassOrObjectSymbol(it)
}
}
override fun getPropertyAccessorSymbol(psi: KtPropertyAccessor): KtPropertyAccessorSymbol = withValidityAssertion {
psi.withFirDeclarationOfType<FirPropertyAccessor, KtPropertyAccessorSymbol>(resolveState) {
firSymbolBuilder.callableBuilder.buildPropertyAccessorSymbol(it)
}
}
override fun getClassOrObjectSymbolByClassId(classId: ClassId): KtClassOrObjectSymbol? = withValidityAssertion {
val symbol = firSymbolProvider.getClassLikeSymbolByFqName(classId) as? FirRegularClassSymbol ?: return null
firSymbolBuilder.classifierBuilder.buildNamedClassOrObjectSymbol(symbol.fir)
}
override fun getTopLevelCallableSymbols(packageFqName: FqName, name: Name): Sequence<KtSymbol> {
val firs = firSymbolProvider.getTopLevelCallableSymbols(packageFqName, name)
return firs.asSequence().map { firSymbol -> firSymbolBuilder.buildSymbol(firSymbol.fir) }
}
override val ROOT_PACKAGE_SYMBOL: KtPackageSymbol = KtFirPackageSymbol(FqName.ROOT, resolveState.project, token)
}
| 34 | null | 4903 | 39,894 | 0ad440f112f353cd2c72aa0a0619f3db2e50a483 | 7,208 | kotlin | Apache License 2.0 |
base-android/src/main/java/com/sfaxdroid/base/SharedPrefsUtils.kt | yassinBaccour | 106,160,036 | false | {"Kotlin": 348508, "Java": 3869} | package com.sfaxdroid.base
import android.content.Context
import android.content.SharedPreferences
// TODO Inject
class SharedPrefsUtils(context: Context) {
private val sharedPreferences: SharedPreferences = context.getSharedPreferences(
Constants.PREFERENCES_NAME,
Context.MODE_PRIVATE
)
private val prefsEditor: SharedPreferences.Editor = sharedPreferences.edit()
fun setSetting(key: String?, value: Int) {
prefsEditor.putInt(key, value)
prefsEditor.commit()
}
fun getSetting(key: String?, value: Int): Int {
return sharedPreferences.getInt(key, value)
}
}
| 0 | Kotlin | 0 | 2 | 136ac811fb1495a8ea2800480954121bf092742b | 633 | SfaxDroid_Wallpaper_App | Apache License 2.0 |
src/main/kotlin/org/crystal/intellij/lang/ast/nodes/CstCast.kt | asedunov | 353,165,557 | false | {"Kotlin": 1661507, "Java": 554445, "Crystal": 245131, "Lex": 192822, "HTML": 445} | package org.crystal.intellij.lang.ast.nodes
import org.crystal.intellij.lang.ast.location.CstLocation
import org.crystal.intellij.lang.ast.CstTransformer
import org.crystal.intellij.lang.ast.CstVisitor
class CstCast(
obj: CstNode<*>,
type: CstNode<*>,
location: CstLocation? = null
) : CstCastBase<CstCast>(obj, type, location) {
override fun copy(
obj: CstNode<*>,
type: CstNode<*>,
location: CstLocation?
) = CstCast(obj, type, location)
override fun acceptSelf(visitor: CstVisitor) = visitor.visitCast(this)
override fun acceptChildren(visitor: CstVisitor) {
obj.accept(visitor)
type.accept(visitor)
}
override fun acceptTransformer(transformer: CstTransformer) = transformer.transformCast(this)
} | 11 | Kotlin | 4 | 33 | 2e255da6c56a33109b8c58a0aa1a692abf977da2 | 781 | intellij-crystal-lang | Apache License 2.0 |
app/src/main/kotlin/com/ohyooo/demo/ui/splash/SplashActivity.kt | ohyooo | 164,578,051 | false | null | package com.ohyooo.demo.ui.splash
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.ohyooo.demo.ui.main.MainActivity
class SplashActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
| 0 | Kotlin | 2 | 34 | 5b0a57429fe31479df80fdb3d567ae0c4795992c | 386 | MVVMBaseProject | Do What The F*ck You Want To Public License |
src/main/kotlin/com/ltpquang/xray/models/TestRun.kt | ltpquang | 282,400,730 | false | null | package com.ltpquang.xray.models
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME> (quangltp) on 7/25/20
*
*/
data class TestRun(
@SerializedName("id") val id : Int = 0,
@SerializedName("status") val status : String = "",
@SerializedName("color") val color : String = "",
@SerializedName("testKey") val testKey : String = "",
@SerializedName("testExecKey") val testExecKey : String = "",
@SerializedName("executedBy") val executedBy : String = "",
@SerializedName("startedOn") val startedOn : String = "",
@SerializedName("finishedOn") val finishedOn : String = "",
@SerializedName("startedOnIso") val startedOnIso : String = "",
@SerializedName("finishedOnIso") val finishedOnIso : String = "",
@SerializedName("duration") val duration : Int = 0,
// @SerializedName("defects") val defects : List<String> = emptyList(),
// @SerializedName("evidences") val evidences : List<String> = emptyList(),
@SerializedName("scenarioOutline") val scenarioOutline : String = ""
// @SerializedName("examples") val examples : List<Example> = emptyList(),
// @SerializedName("testEnvironments") val testEnvironments : List<String> = emptyList(),
// @SerializedName("fixVersions") val fixVersions : List<FixVersion> = emptyList()
)
| 0 | Kotlin | 0 | 1 | b1c3d73be82bf1a6f5a0a096ba993ae94414516d | 1,308 | xray-status-updater | MIT License |
drivers/native-driver/src/nativeTest/kotlin/com/squareup/sqldelight/drivers/native/NativeQueryTest.kt | cashapp | 44,677,680 | false | null | package com.squareup.sqldelight.drivers.native
import co.touchlab.sqliter.DatabaseFileContext
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.driver.test.QueryTest
class NativeQueryTest: QueryTest() {
override fun setupDatabase(schema: SqlDriver.Schema): SqlDriver {
val name = "testdb"
DatabaseFileContext.deleteDatabase(name)
return NativeSqliteDriver(schema, name)
}
} | 184 | null | 357 | 4,281 | f73e0917be5e058d0d988769a239b6923e8f61c1 | 416 | sqldelight | Apache License 2.0 |
library/src/commonMain/kotlin/dev/bluefalcon/Log.kt | icerockdev | 218,058,284 | true | {"Kotlin": 37877, "Ruby": 1687} | package dev.bluefalcon
import kotlin.native.concurrent.ThreadLocal
@ThreadLocal
object Log {
var logger: Logger = DefaultConsoleLogger()
var level: Level = Level.NONE
private fun log(level: Level = Level.VERBOSE, message: () -> String) {
if (this.level.ordinal < level.ordinal) return
logger.log(level, message())
}
fun d(message: () -> String) = log(Level.DEBUG, message)
fun e(message: () -> String) = log(Level.ERROR, message)
fun v(message: () -> String) = log(Level.VERBOSE, message)
enum class Level {
NONE,
ERROR,
DEBUG,
VERBOSE
}
interface Logger {
fun log(level: Level, message: String)
}
}
| 0 | Kotlin | 1 | 0 | 2c823dcf8880d98e710210ab5ebfea20706d24ac | 707 | blue-falcon | MIT License |
src/main/kotlin/ru/nsu/lupa/out/Html.kt | lilvadim | 576,661,907 | false | {"Kotlin": 22514, "Java": 836} | package ru.nsu.lupa.out
import kotlinx.html.*
import kotlinx.html.stream.createHTML
import ru.nsu.lupa.ChainNode
import ru.nsu.lupa.MatchCriteria
import ru.nsu.lupa.Profile
fun convertToHtml(chains: List<ChainNode<Set<MatchCriteria>, Profile>>): String = createHTML().html {
body {
h1 { +"Found Profiles" }
for ((idx, chain) in chains.withIndex()) {
h2 { +"Match Chain #${idx + 1}" }
table {
style {
unsafe {
raw(
"table, th, td {" +
"border:1px solid DarkGray;" +
"width: 100%;" +
"table-layout: fixed;" +
"}"
)
}
}
tr {
th { +"Name" }
th { +"Surname" }
th { +"Username" }
th { +"Email" }
th { +"Phone" }
th { +"Links" }
}
var node: ChainNode<Set<MatchCriteria>, Profile>? = chain
while (node != null) {
val profile = node.value!!
tr {
td { +profile.name?.value.toString() }
td { +profile.surname?.value.toString() }
td { +profile.username?.value.toString() }
td { +profile.email?.value.toString() }
td { +profile.phone?.value.toString() }
td { profile.relatedLinks.forEach { a(href = it) { +it } } }
}
if (node.next != null) {
tr {
td {
+"↓ Matches by ${
node!!.label?.joinToString(separator = ", ") {
it.toString().lowercase()
}
} with profile below"
}
}
}
node = node.next
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 9388aa69457bc625317a3732f2afcd52e02ef1a1 | 2,295 | lupa | Apache License 2.0 |
src/main/kotlin/de/gmuth/ipp/client/IppPrinter.kt | gmuth | 247,626,449 | false | null | package de.gmuth.ipp.client
/**
* Copyright (c) 2020-2022 <NAME>
*/
import de.gmuth.http.Http
import de.gmuth.ipp.client.IppPrinterState.*
import de.gmuth.ipp.core.*
import de.gmuth.ipp.core.IppOperation.*
import de.gmuth.ipp.core.IppStatus.ClientErrorNotFound
import de.gmuth.ipp.core.IppTag.*
import de.gmuth.ipp.iana.IppRegistrationsSection2
import de.gmuth.log.Logging
import java.io.*
import java.net.URI
import java.time.Duration
@SuppressWarnings("kotlin:S1192")
open class IppPrinter(
val printerUri: URI,
var attributes: IppAttributesGroup = IppAttributesGroup(Printer),
httpConfig: Http.Config = Http.Config(),
ippConfig: IppConfig = IppConfig(),
val ippClient: IppClient = IppClient(ippConfig, Http.defaultImplementation.createClient(httpConfig)),
getPrinterAttributesOnInit: Boolean = true,
requestedAttributesOnInit: List<String>? = null
) {
init {
log.debug { "create IppPrinter for $printerUri" }
if (!getPrinterAttributesOnInit) {
log.info { "getPrinterAttributesOnInit disabled => no printer attributes available" }
} else if (attributes.size == 0) {
try {
updateAttributes(requestedAttributesOnInit)
if (isStopped()) {
log.info { toString() }
stateMessage?.let { log.info { it } }
alert?.let { log.info { it } }
alertDescription?.let { log.info { it } }
}
} catch (ippExchangeException: IppExchangeException) {
if (ippExchangeException.statusIs(ClientErrorNotFound))
log.error { ippExchangeException.message }
else {
log.logWithCauseMessages(ippExchangeException)
log.error { "failed to get printer attributes on init" }
ippExchangeException.response?.let {
if (it.containsGroup(Printer)) log.info { "${it.printerGroup.size} attributes parsed" }
else log.warn { it }
}
try {
fetchRawPrinterAttributes("getPrinterAttributesFailed.bin")
} catch (exception: Exception) {
log.error(exception) { "failed to fetch raw printer attributes" }
}
}
throw ippExchangeException
}
}
}
constructor(printerAttributes: IppAttributesGroup, ippClient: IppClient) : this(
printerAttributes.getValues<List<URI>>("printer-uri-supported").first(),
printerAttributes,
ippClient = ippClient
)
// constructors for java usage
constructor(printerUri: String) : this(URI.create(printerUri))
constructor(printerUri: String, ippConfig: IppConfig) : this(URI.create(printerUri), ippConfig = ippConfig)
companion object {
val log = Logging.getLogger {}
val printerStateAttributes = listOf(
"printer-is-accepting-jobs", "printer-state", "printer-state-reasons"
)
val printerClassAttributes = listOf(
"printer-name",
"printer-make-and-model",
"printer-is-accepting-jobs",
"printer-state",
"printer-state-reasons",
"document-format-supported",
"operations-supported",
"color-supported",
"sides-supported",
"media-supported",
"media-ready",
"media-default",
"ipp-versions-supported"
)
}
val ippConfig: IppConfig
get() = ippClient.config
var getJobsRequestedAttributes = listOf(
"job-id", "job-uri", "job-printer-uri", "job-state", "job-name",
"job-state-reasons", "job-originating-user-name"
)
//---------------
// ipp attributes
//---------------
val name: IppString
get() = attributes.getValue("printer-name")
val makeAndModel: IppString
get() = attributes.getValue("printer-make-and-model")
val info: IppString
get() = attributes.getValue("printer-info")
val location: IppString
get() = attributes.getValue("printer-location")
val isAcceptingJobs: Boolean
get() = attributes.getValue("printer-is-accepting-jobs")
val state: IppPrinterState
get() = IppPrinterState.fromInt(attributes.getValue("printer-state"))
val stateReasons: List<String>
get() = attributes.getValues("printer-state-reasons")
val stateMessage: IppString?
get() = attributes.getValueOrNull("printer-state-message")
val documentFormatSupported: List<String>
get() = attributes.getValues("document-format-supported")
val operationsSupported: List<IppOperation>
get() = attributes.getValues<List<Int>>("operations-supported").map {
IppOperation.fromShort(it.toShort())
}
val colorSupported: Boolean
get() = attributes.getValue("color-supported")
val sidesSupported: List<String>
get() = attributes.getValues("sides-supported")
val mediaSupported: List<String>
get() = attributes.getValues("media-supported")
val mediaReady: List<String>
get() = attributes.getValues("media-ready")
val mediaDefault: String
get() = attributes.getValue("media-default")
val versionsSupported: List<String>
get() = attributes.getValues("ipp-versions-supported")
val communicationChannelsSupported: List<IppCommunicationChannel>
get() = mutableListOf<IppCommunicationChannel>().apply {
with(attributes) {
val printerUriSupportedList = getValues<List<URI>>("printer-uri-supported")
val uriSecuritySupportedList = getValues<List<String>>("uri-security-supported")
val uriAuthenticationSupportedList = getValues<List<String>>("uri-authentication-supported")
for ((index, printerUriSupported) in printerUriSupportedList.withIndex())
add(
IppCommunicationChannel(
printerUriSupported,
uriSecuritySupportedList[index],
uriAuthenticationSupportedList[index]
)
)
}
}
val alert: List<String>? // PWG 5100.9
get() = attributes.getValuesOrNull("printer-alert")
val alertDescription: List<IppString>? // PWG 5100.9
get() = attributes.getValuesOrNull("printer-alert-description")
// ----------------------------------------------
// extensions supported by cups and some printers
// https://www.cups.org/doc/spec-ipp.html
// ----------------------------------------------
val deviceUri: URI
get() = attributes.getValue("device-uri")
val printerType: CupsPrinterType
get() = CupsPrinterType(attributes.getValue("printer-type"))
fun hasCapability(capability: CupsPrinterType.Capability) =
printerType.contains(capability)
val markers: List<CupsMarker>
get() = mutableListOf<CupsMarker>().apply {
with(attributes) {
val levels = getValues<List<Int>>("marker-levels")
val lowLevels = getValues<List<Int>>("marker-low-levels")
val highLevels = getValues<List<Int>>("marker-high-levels")
val types = getValues<List<String>>("marker-types")
val names = getValues<List<IppString>>("marker-names")
val colors = getValues<List<IppString>>("marker-colors")
for ((index, type) in types.withIndex())
add(
CupsMarker(
type,
names[index].text,
levels[index],
lowLevels[index],
highLevels[index],
colors[index].text
)
)
}
}
fun marker(color: CupsMarker.Color) = markers.single { it.color == color }
//-----------------
fun isIdle() = state == Idle
fun isStopped() = state == Stopped
fun isProcessing() = state == Processing
fun isMediaEmpty() = stateReasons.contains("media-empty")
fun isMediaNeeded() = stateReasons.contains("media-needed")
fun isDuplexSupported() = sidesSupported.any { it.startsWith("two-sided") }
fun supportsOperations(vararg operations: IppOperation) = operationsSupported.containsAll(operations.toList())
fun supportsVersion(version: String) = versionsSupported.contains(version)
fun isCups() = attributes.contains("cups-version")
//-----------------
// Identify-Printer
//-----------------
fun identify(vararg actions: String) = identify(actions.toList())
fun identify(actions: List<String>): IppResponse {
checkIfValueIsSupported("identify-actions-supported", actions)
val request = ippRequest(IdentifyPrinter).apply {
operationGroup.attribute("identify-actions", Keyword, actions)
}
return exchange(request)
}
fun flash() = identify("flash")
fun sound() = identify("sound")
//-----------------------
// Printer administration
//-----------------------
fun pause() = exchange(ippRequest(PausePrinter))
fun resume() = exchange(ippRequest(ResumePrinter))
fun purgeJobs() = exchange(ippRequest(PurgeJobs))
fun enable() = exchange(ippRequest(EnablePrinter))
fun disable() = exchange(ippRequest(DisablePrinter))
fun holdNewJobs() = exchange(ippRequest(HoldNewJobs))
fun releaseHeldNewJobs() = exchange(ippRequest(ReleaseHeldNewJobs))
fun cancelJobs() = exchange(ippRequest(CancelJobs))
fun cancelMyJobs() = exchange(ippRequest(CancelMyJobs))
//------------------------------------------
// Get-Printer-Attributes
// names of attribute groups: RFC 8011 4.2.5
//------------------------------------------
fun getPrinterAttributes(requestedAttributes: List<String>? = null) =
exchange(ippRequest(GetPrinterAttributes, requestedAttributes = requestedAttributes))
fun getPrinterAttributes(vararg requestedAttributes: String) =
getPrinterAttributes(requestedAttributes.toList())
fun updateAttributes(requestedAttributes: List<String>? = null) {
log.debug { "update attributes: $requestedAttributes" }
getPrinterAttributes(requestedAttributes).run {
if (containsGroup(Printer)) attributes.put(printerGroup)
else log.warn { "no printerGroup in response for requested attributes: $requestedAttributes" }
}
}
fun updateAttributes(vararg requestedAttributes: String) =
updateAttributes(requestedAttributes.toList())
fun updatePrinterStateAttributes() =
updateAttributes(printerStateAttributes)
//-------------
// Validate-Job
//-------------
@Throws(IppExchangeException::class)
fun validateJob(vararg attributeBuilders: IppAttributeBuilder): IppResponse {
val request = attributeBuildersRequest(ValidateJob, attributeBuilders.toList())
return exchange(request)
}
//--------------------------------------
// Print-Job (with subscription support)
//--------------------------------------
@JvmOverloads
fun printJob(
inputStream: InputStream,
attributeBuilders: Collection<IppAttributeBuilder>,
notifyEvents: List<String>? = null
): IppJob {
val request = attributeBuildersRequest(PrintJob, attributeBuilders).apply {
notifyEvents?.let {
checkNotifyEvents(notifyEvents)
createSubscriptionAttributesGroup(notifyEvents)
}
documentInputStream = inputStream
}
return exchangeForIppJob(request)
}
// vararg signatures for convenience
@JvmOverloads
fun printJob(
inputStream: InputStream,
vararg attributeBuilders: IppAttributeBuilder,
notifyEvents: List<String>? = null
) =
printJob(inputStream, attributeBuilders.toList(), notifyEvents)
@JvmOverloads
fun printJob(
byteArray: ByteArray,
vararg attributeBuilders: IppAttributeBuilder,
notifyEvents: List<String>? = null
) =
printJob(ByteArrayInputStream(byteArray), attributeBuilders.toList(), notifyEvents)
@JvmOverloads
fun printJob(file: File, vararg attributeBuilders: IppAttributeBuilder, notifyEvents: List<String>? = null) =
printJob(FileInputStream(file), attributeBuilders.toList(), notifyEvents)
//----------
// Print-URI
//----------
fun printUri(documentUri: URI, vararg attributeBuilders: IppAttributeBuilder): IppJob {
val request = attributeBuildersRequest(PrintURI, attributeBuilders.toList()).apply {
operationGroup.attribute("document-uri", Uri, documentUri)
}
return exchangeForIppJob(request)
}
//-----------
// Create-Job
//-----------
fun createJob(vararg attributeBuilders: IppAttributeBuilder): IppJob {
val request = attributeBuildersRequest(CreateJob, attributeBuilders.toList())
return exchangeForIppJob(request)
}
// ---- factory method for operations Validate-Job, Print-Job, Print-Uri, Create-Job
protected fun attributeBuildersRequest(
operation: IppOperation,
attributeBuilders: Collection<IppAttributeBuilder>
) = ippRequest(operation).apply {
for (attributeBuilder in attributeBuilders) {
val attribute = attributeBuilder.buildIppAttribute(attributes)
checkIfValueIsSupported("${attribute.name}-supported", attribute.values)
// put attribute in operation or job group?
val groupTag = IppRegistrationsSection2.selectGroupForAttribute(attribute.name) ?: Job
if (!containsGroup(groupTag)) createAttributesGroup(groupTag)
log.trace { "$groupTag put $attribute" }
getSingleAttributesGroup(groupTag).put(attribute)
}
}
//-------------------------------
// Get-Job-Attributes (as IppJob)
//-------------------------------
fun getJob(jobId: Int): IppJob {
val request = ippRequest(GetJobAttributes, jobId)
return exchangeForIppJob(request)
}
//---------------------------
// Get-Jobs (as List<IppJob>)
//---------------------------
@JvmOverloads
fun getJobs(
whichJobs: IppWhichJobs? = null,
myJobs: Boolean? = null,
limit: Int? = null,
requestedAttributes: List<String>? = getJobsRequestedAttributes
): Collection<IppJob> {
val request = ippRequest(GetJobs, requestedAttributes = requestedAttributes).apply {
operationGroup.run {
whichJobs?.keyword?.let {
checkIfValueIsSupported("which-jobs-supported", it)
attribute("which-jobs", Keyword, it)
}
myJobs?.let { attribute("my-jobs", IppTag.Boolean, it) }
limit?.let { attribute("limit", Integer, it) }
}
}
return exchange(request)
.getAttributesGroups(Job)
.map { IppJob(this, it) }
}
fun getJobs(whichJobs: IppWhichJobs? = null, vararg requestedAttributes: String) =
getJobs(whichJobs, requestedAttributes = requestedAttributes.toList())
//----------------------------
// Create-Printer-Subscription
//----------------------------
fun createPrinterSubscription(
notifyEvents: List<String>? = listOf("all"), // https://datatracker.ietf.org/doc/html/rfc3995#section-5.3.3.4.2
notifyLeaseDuration: Duration? = null
): IppSubscription {
val request = ippRequest(CreatePrinterSubscriptions).apply {
checkNotifyEvents(notifyEvents)
createSubscriptionAttributesGroup(notifyEvents, notifyLeaseDuration)
}
val subscriptionAttributes = exchange(request).getSingleAttributesGroup(Subscription)
return IppSubscription(this, subscriptionAttributes)
}
fun checkNotifyEvents(notifyEvents: List<String>?) = notifyEvents?.let {
if (it.isNotEmpty() && it.first() != "all")
checkIfValueIsSupported("notify-events-supported", it)
}
//-------------------------------------------------
// Get-Subscription-Attributes (as IppSubscription)
//-------------------------------------------------
fun getSubscription(id: Int) = IppSubscription(
this,
exchange(ippRequest(GetSubscriptionAttributes).apply {
operationGroup.attribute("notify-subscription-id", Integer, id)
}).getSingleAttributesGroup(Subscription)
)
//---------------------------------------------
// Get-Subscriptions (as List<IppSubscription>)
//---------------------------------------------
fun getSubscriptions(
notifyJobId: Int? = null,
mySubscriptions: Boolean? = null,
limit: Int? = null,
requestedAttributes: List<String>? = null
): List<IppSubscription> {
val request = ippRequest(GetSubscriptions, requestedAttributes = requestedAttributes).apply {
operationGroup.run {
notifyJobId?.let { attribute("notify-job-id", Integer, it) }
mySubscriptions?.let { attribute("my-subscriptions", IppTag.Boolean, it) }
limit?.let { attribute("limit", Integer, it) }
}
}
return exchange(request)
.getAttributesGroups(Subscription)
.map { IppSubscription(this, it) }
}
//----------------------
// delegate to IppClient
//----------------------
fun ippRequest(operation: IppOperation, jobId: Int? = null, requestedAttributes: List<String>? = null) =
ippClient.ippRequest(operation, printerUri, jobId, requestedAttributes)
fun exchange(request: IppRequest): IppResponse {
return ippClient.exchange(request.apply {
checkIfValueIsSupported("ipp-versions-supported", version!!)
checkIfValueIsSupported("operations-supported", code!!.toInt())
checkIfValueIsSupported("charset-supported", attributesCharset)
})
}
fun exchangeForIppJob(request: IppRequest): IppJob {
val response = exchange(request)
if (request.containsGroup(Subscription) && !response.containsGroup(Subscription)) {
request.logDetails("REQUEST: ")
val events: List<String> = request.getSingleAttributesGroup(Subscription).getValues("notify-events")
throw IppException("printer/server did not create subscription for events: ${events.joinToString(",")}")
}
val subscriptionsAttributes = response.run {
if (containsGroup(Subscription)) getSingleAttributesGroup(Subscription) else null
}
return IppJob(this, response.jobGroup, subscriptionsAttributes)
}
// -------
// Logging
// -------
override fun toString() = StringBuilder("IppPrinter:").run {
if (attributes.contains("printer-name")) append(" name=$name")
append(", makeAndModel=$makeAndModel")
append(", state=$state, stateReasons=$stateReasons")
if (attributes.contains("printer-is-accepting-jobs")) append(", isAcceptingJobs=$isAcceptingJobs")
toString()
}
fun logDetails() =
attributes.logDetails(title = "PRINTER-$name ($makeAndModel), $state $stateReasons")
// ------------------------------------------------------
// attribute value checking based on printer capabilities
// ------------------------------------------------------
fun checkIfValueIsSupported(supportedAttributeName: String, value: Any) {
if (attributes.size == 0) return
if (!supportedAttributeName.endsWith("-supported"))
throw IppException("attribute name not ending with '-supported'")
if (value is Collection<*>) { // instead of providing another signature just check collections iteratively
for (collectionValue in value) {
checkIfValueIsSupported(supportedAttributeName, collectionValue!!)
}
} else {
isAttributeValueSupported(supportedAttributeName, value)
}
}
fun isAttributeValueSupported(supportedAttributeName: String, value: Any): Boolean? {
val supportedAttribute = attributes[supportedAttributeName] ?: return null
val attributeValueIsSupported = when (supportedAttribute.tag) {
IppTag.Boolean -> { // e.g. 'page-ranges-supported'
supportedAttribute.value as Boolean
}
IppTag.Enum, Charset, NaturalLanguage, MimeMediaType, Keyword, Resolution -> when (supportedAttributeName) {
"media-col-supported" -> with(value as IppCollection) {
members.filter { !supportedAttribute.values.contains(it.name) }
.forEach { log.warn { "member unsupported: $it" } }
// all member names must be supported
supportedAttribute.values.containsAll(members.map { it.name })
}
else -> supportedAttribute.values.contains(value)
}
Integer -> {
if (supportedAttribute.is1setOf()) supportedAttribute.values.contains(value)
else value is Int && value <= supportedAttribute.value as Int // e.g. 'job-priority-supported'
}
RangeOfInteger -> {
value is Int && value in supportedAttribute.value as IntRange
}
else -> null
}
when (attributeValueIsSupported) {
null -> log.warn { "unable to check if value '$value' is supported by $supportedAttribute" }
true -> log.debug { "$supportedAttributeName: $value" }
false -> {
log.warn { "according to printer attributes value '${supportedAttribute.enumNameOrValue(value)}' is not supported." }
log.warn { "$supportedAttribute" }
}
}
return attributeValueIsSupported
}
// -----------------------
// Save printer attributes
// -----------------------
fun savePrinterAttributes(directory: String = ".") {
val printerModel: String = makeAndModel.text.replace("\\s+".toRegex(), "_")
getPrinterAttributes().run {
saveRawBytes(File(directory, "$printerModel.bin"))
printerGroup.saveText(File(directory, "$printerModel.txt"))
}
}
fun fetchRawPrinterAttributes(filename: String = "printer-attributes.bin") {
ippClient.run {
val httpResponse = httpPostRequest(toHttpUri(printerUri), ippRequest(GetPrinterAttributes))
log.info { "http status: ${httpResponse.status}, content-type: ${httpResponse.contentType}" }
File(filename).apply {
httpResponse.contentStream!!.copyTo(outputStream())
log.info { "saved ${length()} bytes: $path" }
}
}
}
var workDirectory: File = File("work")
fun printerDirectory(printerName: String = name.text.replace("\\s+".toRegex(), "_")) =
File(workDirectory, printerName).apply {
if (!mkdirs() && !isDirectory) throw IppException("failed to create printer directory: $path")
}
} | 2 | null | 9 | 54 | 13b133f775f6784e9bb509a86a35f5ce147da86f | 23,592 | ipp-client-kotlin | MIT License |
api/src/test/kotlin/org/jetbrains/kotlinx/dl/api/core/layer/UpSampling1DTest.kt | JetBrains | 249,948,572 | false | null | /*
* Copyright 2021 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.kotlinx.dl.api.core.layer
import org.jetbrains.kotlinx.dl.api.core.layer.reshaping.UpSampling1D
import org.jetbrains.kotlinx.dl.api.core.shape.shape
import org.jetbrains.kotlinx.dl.api.core.shape.toLongArray
import org.junit.jupiter.api.Test
internal class UpSampling1DTest : LayerTest() {
private val input = arrayOf(
arrayOf(
floatArrayOf(0.0f, 1.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(4.0f, 5.0f)
)
)
private val inputShape = input.shape.toLongArray()
@Test
fun default() {
val layer = UpSampling1D()
val expected = arrayOf(
arrayOf(
floatArrayOf(0.0f, 1.0f),
floatArrayOf(0.0f, 1.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(4.0f, 5.0f),
floatArrayOf(4.0f, 5.0f)
)
)
assertLayerOutputIsCorrect(layer, input, expected)
val expectedShape = longArrayOf(inputShape[0], inputShape[1] * 2, inputShape[2])
assertLayerComputedOutputShape(layer, inputShape, expectedShape)
}
@Test
fun testWithNonDefaultUpSamplingSize() {
val layer = UpSampling1D(size = 3)
val expected = arrayOf(
arrayOf(
floatArrayOf(0.0f, 1.0f),
floatArrayOf(0.0f, 1.0f),
floatArrayOf(0.0f, 1.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(2.0f, 3.0f),
floatArrayOf(4.0f, 5.0f),
floatArrayOf(4.0f, 5.0f),
floatArrayOf(4.0f, 5.0f)
)
)
assertLayerOutputIsCorrect(layer, input, expected)
val expectedShape = longArrayOf(inputShape[0], inputShape[1] * 3, inputShape[2])
assertLayerComputedOutputShape(layer, inputShape, expectedShape)
}
}
| 81 | null | 79 | 806 | efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19 | 2,171 | KotlinDL | Apache License 2.0 |
app/src/main/java/com/example/android/lifecycles/step4/BoundLocationManager.kt | tonyo1433 | 131,302,851 | false | null | /*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.lifecycles.step4
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.util.Log
object BoundLocationManager {
fun bindLocationListenerIn(lifecycleOwner: LifecycleOwner,
listener: LocationListener, context: Context) {
BoundLocationListener(lifecycleOwner, listener, context)
}
internal class BoundLocationListener(lifecycleOwner: LifecycleOwner,
private val mListener: LocationListener, private val mContext: Context)//TODO: Add lifecycle observer
: LifecycleObserver {
private var mLocationManager: LocationManager? = null
//TODO: Call this on resume
fun addLocationListener() {
// Note: Use the Fused Location Provider from Google Play Services instead.
// https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
mLocationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
mLocationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, mListener)
Log.d("BoundLocationMgr", "Listener added")
// Force an update with the last location, if available.
val lastLocation = mLocationManager!!.getLastKnownLocation(
LocationManager.GPS_PROVIDER)
if (lastLocation != null) {
mListener.onLocationChanged(lastLocation)
}
}
//TODO: Call this on pause
fun removeLocationListener() {
if (mLocationManager == null) {
return
}
mLocationManager!!.removeUpdates(mListener)
mLocationManager = null
Log.d("BoundLocationMgr", "Listener removed")
}
}
}
| 0 | Kotlin | 0 | 0 | b61bda118b15a5abfe5858bf5664d35c9c5da1ce | 2,660 | lifecycles | Apache License 2.0 |
ambassador-model/src/main/kotlin/com/roche/ambassador/model/score/quality/checks/ContributionGuide.kt | filipowm | 409,076,487 | false | null | package com.roche.ambassador.model.score.quality.checks
import com.roche.ambassador.model.Explanation
import com.roche.ambassador.model.feature.ContributingGuideFeature
import com.roche.ambassador.model.feature.Features
import java.util.*
internal object ContributionGuide : StringLengthCheck() {
private const val MIN_LENGTH = 300
override fun name(): String = Check.CONTRIBUTION_GUIDE
override fun minLength(): Int = MIN_LENGTH
override fun readStringLength(features: Features): Optional<Int> = features.findValue(ContributingGuideFeature::class)
.map { it.contentLength }
.map { it!!.toInt() }
override fun buildExplanation(featureValue: Int, score: Double, builder: Explanation.Builder) {
builder
.description("Contribution Guide")
.addDetails("$score for contribution guide with $featureValue chars length.")
}
} | 22 | Kotlin | 0 | 9 | 11e72d45f1b91e724073b230577033d0115b1a24 | 895 | the-ambassador | Apache License 2.0 |
library/src/test/java/com/minibugdev/drawablebadge/DrawableBadgeBuilderTest.kt | minibugdev | 106,788,532 | false | null | package com.minibugdev.drawablebadge
import android.content.Context
import android.graphics.Bitmap
import android.view.Gravity
import androidx.core.content.ContextCompat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@RunWith(RobolectricTestRunner::class)
class DrawableBadgeBuilderTest {
private lateinit var drawableBuilder: DrawableBadge.Builder
private lateinit var context: Context
@Before
fun setup() {
context = RuntimeEnvironment.application
drawableBuilder = DrawableBadge.Builder(context)
}
@Test
fun testNotPassBitmapOrDrawableShouldThrowIllegalArgumentException() {
assertFailsWith<IllegalArgumentException> {
drawableBuilder.build()
}
}
@Test
fun testConfigOnlyBitmapShouldUsingDefaultConfig() {
val actual = drawableBuilder
.bitmap(Bitmap.createBitmap(128, 128, Bitmap.Config.ALPHA_8))
.build()
val resources = context.resources
val expectedBadgeSize = resources.getDimensionPixelOffset(R.dimen.default_badge_size)
val expectedBorderSize = resources.getDimensionPixelOffset(R.dimen.default_badge_border_size)
val expectedBadgeColor = ContextCompat.getColor(context, R.color.default_badge_color)
val expectedBorderColor = ContextCompat.getColor(context, R.color.default_badge_border_color)
val expectedTextColor = ContextCompat.getColor(context, R.color.default_badge_text_color)
assertEquals(expectedBadgeSize.toFloat(), actual.badgeSize)
assertEquals(expectedBorderSize.toFloat(), actual.badgeBorderSize)
assertEquals(expectedBadgeColor, actual.badgeColor)
assertEquals(expectedBorderColor, actual.badgeBorderColor)
assertEquals(expectedTextColor, actual.textColor)
assertEquals(0f, actual.badgeMargin)
assertEquals(Gravity.TOP or Gravity.END, actual.badgeGravity)
assertEquals(true, actual.isShowBorder)
assertEquals(99, actual.maximumCounter)
}
@Test
fun testCustomConfigShouldUsingCustomConfig() {
val actual = drawableBuilder
.bitmap(Bitmap.createBitmap(128, 128, Bitmap.Config.ALPHA_8))
.badgeSize(10f)
.badgeBorderSize(20f)
.badgeMargin(30f)
.badgeColor(android.R.color.holo_red_dark)
.badgeBorderColor(android.R.color.holo_red_light)
.textColor(android.R.color.black)
.badgeGravity(Gravity.CENTER_VERTICAL or Gravity.END)
.showBorder(false)
.maximumCounter(50)
.showCounter(false)
.build()
val expectedBadgeColor = ContextCompat.getColor(context, android.R.color.holo_red_dark)
val expectedBorderColor = ContextCompat.getColor(context, android.R.color.holo_red_light)
val expectedTextColor = ContextCompat.getColor(context, android.R.color.black)
assertEquals(10f, actual.badgeSize)
assertEquals(20f, actual.badgeBorderSize)
assertEquals(30f, actual.badgeMargin)
assertEquals(expectedBadgeColor, actual.badgeColor)
assertEquals(expectedBorderColor, actual.badgeBorderColor)
assertEquals(expectedTextColor, actual.textColor)
assertEquals(Gravity.CENTER_VERTICAL or Gravity.END, actual.badgeGravity)
assertEquals(false, actual.isShowBorder)
assertEquals(50, actual.maximumCounter)
assertEquals(false, actual.isShowCounter)
}
} | 0 | null | 31 | 134 | fc5879769ec5b2ca7a2b1820b9a903039639009c | 3,269 | DrawableBadge | MIT License |
app/src/main/kotlin/tachiload/tachiyomi/source/model/SManga.kt | drosoCode | 327,565,860 | false | null | package tachiload.tachiyomi.source.model
import tachiload.tachiyomi.source.model.MangaInfo
import java.io.Serializable
interface SManga : Serializable {
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var initialized: Boolean
fun copyFrom(other: SManga) {
if (other.author != null) {
author = other.author
}
if (other.artist != null) {
artist = other.artist
}
if (other.description != null) {
description = other.description
}
if (other.genre != null) {
genre = other.genre
}
if (other.thumbnail_url != null) {
thumbnail_url = other.thumbnail_url
}
status = other.status
if (!initialized) {
initialized = other.initialized
}
}
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
fun create(): SManga {
return SMangaImpl()
}
}
}
fun SManga.toMangaInfo(): MangaInfo {
return MangaInfo(
key = this.url,
title = this.title,
artist = this.artist ?: "",
author = this.author ?: "",
description = this.description ?: "",
genres = this.genre?.split(", ") ?: emptyList(),
status = this.status,
cover = this.thumbnail_url ?: ""
)
}
fun MangaInfo.toSManga(): SManga {
val mangaInfo = this
return SManga.create().apply {
url = mangaInfo.key
title = mangaInfo.title
artist = mangaInfo.artist
author = mangaInfo.author
description = mangaInfo.description
genre = mangaInfo.genres.joinToString(", ")
status = mangaInfo.status
thumbnail_url = mangaInfo.cover
}
}
| 92 | Kotlin | 7 | 9 | 9b60bd12f784cb1f78f2300ae36aca767c4456d8 | 1,976 | tachiyomi | MIT License |
calf-file-picker/src/androidMain/kotlin/com/mohamedrejeb/calf/picker/FilePickerLauncher.android.kt | MohamedRejeb | 674,932,206 | false | null | package com.mohamedrejeb.calf.picker
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import com.mohamedrejeb.calf.io.KmpFile
import java.io.File
@Composable
actual fun rememberFilePickerLauncher(
type: FilePickerFileType,
selectionMode: FilePickerSelectionMode,
onResult: (List<KmpFile>) -> Unit,
): FilePickerLauncher {
val context = LocalContext.current
return when (selectionMode) {
FilePickerSelectionMode.Single -> {
val singlePhotoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
onResult = { uri ->
val file = URIPathHelper.getPath(context, uri)?.let { File(it) }
file?.let { onResult(listOf(it)) }
}
)
remember {
FilePickerLauncher(
type = type,
selectionMode = selectionMode,
onLaunch = {
singlePhotoPickerLauncher.launch(
type.toPickVisualMediaRequest()
)
}
)
}
}
FilePickerSelectionMode.Multiple -> {
val singlePhotoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickMultipleVisualMedia(),
onResult = { uriList ->
val fileList = uriList.mapNotNull { uri ->
URIPathHelper.getPath(context, uri)?.let { File(it) }
}
onResult(fileList)
}
)
remember {
FilePickerLauncher(
type = type,
selectionMode = selectionMode,
onLaunch = {
singlePhotoPickerLauncher.launch(
type.toPickVisualMediaRequest()
)
}
)
}
}
}
}
internal fun FilePickerFileType.toPickVisualMediaRequest(): PickVisualMediaRequest {
return when (this) {
FilePickerFileType.Image -> PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
FilePickerFileType.Video -> PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.VideoOnly)
else -> PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo)
}
}
internal fun FilePickerFileType.isVisualMedia(): Boolean {
return when (this) {
FilePickerFileType.Image -> true
FilePickerFileType.Video -> true
FilePickerFileType.ImageVideo -> true
else -> false
}
}
actual class FilePickerLauncher actual constructor(
type: FilePickerFileType,
selectionMode: FilePickerSelectionMode,
private val onLaunch: () -> Unit,
) {
actual fun launch() {
onLaunch()
}
} | 0 | Kotlin | 5 | 122 | a4c955f60d8eae1ff103c60b60d3919d8feb1d80 | 3,233 | Calf | Apache License 2.0 |
plugins/git-features-trainer/src/git4idea/ift/GitLessonsUtil.kt | p7nov | 381,464,645 | false | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ift
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.SearchTextField
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.impl.VcsLogContentUtil
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.frame.MainFrame
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import com.intellij.vcs.log.util.findBranch
import git4idea.commands.Git
import git4idea.index.actions.runProcess
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.Nls
import training.dsl.LearningBalloonConfig
import training.dsl.LessonContext
import training.dsl.TaskContext
import training.dsl.subscribeForMessageBus
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
object GitLessonsUtil {
fun LessonContext.checkoutBranch(branchName: String) {
task {
addFutureStep {
val changeListManager = ChangeListManager.getInstance(project)
changeListManager.scheduleUpdate()
changeListManager.invokeAfterUpdate(true) {
val repository = GitRepositoryManager.getInstance(project).repositories.first()
if (repository.currentBranch?.name == branchName) {
completeStep()
}
else {
runProcess(project, "", false) {
Git.getInstance().checkout(repository, branchName, null, true, false).throwOnError()
}
completeStep()
}
}
}
}
prepareRuntimeTask {
val vcsLogData = VcsProjectLog.getInstance(project).mainLogUi?.logData ?: return@prepareRuntimeTask
val roots = GitRepositoryManager.getInstance(project).repositories.map(GitRepository::getRoot)
vcsLogData.refresh(roots)
}
}
// Git tool window must showing to reset it
fun LessonContext.resetGitLogWindow() {
prepareRuntimeTask {
val vcsLogUi = VcsProjectLog.getInstance(project).mainLogUi
// todo: find out how to open branches if it is hidden (git4idea.ui.branch.dashboard.SHOW_GIT_BRANCHES_LOG_PROPERTY is internal and can't be accessed)
vcsLogUi?.filterUi?.clearFilters()
PropertiesComponent.getInstance(project).setValue("Vcs.Log.Text.Filter.History", null)
val vcsLogWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.VCS)
VcsLogContentUtil.selectMainLog(vcsLogWindow!!.contentManager)
}
// clear Git tool window to return it to default state (needed in case of restarting the lesson)
task {
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: SearchTextField ->
if (UIUtil.getParentOfType(MainFrame::class.java, ui) != null) {
ui.reset()
true
}
else false
}
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: VcsLogGraphTable ->
ui.jumpToRow(0, true)
ui.selectionModel.clearSelection()
true
}
}
}
fun TaskContext.highlightSubsequentCommitsInGitLog(startCommitRow: Int,
sequenceLength: Int = 1,
highlightInside: Boolean = true,
usePulsation: Boolean = false) {
triggerByPartOfComponent(highlightInside = highlightInside, usePulsation = usePulsation) { ui: VcsLogGraphTable ->
ui.getRectForSubsequentCommits(startCommitRow, sequenceLength)
}
}
fun TaskContext.highlightSubsequentCommitsInGitLog(sequenceLength: Int = 1,
highlightInside: Boolean = true,
usePulsation: Boolean = false,
startCommitPredicate: (VcsCommitMetadata) -> Boolean) {
triggerByPartOfComponent(highlightInside = highlightInside, usePulsation = usePulsation) { ui: VcsLogGraphTable ->
val rowIndexes = (0 until ui.rowCount).toList().toIntArray()
val startCommitRow = ui.model.getCommitMetadata(rowIndexes).indexOfFirst(startCommitPredicate)
if (startCommitRow >= 0) {
ui.getRectForSubsequentCommits(startCommitRow, sequenceLength)
}
else null
}
}
fun TaskContext.highlightLatestCommitsFromBranch(branchName: String,
sequenceLength: Int = 1,
highlightInside: Boolean = true,
usePulsation: Boolean = false) {
highlightSubsequentCommitsInGitLog(sequenceLength, highlightInside, usePulsation) l@{ commit ->
val vcsData = VcsProjectLog.getInstance(project).dataManager ?: return@l false
val root = vcsData.roots.single()
commit.id == vcsData.dataPack.findBranch(branchName, root)?.commitHash
}
}
private fun VcsLogGraphTable.getRectForSubsequentCommits(startCommitRow: Int, sequenceLength: Int): Rectangle {
val cells = (1..4).map { getCellRect(startCommitRow, it, false) }
val width = cells.fold(0) { acc, rect -> acc + rect.width }
return Rectangle(cells[0].x, cells[0].y, width, cells[0].height * sequenceLength)
}
fun TaskContext.triggerOnNotification(checkState: (Notification) -> Boolean) {
addFutureStep {
subscribeForMessageBus(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
if (checkState(notification)) {
completeStep()
}
}
})
}
}
fun TaskContext.gotItStep(position: Balloon.Position, width: Int, @Nls text: String) {
val gotIt = CompletableFuture<Boolean>()
text(text, LearningBalloonConfig(position, width, false) { gotIt.complete(true) })
addStep(gotIt)
}
fun TaskContext.showWarningIfCommitWindowClosed(restoreTaskWhenResolved: Boolean = true) {
showWarningIfToolWindowClosed(ToolWindowId.COMMIT,
GitLessonsBundle.message("git.window.closed.warning",
action("CheckinProject"), strong(VcsBundle.message("commit.dialog.configurable"))),
restoreTaskWhenResolved)
}
fun TaskContext.showWarningIfGitWindowClosed(restoreTaskWhenResolved: Boolean = true) {
showWarningIfToolWindowClosed(ToolWindowId.VCS,
GitLessonsBundle.message("git.window.closed.warning",
action("ActivateVersionControlToolWindow"), strong("Git")),
restoreTaskWhenResolved)
}
private fun TaskContext.showWarningIfToolWindowClosed(toolWindowId: String,
@Language("HTML") @Nls warningMessage: String,
restoreTaskWhenResolved: Boolean) {
showWarning(warningMessage, restoreTaskWhenResolved) {
ToolWindowManager.getInstance(project).getToolWindow(toolWindowId)?.isVisible != true
}
}
} | 1 | null | 1 | 1 | d14025504c582d922141343de97441b2fc226b29 | 7,734 | intellij-community | Apache License 2.0 |
src/main/java/me/shadowalzazel/mcodyssey/items/Other.kt | ShadowAlzazel | 511,383,377 | false | null | package me.shadowalzazel.mcodyssey.items
import me.shadowalzazel.mcodyssey.constants.ItemModels
import me.shadowalzazel.mcodyssey.items.base.OdysseyItem
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextColor
import net.kyori.adventure.text.format.TextDecoration
import org.bukkit.Material
object Other {
// UN-USED !!!
val SILMARIL = OdysseyItem(
name = "elencuile_sapling",
material = Material.AMETHYST_SHARD,
displayName = Component.text("<NAME>", TextColor.color(255, 84, 255), TextDecoration.ITALIC),
lore = listOf(
Component.text("A jewel fruit grown by the world tree on Lupercal", TextColor.color(192, 152, 255 )).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE),
Component.text("Shining with stellar light...", TextColor.color(255, 227, 125)).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE)),
customModel = ItemModels.SILMARIL_OF_YGGLADIEL)
val FRUIT_OF_ERISHKIGAL = OdysseyItem(
name = "elencuile_sapling",
material = Material.ENCHANTED_GOLDEN_APPLE,
displayName = Component.text("<NAME>", TextColor.color(255, 84, 255), TextDecoration.ITALIC),
lore = listOf(Component.text("A fruit engineered at the atomic level", TextColor.color(80, 60, 170)).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE),
Component.text("With the power to alter one's life...", TextColor.color(255, 41, 119)).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE)),
customModel = ItemModels.FRUIT_OF_ERISHKIGAL)
} | 0 | Kotlin | 0 | 3 | 19f50df1a672bc1a34a16ef7e89872a5db1c8f7f | 1,614 | MinecraftOdyssey | MIT License |
Wiles Base/src/main/java/wiles/checker/data/GenericTypesMap.kt | Alex-Costea | 527,241,623 | false | {"Kotlin": 678627, "Java": 31813, "TypeScript": 3656, "CSS": 617, "JavaScript": 240, "Shell": 214} | package wiles.checker.data
class GenericTypesMap : HashMap<String, GenericTypeValue>() | 12 | Kotlin | 0 | 0 | c7c22e4e889b7c1e06f1559825199af4246ca5b3 | 86 | Wiles | MIT License |
src/main/java/com/kotlin/tutorial/controller/UserController.kt | fengzhizi715 | 158,692,744 | false | null | package com.kotlin.tutorial.controller
import com.kotlin.tutorial.service.AuditService
import com.kotlin.tutorial.service.UserReactiveService
import com.kotlin.tutorial.service.UserRxJavaService
import com.kotlin.tutorial.service.UserService
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.runBlocking
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
/**
* Created by tony on 2018/11/22.
*/
@RestController
@RequestMapping("/user")
class UserController {
@Autowired
lateinit var userReactiveService: UserReactiveService
@Autowired
lateinit var userRxJavaService: UserRxJavaService
@Autowired
lateinit var userService: UserService
@Autowired
lateinit var auditService: AuditService
@GetMapping("/reactive/find")
fun findByReactive(@RequestParam age: Int?, @RequestParam city: String?) = userReactiveService.find(age, city)
@GetMapping("/reactive/generate")
fun genDataByReactive() = userReactiveService.generateData()
@GetMapping("/rxjava/find")
fun findByRx(@RequestParam age: Int?, @RequestParam city: String?) = userRxJavaService.find(age, city)
@GetMapping("/rxjava/generate")
fun genDateByRx() = userRxJavaService.generateData()
@GetMapping("/rxjava/login")
fun mockLogin(@RequestParam username: String) = userRxJavaService.login(username)
@GetMapping("/blocking/{username}")
fun getNormalLoginMessage(@PathVariable username: String):String {
val user = userService.findByName(username)
val lastLoginTime = auditService.findByName(user.name).eventDate
return "Hi ${user.name}, you have logged in since $lastLoginTime"
}
@GetMapping("/rxjava/{username}")
fun getRxLoginMessage(@PathVariable username: String)=
userRxJavaService.findByName(username)
.map {
auditService.findByName(it.name).eventDate
}
.map {
"Hi ${username}, you have logged in since $it"
}
@GetMapping("/coroutine/{username}")
fun getLoginMessage(@PathVariable username: String) = runBlocking {
val user = userRxJavaService.findByName(username).awaitSingle()
val lastLoginTime = GlobalScope.async {
auditService.findByName(user.name).eventDate
}.await()
"Hi ${user.name}, you have logged in since $lastLoginTime"
}
} | 0 | Kotlin | 1 | 4 | 51e3726025054ee6f4b79b8412856b99a24d915d | 2,581 | kotlin-spring-reactive-coroutine-demo | Apache License 2.0 |
goldeneye/src/main/java/co/infinum/goldeneye/extensions/Context.kt | infinum | 54,713,189 | false | null | package co.infinum.goldeneye.extensions
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
internal fun Context.hasCameraPermission() = hasPermission(Manifest.permission.CAMERA)
internal fun Context.hasAudioPermission() = hasPermission(Manifest.permission.RECORD_AUDIO)
private fun Context.hasPermission(permission: String) =
ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED | 15 | Kotlin | 52 | 374 | 5f9a7106043b68013aa65c65f8e552f64a46e8c5 | 512 | Android-GoldenEye | Apache License 2.0 |
longpoll/src/commonMain/kotlin/ru/krindra/vkkt/longpoll/user/UserLongPoll.kt | krindra | 780,080,411 | false | {"Kotlin": 1336107} | package ru.krindra.vkkt.longpoll.user
import ru.krindra.vkkt.longpoll.LongPollParameters
import io.ktor.client.network.sockets.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.flow.flow
import ru.krindra.vkkt.core.VkApi
import ru.krindra.vkkt.longpoll.AbstractLongPoll
class UserLongPoll(
private val vkApi: VkApi,
private val mode: Int = 255,
private val version: Int = 3
): AbstractLongPoll<UserLPUpdate> {
private val httpClient = vkApi.httpClient
private var longPollParameters: LongPollParameters? = null
/*
* Get user long poll updates
*/
override suspend fun listen() = flow {
var timeout = 0
fun timeoutCheck(exception: Throwable) = if (timeout > 5) throw exception else timeout++
while (true) {
if (longPollParameters == null)
longPollParameters = getParameters()
try {
for (e in getEvent().updates) emit(e)
timeout = 0
} catch (exception: HttpRequestTimeoutException) {
timeoutCheck(exception)
} catch (exception: SocketTimeoutException) {
timeoutCheck(exception)
}
}
}
private suspend fun getEvent(): UserLPEvent {
val rawEvent = httpClient.get(longPollParameters!!.toUserURL(mode, version)).bodyAsText()
if (rawEvent.contains("fail")) {
val error = UserLPError.fromString(rawEvent)
errorHandle(error)
}
val event = UserLPEvent.fromEvent(rawEvent)
longPollParameters!!.ts = event.ts
return event
}
private suspend fun getParameters(): LongPollParameters {
val resp = vkApi.messages.getLongPollServer(lpVersion = version)
return LongPollParameters(resp.server, resp.key, resp.ts)
}
private suspend fun errorHandle(error: UserLPError) {
when (error.failed) {
1 -> longPollParameters!!.ts = error.ts!!
2,3 -> longPollParameters = getParameters()
else -> throw error
}
}
}
| 0 | Kotlin | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 2,142 | VKKT | MIT License |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/covidcertificate/pdf/core/TestCertificateDrawHelper.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.covidcertificate.pdf.core
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
import de.rki.coronawarnapp.covidcertificate.test.core.TestCertificate
import de.rki.coronawarnapp.covidcertificate.pdf.core.CertificateDrawHelper.Companion.FONT_COLOR
import de.rki.coronawarnapp.covidcertificate.pdf.core.CertificateDrawHelper.Companion.FONT_SIZE
import javax.inject.Inject
class TestCertificateDrawHelper @Inject constructor(@OpenSansTypeFace font: Typeface) {
val paint = Paint().apply {
typeface = font
textSize = FONT_SIZE
color = FONT_COLOR
}
fun drawCertificateDetail(canvas: Canvas, certificate: TestCertificate) {
with(canvas) {
save()
rotate(180f, PdfGenerator.A4_WIDTH / 2f, PdfGenerator.A4_HEIGHT / 2f)
drawTextIntoRectangle(certificate.targetName, paint, TextArea(476.20f, 489.40f, 112.75f))
drawTextIntoRectangle(certificate.testType, paint, TextArea(476.20f, 515.79f, 112.75f))
drawTextIntoRectangle(certificate.testName ?: "", paint, TextArea(314.27f, 581.76f, 236.89f))
drawTextIntoRectangle(certificate.testNameAndManufacturer ?: "", paint, TextArea(314.27f, 628.54f, 236.89f))
drawTextIntoRectangle(certificate.sampleCollectedAtFormatted, paint, TextArea(476.20f, 675.32f, 112.75f))
drawTextIntoRectangle(certificate.testResult, paint, TextArea(476.20f, 712.50f, 112.75f))
drawTextIntoRectangle(certificate.testCenter ?: "", paint, TextArea(476.20f, 741.29f, 112.75f))
drawTextIntoRectangle(
issuerCountryDisplayName(certificate.rawCertificate.test.certificateCountry),
paint,
TextArea(476.20f, 767.68f, 112.75f)
)
drawTextIntoRectangle(certificate.certificateIssuer, paint, TextArea(476.20f, 795.27f, 112.75f))
restore()
}
}
}
| 2 | Kotlin | 516 | 2,493 | aa450b97e701f6481019681cc6f5a03b7dcc6e86 | 1,976 | cwa-app-android | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/jpa/repository/ReferralRepositoryTest.kt | ministryofjustice | 312,544,431 | false | {"Kotlin": 1706888, "Mustache": 5562, "Shell": 2684, "PLpgSQL": 2362, "Dockerfile": 1980} | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.data.domain.PageRequest
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthUser
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.AuthUserFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ReferralFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.RepositoryTest
import java.time.OffsetDateTime
@Transactional
@RepositoryTest
class ReferralRepositoryTest @Autowired constructor(
val entityManager: TestEntityManager,
val endOfServiceReportRepository: EndOfServiceReportRepository,
val referralRepository: ReferralRepository,
val interventionRepository: InterventionRepository,
val authUserRepository: AuthUserRepository,
) {
private val authUserFactory = AuthUserFactory(entityManager)
private val referralFactory = ReferralFactory(entityManager)
private lateinit var authUser: AuthUser
@BeforeEach
fun beforeEach() {
authUser = authUserFactory.create()
}
@Test
fun `service provider report sanity check`() {
val referral = referralFactory.createSent()
referralFactory.createSent(sentAt = OffsetDateTime.now().minusHours(2), intervention = referral.intervention)
val referrals = referralRepository.serviceProviderReportReferrals(
OffsetDateTime.now().minusHours(1),
OffsetDateTime.now().plusHours(1),
setOf(referral.intervention.dynamicFrameworkContract),
PageRequest.of(0, 5),
)
assertThat(referrals.numberOfElements).isEqualTo(1)
}
}
| 8 | Kotlin | 1 | 2 | ba44e866429054452016b73eb71936a61e8ca645 | 1,941 | hmpps-interventions-service | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.