content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.reporting import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import java.io.File class ReportMissingOrExcessiveInlineHint : AnAction() { private val text = "Report Missing or Excessive Inline Hint" private val description = "Text line at caret will be anonymously reported to our servers" companion object { private val LOG = Logger.getInstance(ReportMissingOrExcessiveInlineHint::class.java) } init { val presentation = templatePresentation presentation.text = text presentation.description = description } private val recorderId = "inline-hints-reports" private val file = File(PathManager.getTempPath(), recorderId) override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = false if (!isHintsEnabled()) return CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val range = getCurrentLineRange(editor) if (editor.getInlays(range).isNotEmpty()) { e.presentation.isEnabledAndVisible = true } } override fun actionPerformed(e: AnActionEvent) { val project = CommonDataKeys.PROJECT.getData(e.dataContext)!! val editor = CommonDataKeys.EDITOR.getData(e.dataContext)!! val document = editor.document val range = getCurrentLineRange(editor) val inlays = editor.getInlays(range) if (inlays.isNotEmpty()) { val line = document.getText(range) reportInlays(line.trim(), inlays) showHint(project) } } private fun reportInlays(text: String, inlays: List<Inlay>) { val hintManager = ParameterHintsPresentationManager.getInstance() val hints = inlays.mapNotNull { hintManager.getHintText(it) } trySend(text, hints) } private fun trySend(text: String, inlays: List<String>) { val report = InlayReport(text, inlays) writeToFile(createReportLine(recorderId, report)) trySendFileInBackground() } private fun trySendFileInBackground() { LOG.debug("File: ${file.path} Length: ${file.length()}") if (!file.exists() || file.length() == 0L) return ApplicationManager.getApplication().executeOnPooledThread { val text = file.readText() LOG.debug("File text $text") if (StatsSender.send(text, compress = false)) { file.delete() LOG.debug("File deleted") } } } private fun showHint(project: Project) { val notification = Notification( "Inline Hints", "Inline Hints Reporting", "Problematic inline hint was reported", NotificationType.INFORMATION ) notification.notify(project) } private fun writeToFile(line: String) { if (!file.exists()) { file.createNewFile() } file.appendText(line) } private fun getCurrentLineRange(editor: Editor): TextRange { val offset = editor.caretModel.currentCaret.offset val document = editor.document val line = document.getLineNumber(offset) return TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)) } } private fun isHintsEnabled() = EditorSettingsExternalizable.getInstance().isShowParameterNameHints private fun Editor.getInlays(range: TextRange): List<Inlay> { return inlayModel.getInlineElementsInRange(range.startOffset, range.endOffset) } private class InlayReport(@JvmField var text: String, @JvmField var inlays: List<String>)
java/java-impl/src/com/intellij/reporting/ReportMissingOrExcessiveInlineHint.kt
2583818070
package com.github.pgutkowski.kgraphql.schema.introspection /** * GraphQL introspection system defines __Type to represent all of TypeKinds * If some field does not apply to given type, it returns null */ interface __Type { val kind: TypeKind val name : String? val description : String //OBJECT and INTERFACE only val fields : List<__Field>? //OBJECT only val interfaces : List<__Type>? //INTERFACE and UNION only val possibleTypes : List<__Type>? //ENUM only val enumValues : List<__EnumValue>? //INPUT_OBJECT only val inputFields : List<__InputValue>? //NON_NULL and LIST only val ofType : __Type? } fun __Type.asString() = buildString { append(kind) append(" : ") append(name) append(" ") if(fields != null){ append("[") fields?.forEach { field -> append(field.name).append(" : ").append(field.type.name ?: field.type.kind).append(" ") } append("]") } if(ofType != null){ append(" => ").append(ofType?.name) } }
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/introspection/__Type.kt
3761609677
package com.jraska.github.client import org.junit.rules.ExternalResource class EnableConfigRule( private val key: String, private val value: Any ) : ExternalResource() { lateinit var revert: FakeConfig.RevertSet override fun before() { revert = TestUITestApp.get().appComponent.config.set(key, value) } override fun after() { revert.revert() } }
app/src/androidTest/java/com/jraska/github/client/EnableConfigRule.kt
602009236
package net.nemerosa.ontrack.extension.github.ingestion.extensions.links import net.nemerosa.ontrack.model.annotations.APIDescription /** * Input for the links for a build identified by its name */ @APIDescription("Input for the links for a build identified by its name") class GitHubIngestionLinksByBuildNameInput( owner: String, repository: String, buildLinks: List<GitHubIngestionLink>, addOnly: Boolean, @APIDescription("Name of the build") val buildName: String, ) : AbstractGitHubIngestionLinksInput( owner, repository, buildLinks, addOnly, ) { override fun toPayload() = GitHubIngestionLinksPayload( owner = owner, repository = repository, buildLinks = buildLinks, buildName = buildName, addOnly = addOnly ?: GitHubIngestionLinksPayload.ADD_ONLY_DEFAULT, ) }
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/links/GitHubIngestionLinksByBuildNameInput.kt
3251193066
package net.nemerosa.ontrack.git.model import org.eclipse.jgit.revwalk.RevCommit class GitRange( val from: RevCommit, val to: RevCommit )
ontrack-git/src/main/java/net/nemerosa/ontrack/git/model/GitRange.kt
1655193828
package it.liceoarzignano.bold.utils import android.content.Context import android.content.pm.PackageManager import android.net.ConnectivityManager import android.os.Build import android.util.Log import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import it.liceoarzignano.bold.BuildConfig object SystemUtils { private const val TAG = "SystemUtils" val isNotLegacy: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP fun hasGDrive(context: Context): Boolean = try { val info = context.packageManager .getPackageInfo("com.google.android.apps.docs", 0) info.applicationInfo.enabled } catch (e: PackageManager.NameNotFoundException) { // Gotta catch 'em all false } fun hasNoInternetConnection(context: Context): Boolean { val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return manager.activeNetworkInfo == null } fun hasNoGMS(context: Context): Boolean = GoogleApiAvailability.getInstance() .isGooglePlayServicesAvailable(context) != ConnectionResult.SUCCESS fun getSafetyNetApiKey(context: Context): String = try { val info = context.packageManager .getApplicationInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_META_DATA) val metadata = info.metaData val apiKey = metadata.getString("com.google.android.safetynet.ATTEST_API_KEY") apiKey ?: "" } catch (e: PackageManager.NameNotFoundException) { Log.e(TAG, e.message) "" } }
app/src/main/kotlin/it/liceoarzignano/bold/utils/SystemUtils.kt
4223411505
package net.nemerosa.ontrack.model.extension; import com.fasterxml.jackson.annotation.JsonProperty /** * Options for a feature * * @property isGui Does the extension provides some web components? * @property dependencies List of extensions IDs this feature depends on. */ class ExtensionFeatureOptions( @JsonProperty("gui") val isGui: Boolean = false, val dependencies: Set<String> ) { companion object { /** * Default options */ @JvmField val DEFAULT = ExtensionFeatureOptions( isGui = false, dependencies = emptySet() ) } /** * With GUI */ fun withGui(isGui: Boolean) = ExtensionFeatureOptions(isGui, dependencies) /** * List of extensions IDs this feature depends on. */ fun withDependencies(dependencies: Set<String>) = ExtensionFeatureOptions(isGui, dependencies) /** * Adds a dependency */ fun withDependency(feature: ExtensionFeature) = ExtensionFeatureOptions( isGui, dependencies + feature.id ) }
ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.kt
2384949767
package no.tornadofx.fxsample.springexample import javafx.application.Application import org.springframework.context.support.ClassPathXmlApplicationContext import tornadofx.* import kotlin.reflect.KClass /** * Created by ronsmits on 11/03/2017. */ class SpringExampleApp : App(SpringExampleView::class) { init { val springContext = ClassPathXmlApplicationContext("beans.xml") FX.dicontainer = object : DIContainer { override fun <T : Any> getInstance(type: KClass<T>): T = springContext.getBean(type.java) } } } fun main(args: Array<String>) { Application.launch(SpringExampleApp::class.java, *args) }
spring-example/src/main/kotlin/no/tornadofx/fxsample/springexample/SpringExampleApp.kt
2268780337
package treehou.se.habit.dagger class RxPresenterEvent { enum class PresenterEvent { LOAD, SUBSCRIBE, UNSUBSCRIBE, UNLOAD } }
mobile/src/main/java/treehou/se/habit/dagger/RxPresenterEvent.kt
1559089117
/* * 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 * * 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.materialstudies.reply.ui.compose import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.transition.Slide import androidx.transition.TransitionManager import com.google.android.material.transition.MaterialContainerTransform import com.materialstudies.reply.R import com.materialstudies.reply.data.Account import com.materialstudies.reply.data.AccountStore import com.materialstudies.reply.data.Email import com.materialstudies.reply.data.EmailStore import com.materialstudies.reply.databinding.ComposeRecipientChipBinding import com.materialstudies.reply.databinding.FragmentComposeBinding import com.materialstudies.reply.util.themeColor import kotlin.LazyThreadSafetyMode.NONE /** * A [Fragment] which allows for the composition of a new email. */ class ComposeFragment : Fragment() { private lateinit var binding: FragmentComposeBinding private val args: ComposeFragmentArgs by navArgs() // The new email being composed. private val composeEmail: Email by lazy(NONE) { // Get the id of the email being replied to, if any, and either create an new empty email // or a new reply email. val id = args.replyToEmailId if (id == -1L) EmailStore.create() else EmailStore.createReplyTo(id) } // Handle closing an expanded recipient card when on back is pressed. private val closeRecipientCardOnBackPressed = object : OnBackPressedCallback(false) { var expandedChip: View? = null override fun handleOnBackPressed() { expandedChip?.let { collapseChip(it) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requireActivity().onBackPressedDispatcher.addCallback(this, closeRecipientCardOnBackPressed) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentComposeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.run { closeIcon.setOnClickListener { findNavController().navigateUp() } email = composeEmail composeEmail.nonUserAccountRecipients.forEach { addRecipientChip(it) } senderSpinner.adapter = ArrayAdapter( senderSpinner.context, R.layout.spinner_item_layout, AccountStore.getAllUserAccounts().map { it.email } ) // Set transitions here so we are able to access Fragment's binding views. enterTransition = MaterialContainerTransform().apply { // Manually add the Views to be shared since this is not a standard Fragment to // Fragment shared element transition. startView = requireActivity().findViewById(R.id.fab) endView = emailCardView duration = resources.getInteger(R.integer.reply_motion_duration_large).toLong() scrimColor = Color.TRANSPARENT containerColor = requireContext().themeColor(R.attr.colorSurface) startContainerColor = requireContext().themeColor(R.attr.colorSecondary) endContainerColor = requireContext().themeColor(R.attr.colorSurface) } returnTransition = Slide().apply { duration = resources.getInteger(R.integer.reply_motion_duration_medium).toLong() addTarget(R.id.email_card_view) } } } /** * Add a chip for the given [Account] to the recipients chip group. * * This method also sets up the ability for expanding/collapsing the chip into a recipient * address selection dialog. */ private fun addRecipientChip(acnt: Account) { binding.recipientChipGroup.run { val chipBinding = ComposeRecipientChipBinding.inflate( LayoutInflater.from(context), this, false ).apply { account = acnt root.setOnClickListener { // Bind the views in the expanded card view to this account's details when // clicked and expand. binding.focusedRecipient = acnt expandChip(it) } } addView(chipBinding.root) } } /** * Expand the recipient [chip] into a popup with a list of contact addresses to choose from. */ private fun expandChip(chip: View) { // Configure the analogous collapse transform back to the recipient chip. This should // happen when the card is clicked, any region outside of the card (the card's transparent // scrim) is clicked, or when the back button is pressed. binding.run { recipientCardView.setOnClickListener { collapseChip(chip) } recipientCardScrim.visibility = View.VISIBLE recipientCardScrim.setOnClickListener { collapseChip(chip) } } closeRecipientCardOnBackPressed.expandedChip = chip closeRecipientCardOnBackPressed.isEnabled = true val transform = MaterialContainerTransform().apply { startView = chip endView = binding.recipientCardView scrimColor = Color.TRANSPARENT // Have the transform match the endView card's native elevation as closely as possible. endElevation = requireContext().resources.getDimension( R.dimen.email_recipient_card_popup_elevation_compat ) // Avoid having this transform from running on both the start and end views by setting // its target to the endView. addTarget(binding.recipientCardView) } TransitionManager.beginDelayedTransition(binding.composeConstraintLayout, transform) binding.recipientCardView.visibility = View.VISIBLE // Using INVISIBLE instead of GONE ensures the chip's parent layout won't shift during // the transition due to chips being effectively removed. chip.visibility = View.INVISIBLE } /** * Collapse the recipient card back into its [chip] form. */ private fun collapseChip(chip: View) { // Remove the scrim view and on back pressed callbacks binding.recipientCardScrim.visibility = View.GONE closeRecipientCardOnBackPressed.expandedChip = null closeRecipientCardOnBackPressed.isEnabled = false val transform = MaterialContainerTransform().apply { startView = binding.recipientCardView endView = chip scrimColor = Color.TRANSPARENT startElevation = requireContext().resources.getDimension( R.dimen.email_recipient_card_popup_elevation_compat ) addTarget(chip) } TransitionManager.beginDelayedTransition(binding.composeConstraintLayout, transform) chip.visibility = View.VISIBLE binding.recipientCardView.visibility = View.INVISIBLE } }
Reply/app/src/main/java/com/materialstudies/reply/ui/compose/ComposeFragment.kt
2235090158
package com.hewking.custom import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.Log import android.view.View /** * Created by test on 2018/1/18. */ class EclipseAnimView : View{ constructor(context : Context, attrs : AttributeSet?):super(context,attrs) { } constructor(context: Context) : this(context,null) { } private val mPaint : Paint by lazy { Paint().apply { color = Color.YELLOW strokeWidth = 2f isAntiAlias = true style = Paint.Style.FILL } } private var circleCanvas : Canvas? = null private var circleBitmap : Bitmap? = null init{ mPaint } private var mWidth = 0 private var mHeight = 0 override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) mWidth = w mHeight = h circleBitmap?.recycle() if (measuredWidth != 0 && measuredHeight != 0) { circleBitmap = Bitmap.createBitmap(measuredWidth,measuredHeight,Bitmap.Config.ARGB_8888) circleCanvas = Canvas(circleBitmap) } Log.d("EclipseAnimView : " ,"onSizeChanged :${measuredWidth}") } override fun onAttachedToWindow() { super.onAttachedToWindow() // 开启动画 startAnimator() } private var startAnimator: ValueAnimator? = null private var fraction : Float = 0f private var count : Int = 0 private var eclipseEnd = false private fun startAnimator() { if (startAnimator == null) { startAnimator = ValueAnimator.ofFloat(0f,1f).apply { repeatMode = ValueAnimator.RESTART repeatCount = 2 duration = 2000 addUpdateListener { fraction = it.animatedValue as Float postInvalidateOnAnimation() } addListener(object : AnimatorListenerAdapter(){ override fun onAnimationEnd(animation: Animator?) { eclipseEnd = true fraction = 0f ValueAnimator.ofFloat(0f,4f).apply { duration = 1000 repeatCount = 1 repeatMode = ValueAnimator.RESTART addUpdateListener({ fraction = it.animatedValue as Float postInvalidateOnAnimation() }) start() } } override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) count ++ Log.d("EclipseAnimView : " ,"count :${count}") } }) start() } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() startAnimator?.cancel() circleBitmap?.recycle() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) } val radius = 100f @SuppressLint("DrawAllocation") override fun onDraw(canvas: Canvas) { super.onDraw(canvas) Log.d("EclipseAnimView : " ,"onDraw :${measuredWidth}") canvas.drawARGB(255,23,12,53) if (eclipseEnd) { canvas.save() mPaint.color = Color.YELLOW mPaint.style = Paint.Style.STROKE canvas.translate(mWidth/2f,mHeight/2f) val rectf = RectF(-radius,-radius,radius,radius) canvas.drawArc(rectf,-90 * (1 + fraction),90f ,false,mPaint) if (fraction >= 4) { mPaint.style = Paint.Style.FILL canvas.drawCircle(rectf.centerX(),rectf.centerY(),radius,mPaint) } canvas.restore() } else { circleCanvas?.let { it.save() it.drawARGB(255,23,12,53) mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) it.drawPaint(mPaint) mPaint.xfermode = null it.translate(mWidth / 2f , mHeight / 2f) mPaint.color = Color.YELLOW it.drawCircle(0f,0f,radius,mPaint) mPaint.color = Color.TRANSPARENT mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OUT) Log.d("EclipseAnimView : " ,"fraction :${if(count % 2 == 0)fraction else -fraction}") it.drawCircle((if(count % 2 == 0)fraction else -fraction) * radius * 2,0f,radius,mPaint) mPaint.xfermode = null it.restore() canvas.drawBitmap(circleBitmap,0f,0f,null) } } } }
app/src/main/java/com/hewking/custom/EclipseAnimView.kt
3621175667
package api data class TreeNode<T>(var value: T? = null) { var left: TreeNode<T>? = null var right: TreeNode<T>? = null constructor() : this(null) }
kotlin/src/main/kotlin/api/TreeNode.kt
903644071
package com.shareyourproxy.api.rx import android.content.Context import com.google.android.gms.analytics.GoogleAnalytics import com.google.android.gms.analytics.HitBuilders import com.google.android.gms.analytics.Tracker import com.shareyourproxy.R import com.shareyourproxy.api.domain.model.ChannelType import com.shareyourproxy.api.domain.model.Group import com.shareyourproxy.api.domain.model.User import com.shareyourproxy.api.rx.RxHelper.singleObserveMain import rx.Single import rx.Subscription /** * Log Google Analytics instances. */ class RxGoogleAnalytics constructor(context: Context) { val analytics: GoogleAnalytics = GoogleAnalytics.getInstance(context) val tracker: Tracker = analytics.newTracker(R.xml.global_tracker) fun userAdded(newUser: User): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("Add User").setAction("Google Plus").setLabel(newUser.fullName()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun channelAdded(channelType: ChannelType): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("Channel Event").setAction("Add Channel").setLabel(channelType.label).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun channelEdited(oldChannelType: ChannelType): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("Channel Event").setAction("Edit Channel").setLabel(oldChannelType.label).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun userProfileViewed(user: User): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("User Event").setAction("LoggedInUser Profile View").setLabel(user.fullName()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun contactProfileViewed(user: User): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("User Event").setAction("Contact Profile View").setLabel(user.fullName()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun userContactAdded(user: User): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("User Event").setAction("User Contact Added").setLabel(user.fullName()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun userContactRemoved(user: User): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("User Event").setAction("User Contact Removed").setLabel(user.fullName()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun shareLinkGenerated(group: Group): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("Share Link").setAction("Link Generated").setLabel(group.label()).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } fun contactGroupButtonHit(): Subscription { return rx.Single.create(Single.OnSubscribe<kotlin.Boolean> { singleSubscriber -> try { tracker.send(HitBuilders.EventBuilder().setCategory("User Event").setAction("Group Contact Button Hit").setValue(1).build()) singleSubscriber.onSuccess(true) } catch (e: Exception) { singleSubscriber.onError(e) } }).compose(singleObserveMain<Boolean>()).subscribe() } }
Application/src/main/kotlin/com/shareyourproxy/api/rx/RxGoogleAnalytics.kt
49202672
package com.soywiz.korfl.as3swf import com.soywiz.kds.* import com.soywiz.kmem.* import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* import com.soywiz.korio.util.* import kotlin.collections.set import kotlin.math.* @Suppress("unused") open class SWF : SWFTimelineContainer(), Extra by Extra.Mixin() { private var bytes: SWFData = SWFData() var signature: String? = null var version = 0 var fileLength = 0 var fileLengthCompressed = 0 var frameSize = SWFRectangle() var frameRate = 0.0 var frameCount = 0 var compressed = false var compressionMethod = COMPRESSION_METHOD_ZLIB companion object { const val COMPRESSION_METHOD_ZLIB = "zlib" const val COMPRESSION_METHOD_LZMA = "lzma" const val TOSTRING_FLAG_TIMELINE_STRUCTURE = 0x01 const val TOSTRING_FLAG_AVM1_BYTECODE = 0x02 protected const val FILE_LENGTH_POS = 4 protected const val COMPRESSION_START_POS = 8 } init { version = 10 fileLength = 0 fileLengthCompressed = 0 frameSize = SWFRectangle() frameRate = 50.0 frameCount = 1 compressed = true compressionMethod = COMPRESSION_METHOD_ZLIB } suspend fun loadBytes(bytes: ByteArray): SWF = this.apply { val ba = bytes.toFlash() this.bytes.length = 0 ba.position = 0 ba.readBytes(this.bytes) parse(this.bytes) } suspend fun parse(data: SWFData) { bytes = data parseHeader() parseTags(data, version) } suspend protected fun parseHeader() { signature = "" compressed = false compressionMethod = COMPRESSION_METHOD_ZLIB bytes.position = 0 var signatureByte = bytes.readUI8() when (signatureByte.toChar()) { 'C' -> { compressed = true compressionMethod = COMPRESSION_METHOD_ZLIB } 'Z' -> { compressed = true compressionMethod = COMPRESSION_METHOD_LZMA } 'F' -> { compressed = false } else -> throw Error("Not a SWF. First signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x43 or 0x5A or 0x46)") } signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt())) signatureByte = bytes.readUI8() if (signatureByte != 0x57) throw Error("Not a SWF. Second signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x57)") signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt())) signatureByte = bytes.readUI8() if (signatureByte != 0x53) throw Error("Not a SWF. Third signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x53)") signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt())) version = bytes.readUI8() fileLength = bytes.readUI32() fileLengthCompressed = bytes.length if (fileLength >= fileLengthCompressed * 4) invalidOp("something went wrong! fileLength >= fileLengthCompressed * 4 : $fileLength >= $fileLengthCompressed * 4") if (compressed) { // The following data (up to end of file) is compressed, if header has CWS or ZWS signature bytes.swfUncompress(compressionMethod, fileLength) } frameSize = bytes.readRECT() frameRate = bytes.readFIXED8() frameCount = bytes.readUI16() } override fun toString(indent: Int, flags: Int): String { val indent0 = " ".repeat(indent) val indent2 = " ".repeat(indent + 2) val indent4 = " ".repeat(indent + 4) var s: String = indent0 + "[SWF]\n" + indent2 + "Header:\n" + indent4 + "Version: " + version + "\n" + indent4 + "Compression: " s += if (compressed) { when (compressionMethod) { COMPRESSION_METHOD_ZLIB -> "ZLIB" COMPRESSION_METHOD_LZMA -> "LZMA" else -> "Unknown" } } else { "None" } return s + "\n" + indent4 + "FileLength: " + fileLength + "\n" + indent4 + "FileLengthCompressed: " + fileLengthCompressed + "\n" + indent4 + "FrameSize: " + frameSize.toStringSize() + "\n" + indent4 + "FrameRate: " + frameRate + "\n" + indent4 + "FrameCount: " + frameCount + super.toString(indent, 0) } } @Suppress("unused") class SWFData : BitArray() { companion object { fun dump(ba: FlashByteArray, length: Int, offset: Int = 0) { val posOrig = ba.position val pos = min(max(posOrig + offset, 0), ba.length - length) ba.position = pos var str = "[Dump] total length: " + ba.length + ", original position: " + posOrig for (i in 0 until length) { var b: String = ba.readUnsignedByte().toString(16) if (b.length == 1) { b = "0$b" } if (i % 16 == 0) { var addr: String = (pos + i).toString(16) addr = "00000000".substr(0, 8 - addr.length) + addr str += "\r$addr: " } b += " " str += b } ba.position = posOrig println(str) } } init { endian = Endian.LITTLE_ENDIAN } ///////////////////////////////////////////////////////// // Integers ///////////////////////////////////////////////////////// fun readSI8(): Int = resetBitsPending().readByte() fun writeSI8(value: Int) = resetBitsPending().writeByte(value) fun readSI16(): Int = resetBitsPending().readShort() fun writeSI16(value: Int) = resetBitsPending().writeShort(value) fun readSI32(): Int = resetBitsPending().readInt() fun writeSI32(value: Int) = resetBitsPending().writeInt(value) fun readUI8(): Int = resetBitsPending().readUnsignedByte() fun writeUI8(value: Int) = resetBitsPending().writeByte(value) fun writeUI8(value: Boolean) = writeUI8(if (value) 1 else 0) fun readUI16(): Int = resetBitsPending().readUnsignedShort() fun writeUI16(value: Int) = resetBitsPending().writeShort(value) fun readUI24(): Int { resetBitsPending() val loWord = readUnsignedShort() val hiByte = readUnsignedByte() return (hiByte shl 16) or loWord } fun writeUI24(value: Int) { resetBitsPending() writeShort(value and 0xffff) writeByte(value ushr 16) } fun readUI32(): Int = resetBitsPending().readUnsignedInt() fun writeUI32(value: Int) = resetBitsPending().writeUnsignedInt(value) ///////////////////////////////////////////////////////// // Fixed-point numbers ///////////////////////////////////////////////////////// fun readFIXED(): Double = resetBitsPending().readInt().toDouble() / 65536 //fun writeFIXED(value: Int) = writeFIXED(value.toDouble()) fun writeFIXED(value: Double) = resetBitsPending().writeInt((value * 65536).toInt()) fun readFIXED8(): Double = resetBitsPending().readShort().toDouble() / 256.0 fun writeFIXED8(value: Double) = resetBitsPending().writeShort((value * 256).toInt()) ///////////////////////////////////////////////////////// // Floating-point numbers ///////////////////////////////////////////////////////// fun readFLOAT(): Double = resetBitsPending().readFloat() fun writeFLOAT(value: Double) = resetBitsPending().writeFloat(value) fun readDOUBLE(): Double = resetBitsPending().readDouble() fun writeDOUBLE(value: Double) = resetBitsPending().writeDouble(value) fun readFLOAT16(): Double = Float16.intBitsToDouble(resetBitsPending().readUnsignedShort().toUShort()) fun writeFLOAT16(value: Double) = resetBitsPending().writeShort(Float16.doubleToIntBits(value).toInt()) ///////////////////////////////////////////////////////// // Encoded integer ///////////////////////////////////////////////////////// fun readEncodedU32(): Int { resetBitsPending() var result = readUnsignedByte() if ((result and 0x80) != 0) { result = (result and 0x7f) or (readUnsignedByte() shl 7) if ((result and 0x4000) != 0) { result = (result and 0x3fff) or (readUnsignedByte() shl 14) if ((result and 0x200000) != 0) { result = (result and 0x1fffff) or (readUnsignedByte() shl 21) if ((result and 0x10000000) != 0) { result = (result and 0xfffffff) or (readUnsignedByte() shl 28) } } } } return result } fun writeEncodedU32(_value: Int) { var value = _value while (true) { val v = value and 0x7f value = value ushr 7 if (value == 0) { writeUI8(v) break } writeUI8(v or 0x80) } } ///////////////////////////////////////////////////////// // Bit values ///////////////////////////////////////////////////////// fun readUB(bits: Int): Int = readBits(bits) fun writeUB(bits: Int, value: Int) = writeBits(bits, value) fun writeUB(bits: Int, value: Boolean) = writeUB(bits, if (value) 1 else 0) fun readSB(bits: Int): Int { val shift = 32 - bits return (readBits(bits) shl shift) shr shift } fun writeSB(bits: Int, value: Int) = writeBits(bits, value) fun readFB(bits: Int): Double = (readSB(bits)).toDouble() / 65536 fun writeFB(bits: Int, value: Double) = writeSB(bits, (value * 65536).toInt()) ///////////////////////////////////////////////////////// // String ///////////////////////////////////////////////////////// fun readString(): String { //var index = position //while (this[index++] != 0) Unit resetBitsPending() return this.data.readStringz() //return readUTFBytes(index - position) } fun writeString(value: String?) { if (value != null && value.isNotEmpty()) writeUTFBytes(value) writeByte(0) } ///////////////////////////////////////////////////////// // Labguage code ///////////////////////////////////////////////////////// fun readLANGCODE(): Int { resetBitsPending() return readUnsignedByte() } fun writeLANGCODE(value: Int) { resetBitsPending() writeByte(value) } ///////////////////////////////////////////////////////// // Color records ///////////////////////////////////////////////////////// fun readRGB(): Int { resetBitsPending() val r = readUnsignedByte() val g = readUnsignedByte() val b = readUnsignedByte() return 0xff000000.toInt() or (r shl 16) or (g shl 8) or b } fun writeRGB(value: Int) { resetBitsPending() writeByte((value ushr 16) and 0xff) writeByte((value ushr 8) and 0xff) writeByte((value ushr 0) and 0xff) } fun readRGBA(): Int { resetBitsPending() val rgb = readRGB() and 0x00ffffff val a = readUnsignedByte() return (a shl 24) or rgb } fun writeRGBA(value: Int) { resetBitsPending() writeRGB(value) writeByte((value ushr 24) and 0xff) } fun readARGB(): Int { resetBitsPending() val a = readUnsignedByte() val rgb = readRGB() and 0x00ffffff return (a shl 24) or rgb } fun writeARGB(value: Int) { resetBitsPending() writeByte((value ushr 24) and 0xff) writeRGB(value) } fun readRECT(): SWFRectangle = SWFRectangle().apply { parse(this@SWFData) } fun readMATRIX(): SWFMatrix = SWFMatrix().apply { parse(this@SWFData) } fun readCXFORM(): SWFColorTransform = SWFColorTransform().apply { parse(this@SWFData) } fun readCXFORMWITHALPHA(): SWFColorTransformWithAlpha = SWFColorTransformWithAlpha().apply { parse(this@SWFData) } fun readSHAPE(unitDivisor: Double = 20.0): SWFShape = SWFShape(unitDivisor).apply { parse(this@SWFData) } fun readSHAPEWITHSTYLE(level: Int = 1, unitDivisor: Double = 20.0): SWFShapeWithStyle = SWFShapeWithStyle(unitDivisor).apply { parse(this@SWFData, level) } fun readSTRAIGHTEDGERECORD(numBits: Int) = SWFShapeRecordStraightEdge(numBits).apply { parse(this@SWFData) } fun readCURVEDEDGERECORD(numBits: Int): SWFShapeRecordCurvedEdge = SWFShapeRecordCurvedEdge(numBits).apply { parse(this@SWFData) } fun readSTYLECHANGERECORD(states: Int, fillBits: Int, lineBits: Int, level: Int = 1): SWFShapeRecordStyleChange = SWFShapeRecordStyleChange(states, fillBits, lineBits).apply { parse(this@SWFData, level) } fun readFILLSTYLE(level: Int = 1): SWFFillStyle = SWFFillStyle().apply { parse(this@SWFData, level) } fun readLINESTYLE(level: Int = 1): SWFLineStyle = SWFLineStyle().apply { parse(this@SWFData, level) } fun readLINESTYLE2(level: Int = 1): SWFLineStyle2 = SWFLineStyle2().apply { parse(this@SWFData, level) } fun readBUTTONRECORD(level: Int = 1): SWFButtonRecord? { if (readUI8() == 0) { return null } else { position-- return SWFButtonRecord().apply { parse(this@SWFData, level) } } } fun readBUTTONCONDACTION(): SWFButtonCondAction = SWFButtonCondAction().apply { parse(this@SWFData) } fun readFILTER(): IFilter { val filterId = readUI8() val filter = SWFFilterFactory.create(filterId) filter.parse(this) return filter } fun readTEXTRECORD( glyphBits: Int, advanceBits: Int, previousRecord: SWFTextRecord? = null, level: Int = 1 ): SWFTextRecord? { if (readUI8() == 0) { return null } else { position-- return SWFTextRecord().apply { parse(this@SWFData, glyphBits, advanceBits, previousRecord, level) } } } fun readGLYPHENTRY(glyphBits: Int, advanceBits: Int): SWFGlyphEntry = SWFGlyphEntry().apply { parse(this@SWFData, glyphBits, advanceBits) } fun readZONERECORD(): SWFZoneRecord = SWFZoneRecord(this@SWFData) fun readZONEDATA(): SWFZoneData = SWFZoneData(this@SWFData) fun readKERNINGRECORD(wideCodes: Boolean): SWFKerningRecord = SWFKerningRecord().apply { parse(this@SWFData, wideCodes) } fun readGRADIENT(level: Int = 1): SWFGradient = SWFGradient().apply { parse(this@SWFData, level) } fun readFOCALGRADIENT(level: Int = 1): SWFFocalGradient = SWFFocalGradient().apply { parse(this@SWFData, level) } fun readGRADIENTRECORD(level: Int = 1): SWFGradientRecord = SWFGradientRecord().apply { parse(this@SWFData, level) } fun readMORPHFILLSTYLE(level: Int = 1) = SWFMorphFillStyle().apply { parse(this@SWFData, level) } fun readMORPHLINESTYLE(level: Int = 1) = SWFMorphLineStyle().apply { parse(this@SWFData, level) } fun readMORPHLINESTYLE2(level: Int = 1): SWFMorphLineStyle2 = SWFMorphLineStyle2().apply { parse(this@SWFData, level) } fun readMORPHGRADIENT(level: Int = 1) = SWFMorphGradient().apply { parse(this@SWFData, level) } fun readMORPHFOCALGRADIENT(level: Int = 1) = SWFMorphFocalGradient().apply { parse(this@SWFData, level) } fun readMORPHGRADIENTRECORD(): SWFMorphGradientRecord = SWFMorphGradientRecord().apply { parse(this@SWFData) } fun readACTIONRECORD(): IAction? { val pos: Int = position var action: IAction? = null val actionCode: Int = readUI8() if (actionCode != 0) { val actionLength: Int = if (actionCode >= 0x80) readUI16() else 0 action = SWFActionFactory.create(actionCode, actionLength, pos) action.parse(this) } return action } fun readACTIONVALUE(): SWFActionValue = SWFActionValue().apply { parse(this@SWFData) } fun readREGISTERPARAM(): SWFRegisterParam = SWFRegisterParam().apply { parse(this@SWFData) } fun readSYMBOL(): SWFSymbol = SWFSymbol(this@SWFData) fun readSOUNDINFO(): SWFSoundInfo = SWFSoundInfo().apply { parse(this@SWFData) } fun readSOUNDENVELOPE(): SWFSoundEnvelope = SWFSoundEnvelope(this@SWFData) fun readCLIPACTIONS(version: Int): SWFClipActions = SWFClipActions().apply { parse(this@SWFData, version) } fun readCLIPACTIONRECORD(version: Int): SWFClipActionRecord? { val pos = position val flags = if (version >= 6) readUI32() else readUI16() if (flags == 0) { return null } else { position = pos return SWFClipActionRecord().apply { parse(this@SWFData, version) } } } fun readCLIPEVENTFLAGS(version: Int): SWFClipEventFlags = SWFClipEventFlags().apply { parse(this@SWFData, version) } fun readTagHeader(): SWFRecordHeader { val pos = position val tagTypeAndLength = readUI16() var tagLength = tagTypeAndLength and 0x003f if (tagLength == 0x3f) { // The SWF10 spec sez that this is a signed int. // Shouldn't it be an unsigned int? tagLength = readSI32() } return SWFRecordHeader(tagTypeAndLength ushr 6, tagLength, position - pos) } suspend fun swfUncompress(compressionMethod: String, uncompressedLength: Int = 0) { val pos = position val ba = FlashByteArray() when (compressionMethod) { SWF.COMPRESSION_METHOD_ZLIB -> { readBytes(ba) ba.position = 0 ba.uncompressInWorker() } SWF.COMPRESSION_METHOD_LZMA -> { // LZMA compressed SWF: // 0000 5A 57 53 0F (ZWS, Version 15) // 0004 DF 52 00 00 (Uncompressed size: 21215) // 0008 94 3B 00 00 (Compressed size: 15252) // 000C 5D 00 00 00 01 (LZMA Properties) // 0011 00 3B FF FC A6 14 16 5A ... (15252 bytes of LZMA Compressed Data, until EOF) // 7z LZMA format: // 0000 5D 00 00 00 01 (LZMA Properties) // 0005 D7 52 00 00 00 00 00 00 (Uncompressed size: 21207, 64 bit) // 000D 00 3B FF FC A6 14 16 5A ... (15252 bytes of LZMA Compressed Data, until EOF) // (see also https://github.com/claus/as3swf/pull/23#issuecomment-7203861) // Write LZMA properties for (i in 0 until 5) ba.writeByte(this[i + 12]) // Write uncompressed length (64 bit) ba.endian = Endian.LITTLE_ENDIAN ba.writeUnsignedInt(uncompressedLength - 8) ba.writeUnsignedInt(0) // Write compressed data position = 17 ba.position = 13 ba.writeBytes(this.readBytes(this.bytesAvailable)) ba.position = 13 // Uncompress ba.position = 0 ba.uncompressInWorker(compressionMethod) } else -> error("Unknown compression method: $compressionMethod") } length = pos position = pos writeBytes(ba) position = pos } ///////////////////////////////////////////////////////// // etc ///////////////////////////////////////////////////////// fun readRawTag(): SWFRawTag = SWFRawTag().apply { parse(this@SWFData) } fun skipBytes(length: Int) = run { position += length } } @Suppress("unused", "UNUSED_PARAMETER") open class SWFTimelineContainer { // We're just being lazy here. companion object { var EXTRACT_SOUND_STREAM: Boolean = true } val tags = ArrayList<ITag>() var tagsRaw = ArrayList<SWFRawTag>() var dictionary = hashMapOf<Int, Int>() var scenes = ArrayList<Scene>() var frames = ArrayList<Frame>() var layers = ArrayList<Layer>() var soundStream: SoundStream? = null lateinit var currentFrame: Frame protected var frameLabels = hashMapOf<Int, String>() protected var hasSoundStream: Boolean = false protected var eof: Boolean = false protected var _tmpData: SWFData? = null protected var _tmpVersion: Int = 0 protected var _tmpTagIterator: Int = 0 protected var tagFactory: ISWFTagFactory = SWFTagFactory() internal var rootTimelineContainer: SWFTimelineContainer = this var backgroundColor: Int = 0xffffff var jpegTablesTag: TagJPEGTables? = null fun getCharacter(characterId: Int): IDefinitionTag? { val tagIndex = rootTimelineContainer.dictionary[characterId] ?: 0 if (tagIndex >= 0 && tagIndex < rootTimelineContainer.tags.size) { return rootTimelineContainer.tags[tagIndex] as IDefinitionTag } return null } suspend fun parseTags(data: SWFData, version: Int) { parseTagsInit(data, version) while (data.bytesAvailable > 0) { dispatchProgress(_tmpData!!.position, _tmpData!!.length) val tag = parseTag(_tmpData!!, true) ?: break //println(tag) if (tag.type == TagEnd.TYPE) break } parseTagsFinalize() } private fun dispatchProgress(position: Int, length: Int) { } private fun dispatchWarning(msg: String) { } private fun parseTagsInit(data: SWFData, version: Int) { tags.clear() frames.clear() layers.clear() dictionary = hashMapOf() this.currentFrame = Frame() frameLabels = hashMapOf() hasSoundStream = false _tmpData = data _tmpVersion = version } suspend protected fun parseTag(data: SWFData, async: Boolean = false): ITag? { val pos: Int = data.position // Bail out if eof eof = (pos >= data.length) if (eof) { println("WARNING: end of file encountered, no end tag.") return null } val tagRaw = data.readRawTag() val tagHeader = tagRaw.header val tag: ITag = tagFactory.create(tagHeader.type) try { if (tag is SWFTimelineContainer) { val timelineContainer: SWFTimelineContainer = tag // Currently, the only SWFTimelineContainer (other than the SWF root // itself) is TagDefineSprite (MovieClips have their own timeline). // Inject the current tag factory there. timelineContainer.tagFactory = tagFactory timelineContainer.rootTimelineContainer = this } // Parse tag tag.parse(data, tagHeader.contentLength, _tmpVersion, async) } catch (e: Throwable) { // If we get here there was a problem parsing this particular tag. // Corrupted SWF, possible SWF exploit, or obfuscated SWF. // TODO: register errors and warnings println("ERROR: parse error: " + e.message + ", Tag: " + tag.name + ", Index: " + tags.size) e.printStackTrace() //throw(e) } // Register tag tags.add(tag) tagsRaw.add(tagRaw) // Build dictionary and display list etc processTag(tag) // Adjust position (just in case the parser under- or overflows) if (data.position != pos + tagHeader.tagLength) { val index: Int = tags.size - 1 val excessBytes = data.position - (pos + tagHeader.tagLength) //var eventType: String = if (excessBytes < 0) SWFWarningEvent.UNDERFLOW else SWFWarningEvent.OVERFLOW; //var eventDataPos = pos //var eventDataBytes = if (excessBytes < 0) -excessBytes else excessBytes if (rootTimelineContainer == this) { println( "WARNING: excess bytes: " + excessBytes + ", " + "Tag: " + tag.name + ", " + "Index: " + index ) } else { //eventData.indexRoot = rootTimelineContainer.tags.length; println( "WARNING: excess bytes: " + excessBytes + ", " + "Tag: " + tag.name + ", " + "Index: " + index + ", " + "IndexRoot: " + rootTimelineContainer.tags.size ) } data.position = pos + tagHeader.tagLength } return tag } private fun parseTagsFinalize() { val soundStream = soundStream if (soundStream != null && soundStream.data.length == 0) this.soundStream = null } private fun processTag(tag: ITag) { val currentTagIndex: Int = tags.size - 1 if (tag is IDefinitionTag) { processDefinitionTag(tag, currentTagIndex) return } else if (tag is IDisplayListTag) { processDisplayListTag(tag, currentTagIndex) return } when (tag.type) { TagFrameLabel.TYPE, TagDefineSceneAndFrameLabelData.TYPE -> { // Frame labels and scenes processFrameLabelTag(tag, currentTagIndex) } TagSoundStreamHead.TYPE, TagSoundStreamHead2.TYPE, TagSoundStreamBlock.TYPE -> { // Sound stream if (EXTRACT_SOUND_STREAM) processSoundStreamTag(tag, currentTagIndex) } TagSetBackgroundColor.TYPE -> { // Background color processBackgroundColorTag(tag as TagSetBackgroundColor, currentTagIndex) } TagJPEGTables.TYPE -> { // Global JPEG Table processJPEGTablesTag(tag as TagJPEGTables, currentTagIndex) } } } private fun processDefinitionTag(tag: IDefinitionTag, currentTagIndex: Int) { if (tag.characterId > 0) { // Register definition tag in dictionary // key: character id // value: definition tag index dictionary[tag.characterId] = currentTagIndex // Register character id in the current frame's character array currentFrame.characters.add(tag.characterId) } } private fun processDisplayListTag(tag: IDisplayListTag, currentTagIndex: Int) { when (tag.type) { TagShowFrame.TYPE -> { currentFrame.tagIndexEnd = currentTagIndex if (currentFrame.label == null && currentFrame.frameNumber in frameLabels) { currentFrame.label = frameLabels[currentFrame.frameNumber] } frames.add(currentFrame) currentFrame = currentFrame.clone() currentFrame.frameNumber = frames.size currentFrame.tagIndexStart = currentTagIndex + 1 } TagPlaceObject.TYPE, TagPlaceObject2.TYPE, TagPlaceObject3.TYPE -> { currentFrame.placeObject(currentTagIndex, tag as TagPlaceObject) } TagRemoveObject.TYPE, TagRemoveObject2.TYPE -> { currentFrame.removeObject(tag as TagRemoveObject) } } } private fun processFrameLabelTag(tag: ITag, currentTagIndex: Int) { when (tag.type) { TagDefineSceneAndFrameLabelData.TYPE -> { val tagSceneAndFrameLabelData: TagDefineSceneAndFrameLabelData = tag as TagDefineSceneAndFrameLabelData for (i in 0 until tagSceneAndFrameLabelData.frameLabels.size) { val frameLabel = tagSceneAndFrameLabelData.frameLabels[i] frameLabels[frameLabel.frameNumber] = frameLabel.name } for (i in 0 until tagSceneAndFrameLabelData.scenes.size) { val scene: SWFScene = tagSceneAndFrameLabelData.scenes[i] scenes.add(Scene(scene.offset, scene.name)) } } TagFrameLabel.TYPE -> { val tagFrameLabel = tag as TagFrameLabel currentFrame.label = tagFrameLabel.frameName } } } private fun processSoundStreamTag(tag: ITag, currentTagIndex: Int) { when (tag.type) { TagSoundStreamHead.TYPE, TagSoundStreamHead2.TYPE -> { val tagSoundStreamHead = tag as TagSoundStreamHead soundStream = SoundStream() val soundStream = soundStream!! soundStream.compression = tagSoundStreamHead.streamSoundCompression soundStream.rate = tagSoundStreamHead.streamSoundRate soundStream.size = tagSoundStreamHead.streamSoundSize soundStream.type = tagSoundStreamHead.streamSoundType soundStream.numFrames = 0 soundStream.numSamples = 0 } TagSoundStreamBlock.TYPE -> { if (soundStream != null) { val soundStream = soundStream!! if (!hasSoundStream) { hasSoundStream = true soundStream.startFrame = currentFrame.frameNumber } val tagSoundStreamBlock = tag as TagSoundStreamBlock val soundData = tagSoundStreamBlock.soundData soundData.endian = Endian.LITTLE_ENDIAN soundData.position = 0 when (soundStream.compression) { SoundCompression.ADPCM -> { // ADPCM // TODO } SoundCompression.MP3 -> { // MP3 val numSamples: Int = soundData.readUnsignedShort() @Suppress("UNUSED_VARIABLE") var seekSamples: Int = soundData.readShort() if (numSamples > 0) { soundStream.numSamples += numSamples soundStream.data.writeBytes(soundData, 4) } } } soundStream.numFrames++ } } } } protected fun processBackgroundColorTag(tag: TagSetBackgroundColor, currentTagIndex: Int) { backgroundColor = tag.color } protected fun processJPEGTablesTag(tag: TagJPEGTables, currentTagIndex: Int) { jpegTablesTag = tag } open fun toString(indent: Int = 0, flags: Int = 0): String { var str = "" if (tags.size > 0) { str += "\n" + " ".repeat(indent + 2) + "Tags:" for (i in 0 until tags.size) { str += "\n" + tags[i].toString(indent + 4) } } if ((flags and SWF.TOSTRING_FLAG_TIMELINE_STRUCTURE) != 0) { if (scenes.size > 0) { str += "\n" + " ".repeat(indent + 2) + "Scenes:" for (i in 0 until scenes.size) { str += "\n" + scenes[i].toString(indent + 4) } } if (frames.size > 0) { str += "\n" + " ".repeat(indent + 2) + "Frames:" for (i in 0 until frames.size) { str += "\n" + frames[i].toString(indent + 4) } } if (layers.size > 0) { str += "\n" + " ".repeat(indent + 2) + "Layers:" for (i in 0 until layers.size) { str += "\n" + " ".repeat(indent + 4) + "[" + i + "] " + layers[i].toString(indent + 4) } } } return str } override fun toString() = toString(0, 0) }
korge-swf/src/commonMain/kotlin/com/soywiz/korfl/as3swf/as3swf.kt
2208349970
package com.natpryce.hamkrest /** * A [Matcher] that matches anything, always returning [MatchResult.Match]. */ val anything = object : Matcher<Any?> { override fun invoke(actual: Any?): MatchResult = MatchResult.Match override val description: String get() = "anything" override val negatedDescription: String get() = "nothing" } /** * A [Matcher] that matches nothing, always returning a [MatchResult.Mismatch]. */ val nothing = !anything /** * Returns a matcher that reports if a value is equal to an [expected] value. Handles null comparisons, just as * the `==` operator does. */ fun <T> equalTo(expected: T?): Matcher<T?> = object : Matcher<T?> { override fun invoke(actual: T?): MatchResult = match(actual == expected) { "was: ${describe(actual)}" } override val description: String get() = "is equal to ${describe(expected)}" override val negatedDescription: String get() = "is not equal to ${describe(expected)}" } /** * Returns a matcher that reports if a value is the same instance as [expected] value. */ fun <T> sameInstance(expected: T): Matcher<T> = object : Matcher<T> { override fun invoke(actual: T): MatchResult = match(actual === expected) { "was: ${describe(actual)}" } override val description: String get() = "is same instance as ${describe(expected)}" override val negatedDescription: String get() = "is not same instance as ${describe(expected)}" } /** * Returns a matcher that reports if a value is null. */ fun <T> absent(): Matcher<T?> = object : Matcher<T?> { override fun invoke(actual: T?): MatchResult = match(actual == null) { "was: ${describe(actual)}" } override val description: String get() = "null" } /** * Returns a matcher that reports if a value is not null and meets the criteria of the [valueMatcher] */ fun <T> present(valueMatcher: Matcher<T>? = null) = object : Matcher<T?> { override fun invoke(actual: T?) = if (actual == null) { MatchResult.Mismatch("was: null") } else if (valueMatcher == null) { MatchResult.Match } else { valueMatcher(actual) } override val description: String get() = "is not null" + (if (valueMatcher == null) "" else " & ${valueMatcher.description}") } /** * Returns a matcher that reports if a value of [Any] type is of a type compatible with [downcastMatcher] and, if so, * if the value meets its criteria. */ inline fun <reified T : Any> isA(downcastMatcher: Matcher<T>? = null) = object : Matcher<Any> { override fun invoke(actual: Any) = if (actual !is T) { MatchResult.Mismatch("was: a ${actual.javaClass.kotlin.qualifiedName}") } else if (downcastMatcher == null) { MatchResult.Match } else { downcastMatcher(actual) } override val description: String get() = "is a ${T::class.qualifiedName}" + if (downcastMatcher == null) "" else " ${downcastMatcher.description}" } /** * Returns a matcher that reports if a value of [Any] type is of a type compatible with [downcastMatcher] and, if so, * if the value meets its criteria. */ inline fun <reified T : Any> cast(downcastMatcher: Matcher<T>): Matcher<Any> = isA(downcastMatcher) /** * Returns a matcher that reports if a [Comparable] value is greater than [n] */ fun <N : Comparable<N>> greaterThan(n: N) = _comparesAs("greater than", n) { it > 0 } /** * Returns a matcher that reports if a [Comparable] value is greater than or equal to [n] */ fun <N : Comparable<N>> greaterThanOrEqualTo(n: N) = _comparesAs("greater than or equal to", n) { it >= 0 } /** * Returns a matcher that reports if a [Comparable] value is less than [n] */ fun <N : Comparable<N>> lessThan(n: N) = _comparesAs("less than", n) { it < 0 } /** * Returns a matcher that reports if a [Comparable] value is less than or equal to [n] */ fun <N : Comparable<N>> lessThanOrEqualTo(n: N) = _comparesAs("less than or equal to", n) { it <= 0 } private fun <N : Comparable<N>> _comparesAs(description: String, n: N, expectedSignum: (Int) -> Boolean): Matcher<N> { return object : Matcher<N> { override fun invoke(actual: N): MatchResult = match(expectedSignum(actual.compareTo(n))) { "was: ${describe(actual)}" } override val description: String get() { return "is ${description} ${describe(n)}" } } } /** * Returns a matcher that reports if a [kotlin.Comparable] value falls within the given [range]. * * @param range The range that contains matching values. */ fun <T : Comparable<T>> isWithin(range: ClosedRange<T>): Matcher<T> { fun _isWithin(actual: T, range: ClosedRange<T>): Boolean { return range.contains(actual) } return Matcher.Companion(::_isWithin, range) } /** * Returns a matcher that reports if a block throws an exception of type [T] and, if [exceptionCriteria] is given, * the exception matches the [exceptionCriteria]. */ inline fun <reified T : Throwable> throws(exceptionCriteria: Matcher<T>? = null): Matcher<() -> Unit> { val exceptionName = T::class.qualifiedName return object : Matcher<() -> Unit> { override fun invoke(actual: () -> Unit): MatchResult = try { actual() MatchResult.Mismatch("did not throw") } catch (e: Throwable) { if (e is T) { exceptionCriteria?.invoke(e) ?: MatchResult.Match } else { MatchResult.Mismatch("threw ${e.javaClass.kotlin.qualifiedName}") } } override val description: String get() = "throws ${exceptionName}${exceptionCriteria?.let { " that ${describe(it)}" } ?: ""}" override val negatedDescription: String get() = "does not throw ${exceptionName}${exceptionCriteria?.let { " that ${describe(it)}" } ?: ""}" } }
src/main/kotlin/com/natpryce/hamkrest/core_matchers.kt
2961420558
package tornadofx.adapters import javafx.beans.property.ObjectProperty import javafx.scene.control.* import javafx.util.Callback import tornadofx.mapEach fun TreeTableView<*>.toTornadoFXTable() = TornadoFXTreeTable(this) fun TableView<*>.toTornadoFXTable() : TornadoFXTable<TableColumn<*,*>, TableView<*>> = TornadoFXNormalTable(this) interface TornadoFXTable<COLUMN, out TABLE : Any> { val table: TABLE val contentWidth: Double val properties: Properties val contentColumns: List<TornadoFXColumn<COLUMN>> var skin: Skin<*>? val skinProperty: ObjectProperty<Skin<*>> } class TornadoFXTreeTable(override val table: TreeTableView<*>) : TornadoFXTable<TreeTableColumn<*, *>, TreeTableView<*>> { override val skinProperty = table.skinProperty() override var skin get() = table.skin set(value) { table.skin = value } override val contentColumns get() = table.columns.flatMap { if (it.columns.isEmpty()) listOf(it) else it.columns }.mapEach { toTornadoFXColumn() } override val properties = table.properties private val contentWidthField by lazy { TreeTableView::class.java.getDeclaredField("contentWidth").also { it.isAccessible = true } } override val contentWidth get() = contentWidthField.get(table) as Double var columnResizePolicy: Callback<TreeTableView.ResizeFeatures<Any>, Boolean> get() = table.columnResizePolicy set(value) { table.columnResizePolicy = value } } class TornadoFXNormalTable(override val table: TableView<*>) : TornadoFXTable<TableColumn<*, *>, TableView<*>> { override val skinProperty: ObjectProperty<Skin<*>> get() = table.skinProperty() override val contentColumns get() = table.columns.flatMap { if (it.columns.isEmpty()) listOf(it) else it.columns }.mapEach { toTornadoFXColumn() } override var skin get() = table.skin set(value) { table.skin = value } private val contentWidthField by lazy { TableView::class.java.getDeclaredField("contentWidth").also { it.isAccessible = true } } override val contentWidth get() = contentWidthField.get(table) as Double override val properties = table.properties }
src/main/java/tornadofx/adapters/TornadoFXTables.kt
353611132
package hypr.hypergan.com.hypr.GeneratorLoader data class Person(var faceImage: ByteArray?, var fullImage: ByteArray)
app/src/main/java/hypr/hypergan/com/hypr/GeneratorLoader/Person.kt
3096608699
/* * 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 org.jetbrains.builtInWebServer import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.packaging.artifacts.ArtifactManager internal class ArtifactWebServerRootsProvider : PrefixlessWebServerRootsProvider() { override fun resolve(path: String, project: Project, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { if (!pathQuery.searchInArtifacts) { return null } for (artifact in ArtifactManager.getInstance(project).artifacts) { val root = artifact.outputFile ?: continue return resolver.resolve(path, root, pathQuery = pathQuery) } return null } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { for (artifact in ArtifactManager.getInstance(project).artifacts) { val root = artifact.outputFile ?: continue if (VfsUtilCore.isAncestor(root, file, true)) { return PathInfo(null, file, root) } } return null } }
java/compiler/impl/src/org/jetbrains/builtInWebServer/ArtifactWebServerRootsProvider.kt
3554716909
package com.tamsiree.rxkit.interfaces /** * Created by Tamsiree on 2017/8/14. */ interface OnRxThreeStep { fun onNextOne() fun onNextTwo() fun onNextThree() }
RxKit/src/main/java/com/tamsiree/rxkit/interfaces/OnRxThreeStep.kt
536077888
package de.saschahlusiak.freebloks.game.lobby import androidx.annotation.UiThread interface LobbyDialogDelegate { /** * The lobby dialog has been cancelled with the back button or touch outside */ @UiThread fun onLobbyDialogCancelled() }
app/src/main/java/de/saschahlusiak/freebloks/game/lobby/LobbyDialogDelegate.kt
929169362
package ml.varpeti.hf01 import android.app.Activity import android.graphics.Color import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import android.content.Intent import android.widget.Toast class MainActivity : AppCompatActivity() { val colorOf = arrayOf("#ffffff","#00ff00") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Mentett szöveg visszaállítása val fruits = resources.getStringArray(R.array.fruits) val ll01 = findViewById(R.id.ll01) as LinearLayout for (i in fruits.indices) { val b = Button(this) b.id = i b.setText(fruits[i]) b.setBackgroundColor(Color.parseColor(colorOf[0])) b.tag = 0 b.setOnClickListener { val btn = it as Button val name = btn.text as String var ci = btn.tag as Int Log.i("\\|/", name+" "+btn.tag) if (ci==1) { ci=0 btn.setBackgroundColor(Color.parseColor(colorOf[ci])) btn.tag = ci //Shopping Cart val tw = findViewById<TextView>(R.id.tw01) tw.text = ""+((tw.text as String).toInt()-1) } else { val int = Intent(this, ItemViewActivity::class.java) int.putExtra("name", name) int.putExtra("id", i) startActivityForResult(int,0) } } ll01.addView(b) } //Shopping Cart val tw = findViewById<TextView>(R.id.tw01) tw.text = "0" } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && requestCode == 0) { if (data!!.hasExtra("id")) { val id = data.extras.getInt("id") val ci = data.extras.getInt("status",0) val b = findViewById<Button>(resources.getIdentifier(""+id, "id", getPackageName())) if (ci==1) { b.tag = ci Log.i("\\|/", "res: "+id+" "+ci) b.setBackgroundColor(Color.parseColor(colorOf[ci])) val tw = findViewById<TextView>(R.id.tw01) tw.text = ""+((tw.text as String).toInt()+1) } } } } //Lementés TODO override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) val fruits = resources.getStringArray(R.array.fruits) for (i in fruits.indices) { val b = findViewById<Button>(resources.getIdentifier(""+i, "id", getPackageName())) var ci = b.tag as Int //Log.i("\\|/", ""+ci) savedInstanceState.putInt("b"+i+"color",ci) } } }
Android/work/varpe8/homeworks/01/HF01/app/src/main/java/ml/varpeti/hf01/MainActivity.kt
3253291037
package com.matejdro.wearmusiccenter import android.annotation.TargetApi import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.media.session.MediaController import android.os.Build import android.preference.PreferenceManager import android.provider.Settings import android.service.notification.NotificationListenerService import androidx.lifecycle.Observer import com.google.android.gms.wearable.MessageClient import com.google.android.gms.wearable.NodeClient import com.google.android.gms.wearable.Wearable import com.matejdro.wearmusiccenter.common.CommPaths import com.matejdro.wearmusiccenter.common.MiscPreferences import com.matejdro.wearmusiccenter.common.model.AutoStartMode import com.matejdro.wearmusiccenter.music.ActiveMediaSessionProvider import com.matejdro.wearmusiccenter.music.MusicService import com.matejdro.wearmusiccenter.music.isPlaying import com.matejdro.wearutils.lifecycle.Resource import com.matejdro.wearutils.messages.sendMessageToNearestClient import com.matejdro.wearutils.preferences.definition.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import timber.log.Timber class NotificationService : NotificationListenerService() { private lateinit var preferences: SharedPreferences private var bound = false private var activeMediaProvider: ActiveMediaSessionProvider? = null private val coroutineScope = CoroutineScope(Job()) private lateinit var messageClient: MessageClient private lateinit var nodeClient: NodeClient override fun onCreate() { super.onCreate() preferences = PreferenceManager.getDefaultSharedPreferences(this) nodeClient = Wearable.getNodeClient(applicationContext) messageClient = Wearable.getMessageClient(applicationContext) Timber.d("Service started") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (ACTION_UNBIND_SERVICE == intent?.action && bound && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { requestUnbindSafe() Timber.d("Unbind on command") } return super.onStartCommand(intent, flags, startId) } override fun onListenerConnected() { super.onListenerConnected() Timber.d("Listener connected") val musicServiceNotifyIntent = Intent(this, MusicService::class.java) musicServiceNotifyIntent.action = MusicService.ACTION_NOTIFICATION_SERVICE_ACTIVATED startService(musicServiceNotifyIntent) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !shouldRun()) { //Running notification service is not needed for this app to run, it only needs to be enabled. Timber.d("Unbind on start") // On N+ we can turn off the service requestUnbindSafe() return } activeMediaProvider = ActiveMediaSessionProvider(this) if (MiscPreferences.isAnyKindOfAutoStartEnabled(preferences)) { activeMediaProvider!!.observeForever(mediaObserver) } bound = true } override fun onListenerDisconnected() { Timber.d("Listener disconnected") activeMediaProvider?.removeObserver(mediaObserver) super.onListenerDisconnected() } override fun onDestroy() { Timber.d("Service destroyed") activeMediaProvider?.removeObserver(mediaObserver) coroutineScope.cancel() super.onDestroy() } private fun shouldRun(): Boolean { return MiscPreferences.isAnyKindOfAutoStartEnabled(preferences) } private fun startAppOnWatch() { Timber.d("AttemptToStartApp") coroutineScope.launch { try { val legacySetting = Preferences.getBoolean(preferences, MiscPreferences.AUTO_START) val openType = if (legacySetting) { AutoStartMode.OPEN_APP } else { Preferences.getEnum(preferences, MiscPreferences.AUTO_START_MODE) } val message = when (openType) { AutoStartMode.OFF, null -> return@launch AutoStartMode.SHOW_ICON -> CommPaths.MESSAGE_START_SERVICE AutoStartMode.OPEN_APP -> CommPaths.MESSAGE_OPEN_APP } messageClient.sendMessageToNearestClient(nodeClient, message) Timber.d("Start success") } catch (e: Exception) { Timber.e(e, "Start Fail") } } } private val mediaObserver = Observer<Resource<MediaController>> { Timber.d("Playback update %b %s", MusicService.active, it?.data?.playbackState?.state) if (!MusicService.active && it?.data?.playbackState?.isPlaying() == true) { val autoStartBlacklist = Preferences.getStringSet(preferences, MiscPreferences.AUTO_START_APP_BLACKLIST) if (!autoStartBlacklist.contains(it.data?.packageName)) { startAppOnWatch() } } } companion object { fun isEnabled(context: Context): Boolean { val component = ComponentName(context, NotificationService::class.java) val enabledListeners = Settings.Secure.getString(context.contentResolver, "enabled_notification_listeners") return enabledListeners != null && enabledListeners.contains(component.flattenToString()) } const val ACTION_UNBIND_SERVICE = "UNBIND" } @TargetApi(Build.VERSION_CODES.N) private fun requestUnbindSafe() { try { requestUnbind() } catch (e: SecurityException) { // Sometimes notification service may be unbound before we can unbind safely. // just stop self. stopSelf() } } }
mobile/src/main/java/com/matejdro/wearmusiccenter/NotificationService.kt
423357433
package com.akexorcist.localizationactivity.ui import android.app.Application import android.content.Context import android.content.res.Configuration import com.akexorcist.localizationactivity.core.LocalizationApplicationDelegate import java.util.* abstract class LocalizationApplication : Application() { private var localizationDelegate = LocalizationApplicationDelegate() override fun attachBaseContext(base: Context) { localizationDelegate.setDefaultLanguage(base, getDefaultLanguage()) super.attachBaseContext(localizationDelegate.attachBaseContext(base)) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) localizationDelegate.onConfigurationChanged(this) } override fun getApplicationContext(): Context { return localizationDelegate.getApplicationContext(super.getApplicationContext()) } abstract fun getDefaultLanguage(): Locale }
localizationActivity/src/main/java/com/akexorcist/localizationactivity/ui/LocalizationApplication.kt
1203689262
package com.stripe.android.core.injection import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import java.util.WeakHashMap import java.util.concurrent.atomic.AtomicInteger /** * A [InjectorRegistry] implemented with a weak map. An entry from the map will be will be garbage * collected once the [Injector] instance is no longer held elsewhere. * * Note: the weak map will be cleared when app process is killed by system. * [Injectable] implementations are responsible for detecting this and call * [Injectable.fallbackInitialize] accordingly. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object WeakMapInjectorRegistry : InjectorRegistry { /** * Cache to map [Injector] to its corresponding [InjectorKey]. * Note: the [Injector] is the weak map key for itself to be garbage collected. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @VisibleForTesting val staticCacheMap = WeakHashMap<Injector, @receiver:InjectorKey String>() /** * Global unique monotonically increasing key to be assigned as a suffixes to * registered [Injector]s. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @VisibleForTesting val CURRENT_REGISTER_KEY = AtomicInteger(0) @Synchronized override fun register(injector: Injector, @InjectorKey key: String) { staticCacheMap[injector] = key } @Synchronized override fun retrieve(@InjectorKey injectorKey: String): Injector? { return staticCacheMap.entries.firstOrNull { it.value == injectorKey }?.key } @InjectorKey override fun nextKey(prefix: String): String { return prefix + CURRENT_REGISTER_KEY.incrementAndGet() } fun clear() { synchronized(staticCacheMap) { staticCacheMap.clear() } } }
stripe-core/src/main/java/com/stripe/android/core/injection/WeakMapInjectorRegistry.kt
3328302140
package org.hildan.minecraft.mining.optimizer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.hildan.minecraft.mining.optimizer.blocks.Sample import org.hildan.minecraft.mining.optimizer.geometry.Dimensions import org.hildan.minecraft.mining.optimizer.ore.BlockType import org.hildan.minecraft.mining.optimizer.ore.generateSamples import org.hildan.minecraft.mining.optimizer.patterns.DiggingPattern import org.hildan.minecraft.mining.optimizer.patterns.generated.GenerationConstraints import org.hildan.minecraft.mining.optimizer.patterns.generated.PatternGenerator import org.hildan.minecraft.mining.optimizer.statistics.EvaluatedPattern import org.hildan.minecraft.mining.optimizer.statistics.PatternEvaluator import org.hildan.minecraft.mining.optimizer.statistics.PatternStore private const val NUM_EVAL_SAMPLES = 50 private const val SAMPLE_WIDTH = 16 private const val SAMPLE_HEIGHT = 5 private const val SAMPLE_LENGTH = 16 private const val SAMPLE_LOW_Y_POSITION = 5 private const val MAX_DUG_BLOCKS = 20 fun main() = runBlocking { val sampleDimensions = Dimensions(SAMPLE_WIDTH, SAMPLE_HEIGHT, SAMPLE_LENGTH) val constraints = GenerationConstraints(sampleDimensions, MAX_DUG_BLOCKS) println("Generating $NUM_EVAL_SAMPLES reference samples with lowest Y=$SAMPLE_LOW_Y_POSITION...") val referenceSamples = generateSamples(NUM_EVAL_SAMPLES, sampleDimensions, SAMPLE_LOW_Y_POSITION) println("Starting pattern generation with constraints: $constraints") val generatedPatterns = generatePatternsAsync(constraints) println("Starting pattern evaluation on reference samples...") val evaluatedPatterns = evaluateAsync(referenceSamples, generatedPatterns) val store = storePatternsAndPrintProgress(evaluatedPatterns) printBestPatterns(sampleDimensions, store) } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.generatePatternsAsync(constraints: GenerationConstraints): ReceiveChannel<DiggingPattern> = produce(Dispatchers.Default, capacity = 200) { PatternGenerator(constraints).forEach { send(it) } close() } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.evaluateAsync( referenceSamples: List<Sample>, generatedPatterns: ReceiveChannel<DiggingPattern> ) = produce(Dispatchers.Default, capacity = 200) { repeat(Runtime.getRuntime().availableProcessors() - 1) { launch { val patternEvaluator = PatternEvaluator(referenceSamples) for (p in generatedPatterns) { send(patternEvaluator.evaluate(p)) } } } } private suspend fun storePatternsAndPrintProgress(evaluatedPatterns: ReceiveChannel<EvaluatedPattern>): PatternStore { val store = PatternStore() var count = 0 for (p in evaluatedPatterns) { count++ if (count % 10000 == 0) { println("$count evaluated patterns so far") } if (store.add(p)) { println(store) } } println("Finished with $count total evaluated patterns") return store } fun printBestPatterns(sampleDimensions: Dimensions, store: PatternStore) { val sample = Sample(sampleDimensions, BlockType.STONE) for (pattern in store) { sample.fill(BlockType.STONE) pattern.pattern.digInto(sample) println(sample) println(pattern.statistics.toFullString(NUM_EVAL_SAMPLES)) } }
src/main/kotlin/org/hildan/minecraft/mining/optimizer/McMiningOptimizer.kt
2222846041
@file:JvmName("VideoUtils") package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.annotations.Internal import com.vimeo.networking2.common.Entity import com.vimeo.networking2.enums.LicenseType import com.vimeo.networking2.enums.VideoStatusType import com.vimeo.networking2.enums.asEnum import java.util.Date /** * Video data. * * @param badge Information for the video's badge. * @param categories The categories to which this video belongs. * @param contentRating The content ratings of this video. * @param context The context of the video's subscription, if this video is part of a subscription. * @param createdTime The time in ISO 8601 format when the video was created. * @param description A brief explanation of the video's content. * @param download A list of downloadable files. * @param duration The video's duration in seconds. * @param editSession Information about the Vimeo Create session of a video. * @param embed Information about embedding this video. * @param fileTransferPage Information about the file transfer page associated with this video. This data requires a * bearer token with the private scope. * @param height The video's height in pixels. * @param isPlayable Whether the clip is playable. * @param language The video's primary language. * @param lastUserActionEventDate The time in ISO 8601 format when the user last modified the video. * @param license The Creative Commons license used for the video. See [Video.licenseType]. * @param link The link to the video. * @param live Live playback information. * @param metadata The video's metadata. * @param modifiedTime The time in ISO 8601 format when the video metadata was last modified. * @param name The video's title. * @param parentFolder Information about the folder that contains the video, or null if it is in the root directory. * @param password The privacy-enabled password to watch this video. This data requires a bearer token with the private * scope. * @param pictures The active picture for this video. * @param play The Play representation. * @param privacy The video's privacy setting. * @param releaseTime The time in ISO 8601 format when the video was released. * @param resourceKey The resource key string of the video. * @param reviewPage Information about the review page associated with this video. This data requires a bearer token * with the private scope. * @param spatial 360 spatial data. * @param stats A collection of stats associated with this video. * @param status The status code for the availability of the video. This field is deprecated in favor of [upload] and * [transcode]. See [Video.statusType]. * @param tags An array of all tags assigned to this video. * @param transcode The transcode information for a video upload. * @param upload The upload information for this video. * @param uri The video's canonical relative URI. * @param user The video owner. * @param width The video's width in pixels. */ @JsonClass(generateAdapter = true) data class Video( @Json(name = "badge") val badge: VideoBadge? = null, @Json(name = "categories") val categories: List<Category>? = null, @Json(name = "content_rating") val contentRating: List<String>? = null, @Json(name = "context") val context: VideoContext? = null, @Json(name = "created_time") val createdTime: Date? = null, @Json(name = "description") val description: String? = null, @Json(name = "download") val download: List<DownloadableVideoFile>? = null, @Json(name = "duration") val duration: Int? = null, @Json(name = "edit_session") val editSession: EditSession? = null, @Json(name = "embed") val embed: VideoEmbed? = null, @Internal @Json(name = "file_transfer") val fileTransferPage: FileTransferPage? = null, @Json(name = "height") val height: Int? = null, @Json(name = "is_playable") val isPlayable: Boolean? = null, @Json(name = "language") val language: String? = null, @Json(name = "last_user_action_event_date") val lastUserActionEventDate: Date? = null, @Json(name = "license") val license: String? = null, @Json(name = "link") val link: String? = null, @Json(name = "live") val live: Live? = null, @Json(name = "metadata") val metadata: Metadata<VideoConnections, VideoInteractions>? = null, @Json(name = "modified_time") val modifiedTime: Date? = null, @Json(name = "name") val name: String? = null, @Json(name = "parent_project") val parentFolder: Folder? = null, @Internal @Json(name = "password") val password: String? = null, @Json(name = "pictures") val pictures: PictureCollection? = null, @Internal @Json(name = "play") val play: Play? = null, @Json(name = "privacy") val privacy: Privacy? = null, @Json(name = "release_time") val releaseTime: Date? = null, @Json(name = "resource_key") val resourceKey: String? = null, @Internal @Json(name = "review_page") val reviewPage: ReviewPage? = null, @Json(name = "spatial") val spatial: Spatial? = null, @Json(name = "stats") val stats: VideoStats? = null, @Json(name = "status") @Deprecated("This property is deprecated in favor of upload and transcode.") val status: String? = null, @Json(name = "tags") val tags: List<Tag>? = null, @Json(name = "transcode") val transcode: Transcode? = null, @Json(name = "upload") val upload: Upload? = null, @Json(name = "uri") val uri: String? = null, @Json(name = "user") val user: User? = null, @Json(name = "width") val width: Int? = null ) : Entity { override val identifier: String? = resourceKey } /** * @see Video.license * @see LicenseType */ val Video.licenseType: LicenseType get() = license.asEnum(LicenseType.UNKNOWN) /** * @see Video.status * @see VideoStatusType */ @Deprecated(message = "This property is deprecated in favor of upload and transcode.") val Video.statusType: VideoStatusType get() = status.asEnum(VideoStatusType.UNKNOWN)
models/src/main/java/com/vimeo/networking2/Video.kt
1100749873
/* * 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.work.lint import androidx.work.lint.Stubs.FOREGROUND_INFO import androidx.work.lint.Stubs.NOTIFICATION import com.android.tools.lint.checks.infrastructure.LintDetectorTest.kotlin import com.android.tools.lint.checks.infrastructure.LintDetectorTest.manifest import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Ignore import org.junit.Test class SpecifyForegroundServiceTypeIssueDetectorTest { @Ignore("b/196831196") @Test fun failWhenServiceTypeIsNotSpecified() { val application = kotlin( "com/example/App.kt", """ package com.example import android.app.Notification import androidx.work.ForegroundInfo class App { fun onCreate() { val notification = Notification() val info = ForegroundInfo(0, notification, 1) } } """ ).indented().within("src") lint().files( // Source files NOTIFICATION, FOREGROUND_INFO, application ).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE) .run() /* ktlint-disable max-line-length */ .expect( """ src/com/example/App.kt:9: Error: Missing dataSync foregroundServiceType in the AndroidManifest.xml [SpecifyForegroundServiceType] val info = ForegroundInfo(0, notification, 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """.trimIndent() ) /* ktlint-enable max-line-length */ } @Ignore("b/196831196") @Test fun failWhenSpecifiedServiceTypeIsInSufficient() { val manifest = manifest( """ <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example"> <application> <service android:name="androidx.work.impl.foreground.SystemForegroundService" android:exported="false" android:directBootAware="false" android:enabled="@bool/enable_system_foreground_service_default" android:foregroundServiceType="location" tools:targetApi="n"/> </application> </manifest> """ ).indented() val application = kotlin( "com/example/App.kt", """ package com.example import android.app.Notification import androidx.work.ForegroundInfo class App { fun onCreate() { val notification = Notification() val info = ForegroundInfo(0, notification, 9) } } """ ).indented().within("src") lint().files( // Manifest manifest, // Sources NOTIFICATION, FOREGROUND_INFO, application ).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE) .run() /* ktlint-disable max-line-length */ .expect( """ src/com/example/App.kt:9: Error: Missing dataSync foregroundServiceType in the AndroidManifest.xml [SpecifyForegroundServiceType] val info = ForegroundInfo(0, notification, 9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """.trimIndent() ) /* ktlint-enable max-line-length */ } @Test fun passWhenCorrectForegroundServiceTypeSpecified() { val manifest = manifest( """ <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example"> <application> <service android:name="androidx.work.impl.foreground.SystemForegroundService" android:exported="false" android:directBootAware="false" android:enabled="@bool/enable_system_foreground_service_default" android:foregroundServiceType="location" tools:targetApi="n"/> </application> </manifest> """ ).indented() val application = kotlin( "com/example/App.kt", """ package com.example import android.app.Notification import androidx.work.ForegroundInfo class App { fun onCreate() { val notification = Notification() val info = ForegroundInfo(0, notification, 8) } } """ ).indented().within("src") lint().files( // Manifest manifest, // Sources NOTIFICATION, FOREGROUND_INFO, application ).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE) .run() .expectClean() } @Test fun passWhenMultipleForegroundServiceTypeSpecified() { val manifest = manifest( """ <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example"> <application> <service android:name="androidx.work.impl.foreground.SystemForegroundService" android:exported="false" android:directBootAware="false" android:enabled="@bool/enable_system_foreground_service_default" android:foregroundServiceType="dataSync|location" tools:targetApi="n"/> </application> </manifest> """ ).indented() val application = kotlin( "com/example/App.kt", """ package com.example import android.app.Notification import androidx.work.ForegroundInfo class App { fun onCreate() { val notification = Notification() val info = ForegroundInfo(0, notification, 9) } } """ ).indented().within("src") lint().files( // Manifest manifest, // Sources NOTIFICATION, FOREGROUND_INFO, application ).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE) .run() .expectClean() } }
work/work-lint/src/test/java/androidx/work/lint/SpecifyForegroundServiceTypeIssueDetectorTest.kt
875343052
package au.com.codeka.warworlds.server.admin.handlers /** * This handler is for /admin/sector, and allows us to debug some of the sector handling code. */ class SectorsHandler : AdminHandler() { public override fun get() { render("sectors/index.html", null) } }
server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/SectorsHandler.kt
1839674717
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution.model.rules.cleanup import batect.config.Container import batect.docker.DockerContainer import batect.execution.model.events.ContainerStoppedEvent import batect.execution.model.rules.TaskStepRuleEvaluationResult import batect.execution.model.steps.StopContainerStep import batect.os.OperatingSystem import batect.testutils.equalTo import batect.testutils.given import batect.testutils.imageSourceDoesNotMatter import batect.testutils.on import com.natpryce.hamkrest.assertion.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object StopContainerStepRuleSpec : Spek({ describe("a stop container step rule") { val containerToStop = Container("the-container", imageSourceDoesNotMatter()) val dockerContainerToStop = DockerContainer("some-container-id") given("there are no containers that must be stopped first") { val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, emptySet()) on("evaluating the rule") { val result = rule.evaluate(emptySet()) it("returns a 'stop container' step") { assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(StopContainerStep(containerToStop, dockerContainerToStop)))) } } on("toString()") { it("returns a human-readable representation of itself") { assertThat(rule.toString(), equalTo("StopContainerStepRule(container: 'the-container', Docker container: 'some-container-id', containers that must be stopped first: [])")) } } } given("there are some containers that must be stopped first") { val container1 = Container("container-1", imageSourceDoesNotMatter()) val container2 = Container("container-2", imageSourceDoesNotMatter()) val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, setOf(container1, container2)) given("those containers have been stopped") { val events = setOf( ContainerStoppedEvent(container1), ContainerStoppedEvent(container2) ) on("evaluating the rule") { val result = rule.evaluate(events) it("returns a 'stop container' step") { assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(StopContainerStep(containerToStop, dockerContainerToStop)))) } } } given("those containers have not been stopped") { on("evaluating the rule") { val result = rule.evaluate(emptySet()) it("indicates that the step is not yet ready") { assertThat(result, equalTo(TaskStepRuleEvaluationResult.NotReady)) } } } on("toString()") { it("returns a human-readable representation of itself") { assertThat(rule.toString(), equalTo("StopContainerStepRule(container: 'the-container', Docker container: 'some-container-id', containers that must be stopped first: ['container-1', 'container-2'])")) } } } on("getting the manual cleanup instruction") { val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, emptySet()) val instruction = rule.getManualCleanupInstructionForOperatingSystem(OperatingSystem.Other) it("returns no instruction, since it will be covered by the removal rule's instruction") { assertThat(instruction, equalTo(null)) } } } })
app/src/unitTest/kotlin/batect/execution/model/rules/cleanup/StopContainerStepRuleSpec.kt
1496005413
package org.goskyer.service.impl import org.goskyer.domain.Post import org.goskyer.mapping.PostMapper import org.goskyer.service.PostService import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service /** * Created by zohar on 2017/4/17. * desc: */ @Service class PostServiceImpl: PostService { private val logger = LoggerFactory.getLogger(PostServiceImpl::class.java) @Autowired private lateinit var postMapper:PostMapper override fun getPostByPostId(postId: Int): Post { return postMapper.selectByPostId(postId) } override fun getPostsByUserId(userId: Int): MutableList<Post> { return postMapper.selectByUserId(userId) } override fun addPost(post: Post?): Int { val postId = postMapper.insertPost(post) return postMapper.insertTagPostTotal(post?.tags) } override fun deletePost(PostId: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
src/main/kotlin/org/goskyer/service/impl/PostServiceImpl.kt
1724322683
package com.ddu.ui.adapter import com.iannotation.model.RouteMeta /** * Created by yzbzz on 2018/9/12. */ class ContentItem(itemEntity: RouteMeta) { var colorString = itemEntity.color // override fun getType(): Int = -1 // // override fun variableId(): Int = -1 }
app/src/main/java/com/ddu/ui/adapter/ContentItem.kt
2308666267
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_pagos") class Pago : 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 = "forma_pago") var formaPago : String? = null @Column(name = "forma_pago_descripcion") var formaPagoDescripcion : String? = null @Column(name = "total") var total : BigDecimal? = null @Column(name = "plazo") var plazo : String? = null @Column(name = "tiempo") var tiempo : String? = null }
src/main/kotlin/com/quijotelui/model/Pago.kt
2608863779
package com.habitrpg.android.habitica.ui.views.shops import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import coil.load import com.habitrpg.android.habitica.extensions.dpToPx import com.habitrpg.android.habitica.extensions.fromHtml import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.loadImage abstract class PurchaseDialogContent @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { abstract val imageView: ImageView abstract val titleTextView: TextView init { orientation = VERTICAL gravity = Gravity.CENTER } open fun setItem(item: ShopItem) { if (item.path?.contains("timeTravelBackgrounds") == true) { imageView.load("${DataBindingUtils.BASE_IMAGE_URL}${item.imageName?.replace("icon_", "")}.gif") val params = imageView.layoutParams params.height = 147.dpToPx(context) params.width = 140.dpToPx(context) imageView.layoutParams = params } else { imageView.loadImage(item.imageName) } titleTextView.text = item.text } open fun setQuestContentItem(questContent: QuestContent) { imageView.loadImage("inventory_quest_scroll_" + questContent.key) titleTextView.setText(questContent.text.fromHtml(), TextView.BufferType.SPANNABLE) } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogContent.kt
2650484765
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.ar.core.codelabs.hellogeospatial import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.ar.core.Config import com.google.ar.core.Session import com.google.ar.core.codelabs.hellogeospatial.helpers.ARCoreSessionLifecycleHelper import com.google.ar.core.codelabs.hellogeospatial.helpers.GeoPermissionsHelper import com.google.ar.core.codelabs.hellogeospatial.helpers.HelloGeoView import com.google.ar.core.examples.java.common.helpers.FullScreenHelper import com.google.ar.core.examples.java.common.samplerender.SampleRender import com.google.ar.core.exceptions.CameraNotAvailableException import com.google.ar.core.exceptions.UnavailableApkTooOldException import com.google.ar.core.exceptions.UnavailableDeviceNotCompatibleException import com.google.ar.core.exceptions.UnavailableSdkTooOldException import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException class HelloGeoActivity : AppCompatActivity() { companion object { private const val TAG = "HelloGeoActivity" } lateinit var arCoreSessionHelper: ARCoreSessionLifecycleHelper lateinit var view: HelloGeoView lateinit var renderer: HelloGeoRenderer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Setup ARCore session lifecycle helper and configuration. arCoreSessionHelper = ARCoreSessionLifecycleHelper(this) // If Session creation or Session.resume() fails, display a message and log detailed // information. arCoreSessionHelper.exceptionCallback = { exception -> val message = when (exception) { is UnavailableUserDeclinedInstallationException -> "Please install Google Play Services for AR" is UnavailableApkTooOldException -> "Please update ARCore" is UnavailableSdkTooOldException -> "Please update this app" is UnavailableDeviceNotCompatibleException -> "This device does not support AR" is CameraNotAvailableException -> "Camera not available. Try restarting the app." else -> "Failed to create AR session: $exception" } Log.e(TAG, "ARCore threw an exception", exception) view.snackbarHelper.showError(this, message) } // Configure session features. arCoreSessionHelper.beforeSessionResume = ::configureSession lifecycle.addObserver(arCoreSessionHelper) // Set up the Hello AR renderer. renderer = HelloGeoRenderer(this) lifecycle.addObserver(renderer) // Set up Hello AR UI. view = HelloGeoView(this) lifecycle.addObserver(view) setContentView(view.root) // Sets up an example renderer using our HelloGeoRenderer. SampleRender(view.surfaceView, renderer, assets) } // Configure the session, setting the desired options according to your usecase. fun configureSession(session: Session) { // TODO: Configure ARCore to use GeospatialMode.ENABLED. } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, results: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, results) if (!GeoPermissionsHelper.hasGeoPermissions(this)) { // Use toast instead of snackbar here since the activity will exit. Toast.makeText(this, "Camera and location permissions are needed to run this application", Toast.LENGTH_LONG) .show() if (!GeoPermissionsHelper.shouldShowRequestPermissionRationale(this)) { // Permission denied with checking "Do not ask again". GeoPermissionsHelper.launchPermissionSettings(this) } finish() } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) FullScreenHelper.setFullScreenOnWindowFocusChanged(this, hasFocus) } }
app/src/main/java/com/google/ar/core/codelabs/hellogeospatial/HelloGeoActivity.kt
4019650558
package data.tinder.recommendation import com.squareup.moshi.Json internal class RecommendationUserSpotifyThemeTrackArtist private constructor( @field:Json(name = "name") val name: String, @field:Json(name = "id") val id: String)
data/src/main/kotlin/data/tinder/recommendation/RecommendationUserSpotifyThemeTrackArtist.kt
2386417413
/* * Copyright (C) 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.camera.integration.core import android.content.Context import android.os.Handler import android.os.HandlerThread import android.util.Size import android.view.Surface import androidx.annotation.GuardedBy import androidx.camera.camera2.Camera2Config import androidx.camera.camera2.pipe.integration.CameraPipeConfig import androidx.camera.core.AspectRatio import androidx.camera.core.CameraSelector import androidx.camera.core.CameraXConfig import androidx.camera.core.ExperimentalUseCaseApi import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageAnalysis.BackpressureStrategy import androidx.camera.core.ImageCapture import androidx.camera.core.ImageProxy import androidx.camera.core.impl.ImageOutputConfig import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.testing.CameraPipeConfigTestRule import androidx.camera.testing.CameraUtil import androidx.camera.testing.CameraUtil.PreTestCameraIdList import androidx.camera.testing.LabTestRule import androidx.camera.testing.fakes.FakeLifecycleOwner import androidx.test.core.app.ApplicationProvider import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.After import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized private val DEFAULT_CAMERA_SELECTOR = CameraSelector.DEFAULT_BACK_CAMERA @LargeTest @RunWith(Parameterized::class) internal class ImageAnalysisTest( private val implName: String, private val cameraConfig: CameraXConfig ) { @get:Rule val cameraPipeConfigTestRule = CameraPipeConfigTestRule( active = implName == CameraPipeConfig::class.simpleName, ) @get:Rule val cameraRule = CameraUtil.grantCameraPermissionAndPreTest( PreTestCameraIdList(cameraConfig) ) @get:Rule val labTest: LabTestRule = LabTestRule() companion object { private val DEFAULT_RESOLUTION = Size(640, 480) @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = listOf( arrayOf(Camera2Config::class.simpleName, Camera2Config.defaultConfig()), arrayOf(CameraPipeConfig::class.simpleName, CameraPipeConfig.defaultConfig()) ) } private val analysisResultLock = Any() private val context: Context = ApplicationProvider.getApplicationContext() @GuardedBy("analysisResultLock") private val analysisResults = mutableSetOf<ImageProperties>() private val analyzer = ImageAnalysis.Analyzer { image -> synchronized(analysisResultLock) { analysisResults.add(ImageProperties(image)) } analysisResultsSemaphore.release() image.close() } private lateinit var analysisResultsSemaphore: Semaphore private lateinit var handlerThread: HandlerThread private lateinit var handler: Handler private lateinit var cameraProvider: ProcessCameraProvider private lateinit var fakeLifecycleOwner: FakeLifecycleOwner @Before fun setUp(): Unit = runBlocking { ProcessCameraProvider.configureInstance(cameraConfig) cameraProvider = ProcessCameraProvider.getInstance(context)[10, TimeUnit.SECONDS] handlerThread = HandlerThread("AnalysisThread") handlerThread.start() handler = Handler(handlerThread.looper) analysisResultsSemaphore = Semaphore(0) withContext(Dispatchers.Main) { fakeLifecycleOwner = FakeLifecycleOwner() fakeLifecycleOwner.startAndResume() } } @After fun tearDown(): Unit = runBlocking { if (::cameraProvider.isInitialized) { withContext(Dispatchers.Main) { cameraProvider.unbindAll() cameraProvider.shutdown()[10, TimeUnit.SECONDS] } } if (::handler.isInitialized) { handlerThread.quitSafely() } } @Test fun exceedMaxImagesWithoutClosing_doNotCrash() = runBlocking { // Arrange. val queueDepth = 3 val semaphore = Semaphore(0) val useCase = ImageAnalysis.Builder() .setBackpressureStrategy(ImageAnalysis.STRATEGY_BLOCK_PRODUCER) .setImageQueueDepth(queueDepth) .build() val imageProxyList = mutableListOf<ImageProxy>() useCase.setAnalyzer( CameraXExecutors.newHandlerExecutor(handler), { image -> imageProxyList.add(image) semaphore.release() } ) // Act. withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle( fakeLifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, useCase ) } // Assert: waiting for images does not crash. assertThat(semaphore.tryAcquire(queueDepth + 1, 1, TimeUnit.SECONDS)).isFalse() // Clean it up. useCase.clearAnalyzer() for (image in imageProxyList) { image.close() } } @Test fun analyzesImages_withKEEP_ONLY_LATEST_whenCameraIsOpen() { analyzerAnalyzesImagesWithStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) } @Test fun analyzesImages_withBLOCK_PRODUCER_whenCameraIsOpen() { analyzerAnalyzesImagesWithStrategy(ImageAnalysis.STRATEGY_BLOCK_PRODUCER) } private fun analyzerAnalyzesImagesWithStrategy(@BackpressureStrategy strategy: Int) = runBlocking { val useCase = ImageAnalysis.Builder() .setBackpressureStrategy(strategy) .build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(handler), analyzer) analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS) synchronized(analysisResultLock) { assertThat(analysisResults).isNotEmpty() } } @LabTestRule.LabTestOnly // TODO(b/221321202): flaky on AndroidX test, @LabTestOnly should be removed after resolved. @Test fun analyzerDoesNotAnalyzeImages_whenCameraIsNotOpen() = runBlocking { val useCase = ImageAnalysis.Builder().build() // Bind but do not start lifecycle withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) cameraProvider.unbindAll() } useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(handler), analyzer) // Keep the lifecycle in an inactive state. // Wait a little while for frames to be analyzed. analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS) // No frames should have been analyzed. synchronized(analysisResultLock) { assertThat(analysisResults).isEmpty() } } @Test fun canObtainDefaultBackpressureStrategy() { val imageAnalysis = ImageAnalysis.Builder().build() assertThat(imageAnalysis.backpressureStrategy) .isEqualTo(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) } @Test @ExperimentalUseCaseApi fun canObtainBackgroundExecutor() { val ioExecutor = CameraXExecutors.ioExecutor() val imageAnalysis = ImageAnalysis.Builder() .setBackgroundExecutor(ioExecutor).build() val imageAnalysis2 = ImageAnalysis.Builder().build() // check return when provided an Executor assertThat(imageAnalysis.backgroundExecutor).isSameInstanceAs(ioExecutor) // check default return assertThat(imageAnalysis2.backgroundExecutor).isNull() } @Test fun canObtainDefaultImageQueueDepth() { val imageAnalysis = ImageAnalysis.Builder().build() // Should not be less than 1 assertThat(imageAnalysis.imageQueueDepth).isAtLeast(1) } @Test fun defaultAspectRatioWillBeSet_whenTargetResolutionIsNotSet() = runBlocking { val useCase = ImageAnalysis.Builder().build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } val config = useCase.currentConfig as ImageOutputConfig assertThat(config.targetAspectRatio).isEqualTo(AspectRatio.RATIO_4_3) } @Test fun defaultAspectRatioWontBeSet_whenTargetResolutionIsSet() = runBlocking { assumeTrue(CameraUtil.hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) val useCase = ImageAnalysis.Builder() .setTargetResolution(DEFAULT_RESOLUTION) .build() assertThat( useCase.currentConfig.containsOption(ImageOutputConfig.OPTION_TARGET_ASPECT_RATIO) ).isFalse() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle( fakeLifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, useCase ) } assertThat( useCase.currentConfig.containsOption(ImageOutputConfig.OPTION_TARGET_ASPECT_RATIO) ).isFalse() } @Test fun targetRotationCanBeUpdatedAfterUseCaseIsCreated() { val imageAnalysis = ImageAnalysis.Builder().setTargetRotation(Surface.ROTATION_0).build() imageAnalysis.targetRotation = Surface.ROTATION_90 assertThat(imageAnalysis.targetRotation).isEqualTo(Surface.ROTATION_90) } @Test fun targetResolutionIsUpdatedAfterTargetRotationIsUpdated() = runBlocking { val imageAnalysis = ImageAnalysis.Builder() .setTargetResolution(DEFAULT_RESOLUTION) .setTargetRotation(Surface.ROTATION_0) .build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle( fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, imageAnalysis ) } // Updates target rotation from ROTATION_0 to ROTATION_90. imageAnalysis.targetRotation = Surface.ROTATION_90 val newConfig = imageAnalysis.currentConfig as ImageOutputConfig val expectedTargetResolution = Size( DEFAULT_RESOLUTION.height, DEFAULT_RESOLUTION.width ) // Expected targetResolution will be reversed from original target resolution. assertThat(newConfig.targetResolution == expectedTargetResolution).isTrue() } @Test fun useCaseConfigCanBeReset_afterUnbind() = runBlocking { val useCase = ImageAnalysis.Builder().build() val initialConfig = useCase.currentConfig withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) cameraProvider.unbind(useCase) } val configAfterUnbinding = useCase.currentConfig assertThat(initialConfig == configAfterUnbinding).isTrue() } @Test fun targetRotationIsRetained_whenUseCaseIsReused() = runBlocking { // Generally, the device can't be rotated to Surface.ROTATION_180. Therefore, // use it to do the test. withContext(Dispatchers.Main) { val useCase = ImageAnalysis.Builder().build() cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) useCase.targetRotation = Surface.ROTATION_180 // Check the target rotation is kept when the use case is unbound. cameraProvider.unbind(useCase) assertThat(useCase.targetRotation).isEqualTo(Surface.ROTATION_180) // Check the target rotation is kept when the use case is rebound to the // lifecycle. cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) assertThat(useCase.targetRotation).isEqualTo(Surface.ROTATION_180) } } @Test @Throws(InterruptedException::class) fun useCaseCanBeReusedInSameCamera() = runBlocking { val useCase = ImageAnalysis.Builder().build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(handler), analyzer) assertThat(analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)).isTrue() withContext(Dispatchers.Main) { cameraProvider.unbind(useCase) } analysisResultsSemaphore = Semaphore( /*permits=*/0) // Rebind the use case to the same camera. withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } assertThat(analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)).isTrue() } @Test @Throws(InterruptedException::class) fun useCaseCanBeReusedInDifferentCamera() = runBlocking { val useCase = ImageAnalysis.Builder().build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(handler), analyzer) assertThat(analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)).isTrue() withContext(Dispatchers.Main) { cameraProvider.unbind(useCase) } analysisResultsSemaphore = Semaphore( /*permits=*/0) // Rebind the use case to different camera. withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, useCase) } assertThat(analysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)).isTrue() } @Test fun returnValidTargetRotation_afterUseCaseIsCreated() { val imageCapture = ImageCapture.Builder().build() assertThat(imageCapture.targetRotation).isNotEqualTo(ImageOutputConfig.INVALID_ROTATION) } @Test fun returnCorrectTargetRotation_afterUseCaseIsAttached() = runBlocking { val imageAnalysis = ImageAnalysis.Builder() .setTargetRotation(Surface.ROTATION_180) .build() withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle( fakeLifecycleOwner, DEFAULT_CAMERA_SELECTOR, imageAnalysis ) } assertThat(imageAnalysis.targetRotation).isEqualTo(Surface.ROTATION_180) } private data class ImageProperties( val resolution: Size, val format: Int, val timestamp: Long, val rotationDegrees: Int ) { constructor(image: ImageProxy) : this( Size(image.width, image.height), image.format, image.imageInfo.timestamp, image.imageInfo.rotationDegrees ) } }
camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/ImageAnalysisTest.kt
376944208
package com.github.dynamicextensionsalfresco.osgi import java.io.File /** * Value object representing the OSGi container configuration; * @author Laurens Fridael */ public class Configuration { var frameworkRestartEnabled = true var hotDeployEnabled = true var repositoryBundlesEnabled = true var storageDirectory: File? = null get() = $storageDirectory ?: File(System.getProperty("java.io.tmpdir"), "bundles") var systemPackageCacheMode: PackageCacheMode? = null val systemPackageCache = File(System.getProperty("java.io.tmpdir"), "system-packages.txt") }
alfresco-integration/src/main/kotlin/com/github/dynamicextensionsalfresco/osgi/Configuration.kt
1916741772
fun more(a: Int, b: Int) = a > b fun less(a: Int, b: Int) = a < b fun main(args: Array<String>) { if( more(5, 10) ) { println("5 is more than 10") } else { println("5 isn't more than 10") println("Some meaningless println") println("And one more") } if( less(2, 3)) { println("2 is less than 3") } else <selection>{ println("2 isn't less than 3") println("Some meaningless println") println("And one more") }</selection> }
kotlin-eclipse-ui-test/testData/wordSelection/selectPrevious/BlockStatements/3.kt
2311292538
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl import org.lwjgl.generator.* import org.lwjgl.system.linux.* val GLXContext = "GLXContext".opaque_p val GLXFBConfig = "GLXFBConfig".opaque_p val GLXFBConfig_p = GLXFBConfig.p val GLXFBConfigSGIX = "GLXFBConfigSGIX".opaque_p val GLXFBConfigSGIX_p = GLXFBConfigSGIX.p val GLXWindow = "GLXWindow".opaque_p val GLXDrawable = "GLXDrawable".opaque_p val GLXPixmap = "GLXPixmap".opaque_p val GLXContextID = typedef(XID, "GLXContextID") val GLXPbuffer = "GLXPbuffer".opaque_p fun configGLX() { struct(OPENGL_PACKAGE, "GLXStereoNotifyEventEXT", "glx", mutable = false) { int.member("type", "GenericEvent") unsigned_long.member("serial", "\\# of last request server processed") Bool.member("send_event", "{@code True} if generated by {@code SendEvent} request") Display_p.member("display", "display the event was read from") int.member("extension", "GLX major opcode, from {@code XQueryExtension}") int.member("evtype", "always {@code GLX_STEREO_NOTIFY_EXT}") GLXDrawable.member("window", "XID of the X window affected") Bool.member("stereo_tree", "{@code True} if tree contains stereo windows") } }
modules/templates/src/main/kotlin/org/lwjgl/opengl/GLXTypes.kt
3261106340
/* The MIT License (MIT) Derived from intellij-rust Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors Copyright (c) 2016 JetBrains Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.elmPerformanceTests import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.vfs.* import com.intellij.util.ui.UIUtil import org.elm.openapiext.fullyRefreshDirectory import org.elm.workspace.ElmWorkspaceTestBase import org.elm.workspace.elmWorkspace abstract class ElmRealProjectTestBase : ElmWorkspaceTestBase() { protected fun openRealProject(info: RealProjectInfo): VirtualFile? { val base = openRealProject("testData/${info.path}", info.exclude) if (base == null) { val name = info.name println("SKIP $name: git clone ${info.gitUrl} testData/$name") return null } return base } private fun openRealProject(path: String, exclude: List<String> = emptyList()): VirtualFile? { val projectDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) ?: return null fun isAppropriate(file: VirtualFile): Boolean { val relativePath = file.path.substring(projectDir.path.length + 1) // 1. Ignore excluded files if (exclude.any { relativePath.startsWith(it) }) return false // 2. Ignore hidden files if (file.name.startsWith(".")) return false // Otherwise, analyse it return true } runWriteAction { fullyRefreshDirectoryInUnitTests(projectDir) VfsUtil.copyDirectory(this, projectDir, elmWorkspaceDirectory, ::isAppropriate) fullyRefreshDirectoryInUnitTests(elmWorkspaceDirectory) } project.elmWorkspace.asyncDiscoverAndRefresh() UIUtil.dispatchAllInvocationEvents() return elmWorkspaceDirectory } class RealProjectInfo( val name: String, val path: String, val gitUrl: String, val exclude: List<String> = emptyList() ) companion object { val SPA = RealProjectInfo("elm-spa-example", "elm-spa-example", "https://github.com/rtfeldman/elm-spa-example") val ELM_CSS = RealProjectInfo("elm-css", "elm-css", "https://github.com/rtfeldman/elm-css", exclude = listOf("src/DEPRECATED", "tests")) val ELM_PHYSICS = RealProjectInfo("elm-physics", "elm-physics", "https://github.com/w0rm/elm-physics") val LIST_EXTRA = RealProjectInfo("elm-list-extra", "elm-list-extra", "https://github.com/elm-community/list-extra") val JSON_TREE_VIEW = RealProjectInfo("elm-json-tree-view", "elm-json-tree-view", "https://github.com/klazuka/elm-json-tree-view") val DEV_TOOLS = RealProjectInfo("elm-dev-tools", "elm-dev-tools", "https://github.com/opvasger/elm-dev-tools") } } fun VirtualFile.findDescendants(filter: (VirtualFile) -> Boolean): ArrayList<VirtualFile> { val result = ArrayList<VirtualFile>() VfsUtilCore.visitChildrenRecursively(this, object : VirtualFileVisitor<ArrayList<VirtualFile>>() { override fun visitFile(file: VirtualFile): Boolean { if (!file.isDirectory && filter(file)) result.add(file) return true } }) return result } fun fullyRefreshDirectoryInUnitTests(directory: VirtualFile) { // It's very weird, but real refresh occurs only if // we touch file names. At least in the test environment VfsUtilCore.iterateChildrenRecursively(directory, null) { it.name; true } fullyRefreshDirectory(directory) }
src/test/kotlin/org/elmPerformanceTests/ElmRealProjectTestBase.kt
2582621666
package com.baeldung.range import org.junit.Test import kotlin.test.assertEquals class UntilRangeTest { @Test fun testUntil() { assertEquals(listOf(1, 2, 3, 4), (1 until 5).toList()) } }
projects/tutorials-master/tutorials-master/core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt
3148160264
package com.veyndan.paper.reddit.post.media.mutator import android.support.annotation.StringRes import android.util.Size import com.veyndan.paper.reddit.BuildConfig import com.veyndan.paper.reddit.api.imgur.network.ImgurService import com.veyndan.paper.reddit.api.reddit.model.PostHint import com.veyndan.paper.reddit.api.reddit.model.Source import com.veyndan.paper.reddit.post.media.model.Image import com.veyndan.paper.reddit.post.model.Post import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory class ImgurMutatorFactory : MutatorFactory { companion object { val REGEX = Regex("""^https?://(?:m\.|www\.)?(i\.)?imgur\.com/(a/|gallery/)?(.*)$""") } override fun mutate(post: Post): Maybe<Post> { val matchResult = REGEX.matchEntire(post.linkUrl) return Single.just(post) .filter {BuildConfig.HAS_IMGUR_API_CREDENTIALS && matchResult != null} .map { val isAlbum = matchResult!!.groupValues[2].isNotEmpty() val isDirectImage = matchResult.groupValues[1].isNotEmpty() var linkUrl: String = it.linkUrl var postHint: PostHint = it.postHint if (!isAlbum && !isDirectImage) { // TODO .gifv links are HTML 5 videos so the PostHint should be set accordingly. if (!linkUrl.endsWith(".gifv")) { linkUrl = singleImageUrlToDirectImageUrl(linkUrl) postHint = PostHint.IMAGE } } val images: Observable<Image> if (isAlbum) { postHint = PostHint.IMAGE val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor { chain -> val request: Request = chain.request().newBuilder() .addHeader("Authorization", "Client-ID ${BuildConfig.IMGUR_API_KEY}") .build() chain.proceed(request) } .build() val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://api.imgur.com/3/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .client(client) .build() val imgurService: ImgurService = retrofit.create(ImgurService::class.java) val id: String = matchResult.groupValues[3] images = imgurService.album(id) .flattenAsObservable { basic -> basic.body()!!.data.images } .map { (width, height, link) -> Image(link, Size(width, height)) } } else { val imageDimensAvailable: Boolean = it.preview.images.isNotEmpty() val url: String = if (linkUrl.endsWith(".gifv") && imageDimensAvailable) it.preview.images[0].source.url else linkUrl val size = if (imageDimensAvailable) { val source: Source = it.preview.images[0].source Size(source.width, source.height) } else { Size(0, 0) } @StringRes val type: Int = if (linkUrl.endsWith(".gif") || linkUrl.endsWith(".gifv")) Image.IMAGE_TYPE_GIF else Image.IMAGE_TYPE_STANDARD images = Observable.just(Image(url, size, type)) } it.copy(it.medias.concatWith(images), linkUrl = linkUrl, postHint = postHint) } } /** * Returns a direct image url * (e.g. <a href="http://i.imgur.com/1AGVxLl.png">http://i.imgur.com/1AGVxLl.png</a>) from a * single image url (e.g. <a href="http://imgur.com/1AGVxLl">http://imgur.com/1AGVxLl</a>) * * @param url The single image url. * @return The direct image url. */ private fun singleImageUrlToDirectImageUrl(url: String): String { return "${HttpUrl.parse(url)!!.newBuilder().host("i.imgur.com").build()}.png" } }
app/src/main/java/com/veyndan/paper/reddit/post/media/mutator/ImgurMutatorFactory.kt
1448087708
package com.simplemobiletools.calculator.activities import android.app.Activity import android.appwidget.AppWidgetManager import android.content.Intent import android.content.res.ColorStateList import android.graphics.Color import android.os.Bundle import android.widget.Button import android.widget.RemoteViews import android.widget.SeekBar import com.simplemobiletools.calculator.R import com.simplemobiletools.calculator.extensions.config import com.simplemobiletools.calculator.helpers.MyWidgetProvider import com.simplemobiletools.commons.dialogs.ColorPickerDialog import com.simplemobiletools.commons.dialogs.FeatureLockedDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.IS_CUSTOMIZING_COLORS import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.widget_config.* class WidgetConfigureActivity : SimpleActivity() { private var mBgAlpha = 0f private var mWidgetId = 0 private var mBgColor = 0 private var mTextColor = 0 private var mBgColorWithoutTransparency = 0 private var mFeatureLockedDialog: FeatureLockedDialog? = null public override fun onCreate(savedInstanceState: Bundle?) { useDynamicTheme = false super.onCreate(savedInstanceState) setResult(Activity.RESULT_CANCELED) setContentView(R.layout.widget_config) initVariables() val isCustomizingColors = intent.extras?.getBoolean(IS_CUSTOMIZING_COLORS) ?: false mWidgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID && !isCustomizingColors) { finish() } config_save.setOnClickListener { saveConfig() } config_bg_color.setOnClickListener { pickBackgroundColor() } config_text_color.setOnClickListener { pickTextColor() } val primaryColor = getProperPrimaryColor() config_bg_seekbar.setColors(mTextColor, primaryColor, primaryColor) if (!isCustomizingColors && !isOrWasThankYouInstalled()) { mFeatureLockedDialog = FeatureLockedDialog(this) { if (!isOrWasThankYouInstalled()) { finish() } } } } override fun onResume() { super.onResume() window.decorView.setBackgroundColor(0) if (mFeatureLockedDialog != null && isOrWasThankYouInstalled()) { mFeatureLockedDialog?.dismissDialog() } setupToolbar(config_toolbar) } private fun initVariables() { mBgColor = config.widgetBgColor mBgAlpha = Color.alpha(mBgColor) / 255.toFloat() btn_reset.beVisible() mBgColorWithoutTransparency = Color.rgb(Color.red(mBgColor), Color.green(mBgColor), Color.blue(mBgColor)) config_bg_seekbar.setOnSeekBarChangeListener(seekbarChangeListener) config_bg_seekbar.progress = (mBgAlpha * 100).toInt() updateBackgroundColor() mTextColor = config.widgetTextColor updateTextColor() formula.text = "15,937*5" result.text = "79,685" } private fun saveConfig() { val appWidgetManager = AppWidgetManager.getInstance(this) ?: return val views = RemoteViews(packageName, R.layout.widget).apply { applyColorFilter(R.id.widget_background, mBgColor) } appWidgetManager.updateAppWidget(mWidgetId, views) storeWidgetColors() requestWidgetUpdate() Intent().apply { putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId) setResult(Activity.RESULT_OK, this) } finish() } private fun storeWidgetColors() { config.apply { widgetBgColor = mBgColor widgetTextColor = mTextColor } } private fun requestWidgetUpdate() { Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java).apply { putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId)) sendBroadcast(this) } } private fun updateBackgroundColor() { mBgColor = mBgColorWithoutTransparency.adjustAlpha(mBgAlpha) widget_background.applyColorFilter(mBgColor) config_bg_color.setFillWithStroke(mBgColor, mBgColor) config_save.backgroundTintList = ColorStateList.valueOf(getProperPrimaryColor()) } private fun updateTextColor() { config_text_color.setFillWithStroke(mTextColor, mTextColor) val viewIds = intArrayOf( R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4, R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8, R.id.btn_9, R.id.btn_percent, R.id.btn_power, R.id.btn_root, R.id.btn_clear, R.id.btn_reset, R.id.btn_divide, R.id.btn_multiply, R.id.btn_minus, R.id.btn_plus, R.id.btn_decimal, R.id.btn_equals ) result.setTextColor(mTextColor) formula.setTextColor(mTextColor) config_save.setTextColor(getProperPrimaryColor().getContrastColor()) viewIds.forEach { (findViewById<Button>(it)).setTextColor(mTextColor) } } private fun pickBackgroundColor() { ColorPickerDialog(this, mBgColorWithoutTransparency) { wasPositivePressed, color -> if (wasPositivePressed) { mBgColorWithoutTransparency = color updateBackgroundColor() } } } private fun pickTextColor() { ColorPickerDialog(this, mTextColor) { wasPositivePressed, color -> if (wasPositivePressed) { mTextColor = color updateTextColor() } } } private val seekbarChangeListener = object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { mBgAlpha = progress.toFloat() / 100.toFloat() updateBackgroundColor() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} } }
app/src/main/kotlin/com/simplemobiletools/calculator/activities/WidgetConfigureActivity.kt
3735371691
package com.commonsense.android.kotlin.views.databinding.activities import android.databinding.* import com.commonsense.android.kotlin.system.base.* /** * Created by kasper on 25/07/2017. */ abstract class BaseDatabindingActivityWithData<out view : ViewDataBinding, out Input> : BaseActivityData<Input>(), Databindable<view> { override val binding: view by lazy { createBinding().invoke(layoutInflater) } /** * if we have all required data then we can setup the view and use the binding :) */ override fun onSafeData() { setContentView(binding.root) binding.executePendingBindings() useBinding() } }
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/databinding/activities/BaseDatabindingActivityWithData.kt
2540988789
package ru.fantlab.android.ui.modules.settings import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import kotlinx.android.synthetic.main.activity_settings.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.SettingsModel import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.SettingsAdapter import ru.fantlab.android.ui.base.BaseActivity import ru.fantlab.android.ui.modules.settings.category.SettingsCategoryActivity import ru.fantlab.android.ui.modules.theme.ThemeActivity import ru.fantlab.android.ui.widgets.dialog.FontScaleBottomSheetDialog import ru.fantlab.android.ui.widgets.dialog.LanguageBottomSheetDialog import kotlin.reflect.KFunction0 class SettingsActivity : BaseActivity<SettingsMvp.View, SettingsPresenter>(), SettingsMvp.View, LanguageBottomSheetDialog.LanguageDialogViewActionCallback{ override fun isTransparent(): Boolean = false override fun providePresenter(): SettingsPresenter = SettingsPresenter() override fun layout(): Int = R.layout.activity_settings override fun canBack(): Boolean = true private val adapter: SettingsAdapter by lazy { SettingsAdapter(arrayListOf()) } private val THEME_CHANGE = 55 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = getString(R.string.settings) if (savedInstanceState == null) { setResult(RESULT_CANCELED) } adapter.listener = presenter recycler.addDivider() recycler.adapter = adapter adapter.addItem(SettingsModel(R.drawable.ic_language, getString(R.string.language), "", SettingsModel.LANGUAGE)) adapter.addItem(SettingsModel(R.drawable.ic_theme, getString(R.string.theme_title), "", SettingsModel.THEME)) //adapter.addItem(SettingsModel(R.drawable.ic_forum, getString(R.string.forum), "", SettingsModel.FORUM)) adapter.addItem(SettingsModel(R.drawable.ic_custom, getString(R.string.customization), getString(R.string.customizationHint), SettingsModel.CUSTOMIZATION)) hideShowShadow(true) } override fun onItemClicked(item: SettingsModel) { when (item.settingsType) { SettingsModel.THEME -> { startActivityForResult(Intent(this, ThemeActivity::class.java), THEME_CHANGE) } SettingsModel.LANGUAGE -> { showLanguageList() } else -> { val intent = Intent(this, SettingsCategoryActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.ITEM, item.settingsType) .put(BundleConstant.EXTRA, item.title) .end()) startActivity(intent) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == THEME_CHANGE && resultCode == Activity.RESULT_OK) { setResult(resultCode) finish() } } private fun showLanguageList() { val languageBottomSheetDialog = LanguageBottomSheetDialog() languageBottomSheetDialog.onAttach(this as Context) languageBottomSheetDialog.show(supportFragmentManager, "LanguageBottomSheetDialog") } override fun onLanguageChanged() { setResult(Activity.RESULT_OK) finish() } }
app/src/main/kotlin/ru/fantlab/android/ui/modules/settings/SettingsActivity.kt
3307723029
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.common.secrets import com.google.protobuf.ByteString import com.google.protobuf.kotlin.toByteString import java.nio.file.Path import java.util.Base64 /** * SecretSet that reads in a file and treats it as a two-column CSV file. * * The substring before the first comma (',') is treated as the map keys, and the remainder of the * string after the first comma is interpreted as a base64-encoded ByteString. */ class CsvSecretMap(path: Path) : SecretMap { private val contents: Map<String, ByteString> = path.toFile().readLines().associate { it.substringBefore(',') to Base64.getDecoder().decode(it.substringAfter(',')).toByteString() } override suspend fun get(key: String): ByteString? { return contents[key] } }
src/main/kotlin/org/wfanet/panelmatch/common/secrets/CsvSecretMap.kt
4121095392
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.exchangetasks import com.google.common.truth.Truth.assertThat import com.google.common.truth.extensions.proto.ProtoTruth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.StringValue import com.google.protobuf.kotlin.toByteString import com.google.protobuf.kotlin.toByteStringUtf8 import com.google.protobuf.stringValue import java.io.ByteArrayOutputStream import java.io.File import kotlin.test.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.storage.StorageClient import org.wfanet.measurement.storage.filesystem.FileSystemStorageClient import org.wfanet.panelmatch.common.ShardedFileName import org.wfanet.panelmatch.common.beam.map import org.wfanet.panelmatch.common.beam.testing.BeamTestBase import org.wfanet.panelmatch.common.beam.testing.assertThat import org.wfanet.panelmatch.common.parseDelimitedMessages import org.wfanet.panelmatch.common.storage.StorageFactory import org.wfanet.panelmatch.common.storage.toByteString import org.wfanet.panelmatch.common.testing.runBlockingTest private const val LABEL = "some-label" private const val BLOB_KEY = "some-blob-key" private val BLOB_CONTENTS = "some-data".toByteStringUtf8() @RunWith(JUnit4::class) class ApacheBeamContextTest : BeamTestBase() { @get:Rule val temporaryFolder = TemporaryFolder() private lateinit var storageFactory: StorageFactory private lateinit var storageClient: StorageClient @Before fun setup() { val path = temporaryFolder.root.path storageFactory = StorageFactory { FileSystemStorageClient(File(path)) } storageClient = storageFactory.build() } @Test fun readBlob() = runBlockingTest { val inputLabels = mapOf(LABEL to BLOB_KEY) val inputBlobs = mapOf(LABEL to storageClient.writeBlob(BLOB_KEY, BLOB_CONTENTS)) val context = ApacheBeamContext(pipeline, mapOf(), inputLabels, mapOf(), inputBlobs, storageFactory) assertThat(context.readBlob(LABEL)).isEqualTo(BLOB_CONTENTS) } @Test fun readBlobAsPCollection() = runBlockingTest { val inputLabels = mapOf(LABEL to BLOB_KEY) val inputBlobs = mapOf(LABEL to storageClient.writeBlob(BLOB_KEY, BLOB_CONTENTS)) val context = ApacheBeamContext(pipeline, mapOf(), inputLabels, mapOf(), inputBlobs, storageFactory) assertThat(context.readBlobAsPCollection(LABEL)).containsInAnyOrder(BLOB_CONTENTS) assertThat(context.readBlobAsView(LABEL)).containsInAnyOrder(BLOB_CONTENTS) pipeline.run() } @Test fun readShardedFile() = runBlockingTest { val inputLabels = mapOf(LABEL to BLOB_KEY) val inputBlobs = mapOf(LABEL to storageClient.writeBlob(BLOB_KEY, "foo-*-of-3".toByteStringUtf8())) val shard0Contents = serializeStringsAsProtos("a", "bc", "def") val shard1Contents = serializeStringsAsProtos("xy") val shard2Contents = serializeStringsAsProtos("z") storageClient.writeBlob("foo-0-of-3", shard0Contents) storageClient.writeBlob("foo-1-of-3", shard1Contents) storageClient.writeBlob("foo-2-of-3", shard2Contents) val context = ApacheBeamContext(pipeline, mapOf(), inputLabels, mapOf(), inputBlobs, storageFactory) val stringValueProtos = context.readShardedPCollection(LABEL, stringValue {}) assertThat(stringValueProtos.map { it.value }).containsInAnyOrder("a", "bc", "def", "xy", "z") pipeline.run() } @Test fun write() = runBlockingTest { val outputManifests = mapOf("some-output" to ShardedFileName("some-output-blobkey", 1)) val context = ApacheBeamContext(pipeline, mapOf(), mapOf(), outputManifests, mapOf(), storageFactory) val items = pcollectionOf("Test Collection", stringValue { value = "some-item" }) with(context) { items.writeShardedFiles("some-output") } pipeline.run() val blob = storageClient.getBlob("some-output-blobkey-0-of-1") assertNotNull(blob) val stringValues = blob.toByteString().parseDelimitedMessages(stringValue {}) assertThat(stringValues).containsExactly(stringValue { value = "some-item" }) } @Test fun writeSingleBlob() = runBlockingTest { val label = "some-label" val blobKey = "some-blob-key" val outputLabels = mapOf(label to blobKey) val context = ApacheBeamContext(pipeline, outputLabels, mapOf(), mapOf(), mapOf(), storageFactory) val item = stringValue { value = "some-item" } with(context) { pcollectionOf("Test Collection", item).writeSingleBlob(label) } pipeline.run() val blob = storageClient.getBlob(blobKey) assertNotNull(blob) assertThat(StringValue.parseFrom(blob.toByteString())).isEqualTo(item) } } private fun serializeStringsAsProtos(vararg items: String): ByteString { val output = ByteArrayOutputStream() items.forEach { stringValue { value = it }.writeDelimitedTo(output) } return output.toByteArray().toByteString() }
src/test/kotlin/org/wfanet/panelmatch/client/exchangetasks/ApacheBeamContextTest.kt
2233634104
/* * 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.debugger import com.intellij.openapi.editor.Document import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.util.PsiTreeUtil import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.tang.intellij.lua.psi.* /** * * Created by tangzx on 2017/5/1. */ abstract class LuaDebuggerEvaluator : XDebuggerEvaluator() { override fun getExpressionRangeAtOffset(project: Project, document: Document, offset: Int, sideEffectsAllowed: Boolean): TextRange? { var currentRange: TextRange? = null PsiDocumentManager.getInstance(project).commitAndRunReadAction { try { val file = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@commitAndRunReadAction if (currentRange == null) { val ele = file.findElementAt(offset) if (ele != null && ele.node.elementType == LuaTypes.ID) { val parent = ele.parent when (parent) { is LuaFuncDef, is LuaLocalFuncDef -> currentRange = ele.textRange is LuaClassMethodName, is PsiNameIdentifierOwner -> currentRange = parent.textRange } } } if (currentRange == null) { val expr = PsiTreeUtil.findElementOfClassAtOffset(file, offset, LuaExpr::class.java, false) currentRange = when (expr) { is LuaCallExpr, is LuaClosureExpr, is LuaLiteralExpr -> null else -> expr?.textRange } } } catch (ignored: IndexNotReadyException) { } } return currentRange } override fun evaluate(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?) { var expr = express.trim() if (!expr.endsWith(')')) { val lastDot = express.lastIndexOf('.') val lastColon = express.lastIndexOf(':') if (lastColon > lastDot) // a:xx -> a.xx expr = expr.replaceRange(lastColon, lastColon + 1, ".") } eval(expr, xEvaluationCallback, xSourcePosition) } protected abstract fun eval(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?) }
src/main/java/com/tang/intellij/lua/debugger/LuaDebuggerEvaluator.kt
1859675676
package com.teo.ttasks.util import android.content.Context import android.content.res.Resources import android.util.TypedValue import android.widget.Toast import androidx.annotation.AttrRes import androidx.annotation.StringRes fun Context.getColorFromAttr( @AttrRes attrColor: Int, typedValue: TypedValue = TypedValue(), resolveRefs: Boolean = true ): Int { theme.resolveAttribute(attrColor, typedValue, resolveRefs) return typedValue.data } /** * Display a short-lived Toast message. */ fun Context.toastShort(@StringRes resId: Int) { Toast.makeText(this, resId, Toast.LENGTH_SHORT).show() } /** * Display a short-lived Toast message. */ fun Context.toastShort(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
t-tasks/src/main/java/com/teo/ttasks/util/Extensions.kt
2385554891
package com.intfocus.template.general import java.util.concurrent.PriorityBlockingQueue import java.util.concurrent.ThreadFactory import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock /** * @author liuruilin * @data 2017/11/30 * @describe 带有开始/暂停功能的线程池 */ class PriorityThreadPoolExecutor( corePoolSize: Int, maximumPoolSize: Int, keepAliveTime: Long, unit: TimeUnit, workQueue: PriorityBlockingQueue<Runnable>, factory: ThreadFactory ): ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory) { private var isPause = false private var pauseLock = ReentrantLock() private var unPaused = pauseLock.newCondition() /** * 线程池任务执行前调用 */ override fun beforeExecute(t: Thread?, r: Runnable?) { super.beforeExecute(t, r) } /** * 线程池任务执行完毕后调用 */ override fun afterExecute(r: Runnable?, t: Throwable?) { super.afterExecute(r, t) } fun pause() { pauseLock.lock() try { isPause = true } finally { pauseLock.unlock() } } fun resume() { pauseLock.lock() try { isPause = false unPaused.signalAll() } finally { pauseLock.unlock() } } /** * 线程池终止后调用 */ override fun terminated() { super.terminated() } }
app/src/main/java/com/intfocus/template/general/PriorityThreadPoolExecutor.kt
2878045062
package com.eden.orchid.kss.menu import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.kss.model.KssModel import com.eden.orchid.kss.pages.KssPage @Description("All pages in your styleguide, optionally by section.", name = "Styleguide") class StyleguidePagesMenuItemType : OrchidMenuFactory("styleguide") { @Option @Description("The Styleguide section to get pages for.") lateinit var section: String override fun getMenuItems( context: OrchidContext, page: OrchidPage ): List<MenuItem> { val model = context.resolve(KssModel::class.java) val menuItems = ArrayList<MenuItem>() val pages = model.getSectionRoot(section) if (pages.isNotEmpty()) { menuItems.add(getChildMenuItem(context, null, pages)) } return menuItems } private fun getChildMenuItem(context: OrchidContext, parent: KssPage?, childPages: List<KssPage>): MenuItem { val childMenuItems = ArrayList<MenuItem>() val title: String? if (parent != null) { childMenuItems.add(MenuItem.Builder(context).page(parent).build()) title = parent.title } else { title = "Styleguide Pages" } childPages.forEach { childMenuItems.add(getChildMenuItem(context, it, it.children)) } return MenuItem.Builder(context) .title(title) .children(childMenuItems) .build() } }
plugins/OrchidKSS/src/main/kotlin/com/eden/orchid/kss/menu/StyleguidePagesMenuItemType.kt
1812179356
package jupyter.kotlin import java.util.HashMap import kotlin.reflect.KFunction import kotlin.reflect.KProperty /** * Kotlin REPL has built-in context for getting user-declared functions and variables * and setting invokeWrapper for additional side effects in evaluation. * It can be accessed inside REPL by name `kc`, e.g. kc.showVars() */ class KotlinContext( val vars: HashMap<String, KotlinVariableInfo> = HashMap(), val functions: HashMap<String, KotlinFunctionInfo> = HashMap() ) private fun functionSignature(function: KFunction<*>) = function.toString().replace("Line_\\d+\\.".toRegex(), "") private fun shortenType(name: String) = name.replace("(\\b[_a-zA-Z$][_a-zA-Z0-9$]*\\b\\.)+".toRegex(), "") class KotlinFunctionInfo(val function: KFunction<*>, val line: Any) : Comparable<KotlinFunctionInfo> { val name: String get() = function.name fun toString(shortenTypes: Boolean): String { return if (shortenTypes) { shortenType(toString()) } else toString() } override fun toString(): String { return functionSignature(function) } override fun compareTo(other: KotlinFunctionInfo): Int { return this.toString().compareTo(other.toString()) } override fun hashCode(): Int { return this.toString().hashCode() } override fun equals(other: Any?): Boolean { return if (other is KotlinFunctionInfo) { this.toString() == other.toString() } else false } } class KotlinVariableInfo(val value: Any?, val descriptor: KProperty<*>, val line: Any) { val name: String get() = descriptor.name @Suppress("MemberVisibilityCanBePrivate") val type: String get() = descriptor.returnType.toString() fun toString(shortenTypes: Boolean): String { var type: String = type if (shortenTypes) { type = shortenType(type) } return "$name: $type = $value" } override fun toString(): String { return toString(false) } }
jupyter-lib/lib/src/main/kotlin/jupyter/kotlin/context.kt
3280114952
package org.mitallast.queue.raft.protocol import io.vavr.collection.Vector import org.mitallast.queue.common.codec.Codec import org.mitallast.queue.common.codec.Message data class RaftSnapshot(val meta: RaftSnapshotMetadata, val data: Vector<Message>) : Message { fun toEntry(): LogEntry { return LogEntry(meta.lastIncludedTerm, meta.lastIncludedIndex, 0, this) } companion object { val codec = Codec.of( ::RaftSnapshot, RaftSnapshot::meta, RaftSnapshot::data, RaftSnapshotMetadata.codec, Codec.vectorCodec(Codec.anyCodec()) ) } }
src/main/java/org/mitallast/queue/raft/protocol/RaftSnapshot.kt
2206596963
package de.westnordost.streetcomplete.data.osm.mapdata import org.junit.Before import org.junit.Test import de.westnordost.streetcomplete.data.ApplicationDbTestCase import de.westnordost.osmapi.map.data.Element import de.westnordost.osmapi.map.data.OsmRelation import de.westnordost.osmapi.map.data.OsmRelationMember import de.westnordost.osmapi.map.data.Relation import org.junit.Assert.assertEquals class RelationDaoTest : ApplicationDbTestCase() { private lateinit var dao: RelationDao @Before fun createDao() { dao = RelationDao(dbHelper, RelationMapping(serializer)) } @Test fun putGetNoTags() { val members = listOf( OsmRelationMember(0, "outer", Element.Type.WAY), OsmRelationMember(1, "inner", Element.Type.WAY) ) val relation = OsmRelation(5, 1, members, null) dao.put(relation) val dbRelation = dao.get(5) checkEqual(relation, dbRelation!!) } @Test fun putGetWithTags() { val members = listOf( OsmRelationMember(0, "outer", Element.Type.WAY), OsmRelationMember(1, "inner", Element.Type.WAY) ) val relation = OsmRelation(5, 1, members, mapOf("a key" to "a value")) dao.put(relation) val dbRelation = dao.get(5) checkEqual(relation, dbRelation!!) } private fun checkEqual(relation: Relation, dbRelation: Relation) { assertEquals(relation.id, dbRelation.id) assertEquals(relation.version.toLong(), dbRelation.version.toLong()) assertEquals(relation.tags, dbRelation.tags) assertEquals(relation.members, dbRelation.members) } }
app/src/androidTest/java/de/westnordost/streetcomplete/data/osm/mapdata/RelationDaoTest.kt
3510560338
package org.worldcubeassociation.tnoodle.server.webscrambles.exceptions class ScrambleMatchingException(message: String) : Exception(message) { companion object { fun error(message: String): Nothing = throw ScrambleMatchingException(message) } }
webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/exceptions/ScrambleMatchingException.kt
1963489431
package lt.markmerkk.app.network.events /** * Represent movement event. * More info on events codes [lt.markmerkk.app.entities.Movement] */ class EventPlayerMovement( var connectionId: Int = -1, var movementEventCode: Int = -1 ) : NetworkEvent
core/src/main/java/lt/markmerkk/app/network/events/EventPlayerMovement.kt
992494535
package org.stepik.android.view.step_quiz_choice.ui.delegate import android.view.View import androidx.annotation.StringRes import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fragment_step_quiz.view.* import kotlinx.android.synthetic.main.layout_step_quiz_choice.view.* import org.stepic.droid.R import org.stepik.android.model.Reply import org.stepik.android.presentation.step_quiz.StepQuizFeature import org.stepik.android.presentation.step_quiz.model.ReplyResult import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate import org.stepik.android.view.step_quiz_choice.mapper.ChoiceStepQuizOptionsMapper import org.stepik.android.view.step_quiz_choice.model.Choice import org.stepik.android.view.step_quiz_choice.ui.adapter.ChoicesAdapterDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import ru.nobird.android.ui.adapters.selection.MultipleChoiceSelectionHelper import ru.nobird.android.ui.adapters.selection.SelectionHelper import ru.nobird.android.ui.adapters.selection.SingleChoiceSelectionHelper class ChoiceStepQuizFormDelegate( containerView: View, private val onQuizChanged: (ReplyResult) -> Unit ) : StepQuizFormDelegate { private val context = containerView.context private val quizDescription = containerView.stepQuizDescription private val choiceStepQuizOptionsMapper = ChoiceStepQuizOptionsMapper() private var choicesAdapter: DefaultDelegateAdapter<Choice> = DefaultDelegateAdapter() private lateinit var selectionHelper: SelectionHelper init { containerView.choicesRecycler.apply { itemAnimator = null adapter = choicesAdapter layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) isNestedScrollingEnabled = false } } override fun setState(state: StepQuizFeature.State.AttemptLoaded) { val dataset = state.attempt.dataset ?: return @StringRes val descriptionRes = if (dataset.isMultipleChoice) { R.string.step_quiz_choice_description_multiple } else { R.string.step_quiz_choice_description_single } quizDescription.setText(descriptionRes) val submission = (state.submissionState as? StepQuizFeature.SubmissionState.Loaded) ?.submission val reply = submission?.reply if (!::selectionHelper.isInitialized) { selectionHelper = if (dataset.isMultipleChoice) { MultipleChoiceSelectionHelper(choicesAdapter) } else { SingleChoiceSelectionHelper(choicesAdapter) } choicesAdapter += ChoicesAdapterDelegate(selectionHelper, onClick = ::handleChoiceClick) } choicesAdapter.items = choiceStepQuizOptionsMapper.mapChoices( dataset.options ?: emptyList(), reply?.choices, submission, StepQuizFormResolver.isQuizEnabled(state) ) selectionHelper.reset() reply?.choices?.let { it.forEachIndexed { index, choice -> if (choice) { selectionHelper.select(index) } } } } override fun createReply(): ReplyResult { val choices = (0 until choicesAdapter.itemCount).map { selectionHelper.isSelected(it) } return if ((true !in choices && selectionHelper is SingleChoiceSelectionHelper)) { ReplyResult(Reply(choices = choices), ReplyResult.Validation.Error(context.getString(R.string.step_quiz_choice_empty_reply))) } else { ReplyResult(Reply(choices = choices), ReplyResult.Validation.Success) } } private fun handleChoiceClick(choice: Choice) { when (selectionHelper) { is SingleChoiceSelectionHelper -> selectionHelper.select(choicesAdapter.items.indexOf(choice)) is MultipleChoiceSelectionHelper -> selectionHelper.toggle(choicesAdapter.items.indexOf(choice)) } onQuizChanged(createReply()) } }
app/src/main/java/org/stepik/android/view/step_quiz_choice/ui/delegate/ChoiceStepQuizFormDelegate.kt
3116972302
package ii_collections fun example5() { val result = listOf("a", "bbb", "cc").sortedBy { it.length } result == listOf("a", "cc", "bbb") } // Return a list of customers, sorted by the ascending number of orders they made fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> = this.customers.sortedBy { it.orders.size }
src/ii_collections/_18_Sort_.kt
4080813075
package cn.tino.animatedwebp import javafx.application.Application import main.java.cn.tino.animatedwebp.Styles import tornadofx.* /** * mailTo:[email protected] * Created by tino on 2017 June 17, 18:00. */ class AnimatedWebpKt : App(MainScreen::class) { init { importStylesheet(Styles::class) } } fun main(args: Array<String>) { Application.launch(AnimatedWebpKt::class.java, *args) }
src/main/java/cn/tino/animatedwebp/AnimatedWebpKt.kt
67949349
package tv.fanart import club.minnced.discord.webhook.WebhookClientBuilder import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.choice import com.github.ajalt.clikt.parameters.types.path import com.google.gson.GsonBuilder import kotlinx.coroutines.runBlocking import okhttp3.OkHttpClient import org.koin.core.context.startKoin import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import tv.fanart.api.AuthInterceptor import tv.fanart.api.FanartApi import tv.fanart.bot.FanartBot import tv.fanart.bot.UpdateBot import tv.fanart.config.ConfigRepo import tv.fanart.config.model.UpdateConfig import tv.fanart.discord.ChangeMapper import tv.fanart.discord.DiscordWebhookClient import tv.fanart.util.DateDeserializer import java.nio.file.Path import java.nio.file.Paths import java.time.ZoneId import java.util.* fun main(args: Array<String>) = object : CliktCommand() { val configPath: Path by option( "-c", "--config", help = "Location of config file" ).path( writable = true, readable = true ).default( Paths.get(System.getProperty("user.home"), ".config", "fanart-tv", "discord-bot", "config.hocon") ) val logLevel: String by option( "-l", "--logging", help = "Loggin level" ).choice("OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE").default("INFO") override fun run() = runBlocking { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, logLevel) val configModule = module { single { ConfigRepo(configPath) } } val apiModule = module { single { AuthInterceptor(get<ConfigRepo>().updateConfig?.apiKey ?: UpdateConfig.DEFAULT_API_KEY) } single { Retrofit.Builder() .baseUrl("https://webservice.fanart.tv") .client(OkHttpClient.Builder().addInterceptor(get<AuthInterceptor>()).build()) .addConverterFactory( GsonConverterFactory.create( GsonBuilder().registerTypeAdapter( Date::class.java, DateDeserializer( ZoneId.of( get<ConfigRepo>().updateConfig?.serverTimezone ?: UpdateConfig.DEFAULT_TIMEZONE ) ) ).create() ) ) .build() } single { get<Retrofit>().create(FanartApi::class.java) } } val discordModule = module { single { get<ConfigRepo>().updateConfig?.let { DiscordWebhookClient( WebhookClientBuilder( it.webhookId, it.webhookToken ).build() ) } } single { ChangeMapper() } } val botModule = module { single { UpdateBot(get(), get(), get()) } } startKoin { printLogger() modules(listOf(configModule, apiModule, discordModule, botModule)) } FanartBot().start() } }.main(args)
src/main/kotlin/tv/fanart/Application.kt
2201339489
package org.logout.notifications.telegram.bot import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.logout.notifications.telegram.bot.processor.DissentProcessor import org.logout.notifications.telegram.bot.processor.HelpProcessor import org.logout.notifications.telegram.bot.processor.StaImaNextEventProcessor import org.logout.notifications.telegram.bot.processor.StartProcessor import org.logout.notifications.telegram.data.events.EventRegistry import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.io.FileInputStream @Configuration open class CommonBotConfiguration { @Value("\${data.event.fileName}") lateinit var eventFileName: String @Bean open fun eventRegistry() = EventRegistry(FileInputStream(eventFileName), jacksonObjectMapper()) @Bean open fun staImaNextEventProcessor(eventRegistry: EventRegistry) = StaImaNextEventProcessor(eventRegistry) @Bean open fun helpProcessor() = HelpProcessor() @Bean open fun startProcessor() = StartProcessor() @Bean open fun dissentProcessor() = DissentProcessor() }
src/main/kotlin/org/logout/notifications/telegram/bot/CommonBotConfiguration.kt
3631586484
package org.asqatasun.web.user import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl import org.springframework.stereotype.Service import javax.annotation.PostConstruct import javax.sql.DataSource @Service class UserDetailsService(private val asqaDataSource: DataSource) : JdbcDaoImpl() { @PostConstruct fun init() { setDataSource(asqaDataSource) usersByUsernameQuery = USERS_BY_USERNAME_QUERY authoritiesByUsernameQuery = AUTHORITIES_BY_USERNAME_QUERY } override fun createUserDetails(username: String, userFromUserQuery: UserDetails, combinedAuthorities: List<GrantedAuthority>): UserDetails { return User(username, userFromUserQuery.password, combinedAuthorities) } companion object { private const val USERS_BY_USERNAME_QUERY = "SELECT Email1, Password, Activated as enabled FROM USER WHERE Email1=?" private const val AUTHORITIES_BY_USERNAME_QUERY = ("SELECT USER.Email1, ROLE.Role_Name as authorities FROM USER, ROLE " + "WHERE USER.Email1 = ? AND USER.ROLE_Id_Role=ROLE.Id_Role") } }
server/asqatasun-server/src/main/kotlin/org/asqatasun/web/user/UserDetailsService.kt
2865924806
package com.example.android.testing.nativesample import androidx.test.ext.junitgtest.GtestRunner import androidx.test.ext.junitgtest.TargetLibrary import org.junit.runner.RunWith // Run our tests with the `GtestRunner`, which knows how to load and run GTest suites. @RunWith(GtestRunner::class) // Specify the name of the artifact which contains our tests, as configured in CMakeLists.txt @TargetLibrary(libraryName = "adder-test") class AdderTest
unit/BasicNativeAndroidTest/app/src/androidTest/java/com/example/android/testing/nativesample/AdderTest.kt
716126674
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("DumbModeUtils") package org.jetbrains.kotlin.idea.base.util import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal fun <T> Project.runReadActionInSmartMode(action: () -> T): T { if (ApplicationManager.getApplication().isReadAccessAllowed) return action() return DumbService.getInstance(this).runReadActionInSmartMode(action) } @ApiStatus.Internal fun <T> Project.runWithAlternativeResolveEnabled(action: () -> T): T { @Suppress("UNCHECKED_CAST") var result: T = null as T DumbService.getInstance(this).withAlternativeResolveEnabled { result = action() } @Suppress("USELESS_CAST") return result as T } @ApiStatus.Internal fun Project.runWhenSmart(action: () -> Unit) { DumbService.getInstance(this).runWhenSmart(action) }
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/DumbModeUtils.kt
1660912690
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.utils.DayTester /** * Test for Day25 * @author Jelle Stege */ class Day25Test : DayTester(Day25())
aoc-2015/src/test/kotlin/nl/jstege/adventofcode/aoc2015/days/Day25Test.kt
3467968264
package ktn.pe import java.util.Arrays import java.util.concurrent.Executors import java.util.concurrent.TimeUnit /** * */ object Main { private const val PROBLEM_MIN = 1 private const val PROBLEM_MAX = 12 private const val THREAD_COUNT = 4 /** * @param args * problemNumber options... */ @JvmStatic fun main(args: Array<String>) { if (args.isEmpty()) { help() } else if ("-h" == args[0] || "--help" == args[0]) { help() } else if ("-a" == args[0]) { solveAll() } else if ("-A" == args[0]) { var n = -1 if (args.size > 1) { n = args[1].toInt() } solveAllAsync(n) } else { if (!solve(args)) { help() } } } /** * Show help */ private fun help() { println("problemNumber options...") println("-a all") println("-A [n] all async with n threads") println("-h help") } /** * * @param n * @return */ private fun loadClassName(n: Int): String { return Main::class.java.`package`.name + ".Pe" + n } /** * * @param args * commandline options * @return true means */ internal fun solve(args: Array<String>): Boolean { var done = false try { val n = args[0].toInt() if (n < PROBLEM_MIN || n > PROBLEM_MAX) { return done } val loader = ClassLoader.getSystemClassLoader() val clazz = loader.loadClass(loadClassName(n)) val pe = clazz.newInstance() as Pe val shiftedArgs = Arrays.copyOfRange(args, 1, args.size) pe.setArgs(shiftedArgs) val start = System.currentTimeMillis() pe.solve() val stop = System.currentTimeMillis() println((stop - start).toString() + " ms") done = true } catch (e: NumberFormatException) { System.err.println(e.toString()) } catch (e: ClassNotFoundException) { System.err.println(e.toString()) } catch (e: InstantiationException) { System.err.println(e.toString()) } catch (e: IllegalAccessException) { System.err.println(e.toString()) } return done } private fun solveAll() { val loader = ClassLoader.getSystemClassLoader() var clazz: Class<*> var pe: Pe val start = System.currentTimeMillis() try { for (i in PROBLEM_MIN until PROBLEM_MAX + 1) { clazz = loader.loadClass(loadClassName(i)) pe = clazz.newInstance() as Pe pe.solve() } } catch (e: ClassNotFoundException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } val stop = System.currentTimeMillis() println((stop - start).toString() + " ms") } private fun solveAllAsync(n: Int) { var threadCount = THREAD_COUNT if (n > 0) { threadCount = n } val executor = Executors.newFixedThreadPool(threadCount) val loader = ClassLoader.getSystemClassLoader() val start = System.currentTimeMillis() try { (PROBLEM_MIN until PROBLEM_MAX + 1) .map { loader.loadClass(loadClassName(it)) } .map { it.getDeclaredConstructor().newInstance() as Pe } .forEach { executor.execute(it) } } catch (e: ClassNotFoundException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } val awaitTime = (30 * 1000).toLong() try { executor.shutdown() if (!executor.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)) { executor.shutdownNow() } } catch (e: InterruptedException) { println("awaitTermination interrupted: " + e) executor.shutdownNow() } val stop = System.currentTimeMillis() println((stop - start).toString() + " ms") } }
kt/pe/src/main/kotlin/ktn/pe/Main.kt
3529018192
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.Panel import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.internal.component.impl.DefaultPanel import org.hexworks.zircon.internal.component.renderer.DefaultPanelRenderer import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic @Suppress("UNCHECKED_CAST") @ZirconDsl class PanelBuilder private constructor() : BaseContainerBuilder<Panel, PanelBuilder>( initialRenderer = DefaultPanelRenderer() ) { override fun build(): Panel { return DefaultPanel( componentMetadata = createMetadata(), renderingStrategy = createRenderingStrategy(), initialTitle = title, ).apply { addComponents(*childrenToAdd.toTypedArray()) }.attachListeners() } override fun createCopy() = newBuilder() .withProps(props.copy()) .withChildren(*childrenToAdd.toTypedArray()) override fun calculateContentSize(): Size { // best effort val result = childrenToAdd.map { it.size }.fold(Size.zero(), Size::plus) return if (result < Size.one()) Size.one() else result } companion object { @JvmStatic fun newBuilder() = PanelBuilder() } }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/PanelBuilder.kt
1941962268
package org.hexworks.zircon.internal.component.impl import org.hexworks.zircon.api.behavior.TextOverride import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.component.Paragraph import org.hexworks.zircon.api.component.data.ComponentMetadata import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy import org.hexworks.zircon.api.uievent.Pass import org.hexworks.zircon.api.uievent.UIEventResponse class DefaultParagraph internal constructor( componentMetadata: ComponentMetadata, initialText: String, renderingStrategy: ComponentRenderingStrategy<Paragraph> ) : Paragraph, TextOverride by TextOverride.create(initialText), DefaultComponent( metadata = componentMetadata, renderer = renderingStrategy ) { override fun acceptsFocus() = false override fun focusGiven(): UIEventResponse = Pass override fun focusTaken(): UIEventResponse = Pass override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toSecondaryContentStyle() }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultParagraph.kt
2543164599
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.services import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.expressions.Variable import org.jetbrains.annotations.TestOnly /** * COMPATIBILITY-LAYER: Renamed from VimVariableService * Please see: https://jb.gg/zo8n0r */ interface VariableService { /** * Stores variable. * * The `v:` scope currently is not supported. * @param variable variable to store, if it's scope is null, the default scope for vimContext will be chosen * @param value variable value * @param editor editor * @param context execution context * @param vimContext vim context * @throws ExException("The 'v:' scope is not implemented yet :(") */ fun storeVariable(variable: Variable, value: VimDataType, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext) /** * Get global scope variable value. * @param name variable name */ fun getGlobalVariableValue(name: String): VimDataType? /** * Gets variable value * * The `v:` scope currently is not supported * @param variable variable, if it's scope is null, the default scope for vimContext will be chosen * @param editor editor * @param context execution context * @param vimContext vim context * @throws ExException("The 'v:' scope is not implemented yet :(") */ fun getNullableVariableValue(variable: Variable, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType? /** * Gets variable value. * * The `v:` scope currently is not supported. * @param variable variable, if it's scope is null, the default scope for vimContext will be chosen * @param editor editor * @param context execution context * @param vimContext vim context * @throws ExException("The 'v:' scope is not implemented yet :(") * @throws ExException("E121: Undefined variable: ${scope}:${name}") */ fun getNonNullVariableValue(variable: Variable, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType /** * Checks if the variable locked. * * Returns false if the variable does not exist. * * See `:h lockvar`. * @param variable variable, if it's scope is null, the default scope for vimContext will be chosen * @param editor editor * @param context execution context * @param vimContext vim context */ fun isVariableLocked(variable: Variable, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): Boolean /** * Locks variable. * * See `:h lockvar`. * @param variable variable, if it's scope is null, the default scope for vimContext will be chosen * @param depth lock depth * @param editor editor * @param context execution context * @param vimContext vim context */ fun lockVariable(variable: Variable, depth: Int, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext) /** * Unlocks variable. * * See `:h lockvar`. * @param variable variable, if it's scope is null, the default scope for vimContext will be chosen * @param depth lock depth * @param editor editor * @param context execution context * @param vimContext vim context */ fun unlockVariable(variable: Variable, depth: Int, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext) fun getGlobalVariables(): Map<String, VimDataType> /** * Clears all global variables */ @TestOnly fun clear() }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/services/VariableService.kt
3919154380
fun foo(x: Boolean, y: Boolean) { <selection>x || y && x</selection> }
plugins/kotlin/idea/tests/testData/codeInsight/surroundWith/withIfExpression/complexBoolean.kt
1316213135
// PROBLEM: none enum class MyEnum(val i: Int) { HELLO<caret>(42), WORLD("42") ; constructor(s: String): this(42) } fun test() { MyEnum.HELLO }
plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedSymbol/unusedEnumEntry.kt
301697934
package com.wearefrancis.auth.exception import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatus(HttpStatus.NOT_FOUND) class EntityNotFoundException(message: String) : RuntimeException(message) { companion object { val logger = LoggerFactory.getLogger(EntityNotFoundException::class.java)!! } init { logger.info(message) } }
src/main/kotlin/com/wearefrancis/auth/exception/EntityNotFoundException.kt
2115320690
package dev.mfazio.pennydrop.types import dev.mfazio.pennydrop.game.AI data class Player( var playerName: String = "", var isHuman: Boolean = true, var selectedAI: AI? = null ) { var pennies: Int = defaultPennyCount fun addPennies(count: Int = 1) { pennies += count } var isRolling: Boolean = false companion object { const val defaultPennyCount = 10 } }
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-3/app/src/main/java/dev/mfazio/pennydrop/types/Player.kt
3969761431
/* * Copyright 2021 Armory, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.controllers import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.netflix.spinnaker.orca.api.test.OrcaFixture import com.netflix.spinnaker.orca.api.test.orcaFixture import com.netflix.spinnaker.q.discovery.DiscoveryActivator import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.post import strikt.api.expectThat import strikt.assertions.isEqualTo import strikt.assertions.isFalse import strikt.assertions.isTrue class AdminControllerTest : JUnit5Minutests { fun tests() = rootContext<Fixture> { orcaFixture { Fixture() } test("/admin/instance/enabled endpoint can disable queue Activator") { // wait up to 5 seconds for discoveryActivator to initialize for (i in 1..5) { if (discoveryActivator.enabled){ println("discoveryActivator.enabled = true. Start") break } println("discoveryActivator.enabled = false. Sleep 1sec") Thread.sleep(1000L) } expectThat(discoveryActivator.enabled).isTrue() val response = mockMvc.post("/admin/instance/enabled") { contentType = MediaType.APPLICATION_JSON content = jacksonObjectMapper().writeValueAsString(mapOf("enabled" to false)) }.andReturn().response expectThat(response.status).isEqualTo(200) expectThat(discoveryActivator.enabled).isFalse() } } @AutoConfigureMockMvc class Fixture : OrcaFixture() { @Autowired lateinit var mockMvc: MockMvc @Autowired lateinit var discoveryActivator: DiscoveryActivator } }
orca-web/src/test/kotlin/com/netflix/spinnaker/orca/controllers/AdminControllerTest.kt
307309877
package io.ipoli.android.growth.sideeffect import io.ipoli.android.common.AppSideEffectHandler import io.ipoli.android.common.AppState import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.redux.Action import io.ipoli.android.growth.GrowthAction import io.ipoli.android.growth.usecase.CalculateGrowthStatsUseCase import space.traversal.kapsule.required object GrowthSideEffectHandler : AppSideEffectHandler() { private val calculateGrowthStatsUseCase by required { calculateGrowthStatsUseCase } private val permissionChecker by required { permissionChecker } override suspend fun doExecute(action: Action, state: AppState) { when (action) { is GrowthAction.Load -> { val canReadAppUsageData = permissionChecker.canReadAppUsageStats() val result = calculateGrowthStatsUseCase.execute( CalculateGrowthStatsUseCase.Params(includeAppUsageStats = canReadAppUsageData) ) dispatch( DataLoadedAction.GrowthChanged( dailyGrowth = result.todayGrowth, weeklyGrowth = result.weeklyGrowth, monthlyGrowth = result.monthlyGrowth, includesAppUsageData = canReadAppUsageData ) ) } } } override fun canHandle(action: Action) = action is GrowthAction.Load }
app/src/main/java/io/ipoli/android/growth/sideeffect/GrowthSideEffectHandler.kt
2481024643
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.util.collect import android.text.TextUtils /** * A List implementation that emits toString() calls as comma separated values, useful for * something like multi-get requests in retrofit. * * @param <E> the element type */ class CommaJoinerList<E> constructor(delegate: List<E>) : List<E> by delegate { override fun toString(): String = TextUtils.join(",", this) } fun <T> List<T>.toCommaJoinerList() = CommaJoinerList(this)
libraries/util/src/main/kotlin/io/sweers/catchup/util/collect/CommaJoinerList.kt
1591641280
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script.configuration import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.ide.scratch.ScratchUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ProjectExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotifications import com.intellij.util.ui.UIUtil import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.core.script.* import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptConfigurationManagerExtensions.LOADER import org.jetbrains.kotlin.idea.core.script.configuration.cache.* import org.jetbrains.kotlin.idea.core.script.configuration.loader.DefaultScriptConfigurationLoader import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoader import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoadingContext import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptOutsiderFileConfigurationLoader import org.jetbrains.kotlin.idea.core.script.configuration.utils.* import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder import org.jetbrains.kotlin.idea.core.util.EDT import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import org.jetbrains.kotlin.scripting.resolve.ScriptReportSink import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.script.experimental.api.ScriptDiagnostic /** * Standard implementation of scripts configuration loading and caching. * * ## Loading initiation * * [getOrLoadConfiguration] will be called when we need to show or analyze some script file. * * As described in [DefaultScriptingSupportBase], configuration may be loaded from [cache] * or [reloadOutOfDateConfiguration] will be called on [cache] miss. * * There are 2 tiers [cache]: memory and FS. For now FS cache implemented by [ScriptConfigurationLoader] * because we are not storing classpath roots yet. As a workaround cache.all() will return only memory * cached configurations. So, for now we are indexing roots that loaded from FS with * default [reloadOutOfDateConfiguration] mechanics. * * Also, [ensureLoadedFromCache] may be called from [UnusedSymbolInspection] * to ensure that configuration of all scripts containing some symbol are up-to-date or try load it in sync. * * ## Loading * * When requested, configuration will be loaded using first applicable [loaders]. * It can work synchronously or asynchronously. * * Synchronous loader will be called just immediately. Despite this, its result may not be applied immediately, * see next section for details. * * Asynchronous loader will be called in background thread (by [BackgroundExecutor]). * * ## Applying * * By default loaded configuration will *not* be applied immediately. Instead, we show in editor notification * that suggests user to apply changed configuration. This was done to avoid sporadically starting indexing of new roots, * which may happens regularly for large Gradle projects. * * Notification will be displayed when configuration is going to be updated. First configuration will be loaded * without notification. * * This behavior may be disabled by enabling "auto reload" in project settings. * When enabled, all loaded configurations will be applied immediately, without any notification. * * ## Concurrency * * Each files may be in on of this state: * - scriptDefinition is not ready * - not loaded * - up-to-date * - invalid, in queue (in [BackgroundExecutor] queue) * - invalid, loading * - invalid, waiting for apply * * [reloadOutOfDateConfiguration] guard this states. See it's docs for more details. */ class DefaultScriptingSupport(manager: CompositeScriptConfigurationManager) : DefaultScriptingSupportBase(manager) { // TODO public for tests internal val backgroundExecutor: BackgroundExecutor = when { isUnitTestMode() -> @Suppress("TestOnlyProblems") TestingBackgroundExecutor(manager) else -> DefaultBackgroundExecutor(project, manager) } private val outsiderLoader = ScriptOutsiderFileConfigurationLoader(project) private val fileAttributeCache = ScriptConfigurationFileAttributeCache(project) private val defaultLoader = DefaultScriptConfigurationLoader(project) private val loaders: List<ScriptConfigurationLoader> get() = mutableListOf<ScriptConfigurationLoader>().apply { add(outsiderLoader) add(fileAttributeCache) addAll(LOADER.getPoint(project).extensionList) add(defaultLoader) } private val saveLock = ReentrantLock() override fun createCache(): ScriptConfigurationCache = object : ScriptConfigurationMemoryCache(project) { override fun setLoaded(file: VirtualFile, configurationSnapshot: ScriptConfigurationSnapshot) { super.setLoaded(file, configurationSnapshot) fileAttributeCache.save(file, configurationSnapshot) } } /** * Will be called on [cache] miss to initiate loading of [file]'s script configuration. * * ## Concurrency * * Each files may be in on of the states described below: * - scriptDefinition is not ready. `ScriptDefinitionsManager.getInstance(project).isReady() == false`. * [updateScriptDefinitionsReferences] will be called when [ScriptDefinitionsManager] will be ready * which will call [reloadOutOfDateConfiguration] for opened editors. * - unknown. When [isFirstLoad] true (`cache[file] == null`). * - up-to-date. `cache[file]?.upToDate == true`. * - invalid, in queue. `cache[file]?.upToDate == false && file in backgroundExecutor`. * - invalid, loading. `cache[file]?.upToDate == false && file !in backgroundExecutor`. * - invalid, waiting for apply. `cache[file]?.upToDate == false && file !in backgroundExecutor` and has notification panel? * - invalid, waiting for update. `cache[file]?.upToDate == false` and has notification panel * * Async: * - up-to-date: [reloadOutOfDateConfiguration] will not be called. * - `unknown` and `invalid, in queue`: * Concurrent async loading will be guarded by `backgroundExecutor.ensureScheduled` * (only one task per file will be scheduled at same time) * - `invalid, loading` * Loading should be removed from `backgroundExecutor`, and will be rescheduled on change * and file will be up-to-date checked again. This will happen after current loading, * because only `backgroundExecutor` execute tasks in one thread. * - `invalid, waiting for apply`: * Loading will not be queued, since we are marking file as up-to-date with * not yet applied configuration. * - `invalid, waiting for update`: * Loading wasn't started, only notification is shown * * Sync: * - up-to-date: * [reloadOutOfDateConfiguration] will not be called. * - all other states, i.e: `unknown`, `invalid, in queue`, `invalid, loading` and `invalid, ready for apply`: * everything will be computed just in place, possible concurrently. * [suggestOrSaveConfiguration] calls will be serialized by the [saveLock] */ override fun reloadOutOfDateConfiguration( file: KtFile, isFirstLoad: Boolean, forceSync: Boolean, fromCacheOnly: Boolean, skipNotification: Boolean ): Boolean { val virtualFile = file.originalFile.virtualFile ?: return false if (project.isDisposed || !ScriptDefinitionsManager.getInstance(project).isReady()) return false val scriptDefinition = file.findScriptDefinition() ?: return false val (async, sync) = loaders.partition { it.shouldRunInBackground(scriptDefinition) } val syncLoader = sync.filter { it.loadDependencies(isFirstLoad, file, scriptDefinition, loadingContext) }.firstOrNull() return if (syncLoader == null) { if (!fromCacheOnly) { if (forceSync) { loaders.firstOrNull { it.loadDependencies(isFirstLoad, file, scriptDefinition, loadingContext) } } else { val autoReloadEnabled = KotlinScriptingSettings.getInstance(project).autoReloadConfigurations(scriptDefinition) val forceSkipNotification = skipNotification || autoReloadEnabled // sync loaders can do something, let's recheck val isFirstLoadActual = getCachedConfigurationState(virtualFile)?.applied == null val intercepted = !forceSkipNotification && async.any { it.interceptBackgroundLoading(virtualFile, isFirstLoadActual) { runAsyncLoaders(file, virtualFile, scriptDefinition, listOf(it), true) } } if (!intercepted) { runAsyncLoaders(file, virtualFile, scriptDefinition, async, forceSkipNotification) } } } false } else { true } } private fun runAsyncLoaders( file: KtFile, virtualFile: VirtualFile, scriptDefinition: ScriptDefinition, loaders: List<ScriptConfigurationLoader>, forceSkipNotification: Boolean ) { backgroundExecutor.ensureScheduled(virtualFile) { val cached = getCachedConfigurationState(virtualFile) val applied = cached?.applied if (applied != null && applied.inputs.isUpToDate(project, virtualFile)) { // in case user reverted to applied configuration suggestOrSaveConfiguration(virtualFile, applied, forceSkipNotification) } else if (cached == null || !cached.isUpToDate(project, virtualFile)) { // don't start loading if nothing was changed // (in case we checking for up-to-date and loading concurrently) val actualIsFirstLoad = cached == null loaders.firstOrNull { it.loadDependencies(actualIsFirstLoad, file, scriptDefinition, loadingContext) } } } } @TestOnly fun runLoader(file: KtFile, loader: ScriptConfigurationLoader): ScriptCompilationConfigurationWrapper? { val virtualFile = file.originalFile.virtualFile ?: return null if (!ScriptDefinitionsManager.getInstance(project).isReady()) return null val scriptDefinition = file.findScriptDefinition() ?: return null manager.updater.update { loader.loadDependencies(false, file, scriptDefinition, loadingContext) } return getAppliedConfiguration(virtualFile)?.configuration } private val loadingContext = object : ScriptConfigurationLoadingContext { /** * Used from [ScriptOutsiderFileConfigurationLoader] only. */ override fun getCachedConfiguration(file: VirtualFile): ScriptConfigurationSnapshot? = getAppliedConfiguration(file) ?: getFromGlobalCache(file) private fun getFromGlobalCache(file: VirtualFile): ScriptConfigurationSnapshot? { val info = manager.getLightScriptInfo(file.path) ?: return null return ScriptConfigurationSnapshot(CachedConfigurationInputs.UpToDate, listOf(), info.buildConfiguration()) } override fun suggestNewConfiguration(file: VirtualFile, newResult: ScriptConfigurationSnapshot) { suggestOrSaveConfiguration(file, newResult, false) } override fun saveNewConfiguration(file: VirtualFile, newResult: ScriptConfigurationSnapshot) { suggestOrSaveConfiguration(file, newResult, true) } } private fun suggestOrSaveConfiguration( file: VirtualFile, newResult: ScriptConfigurationSnapshot, forceSkipNotification: Boolean ) { saveLock.withLock { scriptingDebugLog(file) { "configuration received = $newResult" } setLoadedConfiguration(file, newResult) hideInterceptedNotification(file) val newConfiguration = newResult.configuration if (newConfiguration == null) { saveReports(file, newResult.reports) return } val old = getCachedConfigurationState(file) val oldConfiguration = old?.applied?.configuration if (oldConfiguration != null && areSimilar(oldConfiguration, newConfiguration)) { saveReports(file, newResult.reports) file.removeScriptDependenciesNotificationPanel(project) return } val skipNotification = forceSkipNotification || oldConfiguration == null || ApplicationManager.getApplication().isUnitTestModeWithoutScriptLoadingNotification if (skipNotification) { if (oldConfiguration != null) { file.removeScriptDependenciesNotificationPanel(project) } saveReports(file, newResult.reports) setAppliedConfiguration(file, newResult, syncUpdate = true) return } scriptingDebugLog(file) { "configuration changed, notification is shown: old = $oldConfiguration, new = $newConfiguration" } // restore reports for applied configuration in case of previous error old?.applied?.reports?.let { saveReports(file, it) } file.addScriptDependenciesNotificationPanel( newConfiguration, project, onClick = { saveReports(file, newResult.reports) file.removeScriptDependenciesNotificationPanel(project) manager.updater.update { setAppliedConfiguration(file, newResult) } } ) } } private fun saveReports( file: VirtualFile, newReports: List<ScriptDiagnostic> ) { val oldReports = IdeScriptReportSink.getReports(file) if (oldReports != newReports) { scriptingDebugLog(file) { "new script reports = $newReports" } project.service<ScriptReportSink>().attachReports(file, newReports) GlobalScope.launch(EDT(project)) { if (project.isDisposed) return@launch val ktFile = PsiManager.getInstance(project).findFile(file) if (ktFile != null) { DaemonCodeAnalyzer.getInstance(project).restart(ktFile) } EditorNotifications.getInstance(project).updateAllNotifications() } } } fun ensureNotificationsRemoved(file: VirtualFile) { if (cache.remove(file)) { saveReports(file, listOf()) file.removeScriptDependenciesNotificationPanel(project) } // this notification can be shown before something will be in cache hideInterceptedNotification(file) } fun updateScriptDefinitionsReferences() { // remove notification for all files cache.allApplied().forEach { (file, _) -> saveReports(file, listOf()) file.removeScriptDependenciesNotificationPanel(project) hideInterceptedNotification(file) } cache.clear() } private fun hideInterceptedNotification(file: VirtualFile) { loaders.forEach { it.hideInterceptedNotification(file) } } companion object { fun getInstance(project: Project) = (ScriptConfigurationManager.getInstance(project) as CompositeScriptConfigurationManager).default } } /** * Abstraction for [DefaultScriptingSupportBase] based [cache] and [reloadOutOfDateConfiguration]. * Among this two methods concrete implementation should provide script changes listening. * * Basically all requests routed to [cache]. If there is no entry in [cache] or it is considered out-of-date, * then [reloadOutOfDateConfiguration] will be called, which, in turn, should call [setAppliedConfiguration] * immediately or in some future (e.g. after user will click "apply context" or/and configuration will * be calculated by some background thread). * * [ScriptClassRootsCache] will be calculated based on [cache]d configurations. * Every change in [cache] will invalidate [ScriptClassRootsCache] cache. */ abstract class DefaultScriptingSupportBase(val manager: CompositeScriptConfigurationManager) { val project: Project get() = manager.project @Suppress("LeakingThis") protected val cache: ScriptConfigurationCache = createCache() protected abstract fun createCache(): ScriptConfigurationCache /** * Will be called on [cache] miss or when [file] is changed. * Implementation should initiate loading of [file]'s script configuration and call [setAppliedConfiguration] * immediately or in some future * (e.g. after user will click "apply context" or/and configuration will be calculated by some background thread). * * @param isFirstLoad may be set explicitly for optimization reasons (to avoid expensive fs cache access) * @param forceSync should be used in tests only * @param isPostponedLoad is used to postspone loading: show a notification for out of date script and start loading when user request * @param fromCacheOnly load only when builtin fast synchronous loaders are available * @return true, if configuration loaded in sync */ protected abstract fun reloadOutOfDateConfiguration( file: KtFile, isFirstLoad: Boolean = getAppliedConfiguration(file.originalFile.virtualFile) == null, forceSync: Boolean = false, fromCacheOnly: Boolean = false, skipNotification: Boolean = false ): Boolean internal fun getCachedConfigurationState(file: VirtualFile?): ScriptConfigurationState? { if (file == null) return null return cache[file] } fun getAppliedConfiguration(file: VirtualFile?): ScriptConfigurationSnapshot? = getCachedConfigurationState(file)?.applied private fun hasCachedConfiguration(file: KtFile): Boolean = getAppliedConfiguration(file.originalFile.virtualFile) != null fun isConfigurationLoadingInProgress(file: KtFile): Boolean { return !hasCachedConfiguration(file) } fun getOrLoadConfiguration( virtualFile: VirtualFile, preloadedKtFile: KtFile? ): ScriptCompilationConfigurationWrapper? { val cached = getAppliedConfiguration(virtualFile) if (cached != null) return cached.configuration val ktFile = project.getKtFile(virtualFile, preloadedKtFile) ?: return null manager.updater.update { reloadOutOfDateConfiguration(ktFile, isFirstLoad = true) } return getAppliedConfiguration(virtualFile)?.configuration } /** * Load new configuration and suggest applying it (only if it is changed) */ fun ensureUpToDatedConfigurationSuggested(file: KtFile, skipNotification: Boolean = false, forceSync: Boolean = false) { reloadIfOutOfDate(file, skipNotification, forceSync) } private fun reloadIfOutOfDate(file: KtFile, skipNotification: Boolean = false, forceSync: Boolean = false) { if (!forceSync && !ScriptDefinitionsManager.getInstance(project).isReady()) return manager.updater.update { file.originalFile.virtualFile?.let { virtualFile -> val state = cache[virtualFile] if (state == null || forceSync || !state.isUpToDate(project, virtualFile, file)) { reloadOutOfDateConfiguration( file, forceSync = forceSync, isFirstLoad = state == null, skipNotification = skipNotification ) } } } } fun isLoadedFromCache(file: KtFile): Boolean { if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false return file.originalFile.virtualFile?.let { cache[it] != null } ?: true } /** * Ensure that any configuration for [files] is loaded from cache */ fun ensureLoadedFromCache(files: List<KtFile>): Boolean { if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false var allLoaded = true manager.updater.update { files.forEach { file -> file.originalFile.virtualFile?.let { virtualFile -> cache[virtualFile] ?: run { if (!reloadOutOfDateConfiguration( file, isFirstLoad = true, fromCacheOnly = true ) ) { allLoaded = false } } } } } return allLoaded } protected open fun setAppliedConfiguration( file: VirtualFile, newConfigurationSnapshot: ScriptConfigurationSnapshot?, syncUpdate: Boolean = false ) { manager.updater.checkInTransaction() val newConfiguration = newConfigurationSnapshot?.configuration scriptingDebugLog(file) { "configuration changed = $newConfiguration" } if (newConfiguration != null) { cache.setApplied(file, newConfigurationSnapshot) manager.updater.invalidate(file, synchronous = syncUpdate) } } protected fun setLoadedConfiguration( file: VirtualFile, configurationSnapshot: ScriptConfigurationSnapshot ) { cache.setLoaded(file, configurationSnapshot) } @TestOnly internal fun updateScriptDependenciesSynchronously(file: PsiFile) { file.findScriptDefinition() ?: return file as? KtFile ?: error("PsiFile $file should be a KtFile, otherwise script dependencies cannot be loaded") val virtualFile = file.virtualFile if (cache[virtualFile]?.isUpToDate(project, virtualFile, file) == true) return manager.updater.update { reloadOutOfDateConfiguration(file, forceSync = true) } UIUtil.dispatchAllInvocationEvents() } private fun collectConfigurationsWithCache(builder: ScriptClassRootsBuilder) { // own builder for saving to storage val rootsStorage = ScriptClassRootsStorage.getInstance(project) val storageBuilder = ScriptClassRootsBuilder.fromStorage(project, rootsStorage) val ownBuilder = ScriptClassRootsBuilder(storageBuilder) cache.allApplied().forEach { (vFile, configuration) -> ownBuilder.add(vFile, configuration) if (!ScratchUtil.isScratch(vFile)) { // do not store (to disk) scratch file configurations due to huge dependencies // (to be indexed next time - even if you don't use scratches at all) storageBuilder.add(vFile, configuration) } } storageBuilder.toStorage(rootsStorage) builder.add(ownBuilder) } fun collectConfigurations(builder: ScriptClassRootsBuilder) { if (isFSRootsStorageEnabled()) { collectConfigurationsWithCache(builder) } else { cache.allApplied().forEach { (vFile, configuration) -> builder.add(vFile, configuration) } } } } internal fun isFSRootsStorageEnabled(): Boolean = Registry.`is`("kotlin.scripting.fs.roots.storage.enabled") object DefaultScriptConfigurationManagerExtensions { val LOADER: ProjectExtensionPointName<ScriptConfigurationLoader> = ProjectExtensionPointName("org.jetbrains.kotlin.scripting.idea.loader") } val ScriptConfigurationManager.testingBackgroundExecutor: TestingBackgroundExecutor get() { @Suppress("TestOnlyProblems") return (this as CompositeScriptConfigurationManager).default.backgroundExecutor as TestingBackgroundExecutor }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/DefaultScriptingSupport.kt
196905478
package io.github.sdsstudios.ScoreKeeper.Adapters import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.utils.DrawableUtils import io.github.sdsstudios.ScoreKeeper.GameListItem import io.github.sdsstudios.ScoreKeeper.SelectableBackground import io.github.sdsstudios.ScoreKeeper.ViewHolders.GameListItemHolder import kotlin.coroutines.experimental.buildSequence /** * Created by sethsch1 on 29/01/18. */ class GameListAdapter( private val mShowGameState: Boolean, onItemClickListener: OnItemClickListener ) : FlexibleAdapter<GameListItem>(ArrayList()) { val selectedIds: LongArray get() = buildSequence { selectedPositions.forEach { position -> yield(getItem(position)!!.id) } }.toList().toLongArray() init { addListener(onItemClickListener) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val viewHolder = super.onCreateViewHolder(parent, viewType) as GameListItemHolder val drawable = SelectableBackground.create(viewHolder.itemView.context) DrawableUtils.setBackgroundCompat(viewHolder.itemView, drawable) if (mShowGameState) { viewHolder.textViewState.visibility = View.VISIBLE } return viewHolder } }
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Adapters/GameListAdapter.kt
2484235738
interface <lineMarker descr="Is implemented by SkipSupportImpl SkipSupportWithDefaults Click or press ... to navigate">SkipSupport</lineMarker> { fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportImpl<br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportWithDefaults</body></html>">skip</lineMarker>(why: String) fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportWithDefaults</body></html>">skip</lineMarker>() } public interface <lineMarker descr="Is implemented by SkipSupportImpl Click or press ... to navigate">SkipSupportWithDefaults</lineMarker> : SkipSupport { override fun <lineMarker descr="<html><body>Is overridden in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportImpl</body></html>"><lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker></lineMarker>(why: String) {} override fun <lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker>() { skip("not given") } } open class SkipSupportImpl: SkipSupportWithDefaults { override fun <lineMarker descr="Overrides function in 'SkipSupportWithDefaults'">skip</lineMarker>(why: String) = throw RuntimeException(why) } // KT-4428 Incorrect override icon shown for overloaded methods
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverrideIconForOverloadMethodBug.kt
810511867
// IS_APPLICABLE: false // WITH_STDLIB fun foo(): List<String> = emptyList() @Target(AnnotationTarget.TYPE) annotation class Foo fun test(): <caret>List<@Foo String> = foo()
plugins/kotlin/idea/tests/testData/intentions/removeExplicitType/hasAnnotationOnTypeArgument.kt
1369907967
// 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.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.* class FoldIfToReturnAsymmetricallyIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("replace.if.expression.with.return") ) { override fun applicabilityRange(element: KtIfExpression): TextRange? { if (BranchedFoldingUtils.getFoldableBranchedReturn(element.then) == null || element.`else` != null) { return null } val nextElement = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as? KtReturnExpression if (nextElement?.returnedExpression == null) return null return element.ifKeyword.textRange } override fun applyTo(element: KtIfExpression, editor: Editor?) { val condition = element.condition ?: return val thenBranch = element.then ?: return val elseBranch = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as? KtReturnExpression ?: return val psiFactory = KtPsiFactory(element) val newIfExpression = psiFactory.createIf(condition, thenBranch, elseBranch) val thenReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.then!!) ?: return val elseReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.`else`!!) ?: return thenReturn.replace(thenReturn.returnedExpression!!) elseReturn.replace(elseReturn.returnedExpression!!) element.replace(psiFactory.createExpressionByPattern("return $0", newIfExpression)) elseBranch.delete() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt
3006462206
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor import com.intellij.ide.ui.OptionsSearchTopHitProvider import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.options.ex.ConfigurableWrapper class KotlinEditorOptionsTopHitProvider : OptionsSearchTopHitProvider.ApplicationLevelProvider { override fun getId(): String = ID override fun getOptions(): Collection<OptionDescription> = kotlinEditorOptionsDescriptors .map { c -> if (c is ConfigurableWrapper) c.configurable else c } .filterIsInstance<OptionDescription>().toList() }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinEditorOptionsTopHitProvider.kt
2327816676
package json import org.spek.Spek import java.util.HashMap import java.util.ArrayList import kotlin.test.assertEquals import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ContainerNode import com.fasterxml.jackson.databind.node import org.vertx.java.core.json.JsonObject import org.fest.assertions.Assertions import org.fest.assertions.Assertions.* class JsonBuilderSpec : Spek() { fun String.j(): JsonNode { return ObjectMapper().readTree(this)!! } { given("a simple builder") { on("Mapping a key to a value", { val j = json { obj { "k" to "v" } } assertEquals(j.json(), """ {"k": "v"} """.j()) }) on("Mapping 2 key/value pair") { assertEquals( json { obj { "k" to "v" "k2" to "v2" } }.json() , """ {"k": "v", "k2": "v2"} """.j()) } } } }
src/test/kotlin/json/JsonBuilderSpec.kt
2663861549
package club.guacamoledragon.plugin.driver import club.guacamoledragon.plugin.kapchat.Client import club.guacamoledragon.plugin.kapchat.Message import club.guacamoledragon.plugin.ui.ChatRoom import java.awt.Dimension import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import javax.swing.JFrame import javax.swing.WindowConstants fun main(args: Array<String>) { val frame = JFrame("Twitch Chat") val chatroom = ChatRoom() frame.size = Dimension(500, 500) frame.contentPane.add(chatroom.panel) frame.setLocationRelativeTo(null) frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE frame.isVisible = true var kapchatClient: Client = Client("MrsViolence") val onMessageHandler = { msg: Message -> chatroom.appendMessage(msg.nick, msg.message, msg.userData.color) } val onDisconnectHandler: () -> Unit = { kapchatClient = Client(chatroom.channelField.text) kapchatClient .onMessage(onMessageHandler) .connect() } kapchatClient .onMessage(onMessageHandler) .onDisconnect(onDisconnectHandler) .connect() chatroom.goButton.addActionListener { event -> kapchatClient.disconnect() } frame.addWindowListener(object: WindowAdapter() { override fun windowClosing(e: WindowEvent?) { kapchatClient.disconnect() } }) } // Part 4: 1080p @ 30fps/3000bps 02/09/2016 // Part 5: 1080p @ 30fps/3000bps 02/11/2016 // Part 6: 1080p @ 30fps/3000bps 02/11/2016 // Part 7: 1080p @ 30fps/3000bps 02/11/2016
src/test/kotlin/club/guacamoledragon/plugin/driver/kapchat.kt
3635093596
/* * 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.codeInspection.inheritance import com.intellij.CommonBundle import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.* import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.JvmModifiersOwner import com.intellij.lang.jvm.JvmNamedElement import com.intellij.lang.jvm.actions.MemberRequest import com.intellij.lang.jvm.actions.createModifierActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.* import com.intellij.uast.UastSmartPointer import com.intellij.uast.createUastSmartPointer import com.intellij.util.IncorrectOperationException import com.intellij.util.SmartList import org.jetbrains.uast.UClass import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.toUElementOfType class ImplicitSubclassInspection : LocalInspectionTool() { private fun checkClass(aClass: UClass, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { val psiClass = aClass.javaPsi val classIsFinal = aClass.isFinal || psiClass.hasModifierProperty(PsiModifier.PRIVATE) val problems = SmartList<ProblemDescriptor>() val subclassProviders = ImplicitSubclassProvider.EP_NAME.extensions .asSequence().filter { it.isApplicableTo(psiClass) } val subclassInfos = subclassProviders.mapNotNull { it.getSubclassingInfo(psiClass) } val methodsToOverride = aClass.methods.mapNotNull { method -> subclassInfos .mapNotNull { it.methodsInfo?.get(method.javaPsi)?.description } .firstOrNull()?.let { description -> method to description } } val methodsToAttachToClassFix = if (classIsFinal) SmartList<UastSmartPointer<UDeclaration>>() else null for ((method, description) in methodsToOverride) { if (method.isFinal || method.isStatic || method.javaPsi.hasModifierProperty(PsiModifier.PRIVATE)) { methodsToAttachToClassFix?.add(method.createUastSmartPointer()) val methodFixes = createFixesIfApplicable(method, method.name) problemTargets(method, methodHighlightableModifiersSet).forEach { problems.add(manager.createProblemDescriptor( it, description, isOnTheFly, methodFixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)) } } } if (classIsFinal) { val classReasonToBeSubclassed = subclassInfos.firstOrNull()?.description if ((methodsToOverride.isNotEmpty() || classReasonToBeSubclassed != null)) { problemTargets(aClass, classHighlightableModifiersSet).forEach { problems.add(manager.createProblemDescriptor( it, classReasonToBeSubclassed ?: InspectionsBundle.message("inspection.implicit.subclass.display.forClass", psiClass.name), isOnTheFly, createFixesIfApplicable(aClass, psiClass.name ?: "class", methodsToAttachToClassFix ?: emptyList()), ProblemHighlightType.GENERIC_ERROR_OR_WARNING) ) } } } return problems.toTypedArray() } private fun createFixesIfApplicable(aClass: UDeclaration, hintTargetName: String, methodsToAttachToClassFix: List<UastSmartPointer<UDeclaration>> = emptyList()): Array<LocalQuickFix> { val fix = MakeExtendableFix(aClass, hintTargetName, methodsToAttachToClassFix) if (!fix.hasActionsToPerform) return emptyArray() return arrayOf(fix) } private fun problemTargets(declaration: UDeclaration, highlightableModifiersSet: Set<String>): List<PsiElement> { val modifiersElements = getRelatedJavaModifiers(declaration, highlightableModifiersSet) if (modifiersElements.isNotEmpty()) return modifiersElements return listOfNotNull(declaration.uastAnchor?.sourcePsi) } private fun getRelatedJavaModifiers(declaration: UDeclaration, highlightableModifiersSet: Set<String>): List<PsiElement> { val modifierList = (declaration.sourcePsi as? PsiModifierListOwner)?.modifierList ?: return emptyList() return modifierList.children.filter { it is PsiKeyword && highlightableModifiersSet.contains(it.getText()) } } private val methodHighlightableModifiersSet = setOf(PsiModifier.FINAL, PsiModifier.PRIVATE, PsiModifier.STATIC) private val classHighlightableModifiersSet = setOf(PsiModifier.FINAL, PsiModifier.PRIVATE) private class MakeExtendableFix(uDeclaration: UDeclaration, hintTargetName: String, val siblings: List<UastSmartPointer<UDeclaration>> = emptyList()) : LocalQuickFixOnPsiElement(uDeclaration.sourcePsi!!) { companion object { private val LOG = Logger.getInstance("#com.intellij.codeInspection.inheritance.MakeExtendableFix") } private val actionsToPerform = SmartList<IntentionAction>() val hasActionsToPerform: Boolean get() = actionsToPerform.isNotEmpty() init { collectMakeExtendable(uDeclaration, actionsToPerform) for (sibling in siblings) { sibling.element?.let { collectMakeExtendable(it, actionsToPerform, checkParent = false) } } } override fun getFamilyName(): String = QuickFixBundle.message("fix.modifiers.family") override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { try { for (intentionAction in actionsToPerform) { if (intentionAction.isAvailable(project, null, file)) intentionAction.invoke(project, null, file) } } catch (e: IncorrectOperationException) { if (ApplicationManager.getApplication().isUnitTestMode) throw e ApplicationManager.getApplication().invokeLater { Messages.showErrorDialog(project, e.message, CommonBundle.getErrorTitle()) } LOG.info(e) } } private fun collectMakeExtendable(declaration: UDeclaration, actionsList: SmartList<IntentionAction>, checkParent: Boolean = true) { val isClassMember = declaration !is JvmClass addIfApplicable(declaration, JvmModifier.FINAL, false, actionsList) addIfApplicable(declaration, JvmModifier.PRIVATE, false, actionsList) if (isClassMember) { addIfApplicable(declaration, JvmModifier.STATIC, false, actionsList) } if (checkParent && isClassMember) { (declaration.uastParent as? UClass)?.apply { addIfApplicable(this, JvmModifier.FINAL, false, actionsList) addIfApplicable(this, JvmModifier.PRIVATE, false, actionsList) } } } private fun addIfApplicable(declaration: JvmModifiersOwner, modifier: JvmModifier, shouldPresent: Boolean, actionsList: SmartList<IntentionAction>) { if (declaration.hasModifier(modifier) == shouldPresent) return val request = MemberRequest.Modifier(modifier, shouldPresent) actionsList += createModifierActions(declaration, request) } private val MAX_MESSAGES_TO_COMBINE = 3 private val text = when (uDeclaration) { is UClass -> if (actionsToPerform.size <= MAX_MESSAGES_TO_COMBINE) actionsToPerform.joinToString { it.text } else InspectionsBundle.message("inspection.implicit.subclass.make.class.extendable", hintTargetName, siblings.size, siblingsDescription()) else -> if (actionsToPerform.size <= MAX_MESSAGES_TO_COMBINE) actionsToPerform.joinToString { it.text } else InspectionsBundle.message("inspection.implicit.subclass.extendable", hintTargetName) } private fun siblingsDescription() = when (siblings.size) { 1 -> "'${(siblings.firstOrNull()?.element?.javaPsi as? JvmNamedElement)?.name}'" else -> "" } override fun getText(): String = text } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) val uClass = element.toUElementOfType<UClass>() ?: return val problems = checkClass(uClass, holder.manager, isOnTheFly) ?: return for (problem in problems) { holder.registerProblem(problem) } } } }
java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ImplicitSubclassInspection.kt
3030945270
package au.com.tilbrook.android.rxkotlin.utils import rx.Subscription /** * Created by Mitchell Tilbrook on 28/10/15. */ fun Subscription?.unSubscribeIfNotNull() { this?.unsubscribe() }
app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/utils/utils.kt
33660190
package lt.markmerkk.mvp interface HostServicesInteractor { fun copyText(inputText: String) fun ticketWebLinkToClipboard(webLinkToTicket: String) fun openLink(link: String) }
components/src/main/java/lt/markmerkk/mvp/HostServicesInteractor.kt
3551463171
package lt.markmerkk.widgets.dialogs import lt.markmerkk.ResultDispatcher import lt.markmerkk.Strings import lt.markmerkk.entities.Log import lt.markmerkk.ui_2.views.ticket_split.TicketSplitWidget import org.slf4j.LoggerFactory import tornadofx.UIComponent class DialogsInternal( private val resultDispatcher: ResultDispatcher, private val strings: Strings, ): Dialogs { override fun showDialogConfirm( uiComponent: UIComponent, header: String, content: String, onConfirm: () -> Unit, ) { resultDispatcher.publish( DialogConfirmWidget.RESULT_DISPATCH_KEY_BUNDLE, DialogConfirmWidget.DialogBundle( header = header, content = content, onConfirm = onConfirm, ) ) uiComponent.openInternalWindow<DialogConfirmWidget>( escapeClosesWindow = true, ) } override fun showDialogInfo(uiComponent: UIComponent, header: String, content: String) { resultDispatcher.publish( DialogInfoWidget.RESULT_DISPATCH_KEY_BUNDLE, DialogInfoWidget.DialogBundle( header = header, content = content, ) ) uiComponent.openInternalWindow<DialogInfoWidget>( escapeClosesWindow = true, ) } override fun showDialogCustomAction( uiComponent: UIComponent, header: String, content: String, actionTitle: String, onAction: () -> Unit ) { resultDispatcher.publish( DialogCustomActionWidget.RESULT_DISPATCH_KEY_BUNDLE, DialogCustomActionWidget.DialogBundle( header = header, content = content, actionTitle = actionTitle, onAction = onAction, ) ) uiComponent.openInternalWindow<DialogCustomActionWidget>( escapeClosesWindow = true, ) } override fun showDialogSplitTicket( uiComponent: UIComponent, worklog: Log, ) { resultDispatcher.publish( TicketSplitWidget.RESULT_DISPATCH_KEY_ENTITY, worklog, ) uiComponent.openInternalWindow<TicketSplitWidget>( escapeClosesWindow = true, ) } companion object { private val l = LoggerFactory.getLogger(DialogsInternal::class.java)!! } }
app/src/main/java/lt/markmerkk/widgets/dialogs/DialogsInternal.kt
1404047622
/* * 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.tests.server.testing import io.ktor.client.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.server.engine.* import io.ktor.server.plugins.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.server.testing.client.* import io.ktor.util.* import io.ktor.utils.io.* import kotlinx.coroutines.* import kotlin.test.* class TestApplicationTest { private val TestPlugin = createApplicationPlugin("test_plugin") { onCall { call -> if (!call.request.headers.contains("request_header")) { throw BadRequestException("Error") } call.response.header("response_header", call.request.headers["request_header"]!!) } } private val testApplication = TestApplication { install(TestPlugin) routing { get("a") { call.respond("OK") } } } private object TestClientPlugin : HttpClientPlugin<Unit, TestClientPlugin> { override val key: AttributeKey<TestClientPlugin> = AttributeKey("testClientPlugin") override fun prepare(block: Unit.() -> Unit) = TestClientPlugin override fun install(plugin: TestClientPlugin, scope: HttpClient) { scope.sendPipeline.intercept(HttpSendPipeline.State) { context.headers.append("request_header", "value_1") } } } private val testClient = testApplication.createClient { install(TestClientPlugin) } @Test fun testTopLevel() = runBlocking { val response = testClient.get("a") assertEquals("OK", response.bodyAsText()) assertEquals("value_1", response.headers["response_header"]) } @Test fun testApplicationBlock() = testApplication { application { install(TestPlugin) routing { get("a") { call.respond("OK") } } } val client = createClient { install(TestClientPlugin) } val response = client.get("a") assertEquals("OK", response.bodyAsText()) assertEquals("value_1", response.headers["response_header"]) } @Test fun testBridge() = testApplication { install(TestPlugin) routing { get("a") { call.respond("OK") } } val client = createClient { install(TestClientPlugin) } val response = client.get("a") assertEquals("OK", response.bodyAsText()) assertEquals("value_1", response.headers["response_header"]) } @Test fun testExternalServices() = testApplication { externalServices { hosts("http://www.google.com:123", "https://google.com") { routing { get { call.respond("EXTERNAL OK") } } } } routing { get { call.respond("OK") } } val internal = client.get("/") assertEquals("OK", internal.bodyAsText()) val external1 = client.get("//www.google.com:123") assertEquals("EXTERNAL OK", external1.bodyAsText()) val external2 = client.get("https://google.com") assertEquals("EXTERNAL OK", external2.bodyAsText()) assertFailsWith<InvalidTestRequestException> { client.get("//google.com:123") } assertFailsWith<InvalidTestRequestException> { client.get("//google.com") } assertFailsWith<InvalidTestRequestException> { client.get("https://www.google.com") } } @Test fun testCanAccessClient() = testApplication { class TestPluginConfig { lateinit var pluginClient: HttpClient } val TestPlugin = createApplicationPlugin("test", ::TestPluginConfig) { onCall { val externalValue = pluginConfig.pluginClient.get("https://test.com").bodyAsText() it.response.headers.append("test", externalValue) } } install(TestPlugin) { pluginClient = client } externalServices { hosts("https://test.com") { routing { get { call.respond("TEST_VALUE") } } } } routing { get { call.respond("OK") } } val response = client.get("/") assertEquals("OK", response.bodyAsText()) assertEquals("TEST_VALUE", response.headers["test"]) } @Test fun testingSchema() = testApplication { routing { get("/echo") { call.respondText(call.request.local.scheme) } } assertEquals("http", client.get("/echo").bodyAsText()) assertEquals("https", client.get("https://localhost/echo").bodyAsText()) } @Test fun testManualStart() = testApplication { var externalServicesRoutingCalled = false var routingCalled = false var applicationCalled = false var applicationStarted = false externalServices { hosts("https://test.com") { routing { externalServicesRoutingCalled = true } } } routing { routingCalled = true } application { applicationCalled = true environment.monitor.subscribe(ApplicationStarted) { applicationStarted = true } } startApplication() assertEquals(true, routingCalled) assertEquals(true, applicationCalled) assertEquals(true, applicationStarted) assertEquals(true, externalServicesRoutingCalled) } @Test fun testManualStartAndClientCallAfter() = testApplication { externalServices { hosts("https://test.com") { routing { get { call.respond("OK") } } } } routing { get { call.respond([email protected]("https://test.com").bodyAsText()) } } startApplication() assertEquals("OK", client.get("/").bodyAsText()) } @Test fun testClientWithTimeout() = testApplication { val client = createClient { install(HttpTimeout) } externalServices { hosts("http://fake.site.io") { routing { get("/toto") { call.respond("OK") } } } } routing { get("/") { val response = client.get("http://fake.site.io/toto") { timeout { requestTimeoutMillis = 100 } }.bodyAsText() call.respondText(response) } } assertEquals("OK", client.get("/").bodyAsText()) } @Test fun testMultipleParallelRequests() = testApplication { routing { get("/") { call.respondText("OK") } } coroutineScope { val jobs = (1..100).map { async { client.get("/").apply { assertEquals("OK", bodyAsText()) } } } jobs.awaitAll() } } @Test fun testRequestRunningInParallel() = testApplication { routing { post("/") { val text = call.receiveText() call.respondText(text) } } coroutineScope { val secondRequestStarted = CompletableDeferred<Unit>() val request1 = async { client.post("/") { setBody(object : OutgoingContent.WriteChannelContent() { override suspend fun writeTo(channel: ByteWriteChannel) { channel.writeStringUtf8("OK") secondRequestStarted.await() channel.flush() } }) }.apply { assertEquals("OK", bodyAsText()) } } val request2 = async { client.preparePost("/") { setBody("OK") }.execute { secondRequestStarted.complete(Unit) assertEquals("OK", it.bodyAsText()) } } request1.await() request2.await() } } @Test fun testExceptionThrowsByDefault() = testApplication { routing { get("/boom") { throw IllegalStateException("error") } } val error = assertFailsWith<IllegalStateException> { client.get("/boom") } assertEquals("error", error.message) } @Test fun testExceptionRespondsWith500IfFlagSet() = testApplication { environment { config = MapApplicationConfig(CONFIG_KEY_THROW_ON_EXCEPTION to "false") } routing { get("/boom") { throw IllegalStateException("error") } } val response = client.get("/boom") assertEquals(HttpStatusCode.InternalServerError, response.status) } @Test fun testConnectors(): Unit = testApplication { environment { connector { port = 8080 } connector { port = 8081 } module { routing { port(8080) { get { call.respond("8080") } } port(8081) { get { call.respond("8081") } } } } } val response8080 = client.get { host = "0.0.0.0" port = 8080 } assertEquals("8080", response8080.bodyAsText()) val response8081 = client.get { host = "0.0.0.0" port = 8081 } assertEquals("8081", response8081.bodyAsText()) } }
ktor-server/ktor-server-test-host/jvmAndNix/test/TestApplicationTest.kt
2056437978
package org.dvbviewer.controller.data.timer.retrofit import okhttp3.MediaType import okhttp3.RequestBody import org.dvbviewer.controller.data.entities.Timer import retrofit2.Converter internal class TimerRequestBodyConverter : Converter<List<Timer>, RequestBody> { override fun convert(value: List<Timer>): RequestBody { return RequestBody.create(MEDIA_TYPE, value.toString()) } companion object { private val MEDIA_TYPE = MediaType.parse("text") } }
dvbViewerController/src/main/java/org/dvbviewer/controller/data/timer/retrofit/TimerRequestBodyConverter.kt
1250384700
package de.flocksserver.domain.interactors.usecase import dagger.internal.Preconditions import de.flocksserver.domain.PostExecutionThread import de.flocksserver.domain.ThreadExecutor import io.reactivex.Single import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers /** * Created by marcel on 01.08.17. */ abstract class SingleUseCaseWithParameter<T, in Params> internal constructor(private val threadExecutor: ThreadExecutor, private val postExecutionThread: PostExecutionThread) : BaseUseCase() { internal abstract fun buildUseCaseObservable(params: Params): Single<T> fun execute(success: Consumer<T>, error: Consumer<Throwable>, params: Params) { Preconditions.checkNotNull(success) Preconditions.checkNotNull(error) val observable = this.buildUseCaseObservable(params) .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.scheduler) addDisposable(observable.subscribe(success, error)) } }
domain/src/main/java/de/flocksserver/domain/interactors/usecase/SingleUseCaseWithParameter.kt
4150346942
/* * 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_SGIX_pbuffer = "GLXSGIXPbuffer".nativeClassGLX("GLX_SGIX_pbuffer", SGIX) { documentation = """ Native bindings to the $registryLink extension. This extension defines pixel buffers (GLXPbuffers, or pbuffer for short). GLXPbuffers are additional non-visible rendering buffers for an OpenGL renderer. """ IntConstant( "Accepted by the {@code attribute} parameter of #GetFBConfigAttribSGIX().", "MAX_PBUFFER_WIDTH_SGIX"..0x8016, "MAX_PBUFFER_HEIGHT_SGIX"..0x8017, "MAX_PBUFFER_PIXELS_SGIX"..0x8018, "OPTIMAL_PBUFFER_WIDTH_SGIX"..0x8019, "OPTIMAL_PBUFFER_HEIGHT_SGIX"..0x801A ) IntConstant( """ Returned by #GetFBConfigAttribSGIX() (when {@code attribute} is set to #DRAWABLE_TYPE_SGIX) and accepted by the {@code attrib_list} parameter of #ChooseFBConfigSGIX() (following the #DRAWABLE_TYPE_SGIX token). """, "PBUFFER_BIT_SGIX"..0x00000004 ) IntConstant( "Accepted by the {@code attrib_list} parameter of #CreateGLXPbufferSGIX() and by the {@code attribute} parameter of #QueryGLXPbufferSGIX().", "PRESERVED_CONTENTS_SGIX"..0x801B, "LARGEST_PBUFFER_SGIX"..0x801C ) IntConstant( "Accepted by the {@code attribute} parameter of #QueryGLXPbufferSGIX().", "WIDTH_SGIX"..0x801D, "HEIGHT_SGIX"..0x801E, "EVENT_MASK_SGIX"..0x801F ) IntConstant( "Accepted by the {@code mask} parameter of #SelectEventSGIX() and returned in the {@code mask} parameter of #GetSelectedEventSGIX().", "BUFFER_CLOBBER_MASK_SGIX"..0x08000000 ) IntConstant( "Returned in the {@code event_type} field of a \"buffer clobber\" event.", "DAMAGED_SGIX"..0x8020, "SAVED_SGIX"..0x8021 ) IntConstant( "Returned in the {@code draw_type} field of a \"buffer clobber\" event.", "WINDOW_SGIX"..0x8022, "PBUFFER_SGIX"..0x8023 ) IntConstant( "Returned in the {@code mask} field of a \"buffer clobber\" event.", "FRONT_LEFT_BUFFER_BIT_SGIX"..0x00000001, "FRONT_RIGHT_BUFFER_BIT_SGIX"..0x00000002, "BACK_LEFT_BUFFER_BIT_SGIX"..0x00000004, "BACK_RIGHT_BUFFER_BIT_SGIX"..0x00000008, "AUX_BUFFERS_BIT_SGIX"..0x00000010, "DEPTH_BUFFER_BIT_SGIX"..0x00000020, "STENCIL_BUFFER_BIT_SGIX"..0x00000040, "ACCUM_BUFFER_BIT_SGIX"..0x00000080, "SAMPLE_BUFFERS_BIT_SGIX"..0x00000100 ) GLXPbuffer( "CreateGLXPbufferSGIX", "Creates a single GLXPbuffer and returns its XID.", DISPLAY, GLXFBConfig("config", "the {@code GLXFBConfig}"), unsigned_int("width", "the pbuffer width"), unsigned_int("height", "the pbuffer height"), nullable..NullTerminated..int.p("attrib_list", "an optional null-terminated list of attributes") ) void( "DestroyGLXPbufferSGIX", "Destroys a GLXPbuffer.", DISPLAY, GLXPbuffer("pbuf", "the pbuffer to destroy") ) void( "QueryGLXPbufferSGIX", "Queries an attribute associated with a GLXPbuffer.", DISPLAY, GLXPbuffer("pbuf", "the pbuffer being queried"), int("attribute", "the attribute to query"), Check(1)..unsigned_int.p("value", "returns the attribute value") ) void( "SelectEventSGIX", "Selects which GLX events should be received on a GLXdrawable.", DISPLAY, GLXDrawable("drawable", "the GLXDrawable"), unsigned_long("mask", "the selection mask") ) void( "GetSelectedEventSGIX", "Returns which GLX events are selected for a GLXdrawable.", DISPLAY, GLXDrawable("drawable", "the GLXDrawable"), Check(1)..unsigned_long.p("mask", "returns the selection mask") ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GLX_SGIX_pbuffer.kt
3597321833
package mods.octarinecore.common.config import mods.octarinecore.client.gui.NonVerboseArrayEntry import mods.octarinecore.client.resource.get import mods.octarinecore.client.resource.getLines import mods.octarinecore.client.resource.resourceManager import net.minecraftforge.common.config.Configuration import net.minecraftforge.common.config.Property abstract class StringListConfigOption<VALUE>(val domain: String, val path: String) : ConfigPropertyBase() { val list = mutableListOf<VALUE>() lateinit var listProperty: Property override val hasChanged: Boolean get() = listProperty.hasChanged() ?: false override val guiProperties: List<Property> get() = listOf(listProperty) override fun attach(target: Configuration, langPrefix: String, categoryName: String, propertyName: String) { lang = null val defaults = readDefaults(domain, path) listProperty = target.get(categoryName, "${propertyName}", defaults) listProperty.configEntryClass = NonVerboseArrayEntry::class.java listProperty.languageKey = "$langPrefix.$categoryName.${listProperty.name}" read() } abstract fun convertValue(line: String): VALUE? override fun read() { list.clear() listProperty.stringList.forEach { line -> val value = convertValue(line) if (value != null) list.add(value) } } fun readDefaults(domain: String, path: String): Array<String> { val list = arrayListOf<String>() val defaults = resourceManager[domain, path]?.getLines() defaults?.map { it.trim() }?.filter { !it.startsWith("//") && it.isNotEmpty() }?.forEach { list.add(it) } return list.toTypedArray() } }
src/main/kotlin/mods/octarinecore/common/config/StringListConfigOption.kt
3944996220
package com.neva.javarel.foundation.api.osgi import org.objectweb.asm.AnnotationVisitor import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.Opcodes import java.net.URL import java.util.* object ClassUtils { fun toClassName(classReader: ClassReader): String { return classReader.className.replace("/", ".") } fun toClassName(url: URL): String { val file = url.file val canonicalName = file.substring(1, file.length - ".class".length) return canonicalName.replace('/', '.') } fun isAnnotated(classReader: ClassReader, annotation: Class<out Annotation>): Boolean { return isAnnotated(classReader, setOf(annotation)) } fun isAnnotated(classReader: ClassReader, annotations: Set<Class<out Annotation>>): Boolean { val annotationReader = AnnotationReader(); classReader.accept(annotationReader, ClassReader.SKIP_DEBUG); return annotationReader.isAnnotationPresent(annotations); } class AnnotationReader : ClassVisitor(Opcodes.ASM5) { private val visited = ArrayList<String>() override fun visit(paramInt1: Int, paramInt2: Int, paramString1: String?, paramString2: String?, paramString3: String?, paramArrayOfString: Array<String?>) { visited.clear() } override fun visitAnnotation(paramString: String?, paramBoolean: Boolean): AnnotationVisitor? { if (paramString != null) { val annotationClassName = getAnnotationClassName(paramString) visited.add(annotationClassName) } return super.visitAnnotation(paramString, paramBoolean) } fun isAnnotationPresent(annotations: Set<Class<out Annotation>>): Boolean { return annotations.any { annotation -> visited.contains(annotation.name) } } private fun getAnnotationClassName(rawName: String): String { return rawName.substring(1, rawName.length - 1).replace('/', '.') } } }
foundation/src/main/kotlin/com/neva/javarel/foundation/api/osgi/ClassUtils.kt
2040977306
package com.ashish.movieguide.ui.review import com.ashish.movieguide.di.modules.ActivityModule import com.ashish.movieguide.di.multibindings.AbstractComponent import com.ashish.movieguide.di.multibindings.activity.ActivityComponentBuilder import dagger.Subcomponent @Subcomponent(modules = arrayOf(ActivityModule::class)) interface ReviewComponent : AbstractComponent<ReviewActivity> { @Subcomponent.Builder interface Builder : ActivityComponentBuilder<ReviewActivity, ReviewComponent> { fun withModule(module: ActivityModule): Builder } }
app/src/main/kotlin/com/ashish/movieguide/ui/review/ReviewComponent.kt
3442684759
package org.wikipedia.views import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.net.Uri import android.text.TextUtils import android.view.ActionMode import android.view.LayoutInflater import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.load.MultiTransformation import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestListener import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.databinding.ViewActionModeCloseButtonBinding import org.wikipedia.settings.Prefs import org.wikipedia.util.DimenUtil.roundedDpToPx import org.wikipedia.util.ResourceUtil.getThemedColor import org.wikipedia.util.WhiteBackgroundTransformation import java.util.* object ViewUtil { private val CENTER_CROP_ROUNDED_CORNERS = MultiTransformation(CenterCrop(), WhiteBackgroundTransformation(), RoundedCorners(roundedDpToPx(2f))) val ROUNDED_CORNERS = RoundedCorners(roundedDpToPx(15f)) val CENTER_CROP_LARGE_ROUNDED_CORNERS = MultiTransformation(CenterCrop(), WhiteBackgroundTransformation(), ROUNDED_CORNERS) @JvmStatic fun loadImageWithRoundedCorners(view: ImageView, url: String?) { loadImage(view, url, true) } @JvmStatic fun loadImageWithRoundedCorners(view: ImageView, url: String?, largeRoundedSize: Boolean) { loadImage(view, url, true, largeRoundedSize) } @JvmStatic @JvmOverloads fun loadImage(view: ImageView, url: String?, roundedCorners: Boolean = false, largeRoundedSize: Boolean = false, force: Boolean = false, listener: RequestListener<Drawable?>? = null) { val placeholder = getPlaceholderDrawable(view.context) var builder = Glide.with(view) .load(if ((Prefs.isImageDownloadEnabled() || force) && !TextUtils.isEmpty(url)) Uri.parse(url) else null) .placeholder(placeholder) .downsample(DownsampleStrategy.CENTER_INSIDE) .error(placeholder) builder = if (roundedCorners) { builder.transform(if (largeRoundedSize) CENTER_CROP_LARGE_ROUNDED_CORNERS else CENTER_CROP_ROUNDED_CORNERS) } else { builder.transform(WhiteBackgroundTransformation()) } if (listener != null) { builder = builder.listener(listener) } builder.into(view) } fun getPlaceholderDrawable(context: Context): Drawable { return ColorDrawable(getThemedColor(context, R.attr.material_theme_border_color)) } @JvmStatic fun setCloseButtonInActionMode(context: Context, actionMode: ActionMode) { val binding = ViewActionModeCloseButtonBinding.inflate(LayoutInflater.from(context)) actionMode.customView = binding.root binding.closeButton.setOnClickListener { actionMode.finish() } } @JvmStatic fun formatLangButton(langButton: TextView, langCode: String, langButtonTextSizeSmaller: Int, langButtonTextSizeLarger: Int) { val langCodeStandardLength = 3 val langButtonTextMaxLength = 7 if (langCode.length > langCodeStandardLength) { langButton.textSize = langButtonTextSizeSmaller.toFloat() if (langCode.length > langButtonTextMaxLength) { langButton.text = langCode.substring(0, langButtonTextMaxLength).toUpperCase(Locale.ENGLISH) } return } langButton.textSize = langButtonTextSizeLarger.toFloat() } @JvmStatic fun adjustImagePlaceholderHeight(containerWidth: Float, thumbWidth: Float, thumbHeight: Float): Int { return (Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat() / thumbWidth * thumbHeight * containerWidth / Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat()).toInt() } }
app/src/main/java/org/wikipedia/views/ViewUtil.kt
759864685
package katas.kotlin.skiena.graphs import katas.kotlin.skiena.graphs.UnweightedGraphs.diamondGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.disconnectedGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.linearGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.meshGraph import datsok.shouldEqual import org.junit.Test fun <T> Graph<T>.dfs(fromVertex: T, result: MutableList<T> = ArrayList()): List<T> { edgesByVertex[fromVertex]?.forEach { if (it.from !in result) result.add(it.from) if (it.to !in result) { result.add(it.to) dfs(it.to, result) } } return result } fun <T> Graph<T>.dfsEdges(fromVertex: T, result: MutableList<Edge<T>> = ArrayList()): List<Edge<T>> { edgesByVertex[fromVertex]?.forEach { edge -> if (edge !in result && edge.inverse !in result) { result.add(edge) dfsEdges(edge.to, result) } } return result } private val <T> Edge<T>.inverse: Edge<T> get() = Edge(to, from) class DFSTests { @Test fun `depth-first vertex traversal`() { linearGraph.dfs(fromVertex = 1) shouldEqual listOf(1, 2, 3) disconnectedGraph.dfs(fromVertex = 1) shouldEqual listOf(1, 2) diamondGraph.dfs(fromVertex = 1) shouldEqual listOf(1, 2, 3, 4) meshGraph.dfs(fromVertex = 1) shouldEqual listOf(1, 2, 3, 4) } @Test fun `depth-first edge traversal`() { linearGraph.dfsEdges(fromVertex = 1) shouldEqual listOf( Edge(1, 2), Edge(2, 3) ) disconnectedGraph.dfsEdges(fromVertex = 1) shouldEqual listOf( Edge(1, 2) ) diamondGraph.dfsEdges(fromVertex = 1) shouldEqual listOf( Edge(1, 2), Edge(2, 3), Edge(3, 4), Edge(4, 1) ) meshGraph.dfsEdges(fromVertex = 1) shouldEqual listOf( Edge(1, 2), Edge(2, 3), Edge(3, 1), Edge(1, 4), Edge(4, 2), Edge(4, 3) ) } }
kotlin/src/katas/kotlin/skiena/graphs/DFS.kt
1920265785
package org.javacs.kt.util import java.io.ByteArrayOutputStream import java.io.PrintStream import java.util.function.Consumer class DelegatePrintStream(private val delegate: (String) -> Unit): PrintStream(ByteArrayOutputStream(0)) { private val newLine = System.lineSeparator() override fun write(c: Int) = delegate((c.toChar()).toString()) override fun write(buf: ByteArray, off: Int, len: Int) { if (len > 0 && buf.size > 0) { delegate(String(buf, off, len)) } } override fun append(csq: CharSequence): PrintStream { delegate(csq.toString()) return this } override fun append(csq: CharSequence, start: Int, end: Int): PrintStream { delegate(csq.subSequence(start, end).toString()) return this } override fun append(c:Char): PrintStream { delegate((c).toString()) return this } override fun print(x: Boolean) = delegate(x.toString()) override fun print(x: Char) = delegate(x.toString()) override fun print(x: Int) = delegate(x.toString()) override fun print(x: Long) = delegate(x.toString()) override fun print(x: Float) = delegate(x.toString()) override fun print(x: Double) = delegate(x.toString()) override fun print(s: CharArray) = delegate(String(s)) override fun print(s: String) = delegate(s) override fun print(obj: Any) = delegate(obj.toString()) override fun println() = delegate(newLine) override fun println(x: Boolean) = delegate(x.toString() + newLine) override fun println(x: Char) = delegate(x.toString() + newLine) override fun println(x: Int) = delegate(x.toString() + newLine) override fun println(x: Long) = delegate(x.toString() + newLine) override fun println(x: Float) = delegate(x.toString() + newLine) override fun println(x: Double) = delegate(x.toString() + newLine) override fun println(x: CharArray) = delegate(String(x) + newLine) override fun println(x: String) = delegate(x + newLine) override fun println(x: Any) = delegate(x.toString() + newLine) }
shared/src/main/kotlin/org/javacs/kt/util/DelegatePrintStream.kt
2645236844
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'filter{}.forEach{}'" // INTENTION_TEXT_2: "Replace with 'asSequence().filter{}.forEach{}'" import java.util.ArrayList fun foo(list: List<String>): List<Int> { val result = ArrayList<Int>() <caret>for (s in list) { if (s.length > result.size) { result.add(s.hashCode()) } } return result }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/toCollection/resultCollectionUsedInsideLoop.kt
3953235841
// PROBLEM: none // WITH_STDLIB fun Array<List<Int>>.test() { <caret>flatMap { it } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCall/arrayFlatMap2.kt
1481806896