content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2010-2019 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 org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportLazy
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportLazyImpl
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportWarningCollector
import org.jetbrains.kotlin.backend.konan.objcexport.dumpObjCHeader
import org.jetbrains.kotlin.container.*
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
internal fun StorageComponentContainer.initContainer(config: KonanConfig) {
this.useImpl<FrontendServices>()
if (config.configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE) != null) {
this.useImpl<ObjCExportLazyImpl>()
this.useInstance(ObjCExportWarningCollector.SILENT)
useInstance(object : ObjCExportLazy.Configuration {
override val frameworkName: String
get() = config.moduleId
override fun isIncluded(moduleInfo: ModuleInfo): Boolean = true
override fun getCompilerModuleName(moduleInfo: ModuleInfo): String {
TODO()
}
override val objcGenerics: Boolean
get() = config.configuration.getBoolean(KonanConfigKeys.OBJC_GENERICS)
})
}
}
internal fun ComponentProvider.postprocessComponents(context: Context, files: Collection<KtFile>) {
context.frontendServices = this.get<FrontendServices>()
context.config.configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE)?.let {
this.get<ObjCExportLazy>().dumpObjCHeader(files, it)
}
}
class FrontendServices(val deprecationResolver: DeprecationResolver) | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanCompilerFrontendServices.kt | 3419308003 |
package net.nemerosa.ontrack.graphql.schema
import graphql.Scalars.*
import graphql.schema.*
import graphql.schema.GraphQLArgument.newArgument
import graphql.schema.GraphQLFieldDefinition.newFieldDefinition
import graphql.schema.GraphQLObjectType.newObject
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.graphql.schema.actions.UIActionsGraphQLService
import net.nemerosa.ontrack.graphql.schema.actions.actions
import net.nemerosa.ontrack.graphql.support.listType
import net.nemerosa.ontrack.graphql.support.pagination.GQLPaginatedListFactory
import net.nemerosa.ontrack.model.pagination.PageRequest
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.model.support.FreeTextAnnotatorContributor
import org.springframework.stereotype.Component
@Component
class GQLTypeBuild(
private val uiActionsGraphQLService: UIActionsGraphQLService,
private val structureService: StructureService,
private val projectEntityInterface: GQLProjectEntityInterface,
private val validation: GQLTypeValidation,
private val validationRun: GQLTypeValidationRun,
private val runInfo: GQLTypeRunInfo,
private val gqlEnumValidationRunSortingMode: GQLEnumValidationRunSortingMode,
private val runInfoService: RunInfoService,
private val paginatedListFactory: GQLPaginatedListFactory,
creation: GQLTypeCreation,
projectEntityFieldContributors: List<GQLProjectEntityFieldContributor>,
freeTextAnnotatorContributors: List<FreeTextAnnotatorContributor>
) : AbstractGQLProjectEntity<Build>(Build::class.java, ProjectEntityType.BUILD, projectEntityFieldContributors, creation, freeTextAnnotatorContributors) {
override fun getTypeName() = BUILD
override fun createType(cache: GQLTypeCache): GraphQLObjectType {
return newObject()
.name(BUILD)
.withInterface(projectEntityInterface.typeRef)
.fields(projectEntityInterfaceFields())
// Actions
.actions(uiActionsGraphQLService, Build::class)
// Ref to branch
.field(
newFieldDefinition()
.name("branch")
.description("Reference to branch")
.type(GraphQLTypeReference(GQLTypeBranch.BRANCH))
.build()
)
// Promotion runs
.field(
newFieldDefinition()
.name("promotionRuns")
.description("Promotions for this build")
.argument(
newArgument()
.name(ARG_PROMOTION)
.description("Name of the promotion level")
.type(GraphQLString)
.build()
)
.argument(
newArgument()
.name(ARG_LAST_PER_LEVEL)
.description("Returns the last promotion run per promotion level")
.type(GraphQLBoolean)
.build()
)
.type(listType(GraphQLTypeReference(GQLTypePromotionRun.PROMOTION_RUN)))
.dataFetcher(buildPromotionRunsFetcher())
.build()
)
// Validation runs
.field(
newFieldDefinition()
.name("validationRuns")
.description("Validations for this build")
.argument(
newArgument()
.name(ARG_VALIDATION_STAMP)
.description("Name of the validation stamp, can be a regular expression.")
.type(GraphQLString)
.build()
)
.argument(
newArgument()
.name(ARG_COUNT)
.description("Maximum number of validation runs")
.type(GraphQLInt)
.defaultValue(50)
.build()
)
.type(listType(GraphQLTypeReference(GQLTypeValidationRun.VALIDATION_RUN)))
.dataFetcher(buildValidationRunsFetcher())
.build()
)
// Paginated list of validation runs
.field(
paginatedListFactory.createPaginatedField<Build, ValidationRun>(
cache = cache,
fieldName = "validationRunsPaginated",
fieldDescription = "Paginated list of validation runs",
itemType = validationRun,
arguments = listOf(
newArgument()
.name(ARG_SORTING_MODE)
.description("Describes how the validation runs must be sorted.")
.type(gqlEnumValidationRunSortingMode.getTypeRef())
.build(),
),
itemListCounter = { _, build ->
structureService.getValidationRunsCountForBuild(
build.id
)
},
itemListProvider = { env, build, offset, size ->
val sortingMode = env.getArgument<String?>(ARG_SORTING_MODE)
?.let { ValidationRunSortingMode.valueOf(it) }
?: ValidationRunSortingMode.ID
structureService.getValidationRunsForBuild(
buildId = build.id,
offset = offset,
count = size,
sortingMode = sortingMode
)
}
)
)
// Validation runs per validation stamp
.field { f ->
f.name("validations")
.description("Validations per validation stamp")
.argument(
newArgument()
.name(ARG_VALIDATION_STAMP)
.description("Name of the validation stamp")
.type(GraphQLString)
.build()
)
.argument {
it.name(GQLPaginatedListFactory.ARG_OFFSET)
.description("Offset for the page")
.type(GraphQLInt)
.defaultValue(0)
}
.argument {
it.name(GQLPaginatedListFactory.ARG_SIZE)
.description("Size of the page")
.type(GraphQLInt)
.defaultValue(PageRequest.DEFAULT_PAGE_SIZE)
}
.type(listType(validation.typeRef))
.dataFetcher(buildValidationsFetcher())
}
// Build links - "using" direction, with pagination
.field(
paginatedListFactory.createPaginatedField<Build, Build>(
cache = cache,
fieldName = "using",
fieldDescription = "List of builds being used by this one.",
itemType = this,
arguments = listOf(
newArgument()
.name("project")
.description("Keeps only links targeted from this project")
.type(GraphQLString)
.build(),
newArgument()
.name("branch")
.description("Keeps only links targeted from this branch. `project` argument is also required.")
.type(GraphQLString)
.build()
),
itemPaginatedListProvider = { environment, build, offset, size ->
val filter: (Build) -> Boolean = getFilter(environment)
structureService.getBuildsUsedBy(
build,
offset,
size,
filter
)
}
)
)
// Build links - "usedBy" direction, with pagination
.field(
paginatedListFactory.createPaginatedField<Build, Build>(
cache = cache,
fieldName = "usedBy",
fieldDescription = "List of builds using this one.",
itemType = this,
arguments = listOf(
newArgument()
.name("project")
.description("Keeps only links targeted from this project")
.type(GraphQLString)
.build(),
newArgument()
.name("branch")
.description("Keeps only links targeted from this branch. `project` argument is also required.")
.type(GraphQLString)
.build()
),
itemPaginatedListProvider = { environment, build, offset, size ->
val filter = getFilter(environment)
structureService.getBuildsUsing(
build,
offset,
size,
filter
)
}
)
)
// Run info
.field {
it.name("runInfo")
.description("Run info associated with this build")
.type(runInfo.typeRef)
.runInfoFetcher<Build> { entity -> runInfoService.getRunInfo(entity) }
}
// OK
.build()
}
private fun getFilter(environment: DataFetchingEnvironment): (Build) -> Boolean {
val projectName: String? = environment.getArgument("project")
val branchName: String? = environment.getArgument("branch")
val filter: (Build) -> Boolean = if (branchName != null) {
if (projectName == null) {
throw IllegalArgumentException("`project` is required")
} else {
{
it.branch.project.name == projectName && it.branch.name == branchName
}
}
} else if (projectName != null) {
{
it.branch.project.name == projectName
}
} else {
{ true }
}
return filter
}
private fun buildValidationsFetcher(): DataFetcher<List<GQLTypeValidation.GQLTypeValidationData>> =
DataFetcher { environment ->
val build: Build = environment.getSource()
// Filter on validation stamp
val validationStampName: String? = environment.getArgument(ARG_VALIDATION_STAMP)
val offset = environment.getArgument<Int>(GQLPaginatedListFactory.ARG_OFFSET) ?: 0
val size = environment.getArgument<Int>(GQLPaginatedListFactory.ARG_SIZE) ?: 10
if (validationStampName != null) {
val validationStamp: ValidationStamp? =
structureService.findValidationStampByName(
build.project.name,
build.branch.name,
validationStampName
).orElse(null)
if (validationStamp != null) {
listOf(
buildValidation(
validationStamp, build, offset, size
)
)
} else {
emptyList()
}
} else {
// Gets the validation runs for the build
structureService.getValidationStampListForBranch(build.branch.id)
.map { validationStamp -> buildValidation(validationStamp, build, offset, size) }
}
}
private fun buildValidation(
validationStamp: ValidationStamp,
build: Build,
offset: Int,
size: Int
): GQLTypeValidation.GQLTypeValidationData {
return GQLTypeValidation.GQLTypeValidationData(
validationStamp,
structureService.getValidationRunsForBuildAndValidationStamp(
build.id,
validationStamp.id,
offset,
size
)
)
}
private fun buildValidationRunsFetcher() =
DataFetcher { environment ->
val build: Build = environment.getSource()
// Filter
val count: Int = environment.getArgument(ARG_COUNT) ?: 50
val validation: String? = environment.getArgument(ARG_VALIDATION_STAMP)
if (validation != null) {
// Gets one validation stamp by name
val validationStamp = structureService.findValidationStampByName(
build.project.name,
build.branch.name,
validation
).getOrNull()
// If there is one, we return the list of runs for this very stamp
if (validationStamp != null) {
// Gets validations runs for this validation level
return@DataFetcher structureService.getValidationRunsForBuildAndValidationStamp(
build.id,
validationStamp.id,
0,
count
)
}
// If not, we collect the list of matching validation stamp, assuming
// the argument is a regular expression
else {
val vsNameRegex = validation.toRegex()
return@DataFetcher structureService.getValidationStampListForBranch(build.branch.id)
.filter { vs -> vsNameRegex.matches(vs.name) }
.flatMap { vs ->
structureService.getValidationRunsForBuildAndValidationStamp(
build.id,
vs.id,
0, count
)
}
}
} else {
// Gets all the validation runs (limited by count)
return@DataFetcher structureService.getValidationRunsForBuild(build.id, 0, count)
.take(count)
}
}
private fun buildPromotionRunsFetcher() =
DataFetcher<List<PromotionRun>> { environment ->
val build: Build = environment.getSource()
// Last per promotion filter?
val lastPerLevel: Boolean = environment.getArgument(ARG_LAST_PER_LEVEL) ?: false
// Promotion filter
val promotion: String? = environment.getArgument(ARG_PROMOTION)
val promotionLevel: PromotionLevel? = if (promotion != null) {
// Gets the promotion level
structureService.findPromotionLevelByName(
build.project.name,
build.branch.name,
promotion
).orElse(null)
} else {
null
}
if (promotionLevel != null) {
// Gets promotion runs for this promotion level
if (lastPerLevel) {
return@DataFetcher structureService.getLastPromotionRunForBuildAndPromotionLevel(build, promotionLevel)
.map { listOf(it) }
.orElse(listOf())
} else {
return@DataFetcher structureService.getPromotionRunsForBuildAndPromotionLevel(build, promotionLevel)
}
} else {
// Gets all the promotion runs
if (lastPerLevel) {
return@DataFetcher structureService.getLastPromotionRunsForBuild(build.id)
} else {
return@DataFetcher structureService.getPromotionRunsForBuild(build.id)
}
}
}
override fun getSignature(entity: Build): Signature? {
return entity.signature
}
companion object {
/**
* Name of the type
*/
const val BUILD = "Build"
/**
* Filter on the validation runs
*/
const val ARG_VALIDATION_STAMP = "validationStamp"
/**
* Count argument
*/
const val ARG_COUNT = "count"
/**
* Promotion level argument
*/
const val ARG_PROMOTION = "promotion"
/**
* Last per level argument
*/
const val ARG_LAST_PER_LEVEL = "lastPerLevel"
/**
* Sorting mode for the validation runs
*/
const val ARG_SORTING_MODE = "sortingMode"
}
}
| ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypeBuild.kt | 1726961329 |
package net.nemerosa.ontrack.service.support
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Tag
import net.nemerosa.ontrack.model.support.CollectedConnectorStatus
import net.nemerosa.ontrack.model.support.ConnectorStatusIndicator
import net.nemerosa.ontrack.model.support.ConnectorStatusType
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import javax.annotation.PostConstruct
@Component
@Transactional(readOnly = true)
class ConnectorStatusMetrics(
private val connectorStatusIndicator: List<ConnectorStatusIndicator>,
private val connectorStatusJob: ConnectorStatusJob,
private val registry: MeterRegistry
) {
private fun MeterRegistry.register(
name: String,
gauge: (ConnectorStatusJob) -> List<CollectedConnectorStatus>?,
tags: List<Tag>,
extractor: (List<CollectedConnectorStatus>) -> Double
) {
gauge(
name,
tags,
connectorStatusJob
) { job ->
val statuses = gauge(job)
if (statuses != null) {
extractor(statuses)
} else {
0.0
}
}
}
@PostConstruct
fun bindTo() {
connectorStatusIndicator.forEach { indicator ->
val gauge = { job: ConnectorStatusJob -> job.statuses[indicator.type] }
val tags = listOf(
Tag.of("type", indicator.type)
)
registry.register("ontrack_connector_count", gauge, tags) { statuses ->
statuses.size.toDouble()
}
registry.register("ontrack_connector_up", gauge, tags) { statuses ->
statuses.count { it.status.type == ConnectorStatusType.UP }.toDouble()
}
registry.register("ontrack_connector_down", gauge, tags) { statuses ->
statuses.count { it.status.type == ConnectorStatusType.DOWN }.toDouble()
}
}
}
} | ontrack-service/src/main/java/net/nemerosa/ontrack/service/support/ConnectorStatusMetrics.kt | 915824605 |
package net.binggl.mydms.integration
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
const val JWT_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlOWExZTRjY2QwOWE0Y2Y4YWE0YzEzM2U5YjM5NjkyNSIsImlhdCI6MTUxMzk2NTM0NiwiaXNzIjoibG9naW4uYmluZ2dsLm5ldCIsInN1YiI6ImxvZ2luLlVzZXIiLCJUeXBlIjoibG9naW4uVXNlciIsIlVzZXJOYW1lIjoiYmloZSIsIkVtYWlsIjoiYS5iQGMuZGUiLCJDbGFpbXMiOlsibXlkbXN8aHR0cHM6Ly9teWRtcy5iaW5nZ2wubmV0L3xVc2VyIl0sIlVzZXJJZCI6IjEyMzQiLCJEaXNwbGF5TmFtZSI6IkhlbnJpayBCaW5nZ2wifQ.gcSWaxT5MQMqXvptqoxUI6PpI5J7sNmLlcMH3fspscE"
object IntegrationHelpers {
val headers: HttpHeaders
get() {
val headers = HttpHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA
headers.set("Authorization", "Bearer $JWT_TOKEN")
return headers
}
} | Api/src/test/kotlin/net/binggl/mydms/integration/IntegrationHelpers.kt | 2295404092 |
package de.sneakpeek.ui.detail
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import com.squareup.picasso.Picasso
import de.sneakpeek.R
import de.sneakpeek.adapter.ActorsAdapter
import de.sneakpeek.data.MovieInfo
import de.sneakpeek.service.TheMovieDBService
import de.sneakpeek.util.Util
import kotlinx.android.synthetic.main.activity_detail.*
import kotlinx.android.synthetic.main.activity_detail_movie_information.*
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.*
class DetailActivity : AppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
setTheme(if (Util.GetUseLightTheme(application)) R.style.SneakPeekLightTransparentStatusBar else R.style.SneakPeekDarkTransparentStatusBar)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
activity_detail_toolbar.title = ""
setSupportActionBar(activity_detail_toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
if (!intent.extras.containsKey(MOVIE_KEY)) {
Log.e(TAG, "This Activity has to be started via StartMovieActivity")
return
}
val movie = intent.extras.getParcelable<MovieInfo>(MOVIE_KEY)
Picasso.with(this@DetailActivity)
.load("${TheMovieDBService.IMAGE_URL}${movie?.poster_path}")
.placeholder(R.drawable.movie_poster_placeholder)
.into(activity_detail_poster)
val vote_average_fab = if (movie.vote_average.compareTo(0) == 0) {
getString(R.string.activity_detail_vote_average_na)
} else {
"${movie.vote_average}"
}
activity_movie_fab.setImageBitmap(textAsBitmap(vote_average_fab, 40f, Color.WHITE))
activity_detail_original_title.text = if (TextUtils.isEmpty(movie.original_title)) {
""
} else {
" - ${movie.original_title}"
}
activity_detail_director.text = movie.director
activity_detail_original_language.text = Locale(movie.original_language).displayLanguage
activity_detail_genre.text = movie?.genres?.map { it.name ?: "" }?.reduce { acc, s -> "$acc | $s" }
activity_detail_vote_average.text = "${movie.vote_average} / 10"
val numberFormatter = NumberFormat.getCurrencyInstance()
numberFormatter.minimumFractionDigits = 0
activity_detail_budget.text = if (movie.budget == 0) {
getText(R.string.activity_detail_budget_na)
} else {
numberFormatter.format(movie.budget)
}
activity_detail_plot.text = movie.overview
val format = SimpleDateFormat("yyyy-MM-dd", Locale.GERMANY).parse(movie.release_date)
activity_detail_released.text = SimpleDateFormat.getDateInstance().format(format)
activity_detail_runtime.text = "${movie.runtime} min"
activity_detail_writer.text = movie.writer
activity_detail_recycler_view_actors.setHasFixedSize(true)
activity_detail_recycler_view_actors.adapter = ActorsAdapter(movie.credits?.cast ?: emptyList())
activity_detail_recycler_view_actors.itemAnimator = DefaultItemAnimator()
activity_detail_recycler_view_actors.layoutManager = LinearLayoutManager(baseContext)
activity_detail_recycler_view_actors.isNestedScrollingEnabled = false
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
companion object {
private val TAG = DetailActivity::class.java.simpleName
private val MOVIE_KEY = "MOVIE_KEY"
fun StartMovieActivity(context: Context, movie: MovieInfo): Intent {
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(MOVIE_KEY, movie)
return intent
}
}
fun textAsBitmap(text: String, textSize: Float, textColor: Int): Bitmap {
val paint = Paint(ANTI_ALIAS_FLAG)
paint.textSize = textSize
paint.color = textColor
paint.textAlign = Paint.Align.LEFT
val baseline = -paint.ascent() // ascent() is negative
val image = Bitmap.createBitmap(paint.measureText(text).toInt(),
baseline.toInt() + paint.descent().toInt(),
Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
canvas.drawText(text, 0f, baseline, paint)
return image
}
}
| app/src/main/java/de/sneakpeek/ui/detail/DetailActivity.kt | 760867395 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.color
import com.demonwav.mcdev.insight.findColor
import com.demonwav.mcdev.platform.sponge.SpongeModuleType
import com.intellij.psi.PsiElement
import java.awt.Color
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.toUElementOfType
fun PsiElement.findSpongeColor(): Pair<Color, UElement>? =
this.toUElementOfType<UIdentifier>()?.findColor(
SpongeModuleType,
"org.spongepowered.api.util.Color",
arrayOf(
"com.flowpowered.math.vector.Vector3d",
"com.flowpowered.math.vector.Vector3f",
"com.flowpowered.math.vector.Vector3i"
)
)
| src/main/kotlin/platform/sponge/color/SpongeColorUtil.kt | 1322151421 |
package net.dean.jraw.meta
import net.steppschuh.markdowngenerator.link.Link
import net.steppschuh.markdowngenerator.table.Table
import net.steppschuh.markdowngenerator.text.code.Code
import net.steppschuh.markdowngenerator.text.heading.Heading
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
object MarkdownOverviewCreator {
fun create(endpoints: EndpointOverview, f: File) = f.writeText(create(endpoints))
private val dateFormat = SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z")
/** In which order to display endpoints. Statuses that come first will appear first. */
private val implementationOrder = listOf(
ImplementationStatus.IMPLEMENTED,
ImplementationStatus.PLANNED,
ImplementationStatus.NOT_PLANNED
)
private fun create(overview: EndpointOverview): String {
return with (StringBuilder()) {
// Comment to those curious enough to open the file
block("<!--- Generated ${dateFormat.format(Date())}. Use `./gradlew :meta:update` to update. DO NOT " +
"MODIFY DIRECTLY -->")
// Main header
heading("Endpoints")
// Purpose of this file
block(
"This file contains a list of all the endpoints (regardless of if they have been implemented) that " +
"can be found at the [official reddit API docs](https://www.reddit.com/dev/api/oauth). " +
"To update this file, run `./gradlew :meta:update`"
)
// Summary
block("So far, API completion is at **${overview.completionPercentage(decimals = 2)}%**. " +
"${overview.implemented} out of ${overview.effectiveTotal} endpoints (ignoring ${overview.notPlanned} " +
"endpoints not planned) have been implemented ")
val oauthScopes = overview.scopes()
for (scope in oauthScopes) {
val section = overview.byOAuthScope(scope)
heading(if (scope == "any") "(any scope)" else scope, 2)
block("${section.completionPercentage(2)}% completion (${section.implemented} implemented, ${section.planned} planned, and " +
"${section.notPlanned} not planned)")
val table = Table.Builder()
.withAlignments(Table.ALIGN_CENTER, Table.ALIGN_LEFT, Table.ALIGN_LEFT)
.addRow("Method", "Endpoint", "Implementation")
val sorted = section.endpoints.sortedWith(compareBy(
// Show sorted endpoints first, then planned, then not planned
{ implementationOrder.indexOf(it.status) },
// Then sort ascending alphabetically by path
{ it.path },
// Then sort ascending alphabetically by HTTP method
{ it.method }
))
for (e in sorted) {
table.addRow(
Code(e.method),
Link(Code(e.displayPath), e.redditDocLink),
implString(e))
}
block(table.build())
}
toString()
}
}
private fun StringBuilder.heading(text: String, level: Int = 1) = block(Heading(text, level))
private fun StringBuilder.block(obj: Any) {
append(obj)
append("\n\n")
}
private fun implString(e: EndpointMeta): String {
return when (e.status) {
ImplementationStatus.IMPLEMENTED -> {
val method = e.implementation!!
Link(Code("${method.declaringClass.simpleName}.${method.name}()"), e.sourceUrl).toString()
}
ImplementationStatus.NOT_PLANNED -> "Not planned"
ImplementationStatus.PLANNED -> "None"
}
}
}
| meta/src/main/kotlin/net/dean/jraw/meta/MarkdownOverviewCreator.kt | 3382208734 |
package test
import android.app.*
import android.widget.*
import android.os.Bundle
import org.jetbrains.anko.*
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.*
import org.junit.Test
import kotlin.test.*
public open class TestActivity() : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
linearLayout {}
}
}
@RunWith(RobolectricTestRunner::class)
public class RobolectricTest() {
Test
public fun test() {
val activity = Robolectric.buildActivity(javaClass<TestActivity>()).create().get()
val vibrator = activity.vibrator
vibrator.vibrate(100)
println("[COMPLETE]")
}
} | dsl/testData/robolectric/ServiceTest.kt | 973337748 |
/**
* The MIT License
* Copyright (c) 2015 Nicholas Feldman (AngrySoundTech)
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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 tech.feldman.couponcodes.bukkit.database.options
import java.io.File
class SQLiteOptions(val sqlFile: File) : DatabaseOptions
| mods/bukkit/src/main/kotlin/tech/feldman/couponcodes/bukkit/database/options/SQLiteOptions.kt | 1023827354 |
//
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.infrastructure
//---------------------------------------------------------------------------------------------------------------------
/**
* Implementation of MutableMap<K,V> that throws an exception for every operation.
*/
internal class UnusedMap<K, V> : MutableMap<K, V> {
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() = throw UnsupportedOperationException("Attempted to use unused map.")
override val keys: MutableSet<K>
get() = throw UnsupportedOperationException("Attempted to use unused map.")
override val size: Int
get() = throw UnsupportedOperationException("Attempted to use unused map.")
override val values: MutableCollection<V>
get() = throw UnsupportedOperationException("Attempted to use unused map.")
////
override fun clear() {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun containsKey(key: K): Boolean {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun containsValue(value: V): Boolean {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun get(key: K): V? {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun isEmpty(): Boolean {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun put(key: K, value: V): V? {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun putAll(from: Map<out K, V>) {
throw UnsupportedOperationException("Attempted to use unused map.")
}
override fun remove(key: K): V? {
throw UnsupportedOperationException("Attempted to use unused map.")
}
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/infrastructure/UnusedMap.kt | 1225207580 |
package com.example.andretortolano.githubsearch.debug
import android.util.Log
class Logger {
companion object {
private val APPLICATION_TAG = "GITHUB_LOG_TAG"
fun i(message: String?) {
Log.i(APPLICATION_TAG, message);
}
fun e(message: String?) {
Log.e(APPLICATION_TAG, message);
}
}
}
| app/src/main/java/com/example/andretortolano/githubsearch/debug/Logger.kt | 3596902750 |
package ffc.app.setting
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.preference.PreferenceFragmentCompat
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import ffc.api.FfcCentral
import ffc.app.BuildConfig
import ffc.app.FamilyFolderActivity
import ffc.app.R
import ffc.app.auth.legal.LegalAgreementApi
import ffc.app.auth.legal.LegalType
import ffc.app.auth.legal.LegalType.privacy
import ffc.app.auth.legal.LegalType.terms
import org.jetbrains.anko.support.v4.intentFor
import org.jetbrains.anko.support.v4.startActivity
class AboutActivity : FamilyFolderActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preference)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportFragmentManager
.beginTransaction()
.replace(R.id.contentContainer, AboutPreferenceFragment())
.commit()
}
class AboutPreferenceFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.pref_about, rootKey)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
findPreference("version").summary = BuildConfig.VERSION_NAME
findPreference("license").setOnPreferenceClickListener {
startActivity<OssLicensesMenuActivity>()
true
}
findPreference("terms").intent = intentOfLegal(terms)
findPreference("privacy").intent = intentOfLegal(privacy)
}
private fun intentOfLegal(type: LegalType): Intent {
val term = FfcCentral().service<LegalAgreementApi>().latest(type)
return intentFor<LegalViewActivity>().apply {
data = Uri.parse(term.request().url().toString())
}
}
}
}
| ffc/src/main/kotlin/ffc/app/setting/AboutActivity.kt | 3806444137 |
package com.benoitquenaudon.tvfoot.red.util
import androidx.test.runner.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* There was a working implementation that failed on Android so I moved the tests inside AndroidTest
*/
@RunWith(AndroidJUnit4::class)
class StringExtAndroidTest {
@Test
fun stripAccents() {
assertEquals("grece", "grèce".stripAccents())
assertEquals("azerbaidjan", "azerbaïdjan".stripAccents())
}
} | app/src/androidTest/kotlin/com/benoitquenaudon/tvfoot/red/util/StringExtAndroidTest.kt | 2776083819 |
package org.wikipedia.util
import android.content.Context
import android.content.pm.PackageManager
import org.wikipedia.BuildConfig
import org.wikipedia.settings.Prefs
object ReleaseUtil {
private const val RELEASE_PROD = 0
private const val RELEASE_BETA = 1
private const val RELEASE_ALPHA = 2
private const val RELEASE_DEV = 3
val isProdRelease: Boolean
get() = calculateReleaseType() == RELEASE_PROD
val isPreProdRelease: Boolean
get() = calculateReleaseType() != RELEASE_PROD
val isAlphaRelease: Boolean
get() = calculateReleaseType() == RELEASE_ALPHA
val isPreBetaRelease: Boolean
get() = when (calculateReleaseType()) {
RELEASE_PROD, RELEASE_BETA -> false
else -> true
}
val isDevRelease: Boolean
get() = calculateReleaseType() == RELEASE_DEV
fun getChannel(ctx: Context): String {
var channel = Prefs.appChannel
if (channel == null) {
channel = getChannelFromManifest(ctx)
Prefs.appChannel = channel
}
return channel
}
private fun calculateReleaseType(): Int {
return when {
BuildConfig.APPLICATION_ID.contains("beta") -> RELEASE_BETA
BuildConfig.APPLICATION_ID.contains("alpha") -> RELEASE_ALPHA
BuildConfig.APPLICATION_ID.contains("dev") -> RELEASE_DEV
else -> RELEASE_PROD
}
}
private fun getChannelFromManifest(ctx: Context): String {
return try {
val info = ctx.packageManager
.getApplicationInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_META_DATA)
val channel = info.metaData.getString(Prefs.appChannelKey)
channel ?: ""
} catch (t: Throwable) {
""
}
}
}
| app/src/main/java/org/wikipedia/util/ReleaseUtil.kt | 2696800733 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.users
import android.content.Context
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.Mastodon
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.extension.api.lookupUsersMapPaginated
import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable
import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
class IncomingFriendshipsLoader(
context: Context,
accountKey: UserKey?,
data: List<ParcelableUser>?,
fromUser: Boolean
) : AbsRequestUsersLoader(context, accountKey, data, fromUser) {
@Throws(MicroBlogException::class)
override fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> {
when (details.type) {
AccountType.MASTODON -> {
val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java)
return mastodon.getFollowRequests(paging).mapToPaginated {
it.toParcelable(details)
}
}
AccountType.FANFOU -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.getFriendshipsRequests(paging).mapToPaginated(pagination) {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
else -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
return microBlog.lookupUsersMapPaginated(microBlog.getIncomingFriendships(paging)) {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/IncomingFriendshipsLoader.kt | 4145085117 |
package com.brianc.css
data class Color(val r: Short, val g: Short, val b: Short, val a: Short) {
constructor(r: Int, g: Int, b: Int, a: Int) : this(r.toShort(), g.toShort(), b.toShort(), a.toShort())
override fun toString() = "rgba($r,$g,$b,$a)"
companion object {
val BLACK = Color(0, 0, 0, 255)
}
}
| src/com/brianc/css/Color.kt | 1389835639 |
package org.fossasia.susi.ai.login
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.data.contract.ILoginModel
import org.fossasia.susi.ai.data.LoginModel
import org.fossasia.susi.ai.data.UtilModel
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.helper.CredentialHelper
import org.fossasia.susi.ai.login.contract.ILoginPresenter
import org.fossasia.susi.ai.login.contract.ILoginView
import org.fossasia.susi.ai.rest.responses.susi.LoginResponse
import retrofit2.Response
import java.net.UnknownHostException
/**
* Presenter for Login
* The P in MVP
*
* Created by chiragw15 on 4/7/17.
*/
class LoginPresenter(loginActivity: LoginActivity): ILoginPresenter, ILoginModel.OnLoginFinishedListener {
var loginModel: LoginModel = LoginModel()
var utilModel: UtilModel = UtilModel(loginActivity)
var loginView: ILoginView?= null
lateinit var email: String
override fun onAttach(loginView: ILoginView) {
this.loginView = loginView
if (utilModel.getAnonymity()) {
loginView.skipLogin()
return
}
if(utilModel.isLoggedIn()) {
loginView.skipLogin()
return
}
loginView.attachEmails(utilModel.getSavedEmails())
}
override fun skipLogin() {
utilModel.clearToken()
utilModel.saveAnonymity(true)
loginView?.skipLogin()
}
override fun login(email: String, password: String, isSusiServerSelected: Boolean, url: String) {
if (email.isEmpty()) {
loginView?.invalidCredentials(true, Constant.EMAIL)
return
}
if(password.isEmpty()) {
loginView?.invalidCredentials(true, Constant.PASSWORD)
return
}
if (!CredentialHelper.isEmailValid(email)) {
loginView?.invalidCredentials(false, Constant.EMAIL)
return
}
if (!isSusiServerSelected) {
if (url.isEmpty()){
loginView?.invalidCredentials(true, Constant.INPUT_URL)
return
}
if( CredentialHelper.isURLValid(url)) {
if (CredentialHelper.getValidURL(url) != null) {
utilModel.setServer(false)
utilModel.setCustomURL(url)
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
utilModel.setServer(true)
}
this.email = email
loginView?.showProgress(true)
loginModel.login(email.trim({ it <= ' ' }).toLowerCase(), password, this)
}
override fun cancelLogin() {
loginModel.cancelLogin()
}
override fun onError(throwable: Throwable) {
loginView?.showProgress(false)
if (throwable is UnknownHostException) {
loginView?.onLoginError(utilModel.getString(R.string.unknown_host_exception), throwable.message.toString())
} else {
loginView?.onLoginError(utilModel.getString(R.string.error_internet_connectivity),
utilModel.getString(R.string.no_internet_connection))
}
}
override fun onSuccess(response: Response<LoginResponse>) {
loginView?.showProgress(false)
if (response.isSuccessful && response.body() != null) {
utilModel.saveToken(response)
utilModel.deleteAllMessages()
utilModel.saveEmail(email)
utilModel.saveAnonymity(false)
loginView?.onLoginSuccess(response.body().message)
} else if (response.code() == 422) {
loginView?.onLoginError(utilModel.getString(R.string.password_invalid_title),
utilModel.getString(R.string.password_invalid))
} else {
loginView?.onLoginError("${response.code()} " + utilModel.getString(R.string.error), response.message())
}
}
override fun onDetach() {
loginView = null
}
}
| app/src/main/java/org/fossasia/susi/ai/login/LoginPresenter.kt | 2679080961 |
package operator.overloading
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
/**
* 以下示例看得出在Kotlin中,委托属性是如何工作的。
*
* 你创建了一个保存属性值的类,并在修改属性时自动触发更改通知。
* 但是需要相当多的样板代码来为每个属性创建ObservableProperty实例。
*
* Kotlin的委托属性功能可以让你摆脱这些样板代码。
*/
fun main(args: Array<String>) {
val p01 = People01("congwiny", 28, 2000)
p01.addPropertyChangeListener(PropertyChangeListener { event ->
println("Property ${event.propertyName} changed " +
"from ${event.oldValue} to ${event.newValue}")
})
p01.age = 29
p01.salary = 3000
}
class People01(
val name: String, age: Int, salary: Int
) : PropertyChangeAware() {
val _age = ObservableProperty01("age", age, changeSupport)
var age: Int
get() = _age.getValue()
set(value) {
_age.setValue(value)
}
val _salary = ObservableProperty01("salary", salary, changeSupport)
var salary: Int
get() = _salary.getValue()
set(value) {
_salary.setValue(value)
}
}
class ObservableProperty01(
val propName: String, var propValue: Int,
val changeSupport: PropertyChangeSupport
) {
fun getValue(): Int = propValue
fun setValue(newValue: Int) {
val oldValue = propValue
propValue = newValue
changeSupport.firePropertyChange(propName, oldValue, newValue)
}
} | src/main/kotlin/operator/overloading/DelegatedProperties01.kt | 4220926721 |
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* All of [Season]'s connections.
*
* @param videos The Videos connection.
*/
@JsonClass(generateAdapter = true)
data class SeasonConnections(
@Json(name = "videos")
val videos: BasicConnection? = null
)
| models/src/main/java/com/vimeo/networking2/SeasonConnections.kt | 69841066 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.buildtool
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil.unquoteString
import com.intellij.util.execution.ParametersListUtil
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.getBuildConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.toolchain.tools.Rustup.Companion.checkNeedInstallTarget
class CargoBuildTaskProvider : RsBuildTaskProvider<CargoBuildTaskProvider.BuildTask>() {
override fun getId(): Key<BuildTask> = ID
override fun createTask(runConfiguration: RunConfiguration): BuildTask? =
if (runConfiguration is CargoCommandConfiguration) BuildTask() else null
override fun executeTask(
context: DataContext,
configuration: RunConfiguration,
environment: ExecutionEnvironment,
task: BuildTask
): Boolean {
if (configuration !is CargoCommandConfiguration) return false
val buildConfiguration = getBuildConfiguration(configuration) ?: return true
val projectDirectory = buildConfiguration.workingDirectory ?: return false
val configArgs = ParametersListUtil.parse(buildConfiguration.command)
val targetFlagIdx = configArgs.indexOfFirst { it.startsWith("--target") }
val targetFlag = if (targetFlagIdx != -1) configArgs[targetFlagIdx] else null
val targetTriple = when {
targetFlag == "--target" -> configArgs.getOrNull(targetFlagIdx + 1)
targetFlag?.startsWith("--target=") == true -> unquoteString(targetFlag.substringAfter("="))
else -> null
}
if (targetTriple != null && checkNeedInstallTarget(configuration.project, projectDirectory, targetTriple)) {
return false
}
return doExecuteTask(buildConfiguration, environment)
}
class BuildTask : RsBuildTaskProvider.BuildTask<BuildTask>(ID)
companion object {
@JvmField
val ID: Key<BuildTask> = Key.create("CARGO.BUILD_TASK_PROVIDER")
}
}
| src/main/kotlin/org/rust/cargo/runconfig/buildtool/CargoBuildTaskProvider.kt | 282807638 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.ui
import com.intellij.execution.ExecutionBundle
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.util.text.nullize
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.runconfig.RsCommandConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.util.RsCommandLineEditor
import java.nio.file.Path
import java.nio.file.Paths
abstract class RsCommandConfigurationEditor<T : RsCommandConfiguration>(
protected val project: Project
) : SettingsEditor<T>() {
abstract val command: RsCommandLineEditor
protected fun currentWorkspace(): CargoWorkspace? =
CargoCommandConfiguration.findCargoProject(project, command.text, currentWorkingDirectory)?.workspace
protected val currentWorkingDirectory: Path?
get() = workingDirectory.component.text.nullize()?.let { Paths.get(it) }
protected val workingDirectory: LabeledComponent<TextFieldWithBrowseButton> =
WorkingDirectoryComponent()
override fun resetEditorFrom(configuration: T) {
command.text = configuration.command
workingDirectory.component.text = configuration.workingDirectory?.toString().orEmpty()
}
override fun applyEditorTo(configuration: T) {
configuration.command = command.text
configuration.workingDirectory = currentWorkingDirectory
}
}
private class WorkingDirectoryComponent : LabeledComponent<TextFieldWithBrowseButton>() {
init {
component = TextFieldWithBrowseButton().apply {
val fileChooser = FileChooserDescriptorFactory.createSingleFolderDescriptor().apply {
title = ExecutionBundle.message("select.working.directory.message")
}
addBrowseFolderListener(null, null, null, fileChooser)
}
text = ExecutionBundle.message("run.configuration.working.directory.label")
}
}
| src/main/kotlin/org/rust/cargo/runconfig/ui/RsCommandConfigurationEditor.kt | 224009951 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.icons
import com.intellij.ide.IconProvider
import com.intellij.psi.PsiElement
import org.rust.cargo.icons.CargoIcons
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.lang.RsConstants
import org.rust.lang.core.psi.RsFile
import javax.swing.Icon
class RsIconProvider : IconProvider() {
override fun getIcon(element: PsiElement, flags: Int): Icon? = when (element) {
is RsFile -> getFileIcon(element)
else -> null
}
private fun getFileIcon(file: RsFile): Icon? = when {
file.name == RsConstants.MOD_RS_FILE -> RsIcons.MOD_RS
isMainFile(file) -> RsIcons.MAIN_RS
isBuildRs(file) -> CargoIcons.BUILD_RS_ICON
else -> null
}
private fun isMainFile(element: RsFile) =
(element.name == RsConstants.MAIN_RS_FILE || element.name == RsConstants.LIB_RS_FILE)
&& element.isCrateRoot
private fun isBuildRs(element: RsFile): Boolean = // TODO containingTarget
element.isCrateRoot && element.crate.kind == CargoWorkspace.TargetKind.CustomBuild
}
| src/main/kotlin/org/rust/ide/icons/RsIconProvider.kt | 3352289267 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.metalava
import androidx.build.checkapi.ApiLocation
import org.apache.commons.io.FileUtils
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.work.DisableCachingByDefault
import java.io.File
import java.util.concurrent.TimeUnit
/** Compares two API txt files against each other. */
@DisableCachingByDefault(because = "Doesn't benefit from caching")
abstract class CheckApiEquivalenceTask : DefaultTask() {
/**
* Api file (in the build dir) to check
*/
@get:Input
abstract val builtApi: Property<ApiLocation>
/**
* Api file (in source control) to compare against
*/
@get:Input
abstract val checkedInApis: ListProperty<ApiLocation>
@InputFiles @PathSensitive(PathSensitivity.RELATIVE)
fun getTaskInputs(): List<File> {
val checkedInApiLocations = checkedInApis.get()
val checkedInApiFiles = checkedInApiLocations.flatMap { checkedInApiLocation ->
listOf(
checkedInApiLocation.publicApiFile,
checkedInApiLocation.removedApiFile,
checkedInApiLocation.experimentalApiFile,
checkedInApiLocation.restrictedApiFile
)
}
val builtApiLocation = builtApi.get()
val builtApiFiles = listOf(
builtApiLocation.publicApiFile,
builtApiLocation.removedApiFile,
builtApiLocation.experimentalApiFile,
builtApiLocation.restrictedApiFile
)
return checkedInApiFiles + builtApiFiles
}
@TaskAction
fun exec() {
val builtApiLocation = builtApi.get()
for (checkedInApi in checkedInApis.get()) {
checkEqual(checkedInApi.publicApiFile, builtApiLocation.publicApiFile)
checkEqual(checkedInApi.removedApiFile, builtApiLocation.removedApiFile)
checkEqual(checkedInApi.experimentalApiFile, builtApiLocation.experimentalApiFile)
checkEqual(checkedInApi.restrictedApiFile, builtApiLocation.restrictedApiFile)
}
}
}
private fun summarizeDiff(a: File, b: File): String {
if (!a.exists()) {
return "$a does not exist"
}
if (!b.exists()) {
return "$b does not exist"
}
val process = ProcessBuilder(listOf("diff", a.toString(), b.toString()))
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start()
process.waitFor(5, TimeUnit.SECONDS)
var diffLines = process.inputStream.bufferedReader().readLines().toMutableList()
val maxSummaryLines = 50
if (diffLines.size > maxSummaryLines) {
diffLines = diffLines.subList(0, maxSummaryLines)
diffLines.plusAssign("[long diff was truncated]")
}
return diffLines.joinToString("\n")
}
fun checkEqual(expected: File, actual: File) {
if (!FileUtils.contentEquals(expected, actual)) {
val diff = summarizeDiff(expected, actual)
val message = """API definition has changed
Declared definition is $expected
True definition is $actual
Please run `./gradlew updateApi` to confirm these changes are
intentional by updating the API definition.
Difference between these files:
$diff"""
throw GradleException(message)
}
}
| buildSrc/private/src/main/kotlin/androidx/build/metalava/CheckApiEquivalenceTask.kt | 267141412 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb
/** Interface for controller client session that is established between nearby UWB devices. */
interface UwbControllerSessionScope : UwbClientSessionScope {
/**
* The local device's complex channel which can be used for ranging.
*
* A complex channel can only be used for a single ranging session. After the ranging session
* is ended, a new channel will be allocated.
*
* Ranging session duration may also be limited to prevent channels from being used for too
* long. In this case, your ranging session would be suspended and clients would need to
* exchange the new channel with their peer before starting again.
*/
val uwbComplexChannel: UwbComplexChannel
/**
* Dynamically adds a controlee to an active ranging session. The controlee to be added
* must be configured with the a set of parameters that can join the existing connection.
*
* @throws [IllegalStateException] if the ranging is inactive or if the ranging profile
* is that of a unicast profile.
*
* Otherwise, this method will return successfully, and clients are expected to handle either
* [RangingResult.RangingResultPosition] or [RangingResult.RangingResultPeerDisconnected] to
* listen for starts or failures.
*/
suspend fun addControlee(address: UwbAddress)
/**
* Dynamically removes a controlee from an active ranging session.
*
* @throws [IllegalStateException] if the ranging is inactive, if the ranging profile is
* that of a unicast profile, or if the requested device is not being ranged to.
*
* @throws [androidx.core.uwb.exceptions.UwbSystemCallbackException] if the operation failed
* due to hardware or firmware issues.
*
* Otherwise, this method will return successfully, and clients are expected to handle
* [RangingResult.RangingResultPeerDisconnected] to listen for disconnects.
*/
suspend fun removeControlee(address: UwbAddress)
} | core/uwb/uwb/src/main/java/androidx/core/uwb/UwbControllerSessionScope.kt | 3223881193 |
/*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtmp.utils
/**
* Created by pedro on 26/04/21.
*/
object RtmpConfig {
const val DEFAULT_CHUNK_SIZE = 128
var writeChunkSize = DEFAULT_CHUNK_SIZE
var acknowledgementWindowSize = 0
} | rtmp/src/main/java/com/pedro/rtmp/utils/RtmpConfig.kt | 3767443923 |
package com.mocoven.heykotlin.playground
/**
* Created by Mocoven on 16/08/2018.
*/
data class Node(val name: String, val left: Node?, val right: Node?)
val d = Node("d", null, null)
val b = Node("b", null, d)
val c = Node("c", d, null)
val a = Node("a", b, c)
val graph = listOf(a, b, c, d)
var visited: MutableList<Node> = mutableListOf()
fun depthFirst() {
graph.forEach {
if (!visited.contains(it)) {
visitWho(it)
}
}
}
fun visitWho(who: Node) {
if (!visited.contains(who)) {
visited.add(who)
println("visiting ${who.name}")
if (who.left != null) {
visitWho(who.left)
} else if (who.right != null) {
visitWho(who.right)
}
}
} | app/src/main/java/com/mocoven/heykotlin/playground/DepthFirstTraverse.kt | 257753298 |
package diff.patch.accessors
import diff.patch.Getter
import diff.patch.Setter
/**
* @author sebasjm <smarchano></smarchano>@primary.com.ar>
*/
class SimpleGetterSetter<Type: Any>(internal var obj: Type?) : Getter<Type>, Setter<Type> {
override fun get(): Type? {
return obj
}
override fun set(value: Type) {
obj = value
}
}
| src/main/kotlin/diff/patch/accessors/SimpleGetterSetter.kt | 72451304 |
/*******************************************************************************
* Copyright 2000-2014 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.core.resolve.lang.java.structure
import org.eclipse.jdt.core.dom.IVariableBinding
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.load.java.structure.JavaField
import org.jetbrains.kotlin.load.java.structure.JavaType
public class EclipseJavaField(private val javaField: IVariableBinding) : EclipseJavaMember<IVariableBinding>(javaField), JavaField {
override val hasConstantNotNullInitializer: Boolean
get() = false
override val initializerValue: Any?
get() = null
override val isEnumEntry: Boolean = binding.isEnumConstant()
override val type: JavaType
get() = EclipseJavaType.create(binding.getType())
override val containingClass: JavaClass
get() = EclipseJavaClass(binding.getDeclaringClass())
} | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/resolve/lang/java/structure/EclipseJavaField.kt | 2510445462 |
package me.proxer.app.anime.resolver
import io.reactivex.Single
import me.proxer.app.exception.StreamResolutionException
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.toPrefixedUrlOrNull
/**
* @author Ruben Gees
*/
object SteamStreamResolver : StreamResolver() {
override val name = "Steam"
override fun resolve(id: String): Single<StreamResolutionResult> = api.anime.link(id)
.buildSingle()
.map { StreamResolutionResult.Link(it.toPrefixedUrlOrNull() ?: throw StreamResolutionException()) }
}
| src/main/kotlin/me/proxer/app/anime/resolver/SteamStreamResolver.kt | 1047405278 |
/*
* Copyright (C) 2014 yvolk (Yuri Volkov), 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.note
import android.content.Intent
import android.view.View
import android.widget.TextView
import org.andstatus.app.ActivityTestHelper
import org.andstatus.app.R
import org.andstatus.app.account.MyAccount
import org.andstatus.app.activity.ActivityViewItem
import org.andstatus.app.context.DemoData
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.context.TestSuite
import org.andstatus.app.data.TextMediaType
import org.andstatus.app.origin.Origin
import org.andstatus.app.origin.OriginType
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.timeline.TimelineActivity
import org.andstatus.app.timeline.TimelineActivityTest
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.MyHtmlTest
import org.andstatus.app.util.MyLog
import org.junit.Assert
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.properties.Delegates
/**
* On activity testing: http://developer.android.com/tools/testing/activity_testing.html
* @author [email protected]
*/
class NoteEditorTwitterTest : TimelineActivityTest<ActivityViewItem>() {
private val myContext: MyContext = TestSuite.initializeWithAccounts(this)
private var data: NoteEditorData by Delegates.notNull()
override fun getActivityIntent(): Intent {
MyLog.i(this, "setUp started")
if (editingStep.get() != 1) {
MyPreferences.setBeingEditedNoteId(0)
}
val ma: MyAccount = DemoData.demoData.getMyAccount(DemoData.demoData.twitterTestAccountName)
Assert.assertTrue(ma.isValid)
Assert.assertEquals("Account should be in Twitter: $ma", OriginType.TWITTER, ma.origin.originType)
myContext.accounts.setCurrentAccount(ma)
data = getStaticData(ma)
MyLog.i(this, "setUp ended")
return Intent(Intent.ACTION_VIEW,
myContext.timelines.get(TimelineType.HOME, ma.actor, Origin.EMPTY).getUri())
}
private fun getStaticData(ma: MyAccount): NoteEditorData {
return NoteEditorData.Companion.newEmpty(ma)
.setContent(MyHtmlTest.twitterBodyTypedPlain + " " + DemoData.demoData.testRunUid, TextMediaType.PLAIN)
}
@Test
fun testEditing1() {
Assert.assertTrue("MyService is available", MyServiceManager.Companion.isServiceAvailable())
editingTester()
}
@Test
fun testEditing2() {
editingTester()
}
private fun editingTester() {
TestSuite.waitForListLoaded(activity, 2)
when (editingStep.incrementAndGet()) {
2 -> editingStep2()
else -> {
editingStep.set(1)
ActivityTestHelper.openEditor("default", activity)
editingStep1()
}
}
MyLog.v(this, "After step $editingStep ended")
}
private fun editingStep1() {
val method = "editingStep1"
MyLog.v(this, "$method started")
val editorView: View = ActivityTestHelper.hideEditorAndSaveDraft(method, activity)
val editor = activity.getNoteEditor() ?: throw IllegalStateException("No editor")
getInstrumentation().runOnMainSync { editor.startEditingNote(data) }
ActivityTestHelper.waitViewVisible(method, editorView)
assertInitialText("Initial text")
MyLog.v(this, "$method ended")
}
private fun editingStep2() {
val method = "editingStep2"
MyLog.v(this, "$method started")
val editorView = activity.findViewById<View?>(R.id.note_editor)
ActivityTestHelper.waitViewVisible("$method; Restored note is visible", editorView)
assertInitialText("Note restored")
ActivityTestHelper.hideEditorAndSaveDraft(method, activity)
ActivityTestHelper.openEditor(method, activity)
assertTextCleared()
val helper = ActivityTestHelper<TimelineActivity<*>>(activity)
helper.clickMenuItem("$method click Discard", R.id.discardButton)
ActivityTestHelper.waitViewInvisible("$method; Editor hidden after discard", editorView)
MyLog.v(this, "$method ended")
}
private fun assertInitialText(description: String) {
val editor = activity.getNoteEditor() ?: throw IllegalStateException("No editor")
val textView = activity.findViewById<TextView?>(R.id.noteBodyEditText)
ActivityTestHelper.waitTextInAView(description, textView,
MyHtml.fromContentStored(data.getContent(), TextMediaType.PLAIN))
Assert.assertEquals(description, data.toTestSummary(), editor.getData().toTestSummary())
}
private fun assertTextCleared() {
val editor = activity.getNoteEditor() ?: throw IllegalStateException("No editor")
Assert.assertEquals(NoteEditorData.Companion.newEmpty(
activity.myContext.accounts.currentAccount).toTestSummary(),
editor.getData().toTestSummary())
}
companion object {
private val editingStep: AtomicInteger = AtomicInteger()
}
}
| app/src/androidTest/kotlin/org/andstatus/app/note/NoteEditorTwitterTest.kt | 2535434558 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint
import com.demonwav.mcdev.platform.mixin.reference.isMiscDynamicSelector
import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SLICE
import com.demonwav.mcdev.platform.mixin.util.findSourceElement
import com.demonwav.mcdev.util.computeStringArray
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiQualifiedReference
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.parentOfType
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
/**
* Resolves targets of @At.
*
* Resolution of this reference depends on @At.value(), each of which have their own [InjectionPoint]. This injection
* point is in charge of parsing, validating and resolving this reference.
*
* This reference can be resolved in four different ways.
* - [isUnresolved] only checks the bytecode of the target class, to check whether this reference is valid.
* - [TargetReference.resolveReference] resolves to the actual member being targeted, rather than the location it's
* referenced in the target method. This serves as a backup in case nothing else is found to navigate to, and so that
* find usages can take you back to this reference.
* - [collectTargetVariants] is used for auto-completion. It does not take into account what is actually in the target
* string, and instead matches everything the handler *could* match. The references resolve similarly to
* `resolveReference`, although new elements may be created if not found.
* - [resolveNavigationTargets] is used when the user attempts to navigate on this reference. This attempts to take you
* to the actual location in the source code of the target class which is being targeted. Potentially slow as it may
* decompile the target class.
*
* To support the above, injection points must be able to resolve the target element, and support a collect visitor and
* a navigation visitor. The collect visitor finds target instructions in the bytecode of the target method, and the
* navigation visitor makes a best-effort attempt at matching source code elements.
*/
class AtResolver(
private val at: PsiAnnotation,
private val targetClass: ClassNode,
private val targetMethod: MethodNode
) {
companion object {
private fun getInjectionPoint(at: PsiAnnotation): InjectionPoint<*>? {
var atCode = at.findDeclaredAttributeValue("value")?.constantStringValue ?: return null
// remove slice selector
val isInSlice = at.parentOfType<PsiAnnotation>()?.hasQualifiedName(SLICE) ?: false
if (isInSlice) {
if (SliceSelector.values().any { atCode.endsWith(":${it.name}") }) {
atCode = atCode.substringBeforeLast(':')
}
}
return InjectionPoint.byAtCode(atCode)
}
fun usesMemberReference(at: PsiAnnotation): Boolean {
val handler = getInjectionPoint(at) ?: return false
return handler.usesMemberReference()
}
fun getArgs(at: PsiAnnotation): Map<String, String> {
val args = at.findAttributeValue("args")?.computeStringArray() ?: return emptyMap()
return args.asSequence()
.map {
val parts = it.split('=', limit = 2)
if (parts.size == 1) {
parts[0] to ""
} else {
parts[0] to parts[1]
}
}
.toMap()
}
}
fun isUnresolved(): InsnResolutionInfo.Failure? {
val injectionPoint = getInjectionPoint(at)
?: return null // we don't know what to do with custom handlers, assume ok
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val collectVisitor = injectionPoint.createCollectVisitor(
at,
target,
targetClass,
CollectVisitor.Mode.MATCH_FIRST
)
if (collectVisitor == null) {
// syntax error in target
val stringValue = targetAttr?.constantStringValue ?: return InsnResolutionInfo.Failure()
return if (isMiscDynamicSelector(at.project, stringValue)) {
null
} else {
InsnResolutionInfo.Failure()
}
}
collectVisitor.visit(targetMethod)
return if (collectVisitor.result.isEmpty()) {
InsnResolutionInfo.Failure(collectVisitor.filterToBlame)
} else {
null
}
}
fun resolveInstructions(mode: CollectVisitor.Mode = CollectVisitor.Mode.MATCH_ALL): List<CollectVisitor.Result<*>> {
return (getInstructionResolutionInfo(mode) as? InsnResolutionInfo.Success)?.results ?: emptyList()
}
fun getInstructionResolutionInfo(mode: CollectVisitor.Mode = CollectVisitor.Mode.MATCH_ALL): InsnResolutionInfo {
val injectionPoint = getInjectionPoint(at) ?: return InsnResolutionInfo.Failure()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val collectVisitor = injectionPoint.createCollectVisitor(at, target, targetClass, mode)
?: return InsnResolutionInfo.Failure()
collectVisitor.visit(targetMethod)
val result = collectVisitor.result
return if (result.isEmpty()) {
InsnResolutionInfo.Failure(collectVisitor.filterToBlame)
} else {
InsnResolutionInfo.Success(result)
}
}
fun resolveNavigationTargets(): List<PsiElement> {
// First resolve the actual target in the bytecode using the collect visitor
val injectionPoint = getInjectionPoint(at) ?: return emptyList()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
val bytecodeResults = resolveInstructions()
// Then attempt to find the corresponding source elements using the navigation visitor
val targetElement = targetMethod.findSourceElement(
targetClass,
at.project,
GlobalSearchScope.allScope(at.project),
canDecompile = true
) ?: return emptyList()
val targetPsiClass = targetElement.parentOfType<PsiClass>() ?: return emptyList()
val navigationVisitor = injectionPoint.createNavigationVisitor(at, target, targetPsiClass) ?: return emptyList()
targetElement.accept(navigationVisitor)
return bytecodeResults.mapNotNull { bytecodeResult ->
navigationVisitor.result.getOrNull(bytecodeResult.index)
}
}
fun collectTargetVariants(completionHandler: (LookupElementBuilder) -> LookupElementBuilder): List<Any> {
val injectionPoint = getInjectionPoint(at) ?: return emptyList()
val targetAttr = at.findAttributeValue("target")
val target = targetAttr?.let { parseMixinSelector(it) }
// Collect all possible targets
fun <T : PsiElement> doCollectVariants(injectionPoint: InjectionPoint<T>): List<Any> {
val visitor = injectionPoint.createCollectVisitor(at, target, targetClass, CollectVisitor.Mode.COMPLETION)
?: return emptyList()
visitor.visit(targetMethod)
return visitor.result
.mapNotNull { result ->
injectionPoint.createLookup(targetClass, result)?.let { completionHandler(it) }
}
}
return doCollectVariants(injectionPoint)
}
}
sealed class InsnResolutionInfo {
class Success(val results: List<CollectVisitor.Result<*>>) : InsnResolutionInfo()
class Failure(val filterToBlame: String? = null) : InsnResolutionInfo() {
infix fun combine(other: Failure): Failure {
return if (filterToBlame != null) {
this
} else {
other
}
}
}
}
enum class SliceSelector {
FIRST, LAST, ONE
}
object QualifiedMember {
fun resolveQualifier(reference: PsiQualifiedReference): PsiClass? {
val qualifier = reference.qualifier ?: return null
((qualifier as? PsiReference)?.resolve() as? PsiClass)?.let { return it }
((qualifier as? PsiExpression)?.type as? PsiClassType)?.resolve()?.let { return it }
return null
}
}
| src/main/kotlin/platform/mixin/handlers/injectionPoint/AtResolver.kt | 353811689 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.shadow
import com.demonwav.mcdev.framework.EdtInterceptor
import com.demonwav.mcdev.platform.mixin.BaseMixinTest
import com.demonwav.mcdev.platform.mixin.inspection.shadow.ShadowModifiersInspection
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(EdtInterceptor::class)
@DisplayName("Shadow Modifiers Inspection Tests")
class ShadowModifiersInspectionTest : BaseMixinTest() {
@Test
@DisplayName("Shadow Modifiers Inspection Test")
fun shadowModifiersInspectionTest() {
buildProject {
java(
"ShadowData.java",
"""
package test;
import com.demonwav.mcdev.mixintestdata.shadow.MixinBase;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Final;
@Mixin(MixinBase.class)
public class ShadowData {
@Shadow @Final private String privateFinalString;
@Shadow private String privateString;
@Shadow @Final protected String protectedFinalString;
@Shadow protected String protectedString;
@Shadow @Final String packagePrivateFinalString;
@Shadow String packagePrivateString;
@Shadow @Final public String publicFinalString;
@Shadow public String publicString;
@Shadow <warning descr="Invalid access modifiers, has: public, but target member has: protected">public</warning> String wrongAccessor;
<warning descr="@Shadow for final member should be annotated as @Final">@Shadow</warning> protected String noFinal;
@Shadow public String nonExistent;
<warning descr="@Shadow for final member should be annotated as @Final">@Shadow</warning> <warning descr="Invalid access modifiers, has: protected, but target member has: public">protected</warning> String twoIssues;
}
"""
)
}
fixture.enableInspections(ShadowModifiersInspection::class)
fixture.checkHighlighting(true, false, false)
}
}
| src/test/kotlin/platform/mixin/shadow/ShadowModifiersInspectionTest.kt | 488088154 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.trigger
import android.os.Bundle
import android.support.v7.preference.Preference
import android.view.View
import com.pyamsoft.powermanager.Injector
import com.pyamsoft.powermanager.R
import com.pyamsoft.powermanager.service.ForegroundService
import com.pyamsoft.powermanager.uicore.WatchedPreferenceFragment
import javax.inject.Inject
class PowerTriggerPreferenceFragment : WatchedPreferenceFragment() {
@field:Inject internal lateinit var presenter: TriggerPreferencePresenter
private lateinit var triggerInterval: Preference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Injector.with(context) {
it.inject(this)
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.power_trigger_options)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
triggerInterval = findPreference(getString(R.string.trigger_period_key))
}
override fun onStart() {
super.onStart()
presenter.clickEvent(triggerInterval, {
ForegroundService.restartTriggers(context)
})
}
override fun onStop() {
super.onStop()
presenter.stop()
}
override fun onDestroy() {
super.onDestroy()
presenter.destroy()
}
companion object {
const val TAG = "PowerTriggerPreferenceFragment"
}
}
| powermanager/src/main/java/com/pyamsoft/powermanager/trigger/PowerTriggerPreferenceFragment.kt | 3121457708 |
package com.wealthfront.magellan.navigation
import android.content.Context
import android.view.View
public interface ViewTemplateApplier {
public fun onViewCreated(context: Context, view: View): View
}
public interface Navigator {
public val backStack: List<NavigationEvent>
public fun goBack(): Boolean
}
| magellan-library/src/main/java/com/wealthfront/magellan/navigation/Navigator.kt | 3566561422 |
/*
* Copyright (c) 2016 Senic GmbH. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.senic.nuimo
class NuimoBuiltInLedMatrix : NuimoLedMatrix {
companion object {
@JvmField
val BUSY = NuimoBuiltInLedMatrix(1)
}
private constructor(byte: Byte) : super(byte.toMatrixBits())
override fun equals(other: Any?): Boolean {
if (other is NuimoBuiltInLedMatrix) {
return super.equals(other)
}
return super.equals(other)
}
override fun hashCode(): Int = super.hashCode() * 31
}
private fun Byte.toMatrixBits() : Array<Boolean> {
val bits = Array(NuimoLedMatrix.LED_COUNT, { false })
var n = toInt()
var i = 0
while (n > 0) {
bits[i] = n % 2 > 0
n /= 2
i += 1
}
return bits
}
| nuimo/src/main/kotlin/com/senic/nuimo/NuimoBuiltInLedMatrix.kt | 3788977409 |
package de.tum.`in`.tumcampusapp.utils
import android.content.ContentProviderOperation
import android.content.Context
import android.content.OperationApplicationException
import android.graphics.Bitmap
import android.os.RemoteException
import android.provider.ContactsContract
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.tumui.person.model.Contact
import de.tum.`in`.tumcampusapp.component.tumui.person.model.Employee
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
class ContactsHelper {
companion object {
@JvmStatic fun saveToContacts(context: Context, employee: Employee) {
val ops = ArrayList<ContentProviderOperation>()
val rawContactID = ops.size
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build())
// Add full name
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, employee.title)
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, employee.name)
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, employee.surname)
.build())
// Add e-mail address
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, employee.email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build())
val substations = employee.telSubstations
if (substations != null) {
for ((number) in substations) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
.build())
}
}
// Add work: telephone, mobile, fax, website
addContact(ops, rawContactID, employee.businessContact, true)
// Add home: telephone, mobile, fax, website
addContact(ops, rawContactID, employee.privateContact, false)
// Add organisations
employee.groups?.let { groups ->
groups.forEach { group ->
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, group.org)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, group.title)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
.build())
}
}
// Add office hours
val notes = StringBuilder()
notes.append(context.getString(R.string.office_hours))
.append(": ")
.append(employee.consultationHours)
// saveToContacts all rooms
val rooms = employee.rooms
if (rooms != null && !rooms.isEmpty()) {
if (!notes.toString()
.isEmpty()) {
notes.append('\n')
}
notes.append(context.getString(R.string.room))
.append(": ")
.append(rooms[0]
.location)
.append(" (")
.append(rooms[0]
.number)
.append(')')
}
// Finally saveToContacts notes
if (!notes.toString()
.isEmpty()) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, notes.toString())
.build())
}
// Add image
val bitmap = employee.image
if (bitmap != null) { // If an image is selected successfully
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream)
// Adding insert operation to operations list
// to insert Photo in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray())
.build())
try {
stream.flush()
} catch (e: IOException) {
Utils.log(e)
}
}
// Executing all the insert operations as a single database transaction
try {
context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)
Utils.showToast(context, R.string.contact_added)
} catch (e: RemoteException) {
Utils.log(e)
} catch (e: OperationApplicationException) {
Utils.log(e)
}
}
private fun addContact(ops: MutableCollection<ContentProviderOperation>, rawContactID: Int, contact: Contact?, work: Boolean) {
if (contact != null) {
// Add work telephone number
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.telefon)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
if (work) ContactsContract.CommonDataKinds.Phone.TYPE_WORK else ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
.build())
// Add work mobile number
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.mobilephone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
if (work) ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE else ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build())
// Add work fax number
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.fax)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
if (work) ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK else ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME)
.build())
// Add website
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Website.URL, contact.homepage)
.withValue(ContactsContract.CommonDataKinds.Website.TYPE,
if (work) ContactsContract.CommonDataKinds.Website.TYPE_WORK else ContactsContract.CommonDataKinds.Website.TYPE_HOME)
.build())
}
}
}
} | app/src/main/java/de/tum/in/tumcampusapp/utils/ContactsHelper.kt | 4135735850 |
package bteelse.com.br.amipyscho.logic.resultado
import android.content.Context
import android.widget.ImageView
/**
* Created by Felipe on 5/12/2017.
*/
interface RegraResultado {
fun retornaParaUsuario(ctx: Context): String
fun imagemAoFimDoJogo(ctx: Context, imagemNaoPsicopata: ImageView, tracoPsicopatia: ImageView, psicopata: ImageView)
}
| app/src/main/java/bteelse/com/br/amipyscho/logic/resultado/RegraResultado.kt | 1751884438 |
/*
* Copyright (C) 2016-2018, 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.flwor.XpmForBinding
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryForClause
class XQueryForClausePsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node), XQueryForClause, XpmSyntaxValidationElement {
override val bindings: Sequence<XpmForBinding>
get() = children().filterIsInstance<XpmForBinding>()
override val conformanceElement: PsiElement
get() = firstChild
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryForClausePsiImpl.kt | 2609456193 |
package com.habitrpg.android.habitica.ui.viewHolders
import android.annotation.SuppressLint
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.PopupMenu
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.PartyMemberBinding
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class GroupMemberViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), PopupMenu.OnMenuItemClickListener {
private val binding = PartyMemberBinding.bind(itemView)
private var currentUserID: String? = null
private var leaderID: String? = null
var onClickEvent: (() -> Unit)? = null
var sendMessageEvent: (() -> Unit)? = null
var removeMemberEvent: (() -> Unit)? = null
var transferOwnershipEvent: (() -> Unit)? = null
init {
binding.buffIconView.setImageBitmap(HabiticaIconsHelper.imageOfBuffIcon())
itemView.setOnClickListener { onClickEvent?.invoke() }
binding.moreButton.setOnClickListener { showOptionsPopup() }
}
private fun showOptionsPopup() {
val popup = PopupMenu(itemView.context, binding.moreButton)
popup.setOnMenuItemClickListener(this)
val inflater = popup.menuInflater
inflater.inflate(R.menu.party_member_menu, popup.menu)
popup.menu.findItem(R.id.transfer_ownership).isVisible = currentUserID == leaderID
popup.menu.findItem(R.id.remove).isVisible = currentUserID == leaderID
popup.show()
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.send_message -> { sendMessageEvent?.invoke() }
R.id.transfer_ownership -> { transferOwnershipEvent?.invoke() }
R.id.remove -> { removeMemberEvent?.invoke() }
}
return true
}
@SuppressLint("SetTextI18n")
fun bind(user: Member, leaderID: String?, userID: String?) {
binding.avatarView.setAvatar(user)
this.leaderID = leaderID
this.currentUserID = userID
if (user.id == userID) {
binding.youPill.visibility = View.VISIBLE
binding.moreButton.visibility = View.GONE
} else {
binding.youPill.visibility = View.GONE
binding.moreButton.visibility = View.VISIBLE
}
user.stats?.let {
binding.healthBar.set(it.hp ?: 0.0, it.maxHealth?.toDouble() ?: 50.0)
binding.healthTextview.text = "${it.hp?.toInt()} / ${it.maxHealth}"
binding.experienceBar.set(it.exp ?: 0.0, it.toNextLevel?.toDouble() ?: 0.0)
binding.experienceTextview.text = "${it.exp?.toInt()} / ${it.toNextLevel}"
binding.manaBar.set(it.mp ?: 0.0, it.maxMP?.toDouble() ?: 0.0)
binding.manaTextview.text = "${it.mp?.toInt()} / ${it.maxMP}"
}
binding.displayNameTextview.username = user.profile?.name
binding.displayNameTextview.tier = user.contributor?.level ?: 0
if (user.hasClass) {
binding.sublineTextview.text = itemView.context.getString(R.string.user_level_with_class, user.stats?.lvl, user.stats?.getTranslatedClassName(itemView.context.resources))
} else {
binding.sublineTextview.text = itemView.context.getString(R.string.user_level, user.stats?.lvl)
}
if (user.stats?.isBuffed == true) {
binding.buffIconView.visibility = View.VISIBLE
} else {
binding.buffIconView.visibility = View.GONE
}
binding.classIconView.visibility = View.VISIBLE
when (user.stats?.habitClass) {
Stats.HEALER -> {
binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfHealerLightBg())
}
Stats.WARRIOR -> {
binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfWarriorLightBg())
}
Stats.ROGUE -> {
binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfRogueLightBg())
}
Stats.MAGE -> {
binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfMageLightBg())
}
else -> {
binding.classIconView.visibility = View.INVISIBLE
}
}
itemView.isClickable = true
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/GroupMemberViewHolder.kt | 2689557391 |
package org.mtransit.android.commons
import android.content.Context
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.UpdateAvailability
import org.json.JSONObject
import org.mtransit.android.commons.provider.GTFSProvider
import org.mtransit.android.commons.receiver.DataChange
import org.mtransit.commons.StringUtils
import java.util.concurrent.TimeUnit
object AppUpdateUtils : MTLog.Loggable {
val LOG_TAG: String = AppUpdateUtils::class.java.simpleName
private const val FORCE_CHECK_IN_DEBUG = false
// private const val FORCE_CHECK_IN_DEBUG = true // DEBUG
private const val FORCE_UPDATE_AVAILABLE = false
// private const val FORCE_UPDATE_AVAILABLE = true // DEBUG
override fun getLogTag(): String = LOG_TAG
private const val PREF_KEY_AVAILABLE_VERSION_CODE = "pAvailableVersionCode"
private const val PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS = "pAvailableVersionCodeLastCheckInMs"
@JvmStatic
@JvmOverloads
fun getAvailableVersionCode(
context: Context,
filterS: String? = null,
): Int {
return getLastAvailableVersionCode(context, -1).also { lastAvailableVersionCode ->
triggerRefreshIfNecessary(context, lastAvailableVersionCode, AppUpdateFilter.fromJSONString(filterS))
}
}
@Suppress("unused")
private fun hasLastAvailableVersionCode(
context: Context
): Boolean {
return PreferenceUtils.hasPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE)
}
@Suppress("SameParameterValue")
private fun getLastAvailableVersionCode(
context: Context,
defaultValue: Int = PackageManagerUtils.getAppVersionCode(context)
): Int {
return PreferenceUtils.getPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE, defaultValue)
}
private fun setAvailableVersionCode(
context: Context,
lastVersionCode: Int = -1,
newVersionCode: Int = PackageManagerUtils.getAppVersionCode(context),
sync: Boolean = false
) {
MTLog.v(this, "setAvailableVersionCode($newVersionCode)") // DEBUG
if (lastVersionCode == newVersionCode) {
MTLog.d(this, "setAvailableVersionCode() > SKIP (same version code)")
return
}
PreferenceUtils.savePrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE, newVersionCode, sync)
}
private fun getLastCheckInMs(
context: Context,
defaultValue: Long = -1L
): Long {
return PreferenceUtils.getPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS, defaultValue)
}
private fun setLastCheckInMs(
context: Context,
lastCheckInMs: Long = TimeUtils.currentTimeMillis(),
sync: Boolean = false
) {
MTLog.v(this, "setLastCheckInMs($lastCheckInMs)") // DEBUG
PreferenceUtils.savePrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS, lastCheckInMs, sync)
}
private fun setAvailableVersionCodeAndLastCheckInMs(
context: Context,
lastVersionCode: Int = -1,
newVersionCode: Int = PackageManagerUtils.getAppVersionCode(context),
lastCheckInMs: Long = TimeUtils.currentTimeMillis(),
sync: Boolean = false
) {
MTLog.v(this, "setAvailableVersionCodeAndLastCheckInMs($lastVersionCode, $newVersionCode, $lastCheckInMs)") // DEBUG
setAvailableVersionCode(context, lastVersionCode, newVersionCode, sync)
setLastCheckInMs(context, lastCheckInMs, sync)
}
private fun triggerRefreshIfNecessary(
context: Context,
lastAvailableVersionCode: Int,
filter: AppUpdateFilter? = null
) {
if (!FORCE_CHECK_IN_DEBUG && BuildConfig.DEBUG) {
MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (DEBUG build)")
return // NO WORKING FOR DEBUG BUILDS
}
val currentVersionCode = PackageManagerUtils.getAppVersionCode(context)
if (currentVersionCode in 1 until lastAvailableVersionCode) { // IF current valid & current < last DO
MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (new version code already available ($lastAvailableVersionCode > $currentVersionCode))")
return // UPDATE ALREADY AVAILABLE
}
val lastCheckInMs = getLastCheckInMs(context)
MTLog.d(this, "lastCheckInMs: $lastCheckInMs") // DEBUG
val shortTimeAgo = TimeUtils.currentTimeMillis() - TimeUnit.HOURS.toMillis(if (filter?.inFocus == true) 6L else 24L)
MTLog.d(this, "shortTimeAgo: $shortTimeAgo") // DEBUG
if (filter?.forceRefresh != true // not force refresh
&& lastAvailableVersionCode > 0 // last = valid
&& shortTimeAgo < lastCheckInMs // too recent
) {
val timeLapsedInHours = TimeUnit.MILLISECONDS.toHours(TimeUtils.currentTimeMillis() - lastCheckInMs)
MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (last successful refresh too recent ($timeLapsedInHours hours)")
return // LAST REFRESH TOO RECENT
}
if (FORCE_UPDATE_AVAILABLE) {
val newAvailableVersionCode = 1 + if (lastAvailableVersionCode > 0) lastAvailableVersionCode else currentVersionCode
MTLog.d(this, "triggerRefreshIfNecessary() > FORCE_UPDATE_AVAILABLE to $newAvailableVersionCode.")
setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, newAvailableVersionCode, TimeUtils.currentTimeMillis())
broadcastUpdateAvailable(lastAvailableVersionCode, currentVersionCode, newAvailableVersionCode, context)
return // USE DEBUG FORCE UPDATE++
}
val appUpdateManager = AppUpdateManagerFactory.create(context)
val appUpdateInfoTask = appUpdateManager.appUpdateInfo
appUpdateInfoTask.addOnCompleteListener { task -> // ASYNC
if (!task.isSuccessful) {
if (BuildConfig.DEBUG) {
MTLog.d(this, task.exception, "App update info did NOT complete successfully!")
} else {
MTLog.w(this, task.exception, "App update info did NOT complete successfully!")
}
return@addOnCompleteListener
}
val appUpdateInfo = task.result ?: return@addOnCompleteListener
when (appUpdateInfo.updateAvailability()) {
UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> {
MTLog.d(this, "Update in progress already triggered by developer")
}
UpdateAvailability.UNKNOWN -> {
MTLog.d(this, "Update status unknown")
}
UpdateAvailability.UPDATE_NOT_AVAILABLE -> {
MTLog.d(this, "Update NOT available")
if (currentVersionCode > 0) {
setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, currentVersionCode, TimeUtils.currentTimeMillis())
}
}
UpdateAvailability.UPDATE_AVAILABLE -> {
MTLog.d(this, "Update available")
val newAvailableVersionCode = appUpdateInfo.availableVersionCode()
if (newAvailableVersionCode > 0) {
setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, newAvailableVersionCode, TimeUtils.currentTimeMillis())
broadcastUpdateAvailable(lastAvailableVersionCode, currentVersionCode, newAvailableVersionCode, context)
}
}
}
}
}
private fun broadcastUpdateAvailable(
lastAvailableVersionCode: Int,
currentVersionCode: Int,
newAvailableVersionCode: Int,
context: Context
) {
if ((lastAvailableVersionCode == -1 || lastAvailableVersionCode == currentVersionCode) // last was unknown OR same as current
&& newAvailableVersionCode > lastAvailableVersionCode // AND new is newer than last => available update just discovered
) {
DataChange.broadcastDataChange(context, GTFSProvider.getAUTHORITY(context), context.packageName, true) // trigger update in MT
}
}
data class AppUpdateFilter(
val forceRefresh: Boolean = false,
val inFocus: Boolean = false
) {
companion object {
private const val JSON_FORCE_REFRESH = "force_refresh"
private const val JSON_IN_FOCUS = "in_focus"
@JvmStatic
fun fromJSONString(filterS: String?): AppUpdateFilter {
try {
if (!filterS.isNullOrBlank()) {
val json = JSONObject(filterS)
return AppUpdateFilter(
forceRefresh = json.optBoolean(JSON_FORCE_REFRESH, false),
inFocus = json.optBoolean(JSON_IN_FOCUS, false)
)
}
} catch (e: Exception) {
MTLog.w(LOG_TAG, e, "Error while parsing app update filter '$filterS'!")
}
return AppUpdateFilter() // DEFAULT VALUES
}
@JvmStatic
fun toJSONString(filter: AppUpdateFilter?): String {
return try {
JSONObject().apply {
put(JSON_FORCE_REFRESH, filter?.forceRefresh)
put(JSON_IN_FOCUS, filter?.inFocus)
}.toString()
} catch (e: Exception) {
MTLog.w(LOG_TAG, e, "Error while serializing app update filter '$filter'!")
StringUtils.EMPTY
}
}
}
@Suppress("unused")
fun toJSONString() = toJSONString(this)
}
} | src/main/java/org/mtransit/android/commons/AppUpdateUtils.kt | 1392785806 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class FormatTest : WordSpec() {
companion object {
val LINE_SEPARATOR = System.getProperty("line.separator") ?: "\n";
}
init {
"create table" should {
"format well" {
val source =
"CREATE TABLE SYSTEM_CURRENCY_RATE_HISTORY (CREATED_DATE DATETIME NULL,LAST_MODIFIED_DATE DATETIME NULL,RATE NUMERIC(28) NULL,VERSION NUMERIC(19) NOT NULL,REFERENCE_ID VARCHAR(255) NOT NULL,CREATED_BY VARCHAR(36) NULL,LAST_MODIFIED_BY VARCHAR(36) NULL,PRIMARY KEY (VERSION,REFERENCE_ID));";
val expected = """CREATE TABLE SYSTEM_CURRENCY_RATE_HISTORY (
CREATED_DATE DATETIME NULL,
LAST_MODIFIED_DATE DATETIME NULL,
RATE NUMERIC(28) NULL,
VERSION NUMERIC(19) NOT NULL,
REFERENCE_ID VARCHAR(255) NOT NULL,
CREATED_BY VARCHAR(36) NULL,
LAST_MODIFIED_BY VARCHAR(36) NULL,
PRIMARY KEY (VERSION, REFERENCE_ID)
);""".trimIndent()
val actual = format(source, LINE_SEPARATOR)
actual shouldBe expected
}
"format well with options" {
val source =
"CREATE TEMPORARY TABLE SYSTEM_CURRENCY_RATE_HISTORY (CREATED_DATE DATETIME NULL,LAST_MODIFIED_DATE DATETIME NULL,RATE NUMERIC(28) NULL,VERSION NUMERIC(19) NOT NULL,REFERENCE_ID VARCHAR(255) NOT NULL,CREATED_BY VARCHAR(36) NULL,LAST_MODIFIED_BY VARCHAR(36) NULL,PRIMARY KEY (VERSION,REFERENCE_ID));"
val expected = """CREATE TEMPORARY TABLE SYSTEM_CURRENCY_RATE_HISTORY (
CREATED_DATE DATETIME NULL,
LAST_MODIFIED_DATE DATETIME NULL,
RATE NUMERIC(28) NULL,
VERSION NUMERIC(19) NOT NULL,
REFERENCE_ID VARCHAR(255) NOT NULL,
CREATED_BY VARCHAR(36) NULL,
LAST_MODIFIED_BY VARCHAR(36) NULL,
PRIMARY KEY (VERSION, REFERENCE_ID)
);""".trimIndent()
val actual = format(source, LINE_SEPARATOR)
actual shouldBe expected
}
}
"issue #9" should {
"be fixed illegal syntax" {
val source = "CREATE INDEX INDEX_SYSTEM_CURRENCY_RATE_VERSION DESC ON SYSTEM_CURRENCY_RATE (VERSION DESC);"
val expected = "CREATE INDEX INDEX_SYSTEM_CURRENCY_RATE_VERSION ON SYSTEM_CURRENCY_RATE (VERSION DESC);"
val actual = formatLine(source)
actual shouldBe expected
}
}
}
}
| src/test/kotlin/io/github/divinespear/plugin/FormatTest.kt | 2177486107 |
package nl.shadowlink.tools.shadowmapper
sealed class CommandResult {
object Success : CommandResult()
data class Failed(
val error: String
) : CommandResult()
}
| src/main/java/nl/shadowlink/tools/shadowmapper/CommandResult.kt | 1716625376 |
package org.walleth.request
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_request.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kethereum.erc681.ERC681
import org.kethereum.erc681.generateURL
import org.kethereum.model.ChainId
import org.koin.android.ext.android.inject
import org.ligi.compat.HtmlCompat
import org.ligi.kaxt.setVisibility
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.chains.ChainInfoProvider
import org.walleth.chains.getFaucetURL
import org.walleth.data.addresses.CurrentAddressProvider
import org.walleth.data.exchangerate.ExchangeRateProvider
import org.walleth.data.tokens.CurrentTokenProvider
import org.walleth.data.tokens.isRootToken
import org.walleth.qr.show.getQRCodeIntent
import org.walleth.util.copyToClipboard
import org.walleth.util.setQRCode
import org.walleth.valueview.ValueViewController
class RequestActivity : BaseSubActivity() {
private lateinit var currentERC67String: String
private val currentAddressProvider: CurrentAddressProvider by inject()
private val currentTokenProvider: CurrentTokenProvider by inject()
private val chainInfoProvider: ChainInfoProvider by inject()
private val exchangeRateProvider: ExchangeRateProvider by inject()
private var valueInputController: ValueViewController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_request)
supportActionBar?.subtitle = getString(R.string.request_transaction_subtitle)
valueInputController = object : ValueViewController(value_input, exchangeRateProvider, settings) {
override fun refreshNonValues() {
super.refreshNonValues()
refreshQR()
}
}
lifecycleScope.launch(Dispatchers.Main) {
val initText = if (chainInfoProvider.getCurrent().faucets.isNotEmpty()) {
val faucetURL = chainInfoProvider.getCurrent().getFaucetURL(currentAddressProvider.getCurrentNeverNull())
getString(R.string.request_faucet_message,
chainInfoProvider.getCurrent()!!.name,
faucetURL)
} else {
getString(R.string.no_faucet)
}
request_hint.text = HtmlCompat.fromHtml(initText)
request_hint.movementMethod = LinkMovementMethod()
}
add_value_checkbox.setOnCheckedChangeListener { _, isChecked ->
value_input.setVisibility(isChecked)
refreshQR()
}
receive_qrcode.setOnClickListener {
startActivity(getQRCodeIntent(currentERC67String, showAlternateText = true))
}
}
override fun onResume() {
super.onResume()
refreshQR()
lifecycleScope.launch(Dispatchers.Main) {
valueInputController?.setValue(valueInputController?.getValueOrZero(), currentTokenProvider.getCurrent())
}
}
private fun refreshQR() {
lifecycleScope.launch(Dispatchers.Main) {
val currentToken = currentTokenProvider.getCurrent()
if (!add_value_checkbox.isChecked || currentToken.isRootToken()) {
val relevantAddress = currentAddressProvider.getCurrent()
currentERC67String = ERC681(address = relevantAddress!!.hex).generateURL()
if (add_value_checkbox.isChecked) {
try {
currentERC67String = ERC681(
address = relevantAddress.hex,
value = valueInputController?.getValueOrZero(),
chainId = chainInfoProvider.getCurrent()?.let { ChainId(it.chainId) }
).generateURL()
} catch (e: NumberFormatException) {
}
}
} else {
val relevantAddress = currentToken.address.hex
val userAddress = currentAddressProvider.getCurrentNeverNull().hex
val functionParams = mutableListOf("address" to userAddress)
if (add_value_checkbox.isChecked) {
try {
functionParams.add("uint256" to valueInputController?.getValueOrZero().toString())
} catch (e: NumberFormatException) {
}
}
currentERC67String = ERC681(address = relevantAddress, function = "transfer",
functionParams = functionParams).generateURL()
}
receive_qrcode.setQRCode(currentERC67String)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_request, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_share -> true.also {
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, currentERC67String)
type = "text/plain"
}
startActivity(sendIntent)
}
R.id.menu_copy -> true.also {
copyToClipboard(currentERC67String, receive_qrcode)
}
else -> super.onOptionsItemSelected(item)
}
}
| app/src/main/java/org/walleth/request/RequestActivity.kt | 4122213687 |
package com.marknkamau.justjava.testUtils
import com.marknjunge.core.data.model.*
import com.marknkamau.justjava.data.models.CartItem
import com.marknkamau.justjava.data.models.CartOptionEntity
import com.marknkamau.justjava.data.models.CartProductEntity
object SampleData {
val address = Address(0, "Street", "instructions", "-1,1")
val user = User(1, "fName", "lName", 0L, "254712345678", "[email protected]", "token", "PASSWORD", listOf(address))
val productChoiceOption = ProductChoiceOption(0, 0.0, "Single", "A single shot of coffee")
val productChoice = ProductChoice(0, "Single, double or triple", 0, 1, 0, listOf(productChoiceOption))
val product = Product(
1,
"Americano",
"americano",
"https://res.cloudinary.com/marknjunge/justjava/products/americano.jpg",
1574605132,
120.0,
"Italian espresso gets the American treatment; hot water fills the cup for a rich alternative to drip coffee.",
"coffee",
listOf(productChoice),
"enabled"
)
val cartOptionEntity = CartOptionEntity(0, 0, "Single, double or triple", 0, "Single", 20.0, 0)
val cartItem = CartItem(CartProductEntity(0L, 0L, "Americano", 120.0, 120.0, 1), listOf(cartOptionEntity))
val cartItems = listOf(cartItem)
val verifyOrderResponse = VerifyOrderResponse(0, "error", ErrorType.MISSING, ErrorModel.CHOICE, 0, 200.0)
val orderItem = OrderItem(1, 1, 120.0, 120.0, "Americano", listOf(OrderItemOption(1, "Single, double or triple", 3, 0.0, 44, "Single")))
val order =
Order(null, 1579505466, 120.0, PaymentMethod.MPESA, "AGV7OBST", 1, listOf(orderItem), PaymentStatus.PAID, OrderStatus.PENDING, 0)
} | app/src/androidTest/java/com/marknkamau/justjava/testUtils/SampleData.kt | 2352396547 |
package eu.kanade.presentation.library.components
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.util.fastAny
import eu.kanade.domain.library.model.LibraryManga
import eu.kanade.tachiyomi.ui.library.LibraryItem
@Composable
fun LibraryCoverOnlyGrid(
items: List<LibraryItem>,
showDownloadBadges: Boolean,
showUnreadBadges: Boolean,
showLocalBadges: Boolean,
showLanguageBadges: Boolean,
columns: Int,
contentPadding: PaddingValues,
selection: List<LibraryManga>,
onClick: (LibraryManga) -> Unit,
onLongClick: (LibraryManga) -> Unit,
searchQuery: String?,
onGlobalSearchClicked: () -> Unit,
) {
LazyLibraryGrid(
modifier = Modifier.fillMaxSize(),
columns = columns,
contentPadding = contentPadding,
) {
globalSearchItem(searchQuery, onGlobalSearchClicked)
items(
items = items,
contentType = { "library_only_cover_grid_item" },
) { libraryItem ->
LibraryCoverOnlyGridItem(
item = libraryItem,
showDownloadBadge = showDownloadBadges,
showUnreadBadge = showUnreadBadges,
showLocalBadge = showLocalBadges,
showLanguageBadge = showLanguageBadges,
isSelected = selection.fastAny { it.id == libraryItem.libraryManga.id },
onClick = onClick,
onLongClick = onLongClick,
)
}
}
}
@Composable
fun LibraryCoverOnlyGridItem(
item: LibraryItem,
showDownloadBadge: Boolean,
showUnreadBadge: Boolean,
showLocalBadge: Boolean,
showLanguageBadge: Boolean,
isSelected: Boolean,
onClick: (LibraryManga) -> Unit,
onLongClick: (LibraryManga) -> Unit,
) {
val libraryManga = item.libraryManga
val manga = libraryManga.manga
LibraryGridCover(
modifier = Modifier
.selectedOutline(isSelected)
.combinedClickable(
onClick = {
onClick(libraryManga)
},
onLongClick = {
onLongClick(libraryManga)
},
),
mangaCover = eu.kanade.domain.manga.model.MangaCover(
manga.id,
manga.source,
manga.favorite,
manga.thumbnailUrl,
manga.coverLastModified,
),
item = item,
showDownloadBadge = showDownloadBadge,
showUnreadBadge = showUnreadBadge,
showLocalBadge = showLocalBadge,
showLanguageBadge = showLanguageBadge,
)
}
| app/src/main/java/eu/kanade/presentation/library/components/LibraryCoverOnlyGrid.kt | 1388965051 |
package eu.kanade.tachiyomi.source
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import rx.Observable
interface CatalogueSource : Source {
/**
* An ISO 639-1 compliant language code (two letters in lower case).
*/
override val lang: String
/**
* Whether the source has support for latest updates.
*/
val supportsLatest: Boolean
/**
* Returns an observable containing a page with a list of manga.
*
* @param page the page number to retrieve.
*/
fun fetchPopularManga(page: Int): Observable<MangasPage>
/**
* Returns an observable containing a page with a list of manga.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage>
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
fun fetchLatestUpdates(page: Int): Observable<MangasPage>
/**
* Returns the list of filters for the source.
*/
fun getFilterList(): FilterList
}
| source-api/src/main/java/eu/kanade/tachiyomi/source/CatalogueSource.kt | 451816169 |
package eu.kanade.presentation.components
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.util.drawVerticalScrollbar
import eu.kanade.presentation.util.flingBehaviorIgnoringMotionScale
/**
* LazyColumn with fling animation fix
*
* @see flingBehaviorIgnoringMotionScale
*/
@Composable
fun LazyColumn(
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(),
userScrollEnabled: Boolean = true,
content: LazyListScope.() -> Unit,
) {
androidx.compose.foundation.lazy.LazyColumn(
modifier = modifier,
state = state,
contentPadding = contentPadding,
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
content = content,
)
}
/**
* LazyColumn with scrollbar.
*/
@Composable
fun ScrollbarLazyColumn(
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(),
userScrollEnabled: Boolean = true,
content: LazyListScope.() -> Unit,
) {
val direction = LocalLayoutDirection.current
val density = LocalDensity.current
val positionOffset = remember(contentPadding) {
with(density) { contentPadding.calculateEndPadding(direction).toPx() }
}
LazyColumn(
modifier = modifier
.drawVerticalScrollbar(
state = state,
reverseScrolling = reverseLayout,
positionOffsetPx = positionOffset,
),
state = state,
contentPadding = contentPadding,
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
content = content,
)
}
/**
* LazyColumn with fast scroller.
*/
@Composable
fun FastScrollLazyColumn(
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(),
userScrollEnabled: Boolean = true,
content: LazyListScope.() -> Unit,
) {
VerticalFastScroller(
listState = state,
modifier = modifier,
topContentPadding = contentPadding.calculateTopPadding(),
endContentPadding = contentPadding.calculateEndPadding(LocalLayoutDirection.current),
) {
LazyColumn(
state = state,
contentPadding = contentPadding,
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
content = content,
)
}
}
| app/src/main/java/eu/kanade/presentation/components/LazyList.kt | 1759319211 |
package com.grenzfrequence.showmycar.car_types.ui
import android.os.Bundle
import com.grenzfrequence.githubviewerkotlin.base.BaseActivity
import com.grenzfrequence.showmycar.Navigator
import com.grenzfrequence.showmycar.R
import com.grenzfrequence.showmycar.car_types.events.ClickedBuiltDatesViewModelItemEvent
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* Created by grenzfrequence on 14.08.17.
*/
class BuiltDatesActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_built_dates)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onClickedMainTypeViewModelItemEvent(event: ClickedBuiltDatesViewModelItemEvent) {
Navigator.startSummarizeActivity(this, event.manufacturer, event.mainType, event.builtDate)
}
} | app/src/main/java/com/grenzfrequence/showmycar/car_types/ui/BuiltDatesActivity.kt | 3218754159 |
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.database.interfaces.end
class SyncPumpCancelExtendedBolusIfAnyTransaction(
private val timestamp: Long, private val endPumpId: Long, private val pumpType: InterfaceIDs.PumpType, private val pumpSerial: String
) : Transaction<SyncPumpCancelExtendedBolusIfAnyTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val existing = database.extendedBolusDao.findByPumpEndIds(endPumpId, pumpType, pumpSerial)
if (existing != null) // assume EB has been cut already
return result
val running = database.extendedBolusDao.getExtendedBolusActiveAt(timestamp).blockingGet()
if (running != null && running.interfaceIDs.endId == null) { // do not allow overwrite if cut by end event
val pctRun = (timestamp - running.timestamp) / running.duration.toDouble()
running.amount *= pctRun
running.end = timestamp
running.interfaceIDs.endId = endPumpId
database.extendedBolusDao.updateExistingEntry(running)
result.updated.add(running)
}
return result
}
class TransactionResult {
val updated = mutableListOf<ExtendedBolus>()
}
} | database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpCancelExtendedBolusIfAnyTransaction.kt | 2203286751 |
/*
* Copyright 2014 Square 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.squareup.wire
import com.squareup.wire.internal.ProtocolException
import com.squareup.wire.protos.kotlin.edgecases.OneBytesField
import com.squareup.wire.protos.kotlin.edgecases.OneField
import com.squareup.wire.protos.kotlin.edgecases.Recursive
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import okio.EOFException
import okio.IOException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.fail
class ParseTest {
@Test
fun unknownTagIgnored() {
// tag 1 / type 0: 456
// tag 2 / type 0: 789
val data = "08c803109506".decodeHex()
val oneField = OneField.ADAPTER.decode(data.toByteArray())
val expected = OneField(opt_int32 = 456)
assertNotEquals(expected, oneField)
assertEquals(expected, oneField.copy(unknownFields = ByteString.EMPTY))
}
@Test
fun unknownTypeThrowsIOException() {
// tag 1 / type 0: 456
// tag 2 / type 7: 789
val data = "08c803179506".decodeHex()
try {
OneField.ADAPTER.decode(data.toByteArray())
fail()
} catch (expected: ProtocolException) {
assertEquals("Unexpected field encoding: 7", expected.message)
}
}
@Test
fun truncatedMessageThrowsEOFException() {
// tag 1 / 4-byte length delimited string: 0x000000 (3 bytes)
val data = "0a04000000".decodeHex()
try {
OneBytesField.ADAPTER.decode(data.toByteArray())
fail()
} catch (expected: EOFException) {
}
}
@Test
fun lastValueWinsForRepeatedValueOfNonrepeatedField() {
// tag 1 / type 0: 456
// tag 1 / type 0: 789
val data = "08c803089506".decodeHex()
val oneField = OneField.ADAPTER.decode(data.toByteArray())
assertEquals(oneField, OneField(opt_int32 = 789))
}
@Test
fun upToRecursionLimit() {
// tag 2: nested message (64 times)
// tag 1: signed varint32 456
val data = (
"127e127c127a12781276127412721270126e126c126a12681266126" +
"412621260125e125c125a12581256125412521250124e124c124a12481246124412421240123e123c123a123" +
"81236123412321230122e122c122a12281226122412221220121e121c121a12181216121412121210120e120" +
"c120a1208120612041202120008c803"
).decodeHex()
val recursive = Recursive.ADAPTER.decode(data.toByteArray())
assertEquals(456, recursive.value_!!.toInt())
}
@Test
fun overRecursionLimitThrowsIOException() {
// tag 2: nested message (65 times)
// tag 1: signed varint32 456
val data = (
"128001127e127c127a12781276127412721270126e126c126a12681" +
"266126412621260125e125c125a12581256125412521250124e124c124a12481246124412421240123e123c1" +
"23a12381236123412321230122e122c122a12281226122412221220121e121c121a121812161214121212101" +
"20e120c120a1208120612041202120008c803"
).decodeHex()
try {
Recursive.ADAPTER.decode(data.toByteArray())
fail()
} catch (expected: IOException) {
assertEquals("Wire recursion limit exceeded", expected.message)
}
}
}
| wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/ParseTest.kt | 4129838024 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.analysis
import arcs.core.data.EntityType
import arcs.core.data.FieldName
import arcs.core.data.FieldType
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
/** Returns the union of two [EntityType] instances. */
infix fun EntityType.union(other: EntityType) = EntityType(entitySchema union other.entitySchema)
/** Returns the intersection of two [EntityType] instances. */
infix fun EntityType.intersect(other: EntityType): EntityType {
return EntityType(entitySchema intersect other.entitySchema)
}
/**
* Computes the union of the two [Schema] instances. Returns [Outcome.Failure] if the union
* is not possible as the inputs are incompatible.
*/
infix fun Schema.union(other: Schema): Schema {
// TODO(b/154235149): hash, refinement, query
return Schema(
names = names union other.names,
fields = fields union other.fields,
hash = ""
)
}
/** Computes the intersection of the two [Schema] instances. */
infix fun Schema.intersect(other: Schema): Schema {
// TODO(b/154235149): hash, refinement, query
return Schema(
names = names intersect other.names,
fields = fields intersect other.fields,
hash = ""
)
}
/**
* Computes the union of [SchemaFields] instances. Returns [Outcome.Failure] if the union
* results in any incompatibility. e.g., incompatible [FieldType] with the same name.
*/
private infix fun SchemaFields.union(other: SchemaFields): SchemaFields {
return SchemaFields(
singletons = singletons union other.singletons,
collections = collections union other.collections
)
}
/** Computes the intersection of [SchemaFields] instances. */
private infix fun SchemaFields.intersect(other: SchemaFields): SchemaFields {
return SchemaFields(
singletons = singletons intersect other.singletons,
collections = collections intersect other.collections
)
}
/**
* Returns the result of combining two different field maps.
*
* If the maps have common [FieldName] entries, the union succeeds if and only if the corresponding
* [FieldType] values are the same.
*/
private infix fun Map<FieldName, FieldType>.union(
other: Map<FieldName, FieldType>
): Map<FieldName, FieldType> {
val result = mutableMapOf<FieldName, FieldType>()
result.putAll(this)
other.forEach { (name, type) ->
val existing = this[name]
if (existing != null && type != existing) {
throw TypeCheckException(
"Incompatible types for field '$name': $type vs. $existing."
)
}
result[name] = type
}
return result
}
/** Returns the intersection of two field maps. */
private infix fun Map<FieldName, FieldType>.intersect(
other: Map<FieldName, FieldType>
): Map<FieldName, FieldType> {
// TODO(b/156983624): Reference fields should not be compared with equality. Instead we should
// descend into the nested schema and recursively intersect those too.
return filter { (name, type) -> other[name] == type }
}
| java/arcs/core/analysis/EntityTypeOperations.kt | 3421136466 |
package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
/**
*
* @author Jelle Stege
*/
class Day20 : Day(title = "Infinite Elves and Infinite Houses") {
private companion object Configuration {
private const val FIRST_PRESENTS_PER_HOUSE = 10
private const val SECOND_PRESENTS_PER_HOUSE = 11
private const val MAX_HOUSES_VISITED = 50
}
override fun first(input: Sequence<String>): Any {
val wantedPresents = input.head.toInt()
val elves = mutableMapOf<Int, MutableList<Int>>()
var elf = 1
var presents = 0
while (elf <= wantedPresents / 10 && presents <= wantedPresents) {
val elfList = elves.getOrPut(elf) { mutableListOf() }
elfList += elf
presents = elfList.sum() * FIRST_PRESENTS_PER_HOUSE
if (presents >= wantedPresents) {
break
}
elfList
.filter { elf + it <= wantedPresents / 10 }
.forEach { elves.getOrPut(elf + it) { mutableListOf() } += it }
elf++
}
return elf
}
override fun second(input: Sequence<String>): Any {
val wantedPresents = input.head.toInt()
val elves = mutableMapOf<Int, MutableList<Int>>()
var elf = 1
var presents = 0
while (elf <= (wantedPresents / 10) && presents <= wantedPresents) {
if (elf !in elves) {
elves[elf] = mutableListOf()
}
val elfList = elves.remove(elf)!!
elfList += elf
presents = elfList.sum() * SECOND_PRESENTS_PER_HOUSE
if (presents >= wantedPresents) {
break
}
elfList
.filter {
(elf + it < wantedPresents / 10) && (elf + it <= it * MAX_HOUSES_VISITED)
}
.forEach { elves.getOrPut(elf + it) { mutableListOf() } += it }
elf++
}
return elf
}
}
| aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day20.kt | 1993894208 |
package org.hexworks.zircon.internal.component.impl.textedit
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.component.impl.textedit.cursor.Cursor
import org.hexworks.zircon.platform.util.SystemUtils
interface EditableTextBuffer {
var cursor: Cursor
val textBuffer: MutableList<MutableList<Char>>
fun applyTransformation(transformation: TextBufferTransformation): EditableTextBuffer
fun getLastRowIdx(): Int = textBuffer.size - 1
fun getLastColumnIdxForRow(rowIdx: Int): Int = textBuffer[rowIdx].size - 1
fun getColumnCount(rowIdx: Int): Int = textBuffer[rowIdx].size
fun getRow(rowIdx: Int): MutableList<Char> = textBuffer[rowIdx]
fun deleteRow(rowIdx: Int): MutableList<Char> = textBuffer.removeAt(rowIdx)
fun getBoundingBoxSize(): Size = Size.create(
width = textBuffer.asSequence()
.map { it.size }
.maxOrNull() ?: 0,
height = textBuffer.size)
fun getText(): String = textBuffer.joinToString(SystemUtils.getLineSeparator()) { it.joinToString("") }
fun getSize() = textBuffer.size
fun getCharAtOrNull(position: Position): Char? =
if (position.y >= textBuffer.size || textBuffer[position.y].size <= position.x) {
null
} else {
textBuffer[position.y][position.x]
}
fun getCharAtOrElse(
position: Position,
other: (Position) -> Char
): Char = getCharAtOrNull(position) ?: other(position)
fun rowCount(): Int = textBuffer.size
companion object {
fun create(text: String = "", cursor: Cursor = Cursor()): EditableTextBuffer =
DefaultEditableTextBuffer(text, cursor)
}
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/textedit/EditableTextBuffer.kt | 4170580961 |
package forpdateam.ru.forpda.ui.fragments.news.details
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import java.util.ArrayList
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.entity.remote.news.DetailsPage
import forpdateam.ru.forpda.model.interactors.news.ArticleInteractor
import forpdateam.ru.forpda.presentation.articles.detail.ArticleDetailPresenter
import forpdateam.ru.forpda.presentation.articles.detail.ArticleDetailView
import forpdateam.ru.forpda.ui.activities.MainActivity
import forpdateam.ru.forpda.ui.fragments.TabFragment
import forpdateam.ru.forpda.ui.fragments.TabTopScroller
import forpdateam.ru.forpda.ui.fragments.notes.NotesAddPopup
import forpdateam.ru.forpda.ui.views.ExtendedWebView
import forpdateam.ru.forpda.ui.views.ScrimHelper
/**
* Created by isanechek on 8/19/17.
*/
class NewsDetailsFragment : TabFragment(), ArticleDetailView, TabTopScroller {
lateinit var fragmentsPager: androidx.viewpager.widget.ViewPager
private set
private lateinit var progressBar: ProgressBar
private lateinit var imageProgressBar: ProgressBar
private lateinit var detailsImage: ImageView
private lateinit var detailsTitle: TextView
private lateinit var detailsNick: TextView
private lateinit var detailsCount: TextView
private lateinit var detailsDate: TextView
private var isResume = false
private var isScrim = false
private val interactor = ArticleInteractor(
ArticleInteractor.InitData(),
App.get().Di().newsRepository,
App.get().Di().articleTemplate
)
@InjectPresenter
lateinit var presenter: ArticleDetailPresenter
fun provideChildInteractor(): ArticleInteractor {
return interactor
}
fun getAppBar() = appBarLayout
public override fun attachWebView(webView: ExtendedWebView) {
super.attachWebView(webView)
}
@ProvidePresenter
fun providePresenter(): ArticleDetailPresenter = ArticleDetailPresenter(
interactor,
App.get().Di().router,
App.get().Di().linkHandler,
App.get().Di().errorHandler
)
init {
configuration.defaultTitle = App.get().getString(R.string.fragment_title_news)
configuration.isFitSystemWindow = true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.e("lalala", "onCreate " + this + " : " + arguments)
arguments?.apply {
interactor.initData.newsUrl = getString(ARG_NEWS_URL)
interactor.initData.newsId = getInt(ARG_NEWS_ID, 0)
interactor.initData.commentId = getInt(ARG_NEWS_COMMENT_ID, 0)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
baseInflateFragment(inflater, R.layout.fragment_article)
val viewStub = findViewById(R.id.toolbar_content) as ViewStub
viewStub.layoutResource = R.layout.toolbar_news_details
viewStub.inflate()
fragmentsPager = findViewById(R.id.view_pager) as androidx.viewpager.widget.ViewPager
progressBar = findViewById(R.id.progress_bar) as ProgressBar
detailsImage = findViewById(R.id.article_image) as ImageView
detailsTitle = findViewById(R.id.article_title) as TextView
detailsNick = findViewById(R.id.article_nick) as TextView
detailsCount = findViewById(R.id.article_comments_count) as TextView
detailsDate = findViewById(R.id.article_date) as TextView
imageProgressBar = findViewById(R.id.article_progress_bar) as ProgressBar
detailsImage.maxHeight = App.px24 * 10
setScrollFlagsExitUntilCollapsed()
return viewFragment
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val scrimHelper = ScrimHelper(appBarLayout, toolbarLayout)
scrimHelper.setScrimListener { scrim1 ->
isScrim = scrim1
if (scrim1) {
toolbar.navigationIcon?.clearColorFilter()
toolbar.overflowIcon?.clearColorFilter()
toolbarTitleView.visibility = View.VISIBLE
} else {
toolbar.navigationIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
toolbar.overflowIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
toolbarTitleView.visibility = View.GONE
}
updateStatusBar()
}
arguments?.apply {
val newsTitle = getString(ARG_NEWS_TITLE)
val newsNick = getString(ARG_NEWS_AUTHOR_NICK)
val newsDate = getString(ARG_NEWS_DATE)
val newsImageUrl = getString(ARG_NEWS_IMAGE)
val newsCount = getInt(ARG_NEWS_COMMENTS_COUNT, -1)
if (newsTitle != null) {
setTitle(newsTitle)
setTabTitle(String.format(getString(R.string.fragment_tab_title_article), newsTitle))
detailsTitle.text = newsTitle
}
if (newsNick != null) {
detailsNick.text = newsNick
}
if (newsCount != -1) {
detailsCount.text = newsCount.toString()
}
if (newsDate != null) {
detailsDate.text = newsDate
}
if (newsImageUrl != null) {
showArticleImage(newsImageUrl)
}
}
toolbarTitleView.visibility = View.GONE
toolbar.navigationIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
toolbar.overflowIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
detailsNick.setOnClickListener { presenter.openAuthorProfile() }
}
override fun toggleScrollTop() {
((fragmentsPager.adapter as FragmentPagerAdapter).getItem(fragmentsPager.currentItem) as? TabTopScroller)?.toggleScrollTop()
}
override fun addBaseToolbarMenu(menu: Menu) {
super.addBaseToolbarMenu(menu)
menu.add(R.string.copy_link)
.setOnMenuItemClickListener {
presenter.copyLink()
false
}
menu.add(R.string.share)
.setOnMenuItemClickListener {
presenter.shareLink()
false
}
menu.add(R.string.create_note)
.setOnMenuItemClickListener {
presenter.createNote()
false
}
}
override fun onBackPressed(): Boolean {
if (fragmentsPager.currentItem == 1) {
fragmentsPager.currentItem = 0
return true
}
return super.onBackPressed()
}
override fun onResumeOrShow() {
super.onResumeOrShow()
isResume = true
updateStatusBar()
}
override fun onPauseOrHide() {
super.onPauseOrHide()
isResume = false
updateStatusBar()
}
private fun updateStatusBar() {
val defaultSb = MainActivity.getDefaultLightStatusBar(activity!!)
if (isResume) {
MainActivity.setLightStatusBar(activity!!, isScrim && defaultSb)
} else {
MainActivity.setLightStatusBar(activity!!, defaultSb)
}
}
override fun setRefreshing(isRefreshing: Boolean) {
progressBar.visibility = if (isRefreshing) View.VISIBLE else View.GONE
}
override fun showArticle(data: DetailsPage) {
setTitle(data.title)
setTabTitle(String.format(getString(R.string.fragment_tab_title_article), data.title))
detailsTitle.text = data.title
detailsNick.text = data.author
detailsDate.text = data.date
detailsCount.text = data.commentsCount.toString()
data.imgUrl?.also {
showArticleImage(it)
}
val pagerAdapter = FragmentPagerAdapter(childFragmentManager)
fragmentsPager.adapter = pagerAdapter
if (data.commentId > 0) {
appBarLayout.setExpanded(false, true)
fragmentsPager.setCurrentItem(1, true)
}
}
override fun showCreateNote(title: String, url: String) {
NotesAddPopup.showAddNoteDialog(context, title, url)
}
override fun showArticleImage(imageUrl: String) {
ImageLoader.getInstance().displayImage(imageUrl, detailsImage, object : SimpleImageLoadingListener() {
override fun onLoadingStarted(imageUri: String?, view: View?) {
imageProgressBar.visibility = View.VISIBLE
}
override fun onLoadingComplete(imageUri: String?, view: View?, loadedImage: Bitmap?) {
imageProgressBar.visibility = View.GONE
}
})
}
private inner class FragmentPagerAdapter(
fm: androidx.fragment.app.FragmentManager
) : androidx.fragment.app.FragmentPagerAdapter(fm) {
private val fragments = ArrayList<androidx.fragment.app.Fragment>()
private val titles = ArrayList<String>()
init {
fragments.add(ArticleContentFragment())
titles.add(App.get().getString(R.string.news_page_content))
fragments.add(ArticleCommentsFragment())
titles.add(App.get().getString(R.string.news_page_comments))
}
override fun getItem(position: Int): androidx.fragment.app.Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
override fun getPageTitle(position: Int): CharSequence? {
return titles[position]
}
}
companion object {
const val ARG_NEWS_URL = "ARG_NEWS_URL"
const val ARG_NEWS_ID = "ARG_NEWS_ID"
const val ARG_NEWS_COMMENT_ID = "ARG_NEWS_COMMENT_ID"
const val ARG_NEWS_TITLE = "ARG_NEWS_TITLE"
const val ARG_NEWS_AUTHOR_NICK = "ARG_NEWS_AUTHOR_NICK"
//const val ARG_NEWS_AUTHOR_ID = "ARG_NEWS_AUTHOR_ID"
const val ARG_NEWS_COMMENTS_COUNT = "ARG_NEWS_COMMENTS_COUNT"
const val ARG_NEWS_DATE = "ARG_NEWS_DATE"
const val ARG_NEWS_IMAGE = "ARG_NEWS_IMAGE"
}
}
| app/src/main/java/forpdateam/ru/forpda/ui/fragments/news/details/NewsDetailsFragment.kt | 2401340447 |
package com.safframework.ext
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import java.io.File
/**
* Created by Tony Shen on 2017/6/30.
*/
/**
* screen width in pixels
*/
inline val Context.screenWidth
get() = resources.displayMetrics.widthPixels
/**
* screen height in pixels
*/
inline val Context.screenHeight
get() = resources.displayMetrics.heightPixels
inline val Context.isNetworkAvailable: Boolean
@SuppressLint("MissingPermission")
get() {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo?.isConnectedOrConnecting ?: false
}
/**
* returns dip(dp) dimension value in pixels
* @param value dp
*/
fun Context.dp2px(value: Int): Int = (value * resources.displayMetrics.density).toInt()
fun Context.dp2px(value: Float): Int = (value * resources.displayMetrics.density).toInt()
/**
* return sp dimension value in pixels
* @param value sp
*/
fun Context.sp2px(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt()
fun Context.sp2px(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt()
/**
* converts [px] value into dip or sp
* @param px
*/
fun Context.px2dp(px: Int): Float = px.toFloat() / resources.displayMetrics.density
fun Context.px2sp(px: Int): Float = px.toFloat() / resources.displayMetrics.scaledDensity
/**
* return dimen resource value in pixels
* @param resource dimen resource
*/
fun Context.dimen2px(@DimenRes resource: Int): Int = resources.getDimensionPixelSize(resource)
fun Context.string(@StringRes id: Int): String = getString(id)
fun Context.color(@ColorRes id: Int): Int = resources.getColor(id)
fun Context.inflateLayout(@LayoutRes layoutId: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false): View
= LayoutInflater.from(this).inflate(layoutId, parent, attachToRoot)
/**
* 获取当前app的版本号
*/
fun Context.getAppVersion(): String {
val appContext = applicationContext
val manager = appContext.getPackageManager()
try {
val info = manager.getPackageInfo(appContext.getPackageName(), 0)
if (info != null)
return info.versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return ""
}
fun Context.getAppVersionCode(): Int {
val appContext = applicationContext
val manager = appContext.getPackageManager()
try {
val info = manager.getPackageInfo(appContext.getPackageName(), 0)
if (info != null)
return info.versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return 0
}
/**
* 获取应用的包名
*
* @param context context
* @return package name
*/
fun Context.getPackageName(): String = packageName
data class AppInfo(
val apkPath: String,
val packageName: String,
val versionName: String,
val versionCode: Long,
val appName: String,
val icon: Drawable
)
fun Context.getAppInfo(apkPath: String): AppInfo {
val packageInfo = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_META_DATA) as PackageInfo
packageInfo.applicationInfo.sourceDir = apkPath
packageInfo.applicationInfo.publicSourceDir = apkPath
val packageName = packageInfo.packageName
val appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString()
val versionName = packageInfo.versionName
val versionCode = packageInfo.versionCode
val icon = packageManager.getApplicationIcon(packageInfo.applicationInfo)
return AppInfo(apkPath, packageName, versionName, versionCode.toLong(), appName, icon)
}
fun Context.getAppInfos(apkFolderPath: String): List<AppInfo> {
val appInfoList = ArrayList<AppInfo>()
for (file in File(apkFolderPath).listFiles())
appInfoList.add(getAppInfo(file.path))
return appInfoList
} | saf-kotlin-ext/src/main/java/com/safframework/ext/Context+Extension.kt | 2804991995 |
package com.asurasdevelopment.ihh.server.persistence.dao
import javax.persistence.Id
data class Federation(@Id val nr : Int,
val name : String?,
val region : String?) | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/persistence/dao/Federation.kt | 339946015 |
package utnfrsf.dondecurso.common
import android.app.Activity
import android.content.Intent
import android.os.AsyncTask
import android.os.Handler
import android.os.Looper
import android.view.View
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
fun <T> Activity.findView(id: Int): T {
return this.findViewById(id) as T
}
fun <T> View.findView(id: Int): T {
return this.findViewById(id) as T
}
fun Activity.launchActivity(activity: Activity) {
val i = Intent(this, activity::class.java)
startActivity(i)
}
fun View.launchActivity(activity: Activity) {
val i = Intent(this.context, activity::class.java)
this.context.startActivity(i)
}
fun <T> Call<T>.enqueue(onResponse: (call: Call<T>?, response: Response<T>?) -> Any, onFailure: (call: Call<T>?, t: Throwable?) -> Any) {
this.enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>?, response: Response<T>?) {
onResponse(call, response)
}
override fun onFailure(call: Call<T>?, t: Throwable?) {
onFailure(call, t)
}
})
}
fun async(callback: () -> Unit) {
AsyncTask.execute { callback() }
}
fun onUI(callback: () -> Unit) {
Handler(Looper.getMainLooper()).post { callback() }
} | app/src/main/java/utnfrsf/dondecurso/common/extensions.kt | 3926506972 |
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.openapi.extensions.AreaInstance
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import kotlin.streams.toList
/**
* Extension point used to register [Module]s transformations to [ProjectModule]s using coroutines.
*/
interface CoroutineModuleTransformer {
companion object {
private val extensionPointName: ExtensionPointName<CoroutineModuleTransformer> =
ExtensionPointName.create("com.intellij.packagesearch.coroutineModuleTransformer")
internal fun extensions(areaInstance: AreaInstance) =
extensionPointName.extensions(areaInstance).toList()
}
/**
* IMPORTANT: This function is NOT invoked inside a read action.
*
* Transforms [nativeModules] in a [ProjectModule] module if possible, else returns an empty list.
* Its implementation should use the IntelliJ platform APIs for a given build system (eg.
* Gradle or Maven), detect if and which [nativeModules] are controlled by said build system
* and transform them accordingly.
*
* NOTE: some [Module]s in [nativeModules] may be already disposed or about to be. Be sure to
* handle any exceptions and filter out the ones not working.
*
* @param nativeModules The native [Module]s that will be transformed.
* @return [ProjectModule]s wrapping [nativeModules] or an empty list.
*/
suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule>
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/CoroutineModuleTransformer.kt | 3118161419 |
// IS_APPLICABLE: false
public interface I {
public val v: String?
}
public interface I1 : I {
override val v: String<caret>
} | plugins/kotlin/idea/tests/testData/intentions/removeExplicitType/onOverrideInTrait.kt | 2569345220 |
// 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.refactoring.changeSignature
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementFactory
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.ui.RefactoringDialog
import com.intellij.refactoring.util.CanonicalTypes
import com.intellij.util.VisibilityUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangePropertySignatureDialog
import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangeSignatureDialog
import org.jetbrains.kotlin.idea.refactoring.createJavaMethod
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
interface KotlinChangeSignatureConfiguration {
fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor = originalDescriptor
fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = false
fun forcePerformForSelectedFunctionOnly(): Boolean = false
object Empty : KotlinChangeSignatureConfiguration
}
fun KotlinMethodDescriptor.modify(action: (KotlinMutableMethodDescriptor) -> Unit): KotlinMethodDescriptor {
val newDescriptor = KotlinMutableMethodDescriptor(this)
action(newDescriptor)
return newDescriptor
}
fun runChangeSignature(
project: Project,
editor: Editor?,
callableDescriptor: CallableDescriptor,
configuration: KotlinChangeSignatureConfiguration,
defaultValueContext: PsiElement,
@NlsContexts.Command commandName: String? = null
): Boolean {
val result = KotlinChangeSignature(project, editor, callableDescriptor, configuration, defaultValueContext, commandName).run()
if (!result) {
broadcastRefactoringExit(project, "refactoring.changeSignature")
}
return result
}
class KotlinChangeSignature(
project: Project,
editor: Editor?,
callableDescriptor: CallableDescriptor,
val configuration: KotlinChangeSignatureConfiguration,
val defaultValueContext: PsiElement,
@NlsContexts.Command commandName: String?
) : CallableRefactoring<CallableDescriptor>(
project,
editor,
callableDescriptor,
commandName ?: RefactoringBundle.message("changeSignature.refactoring.name")
) {
override fun forcePerformForSelectedFunctionOnly() = configuration.forcePerformForSelectedFunctionOnly()
/**
* @param propertyProcessor:
* - top level
* - member level
* - primary constructor
*
* @param functionProcessor:
* - top level
* - member level
* - local level
* - constructors
*
* @param javaProcessor:
* - member level
*/
private fun <T> selectRefactoringProcessor(
descriptor: KotlinMethodDescriptor,
propertyProcessor: (KotlinMethodDescriptor) -> T?,
functionProcessor: (KotlinMethodDescriptor) -> T?,
javaProcessor: (KotlinMethodDescriptor, PsiMethod) -> T?,
): T? {
return when (val baseDeclaration = descriptor.baseDeclaration) {
is KtProperty, is KtParameter -> propertyProcessor(descriptor)
/**
* functions:
* - top level
* - member level
* - constructors
*
* class:
* - primary constructor
*/
is KtFunction, is KtClass -> functionProcessor(descriptor)
is PsiMethod -> {
if (baseDeclaration.language != JavaLanguage.INSTANCE) {
Messages.showErrorDialog(
KotlinBundle.message("error.text.can.t.change.signature.of.method", baseDeclaration.language.displayName),
commandName
)
return null
}
javaProcessor(descriptor, baseDeclaration)
}
else -> throw KotlinExceptionWithAttachments("Unexpected declaration: ${baseDeclaration::class}")
.withPsiAttachment("element.kt", baseDeclaration)
.withPsiAttachment("file.kt", baseDeclaration.containingFile)
}
}
@TestOnly
fun createSilentRefactoringProcessor(methodDescriptor: KotlinMethodDescriptor): BaseRefactoringProcessor? = selectRefactoringProcessor(
methodDescriptor,
propertyProcessor = { KotlinChangePropertySignatureDialog.createProcessorForSilentRefactoring(project, commandName, it) },
functionProcessor = {
KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature(
project,
commandName,
it,
defaultValueContext
)
},
javaProcessor = { descriptor, _ -> ChangeSignatureProcessor(project, getPreviewInfoForJavaMethod(descriptor).second) }
)
private fun runSilentRefactoring(methodDescriptor: KotlinMethodDescriptor) {
createSilentRefactoringProcessor(methodDescriptor)?.run()
}
private fun runInteractiveRefactoring(methodDescriptor: KotlinMethodDescriptor) {
val dialog = selectRefactoringProcessor(
methodDescriptor,
propertyProcessor = { KotlinChangePropertySignatureDialog(project, it, commandName) },
functionProcessor = { KotlinChangeSignatureDialog(project, editor, it, defaultValueContext, commandName) },
javaProcessor = fun(descriptor: KotlinMethodDescriptor, method: PsiMethod): RefactoringDialog? {
if (descriptor is KotlinChangeSignatureData) {
ChangeSignatureUtil.invokeChangeSignatureOn(method, project)
return null
}
val (preview, javaChangeInfo) = getPreviewInfoForJavaMethod(descriptor)
val javaDescriptor = object : JavaMethodDescriptor(preview) {
@Suppress("UNCHECKED_CAST")
override fun getParameters() = javaChangeInfo.newParameters.toMutableList() as MutableList<ParameterInfoImpl>
}
return object : JavaChangeSignatureDialog(project, javaDescriptor, false, null) {
override fun createRefactoringProcessor(): BaseRefactoringProcessor {
val parameters = parameters
LOG.assertTrue(myMethod.method.isValid)
val newJavaChangeInfo = JavaChangeInfoImpl(
visibility ?: VisibilityUtil.getVisibilityModifier(myMethod.method.modifierList),
javaChangeInfo.method,
methodName,
returnType ?: CanonicalTypes.createTypeWrapper(PsiType.VOID),
parameters.toTypedArray(),
exceptions,
isGenerateDelegate,
myMethodsToPropagateParameters ?: HashSet(),
myMethodsToPropagateExceptions ?: HashSet()
).also {
it.setCheckUnusedParameter()
}
return ChangeSignatureProcessor(myProject, newJavaChangeInfo)
}
}
},
) ?: return
if (isUnitTestMode()) {
try {
dialog.performOKAction()
} finally {
dialog.close(DialogWrapper.OK_EXIT_CODE)
}
} else {
dialog.show()
}
}
private fun getPreviewInfoForJavaMethod(descriptor: KotlinMethodDescriptor): Pair<PsiMethod, JavaChangeInfo> {
val originalMethod = descriptor.baseDeclaration as PsiMethod
val contextFile = defaultValueContext.containingFile as KtFile
// Generate new Java method signature from the Kotlin point of view
val ktChangeInfo = KotlinChangeInfo(methodDescriptor = descriptor, context = defaultValueContext)
val ktSignature = ktChangeInfo.getNewSignature(descriptor.originalPrimaryCallable)
val previewClassName = if (originalMethod.isConstructor) originalMethod.name else "Dummy"
val dummyFileText = with(StringBuilder()) {
contextFile.packageDirective?.let { append(it.text).append("\n") }
append("class $previewClassName {\n").append(ktSignature).append("{}\n}")
toString()
}
val dummyFile = KtPsiFactory(project).createFileWithLightClassSupport("dummy.kt", dummyFileText, originalMethod)
val dummyDeclaration = (dummyFile.declarations.first() as KtClass).body!!.declarations.first()
// Convert to PsiMethod which can be used in Change Signature dialog
val containingClass = PsiElementFactory.getInstance(project).createClass(previewClassName)
val preview = createJavaMethod(dummyDeclaration.getRepresentativeLightMethod()!!, containingClass)
// Create JavaChangeInfo based on new signature
// TODO: Support visibility change
val visibility = VisibilityUtil.getVisibilityModifier(originalMethod.modifierList)
val returnType = CanonicalTypes.createTypeWrapper(preview.returnType ?: PsiType.VOID)
val params = (preview.parameterList.parameters.zip(ktChangeInfo.newParameters)).map {
val (param, paramInfo) = it
// Keep original default value for proper update of Kotlin usages
KotlinAwareJavaParameterInfoImpl(paramInfo.oldIndex, param.name, param.type, paramInfo.defaultValueForCall)
}.toTypedArray()
return preview to JavaChangeInfoImpl(
visibility,
originalMethod,
preview.name,
returnType,
params,
arrayOf<ThrownExceptionInfo>(),
false,
emptySet<PsiMethod>(),
emptySet<PsiMethod>()
)
}
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val adjustedDescriptor = adjustDescriptor(descriptorsForChange) ?: return
val affectedFunctions = adjustedDescriptor.affectedCallables.mapNotNull { it.element }
if (affectedFunctions.any { !checkModifiable(it) }) return
if (configuration.performSilently(affectedFunctions)) {
runSilentRefactoring(adjustedDescriptor)
} else {
runInteractiveRefactoring(adjustedDescriptor)
}
}
fun adjustDescriptor(descriptorsForSignatureChange: Collection<CallableDescriptor>): KotlinMethodDescriptor? {
val baseDescriptor = preferContainedInClass(descriptorsForSignatureChange)
val functionDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, baseDescriptor)
if (functionDeclaration == null) {
LOG.error("Could not find declaration for $baseDescriptor")
return null
}
if (!checkModifiable(functionDeclaration)) {
return null
}
val originalDescriptor = KotlinChangeSignatureData(baseDescriptor, functionDeclaration, descriptorsForSignatureChange)
return configuration.configure(originalDescriptor)
}
private fun preferContainedInClass(descriptorsForSignatureChange: Collection<CallableDescriptor>): CallableDescriptor {
for (descriptor in descriptorsForSignatureChange) {
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration is ClassDescriptor && containingDeclaration.kind != ClassKind.INTERFACE) {
return descriptor
}
}
//choose at random
return descriptorsForSignatureChange.first()
}
companion object {
private val LOG = logger<KotlinChangeSignature>()
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt | 1078648156 |
package org.snakeskin.component.provider
/**
* Represents a component that can be followed. Does not provide any functionality
*/
interface IFollowableProvider | SnakeSkin-Core/src/main/kotlin/org/snakeskin/component/provider/IFollowableProvider.kt | 1651808723 |
package core.API
import org.json.simple.JSONArray
import org.json.simple.JSONObject
class Elevator(elevator: JSONObject) : MessagesInterface {
val id: Int = elevator["id"]?.toString()?.toInt() ?: 0
val y: Double = elevator["y"]?.toString()?.toDouble() ?: 0.0
val passengers = ArrayList<Passenger>()
val state: Int = elevator["state"]?.toString()?.toInt() ?: 0
val speed: Double = elevator["speed"]?.toString()?.toDouble() ?: 0.0
val timeOnFloor: Int = elevator["time_on_floor"]?.toString()?.toInt() ?: 0
val floor: Int = elevator["floor"]?.toString()?.toInt() ?: 0
val type: String = elevator["type"]?.toString() ?: ""
var nextFloor: Int = elevator["next_floor"]?.toString()?.toInt() ?: 0
private set
val messages = ArrayList<JSONObject>()
init {
(elevator["passengers"] as JSONArray).mapTo(passengers) { Passenger(it as JSONObject) }
}
override fun getMessages(): List<JSONObject> = messages
fun goToFloor(floor: Int?) {
this.nextFloor = floor ?: 0
val jo = JSONObject()
jo.put("command", "go_to_floor")
val args = JSONObject()
args.put("elevator_id", this.id)
args.put("floor", floor)
jo.put("args", args)
this.messages.add(jo)
}
} | clients/kotlin_client/client/src/main/kotlin/core/API/Elevator.kt | 1570605458 |
package io.ipoli.android.settings.view
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import io.ipoli.android.R
import io.ipoli.android.common.view.ReduxDialogController
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.LoadPetDialogAction
import io.ipoli.android.pet.PetDialogReducer
import io.ipoli.android.pet.PetDialogViewState
import kotlinx.android.synthetic.main.view_dialog_header.view.*
import org.threeten.bp.DayOfWeek
import org.threeten.bp.format.TextStyle
import java.util.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 5/16/18.
*/
class DaysPickerDialogController(args: Bundle? = null) :
ReduxDialogController<LoadPetDialogAction, PetDialogViewState, PetDialogReducer>(args) {
override val reducer = PetDialogReducer
private val days: List<DayOfWeek> = DayOfWeek.values().toList()
private var listener: (Set<DayOfWeek>) -> Unit = {}
private lateinit var selectedDays: MutableSet<DayOfWeek>
constructor(
selectedDays: Set<DayOfWeek>,
listener: (Set<DayOfWeek>) -> Unit
) : this() {
this.listener = listener
this.selectedDays = selectedDays.toMutableSet()
}
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View =
inflater.inflate(R.layout.dialog_days_picker, null)
override fun onHeaderViewCreated(headerView: View) {
headerView.dialogHeaderTitle.setText(R.string.choose_days_of_week)
}
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog {
val daysOfWeekNames = days.map { it.getDisplayName(TextStyle.FULL, Locale.getDefault()) }
val checked = days.map { selectedDays.contains(it) }
return dialogBuilder
.setMultiChoiceItems(
daysOfWeekNames.toTypedArray(),
checked.toBooleanArray()
) { _, which, isChecked ->
if (isChecked) {
selectedDays.add(days[which])
} else {
selectedDays.remove(days[which])
}
}
.setPositiveButton(R.string.dialog_ok, null)
.setNegativeButton(R.string.cancel, null)
.create()
}
override fun onDialogCreated(dialog: AlertDialog, contentView: View) {
dialog.setOnShowListener {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener {
listener(selectedDays)
dismiss()
}
}
}
override fun onCreateLoadAction() = LoadPetDialogAction
override fun render(state: PetDialogViewState, view: View) {
if (state.type == PetDialogViewState.Type.PET_LOADED) {
changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage)
}
}
} | app/src/main/java/io/ipoli/android/settings/view/DaysPickerDialogController.kt | 1085695940 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistics.metadata
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.scheme.EventsSchemeBuilder
import com.intellij.internal.statistic.eventLog.events.scheme.EventsSchemeBuilder.pluginInfoFields
import com.intellij.internal.statistic.eventLog.events.scheme.FieldDescriptor
import com.intellij.internal.statistic.eventLog.events.scheme.GroupDescriptor
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class EventSchemeBuilderTest : BasePlatformTestCase() {
fun `test generate string field validated by regexp`() {
doFieldTest(EventFields.StringValidatedByRegexp("count", "integer"), hashSetOf("{regexp#integer}"))
}
fun `test generate string field validated by enum`() {
doFieldTest(EventFields.StringValidatedByEnum("system", "os"), hashSetOf("{enum#os}"))
}
fun `test generate string field validated by custom rule`() {
val customValidationRule = TestCustomValidationRule("custom_rule")
CustomValidationRule.EP_NAME.point.registerExtension(customValidationRule, testRootDisposable)
doFieldTest(EventFields.StringValidatedByCustomRule("class", TestCustomValidationRule::class.java), hashSetOf("{util#custom_rule}"))
}
fun `test generate string field validated by list of possible values`() {
doFieldTest(EventFields.String("class", listOf("foo", "bar")), hashSetOf("{enum:foo|bar}"))
}
fun `test generate enum field`() {
doFieldTest(EventFields.Enum("enum", TestEnum::class.java), hashSetOf("{enum:FOO|BAR}"))
}
fun `test generate string list validated by custom rule`() {
val customValidationRule = TestCustomValidationRule("index_id")
CustomValidationRule.EP_NAME.point.registerExtension(customValidationRule, testRootDisposable)
doFieldTest(EventFields.StringValidatedByCustomRule("fields", TestCustomValidationRule::class.java), hashSetOf("{util#index_id}"))
}
fun `test generate string list validated by regexp`() {
doFieldTest(EventFields.StringListValidatedByRegexp("fields", "index_id"), hashSetOf("{regexp#index_id}"))
}
fun `test generate string list validated by enum`() {
doFieldTest(EventFields.StringListValidatedByEnum("fields", "index_id"), hashSetOf("{enum#index_id}"))
}
fun `test generate string list validated by list of possible values`() {
doFieldTest(EventFields.StringList("fields", listOf("foo", "bar")), hashSetOf("{enum:foo|bar}"))
}
fun `test generate string validated by inline regexp`() {
doFieldTest(EventFields.StringValidatedByInlineRegexp("id", "\\d+.\\d+"), hashSetOf("{regexp:\\d+.\\d+}"))
}
fun `test generate string list validated by inline regexp`() {
doFieldTest(EventFields.StringListValidatedByInlineRegexp("fields", "\\d+.\\d+"), hashSetOf("{regexp:\\d+.\\d+}"))
}
fun `test generate plugin info with class name`() {
val expectedValues = hashSetOf(FieldDescriptor("quickfix_name", hashSetOf("{util#class_name}"))) + pluginInfoFields
doCompositeFieldTest(EventFields.Class("quickfix_name"), expectedValues)
}
private fun doFieldTest(eventField: EventField<*>, expectedValues: Set<String>) {
val group = buildGroupDescription(eventField)
val event = group.schema.first()
assertSameElements(event.fields.first().value, expectedValues)
}
private fun doCompositeFieldTest(eventField: EventField<*>, expectedValues: Set<FieldDescriptor>) {
val group = buildGroupDescription(eventField)
val event = group.schema.first()
assertSameElements(event.fields, expectedValues)
}
private fun buildGroupDescription(eventField: EventField<*>): GroupDescriptor {
val eventLogGroup = EventLogGroup("test.group.id", 1)
eventLogGroup.registerEvent("test_event", eventField)
val collector = EventsSchemeBuilder.FeatureUsageCollectorInfo(TestCounterCollector(eventLogGroup),"testPlugin" )
val groups = EventsSchemeBuilder.collectGroupsFromExtensions("count", listOf(collector), "FUS")
assertSize(1, groups)
return groups.first()
}
enum class TestEnum { FOO, BAR }
@Suppress("StatisticsCollectorNotRegistered")
class TestCounterCollector(val eventLogGroup: EventLogGroup) : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = eventLogGroup
}
class TestCustomValidationRule(private val ruleId: String) : CustomValidationRule() {
override fun getRuleId(): String = ruleId
override fun doValidate(data: String, context: EventContext): ValidationResultType {
return ValidationResultType.ACCEPTED
}
}
} | platform/platform-tests/testSrc/com/intellij/internal/statistics/metadata/EventSchemeBuilderTest.kt | 1927422199 |
// Copyright 2000-2022 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.gradleTooling
import org.gradle.api.Named
import org.gradle.api.NamedDomainObjectCollection
import org.gradle.api.Project
import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinSourceSetReflection
internal fun getAdditionalVisibleSourceSets(project: Project, sourceSetName: String): Set<String> {
val kotlinExtension = project.extensions.findByName("kotlin") ?: return emptySet()
val kotlinExtensionClass = kotlinExtension.javaClass
val getSourceSets = kotlinExtensionClass.getMethodOrNull("getSourceSets") ?: return emptySet()
val sourceSets = getSourceSets.invoke(kotlinExtension) as NamedDomainObjectCollection<*>
val sourceSet = sourceSets.findByName(sourceSetName) as? Named ?: return emptySet()
return getAdditionalVisibleSourceSets(sourceSet)
}
internal fun getAdditionalVisibleSourceSets(sourceSet: Named): Set<String> {
return KotlinSourceSetReflection(sourceSet).additionalVisibleSourceSets.map { it.name }.toSet()
}
| plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/getAdditionalVisibleSourceSets.kt | 1005723660 |
// "Convert sealed subclass to object" "false"
// TOOL: org.jetbrains.kotlin.idea.inspections.CanSealedSubClassBeObjectInspection
// ACTION: Make internal
// ERROR: Expected class 'Child' has no actual declaration in module testModule_Common
sealed class SealedClass
expect cla<caret>ss Child : SealedClass | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/canSealedSubClassBeObject/notConvertExpectSubClass/common/common.kt | 870851128 |
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.http
import io.ktor.http.*
import io.ktor.server.util.*
import kotlin.test.*
class ParametersTest {
private val parameters = parametersOf(
"single" to listOf("a"),
"another" to listOf("2"),
"multiple" to listOf("3", "4")
)
@Test
fun testSingleValues() {
val single: String by parameters
val another: Int by parameters
assertEquals("a", single)
assertEquals(2, another)
}
@Test
fun testMultipleAsStrings() {
val multiple: List<String> by parameters
assertEquals(listOf("3", "4"), multiple)
}
@Test
fun testMultipleAsStringsVariance() {
val multiple: MutableList<out String> by parameters
assertEquals(listOf<Any?>("3", "4"), multiple.toList())
}
@Test
fun testMultipleAsIntegers() {
val multiple: List<Int> by parameters
assertEquals(listOf(3, 4), multiple)
}
@Test
fun testMultipleAsLongIntegers() {
val multiple: List<Long> by parameters
assertEquals(listOf(3L, 4L), multiple)
}
}
| ktor-server/ktor-server-core/jvmAndNix/test/io/ktor/server/http/ParametersTest.kt | 2395056133 |
package com.cultureoftech.kotlinweather.weather
import java.util.*
/**
* Created by bgogetap on 2/21/16.
*/
data class CityForecastResponse(val city: City, val list: Array<Day>) {
data class City(val id: Long, val name: String, val country: String)
data class Day(val dt: Long, val temp: Temp, val humidity: Double) {
fun getDate(): Date {
return Date(dt*1000)
}
}
data class Temp(val day: Double, val min: Double, val max: Double, val night: Double, val eve: Double, val morn: Double)
} | app/src/main/kotlin/com/cultureoftech/kotlinweather/weather/CityForecastResponse.kt | 216835937 |
package io.casey.musikcube.remote.ui.tracks.activity
import android.content.Context
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.ui.shared.activity.FragmentActivityWithTransport
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.tracks.constant.Track
import io.casey.musikcube.remote.ui.tracks.fragment.TrackListFragment
class TrackListActivity: FragmentActivityWithTransport() {
private val tracks
get() = content as TrackListFragment
override fun onCreateOptionsMenu(menu: Menu): Boolean =
tracks.createOptionsMenu(menu)
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (tracks.optionsItemSelected(item)) {
true -> true
false -> super.onOptionsItemSelected(item)
}
override fun createContentFragment(): BaseFragment = TrackListFragment.create(intent)
override val contentFragmentTag: String = TrackListFragment.TAG
companion object {
fun getOfflineStartIntent(context: Context): Intent =
getStartIntent(context, Metadata.Category.OFFLINE, 0).apply {
putExtra(Track.Extra.TITLE_ID, R.string.offline_tracks_title)
}
fun getStartIntent(context: Context,
categoryType: String = "",
categoryId: Long = 0,
categoryValue: String = ""): Intent =
Intent(context, TrackListActivity::class.java).apply {
putExtra(
Track.Extra.FRAGMENT_ARGUMENTS,
TrackListFragment.arguments(context, categoryType, categoryId, categoryValue))
}
}
}
| src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/activity/TrackListActivity.kt | 628046927 |
package io.armcha.ribble.data.mapper
import io.armcha.ribble.data.response.*
import io.armcha.ribble.domain.entity.*
import io.armcha.ribble.presentation.utils.extensions.emptyString
import io.armcha.ribble.presentation.utils.extensions.toHtml
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Chatikyan on 03.08.2017.
*/
class Mapper {
@JvmName("translateShotEntity")
fun translate(shotResponseList: List<ShotResponse>): List<Shot> {
return shotResponseList
.asSequence()
.map {
translate(it)
}
.toList()
}
@JvmName("translateLikeEntity")
fun translate(likeResponseList: List<LikeResponse>): List<Like> {
return likeResponseList
.asSequence()
.map {
Like(it.id, translate(it.shotResponse))
}
.toList()
}
@JvmName("translateCommentEntity")
fun translate(commentResponseList: List<CommentResponse>): List<Comment> {
return commentResponseList
.asSequence()
.map {
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)
Comment(it.comment?.toHtml(), translate(it.user), it.likesCount, format.parse(it.createdAt))
}
.toList()
}
fun translate(userResponse: UserResponse?): User {
return User(userResponse?.name,
userResponse?.avatarUrl ?: emptyString,
userResponse?.username,
userResponse?.location ?: emptyString)
}
private fun translate(imageResponse: ImageResponse?): Image {
return imageResponse.let {
Image(imageResponse?.small ?: emptyString,
imageResponse?.normal ?: emptyString,
imageResponse?.big ?: emptyString)
}
}
private fun translate(shotResponse: ShotResponse?): Shot {
return Shot(shotResponse?.title,
shotResponse?.id,
translate(shotResponse?.image),
translate(shotResponse?.user),
shotResponse?.description,
shotResponse?.likesCount,
shotResponse?.viewsCount,
shotResponse?.bucketsCount)
}
} | app/src/main/kotlin/io/armcha/ribble/data/mapper/Mapper.kt | 2435531303 |
package eu.kanade.tachiyomi.ui.library
import androidx.core.view.isVisible
import coil.clear
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.databinding.SourceCompactGridItemBinding
import eu.kanade.tachiyomi.util.view.loadAnyAutoPause
/**
* Class used to hold the displayed data of a manga in the library, like the cover or the title.
* All the elements from the layout file "source_compact_grid_item" are available in this class.
*
* @param binding the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @param coverOnly true if title should be hidden a.k.a cover only mode.
* @constructor creates a new library holder.
*/
class LibraryCompactGridHolder(
override val binding: SourceCompactGridItemBinding,
adapter: FlexibleAdapter<*>,
private val coverOnly: Boolean
) : LibraryHolder<SourceCompactGridItemBinding>(binding.root, adapter) {
/**
* Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this
* holder with the given manga.
*
* @param item the manga item to bind.
*/
override fun onSetValues(item: LibraryItem) {
// Update the title of the manga.
binding.title.text = item.manga.title
// For rounded corners
binding.badges.leftBadges.clipToOutline = true
binding.badges.rightBadges.clipToOutline = true
// Update the unread count and its visibility.
with(binding.badges.unreadText) {
isVisible = item.unreadCount > 0
text = item.unreadCount.toString()
}
// Update the download count and its visibility.
with(binding.badges.downloadText) {
isVisible = item.downloadCount > 0
text = item.downloadCount.toString()
}
// Update the source language and its visibility
with(binding.badges.languageText) {
isVisible = item.sourceLanguage.isNotEmpty()
text = item.sourceLanguage
}
// set local visibility if its local manga
binding.badges.localText.isVisible = item.isLocal
// Update the cover.
binding.thumbnail.clear()
if (coverOnly) {
// Cover only mode: Hides title text unless thumbnail is unavailable
if (!item.manga.thumbnail_url.isNullOrEmpty()) {
binding.thumbnail.loadAnyAutoPause(item.manga)
binding.title.isVisible = false
} else {
binding.title.text = item.manga.title
binding.title.isVisible = true
}
binding.thumbnail.foreground = null
} else {
binding.thumbnail.loadAnyAutoPause(item.manga)
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCompactGridHolder.kt | 5884909 |
package io.armcha.ribble.presentation.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import io.armcha.ribble.di.scope.PerActivity
import io.armcha.ribble.presentation.screen.shot.ShotFragment
import io.armcha.ribble.presentation.screen.shot.TYPE_POPULAR
import io.armcha.ribble.presentation.screen.shot.TYPE_RECENT
import javax.inject.Inject
/**
* Created by Chatikyan on 06.08.2017.
*/
@PerActivity
class ShotPagerAdapter @Inject constructor(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
private val titles = listOf("Popular", "Recent")
override fun getItem(position: Int): Fragment {
return if (position == 0)
ShotFragment.newInstance(TYPE_POPULAR)
else
ShotFragment.newInstance(TYPE_RECENT)
}
override fun getCount(): Int = titles.count()
override fun getPageTitle(position: Int) = titles[position]
} | app/src/main/kotlin/io/armcha/ribble/presentation/adapter/ShotPagerAdapter.kt | 3447834629 |
/*
* Copyright 2021 Michael Rozumyanskiy
*
* 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.michaelrocks.grip.mirrors.signature
import io.michaelrocks.grip.commons.LazyList
import io.michaelrocks.grip.mirrors.GenericTypeListWrapper
import io.michaelrocks.grip.mirrors.Type
import org.objectweb.asm.signature.SignatureReader
import java.util.Collections
interface ClassSignatureMirror {
val typeVariables: List<GenericType.TypeVariable>
val superType: GenericType
val interfaces: List<GenericType>
fun toJvmSignature(): String
class Builder {
private val typeVariables = LazyList<GenericType.TypeVariable>()
private var superType: GenericType = OBJECT_RAW_TYPE
private val interfaces = LazyList<GenericType>()
fun addTypeVariable(builder: GenericType.TypeVariable) = apply {
typeVariables += builder
}
fun superType(superType: GenericType) = apply {
this.superType = superType
}
fun addInterface(interfaceType: GenericType) = apply {
interfaces += interfaceType
}
fun build(): ClassSignatureMirror = ClassSignatureMirrorImpl(this)
private class ClassSignatureMirrorImpl(builder: Builder) : ClassSignatureMirror {
override val typeVariables: List<GenericType.TypeVariable> = builder.typeVariables.detachImmutableCopy()
override val superType: GenericType = builder.superType
override val interfaces: List<GenericType> = builder.interfaces.detachImmutableCopy()
override fun toJvmSignature() = throw UnsupportedOperationException()
}
}
}
internal class LazyClassSignatureMirror(
asmApi: Int,
enclosingGenericDeclaration: GenericDeclaration,
private val signature: String,
) : ClassSignatureMirror {
private val delegate by lazy(LazyThreadSafetyMode.PUBLICATION) {
ClassSignatureReader(asmApi, enclosingGenericDeclaration).run {
SignatureReader(signature).accept(this)
toClassSignature()
}
}
override val typeVariables: List<GenericType.TypeVariable>
get() = delegate.typeVariables
override val superType: GenericType
get() = delegate.superType
override val interfaces: List<GenericType>
get() = delegate.interfaces
override fun toJvmSignature() = signature
}
internal class EmptyClassSignatureMirror(superType: Type?, interfaces: List<Type>) : ClassSignatureMirror {
override val typeVariables: List<GenericType.TypeVariable>
get() = Collections.emptyList()
override val superType =
superType?.let { GenericType.Raw(it) } ?: OBJECT_RAW_TYPE
override val interfaces: List<GenericType> =
if (interfaces.isEmpty()) emptyList() else GenericTypeListWrapper(interfaces)
override fun toJvmSignature() = ""
}
internal fun ClassSignatureMirror.asGenericDeclaration(): GenericDeclaration {
return GenericDeclaration(typeVariables)
}
internal fun ClassSignatureMirror.asLazyGenericDeclaration(): GenericDeclaration {
return LazyGenericDeclaration { asGenericDeclaration() }
}
| library/src/main/java/io/michaelrocks/grip/mirrors/signature/ClassSignatureMirror.kt | 1526585943 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord.framework
import com.intellij.openapi.roots.libraries.LibraryKind
val BUNGEECORD_LIBRARY_KIND: LibraryKind = LibraryKind.create("bungeecord-api")
val WATERFALL_LIBRARY_KIND: LibraryKind = LibraryKind.create("waterfall-api")
| src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/framework/BungeeCordLibraryKind.kt | 3238983562 |
/*
* Copyright 2014-2019 Julien Guerinet
*
* 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.guerinet.mymartlet.ui
import android.content.res.Configuration
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import com.guerinet.morf.Morf
import com.guerinet.morf.morf
import com.guerinet.mymartlet.R
import com.guerinet.mymartlet.model.Course
import com.guerinet.mymartlet.model.Term
import com.guerinet.mymartlet.model.place.Place
import com.guerinet.mymartlet.ui.dialog.list.TermDialogHelper
import com.guerinet.mymartlet.ui.walkthrough.WalkthroughActivity
import com.guerinet.mymartlet.util.Constants
import com.guerinet.mymartlet.util.DayUtils
import com.guerinet.mymartlet.util.Prefs
import com.guerinet.mymartlet.util.manager.HomepageManager
import com.guerinet.mymartlet.util.prefs.DefaultTermPref
import com.guerinet.mymartlet.util.retrofit.TranscriptConverter.TranscriptResponse
import com.guerinet.mymartlet.util.room.daos.CourseDao
import com.guerinet.mymartlet.util.room.daos.TranscriptDao
import com.guerinet.suitcase.coroutines.bgDispatcher
import com.guerinet.suitcase.coroutines.uiDispatcher
import com.guerinet.suitcase.date.extensions.getLongDateString
import com.guerinet.suitcase.prefs.BooleanPref
import com.guerinet.suitcase.util.extensions.getColorCompat
import com.guerinet.suitcase.util.extensions.openUrl
import kotlinx.android.synthetic.main.activity_schedule.*
import kotlinx.android.synthetic.main.fragment_day.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.android.ext.android.inject
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.temporal.ChronoUnit
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.util.Stack
/**
* Displays the user's schedule
* @author Julien Guerinet
* @since 1.0.0
*/
class ScheduleActivity : DrawerActivity() {
private val firstOpenPref by inject<BooleanPref>(Prefs.IS_FIRST_OPEN)
private val twentyFourHourPref by inject<BooleanPref>(Prefs.SCHEDULE_24HR)
private val defaultTermPref by inject<DefaultTermPref>()
private val courseDao by inject<CourseDao>()
private val transcriptDao by inject<TranscriptDao>()
private var term: Term = defaultTermPref.term
private val courses: MutableList<Course> = mutableListOf()
// We need this to know which week to show in the landscape orientation
private var date: LocalDate = LocalDate.now()
override val currentPage = HomepageManager.HomePage.SCHEDULE
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_schedule)
val savedTerm = savedInstanceState?.get(Constants.TERM) as? Term
if (savedTerm != null) {
term = savedTerm
}
// Update the list of courses for this currentTerm and the starting date
updateCoursesAndDate()
// // Render the right view based on the orientation
// if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// renderLandscapeView()
// } else {
// renderPortraitView()
// }
// Check if this is the first time the user is using the app
if (firstOpenPref.value) {
// Show them the walkthrough if it is
startActivity<WalkthroughActivity>(Prefs.IS_FIRST_OPEN to true)
// Save the fact that the walkthrough has been seen at least once
firstOpenPref.value = false
}
}
// Only show the menu in portrait mode
override fun onPrepareOptionsMenu(menu: Menu): Boolean =
resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.refresh, menu)
menuInflater.inflate(R.menu.change_semester, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_change_semester -> {
TermDialogHelper(this, this, term) {
// If it's the same currentTerm as now, do nothing
if (it == term) {
return@TermDialogHelper
}
// Set the instance currentTerm
term = it
// Set the default currentTerm
defaultTermPref.term = term
// Update the courses
updateCoursesAndDate()
// Refresh the content
refreshCourses()
}
return true
}
R.id.action_refresh -> {
refreshCourses()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
// Save the currentTerm
outState.putSerializable(Constants.TERM, term)
}
private suspend fun updateCourses() {
withContext(bgDispatcher) {
// Clear the current courses
courses.clear()
// Get the new courses for the current currentTerm
val localCourses = courseDao.getTermCourses(term)
courses.addAll(localCourses)
}
}
/**
* Gets the courses for the given [Term]
*/
private fun updateCoursesAndDate() {
launch(Dispatchers.Default) {
updateCourses()
// Date is by default set to today
date = LocalDate.now()
// Check if we are in the current semester
if (term != Term.currentTerm()) {
// If not, find the starting date of this semester instead of using today
for (course in courses) {
if (course.startDate.isBefore(date)) {
date = course.startDate
}
}
}
withContext(uiDispatcher) {
// Title
title = term.getString(this@ScheduleActivity)
// TODO This only renders the portrait view
renderPortraitView()
}
}
}
/**
* Refreshes the list of courses for the given currentTerm and the user's transcript
* (only available in portrait mode)
*/
private fun refreshCourses() {
if (!canRefresh()) {
return
}
// Download the courses for this currentTerm
mcGillService.schedule(term).enqueue(object : Callback<List<Course>> {
override fun onResponse(call: Call<List<Course>>, response: Response<List<Course>>) {
launch(Dispatchers.IO) {
courseDao.update(response.body() ?: listOf(), term)
withContext(uiDispatcher) {
// Update the view
toolbarProgress.isVisible = false
updateCourses()
@Suppress("PLUGIN_WARNING")
viewPager.adapter?.notifyDataSetChanged()
}
}
// Download the transcript (if ever the user has new semesters on their transcript)
mcGillService.oldTranscript().enqueue(object : Callback<TranscriptResponse> {
override fun onResponse(
call: Call<TranscriptResponse>,
response: Response<TranscriptResponse>
) {
launch(Dispatchers.IO) {
transcriptDao.update(response.body()?.transcript!!)
}
}
override fun onFailure(call: Call<TranscriptResponse>, t: Throwable) {
handleError("refreshing the transcript", t)
}
})
}
override fun onFailure(call: Call<List<Course>>, t: Throwable) {
handleError("refreshing the courses", t)
}
})
}
/* TODO Bring landscape view back
/**
* Renders the landscape view
*/
@Suppress("PLUGIN_WARNING")
private fun renderLandscapeView() {
// Leave space at the top for the day names
var dayView = View.inflate(this, R.layout.fragment_day_name, null)
// Black line to separate the timetable from the schedule
val dayViewLine = dayView.findViewById<View>(R.id.day_line)
dayViewLine.visibility = View.VISIBLE
// Add the day view to the top of the timetable
timetableContainer.addView(dayView)
// Find the index of the given date
val currentDayIndex = date.dayOfWeek.value
// Go through the 7 days of the week
for (i in 1..7) {
val day = DayOfWeek.of(i)
// Set up the day name
dayView = View.inflate(this, R.layout.fragment_day_name, null)
val dayViewTitle = dayView.findViewById<TextView>(R.id.day_name)
dayViewTitle.setText(DayUtils.getStringId(day))
scheduleContainer!!.addView(dayView)
// Set up the schedule container for that one day
val scheduleContainer = LinearLayout(this)
scheduleContainer.orientation = LinearLayout.VERTICAL
scheduleContainer.layoutParams = LinearLayout.LayoutParams(
resources.getDimensionPixelSize(R.dimen.cell_landscape_width),
ViewGroup.LayoutParams.WRAP_CONTENT)
// Fill the schedule for the current day
fillSchedule(this.timetableContainer, scheduleContainer,
date.plusDays((i - currentDayIndex).toLong()), false)
// Add the current day to the schedule container
this.scheduleContainer!!.addView(scheduleContainer)
// Line
val line = View(this)
line.setBackgroundColor(Color.BLACK)
line.layoutParams = ViewGroup.LayoutParams(
resources.getDimensionPixelSize(R.dimen.schedule_line),
ViewGroup.LayoutParams.MATCH_PARENT)
this.scheduleContainer!!.addView(line)
}
}
*/
/**
* Renders the portrait view
*/
private fun renderPortraitView() {
val viewPager = this.viewPager ?: throw IllegalStateException("No ViewPager found")
val adapter = ScheduleAdapter()
// Set up the ViewPager
viewPager.apply {
this.adapter = adapter
currentItem = adapter.startingDateIndex
addOnPageChangeListener(object :
androidx.viewpager.widget.ViewPager.OnPageChangeListener {
override fun onPageScrolled(i: Int, v: Float, i2: Int) {}
override fun onPageSelected(i: Int) {
//Update the date every time the page is turned to have the right
// week if ever the user rotates his device
date = adapter.getDate(i)
}
override fun onPageScrollStateChanged(i: Int) {}
})
}
}
/**
* Fills the schedule based on given data
*
* @param timetableContainer Container for the timetable
* @param scheduleContainer Container for the schedule
* @param date Date to fill the schedule for
* @param clickable True if the user can click on the courses (portrait),
* false otherwise (landscape)
*/
private fun fillSchedule(
timetableContainer: LinearLayout?,
scheduleContainer: LinearLayout?,
date: LocalDate,
clickable: Boolean
) {
if (timetableContainer == null || scheduleContainer == null) {
return
}
// Clear everything out
timetableContainer.removeAllViews()
scheduleContainer.removeAllViews()
// Go through the list of courses, find which ones are for the given date
val courses = this.courses.filter { it.isForDate(date) }
// Set up the DateTimeFormatter we're going to use for the hours
val pattern = if (twentyFourHourPref.value) "HH:mm" else "hh a"
val formatter = DateTimeFormatter.ofPattern(pattern)
// This will be used of an end time of a course when it is added to the schedule container
var currentCourseEndTime: LocalTime? = null
// Cycle through the hours
for (hour in 8..21) {
// Start inflating a timetable cell
val timetableCell = View.inflate(this, R.layout.item_day_timetable, null)
// Put the correct time
val time = timetableCell.findViewById<TextView>(R.id.cell_time)
time.text = LocalTime.MIDNIGHT.withHour(hour).format(formatter)
// Add it to the right container
timetableContainer.addView(timetableCell)
// Cycle through the half hours
var min = 0
while (min < 31) {
// Initialize the current course to null
var currentCourse: Course? = null
// Get the current time
val currentTime = LocalTime.of(hour, min)
// if currentCourseEndTime = null (no course is being added) or it is equal to
// the current time in min (end of a course being added) we need to add a new view
if (currentCourseEndTime == null || currentCourseEndTime == currentTime) {
// Reset currentCourseEndTime
currentCourseEndTime = null
// Check if there is a course at this time
for (course in courses) {
// If there is, set the current course to that time, and calculate the
// ending time of this course
if (course.roundedStartTime == currentTime) {
currentCourse = course
currentCourseEndTime = course.roundedEndTime
break
}
}
val scheduleCell: View
// There is a course at this time
if (currentCourse != null) {
// Inflate the right view
scheduleCell = View.inflate(this, R.layout.item_day_class, null)
// Set up all of the info
val code = scheduleCell.findViewById<TextView>(R.id.code)
code.text = currentCourse.code
val type = scheduleCell.findViewById<TextView>(R.id.type)
type.text = currentCourse.type
val courseTime = scheduleCell.findViewById<TextView>(R.id.course_time)
courseTime.text = currentCourse.timeString
val location = scheduleCell.findViewById<TextView>(R.id.course_location)
location.text = currentCourse.location
// Find out how long this course is in terms of blocks of 30 min
val length = ChronoUnit.MINUTES.between(
currentCourse.roundedStartTime,
currentCourse.roundedEndTime
).toInt() / 30
// Set the height of the view depending on this height
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
resources
.getDimension(R.dimen.cell_30min_height).toInt() * length
)
scheduleCell.layoutParams = lp
// Check if we need to make the course clickable
if (clickable) {
// We need a final variable for the onClick listener
val course = currentCourse
// OnClick: CourseActivity (for a detailed description of the course)
scheduleCell.setOnClickListener { showCourseDialog(course) }
} else {
scheduleCell.isClickable = false
}
} else {
// Inflate the empty view
scheduleCell = View.inflate(this, R.layout.item_day_empty, null)
}
// Add the given view to the schedule container
scheduleContainer.addView(scheduleCell)
}
min += 30
}
}
}
/**
* Shows a dialog with course information
*
* @param course Clicked [Course]
*/
private fun showCourseDialog(course: Course) {
analytics.event("schedule_course_details")
// Set up the view in the dialog
val view = ScrollView(this)
val container = LinearLayout(this)
container.orientation = LinearLayout.VERTICAL
view.addView(container)
// Create the dialog
val alert = AlertDialog.Builder(this)
.setView(view)
.setCancelable(true)
.setNeutralButton(R.string.done) { dialog, _ -> dialog.dismiss() }
.show()
// Populate the form
val shape = Morf.shape
// .setShowLine(false)
// .setInputDefaultBackground(android.R.color.transparent)
container.morf(shape) {
// Code
addTextInput(R.string.course_code, course.code)
// Title
addTextInput(R.string.course_name, course.title)
// Time
addTextInput(R.string.course_time_title, course.timeString)
// Location
addTextInput(R.string.course_location, course.location)
// Type
addTextInput(R.string.schedule_type, course.type)
// Instructor
addTextInput(R.string.course_prof, course.instructor)
// Section
addTextInput(R.string.course_section, course.section)
// Credits
addTextInput(R.string.course_credits_title, course.credits.toString())
// CRN
addTextInput(R.string.course_crn, course.crn.toString())
val color = getColorCompat(R.color.red)
// Docuum
borderlessButton {
layoutParams(
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
), Gravity.CENTER
)
textId = R.string.course_docuum
textColor = color
onClick {
openUrl(
"http://www.docuum.com/mcgill/${course.subject.toLowerCase()}" +
"/${course.number}"
)
}
}
// Maps
borderlessButton {
layoutParams(
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
), Gravity.CENTER
)
textId = R.string.course_map
textColor = color
onClick {
// Try to find a place that has the right name
launch(uiDispatcher) {
// Load the places from the Firestore
val place =
Place.loadPlaces().firstOrNull { course.location.contains(it.coursePlaceName, true) }
if (place == null) {
// Tell the user
toast(getString(R.string.error_place_not_found, course.location))
// Send a Crashlytics report
Timber.e(NullPointerException("Location not found: ${course.location}"))
} else {
// Close the dialog
alert.dismiss()
// Open the map to the given place
val intent = intentFor<MapActivity>(Constants.ID to place.id)
switchDrawerActivity(intent)
}
}
}
}
}
}
private fun Morf.addTextInput(@StringRes hintId: Int, text: String) = textInput {
this.hintId = hintId
this.text = text
isEnabled = false
}
/**
* Adapter used for the ViewPager in the portrait view of the schedule
*/
internal inner class ScheduleAdapter : androidx.viewpager.widget.PagerAdapter() {
/**
* The initial date to use as a reference
*/
private val startingDate = date
/**
* The index of the starting date (offset of 500001 to get the right day)
*/
val startingDateIndex = 500001 + date.dayOfWeek.value
private val holders = Stack<DayHolder>()
override fun instantiateItem(collection: ViewGroup, position: Int): Any {
val holder = if (holders.isNotEmpty()) {
holders.pop()
} else {
DayHolder(
LayoutInflater.from(collection.context)
.inflate(R.layout.fragment_day, collection, false)
)
}
// Get the date for this view and set it
holder.bind(getDate(position))
collection.addView(holder.view)
return holder.view
}
override fun destroyItem(collection: ViewGroup, position: Int, view: Any) {
val dayView = view as? View ?: error("PagerAdapter item was not View type")
collection.removeView(dayView)
holders.push(DayHolder(view))
}
override fun getCount() = 1000000
fun getDate(position: Int): LocalDate =
startingDate.plusDays((position - startingDateIndex).toLong())
// This is to force the refreshing of all of the views when the view is reloaded
override fun getItemPosition(`object`: Any): Int =
androidx.viewpager.widget.PagerAdapter.POSITION_NONE
override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object`
inner class DayHolder(val view: View) {
internal fun bind(date: LocalDate) {
// Set the titles
view.apply {
dayTitle.setText(DayUtils.getStringId(date.dayOfWeek))
dayDate.text = date.getLongDateString()
// Fill the schedule up
fillSchedule(timetableContainer, scheduleContainer, date, true)
}
}
}
}
}
| app/src/main/java/ui/ScheduleActivity.kt | 4215597776 |
package org.hisp.dhis.android.core.relationship
interface RelationshipService {
fun hasAccessPermission(relationshipType: RelationshipType): Boolean
}
| core/src/main/java/org/hisp/dhis/android/core/relationship/RelationshipService.kt | 1970986050 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.HabitMatcher
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.ui.ThemeSwitcher
import javax.inject.Inject
class ListHabitsMenuBehavior @Inject constructor(
private val screen: Screen,
private val adapter: Adapter,
private val preferences: Preferences,
private val themeSwitcher: ThemeSwitcher
) {
private var showCompleted: Boolean
private var showArchived: Boolean
fun onCreateHabit() {
screen.showSelectHabitTypeDialog()
}
fun onViewFAQ() {
screen.showFAQScreen()
}
fun onViewAbout() {
screen.showAboutScreen()
}
fun onViewSettings() {
screen.showSettingsScreen()
}
fun onToggleShowArchived() {
showArchived = !showArchived
preferences.showArchived = showArchived
updateAdapterFilter()
}
fun onToggleShowCompleted() {
showCompleted = !showCompleted
preferences.showCompleted = showCompleted
updateAdapterFilter()
}
fun onSortByManually() {
adapter.primaryOrder = HabitList.Order.BY_POSITION
}
fun onSortByColor() {
onSortToggleBy(HabitList.Order.BY_COLOR_ASC, HabitList.Order.BY_COLOR_DESC)
}
fun onSortByScore() {
onSortToggleBy(HabitList.Order.BY_SCORE_DESC, HabitList.Order.BY_SCORE_ASC)
}
fun onSortByName() {
onSortToggleBy(HabitList.Order.BY_NAME_ASC, HabitList.Order.BY_NAME_DESC)
}
fun onSortByStatus() {
onSortToggleBy(HabitList.Order.BY_STATUS_ASC, HabitList.Order.BY_STATUS_DESC)
}
private fun onSortToggleBy(defaultOrder: HabitList.Order, reversedOrder: HabitList.Order) {
if (adapter.primaryOrder != defaultOrder) {
if (adapter.primaryOrder != reversedOrder) {
adapter.secondaryOrder = adapter.primaryOrder
}
adapter.primaryOrder = defaultOrder
} else {
adapter.primaryOrder = reversedOrder
}
}
fun onToggleNightMode() {
themeSwitcher.toggleNightMode()
screen.applyTheme()
}
fun onPreferencesChanged() {
updateAdapterFilter()
}
private fun updateAdapterFilter() {
if (preferences.areQuestionMarksEnabled) {
adapter.setFilter(
HabitMatcher(
isArchivedAllowed = showArchived,
isEnteredAllowed = showCompleted,
)
)
} else {
adapter.setFilter(
HabitMatcher(
isArchivedAllowed = showArchived,
isCompletedAllowed = showCompleted,
)
)
}
adapter.refresh()
}
interface Adapter {
fun refresh()
fun setFilter(matcher: HabitMatcher)
var primaryOrder: HabitList.Order
var secondaryOrder: HabitList.Order
}
interface Screen {
fun applyTheme()
fun showAboutScreen()
fun showFAQScreen()
fun showSettingsScreen()
fun showSelectHabitTypeDialog()
}
init {
showCompleted = preferences.showCompleted
showArchived = preferences.showArchived
updateAdapterFilter()
}
}
| uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/list/ListHabitsMenuBehavior.kt | 2936595248 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.impl.service
import com.mcmoonlake.api.service.ServiceAbstract
/**
* 如果继承此服务,那么此服务不可卸载。只有当插件被 disable 时才会释放。
* 注:此服务用于 MoonLake 内的核心服务,请勿依赖此模块。随时将会改动。
*/
abstract class ServiceAbstractCore : ServiceAbstract() {
}
| Core/src/main/kotlin/com/mcmoonlake/impl/service/ServiceAbstractCore.kt | 2848322693 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.map
import com.google.android.ground.model.locationofinterest.LocationOfInterest
/** A [LocationOfInterest] associated with a map. */
data class MapLocationOfInterest(val locationOfInterest: LocationOfInterest)
| ground/src/main/java/com/google/android/ground/ui/map/MapLocationOfInterest.kt | 3570075371 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.receivers
import android.content.Context
import android.content.Intent
import android.net.Uri
import org.isoron.uhabits.core.AppScope
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.reminders.ReminderScheduler
import org.isoron.uhabits.core.ui.NotificationTray
import org.isoron.uhabits.core.utils.DateUtils.Companion.getUpcomingTimeInMillis
import org.isoron.uhabits.notifications.SnoozeDelayPickerActivity
import javax.inject.Inject
@AppScope
class ReminderController @Inject constructor(
private val reminderScheduler: ReminderScheduler,
private val notificationTray: NotificationTray,
private val preferences: Preferences
) {
fun onBootCompleted() {
reminderScheduler.scheduleAll()
}
fun onShowReminder(
habit: Habit,
timestamp: Timestamp,
reminderTime: Long
) {
notificationTray.show(habit, timestamp, reminderTime)
reminderScheduler.scheduleAll()
}
fun onSnoozePressed(habit: Habit, context: Context) {
showSnoozeDelayPicker(habit, context)
}
fun onSnoozeDelayPicked(habit: Habit, delayInMinutes: Int) {
reminderScheduler.snoozeReminder(habit, delayInMinutes.toLong())
notificationTray.cancel(habit)
}
fun onSnoozeTimePicked(habit: Habit?, hour: Int, minute: Int) {
val time: Long = getUpcomingTimeInMillis(hour, minute)
reminderScheduler.scheduleAtTime(habit!!, time)
notificationTray.cancel(habit)
}
fun onDismiss(habit: Habit) {
notificationTray.cancel(habit)
}
private fun showSnoozeDelayPicker(habit: Habit, context: Context) {
context.sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))
val intent = Intent(context, SnoozeDelayPickerActivity::class.java)
intent.data = Uri.parse(habit.uriString)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
| uhabits-android/src/main/java/org/isoron/uhabits/receivers/ReminderController.kt | 2472173105 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
data class PacketInSteerVehicle(
var strafeSpeed: Float,
var forwardSpeed: Float,
var jumping: Boolean,
var sneaking: Boolean
) : PacketInBukkitAbstract("PacketPlayInSteerVehicle") {
@Deprecated("")
constructor() : this(0f, 0f, false, false)
override fun read(data: PacketBuffer) {
strafeSpeed = data.readFloat()
forwardSpeed = data.readFloat()
val flag = data.readByte().toInt()
jumping = (flag and 1) > 0
sneaking = (flag and 2) > 0
}
override fun write(data: PacketBuffer) {
data.writeFloat(strafeSpeed)
data.writeFloat(forwardSpeed)
var flag = 0
if(jumping)
flag = flag or 1
if(sneaking)
flag = flag or 2
data.writeByte(flag)
}
}
| API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInSteerVehicle.kt | 491692628 |
fun main() {
val name = "Kotlin"
val test = "$<caret>`name` test"
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantBackticks/inStringTemplate2.kt | 4182764004 |
// "Import" "true"
// ERROR: Unresolved reference: ext
import dep.TA
import dep.ext
fun use() {
val ta = TA()
ta.ext<caret>
}
/* IGNORE_FIR */ | plugins/kotlin/idea/tests/testData/quickfix/autoImports/typeAliasExtensionProperty.after.kt | 4067646251 |
// 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 git4idea.config.gpg
import com.intellij.dvcs.DvcsUtil
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ColoredTableCellRenderer
import com.intellij.ui.DoubleClickListener
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.JBLabel
import com.intellij.ui.table.JBTable
import com.intellij.util.FontUtil
import com.intellij.util.ui.JBUI
import git4idea.i18n.GitBundle.message
import git4idea.repo.GitRepository
import kotlinx.coroutines.*
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.table.AbstractTableModel
class GitGpgMultiRootConfigDialog(val project: Project,
val secretKeys: SecretKeysValue,
repoConfigs: Map<GitRepository, RepoConfigValue>) : DialogWrapper(project) {
companion object {
private const val ROOT_COLUMN = 0
private const val GPG_KEY_COLUMN = 1
}
private val uiDispatcher get() = AppUIExecutor.onUiThread(ModalityState.any()).coroutineDispatchingContext()
private val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable) { it.cancel() } }
private val repoConfigs = repoConfigs.map { Node(it.key, it.value) }
.sortedBy {
DvcsUtil.getShortRepositoryName(it.repo)
}
private val tableModel = GpgConfigTableModel()
private val table: JBTable
init {
title = message("settings.configure.sign.gpg.for.repos.dialog.title")
table = JBTable(tableModel).apply {
setDefaultRenderer(Any::class.java, MyCellRenderer())
setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
columnModel.getColumn(ROOT_COLUMN).preferredWidth = JBUI.scale(200)
columnModel.getColumn(GPG_KEY_COLUMN).preferredWidth = JBUI.scale(500)
preferredScrollableViewportSize = JBUI.size(700, -1)
object : DoubleClickListener() {
override fun onDoubleClick(e: MouseEvent): Boolean {
if (canEditConfig()) {
editConfig()
return true
}
return false
}
}.installOn(this)
}
init()
initTable()
}
override fun createSouthAdditionalPanel(): JPanel {
val label = JBLabel(message("settings.configure.sign.gpg.synced.with.gitconfig.text"))
label.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND
return JBUI.Panels.simplePanel(label)
}
override fun createCenterPanel(): JComponent {
return ToolbarDecorator.createDecorator(table)
.setEditAction { editConfig() }
.setEditActionUpdater { canEditConfig() }
.disableUpDownActions()
.createPanel()
}
override fun createActions(): Array<Action> {
return arrayOf(okAction)
}
private fun initTable() {
scope.launch(uiDispatcher +
CoroutineName("GitGpgMultiRootConfigDialog - readConfig")) {
table.setPaintBusy(true)
try {
for (repoConfig in repoConfigs) {
repoConfig.config.tryLoad()
}
tableModel.fireTableDataChanged()
secretKeys.tryLoad()
table.repaint()
}
finally {
table.setPaintBusy(false)
}
}
}
private fun canEditConfig(): Boolean {
return table.selectedRowCount == 1
}
private fun editConfig() {
val row = table.selectedRow
val node = repoConfigs[row]
GitGpgConfigDialog(node.repo, secretKeys, node.config).show()
tableModel.fireTableRowsUpdated(row, row)
}
private inner class GpgConfigTableModel : AbstractTableModel() {
override fun getRowCount() = repoConfigs.size
override fun getColumnCount() = 2
override fun getColumnName(column: Int): String {
if (column == ROOT_COLUMN) return message("settings.configure.sign.gpg.root.table.column.name")
if (column == GPG_KEY_COLUMN) return message("settings.configure.sign.gpg.gpg.kep.table.column.name")
error("Column number: $column")
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
val node = repoConfigs[rowIndex]
return when (columnIndex) {
ROOT_COLUMN -> node.repo
GPG_KEY_COLUMN -> node.config
else -> null
}
}
}
private inner class MyCellRenderer : ColoredTableCellRenderer() {
override fun customizeCellRenderer(table: JTable, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
if (value is GitRepository) {
append(DvcsUtil.getShortRepositoryName(value))
}
else if (value is RepoConfigValue) {
val error = value.error
val config = value.value
when {
error != null -> append(message("settings.configure.sign.gpg.error.table.text", error))
config == null -> append(message("settings.configure.sign.gpg.loading.table.text"))
config.key == null -> append(message("settings.configure.sign.gpg.do.not.sign.table.text"))
else -> {
append(config.key.id)
val descriptions = secretKeys.value?.descriptions ?: return
val description = descriptions[config.key]
if (description != null) {
append(FontUtil.spaceAndThinSpace())
append(description, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
}
}
}
}
}
private class Node(val repo: GitRepository, val config: RepoConfigValue)
}
| plugins/git4idea/src/git4idea/config/gpg/GitGpgMultiRootConfigDialog.kt | 2503847133 |
// 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.plugins.github.pullrequest.action
import com.intellij.collaboration.messages.CollaborationToolsBundle.messagePointer
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions.ActionText
import com.intellij.openapi.vcs.FilePath
import com.intellij.vcsUtil.VcsFileUtil.relativePath
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestFileViewedState
import org.jetbrains.plugins.github.api.data.pullrequest.isViewed
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.GIT_REPOSITORY
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.PULL_REQUEST_FILES
import java.util.function.Supplier
internal abstract class GHPRViewedStateAction(
dynamicText: Supplier<@ActionText String>,
private val isViewed: Boolean
) : DumbAwareAction(dynamicText) {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = false
val repository = e.getData(GIT_REPOSITORY) ?: return
val files = e.getData(PULL_REQUEST_FILES) ?: return
val viewedStateProvider = e.getData(PULL_REQUEST_DATA_PROVIDER)?.viewedStateData ?: return
val viewedState = viewedStateProvider.getViewedState()
e.presentation.isEnabledAndVisible = files.any { viewedState.isViewed(repository, it) == !isViewed }
}
override fun actionPerformed(e: AnActionEvent) {
val repository = e.getData(GIT_REPOSITORY)!!
val files = e.getData(PULL_REQUEST_FILES)!!
val viewedStateProvider = e.getData(PULL_REQUEST_DATA_PROVIDER)!!.viewedStateData
val viewedState = viewedStateProvider.getViewedState()
// todo seems we could make all mutations in single request
for (file in files.filter { viewedState.isViewed(repository, it) == !isViewed }) {
val repositoryRelativePath = relativePath(repository.root, file)
viewedStateProvider.updateViewedState(repositoryRelativePath, isViewed)
}
}
private fun Map<String, GHPullRequestFileViewedState>.isViewed(repository: GitRepository, file: FilePath): Boolean? {
val repositoryRelativePath = relativePath(repository.root, file)
return this[repositoryRelativePath]?.isViewed()
}
}
internal class GHPRMarkFilesViewedAction :
GHPRViewedStateAction(messagePointer("action.CodeReview.MarkChangesViewed.text"), true)
internal class GHPRMarkFilesNotViewedAction :
GHPRViewedStateAction(messagePointer("action.CodeReview.MarkChangesNotViewed.text"), false) | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRViewedStateAction.kt | 1611232097 |
package com.rollncode.backtube.screen
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
class TubeActivity : AppCompatActivity() {
companion object {
fun newInstance(context: Context) =
TubeScreenController.newInstance(context, TubeActivity::class.java)
}
private lateinit var controller: TubeScreenController
override fun onCreate(b: Bundle?) {
super.onCreate(b)
controller = TubeScreenController(this, b)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
controller.onActivityResult(requestCode)
}
} | app/src/main/java/com/rollncode/backtube/screen/TubeActivity.kt | 117028266 |
package org.intellij.markdown
public open class IElementType(public val name: String) {
override fun toString(): String {
return name
}
}
| src/org/intellij/markdown/IElementType.kt | 3540041800 |
package ru.alexxxdev.sample
import ru.alexxxdev.kGen.*
import ru.alexxxdev.kGen.FieldSpec.PropertyType.MUTABLE
import ru.alexxxdev.kGen.FieldSpec.ValueType.NULLABLE
import java.io.File
/**
* Created by alexxxdev on 28.02.17.
*/
fun main(args: Array<String>) {
val file = File("src")
kotlinFile("ru.alexxxdev.sample", "Test") {
indent = "\t"
+import(String::class)
+import(ClassName.get(File::class))
field("field1", MUTABLE, NULLABLE) {
className = ClassName.get(File::class)
"null"
}
field("field2") {
+Modifier.PRIVATE
"0"
}
method("fun2") {
+import(String::class)
+"val s = \"123\""
returns(ClassName.get(String::class)) { "s" }
}
method("fun1", Modifier.INTERNAL) {
returns { "\"test\"" }
}
kotlinClass("Class1") {
+Modifier.PRIVATE
val pV = ParameterizedName.get("V", ClassName.get(String::class))
+pV
+import(String::class)
field("field11", MUTABLE, NULLABLE) {
className = pV
"null"
}
method("fun11") {
+Modifier.INTERNAL
+"val s = \"123\""
returns(pV) { "\"test\"" }
}
}
kotlinInterface("Interface1") {
}
kotlinObject("Object1") {
}
}.writeTo(file)
} | src/ru/alexxxdev/sample/Main.kt | 3818129942 |
package tripleklay.ui
import klay.core.Surface
import klay.core.TileSource
import klay.scene.GroupLayer
import klay.scene.ImageLayer
import klay.scene.Layer
import react.RFuture
/**
* Contains icon related utility classes and methods, mostly basic icon factories.
*/
object Icons {
/**
* Defers to another icon. Subclasses decide how to modify the width and height and how to use
* the rendered layer. The base takes care of the callback. By default, returns the size and
* layer without modification.
*/
abstract class Aggregated
/** Creates a new aggregated icon that defers to the given one. */
(
/** Icon that is deferred to. */
val icon: Icon) : Icon {
override fun width(): Float {
return icon.width()
}
override fun height(): Float {
return icon.height()
}
override fun render(): Layer {
return icon.render()
}
override fun state(): RFuture<Icon> {
return icon.state()
}
}
/** Creates an icon using the supplied texture tile `source`. */
fun image(source: TileSource): Icon {
return object : Icon {
override fun width(): Float {
return (if (source.isLoaded) source.tile().width else 0f).toFloat()
}
override fun height(): Float {
return (if (source.isLoaded) source.tile().height else 0f).toFloat()
}
override fun render(): Layer {
return ImageLayer(source)
}
override fun state(): RFuture<Icon> {
return source.tileAsync().map({ this })
}
}
}
/**
* Creates an icon that applies the given scale to the given icon.
*/
fun scaled(icon: Icon, scale: Float): Icon {
return object : Aggregated(icon) {
override fun width(): Float {
return super.width() * scale
}
override fun height(): Float {
return super.height() * scale
}
override fun render(): Layer {
return super.render().setScale(scale)
}
}
}
/**
* Creates an icon that nests and offsets the given icon by the given translation.
*/
fun offset(icon: Icon, tx: Float, ty: Float): Icon {
return object : Aggregated(icon) {
override fun render(): Layer {
val layer = GroupLayer()
layer.addAt(super.render(), tx, ty)
return layer
}
}
}
/**
* Creates a solid square icon of the given size.
*/
fun solid(color: Int, size: Float): Icon {
return object : Icon {
override fun width(): Float {
return size
}
override fun height(): Float {
return size
}
override fun state(): RFuture<Icon> {
return RFuture.success<Icon>(this)
}
override fun render(): Layer {
return object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(color).fillRect(0f, 0f, size, size)
}
}
}
}
}
}
| tripleklay/src/main/kotlin/tripleklay/ui/Icons.kt | 3694042502 |
package soutvoid.com.DsrWeatherApp.domain.city
import com.google.gson.annotations.SerializedName
import soutvoid.com.DsrWeatherApp.domain.coordinates.Coordinates
data class CityOwm(
@SerializedName("id")
val id: Long,
@SerializedName("name")
val name: String,
@SerializedName("coord")
val coordinates: Coordinates,
@SerializedName("country")
val country : String
) | app/src/main/java/soutvoid/com/DsrWeatherApp/domain/city/CityOwm.kt | 635453329 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.gallery
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.afollestad.materialdialogs.MaterialDialog
import com.evernote.android.state.State
import de.dreier.mytargets.R
import de.dreier.mytargets.base.activities.ChildActivityBase
import de.dreier.mytargets.base.gallery.adapters.HorizontalListAdapters
import de.dreier.mytargets.base.gallery.adapters.ViewPagerAdapter
import de.dreier.mytargets.base.navigation.NavigationController
import de.dreier.mytargets.databinding.ActivityGalleryBinding
import de.dreier.mytargets.utils.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
import pl.aprilapps.easyphotopicker.DefaultCallback
import pl.aprilapps.easyphotopicker.EasyImage
import java.io.File
import java.io.IOException
import java.util.*
@RuntimePermissions
class GalleryActivity : ChildActivityBase() {
internal var adapter: ViewPagerAdapter? = null
internal var layoutManager: LinearLayoutManager? = null
internal lateinit var previewAdapter: HorizontalListAdapters
@State
lateinit var imageList: ImageList
private lateinit var binding: ActivityGalleryBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_gallery)
val title = intent.getStringExtra(EXTRA_TITLE)
if (savedInstanceState == null) {
imageList = intent.getParcelableExtra(EXTRA_IMAGES)
}
setSupportActionBar(binding.toolbar)
ToolbarUtils.showHomeAsUp(this)
ToolbarUtils.setTitle(this, title)
Utils.showSystemUI(this)
layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
binding.imagesHorizontalList.layoutManager = layoutManager
adapter = ViewPagerAdapter(this, imageList, binding.toolbar, binding.imagesHorizontalList)
binding.pager.adapter = adapter
previewAdapter = HorizontalListAdapters(this, imageList, { this.goToImage(it) })
binding.imagesHorizontalList.adapter = previewAdapter
previewAdapter.notifyDataSetChanged()
binding.pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
binding.imagesHorizontalList.smoothScrollToPosition(position)
previewAdapter.setSelectedItem(position)
}
override fun onPageScrollStateChanged(state: Int) {
}
})
val currentPos = 0
previewAdapter.setSelectedItem(currentPos)
binding.pager.currentItem = currentPos
if (imageList.size() == 0 && savedInstanceState == null) {
onTakePictureWithPermissionCheck()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.gallery, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.action_share).isVisible = !imageList.isEmpty
menu.findItem(R.id.action_delete).isVisible = !imageList.isEmpty
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> {
val currentItem = binding.pager.currentItem
shareImage(currentItem)
return true
}
R.id.action_delete -> {
val currentItem = binding.pager.currentItem
deleteImage(currentItem)
return true
}
android.R.id.home -> {
navigationController.finish()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun shareImage(currentItem: Int) {
val currentImage = imageList[currentItem]
val file = File(filesDir, currentImage.fileName)
val uri = file.toUri(this)
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "*/*"
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(shareIntent, getString(R.string.share)))
}
private fun deleteImage(currentItem: Int) {
MaterialDialog.Builder(this)
.content(R.string.delete_image)
.negativeText(android.R.string.cancel)
.negativeColorRes(R.color.md_grey_500)
.positiveText(R.string.delete)
.positiveColorRes(R.color.md_red_500)
.onPositive { _, _ ->
imageList.remove(currentItem)
updateResult()
invalidateOptionsMenu()
adapter!!.notifyDataSetChanged()
val nextItem = Math.min(imageList.size() - 1, currentItem)
previewAdapter.setSelectedItem(nextItem)
binding.pager.currentItem = nextItem
}
.show()
}
private fun updateResult() {
navigationController.setResultSuccess(imageList)
}
@NeedsPermission(Manifest.permission.CAMERA)
internal fun onTakePicture() {
EasyImage.openCameraForImage(this, 0)
}
@NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
internal fun onSelectImage() {
EasyImage.openGallery(this, 0)
}
@SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
EasyImage.handleActivityResult(requestCode, resultCode, data, this,
object : DefaultCallback() {
override fun onImagesPicked(
imageFiles: List<File>,
source: EasyImage.ImageSource,
type: Int
) {
loadImages(imageFiles)
}
override fun onCanceled(source: EasyImage.ImageSource?, type: Int) {
//Cancel handling, you might wanna remove taken photo if it was canceled
if (source == EasyImage.ImageSource.CAMERA_IMAGE) {
val photoFile = EasyImage
.lastlyTakenButCanceledPhoto(applicationContext)
photoFile?.delete()
}
}
})
}
private fun loadImages(imageFile: List<File>) {
object : AsyncTask<Void, Void, List<String>>() {
override fun doInBackground(vararg params: Void): List<String> {
val internalFiles = ArrayList<String>()
for (file in imageFile) {
try {
val internal = File.createTempFile("img", file.name, filesDir)
internalFiles.add(internal.name)
file.moveTo(internal)
} catch (e: IOException) {
e.printStackTrace()
}
}
return internalFiles
}
override fun onPostExecute(files: List<String>) {
super.onPostExecute(files)
imageList.addAll(files)
updateResult()
invalidateOptionsMenu()
previewAdapter.notifyDataSetChanged()
adapter!!.notifyDataSetChanged()
val currentPos = imageList.size() - 1
previewAdapter.setSelectedItem(currentPos)
binding.pager.currentItem = currentPos
}
}.execute()
}
private fun goToImage(pos: Int) {
if (imageList.size() == pos) {
onTakePictureWithPermissionCheck()
} else {
binding.pager.setCurrentItem(pos, true)
}
}
companion object {
const val EXTRA_IMAGES = "images"
const val EXTRA_TITLE = "title"
fun getResult(data: Intent): ImageList {
return data.getParcelableExtra(NavigationController.ITEM)
}
}
}
| app/src/main/java/de/dreier/mytargets/base/gallery/GalleryActivity.kt | 576796894 |
package polaris.okapi.tests.example1
import polaris.okapi.App
import polaris.okapi.options.Settings
import polaris.okapi.options.WindowMode
/**
*
* Created by Killian Le Clainche on 12/15/2017.
*/
fun main(args: Array<String>) {
val app = WindowCreation()
app.init()
app.run()
}
fun addCount(count: Int): Int = count + 1
fun addCount(count: Int, function: (Int) -> Int): Int = function(count)
class WindowCreation : App(true) {
override fun init(): Boolean {
if(super.init()) {
currentScreen = ExampleGui(this)
return true
}
return false
}
override fun loadSettings(): Settings {
val settings = Settings()
settings["mipmap"] = 0
settings["oversample"] = 1
settings["icon"] = "resources/boilermake.png"
//OPTIONAL, IN MOST CASES IT'S BEST TO LET DEFAULT BEHAVIOR PERSIST TO HAVE SAVED STATES
settings.windowMode = WindowMode.WINDOWED
settings.title = "Window Creation Test"
return settings
}
}
| tests/polaris/okapi/tests/example1/Example.kt | 1649306212 |
package pl.elpassion.elspace.common
import android.app.Activity
import android.app.Instrumentation
import android.support.test.espresso.intent.Intents
import android.support.test.espresso.intent.matcher.IntentMatchers
fun stubAllIntents() {
Intents.intending(IntentMatchers.anyIntent()).respondWith(Instrumentation.ActivityResult(Activity.RESULT_CANCELED, null))
}
| el-space-app/src/androidTest/java/pl/elpassion/elspace/common/Intents.kt | 2668148954 |
// snippet-sourcedescription:[DetectSyntax.kt demonstrates how to detect syntax in the text.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Comprehend]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.comprehend
// snippet-start:[comprehend.kotlin.detect_syntax.import]
import aws.sdk.kotlin.services.comprehend.ComprehendClient
import aws.sdk.kotlin.services.comprehend.model.DetectSyntaxRequest
import aws.sdk.kotlin.services.comprehend.model.SyntaxLanguageCode
// snippet-end:[comprehend.kotlin.detect_syntax.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main() {
val text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing."
detectAllSyntax(text)
}
// snippet-start:[comprehend.kotlin.detect_syntax.main]
suspend fun detectAllSyntax(textVal: String) {
val request = DetectSyntaxRequest {
text = textVal
languageCode = SyntaxLanguageCode.fromValue("en")
}
ComprehendClient { region = "us-east-1" }.use { comClient ->
val response = comClient.detectSyntax(request)
response.syntaxTokens?.forEach { token ->
println("Language is ${token.text}")
println("Part of speech is ${token.partOfSpeech}")
}
}
}
// snippet-end:[comprehend.kotlin.detect_syntax.main]
| kotlin/services/comprehend/src/main/kotlin/com/kotlin/comprehend/DetectSyntax.kt | 538949550 |
package com.github.codeql.utils.versions
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.declarations.IrClass
fun functionN(pluginContext: IrPluginContext): (Int) -> IrClass {
return { i -> pluginContext.irBuiltIns.functionFactory.functionN(i) }
}
| java/kotlin-extractor/src/main/kotlin/utils/versions/v_1_4_32/Functions.kt | 3258965725 |
package i_introduction._0_Hello_World
import util.TODO
import util.doc0
fun todoTask0(): Nothing = TODO(
"""
Introduction.
Kotlin Koans project consists of 42 small tasks for you to solve.
Typically you'll have to replace the function invocation 'todoTaskN()', which throws an exception,
with the correct code according to the problem.
Using 'documentation =' below the task description you can open the related part of the online documentation.
Press 'Ctrl+Q'(Windows) or 'F1'(Mac OS) on 'doc0()' to call the "Quick Documentation" action;
"See also" section gives you a link.
You can see the shortcut for the "Quick Documentation" action used in your IntelliJ IDEA
by choosing "Help -> Find Action..." (in the top menu), and typing the action name ("Quick Documentation").
The shortcut in use will be written next to the action name.
Using 'references =' you can navigate to the code mentioned in the task description.
Let's start! Make the function 'task0' return "OK".
""",
documentation = doc0(),
references = { task0(); "OK" }
)
fun task0(): String {
return todoTask0()
} | src/i_introduction/_0_Hello_World/HelloWorld.kt | 554807827 |
package com.mgaetan89.showsrage.model
import com.google.gson.Gson
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.network.SickRageApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class Episode_GetStatusBackgroundColorTest(val episode: Episode, val color: Int) {
@Test
fun getStatusBackgroundColor() {
assertThat(this.episode.getStatusBackgroundColor()).isEqualTo(this.color)
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{index}: {0} - {1}")
fun data(): Collection<Array<Any>> {
val gson = SickRageApi.gson
return listOf(
arrayOf(getJsonForStatus(gson, "archived"), R.color.green),
arrayOf(getJsonForStatus(gson, "Archived"), R.color.green),
arrayOf(getJsonForStatus(gson, "downloaded"), R.color.green),
arrayOf(getJsonForStatus(gson, "Downloaded"), R.color.green),
arrayOf(getJsonForStatus(gson, "ignored"), R.color.blue),
arrayOf(getJsonForStatus(gson, "Ignored"), R.color.blue),
arrayOf(getJsonForStatus(gson, "skipped"), R.color.blue),
arrayOf(getJsonForStatus(gson, "Skipped"), R.color.blue),
arrayOf(getJsonForStatus(gson, "snatched"), R.color.purple),
arrayOf(getJsonForStatus(gson, "snatched (proper)"), R.color.purple),
arrayOf(getJsonForStatus(gson, "Snatched"), R.color.purple),
arrayOf(getJsonForStatus(gson, "Snatched (proper)"), R.color.purple),
arrayOf(getJsonForStatus(gson, "unaired"), R.color.yellow),
arrayOf(getJsonForStatus(gson, "Unaired"), R.color.yellow),
arrayOf(getJsonForStatus(gson, "wanted"), R.color.red),
arrayOf(getJsonForStatus(gson, "Wanted"), R.color.red),
arrayOf(gson.fromJson("{}", Episode::class.java), android.R.color.transparent),
arrayOf(getJsonForStatus(gson, null), android.R.color.transparent),
arrayOf(getJsonForStatus(gson, ""), android.R.color.transparent),
arrayOf(getJsonForStatus(gson, "zstatusz"), android.R.color.transparent),
arrayOf(getJsonForStatus(gson, "ZStatusZ"), android.R.color.transparent)
)
}
private fun getJsonForStatus(gson: Gson, status: String?): Episode {
return gson.fromJson("{status: \"$status\"}", Episode::class.java)
}
}
}
| app/src/test/kotlin/com/mgaetan89/showsrage/model/Episode_GetStatusBackgroundColorTest.kt | 4180350496 |
package com.displee.cache
import com.displee.cache.index.Index
import com.displee.cache.index.Index.Companion.INDEX_SIZE
import com.displee.cache.index.Index.Companion.WHIRLPOOL_SIZE
import com.displee.cache.index.Index255
import com.displee.cache.index.Index317
import com.displee.cache.index.ReferenceTable.Companion.FLAG_4
import com.displee.cache.index.ReferenceTable.Companion.FLAG_8
import com.displee.cache.index.ReferenceTable.Companion.FLAG_NAME
import com.displee.cache.index.ReferenceTable.Companion.FLAG_WHIRLPOOL
import com.displee.cache.index.archive.Archive
import com.displee.compress.CompressionType
import com.displee.io.Buffer
import com.displee.io.impl.OutputBuffer
import com.displee.util.generateWhirlpool
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.io.RandomAccessFile
import java.math.BigInteger
import java.util.*
open class CacheLibrary(val path: String, val clearDataAfterUpdate: Boolean = false, private val listener: ProgressListener? = null) {
lateinit var mainFile: RandomAccessFile
private val indices: SortedMap<Int, Index> = TreeMap<Int, Index>()
var index255: Index255? = null
private var rs3 = false
var closed = false
init {
init()
}
private fun init() {
val mainFile317 = File(path, "$CACHE_FILE_NAME.dat")
val index255 = File(path, "$CACHE_FILE_NAME.idx255")
if (mainFile317.exists() && !index255.exists()) {
load317()
} else {
load()
}
}
/**
* Re-create indices and re-read reference tables.
*/
fun reload() {
indices.clear()
init()
}
@Throws(IOException::class)
private fun load() {
val main = File(path, "$CACHE_FILE_NAME.dat2")
mainFile = if (main.exists()) {
RandomAccessFile(main, "rw")
} else {
listener?.notify(-1.0, "Error, main file could not be found")
throw FileNotFoundException("File[path=${main.absolutePath}] could not be found.")
}
val index255File = File(path, "$CACHE_FILE_NAME.idx255")
if (!index255File.exists()) {
listener?.notify(-1.0, "Error, checksum file could not be found.")
throw FileNotFoundException("File[path=${index255File.absolutePath}] could not be found.")
}
val index255 = Index255(this, RandomAccessFile(index255File, "rw"))
this.index255 = index255
listener?.notify(0.0, "Reading indices...")
val indicesLength = index255.raf.length().toInt() / INDEX_SIZE
rs3 = indicesLength > 39
for (i in 0 until indicesLength) {
val file = File(path, "$CACHE_FILE_NAME.idx$i")
val progress = i / (indicesLength - 1.0)
if (!file.exists()) {
listener?.notify(progress, "Could not load index $i, missing idx file.")
continue
}
try {
indices[i] = Index(this, i, RandomAccessFile(file, "rw"))
listener?.notify(progress, "Loaded index $i.")
} catch (e: Exception) {
e.printStackTrace()
listener?.notify(progress, "Failed to load index $i.")
}
}
}
@Throws(IOException::class)
private fun load317() {
val main = File(path, "$CACHE_FILE_NAME.dat")
mainFile = if (main.exists()) {
RandomAccessFile(main, "rw")
} else {
listener?.notify(-1.0, "Error, main file could not be found")
throw FileNotFoundException("File[path=${main.absolutePath}] could not be found.")
}
val indexFiles = File(path).listFiles { _: File, name: String ->
return@listFiles name.startsWith("$CACHE_FILE_NAME.idx")
}
check(indexFiles != null) { "Files are null. Check your cache path." }
listener?.notify(0.0, "Reading indices...")
for (i in indexFiles.indices) {
val file = File(path, "$CACHE_FILE_NAME.idx$i")
val progress = i / (indexFiles.size - 1.0)
if (!file.exists()) {
continue
}
try {
indices[i] = Index317(this, i, RandomAccessFile(file, "rw"))
listener?.notify(progress, "Loaded index $i .")
} catch (e: Exception) {
e.printStackTrace()
listener?.notify(progress, "Failed to load index $i.")
}
}
}
@JvmOverloads
fun createIndex(compressionType: CompressionType = CompressionType.GZIP, version: Int = 6, revision: Int = 0,
named: Boolean = false, whirlpool: Boolean = false, flag4: Boolean = false, flag8: Boolean = false,
writeReferenceTable: Boolean = true): Index {
val id = indices.size
val raf = RandomAccessFile(File(path, "$CACHE_FILE_NAME.idx$id"), "rw")
val index = (if (is317()) Index317(this, id, raf) else Index(this, id, raf)).also { indices[id] = it }
if (!writeReferenceTable) {
return index
}
index.version = version
index.revision = revision
index.compressionType = compressionType
if (named) {
index.flagMask(FLAG_NAME)
}
if (whirlpool) {
index.flagMask(FLAG_WHIRLPOOL)
}
if (isRS3()) {
if (flag4) {
index.flagMask(FLAG_4)
}
if (flag8) {
index.flagMask(FLAG_8)
}
}
index.flag()
check(index.update())
return index
}
fun createIndex(index: Index, writeReferenceTable: Boolean = true): Index {
return createIndex(index.compressionType, index.version, index.revision,
index.isNamed(), index.hasWhirlpool(), index.hasFlag4(), index.hasFlag8(), writeReferenceTable)
}
fun exists(id: Int): Boolean {
return indices.containsKey(id)
}
fun index(id: Int): Index {
val index = indices[id]
checkNotNull(index) { "Index $id doesn't exist. Please use the {@link exists(int) exists} function to verify whether an index exists." }
return index
}
@JvmOverloads
fun put(index: Int, archive: Int, file: Int, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File {
return index(index).add(archive, xtea = xtea).add(file, data)
}
@JvmOverloads
fun put(index: Int, archive: Int, data: ByteArray, xtea: IntArray? = null): Archive {
val currentArchive = index(index).add(archive, -1, xtea)
currentArchive.add(0, data)
return currentArchive
}
@JvmOverloads
fun put(index: Int, archive: Int, file: String, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File {
return index(index).add(archive, xtea = xtea).add(file, data)
}
@JvmOverloads
fun put(index: Int, archive: String, data: ByteArray, xtea: IntArray? = null): Archive {
val currentArchive = index(index).add(archive, xtea = xtea)
currentArchive.add(0, data)
return currentArchive
}
@JvmOverloads
fun put(index: Int, archive: String, file: String, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File {
return index(index).add(archive, xtea = xtea).add(file, data)
}
@JvmOverloads
fun data(index: Int, archive: Int, file: Int = 0, xtea: IntArray? = null): ByteArray? {
return index(index).archive(archive, xtea)?.file(file)?.data
}
@JvmOverloads
fun data(index: Int, archive: Int, file: String, xtea: IntArray? = null): ByteArray? {
return index(index).archive(archive, xtea)?.file(file)?.data
}
@JvmOverloads
fun data(index: Int, archive: String, file: Int, xtea: IntArray? = null): ByteArray? {
return index(index).archive(archive, xtea)?.file(file)?.data
}
@JvmOverloads
fun data(index: Int, archive: String, file: String, xtea: IntArray? = null): ByteArray? {
return index(index).archive(archive, xtea)?.file(file)?.data
}
@JvmOverloads
fun data(index: Int, archive: String, xtea: IntArray? = null): ByteArray? {
return data(index, archive, 0, xtea)
}
fun remove(index: Int, archive: Int, file: Int): com.displee.cache.index.archive.file.File? {
return index(index).archive(archive)?.remove(file)
}
fun remove(index: Int, archive: Int, file: String): com.displee.cache.index.archive.file.File? {
return index(index).archive(archive)?.remove(file)
}
fun remove(index: Int, archive: String, file: String): com.displee.cache.index.archive.file.File? {
return index(index).archive(archive)?.remove(file)
}
fun remove(index: Int, archive: Int): Archive? {
return index(index).remove(archive)
}
fun remove(index: Int, archive: String): Archive? {
return index(index).remove(archive)
}
fun update() {
for (index in indices.values) {
if (index.flaggedArchives().isEmpty() && !index.flagged()) {
continue
}
index.update()
}
}
@Throws(RuntimeException::class)
fun deleteLastIndex() {
if (is317()) {
throw UnsupportedOperationException("317 not supported to remove indices yet.")
}
val id = indices.size - 1
val index = indices[id] ?: return
index.close()
val file = File(path, "$CACHE_FILE_NAME.idx$id")
if (!file.exists() || !file.delete()) {
throw RuntimeException("Failed to remove the random access file of the argued index[id=$id, file exists=${file.exists()}]")
}
index255?.raf?.setLength(id * INDEX_SIZE.toLong())
indices.remove(id)
}
fun generateOldUkeys(): ByteArray {
val buffer = OutputBuffer(indices.size * 8)
for (index in indices()) {
buffer.writeInt(index.crc)
buffer.writeInt(index.revision)
}
return buffer.array()
}
fun generateNewUkeys(exponent: BigInteger, modulus: BigInteger): ByteArray {
val buffer = OutputBuffer(6 + indices.size * 72)
buffer.offset = 5
buffer.writeByte(indices.size)
val emptyWhirlpool = ByteArray(WHIRLPOOL_SIZE)
for (index in indices()) {
buffer.writeInt(index.crc).writeInt(index.revision).writeBytes(index.whirlpool ?: emptyWhirlpool)
}
val indexArray = buffer.array()
val whirlpoolBuffer = OutputBuffer(WHIRLPOOL_SIZE + 1).writeByte(1).writeBytes(indexArray.generateWhirlpool(5, indexArray.size - 5))
buffer.writeBytes(Buffer.cryptRSA(whirlpoolBuffer.array(), exponent, modulus))
val end = buffer.offset
buffer.offset = 0
buffer.writeByte(0)
buffer.writeInt(end - 5)
buffer.offset = end
return buffer.array()
}
fun rebuild(directory: File) {
File(directory.path).mkdirs()
if (is317()) {
File(directory.path, "$CACHE_FILE_NAME.dat").createNewFile()
} else {
File(directory.path, "$CACHE_FILE_NAME.idx255").createNewFile()
File(directory.path, "$CACHE_FILE_NAME.dat2").createNewFile()
}
val indicesSize = indices.values.size
val newLibrary = CacheLibrary(directory.path)
for (index in indices.values) {
val id = index.id
print("\rBuilding index $id/$indicesSize...")
val archiveSector = index255?.readArchiveSector(id)
var writeReferenceTable = true
if (!is317() && archiveSector == null) { //some empty indices don't even have a reference table
writeReferenceTable = false //in that case, don't write it
}
val newIndex = newLibrary.createIndex(index, writeReferenceTable)
for (i in index.archiveIds()) { //only write referenced archives
val data = index.readArchiveSector(i)?.data ?: continue
newIndex.writeArchiveSector(i, data)
}
if (archiveSector != null) {
newLibrary.index255?.writeArchiveSector(id, archiveSector.data)
}
}
newLibrary.close()
println("\rFinished building $indicesSize indices.")
}
fun fixCrcs(update: Boolean) {
indices.values.forEach {
if (it.archiveIds().isEmpty()) {
return@forEach
}
it.fixCRCs(update)
}
}
fun close() {
if (closed) {
return
}
mainFile.close()
index255?.close()
indices.values.forEach { it.close() }
closed = true
}
fun first(): Index? {
if (indices.isEmpty()) {
return null
}
return indices[indices.firstKey()]
}
fun last(): Index? {
if (indices.isEmpty()) {
return null
}
return indices[indices.lastKey()]
}
fun is317(): Boolean {
return index255 == null
}
fun isOSRS(): Boolean {
val index = index(2)
return index.revision >= 300 && indices.size <= 23
}
fun isRS3(): Boolean {
return rs3
}
fun indices(): Array<Index> {
return indices.values.toTypedArray()
}
companion object {
const val CACHE_FILE_NAME = "main_file_cache"
@JvmStatic
@JvmOverloads
fun create(path: String, clearDataAfterUpdate: Boolean = false, listener: ProgressListener? = null): CacheLibrary {
return CacheLibrary(path, clearDataAfterUpdate, listener)
}
}
}
| src/main/kotlin/com/displee/cache/CacheLibrary.kt | 3314349553 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.core
object Constants {
const val restInfix = "restful/"
const val stdMimeType = "text/plain"
const val svgMimeType = "image/svg+xml"
const val pngMimeType = "image/png"
const val xmlMimeType = "application/xml"
const val calcHeight = "calc(100vh - 113px)"
const val actionSeparator = "\n"
const val subTypeJson = "json"
const val subTypeXml = "xml"
//const val krokiUrl = "https://kroki.io/" //see: https://github.com/yuzutech/kroki
const val krokiUrl = "http://localhost:8000/"
//host:port depends on how docker is started
// docker run -d --name kroki -p 8080:8000 yuzutech/kroki
const val demoUrl = "http://localhost:8080/"
const val demoUser = "sven"
const val demoPass = "pass"
const val demoUrlRemote = "https://demo-wicket.jdo.causeway.incode.work/"
val demoRemoteImage = io.kvision.require("img/incode_we_share.jpg")
const val domoxUrl = "http://localhost:8081/"
const val spacing = 10
}
| incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/Constants.kt | 3213903147 |
package au.com.dius.pact.pactbroker
import au.com.dius.pact.provider.broker.com.github.kittinunf.result.Result
import au.com.dius.pact.util.HttpClientUtils.buildUrl
import au.com.dius.pact.util.HttpClientUtils.isJsonResponse
import com.github.salomonbrys.kotson.array
import com.github.salomonbrys.kotson.bool
import com.github.salomonbrys.kotson.get
import com.github.salomonbrys.kotson.keys
import com.github.salomonbrys.kotson.nullObj
import com.github.salomonbrys.kotson.obj
import com.github.salomonbrys.kotson.string
import com.google.common.net.UrlEscapers
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import mu.KLogging
import org.apache.http.HttpResponse
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.ContentType
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import java.net.URI
import java.util.function.BiFunction
import java.util.function.Consumer
/**
* Interface to a HAL Client
*/
interface IHalClient {
/**
* Navigates the URL associated with the given link using the current HAL document
* @param options Map of key-value pairs to use for parsing templated links
* @param link Link name to navigate
*/
fun navigate(options: Map<String, Any> = mapOf(), link: String): IHalClient
/**
* Navigates the URL associated with the given link using the current HAL document
* @param link Link name to navigate
*/
fun navigate(link: String): IHalClient
/**
* Returns the HREF of the named link from the current HAL document
*/
fun linkUrl(name: String): String?
/**
* Calls the closure with a Map of attributes for all links associated with the link name
* @param linkName Name of the link to loop over
* @param closure Closure to invoke with the link attributes
*/
fun forAll(linkName: String, closure: Consumer<Map<String, Any?>>)
/**
* Upload the JSON document to the provided path, using a PUT request
* @param path Path to upload the document
* @param bodyJson JSON contents for the body
*/
fun uploadJson(path: String, bodyJson: String): Any?
/**
* Upload the JSON document to the provided path, using a PUT request
* @param path Path to upload the document
* @param bodyJson JSON contents for the body
* @param closure Closure that will be invoked with details about the response. The result from the closure will be
* returned.
*/
fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>): Any?
/**
* Upload the JSON document to the provided path, using a PUT request
* @param path Path to upload the document
* @param bodyJson JSON contents for the body
* @param closure Closure that will be invoked with details about the response. The result from the closure will be
* returned.
* @param encodePath If the path must be encoded beforehand.
*/
fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>, encodePath: Boolean): Any?
/**
* Upload the JSON document to the provided URL, using a POST request
* @param url Url to upload the document to
* @param body JSON contents for the body
* @return Returns a Success result object with a boolean value to indicate if the request was successful or not. Any
* exception will be wrapped in a Failure
*/
fun postJson(url: String, body: String): Result<Boolean, Exception>
/**
* Upload the JSON document to the provided URL, using a POST request
* @param url Url to upload the document to
* @param body JSON contents for the body
* @param handler Response handler
* @return Returns a Success result object with the boolean value returned from the handler closure. Any
* exception will be wrapped in a Failure
*/
fun postJson(url: String, body: String, handler: ((status: Int, response: CloseableHttpResponse) -> Boolean)?): Result<Boolean, Exception>
/**
* Fetches the HAL document from the provided path
* @param path The path to the HAL document. If it is a relative path, it is relative to the base URL
* @param encodePath If the path should be encoded to make a valid URL
*/
fun fetch(path: String, encodePath: Boolean): JsonElement
/**
* Fetches the HAL document from the provided path
* @param path The path to the HAL document. If it is a relative path, it is relative to the base URL
*/
fun fetch(path: String): JsonElement
}
/**
* HAL client base class
*/
abstract class HalClientBase @JvmOverloads constructor(
val baseUrl: String,
var options: Map<String, Any> = mapOf()
) : IHalClient {
var httpClient: CloseableHttpClient? = null
var pathInfo: JsonElement? = null
var lastUrl: String? = null
override fun postJson(url: String, body: String) = postJson(url, body, null)
override fun postJson(
url: String,
body: String,
handler: ((status: Int, response: CloseableHttpResponse) -> Boolean)?
): Result<Boolean, Exception> {
val client = setupHttpClient()
return Result.of {
val httpPost = HttpPost(url)
httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString())
httpPost.entity = StringEntity(body, ContentType.APPLICATION_JSON)
client.execute(httpPost).use {
if (handler != null) {
handler(it.statusLine.statusCode, it)
} else {
it.statusLine.statusCode < 300
}
}
}
}
open fun setupHttpClient(): CloseableHttpClient {
if (httpClient == null) {
val builder = HttpClients.custom().useSystemProperties()
if (options["authentication"] is List<*>) {
val authentication = options["authentication"] as List<*>
val scheme = authentication.first().toString().toLowerCase()
when (scheme) {
"basic" -> {
if (authentication.size > 2) {
val credsProvider = BasicCredentialsProvider()
val uri = URI(baseUrl)
credsProvider.setCredentials(AuthScope(uri.host, uri.port),
UsernamePasswordCredentials(authentication[1].toString(), authentication[2].toString()))
builder.setDefaultCredentialsProvider(credsProvider)
} else {
logger.warn { "Basic authentication requires a username and password, ignoring." }
}
}
else -> logger.warn { "Hal client Only supports basic authentication, got '$scheme', ignoring." }
}
} else if (options.containsKey("authentication")) {
logger.warn { "Authentication options needs to be a list of values, ignoring." }
}
httpClient = builder.build()
}
return httpClient!!
}
override fun navigate(options: Map<String, Any>, link: String): IHalClient {
pathInfo = pathInfo ?: fetch(ROOT)
pathInfo = fetchLink(link, options)
return this
}
override fun navigate(link: String) = navigate(mapOf(), link)
override fun fetch(path: String) = fetch(path, true)
override fun fetch(path: String, encodePath: Boolean): JsonElement {
lastUrl = path
logger.debug { "Fetching: $path" }
val response = getJson(path, encodePath)
when (response) {
is Result.Success -> return response.value
is Result.Failure -> throw response.error
}
}
private fun getJson(path: String, encodePath: Boolean = true): Result<JsonElement, Exception> {
setupHttpClient()
return Result.of {
val httpGet = HttpGet(buildUrl(baseUrl, path, encodePath))
httpGet.addHeader("Content-Type", "application/json")
httpGet.addHeader("Accept", "application/hal+json, application/json")
val response = httpClient!!.execute(httpGet)
if (response.statusLine.statusCode < 300) {
val contentType = ContentType.getOrDefault(response.entity)
if (isJsonResponse(contentType)) {
return@of JsonParser().parse(EntityUtils.toString(response.entity))
} else {
throw InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got '$contentType'")
}
} else {
when (response.statusLine.statusCode) {
404 -> throw NotFoundHalResponse("No HAL document found at path '$path'")
else -> throw RequestFailedException("Request to path '$path' failed with response '${response.statusLine}'")
}
}
}
}
private fun fetchLink(link: String, options: Map<String, Any>): JsonElement {
if (pathInfo?.nullObj?.get(LINKS) == null) {
throw InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got " +
"a response with no '_links'. URL: '$baseUrl', LINK: '$link'")
}
val links = pathInfo!![LINKS]
if (links.isJsonObject) {
if (!links.obj.has(link)) {
throw InvalidHalResponse("Link '$link' was not found in the response, only the following links where " +
"found: ${links.obj.keys()}. URL: '$baseUrl', LINK: '$link'")
}
val linkData = links[link]
if (linkData.isJsonArray) {
if (options.containsKey("name")) {
val linkByName = linkData.asJsonArray.find { it.isJsonObject && it["name"] == options["name"] }
return if (linkByName != null && linkByName.isJsonObject && linkByName["templated"].isJsonPrimitive &&
linkByName["templated"].bool) {
this.fetch(parseLinkUrl(linkByName["href"].toString(), options), false)
} else if (linkByName != null && linkByName.isJsonObject) {
this.fetch(linkByName["href"].string)
} else {
throw InvalidNavigationRequest("Link '$link' does not have an entry with name '${options["name"]}'. " +
"URL: '$baseUrl', LINK: '$link'")
}
} else {
throw InvalidNavigationRequest ("Link '$link' has multiple entries. You need to filter by the link name. " +
"URL: '$baseUrl', LINK: '$link'")
}
} else if (linkData.isJsonObject) {
return if (linkData.obj.has("templated") && linkData["templated"].isJsonPrimitive &&
linkData["templated"].bool) {
fetch(parseLinkUrl(linkData["href"].string, options), false)
} else {
fetch(linkData["href"].string)
}
} else {
throw InvalidHalResponse("Expected link in map form in the response, but " +
"found: $linkData. URL: '$baseUrl', LINK: '$link'")
}
} else {
throw InvalidHalResponse("Expected a map of links in the response, but " +
"found: $links. URL: '$baseUrl', LINK: '$link'")
}
}
fun parseLinkUrl(href: String, options: Map<String, Any>): String {
var result = ""
var match = URL_TEMPLATE_REGEX.find(href)
var index = 0
while (match != null) {
val start = match.range.start - 1
if (start >= index) {
result += href.substring(index..start)
}
index = match.range.endInclusive + 1
val (key) = match.destructured
result += encodePathParameter(options, key, match.value)
match = URL_TEMPLATE_REGEX.find(href, index)
}
if (index < href.length) {
result += href.substring(index)
}
return result
}
private fun encodePathParameter(options: Map<String, Any>, key: String, value: String): String? {
return UrlEscapers.urlPathSegmentEscaper().escape(options[key]?.toString() ?: value)
}
fun initPathInfo() {
pathInfo = pathInfo ?: fetch(ROOT)
}
override fun uploadJson(path: String, bodyJson: String) = uploadJson(path, bodyJson,
BiFunction { _: String, _: String -> null }, true)
override fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>) =
uploadJson(path, bodyJson, closure, true)
override fun uploadJson(
path: String,
bodyJson: String,
closure: BiFunction<String, String, Any?>,
encodePath: Boolean
): Any? {
val client = setupHttpClient()
val httpPut = HttpPut(buildUrl(baseUrl, path, encodePath))
httpPut.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString())
httpPut.entity = StringEntity(bodyJson, ContentType.APPLICATION_JSON)
client.execute(httpPut).use {
return when {
it.statusLine.statusCode < 300 -> {
EntityUtils.consume(it.entity)
closure.apply("OK", it.statusLine.toString())
}
it.statusLine.statusCode == 409 -> {
val body = it.entity.content.bufferedReader().readText()
closure.apply("FAILED",
"${it.statusLine.statusCode} ${it.statusLine.reasonPhrase} - $body")
}
else -> {
val body = it.entity.content.bufferedReader().readText()
handleFailure(it, body, closure)
}
}
}
}
fun handleFailure(resp: HttpResponse, body: String?, closure: BiFunction<String, String, Any?>): Any? {
if (resp.entity.contentType != null) {
val contentType = ContentType.getOrDefault(resp.entity)
if (isJsonResponse(contentType)) {
var error = "Unknown error"
if (body != null) {
val jsonBody = JsonParser().parse(body)
if (jsonBody != null && jsonBody.obj.has("errors")) {
if (jsonBody["errors"].isJsonArray) {
error = jsonBody["errors"].asJsonArray.joinToString(", ") { it.asString }
} else if (jsonBody["errors"].isJsonObject) {
error = jsonBody["errors"].asJsonObject.entrySet().joinToString(", ") {
if (it.value.isJsonArray) {
"${it.key}: ${it.value.array.joinToString(", ") { it.asString }}"
} else {
"${it.key}: ${it.value.asString}"
}
}
}
}
}
return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $error")
} else {
return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $body")
}
} else {
return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $body")
}
}
override fun linkUrl(name: String): String? {
if (pathInfo!!.obj.has(LINKS)) {
val links = pathInfo!![LINKS]
if (links.isJsonObject && links.obj.has(name)) {
val linkData = links[name]
if (linkData.isJsonObject && linkData.obj.has("href")) {
return fromJson(linkData["href"]).toString()
}
}
}
return null
}
override fun forAll(linkName: String, just: Consumer<Map<String, Any?>>) {
initPathInfo()
val links = pathInfo!![LINKS]
if (links.isJsonObject && links.obj.has(linkName)) {
val matchingLink = links[linkName]
if (matchingLink.isJsonArray) {
matchingLink.asJsonArray.forEach { just.accept(asMap(it.asJsonObject)) }
} else {
just.accept(asMap(matchingLink.asJsonObject))
}
}
}
companion object : KLogging() {
const val ROOT = "/"
const val LINKS = "_links"
val URL_TEMPLATE_REGEX = Regex("\\{(\\w+)\\}")
@JvmStatic
fun asMap(jsonObject: JsonObject) = jsonObject.entrySet().associate { entry -> entry.key to fromJson(entry.value) }
@JvmStatic
fun fromJson(jsonValue: JsonElement): Any? {
return if (jsonValue.isJsonObject) {
asMap(jsonValue.asJsonObject)
} else if (jsonValue.isJsonArray) {
jsonValue.asJsonArray.map { fromJson(it) }
} else if (jsonValue.isJsonNull) {
null
} else {
val primitive = jsonValue.asJsonPrimitive
when {
primitive.isBoolean -> primitive.asBoolean
primitive.isNumber -> primitive.asBigDecimal
else -> primitive.asString
}
}
}
}
}
| pact-jvm-pact-broker/src/main/kotlin/au/com/dius/pact/pactbroker/HalClient.kt | 2904455508 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.