content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package net.nemerosa.ontrack.graphql.schema
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.graphql.support.TypeRef
import net.nemerosa.ontrack.graphql.support.TypedMutationProvider
import net.nemerosa.ontrack.json.JsonParseException
import net.nemerosa.ontrack.model.annotations.APIDescription
import net.nemerosa.ontrack.model.exceptions.BuildNotFoundException
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataJSONInputException
import net.nemerosa.ontrack.model.structure.*
import org.springframework.stereotype.Component
@Component
class ValidationRunMutations(
private val structureService: StructureService,
private val validationRunStatusService: ValidationRunStatusService,
private val validationDataTypeService: ValidationDataTypeService,
private val runInfoService: RunInfoService,
) : TypedMutationProvider() {
override val mutations: List<Mutation> = listOf(
simpleMutation(
name = CREATE_VALIDATION_RUN_FOR_BUILD_BY_NAME,
description = "Creating a validation run for a build identified by its name",
input = CreateValidationRunInput::class,
outputName = "validationRun",
outputDescription = "Created validation run",
outputType = ValidationRun::class
) { input ->
val build = (structureService.findBuildByName(input.project, input.branch, input.build)
.getOrNull()
?: throw BuildNotFoundException(input.project, input.branch, input.build))
validate(build, input)
},
simpleMutation(
name = CREATE_VALIDATION_RUN_FOR_BUILD_BY_ID,
description = "Creating a validation run for a build identified by its ID",
input = CreateValidationRunByIdInput::class,
outputName = "validationRun",
outputDescription = "Created validation run",
outputType = ValidationRun::class
) { input ->
val build = structureService.getBuild(ID.of(input.buildId))
validate(build, input)
}
)
private fun validate(build: Build, input: ValidationRunInput): ValidationRun {
val run = structureService.newValidationRun(
build = build,
validationRunRequest = ValidationRunRequest(
validationStampName = input.validationStamp,
validationRunStatusId = input.validationRunStatus?.let(validationRunStatusService::getValidationRunStatus),
dataTypeId = input.dataTypeId,
data = parseValidationRunData(build, input.validationStamp, input.dataTypeId, input.data),
description = input.description
)
)
// Run info
val runInfo = input.runInfo
if (runInfo != null) {
runInfoService.setRunInfo(
entity = run,
input = runInfo,
)
}
// OK
return run
}
fun parseValidationRunData(
build: Build,
validationStampName: String,
dataTypeId: String?,
data: JsonNode?,
): Any? = data?.run {
// Gets the validation stamp
val validationStamp: ValidationStamp = structureService.getOrCreateValidationStamp(
build.branch,
validationStampName
)
// Gets the data type ID if any
// First, the data type in the request, and if not specified, the type of the validation stamp
val typeId: String? = dataTypeId
?: validationStamp.dataType?.descriptor?.id
// If no type, ignore the data
return typeId
?.run {
// Gets the actual type
validationDataTypeService.getValidationDataType<Any, Any>(this)
}?.run {
// Parses data from the form
try {
fromForm(data)
} catch (ex: JsonParseException) {
throw ValidationRunDataJSONInputException(ex, data)
}
}
}
companion object {
const val CREATE_VALIDATION_RUN_FOR_BUILD_BY_ID = "createValidationRunById"
const val CREATE_VALIDATION_RUN_FOR_BUILD_BY_NAME = "createValidationRun"
}
}
interface ValidationRunInput {
val validationStamp: String
val validationRunStatus: String?
val description: String?
val dataTypeId: String?
val data: JsonNode?
val runInfo: RunInfoInput?
}
class CreateValidationRunInput(
@APIDescription("Project name")
val project: String,
@APIDescription("Branch name")
val branch: String,
@APIDescription("Build name")
val build: String,
@APIDescription("Validation stamp name")
override val validationStamp: String,
@APIDescription("Validation run status")
override val validationRunStatus: String?,
@APIDescription("Validation description")
override val description: String?,
@APIDescription("Type of the data to associated with the validation")
override val dataTypeId: String?,
@APIDescription("Data to associated with the validation")
override val data: JsonNode?,
@APIDescription("Run info")
@TypeRef
override val runInfo: RunInfoInput?,
): ValidationRunInput
class CreateValidationRunByIdInput(
@APIDescription("Build ID")
val buildId: Int,
@APIDescription("Validation stamp name")
override val validationStamp: String,
@APIDescription("Validation run status")
override val validationRunStatus: String?,
@APIDescription("Validation description")
override val description: String?,
@APIDescription("Type of the data to associated with the validation")
override val dataTypeId: String?,
@APIDescription("Data to associated with the validation")
override val data: JsonNode?,
@APIDescription("Run info")
@TypeRef
override val runInfo: RunInfoInput?,
): ValidationRunInput
| ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/ValidationRunMutations.kt | 4245629672 |
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.parentOfType
class IfLetToMatchIntention : RsElementBaseIntentionAction<IfLetToMatchIntention.Context>() {
override fun getText(): String = "Convert if let statement to match"
override fun getFamilyName(): String = text
data class Context(
val ifStmt: RsIfExpr,
val target: RsExpr,
val matchArms: MutableList<MatchArm>,
var elseBody: RsBlock?
)
data class MatchArm(
val matchArm: RsPat,
val body: RsBlock
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
//1) Check that we have an if statement
var ifStatement = element.parentOfType<RsIfExpr>() ?: return null
// We go up in the tree to detect cases like `... else if let Some(value) = x { ... }`
// and select the correct if statement
while (ifStatement.parent is RsElseBranch) {
// In that case
// typeof(if.parent) = RsElseBranch ==> typeof(if.parent.parent) = RsIfExpr
ifStatement = ifStatement.parent.parent as? RsIfExpr ?: return null
}
//Here we have extracted the upper most if statement node
return extractIfLetStatementIfAny(ifStatement)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (ifStmt, target, matchArms, elseBody) = ctx
//var generatedCode = "match ${target.text} {"
var generatedCode = buildString {
append("match ")
append(target.text)
append(" {")
append(matchArms.map { arm -> "${arm.matchArm.text} => ${arm.body.text}" }
.joinToString(", "))
if (elseBody != null) {
append(", _ => ")
append(elseBody.text)
}
append("}")
}
val matchExpression = RsPsiFactory(project).createExpression(generatedCode) as RsMatchExpr
ifStmt.replace(matchExpression)
}
private fun extractIfLetStatementIfAny(iflet: RsIfExpr, ctx: Context? = null): Context? {
val condition = iflet.condition ?: return null
//2) Check that we have a let condition
if (condition.let == null) {
return null
}
//3) Extract the match arm condition
val matchArmPat = condition.pat ?: return null
//4) Extract the target
val target = condition.expr
//5) Extract the if body
val ifBody = iflet.block ?: return null
val matchArm = MatchArm(matchArmPat, ifBody)
var context = if (ctx != null) {
//If we reach this code, that mean we are in a `if let Some(value) = x { ... } else if let Other(value) = x { ... }` case
// ^
val newContext = ctx.copy()
// Check that the target is the same
// Otherwise that doesn't make sense
if (newContext.target.text != target.text) {
return null
}
newContext.matchArms.add(matchArm)
newContext
} else {
val newContext = Context(iflet, target, mutableListOf(matchArm), null)
newContext
}
//6) Extract else body if any
if (iflet.elseBranch != null) {
val elseBody = iflet.elseBranch!!
if (elseBody.ifExpr != null) {
// This particular case mean that we have an `else if` that we must handle
context = extractIfLetStatementIfAny(elseBody.ifExpr!!, context) ?: return null
} else if (elseBody.block != null) {
//This will go in the `_ => { ... }` arm
context.elseBody = elseBody.block
}
}
return context
}
}
| src/main/kotlin/org/rust/ide/intentions/IfLetToMatchIntention.kt | 1033286140 |
package com.thedeadpixelsociety.twodee.input
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.IntMap
import com.badlogic.gdx.utils.ObjectMap
import com.thedeadpixelsociety.twodee.Predicate
import com.thedeadpixelsociety.twodee.gdxArray
class DefaultActionController<T> : ActionController<T>() {
private val keyMap = IntMap<T>()
private val buttonMap = IntMap<Array<T>>()
private val reverseButtonMap = ObjectMap<T, Int>()
private val touchMap = IntMap<Array<T>>()
private val reverseTouchMap = ObjectMap<T, Int>()
private val stateMap = ObjectMap<T, Boolean>()
private val predicateMap = ObjectMap<T, Predicate<T>>()
private val listeners = gdxArray<ActionListener<T>>()
override fun mapKey(action: T, key: Int, predicate: Predicate<T>?) {
val existing = keyMap.findKey(action, false, -1)
if (existing != -1) {
keyMap.remove(key)
stateMap.remove(action)
predicateMap.remove(action)
}
keyMap.put(key, action)
stateMap.put(action, false)
if (predicate != null) predicateMap.put(action, predicate)
}
override fun mapButton(action: T, button: Int, predicate: Predicate<T>?) {
val actions = getActions(buttonMap, button)
if (actions.contains(action)) {
actions.removeValue(action, false)
stateMap.remove(action)
predicateMap.remove(action)
reverseButtonMap.remove(action)
}
actions.add(action)
stateMap.put(action, false)
reverseButtonMap.put(action, button)
if (predicate != null) predicateMap.put(action, predicate)
}
override fun mapTouch(action: T, pointer: Int, predicate: Predicate<T>?) {
val actions = getActions(buttonMap, pointer)
if (actions.contains(action)) {
actions.removeValue(action, false)
stateMap.remove(action)
predicateMap.remove(action)
reverseTouchMap.remove(action)
}
actions.add(action)
stateMap.put(action, false)
reverseTouchMap.put(action, pointer)
if (predicate != null) predicateMap.put(action, predicate)
}
override fun actionDown(action: T): Boolean {
val predicate = predicateMap.get(action, null)
val key = keyMap.findKey(action, false, -1)
if (key != -1) return Gdx.input.isKeyPressed(key) && predicate?.invoke(action) ?: true
val button = reverseButtonMap.get(action, -1)
if (button != -1) return Gdx.input.isButtonPressed(button) && predicate?.invoke(action) ?: true
val pointer = reverseTouchMap.get(action, -1)
if (pointer != -1) return Gdx.input.isTouched(pointer) && predicate?.invoke(action) ?: true
return false
}
override fun actionUp(action: T): Boolean {
return !actionDown(action)
}
private fun getActions(map: IntMap<Array<T>>, key: Int): Array<T> {
var actions = map.get(key)
if (actions == null) {
actions = Array()
map.put(key, actions)
}
return actions
}
override fun update() {
stateMap.forEach {
val action = it.key
val lastState = it.value
val state = actionDown(action)
if (state != lastState) {
listeners.forEach { it.invoke(action, state) }
stateMap.put(action, state)
}
}
}
override fun addListener(listener: ActionListener<T>) {
listeners.add(listener)
}
override fun removeListener(listener: ActionListener<T>) {
listeners.removeValue(listener, true)
}
} | src/main/kotlin/com/thedeadpixelsociety/twodee/input/DefaultActionController.kt | 4172214335 |
/*
* Copyright 2019 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
*
* 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.plaidapp
import io.plaidapp.core.designernews.data.DesignerNewsSearchSourceItem
import io.plaidapp.core.designernews.data.stories.model.Story
import io.plaidapp.core.designernews.data.stories.model.StoryLinks
import io.plaidapp.core.dribbble.data.DribbbleSourceItem
import io.plaidapp.core.dribbble.data.api.model.Images
import io.plaidapp.core.dribbble.data.api.model.Shot
import io.plaidapp.core.dribbble.data.api.model.User
import io.plaidapp.core.producthunt.data.api.model.Post
import io.plaidapp.core.ui.filter.SourceUiModel
import java.util.Date
import java.util.GregorianCalendar
val designerNewsSource = DesignerNewsSearchSourceItem(
"query",
true
)
val designerNewsSourceUiModel = SourceUiModel(
id = "id",
key = designerNewsSource.key,
name = designerNewsSource.name,
active = designerNewsSource.active,
iconRes = designerNewsSource.iconRes,
isSwipeDismissable = designerNewsSource.isSwipeDismissable,
onSourceClicked = {},
onSourceDismissed = {}
)
val dribbbleSource = DribbbleSourceItem("dribbble", true)
val post = Post(
id = 345L,
title = "Plaid",
url = "www.plaid.amazing",
tagline = "amazing",
discussionUrl = "www.disc.plaid",
redirectUrl = "www.d.plaid",
commentsCount = 5,
votesCount = 100
)
val player = User(
id = 1L,
name = "Nick Butcher",
username = "nickbutcher",
avatarUrl = "www.prettyplaid.nb"
)
val shot = Shot(
id = 1L,
title = "Foo Nick",
page = 0,
description = "",
images = Images(),
user = player
).apply {
dataSource = dribbbleSource.key
}
const val userId = 5L
const val storyId = 1345L
val createdDate: Date = GregorianCalendar(2018, 1, 13).time
val commentIds = listOf(11L, 12L)
val storyLinks = StoryLinks(
user = userId,
comments = commentIds,
upvotes = emptyList(),
downvotes = emptyList()
)
val story = Story(
id = storyId,
title = "Plaid 2.0 was released",
page = 0,
createdAt = createdDate,
userId = userId,
links = storyLinks
).apply {
dataSource = designerNewsSource.key
}
| app/src/test/java/io/plaidapp/TestData.kt | 634173977 |
package treehou.se.habit.ui.util
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.mikepenz.community_material_typeface_library.CommunityMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import treehou.se.habit.R
import treehou.se.habit.ui.BaseFragment
import treehou.se.habit.util.Util
import java.util.*
/**
* Fragment for picking categories of icons.
*/
class CategoryPickerFragment : BaseFragment() {
private var lstIcons: RecyclerView? = null
private var adapter: CategoryAdapter? = null
private var container: ViewGroup? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_icon_picker, container, false)
lstIcons = rootView.findViewById<View>(R.id.lst_categories) as RecyclerView
val gridLayoutManager = GridLayoutManager(activity, 1)
lstIcons!!.layoutManager = gridLayoutManager
lstIcons!!.itemAnimator = DefaultItemAnimator()
// Hookup list of categories
val categoryList = ArrayList<CategoryPicker>()
categoryList.add(CategoryPicker(null, getString(R.string.empty), Util.IconCategory.EMPTY))
categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_play, getString(R.string.media), Util.IconCategory.MEDIA))
categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_alarm, getString(R.string.sensor), Util.IconCategory.SENSORS))
categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_power, getString(R.string.command), Util.IconCategory.COMMANDS))
categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_arrow_up, getString(R.string.arrows), Util.IconCategory.ARROWS))
categoryList.add(CategoryPicker(CommunityMaterial.Icon.cmd_view_module, getString(R.string.all), Util.IconCategory.ALL))
adapter = CategoryAdapter(categoryList)
lstIcons!!.adapter = adapter
this.container = container
return rootView
}
private inner class CategoryPicker(var icon: IIcon?, var category: String?, var id: Util.IconCategory?)
/**
* Adapter showing category of icons.
*/
private inner class CategoryAdapter(val categories: MutableList<CategoryPicker>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class CategoryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imgIcon: ImageView = itemView.findViewById<View>(R.id.img_menu) as ImageView
var lblCategory: TextView = itemView.findViewById<View>(R.id.lbl_label) as TextView
}
fun add(category: CategoryPicker) {
categories.add(category)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.item_category, parent, false)
return CategoryHolder(itemView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = categories[position]
val catHolder = holder as CategoryHolder
catHolder.lblCategory.text = item.category
if (item.id != Util.IconCategory.EMPTY) {
val drawable = IconicsDrawable(activity!!, item.icon).color(Color.BLACK).sizeDp(60)
catHolder.imgIcon.setImageDrawable(drawable)
holder.itemView.setOnClickListener { v ->
activity!!.supportFragmentManager.beginTransaction()
.replace(container!!.id, IconPickerFragment.newInstance(item.id!!))
.addToBackStack(null)
.commit()
}
} else {
catHolder.imgIcon.setImageDrawable(null)
holder.itemView.setOnClickListener { v ->
val intent = Intent()
intent.putExtra(IconPickerFragment.RESULT_ICON, "")
activity!!.setResult(Activity.RESULT_OK, intent)
activity!!.finish()
}
}
}
override fun getItemCount(): Int {
return categories.size
}
}
companion object {
fun newInstance(): CategoryPickerFragment {
val fragment = CategoryPickerFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
}
| mobile/src/main/java/treehou/se/habit/ui/util/CategoryPickerFragment.kt | 1617508257 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc
import android.app.Activity
import android.app.Dialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.os.RemoteException
import android.text.SpannableString
import android.text.style.UnderlineSpan
import android.view.*
import android.widget.Button
import android.widget.TextView
import androidx.core.graphics.scale
import androidx.core.net.toUri
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import edu.berkeley.boinc.databinding.ProjectDetailsLayoutBinding
import edu.berkeley.boinc.databinding.ProjectDetailsSlideshowImageLayoutBinding
import edu.berkeley.boinc.rpc.ImageWrapper
import edu.berkeley.boinc.rpc.Project
import edu.berkeley.boinc.rpc.ProjectInfo
import edu.berkeley.boinc.rpc.RpcClient
import edu.berkeley.boinc.utils.Logging
import java.util.*
import kotlinx.coroutines.*
class ProjectDetailsFragment : Fragment() {
private var url: String = ""
// might be null for projects added via manual URL attach
private var projectInfo: ProjectInfo? = null
private var project: Project? = null
private var slideshowImages: List<ImageWrapper> = ArrayList()
private var _binding: ProjectDetailsLayoutBinding? = null
private val binding get() = _binding!!
// display dimensions
private var width = 0
private var height = 0
private var retryLayout = true
private val currentProjectData: Unit
get() {
try {
project = BOINCActivity.monitor!!.projects.firstOrNull { it.masterURL == url }
projectInfo = BOINCActivity.monitor!!.getProjectInfoAsync(url).await()
} catch (e: Exception) {
Logging.logError(Logging.Category.GUI_VIEW, "ProjectDetailsFragment getCurrentProjectData could not" +
" retrieve project list")
}
if (project == null) {
Logging.logWarning(Logging.Category.GUI_VIEW,
"ProjectDetailsFragment getCurrentProjectData could not find project for URL: $url")
}
if (projectInfo == null) {
Logging.logDebug(Logging.Category.GUI_VIEW,
"ProjectDetailsFragment getCurrentProjectData could not find project" +
" attach list for URL: $url")
}
}
// BroadcastReceiver event is used to update the UI with updated information from
// the client. This is generally called once a second.
//
private val ifcsc = IntentFilter("edu.berkeley.boinc.clientstatuschange")
private val mClientStatusChangeRec: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
currentProjectData
if (retryLayout) {
populateLayout()
} else {
updateChangingItems()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
// get data
url = requireArguments().getString("url") ?: ""
currentProjectData
super.onCreate(savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val menuHost: MenuHost = requireActivity() // enables fragment specific menu
// add the project menu to the fragment
menuHost.addMenuProvider(object: MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.project_details_menu, menu)
}
override fun onPrepareMenu(menu: Menu) {
super.onPrepareMenu(menu)
if (project == null) {
return
}
// no new tasks, adapt based on status
val nnt = menu.findItem(R.id.projects_control_nonewtasks)
if (project!!.doNotRequestMoreWork) {
nnt.setTitle(R.string.projects_control_allownewtasks)
} else {
nnt.setTitle(R.string.projects_control_nonewtasks)
}
// project suspension, adapt based on status
val suspend = menu.findItem(R.id.projects_control_suspend)
if (project!!.suspendedViaGUI) {
suspend.setTitle(R.string.projects_control_resume)
} else {
suspend.setTitle(R.string.projects_control_suspend)
}
// detach, only show when project not managed
val remove = menu.findItem(R.id.projects_control_remove)
if (project!!.attachedViaAcctMgr) {
remove.isVisible = false
}
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
lifecycleScope.launch {
when (menuItem.itemId) {
R.id.projects_control_update -> performProjectOperation(RpcClient.PROJECT_UPDATE)
R.id.projects_control_suspend -> if (project!!.suspendedViaGUI) {
performProjectOperation(RpcClient.PROJECT_RESUME)
} else {
performProjectOperation(RpcClient.PROJECT_SUSPEND)
}
R.id.projects_control_nonewtasks -> if (project!!.doNotRequestMoreWork) {
performProjectOperation(RpcClient.PROJECT_ANW)
} else {
performProjectOperation(RpcClient.PROJECT_NNW)
}
R.id.projects_control_reset -> showConfirmationDialog(RpcClient.PROJECT_RESET)
R.id.projects_control_remove -> showConfirmationDialog(RpcClient.PROJECT_DETACH)
else -> {
Logging.logError(Logging.Category.USER_ACTION, "ProjectDetailsFragment onOptionsItemSelected: could not match ID")
}
}
}
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
Logging.logVerbose(Logging.Category.GUI_VIEW, "ProjectDetailsFragment onCreateView")
// Inflate the layout for this fragment
_binding = ProjectDetailsLayoutBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onAttach(context: Context) {
if (context is Activity) {
val size = Point()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
@Suppress("DEPRECATION")
context.windowManager.defaultDisplay.getSize(size)
} else {
val r = context.windowManager.currentWindowMetrics.bounds
size.x = r.width()
size.y = r.height()
}
width = size.x
height = size.y
}
super.onAttach(context)
}
override fun onPause() {
activity?.unregisterReceiver(mClientStatusChangeRec)
super.onPause()
}
override fun onResume() {
super.onResume()
activity?.registerReceiver(mClientStatusChangeRec, ifcsc)
}
private fun showConfirmationDialog(operation: Int) {
val dialog = Dialog(requireActivity()).apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.dialog_confirm)
}
val confirm = dialog.findViewById<Button>(R.id.confirm)
val tvTitle = dialog.findViewById<TextView>(R.id.title)
val tvMessage = dialog.findViewById<TextView>(R.id.message)
// operation-dependent texts
if (operation == RpcClient.PROJECT_DETACH) {
val removeStr = getString(R.string.projects_confirm_detach_confirm)
tvTitle.text = getString(R.string.projects_confirm_title, removeStr)
tvMessage.text = getString(R.string.projects_confirm_message,
removeStr.lowercase(Locale.ROOT), project!!.projectName + " "
+ getString(R.string.projects_confirm_detach_message))
confirm.text = removeStr
} else if (operation == RpcClient.PROJECT_RESET) {
val resetStr = getString(R.string.projects_confirm_reset_confirm)
tvTitle.text = getString(R.string.projects_confirm_title, resetStr)
tvMessage.text = getString(R.string.projects_confirm_message,
resetStr.lowercase(Locale.ROOT),
project!!.projectName)
confirm.text = resetStr
}
confirm.setOnClickListener {
lifecycleScope.launch {
performProjectOperation(operation)
}
dialog.dismiss()
}
dialog.findViewById<Button>(R.id.cancel).apply {
setOnClickListener { dialog.dismiss() }
}
dialog.show()
}
private fun populateLayout() {
if (project == null) {
retryLayout = true
return // if data not available yet, return. Frequently retry with onReceive
}
retryLayout = false
updateChangingItems()
// set website
val content = SpannableString(project!!.masterURL)
content.setSpan(UnderlineSpan(), 0, content.length, 0)
binding.projectUrl.text = content
binding.projectUrl.setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW, project!!.masterURL.toUri()))
}
// set general area
if (projectInfo?.generalArea != null) {
binding.generalArea.text = projectInfo!!.generalArea
} else {
binding.generalAreaWrapper.visibility = View.GONE
}
// set specific area
if (projectInfo?.specificArea != null) {
binding.specificArea.text = projectInfo!!.specificArea
} else {
binding.specificAreaWrapper.visibility = View.GONE
}
// set description
if (projectInfo?.description != null) {
binding.description.text = projectInfo!!.description
} else {
binding.descriptionWrapper.visibility = View.GONE
}
// set home
if (projectInfo?.home != null) {
binding.basedAt.text = projectInfo!!.home
} else {
binding.basedAtWrapper.visibility = View.GONE
}
// load slideshow
lifecycleScope.launch {
updateSlideshowImages()
}
}
private fun updateChangingItems() {
try {
// status
val newStatus = BOINCActivity.monitor!!.getProjectStatus(project!!.masterURL)
if (newStatus.isNotEmpty()) {
binding.statusWrapper.visibility = View.VISIBLE
binding.statusText.text = newStatus
} else {
binding.statusWrapper.visibility = View.GONE
}
} catch (e: Exception) {
Logging.logException(Logging.Category.GUI_VIEW, "ProjectDetailsFragment.updateChangingItems error: ", e)
}
}
// executes project operations in new thread
private suspend fun performProjectOperation(operation: Int) = coroutineScope {
Logging.logVerbose(Logging.Category.USER_ACTION, "performProjectOperation()")
val success = async {
return@async try {
BOINCActivity.monitor!!.projectOp(operation, project!!.masterURL)
} catch (e: Exception) {
Logging.logException(Logging.Category.USER_ACTION, "performProjectOperation() error: ", e)
false
}
}.await()
if (success) {
try {
BOINCActivity.monitor!!.forceRefresh()
} catch (e: RemoteException) {
Logging.logException(Logging.Category.USER_ACTION, "performProjectOperation() error: ", e)
}
} else {
Logging.logError(Logging.Category.USER_ACTION, "performProjectOperation() failed.")
}
}
private suspend fun updateSlideshowImages() = coroutineScope {
Logging.logDebug(Logging.Category.GUI_VIEW,
"UpdateSlideshowImagesAsync updating images in new thread. project:" +
" $project!!.masterURL")
val success = withContext(Dispatchers.Default) {
slideshowImages = try {
BOINCActivity.monitor!!.getSlideshowForProject(project!!.masterURL)
} catch (e: Exception) {
Logging.logError(Logging.Category.GUI_VIEW, "updateSlideshowImages: Could not load data, " +
"clientStatus not initialized.")
return@withContext false
}
return@withContext slideshowImages.isNotEmpty()
}
Logging.logDebug(Logging.Category.GUI_VIEW,
"UpdateSlideshowImagesAsync success: $success, images: ${slideshowImages.size}")
if (success && slideshowImages.isNotEmpty()) {
binding.slideshowLoading.visibility = View.GONE
for (image in slideshowImages) {
val slideshowBinding = ProjectDetailsSlideshowImageLayoutBinding.inflate(layoutInflater)
var bitmap = image.image!!
if (scaleImages(bitmap.height, bitmap.width)) {
bitmap = bitmap.scale(bitmap.width * 2, bitmap.height * 2, filter = false)
}
slideshowBinding.slideshowImage.setImageBitmap(bitmap)
binding.slideshowHook.addView(slideshowBinding.slideshowImage)
}
} else {
binding.slideshowWrapper.visibility = View.GONE
}
}
private fun scaleImages(imageHeight: Int, imageWidth: Int) = height >= imageHeight * 2 && width >= imageWidth * 2
}
| android/BOINC/app/src/main/java/edu/berkeley/boinc/ProjectDetailsFragment.kt | 197848124 |
package com.isupatches.wisefysample.internal.models
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
internal class NetworkTypeTest {
@Test
fun open() {
assertEquals(NetworkType.OPEN, NetworkType.of(NetworkType.OPEN.intVal))
}
@Test
fun wpa2() {
assertEquals(NetworkType.WPA2, NetworkType.of(NetworkType.WPA2.intVal))
}
@Test
fun wep() {
assertEquals(NetworkType.WEP, NetworkType.of(NetworkType.WEP.intVal))
}
@Test
fun unexpected() {
try {
NetworkType.of(999)
fail("Expected IllegalArgumentException from NetworkType.of")
} catch (ex: IllegalArgumentException) {
// Do nothing
}
}
}
| wisefysample/src/test/java/com/isupatches/wisefysample/internal/models/NetworkTypeTest.kt | 2795151749 |
/*
* Copyright (c) 2021 David Allison <[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.ichi2.anki.servicelayer
import android.os.Build
import android.os.LocaleList
import android.widget.EditText
import androidx.annotation.CheckResult
import com.ichi2.libanki.Model
import com.ichi2.libanki.ModelManager
import com.ichi2.utils.JSONObject
import timber.log.Timber
import java.util.*
/**
* The language that a keyboard should open with when an [EditText] is selected
*
* Used so a user doesn't need to change keyboard languages when adding a note, or typing answers
*
* [2021] GBoard is the only known keyboard which supports this API
*/
typealias LanguageHint = Locale
object LanguageHintService {
@JvmStatic
@CheckResult
fun getLanguageHintForField(field: JSONObject): LanguageHint? {
if (!field.has("ad-hint-locale")) {
return null
}
return Locale.forLanguageTag(field.getString("ad-hint-locale"))
}
@JvmStatic
fun setLanguageHintForField(models: ModelManager, model: Model, fieldPos: Int, selectedLocale: Locale) {
val field = model.getField(fieldPos)
field.put("ad-hint-locale", selectedLocale.toLanguageTag())
models.save(model)
Timber.i("Set field locale to %s", selectedLocale)
}
@JvmStatic
fun EditText.applyLanguageHint(languageHint: LanguageHint?) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
this.imeHintLocales = if (languageHint != null) LocaleList(languageHint) else null
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/LanguageHintService.kt | 555871155 |
package hypr.hypergan.com.hypr.DependencyInjection
import hypr.hypergan.com.hypr.Generator.Generator
import hypr.hypergan.com.hypr.GeneratorLoader.EasyGeneratorLoader
import hypr.hypergan.com.hypr.ModelFragmnt.ModelFragmentPresenter
import org.koin.android.module.AndroidModule
import org.koin.dsl.context.Context
class GeneratorModule : AndroidModule() {
override fun context(): Context {
return applicationContext {
context("generator") {
provide { getGeneratorLoader() }
provide { ModelFragmentPresenter(get()) }
}
}
}
fun getGeneratorLoader(): EasyGeneratorLoader {
return EasyGeneratorLoader()
}
} | app/src/main/java/hypr/hypergan/com/hypr/DependencyInjection/GeneratorModule.kt | 4151543272 |
package world.player.skill.cooking
import api.predef.*
import io.luna.game.model.mob.Player
import io.luna.game.model.mob.inter.DialogueInterface
import io.luna.net.msg.out.WidgetItemModelMessageWriter
/**
* A [DialogueInterface] that opens the cook food dialogue.
*/
class CookingInterface(val food: Food, val usingFire: Boolean = false) : DialogueInterface(1743) {
override fun init(plr: Player): Boolean {
val cooked = food.cooked
plr.queue(WidgetItemModelMessageWriter(13716, 190, cooked))
plr.sendText(itemName(cooked), 13717)
return true
}
}
| plugins/world/player/skill/cooking/CookingInterface.kt | 934104761 |
package com.example.andretortolano.githubsearch.ui.screens.showuser
import android.os.Bundle
import android.view.*
import com.example.andretortolano.githubsearch.R
import com.example.andretortolano.githubsearch.api.github.GithubService
import com.example.andretortolano.githubsearch.api.github.responses.User
import com.example.andretortolano.githubsearch.ui.screens.BaseFragment
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_user.*
class ShowUserView : BaseFragment<ShowUserContract.Presenter>(), ShowUserContract.View {
override lateinit var mPresenter: ShowUserContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mPresenter = ShowUserPresenter(this, GithubService(), arguments.getString(USER_LOGIN))
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
menu?.clear()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater!!.inflate(R.layout.fragment_user, container, false)!!
override fun showProgress() {
progress_view.visibility = View.VISIBLE
}
override fun hideProgress() {
progress_view.visibility = View.GONE
}
override fun showErrorMessage(message: String) {
showToast(message)
}
override fun showUser(user: User) {
user_name.text = user.name
Picasso.with(context)
.load(user.avatarUrl)
.placeholder(R.drawable.harrypotter_cat)
.into(user_avatar)
}
companion object {
var USER_LOGIN = "BUNDLE_USER_LOGIN"
fun newInstance(login: String): ShowUserView {
val fragment: ShowUserView = ShowUserView()
val args: Bundle = Bundle()
args.putString(USER_LOGIN, login)
fragment.arguments = args
return fragment
}
}
}
| app/src/main/java/com/example/andretortolano/githubsearch/ui/screens/showuser/ShowUserView.kt | 1781301972 |
package com.icapps.niddler.ui.form.detail.body
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.icapps.niddler.lib.model.ParsedNiddlerMessage
import javax.swing.text.Document
/**
* @author Nicola Verbeeck
* @date 15/11/16.
*/
class NiddlerJsonDataPanel(savedState: Map<String, Any>?, message: ParsedNiddlerMessage) : NiddlerStructuredDataPanel(true, true, savedState, message) {
init {
initUI()
}
override fun createStructuredView() {
this.structuredView = NiddlerJsonTree(message.bodyData as JsonElement).also { it.popup = popup }
}
override fun createPrettyPrintedView(doc: Document) {
doc.remove(0, doc.length)
doc.insertString(0, GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(message.bodyData), null)
}
} | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/detail/body/NiddlerJsonDataPanel.kt | 191195365 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* 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.github.panpf.sketch.test.decode.internal
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.BitmapFactory
import android.graphics.Rect
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import androidx.exifinterface.media.ExifInterface
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.panpf.sketch.datasource.AssetDataSource
import com.github.panpf.sketch.datasource.DataFrom.LOCAL
import com.github.panpf.sketch.datasource.DataFrom.MEMORY
import com.github.panpf.sketch.datasource.FileDataSource
import com.github.panpf.sketch.datasource.ResourceDataSource
import com.github.panpf.sketch.decode.BitmapDecodeResult
import com.github.panpf.sketch.decode.ImageInfo
import com.github.panpf.sketch.decode.ImageInvalidException
import com.github.panpf.sketch.decode.internal.ImageFormat
import com.github.panpf.sketch.decode.internal.appliedExifOrientation
import com.github.panpf.sketch.decode.internal.appliedResize
import com.github.panpf.sketch.decode.internal.calculateSampleSize
import com.github.panpf.sketch.decode.internal.calculateSampleSizeForRegion
import com.github.panpf.sketch.decode.internal.calculateSampledBitmapSize
import com.github.panpf.sketch.decode.internal.calculateSampledBitmapSizeForRegion
import com.github.panpf.sketch.decode.internal.computeSizeMultiplier
import com.github.panpf.sketch.decode.internal.createInSampledTransformed
import com.github.panpf.sketch.decode.internal.createSubsamplingTransformed
import com.github.panpf.sketch.decode.internal.decodeBitmap
import com.github.panpf.sketch.decode.internal.decodeRegionBitmap
import com.github.panpf.sketch.decode.internal.getExifOrientationTransformed
import com.github.panpf.sketch.decode.internal.isAnimatedHeif
import com.github.panpf.sketch.decode.internal.isAnimatedWebP
import com.github.panpf.sketch.decode.internal.isGif
import com.github.panpf.sketch.decode.internal.isHeif
import com.github.panpf.sketch.decode.internal.isInBitmapError
import com.github.panpf.sketch.decode.internal.isSrcRectError
import com.github.panpf.sketch.decode.internal.isSupportInBitmap
import com.github.panpf.sketch.decode.internal.isSupportInBitmapForRegion
import com.github.panpf.sketch.decode.internal.isWebP
import com.github.panpf.sketch.decode.internal.limitedSampleSizeByMaxBitmapSize
import com.github.panpf.sketch.decode.internal.limitedSampleSizeByMaxBitmapSizeForRegion
import com.github.panpf.sketch.decode.internal.maxBitmapSize
import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactory
import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactoryOrNull
import com.github.panpf.sketch.decode.internal.readImageInfoWithBitmapFactoryOrThrow
import com.github.panpf.sketch.decode.internal.realDecode
import com.github.panpf.sketch.decode.internal.sizeString
import com.github.panpf.sketch.decode.internal.supportBitmapRegionDecoder
import com.github.panpf.sketch.fetch.newAssetUri
import com.github.panpf.sketch.fetch.newResourceUri
import com.github.panpf.sketch.request.LoadRequest
import com.github.panpf.sketch.resize.Precision.EXACTLY
import com.github.panpf.sketch.resize.Precision.LESS_PIXELS
import com.github.panpf.sketch.resize.Precision.SAME_ASPECT_RATIO
import com.github.panpf.sketch.resize.Scale.CENTER_CROP
import com.github.panpf.sketch.sketch
import com.github.panpf.sketch.test.R
import com.github.panpf.sketch.test.utils.ExifOrientationTestFileHelper
import com.github.panpf.sketch.test.utils.TestAssets
import com.github.panpf.sketch.test.utils.corners
import com.github.panpf.sketch.test.utils.getTestContext
import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch
import com.github.panpf.sketch.test.utils.size
import com.github.panpf.sketch.test.utils.toRequestContext
import com.github.panpf.sketch.util.Bytes
import com.github.panpf.sketch.util.Size
import com.github.panpf.tools4j.test.ktx.assertThrow
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class DecodeUtilsTest {
@Test
fun testCalculateSampledBitmapSize() {
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/jpeg"
)
)
Assert.assertEquals(
Size(502, 100),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/png"
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/bmp"
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/gif"
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/webp"
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/heic"
)
)
Assert.assertEquals(
Size(503, 101),
calculateSampledBitmapSize(
imageSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/heif"
)
)
}
@Test
fun testCalculateSampledBitmapSizeForRegion() {
Assert.assertEquals(
if (VERSION.SDK_INT >= VERSION_CODES.N) Size(503, 101) else Size(502, 100),
calculateSampledBitmapSizeForRegion(
regionSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/jpeg",
imageSize = Size(1005, 201)
)
)
Assert.assertEquals(
Size(502, 100),
calculateSampledBitmapSizeForRegion(
regionSize = Size(1005, 201),
sampleSize = 2,
mimeType = "image/png",
imageSize = Size(1005, 201)
)
)
Assert.assertEquals(
Size(288, 100),
calculateSampledBitmapSizeForRegion(
regionSize = Size(577, 201),
sampleSize = 2,
mimeType = "image/jpeg",
imageSize = Size(1005, 201)
)
)
Assert.assertEquals(
Size(502, 55),
calculateSampledBitmapSizeForRegion(
regionSize = Size(1005, 111),
sampleSize = 2,
mimeType = "image/jpeg",
imageSize = Size(1005, 201)
)
)
Assert.assertEquals(
Size(288, 55),
calculateSampledBitmapSizeForRegion(
regionSize = Size(577, 111),
sampleSize = 2,
mimeType = "image/jpeg",
imageSize = Size(1005, 201)
)
)
Assert.assertEquals(
Size(288, 55),
calculateSampledBitmapSizeForRegion(
regionSize = Size(577, 111),
sampleSize = 2,
mimeType = "image/jpeg",
)
)
}
@Test
fun testCalculateSampleSize() {
Assert.assertEquals(
1,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(1006, 202),
)
)
Assert.assertEquals(
1,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(1005, 201),
)
)
Assert.assertEquals(
2,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(1004, 200),
)
)
Assert.assertEquals(
2,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(503, 101),
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(252, 51),
)
)
Assert.assertEquals(
8,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(251, 50),
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/jpeg"
)
)
Assert.assertEquals(
2,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/png"
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/bmp"
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/webp"
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/gif"
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/heic"
)
)
Assert.assertEquals(
4,
calculateSampleSize(
imageSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/heif"
)
)
}
@Test
fun testCalculateSampleSizeForRegion() {
Assert.assertEquals(
1,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(1006, 202),
)
)
Assert.assertEquals(
1,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(1005, 201),
)
)
Assert.assertEquals(
2,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(1004, 200),
imageSize = Size(2005, 301),
)
)
Assert.assertEquals(
2,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(502, 100),
imageSize = Size(2005, 301),
)
)
Assert.assertEquals(
4,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(501, 99),
imageSize = Size(2005, 301),
)
)
Assert.assertEquals(
4,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(251, 50),
imageSize = Size(2005, 301),
)
)
Assert.assertEquals(
8,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(250, 49),
imageSize = Size(2005, 301),
)
)
Assert.assertEquals(
if (VERSION.SDK_INT >= VERSION_CODES.N) 4 else 2,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(502, 100),
imageSize = Size(1005, 201),
)
)
Assert.assertEquals(
2,
calculateSampleSizeForRegion(
regionSize = Size(1005, 201),
targetSize = Size(502, 100),
mimeType = "image/png",
imageSize = Size(1005, 201),
)
)
}
@Test
fun testLimitedSampleSizeByMaxBitmapSize() {
val maxSize = maxBitmapSize.width
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize - 1, maxSize))
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize - 1))
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize - 1, maxSize - 1))
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize))
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize + 1, maxSize))
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize, maxSize + 1))
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSize(1, Size(maxSize + 1, maxSize + 1))
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(0, Size(maxSize, maxSize))
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSize(-1, Size(maxSize, maxSize))
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSize(-1, Size(maxSize + 1, maxSize + 1))
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSize(0, Size(maxSize + 1, maxSize + 1))
)
}
@Test
fun testLimitedSampleSizeByMaxBitmapSizeForRegion() {
val maxSize = maxBitmapSize.width
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize - 1, maxSize), 1)
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize - 1), 1)
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(
Size(maxSize - 1, maxSize - 1),
1
)
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), 1)
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize + 1, maxSize), 1)
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize + 1), 1)
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSizeForRegion(
Size(maxSize + 1, maxSize + 1),
1
)
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), 0)
)
Assert.assertEquals(
1,
limitedSampleSizeByMaxBitmapSizeForRegion(Size(maxSize, maxSize), -1)
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSizeForRegion(
Size(maxSize + 1, maxSize + 1),
-1
)
)
Assert.assertEquals(
2,
limitedSampleSizeByMaxBitmapSizeForRegion(
Size(maxSize + 1, maxSize + 1),
0
)
)
}
@Test
fun testRealDecode() {
val context = InstrumentationRegistry.getInstrumentation().context
val sketch = context.sketch
val hasExifFile = ExifOrientationTestFileHelper(context, "sample.jpeg")
.files().find { it.exifOrientation == ExifInterface.ORIENTATION_ROTATE_90 }!!
@Suppress("ComplexRedundantLet")
val result1 = LoadRequest(context, hasExifFile.file.path) {
resizeSize(3000, 3000)
resizePrecision(LESS_PIXELS)
}.let {
realDecode(
it.toRequestContext(),
LOCAL,
ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation),
{ config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(imageInfo.size, bitmap.size)
Assert.assertEquals(
ImageInfo(
1936,
1291,
"image/jpeg",
ExifInterface.ORIENTATION_ROTATE_90
), imageInfo
)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertNull(transformedList)
}
LoadRequest(context, hasExifFile.file.path) {
resizeSize(3000, 3000)
resizePrecision(LESS_PIXELS)
ignoreExifOrientation(true)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(imageInfo.size, bitmap.size)
Assert.assertEquals(
ImageInfo(
1936,
1291,
"image/jpeg",
ExifInterface.ORIENTATION_ROTATE_90
), imageInfo
)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertNull(transformedList)
Assert.assertEquals(result1.bitmap.corners(), bitmap.corners())
}
val result3 = LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(EXACTLY)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(121, 60), bitmap.size)
Assert.assertEquals(
ImageInfo(
1936,
1291,
"image/jpeg",
ExifInterface.ORIENTATION_ROTATE_90
), imageInfo
)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(
listOf(
createInSampledTransformed(16),
createSubsamplingTransformed(Rect(0, 161, 1936, 1129))
),
transformedList
)
}
LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(EXACTLY)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(80, 161), bitmap.size)
Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(
listOf(
createInSampledTransformed(8),
createSubsamplingTransformed(Rect(645, 0, 1290, 1291))
),
transformedList
)
Assert.assertNotEquals(result3.bitmap.corners(), bitmap.corners())
}
val result5 = LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(SAME_ASPECT_RATIO)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(121, 60), bitmap.size)
Assert.assertEquals(
ImageInfo(
1936,
1291,
"image/jpeg",
ExifInterface.ORIENTATION_ROTATE_90
), imageInfo
)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(
listOf(
createInSampledTransformed(16),
createSubsamplingTransformed(Rect(0, 161, 1936, 1129))
),
transformedList
)
}
LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(SAME_ASPECT_RATIO)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(80, 161), bitmap.size)
Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(
listOf(
createInSampledTransformed(8),
createSubsamplingTransformed(Rect(645, 0, 1290, 1291))
),
transformedList
)
Assert.assertNotEquals(result5.bitmap.corners(), bitmap.corners())
}
val result7 = LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(LESS_PIXELS)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", hasExifFile.exifOrientation),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(121, 81), bitmap.size)
Assert.assertEquals(
ImageInfo(
1936,
1291,
"image/jpeg",
ExifInterface.ORIENTATION_ROTATE_90
), imageInfo
)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(listOf(createInSampledTransformed(16)), transformedList)
}
LoadRequest(context, hasExifFile.file.path).newLoadRequest {
resizeSize(100, 200)
resizePrecision(LESS_PIXELS)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(1936, 1291, "image/jpeg", 0),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
}
) { rect, config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeRegionBitmap(rect, config.toBitmapOptions())!!
}
}.apply {
Assert.assertEquals(Size(121, 81), bitmap.size)
Assert.assertEquals(ImageInfo(1936, 1291, "image/jpeg", 0), imageInfo)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(listOf(createInSampledTransformed(16)), transformedList)
Assert.assertEquals(result7.bitmap.corners(), bitmap.corners())
}
val result9 = LoadRequest(context, newAssetUri("sample.bmp")) {
resizeSize(100, 200)
resizePrecision(EXACTLY)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(700, 1012, "image/bmp", 0),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
},
decodeRegion = null
)
}.apply {
Assert.assertEquals(Size(87, 126), bitmap.size)
Assert.assertEquals(ImageInfo(700, 1012, "image/bmp", 0), imageInfo)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(listOf(createInSampledTransformed(8)), transformedList)
}
LoadRequest(context, newAssetUri("sample.bmp")).newLoadRequest {
resizeSize(100, 200)
resizePrecision(EXACTLY)
ignoreExifOrientation(true)
}.let {
realDecode(
requestContext = it.toRequestContext(),
dataFrom = LOCAL,
imageInfo = ImageInfo(700, 1012, "image/jpeg", 0),
decodeFull = { config ->
runBlocking {
sketch.components.newFetcher(it).fetch()
}.dataSource.decodeBitmap(config.toBitmapOptions())!!
},
decodeRegion = null
)
}.apply {
Assert.assertEquals(Size(87, 126), bitmap.size)
Assert.assertEquals(ImageInfo(700, 1012, "image/jpeg", 0), imageInfo)
Assert.assertEquals(LOCAL, dataFrom)
Assert.assertEquals(listOf(createInSampledTransformed(8)), transformedList)
Assert.assertEquals(result9.bitmap.corners(), bitmap.corners())
}
}
@Test
fun testAppliedExifOrientation() {
val (context, sketch) = getTestContextAndNewSketch()
val request = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI)
val hasExifFile = ExifOrientationTestFileHelper(context, "sample.jpeg")
.files().find { it.exifOrientation == ExifInterface.ORIENTATION_ROTATE_90 }!!
val bitmap = BitmapFactory.decodeFile(hasExifFile.file.path)
val result = BitmapDecodeResult(
bitmap = bitmap,
imageInfo = ImageInfo(
width = bitmap.width,
height = bitmap.height,
mimeType = "image/jpeg",
exifOrientation = hasExifFile.exifOrientation
),
dataFrom = LOCAL,
transformedList = null,
extras = null,
)
val resultCorners = result.bitmap.corners()
Assert.assertNull(result.transformedList?.getExifOrientationTransformed())
result.appliedExifOrientation(
sketch,
request.toRequestContext()
).apply {
Assert.assertNotSame(result, this)
Assert.assertNotSame(result.bitmap, this.bitmap)
Assert.assertEquals(Size(result.bitmap.height, result.bitmap.width), this.bitmap.size)
Assert.assertEquals(
Size(result.imageInfo.height, result.imageInfo.width),
this.imageInfo.size
)
Assert.assertNotEquals(resultCorners, this.bitmap.corners())
Assert.assertNotNull(this.transformedList?.getExifOrientationTransformed())
}
val noExifOrientationResult = result.newResult(
imageInfo = result.imageInfo.newImageInfo(exifOrientation = 0)
)
noExifOrientationResult.appliedExifOrientation(
sketch,
request.toRequestContext()
).apply {
Assert.assertSame(noExifOrientationResult, this)
}
}
@Test
fun testAppliedResize() {
val (context, sketch) = getTestContextAndNewSketch()
var request = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI)
val newResult: () -> BitmapDecodeResult = {
BitmapDecodeResult(
bitmap = Bitmap.createBitmap(80, 50, ARGB_8888),
imageInfo = ImageInfo(80, 50, "image/png", 0),
dataFrom = MEMORY,
transformedList = null,
extras = null,
)
}
/*
* LESS_PIXELS
*/
// small
request = request.newLoadRequest {
resize(40, 20, LESS_PIXELS, CENTER_CROP)
}
var result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this !== result)
Assert.assertEquals("20x13", this.bitmap.sizeString)
}
// big
request = request.newLoadRequest {
resize(50, 150, LESS_PIXELS)
}
result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this === result)
}
/*
* SAME_ASPECT_RATIO
*/
// small
request = request.newLoadRequest {
resize(40, 20, SAME_ASPECT_RATIO)
}
result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this !== result)
Assert.assertEquals("40x20", this.bitmap.sizeString)
}
// big
request = request.newLoadRequest {
resize(50, 150, SAME_ASPECT_RATIO)
}
result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this !== result)
Assert.assertEquals("17x50", this.bitmap.sizeString)
}
/*
* EXACTLY
*/
// small
request = request.newLoadRequest {
resize(40, 20, EXACTLY)
}
result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this !== result)
Assert.assertEquals("40x20", this.bitmap.sizeString)
}
// big
request = request.newLoadRequest {
resize(50, 150, EXACTLY)
}
result = newResult()
result.appliedResize(sketch, request.toRequestContext()).apply {
Assert.assertTrue(this !== result)
Assert.assertEquals("50x150", this.bitmap.sizeString)
}
}
@Test
fun testComputeSizeMultiplier() {
Assert.assertEquals(0.2, computeSizeMultiplier(1000, 600, 200, 400, true), 0.1)
Assert.assertEquals(0.6, computeSizeMultiplier(1000, 600, 200, 400, false), 0.1)
Assert.assertEquals(0.3, computeSizeMultiplier(1000, 600, 400, 200, true), 0.1)
Assert.assertEquals(0.4, computeSizeMultiplier(1000, 600, 400, 200, false), 0.1)
Assert.assertEquals(0.6, computeSizeMultiplier(1000, 600, 2000, 400, true), 0.1)
Assert.assertEquals(2.0, computeSizeMultiplier(1000, 600, 2000, 400, false), 0.1)
Assert.assertEquals(0.4, computeSizeMultiplier(1000, 600, 400, 2000, true), 0.1)
Assert.assertEquals(3.3, computeSizeMultiplier(1000, 600, 400, 2000, false), 0.1)
Assert.assertEquals(2.0, computeSizeMultiplier(1000, 600, 2000, 4000, true), 0.1)
Assert.assertEquals(6.6, computeSizeMultiplier(1000, 600, 2000, 4000, false), 0.1)
Assert.assertEquals(3.3, computeSizeMultiplier(1000, 600, 4000, 2000, true), 0.1)
Assert.assertEquals(4.0, computeSizeMultiplier(1000, 600, 4000, 2000, false), 0.1)
}
@Test
fun testReadImageInfoWithBitmapFactory() {
val (context, sketch) = getTestContextAndNewSketch()
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.readImageInfoWithBitmapFactory().apply {
Assert.assertEquals(1291, width)
Assert.assertEquals(1936, height)
Assert.assertEquals("image/jpeg", mimeType)
Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp")
.readImageInfoWithBitmapFactory().apply {
Assert.assertEquals(1080, width)
Assert.assertEquals(1344, height)
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
Assert.assertEquals("image/webp", mimeType)
} else {
Assert.assertEquals("", mimeType)
}
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
ResourceDataSource(
sketch,
LoadRequest(context, newResourceUri(R.xml.network_security_config)),
packageName = context.packageName,
context.resources,
R.xml.network_security_config
).readImageInfoWithBitmapFactory().apply {
Assert.assertEquals(-1, width)
Assert.assertEquals(-1, height)
Assert.assertEquals("", mimeType)
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach {
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactory().apply {
Assert.assertEquals(it.exifOrientation, exifOrientation)
}
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactory(true).apply {
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
}
}
@Test
fun testReadImageInfoWithBitmapFactoryOrThrow() {
val (context, sketch) = getTestContextAndNewSketch()
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.readImageInfoWithBitmapFactoryOrThrow().apply {
Assert.assertEquals(1291, width)
Assert.assertEquals(1936, height)
Assert.assertEquals("image/jpeg", mimeType)
Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp")
.readImageInfoWithBitmapFactoryOrThrow().apply {
Assert.assertEquals(1080, width)
Assert.assertEquals(1344, height)
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
Assert.assertEquals("image/webp", mimeType)
} else {
Assert.assertEquals("", mimeType)
}
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
assertThrow(ImageInvalidException::class) {
ResourceDataSource(
sketch,
LoadRequest(context, newResourceUri(R.xml.network_security_config)),
packageName = context.packageName,
context.resources,
R.xml.network_security_config
).readImageInfoWithBitmapFactoryOrThrow()
}
ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach {
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactoryOrThrow().apply {
Assert.assertEquals(it.exifOrientation, exifOrientation)
}
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactoryOrThrow(true).apply {
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
}
}
@Test
fun testReadImageInfoWithBitmapFactoryOrNull() {
val (context, sketch) = getTestContextAndNewSketch()
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.readImageInfoWithBitmapFactoryOrNull()!!.apply {
Assert.assertEquals(1291, width)
Assert.assertEquals(1936, height)
Assert.assertEquals("image/jpeg", mimeType)
Assert.assertEquals(ExifInterface.ORIENTATION_NORMAL, exifOrientation)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp")
.readImageInfoWithBitmapFactoryOrNull()!!.apply {
Assert.assertEquals(1080, width)
Assert.assertEquals(1344, height)
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
Assert.assertEquals("image/webp", mimeType)
} else {
Assert.assertEquals("", mimeType)
}
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
Assert.assertNull(
ResourceDataSource(
sketch,
LoadRequest(context, newResourceUri(R.xml.network_security_config)),
packageName = context.packageName,
context.resources,
R.xml.network_security_config
).readImageInfoWithBitmapFactoryOrNull()
)
ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach {
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactoryOrNull()!!.apply {
Assert.assertEquals(it.exifOrientation, exifOrientation)
}
FileDataSource(sketch, LoadRequest(context, it.file.path), it.file)
.readImageInfoWithBitmapFactoryOrNull(true)!!.apply {
Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation)
}
}
}
@Test
fun testDecodeBitmap() {
val (context, sketch) = getTestContextAndNewSketch()
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.decodeBitmap()!!.apply {
Assert.assertEquals(1291, width)
Assert.assertEquals(1936, height)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.decodeBitmap(BitmapFactory.Options().apply { inSampleSize = 2 })!!
.apply {
Assert.assertEquals(646, width)
Assert.assertEquals(968, height)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp")
.decodeBitmap()!!.apply {
Assert.assertEquals(1080, width)
Assert.assertEquals(1344, height)
}
Assert.assertNull(
ResourceDataSource(
sketch,
LoadRequest(context, newResourceUri(R.xml.network_security_config)),
packageName = context.packageName,
context.resources,
R.xml.network_security_config
).decodeBitmap()
)
}
@Test
fun testDecodeRegionBitmap() {
val (context, sketch) = getTestContextAndNewSketch()
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.decodeRegionBitmap(Rect(500, 500, 600, 600))!!.apply {
Assert.assertEquals(100, width)
Assert.assertEquals(100, height)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg")
.decodeRegionBitmap(
Rect(500, 500, 600, 600),
BitmapFactory.Options().apply { inSampleSize = 2 })!!
.apply {
Assert.assertEquals(50, width)
Assert.assertEquals(50, height)
}
AssetDataSource(sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp")
.decodeRegionBitmap(Rect(500, 500, 700, 700))!!.apply {
Assert.assertEquals(200, width)
Assert.assertEquals(200, height)
}
assertThrow(IOException::class) {
ResourceDataSource(
sketch,
LoadRequest(context, newResourceUri(R.xml.network_security_config)),
packageName = context.packageName,
context.resources,
R.xml.network_security_config
).decodeRegionBitmap(Rect(500, 500, 600, 600))
}
}
@Test
fun testSupportBitmapRegionDecoder() {
if (VERSION.SDK_INT >= VERSION_CODES.P) {
Assert.assertTrue(ImageFormat.HEIC.supportBitmapRegionDecoder())
} else {
Assert.assertFalse(ImageFormat.HEIC.supportBitmapRegionDecoder())
}
if (VERSION.SDK_INT >= VERSION_CODES.P) {
Assert.assertTrue(ImageFormat.HEIF.supportBitmapRegionDecoder())
} else {
Assert.assertFalse(ImageFormat.HEIF.supportBitmapRegionDecoder())
}
Assert.assertFalse(ImageFormat.BMP.supportBitmapRegionDecoder())
Assert.assertFalse(ImageFormat.GIF.supportBitmapRegionDecoder())
Assert.assertTrue(ImageFormat.JPEG.supportBitmapRegionDecoder())
Assert.assertTrue(ImageFormat.PNG.supportBitmapRegionDecoder())
Assert.assertTrue(ImageFormat.WEBP.supportBitmapRegionDecoder())
}
@Test
fun testIsInBitmapError() {
Assert.assertTrue(
isInBitmapError(IllegalArgumentException("Problem decoding into existing bitmap"))
)
Assert.assertTrue(
isInBitmapError(IllegalArgumentException("bitmap"))
)
Assert.assertFalse(
isInBitmapError(IllegalArgumentException("Problem decoding"))
)
Assert.assertFalse(
isInBitmapError(IllegalStateException("Problem decoding into existing bitmap"))
)
}
@Test
fun testIsSrcRectError() {
Assert.assertTrue(
isSrcRectError(IllegalArgumentException("rectangle is outside the image srcRect"))
)
Assert.assertTrue(
isSrcRectError(IllegalArgumentException("srcRect"))
)
Assert.assertFalse(
isSrcRectError(IllegalStateException("rectangle is outside the image srcRect"))
)
Assert.assertFalse(
isSrcRectError(IllegalArgumentException(""))
)
}
@Test
fun testIsSupportInBitmap() {
Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmap("image/jpeg", 1))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/jpeg", 2))
Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmap("image/png", 1))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/png", 2))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/gif", 1))
Assert.assertEquals(VERSION.SDK_INT >= 21, isSupportInBitmap("image/gif", 2))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/webp", 1))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/webp", 2))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/bmp", 1))
Assert.assertEquals(VERSION.SDK_INT >= 19, isSupportInBitmap("image/bmp", 2))
Assert.assertEquals(false, isSupportInBitmap("image/heic", 1))
Assert.assertEquals(false, isSupportInBitmap("image/heic", 2))
Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmap("image/heif", 1))
Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmap("image/heif", 2))
Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmap("image/svg", 1))
Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmap("image/svg", 2))
}
@Test
fun testIsSupportInBitmapForRegion() {
Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/jpeg"))
Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/png"))
Assert.assertEquals(false, isSupportInBitmapForRegion("image/gif"))
Assert.assertEquals(VERSION.SDK_INT >= 16, isSupportInBitmapForRegion("image/webp"))
Assert.assertEquals(false, isSupportInBitmapForRegion("image/bmp"))
Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmapForRegion("image/heic"))
Assert.assertEquals(VERSION.SDK_INT >= 28, isSupportInBitmapForRegion("image/heif"))
Assert.assertEquals(VERSION.SDK_INT >= 32, isSupportInBitmapForRegion("image/svg"))
}
@Test
fun testIsWebP() {
val context = getTestContext()
Bytes(context.assets.open("sample.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isWebP())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isWebP())
}
Bytes(context.assets.open("sample.webp").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(8, 'V'.code.toByte())
}
}).apply {
Assert.assertFalse(isWebP())
}
Bytes(context.assets.open("sample.jpeg").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isWebP())
}
}
@Test
fun testIsAnimatedWebP() {
val context = getTestContext()
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isAnimatedWebP())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(12, 'X'.code.toByte())
}
}).apply {
Assert.assertFalse(isAnimatedWebP())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(16, 0)
}
}).apply {
Assert.assertFalse(isAnimatedWebP())
}
Bytes(context.assets.open("sample.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isAnimatedWebP())
}
Bytes(context.assets.open("sample.jpeg").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isAnimatedWebP())
}
}
@Test
fun testIsHeif() {
val context = getTestContext()
Bytes(context.assets.open("sample.heic").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isHeif())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isHeif())
}
Bytes(context.assets.open("sample.jpeg").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isHeif())
}
}
@Test
fun testIsAnimatedHeif() {
val context = getTestContext()
Bytes(context.assets.open("sample_anim.heif").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isAnimatedHeif())
}
Bytes(context.assets.open("sample_anim.heif").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(8, 'h'.code.toByte())
set(9, 'e'.code.toByte())
set(10, 'v'.code.toByte())
set(11, 'c'.code.toByte())
}
}).apply {
Assert.assertTrue(isAnimatedHeif())
}
Bytes(context.assets.open("sample_anim.heif").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(8, 'h'.code.toByte())
set(9, 'e'.code.toByte())
set(10, 'v'.code.toByte())
set(11, 'x'.code.toByte())
}
}).apply {
Assert.assertTrue(isAnimatedHeif())
}
Bytes(context.assets.open("sample.heic").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isAnimatedHeif())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isAnimatedHeif())
}
Bytes(context.assets.open("sample.jpeg").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isAnimatedHeif())
}
}
@Test
fun testIsGif() {
val context = getTestContext()
Bytes(context.assets.open("sample_anim.gif").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertTrue(isGif())
}
Bytes(context.assets.open("sample_anim.gif").use {
ByteArray(1024).apply { it.read(this) }.apply {
set(4, '7'.code.toByte())
}
}).apply {
Assert.assertTrue(isGif())
}
Bytes(context.assets.open("sample_anim.webp").use {
ByteArray(1024).apply { it.read(this) }
}).apply {
Assert.assertFalse(isGif())
}
}
} | sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/DecodeUtilsTest.kt | 3243399935 |
package org.mariotaku.ktextension
import nl.komponents.kovenant.Deferred
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.deferred
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReferenceArray
/**
* Created by mariotaku on 2016/12/2.
*/
fun <V, E> combine(promises: List<Promise<V, E>>): Promise<List<V>, E> {
return concreteCombine(promises)
}
fun <V, E> concreteCombine(promises: List<Promise<V, E>>): Promise<List<V>, E> {
val deferred = deferred<List<V>, E>()
val results = AtomicReferenceArray<V>(promises.size)
val successCount = AtomicInteger(promises.size)
fun createArray(): List<V> {
return (0 until results.length()).map { results[it] }
}
fun Promise<V, *>.registerSuccess(idx: Int) {
success { v ->
results.set(idx, v)
if (successCount.decrementAndGet() == 0) {
deferred.resolve(createArray())
}
}
}
fun <V, E> Deferred<V, E>.registerFail(promises: List<Promise<*, E>>) {
val failCount = AtomicInteger(0)
promises.forEach { promise ->
promise.fail { e ->
if (failCount.incrementAndGet() == 1) {
this.reject(e)
}
}
}
}
promises.forEachIndexed { idx, promise ->
promise.registerSuccess(idx)
}
deferred.registerFail(promises)
return deferred.promise
}
| twittnuker/src/main/kotlin/org/mariotaku/ktextension/PromiseArrayCombine.kt | 3313609376 |
package ws.osiris.integration
import com.amazonaws.services.cloudformation.AmazonCloudFormation
import com.amazonaws.services.cloudformation.model.DeleteStackRequest
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.waiters.WaiterParameters
import com.google.gson.Gson
import org.slf4j.LoggerFactory
import ws.osiris.awsdeploy.AwsProfile
import ws.osiris.awsdeploy.cloudformation.getAllRestApis
import ws.osiris.awsdeploy.cloudformation.listAllStacks
import ws.osiris.awsdeploy.codeBucketName
import ws.osiris.awsdeploy.staticFilesBucketName
import ws.osiris.core.HttpHeaders
import ws.osiris.core.MimeTypes
import ws.osiris.core.TestClient
import ws.osiris.server.HttpTestClient
import ws.osiris.server.Protocol
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.BasicFileAttributes
import kotlin.test.assertEquals
private val log = LoggerFactory.getLogger("ws.osiris.integration")
private const val TEST_APP_NAME = "osiris-e2e-test"
private const val TEST_GROUP_ID = "com.example.osiris"
private const val TEST_REGION = "eu-west-1"
fun main(args: Array<String>) {
if (args.isEmpty()) throw IllegalArgumentException("Must provide the Osiris version as the only argument")
EndToEndTest.run(args[0])
}
class EndToEndTest private constructor(
private val region: String,
private val groupId: String,
private val appName: String,
private val osirisVersion: String,
private val profile: AwsProfile,
private val buildRunner: BuildRunner
) {
companion object {
private val log = LoggerFactory.getLogger(EndToEndTest::class.java)
/**
* Runs an end-to-end test that
*/
fun run(osirisVersion: String) {
val profile = AwsProfile.default()
val buildRunner = MavenBuildRunner()
EndToEndTest(TEST_REGION, TEST_GROUP_ID, TEST_APP_NAME, osirisVersion, profile, buildRunner).run()
}
}
//--------------------------------------------------------------------------------------------------
private fun run() {
deleteStack(appName, profile.cloudFormationClient)
TmpDirResource().use { tmpDirResource ->
val buildSpec = BuildSpec(osirisVersion, groupId, appName, tmpDirResource.path)
val projectDir = buildRunner.createProject(buildSpec)
buildRunner.deploy(buildSpec, profile).use { stackResource ->
try {
val server = "${stackResource.apiId}.execute-api.$region.amazonaws.com"
listOf("dev", "prod").forEach { stage ->
log.info("Testing API stage $stage")
val testClient = HttpTestClient(Protocol.HTTPS, server, basePath = "/$stage")
testApi1(testClient)
}
copyUpdatedFiles(projectDir)
buildRunner.deploy(buildSpec, profile)
log.info("Testing API stage dev")
val devTestClient = HttpTestClient(Protocol.HTTPS, server, basePath = "/dev")
testApi2(devTestClient)
log.info("Testing API stage prod")
val testClient = HttpTestClient(Protocol.HTTPS, server, basePath = "/prod")
testApi1(testClient)
} finally {
// the bucket must be empty or the stack can't be deleted
emptyBucket(staticFilesBucketName(appName, null, profile.accountId), profile.s3Client)
}
}
deleteS3Buckets()
}
}
private fun deleteS3Buckets() {
val codeBucketName = codeBucketName(appName, null, profile.accountId)
val staticFilesBucketName = staticFilesBucketName(appName, null, profile.accountId)
if (profile.s3Client.doesBucketExistV2(codeBucketName)) deleteBucket(codeBucketName, profile.s3Client)
if (profile.s3Client.doesBucketExistV2(staticFilesBucketName)) deleteBucket(staticFilesBucketName, profile.s3Client)
}
private fun testApi1(client: TestClient) {
val gson = Gson()
fun Any?.parseJson(): Map<*, *> {
val json = this as? String ?: throw IllegalArgumentException("Value is not a string: $this")
return gson.fromJson(json, Map::class.java)
}
val response1 = client.get("/helloworld")
assertEquals(mapOf("message" to "hello, world!"), response1.body.parseJson())
assertEquals(MimeTypes.APPLICATION_JSON, response1.headers[HttpHeaders.CONTENT_TYPE])
assertEquals(200, response1.status)
val response2 = client.get("/helloplain")
assertEquals("hello, world!", response2.body)
assertEquals(MimeTypes.TEXT_PLAIN, response2.headers[HttpHeaders.CONTENT_TYPE])
assertEquals(mapOf("message" to "hello, Alice!"), client.get("/helloqueryparam?name=Alice").body.parseJson())
assertEquals(mapOf("message" to "hello, Peter!"), client.get("/hello/Peter").body.parseJson())
assertEquals(mapOf("message" to "hello, Bob!"), client.get("/helloenv").body.parseJson())
log.info("API tested successfully")
}
private fun testApi2(client: TestClient) {
val maxTries = 10
fun testApi2(tries: Int, sleepMs: Long) {
try {
assertApi(client)
} catch (e: Throwable) {
if (tries < maxTries) {
log.info("assertApi failed, waiting for {}ms and retrying", sleepMs)
Thread.sleep(sleepMs)
testApi2(tries + 1, sleepMs * 2)
} else {
log.info("assertApi didn't pass after {} attempts", maxTries)
throw e
}
}
}
testApi2(1, 1000)
}
private fun copyUpdatedFiles(projectDir: Path) {
val e2eFilesDir = Paths.get("integration/src/test/e2e-test")
val projectStaticDir = projectDir.resolve("core/src/main/static")
copyDirectoryContents(e2eFilesDir.resolve("static"), projectStaticDir)
val codeDir = projectDir.resolve("core/src/main/kotlin/com/example/osiris/core")
copyDirectoryContents(e2eFilesDir.resolve("code"), codeDir)
}
}
/**
* Auto-closable resource representing a CloudFormation stack; allows the stack to be automatically deleted
* when testing is complete.
*/
internal class StackResource(
val apiId: String,
private val appName: String,
private val cloudFormationClient: AmazonCloudFormation
) : AutoCloseable {
override fun close() {
deleteStack(appName, cloudFormationClient)
}
}
/**
* Auto-closable wrapper around a temporary directory.
*
* When it is closed the directory and its contents are deleted.
*/
internal class TmpDirResource : AutoCloseable {
internal val path: Path = Files.createTempDirectory("osiris-e2e-test")
override fun close() {
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, basicFileAttributes: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(directory: Path, ioException: IOException?): FileVisitResult {
Files.delete(directory)
return FileVisitResult.CONTINUE
}
})
}
}
// --------------------------------------------------------------------------------------------------
/**
* Deletes an S3 bucket, deleting its contents first if it is not empty.
*/
fun deleteBucket(bucketName: String, s3Client: AmazonS3) {
emptyBucket(bucketName, s3Client)
s3Client.deleteBucket(bucketName)
log.info("Deleted bucket {}", bucketName)
}
/**
* Deletes a CloudFormation stack, blocking until the deletion has completed.
*/
fun deleteStack(stack: String, cloudFormationClient: AmazonCloudFormation) {
val stacks = cloudFormationClient.listAllStacks().filter { it.stackName == stack }
if (stacks.isEmpty()) {
log.info("No existing stack found named {}, skipping deletion", stack)
} else {
val name = stacks[0].stackName
log.info("Deleting stack '{}'", name)
val deleteWaiter = cloudFormationClient.waiters().stackDeleteComplete()
cloudFormationClient.deleteStack(DeleteStackRequest().apply { stackName = name })
deleteWaiter.run(WaiterParameters(DescribeStacksRequest().apply { stackName = name }))
log.info("Deleted stack '{}'", name)
}
}
/**
* Deletes all objects from an S3 bucket.
*/
private tailrec fun emptyBucket(bucketName: String, s3Client: AmazonS3) {
if (!s3Client.doesBucketExistV2(bucketName)) return
val objects = s3Client.listObjects(bucketName).objectSummaries
if (objects.isEmpty()) {
return
} else {
objects.forEach { s3Client.deleteObject(bucketName, it.key) }
emptyBucket(bucketName, s3Client)
}
}
/**
* Copies the contents of [src] to [dest], including all subdirectories and their contents
*/
fun copyDirectoryContents(src: Path, dest: Path) {
if (!Files.isDirectory(src) || !Files.isDirectory(dest)) {
throw IllegalArgumentException("src and dest must be directories")
}
Files.walk(src).filter { Files.isRegularFile(it) }.forEach { copyFile(it, src, dest) }
}
/**
* Copies a file and its containing directories from [baseDir] to [destDir].
*
* [baseDir] and [destDir] must be directories and [file] must be a file below [baseDir].
* [file] is copied so the path of the copy relative to [destDir] is the same as the path of
* the original relative to [baseDir].
*/
private fun copyFile(file: Path, baseDir: Path, destDir: Path) {
if (!Files.isDirectory(baseDir) || !Files.isDirectory(destDir)) {
throw IllegalArgumentException("baseDir and destDir must be directories")
}
val relativePath = baseDir.relativize(file)
val destFile = destDir.resolve(relativePath)
Files.createDirectories(destFile.parent)
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING)
log.debug(
"Copied file {} from directory {} to {}",
file.toAbsolutePath(),
baseDir.toAbsolutePath(),
destFile.toAbsolutePath()
)
}
// --------------------------------------------------------------------------------------------------
/**
* Wrapper around a build tool that can create a new project and deploy a project to AWS.
*/
internal interface BuildRunner {
/** Creates a new Osiris project. */
fun createProject(buildSpec: BuildSpec): Path
/** Deploys a project to AWS. */
fun deploy(buildSpec: BuildSpec, profile: AwsProfile): StackResource
}
/**
* Metadata describing an Osiris project build.
*/
internal data class BuildSpec(
val osirisVersion: String,
val groupId: String,
val appName: String,
val parentDir: Path
)
internal class MavenBuildRunner : BuildRunner {
override fun createProject(buildSpec: BuildSpec): Path {
log.info(
"Creating project in {} using Maven archetype version {}, groupId={}, artifactId={}",
buildSpec.parentDir.normalize().toAbsolutePath(),
buildSpec.osirisVersion,
buildSpec.groupId,
buildSpec.appName
)
val exitValue = ProcessBuilder(
"mvn",
"archetype:generate",
"-DarchetypeGroupId=ws.osiris",
"-DarchetypeArtifactId=osiris-archetype",
"-DarchetypeVersion=${buildSpec.osirisVersion}",
"-DgroupId=${buildSpec.groupId}",
"-DartifactId=${buildSpec.appName}",
"-DinteractiveMode=false")
.directory(buildSpec.parentDir.toFile())
.inheritIO()
.start()
.waitFor()
if (exitValue == 0) {
log.info("Project created successfully")
} else {
throw IllegalStateException("Project creation failed, Maven exit value = $exitValue")
}
return buildSpec.projectDir
}
override fun deploy(buildSpec: BuildSpec, profile: AwsProfile): StackResource {
log.info("Deploying project from directory ${buildSpec.projectDir}")
val exitValue = ProcessBuilder("mvn", "deploy")
.directory(buildSpec.projectDir.toFile())
.inheritIO()
.start()
.waitFor()
if (exitValue == 0) {
log.info("Project deployed successfully")
} else {
throw IllegalStateException("Project deployment failed, Maven exit value = $exitValue")
}
val apis = profile.apiGatewayClient.getAllRestApis()
val apiId = apis.firstOrNull { it.name == buildSpec.appName }?.id
?: throw IllegalStateException("No REST API found named ${buildSpec.appName}")
log.info("ID of the deployed API: {}", apiId)
return StackResource(apiId, buildSpec.appName, profile.cloudFormationClient)
}
private val BuildSpec.projectDir: Path get() = parentDir.resolve(appName)
}
// TODO requirements for a general purpose end-to-end testing tool
// * get the project to test
// * generate from artifact
// * git clone
// * existing directory?
// * build
// * maven
// * gradle
// * create buckets if necessary (only if staticFilesBucket and codeBucket are set)
// * deploy
// * test
// * test the API endpoints
// * copy files over the top
// * redeploy
// * (repeat)
// * delete stack
// * delete buckets
| integration/src/test/kotlin/ws/osiris/integration/EndToEndTest.kt | 810169645 |
package org.wikipedia.feed.topread
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.wikipedia.R
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.feed.model.CardType
import org.wikipedia.feed.model.ListCard
import org.wikipedia.util.DateUtil
import org.wikipedia.util.L10nUtil
import java.util.concurrent.TimeUnit
@Parcelize
class TopReadListCard(private val articles: TopRead, val site: WikiSite) :
ListCard<TopReadItemCard>(toItems(articles.articles, site), site), Parcelable {
override fun title(): String {
return L10nUtil.getStringForArticleLanguage(wikiSite().languageCode, R.string.view_top_read_card_title)
}
override fun subtitle(): String {
return DateUtil.getFeedCardDateString(articles.date())
}
override fun type(): CardType {
return CardType.TOP_READ_LIST
}
fun footerActionText(): String {
return L10nUtil.getStringForArticleLanguage(wikiSite().languageCode, R.string.view_top_read_card_action)
}
override fun dismissHashCode(): Int {
return TimeUnit.MILLISECONDS.toDays(articles.date().time).toInt() + wikiSite().hashCode()
}
companion object {
fun toItems(articles: List<PageSummary>, wiki: WikiSite): List<TopReadItemCard> {
return articles.map { TopReadItemCard(it, wiki) }
}
}
}
| app/src/main/java/org/wikipedia/feed/topread/TopReadListCard.kt | 1946926848 |
/*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.data.remote
import android.location.Location
import ch.hsr.geohash.GeoHash
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.Query
import com.google.firebase.database.ServerValue
import com.google.firebase.database.ValueEventListener
import site.paulo.localchat.data.manager.CurrentUserManager
import site.paulo.localchat.ui.utils.Utils
import site.paulo.localchat.ui.utils.getFirebaseId
import timber.log.Timber
import java.util.HashMap
import javax.inject.Inject
import javax.inject.Singleton
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DataSnapshot
import durdinapps.rxfirebase2.DataSnapshotMapper
import durdinapps.rxfirebase2.RxFirebaseAuth
import durdinapps.rxfirebase2.RxFirebaseDatabase
import io.reactivex.Maybe
import site.paulo.localchat.data.model.firebase.*
import site.paulo.localchat.exception.MissingCurrentUserException
@Singleton
class FirebaseHelper @Inject constructor(val firebaseDatabase: FirebaseDatabase,
val currentUserManager: CurrentUserManager,
val firebaseAuth: FirebaseAuth) {
object Reference {
val CHATS = "chats"
val MESSAGES = "messages"
val USERS = "users"
val GEOHASHES = "geohashes"
}
object Child {
val ACCURACY = "acc"
val AGE = "age"
val CHATS = "chats"
val DELIVERED_MESSAGES = "deliveredMessages"
val EMAIL = "email"
val GENDER = "gender"
val GEOHASH = "geohash"
val ID = "id"
val LAST_MESSAGE = "lastMessage"
val LAST_GEO_UPDATE = "lastGeoUpdate"
val LATITUDE = "lat"
val LOCATION = "loc"
val LONGITUDE = "lon"
val MESSAGE = "message"
val NAME = "name"
val OWNER = "owner"
val PIC = "pic"
val TIMESTAMP = "timestamp"
val TOKEN = "token"
val USERS = "users"
}
companion object {
enum class UserDataType {
NAME, AGE, PIC
}
}
private var childEventListeners: HashMap<String, ChildEventListener> = HashMap()
private var valueEventListeners: HashMap<String, ValueEventListener> = HashMap()
/**************** User *********************/
fun getUsers(): Maybe<LinkedHashMap<String, User>> {
return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.USERS),
DataSnapshotMapper.mapOf(User::class.java))
}
//TODO update to user this function
fun getNearbyUsers(geoHash: String): Maybe<LinkedHashMap<String, Any>> {
return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.GEOHASHES).child(geoHash),
DataSnapshotMapper.mapOf(Any::class.java))
}
fun getUser(userId: String): Maybe<User> {
return RxFirebaseDatabase.observeSingleValueEvent(firebaseDatabase.getReference(Reference.USERS).child(userId),
User::class.java)
}
fun registerUser(user: User) {
val userData = mutableMapOf<String, Any>()
userData[Child.EMAIL] = user.email
userData[Child.NAME] = user.name
userData[Child.AGE] = user.age
userData[Child.GENDER] = user.gender
userData[Child.PIC] = "https://api.adorable.io/avatars/240/" + Utils.getFirebaseId(user.email) + ".png"
val completionListener = DatabaseReference.CompletionListener { _, _ ->
Timber.e("User %s registered", user.email)
}
firebaseDatabase.getReference(Reference.USERS).child(Utils.getFirebaseId(user.email)).setValue(userData, completionListener)
}
fun authenticateUser(email: String, password: String): Maybe<AuthResult> {
return RxFirebaseAuth.signInWithEmailAndPassword(firebaseAuth, email, password)
}
fun updateUserData(dataType: UserDataType, newValue: String, completionListener: DatabaseReference.CompletionListener) {
when (dataType) {
UserDataType.NAME -> {
val newName = mutableMapOf<String, Any>()
newName[Child.NAME] = newValue
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId())
.updateChildren(newName, completionListener)
}
UserDataType.AGE -> {
val newAge = mutableMapOf<String, Any>()
newAge[Child.AGE] = newValue.toInt()
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId()).updateChildren(newAge, completionListener)
}
UserDataType.PIC -> {
val newPic = mutableMapOf<String, Any>()
newPic[Child.PIC] = newValue
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId()).updateChildren(newPic, completionListener)
}
}
}
fun updateToken(token: String?) {
val completionListener = DatabaseReference.CompletionListener { _, _ ->
Timber.d("Token updated")
}
if (token != null) {
val newToken = mutableMapOf<String, Any>()
newToken[Child.TOKEN] = token
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId())
.updateChildren(newToken, completionListener)
}
}
fun updateProfilePic(url: String?) {
val completionListener = DatabaseReference.CompletionListener { _, _ ->
Timber.d("Profile pic updated")
}
if (url != null) {
val newProfilePic = mutableMapOf<String, Any>()
newProfilePic[Child.PIC] = url
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId())
.updateChildren(newProfilePic, completionListener)
}
}
fun updateUserLocation(location: Location?, callNext: (() -> Unit)? = null) {
val currentUser = currentUserManager.getUser() ?: return
val locationCompletionListener = DatabaseReference.CompletionListener { _, _ ->
Timber.d("Location updated: lat %s, lon %s", location?.latitude, location?.longitude)
}
val userInfoCompletionListener = DatabaseReference.CompletionListener { _, _ ->
Timber.d("Geohash updated")
}
val removeListener = DatabaseReference.CompletionListener { _, _ ->
Timber.d("Removed from old area")
}
if (location != null) {
val geoHash = GeoHash.geoHashStringWithCharacterPrecision(location.latitude, location.longitude, 5)
currentUser.geohash = geoHash
if (!geoHash.equals(currentUser.geohash))
firebaseDatabase.getReference(Reference.GEOHASHES)
.child(currentUser.geohash)
.child(currentUserManager.getUserId())
.removeValue(removeListener)
val newUserLocation = mutableMapOf<String, Any>()
newUserLocation[Child.LATITUDE] = location.latitude
newUserLocation[Child.LONGITUDE] = location.longitude
newUserLocation[Child.ACCURACY] = location.accuracy
newUserLocation[Child.GEOHASH] = geoHash
firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId())
.updateChildren(newUserLocation, locationCompletionListener)
val newUserInfo = mutableMapOf<String, Any>()
newUserInfo[Child.NAME] = currentUser.name
newUserInfo[Child.PIC] = currentUser.pic
newUserInfo[Child.EMAIL] = currentUser.email
newUserInfo[Child.AGE] = currentUser.age
newUserInfo[Child.LAST_GEO_UPDATE] = ServerValue.TIMESTAMP
firebaseDatabase.getReference(Reference.GEOHASHES)
.child(geoHash)
.child(currentUserManager.getUserId())
.updateChildren(newUserInfo, userInfoCompletionListener)
callNext?.invoke()
}
}
fun registerUserChildEventListener(listener: ChildEventListener) {
registerChildEventListener(firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId()), listener, "User")
}
fun registerUserValueEventListener(listener: ValueEventListener) {
registerValueEventListener(firebaseDatabase.getReference(Reference.USERS)
.child(currentUserManager.getUserId()), listener, "User")
}
/*******************************************/
/**************** Room ****************/
fun sendMessage(message: ChatMessage, chatId: String, completionListener: DatabaseReference.CompletionListener) {
val valueMessage = mutableMapOf<String, Any>()
valueMessage[Child.OWNER] = message.owner
valueMessage[Child.MESSAGE] = message.message
valueMessage[Child.TIMESTAMP] = ServerValue.TIMESTAMP
val valueLastMessage = mutableMapOf<String, Any>()
valueLastMessage[Child.LAST_MESSAGE] = valueMessage
firebaseDatabase.getReference(Reference.MESSAGES).child(chatId).push().setValue(valueMessage, completionListener)
firebaseDatabase.getReference(Reference.CHATS).child(chatId).updateChildren(valueLastMessage)
}
fun getChatRoom(chatId: String): Maybe<Chat> {
val storedChat = firebaseDatabase.getReference(Reference.CHATS).child(chatId)
storedChat.keepSynced(true)
return RxFirebaseDatabase.observeSingleValueEvent(storedChat, Chat::class.java)
}
fun createNewRoom(otherUser: SummarizedUser, otherEmail: String): Chat {
val currentUser = currentUserManager.getUser() ?: throw MissingCurrentUserException("No user set as current")
val summarizedCurrentUser = SummarizedUser(currentUser.name, currentUser.pic)
val summarizedOtherUser = SummarizedUser(otherUser.name, otherUser.pic)
val reference = firebaseDatabase.getReference(Reference.CHATS).push()
val chat = Chat(reference.key!!,
mapOf(Utils.getFirebaseId(currentUser.email) to summarizedCurrentUser,
Utils.getFirebaseId(otherEmail) to summarizedOtherUser),
ChatMessage("", "", 0L),
mapOf(Utils.getFirebaseId(currentUser.email) to 0,
Utils.getFirebaseId(otherEmail) to 0))
reference.setValue(chat)
firebaseDatabase.getReference(Reference.USERS)
.child(Utils.getFirebaseId(currentUser.email))
.child(Child.CHATS)
.updateChildren(mapOf(Utils.getFirebaseId(otherEmail) to reference.key))
firebaseDatabase.getReference(Reference.USERS)
.child(Utils.getFirebaseId(otherEmail))
.child(Child.CHATS)
.updateChildren(mapOf(Utils.getFirebaseId(currentUser.email) to reference.key))
return chat
}
fun registerRoomChildEventListener(listener: ChildEventListener, roomId: String, listenerId: String? = null): Boolean {
firebaseDatabase.getReference(Reference.MESSAGES).child(roomId).keepSynced(true)
return registerChildEventListener(firebaseDatabase.getReference(Reference.MESSAGES)
.child(roomId).orderByChild(Child.TIMESTAMP), listener, listenerId
?: roomId)
}
fun unregisterRoomChildEventListener(listener: ChildEventListener, roomId: String) {
Timber.d("Unregistering room $roomId")
removeChildListeners(firebaseDatabase.getReference(Reference.MESSAGES)
.child(roomId), listener)
childEventListeners.remove(roomId)
}
fun registerRoomValueEventListener(listener: ValueEventListener, roomId: String, listenerId: String? = null): Boolean {
return registerValueEventListener(firebaseDatabase.getReference(Reference.MESSAGES)
.child(roomId).orderByChild(Child.TIMESTAMP), listener, listenerId
?: roomId)
}
fun addRoomSingleValueEventListener(listener: ValueEventListener, roomId: String) {
firebaseDatabase.getReference(Reference.MESSAGES)
.child(roomId).addListenerForSingleValueEvent(listener)
}
fun unregisterRoomValueEventListener(listener: ValueEventListener, roomId: String) {
Timber.d("Unregistering room $roomId")
removeValueListeners(firebaseDatabase.getReference(Reference.MESSAGES)
.child(roomId), listener)
valueEventListeners.remove(roomId)
}
fun registerNewChatRoomChildEventListener(listener: ChildEventListener, _userId: String? = null) {
var userId: String? = _userId
if (userId == null) {
userId = currentUserManager.getUserId()
}
firebaseDatabase.getReference(Reference.USERS).child(userId).child(Child.CHATS).keepSynced(true)
registerChildEventListener(firebaseDatabase.getReference(Reference.USERS).child(userId)
.child(Child.CHATS), listener, "myChats")
}
fun registerNewUsersChildEventListener(listener: ChildEventListener) {
val currentUser = currentUserManager.getUser() ?: return
firebaseDatabase.getReference(Reference.GEOHASHES).child(currentUser.geohash).keepSynced(true)
registerChildEventListener(firebaseDatabase.getReference(Reference.GEOHASHES).child(currentUser.geohash),
listener, "nearbyUsers")
}
fun messageDelivered(chatId: String) {
val mDeliveredRef = firebaseDatabase.getReference(Reference.CHATS).child(chatId).child(Child.DELIVERED_MESSAGES)
mDeliveredRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var delivered = dataSnapshot.child(currentUserManager.getUserId()).value as Long
mDeliveredRef.child(currentUserManager.getUserId()).setValue(++delivered)
}
override fun onCancelled(databaseError: DatabaseError) {
throw databaseError.toException()
}
})
}
/**************************************/
/**************** Listeners ****************/
private fun registerChildEventListener(query: Query, listener: ChildEventListener, listenerIdentifier: String): Boolean {
if (childEventListeners.containsKey(listenerIdentifier)) {
Timber.d("Removing and registering event listener $listenerIdentifier again")
firebaseDatabase.reference.removeEventListener(listener)
}
childEventListeners.put(listenerIdentifier, listener)
query.addChildEventListener(listener)
return true
}
private fun registerValueEventListener(query: Query, listener: ValueEventListener, listenerIdentifier: String): Boolean {
if (!valueEventListeners.containsKey(listenerIdentifier)) {
Timber.d("Registering value listener... $listenerIdentifier")
valueEventListeners.put(listenerIdentifier, listener)
query.addValueEventListener(listener)
return true
}
Timber.d("Listener already registered. Skipping.")
return false
}
fun removeChildListeners(query: Query, listener: ChildEventListener) {
query.removeEventListener(listener)
}
fun removeValueListeners(query: Query, listener: ValueEventListener) {
query.removeEventListener(listener)
}
fun removeAllListeners() {
for ((_, listener) in childEventListeners) {
firebaseDatabase.reference.removeEventListener(listener)
}
for ((_, listener) in valueEventListeners) {
firebaseDatabase.reference.removeEventListener(listener)
}
}
/*******************************************/
}
| app/src/main/kotlin/site/paulo/localchat/data/remote/FirebaseHelper.kt | 2845573251 |
package com.github.kotlinz.kotlinz.data.identity
import com.github.kotlinz.kotlinz.law.MonadLaw
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
object IdentityTest : Spek({
describe("Identity") {
context("as Monad") {
val law = MonadLaw(object : IdentityMonad {})
context("with Int.MAX_VALUE") {
it("should satisfy laws") { law.assertSatisfyingMonadLaw(Int.MAX_VALUE) }
}
context("with Int.MIN_VALUE") {
it("should satisfy laws") { law.assertSatisfyingMonadLaw(Int.MIN_VALUE) }
}
context("with String") {
it("should satisfy laws") { law.assertSatisfyingMonadLaw("Monad Law") }
}
}
}
}) | src/test/kotlin/com/github/kotlinz/kotlinz/data/identity/IdentityTest.kt | 984498538 |
package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.annotation.StringRes
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class SimpleDropdownConfig(
@StringRes override val label: Int,
private val items: List<DropdownItemSpec>
) : DropdownConfig {
override val debugLabel = "simple_dropdown"
override val rawItems = items.map { it.apiValue }
override val displayItems = items.map { it.displayText }
override fun getSelectedItemLabel(index: Int) = displayItems[index]
override fun convertFromRaw(rawValue: String) =
items
.firstOrNull { it.apiValue == rawValue }
?.displayText
?: items[0].displayText
}
| payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/SimpleDropdownConfig.kt | 297512163 |
package com.willmadison.rules
abstract class Condition : RuleElement {
protected var affirmative: RuleElement? = null
protected var negative: RuleElement? = null
abstract fun evaluateCondition(o: Any): Boolean
override fun evaluate(o: Any): Boolean {
if (evaluateCondition(o)) {
return if (affirmative != null) affirmative!!.evaluate(o) else true
} else {
return if (negative != null) negative!!.evaluate(o) else false
}
}
enum class Operator(val symbol: String) {
EQUALS("=="),
EXISTS("exists"),
LESS_THAN("<"),
GREATER_THAN(">"),
CONTAINS("contains");
override fun toString(): String {
return symbol
}
}
} | src/main/kotlin/com/willmadison/rules/Condition.kt | 2609468170 |
package com.github.deadleg.idea.openresty.lua
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.parameterInfo.CreateParameterInfoContext
import com.intellij.lang.parameterInfo.ParameterInfoContext
import com.intellij.lang.parameterInfo.ParameterInfoHandler
import com.intellij.lang.parameterInfo.ParameterInfoUIContext
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext
import com.intellij.psi.PsiElement
class NgxLuaParameterInfoHandler : ParameterInfoHandler<PsiElement, Any> {
override fun couldShowInLookup(): Boolean {
return true
}
override fun getParametersForLookup(item: LookupElement, context: ParameterInfoContext): Array<Any>? {
return null
}
override fun getParametersForDocumentation(p: Any, context: ParameterInfoContext): Array<Any>? {
return null
}
override fun findElementForParameterInfo(context: CreateParameterInfoContext): PsiElement? {
val offset = context.offset
// LuaFunctionCallExpression
return context.file.findElementAt(offset)?.parent?.parent
}
override fun showParameterInfo(element: PsiElement, context: CreateParameterInfoContext) {
// The lua plugin PSI elements have lua in its name
if (!element.javaClass.name.contains("Lua")) {
return
}
// Remove braces
val functionElement = if ("com.sylvanaar.idea.Lua.lang.psi.impl.lists.LuaExpressionListImpl" == element.javaClass.name) {
element.parent.parent
} else {
element
}
val function = if (functionElement.textContains('(')) {
functionElement.text.substring(0, functionElement.text.indexOf('('))
} else {
functionElement.text
}
val parameters = NgxLuaKeywords.getArgs(function) ?: return
context.itemsToShow = parameters.toTypedArray()
context.showHint(element, element.textRange.startOffset, this)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): PsiElement? {
return context.file.findElementAt(context.offset)?.parent?.parent
}
override fun updateParameterInfo(psiElement: PsiElement, context: UpdateParameterInfoContext) {
// The lua plugin PSI elements have lua in its name
if (!psiElement.javaClass.name.contains("Lua")) {
return
}
// Remove braces
val function = if (psiElement.textContains('(')) {
psiElement.text.substring(0, psiElement.text.indexOf('('))
} else {
// Case when getting info from just ngx.location.capture, not ngx.location.capture()
psiElement.text
}
val parameters = NgxLuaKeywords.getArgs(function) ?: return
// Traverse up the tree until we hit the parent that holds the children
var root = context.file.findElementAt(context.offset - 1) // Get element at start of cursor
for (i in 0..2) {
root = root?.parent
if (root == null) {
return
}
}
var numberOfArgs = root!!.children.size
if (numberOfArgs < 0) {
numberOfArgs = 0
} else if (numberOfArgs > parameters.size) {
return
}
context.highlightedParameter = parameters[numberOfArgs - 1]
}
override fun getParameterCloseChars(): String? {
return ",){}\t"
}
override fun tracksParameterIndex(): Boolean {
return true
}
override fun updateUI(p: Any, context: ParameterInfoUIContext) {
val highlightStartOffset = -1
val highlightEndOffset = -1
val buffer = StringBuilder()
if (p is PsiElement) {
buffer.append(p.text)
}
if (p is String) {
buffer.append(p)
}
context.setupUIComponentPresentation(
buffer.toString(),
highlightStartOffset,
highlightEndOffset,
!context.isUIComponentEnabled,
false,
false,
context.defaultParameterColor)
}
}
| src/com/github/deadleg/idea/openresty/lua/NgxLuaParameterInfoHandler.kt | 2199231938 |
package com.visiolink.app.task
import org.gradle.api.DefaultTask
open class VisiolinkGroupTask : DefaultTask() {
init {
group = "visiolink"
}
} | src/main/kotlin/com/visiolink/app/task/VisiolinkGroupTask.kt | 2202563623 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.datastore.preferences.rxjava3
import android.content.Context
import androidx.annotation.GuardedBy
import androidx.datastore.core.DataMigration
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.datastore.rxjava3.RxDataStore
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Creates a property delegate for a single process Preferences DataStore. This should only be
* called once in a file (at the top level), and all usages of the DataStore should use a
* reference the same Instance. The receiver type for the property delegate must be an instance
* of [Context].
*
* This should only be used from a single application in a single classloader in a single process.
*
* Example usage:
* ```
* val Context.myRxDataStore by rxPreferencesDataStore("filename", serializer)
*
* class SomeClass(val context: Context) {
* fun update(): Single<Preferences> = context.myRxDataStore.updateDataAsync {...}
* }
* ```
*
*
* @param name The name of the preferences. The preferences will be stored in a file in the
* "datastore/" subdirectory in the application context's files directory and is generated using
* [preferencesDataStoreFile].
* @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a
* [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions
* are thrown by serializers when data can not be de-serialized.
* @param produceMigrations produce the migrations. The ApplicationContext is passed in to these
* callbacks as a parameter. DataMigrations are run before any access to data can occur. Each
* producer and migration may be run more than once whether or not it already succeeded
* (potentially because another migration failed or a write to disk failed.)
* @param scheduler The scope in which IO operations and transform functions will execute.
*
* @return a property delegate that manages a datastore as a singleton.
*/
@Suppress("MissingJvmstatic")
public fun rxPreferencesDataStore(
name: String,
corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null,
produceMigrations: (Context) -> List<DataMigration<Preferences>> = { listOf() },
scheduler: Scheduler = Schedulers.io()
): ReadOnlyProperty<Context, RxDataStore<Preferences>> {
return RxDataStoreSingletonDelegate(name, corruptionHandler, produceMigrations, scheduler)
}
/**
* Delegate class to manage DataStore as a singleton.
*/
internal class RxDataStoreSingletonDelegate internal constructor(
private val fileName: String,
private val corruptionHandler: ReplaceFileCorruptionHandler<Preferences>?,
private val produceMigrations: (Context) -> List<DataMigration<Preferences>>,
private val scheduler: Scheduler
) : ReadOnlyProperty<Context, RxDataStore<Preferences>> {
private val lock = Any()
@GuardedBy("lock")
@Volatile
private var INSTANCE: RxDataStore<Preferences>? = null
/**
* Gets the instance of the DataStore.
*
* @param thisRef must be an instance of [Context]
* @param property not used
*/
override fun getValue(thisRef: Context, property: KProperty<*>): RxDataStore<Preferences> {
return INSTANCE ?: synchronized(lock) {
if (INSTANCE == null) {
val applicationContext = thisRef.applicationContext
INSTANCE = with(RxPreferenceDataStoreBuilder(applicationContext, fileName)) {
setIoScheduler(scheduler)
@Suppress("NewApi", "ClassVerificationFailure") // b/187418647
produceMigrations(applicationContext).forEach {
addDataMigration(it)
}
corruptionHandler?.let { setCorruptionHandler(it) }
build()
}
}
INSTANCE!!
}
}
} | datastore/datastore-preferences-rxjava3/src/main/java/androidx/datastore/preferences/rxjava3/RxPreferenceDataStoreDelegate.kt | 2066821978 |
/*
* 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.health.connect.client.records
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MealTypeTest {
@Test
fun enums_existInMapping() {
val allEnums = MealType::class.allObjectIntDefEnumsWithPrefix("MEAL_TYPE")
assertThat(MealType.MEAL_TYPE_STRING_TO_INT_MAP.values).containsExactlyElementsIn(allEnums)
assertThat(MealType.MEAL_TYPE_INT_TO_STRING_MAP.keys).containsExactlyElementsIn(allEnums)
}
}
| health/connect/connect-client/src/test/java/androidx/health/connect/client/records/MealTypeTest.kt | 754094771 |
package de.kleinelamas.svbrockscheid.model
import android.os.AsyncTask
import android.util.Log
import androidx.lifecycle.LiveData
import de.kleinelamas.svbrockscheid.SVBApp
import de.kleinelamas.svbrockscheid.connection.ApiClient
import retrofit2.Call
import javax.inject.Inject
/**
* @author Matthias Kutscheid
*/
class TeamLiveData : LiveData<TeamHolder>() {
init {
SVBApp.component.inject(this)
}
@Inject lateinit var apiClient: ApiClient
var task: AsyncTask<Void, Void, TeamHolder>? = null
override fun onActive() {
super.onActive()
refresh()
}
fun refresh() {
task = object : AsyncTask<Void, Void, TeamHolder>() {
override fun doInBackground(vararg p0: Void?): TeamHolder? {
//get all players
return handleTeam(apiClient.getTeam())
}
override fun onPostExecute(result: TeamHolder?) {
super.onPostExecute(result)
value = result
}
}
task?.execute()
}
private fun handleTeam(call: Call<HashMap<String, Array<Player>>>): TeamHolder? {
val response = call.execute()
Log.e("TAG", response.raw().body.toString())
response.body()?.let { return TeamHolder(it) }
return null
}
} | app/src/main/java/de/kleinelamas/svbrockscheid/model/TeamLiveData.kt | 4067366868 |
@file:Suppress("BlockingMethodInNonBlockingContext")
package com.sksamuel.scrimage.io
import com.sksamuel.scrimage.ImmutableImage
import com.sksamuel.scrimage.nio.TiffWriter
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class TiffWriterTest : FunSpec({
val original: ImmutableImage =
ImmutableImage.loader().fromStream(javaClass.getResourceAsStream("/picard.jpeg"))
.scaleTo(300, 200)
test("TIFF output happy path") {
val actual = ImmutableImage.loader().fromBytes(original.bytes(TiffWriter()))
val expected = ImmutableImage.loader().fromStream(javaClass.getResourceAsStream("/picard.tiff"))
expected.pixels().size shouldBe actual.pixels().size
expected shouldBe actual
}
test("TIFF output with compression") {
val actual = ImmutableImage.loader().fromBytes(original.bytes(TiffWriter().withCompressionType("ZLib")))
val expected = ImmutableImage.loader().fromStream(javaClass.getResourceAsStream("/picard_zlib.tiff"))
expected.pixels().size shouldBe actual.pixels().size
expected shouldBe actual
}
})
| scrimage-formats-extra/src/test/kotlin/com/sksamuel/scrimage/io/TiffWriterTest.kt | 3462751978 |
package com.twitter.meil_mitu.twitter4hk.converter
import com.squareup.okhttp.Response
import com.twitter.meil_mitu.twitter4hk.ResponseData
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
interface IPrivacyResultConverter<TPrivacyResult> : IJsonConverter {
@Throws(Twitter4HKException::class)
fun toPrivacyResultResponseData(res: Response): ResponseData<TPrivacyResult>
} | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/IPrivacyResultConverter.kt | 1823474516 |
package com.yechaoa.yutilskt
import android.util.Log
/**
* Created by yechao on 2020/1/7.
* Describe : 日志管理
*
* GitHub : https://github.com/yechaoa
* CSDN : http://blog.csdn.net/yechaoa
*/
object LogUtil {
private var TAG = "LogUtil"
private var IS_LOG = false
private const val MAX_LENGTH = 4000
/**
* 设置是否开启打印
*/
fun setIsLog(isLog: Boolean) {
IS_LOG = isLog
}
fun setIsLog(isLog: Boolean, tag: String) {
TAG = tag
IS_LOG = isLog
}
fun i(msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.i(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.i(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
fun i(tag: String?, msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.i(tag, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.i(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
fun d(msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.d(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.d(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
fun d(tag: String?, msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.d(tag, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.d(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
fun e(msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.e(TAG, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.e(TAG, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
fun e(tag: String?, msg: String) {
if (IS_LOG) {
val info = autoJumpLogInfos
val msgLength = msg.length
var start = 0
var end = MAX_LENGTH
for (i in 0..99) {
if (msgLength > end) {
Log.e(tag, info[1] + info[2] + " --->> " + msg.substring(start, end))
start = end
end += MAX_LENGTH
} else {
Log.e(tag, info[1] + info[2] + " --->> " + msg.substring(start, msgLength))
break
}
}
}
}
/**
* 获取打印信息所在方法名,行号等信息
*/
private val autoJumpLogInfos: Array<String>
get() {
val infos = arrayOf("", "", "")
val elements = Thread.currentThread().stackTrace
infos[0] = elements[4].className.substring(elements[4].className.lastIndexOf(".") + 1)
infos[1] = elements[4].methodName
infos[2] = "(" + elements[4].fileName + ":" + elements[4].lineNumber + ")"
return infos
}
} | yutilskt/src/main/java/com/yechaoa/yutilskt/LogUtil.kt | 3401261179 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.settings
import android.app.Fragment
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceFragment
import org.mozilla.focus.R
import org.mozilla.focus.search.SearchEngineManager
abstract class BaseSettingsFragment : PreferenceFragment() {
interface ActionBarUpdater {
fun updateTitle(titleResId: Int)
fun updateIcon(iconResId: Int)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (activity !is ActionBarUpdater) {
throw IllegalArgumentException("Parent activity must implement ActionBarUpdater")
}
}
protected fun getActionBarUpdater() = activity as ActionBarUpdater
protected fun getSearchEngineSharedPreferences(): SharedPreferences {
return activity.getSharedPreferences(SearchEngineManager.PREF_FILE_SEARCH_ENGINES, Context.MODE_PRIVATE)
}
protected fun navigateToFragment(fragment: Fragment) {
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit()
}
}
| app/src/main/java/org/mozilla/focus/settings/BaseSettingsFragment.kt | 1936983854 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.filters
import com.intellij.execution.filters.Filter
import org.rust.RsTestBase
class RsExplainFilterTest : RsTestBase() {
private val filter: Filter get() = RsExplainFilter()
fun `test old explain format`() {
val text = "src/lib.rs:57:17: 57:25 help: run `rustc --explain E0282` to see a detailed explanation"
doTest(text, text.length, 41, 56)
}
fun `test new explain format`() {
val text = "error: the trait bound `std::string::String: std::ops::Index<_>` is not satisfied [--explain E0277]"
doTest(text, text.length, 83, 98)
}
fun `test error format`() {
val text = "error[E0382]: use of moved value: `v`"
doTest(text, text.length, 5, 12)
}
fun `test warning format`() {
val text = "warning[E0122]: trait bounds are not (yet) enforced in type definitions"
doTest(text, text.length, 7, 14)
}
fun `test nothing to see`() {
val text = "src/lib.rs:57:17: 57:25 error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]"
check(filter.applyFilter(text, text.length) == null)
}
private fun doTest(line: String, entireLength: Int, highlightingStartOffset: Int, highlightingEndOffset: Int) {
val result = checkNotNull(filter.applyFilter(line, entireLength)) {
"No match in $line"
}
val item = result.resultItems.single()
check(item.highlightStartOffset == highlightingStartOffset)
check(item.highlightEndOffset == highlightingEndOffset)
check(item.getHyperlinkInfo() != null)
}
}
| src/test/kotlin/org/rust/cargo/runconfig/filters/RsExplainFilterTest.kt | 2157736114 |
package com.quijotelui.model
import org.hibernate.annotations.Immutable
import java.io.Serializable
import java.math.BigDecimal
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Immutable
@Table(name = "v_ele_guias_receptor_detalle")
class GuiaDestinatarioDetalle : Serializable {
@Id
@Column(name = "id")
var id : Long? = null
@Column(name = "codigo")
var codigo : String? = null
@Column(name = "numero")
var numero : String? = null
@Column(name = "documento")
var documento : String? = null
@Column(name = "codigo_articulo")
var codigoArticulo : String? = null
@Column(name = "nombre_articulo")
var nombreArticulo : String? = null
@Column(name = "cantidad")
var cantidad : BigDecimal? = null
} | src/main/kotlin/com/quijotelui/model/GuiaDestinatarioDetalle.kt | 4134517291 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.testutils
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.test.screenshot.ScreenshotTestRule
import androidx.test.screenshot.assertAgainstGolden
import androidx.test.screenshot.matchers.BitmapMatcher
import androidx.test.screenshot.matchers.MSSIMMatcher
/**
* Asserts this bitmap against the golden identified by the given name.
*
* Note: The golden identifier should be unique per your test module (unless you want multiple tests
* to match the same golden). The name must not contain extension. You should also avoid adding
* strings like "golden", "image" and instead describe what is the golder referring to.
*
* @param rule The screenshot test rule that provides the comparison and reporting.
* @param goldenIdentifier Name of the golden. Allowed characters: 'A-Za-z0-9_-'
* @param matcher The algorithm to be used to perform the matching. By default [MSSIMMatcher]
* is used.
*/
fun ImageBitmap.assertAgainstGolden(
rule: ScreenshotTestRule,
goldenIdentifier: String,
matcher: BitmapMatcher = MSSIMMatcher()
) = asAndroidBitmap().assertAgainstGolden(rule, goldenIdentifier, matcher) | compose/test-utils/src/androidMain/kotlin/androidx/compose/testutils/ScreenshotTestsUtils.android.kt | 2121134572 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.room.solver.types
import androidx.room.compiler.processing.XType
import androidx.room.solver.CodeGenScope
/**
* We have a special class for upcasting types in type converters. (e.g. Int to Number)
* It is used in the pathfinding to be more expensive than exactly matching calls to prioritize
* exact matches.
*/
class UpCastTypeConverter(
upCastFrom: XType,
upCastTo: XType
) : TypeConverter(
from = upCastFrom,
to = upCastTo,
cost = Cost.UP_CAST
) {
override fun doConvert(inputVarName: String, outputVarName: String, scope: CodeGenScope) {
scope.builder.addStatement("%L = %L", outputVarName, inputVarName)
}
override fun doConvert(inputVarName: String, scope: CodeGenScope): String {
// normally, we don't need to generate any code here but if the upcast is converting from
// a primitive to boxed; we need to. Otherwise, output value won't become an object and
// that might break the rest of the code generation (e.g. checking nullable on primitive)
return if (to.asTypeName().isBoxedPrimitive && from.asTypeName().isPrimitive) {
super.doConvert(inputVarName, scope)
} else {
inputVarName
}
}
} | room/room-compiler/src/main/kotlin/androidx/room/solver/types/UpCastTypeConverter.kt | 1363172418 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.javac
import androidx.room.compiler.processing.XNullability
import androidx.room.compiler.processing.javac.kotlin.KmType
internal val KmType.nullability: XNullability
get() = if (isNullable()) {
XNullability.NULLABLE
} else {
// if there is an upper bound information, use its nullability (e.g. it might be T : Foo?)
extendsBound?.nullability ?: XNullability.NONNULL
}
| room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/KmTypeExt.kt | 1839392242 |
package com.simplemobiletools.commons.asynctasks
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.ContentValues
import android.os.AsyncTask
import android.os.Handler
import android.provider.MediaStore
import androidx.core.app.NotificationCompat
import androidx.core.util.Pair
import androidx.documentfile.provider.DocumentFile
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.CONFLICT_KEEP_BOTH
import com.simplemobiletools.commons.helpers.CONFLICT_SKIP
import com.simplemobiletools.commons.helpers.getConflictResolution
import com.simplemobiletools.commons.helpers.isOreoPlus
import com.simplemobiletools.commons.interfaces.CopyMoveListener
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.lang.ref.WeakReference
class CopyMoveTask(
val activity: BaseSimpleActivity, val copyOnly: Boolean, val copyMediaOnly: Boolean, val conflictResolutions: LinkedHashMap<String, Int>,
listener: CopyMoveListener, val copyHidden: Boolean
) : AsyncTask<Pair<ArrayList<FileDirItem>, String>, Void, Boolean>() {
private val INITIAL_PROGRESS_DELAY = 3000L
private val PROGRESS_RECHECK_INTERVAL = 500L
private var mListener: WeakReference<CopyMoveListener>? = null
private var mTransferredFiles = ArrayList<FileDirItem>()
private var mFileDirItemsToDelete = ArrayList<FileDirItem>() // confirm the deletion of files on Android 11 from Downloads and Android at once
private var mDocuments = LinkedHashMap<String, DocumentFile?>()
private var mFiles = ArrayList<FileDirItem>()
private var mFileCountToCopy = 0
private var mDestinationPath = ""
// progress indication
private var mNotificationBuilder: NotificationCompat.Builder
private var mCurrFilename = ""
private var mCurrentProgress = 0L
private var mMaxSize = 0
private var mNotifId = 0
private var mIsTaskOver = false
private var mProgressHandler = Handler()
init {
mListener = WeakReference(listener)
mNotificationBuilder = NotificationCompat.Builder(activity)
}
override fun doInBackground(vararg params: Pair<ArrayList<FileDirItem>, String>): Boolean? {
if (params.isEmpty()) {
return false
}
val pair = params[0]
mFiles = pair.first!!
mDestinationPath = pair.second!!
mFileCountToCopy = mFiles.size
mNotifId = (System.currentTimeMillis() / 1000).toInt()
mMaxSize = 0
for (file in mFiles) {
if (file.size == 0L) {
file.size = file.getProperSize(activity, copyHidden)
}
val newPath = "$mDestinationPath/${file.name}"
val fileExists = activity.getDoesFilePathExist(newPath)
if (getConflictResolution(conflictResolutions, newPath) != CONFLICT_SKIP || !fileExists) {
mMaxSize += (file.size / 1000).toInt()
}
}
mProgressHandler.postDelayed({
initProgressNotification()
updateProgress()
}, INITIAL_PROGRESS_DELAY)
for (file in mFiles) {
try {
val newPath = "$mDestinationPath/${file.name}"
var newFileDirItem = FileDirItem(newPath, newPath.getFilenameFromPath(), file.isDirectory)
if (activity.getDoesFilePathExist(newPath)) {
val resolution = getConflictResolution(conflictResolutions, newPath)
if (resolution == CONFLICT_SKIP) {
mFileCountToCopy--
continue
} else if (resolution == CONFLICT_KEEP_BOTH) {
val newFile = activity.getAlternativeFile(File(newFileDirItem.path))
newFileDirItem = FileDirItem(newFile.path, newFile.name, newFile.isDirectory)
}
}
copy(file, newFileDirItem)
} catch (e: Exception) {
activity.showErrorToast(e)
return false
}
}
return true
}
override fun onPostExecute(success: Boolean) {
if (activity.isFinishing || activity.isDestroyed) {
return
}
deleteProtectedFiles()
mProgressHandler.removeCallbacksAndMessages(null)
activity.notificationManager.cancel(mNotifId)
val listener = mListener?.get() ?: return
if (success) {
listener.copySucceeded(copyOnly, mTransferredFiles.size >= mFileCountToCopy, mDestinationPath, mTransferredFiles.size == 1)
} else {
listener.copyFailed()
}
}
private fun initProgressNotification() {
val channelId = "Copy/Move"
val title = activity.getString(if (copyOnly) R.string.copying else R.string.moving)
if (isOreoPlus()) {
val importance = NotificationManager.IMPORTANCE_LOW
NotificationChannel(channelId, title, importance).apply {
enableLights(false)
enableVibration(false)
activity.notificationManager.createNotificationChannel(this)
}
}
mNotificationBuilder.setContentTitle(title)
.setSmallIcon(R.drawable.ic_copy_vector)
.setChannelId(channelId)
}
private fun updateProgress() {
if (mIsTaskOver) {
activity.notificationManager.cancel(mNotifId)
cancel(true)
return
}
mNotificationBuilder.apply {
setContentText(mCurrFilename)
setProgress(mMaxSize, (mCurrentProgress / 1000).toInt(), false)
activity.notificationManager.notify(mNotifId, build())
}
mProgressHandler.removeCallbacksAndMessages(null)
mProgressHandler.postDelayed({
updateProgress()
if (mCurrentProgress / 1000 >= mMaxSize) {
mIsTaskOver = true
}
}, PROGRESS_RECHECK_INTERVAL)
}
private fun copy(source: FileDirItem, destination: FileDirItem) {
if (source.isDirectory) {
copyDirectory(source, destination.path)
} else {
copyFile(source, destination)
}
}
private fun copyDirectory(source: FileDirItem, destinationPath: String) {
if (!activity.createDirectorySync(destinationPath)) {
val error = String.format(activity.getString(R.string.could_not_create_folder), destinationPath)
activity.showErrorToast(error)
return
}
if (activity.isPathOnOTG(source.path)) {
val children = activity.getDocumentFile(source.path)?.listFiles() ?: return
for (child in children) {
val newPath = "$destinationPath/${child.name}"
if (File(newPath).exists()) {
continue
}
val oldPath = "${source.path}/${child.name}"
val oldFileDirItem = FileDirItem(oldPath, child.name!!, child.isDirectory, 0, child.length())
val newFileDirItem = FileDirItem(newPath, child.name!!, child.isDirectory)
copy(oldFileDirItem, newFileDirItem)
}
mTransferredFiles.add(source)
} else if (activity.isRestrictedSAFOnlyRoot(source.path)) {
activity.getAndroidSAFFileItems(source.path, true) { files ->
for (child in files) {
val newPath = "$destinationPath/${child.name}"
if (activity.getDoesFilePathExist(newPath)) {
continue
}
val oldPath = "${source.path}/${child.name}"
val oldFileDirItem = FileDirItem(oldPath, child.name, child.isDirectory, 0, child.size)
val newFileDirItem = FileDirItem(newPath, child.name, child.isDirectory)
copy(oldFileDirItem, newFileDirItem)
}
mTransferredFiles.add(source)
}
} else if (activity.isAccessibleWithSAFSdk30(source.path)) {
val children = activity.getDocumentSdk30(source.path)?.listFiles() ?: return
for (child in children) {
val newPath = "$destinationPath/${child.name}"
if (File(newPath).exists()) {
continue
}
val oldPath = "${source.path}/${child.name}"
val oldFileDirItem = FileDirItem(oldPath, child.name!!, child.isDirectory, 0, child.length())
val newFileDirItem = FileDirItem(newPath, child.name!!, child.isDirectory)
copy(oldFileDirItem, newFileDirItem)
}
mTransferredFiles.add(source)
} else {
val children = File(source.path).list()
for (child in children) {
val newPath = "$destinationPath/$child"
if (activity.getDoesFilePathExist(newPath)) {
continue
}
val oldFile = File(source.path, child)
val oldFileDirItem = oldFile.toFileDirItem(activity)
val newFileDirItem = FileDirItem(newPath, newPath.getFilenameFromPath(), oldFile.isDirectory)
copy(oldFileDirItem, newFileDirItem)
}
mTransferredFiles.add(source)
}
}
private fun copyFile(source: FileDirItem, destination: FileDirItem) {
if (copyMediaOnly && !source.path.isMediaFile()) {
mCurrentProgress += source.size
return
}
val directory = destination.getParentPath()
if (!activity.createDirectorySync(directory)) {
val error = String.format(activity.getString(R.string.could_not_create_folder), directory)
activity.showErrorToast(error)
mCurrentProgress += source.size
return
}
mCurrFilename = source.name
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
if (!mDocuments.containsKey(directory) && activity.needsStupidWritePermissions(destination.path)) {
mDocuments[directory] = activity.getDocumentFile(directory)
}
out = activity.getFileOutputStreamSync(destination.path, source.path.getMimeType(), mDocuments[directory])
inputStream = activity.getFileInputStreamSync(source.path)!!
var copiedSize = 0L
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = inputStream.read(buffer)
while (bytes >= 0) {
out!!.write(buffer, 0, bytes)
copiedSize += bytes
mCurrentProgress += bytes
bytes = inputStream.read(buffer)
}
out?.flush()
if (source.size == copiedSize && activity.getDoesFilePathExist(destination.path)) {
mTransferredFiles.add(source)
if (copyOnly) {
activity.rescanPath(destination.path) {
if (activity.baseConfig.keepLastModified) {
updateLastModifiedValues(source, destination)
activity.rescanPath(destination.path)
}
}
} else if (activity.baseConfig.keepLastModified) {
updateLastModifiedValues(source, destination)
activity.rescanPath(destination.path)
inputStream.close()
out?.close()
deleteSourceFile(source)
} else {
inputStream.close()
out?.close()
deleteSourceFile(source)
}
}
} catch (e: Exception) {
activity.showErrorToast(e)
} finally {
inputStream?.close()
out?.close()
}
}
private fun updateLastModifiedValues(source: FileDirItem, destination: FileDirItem) {
copyOldLastModified(source.path, destination.path)
val lastModified = File(source.path).lastModified()
if (lastModified != 0L) {
File(destination.path).setLastModified(lastModified)
}
}
private fun deleteSourceFile(source: FileDirItem) {
if (activity.isRestrictedWithSAFSdk30(source.path) && !activity.canManageMedia()) {
mFileDirItemsToDelete.add(source)
} else {
activity.deleteFileBg(source, isDeletingMultipleFiles = false)
activity.deleteFromMediaStore(source.path)
}
}
// if we delete multiple files from Downloads folder on Android 11 or 12 without being a Media Management app, show the confirmation dialog just once
private fun deleteProtectedFiles() {
if (mFileDirItemsToDelete.isNotEmpty()) {
val fileUris = activity.getFileUrisFromFileDirItems(mFileDirItemsToDelete)
activity.deleteSDK30Uris(fileUris) { success ->
if (success) {
mFileDirItemsToDelete.forEach {
activity.deleteFromMediaStore(it.path)
}
}
}
}
}
private fun copyOldLastModified(sourcePath: String, destinationPath: String) {
val projection = arrayOf(
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATE_MODIFIED
)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${MediaStore.MediaColumns.DATA} = ?"
var selectionArgs = arrayOf(sourcePath)
val cursor = activity.applicationContext.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val dateTaken = cursor.getLongValue(MediaStore.Images.Media.DATE_TAKEN)
val dateModified = cursor.getIntValue(MediaStore.Images.Media.DATE_MODIFIED)
val values = ContentValues().apply {
put(MediaStore.Images.Media.DATE_TAKEN, dateTaken)
put(MediaStore.Images.Media.DATE_MODIFIED, dateModified)
}
selectionArgs = arrayOf(destinationPath)
activity.applicationContext.contentResolver.update(uri, values, selection, selectionArgs)
}
}
}
}
| commons/src/main/kotlin/com/simplemobiletools/commons/asynctasks/CopyMoveTask.kt | 4022627202 |
/*
* Copyright 2020 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.idea.perf.cvtracer
/**
* Statistics for CachedValue computations, usually grouped by the name of the
* class that created the CachedValue.
*/
interface CachedValueStats {
val description: String
val computeTimeNs: Long
val hits: Long // Number of times a value was reused, without recomputing it.
val misses: Long // Number of times a value had to be recomputed.
val hitRatio: Double get() = hits.toDouble() / maxOf(1L, hits + misses)
}
class MutableCachedValueStats(
override val description: String,
override var computeTimeNs: Long,
override var hits: Long,
override var misses: Long
): CachedValueStats
| src/main/java/com/google/idea/perf/cvtracer/CachedValueStats.kt | 3865403907 |
// Copyright 2021 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
//
// 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.google.android.libraries.car.trusteddevice.storage
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.IOException
import java.time.Clock
import org.junit.Test
import org.junit.runner.RunWith
private val DEFAULT_CAR_ID = "testId"
private val DEFAULT_HANDLE = "handle".toByteArray()
private val DEFAULT_TOKEN = "token".toByteArray()
private val CREDENTIALS_TABLE_NAME = "credentials"
private val UNLOCK_HISTORY_TABLE_NAME = "unlock_history"
@RunWith(AndroidJUnit4::class)
class DatabaseMigrationTest {
private val TEST_DB = "migration-test"
val helper: MigrationTestHelper =
MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
TrustedDeviceDatabase::class.java.canonicalName,
FrameworkSQLiteOpenHelperFactory()
)
@Test
@Throws(IOException::class)
fun testMigrate3To4() {
var database = helper.createDatabase(TEST_DB, 3)
var values = ContentValues()
values.put("carId", DEFAULT_CAR_ID)
values.put("token", DEFAULT_HANDLE)
values.put("handle", DEFAULT_TOKEN)
database.insert(CREDENTIALS_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values)
val now = Clock.systemUTC().instant()
values = ContentValues()
values.put("carId", DEFAULT_CAR_ID)
values.put("instant", now.getNano())
database.insert(UNLOCK_HISTORY_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values)
database.close()
database = helper.runMigrationsAndValidate(TEST_DB, 4, true, DatabaseProvider.DB_MIGRATION_3_4)
database.close()
}
}
| trusteddevice/tests/unit/src/com/google/android/libraries/car/trusteddevice/storage/DatabaseMigrationTest.kt | 3959912477 |
package nl.mpcjanssen.simpletask
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.mobeta.android.dslv.DragSortListView
import nl.mpcjanssen.simpletask.util.Config
import java.util.*
import kotlin.collections.ArrayList
class FilterSortFragment : Fragment() {
private var originalItems: ArrayList<String>? = null
private var lv: DragSortListView? = null
internal lateinit var adapter: SortItemAdapter
internal var directions = ArrayList<String>()
internal var adapterList = ArrayList<String>()
internal var sortUpId: Int = 0
internal var sortDownId: Int = 0
internal lateinit var m_app: TodoApplication
private val onDrop = DragSortListView.DropListener { from, to ->
if (from != to) {
val item = adapter.getItem(from)
adapter.remove(item)
adapter.insert(item, to)
val sortItem = directions[from]
directions.removeAt(from)
directions.add(to, sortItem)
}
}
private val onRemove = DragSortListView.RemoveListener { which -> adapter.remove(adapter.getItem(which)) }
private // this DSLV xml declaration does not call for the use
// of the default DragSortController; therefore,
// DSLVFragment has a buildController() method.
val layout: Int
get() = R.layout.simple_list_item_single_choice
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val arguments = arguments
if (originalItems == null) {
if (savedInstanceState != null) {
originalItems = savedInstanceState.getStringArrayList(STATE_SELECTED)
} else {
originalItems = arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS)?: ArrayList()
}
}
Log.d(TAG, "Created view with: " + originalItems)
m_app = TodoApplication.app
// Set the proper theme
if (Config.isDarkTheme || Config.isBlackTheme) {
sortDownId = R.drawable.ic_action_sort_down_dark
sortUpId = R.drawable.ic_action_sort_up_dark
} else {
sortDownId = R.drawable.ic_action_sort_down
sortUpId = R.drawable.ic_action_sort_up
}
adapterList.clear()
val layout: LinearLayout
layout = inflater.inflate(R.layout.single_filter,
container, false) as LinearLayout
val keys = resources.getStringArray(R.array.sortKeys)
for (item in originalItems!!) {
val parts = item.split("!".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val sortType: String
var sortDirection: String
if (parts.size == 1) {
sortType = parts[0]
sortDirection = Query.NORMAL_SORT
} else {
sortDirection = parts[0]
sortType = parts[1]
if (sortDirection.isEmpty() || sortDirection != Query.REVERSED_SORT) {
sortDirection = Query.NORMAL_SORT
}
}
val index = Arrays.asList(*keys).indexOf(sortType)
if (index != -1) {
adapterList.add(sortType)
directions.add(sortDirection)
keys[index] = null
}
}
// Add sorts not already in the sortlist
for (item in keys) {
if (item != null) {
adapterList.add(item)
directions.add(Query.NORMAL_SORT)
}
}
lv = layout.findViewById(R.id.dslistview) as DragSortListView
lv!!.setDropListener(onDrop)
lv!!.setRemoveListener(onRemove)
adapter = SortItemAdapter(activity, R.layout.sort_list_item, R.id.text, adapterList)
lv!!.adapter = adapter
lv!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
var direction = directions[position]
if (direction == Query.REVERSED_SORT) {
direction = Query.NORMAL_SORT
} else {
direction = Query.REVERSED_SORT
}
directions.removeAt(position)
directions.add(position, direction)
adapter.notifyDataSetChanged()
}
return layout
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putStringArrayList(STATE_SELECTED, selectedItem)
}
override fun onDestroyView() {
originalItems = selectedItem
super.onDestroyView()
}
val selectedItem: ArrayList<String>
get() {
val multiSort = ArrayList<String>()
if (lv != null) {
for (i in 0..adapter.count - 1) {
multiSort.add(directions[i] + Query.SORT_SEPARATOR + adapter.getSortType(i))
}
} else if (originalItems != null) {
multiSort.addAll(originalItems as ArrayList<String>)
} else {
multiSort.addAll(arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS) ?: java.util.ArrayList())
}
return multiSort
}
inner class SortItemAdapter(context: Context?, resource: Int, textViewResourceId: Int, objects: List<String>) : ArrayAdapter<String>(context, resource, textViewResourceId, objects) {
private val names: Array<String>
init {
names = resources.getStringArray(R.array.sort)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val row = super.getView(position, convertView, parent)
val reverseButton = row.findViewById(R.id.reverse_button) as ImageButton
val label = row.findViewById(R.id.text) as TextView
label.text = Config.getSortString(adapterList[position])
if (directions[position] == Query.REVERSED_SORT) {
reverseButton.setBackgroundResource(sortUpId)
} else {
reverseButton.setBackgroundResource(sortDownId)
}
return row
}
fun getSortType(position: Int): String {
return adapterList[position]
}
}
companion object {
private val STATE_SELECTED = "selectedItem"
internal val TAG = FilterActivity::class.java.simpleName
}
}
| app/src/main/java/nl/mpcjanssen/simpletask/FilterSortFragment.kt | 2795988266 |
package com.adgvcxz.diycode.binding.recycler
import com.adgvcxz.diycode.binding.base.BaseViewModel
/**
* zhaowei
* Created by zhaowei on 2017/2/27.
*/
interface OnRecyclerViewItemClickListener<in T: BaseViewModel> {
fun OnClick(t: T)
} | app/src/main/java/com/adgvcxz/diycode/binding/recycler/OnRecyclerViewItemClickListener.kt | 2844730126 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* 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.tang.intellij.lua.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.tree.IElementType
import com.tang.intellij.lua.psi.LuaExpr
import com.tang.intellij.lua.stubs.LuaExprStubImpl
/**
* 表达式基类
* Created by TangZX on 2016/12/4.
*/
abstract class LuaExprMixin : LuaExprStubMixin<LuaExprStubImpl<*>>, LuaExpr {
constructor(stub: LuaExprStubImpl<*>, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
constructor(node: ASTNode) : super(node)
constructor(stub: LuaExprStubImpl<*>, nodeType: IElementType, node: ASTNode) : super(stub, nodeType, node)
}
| src/main/java/com/tang/intellij/lua/psi/impl/LuaExprMixin.kt | 2096898965 |
package rm.com.audiowave
import android.os.Handler
import android.os.Looper
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Created by alex
*/
internal val MAIN_THREAD = Handler(Looper.getMainLooper())
internal val SAMPLER_THREAD: ExecutorService = Executors.newSingleThreadExecutor()
object Sampler {
fun downSampleAsync(data: ByteArray, targetSize: Int, answer: (ByteArray) -> Unit) {
SAMPLER_THREAD.submit {
val scaled = downSample(data, targetSize)
MAIN_THREAD.post {
answer(scaled)
}
}
}
fun downSample(data: ByteArray, targetSize: Int): ByteArray {
val targetSized = ByteArray(targetSize)
val chunkSize = data.size / targetSize
val chunkStep = Math.max(Math.floor((chunkSize / 10.0)), 1.0).toInt()
var prevDataIndex = 0
var sampledPerChunk = 0F
var sumPerChunk = 0F
if (targetSize >= data.size) {
return targetSized.paste(data)
}
for (index in 0..data.size step chunkStep) {
val currentDataIndex = (targetSize * index.toLong() / data.size).toInt()
if (prevDataIndex == currentDataIndex) {
sampledPerChunk += 1
sumPerChunk += data[index].abs
} else {
targetSized[prevDataIndex] = (sumPerChunk / sampledPerChunk).toByte()
sumPerChunk = 0F
sampledPerChunk = 0F
prevDataIndex = currentDataIndex
}
}
return targetSized
}
}
internal val Byte.abs: Byte
get() = when (this) {
Byte.MIN_VALUE -> Byte.MAX_VALUE
in (Byte.MIN_VALUE + 1..0) -> (-this).toByte()
else -> this
}
internal fun ByteArray.paste(other: ByteArray): ByteArray {
if (size == 0) return byteArrayOf()
return this.apply {
forEachIndexed { i, _ ->
this[i] = other.getOrElse(i, { this[i].abs })
}
}
}
| audiowave/src/main/kotlin/rm/com/audiowave/Sampler.kt | 3378709555 |
package de.pbauerochse.worklogviewer.fx.components.tabs
import de.pbauerochse.worklogviewer.fx.components.statistics.data.TaskCountByProjectAndUserStatisticData
import de.pbauerochse.worklogviewer.fx.components.statistics.data.TaskCountByUserAndProjectStatisticData
import de.pbauerochse.worklogviewer.fx.components.statistics.panels.TaskCountByUserAndProjectStatistics
import de.pbauerochse.worklogviewer.fx.components.statistics.panels.TimeByGroupingCriteriaChart
import de.pbauerochse.worklogviewer.fx.components.statistics.panels.TimePerProjectAndUserGraphStatistics
import de.pbauerochse.worklogviewer.fx.components.statistics.panels.TimePerUserAndProjectGraphStatistics
import de.pbauerochse.worklogviewer.timereport.view.ReportView
import javafx.scene.Node
/**
* Tab, that displays the results for a single Project
* independent of the work author
*/
internal class ProjectWorklogTab : WorklogsTab("") {
override fun getStatistics(reportView: ReportView): List<Node> {
val dataByUser = TaskCountByUserAndProjectStatisticData(reportView.issues)
val dataByProject = TaskCountByProjectAndUserStatisticData(reportView.issues)
return listOfNotNull(
reportView.appliedGrouping?.let { TimeByGroupingCriteriaChart(reportView) },
TaskCountByUserAndProjectStatistics(dataByUser),
TimePerProjectAndUserGraphStatistics(dataByUser),
TimePerUserAndProjectGraphStatistics(dataByProject)
)
}
}
| application/src/main/java/de/pbauerochse/worklogviewer/fx/components/tabs/ProjectWorklogTab.kt | 2574546282 |
package com.marcinmoskala.model
interface SkillBase: Connector {
override val visibleName: String
override val linkTo: String?
val description: String?
} | src/main/kotlin/com/marcinmoskala/model/SkillBase.kt | 959893521 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.ConditionsGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.BLOCKER, tags = [Tags.BUG])
@ConstantRemediation("2min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class IdenticalExpressionCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.COMPARISON_EXPRESSION)
}
override fun visitNode(node: AstNode) {
val operator = node.getFirstChildOrNull(ConditionsGrammar.RELATIONAL_OPERATOR)
if (operator != null) {
val leftSide = node.firstChild
val rightSide = node.lastChild
if (CheckUtils.equalNodes(leftSide, rightSide)) {
addIssue(leftSide, getLocalizedMessage(), operator.tokenValue)
.secondary(rightSide, "Original")
}
}
}
}
| zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/IdenticalExpressionCheck.kt | 1899448920 |
package net.ebt.muzei.miyazaki.load
import android.content.Context
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.ProviderContract
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.ebt.muzei.miyazaki.common.BuildConfig.GHIBLI_AUTHORITY
import net.ebt.muzei.miyazaki.database.ArtworkDatabase
class UpdateMuzeiWorker(
context: Context,
workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
companion object {
private const val CURRENT_PREF_NAME = "MuzeiGhibli.current"
private const val SELECTED_COLOR = "muzei_color"
fun toggleColor(context: Context, color: String) {
val sharedPreferences = context.getSharedPreferences(
CURRENT_PREF_NAME, Context.MODE_PRIVATE)
val currentColor = sharedPreferences.getString(SELECTED_COLOR, null)
sharedPreferences.edit {
if (color == currentColor) {
remove(SELECTED_COLOR)
} else {
putString(SELECTED_COLOR, color)
}
}
enqueueUpdate(context)
}
fun getCurrentColor(context: Context): String? {
val sharedPreferences = context.getSharedPreferences(
CURRENT_PREF_NAME, Context.MODE_PRIVATE)
return sharedPreferences.getString(SELECTED_COLOR, null)
}
private fun enqueueUpdate(context: Context) {
val workManager = WorkManager.getInstance(context)
workManager.enqueueUniqueWork("load", ExistingWorkPolicy.APPEND,
OneTimeWorkRequestBuilder<UpdateMuzeiWorker>()
.build())
}
}
override suspend fun doWork(): Result {
val sharedPreferences = applicationContext.getSharedPreferences(
CURRENT_PREF_NAME, Context.MODE_PRIVATE)
val artworkList = ArtworkDatabase.getInstance(applicationContext)
.artworkDao()
.getArtwork(sharedPreferences.getString(SELECTED_COLOR, ""))
withContext(Dispatchers.IO) {
val providerClient = ProviderContract.getProviderClient(
applicationContext, GHIBLI_AUTHORITY)
providerClient.setArtwork(artworkList.shuffled().map { artwork ->
Artwork.Builder()
.token(artwork.hash)
.persistentUri(artwork.url.toUri())
.title(artwork.caption)
.byline(artwork.subtitle)
.build()
})
}
return Result.success()
}
}
| android-common/src/main/java/net/ebt/muzei/miyazaki/load/UpdateMuzeiWorker.kt | 3713285697 |
package com.rhm.pwn.home_feature
import com.badoo.mvicore.element.Actor
import com.badoo.mvicore.element.Reducer
import com.badoo.mvicore.feature.ActorReducerFeature
import com.rhm.pwn.home_feature.HomeFeatureOld.Wish
import com.rhm.pwn.home_feature.HomeFeatureOld.Effect
import com.rhm.pwn.home_feature.HomeFeatureOld.State
import com.rhm.pwn.model.URLCheck
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
class HomeFeatureOld : ActorReducerFeature<Wish, Effect, State, Nothing>(
initialState = State(),
actor = ActorImpl(),
reducer = ReducerImpl()
) {
data class State(
val isLoading: Boolean = false,
val editShown: Boolean = false,
val editUrlCheck: URLCheck? = null,
val list: List<URLCheck> = emptyList())
sealed class Wish {
object HomeScreenLoading : Wish()
data class HomeScreenView(val urlCheck: URLCheck)
data class HomeScreenEditOpen(val urlCheck: URLCheck)
object HomeScreenEditCancel : Wish()
data class HomeScreenEditSave(val urlCheck: URLCheck)
data class HomeScreenEditDelete(val urlCheck: URLCheck)
data class HomeScreenEditSelect(val urlCheck: URLCheck)
}
sealed class Effect {
object StartedLoading : Effect()
data class FinishedWithSuccess(val urlChecks: List<URLCheck>) : Effect()
data class FinishedWithFailure(val throwable: Throwable) : Effect()
}
class ActorImpl : Actor<State, Wish, Effect> {
private val service: Observable<List<URLCheck>> = TODO()
override fun invoke(state: State, wish: Wish): Observable<Effect> = when (wish) {
is Wish.HomeScreenLoading -> {
if (!state.isLoading) {
service
.observeOn(AndroidSchedulers.mainThread())
.map { Effect.FinishedWithSuccess(urlChecks = it) as Effect }
.startWith(Effect.StartedLoading)
.onErrorReturn { Effect.FinishedWithFailure(it) }
} else {
Observable.empty()
}
}
else -> Observable.empty()
}
}
class ReducerImpl : Reducer<State, Effect> {
override fun invoke(state: State, effect: Effect): State = when (effect) {
is Effect.StartedLoading -> state.copy(
isLoading = true
)
is Effect.FinishedWithSuccess -> state.copy(
isLoading = false,
list = effect.urlChecks
)
is Effect.FinishedWithFailure -> state.copy(
isLoading = false
)
}
}
} | app/src/main/java/com/rhm/pwn/home_feature/HomeFeatureOld.kt | 2513840355 |
package org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.serial.JsonConfig
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.toFileSafeString
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.stripNewlines
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.ScrambleDrawingData
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.Competition
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.ZipInterchangeInfo
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.Folder
import java.time.LocalDateTime
data class InterchangeFolder(val wcif: Competition, val uniqueTitles: Map<String, ScrambleDrawingData>, val globalTitle: String) {
fun assemble(generationDate: LocalDateTime, versionTag: String, generationUrl: String?): Folder {
val safeGlobalTitle = globalTitle.toFileSafeString()
val jsonInterchangeData = ZipInterchangeInfo(globalTitle, versionTag, generationDate, generationUrl, wcif)
val jsonStr = JsonConfig.SERIALIZER.encodeToString(ZipInterchangeInfo.serializer(), jsonInterchangeData)
val jsonpFileName = "$safeGlobalTitle.jsonp"
val jsonpStr = "var SCRAMBLES_JSON = $jsonStr;"
val viewerResource = this::class.java.getResourceAsStream(HTML_SCRAMBLE_VIEWER).bufferedReader().readText()
.replace("%SCRAMBLES_JSONP_FILENAME%", jsonpFileName)
return folder("Interchange") {
folder("txt") {
for ((uniqueTitle, scrambleRequest) in uniqueTitles) {
val scrambleLines = scrambleRequest.scrambleSet.allScrambles.flatMap { it.allScrambleStrings }
val txtScrambles = scrambleLines.stripNewlines().joinToString("\r\n")
file("$uniqueTitle.txt", txtScrambles)
}
}
file("$safeGlobalTitle.json", jsonStr)
file(jsonpFileName, jsonpStr)
file("$safeGlobalTitle.html", viewerResource)
}
}
companion object {
private const val HTML_SCRAMBLE_VIEWER = "/wca/scrambleviewer.html"
}
}
| webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/zip/folder/InterchangeFolder.kt | 569567549 |
package assimp.postProcess
import assimp.AiMesh
import assimp.AiPrimitiveType
import assimp.or
import glm_.glm
import glm_.vec3.Vec3
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.StringSpec
import kotlin.math.cos
import kotlin.math.sin
class TriangulateTest : StringSpec() {
init {
val count = 1000
val piProcess = TriangulateProcess()
val mesh = AiMesh().apply {
numFaces = count
faces = MutableList(count) { mutableListOf<Int>() }
vertices = MutableList(count * 10) { Vec3() }
primitiveTypes = AiPrimitiveType.POINT or AiPrimitiveType.LINE or AiPrimitiveType.LINE or AiPrimitiveType.POLYGON
}
run {
var m = 0
var t = 0
var q = 4
while (m < count) {
++t
val face = mesh.faces[m]
var numIndices = t
if (4 == t) {
numIndices = q++
t = 0
if (10 == q) q = 4
}
for (i in 0 until numIndices)
face += 0
for (p in 0 until numIndices) {
face[p] = mesh.numVertices
// construct fully convex input data in ccw winding, xy plane
mesh.vertices[mesh.numVertices++](
cos(p * glm.PI2f / numIndices),
sin(p * glm.PI2f / numIndices), 0f)
}
++m
}
}
"triangulate process test" {
piProcess.triangulateMesh(mesh)
var m = 0
var t = 0
var q = 4
var max = count
var idx = 0
while (m < max) {
++t
val face = mesh.faces[m]
if (4 == t) {
t = 0
max += q - 3
val ait = BooleanArray(q)
var i = 0
val tt = q - 2
while (i < tt) {
val f = mesh.faces[m]
f.size shouldBe 3
for (qqq in 0 until f.size)
ait[f[qqq] - idx] = true
++i
++m
}
ait.forEach { it shouldBe true }
--m
idx += q
if (++q == 10)
q = 4
} else {
face.size shouldBe t
for (i in face.indices)
face[i] shouldBe idx++
}
++m
}
// we should have no valid normal vectors now necause we aren't a pure polygon mesh
mesh.normals.isEmpty() shouldBe true
}
}
} | src/test/kotlin/assimp/postProcess/Triangulate Test.kt | 1914010952 |
package org.koin.koincomponent
import org.koin.Simple
import org.koin.core.Koin
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.assertHasNoStandaloneInstance
import kotlin.native.concurrent.ThreadLocal
import kotlin.test.Test
import kotlin.test.assertEquals
abstract class CustomKoinComponent : KoinComponent {
override fun getKoin(): Koin = customKoin
@ThreadLocal
companion object {
val customKoin = koinApplication {
modules(module {
single { Simple.ComponentA() }
})
}.koin
}
}
class MyCustomApp : CustomKoinComponent() {
val a: Simple.ComponentA by inject()
}
class CustomKoinComponentTest {
@Test
fun can_inject_KoinComponent_from_custom_instance() {
val app = MyCustomApp()
val a = CustomKoinComponent.customKoin.get<Simple.ComponentA>()
assertEquals(app.a, a)
assertHasNoStandaloneInstance()
}
} | core/koin-core/src/commonTest/kotlin/org/koin/koincomponent/CustomKoinComponentTest.kt | 3662545059 |
package eu.kanade.tachiyomi.ui.manga
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.graphics.drawable.VectorDrawableCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.support.RouterPagerAdapter
import com.jakewharton.rxrelay.BehaviorRelay
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.base.controller.RxController
import eu.kanade.tachiyomi.ui.base.controller.TabbedController
import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe
import eu.kanade.tachiyomi.ui.catalogue.CatalogueController
import eu.kanade.tachiyomi.ui.manga.chapter.ChaptersController
import eu.kanade.tachiyomi.ui.manga.chapter.ChaptersPresenter
import eu.kanade.tachiyomi.ui.manga.info.MangaInfoController
import eu.kanade.tachiyomi.ui.manga.track.TrackController
import eu.kanade.tachiyomi.util.toast
import kotlinx.android.synthetic.main.main_activity.*
import kotlinx.android.synthetic.main.manga_controller.*
import rx.Subscription
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Date
class MangaController : RxController, TabbedController {
constructor(manga: Manga?,
fromCatalogue: Boolean = false,
smartSearchConfig: CatalogueController.SmartSearchConfig? = null,
update: Boolean = false) : super(Bundle().apply {
putLong(MANGA_EXTRA, manga?.id ?: 0)
putBoolean(FROM_CATALOGUE_EXTRA, fromCatalogue)
putParcelable(SMART_SEARCH_CONFIG_EXTRA, smartSearchConfig)
putBoolean(UPDATE_EXTRA, update)
}) {
this.manga = manga
if (manga != null) {
source = Injekt.get<SourceManager>().getOrStub(manga.source)
}
}
// EXH -->
constructor(redirect: ChaptersPresenter.EXHRedirect) : super(Bundle().apply {
putLong(MANGA_EXTRA, redirect.manga.id!!)
putBoolean(UPDATE_EXTRA, redirect.update)
}) {
this.manga = redirect.manga
if (manga != null) {
source = Injekt.get<SourceManager>().getOrStub(redirect.manga.source)
}
}
// EXH <--
constructor(mangaId: Long) : this(
Injekt.get<DatabaseHelper>().getManga(mangaId).executeAsBlocking())
@Suppress("unused")
constructor(bundle: Bundle) : this(bundle.getLong(MANGA_EXTRA))
var manga: Manga? = null
private set
var source: Source? = null
private set
private var adapter: MangaDetailAdapter? = null
val fromCatalogue = args.getBoolean(FROM_CATALOGUE_EXTRA, false)
var update = args.getBoolean(UPDATE_EXTRA, false)
// EXH -->
val smartSearchConfig: CatalogueController.SmartSearchConfig? = args.getParcelable(SMART_SEARCH_CONFIG_EXTRA)
// EXH <--
val lastUpdateRelay: BehaviorRelay<Date> = BehaviorRelay.create()
val chapterCountRelay: BehaviorRelay<Float> = BehaviorRelay.create()
val mangaFavoriteRelay: PublishRelay<Boolean> = PublishRelay.create()
private val trackingIconRelay: BehaviorRelay<Boolean> = BehaviorRelay.create()
private var trackingIconSubscription: Subscription? = null
override fun getTitle(): String? {
return manga?.title
}
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.manga_controller, container, false)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
if (manga == null || source == null) return
requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 301)
adapter = MangaDetailAdapter()
manga_pager.offscreenPageLimit = 3
manga_pager.adapter = adapter
if (!fromCatalogue)
manga_pager.currentItem = CHAPTERS_CONTROLLER
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
adapter = null
}
override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) {
super.onChangeStarted(handler, type)
if (type.isEnter) {
activity?.tabs?.setupWithViewPager(manga_pager)
trackingIconSubscription = trackingIconRelay.subscribe { setTrackingIconInternal(it) }
}
}
override fun onChangeEnded(handler: ControllerChangeHandler, type: ControllerChangeType) {
super.onChangeEnded(handler, type)
if (manga == null || source == null) {
activity?.toast(R.string.manga_not_in_db)
router.popController(this)
}
}
override fun configureTabs(tabs: TabLayout) {
with(tabs) {
tabGravity = TabLayout.GRAVITY_FILL
tabMode = TabLayout.MODE_FIXED
}
}
override fun cleanupTabs(tabs: TabLayout) {
trackingIconSubscription?.unsubscribe()
setTrackingIconInternal(false)
}
fun setTrackingIcon(visible: Boolean) {
trackingIconRelay.call(visible)
}
private fun setTrackingIconInternal(visible: Boolean) {
val tab = activity?.tabs?.getTabAt(TRACK_CONTROLLER) ?: return
val drawable = if (visible)
VectorDrawableCompat.create(resources!!, R.drawable.ic_done_white_18dp, null)
else null
val view = tabField.get(tab) as LinearLayout
val textView = view.getChildAt(1) as TextView
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
textView.compoundDrawablePadding = if (visible) 4 else 0
}
private inner class MangaDetailAdapter : RouterPagerAdapter(this@MangaController) {
private val tabCount = if (Injekt.get<TrackManager>().hasLoggedServices()) 3 else 2
private val tabTitles = listOf(
R.string.manga_detail_tab,
R.string.manga_chapters_tab,
R.string.manga_tracking_tab)
.map { resources!!.getString(it) }
override fun getCount(): Int {
return tabCount
}
override fun configureRouter(router: Router, position: Int) {
if (!router.hasRootController()) {
val controller = when (position) {
INFO_CONTROLLER -> MangaInfoController()
CHAPTERS_CONTROLLER -> ChaptersController()
TRACK_CONTROLLER -> TrackController()
else -> error("Wrong position $position")
}
router.setRoot(RouterTransaction.with(controller))
}
}
override fun getPageTitle(position: Int): CharSequence {
return tabTitles[position]
}
}
companion object {
// EXH -->
const val UPDATE_EXTRA = "update"
const val SMART_SEARCH_CONFIG_EXTRA = "smartSearchConfig"
// EXH <--
const val FROM_CATALOGUE_EXTRA = "from_catalogue"
const val MANGA_EXTRA = "manga"
const val INFO_CONTROLLER = 0
const val CHAPTERS_CONTROLLER = 1
const val TRACK_CONTROLLER = 2
private val tabField = TabLayout.Tab::class.java.getDeclaredField("view")
.apply { isAccessible = true }
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaController.kt | 2322228615 |
package com.mindera.skeletoid.routing.unfreeze
import android.content.Context
import android.content.Intent
import com.mindera.skeletoid.utils.extensions.mock
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito.verify
class OpenUnfreezeScreenCommandTest {
@Test
fun testNavigate() {
val context = mock<Context>()
val command = OpenUnfreezeScreenCommand(context)
command.navigate()
verify(context).startActivity(ArgumentMatchers.any(Intent::class.java))
}
} | base/src/test/java/com/mindera/skeletoid/routing/unfreeze/OpenUnfreezeScreenCommandTest.kt | 1380248161 |
/*
* WayPoint.kt
* Implements the WayPoint data class
* A WayPoint stores a location plus additional metadata
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook.core
import android.location.Location
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.Expose
import kotlinx.parcelize.Parcelize
import org.y20k.trackbook.helpers.LocationHelper
/*
* WayPoint data class
*/
@Keep
@Parcelize
data class WayPoint(@Expose val provider: String,
@Expose val latitude: Double,
@Expose val longitude: Double,
@Expose val altitude: Double,
@Expose val accuracy: Float,
@Expose val time: Long,
@Expose val distanceToStartingPoint: Float = 0f,
@Expose val numberSatellites: Int = 0,
@Expose var isStopOver: Boolean = false,
@Expose var starred: Boolean = false): Parcelable {
/* Constructor using just Location */
constructor(location: Location) : this (location.provider, location.latitude, location.longitude, location. altitude, location.accuracy, location.time)
/* Constructor using Location plus distanceToStartingPoint and numberSatellites */
constructor(location: Location, distanceToStartingPoint: Float) : this (location.provider, location.latitude, location.longitude, location. altitude, location.accuracy, location.time, distanceToStartingPoint, LocationHelper.getNumberOfSatellites(location))
/* Converts WayPoint into Location */
fun toLocation(): Location {
val location: Location = Location(provider)
location.latitude = latitude
location.longitude = longitude
location.altitude = altitude
location.accuracy = accuracy
location.time = time
return location
}
}
| app/src/main/java/org/y20k/trackbook/core/WayPoint.kt | 3084142385 |
package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.shared.logging.LTag
import javax.inject.Inject
/**
* InjectionSnackSettingResponsePacket
*/
class InjectionSnackSettingResponsePacket(
injector: HasAndroidInjector
) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
var result = 0
init {
msgType = 0x87.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket init ")
}
override fun handleMessage(data: ByteArray?) {
val defectCheck = defect(data)
if (defectCheck != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
result = getByteToInt(bufferData)
if(!isSuccSettingResponseResult(result)) {
diaconnG8Pump.resultErrorCode = result
failed = true
return
}
diaconnG8Pump.otpNumber = getIntToInt(bufferData)
aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result")
aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}")
}
override fun getFriendlyName(): String {
return "PUMP_INJECTION_SNACK_SETTING_RESPONSE"
}
} | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt | 1699245321 |
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan
import android.bluetooth.le.ScanRecord
import android.bluetooth.le.ScanResult
import android.os.ParcelUuid
class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: ScanRecord, private val podId: Long) {
private val sequenceNo: Int
private val lotNo: Long
@Throws(DiscoveredInvalidPodException::class)
private fun validateServiceUUIDs() {
val serviceUuids = scanRecord.serviceUuids
if (serviceUuids.size != 9) {
throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUuids.size, serviceUuids)
}
if (extractUUID16(serviceUuids[0]) != MAIN_SERVICE_UUID) {
// this is the service that we filtered for
throw DiscoveredInvalidPodException(
"The first exposed service UUID should be 4024, got " + extractUUID16(
serviceUuids[0]
),
serviceUuids
)
}
// TODO understand what is serviceUUIDs[1]. 0x2470. Alarms?
if (extractUUID16(serviceUuids[2]) != UNKNOWN_THIRD_SERVICE_UUID) {
// constant?
throw DiscoveredInvalidPodException(
"The third exposed service UUID should be 000a, got " + serviceUuids[2],
serviceUuids
)
}
}
@Throws(DiscoveredInvalidPodException::class)
private fun validatePodId() {
val serviceUUIDs = scanRecord.serviceUuids
val hexPodId = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4])
val podId = hexPodId.toLong(16)
if (this.podId != podId) {
throw DiscoveredInvalidPodException(
"This is not the POD we are looking for: ${this.podId} . Found: $podId/$hexPodId",
serviceUUIDs
)
}
}
private fun parseLotNo(): Long {
val serviceUUIDs = scanRecord.serviceUuids
val lotSeq = extractUUID16(serviceUUIDs[5]) +
extractUUID16(serviceUUIDs[6]) +
extractUUID16(serviceUUIDs[7])
return lotSeq.substring(0, 10).toLong(16)
}
private fun parseSeqNo(): Int {
val serviceUUIDs = scanRecord.serviceUuids
val lotSeq = extractUUID16(serviceUUIDs[7]) +
extractUUID16(serviceUUIDs[8])
return lotSeq.substring(2).toInt(16)
}
override fun toString(): String {
return "BleDiscoveredDevice{" +
"scanRecord=" + scanRecord +
", podID=" + podId +
"scanResult=" + scanResult +
", sequenceNo=" + sequenceNo +
", lotNo=" + lotNo +
'}'
}
companion object {
const val MAIN_SERVICE_UUID = "4024"
const val UNKNOWN_THIRD_SERVICE_UUID = "000a" // FIXME: why is this 000a?
private fun extractUUID16(uuid: ParcelUuid): String {
return uuid.toString().substring(4, 8)
}
}
init {
validateServiceUUIDs()
validatePodId()
lotNo = parseLotNo()
sequenceNo = parseSeqNo()
}
}
| omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt | 2081818925 |
package com.github.kronenpj.iqtimesheet.IQTimeSheet
internal enum class ActivityCodes {
TASKADD, TASKEDIT, TASKREVIVE, EDIT, REPORT, PREFS, ABOUT, EDIT_ID, RETIRE_ID, SCRUB_DB
}
| IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/ActivityCodes.kt | 1636046541 |
package expo.modules.kotlin.allocators
/**
* This class was created based on https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java.
*/
class ObjectConstructorFactory {
fun <T> get(clazz: Class<T>): ObjectConstructor<T> =
tryToUseDefaultConstructor(clazz) ?: useUnsafeAllocator(clazz)
private fun <T> tryToUseDefaultConstructor(clazz: Class<T>): ObjectConstructor<T>? {
return try {
val ctor = clazz.getDeclaredConstructor()
if (!ctor.isAccessible) {
ctor.isAccessible = true
}
ObjectConstructor {
ctor.newInstance() as T
}
} catch (e: NoSuchMethodException) {
null
}
}
private fun <T> useUnsafeAllocator(clazz: Class<T>): ObjectConstructor<T> {
val allocator = UnsafeAllocator.createAllocator(clazz)
return ObjectConstructor {
allocator.newInstance()
}
}
}
| packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/allocators/ObjectConstructorFactory.kt | 4015836605 |
// Code generated by Wire protocol buffer compiler, do not edit.
// Source: com.squareup.wire.protos.kotlin.repeated.Thing in repeated.proto
package com.squareup.wire.protos.kotlin.repeated
import com.squareup.wire.FieldEncoding
import com.squareup.wire.Message
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.ProtoReader
import com.squareup.wire.ProtoWriter
import com.squareup.wire.ReverseProtoWriter
import com.squareup.wire.Syntax.PROTO_2
import com.squareup.wire.WireField
import com.squareup.wire.`internal`.sanitize
import kotlin.Any
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Unit
import kotlin.jvm.JvmField
import okio.ByteString
public class Thing(
@field:WireField(
tag = 1,
adapter = "com.squareup.wire.ProtoAdapter#STRING",
)
@JvmField
public val name: String? = null,
unknownFields: ByteString = ByteString.EMPTY,
) : Message<Thing, Thing.Builder>(ADAPTER, unknownFields) {
public override fun newBuilder(): Builder {
val builder = Builder()
builder.name = name
builder.addUnknownFields(unknownFields)
return builder
}
public override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is Thing) return false
if (unknownFields != other.unknownFields) return false
if (name != other.name) return false
return true
}
public override fun hashCode(): Int {
var result = super.hashCode
if (result == 0) {
result = unknownFields.hashCode()
result = result * 37 + (name?.hashCode() ?: 0)
super.hashCode = result
}
return result
}
public override fun toString(): String {
val result = mutableListOf<String>()
if (name != null) result += """name=${sanitize(name)}"""
return result.joinToString(prefix = "Thing{", separator = ", ", postfix = "}")
}
public fun copy(name: String? = this.name, unknownFields: ByteString = this.unknownFields): Thing
= Thing(name, unknownFields)
public class Builder : Message.Builder<Thing, Builder>() {
@JvmField
public var name: String? = null
public fun name(name: String?): Builder {
this.name = name
return this
}
public override fun build(): Thing = Thing(
name = name,
unknownFields = buildUnknownFields()
)
}
public companion object {
@JvmField
public val ADAPTER: ProtoAdapter<Thing> = object : ProtoAdapter<Thing>(
FieldEncoding.LENGTH_DELIMITED,
Thing::class,
"type.googleapis.com/com.squareup.wire.protos.kotlin.repeated.Thing",
PROTO_2,
null,
"repeated.proto"
) {
public override fun encodedSize(`value`: Thing): Int {
var size = value.unknownFields.size
size += ProtoAdapter.STRING.encodedSizeWithTag(1, value.name)
return size
}
public override fun encode(writer: ProtoWriter, `value`: Thing): Unit {
ProtoAdapter.STRING.encodeWithTag(writer, 1, value.name)
writer.writeBytes(value.unknownFields)
}
public override fun encode(writer: ReverseProtoWriter, `value`: Thing): Unit {
writer.writeBytes(value.unknownFields)
ProtoAdapter.STRING.encodeWithTag(writer, 1, value.name)
}
public override fun decode(reader: ProtoReader): Thing {
var name: String? = null
val unknownFields = reader.forEachTag { tag ->
when (tag) {
1 -> name = ProtoAdapter.STRING.decode(reader)
else -> reader.readUnknownField(tag)
}
}
return Thing(
name = name,
unknownFields = unknownFields
)
}
public override fun redact(`value`: Thing): Thing = value.copy(
unknownFields = ByteString.EMPTY
)
}
private const val serialVersionUID: Long = 0L
}
}
| wire-library/wire-tests/src/jvmKotlinInteropTest/proto-kotlin/com/squareup/wire/protos/kotlin/repeated/Thing.kt | 727088691 |
package com.squareup.wire
import com.squareup.moshi.Moshi
import com.squareup.wire.json.assertJsonEquals
import com.squareup.wire.proto2.kotlin.Getters
import com.squareup.wire.proto2.person.kotlin.Person.PhoneNumber
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import com.squareup.wire.proto2.person.java.Person as JavaPerson
import com.squareup.wire.proto2.person.javainteropkotlin.Person as JavaInteropKotlinPerson
import com.squareup.wire.proto2.person.kotlin.Person as KotlinPerson
class MoshiPersonTest {
/**
* When we encounter an explicit null in the JSON, we discard it. As a consequence we won't
* overwrite a non-null value with null which could happen in malformed JSON that repeats a value.
*/
@Test
fun javaClobberNonNullWithNull() {
val personWithName = moshi.adapter(JavaPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"[email protected]"}""")
assertThat(personWithName!!.email).isEqualTo("[email protected]")
val personWithNameClobberedWithNull = moshi.adapter(JavaPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"[email protected]","email":null}""")
assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("[email protected]")
}
@Test
fun kotlinClobberNonNullWithNull() {
val personWithName = moshi.adapter(KotlinPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"[email protected]"}""")
assertThat(personWithName!!.email).isEqualTo("[email protected]")
val personWithNameClobberedWithNull = moshi.adapter(KotlinPerson::class.java)
.fromJson("""{"id":1,"name":"Jo","email":"[email protected]","email":null}""")
assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("[email protected]")
}
@Test
fun kotlinWithoutBuilderFromJson() {
val personWithName = moshi.adapter(KotlinPerson::class.java)
.fromJson(
"""
|{
| "id": 1,
| "name": "Jo",
| "email": "[email protected]",
| "phone": [
| {"number": "555-555-5555"},
| {"number": "444-444-4444"}
| ],
| "favorite_numbers": [1, 2, 3],
| "area_numbers": {
| "519": "555-5555"
| },
| "is_canadian": true
|}
""".trimMargin()
)
assertThat(personWithName)
.isEqualTo(
KotlinPerson(
id = 1,
name = "Jo",
email = "[email protected]",
phone = listOf(PhoneNumber("555-555-5555"), PhoneNumber("444-444-4444")),
favorite_numbers = listOf(1, 2, 3),
area_numbers = mapOf(519 to "555-5555"),
is_canadian = true,
)
)
}
@Test
fun kotlinWithoutBuilderToJson() {
val json = moshi.adapter(KotlinPerson::class.java)
.toJson(
KotlinPerson(
id = 1,
name = "Jo",
email = "[email protected]",
phone = listOf(PhoneNumber("555-555-5555"), PhoneNumber("444-444-4444")),
favorite_numbers = listOf(1, 2, 3),
area_numbers = mapOf(519 to "555-5555"),
is_canadian = true,
)
)
assertJsonEquals(
"""
|{
| "id": 1,
| "name": "Jo",
| "email": "[email protected]",
| "phone": [
| {"number": "555-555-5555"},
| {"number": "444-444-4444"}
| ],
| "favorite_numbers": [1, 2, 3],
| "area_numbers": {
| "519": "555-5555"
| },
| "is_canadian": true
|}
""".trimMargin(),
json
)
}
@Test
fun javaInteropKotlinClobberNonNullWithNull() {
val personWithName = moshi.adapter(JavaInteropKotlinPerson::class.java)
.fromJson("{\"id\":1,\"name\":\"Jo\",\"email\":\"[email protected]\"}")
assertThat(personWithName!!.email).isEqualTo("[email protected]")
val personWithNameClobberedWithNull = moshi.adapter(JavaInteropKotlinPerson::class.java)
.fromJson("{\"id\":1,\"name\":\"Jo\",\"email\":\"[email protected]\",\"email\":null}")
assertThat(personWithNameClobberedWithNull!!.email).isEqualTo("[email protected]")
}
@Test
fun kotlinGettersFromJson() {
val getters = moshi.adapter(Getters::class.java)
.fromJson("""{"isa":1,"isA":2,"is_a":3,"is32":32,"isb":true}""")
assertThat(getters).isEqualTo(Getters(isa = 1, isA = 2, is_a = 3, is32 = 32, isb = true))
}
@Test
fun kotlinGettersToJson() {
val getters = moshi.adapter(Getters::class.java)
.toJson(Getters(isa = 1, isA = 2, is_a = 3, is32 = 32, isb = true))
assertThat(getters).isEqualTo("""{"isa":1,"isA":2,"is_a":3,"is32":32,"isb":true}""")
}
companion object {
private val moshi = Moshi.Builder()
.add(WireJsonAdapterFactory())
.build()
}
}
| wire-library/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiPersonTest.kt | 2806294668 |
/*
* 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.data
/**
* Specifies the access mode for a [Handle].
*/
enum class HandleMode(
val canRead: Boolean = false,
val canWrite: Boolean = false,
val canQuery: Boolean = false
) {
/** [Handle] is read only. */
Read(canRead = true),
/** [Handle] is write only. */
Write(canWrite = true),
/** [Handle] is query only. */
Query(canQuery = true),
/** [Handle] is read-write. */
ReadWrite(canRead = true, canWrite = true),
/** [Handle] is read-query. */
ReadQuery(canRead = true, canQuery = true),
/** [Handle] is query-write. */
WriteQuery(canWrite = true, canQuery = true),
/** [Handle] is read-query-write. */
ReadWriteQuery(canRead = true, canWrite = true, canQuery = true);
}
| java/arcs/core/data/HandleMode.kt | 397835356 |
package failchat
import failchat.util.sleep
import java.time.Duration
fun <T> doAwhile(tries: Int, retryDelay: Duration, operation: () -> T): T {
lateinit var lastException: Throwable
repeat(tries) {
try {
return operation.invoke()
} catch (t: Throwable) {
lastException = t
sleep(retryDelay)
}
}
throw lastException
}
fun Long.s(): Duration = Duration.ofSeconds(this)
fun Int.s(): Duration = Duration.ofSeconds(this.toLong())
fun Long.ms(): Duration = Duration.ofMillis(this)
fun Int.ms(): Duration = Duration.ofMillis(this.toLong())
object Utils
fun readResourceAsString(resource: String): String {
val bytes = Utils::class.java.getResourceAsStream(resource)?.readBytes() ?: error("No resource $resource")
return String(bytes)
}
| src/test/kotlin/failchat/Utils.kt | 1145380310 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.plugin.artifacts
import com.intellij.openapi.application.PathManager
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants.KOTLIN_MAVEN_GROUP_ID
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinArtifactsDownloader.downloadArtifactForIdeFromSources
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinMavenUtils
import java.io.File
object TestKotlinArtifacts {
private fun getLibraryFile(groupId: String, artifactId: String, libraryFileName: String): File {
val version = KotlinMavenUtils.findLibraryVersion(libraryFileName)
?: error("Cannot find library version for library $libraryFileName")
return KotlinMavenUtils.findArtifactOrFail(groupId, artifactId, version).toFile()
}
private fun getJar(artifactId: String) =
downloadArtifactForIdeFromSources("kotlinc_kotlin_stdlib.xml", artifactId)
private fun getSourcesJar(artifactId: String) =
downloadArtifactForIdeFromSources("kotlinc_kotlin_stdlib.xml", artifactId, suffix = "-sources.jar")
val kotlinStdlibCommon: File by lazy { getJar("kotlin-stdlib-common") }
val kotlinStdlibCommonSources: File by lazy { getSourcesJar("kotlin-stdlib-common") }
val jsr305: File by lazy { getLibraryFile("com.google.code.findbugs", "jsr305", "jsr305.xml") }
val junit3: File by lazy { getLibraryFile("junit", "junit", "JUnit3.xml") }
@JvmStatic
val compilerTestDataDir: File by lazy {
downloadAndUnpack(
libraryFileName = "kotlinc_kotlin_compiler_cli.xml",
artifactId = "kotlin-compiler-testdata-for-ide",
dirName = "kotlinc-testdata-2",
)
}
@JvmStatic
fun compilerTestData(compilerTestDataPath: String): String {
return compilerTestDataDir.resolve(compilerTestDataPath).canonicalPath
}
@JvmStatic
val jpsPluginTestDataDir: File by lazy {
downloadAndUnpack(
libraryFileName = "kotlinc_kotlin_jps_plugin_tests.xml",
artifactId = "kotlin-jps-plugin-testdata-for-ide",
dirName = "kotlinc-jps-testdata",
)
}
@JvmStatic
val jsIrRuntimeDir: File by lazy {
downloadArtifactForIdeFromSources(
libraryFileName = "kotlinc_kotlin_jps_plugin_tests.xml",
artifactId = "js-ir-runtime-for-ide",
suffix = ".klib"
)
}
@JvmStatic
fun jpsPluginTestData(jpsTestDataPath: String): String {
return jpsPluginTestDataDir.resolve(jpsTestDataPath).canonicalPath
}
private fun downloadAndUnpack(libraryFileName: String, artifactId: String, dirName: String): File {
val jar = downloadArtifactForIdeFromSources(libraryFileName, artifactId)
return LazyZipUnpacker(File(PathManager.getCommunityHomePath()).resolve("out").resolve(dirName)).lazyUnpack(jar)
}
}
| plugins/kotlin/base/plugin/test/org/jetbrains/kotlin/idea/artifacts/TestKotlinArtifacts.kt | 1558315261 |
package failchat.gui
import failchat.kodein
import failchat.platform.windows.WindowsCtConfigurator
import failchat.skin.Skin
import javafx.application.Application
import javafx.stage.Stage
import org.apache.commons.configuration2.Configuration
import org.kodein.di.instance
class ChatFrameLauncher : Application() {
override fun start(primaryStage: Stage) {
//todo remove copypaste
val config = kodein.instance<Configuration>()
val isWindows = com.sun.jna.Platform.isWindows()
val ctConfigurator: ClickTransparencyConfigurator? = if (isWindows) {
WindowsCtConfigurator(config)
} else {
null
}
val chat = ChatFrame(
this,
kodein.instance<Configuration>(),
kodein.instance<List<Skin>>(),
lazy { kodein.instance<GuiEventHandler>() },
ctConfigurator
)
// init web engine (fixes flickering)
chat.clearWebContent()
chat.show()
}
}
| src/main/kotlin/failchat/gui/ChatFrameLauncher.kt | 2251634118 |
package arcs.core.storage.util
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.withTimeout
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class SimpleQueueTest {
@Test
fun enqueueSingleJob() = runBlockingTest {
val queue = SimpleQueue()
val deferred = CompletableDeferred<Unit>()
queue.enqueue {
deferred.complete(Unit)
}
withTimeout(5000) {
deferred.await()
}
}
@Test
fun enqueueSingleJobAndWait() = runBlockingTest {
val queue = SimpleQueue()
var ran = false
withTimeout(5000) {
queue.enqueueAndWait { ran = true }
}
assertThat(ran).isTrue()
}
@Test
fun enqueueAndWait_propagatesException() = runBlockingTest {
val queue = SimpleQueue()
class FakeException : Exception("test dummy")
val dummyException = FakeException()
val receivedException = assertFailsWith<FakeException> {
queue.enqueueAndWait { throw dummyException }
}
// Strangely, the returned exception seems to be wrapped in itself... is this a Kotlin bug?
assertThat(receivedException.cause).isEqualTo(dummyException)
}
@Test
fun onEmptyIsCalled() = runBlockingTest {
val deferred = CompletableDeferred<Unit>()
val queue = SimpleQueue(
onEmpty = {
deferred.complete(Unit)
}
)
queue.enqueue { }
withTimeout(5000) {
deferred.await()
}
}
@Test
fun enqueueSerialized() = runBlockingTest {
val active = atomic(0)
val ran = atomic(0)
val deferred = CompletableDeferred<Unit>()
val queue = SimpleQueue(
onEmpty = {
assertThat(active.incrementAndGet()).isEqualTo(1)
active.decrementAndGet()
deferred.complete(Unit)
}
)
val jobCount = 1000
repeat(jobCount) {
queue.enqueue {
assertThat(active.incrementAndGet()).isEqualTo(1)
suspendCancellableCoroutine<Unit> { it.resume(Unit) {} }
active.decrementAndGet()
ran.incrementAndGet()
}
}
deferred.await()
assertThat(ran.value).isEqualTo(jobCount)
}
}
| javatests/arcs/core/storage/util/SimpleQueueTest.kt | 253964266 |
package luhnmod10
import kotlin.system.measureTimeMillis
import org.junit.Test
class Luhnmod10Benchmark {
@Test fun benchmarkValid() {
val iterations = 100_000_000
val deltaMs = measureTimeMillis {
for (i in 1..iterations) {
valid("4242424242424242")
}
}
val deltaPerOpMs = deltaMs.toDouble() / iterations
val deltaPerOpNs = deltaPerOpMs * 1_000_000
println("valid is %.0fns per op".format(deltaPerOpNs))
}
}
| src/test/kotlin/luhnmod10/LuhnMod10Benchmark.kt | 3548076830 |
package com.timepath.hl2.io.bsp.lump
import com.timepath.hl2.io.bsp.Lump
import com.timepath.hl2.io.bsp.LumpHandler
import com.timepath.io.OrderedInputStream
import java.io.IOException
private val MAX_MAP_SURFEDGES = 512000
class SurfaceEdge {
class Handler : LumpHandler<IntArray> {
override fun invoke(l: Lump, ois: OrderedInputStream): IntArray {
val e = IntArray(l.length / 4)
for (i in e.indices) {
e[i] = ois.readInt()
}
return e
}
}
}
| src/main/kotlin/com/timepath/hl2/io/bsp/lump/SurfaceEdge.kt | 3538171679 |
package org.wordpress.android
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
/**
* Custom AndroidJUnitRunner that replaces the original application with [WordPressTest_Application].
*/
class WordPressTestRunner : AndroidJUnitRunner() {
override fun newApplication(classLoader: ClassLoader, className: String, context: Context): Application {
return super.newApplication(classLoader, WordPressTest_Application::class.java.name, context)
}
}
| WordPress/src/androidTest/java/org/wordpress/android/WordPressTestRunner.kt | 2029469673 |
package org.wordpress.android.ui.mysite.cards.dashboard.error
import android.view.ViewGroup
import org.wordpress.android.databinding.MySiteErrorCardBinding
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.ErrorCard
import org.wordpress.android.ui.mysite.cards.dashboard.CardViewHolder
import org.wordpress.android.util.extensions.viewBinding
class ErrorCardViewHolder(
parent: ViewGroup
) : CardViewHolder<MySiteErrorCardBinding>(
parent.viewBinding(MySiteErrorCardBinding::inflate)
) {
fun bind(card: ErrorCard) = with(binding) {
retry.setOnClickListener { card.onRetryClick.click() }
}
}
| WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/dashboard/error/ErrorCardViewHolder.kt | 683900212 |
/* Copyright 2018-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.neuralprocessor.embeddingsprocessor
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.embeddings.EmbeddingsMap
import com.kotlinnlp.simplednn.core.layers.LayerInterface
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters
import com.kotlinnlp.simplednn.core.neuralprocessor.batchfeedforward.BatchFeedforwardProcessor
import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsAccumulator
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* Extension of the [EmbeddingsProcessor] with a context vector that is concatenated to each embedding.
*
* The [dropout] has no effect on the [contextVector].
*
* @param embeddingsMap an embeddings map
* @param contextVector the context vector concatenated to each embedding
* @param dropout the probability to get the unknown embedding (default 0.0)
*/
class EmbeddingsProcessorWithContext<T>(
embeddingsMap: EmbeddingsMap<T>,
private val contextVector: ParamsArray,
dropout: Double = 0.0
) : EmbeddingsProcessor<T>(
embeddingsMap = embeddingsMap,
dropout = dropout
) {
/**
* The processor that concatenates the [contextVector] to each embedding.
*/
private val concatProcessor = BatchFeedforwardProcessor<DenseNDArray>(
model = StackedLayersParameters(
LayerInterface(sizes = listOf(embeddingsMap.size, contextVector.values.length), type = LayerType.Input.Dense),
LayerInterface(sizes = listOf(), connectionType = LayerType.Connection.Concat)),
dropout = 0.0,
propagateToInput = true)
/**
* Accumulator of the errors of the [contextVector].
*/
private val contextErrorsAccumulator by lazy { ParamsErrorsAccumulator() }
/**
* The Forward.
*
* @param input the input
*
* @return the result of the forward
*/
override fun forward(input: List<T>): List<DenseNDArray> {
val embeddings: List<DenseNDArray> = super.forward(input)
return this.concatProcessor.forward(embeddings.map { listOf(it, this.contextVector.values) }.toTypedArray())
}
/**
* The Backward.
*
* @param outputErrors the output errors
*/
override fun backward(outputErrors: List<DenseNDArray>) {
val concatErrors: List<List<DenseNDArray>> = this.concatProcessor.let {
it.backward(outputErrors)
it.getInputsErrors(copy = false)
}
super.backward(concatErrors.map { it.first() })
this.accumulateContextVectorErrors(concatErrors.map { it.last() })
}
/**
* Return the params errors of the last backward.
*
* @param copy a Boolean indicating whether the returned errors must be a copy or a reference (default true)
*
* @return the parameters errors
*/
override fun getParamsErrors(copy: Boolean) =
super.getParamsErrors(copy) + this.contextErrorsAccumulator.getParamsErrors(copy)
/**
* Accumulate the errors of the context vector.
*
* @param outputErrors the errors to accumulate
*/
private fun accumulateContextVectorErrors(outputErrors: List<DenseNDArray>) {
this.contextErrorsAccumulator.clear()
this.contextErrorsAccumulator.accumulate(params = this.contextVector, errors = outputErrors)
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/neuralprocessor/embeddingsprocessor/EmbeddingsProcessorWithContext.kt | 2861841362 |
package com.kevinmost.koolbelt.util
class SelfReference<T> {
val self: T by lazy {
__self ?: throw IllegalStateException("Do not use `self` until initialized.")
}
var __self: T? = null
}
/**
* Allows referencing "this" (via the "self" variable) while initializing this value
*
* See: http://stackoverflow.com/q/35100389 for the idea and a sample. Rewritten slightly to
* allow the [initializer] block to be inlined.
*/
inline fun <T> selfReference(initializer: SelfReference<T>.() -> T): T {
return SelfReference<T>().apply { __self = initializer() }.self
}
| core/src/main/java/com/kevinmost/koolbelt/util/SelfReference.kt | 1716080088 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain contexte at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.merge.avg
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class AvgLayerStructureSpec : Spek({
describe("a AvgLayer") {
context("forward") {
val layer = AvgLayerUtils.buildLayer()
layer.forward()
it("should match the expected outputArray") {
assertTrue {
layer.outputArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.275, 0.075, 0.025)),
tolerance = 1.0e-05)
}
}
}
context("backward") {
val layer = AvgLayerUtils.buildLayer()
layer.forward()
layer.outputArray.assignErrors(AvgLayerUtils.getOutputErrors())
layer.backward(propagateToInput = true)
it("should match the expected errors of the inputArray at index 0") {
assertTrue {
layer.inputArrays[0].errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)),
tolerance = 1.0e-05)
}
}
it("should match the expected errors of the inputArray at index 1") {
assertTrue {
layer.inputArrays[1].errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)),
tolerance = 1.0e-05)
}
}
it("should match the expected errors of the inputArray at index 2") {
assertTrue {
layer.inputArrays[2].errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)),
tolerance = 1.0e-05)
}
}
it("should match the expected errors of the inputArray at index 3") {
assertTrue {
layer.inputArrays[3].errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25, -0.05, 0.1)),
tolerance = 1.0e-05)
}
}
}
}
})
| src/test/kotlin/core/layers/merge/avg/AvgLayerStructureSpec.kt | 1590717956 |
package org.wordpress.android.ui.posts.editor
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.editor.EditorFragmentAbstract.TrackableEvent
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
@RunWith(MockitoJUnitRunner::class)
class EditorTrackerTest {
@Test
fun `verify trackEditorEvent maps TrackableEvent to correct Stat item`() {
// Arrange
val analyticsTracker = mock<AnalyticsTrackerWrapper>()
val editorTracker = createEditorTracker(analyticsTracker)
// Act
trackEventToStatMap.forEach { (trackableEvent, expectedStat) ->
editorTracker.trackEditorEvent(trackableEvent, "")
// Assert
verify(analyticsTracker).track(eq(expectedStat), anyOrNull<Map<String, *>>())
}
}
@Test
fun `verify trackEditorEvent adds correct editor name property to all events`() {
// Arrange
val analyticsTracker = mock<AnalyticsTrackerWrapper>()
val editorTracker = createEditorTracker(analyticsTracker)
// Act
trackEventToStatMap.forEach { (trackableEvent, _) ->
editorTracker.trackEditorEvent(trackableEvent, editorName)
}
// Assert
verify(analyticsTracker, times(trackEventToStatMap.size))
.track(anyOrNull(), eq(mapOf("editor" to editorName)))
}
private companion object Fixtures {
private const val editorName = "test_editor_name"
private val trackEventToStatMap = mapOf(
TrackableEvent.BOLD_BUTTON_TAPPED to Stat.EDITOR_TAPPED_BOLD,
TrackableEvent.BLOCKQUOTE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_BLOCKQUOTE,
TrackableEvent.ELLIPSIS_COLLAPSE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ELLIPSIS_COLLAPSE,
TrackableEvent.ELLIPSIS_EXPAND_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ELLIPSIS_EXPAND,
TrackableEvent.HEADING_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING,
TrackableEvent.HEADING_1_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_1,
TrackableEvent.HEADING_2_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_2,
TrackableEvent.HEADING_3_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_3,
TrackableEvent.HEADING_4_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_4,
TrackableEvent.HEADING_5_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_5,
TrackableEvent.HEADING_6_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HEADING_6,
TrackableEvent.HORIZONTAL_RULE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HORIZONTAL_RULE,
TrackableEvent.FORMAT_ALIGN_LEFT_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ALIGN_LEFT,
TrackableEvent.FORMAT_ALIGN_CENTER_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ALIGN_CENTER,
TrackableEvent.FORMAT_ALIGN_RIGHT_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ALIGN_RIGHT,
TrackableEvent.HTML_BUTTON_TAPPED to Stat.EDITOR_TAPPED_HTML,
TrackableEvent.IMAGE_EDITED to Stat.EDITOR_EDITED_IMAGE,
TrackableEvent.ITALIC_BUTTON_TAPPED to Stat.EDITOR_TAPPED_ITALIC,
TrackableEvent.LINK_ADDED_BUTTON_TAPPED to Stat.EDITOR_TAPPED_LINK_ADDED,
TrackableEvent.LIST_BUTTON_TAPPED to Stat.EDITOR_TAPPED_LIST,
TrackableEvent.LIST_ORDERED_BUTTON_TAPPED to Stat.EDITOR_TAPPED_LIST_ORDERED,
TrackableEvent.LIST_UNORDERED_BUTTON_TAPPED to Stat.EDITOR_TAPPED_LIST_UNORDERED,
TrackableEvent.MEDIA_BUTTON_TAPPED to Stat.EDITOR_TAPPED_IMAGE,
TrackableEvent.NEXT_PAGE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_NEXT_PAGE,
TrackableEvent.PARAGRAPH_BUTTON_TAPPED to Stat.EDITOR_TAPPED_PARAGRAPH,
TrackableEvent.PREFORMAT_BUTTON_TAPPED to Stat.EDITOR_TAPPED_PREFORMAT,
TrackableEvent.READ_MORE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_READ_MORE,
TrackableEvent.STRIKETHROUGH_BUTTON_TAPPED to Stat.EDITOR_TAPPED_STRIKETHROUGH,
TrackableEvent.UNDERLINE_BUTTON_TAPPED to Stat.EDITOR_TAPPED_UNDERLINE,
TrackableEvent.REDO_TAPPED to Stat.EDITOR_TAPPED_REDO,
TrackableEvent.UNDO_TAPPED to Stat.EDITOR_TAPPED_UNDO
)
fun createEditorTracker(analyticsTrackerWrapper: AnalyticsTrackerWrapper = mock()) =
EditorTracker(mock(), analyticsTrackerWrapper)
}
}
| WordPress/src/test/java/org/wordpress/android/ui/posts/editor/EditorTrackerTest.kt | 3897794860 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.indrnn
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper
import com.kotlinnlp.simplednn.core.arrays.getInputErrors
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The helper which executes the backward on a [layer].
*
* @property layer the [IndRNNLayer] in which the backward is executed
*/
internal class IndRNNBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>(
override val layer: IndRNNLayer<InputNDArrayType>
) : BackwardHelper<InputNDArrayType>(layer) {
/**
* Executes the backward calculating the errors of the parameters and eventually of the input through the SGD
* algorithm, starting from the preset errors of the output array.
*
* @param propagateToInput whether to propagate the errors to the input array
*/
override fun execBackward(propagateToInput: Boolean) {
val prevStateLayer = this.layer.layersWindow.getPrevState()
val nextStateLayer = this.layer.layersWindow.getNextState()
if (nextStateLayer != null) {
this.addLayerRecurrentGradients(nextStateLayer as IndRNNLayer<*>)
}
this.layer.applyOutputActivationDeriv() // must be applied AFTER having added the recurrent contribution
this.assignParamsGradients(prevStateOutput = prevStateLayer?.outputArray)
if (propagateToInput) {
this.assignLayerGradients()
}
}
/**
* gb = gy * 1
* gw = gb (dot) x'
* gwRec = gy * yPrev
*
* @param prevStateOutput the output array in the previous state
*/
private fun assignParamsGradients(prevStateOutput: AugmentedArray<DenseNDArray>?) {
this.layer.outputArray.assignParamsGradients(
gw = this.layer.params.feedforwardUnit.weights.errors.values,
gb = this.layer.params.feedforwardUnit.biases.errors.values,
x = this.layer.inputArray.values
)
val gwRec = this.layer.params.recurrentWeights.errors.values as DenseNDArray
val yPrev = prevStateOutput?.values
if (yPrev != null)
gwRec.assignProd(this.layer.outputArray.errors, yPrev)
else
gwRec.zeros()
}
/**
* gx = gb (dot) w
*/
private fun assignLayerGradients() {
this.layer.inputArray.assignErrors(
this.layer.outputArray.getInputErrors(w = this.layer.params.feedforwardUnit.weights.values)
)
}
/**
* gy += gyNext * wRec
*/
private fun addLayerRecurrentGradients(nextStateLayer: IndRNNLayer<*>) {
val gy: DenseNDArray = this.layer.outputArray.errors
val wRec: DenseNDArray = this.layer.params.recurrentWeights.values
val gRec = nextStateLayer.outputArray.errors.prod(wRec)
gy.assignSum(gRec)
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/indrnn/IndRNNBackwardHelper.kt | 3094532858 |
package com.kelsos.mbrc.commands.model
import com.fasterxml.jackson.databind.node.ObjectNode
import com.kelsos.mbrc.constants.Protocol
import com.kelsos.mbrc.events.bus.RxBus
import com.kelsos.mbrc.events.ui.RepeatChange
import com.kelsos.mbrc.events.ui.ScrobbleChange
import com.kelsos.mbrc.events.ui.ShuffleChange
import com.kelsos.mbrc.events.ui.VolumeChange
import com.kelsos.mbrc.interfaces.ICommand
import com.kelsos.mbrc.interfaces.IEvent
import com.kelsos.mbrc.model.MainDataModel
import javax.inject.Inject
class UpdatePlayerStatus
@Inject
constructor(
private val model: MainDataModel,
private val bus: RxBus
) : ICommand {
override fun execute(e: IEvent) {
val node = e.data as ObjectNode
model.playState = node.path(Protocol.PlayerState).asText()
val newMute = node.path(Protocol.PlayerMute).asBoolean()
if (newMute != model.isMute) {
model.isMute = newMute
bus.post(if (newMute) VolumeChange() else VolumeChange(model.volume))
}
model.setRepeatState(node.path(Protocol.PlayerRepeat).asText())
bus.post(RepeatChange(model.repeat))
val newShuffle = node.path(Protocol.PlayerShuffle).asText()
if (newShuffle != model.shuffle) {
//noinspection ResourceType
model.shuffle = newShuffle
bus.post(ShuffleChange(newShuffle))
}
val newScrobbleState = node.path(Protocol.PlayerScrobble).asBoolean()
if (newScrobbleState != model.isScrobblingEnabled) {
model.isScrobblingEnabled = newScrobbleState
bus.post(ScrobbleChange(newScrobbleState))
}
val newVolume = Integer.parseInt(node.path(Protocol.PlayerVolume).asText())
if (newVolume != model.volume) {
model.volume = newVolume
bus.post(VolumeChange(model.volume))
}
}
}
| app/src/main/kotlin/com/kelsos/mbrc/commands/model/UpdatePlayerStatus.kt | 3866802513 |
// 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.openapi.application
import com.intellij.openapi.progress.blockingContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Experimental
import kotlin.coroutines.CoroutineContext
/**
* Suspends until it's possible to obtain the read lock and then
* runs the [action] holding the lock **without** preventing write actions.
* See [constrainedReadAction] for semantic details.
*
* @see readActionBlocking
*/
suspend fun <T> readAction(action: () -> T): T {
return constrainedReadAction(action = action)
}
/**
* Suspends until it's possible to obtain the read lock in smart mode and then
* runs the [action] holding the lock **without** preventing write actions.
* See [constrainedReadAction] for semantic details.
*
* @see smartReadActionBlocking
*/
suspend fun <T> smartReadAction(project: Project, action: () -> T): T {
return constrainedReadAction(ReadConstraint.inSmartMode(project), action = action)
}
/**
* Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction]
* **without** preventing write actions.
*
* The function suspends if at the moment of calling it's not possible to acquire the read lock,
* or if [constraints] are not [satisfied][ReadConstraint.isSatisfied].
* If the write action happens while the [action] is running, then the [action] is canceled,
* and the function suspends until its possible to acquire the read lock, and then the [action] is tried again.
*
* Since the [action] might me executed several times, it must be idempotent.
* The function returns when given [action] was completed fully.
* To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled].
*
* The [action] is dispatched to [Dispatchers.Default], because a read action is expected to be a CPU-bound task.
*
* @see constrainedReadActionBlocking
*/
suspend fun <T> constrainedReadAction(vararg constraints: ReadConstraint, action: () -> T): T {
return readActionSupport().executeReadAction(constraints.toList(), blocking = false, action)
}
/**
* Suspends until it's possible to obtain the read lock and then
* runs the [action] holding the lock and **preventing** write actions.
* See [constrainedReadActionBlocking] for semantic details.
*
* @see readAction
*/
suspend fun <T> readActionBlocking(action: () -> T): T {
return constrainedReadActionBlocking(action = action)
}
/**
* Suspends until it's possible to obtain the read lock in smart mode and then
* runs the [action] holding the lock and **preventing** write actions.
* See [constrainedReadActionBlocking] for semantic details.
*
* @see smartReadAction
*/
suspend fun <T> smartReadActionBlocking(project: Project, action: () -> T): T {
return constrainedReadActionBlocking(ReadConstraint.inSmartMode(project), action = action)
}
/**
* Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction]
* **preventing** write actions.
*
* The function suspends if at the moment of calling it's not possible to acquire the read lock,
* or if [constraints] are not [satisfied][ReadConstraint.isSatisfied].
* If the write action happens while the [action] is running, then the [action] is **not** canceled,
* meaning the [action] will block pending write actions until finished.
*
* The function returns when given [action] was completed fully.
* To support cancellation, the [action] must regularly invoke [com.intellij.openapi.progress.ProgressManager.checkCanceled].
*
* The [action] is dispatched to [Dispatchers.Default], because a read action is expected to be a CPU-bound task.
*
* @see constrainedReadAction
*/
suspend fun <T> constrainedReadActionBlocking(vararg constraints: ReadConstraint, action: () -> T): T {
return readActionSupport().executeReadAction(constraints.toList(), blocking = true, action)
}
/**
* Runs given [action] under [write lock][com.intellij.openapi.application.Application.runWriteAction].
*
* Currently, the [action] is dispatched by [Dispatchers.EDT] within the [context modality state][asContextElement].
* If the calling coroutine is already executed by [Dispatchers.EDT], then no re-dispatch happens.
* Acquiring the write-lock happens in blocking manner,
* i.e. [runWriteAction][com.intellij.openapi.application.Application.runWriteAction] call will block
* until all currently running read actions are finished.
*
* NB This function is an API stub.
* The implementation will change once running write actions would be allowed on other threads.
* This function exists to make it possible to use it in suspending contexts
* before the platform is ready to handle write actions differently.
*/
@Experimental
suspend fun <T> writeAction(action: () -> T): T {
return withContext(Dispatchers.EDT) {
blockingContext {
ApplicationManager.getApplication().runWriteAction(Computable(action))
}
}
}
private fun readActionSupport() = ApplicationManager.getApplication().getService(ReadActionSupport::class.java)
/**
* The code within [ModalityState.any] context modality state must only perform pure UI operations,
* it must not access any PSI, VFS, project model, or indexes. It also must not show any modal dialogs.
*/
fun ModalityState.asContextElement(): CoroutineContext = coroutineSupport().asContextElement(this)
/**
* UI dispatcher which dispatches onto Swing event dispatching thread within the [context modality state][asContextElement].
* If no context modality state is specified, then the coroutine is dispatched within [ModalityState.NON_MODAL] modality state.
*
* This dispatcher is also installed as [Dispatchers.Main].
* Use [Dispatchers.EDT] when in doubt, use [Dispatchers.Main] if the coroutine doesn't care about IJ model,
* e.g. when it is also able to be executed outside of IJ process.
*/
@Suppress("UnusedReceiverParameter")
val Dispatchers.EDT: CoroutineContext get() = coroutineSupport().edtDispatcher()
private fun coroutineSupport() = ApplicationManager.getApplication().getService(CoroutineSupport::class.java)
| platform/core-api/src/com/intellij/openapi/application/coroutines.kt | 63633473 |
package org.example.myapp.main
import org.avaje.jettyrunner.JettyRun
/**
* A Kotlin main method to run Jetty.
*/
fun main(args: Array<String>) {
println("starting jetty ...")
val jettyRun = JettyRun()
jettyRun.setHttpPort(9090)
jettyRun.runServer()
} | src/test/java/org/example/myapp/main/RunJetty.kt | 2254455116 |
/*
* 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
*
* 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.samples.apps.nowinandroid.core.domain
import com.google.samples.apps.nowinandroid.core.data.repository.NewsRepository
import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository
import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.map
/**
* A use case responsible for obtaining news resources with their associated bookmarked (also known
* as "saved") state.
*/
class GetSaveableNewsResourcesStreamUseCase @Inject constructor(
private val newsRepository: NewsRepository,
userDataRepository: UserDataRepository
) {
private val bookmarkedNewsResourcesStream = userDataRepository.userDataStream.map {
it.bookmarkedNewsResources
}
/**
* Returns a list of SaveableNewsResources which match the supplied set of topic ids or author
* ids.
*
* @param filterTopicIds - A set of topic ids used to filter the list of news resources. If
* this is empty AND filterAuthorIds is empty the list of news resources will not be filtered.
* @param filterAuthorIds - A set of author ids used to filter the list of news resources. If
* this is empty AND filterTopicIds is empty the list of news resources will not be filtered.
*
*/
operator fun invoke(
filterTopicIds: Set<String> = emptySet(),
filterAuthorIds: Set<String> = emptySet()
): Flow<List<SaveableNewsResource>> =
if (filterTopicIds.isEmpty() && filterAuthorIds.isEmpty()) {
newsRepository.getNewsResourcesStream()
} else {
newsRepository.getNewsResourcesStream(
filterTopicIds = filterTopicIds,
filterAuthorIds = filterAuthorIds
)
}.mapToSaveableNewsResources(bookmarkedNewsResourcesStream)
}
private fun Flow<List<NewsResource>>.mapToSaveableNewsResources(
savedNewsResourceIdsStream: Flow<Set<String>>
): Flow<List<SaveableNewsResource>> =
filterNot { it.isEmpty() }
.combine(savedNewsResourceIdsStream) { newsResources, savedNewsResourceIds ->
newsResources.map { newsResource ->
SaveableNewsResource(
newsResource = newsResource,
isSaved = savedNewsResourceIds.contains(newsResource.id)
)
}
}
| core/domain/src/main/java/com/google/samples/apps/nowinandroid/core/domain/GetSaveableNewsResourcesStreamUseCase.kt | 347094549 |
/*
* 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
*
* 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.samples.apps.nowinandroid.feature.bookmarks
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.grid.GridCells.Adaptive
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaLoadingWheel
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState
import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Loading
import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Success
import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank
import com.google.samples.apps.nowinandroid.core.ui.newsFeed
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun BookmarksRoute(
modifier: Modifier = Modifier,
viewModel: BookmarksViewModel = hiltViewModel()
) {
val feedState by viewModel.feedUiState.collectAsStateWithLifecycle()
BookmarksScreen(
feedState = feedState,
removeFromBookmarks = viewModel::removeFromSavedResources,
modifier = modifier
)
}
/**
* Displays the user's bookmarked articles. Includes support for loading and empty states.
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
@Composable
internal fun BookmarksScreen(
feedState: NewsFeedUiState,
removeFromBookmarks: (String) -> Unit,
modifier: Modifier = Modifier
) {
when (feedState) {
Loading -> LoadingState(modifier)
is Success -> if (feedState.feed.isNotEmpty()) {
BookmarksGrid(feedState, removeFromBookmarks, modifier)
} else {
EmptyState(modifier)
}
}
}
@Composable
private fun LoadingState(modifier: Modifier = Modifier) {
NiaLoadingWheel(
modifier = modifier
.fillMaxWidth()
.wrapContentSize()
.testTag("forYou:loading"),
contentDesc = stringResource(id = R.string.saved_loading),
)
}
@Composable
private fun BookmarksGrid(
feedState: NewsFeedUiState,
removeFromBookmarks: (String) -> Unit,
modifier: Modifier = Modifier
) {
val scrollableState = rememberLazyGridState()
TrackScrollJank(scrollableState = scrollableState, stateName = "bookmarks:grid")
LazyVerticalGrid(
columns = Adaptive(300.dp),
contentPadding = PaddingValues(16.dp),
horizontalArrangement = Arrangement.spacedBy(32.dp),
verticalArrangement = Arrangement.spacedBy(24.dp),
state = scrollableState,
modifier = modifier
.fillMaxSize()
.testTag("bookmarks:feed")
) {
newsFeed(
feedState = feedState,
onNewsResourcesCheckedChanged = { id, _ -> removeFromBookmarks(id) },
)
item(span = { GridItemSpan(maxLineSpan) }) {
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing))
}
}
}
@Composable
private fun EmptyState(modifier: Modifier = Modifier) {
Column(
modifier = modifier
.padding(16.dp)
.fillMaxSize()
.testTag("bookmarks:empty"),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier.fillMaxWidth(),
painter = painterResource(id = R.drawable.img_empty_bookmarks),
contentDescription = null
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = stringResource(id = R.string.bookmarks_empty_error),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(id = R.string.bookmarks_empty_description),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium
)
}
}
@Preview
@Composable
private fun LoadingStatePreview() {
NiaTheme {
LoadingState()
}
}
@Preview
@Composable
private fun BookmarksGridPreview() {
NiaTheme {
BookmarksGrid(
feedState = Success(
previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
removeFromBookmarks = {}
)
}
}
@Preview
@Composable
fun EmptyStatePreview() {
NiaTheme {
EmptyState()
}
}
| feature/bookmarks/src/main/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksScreen.kt | 1553391132 |
package edu.byu.suite.features.testingCenter.model.scores
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import edu.byu.support.ByuParcelable2
import edu.byu.support.ByuParcelable2.Companion.parcelableCreator
/**
* Created by cwoodfie on 8/2/16
*/
data class Schedule(
@SerializedName("dept_name")
val deptName: String?,
@SerializedName("catalog_number")
val catalogNumber: String?,
val shortDescription: String?
): ByuParcelable2 {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<Schedule> = parcelableCreator(::Schedule)
}
private constructor(parcel: Parcel): this(
parcel.readString(),
parcel.readString(),
parcel.readString()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(deptName)
parcel.writeString(catalogNumber)
parcel.writeString(shortDescription)
}
}
| app/src/main/java/edu/byu/suite/features/testingCenter/model/scores/Schedule.kt | 147297705 |
package core
import core.API.Elevator
import core.API.Passenger
class Strategy : BaseStrategy() {
override fun onTick(myPassengers: List<Passenger>, myElevators: List<Elevator>, enemyPassengers: List<Passenger>, enemyElevators: List<Elevator>) {
for (e in myElevators) {
for (p in myPassengers) {
if (p.state < 5) {
if (e.state != 1) {
e.goToFloor(p.fromFloor)
}
if (e.floor == p.fromFloor) {
p.setElevator(e)
}
}
}
if (e.passengers.size > 0 && e.state != 1) {
e.goToFloor(e.passengers[0].destFloor)
}
}
}
} | clients/kotlin_client/client/src/main/kotlin/core/Strategy.kt | 3917192297 |
package database.save
import com.onyx.exception.NoResultsException
import com.onyx.persistence.IManagedEntity
import database.base.DatabaseBaseTest
import entities.AllAttributeEntity
import org.junit.*
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
import org.junit.runners.Parameterized
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.Future
import kotlin.reflect.KClass
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(Parameterized::class)
class StandardIdentifierConcurrencyTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) {
companion object {
private val threadPool = Executors.newFixedThreadPool(10)
}
/**
* Tests Batch inserting 10,000 record with a String identifier
* last test took: 759(mac)
*/
@Test
fun aConcurrencyStandardPerformanceTest() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val before = System.currentTimeMillis()
for (i in 0..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
if (i % 500 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
})
}
}
threads.forEach { it.get() }
val after = System.currentTimeMillis()
assertTrue(after - before < 350, "Should not take more than 1.5 seconds to complete")
}
/**
* Runs 10 threads that insert 10k entities with a String identifier.
* After insertion, this test validates the data integrity.
* last test took: 698(win) 2231(mac)
*/
@Test
fun concurrencyStandardSaveIntegrityTest() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val entitiesToValidate = ArrayList<AllAttributeEntity>()
for (i in 0..5000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
entitiesToValidate.add(entity)
if (i % 10 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
tmpList.forEach {
manager.saveEntity(it)
}
}
}
threads.forEach { it.get() }
// Validate entities to ensure it was persisted correctly
entitiesToValidate.parallelStream().forEach {
var newEntity = AllAttributeEntity()
newEntity.id = it.id
newEntity = manager.find(newEntity)
assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}")
assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}")
}
}
@Test
fun concurrencyStandardSaveIntegrityTestWithBatching() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val entitiesToValidate = ArrayList<AllAttributeEntity>()
for (i in 1..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
entitiesToValidate.add(entity)
if (i % 1000 == 0) {
val tmpList = ArrayList<AllAttributeEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
})
}
}
threads.forEach { it.get() }
// Validate entities to ensure it was persisted correctly
entitiesToValidate.parallelStream().forEach {
var newEntity = AllAttributeEntity()
newEntity.id = it.id
newEntity = manager.find(newEntity)
assertEquals(it.id, newEntity.id, "ID was not as expected ${it.id}")
assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not as expected ${it.longPrimitive}")
}
}
@Test
fun concurrencyStandardDeleteIntegrityTest() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val entitiesToValidate = ArrayList<AllAttributeEntity>()
val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>()
for (i in 0..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
if (i % 2 == 0) {
entitiesToValidateDeleted.add(entity)
} else {
entitiesToValidate.add(entity)
}
if (i % 10 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
tmpList.forEach {
manager.saveEntity(it)
}
})
}
}
threads.forEach { it.get() }
threads.clear()
entities.clear()
var deleteCount = 0
for (i in 0..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
entitiesToValidate.add(entity)
if (i % 10 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
val deletedIndex = deleteCount
threads.add(async(threadPool) {
tmpList.forEach { manager.saveEntity(it) }
var t = deletedIndex
while (t < deletedIndex + 5 && t < entitiesToValidateDeleted.size) {
manager.deleteEntity(entitiesToValidateDeleted[t])
t++
}
})
deleteCount += 5
}
}
threads.forEach { it.get() }
entitiesToValidate.parallelStream().forEach {
var newEntity = AllAttributeEntity()
newEntity.id = it.id
newEntity = manager.find(newEntity)
assertEquals(it.longPrimitive, newEntity.longPrimitive, "longPrimitive was not persisted correctly")
}
entitiesToValidateDeleted.parallelStream().forEach {
val newEntity = AllAttributeEntity()
newEntity.id = it.id
var pass = false
try {
manager.find<IManagedEntity>(newEntity)
} catch (e: NoResultsException) {
pass = true
}
assertTrue(pass, "Entity ${newEntity.id} was not deleted")
}
}
@Test
fun concurrencyStandardDeleteBatchIntegrityTest() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val entitiesToValidate = ArrayList<AllAttributeEntity>()
val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>()
val ignore = HashMap<String, AllAttributeEntity>()
for (i in 0..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
if (i % 2 == 0) {
entitiesToValidateDeleted.add(entity)
ignore.put(entity.id!!, entity)
} else {
entitiesToValidate.add(entity)
}
if (i % 10 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
})
}
}
threads.forEach { it.get() }
threads.clear()
entities.clear()
for (i in 0..10000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
entitiesToValidate.add(entity)
if (i % 10 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
for(k in 0 .. 6) {
var entityToDelete:IManagedEntity? = null
synchronized(entitiesToValidateDeleted) {
if (entitiesToValidateDeleted.size > 0) {
entityToDelete = entitiesToValidateDeleted.removeAt(0)
}
}
if(entityToDelete != null)
manager.deleteEntity(entityToDelete!!)
}
})
}
}
threads.forEach { it.get() }
entitiesToValidate.parallelStream().forEach {
var newEntity = AllAttributeEntity()
newEntity.id = it.id
if (!ignore.containsKey(newEntity.id)) {
newEntity = manager.find(newEntity)
assertEquals(it.longPrimitive, newEntity.longPrimitive, "Entity did not hydrate correctly")
}
}
entitiesToValidateDeleted.parallelStream().forEach {
val newEntity = AllAttributeEntity()
newEntity.id = it.id
var pass = false
try {
manager.find<IManagedEntity>(newEntity)
} catch (e: NoResultsException) {
pass = true
}
assertTrue(pass, "Entity ${newEntity.id} was not deleted")
}
}
/**
* Executes 10 threads that insert 30k entities with string id, then 10k are updated and 10k are deleted.
* Then it validates the integrity of those actions
*/
@Test
fun concurrencyStandardAllIntegrityTest() {
val threads = ArrayList<Future<*>>()
val entities = ArrayList<AllAttributeEntity>()
val entitiesToValidate = ArrayList<AllAttributeEntity>()
val entitiesToValidateDeleted = ArrayList<AllAttributeEntity>()
val entitiesToValidateUpdated = ArrayList<AllAttributeEntity>()
val ignore = HashMap<String, AllAttributeEntity>()
for (i in 0..30000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
// Delete Even ones
when {
i % 2 == 0 -> {
entitiesToValidateDeleted.add(entity)
ignore.put(entity.id!!, entity)
}
i % 3 == 0 && i % 2 != 0 -> entitiesToValidateUpdated.add(entity)
else -> entitiesToValidate.add(entity)
}
if (i % 1000 == 0) {
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
})
}
}
threads.forEach { it.get() }
threads.clear()
entities.clear()
entitiesToValidateDeleted -= entitiesToValidateUpdated
entitiesToValidateUpdated -= entitiesToValidateDeleted
val entitiesToBeDeleted = ArrayList<AllAttributeEntity>(entitiesToValidateDeleted)
entitiesToValidateUpdated.forEach { it.longPrimitive = 45645 }
var updateCount = 0
for (i in 0..30000) {
val entity = AllAttributeEntity()
entity.id = randomString + i
entity.longValue = 4L
entity.longPrimitive = 3L
entity.stringValue = "String key"
entity.dateValue = Date(1483736263743L)
entity.doublePrimitive = 342.23
entity.doubleValue = 232.2
entity.booleanPrimitive = true
entity.booleanValue = false
entities.add(entity)
if (i % 20 == 0) {
entitiesToValidate.add(entity)
val tmpList = ArrayList<IManagedEntity>(entities)
entities.clear()
val updatedIndex = updateCount
threads.add(async(threadPool) {
manager.saveEntities(tmpList)
var t = updatedIndex
while (t < updatedIndex + 13 && t < entitiesToValidateUpdated.size) {
manager.saveEntity<IManagedEntity>(entitiesToValidateUpdated[t])
t++
}
for(k in 0..31) {
var entityToDelete:AllAttributeEntity? = null
synchronized(entitiesToBeDeleted) {
if(!entitiesToBeDeleted.isEmpty())
entityToDelete = entitiesToBeDeleted.removeAt(0)
}
if(entityToDelete != null)
manager.deleteEntity(entityToDelete!!)
}
})
updateCount += 13
}
}
entitiesToValidateDeleted -= entitiesToValidateUpdated
threads.forEach { it.get() }
var failedEntities = 0
entitiesToValidate.parallelStream().forEach {
val newEntity = AllAttributeEntity()
newEntity.id = it.id
if (!ignore.containsKey(newEntity.id)) {
try {
manager.find<IManagedEntity>(newEntity)
} catch (e: Exception) {
failedEntities++
}
}
}
assertEquals(0, failedEntities, "There were several entities that failed to be found")
entitiesToValidateDeleted.parallelStream().forEach {
val newEntity = AllAttributeEntity()
newEntity.id = it.id
var pass = false
try {
manager.find<IManagedEntity>(newEntity)
} catch (e: NoResultsException) {
pass = true
}
if (!pass) {
failedEntities++
manager.deleteEntity(newEntity)
manager.find<IManagedEntity>(newEntity)
}
}
assertEquals(0, failedEntities, "There were several entities that failed to be deleted")
entitiesToValidateUpdated.parallelStream().forEach {
var newEntity = AllAttributeEntity()
newEntity.id = it.id
newEntity = manager.find(newEntity)
assertEquals(45645L, newEntity.longPrimitive, "Entity failed to update")
}
}
}
| onyx-database-tests/src/test/kotlin/database/save/StandardIdentifierConcurrencyTest.kt | 3072364590 |
// IS_APPLICABLE: false
val <caret>foo = 1
get() {
return field
} | plugins/kotlin/idea/tests/testData/intentions/convertPropertyToFunction/initializerWithGetter.kt | 3066595131 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.cli.common.arguments.ManualLanguageFeatureSetting
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.createArguments
import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKpmJvmPlatform
import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKpmNativePlatform
import org.jetbrains.kotlin.idea.base.externalSystem.findAll
import org.jetbrains.kotlin.idea.base.facet.isKpmModule
import org.jetbrains.kotlin.idea.base.facet.refinesFragmentIds
import org.jetbrains.kotlin.idea.base.projectStructure.ExternalCompilerVersionProvider
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl.findKotlinPluginVersion
import org.jetbrains.kotlin.idea.gradleJava.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
class KotlinFragmentDataService : AbstractProjectDataService<KotlinFragmentData, Void>() {
override fun getTargetDataKey(): Key<KotlinFragmentData> = KotlinFragmentData.KEY
override fun postProcess(
toImport: MutableCollection<out DataNode<KotlinFragmentData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
for (fragmentDataNode in toImport) {
val sourceSetDataNode = ExternalSystemApiUtil.findParent(fragmentDataNode, GradleSourceSetData.KEY)
?: error("Failed to find parent GradleSourceSetData for KotlinKPMGradleFragmentData '${fragmentDataNode.data.externalName}'")
val ideModule = modelsProvider.findIdeModule(sourceSetDataNode.data) ?: continue
val moduleNode = ExternalSystemApiUtil.findParent(sourceSetDataNode, ProjectKeys.MODULE) ?: continue
configureFacetByFragmentData(ideModule, modelsProvider, moduleNode, sourceSetDataNode, fragmentDataNode)?.also { kotlinFacet ->
GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(kotlinFacet, sourceSetDataNode) }
}
}
}
companion object {
private fun KotlinFacet.configureFacet(
compilerVersion: IdeKotlinVersion?,
platform: TargetPlatform?, // if null, detect by module dependencies
modelsProvider: IdeModifiableModelsProvider,
) {
val module = module
with(configuration.settings) {
compilerArguments = null
targetPlatform = null
compilerSettings = null
initializeIfNeeded(
module,
modelsProvider.getModifiableRootModel(module),
platform,
compilerVersion
)
val apiLevel = apiLevel
val languageLevel = languageLevel
if (languageLevel != null && apiLevel != null && apiLevel > languageLevel) {
this.apiLevel = languageLevel
}
}
ExternalCompilerVersionProvider.set(module, compilerVersion)
}
private fun configureFacetByFragmentData(
ideModule: Module,
modelsProvider: IdeModifiableModelsProvider,
moduleNode: DataNode<ModuleData>,
sourceSetNode: DataNode<GradleSourceSetData>,
fragmentDataNode: DataNode<KotlinFragmentData>
): KotlinFacet? {
val compilerVersion = moduleNode.findAll(BuildScriptClasspathData.KEY).firstOrNull()?.data?.let(::findKotlinPluginVersion)
?: return null
val platform = when (fragmentDataNode.data.platform) {
KotlinPlatform.COMMON -> CommonPlatforms.defaultCommonPlatform
KotlinPlatform.JVM, KotlinPlatform.ANDROID -> fragmentDataNode.data.platforms
.filterIsInstance<IdeaKpmJvmPlatform>()
.map { it.jvmTarget }
.singleOrNull()
?.let { JvmTarget.valueOf(it) }
?.let { JvmPlatforms.jvmPlatformByTargetVersion(it) }
?: JvmPlatforms.defaultJvmPlatform
// TODO should we select platform depending on isIr platform detail?
KotlinPlatform.JS -> JsPlatforms.defaultJsPlatform
KotlinPlatform.NATIVE -> fragmentDataNode.data.platforms
.filterIsInstance<IdeaKpmNativePlatform>()
.mapNotNull { KonanTarget.predefinedTargets[it.konanTarget] }
.ifNotEmpty { NativePlatforms.nativePlatformByTargets(this) }
?: NativePlatforms.unspecifiedNativePlatform
}
val languageSettings = fragmentDataNode.data.languageSettings
val compilerArguments = platform.createArguments {
multiPlatform = true
languageSettings?.also {
languageVersion = it.languageVersion
apiVersion = it.apiVersion
progressiveMode = it.isProgressiveMode
internalArguments = it.enabledLanguageFeatures.mapNotNull {
val feature = LanguageFeature.fromString(it) ?: return@mapNotNull null
val arg = "-XXLanguage:+$it"
ManualLanguageFeatureSetting(feature, LanguageFeature.State.ENABLED, arg)
}
optIn = it.optInAnnotationsInUse.toTypedArray()
pluginOptions = it.compilerPluginArguments.toTypedArray()
pluginClasspaths = it.compilerPluginClasspath.map(File::getPath).toTypedArray()
freeArgs = it.freeCompilerArgs.toMutableList()
}
}
val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, GradleConstants.SYSTEM_ID.id)
kotlinFacet.configureFacet(
compilerVersion,
platform,
modelsProvider,
)
ideModule.hasExternalSdkConfiguration = sourceSetNode.data.sdkName != null
ideModule.isKpmModule = true
ideModule.refinesFragmentIds = fragmentDataNode.data.refinesFragmentIds.toList()
applyCompilerArgumentsToFacet(compilerArguments, platform.createArguments(), kotlinFacet, modelsProvider)
kotlinFacet.noVersionAutoAdvance()
return kotlinFacet
}
}
}
| plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinFragmentDataService.kt | 2538417400 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.io
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.testFramework.rules.InMemoryFsExtension
import com.intellij.util.io.write
import com.intellij.util.lang.HashMapZipFile
import com.intellij.util.lang.ImmutableZipFile
import com.intellij.util.lang.ZipFile
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.configuration.ConfigurationProvider
import org.jetbrains.intellij.build.tasks.DirSource
import org.jetbrains.intellij.build.tasks.ZipSource
import org.jetbrains.intellij.build.tasks.buildJar
import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
import kotlin.random.Random
@Suppress("UsePropertyAccessSyntax")
class ZipTest {
@RegisterExtension
@JvmField
// not used in every test because we want to check the real FS behaviour
val fs = InMemoryFsExtension()
@Test
fun `interrupt thread`(@TempDir tempDir: Path) {
val (list, archiveFile) = createLargeArchive(128, tempDir)
checkZip(archiveFile) { zipFile ->
val tasks = mutableListOf<ForkJoinTask<*>>()
// force init of AssertJ to avoid ClosedByInterruptException on reading FileLoader index
ConfigurationProvider.CONFIGURATION_PROVIDER
for (i in 0..100) {
tasks.add(ForkJoinTask.adapt(Runnable {
val ioThread = runInThread {
while (!Thread.currentThread().isInterrupted()) {
for (name in list) {
assertThat(zipFile.getResource(name)).isNotNull()
}
}
}
// once in a while, the IO thread is stopped
Thread.sleep(50)
ioThread.interrupt()
Thread.sleep(10)
ioThread.join()
}))
}
ForkJoinTask.invokeAll(tasks)
}
}
@Test
fun `read zip file with more than 65K entries`() {
Assumptions.assumeTrue(SystemInfoRt.isUnix)
val (list, archiveFile) = createLargeArchive(Short.MAX_VALUE * 2 + 20, fs.root)
checkZip(archiveFile) { zipFile ->
for (name in list) {
assertThat(zipFile.getResource(name)).isNotNull()
}
}
}
private fun createLargeArchive(size: Int, tempDir: Path): Pair<MutableList<String>, Path> {
val random = Random(42)
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val list = mutableListOf<String>()
for (i in 0..size) {
val name = "entry-item${random.nextInt()}-$i"
list.add(name)
Files.write(dir.resolve(name), random.nextBytes(random.nextInt(32)))
}
val archiveFile = tempDir.resolve("archive.zip")
zip(archiveFile, mapOf(dir to ""))
return Pair(list, archiveFile)
}
@Test
fun `custom prefix`(@TempDir tempDir: Path) {
val random = Random(42)
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val list = mutableListOf<String>()
for (i in 0..10) {
val name = "entry-item${random.nextInt()}-$i"
list.add(name)
Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128)))
}
val archiveFile = tempDir.resolve("archive.zip")
zip(archiveFile, mapOf(dir to "test"))
checkZip(archiveFile) { zipFile ->
for (name in list) {
assertThat(zipFile.getResource("test/$name")).isNotNull()
}
}
}
@Test
fun excludes(@TempDir tempDir: Path) {
val random = Random(42)
val dir = Files.createDirectories(tempDir.resolve("dir"))
val list = mutableListOf<String>()
for (i in 0..10) {
val name = "entry-item${random.nextInt()}-$i"
list.add(name)
Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128)))
}
Files.write(dir.resolve("do-not-ignore-me"), random.nextBytes(random.nextInt(128)))
Files.write(dir.resolve("test-relative-ignore"), random.nextBytes(random.nextInt(128)))
val iconRobotsFile = dir.resolve("some/nested/dir/icon-robots.txt")
iconRobotsFile.write("text")
val rootIconRobotsFile = dir.resolve("icon-robots.txt")
rootIconRobotsFile.write("text2")
val archiveFile = tempDir.resolve("archive.zip")
val fs = dir.fileSystem
buildJar(archiveFile, listOf(DirSource(dir = dir, excludes = listOf(
fs.getPathMatcher("glob:**/entry-item*"),
fs.getPathMatcher("glob:test-relative-ignore"),
fs.getPathMatcher("glob:**/icon-robots.txt"),
))))
checkZip(archiveFile) { zipFile ->
if (zipFile is ImmutableZipFile) {
assertThat(zipFile.getOrComputeNames()).containsExactly(
"entry-item663137163-10",
"entry-item972016666-0",
"entry-item1791766502-3",
"entry-item1705343313-9",
"entry-item-942605861-5",
"entry-item1578011503-7",
"entry-item949746295-2",
"entry-item-245744780-1",
"do-not-ignore-me",
"icon-robots.txt",
"entry-item-2145949183-8",
"entry-item-1326272896-6",
"entry-item828400960-4"
)
}
for (name in list) {
assertThat(zipFile.getResource("test/$name")).isNull()
}
assertThat(zipFile.getResource("do-not-ignore-me")).isNotNull()
assertThat(zipFile.getResource("test-relative-ignore")).isNull()
assertThat(zipFile.getResource("some/nested/dir/icon-robots.txt")).isNull()
assertThat(zipFile.getResource("unknown")).isNull()
}
}
@Test
fun excludesInZipSource(@TempDir tempDir: Path) {
val random = Random(42)
val dir = Files.createDirectories(tempDir.resolve("zip"))
Files.write(dir.resolve("zip-included"), random.nextBytes(random.nextInt(128)))
Files.write(dir.resolve("zip-excluded"), random.nextBytes(random.nextInt(128)))
val zip = tempDir.resolve("test.zip")
zip(zip, mapOf(dir to ""))
val archiveFile = tempDir.resolve("archive.zip")
buildJar(archiveFile, listOf(
ZipSource(file = zip, excludes = listOf(Regex("^zip-excl.*")))
))
checkZip(archiveFile) { zipFile ->
if (zipFile is ImmutableZipFile) {
assertThat(zipFile.getOrComputeNames()).containsExactly("zip-included")
}
}
}
@Test
fun skipIndex(@TempDir tempDir: Path) {
val dir = Files.createDirectories(tempDir.resolve("dir"))
Files.writeString(dir.resolve("file1"), "1")
Files.writeString(dir.resolve("file2"), "2")
val archiveFile = tempDir.resolve("archive.zip")
buildJar(archiveFile, listOf(DirSource(dir = dir, excludes = emptyList())), compress = true)
java.util.zip.ZipFile(archiveFile.toString()).use { zipFile ->
assertThat(zipFile.entries().asSequence().map { it.name }.toList())
.containsExactlyInAnyOrder("file1", "file2")
}
checkZip(archiveFile) { }
}
@Test
fun `small file`(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
val file = dir.resolve("samples/nested_dir/__init__.py")
Files.createDirectories(file.parent)
Files.writeString(file, "\n")
val archiveFile = tempDir.resolve("archive.zip")
zipWithCompression(archiveFile, mapOf(dir to ""))
HashMapZipFile.load(archiveFile).use { zipFile ->
for (name in zipFile.entries) {
val entry = zipFile.getRawEntry("samples/nested_dir/__init__.py")
assertThat(entry).isNotNull()
assertThat(entry!!.isCompressed()).isFalse()
assertThat(String(entry.getData(zipFile), Charsets.UTF_8)).isEqualTo("\n")
}
}
}
@Test
fun compression(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val data = Random(42).nextBytes(4 * 1024)
Files.write(dir.resolve("file"), data + data + data)
val archiveFile = tempDir.resolve("archive.zip")
zipWithCompression(archiveFile, mapOf(dir to ""))
HashMapZipFile.load(archiveFile).use { zipFile ->
val entry = zipFile.getRawEntry("file")
assertThat(entry).isNotNull()
assertThat(entry!!.isCompressed()).isTrue()
}
}
@Test
fun `large file`(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val random = Random(42)
Files.write(dir.resolve("largeFile1"), random.nextBytes(10 * 1024 * 1024))
Files.write(dir.resolve("largeFile2"), random.nextBytes(1 * 1024 * 1024))
Files.write(dir.resolve("largeFile3"), random.nextBytes(2 * 1024 * 1024))
val archiveFile = tempDir.resolve("archive.zip")
zip(archiveFile, mapOf(dir to ""))
checkZip(archiveFile) { zipFile ->
val entry = zipFile.getResource("largeFile1")
assertThat(entry).isNotNull()
}
}
@Test
fun `large incompressible file compressed`(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val random = Random(42)
val data = random.nextBytes(10 * 1024 * 1024)
Files.write(dir.resolve("largeFile1"), data)
Files.write(dir.resolve("largeFile2"), random.nextBytes(1 * 1024 * 1024))
Files.write(dir.resolve("largeFile3"), random.nextBytes(2 * 1024 * 1024))
val archiveFile = tempDir.resolve("archive.zip")
zipWithCompression(archiveFile, mapOf(dir to ""))
checkZip(archiveFile) { zipFile ->
val entry = zipFile.getResource("largeFile1")
assertThat(entry).isNotNull()
}
}
@Test
fun `large compressible file compressed`(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val random = Random(42)
val data = random.nextBytes(2 * 1024 * 1024)
Files.write(dir.resolve("largeFile1"), data + data + data + data + data + data + data + data + data + data)
Files.write(dir.resolve("largeFile2"), data + data + data + data)
Files.write(dir.resolve("largeFile3"), data + data)
val archiveFile = tempDir.resolve("archive.zip")
zipWithCompression(archiveFile, mapOf(dir to ""))
checkZip(archiveFile) { zipFile ->
val entry = zipFile.getResource("largeFile1")
assertThat(entry).isNotNull()
}
}
@Test
fun `write all dir entries`(@TempDir tempDir: Path) {
val dir = tempDir.resolve("dir")
Files.createDirectories(dir)
val random = Random(42)
val data = random.nextBytes(2 * 1024 * 1024)
dir.resolve("dir/subDir/foo.class").write(data)
val archiveFile = tempDir.resolve("archive.zip")
zip(archiveFile, mapOf(dir to ""), addDirEntriesMode = AddDirEntriesMode.ALL)
HashMapZipFile.load(archiveFile).use { zipFile ->
assertThat(zipFile.getRawEntry("dir/subDir")).isNotNull
}
}
// check both IKV- and non-IKV variants of immutable zip file
private fun checkZip(file: Path, checker: (ZipFile) -> Unit) {
HashMapZipFile.load(file).use { zipFile ->
checker(zipFile)
}
ImmutableZipFile.load(file).use { zipFile ->
checker(zipFile)
}
}
}
private fun runInThread(block: () -> Unit): Thread {
val thread = Thread(block, "test interrupt")
thread.isDaemon = true
thread.start()
return thread
}
| build/tasks/test/org/jetbrains/intellij/build/io/ZipTest.kt | 3058610790 |
// "Change to 'var'" "true"
val String.prop: Int
get() {
val p = 1
<caret>p = 2
return p
}
/* IGNORE_FIR */ | plugins/kotlin/idea/tests/testData/quickfix/variables/changeMutability/localInGetter.kt | 789313560 |
package com.intellij.cce.evaluation
import com.intellij.cce.core.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.io.exists
import com.intellij.cce.workspace.EvaluationWorkspace
import org.jetbrains.idea.maven.project.MavenProjectsManager
import java.nio.file.Paths
class SetupJDKStep(private val project: Project) : SetupSdkStep() {
override val name: String = "Set up JDK step"
override val description: String = "Configure project JDK if needed"
override fun isApplicable(language: Language): Boolean = language in setOf(Language.JAVA, Language.KOTLIN, Language.SCALA)
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace {
ApplicationManager.getApplication().invokeAndWait {
WriteAction.run<Throwable> {
val projectRootManager = ProjectRootManager.getInstance(project)
val mavenManager = MavenProjectsManager.getInstance(project)
val projectSdk = projectRootManager.projectSdk
if (projectSdk != null) {
println("Project JDK already configured")
} else {
println("Project JDK not configured")
val sdk = configureProjectSdk(projectRootManager.projectSdkName)
if (sdk != null) {
println("JDK \"${sdk.name}\" (${sdk.homePath}) will be used as a project SDK")
projectRootManager.projectSdk = sdk
}
}
mavenManager.importingSettings.jdkForImporter = ExternalSystemJdkUtil.USE_PROJECT_JDK
}
}
return workspace
}
private fun configureProjectSdk(expectedSdkName: String?): Sdk? {
println("Try to configure project JDK")
val sdkTable = ProjectJdkTable.getInstance()
val javaHome = System.getenv("EVALUATION_JAVA") ?: System.getenv("JAVA_HOME")
if (javaHome != null) {
println("Java found in $javaHome")
return if (isIdeaCommunityProject()) {
configureIdeaJdks(javaHome)
} else {
val jdkName = expectedSdkName ?: "Evaluation JDK"
val jdk = JavaSdk.getInstance().createJdk(jdkName, javaHome, false)
sdkTable.addJdk(jdk)
jdk
}
}
println("Java SDK not configured for the project: ${project.basePath}")
return null
}
private fun configureIdeaJdks(javaHome: String): Sdk {
println("Project (${project.basePath}) marked as IntelliJ project")
val ideaJdk = JavaSdk.getInstance().createJdk("IDEA jdk", javaHome, false)
val jdk = JavaSdk.getInstance().createJdk("1.8", javaHome, false)
val sdkTable = ProjectJdkTable.getInstance()
if (SystemInfo.isWindows) {
println("Configuring tools.jar...")
ideaJdk.addToolsJarToClasspath()
jdk.addToolsJarToClasspath()
}
sdkTable.addJdk(ideaJdk)
sdkTable.addJdk(jdk)
return ideaJdk
}
private fun isIdeaCommunityProject(): Boolean = System.getenv("EVALUATE_ON_IDEA") != null
private fun Sdk.addToolsJarToClasspath() {
val javaHome = homePath
if (javaHome == null) {
println("Could not add tools.jar for JDK. Home path not found")
return
}
val toolsJar = Paths.get(javaHome, "lib", "tools.jar")
if (!toolsJar.exists()) {
println("Could not add tools.jar to \"$name\" JDK")
}
sdkModificator.addRoot(toolsJar.toString(), OrderRootType.CLASSES)
sdkModificator.commitChanges()
println("tools.jar successfully added to \"$name\" JDK")
}
} | plugins/evaluation-plugin/languages/java/src/com/intellij/cce/evaluation/SetupJDKStep.kt | 1559311330 |
// Copyright 2000-2018 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 com.intellij.codeInspection
import com.intellij.jvm.analysis.JvmAnalysisKtTestsUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
@TestDataPath("/testData/codeInspection/unstableApiUsage")
class KtUnstableApiUsageInspectionTest : UnstableApiUsageInspectionTestBase() {
override fun getBasePath() = "${TEST_DATA_PROJECT_RELATIVE_BASE_PATH}/codeInspection/unstableApiUsage"
override fun performAdditionalSetUp() {
// otherwise assertion in PsiFileImpl ("Access to tree elements not allowed") will not pass
(myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter(VirtualFileFilter.NONE)
}
fun testInspection() {
inspection.myIgnoreInsideImports = false
myFixture.testHighlighting("UnstableElementsTest.kt")
}
fun testIgnoreImports() {
inspection.myIgnoreInsideImports = true
myFixture.testHighlighting("UnstableElementsIgnoreImportsTest.kt")
}
} | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/KtUnstableApiUsageInspectionTest.kt | 676797813 |
/*
* Copyright 2000-2015 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 com.intellij.diff.merge
import com.intellij.diff.merge.MergeTestBase.SidesState.*
import com.intellij.diff.util.Side
import com.intellij.diff.util.TextDiffType.*
import com.intellij.diff.util.ThreeSide
class MergeTest : MergeTestBase() {
fun testChangeTypes() {
test("", "", "", 0) {
}
test("x", "x", "x", 0) {
}
test("x_y_z a x", "x_y_z a x", "x_y_z a x", 0) {
}
test1("x", "x", "y") {
0.assertType(MODIFIED, RIGHT)
0.assertContent("x", 0, 1)
0.assertResolved(NONE)
}
test1("x", "y", "x") {
0.assertType(MODIFIED, BOTH)
0.assertContent("y", 0, 1)
0.assertResolved(NONE)
}
test2("x_Y", "Y", "Y_z") {
0.assertType(INSERTED, LEFT)
0.assertContent("", 0, 0)
0.assertResolved(NONE)
1.assertType(INSERTED, RIGHT)
1.assertContent("", 1, 1)
1.assertResolved(NONE)
}
test2("Y_z", "x_Y_z", "x_Y") {
0.assertType(DELETED, LEFT)
0.assertContent("x", 0, 1)
0.assertResolved(NONE)
1.assertType(DELETED, RIGHT)
1.assertContent("z", 2, 3)
1.assertResolved(NONE)
}
test1("X_Z", "X_y_Z", "X_Z") {
0.assertType(DELETED, BOTH)
0.assertContent("y", 1, 2)
0.assertResolved(NONE)
}
test1("X_y_Z", "X_Z", "X_y_Z") {
0.assertType(INSERTED, BOTH)
0.assertContent("", 1, 1)
0.assertResolved(NONE)
}
test1("x", "y", "z") {
0.assertType(CONFLICT, BOTH)
0.assertContent("y", 0, 1)
0.assertResolved(NONE)
}
test1("z_Y", "x_Y", "Y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("x", 0, 1)
0.assertResolved(NONE)
}
test1("z_Y", "x_Y", "k_x_Y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("x", 0, 1)
0.assertResolved(NONE)
}
test1("x_Y", "Y", "z_Y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("", 0, 0)
0.assertResolved(NONE)
}
test1("x_Y", "Y", "z_x_Y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("", 0, 0)
0.assertResolved(NONE)
}
test1("x_Y", "x_z_Y", "z_Y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("x_z", 0, 2)
0.assertResolved(NONE)
}
}
fun testLastLine() {
test1("x", "x_", "x") {
0.assertType(DELETED, BOTH)
0.assertContent("", 1, 2)
0.assertResolved(NONE)
}
test1("x_", "x_", "x") {
0.assertType(DELETED, RIGHT)
0.assertContent("", 1, 2)
0.assertResolved(NONE)
}
test1("x_", "x_", "x_y") {
0.assertType(MODIFIED, RIGHT)
0.assertContent("", 1, 2)
0.assertResolved(NONE)
}
test1("x", "x_", "x_y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("", 1, 2)
0.assertResolved(NONE)
}
test1("x_", "x", "x_y") {
0.assertType(CONFLICT, BOTH)
0.assertContent("", 1, 1)
0.assertResolved(NONE)
}
}
fun testModifications() {
test1("x", "x", "y") {
0.apply(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("y")
}
test1("x", "x", "y") {
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
test1("X_x_Z", "X_x_Z", "X_y_Z") {
0.apply(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("X_y_Z")
}
test1("z", "x", "y") {
0.apply(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("y")
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("y_z")
assertContent("y_z")
}
test1("z", "x", "y") {
0.apply(Side.LEFT)
0.assertResolved(LEFT)
0.assertContent("z")
0.apply(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("z_y")
assertContent("z_y")
}
test1("X", "X", "X_y") {
0.apply(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("X_y")
}
test1("X", "X", "X_y") {
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("")
assertContent("X")
}
test1("X_z", "X", "X_y") {
0.apply(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("y")
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("y_z")
assertContent("X_y_z")
}
test1("X_z", "X_y", "X") {
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("z")
assertContent("X_z")
}
test1("X_z", "X_y", "X") {
0.apply(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("")
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("z")
assertContent("X_z")
}
}
fun testModificationsIgnore() {
test1("x", "x", "y") {
0.ignore(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
test1("x", "x", "y") {
0.ignore(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
test1("z", "x", "y") {
0.ignore(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("x")
0.ignore(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
test1("z", "x", "y") {
0.apply(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("y")
0.ignore(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("y")
}
test1("z", "x", "y") {
0.ignore(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("x")
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("z")
assertContent("z")
}
test1("X_z", "X_y", "X") {
0.ignore(Side.RIGHT)
0.assertResolved(RIGHT)
0.assertContent("y")
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertContent("z")
assertContent("X_z")
}
test1("X_z", "X_y", "X") {
0.ignore(Side.LEFT)
0.assertResolved(LEFT)
0.assertContent("y")
0.apply(Side.RIGHT)
0.assertResolved(BOTH)
0.assertContent("")
assertContent("X")
}
}
fun testModificationsModifiers() {
test1("x", "x", "y") {
0.apply(Side.RIGHT, true)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("y")
}
test1("x", "x", "y") {
0.ignore(Side.RIGHT, true)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
test1("z", "x", "y") {
0.apply(Side.RIGHT, true)
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("y")
}
test1("z", "x", "y") {
0.ignore(Side.RIGHT, true)
0.assertResolved(BOTH)
0.assertContent("x")
assertContent("x")
}
}
fun testResolve() {
test1("y z", "x y z", "x y") {
0.resolve()
0.assertResolved(BOTH)
0.assertContent("y")
assertContent("y")
}
test2("y z_Y_x y", "x y z_Y_x y z", "x y_Y_y z") {
0.resolve()
0.assertResolved(BOTH)
0.assertContent("y")
1.resolve()
1.assertResolved(BOTH)
1.assertContent("y")
assertContent("y_Y_y")
}
test2("y z_Y_x y", "x y z_Y_x y z", "x y_Y_y z") {
0.apply(Side.LEFT, true)
0.assertResolved(BOTH)
0.assertContent("y z")
1.resolve()
1.assertResolved(BOTH)
1.assertContent("y")
assertContent("y z_Y_y")
}
test1("y z", "x y z", "x y") {
assertTrue(0.canResolveConflict())
replaceText(2, 3, "U")
assertContent("x U z")
assertFalse(0.canResolveConflict())
}
test2("y z_Y_x y", "x y z_Y_x y z", "x y_Y_y z") {
assertTrue(0.canResolveConflict())
assertTrue(1.canResolveConflict())
replaceText(2, 3, "U")
assertFalse(0.canResolveConflict())
assertTrue(1.canResolveConflict())
assertContent("x U z_Y_x y z")
checkUndo(1) {
1.resolve()
}
1.assertResolved(BOTH)
1.assertContent("y")
assertFalse(0.canResolveConflict())
assertFalse(1.canResolveConflict())
assertContent("x U z_Y_y")
replaceText(2, 3, "y")
assertTrue(0.canResolveConflict())
assertFalse(1.canResolveConflict())
checkUndo(1) {
0.resolve()
}
assertFalse(0.canResolveConflict())
assertFalse(1.canResolveConflict())
assertContent("y_Y_y")
}
}
fun testUndoSimple() {
test1("x", "y", "z") {
checkUndo(1) {
0.apply(Side.RIGHT)
}
}
test1("x", "y", "z") {
checkUndo(1) {
0.apply(Side.RIGHT, true)
}
}
test1("x", "y", "z") {
checkUndo(1) {
0.ignore(Side.RIGHT)
}
}
test1("x", "y", "z") {
checkUndo(1) {
0.ignore(Side.RIGHT, true)
}
}
test1("x", "y", "z") {
checkUndo(2) {
0.apply(Side.RIGHT)
0.apply(Side.LEFT)
}
}
test1("x", "y", "z") {
checkUndo(2) {
0.apply(Side.RIGHT)
0.apply(Side.RIGHT)
}
}
test1("X", "X_y", "X") {
checkUndo(1) {
0.apply(Side.RIGHT)
}
}
test1("X", "X", "X_y") {
checkUndo(1) {
0.apply(Side.LEFT)
}
}
test1("X", "X", "X_y") {
checkUndo(1) {
0.apply(Side.RIGHT)
}
}
test1("X_z", "X_y", "X") {
checkUndo(1) {
0.apply(Side.LEFT)
}
}
test1("X_z", "X_y", "X") {
checkUndo(1) {
0.apply(Side.RIGHT)
}
}
test2("y_X", "X", "X_z") {
checkUndo(1) {
0.apply(Side.LEFT)
}
checkUndo(1) {
1.apply(Side.RIGHT)
}
assertContent("y_X_z")
}
}
fun testRangeModification() {
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { replaceText(!2 - 0, !2 - 1, "D") }
0.assertContent("a_D_c", 1, 4)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { replaceText(!2 - -1, !2 - 2, "D") }
0.assertContent("aDc", 1, 2)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { replaceText("c", "u_x") }
0.assertContent("a_b_u_x", 1, 5)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { deleteText("c_") }
0.assertContent("a_b", 1, 3)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { insertTextBefore("b", "q") }
0.assertContent("a_qb_c", 1, 4)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { insertTextAfter("b", "q") }
0.assertContent("a_bq_c", 1, 4)
}
test1("X_x_y_z_Y", "X_a_b_c_Y", "X_x_y_z_Y") {
0.assertContent("a_b_c", 1, 4)
checkUndo(1) { insertText(0, "a_b_c_") }
0.assertContent("a_b_c", 4, 7)
}
test1("A_X_x_y_z_Y", "A_X_a_b_c_Y", "A_X_x_y_z_Y") {
0.assertContent("a_b_c", 2, 5)
checkUndo(1) { replaceText("X_a_b", "q_w_e") }
0.assertContent("c")
}
test1("X_x_y_z_Y_A", "X_a_b_c_Y_A", "X_x_y_z_Y_A") {
0.assertContent("a_b_c")
checkUndo(1) { replaceText("c_Y", "q") }
0.assertContent("a_b")
}
test1("A_X_x_Y_A", "A_X_b_Y_A", "A_X_x_z_Y_A") {
0.assertContent("b")
checkUndo(1) { replaceText("X_b_Y", "q") }
0.assertContent("", 2, 2)
assertContent("A_q_A")
}
}
fun testNonConflictsActions() {
val text1 = """
1 ======
insert left
2 ======
remove right
3 ======
new both
4 ======
modify both
5 ======
modify
6 ======
7 ======
8 ======""".trimIndent()
val text2 = """
1 ======
2 ======
remove right
3 ======
4 ======
modify
5 ======
modify
6 ======
7 ======
delete modify
8 ======""".trimIndent()
val text3 = """
1 ======
2 ======
3 ======
new both
4 ======
modify both
5 ======
modify right
6 ======
7 ======
modify
8 ======""".trimIndent()
testN(text1, text2, text3) {
checkUndo(1) {
runApplyNonConflictsAction(ThreeSide.BASE)
}
assertChangesCount(1)
assertContent("""
1 ======
insert left
2 ======
3 ======
new both
4 ======
modify both
5 ======
modify right
6 ======
7 ======
delete modify
8 ======""".trimIndent())
}
testN(text1, text2, text3) {
checkUndo(1) {
runApplyNonConflictsAction(ThreeSide.LEFT)
}
assertChangesCount(3)
assertContent("""
1 ======
insert left
2 ======
remove right
3 ======
new both
4 ======
modify both
5 ======
modify
6 ======
7 ======
delete modify
8 ======""".trimIndent())
}
testN(text1, text2, text3) {
checkUndo(1) {
runApplyNonConflictsAction(ThreeSide.RIGHT)
}
assertChangesCount(2)
assertContent("""
1 ======
2 ======
3 ======
new both
4 ======
modify both
5 ======
modify right
6 ======
7 ======
delete modify
8 ======""".trimIndent())
}
testN(text1, text2, text3) {
replaceText(!5 - 0, !5 - 0, "USER ")
checkUndo(1) {
runApplyNonConflictsAction(ThreeSide.BASE)
}
assertChangesCount(2)
assertContent("""
1 ======
insert left
2 ======
3 ======
new both
4 ======
USER modify
5 ======
modify right
6 ======
7 ======
delete modify
8 ======""".trimIndent())
}
testN(text1, text2, text3) {
replaceText(!7 - 0, !7 - 0, "USER ")
checkUndo(1) {
runApplyNonConflictsAction(ThreeSide.RIGHT)
}
assertChangesCount(3)
assertContent("""
1 ======
2 ======
3 ======
new both
4 ======
modify both
5 ======
USER modify
6 ======
7 ======
delete modify
8 ======""".trimIndent())
}
}
fun testNoConflicts() {
test2("a_Ins1_b_ccc", "a_b_ccc", "a_b_dddd") {
0.assertRange(1, 2, 1, 1, 1, 1)
1.assertRange(3, 4, 2, 3, 2, 3)
0.apply(Side.LEFT)
0.assertRange(1, 2, 1, 2, 1, 1)
1.assertRange(3, 4, 3, 4, 2, 3)
assertContent("a_Ins1_b_ccc")
runApplyNonConflictsAction(ThreeSide.BASE)
0.assertRange(1, 2, 1, 2, 1, 1)
1.assertRange(3, 4, 3, 4, 2, 3)
assertContent("a_Ins1_b_dddd")
0.assertResolved(BOTH)
1.assertResolved(BOTH)
}
}
fun testConflictingChange() {
test("1_2_3_X_a_b_c_Y_Ver1_Ver12_Z",
"X_a_b_c_Y_" + "Ver12_Ver23_Z",
"X_" + "Y_" + "Ver23_Ver3_Z", 3) {
0.assertType(INSERTED)
1.assertType(DELETED)
2.assertType(CONFLICT)
runApplyNonConflictsAction(ThreeSide.BASE)
0.assertResolved(BOTH)
1.assertResolved(BOTH)
2.assertResolved(NONE)
assertContent("1_2_3_X_Y_Ver12_Ver23_Z")
}
}
fun testApplyMergeThenUndo() {
test1("X_b_Y", "X_1_2_3_Y", "X_a_Y") {
0.assertRange(1, 2, 1, 4, 1, 2)
0.apply(Side.RIGHT)
0.assertRange(1, 2, 1, 2, 1, 2)
0.assertContent("a")
checkUndo(1) {
0.apply(Side.LEFT)
0.assertRange(1, 2, 1, 3, 1, 2)
0.assertContent("a_b")
}
assertContent("X_a_b_Y")
}
}
fun testApplyModifiedDeletedConflict() {
test1("X_Y", "X_1_2_3_Y", "X_a_Y") {
0.assertRange(1, 1, 1, 4, 1, 2)
0.assertContent("1_2_3")
runApplyNonConflictsAction(ThreeSide.BASE)
0.assertResolved(NONE)
0.apply(Side.RIGHT)
0.assertRange(1, 1, 1, 2, 1, 2)
0.assertResolved(BOTH)
assertContent("X_a_Y")
}
}
fun testInvalidatingChange() {
test1("X_1_2_Y", "X_1_Ins_2_Y", "X_1_2_Y") {
0.assertType(DELETED)
0.assertRange(2, 2, 2, 3, 2, 2)
deleteText("1_Ins_2_")
0.assertResolved(BOTH)
0.assertRange(2, 2, 2, 2, 2, 2)
}
}
fun testApplySeveralActions() {
test("X_1_Y_2_Z_3_4_U_W_",
"X_a_Y_b_Z_c_U_d_W_",
"X_a_Y_B_Z_C_U_D_W_", 4) {
0.assertType(MODIFIED)
1.assertType(CONFLICT)
2.assertType(CONFLICT)
3.assertType(CONFLICT)
0.apply(Side.LEFT)
0.assertResolved(BOTH)
0.assertResolved(BOTH)
3.apply(Side.RIGHT)
3.assertResolved(BOTH)
assertContent("X_1_Y_b_Z_c_U_D_W_")
1.apply(Side.RIGHT)
1.assertResolved(RIGHT)
assertContent("X_1_Y_B_Z_c_U_D_W_")
1.apply(Side.LEFT)
2.apply(Side.LEFT)
2.apply(Side.RIGHT)
1.assertResolved(BOTH)
2.assertResolved(BOTH)
assertContent("X_1_Y_B_2_Z_3_4_C_U_D_W_")
}
}
fun testIgnoreChangeAction() {
test2("X_1_Y_2_Z", "X_a_Y_b_Z", "X_a_Y_B_Z") {
0.assertType(MODIFIED)
1.assertType(CONFLICT)
0.ignore(Side.LEFT)
0.assertRange(1, 2, 1, 2, 1, 2)
assertContent("X_a_Y_b_Z")
0.ignore(Side.RIGHT)
0.assertResolved(BOTH)
0.assertRange(1, 2, 1, 2, 1, 2)
assertContent("X_a_Y_b_Z")
}
}
fun testLongBase() {
test1("X_1_2_3_Z", "X_1_b_3_d_e_f_Z", "X_a_b_c_Z") {
0.assertType(CONFLICT)
0.assertRange(1, 4, 1, 7, 1, 4)
}
}
fun testReplaceBaseWithBranch() {
test2("a_X_b_c", "A_X_B_c", "1_X_1_c") {
0.assertType(CONFLICT)
1.assertType(CONFLICT)
0.apply(Side.LEFT)
assertContent("a_X_B_c")
replaceText("a_X_B_c", "a_X_b_c")
0.assertRange(0, 1, 0, 1, 0, 1)
1.assertRange(2, 3, 2, 3, 2, 3)
}
}
fun testError1() {
testN("start_change_ a_ b",
"start_CHANGE_ a_ b",
" }_ return new DiffFragment(notEmptyContent(buffer1), notEmptyContent(buffer2));_ }") {
}
}
fun testError2() {
test1("C_X", "C_", "C_") {
0.assertRange(1, 2, 1, 2, 1, 2)
}
}
fun testError3() {
testN("original_local_local_local_original_",
"original_original_original_original_original_",
"original_remote_remote_remote_original_") {
}
}
}
| platform/diff-impl/tests/com/intellij/diff/merge/MergeTest.kt | 2609839304 |
package io.ktor.utils.io
import io.ktor.utils.io.bits.*
import java.nio.*
/**
* Visitor function that is invoked for every available buffer (or chunk) of a channel.
* The last parameter shows that the buffer is known to be the last.
*/
public typealias ConsumeEachBufferVisitor = (buffer: ByteBuffer, last: Boolean) -> Boolean
/**
* For every available bytes range invokes [visitor] function until it return false or end of stream encountered.
* The provided buffer should be never captured outside of the visitor block otherwise resource leaks, crashes and
* data corruptions may occur. The visitor block may be invoked multiple times, once or never.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public suspend inline fun ByteReadChannel.consumeEachBufferRange(visitor: ConsumeEachBufferVisitor) {
var continueFlag: Boolean
var lastChunkReported = false
do {
continueFlag = false
read { source, start, endExclusive ->
val nioBuffer = when {
endExclusive > start -> source.slice(start, endExclusive - start).buffer
else -> Memory.Empty.buffer
}
lastChunkReported = nioBuffer.remaining() == availableForRead && isClosedForWrite
continueFlag = visitor(nioBuffer, lastChunkReported)
nioBuffer.position()
}
if (lastChunkReported && isClosedForRead) {
break
}
} while (continueFlag)
}
| ktor-io/jvm/src/io/ktor/utils/io/ConsumeEach.kt | 808605552 |
package example
import kotlin.io.*
class KotlinClass {
fun run() {
println("KotlinClass run()")
}
}
| src/test/resources/projects/kotlinFirst/src/main/kotlin/example/KotlinClass.kt | 3922626181 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio.internals
import io.ktor.http.*
import io.ktor.utils.io.*
internal const val HTAB: Char = '\u0009'
internal fun CharSequence.hashCodeLowerCase(start: Int = 0, end: Int = length): Int {
var hashCode = 0
for (pos in start until end) {
val v = get(pos).code.toLowerCase()
hashCode = 31 * hashCode + v
}
return hashCode
}
internal fun CharSequence.equalsLowerCase(start: Int = 0, end: Int = length, other: CharSequence): Boolean {
if (end - start != other.length) return false
for (pos in start until end) {
if (get(pos).code.toLowerCase() != other[pos - start].code.toLowerCase()) return false
}
return true
}
@Suppress("NOTHING_TO_INLINE")
private inline fun Int.toLowerCase() =
if (this in 'A'.code..'Z'.code) 'a'.code + (this - 'A'.code) else this
internal val DefaultHttpMethods =
AsciiCharTree.build(HttpMethod.DefaultMethods, { it.value.length }, { m, idx -> m.value[idx] })
private val HexTable = (0..0xff).map { v ->
when {
v in 0x30..0x39 -> v - 0x30L
v >= 'a'.code.toLong() && v <= 'f'.code.toLong() -> v - 'a'.code.toLong() + 10
v >= 'A'.code.toLong() && v <= 'F'.code.toLong() -> v - 'A'.code.toLong() + 10
else -> -1L
}
}.toLongArray()
internal val HexLetterTable: ByteArray = (0..0xf).map {
if (it < 0xa) (0x30 + it).toByte() else ('a' + it - 0x0a).code.toByte()
}.toByteArray()
internal fun CharSequence.parseHexLong(): Long {
var result = 0L
val table = HexTable
for (i in 0 until length) {
val v = this[i].code and 0xffff
val digit = if (v < 0xff) table[v] else -1L
if (digit == -1L) hexNumberFormatException(this, i)
result = (result shl 4) or digit
}
return result
}
/**
* Converts [CharSequence] representation in decimal format to [Long]
*/
public fun CharSequence.parseDecLong(): Long {
val length = length
if (length > 19) numberFormatException(this)
if (length == 19) return parseDecLongWithCheck()
var result = 0L
for (i in 0 until length) {
val digit = this[i].code.toLong() - 0x30L
if (digit < 0 || digit > 9) numberFormatException(this, i)
result = (result shl 3) + (result shl 1) + digit
}
return result
}
private fun CharSequence.parseDecLongWithCheck(): Long {
var result = 0L
for (i in 0 until length) {
val digit = this[i].code.toLong() - 0x30L
if (digit < 0 || digit > 9) numberFormatException(this, i)
result = (result shl 3) + (result shl 1) + digit
if (result < 0) numberFormatException(this)
}
return result
}
internal suspend fun ByteWriteChannel.writeIntHex(value: Int) {
require(value > 0) { "Does only work for positive numbers" } // zero is not included!
var current = value
val table = HexLetterTable
var digits = 0
while (digits++ < 8) {
val v = current ushr 28
current = current shl 4
if (v != 0) {
writeByte(table[v])
break
}
}
while (digits++ < 8) {
val v = current ushr 28
current = current shl 4
writeByte(table[v])
}
}
private fun hexNumberFormatException(s: CharSequence, idx: Int): Nothing {
throw NumberFormatException("Invalid HEX number: $s, wrong digit: ${s[idx]}")
}
private fun numberFormatException(cs: CharSequence, idx: Int) {
throw NumberFormatException("Invalid number: $cs, wrong digit: ${cs[idx]} at position $idx")
}
private fun numberFormatException(cs: CharSequence) {
throw NumberFormatException("Invalid number $cs: too large for Long type")
}
| ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Chars.kt | 1917776194 |
package io.ktor.utils.io.charsets
import io.ktor.utils.io.core.*
import io.ktor.utils.io.js.*
import org.khronos.webgl.*
public actual abstract class Charset(internal val _name: String) {
public actual abstract fun newEncoder(): CharsetEncoder
public actual abstract fun newDecoder(): CharsetDecoder
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class.js != other::class.js) return false
other as Charset
if (_name != other._name) return false
return true
}
override fun hashCode(): Int {
return _name.hashCode()
}
override fun toString(): String {
return _name
}
public actual companion object {
@Suppress("LocalVariableName")
public actual fun forName(name: String): Charset {
if (name == "UTF-8" || name == "utf-8" || name == "UTF8" || name == "utf8") return Charsets.UTF_8
if (name == "ISO-8859-1" || name == "iso-8859-1" ||
name.replace('_', '-').let { it == "iso-8859-1" || it.lowercase() == "iso-8859-1" } ||
name == "latin1" || name == "Latin1"
) {
return Charsets.ISO_8859_1
}
throw IllegalArgumentException("Charset $name is not supported")
}
public actual fun isSupported(charset: String): Boolean = when {
charset == "UTF-8" || charset == "utf-8" || charset == "UTF8" || charset == "utf8" -> true
charset == "ISO-8859-1" || charset == "iso-8859-1" || charset.replace('_', '-').let {
it == "iso-8859-1" || it.lowercase() == "iso-8859-1"
} || charset == "latin1" -> true
else -> false
}
}
}
public actual val Charset.name: String get() = _name
// -----------------------
public actual abstract class CharsetEncoder(internal val _charset: Charset)
private data class CharsetEncoderImpl(private val charset: Charset) : CharsetEncoder(charset)
public actual val CharsetEncoder.charset: Charset get() = _charset
public actual fun CharsetEncoder.encodeToByteArray(input: CharSequence, fromIndex: Int, toIndex: Int): ByteArray =
encodeToByteArrayImpl1(input, fromIndex, toIndex)
internal actual fun CharsetEncoder.encodeImpl(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Buffer): Int {
require(fromIndex <= toIndex)
if (charset == Charsets.ISO_8859_1) {
return encodeISO88591(input, fromIndex, toIndex, dst)
}
require(charset === Charsets.UTF_8) { "Only UTF-8 encoding is supported in JS" }
val encoder = TextEncoder() // Only UTF-8 is supported so we know that at most 6 bytes per character is used
var start = fromIndex
var dstRemaining = dst.writeRemaining
while (start < toIndex && dstRemaining > 0) {
val numChars = minOf(toIndex - start, dstRemaining / 6).coerceAtLeast(1)
val dropLastChar = input[start + numChars - 1].isHighSurrogate()
val endIndexExclusive = when {
dropLastChar && numChars == 1 -> start + 2
dropLastChar -> start + numChars - 1
else -> start + numChars
}
val array1 = encoder.encode(input.substring(start, endIndexExclusive))
if (array1.length > dstRemaining) break
dst.writeFully(array1)
start = endIndexExclusive
dstRemaining -= array1.length
}
return start - fromIndex
}
public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) {
require(charset === Charsets.UTF_8)
// we only support UTF-8 so as far as input is UTF-8 encoded string then we simply copy bytes
dst.writePacket(input)
}
internal actual fun CharsetEncoder.encodeComplete(dst: Buffer): Boolean = true
// ----------------------------------------------------------------------
public actual abstract class CharsetDecoder(internal val _charset: Charset)
private data class CharsetDecoderImpl(private val charset: Charset) : CharsetDecoder(charset)
public actual val CharsetDecoder.charset: Charset get() = _charset
internal actual fun CharsetDecoder.decodeBuffer(
input: Buffer,
out: Appendable,
lastBuffer: Boolean,
max: Int
): Int {
if (max == 0) return 0
val decoder = Decoder(charset.name)
val copied: Int
input.readDirectInt8Array { view ->
val result = view.decodeBufferImpl(decoder, max)
out.append(result.charactersDecoded)
copied = result.bytesConsumed
result.bytesConsumed
}
return copied
}
public actual fun CharsetDecoder.decode(input: Input, dst: Appendable, max: Int): Int {
val decoder = Decoder(charset.name, true)
var charactersCopied = 0
// use decode stream while we have remaining characters count > buffer size in bytes
// it is much faster than using decodeBufferImpl
input.takeWhileSize { buffer ->
val rem = max - charactersCopied
val bufferSize = buffer.readRemaining
if (rem < bufferSize) return@takeWhileSize 0
buffer.readDirectInt8Array { view ->
val decodedText = decodeWrap {
decoder.decodeStream(view, stream = true)
}
dst.append(decodedText)
charactersCopied += decodedText.length
view.byteLength
}
when {
charactersCopied == max -> {
val tail = try {
decoder.decode()
} catch (_: dynamic) {
""
}
if (tail.isNotEmpty()) {
// if we have a trailing byte then we can't handle this chunk via fast-path
// because we don't know how many bytes in the end we need to preserve
buffer.rewind(bufferSize)
}
0
}
charactersCopied < max -> MAX_CHARACTERS_SIZE_IN_BYTES
else -> 0
}
}
if (charactersCopied < max) {
var size = 1
input.takeWhileSize(1) { buffer ->
val rc = buffer.readDirectInt8Array { view ->
val result = view.decodeBufferImpl(decoder, max - charactersCopied)
dst.append(result.charactersDecoded)
charactersCopied += result.charactersDecoded.length
result.bytesConsumed
}
when {
rc > 0 -> size = 1
size == MAX_CHARACTERS_SIZE_IN_BYTES -> size = 0
else -> size++
}
size
}
}
return charactersCopied
}
public actual fun CharsetDecoder.decodeExactBytes(input: Input, inputLength: Int): String {
if (inputLength == 0) return ""
if (input.headRemaining >= inputLength) {
val decoder = Decoder(charset._name, true)
val head = input.head
val view = input.headMemory.view
val text = decodeWrap {
val subView: ArrayBufferView = when {
head.readPosition == 0 && inputLength == view.byteLength -> view
else -> DataView(view.buffer, view.byteOffset + head.readPosition, inputLength)
}
decoder.decode(subView)
}
input.discardExact(inputLength)
return text
}
return decodeExactBytesSlow(input, inputLength)
}
// -----------------------------------------------------------
public actual object Charsets {
public actual val UTF_8: Charset = CharsetImpl("UTF-8")
public actual val ISO_8859_1: Charset = CharsetImpl("ISO-8859-1")
}
private data class CharsetImpl(val name: String) : Charset(name) {
override fun newEncoder(): CharsetEncoder = CharsetEncoderImpl(this)
override fun newDecoder(): CharsetDecoder = CharsetDecoderImpl(this)
}
public actual open class MalformedInputException actual constructor(message: String) : Throwable(message)
private fun CharsetDecoder.decodeExactBytesSlow(input: Input, inputLength: Int): String {
val decoder = Decoder(charset.name, true)
var inputRemaining = inputLength
val sb = StringBuilder(inputLength)
decodeWrap {
input.takeWhileSize(6) { buffer ->
val chunkSize = buffer.readRemaining
val size = minOf(chunkSize, inputRemaining)
val text = when {
buffer.readPosition == 0 && buffer.memory.view.byteLength == size -> decoder.decodeStream(
buffer.memory.view,
true
)
else -> decoder.decodeStream(
Int8Array(
buffer.memory.view.buffer,
buffer.memory.view.byteOffset + buffer.readPosition,
size
),
true
)
}
sb.append(text)
buffer.discardExact(size)
inputRemaining -= size
if (inputRemaining > 0) 6 else 0
}
if (inputRemaining > 0) {
input.takeWhile { buffer ->
val chunkSize = buffer.readRemaining
val size = minOf(chunkSize, inputRemaining)
val text = when {
buffer.readPosition == 0 && buffer.memory.view.byteLength == size -> {
decoder.decode(buffer.memory.view)
}
else -> decoder.decodeStream(
Int8Array(
buffer.memory.view.buffer,
buffer.memory.view.byteOffset + buffer.readPosition,
size
),
true
)
}
sb.append(text)
buffer.discardExact(size)
inputRemaining -= size
true
}
}
sb.append(decoder.decode())
}
if (inputRemaining > 0) {
throw EOFException(
"Not enough bytes available: had only ${inputLength - inputRemaining} instead of $inputLength"
)
}
return sb.toString()
}
| ktor-io/js/src/io/ktor/utils/io/charsets/CharsetJS.kt | 2678601138 |
package eu.kanade.tachiyomi.data.backup.legacy.serializer
import eu.kanade.tachiyomi.data.backup.legacy.models.DHistory
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
/**
* JSON Serializer used to write / read [DHistory] to / from json
*/
object HistoryTypeSerializer : KSerializer<DHistory> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("History")
override fun serialize(encoder: Encoder, value: DHistory) {
encoder as JsonEncoder
encoder.encodeJsonElement(
buildJsonArray {
add(value.url)
add(value.lastRead)
}
)
}
override fun deserialize(decoder: Decoder): DHistory {
decoder as JsonDecoder
val array = decoder.decodeJsonElement().jsonArray
return DHistory(
url = array[0].jsonPrimitive.content,
lastRead = array[1].jsonPrimitive.long
)
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/backup/legacy/serializer/HistoryTypeSerializer.kt | 380822317 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
import core.linux.*
val GLX_EXT_swap_control = "GLXEXTSwapControl".nativeClassGLX("GLX_EXT_swap_control", EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT_swap_control")} extension.
This extension allows an application to specify a minimum periodicity of color buffer swaps, measured in video frame periods, for a particular drawable.
It also allows an application to query the swap interval and the implementation-dependent maximum swap interval of a drawable.
"""
IntConstant(
"The current swap interval and implementation-dependent max swap interval for a particular drawable.",
"SWAP_INTERVAL_EXT"..0x20F1,
"MAX_SWAP_INTERVAL_EXT"..0x20F2
)
void(
"SwapIntervalEXT",
"""
Specifies the minimum number of video frame periods per buffer swap for a particular GLX drawable (e.g. a value of two means that the color buffers will
be swapped at most every other video frame). The interval takes effect when #SwapBuffers() is first called on the drawable subsequent to the
{@code glXSwapIntervalEXT} call.
""",
DISPLAY,
GLXDrawable("drawable", "the drawable"),
int("interval", "the swap interval")
)
} | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GLX_EXT_swap_control.kt | 496652288 |
package com.taskworld.kxandroid
fun runOnBackgroundThread(f: () -> Unit) {
Thread() {
f()
}.start()
}
| kxandroid/src/main/kotlin/com/taskworld/kxandroid/Concurrent.kt | 3834765950 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val OES_texture_float = EXT_FLAG.nativeClassGLES("OES_texture_float", postfix = OES) {
documentation =
"""
When true, the $registryLink extension is supported.
These extensions add texture formats with 16- (aka half float) and 32-bit floating-point components. The 32-bit floating-point components are in the
standard IEEE float format. The 16-bit floating-point components have 1 sign bit, 5 exponent bits, and 10 mantissa bits. Floating-point components are
clamped to the limits of the range representable by their format.
The OES_texture_float extension string indicates that the implementation supports 32-bit floating pt texture formats.
Both these extensions only require NEAREST magnification filter and NEAREST, and NEAREST_MIPMAP_NEAREST minification filters to be supported.
"""
}
val OES_texture_half_float = "OESTextureHalfFloat".nativeClassGLES("OES_texture_half_float", postfix = OES) {
documentation =
"""
Native bindings to the ${registryLink("OES_texture_float")} extension.
These extensions add texture formats with 16- (aka half float) and 32-bit floating-point components. The 32-bit floating-point components are in the
standard IEEE float format. The 16-bit floating-point components have 1 sign bit, 5 exponent bits, and 10 mantissa bits. Floating-point components are
clamped to the limits of the range representable by their format.
The OES_texture_half_float extension string indicates that the implementation supports 16-bit floating pt texture formats.
Both these extensions only require NEAREST magnification filter and NEAREST, and NEAREST_MIPMAP_NEAREST minification filters to be supported.
"""
IntConstant(
"Accepted by the {@code type} parameter of TexImage2D, TexSubImage2D, TexImage3D, and TexSubImage3D.",
"HALF_FLOAT_OES"..0x8D61
)
} | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_texture_float.kt | 2434333012 |
/*
*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fredboat.command.moderation
import com.fredboat.sentinel.SentinelExchanges
import com.fredboat.sentinel.entities.ModRequest
import com.fredboat.sentinel.entities.ModRequestType
import fredboat.commandmeta.abs.CommandContext
import fredboat.messaging.internal.Context
import fredboat.perms.Permission
import fredboat.sentinel.User
import fredboat.util.ArgumentUtil
import fredboat.util.TextUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.amqp.core.MessageDeliveryMode
import reactor.core.publisher.Mono
/**
* Created by napster on 27.01.18.
*
* Unban a user.
*/
class UnbanCommand(name: String, vararg aliases: String) : DiscordModerationCommand(name, *aliases) {
companion object {
private val log: Logger = LoggerFactory.getLogger(UnbanCommand::class.java)
}
override fun modAction(args: DiscordModerationCommand.ModActionInfo): Mono<Unit> {
return args.context.sentinel.genericMonoSendAndReceive<String, Unit>(
exchange = SentinelExchanges.REQUESTS,
request = ModRequest(
guildId = args.context.guild.id,
userId = args.targetUser.id,
type = ModRequestType.UNBAN,
reason = args.formattedReason
),
routingKey = args.context.routingKey,
mayBeEmpty = true,
deliveryMode = MessageDeliveryMode.PERSISTENT,
transform = {}
)
}
override fun requiresMember() = false
override fun onSuccess(args: DiscordModerationCommand.ModActionInfo): () -> Unit {
val successOutput = args.context.i18nFormat("unbanSuccess",
args.targetUser.asMention + " " + TextUtils.escapeAndDefuse(args.targetAsString()))
return {
args.context.replyWithName(successOutput)
}
}
override fun onFail(args: DiscordModerationCommand.ModActionInfo): (t: Throwable) -> Unit {
val escapedTargetName = TextUtils.escapeAndDefuse(args.targetAsString())
return { t ->
val context = args.context
if (t is IllegalArgumentException) { //user was not banned in this guild (see GuildController#unban(String) handling of the response)
context.reply(context.i18nFormat("modUnbanFailNotBanned", args.targetUser.asMention))
} else {
log.error("Failed to unban ${args.targetUser} from ${args.context.guild}")
context.replyWithName(context.i18nFormat("modUnbanFail",
args.targetUser.asMention + " " + escapedTargetName))
}
}
}
override suspend fun fromFuzzySearch(context: CommandContext, searchTerm: String): Mono<User> {
return fetchBanlist(context)
.collectList()
.map { banlist ->
ArgumentUtil.checkSingleFuzzyUserSearchResult(
banlist.map { User(it.user) }, context, searchTerm, true).orElse(null)
}
}
override suspend fun checkPreconditionWithFeedback(user: User, context: CommandContext): Mono<Boolean> {
return fetchBanlist(context)
.collectList()
.map { banlist ->
if (banlist.stream().noneMatch { it.user.id == user.id }) {
context.reply(context.i18nFormat("modUnbanFailNotBanned", user.asMention))
return@map false
}
true
}
}
override suspend fun checkAuthorizationWithFeedback(args: DiscordModerationCommand.ModActionInfo): Boolean {
return args.context.run {
checkInvokerPermissionsWithFeedback(Permission.BAN_MEMBERS)
&& checkSelfPermissionsWithFeedback(Permission.BAN_MEMBERS)
}
}
//don't dm users upon being unbanned
override fun dmForTarget(args: DiscordModerationCommand.ModActionInfo): String? = null
override fun help(context: Context): String {
return ("{0}{1} userId OR username\n"
+ "#" + context.i18n("helpUnbanCommand"))
}
}
| FredBoat/src/main/java/fredboat/command/moderation/UnbanCommand.kt | 3661591788 |
package i_introduction._2_Named_Arguments
import util.*
import i_introduction._1_Java_To_Kotlin_Converter.task1
fun todoTask2(): Nothing = TODO(
"""
Task 2.
Implement the same logic as in 'task1' again through the library method 'joinToString()'.
Change values of some of the 'joinToString' arguments.
Use default and named arguments to improve the readability of the function invocation.
""",
documentation = doc2(),
references = { collection: Collection<Int> -> task1(collection); collection.joinToString() })
fun task2(collection: Collection<Int>): String {
return collection.joinToString (prefix = "{", postfix = "}")
}
| src/i_introduction/_2_Named_Arguments/NamedArguments.kt | 3711621943 |
/*
* Copyright 2000-2017 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 com.intellij.java.lexer
import com.intellij.lang.java.lexer.JavaLexer
import com.intellij.pom.java.LanguageLevel
import com.intellij.util.text.ByteArrayCharSequence
import com.intellij.util.text.CharArrayCharSequence
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class JavaKeywordsTest {
@Test fun hardAndSoft() {
assertTrue(JavaLexer.isKeyword("char", LanguageLevel.JDK_1_9))
assertFalse(JavaLexer.isSoftKeyword("char", LanguageLevel.JDK_1_9))
assertFalse(JavaLexer.isKeyword("module", LanguageLevel.JDK_1_9))
assertTrue(JavaLexer.isSoftKeyword("module", LanguageLevel.JDK_1_9))
}
@Test fun sequences() {
assertTrue(JavaLexer.isSoftKeyword(ByteArrayCharSequence.convertToBytesIfPossible("module"), LanguageLevel.JDK_1_9))
assertTrue(JavaLexer.isSoftKeyword(CharArrayCharSequence("[module]".toCharArray(), 1, 7), LanguageLevel.JDK_1_9))
}
@Test fun nullTolerance() {
assertFalse(JavaLexer.isKeyword(null, LanguageLevel.JDK_1_3))
assertFalse(JavaLexer.isSoftKeyword(null, LanguageLevel.JDK_1_9))
}
} | java/java-tests/testSrc/com/intellij/java/lexer/JavaKeywordsTest.kt | 2535998042 |
package org.wikipedia.page.leadimages
import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import org.wikipedia.R
import org.wikipedia.databinding.ViewPageHeaderBinding
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.GradientUtil
import org.wikipedia.views.FaceAndColorDetectImageView
import org.wikipedia.views.LinearLayoutOverWebView
import org.wikipedia.views.ObservableWebView
class PageHeaderView : LinearLayoutOverWebView, ObservableWebView.OnScrollChangeListener {
interface Callback {
fun onImageClicked()
fun onCallToActionClicked()
}
private val binding = ViewPageHeaderBinding.inflate(LayoutInflater.from(context), this)
var callback: Callback? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
init {
binding.viewPageHeaderImageGradientBottom.background = GradientUtil.getPowerGradient(R.color.black38, Gravity.BOTTOM)
binding.viewPageHeaderImage.setOnClickListener {
callback?.onImageClicked()
}
binding.callToActionContainer.setOnClickListener {
callback?.onCallToActionClicked()
}
}
override fun onScrollChanged(oldScrollY: Int, scrollY: Int, isHumanScroll: Boolean) {
updateScroll(scrollY)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
updateScroll()
}
private fun updateScroll(scrollY: Int = -translationY.toInt()) {
binding.viewPageHeaderImage.translationY = 0f
translationY = -height.coerceAtMost(scrollY).toFloat()
}
fun hide() {
visibility = GONE
}
fun show() {
layoutParams = CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.leadImageHeightForDevice(context))
visibility = VISIBLE
}
fun getImageView(): FaceAndColorDetectImageView {
return binding.viewPageHeaderImage
}
fun setUpCallToAction(callToActionText: String?) {
if (callToActionText != null) {
binding.callToActionContainer.visibility = VISIBLE
binding.callToActionText.text = callToActionText
binding.viewPageHeaderImageGradientBottom.visibility = VISIBLE
} else {
binding.callToActionContainer.visibility = GONE
binding.viewPageHeaderImageGradientBottom.visibility = GONE
}
}
fun loadImage(url: String?) {
if (url.isNullOrEmpty()) {
hide()
} else {
show()
binding.viewPageHeaderImage.loadImage(Uri.parse(url))
}
}
}
| app/src/main/java/org/wikipedia/page/leadimages/PageHeaderView.kt | 2857734233 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.settings.internal
import android.database.Cursor
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementBinder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementWrapper
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.WhereStatementBinder
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.arch.db.stores.internal.StoreFactory
import org.hisp.dhis.android.core.settings.ProgramConfigurationSetting
import org.hisp.dhis.android.core.settings.ProgramConfigurationSettingTableInfo
@Suppress("MagicNumber")
internal object ProgramConfigurationSettingStore {
private val BINDER =
StatementBinder<ProgramConfigurationSetting> { o: ProgramConfigurationSetting, w: StatementWrapper ->
w.bind(1, o.uid())
w.bind(2, o.completionSpinner())
w.bind(3, o.optionalSearch())
}
private val WHERE_UPDATE_BINDER =
WhereStatementBinder<ProgramConfigurationSetting> { _: ProgramConfigurationSetting, _: StatementWrapper ->
}
private val WHERE_DELETE_BINDER =
WhereStatementBinder<ProgramConfigurationSetting> { _: ProgramConfigurationSetting, _: StatementWrapper ->
}
fun create(databaseAdapter: DatabaseAdapter?): ObjectWithoutUidStore<ProgramConfigurationSetting> {
return StoreFactory.objectWithoutUidStore(
databaseAdapter!!, ProgramConfigurationSettingTableInfo.TABLE_INFO,
BINDER,
WHERE_UPDATE_BINDER,
WHERE_DELETE_BINDER
) { cursor: Cursor -> ProgramConfigurationSetting.create(cursor) }
}
}
| core/src/main/java/org/hisp/dhis/android/core/settings/internal/ProgramConfigurationSettingStore.kt | 3534538490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.