content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.cognifide.gradle.aem.instance.tasks
import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction
import com.cognifide.gradle.aem.common.instance.action.ReloadAction
import com.cognifide.gradle.aem.common.instance.names
import com.cognifide.gradle.aem.common.tasks.Instance
import org.gradle.api.tasks.TaskAction
open class InstanceReload : Instance() {
private var reloadOptions: ReloadAction.() -> Unit = {}
fun reload(options: ReloadAction.() -> Unit) {
this.reloadOptions = options
}
private var awaitUpOptions: AwaitUpAction.() -> Unit = {}
fun awaitUp(options: AwaitUpAction.() -> Unit) {
this.awaitUpOptions = options
}
@TaskAction
fun reload() {
instanceManager.awaitReloaded(anyInstances, reloadOptions, awaitUpOptions)
common.notifier.lifecycle("Instance(s) reloaded", "Which: ${anyInstances.names}")
}
init {
description = "Reloads all AEM instance(s)."
}
companion object {
const val NAME = "instanceReload"
}
}
| src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceReload.kt | 2860077243 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.status
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewTreeObserver
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.linkedin.android.spyglass.suggestions.SuggestionsResult
import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager
import com.linkedin.android.spyglass.tokenization.QueryToken
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig
import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractActivity
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.domain.STATUS_LIMIT
import com.sinyuk.fanfou.domain.StatusCreation
import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT
import com.sinyuk.fanfou.ui.editor.EditorView
import com.sinyuk.fanfou.ui.editor.MentionListView
import com.sinyuk.fanfou.ui.timeline.TimelineView
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.fanfou.viewmodel.PlayerViewModel
import kotlinx.android.synthetic.main.status_view.*
import kotlinx.android.synthetic.main.status_view_footer.*
import kotlinx.android.synthetic.main.status_view_reply_actionbar.*
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/12.
*
*/
class StatusView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager {
companion object {
fun newInstance(status: Status, photoExtra: Bundle? = null) = StatusView().apply {
arguments = Bundle().apply {
putParcelable("status", status)
putBundle("photoExtra", photoExtra)
}
}
}
override fun layoutId() = R.layout.status_view
@Inject
lateinit var factory: FanfouViewModelFactory
private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) }
override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
super.onEnterAnimationEnd(savedInstanceState)
navBack.setOnClickListener { onBackPressedSupport() }
setupEditor()
setupKeyboard()
onTextChanged(0)
setupViewPager()
val status = arguments!!.getParcelable<Status>("status")
fullscreenButton.setOnClickListener {
(activity as AbstractActivity).start(EditorView.newInstance(status.id,
replyEt.mentionsText,
StatusCreation.REPOST_STATUS))
replyEt.text = null
}
}
private fun setupViewPager() {
val status = arguments!!.getParcelable<Status>("status")
val bundle = arguments!!.getBundle("photoExtra")
val fragments: List<Fragment> = if (findChildFragment(TimelineView::class.java) == null) {
val mentionView = MentionListView()
mentionView.onItemClickListener = onSuggestionSelectListener
mutableListOf(TimelineView.contextTimeline(TIMELINE_CONTEXT, status, bundle), mentionView)
} else {
mutableListOf(findChildFragment(TimelineView::class.java), MentionListView())
}
viewPager.setPagingEnabled(false)
viewPager.offscreenPageLimit = 1
viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getItem(position: Int) = fragments[position]
override fun getCount() = fragments.size
}
}
private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null
private fun setupKeyboard() {
keyboardListener = KeyboardUtil.attach(activity, panelRoot, {
// TODO: how comes the Exception: panelRootContainer must not be null
panelRootContainer?.visibility =
if (it) {
if (replyEt.requestFocus()) replyEt.setSelection(replyEt.text.length)
View.VISIBLE
} else {
replyEt.clearFocus()
View.GONE
}
})
}
private val config = WordTokenizerConfig.Builder()
.setExplicitChars("@")
.setThreshold(3)
.setMaxNumKeywords(5)
.setWordBreakChars(" ").build()
private fun setupEditor() {
replyEt.tokenizer = WordTokenizer(config)
replyEt.setAvoidPrefixOnTap(true)
replyEt.setQueryTokenReceiver(this)
replyEt.setSuggestionsVisibilityManager(this)
replyEt.setAvoidPrefixOnTap(true)
replyCommitButton.setOnClickListener { }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
textCountProgress.min = 0
textCountProgress.max = STATUS_LIMIT
replyEt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
onTextChanged(s?.length ?: 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
/**
* @param count 字数
*/
private fun onTextChanged(count: Int) {
textCountProgress.progress = count
replyCommitButton.isEnabled = count in 1..STATUS_LIMIT
}
private val onSuggestionSelectListener = object : MentionListView.OnItemClickListener {
override fun onItemClick(position: Int, item: Suggestible) {
(item as Player).let {
replyEt.insertMention(it)
displaySuggestions(false)
playerViewModel.updateMentionedAt(it) //
onTextChanged(replyEt.text.length)
replyEt.requestFocus()
replyEt.setSelection(replyEt.text.length)
}
}
}
@Suppress("PrivatePropertyName")
private val BUCKET = "player-mentioned"
override fun onQueryReceived(queryToken: QueryToken): MutableList<String> {
val data = playerViewModel.filter(queryToken.keywords)
onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET)
return arrayOf(BUCKET).toMutableList()
}
override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) {
val data = result.suggestions
if (data?.isEmpty() != false) return
displaySuggestions(true)
findChildFragment(MentionListView::class.java).setData(data)
}
override fun displaySuggestions(display: Boolean) {
viewPager.setCurrentItem(if (display) 1 else 0, true)
}
override fun isDisplayingSuggestions() = viewPager.currentItem == 1
override fun onBackPressedSupport(): Boolean {
when {
panelRootContainer.visibility == View.VISIBLE -> KeyboardUtil.hideKeyboard(panelRootContainer)
isDisplayingSuggestions -> displaySuggestions(false)
else -> pop()
}
return true
}
override fun onDestroy() {
keyboardListener?.let { KeyboardUtil.detach(activity, it) }
activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) }
super.onDestroy()
}
} | presentation/src/main/java/com/sinyuk/fanfou/ui/status/StatusView.kt | 1441581882 |
package com.timepath.vfs.provider.jdbc
import com.timepath.vfs.MockFile
import com.timepath.vfs.SimpleVFile
import com.timepath.vfs.provider.ProviderStub
import org.jetbrains.annotations.NonNls
import java.sql.SQLException
import java.text.MessageFormat
import java.util.LinkedList
import java.util.logging.Level
/**
* @author TimePath
*/
class JDBCTable(private val jdbcProvider: JDBCProvider, name: String) : ProviderStub(name) {
override fun get(NonNls name: String) = list().firstOrNull { name == it.name }
SuppressWarnings("NestedTryStatement")
override fun list(): Collection<SimpleVFile> {
val rows = LinkedList<MockFile>()
try {
jdbcProvider.conn.prepareStatement("SELECT * FROM ${name}").let { st ->
st.executeQuery().let { rs ->
val len = rs.getMetaData().getColumnCount()
while (rs.next()) {
val sb = StringBuilder()
for (i in 0..len - 1) {
sb.append('\t').append(rs.getString(i + 1))
}
rows.add(MockFile(rs.getString(1), sb.substring(1)))
}
}
}
} catch (e: SQLException) {
JDBCProvider.LOG.log(Level.SEVERE, MessageFormat.format("Reading from table {0}", name), e)
}
return rows
}
}
| src/main/kotlin/com/timepath/vfs/provider/jdbc/JDBCTable.kt | 3486848447 |
/*
* Copyright 2017-2022 Adobe.
*
* 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.adobe.testing.s3mock.its
import com.adobe.testing.s3mock.util.DigestUtil
import com.amazonaws.services.s3.model.AmazonS3Exception
import com.amazonaws.services.s3.model.CopyObjectRequest
import com.amazonaws.services.s3.model.MetadataDirective
import com.amazonaws.services.s3.model.ObjectMetadata
import com.amazonaws.services.s3.model.PutObjectRequest
import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInfo
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.util.UUID
/**
* Test the application using the AmazonS3 SDK V1.
*/
internal class CopyObjectV1IT : S3TestBase() {
/**
* Puts an Object; Copies that object to a new bucket; Downloads the object from the new bucket;
* compares checksums of original and copied object.
*/
@Test
fun shouldCopyObject(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey)
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
@Test
fun testCopyObject_successMatch(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey)
val matchingEtag = "\"${putObjectResult.eTag}\""
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
.withMatchingETagConstraint(matchingEtag)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
@Test
fun testCopyObject_successNoneMatch(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey)
val nonMatchingEtag = "\"${randomName}\""
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
.withNonmatchingETagConstraint(nonMatchingEtag)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
@Test
fun testCopyObject_failureMatch(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, _) = givenBucketAndObjectV1(testInfo, sourceKey)
val nonMatchingEtag = "\"${randomName}\""
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
.withMatchingETagConstraint(nonMatchingEtag)
s3Client.copyObject(copyObjectRequest)
assertThatThrownBy {
s3Client.getObject(destinationBucketName, destinationKey)
}
.isInstanceOf(AmazonS3Exception::class.java)
.hasMessageContaining("Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;")
.hasMessageContaining("The specified key does not exist.")
}
@Test
fun testCopyObject_failureNoneMatch(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey)
val matchingEtag = "\"${putObjectResult.eTag}\""
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
.withNonmatchingETagConstraint(matchingEtag)
s3Client.copyObject(copyObjectRequest)
assertThatThrownBy {
s3Client.getObject(destinationBucketName, destinationKey)
}
.isInstanceOf(AmazonS3Exception::class.java)
.hasMessageContaining("Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;")
.hasMessageContaining("The specified key does not exist.")
}
/**
* Puts an Object; Copies that object to the same bucket and the same key;
* Downloads the object; compares checksums of original and copied object.
*/
@Test
fun shouldCopyObjectToSameKey(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = UPLOAD_FILE_NAME
val objectMetadata = ObjectMetadata()
objectMetadata.userMetadata = mapOf("test-key" to "test-value")
val putObjectRequest =
PutObjectRequest(bucketName, sourceKey, uploadFile).withMetadata(objectMetadata)
val putObjectResult = s3Client.putObject(putObjectRequest)
//TODO: this is actually illegal on S3. when copying to the same key like this, S3 will throw:
// This copy request is illegal because it is trying to copy an object to itself without
// changing the object's metadata, storage class, website redirect location or encryption attributes.
val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, bucketName, sourceKey)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(bucketName, sourceKey)
val copiedObjectMetadata = copiedObject.objectMetadata
assertThat(copiedObjectMetadata.userMetadata["test-key"]).isEqualTo("test-value")
val objectContent = copiedObject.objectContent
val copiedDigest = DigestUtil.hexDigest(objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
/**
* Puts an Object; Copies that object with REPLACE directive to the same bucket and the same key;
* Downloads the object; compares checksums of original and copied object.
*/
@Test
fun shouldCopyObjectWithReplaceToSameKey(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = UPLOAD_FILE_NAME
val objectMetadata = ObjectMetadata()
objectMetadata.userMetadata = mapOf("test-key" to "test-value")
val putObjectRequest =
PutObjectRequest(bucketName, sourceKey, uploadFile).withMetadata(objectMetadata)
val putObjectResult = s3Client.putObject(putObjectRequest)
val replaceObjectMetadata = ObjectMetadata()
replaceObjectMetadata.userMetadata = mapOf("test-key2" to "test-value2")
val copyObjectRequest = CopyObjectRequest()
.withSourceBucketName(bucketName)
.withSourceKey(sourceKey)
.withDestinationBucketName(bucketName)
.withDestinationKey(sourceKey)
.withMetadataDirective(MetadataDirective.REPLACE)
.withNewObjectMetadata(replaceObjectMetadata)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(bucketName, sourceKey)
val copiedObjectMetadata = copiedObject.objectMetadata
assertThat(copiedObjectMetadata.userMetadata["test-key"])
.`as`("Original userMetadata must have been replaced.")
.isNullOrEmpty()
assertThat(copiedObjectMetadata.userMetadata["test-key2"]).isEqualTo("test-value2")
val objectContent = copiedObject.objectContent
val copiedDigest = DigestUtil.hexDigest(objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
/**
* Puts an Object; Copies that object to a new bucket with new user metadata; Downloads the
* object from the new bucket;
* compares checksums of original and copied object; compares copied object user metadata with
* the new user metadata specified during copy request.
*/
@Test
fun shouldCopyObjectWithNewUserMetadata(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey)
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey/withNewUserMetadata"
val objectMetadata = ObjectMetadata()
objectMetadata.addUserMetadata("key", "value")
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
copyObjectRequest.newObjectMetadata = objectMetadata
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
assertThat(copiedObject.objectMetadata.userMetadata)
.`as`("User metadata should be identical!")
.isEqualTo(objectMetadata.userMetadata)
}
/**
* Puts an Object with some user metadata; Copies that object to a new bucket.
* Downloads the object from the new bucket;
* compares checksums of original and copied object; compares copied object user metadata with
* the source object user metadata;
*/
@Test
fun shouldCopyObjectWithSourceUserMetadata(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = UPLOAD_FILE_NAME
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey/withSourceObjectUserMetadata"
val sourceObjectMetadata = ObjectMetadata()
sourceObjectMetadata.addUserMetadata("key", "value")
val putObjectRequest = PutObjectRequest(bucketName, sourceKey, uploadFile)
putObjectRequest.metadata = sourceObjectMetadata
val putObjectResult = s3Client.putObject(putObjectRequest)
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
assertThat(copiedObject.objectMetadata.userMetadata)
.`as`("User metadata should be identical!")
.isEqualTo(sourceObjectMetadata.userMetadata)
}
/**
* Copy an object to a key needing URL escaping.
*
* @see .shouldCopyObject
*/
@Test
fun shouldCopyObjectToKeyNeedingEscaping(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = UPLOAD_FILE_NAME
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/some escape-worthy characters %$@ $sourceKey"
val putObjectResult = s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile))
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
/**
* Copy an object from a key needing URL escaping.
*
* @see .shouldCopyObject
*/
@Test
fun shouldCopyObjectFromKeyNeedingEscaping(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = "some escape-worthy characters %$@ $UPLOAD_FILE_NAME"
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val putObjectResult = s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile))
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
s3Client.copyObject(copyObjectRequest)
val copiedObject = s3Client.getObject(destinationBucketName, destinationKey)
val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent)
copiedObject.close()
assertThat(copiedDigest)
.`as`("Source file and copied File should have same digests")
.isEqualTo(putObjectResult.eTag)
}
/**
* Puts an Object; Copies that object to a new bucket; Downloads the object from the new bucket;
* compares checksums of original and copied object.
*/
@Test
@Throws(Exception::class)
fun shouldCopyObjectEncrypted(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val uploadFile = File(UPLOAD_FILE_NAME)
val sourceKey = UPLOAD_FILE_NAME
s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile))
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf/$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
copyObjectRequest.sseAwsKeyManagementParams = SSEAwsKeyManagementParams(TEST_ENC_KEY_ID)
val copyObjectResult = s3Client.copyObject(copyObjectRequest)
val metadata = s3Client.getObjectMetadata(destinationBucketName, destinationKey)
val uploadFileIs: InputStream = FileInputStream(uploadFile)
val uploadDigest = DigestUtil.hexDigest(TEST_ENC_KEY_ID, uploadFileIs)
assertThat(copyObjectResult.eTag)
.`as`("ETag should match")
.isEqualTo(uploadDigest)
assertThat(metadata.contentLength)
.`as`("Files should have the same length")
.isEqualTo(uploadFile.length())
}
/**
* Tests that an object won't be copied with wrong encryption Key.
*/
@Test
fun shouldNotObjectCopyWithWrongEncryptionKey(testInfo: TestInfo) {
val sourceKey = UPLOAD_FILE_NAME
val (bucketName, _) = givenBucketAndObjectV1(testInfo, sourceKey)
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
copyObjectRequest.sseAwsKeyManagementParams = SSEAwsKeyManagementParams(TEST_WRONG_KEY_ID)
assertThatThrownBy { s3Client.copyObject(copyObjectRequest) }
.isInstanceOf(AmazonS3Exception::class.java)
.hasMessageContaining("Status Code: 400; Error Code: KMS.NotFoundException")
}
/**
* Tests that a copy request for a non-existing object throws the correct error.
*/
@Test
fun shouldThrowNoSuchKeyOnCopyForNonExistingKey(testInfo: TestInfo) {
val bucketName = givenBucketV1(testInfo)
val sourceKey = randomName
val destinationBucketName = givenRandomBucketV1()
val destinationKey = "copyOf$sourceKey"
val copyObjectRequest =
CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey)
assertThatThrownBy { s3Client.copyObject(copyObjectRequest) }
.isInstanceOf(AmazonS3Exception::class.java)
.hasMessageContaining("Status Code: 404; Error Code: NoSuchKey")
}
@Test
fun multipartCopy() {
//content larger than default part threshold of 5MiB
val contentLen = 10 * _1MB
val objectMetadata = ObjectMetadata()
objectMetadata.contentLength = contentLen.toLong()
val assumedSourceKey = UUID.randomUUID().toString()
val sourceBucket = givenRandomBucketV1()
val targetBucket = givenRandomBucketV1()
val transferManager = createTransferManager()
val upload = transferManager
.upload(
sourceBucket, assumedSourceKey,
randomInputStream(contentLen), objectMetadata
)
val uploadResult = upload.waitForUploadResult()
assertThat(uploadResult.key).isEqualTo(assumedSourceKey)
val assumedDestinationKey = UUID.randomUUID().toString()
val copy = transferManager.copy(
sourceBucket, assumedSourceKey, targetBucket,
assumedDestinationKey
)
val copyResult = copy.waitForCopyResult()
assertThat(copyResult.destinationKey).isEqualTo(assumedDestinationKey)
assertThat(uploadResult.eTag)
.`as`("Hashes for source and target S3Object do not match.")
.isEqualTo(copyResult.eTag)
}
}
| integration-tests/src/test/kotlin/com/adobe/testing/s3mock/its/CopyObjectV1IT.kt | 3285210315 |
// GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.CSIPersistentVolumeSource as model_CSIPersistentVolumeSource
import io.fabric8.kubernetes.api.model.CSIVolumeSource as model_CSIVolumeSource
import io.fabric8.kubernetes.api.model.LocalObjectReference as model_LocalObjectReference
import io.fabric8.kubernetes.api.model.SecretReference as model_SecretReference
fun model_CSIPersistentVolumeSource.`nodePublishSecretRef`(block: model_SecretReference.() -> Unit = {}) {
if(this.`nodePublishSecretRef` == null) {
this.`nodePublishSecretRef` = model_SecretReference()
}
this.`nodePublishSecretRef`.block()
}
fun model_CSIVolumeSource.`nodePublishSecretRef`(block: model_LocalObjectReference.() -> Unit = {}) {
if(this.`nodePublishSecretRef` == null) {
this.`nodePublishSecretRef` = model_LocalObjectReference()
}
this.`nodePublishSecretRef`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/nodePublishSecretRef.kt | 1284884984 |
/*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.preference
import android.content.Context
import android.util.AttributeSet
import im.vector.util.VectorUtils
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.data.Room
/**
* Specialized class to target a Room avatar preference.
* Based don the avatar preference class it redefines refreshAvatar() and
* add the new method setConfiguration().
*/
class RoomAvatarPreference : UserAvatarPreference {
private var mRoom: Room? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun refreshAvatar() {
if (null != mAvatarView && null != mRoom) {
VectorUtils.loadRoomAvatar(context, mSession, mAvatarView, mRoom)
}
}
fun setConfiguration(aSession: MXSession, aRoom: Room) {
mSession = aSession
mRoom = aRoom
refreshAvatar()
}
} | vector/src/main/java/im/vector/preference/RoomAvatarPreference.kt | 1537895136 |
package com.mikepenz.materialdrawer.model
import android.view.View
import android.widget.CompoundButton
import android.widget.ToggleButton
import androidx.annotation.LayoutRes
import com.mikepenz.materialdrawer.R
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener
import com.mikepenz.materialdrawer.model.interfaces.Checkable
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
/**
* An abstract [IDrawerItem] implementation describing a drawerItem with support for a toggle
*/
open class AbstractToggleableDrawerItem<Item : AbstractToggleableDrawerItem<Item>> : Checkable, BaseDescribeableDrawerItem<Item, AbstractToggleableDrawerItem.ViewHolder>() {
var isToggleEnabled = true
override var isChecked = false
var onCheckedChangeListener: OnCheckedChangeListener? = null
override val type: Int
get() = R.id.material_drawer_item_primary_toggle
override val layoutRes: Int
@LayoutRes
get() = R.layout.material_drawer_item_toggle
private val checkedChangeListener = object : CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton, ic: Boolean) {
if (isEnabled) {
isChecked = ic
onCheckedChangeListener?.onCheckedChanged(this@AbstractToggleableDrawerItem, buttonView, ic)
} else {
buttonView.setOnCheckedChangeListener(null)
buttonView.isChecked = !ic
buttonView.setOnCheckedChangeListener(this)
}
}
}
@Deprecated("Please consider to replace with the actual property setter")
fun withToggleEnabled(toggleEnabled: Boolean): Item {
this.isToggleEnabled = toggleEnabled
return this as Item
}
@Deprecated("Please consider to replace with the actual property setter")
fun withOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener): Item {
this.onCheckedChangeListener = onCheckedChangeListener
return this as Item
}
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
//bind the basic view parts
bindViewHelper(holder)
//handle the toggle
holder.toggle.setOnCheckedChangeListener(null)
holder.toggle.isChecked = isChecked
holder.toggle.setOnCheckedChangeListener(checkedChangeListener)
holder.toggle.isEnabled = isToggleEnabled
//add a onDrawerItemClickListener here to be able to check / uncheck if the drawerItem can't be selected
withOnDrawerItemClickListener { v, item, position ->
if (!isSelectable) {
isChecked = !isChecked
holder.toggle.isChecked = isChecked
}
false
}
//call the onPostBindView method to trigger post bind view actions (like the listener to modify the item if required)
onPostBindView(this, holder.itemView)
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
open class ViewHolder internal constructor(view: View) : BaseViewHolder(view) {
internal val toggle: ToggleButton = view.findViewById<ToggleButton>(R.id.material_drawer_toggle)
}
}
| materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/AbstractToggleableDrawerItem.kt | 738839465 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import COMMON
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.ext.PagingTypeNames
import androidx.room.ext.SupportDbTypeNames
import androidx.room.ext.hasAnnotation
import androidx.room.ext.typeName
import androidx.room.processor.ProcessorErrors.RAW_QUERY_STRING_PARAMETER_REMOVED
import androidx.room.testing.TestInvocation
import androidx.room.testing.TestProcessor
import androidx.room.vo.RawQueryMethod
import com.google.auto.common.MoreElements
import com.google.auto.common.MoreTypes
import com.google.common.truth.Truth
import com.google.testing.compile.CompileTester
import com.google.testing.compile.JavaFileObjects
import com.google.testing.compile.JavaSourcesSubjectFactory
import com.squareup.javapoet.ArrayTypeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeName
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class RawQueryMethodProcessorTest {
@Test
fun supportRawQuery() {
singleQueryMethod(
"""
@RawQuery
abstract public int[] foo(SupportSQLiteQuery query);
""") { query, _ ->
assertThat(query.name, `is`("foo"))
assertThat(query.runtimeQueryParam, `is`(
RawQueryMethod.RuntimeQueryParameter(
paramName = "query",
type = SupportDbTypeNames.QUERY
)
))
assertThat(query.returnType.typeName(),
`is`(ArrayTypeName.of(TypeName.INT) as TypeName))
}.compilesWithoutError()
}
@Test
fun stringRawQuery() {
singleQueryMethod(
"""
@RawQuery
abstract public int[] foo(String query);
""") { _, _ ->
}.failsToCompile().withErrorContaining(RAW_QUERY_STRING_PARAMETER_REMOVED)
}
@Test
fun withObservedEntities() {
singleQueryMethod(
"""
@RawQuery(observedEntities = User.class)
abstract public LiveData<User> foo(SupportSQLiteQuery query);
""") { query, _ ->
assertThat(query.name, `is`("foo"))
assertThat(query.runtimeQueryParam, `is`(
RawQueryMethod.RuntimeQueryParameter(
paramName = "query",
type = SupportDbTypeNames.QUERY
)
))
assertThat(query.observedTableNames.size, `is`(1))
assertThat(query.observedTableNames, `is`(setOf("User")))
}.compilesWithoutError()
}
@Test
fun observableWithoutEntities() {
singleQueryMethod(
"""
@RawQuery(observedEntities = {})
abstract public LiveData<User> foo(SupportSQLiteQuery query);
""") { query, _ ->
assertThat(query.name, `is`("foo"))
assertThat(query.runtimeQueryParam, `is`(
RawQueryMethod.RuntimeQueryParameter(
paramName = "query",
type = SupportDbTypeNames.QUERY
)
))
assertThat(query.observedTableNames, `is`(emptySet()))
}.failsToCompile()
.withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE)
}
@Test
fun observableWithoutEntities_dataSourceFactory() {
singleQueryMethod(
"""
@RawQuery
abstract public ${PagingTypeNames.DATA_SOURCE_FACTORY}<Integer, User> getOne();
""") { _, _ ->
// do nothing
}.failsToCompile()
.withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE)
}
@Test
fun observableWithoutEntities_positionalDataSource() {
singleQueryMethod(
"""
@RawQuery
abstract public ${PagingTypeNames.POSITIONAL_DATA_SOURCE}<User> getOne();
""") { _, _ ->
// do nothing
}.failsToCompile()
.withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE)
}
@Test
fun positionalDataSource() {
singleQueryMethod(
"""
@RawQuery(observedEntities = {User.class})
abstract public ${PagingTypeNames.POSITIONAL_DATA_SOURCE}<User> getOne(
SupportSQLiteQuery query);
""") { _, _ ->
// do nothing
}.compilesWithoutError()
}
@Test
fun pojo() {
val pojo: TypeName = ClassName.get("foo.bar.MyClass", "MyPojo")
singleQueryMethod(
"""
public class MyPojo {
public String foo;
public String bar;
}
@RawQuery
abstract public MyPojo foo(SupportSQLiteQuery query);
""") { query, _ ->
assertThat(query.name, `is`("foo"))
assertThat(query.runtimeQueryParam, `is`(
RawQueryMethod.RuntimeQueryParameter(
paramName = "query",
type = SupportDbTypeNames.QUERY
)
))
assertThat(query.returnType.typeName(), `is`(pojo))
assertThat(query.observedTableNames, `is`(emptySet()))
}.compilesWithoutError()
}
@Test
fun void() {
singleQueryMethod(
"""
@RawQuery
abstract public void foo(SupportSQLiteQuery query);
""") { _, _ ->
}.failsToCompile().withErrorContaining(
ProcessorErrors.RAW_QUERY_BAD_RETURN_TYPE
)
}
@Test
fun noArgs() {
singleQueryMethod(
"""
@RawQuery
abstract public int[] foo();
""") { _, _ ->
}.failsToCompile().withErrorContaining(
ProcessorErrors.RAW_QUERY_BAD_PARAMS
)
}
@Test
fun tooManyArgs() {
singleQueryMethod(
"""
@RawQuery
abstract public int[] foo(SupportSQLiteQuery query,
SupportSQLiteQuery query2);
""") { _, _ ->
}.failsToCompile().withErrorContaining(
ProcessorErrors.RAW_QUERY_BAD_PARAMS
)
}
@Test
fun varargs() {
singleQueryMethod(
"""
@RawQuery
abstract public int[] foo(SupportSQLiteQuery... query);
""") { _, _ ->
}.failsToCompile().withErrorContaining(
ProcessorErrors.RAW_QUERY_BAD_PARAMS
)
}
@Test
fun observed_notAnEntity() {
singleQueryMethod(
"""
@RawQuery(observedEntities = {${COMMON.NOT_AN_ENTITY_TYPE_NAME}.class})
abstract public int[] foo(SupportSQLiteQuery query);
""") { _, _ ->
}.failsToCompile().withErrorContaining(
ProcessorErrors.rawQueryBadEntity(COMMON.NOT_AN_ENTITY_TYPE_NAME)
)
}
@Test
fun observed_relationPojo() {
singleQueryMethod(
"""
public static class MyPojo {
public String foo;
@Relation(
parentColumn = "foo",
entityColumn = "name"
)
public java.util.List<User> users;
}
@RawQuery(observedEntities = MyPojo.class)
abstract public int[] foo(SupportSQLiteQuery query);
""") { method, _ ->
assertThat(method.observedTableNames, `is`(setOf("User")))
}.compilesWithoutError()
}
@Test
fun observed_embedded() {
singleQueryMethod(
"""
public static class MyPojo {
public String foo;
@Embedded
public User users;
}
@RawQuery(observedEntities = MyPojo.class)
abstract public int[] foo(SupportSQLiteQuery query);
""") { method, _ ->
assertThat(method.observedTableNames, `is`(setOf("User")))
}.compilesWithoutError()
}
private fun singleQueryMethod(
vararg input: String,
handler: (RawQueryMethod, TestInvocation) -> Unit
): CompileTester {
return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
.that(listOf(JavaFileObjects.forSourceString("foo.bar.MyClass",
DAO_PREFIX
+ input.joinToString("\n")
+ DAO_SUFFIX
), COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.USER,
COMMON.DATA_SOURCE_FACTORY, COMMON.POSITIONAL_DATA_SOURCE,
COMMON.NOT_AN_ENTITY))
.processedWith(TestProcessor.builder()
.forAnnotations(Query::class, Dao::class, ColumnInfo::class,
Entity::class, PrimaryKey::class, RawQuery::class)
.nextRunHandler { invocation ->
val (owner, methods) = invocation.roundEnv
.getElementsAnnotatedWith(Dao::class.java)
.map {
Pair(it,
invocation.processingEnv.elementUtils
.getAllMembers(MoreElements.asType(it))
.filter {
it.hasAnnotation(RawQuery::class)
}
)
}.first { it.second.isNotEmpty() }
val parser = RawQueryMethodProcessor(
baseContext = invocation.context,
containing = MoreTypes.asDeclared(owner.asType()),
executableElement = MoreElements.asExecutable(methods.first()))
val parsedQuery = parser.process()
handler(parsedQuery, invocation)
true
}
.build())
}
companion object {
private const val DAO_PREFIX = """
package foo.bar;
import androidx.annotation.NonNull;
import androidx.room.*;
import androidx.sqlite.db.SupportSQLiteQuery;
import androidx.lifecycle.LiveData;
@Dao
abstract class MyClass {
"""
private const val DAO_SUFFIX = "}"
}
} | room/compiler/src/test/kotlin/androidx/room/processor/RawQueryMethodProcessorTest.kt | 4214973657 |
package com.ivanovsky.passnotes.presentation.note_editor.view
enum class TextInputLines {
SINGLE_LINE,
MULTIPLE_LINES
} | app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note_editor/view/TextInputLines.kt | 2602981785 |
package com.ivanovsky.passnotes.domain.interactor.filepicker
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.file.FileSystemResolver
class FilePickerInteractor(private val fileSystemResolver: FileSystemResolver) {
fun getFileList(dir: FileDescriptor): OperationResult<List<FileDescriptor>> {
return fileSystemResolver.resolveProvider(dir.fsAuthority).listFiles(dir)
}
fun getParent(file: FileDescriptor): OperationResult<FileDescriptor> {
return fileSystemResolver.resolveProvider(file.fsAuthority).getParent(file)
}
} | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/filepicker/FilePickerInteractor.kt | 1170112905 |
package nl.deltadak.plep.ui.taskcell
import javafx.geometry.Pos
import javafx.scene.control.CheckBox
import javafx.scene.control.ComboBox
import javafx.scene.control.Label
import javafx.scene.control.TreeItem
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.Region
import javafx.scene.text.TextAlignment
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.tables.Colors
import nl.deltadak.plep.ui.taskcell.components.textlabel.TextLabelStyle
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.ChangeListenerWithBlocker
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.InvalidationListenerWithBlocker
import nl.deltadak.plep.ui.util.LABEL_MAGIK
/**
* Manages the layout of a TreeCell. Always contains a CheckBox and a Label (text). Also contains a ComboBox (dropdown menu) if the Cell is the root of a task.
* The given components are updated with the correct layout.
*
* @property taskCell Cell to set layout on.
* @property doneChangeListener Should provide the ability to temporarily block the listener of the checkbox.
* @property checkBox Checkbox of the task.
* @property label Text of the task.
* @property labelChangeListener Should provide the ability to temporarily block the listener of the combobox.
* @property root Root item of the TreeView in which the task is.
* @property comboBox Combobox of the task.
*/
class TaskLayout(private val taskCell: TaskCell, private val doneChangeListener: ChangeListenerWithBlocker<Boolean>, private val checkBox: CheckBox, val label: Label, private val labelChangeListener: InvalidationListenerWithBlocker, val root: TreeItem<HomeworkTask>, private val comboBox: ComboBox<String>) {
/**
* Updates the layout.
* The homeworktask could be null, since updating is initiated by JavaFX.
*
* @param homeworkTask The Homework task to be displayed in the Cell.
*/
fun update(homeworkTask: HomeworkTask?) {
if (taskCell.isEmpty) {
taskCell.graphic = null
taskCell.text = null
} else {
if (homeworkTask != null) {
setLayout(homeworkTask)
}
}
}
private fun setLayout(homeworkTask: HomeworkTask) {
// Create the container for components.
val cellBox = HBox(10.0)
cellBox.alignment = Pos.CENTER_LEFT
setCheckBox(homeworkTask)
setTextLabel(homeworkTask)
// Get style from the database and apply to the item.
val color = Colors.get(homeworkTask.colorID)
taskCell.style = "-fx-control-inner-background: #$color"
TextLabelStyle().setDoneStyle(homeworkTask.done, label, comboBox)
// If the item is top level, a parent task, it has to show a course label (ComboBox), and it has to have a context menu.
if (taskCell.treeItem.parent == root) {
val region = setComboBox(homeworkTask)
cellBox.children.addAll(checkBox, label, region, comboBox)
taskCell.graphic = cellBox
taskCell.text = null
} else {
// Set up subtask, with context menu disabled.
with(taskCell) {
contextMenu = null
graphic = cellBox.apply { children.addAll(checkBox, label) }
text = null
}
}
}
/**
* Setup checkbox.
*/
private fun setCheckBox(homeworkTask: HomeworkTask) {
// Block the listener on the checkbox when we manually toggle it, so it corresponds to the value in the database.
doneChangeListener.block = true
val done = homeworkTask.done
// Manually toggle, if necessary.
checkBox.isSelected = done
doneChangeListener.block = false
}
/**
* Setup text label.
*/
private fun setTextLabel(homeworkTask: HomeworkTask) {
with(label) {
text = homeworkTask.text
prefWidthProperty().bind(taskCell.treeView.widthProperty().subtract(LABEL_MAGIK))
isWrapText = true
textAlignment = TextAlignment.JUSTIFY
}
}
/**
* Setup combobox.
*/
private fun setComboBox(homeworkTask: HomeworkTask): Region {
// Before setting value, we need to temporarily disable the listener, otherwise it fires and goes unnecessarily updating the database, which takes a lot of time.
labelChangeListener.block = true
comboBox.value = homeworkTask.label
labelChangeListener.block = false
// Create a region to make sure that the ComboBox is aligned on the right.
val region = Region()
HBox.setHgrow(region, Priority.ALWAYS)
return region
}
}
| src/main/kotlin/nl/deltadak/plep/ui/taskcell/TaskLayout.kt | 2527412726 |
package com.orgzly.android.query
class QueryTokenizer(val str: String, private val groupOpen: String, private val groupClose: String) {
val tokens = tokanize(str)
var nextToken = 0
fun hasMoreTokens(): Boolean = nextToken < tokens.size
fun nextToken() = tokens[nextToken++]
private fun tokanize(str: String): List<String> {
return tokenRegex.findAll(str).map { it.value }.toList()
}
companion object {
val TAG: String = QueryTokenizer::class.java.name
private const val char = """[^")(\s]"""
private const val doubleQuoted = """"[^"\\]*(?:\\.[^"\\]*)*""""
private const val doubleQuotedWithPrefix = """$char*$doubleQuoted"""
private const val groupOpener = """\("""
private const val groupCloser = """\)"""
private const val rest = """$char+"""
private val tokenRegex =
listOf(doubleQuotedWithPrefix, groupOpener, groupCloser, rest)
.joinToString("|").toRegex()
fun unquote(s: String): String {
if (s.length < 2) {
return s
}
val first = s[0]
val last = s[s.length - 1]
if (first != last || first != '"') {
return s
}
val b = StringBuilder(s.length - 2)
var quote = false
for (i in 1 until s.length - 1) {
val c = s[i]
if (c == '\\' && !quote) {
quote = true
continue
}
quote = false
b.append(c)
}
return b.toString()
}
fun quote(s: String, delim: String): String {
if (s.isEmpty()) {
return "\"\""
}
for (element in s) {
if (element == '"' || element == '\\' || delim.indexOf(element) >= 0) {
return quoteUnconditionally(s)
}
}
return s
}
fun quoteUnconditionally(s: String): String {
val builder = StringBuilder(s.length + 8)
builder.append('"')
for (element in s) {
if (element == '"') {
builder.append('\\')
}
builder.append(element)
continue
}
builder.append('"')
return builder.toString()
}
}
} | app/src/main/java/com/orgzly/android/query/QueryTokenizer.kt | 1169657403 |
package com.orgzly.android.ui.drawer
import android.content.Intent
import android.content.res.Resources
import android.view.Menu
import androidx.lifecycle.Observer
import com.google.android.material.navigation.NavigationView
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.AppIntent
import com.orgzly.android.db.entity.BookAction
import com.orgzly.android.db.entity.BookView
import com.orgzly.android.db.entity.SavedSearch
import com.orgzly.android.ui.books.BooksFragment
import com.orgzly.android.ui.main.MainActivity
import com.orgzly.android.ui.main.MainActivityViewModel
import com.orgzly.android.ui.notes.book.BookFragment
import com.orgzly.android.ui.notes.query.QueryFragment
import com.orgzly.android.ui.savedsearches.SavedSearchesFragment
import com.orgzly.android.util.LogUtils
import java.util.*
internal class DrawerNavigationView(
private val activity: MainActivity,
viewModel: MainActivityViewModel,
navView: NavigationView) {
private val menu: Menu = navView.menu
private val menuItemIdMap = hashMapOf<String, Int>()
private var activeFragmentTag: String? = null
init {
// Add mapping for groups
menuItemIdMap[BooksFragment.drawerItemId] = R.id.books
menuItemIdMap[SavedSearchesFragment.getDrawerItemId()] = R.id.searches
// Setup intents
menu.findItem(R.id.searches).intent = Intent(AppIntent.ACTION_OPEN_SAVED_SEARCHES)
menu.findItem(R.id.books).intent = Intent(AppIntent.ACTION_OPEN_BOOKS)
menu.findItem(R.id.settings).intent = Intent(AppIntent.ACTION_OPEN_SETTINGS)
viewModel.books().observe(activity, Observer {
refreshFromBooks(it)
})
viewModel.savedSearches().observe(activity, Observer {
refreshFromSavedSearches(it)
})
}
fun updateActiveFragment(fragmentTag: String) {
this.activeFragmentTag = fragmentTag
setActiveItem(fragmentTag)
}
private fun setActiveItem(fragmentTag: String) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, fragmentTag)
this.activeFragmentTag = fragmentTag
val fragment = activity.supportFragmentManager.findFragmentByTag(activeFragmentTag)
// Uncheck all
for (i in 0 until menu.size()) {
menu.getItem(i).isChecked = false
}
if (fragment != null && fragment is DrawerItem) {
val fragmentMenuItemId = fragment.getCurrentDrawerItemId()
val itemId = menuItemIdMap[fragmentMenuItemId]
if (itemId != null) {
menu.findItem(itemId)?.isChecked = true
}
}
}
private fun refreshFromSavedSearches(savedSearches: List<SavedSearch>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedSearches.size)
removeItemsWithOrder(1)
savedSearches.forEach { savedSearch ->
val intent = Intent(AppIntent.ACTION_OPEN_QUERY)
intent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.query)
val id = generateRandomUniqueId()
val item = menu.add(R.id.drawer_group, id, 1, savedSearch.name)
menuItemIdMap[QueryFragment.getDrawerItemId(savedSearch.query)] = id
item.intent = intent
item.isCheckable = true
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun refreshFromBooks(books: List<BookView>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, books.size)
removeItemsWithOrder(3)
books.forEach { book ->
val intent = Intent(AppIntent.ACTION_OPEN_BOOK)
intent.putExtra(AppIntent.EXTRA_BOOK_ID, book.book.id)
val id = generateRandomUniqueId()
val name = book.book.run { title ?: name }
val item = menu.add(R.id.drawer_group, id, 3, name)
item.isEnabled = !book.book.isDummy
item.intent = intent
item.isCheckable = true
if (book.book.lastAction?.type == BookAction.Type.ERROR) {
item.setActionView(R.layout.drawer_item_sync_failed)
} else if (book.isOutOfSync()) {
item.setActionView(R.layout.drawer_item_sync_needed)
}
menuItemIdMap[BookFragment.getDrawerItemId(book.book.id)] = id
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun generateRandomUniqueId(): Int {
val rand = Random()
while (true) {
val id = rand.nextInt(Integer.MAX_VALUE) + 1
try {
activity.resources.getResourceName(id)
} catch (e: Resources.NotFoundException) {
return id
}
}
}
private fun removeItemsWithOrder(orderToDelete: Int) {
val itemIdsToRemove = HashSet<Int>()
var i = 0
while (true) {
val item = menu.getItem(i++) ?: break
val order = item.order
if (order > orderToDelete) {
break
} else if (order == orderToDelete) {
itemIdsToRemove.add(item.itemId)
}
}
for (id in itemIdsToRemove) {
menu.removeItem(id)
}
}
companion object {
private val TAG = DrawerNavigationView::class.java.name
}
}
| app/src/main/java/com/orgzly/android/ui/drawer/DrawerNavigationView.kt | 18121676 |
package com.piticlistudio.playednext.data.entity.mapper.datasources.image
import com.piticlistudio.playednext.data.entity.giantbomb.GiantbombGameImage
import com.piticlistudio.playednext.test.factory.DataFactory
import com.piticlistudio.playednext.test.factory.GameImageFactory.Factory.makeGiantbombGameImage
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
/**
* Test cases for [GiantbombImageMapper]
* Created by e-jegi on 3/26/2018.
*/
internal class GiantbombImageMapperTest {
private val mapper = GiantbombImageMapper()
@Nested
@DisplayName("When we call mapFromDataLayer")
inner class MapFromModel {
@Test
fun `then should map into GameImage with medium url values`() {
val response = makeGiantbombGameImage()
val result = mapper.mapFromDataLayer(response)
assertNotNull(result)
with(result) {
assertEquals(response.medium_url, result?.url)
}
}
@Test
fun `then should map into GameImage with screen_url value when medium_url is null`() {
val response = GiantbombGameImage(icon_url = DataFactory.randomString(),
medium_url = null,
original_url = DataFactory.randomString(),
screen_large_url = DataFactory.randomString(),
screen_url = DataFactory.randomString(),
small_url = DataFactory.randomString(),
super_url = DataFactory.randomString(),
thumb_url = DataFactory.randomString(),
tiny_url = DataFactory.randomString())
val result = mapper.mapFromDataLayer(response)
assertNotNull(result)
with(result) {
assertEquals(response.screen_url, result?.url)
}
}
@Test
fun `then should map into GameImage with screen_large_url value when medium_url and screen_url are null`() {
val response = GiantbombGameImage(icon_url = DataFactory.randomString(),
medium_url = null,
original_url = DataFactory.randomString(),
screen_large_url = DataFactory.randomString(),
screen_url = null,
small_url = DataFactory.randomString(),
super_url = DataFactory.randomString(),
thumb_url = DataFactory.randomString(),
tiny_url = DataFactory.randomString())
val result = mapper.mapFromDataLayer(response)
assertNotNull(result)
with(result) {
assertEquals(response.screen_large_url, result?.url)
}
}
@Test
fun `then should map into GameImage with small_url value when medium_url, screen_url and screen_large_url are null`() {
val response = GiantbombGameImage(icon_url = DataFactory.randomString(),
medium_url = null,
original_url = DataFactory.randomString(),
screen_large_url = null,
screen_url = null,
small_url = DataFactory.randomString(),
super_url = DataFactory.randomString(),
thumb_url = DataFactory.randomString(),
tiny_url = DataFactory.randomString())
val result = mapper.mapFromDataLayer(response)
assertNotNull(result)
with(result) {
assertEquals(response.small_url, result?.url)
}
}
@Test
fun `then should map into GameImage with original_url value when medium_url, screen_url, screen_large_url and small_url are null`() {
val response = GiantbombGameImage(icon_url = DataFactory.randomString(),
medium_url = null,
original_url = DataFactory.randomString(),
screen_large_url = null,
screen_url = null,
small_url = null,
super_url = DataFactory.randomString(),
thumb_url = DataFactory.randomString(),
tiny_url = DataFactory.randomString())
val result = mapper.mapFromDataLayer(response)
assertNotNull(result)
with(result) {
assertEquals(response.original_url, result?.url)
}
}
@Test
fun `then should return null if no available url to map from`() {
val response = GiantbombGameImage(icon_url = DataFactory.randomString(),
medium_url = null,
original_url = null,
screen_large_url = null,
screen_url = null,
small_url = null,
super_url = DataFactory.randomString(),
thumb_url = DataFactory.randomString(),
tiny_url = DataFactory.randomString())
val result = mapper.mapFromDataLayer(response)
assertNull(result)
}
}
} | app/src/test/java/com/piticlistudio/playednext/data/entity/mapper/datasources/image/GiantbombImageMapperTest.kt | 1290271119 |
package fr.free.nrw.commons
import android.content.ContentProviderClient
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.util.LruCache
import com.nhaarman.mockito_kotlin.mock
import com.squareup.leakcanary.RefWatcher
import fr.free.nrw.commons.auth.AccountUtil
import fr.free.nrw.commons.auth.SessionManager
import fr.free.nrw.commons.data.DBOpenHelper
import fr.free.nrw.commons.di.CommonsApplicationComponent
import fr.free.nrw.commons.di.CommonsApplicationModule
import fr.free.nrw.commons.di.DaggerCommonsApplicationComponent
import fr.free.nrw.commons.location.LocationServiceManager
import fr.free.nrw.commons.mwapi.MediaWikiApi
import fr.free.nrw.commons.nearby.NearbyPlaces
import fr.free.nrw.commons.upload.UploadController
class TestCommonsApplication : CommonsApplication() {
private var mockApplicationComponent: CommonsApplicationComponent? = null
override fun onCreate() {
if (mockApplicationComponent == null) {
mockApplicationComponent = DaggerCommonsApplicationComponent.builder()
.appModule(MockCommonsApplicationModule(this)).build()
}
super.onCreate()
}
// No leakcanary in unit tests.
override fun setupLeakCanary(): RefWatcher = RefWatcher.DISABLED
}
@Suppress("MemberVisibilityCanBePrivate")
class MockCommonsApplicationModule(appContext: Context) : CommonsApplicationModule(appContext) {
val accountUtil: AccountUtil = mock()
val appSharedPreferences: SharedPreferences = mock()
val defaultSharedPreferences: SharedPreferences = mock()
val otherSharedPreferences: SharedPreferences = mock()
val uploadController: UploadController = mock()
val mockSessionManager: SessionManager = mock()
val locationServiceManager: LocationServiceManager = mock()
val mockDbOpenHelper: DBOpenHelper = mock()
val nearbyPlaces: NearbyPlaces = mock()
val lruCache: LruCache<String, String> = mock()
val categoryClient: ContentProviderClient = mock()
val contributionClient: ContentProviderClient = mock()
val modificationClient: ContentProviderClient = mock()
val uploadPrefs: SharedPreferences = mock()
override fun provideCategoryContentProviderClient(context: Context?): ContentProviderClient = categoryClient
override fun provideContributionContentProviderClient(context: Context?): ContentProviderClient = contributionClient
override fun provideModificationContentProviderClient(context: Context?): ContentProviderClient = modificationClient
override fun providesDirectNearbyUploadPreferences(context: Context?): SharedPreferences = uploadPrefs
override fun providesAccountUtil(context: Context): AccountUtil = accountUtil
override fun providesApplicationSharedPreferences(context: Context): SharedPreferences = appSharedPreferences
override fun providesDefaultSharedPreferences(context: Context): SharedPreferences = defaultSharedPreferences
override fun providesOtherSharedPreferences(context: Context): SharedPreferences = otherSharedPreferences
override fun providesUploadController(sessionManager: SessionManager, sharedPreferences: SharedPreferences, context: Context): UploadController = uploadController
override fun providesSessionManager(context: Context, mediaWikiApi: MediaWikiApi, sharedPreferences: SharedPreferences): SessionManager = mockSessionManager
override fun provideLocationServiceManager(context: Context): LocationServiceManager = locationServiceManager
override fun provideDBOpenHelper(context: Context): DBOpenHelper = mockDbOpenHelper
override fun provideNearbyPlaces(): NearbyPlaces = nearbyPlaces
override fun provideLruCache(): LruCache<String, String> = lruCache
} | app/src/test/kotlin/fr/free/nrw/commons/TestCommonsApplication.kt | 2577388714 |
package io.sonatalang.snc.frontend.domain.token
object NewLineToken : BasicToken(false), TokenFactory<NewLineToken> {
override fun with(character: Char) = this
override fun toString() = "\n"
override fun isSuitable(character: Char) = character == '\n'
override fun create(character: Char) = NewLineToken
}
| frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/NewLineToken.kt | 3518168341 |
package com.openconference.sessiondetails.presentationmodel
import com.openconference.model.Session
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.FormatStyle
import java.util.*
/**
* Responsible to transform a Session to [SessionDetailItem]
*
* @author Hannes Dorfmann
*/
interface SessionDetailsPresentationModelTransformer {
fun transform(session: Session): SessionDetail
}
/**
* Phone Session Details Presentation Model Transformer
* @author Hannes Dorfmann
*/
// TODO Tablet
class PhoneSessionDetailsPresentationModelTransformer : SessionDetailsPresentationModelTransformer {
private val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
override fun transform(session: Session): SessionDetail {
val items = ArrayList<SessionDetailItem>()
// TODO use settings for time zone (users preferences)
val zoneId = ZoneId.systemDefault()
val start = session.startTime()
val localStart = if (start == null) null else LocalDateTime.ofInstant(start, zoneId)
val end = session.endTime()
val localEnd = if (end == null) null else LocalDateTime.ofInstant(end, zoneId)
if (start != null) {
val dateStr = if (end != null) {
"${dateFormatter.format(localStart)} - ${dateFormatter.format(localEnd)}"
} else {
dateFormatter.format(localStart)
}
items.add(SessionDateTimeItem(dateStr))
}
// Location
val locationName = session.locationName()
if (locationName != null) items.add(SessionLocationItem(locationName))
// Description
val description = session.description()
if (description != null) {
if (items.isNotEmpty()) items.add(SessionSeparatorItem())
items.add(SessionDescriptionItem(description))
}
// TODO TAGS
// Tags
/*
val tags = session.tags()
if (tags != null) items.add(SessionTagsItem(tags))
*/
// Speakers
if (session.speakers().isNotEmpty()) {
items.add(SessionSeparatorItem())
}
session.speakers().forEach { items.add(SessionSpeakerItem(it)) }
// TODO refactor
return SessionDetail(session.id(), session.title(), session, items, session.favorite())
}
} | app/src/main/java/com/openconference/sessiondetails/presentationmodel/SessionDetailsPresentationModelTransformer.kt | 2119214681 |
/*
* 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.android.libraries.pcc.chronicle.analysis.impl
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.StorageMedia
import com.google.android.libraries.pcc.chronicle.api.policy.annotation.Annotation
import com.google.common.truth.Truth.assertThat
import java.time.Duration
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AnnotationTest {
@Test
fun duration_toAnnotation() {
assertThat(Duration.ofMillis(150).toAnnotation()).isEqualTo(Annotation.createTtl("0 minutes"))
assertThat(Duration.ofMillis(1500).toAnnotation()).isEqualTo(Annotation.createTtl("0 minutes"))
assertThat(Duration.ofSeconds(60).toAnnotation()).isEqualTo(Annotation.createTtl("1 minutes"))
assertThat(Duration.ofDays(10).toAnnotation())
.isEqualTo(Annotation.createTtl("${Duration.ofDays(10).toMinutes()} minutes"))
}
@Test
fun managementStrategy_toAnnotations_passThru() {
val annotations = ManagementStrategy.PassThru.toAnnotations()
assertThat(annotations).containsExactly(ANNOTATION_IN_MEMORY)
}
@Test
fun managementStrategy_toAnnotations_storedEncryptedLocalDiskNoTtl() {
val annotations =
ManagementStrategy.Stored(encrypted = true, media = StorageMedia.LOCAL_DISK, ttl = null)
.toAnnotations()
assertThat(annotations).containsExactly(ANNOTATION_PERSISTENT, ANNOTATION_ENCRYPTED)
}
@Test
fun managementStrategy_toAnnotations_storedUnencryptedMemoryNoTtl() {
val annotations =
ManagementStrategy.Stored(encrypted = false, media = StorageMedia.MEMORY, ttl = null)
.toAnnotations()
assertThat(annotations).containsExactly(ANNOTATION_IN_MEMORY)
}
@Test
fun managementStrategy_toAnnotations_storedUnencryptedMemoryTtl() {
val annotations =
ManagementStrategy.Stored(
encrypted = false,
media = StorageMedia.MEMORY,
ttl = Duration.ofMinutes(5)
)
.toAnnotations()
assertThat(annotations)
.containsExactly(ANNOTATION_IN_MEMORY, Duration.ofMinutes(5).toAnnotation())
}
@Test
fun managementStrategy_toAnnotations_storedEncryptedRemoteTtl() {
val annotations =
ManagementStrategy.Stored(
encrypted = true,
media = StorageMedia.REMOTE_DISK,
ttl = Duration.ofMinutes(500)
)
.toAnnotations()
assertThat(annotations)
.containsExactly(
ANNOTATION_REMOTE_PERSISTENT,
ANNOTATION_ENCRYPTED,
Duration.ofMinutes(500).toAnnotation()
)
}
}
| javatests/com/google/android/libraries/pcc/chronicle/analysis/impl/AnnotationTest.kt | 2846956362 |
package com.battlelancer.seriesguide.traktapi
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import com.battlelancer.seriesguide.provider.SgRoomDatabase.Companion.getInstance
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.safeShow
/**
* Allows to check into an episode. Launching activities should subscribe to
* [TraktTask.TraktActionCompleteEvent] to display status toasts.
*/
class CheckInDialogFragment : GenericCheckInDialogFragment() {
override fun checkInTrakt(message: String) {
TraktTask(requireContext()).checkInEpisode(
requireArguments().getLong(ARG_EPISODE_ID),
requireArguments().getString(ARG_ITEM_TITLE),
message
).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
companion object {
/**
* Builds and shows a new [CheckInDialogFragment] setting all values based on the given
* episode row ID.
*
* @return `false` if the fragment was not shown.
*/
fun show(context: Context, fragmentManager: FragmentManager, episodeId: Long): Boolean {
val episode = getInstance(context).sgEpisode2Helper().getEpisodeWithShow(episodeId)
?: return false
val f = CheckInDialogFragment()
val args = Bundle()
args.putLong(ARG_EPISODE_ID, episodeId)
val episodeTitleWithNumbers = (episode.seriestitle
+ " "
+ TextTools.getNextEpisodeString(
context,
episode.season,
episode.episodenumber,
episode.episodetitle
))
args.putString(ARG_ITEM_TITLE, episodeTitleWithNumbers)
f.arguments = args
return f.safeShow(fragmentManager, "checkInDialog")
}
}
} | app/src/main/java/com/battlelancer/seriesguide/traktapi/CheckInDialogFragment.kt | 3532064690 |
package cc.redpen.intellij
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.LangDataKeys.PSI_FILE
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.CustomStatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget.WidgetBorder.WIDE
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.status.EditorBasedWidget
import com.intellij.openapi.wm.impl.status.TextPanel
import com.intellij.psi.PsiManager
import com.intellij.ui.ClickListener
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.UIUtil
import java.awt.Component
import java.awt.Graphics
import java.awt.Point
import java.awt.event.MouseEvent
open class StatusWidget constructor(project: Project) : EditorBasedWidget(project), CustomStatusBarWidget, ProjectComponent {
val provider = RedPenProvider.forProject(project)
var enabled: Boolean = false
val actionGroupId = "RedPen " + project.basePath
companion object {
fun forProject(project: Project) = project.getComponent(StatusWidget::class.java)!!
}
var actionGroup: DefaultActionGroup? = null
private val component = object: TextPanel.ExtraSize() {
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (enabled && text != null) {
val arrows = AllIcons.Ide.Statusbar_arrows
arrows.paintIcon(this, g, bounds.width - insets.right - arrows.iconWidth - 2,
bounds.height / 2 - arrows.iconHeight / 2)
}
}
}
override fun projectOpened() {
install(WindowManager.getInstance().getStatusBar(project))
myStatusBar.addWidget(this, "before Encoding")
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
showPopup(e)
return true
}
}.installOn(component)
component.border = WIDE
component.toolTipText = "RedPen language"
registerActions()
}
override fun projectClosed() {
myStatusBar.removeWidget(ID())
unregisterActions()
}
override fun getComponentName(): String = "StatusWidget"
override fun initComponent() {}
override fun disposeComponent() {}
open fun registerActions() {
val actionManager = ActionManager.getInstance() ?: return
actionGroup = DefaultActionGroup()
provider.configs.keys.forEach { key ->
actionGroup!!.add(object : AnAction() {
init { templatePresentation.text = key }
override fun actionPerformed(e: AnActionEvent) {
provider.setConfigFor(e.getData(PSI_FILE)!!, key)
DaemonCodeAnalyzer.getInstance(e.project).restart()
}
})
}
actionManager.registerAction(actionGroupId, actionGroup!!)
}
open internal fun unregisterActions() {
ActionManager.getInstance()?.unregisterAction(actionGroupId)
}
override fun ID(): String {
return "RedPen"
}
override fun getPresentation(platformType: StatusBarWidget.PlatformType): StatusBarWidget.WidgetPresentation? {
return null
}
open fun update(configKey: String) {
if (isDisposed) return
ApplicationManager.getApplication().invokeLater {
component.text = configKey
component.foreground = if (enabled) UIUtil.getActiveTextColor() else UIUtil.getInactiveTextColor()
}
}
override fun selectionChanged(event: FileEditorManagerEvent) {
val file = if (event.newFile == null) null else PsiManager.getInstance(project!!).findFile(event.newFile!!)
if (file != null && provider.getParser(file) != null) {
enabled = true
update(provider.getConfigKeyFor(file))
}
else {
enabled = false
update("n/a")
}
}
override fun getComponent(): TextPanel {
return component
}
internal fun showPopup(e: MouseEvent) {
if (!enabled) return
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
"RedPen", actionGroup!!, getContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false)
val dimension = popup.content.preferredSize
val at = Point(0, -dimension.height)
popup.show(RelativePoint(e.component, at))
Disposer.register(this, popup)
}
private fun getContext(): DataContext {
val editor = editor
val parent = DataManager.getInstance().getDataContext(myStatusBar as Component)
return SimpleDataContext.getSimpleContext(
CommonDataKeys.VIRTUAL_FILE_ARRAY.name,
arrayOf(selectedFile!!),
SimpleDataContext.getSimpleContext(CommonDataKeys.PROJECT.name,
project,
SimpleDataContext.getSimpleContext(PlatformDataKeys.CONTEXT_COMPONENT.name,
editor?.component, parent)))
}
fun rebuild() {
unregisterActions()
registerActions()
}
}
| src/cc/redpen/intellij/StatusWidget.kt | 144039327 |
package net
import SearchResponse
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import data.Repository
import java.io.PrintWriter
import java.nio.file.Path
class ProjectExtractor(val savePath: Path, val start:String, val end:String)
{
fun extract(page : Int = 0)
{
var results = HashMap<String, Repository>()
var totalCount = 0
val requestBuilder = RequestBuilder(start, end)
if(savePath.toFile().exists())
results = Gson().fromJson(savePath.toFile().readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
requestBuilder.page = page;
while(true)
{
val (request, response, result) = requestBuilder.build().responseObject(SearchResponse.Deserializer());
val (search, err) = result
println(request.url)
search?.let {
search.items.forEach({
if(it.full_name.isNullOrEmpty() || it.language.isNullOrEmpty())
return@forEach
if(!results.containsKey(it.full_name) && it.size < 2048000 && it.language.equals("Java")) {
results.put(it.full_name, it);
println("added ${it.full_name}")
}
})
totalCount += search.items.size;
}
if(requestBuilder.page > 34)
break
else if(err != null) {
Thread.sleep(10000)
}else if(search!!.items.isEmpty())
break
else
requestBuilder.page++;
}
savePath.toFile().printWriter().use { out: PrintWriter ->
out.print(GsonBuilder().setPrettyPrinting().create().toJson(results))
}
}
}
| src/main/kotlin/net/ProjectExtractor.kt | 2034555772 |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import org.springframework.context.ApplicationListener
import org.springframework.context.ConfigurableApplicationContext
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.function.Predicate
/**
* An [ApplicationListener] implementation you can use to wait for an execution
* to complete. Much better than `Thread.sleep(whatever)` in your tests.
*/
class ExecutionLatch(private val predicate: Predicate<ExecutionComplete>) :
ApplicationListener<ExecutionComplete> {
private val latch = CountDownLatch(1)
override fun onApplicationEvent(event: ExecutionComplete) {
if (predicate.test(event)) {
latch.countDown()
}
}
fun await() = latch.await(10, TimeUnit.SECONDS)
}
fun ConfigurableApplicationContext.runToCompletion(execution: Execution, launcher: (Execution) -> Unit, repository: ExecutionRepository) {
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(execution)
}
/**
* Given parent and child pipelines:
* 1) Start child pipeline
* 2) Invoke parent pipeline and continue until completion
*
* Useful for testing failure interactions between pipelines. Child pipeline can be inspected prior to
* completion, and subsequently completed via [runToCompletion].
*/
fun ConfigurableApplicationContext.runParentToCompletion(
parent: Execution,
child: Execution,
launcher: (Execution) -> Unit,
repository: ExecutionRepository
) {
val latch = ExecutionLatch(Predicate {
it.executionId == parent.id
})
addApplicationListener(latch)
launcher.invoke(child)
launcher.invoke(parent)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(parent)
}
fun ConfigurableApplicationContext.restartAndRunToCompletion(stage: Stage, launcher: (Execution, String) -> Unit, repository: ExecutionRepository) {
val execution = stage.execution
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution, stage.id)
assert(latch.await()) { "Pipeline did not complete after restarting" }
repository.waitForAllStagesToComplete(execution)
}
private fun ExecutionRepository.waitForAllStagesToComplete(execution: Execution) {
var complete = false
while (!complete) {
Thread.sleep(100)
complete = retrieve(PIPELINE, execution.id)
.run {
status.isComplete && stages
.map(Stage::getStatus)
.all { it.isComplete || it == NOT_STARTED }
}
}
}
| orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/ExecutionLatch.kt | 1635152740 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composemail.ui.utils
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.ConstraintSetScope
@Composable
fun rememberConstraintSet(
key: Any = Unit,
constraints: ConstraintSetScope.() -> Unit
): ConstraintSet {
val constraintSet = remember(key) {
ConstraintSet(constraints)
}
return constraintSet
} | demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/utils/ConstraintUtils.kt | 2783552708 |
/*
* Copyright 2022 Ren Binden
*
* 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.rpkit.permissions.bukkit.listener
import com.rpkit.permissions.bukkit.RPKPermissionsBukkit
import com.rpkit.permissions.bukkit.database.table.RPKProfileGroupTable
import com.rpkit.players.bukkit.event.profile.RPKBukkitProfileDeleteEvent
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class RPKProfileDeleteListener(private val plugin: RPKPermissionsBukkit) : Listener {
@EventHandler
fun onProfileDelete(event: RPKBukkitProfileDeleteEvent) {
val profileId = event.profile.id
if (profileId != null) {
plugin.database.getTable(RPKProfileGroupTable::class.java).delete(profileId)
}
}
} | bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/listener/RPKProfileDeleteListener.kt | 468279708 |
package test.assertk.assertions
import assertk.assertThat
import assertk.assertions.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class MapTest {
//region contains
@Test fun contains_element_present_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).contains("two" to 2)
}
@Test fun contains_element_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).contains("one" to 1)
}
assertEquals("expected to contain:<{\"one\"=1}> but was:<{}>", error.message)
}
@Test fun contains_element_with_nullable_value_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int?>()).contains("one" to null)
}
assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message)
}
//endregion
//region doesNotContain
@Test fun doesNotContain_element_missing_passes() {
assertThat(emptyMap<String, Int>()).doesNotContain("one" to 1)
}
@Test fun doesNotContain_element_with_missing_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).doesNotContain("one" to null)
}
@Test fun doesNotContain_element_present_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).doesNotContain("two" to 2)
}
assertEquals("expected to not contain:<{\"two\"=2}> but was:<{\"one\"=1, \"two\"=2}>", error.message)
}
//endregion
//region containsNone
@Test fun containsNone_missing_elements_passes() {
assertThat(emptyMap<String, Int>()).containsNone("one" to 1)
}
@Test fun containsNone_missing_elements_with_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).containsNone("one" to null)
}
@Test fun containsNone_present_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsNone("two" to 2, "three" to 3)
}
assertEquals(
"""expected to contain none of:<{"two"=2, "three"=3}> but was:<{"one"=1, "two"=2}>
| elements not expected:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//region
//region containsAll
@Test fun containsAll_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsAll("two" to 2, "one" to 1)
}
@Test fun containsAll_extra_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2, "three" to 3)).containsAll("one" to 1, "two" to 2)
}
@Test fun containsAll_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsAll("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain all:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_nullable_values_fails() {
val error = assertFails {
assertThat(mapOf<String, Any?>()).containsAll("key" to null)
}
assertEquals(
"""expected to contain all:<{"key"=null}> but was:<{}>
| elements not found:<{"key"=null}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_some_elements_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1)).containsAll("one" to 1, "two" to 2)
}
assertEquals(
"""expected to contain all:<{"one"=1, "two"=2}> but was:<{"one"=1}>
| elements not found:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//endregion
//region containsOnly
@Test fun containsOnly_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("two" to 2, "one" to 1)
}
@Test fun containsOnly_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsOnly("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain only:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
| extra elements found:<{"one"=2, "two"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_missing_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("three" to 3)
}
assertEquals(
"""expected to contain only:<{"three"=3}> but was:<{"one"=1, "two"=2}>
| elements not found:<{"three"=3}>
| extra elements found:<{"one"=1, "two"=2}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_extra_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("one" to 1)
}
assertEquals(
"""expected to contain only:<{"one"=1}> but was:<{"one"=1, "two"=2}>
| extra elements found:<{"two"=2}>
""".trimMargin(), error.message
)
}
//endregion
//region isEmpty
@Test fun isEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isEmpty()
}
@Test fun isEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isEmpty()
}
assertEquals("expected to be empty but was:<{null=null}>", error.message)
}
//endregion
//region isNotEmpty
@Test fun isNotEmpty_non_empty_passes() {
assertThat(mapOf<Any?, Any?>(null to null)).isNotEmpty()
}
@Test fun isNotEmpty_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>()).isNotEmpty()
}
assertEquals("expected to not be empty", error.message)
}
//endregion
//region isNullOrEmpty
@Test fun isNullOrEmpty_null_passes() {
assertThat(null as Map<Any?, Any?>?).isNullOrEmpty()
}
@Test fun isNullOrEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isNullOrEmpty()
}
@Test fun isNullOrEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isNullOrEmpty()
}
assertEquals("expected to be null or empty but was:<{null=null}>", error.message)
}
//endregion
//region hasSize
@Test fun hasSize_correct_size_passes() {
assertThat(emptyMap<String, Int>()).hasSize(0)
}
@Test fun hasSize_wrong_size_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSize(1)
}
assertEquals("expected [size]:<[1]> but was:<[0]> ({})", error.message)
}
//endregion
//region hasSameSizeAs
@Test fun hasSameSizeAs_equal_sizes_passes() {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(emptyMap<String, Int>())
}
@Test fun hasSameSizeAs_non_equal_sizes_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(mapOf("one" to 1))
}
assertEquals("expected to have same size as:<{\"one\"=1}> (1) but was size:(0)", error.message)
}
//endregion
//region key
@Test fun index_successful_assertion_passes() {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(1)
}
@Test fun index_unsuccessful_assertion_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(2)
}
assertEquals("expected [subject[\"one\"]]:<[2]> but was:<[1]> ({\"one\"=1, \"two\"=2})", error.message)
}
@Test fun index_missing_key_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("wrong").isEqualTo(1)
}
assertEquals("expected [subject] to have key:<\"wrong\">", error.message)
}
//endregion
}
| assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt | 1995895183 |
package test.assertk
import assertk.assertAll
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.fail
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFalse
class AssertTest {
//region transform
@Test fun transform_that_throws_always_fails_assertion() {
val error = assertFails {
assertAll {
assertThat(0).transform { fail("error") }.isEqualTo(0)
}
}
assertEquals("error", error.message)
}
@Test fun transform_does_not_run_after_throws() {
var run = false
val error = assertFails {
assertAll {
assertThat(0).transform { fail("error") }.transform { run = true }.isEqualTo(0)
}
}
assertEquals("error", error.message)
assertFalse(run)
}
@Test fun transform_rethrows_thrown_exception() {
val error = assertFails {
assertAll {
assertThat(0).transform { throw MyException("error") }.isEqualTo(0)
}
}
assertEquals(MyException::class, error::class)
assertEquals("error", error.message)
}
//endregion
//region given
@Test fun given_rethrows_thrown_exception() {
val error = assertFails {
assertAll {
assertThat(0).given { throw MyException("error") }
}
}
assertEquals(MyException::class, error::class)
assertEquals("error", error.message)
}
//endregion
//region assertThat
@Test fun assertThat_inherits_name_of_parent_assertion_by_default() {
val error = assertFails {
assertThat(0, name = "test").assertThat(1).isEqualTo(2)
}
assertEquals("expected [test]:<[2]> but was:<[1]> (0)", error.message)
}
@Test fun assertThat_failing_transformed_assert_shows_original_by_displayActual_lambda() {
val error = assertFails {
assertThat(0, name = "test", displayActual = { "Number:${it}" })
.assertThat(1).isEqualTo(2)
}
assertEquals("expected [test]:<[2]> but was:<[1]> (Number:0)", error.message)
}
@Test fun assertThat_on_failing_assert_is_ignored() {
val error = assertFails {
assertAll {
assertThat(0, name = "test").transform { fail("error") }.assertThat(1, name = "ignored").isEqualTo(2)
}
}
assertEquals("error", error.message)
}
//endregion
private class MyException(message: String) : Exception(message)
} | assertk/src/commonTest/kotlin/test/assertk/AssertTest.kt | 1905445981 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.permissions.bukkit.event.group
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import com.rpkit.permissions.bukkit.group.RPKGroup
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitGroupUnassignProfileEvent(
override val group: RPKGroup,
override val profile: RPKProfile,
isAsync: Boolean
) : RPKBukkitEvent(isAsync), RPKGroupUnassignProfileEvent, Cancellable {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-permissions-lib-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/event/group/RPKBukkitGroupUnassignProfileEvent.kt | 3524945525 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.model
data class ModelCodegenConfigAndroid(val javaPackageName: String?)
| packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfigAndroid.kt | 1921710925 |
package com.fsck.k9.storage.messages
import android.database.Cursor
import androidx.core.database.getLongOrNull
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.helper.map
import com.fsck.k9.mail.FolderClass
import com.fsck.k9.mail.FolderType
import com.fsck.k9.mailstore.FolderDetailsAccessor
import com.fsck.k9.mailstore.FolderMapper
import com.fsck.k9.mailstore.FolderNotFoundException
import com.fsck.k9.mailstore.LockableDatabase
import com.fsck.k9.mailstore.MoreMessages
import com.fsck.k9.mailstore.toFolderType
internal class RetrieveFolderOperations(private val lockableDatabase: LockableDatabase) {
fun <T> getFolder(folderId: Long, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "id = ?",
selectionArguments = arrayOf(folderId.toString()),
mapper = mapper
)
}
fun <T> getFolder(folderServerId: String, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "server_id = ?",
selectionArguments = arrayOf(folderServerId),
mapper = mapper
)
}
private fun <T> getFolder(selection: String, selectionArguments: Array<String>, mapper: FolderMapper<T>): T? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
FOLDER_COLUMNS,
selection,
selectionArguments,
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) {
val cursorFolderAccessor = CursorFolderAccessor(cursor)
mapper.map(cursorFolderAccessor)
} else {
null
}
}
}
}
fun <T> getFolders(excludeLocalOnly: Boolean = false, mapper: FolderMapper<T>): List<T> {
val selection = if (excludeLocalOnly) "local_only = 0" else null
return lockableDatabase.execute(false) { db ->
db.query("folders", FOLDER_COLUMNS, selection, null, null, null, "id").use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
fun <T> getDisplayFolders(displayMode: FolderMode, outboxFolderId: Long?, mapper: FolderMapper<T>): List<T> {
return lockableDatabase.execute(false) { db ->
val displayModeSelection = getDisplayModeSelection(displayMode)
val outboxFolderIdOrZero = outboxFolderId ?: 0
val query =
"""
SELECT ${FOLDER_COLUMNS.joinToString()}, (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND (messages.read = 0 OR folders.id = ?)
), (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND messages.flagged = 1
)
FROM folders
$displayModeSelection
"""
db.rawQuery(query, arrayOf(outboxFolderIdOrZero.toString())).use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
private fun getDisplayModeSelection(displayMode: FolderMode): String {
return when (displayMode) {
FolderMode.ALL -> {
""
}
FolderMode.FIRST_CLASS -> {
"WHERE display_class = '${FolderClass.FIRST_CLASS.name}'"
}
FolderMode.FIRST_AND_SECOND_CLASS -> {
"WHERE display_class IN ('${FolderClass.FIRST_CLASS.name}', '${FolderClass.SECOND_CLASS.name}')"
}
FolderMode.NOT_SECOND_CLASS -> {
"WHERE display_class != '${FolderClass.SECOND_CLASS.name}'"
}
FolderMode.NONE -> {
throw AssertionError("Invalid folder display mode: $displayMode")
}
}
}
fun getFolderId(folderServerId: String): Long? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("id"),
"server_id = ?",
arrayOf(folderServerId),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getLong(0) else null
}
}
}
fun getFolderServerId(folderId: Long): String? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("server_id"),
"id = ?",
arrayOf(folderId.toString()),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
}
}
}
fun getMessageCount(folderId: Long): Int {
return lockableDatabase.execute(false) { db ->
db.rawQuery(
"SELECT COUNT(id) FROM messages WHERE empty = 0 AND deleted = 0 AND folder_id = ?",
arrayOf(folderId.toString())
).use { cursor ->
if (cursor.moveToFirst()) cursor.getInt(0) else 0
}
}
}
fun hasMoreMessages(folderId: Long): MoreMessages {
return getFolder(folderId) { it.moreMessages } ?: throw FolderNotFoundException(folderId)
}
}
private class CursorFolderAccessor(val cursor: Cursor) : FolderDetailsAccessor {
override val id: Long
get() = cursor.getLong(0)
override val name: String
get() = cursor.getString(1)
override val type: FolderType
get() = cursor.getString(2).toFolderType()
override val serverId: String?
get() = cursor.getString(3)
override val isLocalOnly: Boolean
get() = cursor.getInt(4) == 1
override val isInTopGroup: Boolean
get() = cursor.getInt(5) == 1
override val isIntegrate: Boolean
get() = cursor.getInt(6) == 1
override val syncClass: FolderClass
get() = cursor.getString(7).toFolderClass(FolderClass.INHERITED)
override val displayClass: FolderClass
get() = cursor.getString(8).toFolderClass(FolderClass.NO_CLASS)
override val notifyClass: FolderClass
get() = cursor.getString(9).toFolderClass(FolderClass.INHERITED)
override val pushClass: FolderClass
get() = cursor.getString(10).toFolderClass(FolderClass.SECOND_CLASS)
override val visibleLimit: Int
get() = cursor.getInt(11)
override val moreMessages: MoreMessages
get() = MoreMessages.fromDatabaseName(cursor.getString(12))
override val lastChecked: Long?
get() = cursor.getLongOrNull(13)
override val unreadMessageCount: Int
get() = cursor.getInt(14)
override val starredMessageCount: Int
get() = cursor.getInt(15)
override fun serverIdOrThrow(): String {
return serverId ?: error("No server ID found for folder '$name' ($id)")
}
}
private fun String?.toFolderClass(defaultValue: FolderClass): FolderClass {
return if (this == null) defaultValue else FolderClass.valueOf(this)
}
private val FOLDER_COLUMNS = arrayOf(
"id",
"name",
"type",
"server_id",
"local_only",
"top_group",
"integrate",
"poll_class",
"display_class",
"notify_class",
"push_class",
"visible_limit",
"more_messages",
"last_updated"
)
| app/storage/src/main/java/com/fsck/k9/storage/messages/RetrieveFolderOperations.kt | 3583381349 |
package org.squarecell.wow.addon_support.builders
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.ide.util.projectWizard.ModuleBuilderListener
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFileManager
import org.squarecell.wow.addon_support.config.MainFile
import org.squarecell.wow.addon_support.config.ProjectSettingsKeys
import org.squarecell.wow.addon_support.modules.AddOnModuleType
import org.squarecell.wow.addon_support.wizard_steps.AddOnWizardStep
import java.io.File
class AddOnModuleBuilder : ModuleBuilder(), ModuleBuilderListener {
init {
addListener(this)
}
override fun moduleCreated(module: Module) {
val tocFilePath = contentEntryPath + File.separator + module.name + ".toc"
var mainFilePath = contentEntryPath + File.separator + PropertiesComponent
.getInstance().getValue(ProjectSettingsKeys.AddOnMainFileName)
if (!mainFilePath.endsWith(".lua"))
mainFilePath += ".lua"
File(tocFilePath).writeText(PropertiesComponent.getInstance().getValue("tocFile")!!)
val file = File(mainFilePath)
file.createNewFile()
file.appendText(MainFile.initAce3AddOn)
file.appendText(MainFile.defaultInitFunc)
file.appendText(MainFile.defaultLoadFunc)
file.appendText(MainFile.defaultUnloadFunc)
}
override fun setupRootModel(modifiableRootModel: ModifiableRootModel) {
val path = contentEntryPath + File.separator + "Libs"
File(path).mkdirs()
val sourceRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)!!
val jarUtil = JarFileSystem.getInstance()
val desc = PluginManager.getPlugin(PluginId.getId("org.squarecell.wow.addon_support"))!!
val pluginPath = desc.path.absolutePath
val realPath = VfsUtil.pathToUrl(pluginPath)
val pluginVD = VirtualFileManager.getInstance().findFileByUrl(realPath)!!
val file = jarUtil.refreshAndFindFileByPath(pluginVD.path + "!/Wow_sdk")!!
// val classesDir = pluginVD.findChild("classes")?: pluginVD
// val deps = classesDir.findChild("Wow_sdk")!!
file.children.forEach {
VfsUtil.copy(this, it, sourceRoot)
}
super.doAddContentEntry(modifiableRootModel)?.addSourceFolder(sourceRoot, false)
}
override fun getModuleType(): ModuleType<*> {
return AddOnModuleType.instance
}
override fun getCustomOptionsStep(context: WizardContext,
parentDisposable: Disposable?): ModuleWizardStep? {
return AddOnWizardStep()
}
}
| src/org/squarecell/wow/addon_support/builders/AddOnModuleBuilder.kt | 1170516204 |
/*
* 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.summit.ast
import com.google.common.truth.Truth.assertThat
import com.google.summit.ast.Node
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class SourceLocationTest {
@Test
fun spanOf_chooses_nonNullValues() {
val unknown = SourceLocation.UNKNOWN
val withLinesOnly = SourceLocation(1, null, 3, null)
val withLinesAndColumns = SourceLocation(withLinesOnly.startLine, 10, withLinesOnly.endLine, 10)
assertThat(spanOf(unknown, unknown)).isEqualTo(unknown)
assertThat(spanOf(withLinesOnly, unknown)).isEqualTo(withLinesOnly)
assertThat(spanOf(unknown, withLinesOnly)).isEqualTo(withLinesOnly)
assertThat(spanOf(withLinesOnly, withLinesAndColumns)).isEqualTo(withLinesAndColumns)
assertThat(spanOf(withLinesAndColumns, withLinesOnly)).isEqualTo(withLinesAndColumns)
}
@Test
fun spanOf_returns_newRange() {
val lower = SourceLocation(1, 1, 2, 2)
val upper = SourceLocation(2, 2, 3, 3)
val expected = SourceLocation(lower.startLine, lower.startColumn,
upper.endLine, upper.endColumn)
assertThat(spanOf(lower, upper)).isEqualTo(expected)
assertThat(spanOf(upper, lower)).isEqualTo(expected)
}
@Test
fun spanOf_is_idempotent() {
val loc = SourceLocation(1, 3, 4, 2)
assertThat(spanOf(loc)).isEqualTo(loc)
assertThat(spanOf(loc, loc, loc)).isEqualTo(loc)
assertThat(spanOf(loc, spanOf(loc, loc))).isEqualTo(loc)
}
@Test
fun spanOf_ranks_lineOverColumn() {
val widerLines = SourceLocation(1, 6, 10, 5)
val widerColumns = SourceLocation(5, 1, 6, 10)
assertThat(spanOf(widerLines, widerColumns)).isEqualTo(widerLines)
assertThat(spanOf(widerColumns, widerLines)).isEqualTo(widerLines)
}
}
| src/main/javatests/com/google/summit/ast/SourceLocationTest.kt | 3711422681 |
package com.fuyoul.sanwenseller.ui.money
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.csl.refresh.SmartRefreshLayout
import com.csl.refresh.api.RefreshLayout
import com.csl.refresh.listener.OnRefreshLoadmoreListener
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.reqhttp.ReqInCome
import com.fuyoul.sanwenseller.bean.reshttp.ResMoneyItem
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.Data
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.listener.AppBarStateChangeListener
import com.fuyoul.sanwenseller.structure.model.MoneyInComeM
import com.fuyoul.sanwenseller.structure.presenter.MoneyInComeP
import com.fuyoul.sanwenseller.structure.view.MoneyInComeV
import com.fuyoul.sanwenseller.utils.GlideUtils
import com.fuyoul.sanwenseller.utils.TimeDateUtils
import com.netease.nim.uikit.NimUIKit
import com.netease.nim.uikit.StatusBarUtils
import kotlinx.android.synthetic.main.moneyinfolayout.*
import kotlinx.android.synthetic.main.waitforsettlementlayout.*
import java.util.*
/**
* @author: chen
* @CreatDate: 2017\10\31 0031
* @Desc:待结算
*/
class SettlementTypeActivity : BaseActivity<MoneyInComeM, MoneyInComeV, MoneyInComeP>() {
companion object {
fun start(context: Context, isHistoryType: Boolean, year: String?, month: String?) {
val intent = Intent(context, SettlementTypeActivity::class.java)
intent.putExtra("isHistoryType", isHistoryType)
if (isHistoryType) {
intent.putExtra("year", year)
intent.putExtra("month", month)
}
context.startActivity(intent)
}
}
private val req = ReqInCome()
private var index = 0
private var defaultState = AppBarStateChangeListener.State.EXPANDED//默认是展开状态
private var adapter: ThisAdapter? = null
override fun setLayoutRes(): Int = R.layout.waitforsettlementlayout
override fun initData(savedInstanceState: Bundle?) {
StatusBarUtils.setTranslucentForCoordinatorLayout(this, 30)
setSupportActionBar(toolbar)
//如果是结算历史
if (intent.getBooleanExtra("isHistoryType", false)) {
req.ordersDate = "${intent.getStringExtra("year")}${intent.getStringExtra("month")}"
}
getPresenter().viewImpl?.initAdapter(this)
getPresenter().getData(this, req, true)
}
override fun setListener() {
waitForSettlementRefreshLayout.setOnRefreshLoadmoreListener(object : OnRefreshLoadmoreListener {
override fun onRefresh(refreshlayout: RefreshLayout?) {
index = 0
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, true)
}
override fun onLoadmore(refreshlayout: RefreshLayout?) {
index++
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, false)
}
})
appBarLayoutOfWaitSettlement.addOnOffsetChangedListener(listener)
toolbar.setNavigationOnClickListener {
finish()
}
}
override fun onResume() {
super.onResume()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun onPause() {
super.onPause()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun getPresenter(): MoneyInComeP = MoneyInComeP(initViewImpl())
override fun initViewImpl(): MoneyInComeV = object : MoneyInComeV() {
override fun getAdapter(): BaseAdapter {
if (adapter == null) {
adapter = ThisAdapter()
}
return adapter!!
}
override fun initAdapter(context: Context) {
val manager = LinearLayoutManager(this@SettlementTypeActivity)
manager.orientation = LinearLayoutManager.VERTICAL
waitForSettlementDataList.layoutManager = manager
waitForSettlementDataList.adapter = getAdapter()
}
override fun setViewInfo(data: ResMoneyItem) {
priceCount.text = "${data.countPrice}"
orderCount.text = "${data.countOrders}"
}
}
override fun initTopBar(): TopBarOption = TopBarOption()
inner class ThisAdapter : BaseAdapter(this) {
override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) {
val item = datas[position] as ResMoneyItem.IncomeListBean
GlideUtils.loadNormalImg(this@SettlementTypeActivity, JSON.parseArray(item.imgs).getJSONObject(0).getString("url"), holder.itemView.findViewById(R.id.orderItemIcon))
GlideUtils.loadNormalImg(this@SettlementTypeActivity, item.avatar, holder.itemView.findViewById(R.id.orderItemHead))
holder.itemView.findViewById<TextView>(R.id.orderItemPrice).text = "¥${item.totalPrice}"
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).text = "${item.name}"
holder.itemView.findViewById<TextView>(R.id.orderItemDes).text = "${item.introduce}"
holder.itemView.findViewById<TextView>(R.id.orderItemTime).text = "${TimeDateUtils.stampToDate(item.ordersDate)}"
holder.itemView.findViewById<TextView>(R.id.orderItemNick).text = "${item.nickname}"
var typeIcon: Drawable? = null
if (item.type == Data.QUICKTESTBABY) {
typeIcon = resources.getDrawable(R.mipmap.icon_quicktesttype)
typeIcon.setBounds(0, 0, typeIcon.minimumWidth, typeIcon.minimumHeight)
}
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).setCompoundDrawables(null, null, typeIcon, null)
val orderItemState = holder.itemView.findViewById<TextView>(R.id.orderItemState)
orderItemState.text = "交易完成"
val orderItemFuncLayout = holder.itemView.findViewById<LinearLayout>(R.id.orderItemFuncLayout)
orderItemFuncLayout.visibility = View.VISIBLE
val orderItemReleaseTime = holder.itemView.findViewById<LinearLayout>(R.id.orderItemReleaseTime)
orderItemReleaseTime.visibility = View.GONE
val orderItemFuncRight = holder.itemView.findViewById<TextView>(R.id.orderItem_Func_Right)
orderItemFuncRight.text = "联系买家"
orderItemFuncRight.setOnClickListener {
NimUIKit.startP2PSession(this@SettlementTypeActivity, "user_${item.user_info_id}")
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_MONEY, R.layout.orderitem))
}
override fun onItemClicked(view: View, position: Int) {
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getSmartRefreshLayout(): SmartRefreshLayout = waitForSettlementRefreshLayout
override fun getRecyclerView(): RecyclerView = waitForSettlementDataList
}
private val listener = object : AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout?, state: State) {
when (state) {
State.EXPANDED -> {
//展开状态
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
State.COLLAPSED -> {
//折叠状态
toolbarOfMoneyInfo.setNavigationIcon(R.mipmap.ic_yb_top_back)
StatusBarUtils.StatusBarLightMode(this@SettlementTypeActivity, R.color.color_white)
toolbar.setBackgroundResource(R.drawable.back_titlebar)
}
else -> {
//中间状态
//如果之前是折叠状态,则表示在向下滑动
if (defaultState == State.COLLAPSED) {
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
}
}
defaultState = state
}
}
} | app/src/main/java/com/fuyoul/sanwenseller/ui/money/SettlementTypeActivity.kt | 915715459 |
package fr.free.nrw.commons.actions
import io.reactivex.Observable
import io.reactivex.Single
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.edit.Edit
import org.wikipedia.wikidata.Entities
import retrofit2.http.*
/**
* This interface facilitates wiki commons page editing services to the Networking module
* which provides all network related services used by the app.
*
* This interface posts a form encoded request to the wikimedia API
* with editing action as argument to edit a particular page
*/
interface PageEditInterface {
/**
* This method posts such that the Content which the page
* has will be completely replaced by the value being passed to the
* "text" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param text Holds the page content
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("text") text: String,
// NOTE: This csrf shold always be sent as the last field of form data
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be appended with the value being passed to the
* "appendText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param appendText Text to add to the end of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postAppendEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("appendtext") appendText: String,
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be prepended with the value being passed to the
* "prependText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param prependText Text to add to the beginning of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postPrependEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("prependtext") prependText: String,
@Field("token") token: String
): Observable<Edit>
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=wbsetlabel&format=json&site=commonswiki&formatversion=2")
fun postCaptions(
@Field("summary") summary: String,
@Field("title") title: String,
@Field("language") language: String,
@Field("value") value: String,
@Field("token") token: String
): Observable<Entities>
/**
* Get wiki text for provided file names
* @param titles : Name of the file
* @return Single<MwQueryResult>
*/
@GET(
Service.MW_API_PREFIX +
"action=query&prop=revisions&rvprop=content|timestamp&rvlimit=1&converttitles="
)
fun getWikiText(
@Query("titles") title: String
): Single<MwQueryResponse?>
} | app/src/main/java/fr/free/nrw/commons/actions/PageEditInterface.kt | 157903978 |
package com.github.kittinunf.reactiveandroid.support.v4.widget
import android.support.v4.widget.SwipeRefreshLayout
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Property
//================================================================================
val SwipeRefreshLayout.rx_refreshing: MutableProperty<Boolean>
get() {
val getter = { isRefreshing }
val setter: (Boolean) -> Unit = { isRefreshing = it }
return createMainThreadMutableProperty(getter, setter)
}
val SwipeRefreshLayout.rx_nestedScrollingEnabled: MutableProperty<Boolean>
get() {
val getter = { isNestedScrollingEnabled }
val setter: (Boolean) -> Unit = { isNestedScrollingEnabled = it }
return createMainThreadMutableProperty(getter, setter)
}
| reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/SwipeRefreshLayoutProperty.kt | 3481789443 |
/**
* Checks chat for user written messages and responds to specific queries
* Created by zingmars on 04.10.2015.
*/
package BotPlugins
import Containers.PluginBufferItem
public class UserCommands : BasePlugin()
{
override fun pubInit() :Boolean
{
return true
}
override fun connector(buffer : PluginBufferItem) :Boolean
{
var message = buffer.message.split(" ")
when(message[0].toLowerCase()) {
"!ping" -> controller?.AddToBoxBuffer(buffer.userName + ": PONG!")
"!nextstream" -> controller?.AddToBoxBuffer(buffer.userName + ": Soon")
//TODO: have some sort of database where plugins can register their commands so this command can be automated.
"!help" -> {
controller?.AddToBoxBuffer("For more information please see https://github.com/zingmars/Cbox-bot. For feature requests ask zingmars.")
controller?.AddToBoxBuffer("!about - About this bot; !lastseen <username> - Output the date of user's last message; !ping - check if I'm alive; !help - display this; !time - time related commands (try help as a parameter)")
controller?.AddToBoxBuffer("!laststream <username> - Get when an user has last streamed (try !laststream zingmars); !nextstream - OTG's next stream time")
controller?.AddToBoxBuffer("Available commands:")
}
"!about" -> {
controller?.AddToBoxBuffer("Hi! My name is " + handler?.username + " and I'm a bot for cbox.ws written in Kotlin. Check me out at: https://github.com/zingmars/Cbox-bot")
}
}
return true
}
} | src/BotPlugins/UserCommands.kt | 1259019030 |
package org.rust.ide.typing
import org.intellij.lang.annotations.Language
class RustEnterInStringLiteralHandlerTest : RustTypingTestCaseBase() {
override val dataPath = "org/rust/ide/typing/string/fixtures"
fun testSimple() = doTest("""
fn main() {
let lit = "Hello, /*caret*/World";
println!("{}", lit);
}
""", """
fn main() {
let lit = "Hello, \
/*caret*/World";
println!("{}", lit);
}
""")
fun testMultilineText() = doTest("""
fn main() {
let lit = "\
Multiline text
last/*caret*/ line";
}
""", """
fn main() {
let lit = "\
Multiline text
last
/*caret*/line";
}
""")
fun testBeforeOpening() = doTest("""
fn main() {
let lit =/*caret*/"Hello, World";
}
""", """
fn main() {
let lit =
/*caret*/"Hello, World";
}
""")
fun testAfterOpening() = doTest("""
fn main() {
"/*caret*/Hello, World";
}
""", """
fn main() {
"\
/*caret*/Hello, World";
}
""")
fun testInsideOpening() = doTest("""
fn main() {
b/*caret*/"Hello, World";
}
""", """
fn main() {
b
/*caret*/"Hello, World";
}
""")
fun testBeforeClosing() = doTest("""
fn main() {
"Hello, World/*caret*/";
}
""", """
fn main() {
"Hello, World\
/*caret*/";
}
""")
fun testAfterClosing() = doTest("""
fn main() {
"Hello, World"/*caret*/;
}
""", """
fn main() {
"Hello, World"
/*caret*/;
}
""")
fun testRawLiteral() = doTest("""
fn main() {
r"Hello,/*caret*/ World";
}
""", """
fn main() {
r"Hello,
/*caret*/ World";
}
""")
fun testBeforeEscape() = doTest("""
fn main() {
"foo/*caret*/\n"
}
""", """
fn main() {
"foo\
/*caret*/\n"
}
""")
fun testAfterEscape() = doTest("""
fn main() {
"foo\n/*caret*/bar"
}
""", """
fn main() {
"foo\n\
/*caret*/bar"
}
""")
fun testInsideEscape() = doTest("""
fn main() {
"foo\u{00/*caret*/00}"
}
""", """
fn main() {
"foo\u{00
/*caret*/00}"
}
""")
fun testInsideEscapeAfterSlash() = doTest("""
fn main() {
"foo\/*caret*/u{0000}"
}
""", """
fn main() {
"foo\
/*caret*/u{0000}"
}
""")
fun testBetweenQuoteEscape() = doTest("""
fn main() {
"/*caret*/\n"
}
""", """
fn main() {
"\
/*caret*/\n"
}
""")
fun testBetweenEscapeQuote() = doTest("""
fn main() {
"foo\n/*caret*/"
}
""", """
fn main() {
"foo\n\
/*caret*/"
}
""")
fun testIncomplete() = doTest("""
fn main() {
"foo/*caret*/
""", """
fn main() {
"foo
/*caret*/
""")
fun testIncompleteEscape() = doTest("""
fn main() {
"foo\n/*caret*/
""", """
fn main() {
"foo\n\
/*caret*/
""")
fun testRawIncomplete() = doTest("""
fn main() {
r##"foo/*caret*/
""", """
fn main() {
r##"foo
/*caret*/
""")
fun doTest(@Language("Rust") before: String, @Language("Rust") after: String) {
InlineFile(before).withCaret()
myFixture.type('\n')
myFixture.checkResult(replaceCaretMarker(after))
}
}
| src/test/kotlin/org/rust/ide/typing/RustEnterInStringLiteralHandlerTest.kt | 2154142024 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.windowmanagersample.embedding
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.example.windowmanagersample.R
open class SplitActivityD : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findViewById<View>(R.id.root_split_activity_layout)
.setBackgroundColor(Color.parseColor("#eeeeee"))
}
}
| WindowManager/app/src/main/java/com/example/windowmanagersample/embedding/SplitActivityD.kt | 1653253238 |
package org.luxons.sevenwonders.engine.data.definitions
import org.luxons.sevenwonders.engine.cards.Requirements
import org.luxons.sevenwonders.engine.wonders.Wonder
import org.luxons.sevenwonders.engine.wonders.WonderStage
import org.luxons.sevenwonders.model.resources.ResourceType
import org.luxons.sevenwonders.model.wonders.WonderName
import org.luxons.sevenwonders.model.wonders.WonderSide
internal class WonderDefinition(
val name: WonderName,
val sides: Map<WonderSide, WonderSideDefinition>,
) {
fun create(wonderSide: WonderSide): Wonder = sides[wonderSide]!!.createWonder(name)
}
internal class WonderSideDefinition(
private val initialResource: ResourceType,
private val stages: List<WonderStageDefinition>,
val image: String,
) {
fun createWonder(name: String): Wonder = Wonder(name, initialResource, stages.map { it.create() }, image)
}
internal class WonderStageDefinition(
private val requirements: Requirements,
private val effects: EffectsDefinition,
) {
fun create(): WonderStage = WonderStage(requirements, effects.create())
}
| sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/data/definitions/WonderDefinition.kt | 535388536 |
package org.rust.lang.core.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.lang.core.psi.RustExternCrateItemElement
import org.rust.lang.core.psi.impl.RustPsiImplUtil
import org.rust.lang.core.psi.impl.RustStubbedNamedElementImpl
import org.rust.lang.core.resolve.ref.RustExternCrateReferenceImpl
import org.rust.lang.core.resolve.ref.RustReference
import org.rust.lang.core.stubs.RustExternCrateItemElementStub
abstract class RustExternCrateItemImplMixin : RustStubbedNamedElementImpl<RustExternCrateItemElementStub>,
RustExternCrateItemElement {
constructor(node: ASTNode) : super(node)
constructor(stub: RustExternCrateItemElementStub, elementType: IStubElementType<*, *>) : super(stub, elementType)
override fun getReference(): RustReference = RustExternCrateReferenceImpl(this)
override val referenceNameElement: PsiElement get() = identifier
override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub)
}
| src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustExternCrateItemImplMixin.kt | 4000963059 |
package net.perfectdreams.loritta.serializable
import kotlinx.serialization.Serializable
@Serializable
class CustomCommand(
val label: String,
val codeType: CustomCommandCodeType,
val code: String
) | loritta-serializable-commons/src/commonMain/kotlin/net/perfectdreams/loritta/serializable/CustomCommand.kt | 2127709203 |
package com.jaynewstrom.concrete
import android.content.Context
import android.content.ContextWrapper
import android.view.LayoutInflater
internal class ConcreteWallContext<C>(
baseContext: Context,
private val wall: ConcreteWall<C>
) : ContextWrapper(baseContext) {
private var inflater: LayoutInflater? = null
override fun getSystemService(name: String): Any? {
if (Concrete.isService(name)) {
return wall
}
if (Context.LAYOUT_INFLATER_SERVICE == name) {
if (inflater == null) {
inflater = LayoutInflater.from(baseContext).cloneInContext(this)
}
return inflater
}
return super.getSystemService(name)
}
}
| concrete/src/main/java/com/jaynewstrom/concrete/ConcreteWallContext.kt | 230516060 |
package ir.iais.utilities.javautils.utils
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.annotation.JsonFormat.Shape
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import ir.iais.utilities.javautils.enums.IOrdinal
/** Created by mgh on 10/15/16. */
@JsonFormat(shape = Shape.OBJECT)
@JsonIgnoreProperties("name", "ordinal", allowGetters = true)
enum class InsuranceType constructor(val desc: String, val value: Boolean?) : IOrdinal {
FullTime("تمام وقت", true),
hourly("بر حسب حضور", true),
None("ندارد", false)
}
| src/test/java/ir/iais/utilities/javautils/utils/InsuranceType.kt | 2016985467 |
package nuclearbot.gui.components.chat
import java.util.*
import javax.swing.AbstractListModel
import javax.swing.JList
/*
* Copyright (C) 2017 NuclearCoder
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Custom JList that uses a custom model which only keeps the last lines.<br></br>
* <br></br>
* NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br>
* @author NuclearCoder (contact on the GitHub repo)
*/
class LimitedStringList(capacity: Int = 50) : JList<String>() {
private val listModel = LimitedStringList.Model(capacity).also { model = it }
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
listModel.add(text)
}
/**
* The ListModel used by the LimitedStringList class
*/
class Model(private val capacity: Int) : AbstractListModel<String>() {
private val arrayList = ArrayList<String>(capacity)
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
val index0: Int
val index1: Int
if (arrayList.size == capacity) {
index0 = 0
index1 = capacity - 1
arrayList.removeAt(0)
} else {
index1 = arrayList.size
index0 = index1
}
arrayList.add(text)
fireContentsChanged(this, index0, index1)
}
override fun getSize(): Int {
return arrayList.size
}
override fun getElementAt(index: Int): String {
return arrayList[index]
}
}
}
| src/nuclearbot/gui/components/chat/LimitedStringList.kt | 2193133649 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.model
open class Bus(val id: Int,
val position: Position,
val heading: Int,
val destination: String)
| android-app/src/main/kotlin/fr/cph/chicago/core/model/Bus.kt | 2928489330 |
package fr.free.nrw.commons.customselector.helper
import android.net.Uri
import fr.free.nrw.commons.customselector.model.Folder
import fr.free.nrw.commons.customselector.model.Image
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
/**
* Custom Selector Image Helper Test
*/
internal class ImageHelperTest {
var uri: Uri = mock(Uri::class.java)
private val folderImage1 = Image(1, "image1", uri, "abc/abc", 1, "bucket1")
private val folderImage2 = Image(2, "image1", uri, "xyz/xyz", 2, "bucket2")
private val mockImageList = ArrayList<Image>(listOf(folderImage1, folderImage2))
private val folderImageList1 = ArrayList<Image>(listOf(folderImage1))
private val folderImageList2 = ArrayList<Image>(listOf(folderImage2))
/**
* Test folder list from images.
*/
@Test
fun folderListFromImages() {
val folderList = ArrayList<Folder>(listOf(Folder(1, "bucket1", folderImageList1), Folder(2, "bucket2", folderImageList2)))
assertEquals(folderList, ImageHelper.folderListFromImages(mockImageList))
}
/**
* Test filter images.
*/
@Test
fun filterImages() {
assertEquals(folderImageList1, ImageHelper.filterImages(mockImageList, 1))
}
/**
* Test get index from image list.
*/
@Test
fun getIndex() {
assertEquals(1,ImageHelper.getIndex(mockImageList, folderImage2))
}
/**
* Test get index list.
*/
@Test
fun getIndexList() {
assertEquals(ArrayList<Int>(listOf(0)), ImageHelper.getIndexList(mockImageList, folderImageList2))
}
} | app/src/test/kotlin/fr/free/nrw/commons/customselector/helper/ImageHelperTest.kt | 1078509340 |
package com.christian.nav.me
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.christian.R
import com.christian.common.GOSPEL_EN
import com.christian.common.GOSPEL_ZH
import com.christian.common.auth
import com.christian.common.data.Gospel
import com.christian.common.firestore
import com.christian.databinding.ItemChatBinding
import com.christian.databinding.ItemGospelBinding
import com.christian.nav.disciple.ChatItemView
import com.christian.nav.gospel.GospelItemView
import com.christian.nav.gospel.HidingGospelItemView
import com.christian.nav.home.VIEW_TYPE_CHAT
import com.christian.nav.home.VIEW_TYPE_GOSPEL
import com.christian.swipe.SwipeBackActivity
import com.christian.util.ChristianUtil
import com.christian.view.ItemDecoration
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.fragment_detail_me.view.*
import kotlinx.android.synthetic.main.fragment_nav_rv.view.*
import kotlinx.android.synthetic.main.activity_tb_immersive.*
class HidingGospelFragment: Fragment() {
var meDetailTabId: Int = -1
private lateinit var v: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
v = inflater.inflate(R.layout.fragment_detail_me, container, false)
initView()
return v
}
private lateinit var gospelAdapter: FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>
private lateinit var query: Query
var mPosition = -1
private fun initView() {
initRv()
v.me_detail_pb.isIndeterminate = true
v.fragment_nav_rv.setProgressBar(v.me_detail_pb)
}
private fun initRv() {
v.fragment_nav_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64)))
getMeFromSettingId()
if (::gospelAdapter.isInitialized) {gospelAdapter.startListening()
v.fragment_nav_rv.adapter = gospelAdapter} // 我的-门徒-喜欢 崩溃处理
}
override fun onDestroy() {
super.onDestroy()
if (::gospelAdapter.isInitialized) gospelAdapter.stopListening() // 我的-门徒-喜欢 崩溃处理
}
/**
* tabId = 0, settingId = 0, history gospels
* tabId = 0, settingId = 1, favorite gospels
* tabId = 0, settingId = 2, published gospels
*
*
* tabId = 1, settingId = 0, history disciples
* tabId = 1, settingId = 1, following disciples
* tabId = 1, settingId = 2, followed disciples
*/
private fun getMeFromSettingId() {
(requireActivity() as HidingGospelActivity).tb_immersive_toolbar.title =
getString(R.string.hidden_gospel)
query = if (meDetailTabId == 0) {
firestore.collection(GOSPEL_EN).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
} else {
firestore.collection(GOSPEL_ZH).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
}
val options = FirestoreRecyclerOptions.Builder<Gospel>()
// .setLifecycleOwner(this@NavFragment)
.setQuery(query, Gospel::class.java)
.build()
gospelAdapter = object : FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>(options) {
override fun getItemViewType(position: Int): Int {
return when {
getItem(position).title.isEmpty() -> {
VIEW_TYPE_CHAT
}
else -> {
VIEW_TYPE_GOSPEL
}
}
}
@NonNull
override fun onCreateViewHolder(@NonNull parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder {
when(viewType) {
0 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
1 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_chat, parent, false)
val binding = ItemChatBinding.bind(view)
return ChatItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
else -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
}
}
override fun onBindViewHolder(@NonNull holder: RecyclerView.ViewHolder,
position: Int,
@NonNull model: Gospel
) {
when {
model.title.isEmpty() -> {
applyViewHolderAnimation(holder as ChatItemView)
holder.bind(meDetailTabId, model)
}
else -> {
applyViewHolderAnimation(holder as HidingGospelItemView)
holder.bind(meDetailTabId, model)
}
}
}
override fun onDataChanged() {
super.onDataChanged()
v.me_detail_pb.visibility = View.GONE
v.me_detail_pb.isIndeterminate = false
if (itemCount == 0) {
} else {
v.fragment_nav_rv.scheduleLayoutAnimation()
}
}
override fun onError(e: FirebaseFirestoreException) {
super.onError(e)
Log.d("MeDetailFragment", e.toString())
}
}
v.fragment_nav_rv.adapter = gospelAdapter
}
fun applyViewHolderAnimation(holder: HidingGospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: GospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: ChatItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
} | app/src/main/java/com/christian/nav/me/HidingGospelFragment.kt | 2409808188 |
package com.bl_lia.kirakiratter.data.repository.datasource.auth
import io.reactivex.Single
import com.bl_lia.kirakiratter.domain.value_object.AccessToken
import com.bl_lia.kirakiratter.domain.value_object.AppCredentials
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface AuthService {
@FormUrlEncoded
@POST("oauth/token")
fun fetchOAuthToken(
@Field("client_id") clientId: String,
@Field("client_secret") clientSecret: String,
@Field("redirect_uri") redirectUri: String,
@Field("code") code: String,
@Field("grant_type") grantType: String
): Single<AccessToken>
@FormUrlEncoded
@POST("api/v1/apps")
fun authenticateApp(
@Field("client_name") clientName: String,
@Field("redirect_uris") redirectUri: String,
@Field("scopes") scopes: String,
@Field("website") website: String
): Single<AppCredentials>
} | app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/auth/AuthService.kt | 3141182615 |
package de.markhaehnel.rbtv.rocketbeanstv
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("de.markhaehnel.rbtv.rocketbeanstv", appContext.packageName)
}
}
| app/src/androidTest/java/de/markhaehnel/rbtv/rocketbeanstv/ExampleInstrumentedTest.kt | 1070440991 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import android.graphics.Rect
import android.view.View
import com.facebook.litho.testing.LegacyLithoViewRule
import com.facebook.litho.testing.testrunner.LithoTestRunner
import com.facebook.litho.widget.MountSpecLifecycleTester
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(LithoTestRunner::class)
class DynamicPropsExtensionTest {
@JvmField @Rule val lithoViewRule: LegacyLithoViewRule = LegacyLithoViewRule()
@Test
fun `when dynamic vale is set should override attribute set by MountSpec`() {
val c: ComponentContext = lithoViewRule.context
val root =
MountSpecLifecycleTester.create(c)
.intrinsicSize(Size(100, 100))
.lifecycleTracker(LifecycleTracker())
.defaultScale(0.5f)
.scaleX(DynamicValue(0.2f))
.scaleY(DynamicValue(0.2f))
.build()
lithoViewRule.render { root }
val content: View = lithoViewRule.lithoView.getChildAt(0)
assertThat(content.scaleX)
.describedAs("scale should be applied from the dynamic value")
.isEqualTo(0.2f)
// unmount everything
lithoViewRule.useComponentTree(null)
assertThat(content.scaleX)
.describedAs("scale should be restored to the initial value")
.isEqualTo(0.5f)
}
@Test
fun `when dynamic vale is set on LithoView should be unset when root is unmounted`() {
val c: ComponentContext = lithoViewRule.context
val root =
Column.create(c)
.alpha(DynamicValue(0.2f))
.child(
MountSpecLifecycleTester.create(c)
.intrinsicSize(Size(100, 100))
.lifecycleTracker(LifecycleTracker()))
.build()
lithoViewRule.render { root }
assertThat(lithoViewRule.lithoView.alpha)
.describedAs("alpha should be applied from the dynamic value")
.isEqualTo(0.2f)
lithoViewRule.componentTree.mountComponent(Rect(0, -10, 1080, -5), true)
assertThat(lithoViewRule.lithoView.alpha)
.describedAs("alpha should be restored to default value")
.isEqualTo(1f)
}
}
| litho-it/src/test/java/com/facebook/litho/DynamicPropsExtensionTest.kt | 1533390304 |
/*
* The MIT License (MIT)
*
* FXGL - JavaFX Game Library
*
* Copyright (c) 2015-2016 AlmasB (almaslvl@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almasb.fxglgames.outrun
import com.almasb.fxgl.entity.component.Component
import javafx.beans.property.SimpleDoubleProperty
import java.lang.Math.min
/**
*
*
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
class PlayerComponent : Component() {
private var speed = 0.0
private var dy = 0.0
val boost = SimpleDoubleProperty(100.0)
override fun onUpdate(tpf: Double) {
speed = tpf * 200
dy += tpf / 4;
if (entity.x < 80 || entity.rightX > 600 - 80) {
if (dy > 0.017) {
dy -= tpf
}
}
entity.y -= dy
boost.set(min(boost.get() + tpf * 5, 100.0))
}
fun getSpeed() = dy
fun up() {
entity.translateY(-speed)
}
fun down() {
entity.translateY(speed)
}
fun left() {
if (entity.x >= speed)
entity.translateX(-speed)
}
fun right() {
if (entity.rightX + speed <= 600)
entity.translateX(speed)
}
fun boost() {
if (boost.get() <= speed * 2)
return
boost.set(Math.max(boost.get() - speed / 2, 0.0))
entity.y -= speed
}
fun applyExtraBoost() {
dy += 10
}
fun removeExtraBoost() {
dy = Math.max(0.0, dy - 10)
}
fun reset() {
dy = 0.0
// val anim = fadeOutIn(entity.view, Duration.seconds(1.5))
// anim.animatedValue.interpolator = Interpolators.BOUNCE.EASE_IN()
// anim.startInPlayState()
}
} | OutRun/src/main/kotlin/com/almasb/fxglgames/outrun/PlayerComponent.kt | 4219513549 |
package net.dinkla.raytracer.math
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
class PolynomialsTest {
@Test
@Throws(Exception::class)
fun testSolveQuadric() {
// A*x^2 + B*x + C = 0
val s1 = doubleArrayOf(-16.0, 0.0, 1.0)
val sol = doubleArrayOf(0.0, 0.0)
val num = Polynomials.solveQuadric(s1, sol)
assertEquals(2, num)
assertEquals(4.0, sol[0])
assertEquals(-4.0, sol[1])
}
@Test
@Throws(Exception::class)
fun testSolveQuartic() {
// A*x^4 + B*x^3 + C*x^2+ D*x + E = 0
val s1 = doubleArrayOf(1.2, -3.2, 1.7, 2.5, -1.02)
val sol = doubleArrayOf(0.0, 0.0, 0.0, 0.0)
val num = Polynomials.solveQuartic(s1, sol)
println("num=" + num)
for (f in sol) {
println("f=" + f)
}
}
@Test
@Throws(Exception::class)
fun testSolveCubic() {
// A*x^3 + B*x^2 + C*x + D = 0
val s1 = doubleArrayOf(0.0, 0.0, 0.0, 1.0)
val sol = doubleArrayOf(0.0, 0.0, 0.0)
var num = Polynomials.solveCubic(s1, sol)
assertEquals(1, num)
assertEquals(0.0, sol[0])
val s2 = doubleArrayOf(8.0, 0.0, 0.0, 1.0)
num = Polynomials.solveCubic(s2, sol)
assertEquals(1, num)
assertEquals(-2.0, sol[0])
val s3 = doubleArrayOf(-8.0, 0.0, 0.0, 1.0)
num = Polynomials.solveCubic(s3, sol)
assertEquals(1, num)
assertEquals(2.0, sol[0])
val s4 = doubleArrayOf(1.2, -3.2, 1.7, 2.5)
num = Polynomials.solveCubic(s4, sol)
assertEquals(1, num)
assertEquals(-1.63938, sol[0], 0.00001)
/*
System.out.println("num=" + num);
for (double f : sol) {
System.out.println("f=" + f);
}
*/
}
}
| src/test/kotlin/net/dinkla/raytracer/math/PolynomialsTest.kt | 628917214 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.data.database.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
/**
* A table to store playlist information.
*/
@ExperimentalHorologistMediaDataApi
@Entity
public data class PlaylistEntity(
@PrimaryKey val playlistId: String,
val name: String,
val artworkUri: String?
)
| media-data/src/main/java/com/google/android/horologist/media/data/database/model/PlaylistEntity.kt | 317901811 |
package br.com.codeteam.ctanywhere.ext
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
/**
* Created by Bruno Rodrigues e Rodrigues on 21/05/2018.
*/
fun Context.hasPermissions(vararg permissions: String): Boolean {
for (permission in permissions) {
if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
return false
}
}
return true
}
@Suppress("unused")
fun Context.checkSelfPermissions(permission: String) = ContextCompat.checkSelfPermission(this, permission)
fun Context.getColorCompat(@ColorRes res: Int): Int = ContextCompat.getColor(this, res)
@Suppress("unused")
fun Context.getDrawableCompat(@DrawableRes res: Int): Drawable = ContextCompat.getDrawable(this, res)!!
| app/src/main/java/br/com/codeteam/ctanywhere/ext/ContextExt.kt | 2581933500 |
package com.zhuinden.simplestacktutorials.steps.step_7.features.profile
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.zhuinden.simplestackextensions.fragments.KeyedFragment
import com.zhuinden.simplestacktutorials.R
class ProfileFragment : KeyedFragment(R.layout.step7_profile_fragment) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Toast.makeText(requireContext(), "Welcome!", Toast.LENGTH_LONG).show()
}
} | tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_7/features/profile/ProfileFragment.kt | 1667724498 |
package com.eden.orchid.swiftdoc.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.OrchidMenuFactory
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.swiftdoc.SwiftdocModel
import com.eden.orchid.swiftdoc.page.SwiftdocStatementPage
import javax.inject.Inject
@Description("Links to all Swift elements of a particular type.", name = "Swift Pages")
class SwiftdocMenuItem
@Inject
constructor(
context: OrchidContext,
val model: SwiftdocModel
) : OrchidMenuFactory(context, "swiftdocPages", 100) {
@Option
lateinit var docType: String
@Option
lateinit var title: String
override fun getMenuItems(): List<MenuItem> {
val pages: List<SwiftdocStatementPage> = when(docType) {
"class" -> model.classPages
"struct" -> model.structPages
"enum" -> model.enumPages
"protocol" -> model.protocolPages
"global" -> model.globalPages
else -> emptyList()
}
if(!pages.isEmpty()) {
return listOf(
MenuItem.Builder(context)
.title(title)
.pages(pages.sortedBy { it.statement.name })
.build()
)
}
return emptyList()
}
} | plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/menu/SwiftdocMenuItem.kt | 3972374132 |
/*
* Copyright 2021 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.homebutton.main
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.pyamsoft.pydroid.arch.UiViewState
import javax.inject.Inject
internal interface ToolbarViewState : UiViewState {
val topBarHeight: Int
}
internal class MutableToolbarViewState @Inject internal constructor() : ToolbarViewState {
override var topBarHeight by mutableStateOf(0)
}
| app/src/main/java/com/pyamsoft/homebutton/main/ToolbarViewState.kt | 4141823317 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 26